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
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
//! CodeGen Lowering — target-independent IR-to-MachineIR translation.
//! Clean-room behavioral reconstruction. Phase 6 — LLVM.CODEGEN.1 Court.
//!
//! This module provides the core lowering infrastructure that translates
//! LLVM IR into generic MachineIR (GlobalISel) before target-specific
//! instruction selection:
//!
//! - IRTranslator: translate LLVM IR to generic MachineIR (GlobalISel entry)
//! - Generic opcode mapping: IR opcode → G_* instruction mapping tables
//! - Type legalization: map IR types to legal machine types
//! - ABI lowering: handle calling conventions in generic form
//! - Switch lowering: lower switch to jump table / binary tree / bit test
//! - Select lowering: lower select to branch+phi sequence
//! - LandingPad lowering: lower exception landing pads
//! - VAArg lowering: lower variable argument access
//! - Stack protector lowering: insert stack canary checks
//! - PatchPoint/StackMap lowering: lower GC safepoint intrinsics
//! - InlineAsm lowering: lower inline assembly to machine form
//! - Debug info lowering: translate DbgInfoIntrinsic to DBG_VALUE/DBG_LABEL

use std::collections::HashMap;

// ============================================================================
// Generic MachineIR Opcodes (GlobalISel G_* instructions)
// ============================================================================

/// Generic MachineIR opcodes for target-independent lowering.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum MOpcode {
    // Terminators
    G_BR,
    G_BRCOND,
    G_BRINDIRECT,
    G_BRJT,
    G_RETURN,

    // Integer arithmetic
    G_ADD,
    G_SUB,
    G_MUL,
    G_SDIV,
    G_UDIV,
    G_SREM,
    G_UREM,
    G_AND,
    G_OR,
    G_XOR,
    G_SHL,
    G_LSHR,
    G_ASHR,

    // Floating-point arithmetic
    G_FADD,
    G_FSUB,
    G_FMUL,
    G_FDIV,
    G_FREM,
    G_FNEG,
    G_FABS,
    G_FSQRT,
    G_FMA,

    // Comparison
    G_ICMP,
    G_FCMP,

    // Conversion
    G_TRUNC,
    G_ZEXT,
    G_SEXT,
    G_FPTRUNC,
    G_FPEXT,
    G_FPTOUI,
    G_FPTOSI,
    G_UITOFP,
    G_SITOFP,
    G_BITCAST,
    G_PTRTOINT,
    G_INTTOPTR,
    G_ADDRSPACE_CAST,

    // Memory
    G_LOAD,
    G_STORE,
    G_GEP,
    G_FRAME_INDEX,
    G_GLOBAL_VALUE,
    G_CONSTANT,

    // Vector
    G_EXTRACT_VEC_ELT,
    G_INSERT_VEC_ELT,
    G_BUILD_VECTOR,
    G_SHUFFLE_VECTOR,
    G_CONCAT_VECTORS,

    // Intrinsics
    G_INTRINSIC,
    G_INTRINSIC_W_SIDE_EFFECTS,

    // Variadic
    G_VASTART,
    G_VAARG,
    G_VAEND,
    G_VACOPY,

    // Exception handling
    G_LANDINGPAD,
    G_RESUME,
    G_CLEANUPRET,

    // Atomic
    G_ATOMICRMW_XCHG,
    G_ATOMICRMW_ADD,
    G_ATOMICRMW_SUB,
    G_ATOMICRMW_AND,
    G_ATOMICRMW_NAND,
    G_ATOMICRMW_OR,
    G_ATOMICRMW_XOR,
    G_ATOMICRMW_MIN,
    G_ATOMICRMW_MAX,
    G_ATOMICRMW_UMIN,
    G_ATOMICRMW_UMAX,
    G_ATOMIC_CMPXCHG,

    // Stack
    G_STACKPROTECTOR,
    G_STACKPROTECTOR_CHECK,

    // Other
    G_SELECT,
    G_PHI,
    G_UNREACHABLE,
    G_CONSTANT_POOL,
    G_JUMP_TABLE,
    G_DYN_STACKALLOC,

    // Debug
    G_DBG_VALUE,
    G_DBG_LABEL,
    G_DBG_DECLARE,

    // Patches
    G_PATCHPOINT,
    G_STACKMAP,
    G_STATEPOINT,

    // Inline assembly
    G_INLINEASM,
}

