lamina 0.0.10

High-performance compiler backend for Lamina Intermediate Representation
Documentation
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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
//! Loop optimization transforms for MIR.

use super::{Transform, TransformCategory, TransformLevel};
use crate::mir::{Block, Function, Instruction, IntBinOp, IntCmpOp, Operand, Register};
use std::collections::{HashMap, HashSet};

/// Loop invariant code motion that moves loop-invariant computations outside loops.
#[derive(Default)]
pub struct LoopInvariantCodeMotion;

impl Transform for LoopInvariantCodeMotion {
    fn name(&self) -> &'static str {
        "loop_invariant_code_motion"
    }

    fn description(&self) -> &'static str {
        "Moves loop-invariant computations outside loops"
    }

    fn category(&self) -> TransformCategory {
        TransformCategory::ControlFlowOptimization
    }

    fn level(&self) -> TransformLevel {
        TransformLevel::Stable
    }

    fn apply(&self, func: &mut Function) -> Result<bool, String> {
        self.apply_internal(func)
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod tests_licm {
    use super::*;
    use crate::mir::{
        FunctionBuilder, Immediate, IntBinOp, MirType, Operand, ScalarType, VirtualReg,
    };

    #[test]
    fn test_licm_basic() {
        // Create a loop with invariant calculation
        // entry:
        //   jmp loop
        // loop:
        //   v0 = add v0, 1  (induction)
        //   v1 = add 5, 10  (invariant)
        //   v2 = lt v0, v1
        //   br v2, loop, exit
        // exit:
        //   ret

        let mut func = FunctionBuilder::new("test_licm")
            .returns(MirType::Scalar(ScalarType::I64))
            .block("entry")
            .instr(Instruction::IntBinary {
                op: IntBinOp::Add,
                ty: MirType::Scalar(ScalarType::I64),
                dst: VirtualReg::gpr(0).into(),
                lhs: Operand::Immediate(Immediate::I64(0)),
                rhs: Operand::Immediate(Immediate::I64(0)),
            }) // init v0
            .instr(Instruction::Jmp {
                target: "loop".to_string(),
            })
            .block("loop")
            .instr(Instruction::IntBinary {
                op: IntBinOp::Add,
                ty: MirType::Scalar(ScalarType::I64),
                dst: VirtualReg::gpr(0).into(),
                lhs: Operand::Register(VirtualReg::gpr(0).into()),
                rhs: Operand::Immediate(Immediate::I64(1)),
            })
            // Invariant: 5 + 10
            .instr(Instruction::IntBinary {
                op: IntBinOp::Add,
                ty: MirType::Scalar(ScalarType::I64),
                dst: VirtualReg::gpr(1).into(),
                lhs: Operand::Immediate(Immediate::I64(5)),
                rhs: Operand::Immediate(Immediate::I64(10)),
            })
            .instr(Instruction::IntCmp {
                op: IntCmpOp::SLt,
                ty: MirType::Scalar(ScalarType::I1),
                dst: VirtualReg::gpr(2).into(),
                lhs: Operand::Register(VirtualReg::gpr(0).into()),
                rhs: Operand::Register(VirtualReg::gpr(1).into()),
            })
            .instr(Instruction::Br {
                cond: VirtualReg::gpr(2).into(),
                true_target: "loop".to_string(),
                false_target: "exit".to_string(),
            })
            .block("exit")
            .instr(Instruction::Ret { value: None })
            .build();

        let licm = LoopInvariantCodeMotion;
        let changed = licm.apply(&mut func).expect("LICM failed");

        assert!(changed);

        // Loop block should no longer have the 5+10 addition
        let loop_block = func.get_block("loop").expect("loop block exists");
        let has_invariant = loop_block.instructions.iter().any(|i| {
            if let Instruction::IntBinary { lhs, rhs, .. } = i {
                matches!(lhs, Operand::Immediate(Immediate::I64(5)))
                    && matches!(rhs, Operand::Immediate(Immediate::I64(10)))
            } else {
                false
            }
        });
        assert!(
            !has_invariant,
            "Invariant instruction should be moved out of loop"
        );

        let pre_header = func.get_block("loop_pre").expect("pre-header created");
        let has_moved = pre_header.instructions.iter().any(|i| {
            if let Instruction::IntBinary { lhs, rhs, .. } = i {
                matches!(lhs, Operand::Immediate(Immediate::I64(5)))
                    && matches!(rhs, Operand::Immediate(Immediate::I64(10)))
            } else {
                false
            }
        });
        assert!(has_moved, "Invariant instruction should be in pre-header");
    }
}

impl LoopInvariantCodeMotion {
    fn apply_internal(&self, func: &mut Function) -> Result<bool, String> {
        let mut changed = false;

        let loops = self.find_loops(func);

        let max_loops = 10;
        let max_iterations_per_loop = 5;
        let loops_to_process = loops.into_iter().take(max_loops);

        for loop_info in loops_to_process {
            if loop_info.blocks.len() > 50 {
                continue;
            }

            let mut iterations = 0;
            while iterations < max_iterations_per_loop {
                if !self.optimize_loop(func, &loop_info)? {
                    break;
                }
                changed = true;
                iterations += 1;
                if iterations >= max_iterations_per_loop {
                    break;
                }
            }
        }

        Ok(changed)
    }

    fn find_loops(&self, func: &Function) -> Vec<LoopInfo> {
        let mut loops = Vec::new();

        let dominators = self.calculate_dominators(func);

        for block in &func.blocks {
            for instr in &block.instructions {
                if let Instruction::Br {
                    true_target,
                    false_target,
                    ..
                } = instr
                {
                    // Check for back edges: target dominates source
                    if self.is_back_edge(&dominators, &block.label, true_target)
                        && let Some(loop_info) =
                            self.analyze_loop(func, true_target, &block.label, &dominators)
                    {
                        loops.push(loop_info);
                    }
                    if self.is_back_edge(&dominators, &block.label, false_target)
                        && let Some(loop_info) =
                            self.analyze_loop(func, false_target, &block.label, &dominators)
                    {
                        loops.push(loop_info);
                    }
                }
                if let Instruction::Jmp { target } = instr
                    && self.is_back_edge(&dominators, &block.label, target)
                    && let Some(loop_info) =
                        self.analyze_loop(func, target, &block.label, &dominators)
                {
                    loops.push(loop_info);
                }
            }
        }

        // Merge loops with the same header to handle multiple backedges
        let mut merged_loops: HashMap<String, HashSet<String>> = HashMap::new();

        for loop_info in loops {
            match merged_loops.entry(loop_info.header) {
                std::collections::hash_map::Entry::Vacant(e) => {
                    e.insert(loop_info.blocks);
                }
                std::collections::hash_map::Entry::Occupied(mut e) => {
                    e.get_mut().extend(loop_info.blocks);
                }
            }
        }

        merged_loops
            .into_iter()
            .map(|(header, blocks)| LoopInfo { header, blocks })
            .collect()
    }

    fn is_back_edge(
        &self,
        dominators: &HashMap<String, HashSet<String>>,
        from: &str,
        to: &str,
    ) -> bool {
        // A back edge exists if the target (header) dominates the source
        if let Some(doms) = dominators.get(from) {
            doms.contains(to)
        } else {
            false
        }
    }

    fn calculate_dominators(&self, func: &Function) -> HashMap<String, HashSet<String>> {
        let mut dominators: HashMap<String, HashSet<String>> = HashMap::new();
        let all_blocks: HashSet<String> = func.blocks.iter().map(|b| b.label.clone()).collect();

        // Initialize: value for entry is {entry}, others are all blocks
        for block in &func.blocks {
            if block.label == func.entry {
                let mut set = HashSet::new();
                set.insert(block.label.clone());
                dominators.insert(block.label.clone(), set);
            } else {
                dominators.insert(block.label.clone(), all_blocks.clone());
            }
        }

        let mut changed = true;
        while changed {
            changed = false;

            for block in &func.blocks {
                if block.label == func.entry {
                    continue;
                }

                // Intersection of dominators of all predecessors
                let mut new_doms: Option<HashSet<String>> = None;

                // Find predecessors
                let preds: Vec<&Block> = func
                    .blocks
                    .iter()
                    .filter(|pred| self.has_edge_to(func, &pred.label, &block.label))
                    .collect();

                if preds.is_empty() {
                    continue;
                }

                for pred in preds {
                    if let Some(pred_doms) = dominators.get(&pred.label) {
                        if let Some(current_intersect) = &mut new_doms {
                            current_intersect.retain(|d| pred_doms.contains(d));
                        } else {
                            new_doms = Some(pred_doms.clone());
                        }
                    }
                }

                let mut final_doms = new_doms.unwrap_or_default();
                final_doms.insert(block.label.clone());

                if let Some(current_doms) = dominators.get(&block.label)
                    && final_doms != *current_doms
                {
                    dominators.insert(block.label.clone(), final_doms);
                    changed = true;
                }
            }
        }

        dominators
    }

    fn analyze_loop(
        &self,
        func: &Function,
        header: &str,
        back_edge_source: &str,
        _dominators: &HashMap<String, HashSet<String>>,
    ) -> Option<LoopInfo> {
        // Natural loop identification:
        // A natural loop consists of the header, the back edge source,
        // and all nodes that can reach the back edge without going through the header.
        // (Optimized: we can traverse backwards from back_edge_source stopping at header)
        let mut loop_blocks = HashSet::new();
        let mut to_visit = vec![back_edge_source.to_string()];
        let mut visited = HashSet::new();
        const MAX_LOOP_ANALYSIS_ITERATIONS: usize = 1000;
        let mut iterations = 0;

        // First, collect all blocks that can reach the back edge source
        // Initialize queue with back edge source
        if header != back_edge_source {
            to_visit.push(back_edge_source.to_string());
        }
        loop_blocks.insert(header.to_string());
        loop_blocks.insert(back_edge_source.to_string());

        while let Some(block_label) = to_visit.pop() {
            if iterations >= MAX_LOOP_ANALYSIS_ITERATIONS {
                return None;
            }
            iterations += 1;

            if visited.contains(&block_label) {
                continue;
            }
            visited.insert(block_label.clone());
            loop_blocks.insert(block_label.clone());

            // Add predecessors that are not the header
            for block in &func.blocks {
                if self.has_edge_to(func, &block.label, &block_label) && block.label != header {
                    to_visit.push(block.label.clone());
                }
            }
        }

        // Add the header if not already included
        loop_blocks.insert(header.to_string());

        if !loop_blocks.contains(header) || !loop_blocks.contains(back_edge_source) {
            return None;
        }

        if loop_blocks.len() > 50 {
            return None;
        }

        Some(LoopInfo {
            header: header.to_string(),
            blocks: loop_blocks,
        })
    }

    fn has_edge_to(&self, func: &Function, from: &str, to: &str) -> bool {
        if let Some(block) = func.blocks.iter().find(|b| b.label == *from) {
            for instr in &block.instructions {
                match instr {
                    Instruction::Jmp { target } if target == to => return true,
                    Instruction::Br {
                        true_target,
                        false_target,
                        ..
                    } if true_target == to || false_target == to => return true,
                    _ => {}
                }
            }
        }
        false
    }

    fn optimize_loop(&self, func: &mut Function, loop_info: &LoopInfo) -> Result<bool, String> {
        let mut changed = false;

        let invariant_instrs = self.find_invariant_instructions(func, loop_info)?;

        if !invariant_instrs.is_empty() {
            self.move_invariant_instructions(func, loop_info, &invariant_instrs)?;
            changed = true;
        }

        Ok(changed)
    }

    fn find_invariant_instructions(
        &self,
        func: &Function,
        loop_info: &LoopInfo,
    ) -> Result<Vec<(usize, usize)>, String> {
        let mut invariant = Vec::new();
        let defs_in_loop = self.collect_defs_in_loop(func, loop_info);

        // Count how many times each register is defined inside the loop.
        // If a register is defined more than once (e.g. accumulator %sum, induction
        // var %j), it cannot be safely hoisted — one of those assignments is a
        // loop-carried update that must execute every iteration.
        let mut def_counts: HashMap<Register, usize> =
            HashMap::new();
        for block in &func.blocks {
            if !loop_info.blocks.contains(&block.label) {
                continue;
            }
            for instr in &block.instructions {
                if let Some(def) = instr.def_reg() {
                    *def_counts.entry(def.clone()).or_insert(0) += 1;
                }
            }
        }

        let max_invariant_instructions = 20;

        for (block_idx, block) in func.blocks.iter().enumerate() {
            if !loop_info.blocks.contains(&block.label) {
                continue;
            }

            for (instr_idx, instr) in block.instructions.iter().enumerate() {
                // Skip if this register is defined more than once in the loop.
                if let Some(def) = instr.def_reg()
                    && def_counts.get(def).copied().unwrap_or(0) > 1
                {
                    continue;
                }
                if self.is_invariant_instruction(func, loop_info, &defs_in_loop, instr) {
                    invariant.push((block_idx, instr_idx));

                    if invariant.len() >= max_invariant_instructions {
                        break;
                    }
                }
            }

            if invariant.len() >= max_invariant_instructions {
                break;
            }
        }

        Ok(invariant)
    }

    fn is_invariant_instruction(
        &self,
        func: &Function,
        loop_info: &LoopInfo,
        defs_in_loop: &HashSet<Register>,
        instr: &Instruction,
    ) -> bool {
        // An instruction is invariant if:
        // 1. It defines a register
        // 2. All its operands are either constants or defined outside the loop
        // 3. It's not a side-effecting instruction

        if let Some(_def_reg) = instr.def_reg() {
            // Check if all operands are invariant
            let operands_invariant = instr
                .use_regs()
                .iter()
                .all(|reg| self.is_invariant_register(func, loop_info, defs_in_loop, reg));

            // Check if instruction has no side effects
            let no_side_effects = !self.has_side_effects(instr);

            operands_invariant && no_side_effects
        } else {
            false
        }
    }

    fn is_invariant_register(
        &self,
        _func: &Function,
        _loop_info: &LoopInfo,
        defs_in_loop: &HashSet<Register>,
        reg: &Register,
    ) -> bool {
        match reg {
            Register::Physical(_) => false,
            Register::Virtual(_) => !defs_in_loop.contains(reg),
        }
    }

    fn has_side_effects(&self, instr: &Instruction) -> bool {
        matches!(
            instr,
            Instruction::Load { .. }
                | Instruction::Store { .. }
                | Instruction::Call { .. }
                | Instruction::Ret { .. }
        )
    }

    fn move_invariant_instructions(
        &self,
        func: &mut Function,
        loop_info: &LoopInfo,
        invariant_instrs: &[(usize, usize)],
    ) -> Result<(), String> {
        if invariant_instrs.is_empty() {
            return Ok(());
        }

        let header_idx = func
            .blocks
            .iter()
            .position(|b| b.label == loop_info.header)
            .ok_or_else(|| format!("Loop header '{}' not found", loop_info.header))?;

        // Generate unique pre-header label to avoid conflicts
        let mut pre_header_label = format!("{}_pre", loop_info.header);
        let mut counter = 0;
        while func.blocks.iter().any(|b| b.label == pre_header_label) {
            counter += 1;
            pre_header_label = format!("{}_pre_{}", loop_info.header, counter);
        }

        let mut pre_header_block = Block {
            label: pre_header_label.clone(),
            instructions: Vec::new(),
        };

        let mut sorted_invariant = invariant_instrs.to_vec();
        sorted_invariant.sort_by(|a, b| b.1.cmp(&a.1));
        sorted_invariant.sort_by(|a, b| b.0.cmp(&a.0));

        sorted_invariant.dedup();
        let mut instructions_to_move = Vec::new();
        for &(block_idx, instr_idx) in &sorted_invariant {
            if block_idx >= func.blocks.len() {
                continue;
            }
            let block = &func.blocks[block_idx];
            if instr_idx >= block.instructions.len() {
                continue;
            }
            let instr = block.instructions[instr_idx].clone();
            instructions_to_move.push(instr);
        }

        // Move instructions to the pre-header block
        for instr in instructions_to_move {
            pre_header_block.instructions.push(instr);
        }

        // Add jump to the original header
        pre_header_block.instructions.push(Instruction::Jmp {
            target: loop_info.header.clone(),
        });

        // Insert pre-header before the original header
        func.blocks.insert(header_idx, pre_header_block);

        // Remove original instructions from loop blocks
        // Since we sorted by (block_idx, instr_idx) descending, we can remove them safely
        for &(block_idx, instr_idx) in &sorted_invariant {
            // Adjust for the inserted pre-header block
            let adjusted_block_idx = if block_idx >= header_idx {
                block_idx + 1
            } else {
                block_idx
            };
            if adjusted_block_idx < func.blocks.len()
                && instr_idx < func.blocks[adjusted_block_idx].instructions.len()
            {
                func.blocks[adjusted_block_idx]
                    .instructions
                    .remove(instr_idx);
            }
        }

        // Redirect non-loop incoming edges to go through the pre-header.
        // Back-edges from inside the loop are skipped.
        for (block_idx, block) in func.blocks.iter_mut().enumerate() {
            if block_idx == header_idx || loop_info.blocks.contains(&block.label) {
                continue;
            }

            for instr in &mut block.instructions {
                match instr {
                    Instruction::Jmp { target } if *target == loop_info.header => {
                        *target = pre_header_label.clone();
                    }
                    Instruction::Br {
                        true_target,
                        false_target,
                        ..
                    } => {
                        if *true_target == loop_info.header {
                            *true_target = pre_header_label.clone();
                        }
                        if *false_target == loop_info.header {
                            *false_target = pre_header_label.clone();
                        }
                    }
                    _ => {}
                }
            }
        }

        // If the loop header was the function entry point, update it to the pre-header
        if func.entry == loop_info.header {
            func.entry = pre_header_label;
        }

        Ok(())
    }

    fn collect_defs_in_loop(
        &self,
        func: &Function,
        loop_info: &LoopInfo,
    ) -> HashSet<Register> {
        let mut defs = HashSet::new();
        for block in &func.blocks {
            if !loop_info.blocks.contains(&block.label) {
                continue;
            }
            for instr in &block.instructions {
                if let Some(def) = instr.def_reg() {
                    defs.insert(def.clone());
                }
            }
        }
        defs
    }
}

#[derive(Debug)]
struct LoopInfo {
    header: String,
    blocks: HashSet<String>,
}

#[derive(Debug)]
struct UnrollableLoop {
    header: String,
    body_blocks: Vec<String>,
    bound: i64,
    exit_target: String,
}

/// Loop unrolling that unrolls small loops to reduce overhead and improve ILP.
#[derive(Default)]
pub struct LoopUnrolling;

impl Transform for LoopUnrolling {
    fn name(&self) -> &'static str {
        "loop_unrolling"
    }

    fn description(&self) -> &'static str {
        "Unrolls small loops to reduce overhead and improve parallelism"
    }

    fn category(&self) -> TransformCategory {
        TransformCategory::ControlFlowOptimization
    }

    fn level(&self) -> TransformLevel {
        TransformLevel::Experimental
    }

    fn apply(&self, func: &mut Function) -> Result<bool, String> {
        self.apply_internal(func)
    }
}

