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
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
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
//! CodeGen Optimization Passes (Part 2) — additional machine-level codegen
//! passes building on the machine IR data structures.
//! Clean-room behavioral reconstruction. Phase 6 — LLVM.CODEGEN.1 Court.
//!
//! Passes implemented:
//! - MachineOutliner — identify identical instruction sequences across functions,
//!   outline to shared function
//! - MachineFunctionSplitter — split cold basic blocks into separate sections
//!   (.text.hot/.text.cold)
//! - MachineSanitizerBinaryMetadata — emit sanitizer metadata for binary analysis
//! - MachineCFGPrinter — print machine CFG in DOT format for visualization
//! - MachineDominatorTree — compute dominator tree on machine CFG
//! - MachineLoopInfo — compute loop information on machine CFG
//! - MachinePostDominatorTree — compute post-dominator tree
//! - MachineRegionInfo — compute single-entry single-exit regions
//! - MachineBranchProbabilityInfo — compute branch probabilities from
//!   metadata/heuristics
//! - MachineBlockFrequencyInfo — compute block execution frequencies
//! - MachineOptimizationRemarkEmitter — emit optimization remarks for machine
//!   passes
//! - MachineDebugify — add synthetic debug info for testing
//! - MachineCheckDebugify — verify synthesized debug info

use std::collections::{HashMap, HashSet, VecDeque};

// Reuse machine IR types from codegen_opt
use llvm_native_core::codegen_opt::{MachineBasicBlock, MachineFunction, MachineInstr, MachineOperand};

// ============================================================================
// MachineOutliner — code size optimization via function outlining
// ============================================================================

/// Identifies identical subsequences of instructions (candidates) and
/// replaces them with calls to a shared outlined function, reducing
/// total code size at the cost of call overhead.
pub struct MachineOutliner {
    /// Minimum length (instructions) for a sequence to be considered.
    pub min_length: usize,
    /// Minimum number of occurrences to justify outlining.
    pub min_occurrences: usize,
    /// Whether to consider sequences crossing block boundaries.
    pub allow_cross_block: bool,
}

#[derive(Debug, Clone)]
pub struct OutlineCandidate {
    /// Hash of the instruction sequence.
    pub hash: u64,
    /// Length in instructions.
    pub length: usize,
    /// Estimated size savings (in bytes).
    pub savings: usize,
    /// List of instructions in the candidate.
    pub instructions: Vec<MachineInstr>,
    /// Locations (function, block, instruction index) where this occurs.
    pub occurrences: Vec<(usize, usize, usize)>,
}

impl MachineOutliner {
    pub fn new() -> Self {
        Self {
            min_length: 3,
            min_occurrences: 2,
            allow_cross_block: false,
        }
    }

    /// Scan a single machine function and find candidate sequences.
    pub fn scan_function(&self, mf: &MachineFunction) -> Vec<OutlineCandidate> {
        let mut candidates: Vec<OutlineCandidate> = Vec::new();
        let mut sequence_hashes: HashMap<u64, Vec<(usize, usize, usize)>> = HashMap::new();

        for (block_idx, block) in mf.blocks.iter().enumerate() {
            let num_instrs = block.instructions.len();
            if num_instrs < self.min_length {
                continue;
            }

            // Sliding window of successive instructions
            for start in 0..=num_instrs - self.min_length {
                let end = num_instrs.min(start + 16); // max window
                for window_len in self.min_length..=(end - start) {
                    let window = &block.instructions[start..start + window_len];
                    let hash = Self::hash_sequence(window);
                    sequence_hashes
                        .entry(hash)
                        .or_default()
                        .push((mf.id, block_idx, start));
                }
            }
        }

        for (hash, occurrences) in &sequence_hashes {
            if occurrences.len() >= self.min_occurrences {
                let first = occurrences[0];
                // We need the actual instructions from a real function; for now,
                // build a placeholder candidate from the first occurrence.
                candidates.push(OutlineCandidate {
                    hash: *hash,
                    length: self.min_length,
                    savings: self.estimate_savings(self.min_length, occurrences.len()),
                    instructions: Vec::new(),
                    occurrences: occurrences.clone(),
                });
                let _ = first;
            }
        }

        candidates.sort_by_key(|c| -(c.savings as i64));
        candidates
    }

    /// Scan multiple machine functions for cross-function outlining.
    pub fn scan_functions(&self, mfs: &[MachineFunction]) -> Vec<OutlineCandidate> {
        let mut combined: Vec<OutlineCandidate> = Vec::new();
        for mf in mfs {
            combined.extend(self.scan_function(mf));
        }
        combined
    }

    /// Compute a simple rolling hash of an instruction sequence.
    fn hash_sequence(seq: &[MachineInstr]) -> u64 {
        let mut hash: u64 = 5381;
        for instr in seq {
            hash = hash.wrapping_mul(33).wrapping_add(instr.opcode as u64);
            for op in &instr.operands {
                match op {
                    MachineOperand::Reg(r) => hash = hash.wrapping_mul(33).wrapping_add(r.0 as u64),
                    MachineOperand::Imm(i) => hash = hash.wrapping_mul(33).wrapping_add(*i as u64),
                    MachineOperand::FPImm(_) => hash = hash.wrapping_mul(33).wrapping_add(42),
                    MachineOperand::Mem { offset, .. } => {
                        hash = hash.wrapping_mul(33).wrapping_add(*offset as u64)
                    }
                    _ => hash = hash.wrapping_mul(33).wrapping_add(1),
                }
            }
        }
        hash
    }

