File size: 9,915 Bytes
5e4510c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
#!/usr/bin/env python3
"""
MLIR Lowering Pipeline - Use mlir-opt to lower arith operations to LLVM
Uses proper MLIR lowering passes to convert all dialects to LLVM-compatible ones.
"""

import subprocess
import tempfile
import shutil
from pathlib import Path
import time

class MLIRLoweringPipeline:
    def __init__(self):
        self.verify_tools()
        
    def verify_tools(self):
        """Verify required MLIR tools"""
        required_tools = ['mlir-opt', 'mlir-translate']
        for tool in required_tools:
            if not shutil.which(tool):
                raise RuntimeError(f"Required tool not found: {tool}")
        print("βœ… MLIR tools verified: mlir-opt, mlir-translate")

    def find_available_passes(self):
        """Find what lowering passes are available"""
        print("πŸ” Finding available lowering passes...")
        
        try:
            result = subprocess.run(['mlir-opt', '--help'], capture_output=True, text=True)
            help_text = result.stdout
            
            # Look for conversion passes
            conversion_passes = []
            for line in help_text.splitlines():
                line = line.strip()
                if 'convert-' in line and '-to-' in line:
                    # Extract pass name
                    if line.startswith('--'):
                        pass_name = line.split()[0][2:]  # Remove --
                        conversion_passes.append(pass_name)
            
            print("πŸ“‹ Available conversion passes:")
            relevant_passes = []
            for pass_name in sorted(conversion_passes):
                if any(keyword in pass_name for keyword in ['arith', 'func', 'llvm', 'std', 'scf']):
                    print(f"   βœ… {pass_name}")
                    relevant_passes.append(pass_name)
                else:
                    print(f"   ❓ {pass_name}")
            
            return relevant_passes
            
        except Exception as e:
            print(f"❌ Error finding passes: {e}")
            return []

    def test_lowering_passes(self, input_file):
        """Test different lowering pass combinations"""
        print(f"\nπŸ§ͺ Testing lowering passes on {input_file}...")
        
        # Common lowering pass sequences
        pass_sequences = [
            # Basic arith lowering
            ["convert-arith-to-llvm"],
            
            # More comprehensive lowering
            ["convert-arith-to-llvm", "convert-func-to-llvm"],
            
            # Full lowering pipeline
            [
                "convert-arith-to-llvm",
                "convert-func-to-llvm", 
                "convert-scf-to-cf",
                "convert-cf-to-llvm"
            ],
            
            # Alternative approaches
            ["arith-bufferize", "convert-arith-to-llvm"],
            ["canonicalize", "convert-arith-to-llvm", "canonicalize"],
            
            # Try with reconcile-unrealized-casts
            [
                "convert-arith-to-llvm",
                "convert-func-to-llvm",
                "reconcile-unrealized-casts"
            ]
        ]
        
        successful_sequences = []
        
        for i, passes in enumerate(pass_sequences):
            print(f"\nπŸ“‹ Testing sequence {i+1}: {' β†’ '.join(passes)}")
            
            success = self.test_pass_sequence(input_file, passes)
            if success:
                successful_sequences.append(passes)
                print(f"   βœ… Sequence {i+1} works!")
            else:
                print(f"   ❌ Sequence {i+1} failed")
        
        return successful_sequences

    def test_pass_sequence(self, input_file, passes):
        """Test a specific sequence of passes"""
        try:
            # Build pipeline
            pipeline = f"builtin.module({','.join(passes)})"
            
            with tempfile.NamedTemporaryFile(suffix='.mlir', delete=False) as temp_file:
                # Apply passes
                cmd = ['mlir-opt', input_file, f'--pass-pipeline={pipeline}']
                result = subprocess.run(cmd, capture_output=True, text=True, timeout=15)
                
                if result.returncode != 0:
                    return False
                
                # Write result to temp file
                temp_file.write(result.stdout)
                temp_file.flush()
                
                # Test LLVM translation
                cmd = ['mlir-translate', '--mlir-to-llvmir', temp_file.name]
                translate_result = subprocess.run(cmd, capture_output=True, text=True, timeout=10)
                
                success = translate_result.returncode == 0
                if success:
                    print(f"      πŸ’‘ LLVM IR size: {len(translate_result.stdout)} chars")
                
                return success
                
        except Exception as e:
            print(f"      ❌ Error: {e}")
            return False
        finally:
            try:
                Path(temp_file.name).unlink()
            except:
                pass

    def create_lowered_file(self, input_file, output_file, pass_sequence):
        """Create a fully lowered MLIR file"""
        print(f"\nπŸš€ Creating lowered file: {input_file} β†’ {output_file}")
        print(f"πŸ“‹ Using passes: {' β†’ '.join(pass_sequence)}")
        
        try:
            # Build pipeline
            pipeline = f"builtin.module({','.join(pass_sequence)})"
            
            start_time = time.time()
            cmd = ['mlir-opt', input_file, f'--pass-pipeline={pipeline}', '-o', output_file]
            result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
            elapsed = time.time() - start_time
            
            if result.returncode != 0:
                print(f"❌ Lowering failed: {result.stderr}")
                return False
            
            print(f"βœ… Lowering completed in {elapsed:.3f}s")
            
            # Verify the output
            output_path = Path(output_file)
            if output_path.exists():
                size = output_path.stat().st_size
                print(f"πŸ“„ Output file size: {size} bytes")
                
                # Test LLVM translation
                cmd = ['mlir-translate', '--mlir-to-llvmir', output_file]
                translate_result = subprocess.run(cmd, capture_output=True, text=True, timeout=15)
                
                if translate_result.returncode == 0:
                    llvm_size = len(translate_result.stdout)
                    print(f"βœ… LLVM translation successful! LLVM IR size: {llvm_size} chars")
                    
                    # Save LLVM IR too
                    llvm_file = output_file.replace('.mlir', '.ll')
                    with open(llvm_file, 'w') as f:
                        f.write(translate_result.stdout)
                    print(f"πŸ’Ύ LLVM IR saved to: {llvm_file}")
                    
                    return True
                else:
                    print(f"❌ LLVM translation failed: {translate_result.stderr[:200]}...")
                    return False
            
            return False
            
        except Exception as e:
            print(f"❌ Error creating lowered file: {e}")
            return False

    def process_file(self, input_file):
        """Complete pipeline to lower an MLIR file"""
        input_path = Path(input_file)
        if not input_path.exists():
            print(f"❌ Input file not found: {input_file}")
            return None
        
        print(f"🎯 Processing {input_file}")
        print(f"πŸ“Š Input size: {input_path.stat().st_size} bytes")
        
        # Find available passes
        available_passes = self.find_available_passes()
        
        # Test lowering approaches
        successful_sequences = self.test_lowering_passes(str(input_path))
        
        if not successful_sequences:
            print("❌ No working lowering sequences found!")
            return None
        
        # Use the first successful sequence
        best_sequence = successful_sequences[0]
        print(f"\n🎯 Using best sequence: {' β†’ '.join(best_sequence)}")
        
        # Create output filename
        output_file = str(input_path.parent / f"{input_path.stem}_lowered{input_path.suffix}")
        
        # Create the lowered file
        if self.create_lowered_file(str(input_path), output_file, best_sequence):
            print(f"πŸŽ‰ Success! Lowered file created: {output_file}")
            return output_file
        else:
            print("❌ Failed to create lowered file")
            return None

def main():
    print("πŸš€ MLIR Lowering Pipeline")
    print("=" * 50)
    
    pipeline = MLIRLoweringPipeline()
    
    # Process your attention file
    input_file = "mlir/self_attn_with_consts_linalg_dialect.mlir"
    # input_file = "mlir/export_mlir.mlir"
    
    if not Path(input_file).exists():
        print(f"❌ Input file not found: {input_file}")
        print("Please specify the correct path to your MLIR file.")
        return
    
    lowered_file = pipeline.process_file(input_file)
    
    if lowered_file:
        print(f"\n🎯 Next steps:")
        print(f"1. Update your evaluator to use: {lowered_file}")
        print(f"2. The lowered file should work with mlir-translate")
        print(f"3. Run evolution with real LLVM execution!")
        print(f"\nπŸ“‹ Quick test:")
        print(f"   mlir-translate --mlir-to-llvmir {lowered_file}")
    else:
        print("\n⚠️ Lowering failed. You may need to:")
        print("1. Check which conversion passes are available in your MLIR build")
        print("2. Manually inspect the MLIR file for unsupported constructs")
        print("3. Use alternative approaches like the dialect converter")

if __name__ == "__main__":
    main()