impl MOpcode {
    pub fn as_str(&self) -> &'static str {
        match self {
            MOpcode::G_BR => "G_BR",
            MOpcode::G_BRCOND => "G_BRCOND",
            MOpcode::G_BRINDIRECT => "G_BRINDIRECT",
            MOpcode::G_BRJT => "G_BRJT",
            MOpcode::G_RETURN => "G_RETURN",
            MOpcode::G_ADD => "G_ADD",
            MOpcode::G_SUB => "G_SUB",
            MOpcode::G_MUL => "G_MUL",
            MOpcode::G_SDIV => "G_SDIV",
            MOpcode::G_UDIV => "G_UDIV",
            MOpcode::G_SREM => "G_SREM",
            MOpcode::G_UREM => "G_UREM",
            MOpcode::G_AND => "G_AND",
            MOpcode::G_OR => "G_OR",
            MOpcode::G_XOR => "G_XOR",
            MOpcode::G_SHL => "G_SHL",
            MOpcode::G_LSHR => "G_LSHR",
            MOpcode::G_ASHR => "G_ASHR",
            MOpcode::G_FADD => "G_FADD",
            MOpcode::G_FSUB => "G_FSUB",
            MOpcode::G_FMUL => "G_FMUL",
            MOpcode::G_FDIV => "G_FDIV",
            MOpcode::G_FREM => "G_FREM",
            MOpcode::G_FNEG => "G_FNEG",
            MOpcode::G_FABS => "G_FABS",
            MOpcode::G_FSQRT => "G_FSQRT",
            MOpcode::G_FMA => "G_FMA",
            MOpcode::G_ICMP => "G_ICMP",
            MOpcode::G_FCMP => "G_FCMP",
            MOpcode::G_TRUNC => "G_TRUNC",
            MOpcode::G_ZEXT => "G_ZEXT",
            MOpcode::G_SEXT => "G_SEXT",
            MOpcode::G_FPTRUNC => "G_FPTRUNC",
            MOpcode::G_FPEXT => "G_FPEXT",
            MOpcode::G_FPTOUI => "G_FPTOUI",
            MOpcode::G_FPTOSI => "G_FPTOSI",
            MOpcode::G_UITOFP => "G_UITOFP",
            MOpcode::G_SITOFP => "G_SITOFP",
            MOpcode::G_BITCAST => "G_BITCAST",
            MOpcode::G_PTRTOINT => "G_PTRTOINT",
            MOpcode::G_INTTOPTR => "G_INTTOPTR",
            MOpcode::G_ADDRSPACE_CAST => "G_ADDRSPACE_CAST",
            MOpcode::G_LOAD => "G_LOAD",
            MOpcode::G_STORE => "G_STORE",
            MOpcode::G_GEP => "G_GEP",
            MOpcode::G_FRAME_INDEX => "G_FRAME_INDEX",
            MOpcode::G_GLOBAL_VALUE => "G_GLOBAL_VALUE",
            MOpcode::G_CONSTANT => "G_CONSTANT",
            MOpcode::G_EXTRACT_VEC_ELT => "G_EXTRACT_VEC_ELT",
            MOpcode::G_INSERT_VEC_ELT => "G_INSERT_VEC_ELT",
            MOpcode::G_BUILD_VECTOR => "G_BUILD_VECTOR",
            MOpcode::G_SHUFFLE_VECTOR => "G_SHUFFLE_VECTOR",
            MOpcode::G_CONCAT_VECTORS => "G_CONCAT_VECTORS",
            MOpcode::G_INTRINSIC => "G_INTRINSIC",
            MOpcode::G_INTRINSIC_W_SIDE_EFFECTS => "G_INTRINSIC_W_SIDE_EFFECTS",
            MOpcode::G_VASTART => "G_VASTART",
            MOpcode::G_VAARG => "G_VAARG",
            MOpcode::G_VAEND => "G_VAEND",
            MOpcode::G_VACOPY => "G_VACOPY",
            MOpcode::G_LANDINGPAD => "G_LANDINGPAD",
            MOpcode::G_RESUME => "G_RESUME",
            MOpcode::G_CLEANUPRET => "G_CLEANUPRET",
            MOpcode::G_ATOMICRMW_XCHG => "G_ATOMICRMW_XCHG",
            MOpcode::G_ATOMICRMW_ADD => "G_ATOMICRMW_ADD",
            MOpcode::G_ATOMICRMW_SUB => "G_ATOMICRMW_SUB",
            MOpcode::G_ATOMICRMW_AND => "G_ATOMICRMW_AND",
            MOpcode::G_ATOMICRMW_NAND => "G_ATOMICRMW_NAND",
            MOpcode::G_ATOMICRMW_OR => "G_ATOMICRMW_OR",
            MOpcode::G_ATOMICRMW_XOR => "G_ATOMICRMW_XOR",
            MOpcode::G_ATOMICRMW_MIN => "G_ATOMICRMW_MIN",
            MOpcode::G_ATOMICRMW_MAX => "G_ATOMICRMW_MAX",
            MOpcode::G_ATOMICRMW_UMIN => "G_ATOMICRMW_UMIN",
            MOpcode::G_ATOMICRMW_UMAX => "G_ATOMICRMW_UMAX",
            MOpcode::G_ATOMIC_CMPXCHG => "G_ATOMIC_CMPXCHG",
            MOpcode::G_STACKPROTECTOR => "G_STACKPROTECTOR",
            MOpcode::G_STACKPROTECTOR_CHECK => "G_STACKPROTECTOR_CHECK",
            MOpcode::G_SELECT => "G_SELECT",
            MOpcode::G_PHI => "G_PHI",
            MOpcode::G_UNREACHABLE => "G_UNREACHABLE",
            MOpcode::G_CONSTANT_POOL => "G_CONSTANT_POOL",
            MOpcode::G_JUMP_TABLE => "G_JUMP_TABLE",
            MOpcode::G_DYN_STACKALLOC => "G_DYN_STACKALLOC",
            MOpcode::G_DBG_VALUE => "G_DBG_VALUE",
            MOpcode::G_DBG_LABEL => "G_DBG_LABEL",
            MOpcode::G_DBG_DECLARE => "G_DBG_DECLARE",
            MOpcode::G_PATCHPOINT => "G_PATCHPOINT",
            MOpcode::G_STACKMAP => "G_STACKMAP",
            MOpcode::G_STATEPOINT => "G_STATEPOINT",
            MOpcode::G_INLINEASM => "G_INLINEASM",
        }
    }
}

// ============================================================================
// IR to Generic Opcode Mapping Table
// ============================================================================

/// Maps a standard IR opcode name to the corresponding generic MachineIR opcode.
pub fn ir_opcode_to_mopcode(ir_op: &str) -> Option<MOpcode> {
    match ir_op {
        "br" => Some(MOpcode::G_BR),
        "brcond" => Some(MOpcode::G_BRCOND),
        "switch" => Some(MOpcode::G_BRJT),
        "ret" => Some(MOpcode::G_RETURN),
        "add" => Some(MOpcode::G_ADD),
        "sub" => Some(MOpcode::G_SUB),
        "mul" => Some(MOpcode::G_MUL),
        "sdiv" => Some(MOpcode::G_SDIV),
        "udiv" => Some(MOpcode::G_UDIV),
        "srem" => Some(MOpcode::G_SREM),
        "urem" => Some(MOpcode::G_UREM),
        "and" => Some(MOpcode::G_AND),
        "or" => Some(MOpcode::G_OR),
        "xor" => Some(MOpcode::G_XOR),
        "shl" => Some(MOpcode::G_SHL),
        "lshr" => Some(MOpcode::G_LSHR),
        "ashr" => Some(MOpcode::G_ASHR),
        "fadd" => Some(MOpcode::G_FADD),
        "fsub" => Some(MOpcode::G_FSUB),
        "fmul" => Some(MOpcode::G_FMUL),
        "fdiv" => Some(MOpcode::G_FDIV),
        "frem" => Some(MOpcode::G_FREM),
        "fneg" => Some(MOpcode::G_FNEG),
        "icmp" => Some(MOpcode::G_ICMP),
        "fcmp" => Some(MOpcode::G_FCMP),
        "trunc" => Some(MOpcode::G_TRUNC),
        "zext" => Some(MOpcode::G_ZEXT),
        "sext" => Some(MOpcode::G_SEXT),
        "fptrunc" => Some(MOpcode::G_FPTRUNC),
        "fpext" => Some(MOpcode::G_FPEXT),
        "fptoui" => Some(MOpcode::G_FPTOUI),
        "fptosi" => Some(MOpcode::G_FPTOSI),
        "uitofp" => Some(MOpcode::G_UITOFP),
        "sitofp" => Some(MOpcode::G_SITOFP),
        "bitcast" => Some(MOpcode::G_BITCAST),
        "inttoptr" => Some(MOpcode::G_INTTOPTR),
        "ptrtoint" => Some(MOpcode::G_PTRTOINT),
        "load" => Some(MOpcode::G_LOAD),
        "store" => Some(MOpcode::G_STORE),
        "getelementptr" => Some(MOpcode::G_GEP),
        "extractelement" => Some(MOpcode::G_EXTRACT_VEC_ELT),
        "insertelement" => Some(MOpcode::G_INSERT_VEC_ELT),
        "shufflevector" => Some(MOpcode::G_SHUFFLE_VECTOR),
        "select" => Some(MOpcode::G_SELECT),
        "phi" => Some(MOpcode::G_PHI),
        "unreachable" => Some(MOpcode::G_UNREACHABLE),
        "landingpad" => Some(MOpcode::G_LANDINGPAD),
        "resume" => Some(MOpcode::G_RESUME),
        "va_arg" => Some(MOpcode::G_VAARG),
        "atomicrmw" => Some(MOpcode::G_ATOMICRMW_XCHG),
        "cmpxchg" => Some(MOpcode::G_ATOMIC_CMPXCHG),
        "alloca" => Some(MOpcode::G_FRAME_INDEX),
        _ => None,
    }
}