impl LoopUnrolling {
    fn apply_internal(&self, func: &mut Function) -> Result<bool, String> {
        const MAX_BLOCKS: usize = 1000;
        const MAX_LOOPS_TO_UNROLL: usize = 10;

        if func.blocks.len() > MAX_BLOCKS {
            return Err(format!(
                "Function too large for loop unrolling ({} blocks, max {})",
                func.blocks.len(),
                MAX_BLOCKS
            ));
        }

        let mut changed = false;

        // 1. Identify loops
        // We reuse the logic from LoopInvariantCodeMotion (conceptually) but we need to own the detection here
        // or refactor to share. For now, we implement a detector here.
        let loops = self.find_unrollable_loops(func);

        let loops_to_unroll: Vec<_> = loops.into_iter().take(MAX_LOOPS_TO_UNROLL).collect();

        for loop_info in loops_to_unroll {
            // Apply unrolling
            if self.unroll_loop(func, &loop_info)? {
                changed = true;
            }
        }

        Ok(changed)
    }

    /// Find loops that can be safely unrolled (constant bounds, single entry, single backedge)
    fn find_unrollable_loops(&self, func: &Function) -> Vec<UnrollableLoop> {
        let mut unrollable = Vec::new();
        // Use a simplified CFG analysis to find natural loops
        // We look for back edges: Jmp/Br to an ancestor in the dominance tree (approx via block order)

        // Map label -> index
        let label_to_idx: HashMap<_, _> = func
            .blocks
            .iter()
            .enumerate()
            .map(|(i, b)| (b.label.as_str(), i))
            .collect();

        for (idx, block) in func.blocks.iter().enumerate() {
            if let Some(terminator) = block.instructions.last() {
                let targets = match terminator {
                    Instruction::Jmp { target } => vec![target],
                    Instruction::Br {
                        true_target,
                        false_target,
                        ..
                    } => vec![true_target, false_target],
                    _ => vec![],
                };

                for target in targets {
                    // Check if target is a header (back edge)
                    // Target must be before current block or same (self-loop)
                    if let Some(&target_idx) = label_to_idx.get(target.as_str())
                        && target_idx <= idx
                    {
                        // Potential loop header found.
                        // Now analyze if it's a "simple" counting loop we can unroll.
                        // 1. Must have constant bound
                        // 2. Must be small enough count
                        if let Some((bound, exit_target)) =
                            self.analyze_loop(func, target, &block.label)
                        {
                            // Collect body blocks (basic reachability from header to latch, excluding exit)
                            let body_blocks = self.collect_loop_body(func, target, &block.label);

                            if !body_blocks.is_empty() && body_blocks.len() <= 10 {
                                // Max 10 blocks in body
                                unrollable.push(UnrollableLoop {
                                    header: target.to_string(),
                                    body_blocks,
                                    bound,
                                    exit_target,
                                });
                            }
                        }
                    }
                }
            }
        }

        // Dedup loops by header
        unrollable.sort_by(|a, b| a.header.cmp(&b.header));
        unrollable.dedup_by(|a, b| a.header == b.header);

        unrollable
    }