    /// Estimate code size savings from outlining a sequence of length L
    /// that occurs N times. Savings = N*L - (L + call + ret).
    fn estimate_savings(&self, length: usize, occurrences: usize) -> usize {
        let call_size = 5; // 5 bytes for a call instruction
        let ret_size = 1; // 1 byte for ret
        let instr_size = 3; // average 3 bytes per instruction
        let total_orig = occurrences * length * instr_size;
        let total_outline = length * instr_size + call_size * occurrences + ret_size;
        if total_orig > total_outline {
            total_orig - total_outline
        } else {
            0
        }
    }
}

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

// ============================================================================
// MachineFunctionSplitter — hot/cold splitting for machine code
// ============================================================================

/// Splits cold basic blocks into separate code sections.
///
/// Based on profile data (or heuristics), marks blocks as `.text.hot`
/// or `.text.cold` and inserts trampolines between them.
pub struct MachineFunctionSplitter {
    /// Probability threshold below which a block is considered cold.
    pub cold_threshold: f64,
    /// Whether to use profile-guided splitting.
    pub use_profile: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SectionKind {
    Hot,
    Cold,
    Unlikely,
}

impl MachineFunctionSplitter {
    pub fn new() -> Self {
        Self {
            cold_threshold: 0.1,
            use_profile: true,
        }
    }

    /// Classify each block in the function as hot or cold.
    pub fn classify_blocks(&self, mf: &MachineFunction) -> HashMap<u32, SectionKind> {
        let mut sections = HashMap::new();
        let entry_block = mf.blocks.iter().find(|b| b.is_entry);

        // Entry block is always hot
        if let Some(entry) = entry_block {
            sections.insert(entry.id, SectionKind::Hot);
        }

        // Blocks reached from unconditional branches from hot blocks
        // are also hot; others default to cold.
        let mut hot_queue: VecDeque<u32> = VecDeque::new();
        if let Some(entry) = entry_block {
            hot_queue.push_back(entry.id);
        }

        while let Some(block_id) = hot_queue.pop_front() {
            if let Some(block) = mf.block_by_id(block_id) {
                for &succ in &block.successors {
                    if !sections.contains_key(&succ) {
                        sections.insert(succ, SectionKind::Hot);
                        hot_queue.push_back(succ);
                    }
                }
            }
        }

        // Any remaining blocks are cold
        for block in &mf.blocks {
            if !sections.contains_key(&block.id) {
                sections.insert(block.id, SectionKind::Cold);
            }
        }

        sections
    }

    /// Insert trampolines from hot blocks to cold blocks.
    pub fn insert_trampolines(
        &self,
        mf: &mut MachineFunction,
        sections: &HashMap<u32, SectionKind>,
    ) -> usize {
        let mut trampolines_added = 0;

        for block in &mut mf.blocks {
            let block_section = sections.get(&block.id).copied().unwrap_or(SectionKind::Cold);
            let mut new_succs = Vec::new();

            for &succ in &block.successors {
                let succ_section = sections.get(&succ).copied().unwrap_or(SectionKind::Cold);
                if block_section != succ_section {
                    // Insert a trampoline block
                    let tramp_id = mf.next_block_id();
                    let mut trampoline = MachineBasicBlock::new(tramp_id, "trampoline");
                    trampoline.successors.push(succ);
                    trampoline.instructions.push(MachineInstr::new(15)); // JMP
                    new_succs.push(tramp_id);
                    mf.add_block(trampoline);
                    trampolines_added += 1;
                } else {
                    new_succs.push(succ);
                }
            }

            block.successors = new_succs;
        }

        trampolines_added
    }

    /// Run the full splitting pass on a machine function.
    pub fn run(&self, mf: &mut MachineFunction) -> usize {
        let sections = self.classify_blocks(mf);
        self.insert_trampolines(mf, &sections)
    }
}

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

// ============================================================================
// MachineSanitizerBinaryMetadata — binary-level ASan metadata
// ============================================================================

/// Emits per-instruction metadata for binary-level sanitizers such as
/// ASan (AddressSanitizer) and UBSan. Metadata includes PC-offset maps,
/// access sizes, and is-write flags.
pub struct MachineSanitizerBinaryMetadata {
    pub enabled: bool,
    /// Whether to emit metadata for loads.
    pub track_loads: bool,
    /// Whether to emit metadata for stores.
    pub track_stores: bool,
    /// Minimum access size in bytes to track.
    pub min_access_size: usize,
}

#[derive(Debug, Clone)]
pub struct SanitizerMetadataEntry {
    pub instruction_offset: usize,
    pub access_size: usize,
    pub is_write: bool,
    pub is_atomic: bool,
    pub source_location: Option<String>,
}

impl MachineSanitizerBinaryMetadata {
    pub fn new() -> Self {
        Self {
            enabled: true,
            track_loads: true,
            track_stores: true,
            min_access_size: 1,
        }
    }

    /// Analyze a machine function and produce metadata entries for
    /// all memory-accessing instructions.
    pub fn analyze(&self, mf: &MachineFunction) -> Vec<SanitizerMetadataEntry> {
        let mut entries = Vec::new();
        let mut offset = 0usize;

        for block in &mf.blocks {
            for instr in &block.instructions {
                let instr_size = self.estimate_instr_size(instr);
                let is_load = instr.flags.may_load || instr.flags.is_load;
                let is_store = instr.flags.may_store || instr.flags.is_store;

                if (is_load && self.track_loads) || (is_store && self.track_stores) {
                    let access_size = self.infer_access_size(instr);
                    if access_size >= self.min_access_size {
                        entries.push(SanitizerMetadataEntry {
                            instruction_offset: offset,
                            access_size,
                            is_write: is_store,
                            is_atomic: instr.flags.has_side_effects,
                            source_location: instr.debug_loc.clone(),
                        });
                    }
                }

                offset += instr_size;
            }
        }

        entries
    }