/// Returns true if the generic opcode is a terminator.
pub fn is_terminator(op: MOpcode) -> bool {
    matches!(
        op,
        MOpcode::G_BR
            | MOpcode::G_BRCOND
            | MOpcode::G_BRINDIRECT
            | MOpcode::G_BRJT
            | MOpcode::G_RETURN
            | MOpcode::G_UNREACHABLE
            | MOpcode::G_CLEANUPRET
    )
}

/// Returns true if the generic opcode may load from memory.
pub fn may_load(op: MOpcode) -> bool {
    matches!(
        op,
        MOpcode::G_LOAD
            | MOpcode::G_ATOMICRMW_XCHG
            | MOpcode::G_ATOMICRMW_ADD
            | MOpcode::G_ATOMICRMW_SUB
            | MOpcode::G_ATOMICRMW_AND
            | MOpcode::G_ATOMICRMW_NAND
            | MOpcode::G_ATOMICRMW_OR
            | MOpcode::G_ATOMICRMW_XOR
            | MOpcode::G_ATOMICRMW_MIN
            | MOpcode::G_ATOMICRMW_MAX
            | MOpcode::G_ATOMICRMW_UMIN
            | MOpcode::G_ATOMICRMW_UMAX
            | MOpcode::G_ATOMIC_CMPXCHG
            | MOpcode::G_VAARG
    )
}

// ============================================================================
// Type Legalization
// ============================================================================

/// Describes how an IR type maps to a legal machine register type.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TypeLegalAction {
    /// Use as-is.
    Legal,
    /// Widen to a larger scalar type (e.g., i8 → i32).
    WidenScalar,
    /// Split into smaller scalars (e.g., i128 → i64 + i64).
    NarrowScalar,
    /// Widen vector element count.
    WidenVector,
    /// Split vector into sub-vectors.
    SplitVector,
    /// Scalarize (do element-wise operations).
    Scalarize,
    /// Not supported on this target.
    Unsupported,
}

/// LegalizeInfo describes how each type should be handled.
pub struct LegalizeInfo {
    /// Map from type bitwidth to action.
    scalar_actions: HashMap<u32, TypeLegalAction>,
    /// Map from vector (num_elements, elem_bits) to action.
    vector_actions: HashMap<(u32, u32), TypeLegalAction>,
    /// Maximum legal scalar width in bits.
    max_legal_scalar: u32,
    /// Minimum legal scalar width in bits.
    min_legal_scalar: u32,
}

impl LegalizeInfo {
    pub fn new() -> Self {
        Self {
            scalar_actions: HashMap::new(),
            vector_actions: HashMap::new(),
            max_legal_scalar: 64,
            min_legal_scalar: 8,
        }
    }

    /// Set a scalar type as legal.
    pub fn set_scalar_legal(&mut self, bits: u32) {
        self.scalar_actions.insert(bits, TypeLegalAction::Legal);
    }

    /// Set a scalar type to be widened to target_bits.
    pub fn set_scalar_widen_to(&mut self, bits: u32, target_bits: u32) {
        self.scalar_actions
            .insert(bits, TypeLegalAction::WidenScalar);
        self.scalar_actions
            .insert(target_bits, TypeLegalAction::Legal);
    }

    /// Query the action for a scalar type.
    pub fn get_scalar_action(&self, bits: u32) -> TypeLegalAction {
        self.scalar_actions
            .get(&bits)
            .copied()
            .unwrap_or(TypeLegalAction::Unsupported)
    }

    /// Set a vector type as legal.
    pub fn set_vector_legal(&mut self, num_elements: u32, elem_bits: u32) {
        self.vector_actions
            .insert((num_elements, elem_bits), TypeLegalAction::Legal);
    }

    /// Query the action for a vector type.
    pub fn get_vector_action(&self, num_elements: u32, elem_bits: u32) -> TypeLegalAction {
        self.vector_actions
            .get(&(num_elements, elem_bits))
            .copied()
            .unwrap_or(TypeLegalAction::Scalarize)
    }
}

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

// ============================================================================
// ABI Lowering Info
// ============================================================================

/// Describes how a scalar type is passed or returned.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ArgPassing {
    /// Passed in a register.
    InRegister,
    /// Passed on the stack.
    OnStack,
    /// Split across multiple registers (two halves).
    SplitReg,
    /// Passed via pointer (byval).
    Indirect,
}

/// ABI lowering information for a target.
pub struct ABILowering {
    /// Target triple (e.g., "x86_64-linux-gnu").
    pub triple: String,
    /// Primary integer register width.
    pub pointer_width: u32,
    /// Maximum number of integer argument registers.
    pub max_int_arg_regs: u32,
    /// Maximum number of floating-point argument registers.
    pub max_fp_arg_regs: u32,
    /// Which argument positions are passed in registers.
    pub arg_assignments: HashMap<u32, ArgPassing>,
}

impl ABILowering {
    pub fn new(triple: &str) -> Self {
        let pointer_width = if triple.starts_with("x86_64") { 64 } else { 32 };
        let max_int = if triple.starts_with("x86_64") { 6 } else { 0 };
        let max_fp = if triple.starts_with("x86_64") { 8 } else { 0 };

        Self {
            triple: triple.to_string(),
            pointer_width,
            max_int_arg_regs: max_int,
            max_fp_arg_regs: max_fp,
            arg_assignments: HashMap::new(),
        }
    }

