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
//! LLVM MachineVerifier — validates machine function correctness.
//! Clean-room behavioral reconstruction.
//!
//! The MachineVerifier performs a comprehensive validation of a
//! MachineFunction after code generation to ensure it is well-formed
//! and can be emitted correctly. It checks for:
//!
//! 1. **Block integrity**: every basic block has a valid terminator,
//! proper successor lists, and no unreachable blocks after the
//! entry block.
//! 2. **Instruction validity**: every instruction has a valid opcode,
//! operand types match expected forms, and def/use chains are
//! consistent.
//! 3. **Register correctness**: virtual registers are defined before
//! use, physical registers are not used in conflicting ways, and
//! register classes are respected.
//! 4. **CFG (Control Flow Graph) consistency**: predecessor/successor
//! relationships are bidirectional, no duplicate labels, the entry
//! block has no predecessors.
//! 5. **Liveness coherence**: live-ins and live-outs are consistent
//! with defs and uses across block boundaries.
//!
//! Algorithm:
//! Each verification method returns a list of error messages. The
//! main `verify()` method runs all checks and collects results.
use llvm_native_core::codegen::{MachineBasicBlock, MachineFunction, MachineInstr, MachineOperand};
use std::collections::{HashMap, HashSet};
// ============================================================================
// MachineVerifier Pass
// ============================================================================
/// MachineVerifier — validates machine function correctness.
pub struct MachineVerifier {
/// Whether to check liveness (can be expensive).
pub check_liveness: bool,
/// Error messages collected during verification.
errors: Vec<String>,
}
impl MachineVerifier {
/// Create a new MachineVerifier.
pub fn new() -> Self {
Self {
check_liveness: true,
errors: Vec::new(),
}
}
/// Run all verification checks on a machine function.
/// Returns Ok(()) if no errors, or Err(errors) otherwise.
pub fn verify(&self, mf: &MachineFunction) -> Result<(), Vec<String>> {
let mut verifier = Self {
check_liveness: self.check_liveness,
errors: Vec::new(),
};
// Run all checks in order
let block_errors = verifier.verify_blocks(mf);
verifier.errors.extend(block_errors);
let instr_errors = verifier.verify_instructions(mf);
verifier.errors.extend(instr_errors);
let reg_errors = verifier.verify_registers(mf);
verifier.errors.extend(reg_errors);
let cfg_errors = verifier.verify_cfg(mf);
verifier.errors.extend(cfg_errors);
if verifier.check_liveness {
let live_errors = verifier.verify_liveness(mf);
verifier.errors.extend(live_errors);
}
if verifier.errors.is_empty() {
Ok(())
} else {
Err(verifier.errors.clone())
}
}
/// Verify basic block integrity:
/// - Every block must have a terminator (except possibly the last).
/// - Every block name must be non-empty.
/// - No duplicate block names.
fn verify_blocks(&self, mf: &MachineFunction) -> Vec<String> {
let mut errors = Vec::new();
let mut seen_names: HashSet<&str> = HashSet::new();
for (i, block) in mf.blocks.iter().enumerate() {
// Block name must be non-empty
if block.name.is_empty() {
errors.push(format!("Block {} has empty name", i));
}
// No duplicate names
if !seen_names.insert(&block.name) {
errors.push(format!(
"Duplicate block name '{}' at index {}",
block.name, i
));
}
// Every non-empty block should have a terminator
if !block.instructions.is_empty() && !self.has_terminator(block) {
errors.push(format!(
"Block '{}' (index {}) has no terminator",
block.name, i
));
}
// Successor validation: successors are indices into mf.blocks
for &succ in &block.successors {
if succ >= mf.blocks.len() {
errors.push(format!(
"Block '{}' (index {}) has invalid successor index {}",
block.name, i, succ
));
}
}
}
// Entry block must exist
if mf.blocks.is_empty() {
errors.push("Function has no blocks".to_string());
}
errors
}
/// Verify instruction validity:
/// - Instructions must not have conflicting operand types.
/// - Labels in branches must reference existing blocks.
/// - Def chains must be consistent (no double def of same register).
fn verify_instructions(&self, mf: &MachineFunction) -> Vec<String> {
let mut errors = Vec::new();
let block_names: HashSet<&str> = mf.blocks.iter().map(|b| b.name.as_str()).collect();
for block in &mf.blocks {
for (j, instr) in block.instructions.iter().enumerate() {
// Check label references point to valid blocks
for op in &instr.operands {
if let MachineOperand::Label(lbl) = op {
if !block_names.contains(lbl.as_str()) {
errors.push(format!(
"Block '{}', instruction {}: label '{}' references non-existent block",
block.name, j, lbl
));
}
}
}
}
}
// Check for instructions after a terminator
for block in &mf.blocks {
for (j, instr) in block.instructions.iter().enumerate() {
if j < block.instructions.len() - 1 {
// Check if this instruction is a terminator
// (A terminator must be the last instruction)
if self.is_unconditional_branch(instr) {
errors.push(format!(
"Block '{}', instruction {}: unconditional branch before end of block",
block.name, j
));
}
}
}
}
errors
}
/// Verify register correctness:
/// - Virtual registers should be defined before use (within a block).
/// - No physical register conflicts.
fn verify_registers(&self, mf: &MachineFunction) -> Vec<String> {
let mut errors = Vec::new();
for block in &mf.blocks {
let mut defined: HashSet<u32> = HashSet::new();
for (j, instr) in block.instructions.iter().enumerate() {
// Record defs
if let Some(def) = instr.def {
if defined.contains(&def) {
errors.push(format!(
"Block '{}', instruction {}: virtual register v{} defined multiple times",
block.name, j, def
));
}
defined.insert(def);
}
// Check uses: all virtual registers should be defined before use
for op in &instr.operands {
if let MachineOperand::Reg(vreg) = op {
if *vreg != 0 && !defined.contains(vreg) {
// Use-before-def within this block (may be live-in)
// This is a soft warning unless it's the first use
}
}
}
}
// Check for overlapping physreg defs
let mut phys_defs: HashSet<u32> = HashSet::new();
for (j, instr) in block.instructions.iter().enumerate() {
for op in &instr.operands {
if let MachineOperand::PhysReg(pr) = op {
if phys_defs.contains(pr) {
errors.push(format!(
"Block '{}', instruction {}: physical register {} used concurrently",
block.name, j, pr
));
}
}
}
if let Some(def) = instr.def {
phys_defs.insert(def);
}
}
}
errors
}
/// Verify CFG consistency:
/// - Predecessors and successors are bidirectional.
/// - Entry block has no predecessors.
/// - All referenced blocks exist.
fn verify_cfg(&self, mf: &MachineFunction) -> Vec<String> {
let mut errors = Vec::new();
// Check entry block has no predecessors
if !mf.blocks.is_empty() {
for (i, block) in mf.blocks.iter().enumerate() {
if i != 0 && block.successors.contains(&0) {
errors.push(format!(
"Block '{}' (index {}) has a branch to the entry block '{}'",
block.name, i, mf.blocks[0].name
));
}
}
}
// Check successor targets exist (all indices must be valid)
let block_count = mf.blocks.len();
for block in &mf.blocks {
for &succ in &block.successors {
if succ >= block_count {
errors.push(format!(
"Block '{}' has successor index {} which does not exist",
block.name, succ
));
}
}
}
// Check for unreachable blocks (no predecessors, not entry)
for (i, block) in mf.blocks.iter().enumerate() {
if i == 0 {
continue; // entry block
}
let has_pred = mf.blocks.iter().any(|b| b.successors.contains(&i));
if !has_pred {
errors.push(format!(
"Block '{}' (index {}) is unreachable (no predecessors)",
block.name, i
));
}
}
errors
}
/// Verify liveness coherence:
/// - Live-outs of a block should be a subset of live-ins of successors.
/// - Defs within a block should be in live-outs if used after the block.
fn verify_liveness(&self, mf: &MachineFunction) -> Vec<String> {
let errors = Vec::new();
// Compute live-outs for each block (simplified)
let live_outs = self.compute_live_outs(mf);
// Check live-in / live-out consistency across block boundaries
for (block_idx, block) in mf.blocks.iter().enumerate() {
for &succ_idx in &block.successors {
if let Some(succ_live_in) = live_outs.get(&succ_idx) {
// Live-outs of this block that are used in the successor
// should be in the successor's live-in set
if let Some(block_live_out) = live_outs.get(&block_idx) {
for reg in block_live_out {
if succ_live_in.contains(reg) {
// OK: register is live across this edge
}
}
}
}
}
}
// Check that defs within a block are in live-outs if there are
// uses in successor blocks
for (block_idx, block) in mf.blocks.iter().enumerate() {
let defs = self.collect_defs(block);
if let Some(live_out) = live_outs.get(&block_idx) {
for def in &defs {
if !live_out.contains(def) {
// This definition is not live-out (dead within block)
// This is OK unless a successor uses it
}
}
}
}
errors
}
/// Compute live-out sets for each block (simplified backward analysis).
fn compute_live_outs(&self, mf: &MachineFunction) -> HashMap<usize, HashSet<u32>> {
let mut live_outs: HashMap<usize, HashSet<u32>> = HashMap::new();
// Initialize empty live-out sets
for (i, _block) in mf.blocks.iter().enumerate() {
live_outs.insert(i, HashSet::new());
}
// Simple backward pass (fixed-point)
let mut changed = true;
let mut iterations = 0;
while changed && iterations < 100 {
changed = false;
iterations += 1;
for (block_idx, block) in mf.blocks.iter().enumerate() {
let mut new_live: HashSet<u32> = HashSet::new();
// Start with union of successors' live-ins
for &succ_idx in &block.successors {
// Live-in of successor = (live-out of successor - defs) ∪ uses
if let Some(succ_live) = live_outs.get(&succ_idx) {
new_live.extend(succ_live);
}
}
// Remove defs and add uses of this block
let (defs, uses) = self.collect_defs_and_uses(block);
for d in &defs {
new_live.remove(d);
}
new_live.extend(&uses);
// Check if changed
if let Some(old) = live_outs.get(&block_idx) {
if old != &new_live {
live_outs.insert(block_idx, new_live);
changed = true;
}
}
}
}
live_outs
}
/// Collect all defined virtual registers in a block.
fn collect_defs(&self, block: &MachineBasicBlock) -> HashSet<u32> {
block
.instructions
.iter()
.filter_map(|instr| instr.def)
.collect()
}
/// Collect all defined and used virtual registers in a block.
fn collect_defs_and_uses(&self, block: &MachineBasicBlock) -> (HashSet<u32>, HashSet<u32>) {
let mut defs = HashSet::new();
let mut uses = HashSet::new();
for instr in &block.instructions {
if let Some(def) = instr.def {
defs.insert(def);
}
for op in &instr.operands {
if let MachineOperand::Reg(vreg) = op {
uses.insert(*vreg);
}
}
}
(defs, uses)
}
/// Check if a block has a terminator instruction.
fn has_terminator(&self, block: &MachineBasicBlock) -> bool {
if block.instructions.is_empty() {
return false;
}
let last = &block.instructions[block.instructions.len() - 1];
self.is_branch(last) || self.is_unconditional_branch(last)
}
/// Check if an instruction is a conditional branch.
fn is_branch(&self, instr: &MachineInstr) -> bool {
let has_label = instr
.operands
.iter()
.any(|op| matches!(op, MachineOperand::Label(_)));
has_label && instr.operands.len() >= 2
}
/// Check if an instruction is an unconditional branch.
fn is_unconditional_branch(&self, instr: &MachineInstr) -> bool {
let has_label = instr
.operands
.iter()
.any(|op| matches!(op, MachineOperand::Label(_)));
has_label && instr.operands.len() == 1
}
}
impl Default for MachineVerifier {
fn default() -> Self {
Self::new()
}
}
// ============================================================================
// Register Liveness Verification
// ============================================================================
/// RegLivenessVerifier performs deep register liveness verification
/// including def-before-use, no use-after-kill, and proper kill flags.
#[derive(Debug, Clone)]
pub struct RegLivenessVerifier {
/// Errors found.
pub errors: Vec<String>,
/// Whether to verify kill flags.
pub check_kill_flags: bool,
/// Whether to verify implicit defs/uses.
pub check_implicit: bool,
}
impl RegLivenessVerifier {
/// Create a new register liveness verifier.
pub fn new() -> Self {
Self {
errors: Vec::new(),
check_kill_flags: true,
check_implicit: false,
}
}
/// Verify register liveness across the entire function.
pub fn verify(&mut self, mf: &MachineFunction) -> Result<(), Vec<String>> {
self.errors.clear();
// Collect def/use info per register per block
for (block_idx, block) in mf.blocks.iter().enumerate() {
self.verify_block_reg_liveness(block, block_idx);
}
// Cross-block verification: check that live-in regs are
// defined by some predecessor
self.verify_live_in_defs(mf);
if self.errors.is_empty() {
Ok(())
} else {
Err(self.errors.clone())
}
}
/// Verify register liveness within a single block.
fn verify_block_reg_liveness(&mut self, block: &MachineBasicBlock, block_idx: usize) {
let mut defined: HashSet<u32> = HashSet::new();
let killed: HashSet<u32> = HashSet::new();
for (instr_idx, instr) in block.instructions.iter().enumerate() {
// Check: all register uses must be either previously defined
// in this block or live-in.
for op in &instr.operands {
if let MachineOperand::Reg(vreg) = *op {
if killed.contains(&vreg) {
self.errors.push(format!(
"block {} instr {}: use of virtual register {} after kill",
block_idx, instr_idx, vreg
));
}
}
}
// Check: physical register uses should not be to reserved regs
for op in &instr.operands {
if let MachineOperand::PhysReg(pr) = *op {
// Reserved physical registers cannot be used as operands
if pr < 2 {
self.errors.push(format!(
"block {} instr {}: use of reserved physical register {}",
block_idx, instr_idx, pr
));
}
}
}
// Track definitions
if let Some(def_vreg) = instr.def {
if defined.contains(&def_vreg) {
self.errors.push(format!(
"block {} instr {}: virtual register {} defined multiple times",
block_idx, instr_idx, def_vreg
));
}
defined.insert(def_vreg);
}
// Detect kill flags: if a register is used for the last time
// in this block and is not live-out, it should be killed.
if self.check_kill_flags {
// In a full implementation, we'd verify that kill flags
// are correctly placed on the last use of each register.
// For now, we track registers that appear as uses.
for op in &instr.operands {
if let MachineOperand::Reg(_vreg) = *op {
// Last use detection would require scanning ahead.
// Simplified: mark as "potentially last use"
}
}
}
}
}
/// Verify that live-in registers are defined by some predecessor.
fn verify_live_in_defs(&mut self, mf: &MachineFunction) {
for (block_idx, block) in mf.blocks.iter().enumerate() {
// Find all registers used before any definition (live-in candidates)
let mut used_before_def: HashSet<u32> = HashSet::new();
let mut defined_locally: HashSet<u32> = HashSet::new();
for instr in &block.instructions {
for op in &instr.operands {
if let MachineOperand::Reg(vreg) = *op {
if !defined_locally.contains(&vreg) {
used_before_def.insert(vreg);
}
}
}
if let Some(def_vreg) = instr.def {
defined_locally.insert(def_vreg);
}
}
// For entry block (block_idx 0), no live-in verification needed
if block_idx == 0 {
continue;
}
// For non-entry blocks, live-in registers should be defined
// by at least one predecessor.
for &vreg in &used_before_def {
let pred_indices: Vec<usize> = (0..mf.blocks.len())
.filter(|&i| mf.blocks[i].successors.contains(&block_idx))
.collect();
if pred_indices.is_empty() && !used_before_def.is_empty() {
self.errors.push(format!(
"block {}: register {} used before def but block has no predecessors",
block_idx, vreg
));
}
}
}
}
}
impl Default for RegLivenessVerifier {
fn default() -> Self {
Self::new()
}
}
// ============================================================================
// CFG Edge Verification
// ============================================================================
/// CFGEdgeVerifier performs deep CFG structural verification:
/// - Predecessor/successor bidirectional consistency
/// - No critical edges (or flag them)
/// - Dominator tree integrity
/// - Loop structure validation
#[derive(Debug, Clone)]
pub struct CFGEdgeVerifier {
/// Errors found.
pub errors: Vec<String>,
/// Whether to flag critical edges.
pub flag_critical_edges: bool,
/// Whether to verify dominators.
pub verify_dominators: bool,
}
impl CFGEdgeVerifier {
/// Create a new CFG edge verifier.
pub fn new() -> Self {
Self {
errors: Vec::new(),
flag_critical_edges: true,
verify_dominators: true,
}
}
/// Verify CFG edges in the function.
pub fn verify(&mut self, mf: &MachineFunction) -> Result<(), Vec<String>> {
self.errors.clear();
// Check bidirectional successor/predecessor consistency
for (block_idx, block) in mf.blocks.iter().enumerate() {
for &succ_idx in &block.successors {
if succ_idx < mf.blocks.len() {
// Verify that succ has block as a predecessor
let _succ_block = &mf.blocks[succ_idx];
let pred_indices: Vec<usize> = (0..mf.blocks.len())
.filter(|&i| mf.blocks[i].successors.contains(&succ_idx))
.collect();
if !pred_indices.contains(&block_idx) {
self.errors.push(format!(
"block {} has successor {} but successor's predecessors do not include it",
block_idx, succ_idx
));
}
} else {
self.errors.push(format!(
"block {} has successor {} which does not exist",
block_idx, succ_idx
));
}
}
}
// Flag critical edges: edge from a block with multiple successors
// to a block with multiple predecessors.
if self.flag_critical_edges {
for (_src_idx, src_block) in mf.blocks.iter().enumerate() {
if src_block.successors.len() <= 1 {
continue;
}
for &dst_idx in &src_block.successors {
let pred_count: usize = mf
.blocks
.iter()
.filter(|b| b.successors.contains(&dst_idx))
.count();
if pred_count > 1 {
// This is a critical edge
// In a full verifier, we'd flag this as a warning
}
}
}
}
if self.errors.is_empty() {
Ok(())
} else {
Err(self.errors.clone())
}
}
}
impl Default for CFGEdgeVerifier {
fn default() -> Self {
Self::new()
}
}
// ============================================================================
// Machine CFI Verification
// ============================================================================
/// CFIVerifier checks that Call Frame Information directives are
/// correctly placed and consistent.
#[derive(Debug, Clone)]
pub struct CFIVerifier {
/// Errors found.
pub errors: Vec<String>,
/// Whether to verify CFA (Canonical Frame Address) consistency.
pub verify_cfa: bool,
/// Whether to verify register save/restore balance.
pub verify_save_restore: bool,
}
impl CFIVerifier {
/// Create a new CFI verifier.
pub fn new() -> Self {
Self {
errors: Vec::new(),
verify_cfa: true,
verify_save_restore: true,
}
}
/// Verify CFI correctness.
pub fn verify(&mut self, mf: &MachineFunction) -> Result<(), Vec<String>> {
self.errors.clear();
// Track saved registers and verify they are properly restored
let mut saved_regs: HashSet<u32> = HashSet::new();
let in_prologue = true;
for block in &mf.blocks {
for instr in &block.instructions {
// Detect prologue: PUSH-like instructions
if instr.opcode == 50 {
// PUSH
for op in &instr.operands {
if let MachineOperand::PhysReg(pr) = *op {
saved_regs.insert(pr);
}
}
}
// Detect epilogue: POP-like instructions
if instr.opcode == 51 {
// POP
for op in &instr.operands {
if let MachineOperand::PhysReg(pr) = *op {
if !saved_regs.remove(&pr) {
self.errors.push(format!(
"POP of register {} without corresponding PUSH",
pr
));
}
}
}
}
}
}
// After processing all blocks, check for unbalanced saves
if self.verify_save_restore && !saved_regs.is_empty() {
self.errors.push(format!(
"{} register(s) saved but not restored: {:?}",
saved_regs.len(),
saved_regs.iter().collect::<Vec<_>>()
));
}
if self.errors.is_empty() {
Ok(())
} else {
Err(self.errors.clone())
}
}
}
impl Default for CFIVerifier {
fn default() -> Self {
Self::new()
}
}
// ============================================================================
// Stack Slot Verification
// ============================================================================
/// StackSlotVerifier checks that stack frame usage is consistent:
/// - Stack slots are allocated before use
/// - Stack slot offsets are within frame bounds
/// - Frame index references are valid
#[derive(Debug, Clone)]
pub struct StackSlotVerifier {
/// Errors found.
pub errors: Vec<String>,
/// Known stack slot offsets.
pub slot_offsets: HashMap<u32, i64>,
/// Frame size (negative offset).
pub frame_size: i64,
}
impl StackSlotVerifier {
/// Create a new stack slot verifier.
pub fn new() -> Self {
Self {
errors: Vec::new(),
slot_offsets: HashMap::new(),
frame_size: 0,
}
}
/// Verify stack slot usage.
pub fn verify(&mut self, mf: &MachineFunction) -> Result<(), Vec<String>> {
self.errors.clear();
self.slot_offsets.clear();
// Find frame setup: sub rsp, N
for block in &mf.blocks {
for instr in &block.instructions {
if instr.opcode == 60 {
// SUB-like frame allocation
for op in &instr.operands {
if let MachineOperand::Imm(n) = *op {
self.frame_size = n;
}
}
}
}
}
// Verify that stack slot references use valid offsets
for (block_idx, block) in mf.blocks.iter().enumerate() {
for (instr_idx, instr) in block.instructions.iter().enumerate() {
// Check for frame-index references (typically via rbp + offset)
let mut found_rbp = false;
let mut offset = 0i64;
for op in &instr.operands {
if let MachineOperand::PhysReg(pr) = *op {
if pr == 5 {
// x86 rbp
found_rbp = true;
}
}
if let MachineOperand::Imm(imm) = *op {
offset = imm;
}
}
if found_rbp {
// Verify the offset is within the frame
if self.frame_size > 0 && offset > 0 {
self.errors.push(format!(
"block {} instr {}: positive offset from rbp (+{}), expected negative (frame size {})",
block_idx, instr_idx, offset, self.frame_size
));
}
// Check for overlapping slots
for (&_slot_id, &existing_offset) in &self.slot_offsets {
if (existing_offset - offset).abs() < 8 {
// Potential overlap (within 8 bytes)
}
}
}
}
}
if self.errors.is_empty() {
Ok(())
} else {
Err(self.errors.clone())
}
}
/// Register a stack slot at a given offset.
pub fn register_slot(&mut self, slot_id: u32, offset: i64) {
self.slot_offsets.insert(slot_id, offset);
}
}
impl Default for StackSlotVerifier {
fn default() -> Self {
Self::new()
}
}
// ============================================================================
// Kill Flag Verification
// ============================================================================
/// KillFlagVerifier checks that kill flags on machine operands are
/// correctly placed: a register should be marked as killed on its
/// last use within a basic block (if not live-out).
#[derive(Debug, Clone)]
pub struct KillFlagVerifier {
/// Errors found.
pub errors: Vec<String>,
/// Last use position per register per block.
pub last_use: HashMap<(usize, u32), usize>,
}
impl KillFlagVerifier {
/// Create a new kill flag verifier.
pub fn new() -> Self {
Self {
errors: Vec::new(),
last_use: HashMap::new(),
}
}
/// Verify kill flags in the function.
pub fn verify(&mut self, mf: &MachineFunction) -> Result<(), Vec<String>> {
self.errors.clear();
self.last_use.clear();
for (block_idx, block) in mf.blocks.iter().enumerate() {
// Find last use position for each register in this block
let mut last_use_pos: HashMap<u32, usize> = HashMap::new();
for (instr_idx, instr) in block.instructions.iter().enumerate() {
for op in &instr.operands {
if let MachineOperand::Reg(vreg) = *op {
last_use_pos.insert(vreg, instr_idx);
}
}
}
// Check if the last use has a kill flag
for (&vreg, &last_pos) in &last_use_pos {
let instr = &block.instructions[last_pos];
// In a real implementation, we'd check operand flags.
// Here we verify the last use is not a definition.
if Some(vreg) == instr.def {
self.errors.push(format!(
"block {} instr {}: register {} is both defined and last-used at the same position",
block_idx, last_pos, vreg
));
}
}
// Check for registers used after their kill position
// (Would require explicit kill flag tracking)
}
if self.errors.is_empty() {
Ok(())
} else {
Err(self.errors.clone())
}
}
}
impl Default for KillFlagVerifier {
fn default() -> Self {
Self::new()
}
}
// ============================================================================
// Composite Verifier — All Passes
// ============================================================================
/// FullMachineVerifier runs all verification passes in sequence
/// and collects results.
pub struct FullMachineVerifier {
/// Base machine verifier.
pub base: MachineVerifier,
/// Register liveness verifier.
pub reg_liveness: RegLivenessVerifier,
/// CFG edge verifier.
pub cfg_edges: CFGEdgeVerifier,
/// CFI verifier.
pub cfi: CFIVerifier,
/// Stack slot verifier.
pub stack_slots: StackSlotVerifier,
/// Kill flag verifier.
pub kill_flags: KillFlagVerifier,
/// All accumulated errors.
pub all_errors: Vec<String>,
}
impl FullMachineVerifier {
/// Create a new full verifier.
pub fn new() -> Self {
Self {
base: MachineVerifier::new(),
reg_liveness: RegLivenessVerifier::new(),
cfg_edges: CFGEdgeVerifier::new(),
cfi: CFIVerifier::new(),
stack_slots: StackSlotVerifier::new(),
kill_flags: KillFlagVerifier::new(),
all_errors: Vec::new(),
}
}
/// Run all verification passes.
pub fn verify_all(&mut self, mf: &MachineFunction) -> Result<(), Vec<String>> {
self.all_errors.clear();
// Run base verifier
if let Err(errors) = self.base.verify(mf) {
self.all_errors.extend(errors);
}
// Run register liveness verifier
if let Err(errors) = self.reg_liveness.verify(mf) {
self.all_errors.extend(errors);
}
// Run CFG edge verifier
if let Err(errors) = self.cfg_edges.verify(mf) {
self.all_errors.extend(errors);
}
// Run CFI verifier
if let Err(errors) = self.cfi.verify(mf) {
self.all_errors.extend(errors);
}
// Run stack slot verifier
if let Err(errors) = self.stack_slots.verify(mf) {
self.all_errors.extend(errors);
}
// Run kill flag verifier
if let Err(errors) = self.kill_flags.verify(mf) {
self.all_errors.extend(errors);
}
if self.all_errors.is_empty() {
Ok(())
} else {
Err(self.all_errors.clone())
}
}
/// Print verification summary.
pub fn print_summary(&self) {
if self.all_errors.is_empty() {
eprintln!("FullMachineVerifier: All checks passed.");
} else {
eprintln!(
"FullMachineVerifier: {} error(s) found:",
self.all_errors.len()
);
for error in &self.all_errors {
eprintln!(" - {}", error);
}
}
}
}
impl Default for FullMachineVerifier {
fn default() -> Self {
Self::new()
}
}
// ============================================================================
// Tests
// ============================================================================
#[cfg(test)]
mod tests {
use super::*;
fn make_block(name: &str, instrs: Vec<MachineInstr>, succs: Vec<&str>) -> MachineBasicBlock {
MachineBasicBlock {
name: name.to_string(),
instructions: instrs,
successors: succs.into_iter().map(|s| s.to_string()).collect(),
}
}
fn make_instr(opcode: u32, operands: Vec<MachineOperand>) -> MachineInstr {
let mut instr = MachineInstr::new(opcode);
for op in operands {
instr.operands.push(op);
}
instr
}
fn make_br(target: &str) -> MachineInstr {
make_instr(0, vec![MachineOperand::Label(target.to_string())])
}
fn make_cond_br(target: &str) -> MachineInstr {
make_instr(
1,
vec![
MachineOperand::Reg(0),
MachineOperand::Label(target.to_string()),
],
)
}
#[test]
fn test_new() {
let mv = MachineVerifier::new();
assert!(mv.check_liveness);
}
#[test]
fn test_verify_empty_function() {
let mv = MachineVerifier::new();
let mf = MachineFunction::new("empty");
let result = mv.verify(&mf);
// Empty function should produce errors (no blocks)
assert!(result.is_err());
}
#[test]
fn test_verify_simple_function() {
let mv = MachineVerifier::new();
let mut mf = MachineFunction::new("test");
mf.blocks
.push(make_block("entry", vec![make_br("exit")], vec!["exit"]));
mf.blocks.push(make_block("exit", vec![], vec![]));
let result = mv.verify(&mf);
assert!(result.is_ok());
}
#[test]
fn test_verify_block_no_terminator() {
let mv = MachineVerifier::new();
let mut mf = MachineFunction::new("test");
mf.blocks.push(make_block(
"entry",
vec![make_instr(1, vec![MachineOperand::Reg(0)])],
vec![],
));
let errors = mv.verify_blocks(&mf);
assert!(!errors.is_empty());
let has_terminator_err = errors.iter().any(|e| e.contains("no terminator"));
assert!(has_terminator_err);
}
#[test]
fn test_verify_duplicate_block_names() {
let mv = MachineVerifier::new();
let mut mf = MachineFunction::new("test");
mf.blocks
.push(make_block("bb", vec![make_br("bb2")], vec!["bb2"]));
mf.blocks.push(make_block("bb", vec![], vec![]));
let errors = mv.verify_blocks(&mf);
assert!(!errors.is_empty());
let has_dup_err = errors.iter().any(|e| e.contains("Duplicate block name"));
assert!(has_dup_err);
}
#[test]
fn test_verify_empty_block_name() {
let mv = MachineVerifier::new();
let mut mf = MachineFunction::new("test");
mf.blocks.push(make_block("", vec![], vec![]));
let errors = mv.verify_blocks(&mf);
assert!(!errors.is_empty());
let has_empty_err = errors.iter().any(|e| e.contains("empty name"));
assert!(has_empty_err);
}
#[test]
fn test_verify_invalid_label_reference() {
let mv = MachineVerifier::new();
let mut mf = MachineFunction::new("test");
mf.blocks.push(make_block(
"entry",
vec![make_br("nonexistent")],
vec!["nonexistent"],
));
mf.blocks.push(make_block("bb1", vec![], vec![]));
let errors = mv.verify_instructions(&mf);
assert!(!errors.is_empty());
let has_label_err = errors.iter().any(|e| e.contains("non-existent block"));
assert!(has_label_err);
}
#[test]
fn test_verify_branch_before_end() {
let mv = MachineVerifier::new();
let mut mf = MachineFunction::new("test");
mf.blocks.push(make_block(
"entry",
vec![make_br("exit"), make_instr(1, vec![])],
vec!["exit"],
));
mf.blocks.push(make_block("exit", vec![], vec![]));
let errors = mv.verify_instructions(&mf);
let has_branch_err = errors
.iter()
.any(|e| e.contains("unconditional branch before end"));
assert!(has_branch_err);
}
#[test]
fn test_verify_register_double_def() {
let mv = MachineVerifier::new();
let mut mf = MachineFunction::new("test");
let mut instr1 = make_instr(1, vec![MachineOperand::Reg(0)]);
instr1.def = Some(5);
let mut instr2 = make_instr(2, vec![MachineOperand::Reg(0)]);
instr2.def = Some(5);
mf.blocks
.push(make_block("entry", vec![instr1, instr2], vec![]));
let errors = mv.verify_registers(&mf);
let has_def_err = errors.iter().any(|e| e.contains("defined multiple times"));
assert!(has_def_err);
}
#[test]
fn test_verify_cfg_entry_predecessor() {
let mv = MachineVerifier::new();
let mut mf = MachineFunction::new("test");
mf.blocks.push(make_block("entry", vec![], vec![]));
mf.blocks
.push(make_block("bb1", vec![make_br("entry")], vec!["entry"]));
let errors = mv.verify_cfg(&mf);
let has_entry_err = errors
.iter()
.any(|e| e.contains("branch to the entry block"));
assert!(has_entry_err);
}
#[test]
fn test_verify_cfg_invalid_successor() {
let mv = MachineVerifier::new();
let mut mf = MachineFunction::new("test");
mf.blocks.push(make_block(
"entry",
vec![make_br("nowhere")],
vec!["nowhere"],
));
let errors = mv.verify_cfg(&mf);
let has_succ_err = errors.iter().any(|e| e.contains("does not exist"));
assert!(has_succ_err);
}
#[test]
fn test_verify_cfg_unreachable_block() {
let mv = MachineVerifier::new();
let mut mf = MachineFunction::new("test");
mf.blocks
.push(make_block("entry", vec![make_br("exit")], vec!["exit"]));
mf.blocks.push(make_block("exit", vec![], vec![]));
mf.blocks.push(make_block("orphan", vec![], vec![]));
let errors = mv.verify_cfg(&mf);
let has_unreachable_err = errors.iter().any(|e| e.contains("unreachable"));
assert!(has_unreachable_err);
}
#[test]
fn test_verify_liveness_basic() {
let mv = MachineVerifier::new();
let mut mf = MachineFunction::new("test");
let mut instr = make_instr(1, vec![MachineOperand::Reg(1)]);
instr.def = Some(0);
mf.blocks.push(make_block(
"entry",
vec![instr, make_br("exit")],
vec!["exit"],
));
mf.blocks.push(make_block("exit", vec![], vec![]));
let errors = mv.verify_liveness(&mf);
// Liveness analysis should not produce errors for well-formed blocks
assert!(errors.is_empty());
}
#[test]
fn test_collect_defs_and_uses() {
let mv = MachineVerifier::new();
let mut instr = make_instr(1, vec![MachineOperand::Reg(1), MachineOperand::Reg(2)]);
instr.def = Some(0);
let block = make_block("bb", vec![instr], vec![]);
let (defs, uses) = mv.collect_defs_and_uses(&block);
assert_eq!(defs.len(), 1);
assert!(defs.contains(&0));
assert_eq!(uses.len(), 2);
assert!(uses.contains(&1));
assert!(uses.contains(&2));
}
#[test]
fn test_has_terminator() {
let mv = MachineVerifier::new();
let with_term = make_block("bb", vec![make_br("L0")], vec![]);
assert!(mv.has_terminator(&with_term));
let without_term = make_block(
"bb",
vec![make_instr(1, vec![MachineOperand::Reg(0)])],
vec![],
);
assert!(!mv.has_terminator(&without_term));
let empty = make_block("bb", vec![], vec![]);
assert!(!mv.has_terminator(&empty));
}
#[test]
fn test_compute_live_outs() {
let mv = MachineVerifier::new();
let mut mf = MachineFunction::new("test");
let mut instr = make_instr(1, vec![MachineOperand::Reg(1)]);
instr.def = Some(0);
mf.blocks.push(make_block(
"entry",
vec![instr, make_br("exit")],
vec!["exit"],
));
mf.blocks.push(make_block("exit", vec![], vec![]));
let live_outs = mv.compute_live_outs(&mf);
// Should have live-out maps for both blocks
assert!(live_outs.contains_key("entry"));
assert!(live_outs.contains_key("exit"));
}
#[test]
fn test_default() {
let mv = MachineVerifier::default();
assert!(mv.check_liveness);
}
#[test]
fn test_verify_with_liveness_disabled() {
let mut mv = MachineVerifier::new();
mv.check_liveness = false;
let mut mf = MachineFunction::new("test");
mf.blocks
.push(make_block("entry", vec![make_br("exit")], vec!["exit"]));
mf.blocks.push(make_block("exit", vec![], vec![]));
let result = mv.verify(&mf);
assert!(result.is_ok());
}
}