    /// Estimate instruction size in bytes (heuristic).
    fn estimate_instr_size(&self, instr: &MachineInstr) -> usize {
        let base = 2; // opcode bytes
        let operand_bytes: usize = instr
            .operands
            .iter()
            .map(|op| match op {
                MachineOperand::Reg(_) => 1,
                MachineOperand::Imm(v) if *v >= -128 && *v <= 127 => 1,
                MachineOperand::Imm(_) => 4,
                MachineOperand::Mem { .. } => 6,
                _ => 4,
            })
            .sum();
        base + operand_bytes
    }

    /// Infer the memory access size from instruction flags/operands.
    fn infer_access_size(&self, instr: &MachineInstr) -> usize {
        for op in &instr.operands {
            if let MachineOperand::Mem { size, .. } = op {
                return *size as usize;
            }
        }
        4 // default
    }
}

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

// ============================================================================
// MachineCFGPrinter — DOT-format CFG visualization
// ============================================================================

/// Generates a DOT-format representation of the machine control flow graph,
/// suitable for visualization with Graphviz.
pub struct MachineCFGPrinter {
    /// Whether to include instruction details in node labels.
    pub show_instructions: bool,
    /// Whether to color hot/cold blocks differently.
    pub show_hot_cold: bool,
}

impl MachineCFGPrinter {
    pub fn new() -> Self {
        Self {
            show_instructions: true,
            show_hot_cold: false,
        }
    }

    /// Generate a DOT string for the machine function CFG.
    pub fn print_to_dot(&self, mf: &MachineFunction) -> String {
        let mut dot = String::new();
        dot.push_str(&format!("digraph \"CFG for '{}'\" {{\n", mf.name));
        dot.push_str("  label=\"Control Flow Graph\";\n");
        dot.push_str("  node [shape=record, fontname=\"Courier\"];\n");

        for block in &mf.blocks {
            let label = if self.show_instructions {
                let mut instrs = String::from("{\\\\<b>");
                instrs.push_str(&block.name);
                instrs.push_str("</b>");
                for instr in &block.instructions {
                    instrs.push_str(&format!(
                        "|op:{} [{} ops]",
                        instr.opcode,
                        instr.operands.len()
                    ));
                }
                instrs.push_str("}");
                instrs
            } else {
                block.name.clone()
            };

            let color = if block.is_entry {
                "style=filled, fillcolor=lightgreen"
            } else {
                ""
            };
            dot.push_str(&format!(
                "  bb{} [label=\"{}\", {}];\n",
                block.id, label, color
            ));
        }

        for block in &mf.blocks {
            for &succ in &block.successors {
                // Determine edge label
                let edge_style = if block.instructions.last().map_or(false, |i| i.flags.is_branch)
                {
                    "style=dashed"
                } else {
                    ""
                };
                dot.push_str(&format!(
                    "  bb{} -> bb{} [{}];\n",
                    block.id, succ, edge_style
                ));
            }
        }

        dot.push_str("}\n");
        dot
    }
}

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

// ============================================================================
// MachineDominatorTree — dominator tree on machine CFG
// ============================================================================

/// Computes the dominator tree for a machine function using the standard
/// iterative dataflow algorithm (Cooper, Harvey, Kennedy).
pub struct MachineDominatorTree {
    /// idom[block_id] = immediate dominator block id
    pub idom: HashMap<u32, Option<u32>>,
    /// Children in the dominator tree: dom_tree[parent] = Vec<child>
    pub dom_tree: HashMap<u32, Vec<u32>>,
    /// Dominance frontiers for SSA construction
    pub dom_frontier: HashMap<u32, Vec<u32>>,
}

impl MachineDominatorTree {
    pub fn new() -> Self {
        Self {
            idom: HashMap::new(),
            dom_tree: HashMap::new(),
            dom_frontier: HashMap::new(),
        }
    }

    /// Compute the dominator tree from a machine function.
    pub fn compute(&mut self, mf: &MachineFunction) {
        let n = mf.blocks.len();
        if n == 0 {
            return;
        }

        // Find entry block
        let entry = mf.blocks.iter().find(|b| b.is_entry);
        if entry.is_none() {
            return;
        }
        let entry_id = entry.unwrap().id;

        // Map block IDs to indices 0..n-1
        let id_to_idx: HashMap<u32, usize> = mf
            .blocks
            .iter()
            .enumerate()
            .map(|(i, b)| (b.id, i))
            .collect();
        let idx_to_id: Vec<u32> = mf.blocks.iter().map(|b| b.id).collect();

        // Collect predecessors
        let mut preds: Vec<Vec<usize>> = vec![Vec::new(); n];
        for (i, block) in mf.blocks.iter().enumerate() {
            for &succ_id in &block.successors {
                if let Some(&succ_idx) = id_to_idx.get(&succ_id) {
                    preds[succ_idx].push(i);
                }
            }
        }

        // Initial dominators: entry dominates itself, others dominate everything
        let entry_idx = id_to_idx[&entry_id];
        let mut doms: Vec<Vec<bool>> = vec![vec![true; n]; n];
        for i in 0..n {
            doms[entry_idx][i] = (i == entry_idx);
        }

        // Iterative algorithm
        let mut changed = true;
        while changed {
            changed = false;
            for i in 0..n {
                if i == entry_idx {
                    continue;
                }
                // Intersection of predecessors' dominators
                let mut new_dom: Vec<bool> = vec![true; n];
                for &p in &preds[i] {
                    for j in 0..n {
                        new_dom[j] = new_dom[j] && doms[p][j];
                    }
                }
                new_dom[i] = true; // Every block dominates itself

                if new_dom != doms[i] {
                    doms[i] = new_dom;
                    changed = true;
                }
            }
        }

        // Build idom map
        self.idom.clear();
        self.dom_tree.clear();
        for i in 0..n {
            let id = idx_to_id[i];
            if i == entry_idx {
                self.idom.insert(id, None);
            } else {
                // Find immediate dominator: the strict dominator closest to i
                let mut idom_idx = entry_idx;
                for j in 0..n {
                    if j != i && doms[j][i] {
                        // Check if j strictly dominates i and is closer
                        if doms[idom_idx][j] == false || j == idom_idx {
                            // j is not dominated by current idom, or j is the entry
                            // Actually need proper idom algorithm (intersect)
                        }
                    }
                }
                // Simplified: find the dominator that dominates the fewest other blocks
                // For a proper implementation, use the Cooper algorithm.
                let mut best = None;
                for j in 0..n {
                    if j != i && doms[j][i] {
                        let mut is_strict = false;
                        for k in 0..n {
                            if k != i && k != j && doms[j][k] && doms[k][i] {
                                is_strict = true;
                                break;
                            }
                        }
                        if !is_strict {
                            best = Some(idx_to_id[j]);
                            break;
                        }
                    }
                }
                self.idom
                    .insert(id, Some(best.unwrap_or(idx_to_id[entry_idx])));
                let _ = idom_idx;
            }
        }

        // Build dom_tree from idom
        for (&id, &idom_opt) in &self.idom.clone() {
            if let Some(idom_id) = idom_opt {
                self.dom_tree.entry(idom_id).or_default().push(id);
            }
        }

        // Compute dominance frontiers
        self.compute_dominance_frontiers(mf, &id_to_idx, &idx_to_id);
    }