    /// Determine how argument `arg_idx` of type `ty_bits` should be passed.
    pub fn classify_arg(&self, arg_idx: u32, ty_bits: u32, is_fp: bool) -> ArgPassing {
        if is_fp && arg_idx < self.max_fp_arg_regs {
            ArgPassing::InRegister
        } else if !is_fp && arg_idx < self.max_int_arg_regs {
            if ty_bits > self.pointer_width {
                ArgPassing::SplitReg
            } else {
                ArgPassing::InRegister
            }
        } else {
            ArgPassing::OnStack
        }
    }

    /// Build assignment map for a function.
    pub fn assign_args(&mut self, num_args: u32) {
        self.arg_assignments.clear();
        for i in 0..num_args {
            let passing = if i < self.max_int_arg_regs {
                ArgPassing::InRegister
            } else {
                ArgPassing::OnStack
            };
            self.arg_assignments.insert(i, passing);
        }
    }
}

// ============================================================================
// Switch Lowering
// ============================================================================

/// Lower a switch instruction to one of several strategies.
pub enum SwitchLoweringStrategy {
    /// Lower to a jump table for dense case ranges.
    JumpTable {
        base: u64,
        default_block: u32,
        cases: Vec<(u64, u32)>,
    },
    /// Lower to a binary search tree of conditional branches.
    BinarySearch {
        default_block: u32,
        cases: Vec<(u64, u32)>,
    },
    /// Lower to bit test for sparse small-ranges.
    BitTest {
        base: u64,
        num_bits: u32,
        default_block: u32,
        case_blocks: Vec<u32>,
    },
    /// Fall back to a chain of conditional branches.
    ConditionalChain {
        default_block: u32,
        cases: Vec<(u64, u32)>,
    },
}

/// SwitchLowering selects the best strategy for a given set of cases.
pub struct SwitchLowering {
    /// Minimum number of cases to use a jump table.
    pub min_jump_table_size: usize,
    /// Maximum density for binary search (max range / num cases).
    pub max_binary_search_density: u64,
}

impl SwitchLowering {
    pub fn new() -> Self {
        Self {
            min_jump_table_size: 4,
            max_binary_search_density: 10,
        }
    }

    /// Choose the best lowering strategy for a set of case values and targets.
    pub fn select_strategy(
        &self,
        cases: &[(u64, u32)],
        default_block: u32,
    ) -> SwitchLoweringStrategy {
        if cases.is_empty() {
            return SwitchLoweringStrategy::BinarySearch {
                default_block,
                cases: Vec::new(),
            };
        }

        let min_val = cases.iter().map(|(v, _)| *v).min().unwrap();
        let max_val = cases.iter().map(|(v, _)| *v).max().unwrap();
        let range = max_val - min_val;
        let density = range / cases.len() as u64;

        if cases.len() >= self.min_jump_table_size && density <= self.max_binary_search_density {
            // Dense: use a jump table
            let mut jump_cases = Vec::new();
            for &(val, block) in cases {
                jump_cases.push((val - min_val, block));
            }
            SwitchLoweringStrategy::JumpTable {
                base: min_val,
                default_block,
                cases: jump_cases,
            }
        } else if cases.len() <= 8 {
            // Small: use conditional chain
            SwitchLoweringStrategy::ConditionalChain {
                default_block,
                cases: cases.to_vec(),
            }
        } else {
            // Medium: use binary search
            SwitchLoweringStrategy::BinarySearch {
                default_block,
                cases: cases.to_vec(),
            }
        }
    }
}

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

// ============================================================================
// Select Lowering
// ============================================================================

/// Lower a select instruction (a = cond ? true_val : false_val) into
/// a branch+phi sequence for targets without conditional moves.
pub struct SelectLowering {
    /// Whether the target has a conditional move instruction.
    pub has_conditional_move: bool,
}

impl SelectLowering {
    pub fn new() -> Self {
        Self {
            has_conditional_move: false,
        }
    }

    /// Determine if a select should be lowered to branch+phi.
    pub fn should_lower_to_branch(&self, _true_block: u32, _false_block: u32) -> bool {
        !self.has_conditional_move
    }
}

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

// ============================================================================
// LandingPad Lowering
// ============================================================================

/// Information about an exception landing pad.
#[derive(Debug, Clone)]
pub struct LandingPadInfo {
    pub block_id: u32,
    pub catch_types: Vec<u32>,
    pub filter_types: Vec<u32>,
    pub cleanup: bool,
}

/// Lower landing pad instructions to exception dispatch sequences.
pub struct LandingPadLowering {
    pub pads: Vec<LandingPadInfo>,
}

impl LandingPadLowering {
    pub fn new() -> Self {
        Self { pads: Vec::new() }
    }

    /// Add a landing pad to be lowered.
    pub fn add_pad(&mut self, block_id: u32, catch_types: Vec<u32>, cleanup: bool) {
        self.pads.push(LandingPadInfo {
            block_id,
            catch_types,
            filter_types: Vec::new(),
            cleanup,
        });
    }
}

// ============================================================================
// VAArg Lowering
// ============================================================================

/// Lower va_arg access to target-specific code sequences.
pub struct VAArgLowering {
    pub is_x86_64: bool,
}

impl VAArgLowering {
    pub fn new(is_x86_64: bool) -> Self {
        Self { is_x86_64 }
    }

    /// Get the number of integer registers used for varargs on this platform.
    pub fn num_int_regs(&self) -> u32 {
        if self.is_x86_64 {
            6
        } else {
            0
        }
    }

    /// Get the number of FP registers used for varargs on this platform.
    pub fn num_fp_regs(&self) -> u32 {
        if self.is_x86_64 {
            8
        } else {
            0
        }
    }
}

// ============================================================================
// Stack Protector Lowering
// ============================================================================

/// Inserts stack canary checks before function returns.
pub struct StackProtectorLowering {
    pub enabled: bool,
    pub canary_offset: i32,
}

impl StackProtectorLowering {
    pub fn new() -> Self {
        Self {
            enabled: true,
            canary_offset: -8,
        }
    }

    /// Returns whether we should insert a stack protector for this function.
    pub fn should_protect(&self, has_local_array: bool) -> bool {
        self.enabled && has_local_array
    }
}

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

// ============================================================================
// PatchPoint / StackMap Lowering
// ============================================================================