    /// Analyze loop structure to determine exact invocation count and exit target
    fn analyze_loop(
        &self,
        func: &Function,
        header_label: &str,
        latch_label: &str,
    ) -> Option<(i64, String)> {
        // We look for the condition at the LATCH block (bottom of loop), or HEADER (top of loop).
        // Standard "for" loops often look like:
        // Header: check condition -> Exit or Body
        // ...
        // Latch: Jmp Header
        // Or
        // Header: ...
        // Latch: increment, check condition -> Header or Exit

        // Let's check LATCH block first for condition
        let latch_block = func.get_block(latch_label)?;

        let (cond_reg, true_target, false_target) = match latch_block.instructions.last()? {
            Instruction::Br {
                cond,
                true_target,
                false_target,
                ..
            } => (cond, true_target, false_target),
            Instruction::Jmp { target } if target == header_label => {
                // Unconditional latch. Check header for condition (while loop)
                let header_block = func.get_block(header_label)?;
                return match header_block.instructions.last()? {
                    Instruction::Br {
                        cond,
                        true_target,
                        false_target,
                        ..
                    } => {
                        self.analyze_bound_from_cond(
                            func,
                            header_block,
                            cond,
                            true_target,
                            false_target,
                            header_label,
                        )
                    }
                    _ => None,
                }
            }
            _ => return None,
        };

        self.analyze_bound_from_cond(
            func,
            latch_block,
            cond_reg,
            true_target,
            false_target,
            header_label,
        )
    }