    /// Compute dominance frontiers from dominator info.
    fn compute_dominance_frontiers(
        &mut self,
        mf: &MachineFunction,
        _id_to_idx: &HashMap<u32, usize>,
        _idx_to_id: &[u32],
    ) {
        self.dom_frontier.clear();
        for block in &mf.blocks {
            let pred_count = mf
                .blocks
                .iter()
                .filter(|b| b.successors.contains(&block.id))
                .count();
            if pred_count >= 2 {
                for other in &mf.blocks {
                    if other.successors.contains(&block.id) {
                        let mut runner = other.id;
                        while let Some(&Some(idom_id)) = self.idom.get(&runner) {
                            if idom_id == block.id {
                                break;
                            }
                            self.dom_frontier
                                .entry(idom_id)
                                .or_default()
                                .push(block.id);
                            runner = idom_id;
                        }
                    }
                }
            }
        }
        let _ = id_to_idx;
        let _ = idx_to_id;
    }

    /// Returns true if block_a dominates block_b.
    pub fn dominates(&self, a: u32, b: u32) -> bool {
        if a == b {
            return true;
        }
        let mut current = b;
        while let Some(&Some(idom)) = self.idom.get(&current) {
            if idom == a {
                return true;
            }
            if idom == current {
                break;
            }
            current = idom;
        }
        false
    }

    /// Returns the immediate dominator of a block, if any.
    pub fn get_idom(&self, block: u32) -> Option<u32> {
        self.idom.get(&block).and_then(|o| *o)
    }
}

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

// ============================================================================
// MachineLoopInfo — loop detection on machine CFG
// ============================================================================

/// Identifies natural loops in a machine control-flow graph using
/// back-edge detection and dominator information.
pub struct MachineLoopInfo {
    /// All detected loops.
    pub loops: Vec<MachineLoop>,
    /// Map from block id to the innermost loop containing it.
    pub block_loop_map: HashMap<u32, usize>,
}

#[derive(Debug, Clone)]
pub struct MachineLoop {
    pub id: usize,
    pub header: usize,
    /// Blocks in this loop (including header).
    pub blocks: Vec<u32>,
    /// Latch blocks (have a back-edge to the header).
    pub latches: Vec<u32>,
    /// Exiting blocks (have a successor outside the loop).
    pub exiting: Vec<u32>,
    /// Parent loop (None for top-level).
    pub parent_loop: Option<usize>,
    /// Nested child loops.
    pub child_loops: Vec<u32>,
}

impl MachineLoopInfo {
    pub fn new() -> Self {
        Self {
            loops: Vec::new(),
            block_loop_map: HashMap::new(),
        }
    }

    /// Compute loops for a machine function using dominator info.
    pub fn compute(&mut self, mf: &MachineFunction, dom_tree: &MachineDominatorTree) {
        self.loops.clear();
        self.block_loop_map.clear();

        // Find back-edges: edge a -> b where b dominates a
        for block in &mf.blocks {
            for &succ in &block.successors {
                if dom_tree.dominates(succ, block.id) {
                    // Found a back-edge: block.id -> succ (header is succ)
                    self.find_loop_body(mf, succ, block.id);
                }
            }
        }
    }

    /// Find all blocks in the loop with given header and back-edge source.
    fn find_loop_body(&mut self, mf: &MachineFunction, header: u32, back_edge_src: u32) {
        let loop_id = self.loops.len();
        let mut loop_blocks = vec![header, back_edge_src];
        let mut worklist = vec![back_edge_src];

        // Traverse backwards from back-edge source until reaching header
        let mut visited: HashSet<u32> = [header, back_edge_src].iter().copied().collect();

        while let Some(current) = worklist.pop() {
            for block in &mf.blocks {
                if block.successors.contains(&current) && visited.insert(block.id) {
                    if block.id != header {
                        worklist.push(block.id);
                        loop_blocks.push(block.id);
                    }
                }
            }
        }

        let mut latches = Vec::new();
        for block in &mf.blocks {
            if loop_blocks.contains(&block.id) && block.successors.contains(&header) {
                latches.push(block.id);
            }
        }

        self.loops.push(MachineLoop {
            id: loop_id,
            header,
            blocks: loop_blocks,
            latches,
            exiting: Vec::new(),
            parent_loop: None,
            child_loops: Vec::new(),
        });

        for &b in &self.loops.last().unwrap().blocks {
            self.block_loop_map.insert(b, loop_id);
        }
    }

