llvm-native-core-ext 0.1.0

Extended modules for llvm-native-core: analysis passes, transforms, codegen extras, bitcode, linker, JIT, utilities. Part of the llvm-native workspace (https://crates.io/crates/llvm-native).
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
//! Machine LICM — hoists loop-invariant machine instructions out of
//! loops to reduce redundant computation.
//! Clean-room behavioral reconstruction.
//!
//! @llvm_behavior: MachineLICM performs loop-invariant code motion on
//! machine instructions (after register allocation). It identifies
//! instructions within a loop whose operands are either constants or
//! defined outside the loop, and hoists them to the loop preheader.
//!
//! Key differences from IR-level LICM:
//! - Operates on machine instructions (physical/virtual registers)
//! - Must respect register pressure (hoisting may increase live ranges)
//! - Must consider side effects (memory operations, calls)
//! - Must respect control dependence (speculative execution safety)
//!
//! Algorithm:
//! 1. Find all loops in the machine function (using block CFG)
//! 2. For each loop, iterate instructions in loop body blocks
//! 3. Check if each instruction is loop-invariant:
//!    a. All operands are defined outside the loop, or are constants
//!    b. The instruction has no side effects (unless safe to speculatively execute)
//!    c. The instruction dominates all loop exits
//! 4. Hoist eligible instructions to the preheader
//! 5. Repeat until no more invariants found

use llvm_native_core::codegen::{MachineBasicBlock, MachineFunction, MachineInstr, MachineOperand, VirtReg};
use std::collections::{HashMap, HashSet, VecDeque};

// ============================================================================
// Machine Loop Info
// ============================================================================

/// A loop in the machine CFG, identified by its header block index.
#[derive(Debug, Clone)]
struct MachineLoop {
    /// Index of the header block.
    pub header: usize,
    /// Indices of blocks in the loop body (including header).
    pub blocks: Vec<usize>,
    /// Index of the preheader block (dominates header, outside loop).
    pub preheader: Option<usize>,
    /// Indices of exit blocks.
    pub exits: Vec<usize>,
}

// ============================================================================
// Machine LICM Pass
// ============================================================================

/// MachineLICM — hoists loop-invariant machine instructions.
pub struct MachineLICM {
    /// Number of instructions hoisted.
    pub hoisted: usize,
    /// Whether to hoist loads (may be unsafe for faulting loads).
    pub hoist_loads: bool,
    /// Whether to hoist stores (rarely safe).
    pub hoist_stores: bool,
}

impl MachineLICM {
    /// Create a new MachineLICM pass.
    pub fn new() -> Self {
        Self {
            hoisted: 0,
            hoist_loads: false,
            hoist_stores: false,
        }
    }

    /// Run MachineLICM on a machine function.
    ///
    /// Returns the number of instructions hoisted.
    pub fn run_on_function(&mut self, mf: &mut MachineFunction) -> usize {
        self.hoisted = 0;

        // Step 1: Find all loops in the machine function
        let loops = self.find_loops(mf);

        if loops.is_empty() {
            return 0;
        }

        // Step 2: Process each loop, hoisting invariants
        for machine_loop in &loops {
            let mut changed = true;
            // Iterate to a fixed point: hoisting one invariant may make
            // others invariant
            let mut iteration = 0;
            while changed && iteration < 32 {
                changed = false;
                iteration += 1;

                for &block_idx in &machine_loop.blocks {
                    if block_idx >= mf.blocks.len() {
                        continue;
                    }

                    let block = &mf.blocks[block_idx];
                    let num_insts = block.instructions.len();

                    for inst_idx in 0..num_insts {
                        // Can't modify while iterating — collect candidates
                        // In the real implementation, we'd cache invariants.
                        // Here we approximate by checking invariants.
                        if block_idx >= mf.blocks.len()
                            || inst_idx >= mf.blocks[block_idx].instructions.len()
                        {
                            continue;
                        }

                        let mi = &mf.blocks[block_idx].instructions[inst_idx];

                        if self.is_loop_invariant(mi, &machine_loop.blocks)
                            && self.is_safe_to_hoist(mi)
                        {
                            if let Some(preheader) = machine_loop.preheader {
                                let num_insts_before = mf.blocks[block_idx].instructions.len();
                                self.hoist_instruction(mf, inst_idx, preheader);
                                changed = true;
                                self.hoisted += 1;

                                // If the instruction was removed, adjust
                                if mf.blocks[block_idx].instructions.len() < num_insts_before {
                                    break; // Restart iterating the block
                                }
                            }
                        }
                    }
                }
            }
        }

        self.hoisted
    }

    // ========================================================================
    // Loop detection
    // ========================================================================

    /// Find all natural loops in a machine function.
    ///
    /// Uses the CFG formed by block successors. A natural loop has a
    /// single entry point (the header) and at least one backedge.
    pub fn find_loops(&self, mf: &MachineFunction) -> Vec<MachineLoop> {
        let n = mf.blocks.len();
        if n == 0 {
            return Vec::new();
        }

        let mut loops = Vec::new();

        // Build successor/predecessor maps
        let mut succs: HashMap<usize, Vec<usize>> = HashMap::new();
        let mut preds: HashMap<usize, Vec<usize>> = HashMap::new();

        for (idx, block) in mf.blocks.iter().enumerate() {
            for &succ_idx in &block.successors {
                succs.entry(idx).or_default().push(succ_idx);
                preds.entry(succ_idx).or_default().push(idx);
            }
            // Implicit fall-through to next block if no explicit successors
            if block.successors.is_empty() && idx + 1 < n {
                succs.entry(idx).or_default().push(idx + 1);
                preds.entry(idx + 1).or_default().push(idx);
            }
            // Default: self-loop prevention
            succs.entry(idx).or_default();
            preds.entry(idx).or_default();
        }

        // Find backedges: edge a → b where b dominates a (a is in loop with header b)
        for (&header, pred_list) in &preds {
            for &pred in pred_list {
                // Check if pred → header is a backedge:
                // header dominates pred (header is ancestor in dom tree of pred)
                if self.is_backedge(header, pred, &succs, &preds) {
                    // Collect loop blocks: all blocks that can reach the backedge
                    // source (pred) without going through the header
                    let mut loop_blocks = HashSet::new();
                    loop_blocks.insert(header);
                    loop_blocks.insert(pred);

                    // Reverse reachability from pred (excluding header)
                    let mut stack = vec![pred];
                    while let Some(bb) = stack.pop() {
                        for &p in preds.get(&bb).unwrap_or(&Vec::new()) {
                            if p != header && !loop_blocks.contains(&p) {
                                loop_blocks.insert(p);
                                stack.push(p);
                            }
                        }
                    }

                    let blocks: Vec<usize> = {
                        let mut v: Vec<usize> = loop_blocks.into_iter().collect();
                        v.sort();
                        v
                    };

                    // Find preheader: a predecessor of header that is not in the loop
                    let preheader = preds
                        .get(&header)
                        .unwrap_or(&Vec::new())
                        .iter()
                        .find(|p| !blocks.contains(p))
                        .copied();

                    // Find exits: blocks in loop with successors outside loop
                    let mut exits = Vec::new();
                    for &bb in &blocks {
                        if let Some(succ_list) = succs.get(&bb) {
                            for &s in succ_list {
                                if !blocks.contains(&s) {
                                    exits.push(s);
                                }
                            }
                        }
                    }
                    exits.sort();
                    exits.dedup();

                    loops.push(MachineLoop {
                        header,
                        blocks,
                        preheader,
                        exits,
                    });
                }
            }
        }

        loops
    }

    /// Check if edge (from → to) is a backedge.
    ///
    /// A backedge exists from 'from' to 'to' if 'to' dominates 'from'.
    /// Simplified: check if 'to' appears before 'from' in a DFS ordering
    /// from the entry block (block 0).
    fn is_backedge(
        &self,
        header: usize,
        pred: usize,
        succs: &HashMap<usize, Vec<usize>>,
        _preds: &HashMap<usize, Vec<usize>>,
    ) -> bool {
        // Simplified backedge detection:
        // If pred >= header and there's a path from header to pred,
        // then pred → header is likely a backedge.
        if pred < header {
            return false;
        }

        // DFS from header to see if pred is reachable
        let mut visited = HashSet::new();
        let mut stack = vec![header];
        visited.insert(header);

        while let Some(node) = stack.pop() {
            if node == pred {
                return true; // pred reachable from header → backedge
            }
            if let Some(succ_list) = succs.get(&node) {
                for &s in succ_list {
                    if visited.insert(s) {
                        stack.push(s);
                    }
                }
            }
        }

        false
    }

    // ========================================================================
    // Invariant checking
    // ========================================================================

    /// Check if a machine instruction is loop-invariant.
    ///
    /// An instruction is loop-invariant if all its operands are either:
    /// - Constants/immediates
    /// - Defined by instructions outside the loop
    /// - Defined by other loop-invariant instructions inside the loop
    pub fn is_loop_invariant(&self, mi: &MachineInstr, loop_blocks: &[usize]) -> bool {
        let loop_set: HashSet<usize> = loop_blocks.iter().copied().collect();

        // Check each operand
        for operand in &mi.operands {
            match operand {
                MachineOperand::Reg(_vreg) => {
                    // A virtual register use: check if defined outside the loop.
                    // In a real implementation, we'd trace the def chain.
                    // For now, we conservatively assume VRegs might be defined
                    // inside the loop unless proven otherwise.
                    //
                    // Simplified: if the operand isn't a loop-invariant constant,
                    // assume it may be defined inside.
                }
                MachineOperand::PhysReg(_) => {
                    // Physical registers: could be clobbered inside the loop.
                    // Be conservative: only hoist if we can prove the physreg
                    // is not written in the loop.
                    return false;
                }
                MachineOperand::Imm(_) | MachineOperand::Label(_) | MachineOperand::Global(_) => {
                    // Constants and labels are always loop-invariant
                }
            }
        }

        // Check if the instruction definition is a side-effecting operation
        // that must stay in the loop
        if !self.is_safe_to_hoist(mi) {
            return false;
        }

        // For the simplified model: consider it invariant if it has no physreg
        // operands (which are the most common source of loop-variant operands).
        let has_physreg = mi
            .operands
            .iter()
            .any(|op| matches!(op, MachineOperand::PhysReg(_)));

        !has_physreg
    }

    /// Check if it's safe to hoist an instruction.
    ///
    /// Safety conditions:
    /// - Instruction must not have unpredictable side effects
    /// - Memory operations (loads) may fault; only hoist if dominating all exits
    /// - Calls are generally not safe to hoist (may have side effects)
    /// - Stores should not be hoisted (would change memory ordering)
    pub fn is_safe_to_hoist(&self, mi: &MachineInstr) -> bool {
        let opcode = mi.opcode;

        // Approximate opcode classification for common architectures:
        // This is a simplified heuristic based on typical opcode assignments.

        // Memory loads (opcode ranges 2-3 typically): only if hoist_loads is enabled
        let is_load = opcode == 2 || opcode == 3;
        if is_load && !self.hoist_loads {
            return false;
        }

        // Memory stores: almost never safe to hoist
        let is_store = opcode == 20 || opcode == 21;
        if is_store && !self.hoist_stores {
            return false;
        }

        // Branches and calls: never safe to hoist
        let is_branch_or_call = opcode >= 7 && opcode <= 12;
        if is_branch_or_call {
            return false;
        }

        // Side-effect-free ALU operations: safe to hoist
        // (add, sub, mul, and, or, xor, shifts, etc.)
        true
    }

    // ========================================================================
    // Hoisting
    // ========================================================================

    /// Hoist an instruction from its block to the preheader.
    ///
    /// Removes the instruction from its current position and inserts it
    /// at the end of the preheader block (before the terminator).
    pub fn hoist_instruction(&mut self, mf: &mut MachineFunction, mi_idx: usize, preheader: usize) {
        if preheader >= mf.blocks.len() || mi_idx >= mf.blocks.len() {
            return;
        }

        // Find which block contains this instruction
        let mut source_block_idx = None;
        for (idx, block) in mf.blocks.iter().enumerate() {
            if mi_idx < block.instructions.len() {
                // This is a guess — in a real implementation we'd track
                // the block for each instruction.
                source_block_idx = Some(idx);
                break;
            }
        }

        if let Some(src_idx) = source_block_idx {
            if src_idx >= mf.blocks.len() || mi_idx >= mf.blocks[src_idx].instructions.len() {
                return;
            }

            // Remove the instruction from the source block
            let mi = mf.blocks[src_idx].instructions.remove(mi_idx);

            // Insert before the terminator in the preheader
            let ph_block = &mut mf.blocks[preheader];
            let insert_pos = if ph_block.instructions.is_empty() {
                0
            } else {
                // Insert before the last instruction (typically the terminator)
                let last = ph_block.instructions.len().saturating_sub(1);
                // Check if last instruction is a branch-like terminator
                let last_opcode = ph_block.instructions[last].opcode;
                if last_opcode >= 7 && last_opcode <= 12 {
                    last // Insert before terminator
                } else {
                    ph_block.instructions.len() // Append
                }
            };

            ph_block.instructions.insert(insert_pos, mi);
        }
    }
}

impl Default for MachineLICM {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// MachineLoopInfo — Full Loop Detection and Analysis
// ============================================================================

/// MachineLoopInfo provides comprehensive loop analysis for machine functions.
/// Builds upon MachineLoop to include nesting, depth, invariants, and
/// register pressure estimates.
#[derive(Debug, Clone)]
pub struct MachineLoopInfo {
    /// All loops in the function, in nesting order (outer to inner).
    pub loops: Vec<MachineLoop>,
    /// Mapping from block index to the innermost loop containing it.
    pub block_to_loop: HashMap<usize, usize>,
    /// Loop nesting depths.
    pub depths: HashMap<usize, u32>,
    /// Dominator tree for loop detection.
    pub idom: Vec<Option<usize>>,
    /// Set of blocks that are loop headers.
    pub headers: HashSet<usize>,
}

impl MachineLoopInfo {
    /// Create a new machine loop info.
    pub fn new() -> Self {
        Self {
            loops: Vec::new(),
            block_to_loop: HashMap::new(),
            depths: HashMap::new(),
            idom: Vec::new(),
            headers: HashSet::new(),
        }
    }

    /// Analyze loops in the machine function.
    pub fn analyze(&mut self, mf: &MachineFunction) {
        self.loops.clear();
        self.block_to_loop.clear();
        self.depths.clear();
        self.headers.clear();

        if mf.blocks.is_empty() {
            return;
        }

        // Build dominance info
        self.build_dominators(mf);

        // Find back edges and identify loops
        self.find_loops_from_backedges(mf);

        // Compute nesting depths
        self.compute_depths();
    }

    /// Build immediate dominators.
    fn build_dominators(&mut self, mf: &MachineFunction) {
        let n = mf.blocks.len();
        self.idom = vec![None; n];
        if n == 0 {
            return;
        }

        // Entry dominates itself
        self.idom[0] = Some(0);

        let mut changed = true;
        while changed {
            changed = false;
            for i in 1..n {
                // Find predecessors
                let pred_indices: Vec<usize> = (0..n)
                    .filter(|&p| mf.blocks[p].successors.contains(&i))
                    .collect();

                if pred_indices.is_empty() {
                    continue;
                }

                // New idom = intersection of predecessors' idoms
                let mut new_idom = pred_indices[0];
                for &p in &pred_indices[1..] {
                    new_idom = self.intersect(new_idom, p);
                }

                if self.idom[i] != Some(new_idom) {
                    self.idom[i] = Some(new_idom);
                    changed = true;
                }
            }
        }
    }

    /// Intersect two nodes in the dominator tree.
    fn intersect(&self, mut a: usize, mut b: usize) -> usize {
        while a != b {
            while a > b {
                a = self.idom[a].unwrap_or(a);
            }
            while b > a {
                b = self.idom[b].unwrap_or(b);
            }
        }
        a
    }

    /// Find loops by detecting back edges.
    fn find_loops_from_backedges(&mut self, mf: &MachineFunction) {
        let n = mf.blocks.len();

        for src in 0..n {
            for &dst in &mf.blocks[src].successors {
                {
                    // Check if src -> dst is a back edge:
                    // dst dominates src (idom(src) eventually reaches dst)
                    if self.is_backedge(src, dst) {
                        // dst is a loop header; collect loop body
                        let body = self.collect_loop_body(dst, src, mf);
                        let exits = self.find_exits(dst, &body, mf);

                        let preheader = self.find_preheader(dst, &body, mf);

                        let ml = MachineLoop {
                            header: dst,
                            blocks: body,
                            preheader,
                            exits,
                        };

                        self.loops.push(ml);
                        self.headers.insert(dst);
                    }
                }
            }
        }

        // Sort by size (outer loops first)
        self.loops.sort_by_key(|l| -(l.blocks.len() as isize));
    }

    /// Check if src -> dst is a back edge.
    fn is_backedge(&self, src: usize, dst: usize) -> bool {
        // dst dominates src: walk idom from src, if we reach dst, it's a back edge
        let mut current = src;
        let mut visited = HashSet::new();

        while let Some(idom) = self.idom.get(current).copied().flatten() {
            if idom == dst {
                return true;
            }
            if idom == current || !visited.insert(current) {
                break;
            }
            current = idom;
        }

        false
    }

    /// Collect blocks in the loop body (header + blocks reachable from
    /// header that have a path back to header without going through header).
    fn collect_loop_body(
        &self,
        header: usize,
        backedge_src: usize,
        mf: &MachineFunction,
    ) -> Vec<usize> {
        let mut body = HashSet::new();
        body.insert(header);

        // Work backwards from backedge_src through predecessors,
        // collecting blocks that can reach backedge_src without
        // going through header.
        let mut worklist = vec![backedge_src];
        let mut visited = HashSet::new();
        visited.insert(header);

        while let Some(block) = worklist.pop() {
            if !body.insert(block) {
                continue;
            }

            // Find predecessors (blocks that have `block` as successor)
            let preds: Vec<usize> = (0..mf.blocks.len())
                .filter(|&p| mf.blocks[p].successors.contains(&block))
                .collect();

            for pred in preds {
                if visited.insert(pred) {
                    worklist.push(pred);
                }
            }
        }

        let mut body_vec: Vec<usize> = body.into_iter().collect();
        body_vec.sort_unstable();
        body_vec
    }

    /// Find loop exit blocks.
    fn find_exits(&self, header: usize, body: &[usize], mf: &MachineFunction) -> Vec<usize> {
        let body_set: HashSet<usize> = body.iter().copied().collect();
        let mut exits = Vec::new();

        for &block in body {
            for &succ in &mf.blocks[block].successors {
                if !body_set.contains(&succ) {
                    exits.push(succ);
                }
            }
        }

        exits.sort_unstable();
        exits.dedup();
        exits
    }

    /// Find a suitable preheader for the loop.
    fn find_preheader(&self, header: usize, body: &[usize], mf: &MachineFunction) -> Option<usize> {
        let body_set: HashSet<usize> = body.iter().copied().collect();

        // Find predecessors of header that are not in the loop body
        let preds: Vec<usize> = (0..mf.blocks.len())
            .filter(|&p| mf.blocks[p].successors.contains(&header) && !body_set.contains(&p))
            .collect();

        // If there's exactly one, it's a natural preheader
        if preds.len() == 1 {
            Some(preds[0])
        } else if !preds.is_empty() {
            // Return the first as a candidate
            Some(preds[0])
        } else {
            None
        }
    }

    /// Compute nesting depths for all loops.
    fn compute_depths(&mut self) {
        for (i, outer) in self.loops.iter().enumerate() {
            let outer_set: HashSet<usize> = outer.blocks.iter().copied().collect();
            let mut depth = 1;

            for inner in &self.loops {
                if inner.header == outer.header {
                    continue;
                }
                let inner_set: HashSet<usize> = inner.blocks.iter().copied().collect();
                if inner_set.is_subset(&outer_set) && inner_set.len() < outer_set.len() {
                    depth += 1;
                }
            }

            self.depths.insert(i, depth);

            // Map blocks to innermost loop
            for &block in &outer.blocks {
                if !self.block_to_loop.contains_key(&block) {
                    self.block_to_loop.insert(block, i);
                }
            }
        }
    }

    /// Get the loop containing a block, if any.
    pub fn get_loop_for_block(&self, block: usize) -> Option<&MachineLoop> {
        self.block_to_loop
            .get(&block)
            .and_then(|&idx| self.loops.get(idx))
    }

    /// Check if a block is a loop header.
    pub fn is_loop_header(&self, block: usize) -> bool {
        self.headers.contains(&block)
    }

    /// Get the depth of a loop.
    pub fn get_loop_depth(&self, loop_idx: usize) -> u32 {
        self.depths.get(&loop_idx).copied().unwrap_or(0)
    }
}

impl Default for MachineLoopInfo {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// Loop Safety Predicates for Machine Operations
// ============================================================================

/// SafetyPredicate categorizes whether a machine instruction can
/// be safely hoisted or sunk.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SafetyPredicate {
    /// Always safe to hoist/sink (e.g., pure ALU).
    Always,
    /// Safe if no exception can occur (e.g., non-faulting loads).
    NoException,
    /// Safe if memory doesn't alias (e.g., stores/loads).
    NoAlias,
    /// Safe only if dominating all exits (control-dependent).
    DominateExits,
    /// Never safe (has side effects, calls, etc.).
    Never,
}

/// LoopSafetyAnalyzer determines safety predicates for machine instructions.
pub struct LoopSafetyAnalyzer {
    /// Cache of safety predicates per instruction.
    pub predicate_cache: HashMap<(usize, usize), SafetyPredicate>,
}

impl LoopSafetyAnalyzer {
    /// Create a new safety analyzer.
    pub fn new() -> Self {
        Self {
            predicate_cache: HashMap::new(),
        }
    }

    /// Analyze an instruction's safety for hoisting.
    pub fn analyze_instruction(&self, instr: &MachineInstr) -> SafetyPredicate {
        // Check for branches/calls (never safe)
        let has_label = instr
            .operands
            .iter()
            .any(|op| matches!(op, MachineOperand::Label(_)));

        if has_label {
            return SafetyPredicate::Never;
        }

        // Check for memory operations
        let is_load = instr.opcode == 2 || instr.opcode == 3;
        let is_store = instr.opcode == 4 || instr.opcode == 5;

        if is_store {
            SafetyPredicate::NoAlias
        } else if is_load {
            SafetyPredicate::NoException
        } else {
            // Pure ALU operation
            SafetyPredicate::Always
        }
    }

    /// Check if an instruction is safe to hoist from a loop.
    pub fn is_safe_to_hoist(
        &self,
        instr: &MachineInstr,
        loop_body: &[usize],
        block_idx: usize,
        mf: &MachineFunction,
    ) -> bool {
        let pred = self.analyze_instruction(instr);

        match pred {
            SafetyPredicate::Always => true,
            SafetyPredicate::NoException => {
                // Check if the load address is known non-faulting
                // Conservative: only hoist if the load is from a known-valid address
                false // Conservative default
            }
            SafetyPredicate::NoAlias => {
                // Check if the store may alias with other memory ops in loop
                false // Conservative default
            }
            SafetyPredicate::DominateExits => {
                // Check if the instruction dominates all loop exits
                self.dominates_all_exits(block_idx, loop_body, mf)
            }
            SafetyPredicate::Never => false,
        }
    }

    /// Check if a block dominates all loop exits (simplified).
    fn dominates_all_exits(
        &self,
        block_idx: usize,
        _loop_body: &[usize],
        _mf: &MachineFunction,
    ) -> bool {
        // Simplified: only true if the instruction is in the loop header
        // or there's a single exit that is below in the layout.
        block_idx == 0 // Conservative
    }

    /// Clear the predicate cache.
    pub fn clear_cache(&mut self) {
        self.predicate_cache.clear();
    }
}

impl Default for LoopSafetyAnalyzer {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// Register Pressure Consideration
// ============================================================================

/// RegisterPressure tracks the number of live registers at each point
/// and estimates the impact of code motion on register pressure.
pub struct RegisterPressure {
    /// Maximum number of live registers observed.
    pub max_pressure: usize,
    /// Current register pressure at each block.
    pub pressure_per_block: HashMap<usize, usize>,
    /// Available physical registers.
    pub available_regs: usize,
    /// Threshold above which hoisting is discouraged.
    pub high_pressure_threshold: usize,
}

impl RegisterPressure {
    /// Create a new register pressure tracker.
    pub fn new(available_regs: usize) -> Self {
        Self {
            max_pressure: 0,
            pressure_per_block: HashMap::new(),
            available_regs,
            high_pressure_threshold: available_regs * 3 / 4,
        }
    }

    /// Compute register pressure for all blocks.
    pub fn compute(&mut self, mf: &MachineFunction) {
        self.pressure_per_block.clear();
        self.max_pressure = 0;

        for (block_idx, block) in mf.blocks.iter().enumerate() {
            let mut live: HashSet<VirtReg> = HashSet::new();
            let mut block_max = 0;

            for instr in &block.instructions {
                // Add uses to live set
                for op in &instr.operands {
                    if let MachineOperand::Reg(vreg) = *op {
                        live.insert(vreg);
                    }
                    if let MachineOperand::PhysReg(_pr) = *op {
                        // Physical regs also consume register resources
                    }
                }

                block_max = block_max.max(live.len());

                // Remove def from live set
                if let Some(def_vreg) = instr.def {
                    live.remove(&def_vreg);
                }
            }

            self.pressure_per_block.insert(block_idx, block_max);
            self.max_pressure = self.max_pressure.max(block_max);
        }
    }

    /// Check if hoisting would increase register pressure unacceptably.
    pub fn would_increase_pressure(&self, block_idx: usize, _vregs_added: &[VirtReg]) -> bool {
        let current = self
            .pressure_per_block
            .get(&block_idx)
            .copied()
            .unwrap_or(0);

        // If current pressure + new registers exceeds threshold, hoisting
        // may cause spilling.
        current + _vregs_added.len() > self.high_pressure_threshold
    }

    /// Estimate the cost of hoisting in terms of register pressure.
    pub fn hoisting_cost(&self, from_block: usize, to_block: usize, vregs_used: &[VirtReg]) -> i64 {
        let from_pressure = self
            .pressure_per_block
            .get(&from_block)
            .copied()
            .unwrap_or(0);
        let to_pressure = self.pressure_per_block.get(&to_block).copied().unwrap_or(0);

        // Negative cost = hoisting is beneficial (reduces pressure in loop)
        // Positive cost = hoisting is costly (increases pressure in preheader)
        let loop_reduction = from_pressure as i64 - vregs_used.len() as i64;
        let preheader_increase = (to_pressure + vregs_used.len()) as i64;

        preheader_increase - loop_reduction
    }

    /// Print pressure statistics.
    pub fn print_stats(&self) {
        eprintln!(
            "RegisterPressure: max={}, available={}, threshold={}",
            self.max_pressure, self.available_regs, self.high_pressure_threshold
        );
    }
}

impl Default for RegisterPressure {
    fn default() -> Self {
        Self::new(16)
    }
}

// ============================================================================
// Machine Instruction Sinking
// ============================================================================

/// MachineSink moves instructions down into successor blocks when
/// they are only needed on certain paths, reducing register pressure
/// on other paths (inverse of LICM).
pub struct MachineSink {
    /// Number of instructions sunk.
    pub sunk: usize,
    /// Maximum sink depth.
    pub max_depth: usize,
}

impl MachineSink {
    /// Create a new MachineSink pass.
    pub fn new() -> Self {
        Self {
            sunk: 0,
            max_depth: 10,
        }
    }

    /// Run instruction sinking on a function.
    pub fn run_on_function(&mut self, mf: &mut MachineFunction) -> usize {
        self.sunk = 0;

        for block_idx in 0..mf.blocks.len() {
            let succ_indices: Vec<usize> = {
                let block = &mf.blocks[block_idx];
                block.successors.clone()
            };

            if succ_indices.len() <= 1 {
                continue;
            }

            // For each instruction, check if it's only used in one successor
            let mut to_sink: Vec<(usize, usize)> = Vec::new();

            for (instr_idx, instr) in mf.blocks[block_idx].instructions.iter().enumerate() {
                if instr.def.is_none() {
                    continue;
                }

                let def_vreg = instr.def.unwrap();

                // Check which successor uses this def
                let mut users: Vec<usize> = Vec::new();
                for &succ_idx in &succ_indices {
                    let succ = &mf.blocks[succ_idx];
                    let used_in_succ = succ.instructions.iter().any(|mi| {
                        mi.operands.iter().any(|op| {
                            if let MachineOperand::Reg(v) = *op {
                                v == def_vreg
                            } else {
                                false
                            }
                        })
                    });
                    if used_in_succ {
                        users.push(succ_idx);
                    }
                }

                // If used in exactly one successor and nowhere else,
                // we can sink the instruction to that successor.
                if users.len() == 1 {
                    // Check no other blocks use this def
                    let all_other_blocks_use = mf.blocks.iter().enumerate().any(|(i, b)| {
                        i != block_idx
                            && i != users[0]
                            && b.instructions.iter().any(|mi| {
                                mi.operands.iter().any(|op| {
                                    if let MachineOperand::Reg(v) = *op {
                                        v == def_vreg
                                    } else {
                                        false
                                    }
                                })
                            })
                    });

                    if !all_other_blocks_use {
                        to_sink.push((instr_idx, users[0]));
                    }
                }
            }

            // Sink instructions (in reverse order)
            to_sink.sort_by_key(|(i, _)| *i);
            for &(instr_idx, target) in to_sink.iter().rev() {
                if instr_idx < mf.blocks[block_idx].instructions.len() {
                    let instr = mf.blocks[block_idx].instructions.remove(instr_idx);
                    mf.blocks[target].instructions.insert(0, instr);
                    self.sunk += 1;
                }
            }
        }

        self.sunk
    }
}

impl Default for MachineSink {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// LICM with Loop Info and Register Pressure
// ============================================================================

/// FullLICM orchestrates loop detection, safety analysis, register
/// pressure tracking, and code motion into a complete LICM pass.
pub struct FullLICM {
    /// Core LICM pass.
    pub licm: MachineLICM,
    /// Loop information.
    pub loop_info: MachineLoopInfo,
    /// Safety analyzer.
    pub safety: LoopSafetyAnalyzer,
    /// Register pressure tracker.
    pub pressure: RegisterPressure,
    /// Instruction sinker.
    pub sink: MachineSink,
}

impl FullLICM {
    /// Create a new FullLICM pass.
    pub fn new() -> Self {
        Self {
            licm: MachineLICM::new(),
            loop_info: MachineLoopInfo::new(),
            safety: LoopSafetyAnalyzer::new(),
            pressure: RegisterPressure::new(16),
            sink: MachineSink::new(),
        }
    }

    /// Run full LICM on a machine function.
    pub fn run_on_function(&mut self, mf: &mut MachineFunction) -> usize {
        // Step 1: Analyze loops
        self.loop_info.analyze(mf);

        // Step 2: Compute register pressure baseline
        self.pressure.compute(mf);

        // Step 3: Run core LICM
        let hoisted = self.licm.run_on_function(mf);

        // Step 4: Run sinking to balance register pressure
        let sunk = self.sink.run_on_function(mf);

        hoisted + sunk
    }

    /// Print pass statistics.
    pub fn print_stats(&self) {
        eprintln!(
            "FullLICM: {} hoisted, {} sunk, {} loops found",
            self.licm.hoisted,
            self.sink.sunk,
            self.loop_info.loops.len()
        );
        self.pressure.print_stats();
    }
}

impl Default for FullLICM {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    fn make_mi(opcode: u32) -> MachineInstr {
        MachineInstr {
            opcode,
            operands: Vec::new(),
            def: None,
        }
    }

    fn make_mi_with_physreg(opcode: u32, reg: u32) -> MachineInstr {
        MachineInstr {
            opcode,
            operands: vec![MachineOperand::PhysReg(reg)],
            def: None,
        }
    }

    fn make_mi_with_imm(opcode: u32) -> MachineInstr {
        MachineInstr {
            opcode,
            operands: vec![MachineOperand::Imm(42)],
            def: None,
        }
    }

    #[test]
    fn test_machine_licm_new() {
        let licm = MachineLICM::new();
        assert_eq!(licm.hoisted, 0);
        assert!(!licm.hoist_loads);
        assert!(!licm.hoist_stores);
    }

    #[test]
    fn test_default() {
        let licm = MachineLICM::default();
        assert!(!licm.hoist_loads);
    }

    #[test]
    fn test_is_safe_to_hoist_alu() {
        let licm = MachineLICM::new();
        let mi = make_mi(1); // ALU op
        assert!(licm.is_safe_to_hoist(&mi));
    }

    #[test]
    fn test_is_safe_to_hoist_load_disabled() {
        let licm = MachineLICM::new();
        let mi = make_mi(2); // Load op
        assert!(!licm.is_safe_to_hoist(&mi));
    }

    #[test]
    fn test_is_safe_to_hoist_load_enabled() {
        let mut licm = MachineLICM::new();
        licm.hoist_loads = true;
        let mi = make_mi(2); // Load op
        assert!(licm.is_safe_to_hoist(&mi));
    }

    #[test]
    fn test_is_safe_to_hoist_branch() {
        let licm = MachineLICM::new();
        let mi = make_mi(7); // Branch op
        assert!(!licm.is_safe_to_hoist(&mi));
    }

    #[test]
    fn test_is_loop_invariant_physreg() {
        let licm = MachineLICM::new();
        let mi = make_mi_with_physreg(1, 3);
        let loop_blocks = vec![0, 1, 2];
        // Has physreg operand → not invariant
        assert!(!licm.is_loop_invariant(&mi, &loop_blocks));
    }

    #[test]
    fn test_is_loop_invariant_imm() {
        let licm = MachineLICM::new();
        let mi = make_mi_with_imm(1);
        let loop_blocks = vec![0, 1, 2];
        // Immediate operands are loop-invariant
        assert!(licm.is_loop_invariant(&mi, &loop_blocks));
    }

    #[test]
    fn test_is_loop_invariant_no_ops() {
        let licm = MachineLICM::new();
        let mi = make_mi(5);
        let loop_blocks = vec![0, 1, 2];
        // No operands → trivially invariant (if safe to hoist)
        assert!(licm.is_loop_invariant(&mi, &loop_blocks));
    }

    #[test]
    fn test_find_loops_empty() {
        let licm = MachineLICM::new();
        let mf = MachineFunction::new("empty");
        let loops = licm.find_loops(&mf);
        assert!(loops.is_empty());
    }

    #[test]
    fn test_find_loops_single_block() {
        let licm = MachineLICM::new();
        let mut mf = MachineFunction::new("func");
        mf.push_block(MachineBasicBlock {
            name: "entry".to_string(),
            instructions: vec![make_mi(1)],
            successors: Vec::new(),
        });
        let loops = licm.find_loops(&mf);
        // Single block: no backedges → no loops
        assert!(loops.is_empty());
    }

    #[test]
    fn test_find_loops_with_backedge() {
        let licm = MachineLICM::new();
        let mut mf = MachineFunction::new("func");
        mf.push_block(MachineBasicBlock {
            name: "entry".to_string(),
            instructions: Vec::new(),
            successors: vec!["loop_header".to_string()],
        });
        mf.push_block(MachineBasicBlock {
            name: "loop_header".to_string(),
            instructions: Vec::new(),
            successors: vec!["loop_body".to_string()],
        });
        mf.push_block(MachineBasicBlock {
            name: "loop_body".to_string(),
            instructions: Vec::new(),
            successors: vec!["loop_header".to_string()], // backedge
        });
        let loops = licm.find_loops(&mf);
        // Should find loop with header=1
        assert!(!loops.is_empty());
    }

    #[test]
    fn test_run_on_empty_function() {
        let mut licm = MachineLICM::new();
        let mut mf = MachineFunction::new("empty");
        let count = licm.run_on_function(&mut mf);
        assert_eq!(count, 0);
    }

    #[test]
    fn test_run_on_simple_function() {
        let mut licm = MachineLICM::new();
        let mut mf = MachineFunction::new("func");
        mf.push_block(MachineBasicBlock {
            name: "entry".to_string(),
            instructions: vec![make_mi(1)],
            successors: Vec::new(),
        });
        let count = licm.run_on_function(&mut mf);
        // No loops → no hoisting
        assert_eq!(count, 0);
    }

    #[test]
    fn test_hoist_instruction() {
        let mut licm = MachineLICM::new();
        let mut mf = MachineFunction::new("func");
        mf.push_block(MachineBasicBlock {
            name: "preheader".to_string(),
            instructions: Vec::new(),
            successors: vec!["body".to_string()],
        });
        mf.push_block(MachineBasicBlock {
            name: "body".to_string(),
            instructions: vec![make_mi(1)],
            successors: Vec::new(),
        });

        // Hoist the ALU instruction from body (idx 1) to preheader (idx 0)
        licm.hoist_instruction(&mut mf, 0, 0);
        // The body block should now be empty
        assert_eq!(mf.blocks[1].instructions.len(), 0);
        // The preheader should have the instruction
        assert_eq!(mf.blocks[0].instructions.len(), 1);
    }

    #[test]
    fn test_hoist_loads_flag() {
        let mut licm = MachineLICM::new();
        assert!(!licm.hoist_loads);
        licm.hoist_loads = true;
        assert!(licm.hoist_loads);
    }

    #[test]
    fn test_hoist_stores_flag() {
        let mut licm = MachineLICM::new();
        assert!(!licm.hoist_stores);
        licm.hoist_stores = true;
        assert!(licm.hoist_stores);
    }
}