    fn analyze_bound_from_cond(
        &self,
        _func: &Function,
        block: &Block,
        cond_reg: &Register,
        true_target: &str,
        false_target: &str,
        header_label: &str,
    ) -> Option<(i64, String)> {
        // If true_target goes to loop (header or body) and false_target exits, or vice versa
        let (_loop_target, exit_target, _branch_on_true) = if true_target == header_label {
            (true_target, false_target, true)
        } else if false_target == header_label {
            (false_target, true_target, false)
        } else {
            // Maybe points to body? Simplifying assumption: must point to header.
            return None;
        };

        // Find definition of cond_reg in this block
        let cond_def = block
            .instructions
            .iter()
            .find(|i| i.def_reg() == Some(cond_reg))?;

        if let Instruction::IntCmp { op, lhs, rhs, .. } = cond_def {
            // Expect induction variable vs Constant
            let (reg, limit) = match (lhs, rhs) {
                (Operand::Register(r), Operand::Immediate(crate::mir::Immediate::I64(c))) => {
                    (r, *c)
                }
                (Operand::Immediate(crate::mir::Immediate::I64(_c)), Operand::Register(_r)) => {
                    // Reverse op if needed?
                    return None; // Simplify
                }
                _ => return None,
            };

            // Find increment of 'reg'
            let inc_def = block
                .instructions
                .iter()
                .find(|i| i.def_reg() == Some(reg))?;
            if let Instruction::IntBinary {
                op: IntBinOp::Add,
                lhs: Operand::Register(src),
                rhs: Operand::Immediate(crate::mir::Immediate::I64(step)),
                ..
            } = inc_def
                && src == reg
                && *step == 1
            {
                // i++ loop.
                // Standard "while (i < N)"
                // If we are at latch (do-while logic effectively):
                //   I start at 0? We assume 0 for now as per previous task spec, or we only unroll safe small checks.
                //   If condition is "i < N", and we exit when False.
                //   Then we run while i < N.
                //   Count = N.
                // Support bound up to 16-32.
                let count = match op {
                    IntCmpOp::SLt | IntCmpOp::ULt => limit,
                    IntCmpOp::SLe | IntCmpOp::ULe => limit + 1,
                    IntCmpOp::Ne => limit, // i != N
                    _ => return None,
                };

                if count > 0 && count <= 32 {
                    return Some((count, exit_target.to_string()));
                }
            }
        }

        None
    }