/// Lower GC safepoint intrinsics (patchpoint, stackmap, statepoint).
pub struct GCSafepointLowering {
    pub next_id: u64,
}

#[derive(Debug, Clone)]
pub struct StackMapRecord {
    pub id: u64,
    pub offset: u32,
    pub locations: Vec<StackMapLocation>,
}

#[derive(Debug, Clone)]
pub enum StackMapLocation {
    Register(u32),
    Direct(u32),
    Indirect(u32, i32),
    Constant(i64),
    ConstantIndex(u32),
}

impl GCSafepointLowering {
    pub fn new() -> Self {
        Self { next_id: 0 }
    }

    /// Generate a new stack map ID.
    pub fn next_stackmap_id(&mut self) -> u64 {
        let id = self.next_id;
        self.next_id += 1;
        id
    }
}

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

// ============================================================================
// InlineAsm Lowering
// ============================================================================

/// Lower inline assembly from LLVM IR to machine instruction sequences.
pub struct InlineAsmLowering {
    pub target_arch: String,
}

#[derive(Debug, Clone)]
pub struct InlineAsmInfo {
    pub asm_string: String,
    pub constraints: String,
    pub has_side_effects: bool,
    pub is_align_stack: bool,
    pub inputs: Vec<InlineAsmOperand>,
    pub outputs: Vec<InlineAsmOperand>,
    pub clobbers: Vec<String>,
}

#[derive(Debug, Clone)]
pub struct InlineAsmOperand {
    pub reg_num: u32,
    pub constraint: String,
    pub is_output: bool,
}

impl InlineAsmLowering {
    pub fn new(arch: &str) -> Self {
        Self {
            target_arch: arch.to_string(),
        }
    }

    /// Parse an inline assembly constraint string.
    pub fn parse_constraints(&self, constraints: &str) -> Vec<InlineAsmOperand> {
        let mut operands = Vec::new();
        let parts: Vec<&str> = constraints.split(',').collect();
        for (i, part) in parts.iter().enumerate() {
            let trimmed = part.trim();
            if !trimmed.is_empty() {
                operands.push(InlineAsmOperand {
                    reg_num: i as u32,
                    constraint: trimmed.to_string(),
                    is_output: trimmed.starts_with('='),
                });
            }
        }
        operands
    }
}

// ============================================================================
// Debug Info Lowering
// ============================================================================

/// Lower LLVM debug info intrinsics (llvm.dbg.value, llvm.dbg.declare) to
/// machine-level debug instructions (DBG_VALUE, DBG_LABEL, DBG_DECLARE).
pub struct DebugInfoLowering {
    pub next_label_id: u32,
}

#[derive(Debug, Clone)]
pub struct MachineDbgValue {
    pub variable: String,
    pub expression: String,
    pub reg: Option<u32>,
    pub stack_offset: Option<i32>,
    pub location: Option<String>,
}

impl DebugInfoLowering {
    pub fn new() -> Self {
        Self { next_label_id: 0 }
    }

    /// Create a DBG_VALUE for a register location.
    pub fn create_dbg_value_reg(
        &mut self,
        variable: &str,
        expression: &str,
        reg: u32,
        loc: Option<&str>,
    ) -> MachineDbgValue {
        MachineDbgValue {
            variable: variable.to_string(),
            expression: expression.to_string(),
            reg: Some(reg),
            stack_offset: None,
            location: loc.map(|s| s.to_string()),
        }
    }

    /// Create a DBG_VALUE for a stack location.
    pub fn create_dbg_value_stack(
        &mut self,
        variable: &str,
        expression: &str,
        offset: i32,
        loc: Option<&str>,
    ) -> MachineDbgValue {
        MachineDbgValue {
            variable: variable.to_string(),
            expression: expression.to_string(),
            reg: None,
            stack_offset: Some(offset),
            location: loc.map(|s| s.to_string()),
        }
    }

    /// Generate a new unique DBG_LABEL identifier.
    pub fn next_label_id(&mut self) -> u32 {
        let id = self.next_label_id;
        self.next_label_id += 1;
        id
    }
}

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

// ============================================================================
// IRTranslator — Main entry point for GlobalISel
// ============================================================================

/// The IRTranslator is the main driver that converts LLVM IR functions
/// into generic MachineIR. It orchestrates opcode mapping, type legalization,
/// ABI lowering, and all the specialized lowering passes.
pub struct IRTranslator {
    pub legalize_info: LegalizeInfo,
    pub abi_lowering: ABILowering,
    pub switch_lowering: SwitchLowering,
    pub select_lowering: SelectLowering,
    pub landing_pad_lowering: LandingPadLowering,
    pub vaarg_lowering: VAArgLowering,
    pub stack_protector: StackProtectorLowering,
    pub gc_lowering: GCSafepointLowering,
    pub inline_asm: InlineAsmLowering,
    pub debug_info: DebugInfoLowering,
    /// Statistics
    pub instructions_translated: usize,
    pub opcodes_unmapped: usize,
}

impl IRTranslator {
    pub fn new(target_triple: &str) -> Self {
        let mut legalize = LegalizeInfo::new();
        // Set up basic legal types
        for bits in &[1, 8, 16, 32, 64] {
            legalize.set_scalar_legal(*bits);
        }

        Self {
            legalize_info: legalize,
            abi_lowering: ABILowering::new(target_triple),
            switch_lowering: SwitchLowering::new(),
            select_lowering: SelectLowering::new(),
            landing_pad_lowering: LandingPadLowering::new(),
            vaarg_lowering: VAArgLowering::new(target_triple.starts_with("x86_64")),
            stack_protector: StackProtectorLowering::new(),
            gc_lowering: GCSafepointLowering::new(),
            inline_asm: InlineAsmLowering::new(if target_triple.starts_with("x86_64") {
                "x86_64"
            } else if target_triple.starts_with("aarch64") {
                "aarch64"
            } else if target_triple.starts_with("riscv64") {
                "riscv64"
            } else {
                "unknown"
            }),
            debug_info: DebugInfoLowering::new(),
            instructions_translated: 0,
            opcodes_unmapped: 0,
        }
    }

    /// Translate an IR opcode to a generic MachineIR opcode, recording stats.
    pub fn translate_opcode(&mut self, ir_op: &str) -> Option<MOpcode> {
        match ir_opcode_to_mopcode(ir_op) {
            Some(mop) => {
                self.instructions_translated += 1;
                Some(mop)
            }
            None => {
                self.opcodes_unmapped += 1;
                None
            }
        }
    }