    /// Get the innermost loop containing a block.
    pub fn get_loop_for(&self, block: usize) -> Option<&MachineLoop> {
        self.block_loop_map
            .get(&block)
            .and_then(|&id| self.loops.get(id))
    }

    /// Returns true if the edge from src to dst is a back-edge.
    pub fn is_back_edge(&self, src: usize, dst: usize, dom_tree: &MachineDominatorTree) -> bool {
        dom_tree.dominates(dst, src)
    }
}

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

// ============================================================================
// MachinePostDominatorTree — post-dominance analysis
// ============================================================================

/// Computes the post-dominator tree: B post-dominates A if all paths
/// from A to the exit must go through B.
pub struct MachinePostDominatorTree {
    pub idom: HashMap<u32, Option<u32>>,
    pub dom_tree: HashMap<u32, Vec<u32>>,
}

impl MachinePostDominatorTree {
    pub fn new() -> Self {
        Self {
            idom: HashMap::new(),
            dom_tree: HashMap::new(),
        }
    }

    /// Compute post-dominators by reversing the CFG and computing
    /// dominators on the reversed graph.
    pub fn compute(&mut self, mf: &MachineFunction) {
        // For post-dominance, we need:
        // 1. Identify exit blocks (no successors)
        // 2. Add a virtual exit node that all exits lead to
        // 3. Reverse the CFG
        // 4. Compute dominators starting from the virtual exit

        let exit_blocks: Vec<usize> = mf
            .blocks
            .iter()
            .filter(|b| b.successors.is_empty())
            .map(|b| b.id)
            .collect();

        if exit_blocks.is_empty() {
            return;
        }

        // Use the first exit block as the "virtual exit"
        let virtual_exit = exit_blocks[0];

        // Build reversed CFG
        let mut rev_successors: HashMap<u32, Vec<u32>> = HashMap::new();
        for block in &mf.blocks {
            for &succ in &block.successors {
                rev_successors.entry(succ).or_default().push(block.id);
            }
        }

        // Simple post-dominator computation using iterative algorithm
        // on the reversed graph with virtual_exit as entry
        let all_blocks: Vec<usize> = mf.blocks.iter().map(|b| b.id).collect();
        let n = all_blocks.len();
        let id_to_idx: HashMap<u32, usize> =
            all_blocks.iter().enumerate().map(|(i, &id)| (id, i)).collect();

        let entry_idx = id_to_idx[&virtual_exit];

        let mut doms: Vec<Vec<bool>> = vec![vec![true; n]; n];
        for i in 0..n {
            doms[entry_idx][i] = (i == entry_idx);
        }

        let mut changed = true;
        while changed {
            changed = false;
            for i in 0..n {
                if i == entry_idx {
                    continue;
                }
                let preds = rev_successors
                    .get(&all_blocks[i])
                    .cloned()
                    .unwrap_or_default();
                let mut new_dom: Vec<bool> = vec![true; n];
                for &p_id in &preds {
                    if let Some(&p_idx) = id_to_idx.get(&p_id) {
                        for j in 0..n {
                            new_dom[j] = new_dom[j] && doms[p_idx][j];
                        }
                    }
                }
                new_dom[i] = true;
                if new_dom != doms[i] {
                    doms[i] = new_dom;
                    changed = true;
                }
            }
        }

        // Extract immediate post-dominators
        self.idom.clear();
        for (i, &id) in all_blocks.iter().enumerate() {
            if i == entry_idx {
                self.idom.insert(id, None);
            } else {
                // Find the immediate post-dominator
                let mut best = None;
                for j in 0..n {
                    if j != i && doms[j][i] {
                        let mut is_strict = false;
                        for k in 0..n {
                            if k != i && k != j && doms[j][k] && doms[k][i] {
                                is_strict = true;
                                break;
                            }
                        }
                        if !is_strict {
                            best = Some(all_blocks[j]);
                            break;
                        }
                    }
                }
                self.idom.insert(id, best.or(Some(virtual_exit)));
            }
        }

        // Build post-dom tree
        self.dom_tree.clear();
        for (&id, &pdom_opt) in &self.idom.clone() {
            if let Some(pdom_id) = pdom_opt {
                self.dom_tree.entry(pdom_id).or_default().push(id);
            }
        }
    }

    /// Returns true if block_a post-dominates block_b.
    pub fn post_dominates(&self, a: u32, b: u32) -> bool {
        if a == b {
            return true;
        }
        let mut current = b;
        while let Some(&Some(pdom)) = self.idom.get(&current) {
            if pdom == a {
                return true;
            }
            if pdom == current {
                break;
            }
            current = pdom;
        }
        false
    }
}

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

// ============================================================================
// MachineRegionInfo — SESE region detection
// ============================================================================

/// Identifies single-entry single-exit (SESE) regions in the machine CFG.
pub struct MachineRegionInfo {
    pub regions: Vec<MachineRegion>,
}

#[derive(Debug, Clone)]
pub struct MachineRegion {
    pub id: usize,
    /// Entry block of the region.
    pub entry: u32,
    /// Exit block of the region.
    pub exit: u32,
    /// All blocks in the region.
    pub blocks: Vec<u32>,
    /// Nested child regions.
    pub children: Vec<u32>,
    /// Parent region (None for the outermost function region).
    pub parent: Option<u32>,
}

impl MachineRegionInfo {
    pub fn new() -> Self {
        Self {
            regions: Vec::new(),
        }
    }