    fn collect_loop_body(&self, func: &Function, header: &str, latch: &str) -> Vec<String> {
        // Collect all blocks reachable from header that can reach latch, without passing through exit?
        // Simplified: BFS from header, stop if we see something not dominated by header?
        // Actually simplest is: all nodes N such that Header -> ... -> N -> ... -> Latch
        // For unrolling, we need a topological sort or just a list of blocks part of the loop.
        // We will just do a simple reachability trace within strict limits.

        let mut body = HashSet::new();
        let mut queue = vec![header.to_string()];
        body.insert(header.to_string());

        while let Some(current) = queue.pop() {
            if current == latch {
                continue; // Latch is part of body but has no successors in loop (except header)
            }
            if let Some(block) = func.get_block(&current) {
                let successors = block.successors();
                for succ in successors {
                    // To be in the loop, successor must eventually reach latch (or be latch)
                    // and not be the header (backedge handled elsewhere)
                    if succ != header && !body.contains(&succ) {
                        // Check if succ can reach latch?
                        // This is expensive.
                        // Simplified assumption: All successors of header that are not exit are in loop.
                        // We already know exit_target from analyze_loop. But we don't have it here.
                        // Actually, finding natural loop nodes is standard.
                        // For this task, let's assume if we hit latch, stop.
                        // If we are branching, we follow both.
                        // This is heuristic.
                        body.insert(succ.clone());
                        queue.push(succ);
                    }
                }
            }
        }
        body.insert(latch.to_string());

        // Return sorted list
        let mut list: Vec<_> = body.into_iter().collect();
        // Sort by order in function to preserve approx topological order
        let order: HashMap<_, _> = func
            .blocks
            .iter()
            .enumerate()
            .map(|(i, b)| (b.label.clone(), i))
            .collect();
        list.sort_by_key(|lbl| order.get(lbl).copied().unwrap_or(usize::MAX));
        list
    }