    /// Get statistics summary.
    pub fn stats_summary(&self) -> String {
        format!(
            "IRTranslator: {} instructions translated, {} opcodes unmapped",
            self.instructions_translated, self.opcodes_unmapped
        )
    }
}

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

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

    #[test]
    fn test_ir_to_mopcode_add() {
        assert_eq!(ir_opcode_to_mopcode("add"), Some(MOpcode::G_ADD));
    }

    #[test]
    fn test_ir_to_mopcode_sub() {
        assert_eq!(ir_opcode_to_mopcode("sub"), Some(MOpcode::G_SUB));
    }

    #[test]
    fn test_ir_to_mopcode_load() {
        assert_eq!(ir_opcode_to_mopcode("load"), Some(MOpcode::G_LOAD));
    }

    #[test]
    fn test_ir_to_mopcode_store() {
        assert_eq!(ir_opcode_to_mopcode("store"), Some(MOpcode::G_STORE));
    }

    #[test]
    fn test_ir_to_mopcode_unknown() {
        assert_eq!(ir_opcode_to_mopcode("unknown_op"), None);
    }

    #[test]
    fn test_is_terminator() {
        assert!(is_terminator(MOpcode::G_BR));
        assert!(is_terminator(MOpcode::G_RETURN));
        assert!(!is_terminator(MOpcode::G_ADD));
    }

    #[test]
    fn test_may_load() {
        assert!(may_load(MOpcode::G_LOAD));
        assert!(!may_load(MOpcode::G_STORE));
        assert!(!may_load(MOpcode::G_ADD));
    }

    #[test]
    fn test_legalize_info_scalar() {
        let mut info = LegalizeInfo::new();
        info.set_scalar_legal(32);
        assert_eq!(info.get_scalar_action(32), TypeLegalAction::Legal);
        assert_eq!(info.get_scalar_action(8), TypeLegalAction::Unsupported);
    }

    #[test]
    fn test_abi_lowering_x86_64() {
        let abi = ABILowering::new("x86_64-linux-gnu");
        assert_eq!(abi.pointer_width, 64);
        assert_eq!(abi.max_int_arg_regs, 6);
        assert_eq!(abi.max_fp_arg_regs, 8);
    }

    #[test]
    fn test_abi_lowering_classify() {
        let abi = ABILowering::new("x86_64-linux-gnu");
        assert_eq!(abi.classify_arg(0, 32, false), ArgPassing::InRegister);
        assert_eq!(abi.classify_arg(10, 32, false), ArgPassing::OnStack);
    }

    #[test]
    fn test_switch_dense() {
        let sl = SwitchLowering::new();
        let cases = vec![(10, 2), (11, 3), (12, 4), (13, 5), (14, 6)];
        match sl.select_strategy(&cases, 1) {
            SwitchLoweringStrategy::JumpTable {
                base,
                default_block,
                ..
            } => {
                assert_eq!(base, 10);
                assert_eq!(default_block, 1);
            }
            _ => panic!("Expected JumpTable strategy"),
        }
    }

    #[test]
    fn test_switch_sparse() {
        let sl = SwitchLowering::new();
        let cases = vec![(1, 2), (100, 3)];
        match sl.select_strategy(&cases, 1) {
            SwitchLoweringStrategy::ConditionalChain { .. } => {}
            _ => {} // BinarySearch is also acceptable
        }
    }

    #[test]
    fn test_select_lowering() {
        let sl = SelectLowering::new();
        assert!(sl.should_lower_to_branch(0, 0));
    }

    #[test]
    fn test_va_arg_lowering() {
        let val = VAArgLowering::new(true);
        assert_eq!(val.num_int_regs(), 6);
        assert_eq!(val.num_fp_regs(), 8);
    }

    #[test]
    fn test_stack_protector() {
        let sp = StackProtectorLowering::new();
        assert!(sp.should_protect(true));
        assert!(!sp.should_protect(false));
    }

    #[test]
    fn test_gc_lowering() {
        let mut gc = GCSafepointLowering::new();
        assert_eq!(gc.next_stackmap_id(), 0);
        assert_eq!(gc.next_stackmap_id(), 1);
    }

    #[test]
    fn test_inline_asm_constraints() {
        let iasm = InlineAsmLowering::new("x86_64");
        let ops = iasm.parse_constraints("=r,r,m");
        assert_eq!(ops.len(), 3);
        assert!(ops[0].is_output);
        assert!(!ops[1].is_output);
    }

    #[test]
    fn test_debug_info_lowering() {
        let mut dil = DebugInfoLowering::new();
        let dbg = dil.create_dbg_value_reg("x", "DW_OP_reg", 5, None);
        assert_eq!(dbg.variable, "x");
        assert_eq!(dbg.reg, Some(5));
    }

    #[test]
    fn test_ir_translator_new() {
        let translator = IRTranslator::new("x86_64-linux-gnu");
        assert!(translator.instructions_translated == 0);
    }

    #[test]
    fn test_ir_translator_translate() {
        let mut translator = IRTranslator::new("x86_64-linux-gnu");
        let result = translator.translate_opcode("add");
        assert_eq!(result, Some(MOpcode::G_ADD));
        assert_eq!(translator.instructions_translated, 1);
    }

    #[test]
    fn test_ir_translator_unknown() {
        let mut translator = IRTranslator::new("x86_64-linux-gnu");
        let result = translator.translate_opcode("nonexistent");
        assert_eq!(result, None);
        assert_eq!(translator.opcodes_unmapped, 1);
    }
}

// ============================================================================
// Calling Convention Lowering
// ============================================================================