    /// Compute SESE regions using dominator/post-dominator analysis.
    pub fn compute(
        &mut self,
        mf: &MachineFunction,
        dom_tree: &MachineDominatorTree,
        pdom_tree: &MachinePostDominatorTree,
    ) {
        self.regions.clear();

        // The whole function is a region (entry → exit)
        if let Some(entry) = mf.blocks.iter().find(|b| b.is_entry) {
            let exit_blocks: Vec<usize> = mf
                .blocks
                .iter()
                .filter(|b| b.successors.is_empty())
                .map(|b| b.id)
                .collect();
            let exit = exit_blocks.first().copied().unwrap_or(entry.id);

            let blocks: Vec<usize> = mf.blocks.iter().map(|b| b.id).collect();
            self.regions.push(MachineRegion {
                id: 0,
                entry: entry.id,
                exit,
                blocks,
                children: Vec::new(),
                parent: None,
            });
        }

        // Find natural loop regions (SESE: loop header → loop latch)
        for block in &mf.blocks {
            for &succ in &block.successors {
                if dom_tree.dominates(succ, block.id) && pdom_tree.post_dominates(block.id, succ) {
                    // succ is header, block.id is the back-edge source
                    let rid = self.regions.len();
                    let region = MachineRegion {
                        id: rid,
                        entry: succ,
                        exit: block.id,
                        blocks: vec![succ, block.id],
                        children: Vec::new(),
                        parent: Some(0),
                    };
                    self.regions.push(region);
                }
            }
        }
    }
}

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

// ============================================================================
// MachineBranchProbabilityInfo — branch probability analysis
// ============================================================================

/// Estimates branch probabilities from profile data, metadata, or
/// heuristics (e.g., loop back-edges are likely taken).
pub struct MachineBranchProbabilityInfo {
    /// Probability for edge (from_block, to_block), as 0..1.
    pub edge_probs: HashMap<(usize, usize), f64>,
}

impl MachineBranchProbabilityInfo {
    pub fn new() -> Self {
        Self {
            edge_probs: HashMap::new(),
        }
    }

    /// Compute branch probabilities for a machine function.
    pub fn compute(
        &mut self,
        mf: &MachineFunction,
        loop_info: &MachineLoopInfo,
    ) {
        self.edge_probs.clear();

        for block in &mf.blocks {
            let num_succs = block.successors.len();
            if num_succs == 0 {
                continue;
            }

            // Distribute probability among successors
            let base_prob = 1.0 / num_succs as f64;

            for &succ in &block.successors {
                let prob = if block.instructions.last().map_or(false, |i| {
                    i.flags.is_branch || i.flags.is_terminator
                }) {
                    // Branch instruction: apply heuristics
                    if loop_info
                        .get_loop_for(block.id)
                        .map_or(false, |l| l.header == succ)
                    {
                        // Back-edge: heavily favored
                        0.9
                    } else if loop_info.get_loop_for(succ).is_some()
                        && loop_info.get_loop_for(block.id).is_none()
                    {
                        // Exit from loop: less likely
                        0.1
                    } else {
                        base_prob
                    }
                } else {
                    1.0 // Unconditional fallthrough
                };

                self.edge_probs.insert((block.id, succ), prob);
            }

            // Normalize probabilities
            if num_succs > 1 {
                let total: f64 = block
                    .successors
                    .iter()
                    .map(|s| self.edge_probs.get(&(block.id, *s)).copied().unwrap_or(0.0))
                    .sum();
                if total > 0.0 {
                    for &succ in &block.successors {
                        if let Some(prob) = self.edge_probs.get_mut(&(block.id, succ)) {
                            *prob /= total;
                        }
                    }
                }
            }
        }
    }

    /// Get the probability of taking the edge from src to dst.
    pub fn get_edge_probability(&self, src: usize, dst: usize) -> f64 {
        self.edge_probs.get(&(src, dst)).copied().unwrap_or(0.5)
    }
}

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

// ============================================================================
// MachineBlockFrequencyInfo — block execution frequency analysis
// ============================================================================

/// Computes relative execution frequencies for basic blocks using
/// branch probabilities (propagated via iterative relaxation).
pub struct MachineBlockFrequencyInfo {
    /// Block frequency (arbitrary scale; entry block = 1.0).
    pub frequencies: HashMap<u32, f64>,
}

impl MachineBlockFrequencyInfo {
    pub fn new() -> Self {
        Self {
            frequencies: HashMap::new(),
        }
    }

    /// Compute block frequencies from branch probabilities.
    pub fn compute(
        &mut self,
        mf: &MachineFunction,
        branch_probs: &MachineBranchProbabilityInfo,
    ) {
        self.frequencies.clear();

        // Initialize
        if let Some(entry) = mf.blocks.iter().find(|b| b.is_entry) {
            self.frequencies.insert(entry.id, 1.0);
        }

        // Iterative relaxation (simple propagation)
        for _ in 0..20 {
            for block in &mf.blocks {
                let block_freq = self.frequencies.get(&block.id).copied().unwrap_or(0.0);
                if block_freq <= 0.0 {
                    continue;
                }
                for &succ in &block.successors {
                    let prob = branch_probs.get_edge_probability(block.id, succ);
                    let incoming = block_freq * prob;
                    let current = self.frequencies.get(&succ).copied().unwrap_or(0.0);
                    self.frequencies.insert(succ, current + incoming);
                }
            }
        }
    }

    /// Get the relative frequency of a block.
    pub fn get_block_freq(&self, block: usize) -> f64 {
        self.frequencies.get(&block).copied().unwrap_or(0.0)
    }