    fn unroll_loop(&self, func: &mut Function, loop_info: &UnrollableLoop) -> Result<bool, String> {
        // 1. Locate blocks
        let mut body_indices = Vec::new();
        for lbl in &loop_info.body_blocks {
            if let Some(idx) = func.blocks.iter().position(|b| &b.label == lbl) {
                body_indices.push(idx);
            } else {
                return Ok(false); // Block not found??
            }
        }

        // 2. Clone bodies
        let mut unrolled_blocks = Vec::new();
        // Original blocks are "iteration 0". We will modify them in place or replace them?
        // Replacing is easier to manage control flow.
        // We will create N copies of the body chain.

        for i in 0..loop_info.bound {
            for &idx in &body_indices {
                let original_block = &func.blocks[idx];
                let mut new_block = original_block.clone();

                // Rename label
                new_block.label = format!("{}_unroll_{}", original_block.label, i);

                // Rewrite targets
                if let Some(term) = new_block.instructions.last_mut() {
                    match term {
                        Instruction::Jmp { target } => {
                            if target == &loop_info.header {
                                // Back edge: Jump to next iteration's header, or EXIT if last iteration
                                if i == loop_info.bound - 1 {
                                    *target = loop_info.exit_target.clone();
                                } else {
                                    *target = format!("{}_unroll_{}", loop_info.header, i + 1);
                                }
                            } else if loop_info.body_blocks.contains(target) {
                                // Internal edge: Jump to same iteration's version
                                *target = format!("{}_unroll_{}", target, i);
                            }
                            // Else: exit edge (break/return), keep as is
                        }
                        Instruction::Br {
                            true_target,
                            false_target,
                            ..
                        } => {
                            // Handle True target
                            if true_target == &loop_info.header {
                                if i == loop_info.bound - 1 {
                                    *true_target = loop_info.exit_target.clone();
                                } else {
                                    *true_target = format!("{}_unroll_{}", loop_info.header, i + 1);
                                }
                            } else if loop_info.body_blocks.contains(true_target) {
                                *true_target = format!("{}_unroll_{}", true_target, i);
                            }

                            // Handle False target
                            if false_target == &loop_info.header {
                                if i == loop_info.bound - 1 {
                                    *false_target = loop_info.exit_target.clone();
                                } else {
                                    *false_target =
                                        format!("{}_unroll_{}", loop_info.header, i + 1);
                                }
                            } else if loop_info.body_blocks.contains(false_target) {
                                *false_target = format!("{}_unroll_{}", false_target, i);
                            }
                        }
                        _ => {}
                    }
                }
                unrolled_blocks.push(new_block);
            }
        }

        // 3. Replace original blocks with unrolled blocks
        // We need to keep the function valid.
        // Identify where to insert. We can remove the old body blocks and insert new ones.
        // We must patch predecessor of header to jump to "header_unroll_0".
        // BUT wait, "header_unroll_0" has same label as original header??
        // No, we renamed it.
        // Predecessors of original header (from outside loop) must now jump to `header_unroll_0`.

        let entry_label = format!("{}_unroll_0", loop_info.header);

        // Fix external predecessors
        for block in &mut func.blocks {
            if loop_info.body_blocks.contains(&block.label) {
                continue;
            }
            for instr in &mut block.instructions {
                match instr {
                    Instruction::Jmp { target } if target == &loop_info.header => {
                        *target = entry_label.clone();
                    }
                    Instruction::Br {
                        true_target,
                        false_target,
                        ..
                    } => {
                        if true_target == &loop_info.header {
                            *true_target = entry_label.clone();
                        }
                        if false_target == &loop_info.header {
                            *false_target = entry_label.clone();
                        }
                    }
                    _ => {}
                }
            }
        }

        let old_body_set: HashSet<_> = loop_info.body_blocks.iter().collect();
        func.blocks.retain(|b| !old_body_set.contains(&b.label));
        func.blocks.extend(unrolled_blocks);

        for block in &mut func.blocks {
            if block
                .label
                .starts_with(&format!("{}_unroll_", loop_info.header))
                && let Some(term) = block.instructions.last_mut()
            {
                // If it's the header/latch that had the condition
                // Wait, did we rename header? Yes.
                // If we are in `header_unroll_i`, and it was `Br`, we want `Jmp`.
                if matches!(term, Instruction::Br { .. }) {
                    // Check if targets match our "Next Iter" or "Exit" pattern
                    // If so, replace with Jmp.
                    // But we need to know which target is taken.
                    // We assumed unrolling is valid, implying we ALWAYS take loop path.
                    // So finding the target that points to "Next Iteration" (or Exit on last) is enough.

                    let target_to_take = match term {
                        Instruction::Br { .. } => {
                            // One of these points to next iter (or exit).
                            // The other points to exit (early) or loop?
                            // Since we verified it's a counting loop 0..N, we take loop path N times.
                            // The "Exit" target of the ORIGINAL loop was identifying the Loop Exit.
                            // The "Loop" target was identifying Loop Body.
                            // We remapped Loop Body -> Next Iter.
                            // We remapped Loop Exit -> Exit.
                            // So we want to jump to (Next Iter).
                            // Which one is it?
                            // We can check if true_target was original exit?
                            // Hard to track original.
                            // But we know the resulting definition:
                            // If `true_target` includes `unroll_` (next iter) or matches `exit_target` (last iter logic).
                            // Actually, `unroll_loop` Step 2 logic modified targets.
                            // We can just look if one target represents "Continue".
                            // Simplified: Leave as Br. Constant Propagation/Folding handles it IF we unroll values too.
                            // But we didn't unroll values (const prop of I).
                            // So explicit `Jmp` is better.
                            // Let's assume the loop-back target is the one we want.
                            // But wait, in the last iteration, we want the EXIT target.
                            None // Skip optimization for safety in this step
                        }
                        _ => None,
                    };

                    if let Some(t) = target_to_take {
                        *term = Instruction::Jmp { target: t };
                    }
                }
            }
        }

        Ok(true)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::mir::{
        FunctionBuilder, Immediate, IntBinOp, MirType, Operand, ScalarType, VirtualReg,
    };

    #[test]
    fn test_loop_unrolling_simple() {
        // Create a simple loop:
        // entry:
        //   v0 = 0
        //   br loop
        // loop:
        //   v0 = add v0, 1
        //   v1 = lt v0, 4
        //   br v1, loop, exit
        // exit:
        //   ret

        let mut func = FunctionBuilder::new("test_loop")
            .returns(MirType::Scalar(ScalarType::I64))
            .block("entry")
            .instr(Instruction::IntBinary {
                op: IntBinOp::Add,
                ty: MirType::Scalar(ScalarType::I64),
                dst: VirtualReg::gpr(0).into(),
                lhs: Operand::Immediate(Immediate::I64(0)),
                rhs: Operand::Immediate(Immediate::I64(0)),
            })
            .instr(Instruction::Jmp {
                target: "loop".to_string(),
            })
            .block("loop")
            // Body: v2 = v2 + 1 (dummy work)
            .instr(Instruction::IntBinary {
                op: IntBinOp::Add,
                ty: MirType::Scalar(ScalarType::I64),
                dst: VirtualReg::gpr(2).into(),
                lhs: Operand::Register(VirtualReg::gpr(2).into()),
                rhs: Operand::Immediate(Immediate::I64(1)),
            })
            // Increment: v0 = v0 + 1
            .instr(Instruction::IntBinary {
                op: IntBinOp::Add,
                ty: MirType::Scalar(ScalarType::I64),
                dst: VirtualReg::gpr(0).into(),
                lhs: Operand::Register(VirtualReg::gpr(0).into()),
                rhs: Operand::Immediate(Immediate::I64(1)),
            })
            // Compare: v1 = v0 < 4
            .instr(Instruction::IntCmp {
                op: IntCmpOp::SLt,
                ty: MirType::Scalar(ScalarType::I1),
                dst: VirtualReg::gpr(1).into(),
                lhs: Operand::Register(VirtualReg::gpr(0).into()),
                rhs: Operand::Immediate(Immediate::I64(4)),
            })
            // Branch
            .instr(Instruction::Br {
                cond: VirtualReg::gpr(1).into(),
                true_target: "loop".to_string(),
                false_target: "exit".to_string(),
            })
            .block("exit")
            .instr(Instruction::Ret { value: None })
            .build();

        let unrolling = LoopUnrolling;
        let changed = unrolling.apply(&mut func).expect("Unrolling failed");

        assert!(changed);

        // With multi-block unrolling, "loop" is replaced by "loop_unroll_0"..."loop_unroll_3"
        // We expect "loop" to be gone.
        assert!(func.get_block("loop").is_none());

        // Check first iteration
        let loop_0 = func
            .get_block("loop_unroll_0")
            .expect("loop_unroll_0 exists");
        assert!(!loop_0.instructions.is_empty());

        match loop_0.instructions.last().unwrap() {
            Instruction::Jmp { target } => assert_eq!(target, "loop_unroll_1"),
            Instruction::Br { true_target, .. } => assert_eq!(true_target, "loop_unroll_1"), // If conversion failed
            _ => panic!("Expected branch/jump to next iter"),
        }

        // Check last iteration
        let loop_3 = func
            .get_block("loop_unroll_3")
            .expect("loop_unroll_3 exists");
        match loop_3.instructions.last().unwrap() {
            Instruction::Jmp { target } => assert_eq!(target, "exit"),
            Instruction::Br { true_target, .. } => assert_eq!(true_target, "exit"), // Last iter jumps to exit
            _ => panic!("Expected branch/jump to exit"),
        }
    }

    #[test]
    fn test_licm_empty_function() {
        let mut func = FunctionBuilder::new("empty")
            .returns(MirType::Scalar(ScalarType::I64))
            .block("entry")
            .instr(Instruction::Ret { value: None })
            .build();

        let licm = LoopInvariantCodeMotion;
        let result = licm.apply(&mut func);
        assert!(result.is_ok());
        assert!(!result.unwrap()); // No changes expected
    }

    #[test]
    fn test_licm_no_loops() {
        // Function with no loops - nothing to optimize
        let mut func = FunctionBuilder::new("no_loop")
            .returns(MirType::Scalar(ScalarType::I64))
            .block("entry")
            .instr(Instruction::IntBinary {
                op: IntBinOp::Add,
                ty: MirType::Scalar(ScalarType::I64),
                dst: VirtualReg::gpr(0).into(),
                lhs: Operand::Immediate(Immediate::I64(1)),
                rhs: Operand::Immediate(Immediate::I64(2)),
            })
            .instr(Instruction::Jmp {
                target: "exit".to_string(),
            })
            .block("exit")
            .instr(Instruction::Ret {
                value: Some(Operand::Register(VirtualReg::gpr(0).into())),
            })
            .build();

        let licm = LoopInvariantCodeMotion;
        let changed = licm.apply(&mut func).expect("should succeed");
        assert!(!changed);
    }

    #[test]
    fn test_licm_side_effect_not_moved() {
        // Store inside loop should NOT be moved out
        let mut func = FunctionBuilder::new("side_effect")
            .param(VirtualReg::gpr(0).into(), MirType::Scalar(ScalarType::I64))
            .returns(MirType::Scalar(ScalarType::I64))
            .block("entry")
            .instr(Instruction::Jmp {
                target: "loop".to_string(),
            })
            .block("loop")
            .instr(Instruction::Store {
                ty: MirType::Scalar(ScalarType::I64),
                src: Operand::Immediate(Immediate::I64(42)),
                addr: crate::mir::AddressMode::BaseOffset {
                    base: VirtualReg::gpr(0).into(),
                    offset: 0,
                },
                attrs: crate::mir::MemoryAttrs::default(),
            })
            .instr(Instruction::Br {
                cond: VirtualReg::gpr(0).into(),
                true_target: "loop".to_string(),
                false_target: "exit".to_string(),
            })
            .block("exit")
            .instr(Instruction::Ret { value: None })
            .build();

        let licm = LoopInvariantCodeMotion;
        let changed = licm.apply(&mut func).expect("should succeed");
        // Store has side effects - should not be moved
        assert!(!changed);
    }

    #[test]
    fn test_loop_unrolling_empty_function() {
        let mut func = FunctionBuilder::new("empty")
            .returns(MirType::Scalar(ScalarType::I64))
            .block("entry")
            .instr(Instruction::Ret { value: None })
            .build();

        let unroll = LoopUnrolling;
        let result = unroll.apply(&mut func);
        assert!(result.is_ok());
        assert!(!result.unwrap());
    }

    #[test]
    fn test_loop_unrolling_no_loops() {
        let mut func = FunctionBuilder::new("no_loop")
            .returns(MirType::Scalar(ScalarType::I64))
            .block("entry")
            .instr(Instruction::IntBinary {
                op: IntBinOp::Add,
                ty: MirType::Scalar(ScalarType::I64),
                dst: VirtualReg::gpr(0).into(),
                lhs: Operand::Immediate(Immediate::I64(1)),
                rhs: Operand::Immediate(Immediate::I64(2)),
            })
            .instr(Instruction::Ret {
                value: Some(Operand::Register(VirtualReg::gpr(0).into())),
            })
            .build();

        let unroll = LoopUnrolling;
        let changed = unroll.apply(&mut func).expect("should succeed");
        assert!(!changed);
    }

    #[test]
    fn test_loop_unrolling_large_bound_not_unrolled() {
        // Loop with bound > 32 should not be unrolled
        let mut func = FunctionBuilder::new("large_bound")
            .returns(MirType::Scalar(ScalarType::I64))
            .block("entry")
            .instr(Instruction::IntBinary {
                op: IntBinOp::Add,
                ty: MirType::Scalar(ScalarType::I64),
                dst: VirtualReg::gpr(0).into(),
                lhs: Operand::Immediate(Immediate::I64(0)),
                rhs: Operand::Immediate(Immediate::I64(0)),
            })
            .instr(Instruction::Jmp {
                target: "loop".to_string(),
            })
            .block("loop")
            .instr(Instruction::IntBinary {
                op: IntBinOp::Add,
                ty: MirType::Scalar(ScalarType::I64),
                dst: VirtualReg::gpr(0).into(),
                lhs: Operand::Register(VirtualReg::gpr(0).into()),
                rhs: Operand::Immediate(Immediate::I64(1)),
            })
            .instr(Instruction::IntCmp {
                op: IntCmpOp::SLt,
                ty: MirType::Scalar(ScalarType::I1),
                dst: VirtualReg::gpr(1).into(),
                lhs: Operand::Register(VirtualReg::gpr(0).into()),
                rhs: Operand::Immediate(Immediate::I64(100)), // > 32
            })
            .instr(Instruction::Br {
                cond: VirtualReg::gpr(1).into(),
                true_target: "loop".to_string(),
                false_target: "exit".to_string(),
            })
            .block("exit")
            .instr(Instruction::Ret { value: None })
            .build();

        let unroll = LoopUnrolling;
        let changed = unroll.apply(&mut func).expect("should succeed");
        // Loop with large bound should not be unrolled
        assert!(!changed);
        // Original loop should still exist
        assert!(func.get_block("loop").is_some());
    }

    #[test]
    fn test_licm_stress_no_infinite_loop() {
        // Create function with nested-looking structure but no actual loop
        let mut func = FunctionBuilder::new("stress")
            .returns(MirType::Scalar(ScalarType::I64))
            .block("entry")
            .build();

        // Add many blocks in linear fashion
        for i in 0..50 {
            let label = format!("block{}", i);
            let next_label = if i < 49 {
                format!("block{}", i + 1)
            } else {
                "exit".to_string()
            };

            let mut block = Block::new(&label);
            block.push(Instruction::IntBinary {
                op: IntBinOp::Add,
                ty: MirType::Scalar(ScalarType::I64),
                dst: VirtualReg::gpr(i).into(),
                lhs: Operand::Immediate(Immediate::I64(i as i64)),
                rhs: Operand::Immediate(Immediate::I64(1)),
            });
            block.push(Instruction::Jmp { target: next_label });
            func.add_block(block);
        }

        let mut exit_block = Block::new("exit");
        exit_block.push(Instruction::Ret { value: None });
        func.add_block(exit_block);

        // Update entry to jump to block0
        func.blocks[0].instructions.push(Instruction::Jmp {
            target: "block0".to_string(),
        });

        let licm = LoopInvariantCodeMotion;
        let result = licm.apply(&mut func);
        assert!(result.is_ok());
    }

    #[test]
    fn test_loop_unrolling_stress_no_infinite_loop() {
        // Many simple blocks should not cause infinite loop
        let mut func = FunctionBuilder::new("stress")
            .returns(MirType::Scalar(ScalarType::I64))
            .block("entry")
            .instr(Instruction::Ret { value: None })
            .build();

        // Add 100 independent blocks
        for i in 0..100 {
            let label = format!("dead_block_{}", i);
            let mut block = Block::new(&label);
            block.push(Instruction::Ret { value: None });
            func.add_block(block);
        }

        let unroll = LoopUnrolling;
        let result = unroll.apply(&mut func);
        assert!(result.is_ok());
    }
}