/// Represents a lowered calling convention assignment.
#[derive(Debug, Clone)]
pub struct CCValAssign {
    /// Argument/return value index.
    pub arg_idx: u32,
    /// Width in bits.
    pub width: u32,
    /// Location where the value is placed.
    pub loc: CCLocation,
    /// Whether this value needs extension (sign-extend, zero-extend).
    pub needs_ext: Option<SignExt>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CCLocation {
    /// In a register.
    Reg(u32),
    /// In memory at the given stack offset.
    Mem(i32),
    /// Split across two registers.
    SplitReg { lo: u32, hi: u32 },
    /// Passed as an indirect pointer.
    Indirect(i32),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SignExt {
    SExt,
    ZExt,
}

/// Target-specific calling convention analyzer.
pub struct CallingConvLowering {
    pub target: String,
    pub pointer_width: u32,
    pub is_64bit: bool,
}

impl CallingConvLowering {
    pub fn new(target: &str) -> Self {
        let is_64bit = target.starts_with("x86_64") || target.starts_with("aarch64");
        CallingConvLowering {
            target: target.to_string(),
            pointer_width: if is_64bit { 64 } else { 32 },
            is_64bit,
        }
    }

    /// Classify a return value type for the target's C calling convention.
    pub fn classify_return_type(&self, ty_bits: u32, is_fp: bool) -> Vec<CCValAssign> {
        if is_fp && ty_bits <= 64 {
            vec![CCValAssign {
                arg_idx: 0,
                width: ty_bits,
                loc: CCLocation::Reg(0),
                needs_ext: None,
            }]
        } else if ty_bits <= self.pointer_width {
            vec![CCValAssign {
                arg_idx: 0,
                width: ty_bits,
                loc: CCLocation::Reg(0),
                needs_ext: if ty_bits < 32 {
                    Some(SignExt::ZExt)
                } else {
                    None
                },
            }]
        } else if ty_bits <= 128 && self.is_64bit {
            vec![CCValAssign {
                arg_idx: 0,
                width: ty_bits / 2,
                loc: CCLocation::SplitReg { lo: 0, hi: 1 },
                needs_ext: None,
            }]
        } else {
            vec![CCValAssign {
                arg_idx: 0,
                width: self.pointer_width,
                loc: CCLocation::Indirect(0),
                needs_ext: None,
            }]
        }
    }

    /// Classify an incoming function argument.
    pub fn classify_argument(
        &self,
        arg_idx: u32,
        ty_bits: u32,
        is_fp: bool,
        next_int_reg: &mut u32,
        next_fp_reg: &mut u32,
        next_stack_offset: &mut i32,
    ) -> CCValAssign {
        let max_int_regs = if self.is_64bit { 6 } else { 0 };
        let max_fp_regs = if self.is_64bit { 8 } else { 0 };

        if is_fp && *next_fp_reg < max_fp_regs {
            let reg = *next_fp_reg;
            *next_fp_reg += 1;
            CCValAssign {
                arg_idx,
                width: ty_bits,
                loc: CCLocation::Reg(reg),
                needs_ext: None,
            }
        } else if !is_fp && *next_int_reg < max_int_regs {
            let reg = *next_int_reg;
            *next_int_reg += 1;
            if ty_bits > self.pointer_width && *next_int_reg < max_int_regs {
                let hi_reg = *next_int_reg;
                *next_int_reg += 1;
                CCValAssign {
                    arg_idx,
                    width: ty_bits,
                    loc: CCLocation::SplitReg { lo: reg, hi: hi_reg },
                    needs_ext: None,
                }
            } else {
                CCValAssign {
                    arg_idx,
                    width: ty_bits,
                    loc: CCLocation::Reg(reg),
                    needs_ext: if ty_bits < 32 {
                        Some(SignExt::ZExt)
                    } else {
                        None
                    },
                }
            }
        } else {
            let offset = *next_stack_offset;
            *next_stack_offset += 8;
            CCValAssign {
                arg_idx,
                width: ty_bits,
                loc: CCLocation::Mem(offset),
                needs_ext: None,
            }
        }
    }
}

// ============================================================================
// Stack Frame Lowering
// ============================================================================

/// Information about the stack frame for a function.
#[derive(Debug, Clone)]
pub struct StackFrameInfo {
    /// Total frame size in bytes.
    pub frame_size: u32,
    /// Stack alignment in bytes.
    pub alignment: u32,
    /// Offset to the return address from the frame base.
    pub return_address_offset: i32,
    /// Offset to the saved frame pointer from the frame base.
    pub frame_pointer_offset: i32,
    /// Offsets of local variables (negative offsets from FP).
    pub locals: Vec<(String, i32, u32)>,
    /// Offsets of callee-saved registers.
    pub callee_saved: Vec<(u32, i32)>,
    /// Whether this function needs a frame pointer.
    pub has_frame_pointer: bool,
    /// Whether this function has a dynamic alloca.
    pub has_dynamic_alloca: bool,
}

impl StackFrameInfo {
    pub fn new() -> Self {
        StackFrameInfo {
            frame_size: 0,
            alignment: 16,
            return_address_offset: 8,
            frame_pointer_offset: 0,
            locals: Vec::new(),
            callee_saved: Vec::new(),
            has_frame_pointer: false,
            has_dynamic_alloca: false,
        }
    }

    /// Allocate space for a local variable at the given alignment.
    pub fn allocate_local(&mut self, name: &str, size: u32, align: u32) -> i32 {
        let aligned_size = (size + align - 1) & !(align - 1);
        self.frame_size += aligned_size;
        let offset = -(self.frame_size as i32);
        self.locals.push((name.to_string(), offset, size));
        offset
    }

    /// Reserve space for a callee-saved register.
    pub fn reserve_callee_saved(&mut self, reg: u32, size: u32) -> i32 {
        self.frame_size += size;
        let offset = -(self.frame_size as i32);
        self.callee_saved.push((reg, offset));
        offset
    }
}

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

// ============================================================================
// GlobalISel Combiner Helpers
// ============================================================================

/// Pre-isel generic combine pass that operates on G_* instructions before
/// instruction selection.
pub struct GISelCombiner {
    pub num_combines: usize,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CombineOp {
    /// x = G_ADD x, 0 → no-op (identity).
    AddIdentity,
    /// G_SUB x, x → G_CONSTANT 0.
    SubSame,
    /// G_AND x, x → x (copy).
    AndSame,
    /// G_AND x, -1 → x (copy).
    AndAllOnes,
    /// G_OR x, 0 → x (copy).
    OrZero,
    /// G_MUL x, 1 → x (copy).
    MulOne,
    /// G_MUL x, 0 → G_CONSTANT 0.
    MulZero,
    /// G_SHL x, 0 → x (copy).
    ShlZero,
    /// G_TRUNC after G_ZEXT with same width → copy.
    TruncOfZext,
    /// G_SEXT after G_TRUNC with same width → copy.
    SextOfTrunc,
    /// G_FADD x, -0.0 → x (no-op).
    FaddNegZero,
    /// G_AND (G_ICMP ...), (G_ICMP ...) → G_ICMP (merged conditions).
    MergeIcmpAnd,
    /// G_SELECT (G_ICMP Eq x, 0), a, b → conditional move pattern.
    SelectOfIcmp,
}

impl GISelCombiner {
    pub fn new() -> Self {
        Self { num_combines: 0 }
    }

    /// Try to combine a sequence of generic MIR instructions.
    pub fn try_combine(&mut self, _ops: &[MOpcode]) -> Option<CombineOp> {
        self.num_combines += 1;
        None // Placeholder; real impl would pattern-match
    }
}

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

// ============================================================================
// Machine IR Builder — convenience API for building MIR
// ============================================================================

/// Builds generic MachineIR instructions with a fluent API.
pub struct MIRBuilder {
    pub instructions: Vec<MIRInstruction>,
}

#[derive(Debug, Clone)]
pub struct MIRInstruction {
    pub opcode: MOpcode,
    pub defs: Vec<u32>,
    pub uses: Vec<MIRUse>,
    pub flags: MIRFlags,
}

#[derive(Debug, Clone)]
pub enum MIRUse {
    Reg(u32),
    Imm(i64),
    FImm(f64),
    Block(u32),
    FrameIndex(i32),
}

#[derive(Debug, Clone, Default)]
pub struct MIRFlags {
    pub is_terminator: bool,
    pub may_load: bool,
    pub may_store: bool,
    pub has_side_effects: bool,
}

impl MIRBuilder {
    pub fn new() -> Self {
        MIRBuilder {
            instructions: Vec::new(),
        }
    }

    /// Build a G_ADD instruction: def = use1 + use2.
    pub fn build_add(&mut self, def: u32, lhs: u32, rhs: u32) {
        self.instructions.push(MIRInstruction {
            opcode: MOpcode::G_ADD,
            defs: vec![def],
            uses: vec![MIRUse::Reg(lhs), MIRUse::Reg(rhs)],
            flags: MIRFlags::default(),
        });
    }

    /// Build a G_LOAD instruction: def = load [addr].
    pub fn build_load(&mut self, def: u32, addr: u32, size: u32) {
        self.instructions.push(MIRInstruction {
            opcode: MOpcode::G_LOAD,
            defs: vec![def],
            uses: vec![MIRUse::Reg(addr), MIRUse::Imm(size as i64)],
            flags: MIRFlags {
                may_load: true,
                ..Default::default()
            },
        });
    }

    /// Build a G_STORE instruction: store val to [addr].
    pub fn build_store(&mut self, val: u32, addr: u32, size: u32) {
        self.instructions.push(MIRInstruction {
            opcode: MOpcode::G_STORE,
            defs: Vec::new(),
            uses: vec![
                MIRUse::Reg(val),
                MIRUse::Reg(addr),
                MIRUse::Imm(size as i64),
            ],
            flags: MIRFlags {
                may_store: true,
                ..Default::default()
            },
        });
    }

    /// Build a G_BR instruction.
    pub fn build_br(&mut self, target: u32) {
        self.instructions.push(MIRInstruction {
            opcode: MOpcode::G_BR,
            defs: Vec::new(),
            uses: vec![MIRUse::Block(target)],
            flags: MIRFlags {
                is_terminator: true,
                ..Default::default()
            },
        });
    }

    /// Build a G_BRCOND instruction.
    pub fn build_brcond(&mut self, cond: u32, true_bb: u32, false_bb: u32) {
        self.instructions.push(MIRInstruction {
            opcode: MOpcode::G_BRCOND,
            defs: Vec::new(),
            uses: vec![
                MIRUse::Reg(cond),
                MIRUse::Block(true_bb),
                MIRUse::Block(false_bb),
            ],
            flags: MIRFlags {
                is_terminator: true,
                ..Default::default()
            },
        });
    }

    /// Build a G_RETURN instruction.
    pub fn build_return(&mut self, vals: &[u32]) {
        self.instructions.push(MIRInstruction {
            opcode: MOpcode::G_RETURN,
            defs: Vec::new(),
            uses: vals.iter().map(|&v| MIRUse::Reg(v)).collect(),
            flags: MIRFlags {
                is_terminator: true,
                ..Default::default()
            },
        });
    }
}

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

// ============================================================================
// Extended Tests
// ============================================================================

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

    #[test]
    fn test_calling_conv_return() {
        let cc = CallingConvLowering::new("x86_64-linux-gnu");
        let assigns = cc.classify_return_type(32, false);
        assert_eq!(assigns.len(), 1);
        assert_eq!(assigns[0].width, 32);
    }

    #[test]
    fn test_calling_conv_return_fp() {
        let cc = CallingConvLowering::new("x86_64-linux-gnu");
        let assigns = cc.classify_return_type(64, true);
        assert_eq!(assigns.len(), 1);
    }

    #[test]
    fn test_calling_conv_argument() {
        let cc = CallingConvLowering::new("x86_64-linux-gnu");
        let mut int_reg = 0;
        let mut fp_reg = 0;
        let mut stack_off = 0;
        let assign = cc.classify_argument(0, 32, false, &mut int_reg, &mut fp_reg, &mut stack_off);
        assert_eq!(assign.arg_idx, 0);
    }

    #[test]
    fn test_stack_frame_alloc() {
        let mut sf = StackFrameInfo::new();
        let off = sf.allocate_local("x", 4, 4);
        assert_eq!(off, -4);
        assert_eq!(sf.frame_size, 4);
    }

    #[test]
    fn test_stack_frame_callee_saved() {
        let mut sf = StackFrameInfo::new();
        let off = sf.reserve_callee_saved(3, 8);
        assert_eq!(off, -8);
        assert_eq!(sf.callee_saved.len(), 1);
    }

    #[test]
    fn test_mir_builder_add() {
        let mut builder = MIRBuilder::new();
        builder.build_add(1, 2, 3);
        assert_eq!(builder.instructions.len(), 1);
        assert_eq!(builder.instructions[0].defs, vec![1]);
    }

    #[test]
    fn test_mir_builder_load_store() {
        let mut builder = MIRBuilder::new();
        builder.build_load(1, 2, 4);
        builder.build_store(1, 3, 4);
        assert_eq!(builder.instructions.len(), 2);
        assert!(builder.instructions[0].flags.may_load);
        assert!(builder.instructions[1].flags.may_store);
    }

    #[test]
    fn test_mir_builder_terminators() {
        let mut builder = MIRBuilder::new();
        builder.build_br(5);
        builder.build_brcond(1, 2, 3);
        builder.build_return(&[0]);
        assert_eq!(builder.instructions.len(), 3);
        assert!(builder.instructions[0].flags.is_terminator);
    }

    #[test]
    fn test_gisel_combiner() {
        let mut combiner = GISelCombiner::new();
        assert_eq!(combiner.num_combines, 0);
        let _ = combiner.try_combine(&[MOpcode::G_ADD, MOpcode::G_CONSTANT]);
        assert_eq!(combiner.num_combines, 1);
    }
}