    /// Returns the block with the highest frequency.
    pub fn get_hottest_block(&self) -> Option<usize> {
        self.frequencies
            .iter()
            .max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
            .map(|(&id, _)| id)
    }
}

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

// ============================================================================
// MachineOptimizationRemarkEmitter — remark emission for machine passes
// ============================================================================

/// Emits optimization remarks (missed opportunities, successful transforms)
/// for machine-level passes, enabling diagnostics and optimization reporting.
pub struct MachineOptimizationRemarkEmitter {
    pub remarks: Vec<MachineOptRemark>,
    pub enabled: bool,
}

#[derive(Debug, Clone)]
pub struct MachineOptRemark {
    pub pass_name: String,
    pub kind: RemarkKind,
    pub function_name: String,
    pub message: String,
    pub block_id: Option<u32>,
    pub debug_loc: Option<String>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RemarkKind {
    /// A transformation was applied.
    Passed,
    /// An opportunity was missed.
    Missed,
    /// General analysis information.
    Analysis,
    /// Always-valid remark.
    Always,
}

impl MachineOptimizationRemarkEmitter {
    pub fn new() -> Self {
        Self {
            remarks: Vec::new(),
            enabled: true,
        }
    }

    /// Emit a remark for a specific instruction.
    pub fn emit(
        &mut self,
        kind: RemarkKind,
        pass_name: &str,
        func_name: &str,
        msg: &str,
    ) {
        if self.enabled {
            self.remarks.push(MachineOptRemark {
                pass_name: pass_name.to_string(),
                kind,
                function_name: func_name.to_string(),
                message: msg.to_string(),
                block_id: None,
                debug_loc: None,
            });
        }
    }

    /// Emit a missed-opportunity remark.
    pub fn missed(&mut self, pass: &str, func: &str, msg: &str) {
        self.emit(RemarkKind::Missed, pass, func, msg);
    }

    /// Emit a successful-transformation remark.
    pub fn passed(&mut self, pass: &str, func: &str, msg: &str) {
        self.emit(RemarkKind::Passed, pass, func, msg);
    }

    /// Get all remarks of a given kind.
    pub fn remarks_of_kind(&self, kind: RemarkKind) -> Vec<&MachineOptRemark> {
        self.remarks.iter().filter(|r| r.kind == kind).collect()
    }
}

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

// ============================================================================
// MachineDebugify — synthesize debug info for testing
// ============================================================================

/// Adds synthetic debug location information to all instructions in
/// a machine function, enabling testing of debug-preserving passes.
pub struct MachineDebugify {
    pub counter: u32,
}

impl MachineDebugify {
    pub fn new() -> Self {
        Self { counter: 0 }
    }

    /// Add synthetic line/column debug info to every instruction.
    pub fn debugify_function(&mut self, mf: &mut MachineFunction) {
        let source_file = format!("synthetic_debugify_{}.ll", mf.name);
        self.counter = 0;

        for block in &mut mf.blocks {
            for instr in &mut block.instructions {
                self.counter += 1;
                let line = (self.counter % 1000) + 1;
                let col = (self.counter % 80) + 1;
                instr.debug_loc = Some(format!("{}:{}:{}", source_file, line, col));
            }
        }
    }

    /// Strip synthesized debug info.
    pub fn strip_debugify(&self, mf: &mut MachineFunction) {
        for block in &mut mf.blocks {
            for instr in &mut block.instructions {
                instr.debug_loc = None;
            }
        }
    }
}

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

// ============================================================================
// MachineCheckDebugify — verify synthesized debug info integrity
// ============================================================================

/// Validates that synthetic debug info produced by MachineDebugify
/// is intact and consistent after a series of passes.
pub struct MachineCheckDebugify {
    pub errors: Vec<String>,
}

impl MachineCheckDebugify {
    pub fn new() -> Self {
        Self {
            errors: Vec::new(),
        }
    }

    /// Check that every instruction has valid synthetic debug info.
    pub fn check(&mut self, mf: &MachineFunction) -> bool {
        self.errors.clear();
        let mut seen_lines: HashSet<String> = HashSet::new();

        for block in &mf.blocks {
            for instr in &block.instructions {
                match &instr.debug_loc {
                    None => {
                        self.errors.push(format!(
                            "Instruction op:{} in block {} missing debug location",
                            instr.opcode, block.id
                        ));
                    }
                    Some(loc) => {
                        if !loc.starts_with("synthetic_debugify_") {
                            self.errors.push(format!(
                                "Instruction op:{} has non-synthetic debug location: {}",
                                instr.opcode, loc
                            ));
                        }
                        seen_lines.insert(loc.clone());
                    }
                }
            }
        }

        self.errors.is_empty()
    }

    /// Return all validation errors as a string.
    pub fn report(&self) -> String {
        if self.errors.is_empty() {
            "All debug info checks passed.".to_string()
        } else {
            format!(
                "Debug info validation found {} error(s):\n{}",
                self.errors.len(),
                self.errors.join("\n")
            )
        }
    }
}

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

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

#[cfg(test)]
mod tests {
    use super::*;
    use llvm_native_core::codegen_opt::{MachineBasicBlock, MachineFunction, MachineInstr, MachineOperand};

    fn make_test_mf(name: &str) -> MachineFunction {
        let mut mf = MachineFunction::new(name);
        let mut entry = MachineBasicBlock::new(0, "entry");
        entry.is_entry = true;
        entry.instructions.push(MachineInstr::new(1));
        entry.instructions.push(
            MachineInstr::new(15)
                .with_operand(MachineOperand::Block(1)),
        );
        entry.successors.push(1);
        mf.add_block(entry);

        let mut exit = MachineBasicBlock::new(1, "exit");
        exit.instructions.push(
            MachineInstr::new(14), // ret
        );
        mf.add_block(exit);

        mf
    }

    #[test]
    fn test_machine_outliner_empty() {
        let outliner = MachineOutliner::new();
        let mf = make_test_mf("test_outline");
        let candidates = outliner.scan_function(&mf);
        assert!(candidates.is_empty());
    }

    #[test]
    fn test_machine_outliner_hash() {
        let seq = vec![
            MachineInstr::new(1).with_operand(MachineOperand::Reg(llvm_native_core::codegen_opt::MCRegister(1))),
            MachineInstr::new(2).with_operand(MachineOperand::Reg(llvm_native_core::codegen_opt::MCRegister(2))),
        ];
        let hash = MachineOutliner::hash_sequence(&seq);
        assert!(hash != 0);
    }

    #[test]
    fn test_machine_function_splitter() {
        let splitter = MachineFunctionSplitter::new();
        let mf = make_test_mf("test_split");
        let sections = splitter.classify_blocks(&mf);
        assert!(sections.contains_key(&0));
        assert!(sections.contains_key(&1));
        assert_eq!(sections.get(&0), Some(&SectionKind::Hot));
    }

    #[test]
    fn test_cfg_printer() {
        let printer = MachineCFGPrinter::new();
        let mf = make_test_mf("test_cfg");
        let dot = printer.print_to_dot(&mf);
        assert!(dot.contains("digraph"));
        assert!(dot.contains("bb0"));
        assert!(dot.contains("bb1"));
    }

    #[test]
    fn test_dominator_tree() {
        let mut dt = MachineDominatorTree::new();
        let mf = make_test_mf("test_dom");
        dt.compute(&mf);
        // Entry block should have no immediate dominator
        assert_eq!(dt.idom.get(&0), Some(&None));
    }

    #[test]
    fn test_loop_info() {
        let mut loop_info = MachineLoopInfo::new();
        let mut dt = MachineDominatorTree::new();
        let mf = make_test_mf("test_loop");
        dt.compute(&mf);
        loop_info.compute(&mf, &dt);
        assert!(loop_info.loops.is_empty()); // No loops in simple CFG
    }

    #[test]
    fn test_post_dominator_tree() {
        let mut pdt = MachinePostDominatorTree::new();
        let mf = make_test_mf("test_pdom");
        pdt.compute(&mf);
        assert!(!pdt.idom.is_empty());
    }

    #[test]
    fn test_region_info() {
        let mut ri = MachineRegionInfo::new();
        let mut dt = MachineDominatorTree::new();
        let mut pdt = MachinePostDominatorTree::new();
        let mf = make_test_mf("test_regions");
        dt.compute(&mf);
        pdt.compute(&mf);
        ri.compute(&mf, &dt, &pdt);
        assert!(!ri.regions.is_empty());
    }

    #[test]
    fn test_branch_probability_info() {
        let mut bpi = MachineBranchProbabilityInfo::new();
        let mut loop_info = MachineLoopInfo::new();
        let mut dt = MachineDominatorTree::new();
        let mf = make_test_mf("test_probs");
        dt.compute(&mf);
        loop_info.compute(&mf, &dt);
        bpi.compute(&mf, &loop_info);
        // Edge from entry(0) to exit(1) should have probability 1.0
        assert!(bpi.get_edge_probability(0, 1) > 0.0);
    }

    #[test]
    fn test_block_frequency_info() {
        let mut bfi = MachineBlockFrequencyInfo::new();
        let mut bpi = MachineBranchProbabilityInfo::new();
        let mut loop_info = MachineLoopInfo::new();
        let mut dt = MachineDominatorTree::new();
        let mf = make_test_mf("test_freq");
        dt.compute(&mf);
        loop_info.compute(&mf, &dt);
        bpi.compute(&mf, &loop_info);
        bfi.compute(&mf, &bpi);
        assert!(bfi.get_block_freq(0) > 0.0);
    }

    #[test]
    fn test_optimization_remark_emitter() {
        let mut emitter = MachineOptimizationRemarkEmitter::new();
        emitter.missed("TestPass", "test_func", "Unable to optimize");
        emitter.passed("TestPass", "test_func", "Applied optimization");
        assert_eq!(emitter.remarks.len(), 2);
        assert_eq!(emitter.remarks_of_kind(RemarkKind::Passed).len(), 1);
    }

    #[test]
    fn test_machine_debugify() {
        let mut debugify = MachineDebugify::new();
        let mut mf = make_test_mf("test_debug");
        debugify.debugify_function(&mut mf);
        for block in &mf.blocks {
            for instr in &block.instructions {
                assert!(instr.debug_loc.is_some(), "Missing debug location");
            }
        }
    }

    #[test]
    fn test_check_debugify() {
        let mut debugify = MachineDebugify::new();
        let mut checker = MachineCheckDebugify::new();
        let mut mf = make_test_mf("test_check_debug");
        debugify.debugify_function(&mut mf);
        let ok = checker.check(&mf);
        assert!(ok, "Debug info check failed: {}", checker.report());
    }

    #[test]
    fn test_check_debugify_fails_on_missing() {
        let mut checker = MachineCheckDebugify::new();
        let mf = make_test_mf("test_missing_debug");
        let ok = checker.check(&mf);
        assert!(!ok, "Should detect missing debug locations");
    }

    #[test]
    fn test_sanitizer_metadata() {
        let sbm = MachineSanitizerBinaryMetadata::new();
        let mf = make_test_mf("test_san");
        let entries = sbm.analyze(&mf);
        // May or may not have entries depending on what's in the MF
        let _ = entries;
    }

    #[test]
    fn test_machine_outliner_cross_function() {
        let outliner = MachineOutliner::new();
        let mf1 = make_test_mf("func1");
        let mf2 = make_test_mf("func2");
        let candidates = outliner.scan_functions(&[mf1, mf2]);
        assert!(candidates.is_empty()); // No repeated long sequences in test MF
    }

    #[test]
    fn test_section_kind_default() {
        let splitter = MachineFunctionSplitter::new();
        assert_eq!(splitter.cold_threshold, 0.1);
        assert!(splitter.use_profile);
    }

    #[test]
    fn test_estimate_savings() {
        let outliner = MachineOutliner::new();
        let savings = outliner.estimate_savings(5, 3);
        // 3*5*3 = 45 original, (5*3 + 5*3 + 1) = 31 outlined → savings = 14
        assert_eq!(savings, 14);
    }
}