llvm-native-core 0.1.2

LLVM-native core semantic engine — IR, CodeGen, X86 MC, Clang frontend pipeline
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
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
//! Clang ↔ TargetMachine Integration — bridge between Clang compiler
//! flags and LLVM target backends.
//!
//! This module handles all target-specific decisions:
//! - Detecting the target triple from compiler flags (-target, -m32, -m64, -arch)
//! - Configuring the data layout and ABI from the target description
//! - Per-target codegen hooks (struct passing convention, return-value
//!   lowering, varargs, setjmp/longjmp, address-space mapping)
//! - Translating Clang-level flags (-march, -mcpu, -mattr) into LLVM
//!   target feature strings
//! - Selecting ABI, code model, relocation model, debug-info kind,
//!   optimisation level, and stack-protector strength
//! - Mapping Clang function-attribute flags onto LLVM IR function
//!   attributes
//!
//! Clean-room behavioural reconstruction from published Clang and LLVM
//! documentation.  No LLVM/Clang source code is consulted.

use std::collections::HashMap;
use std::collections::HashSet;

use crate::data_layout::DataLayout;
use crate::target_info::TargetFeature;
use crate::target_machine::{
    CodeGenOptLevel, CodeModel, FloatABI, RelocModel, TargetMachine, TargetOptions,
};
use crate::triple::{Arch, Triple};

// ═══════════════════════════════════════════════════════════════════════════
// Debug Info Kind
// ═══════════════════════════════════════════════════════════════════════════

/// Amount of debug information to emit.  Mirrors the `-g` / `-g0`…`-g3`
/// flags that Clang passes to cc1.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DebugInfoKind {
    /// No debug info at all  (`-g0`, or no `-g` flag).
    NoDebug,
    /// Emit line-tables only — enough for backtraces but no types or
    /// variables  (`-g1` / `-gline-tables-only`).
    LineTablesOnly,
    /// Limited debug info — omit debug info for types and some scoping
    /// to keep binary size reasonable  (`-g2` / `-glimited`).
    LimitedDebug,
    /// Full debug info — includes all types, variables, and scoping
    /// (`-g`, `-g3`).
    FullDebug,
    /// Full debug info plus macro definitions  (`-g3`, `-gfull`).
    FullWithMacros,
}

impl DebugInfoKind {
    /// Convert the `-g` flag value to a `DebugInfoKind`.
    pub fn from_flag(g_level: u8) -> Self {
        match g_level {
            0 => Self::NoDebug,
            1 => Self::LineTablesOnly,
            2 => Self::LimitedDebug,
            3 => Self::FullWithMacros,
            _ => Self::FullDebug,
        }
    }

    /// Whether any debug info is emitted.
    pub fn has_debug(&self) -> bool {
        !matches!(self, Self::NoDebug)
    }

    /// Whether full type information is emitted.
    pub fn has_types(&self) -> bool {
        matches!(self, Self::FullDebug | Self::FullWithMacros)
    }

    /// String representation for passing to LLVM.
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::NoDebug => "none",
            Self::LineTablesOnly => "line-tables-only",
            Self::LimitedDebug => "limited",
            Self::FullDebug => "full",
            Self::FullWithMacros => "full-with-macros",
        }
    }
}

impl Default for DebugInfoKind {
    fn default() -> Self {
        Self::NoDebug
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Stack Protector Level
// ═══════════════════════════════════════════════════════════════════════════

/// Stack-protector strength requested by compiler flags.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum StackProtectorLevel {
    /// No stack protection.
    None,
    /// `-fstack-protector` — protect functions with stack arrays larger
    /// than ~8 bytes (heuristic).
    Basic,
    /// `-fstack-protector-strong` — protect any function that has a local
    /// array, a local that has its address taken, or a call to `alloca`.
    Strong,
    /// `-fstack-protector-all` — protect *every* function.
    All,
}

impl StackProtectorLevel {
    pub fn from_flag(flag: &str) -> Self {
        match flag {
            "none" | "off" => Self::None,
            "all" => Self::All,
            "strong" => Self::Strong,
            _ => Self::Basic,
        }
    }

    pub fn is_enabled(&self) -> bool {
        *self > Self::None
    }

    pub fn as_llvm_str(&self) -> &'static str {
        match self {
            Self::None => "none",
            Self::Basic => "basic",
            Self::Strong => "strong",
            Self::All => "all",
        }
    }
}

impl Default for StackProtectorLevel {
    fn default() -> Self {
        Self::None
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Optimisation Level  (Clang → LLVM)
// ═══════════════════════════════════════════════════════════════════════════

/// Clang optimisation level, matched to LLVM `CodeGenOptLevel`.
///
/// | Clang  | LLVM        |
/// |--------|-------------|
/// | `-O0`  | None        |
/// | `-O1`  | Less        |
/// | `-O2`  | Default     |
/// | `-O3`  | Aggressive  |
/// | `-Os`  | Default + size  |
/// | `-Oz`  | Aggressive + size |
/// | `-Ofast` | Aggressive + fast-math |
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ClangOptLevel {
    None,
    Less,
    Default,
    Aggressive,
    DefaultSize,
    AggressiveSize,
    FastMath,
}

impl ClangOptLevel {
    /// Parse from the `-O` flag argument.
    pub fn from_flag(s: &str) -> Self {
        match s {
            "0" => Self::None,
            "1" => Self::Less,
            "2" | "" => Self::Default,
            "3" => Self::Aggressive,
            "s" => Self::DefaultSize,
            "z" => Self::AggressiveSize,
            "fast" => Self::FastMath,
            _ => Self::Default,
        }
    }

    /// Convert to LLVM `CodeGenOptLevel`.
    pub fn to_llvm_opt(&self) -> CodeGenOptLevel {
        match self {
            Self::None => CodeGenOptLevel::None,
            Self::Less => CodeGenOptLevel::Less,
            Self::Default | Self::DefaultSize => CodeGenOptLevel::Default,
            Self::Aggressive | Self::AggressiveSize | Self::FastMath => CodeGenOptLevel::Aggressive,
        }
    }

    /// Whether this optimisation level focuses on size.
    pub fn is_size_oriented(&self) -> bool {
        matches!(self, Self::DefaultSize | Self::AggressiveSize)
    }

    /// Whether fast-math flags should be implied.
    pub fn implies_fast_math(&self) -> bool {
        matches!(self, Self::FastMath)
    }

    /// String representation.
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::None => "O0",
            Self::Less => "O1",
            Self::Default => "O2",
            Self::Aggressive => "O3",
            Self::DefaultSize => "Os",
            Self::AggressiveSize => "Oz",
            Self::FastMath => "Ofast",
        }
    }
}

impl Default for ClangOptLevel {
    fn default() -> Self {
        Self::None
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// ABI Descriptor
// ═══════════════════════════════════════════════════════════════════════════

/// Clang-level ABI specification derived from `-mabi=`, `-mfloat-abi=`,
/// and the target triple.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClangABI {
    /// Fundamental integer/pointer ABI  (e.g. `"ilp32"`, `"lp64"`, `"lp64d"`).
    pub base_abi: String,
    /// Floating-point ABI  (`"soft"`, `"hard"`, `"softfp"`).
    pub float_abi: String,
    /// Target triple.
    pub triple: String,
}

impl ClangABI {
    pub fn new(triple: &str) -> Self {
        let t = Triple::parse(triple);
        let (base_abi, float_abi) = Self::default_abi_for_arch(t.arch);
        Self {
            base_abi,
            float_abi,
            triple: triple.to_string(),
        }
    }

    /// Detect the default ABI from the target triple.
    fn default_abi_for_arch(arch: Arch) -> (String, String) {
        match arch {
            Arch::X86_64 => (String::from("lp64"), String::from("hard")),
            Arch::X86 => (String::from("ilp32"), String::from("hard")),
            Arch::AArch64 => (String::from("lp64"), String::from("hard")),
            Arch::ARM => (String::from("ilp32"), String::from("soft")),
            Arch::Thumb => (String::from("ilp32"), String::from("soft")),
            Arch::AArch64_32 => (String::from("ilp32"), String::from("hard")),
            Arch::RISCV64 => (String::from("lp64d"), String::from("hard")),
            Arch::RISCV32 => (String::from("ilp32"), String::from("hard")),
            Arch::Mips | Arch::Mipsel => (String::from("o32"), String::from("hard")),
            Arch::Mips64 | Arch::Mips64el => (String::from("n64"), String::from("hard")),
            Arch::PowerPC => (String::from("ilp32"), String::from("hard")),
            Arch::PowerPC64 | Arch::PowerPC64le => (String::from("lp64"), String::from("hard")),
            Arch::Sparc => (String::from("ilp32"), String::from("hard")),
            Arch::Sparcv9 => (String::from("lp64"), String::from("hard")),
            Arch::SystemZ => (String::from("lp64"), String::from("hard")),
            Arch::WebAssembly32 => (String::from("ilp32"), String::from("soft")),
            Arch::WebAssembly64 => (String::from("lp64"), String::from("soft")),
            Arch::AVR => (String::from("ilp16"), String::from("soft")),
            Arch::MSP430 => (String::from("ilp16"), String::from("soft")),
            Arch::BPF | Arch::BPFEB | Arch::BPF64 => (String::from("lp64"), String::from("soft")),
            Arch::Hexagon => (String::from("ilp32"), String::from("soft")),
            Arch::Lanai => (String::from("ilp32"), String::from("soft")),
            Arch::NVPTX | Arch::NVPTX64 => (String::from("lp64"), String::from("hard")),
            Arch::AMDGPU => (String::from("lp64"), String::from("hard")),
            Arch::ARC => (String::from("ilp32"), String::from("soft")),
            Arch::CSKY => (String::from("ilp32"), String::from("soft")),
            Arch::Xtensa => (String::from("ilp32"), String::from("soft")),
            _ => (String::from("ilp32"), String::from("soft")),
        }
    }

    /// Override the base ABI from a `-mabi=` flag.
    pub fn with_base_abi(mut self, abi: &str) -> Self {
        self.base_abi = abi.to_string();
        self
    }

    /// Override the float ABI from a `-mfloat-abi=` flag.
    pub fn with_float_abi(mut self, fa: &str) -> Self {
        self.float_abi = fa.to_string();
        self
    }

    /// Whether this is a soft-float ABI.
    pub fn is_soft_float(&self) -> bool {
        self.float_abi == "soft"
    }

    /// Whether this is a 64-bit ABI (lp64, lp64d, n64).
    pub fn is_64bit(&self) -> bool {
        matches!(
            self.base_abi.as_str(),
            "lp64" | "lp64d" | "lp64f" | "n64" | "aarch64" | "ilp64"
        )
    }

    /// Convert float ABI to LLVM `FloatABI`.
    pub fn to_llvm_float_abi(&self) -> FloatABI {
        match self.float_abi.as_str() {
            "soft" => FloatABI::Soft,
            "hard" | "softfp" => FloatABI::Hard,
            _ => FloatABI::Default,
        }
    }
}

impl Default for ClangABI {
    fn default() -> Self {
        Self::new("x86_64-unknown-linux-gnu")
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Target CodeGen Info — per-target ABI hooks
// ═══════════════════════════════════════════════════════════════════════════

/// Architecture-specific code generation conventions.
///
/// Different targets have different conventions for how structs are
/// returned, how varargs are handled, whether `setjmp`/`longjmp` need
/// special lowering, address-space layout, etc.
#[derive(Debug, Clone)]
pub struct TargetCodeGenInfo {
    /// Target architecture.
    pub arch: Arch,
    /// Whether structs are returned via hidden sret-pointer (X86-64 style).
    pub uses_sret_demotion: bool,
    /// Whether an aggregate returned indirectly uses a struct-return
    /// pointer in the first integer register (x86-64 SysV: `rdi`, ARM:
    /// `r0`).
    pub indirect_struct_return: bool,
    /// Maximum integer size (in bits) that can be returned in registers.
    pub max_reg_return_size: u32,
    /// Whether to split small structs across registers (e.g. `{i32,i32}`
    /// into `eax`:`edx`).
    pub split_struct_return: bool,
    /// Whether varargs need the caller to set up a register-save area
    /// (true on most RISC ABIs, true for x86-64 SysV with `va_list`).
    pub varargs_save_area: bool,
    /// Whether `setjmp` needs `returns_twice` attribute.
    pub setjmp_returns_twice: bool,
    /// Whether `longjmp` is marked `noreturn`.
    pub longjmp_noreturn: bool,
    /// Address space for globals (typically 0; NVPTX uses 1 for some).
    pub global_address_space: u32,
    /// Address space for constant globals.
    pub constant_address_space: u32,
    /// Address space for thread-local storage.
    pub tls_address_space: u32,
    /// Whether the stack grows down (virtually always true).
    pub stack_grows_down: bool,
    /// Natural stack alignment in bytes.
    pub stack_alignment: u32,
    /// Whether a NULL function pointer dereference is guaranteed to trap.
    pub null_pointer_is_valid: bool,
    /// Whether this target uses the regparm calling convention on x86.
    pub use_regparm: bool,
    /// Default number of register parameters on x86 (0 = caller stack).
    pub regparm_count: u32,
}

impl TargetCodeGenInfo {
    /// Create default codegen info for an architecture.
    pub fn for_arch(arch: Arch) -> Self {
        match arch {
            Arch::X86_64 => Self {
                arch,
                uses_sret_demotion: true,
                indirect_struct_return: true,
                max_reg_return_size: 128,
                split_struct_return: true,
                varargs_save_area: true,
                setjmp_returns_twice: true,
                longjmp_noreturn: true,
                global_address_space: 0,
                constant_address_space: 0,
                tls_address_space: 0,
                stack_grows_down: true,
                stack_alignment: 16,
                null_pointer_is_valid: false,
                use_regparm: false,
                regparm_count: 0,
            },
            Arch::X86 => Self {
                arch,
                uses_sret_demotion: false,
                indirect_struct_return: false,
                max_reg_return_size: 64,
                split_struct_return: false,
                varargs_save_area: false,
                setjmp_returns_twice: true,
                longjmp_noreturn: true,
                global_address_space: 0,
                constant_address_space: 0,
                tls_address_space: 0,
                stack_grows_down: true,
                stack_alignment: 16,
                null_pointer_is_valid: false,
                use_regparm: true,
                regparm_count: 3,
            },
            Arch::AArch64 => Self {
                arch,
                uses_sret_demotion: true,
                indirect_struct_return: true,
                max_reg_return_size: 128,
                split_struct_return: true,
                varargs_save_area: true,
                setjmp_returns_twice: true,
                longjmp_noreturn: true,
                global_address_space: 0,
                constant_address_space: 0,
                tls_address_space: 0,
                stack_grows_down: true,
                stack_alignment: 16,
                null_pointer_is_valid: false,
                use_regparm: false,
                regparm_count: 0,
            },
            Arch::ARM | Arch::ARMeb => Self {
                arch,
                uses_sret_demotion: false,
                indirect_struct_return: true,
                max_reg_return_size: 64,
                split_struct_return: true,
                varargs_save_area: true,
                setjmp_returns_twice: true,
                longjmp_noreturn: true,
                global_address_space: 0,
                constant_address_space: 0,
                tls_address_space: 0,
                stack_grows_down: true,
                stack_alignment: 8,
                null_pointer_is_valid: false,
                use_regparm: false,
                regparm_count: 0,
            },
            Arch::Thumb | Arch::Thumbeb => Self {
                arch,
                uses_sret_demotion: false,
                indirect_struct_return: true,
                max_reg_return_size: 64,
                split_struct_return: false,
                varargs_save_area: true,
                setjmp_returns_twice: true,
                longjmp_noreturn: true,
                global_address_space: 0,
                constant_address_space: 0,
                tls_address_space: 0,
                stack_grows_down: true,
                stack_alignment: 8,
                null_pointer_is_valid: false,
                use_regparm: false,
                regparm_count: 0,
            },
            Arch::RISCV64 => Self {
                arch,
                uses_sret_demotion: true,
                indirect_struct_return: true,
                max_reg_return_size: 128,
                split_struct_return: true,
                varargs_save_area: true,
                setjmp_returns_twice: true,
                longjmp_noreturn: true,
                global_address_space: 0,
                constant_address_space: 0,
                tls_address_space: 0,
                stack_grows_down: true,
                stack_alignment: 16,
                null_pointer_is_valid: false,
                use_regparm: false,
                regparm_count: 0,
            },
            Arch::RISCV32 => Self {
                arch,
                uses_sret_demotion: false,
                indirect_struct_return: true,
                max_reg_return_size: 64,
                split_struct_return: true,
                varargs_save_area: true,
                setjmp_returns_twice: true,
                longjmp_noreturn: true,
                global_address_space: 0,
                constant_address_space: 0,
                tls_address_space: 0,
                stack_grows_down: true,
                stack_alignment: 16,
                null_pointer_is_valid: false,
                use_regparm: false,
                regparm_count: 0,
            },
            Arch::Mips | Arch::Mipsel | Arch::Mips64 | Arch::Mips64el => Self {
                arch,
                uses_sret_demotion: false,
                indirect_struct_return: true,
                max_reg_return_size: 64,
                split_struct_return: false,
                varargs_save_area: true,
                setjmp_returns_twice: true,
                longjmp_noreturn: true,
                global_address_space: 0,
                constant_address_space: 0,
                tls_address_space: 0,
                stack_grows_down: true,
                stack_alignment: 8,
                null_pointer_is_valid: false,
                use_regparm: false,
                regparm_count: 0,
            },
            Arch::PowerPC | Arch::PowerPC64 | Arch::PowerPC64le => Self {
                arch,
                uses_sret_demotion: true,
                indirect_struct_return: true,
                max_reg_return_size: 64,
                split_struct_return: true,
                varargs_save_area: true,
                setjmp_returns_twice: true,
                longjmp_noreturn: true,
                global_address_space: 0,
                constant_address_space: 0,
                tls_address_space: 0,
                stack_grows_down: true,
                stack_alignment: 16,
                null_pointer_is_valid: false,
                use_regparm: false,
                regparm_count: 0,
            },
            Arch::SystemZ => Self {
                arch,
                uses_sret_demotion: true,
                indirect_struct_return: true,
                max_reg_return_size: 128,
                split_struct_return: false,
                varargs_save_area: true,
                setjmp_returns_twice: true,
                longjmp_noreturn: true,
                global_address_space: 0,
                constant_address_space: 0,
                tls_address_space: 0,
                stack_grows_down: true,
                stack_alignment: 8,
                null_pointer_is_valid: false,
                use_regparm: false,
                regparm_count: 0,
            },
            Arch::WebAssembly32 | Arch::WebAssembly64 => Self {
                arch,
                uses_sret_demotion: false,
                indirect_struct_return: false,
                max_reg_return_size: 64,
                split_struct_return: false,
                varargs_save_area: false,
                setjmp_returns_twice: true,
                longjmp_noreturn: true,
                global_address_space: 0,
                constant_address_space: 0,
                tls_address_space: 0,
                stack_grows_down: true,
                stack_alignment: 16,
                null_pointer_is_valid: false,
                use_regparm: false,
                regparm_count: 0,
            },
            _ => Self {
                arch,
                uses_sret_demotion: false,
                indirect_struct_return: true,
                max_reg_return_size: 64,
                split_struct_return: false,
                varargs_save_area: true,
                setjmp_returns_twice: true,
                longjmp_noreturn: true,
                global_address_space: 0,
                constant_address_space: 0,
                tls_address_space: 0,
                stack_grows_down: true,
                stack_alignment: 16,
                null_pointer_is_valid: false,
                use_regparm: false,
                regparm_count: 0,
            },
        }
    }

    /// Whether the structure return convention uses hidden pointer parameter.
    pub fn should_pass_indirectly(&self, size: u32) -> bool {
        if !self.indirect_struct_return {
            return false;
        }
        size > self.max_reg_return_size / 8
    }

    /// Whether an aggregate is returned via hidden sret pointer in the
    /// first suitable register (often the one used for the first arg).
    pub fn uses_sret(&self) -> bool {
        self.uses_sret_demotion
    }
}

impl Default for TargetCodeGenInfo {
    fn default() -> Self {
        Self::for_arch(Arch::X86_64)
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Host CPU Detection
// ═══════════════════════════════════════════════════════════════════════════

/// Host CPU name detection — `-march=native` support.
#[derive(Debug, Clone)]
pub struct HostCpuDetector {
    /// Cached host CPU name.
    cached_name: Option<String>,
    /// Cached host CPU features.
    cached_features: Option<HashSet<String>>,
}

impl HostCpuDetector {
    pub fn new() -> Self {
        Self {
            cached_name: None,
            cached_features: None,
        }
    }

    /// Get the host CPU name (platform-dependent).
    pub fn host_cpu_name(&mut self) -> &str {
        if self.cached_name.is_none() {
            self.cached_name = Some(Self::detect_host_cpu());
        }
        self.cached_name.as_deref().unwrap()
    }

    /// Get the set of host CPU features.
    pub fn host_cpu_features(&mut self) -> &HashSet<String> {
        if self.cached_features.is_none() {
            self.cached_features = Some(Self::detect_host_features());
        }
        self.cached_features.as_ref().unwrap()
    }

    /// Platform-specific host CPU detection.
    #[cfg(target_arch = "x86_64")]
    fn detect_host_cpu() -> String {
        // On x86-64, CPUs can be differentiated via CPUID.
        // We map the highest supported ISA level to a name.
        if Self::has_x86_feature("avx512f") {
            String::from("skylake-avx512")
        } else if Self::has_x86_feature("avx2") {
            String::from("haswell")
        } else if Self::has_x86_feature("avx") {
            String::from("sandybridge")
        } else if Self::has_x86_feature("sse4_2") {
            String::from("nehalem")
        } else if Self::has_x86_feature("sse4_1") {
            String::from("penryn")
        } else if Self::has_x86_feature("ssse3") {
            String::from("core2")
        } else if Self::has_x86_feature("sse3") {
            String::from("prescott")
        } else {
            String::from("pentium4")
        }
    }

    #[cfg(target_arch = "aarch64")]
    fn detect_host_cpu() -> String {
        if Self::has_aarch64_feature("sve2") {
            String::from("neoverse-v2")
        } else if Self::has_aarch64_feature("sve") {
            String::from("neoverse-n2")
        } else if Self::has_aarch64_feature("neon") {
            String::from("cortex-a76")
        } else {
            String::from("cortex-a53")
        }
    }

    #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
    fn detect_host_cpu() -> String {
        String::from("generic")
    }

    #[cfg(target_arch = "x86_64")]
    fn detect_host_features() -> HashSet<String> {
        let mut feats = HashSet::new();
        let all = [
            ("mmx", "mmx"),
            ("sse", "sse"),
            ("sse2", "sse2"),
            ("sse3", "sse3"),
            ("ssse3", "ssse3"),
            ("sse4.1", "sse4.1"),
            ("sse4.2", "sse4.2"),
            ("popcnt", "popcnt"),
            ("avx", "avx"),
            ("avx2", "avx2"),
            ("fma", "fma"),
            ("bmi", "bmi"),
            ("bmi2", "bmi2"),
            ("lzcnt", "lzcnt"),
            ("avx512f", "avx512f"),
            ("avx512bw", "avx512bw"),
            ("avx512dq", "avx512dq"),
            ("avx512vl", "avx512vl"),
        ];
        for (feat, _name) in &all {
            if Self::has_x86_feature(feat) {
                feats.insert(feat.to_string());
            }
        }
        feats
    }

    #[cfg(target_arch = "aarch64")]
    fn detect_host_features() -> HashSet<String> {
        let mut feats = HashSet::new();
        let all = [
            ("fp", "fp"),
            ("asimd", "neon"),
            ("crc", "crc"),
            ("crypto", "crypto"),
            ("fp16", "fp16"),
            ("lse", "lse"),
            ("rdm", "rdm"),
            ("rcpc", "rcpc"),
            ("dotprod", "dotprod"),
            ("sve", "sve"),
            ("sve2", "sve2"),
            ("i8mm", "i8mm"),
        ];
        for (feat, _name) in &all {
            if Self::has_aarch64_feature(feat) {
                feats.insert(feat.to_string());
            }
        }
        feats
    }

    #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
    fn detect_host_features() -> HashSet<String> {
        HashSet::new()
    }

    #[cfg(target_arch = "x86_64")]
    fn has_x86_feature(_feat: &str) -> bool {
        // Stub: in a full implementation this would use CPUID.
        // For now we assume a reasonable baseline.
        matches!(
            _feat,
            "mmx"
                | "sse"
                | "sse2"
                | "sse3"
                | "ssse3"
                | "sse4.1"
                | "sse4.2"
                | "popcnt"
                | "avx"
                | "avx2"
        )
    }

    #[cfg(target_arch = "aarch64")]
    fn has_aarch64_feature(_feat: &str) -> bool {
        matches!(_feat, "fp" | "asimd" | "crc" | "crypto" | "lse")
    }
}

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

// ═══════════════════════════════════════════════════════════════════════════
// CPU Feature Database — maps CPU names to feature sets
// ═══════════════════════════════════════════════════════════════════════════

/// Database of known CPU cores and their features.
#[derive(Debug, Clone)]
pub struct CpuFeatureDatabase {
    /// CPU name → feature set
    cpus: HashMap<String, HashSet<String>>,
    /// Feature name → aliases and implied features
    features: HashMap<String, TargetFeature>,
    host_detector: HostCpuDetector,
}

impl CpuFeatureDatabase {
    pub fn new() -> Self {
        let mut db = Self {
            cpus: HashMap::new(),
            features: HashMap::new(),
            host_detector: HostCpuDetector::new(),
        };
        db.register_x86_cpus();
        db.register_aarch64_cpus();
        db.register_arm_cpus();
        db.register_riscv_cpus();
        db.register_x86_features();
        db.register_aarch64_features();
        db.register_arm_features();
        db.register_riscv_features();
        db
    }

    /// Look up the feature set for a named CPU.
    pub fn cpu_features(&self, cpu_name: &str) -> Option<&HashSet<String>> {
        if cpu_name == "native" {
            // For `-mcpu=native`, we need the host detector.
            // We can't easily return a &HashSet from host_detector,
            // so we return None to signal "use host detection".
            None
        } else {
            self.cpus.get(cpu_name)
        }
    }

    /// Resolve a CPU name to features.  Returns the set of features.
    pub fn resolve_cpu(&mut self, cpu_name: &str) -> HashSet<String> {
        if cpu_name == "native" {
            return self.host_detector.host_cpu_features().clone();
        }
        if cpu_name == "generic" {
            return HashSet::new();
        }
        self.cpus.get(cpu_name).cloned().unwrap_or_default()
    }

    /// Build the combined feature string from a CPU and extra features.
    pub fn feature_string(&mut self, cpu: &str, extra_features: &[(String, bool)]) -> String {
        let mut feats: HashSet<String> = if cpu.is_empty() || cpu == "generic" {
            HashSet::new()
        } else {
            self.resolve_cpu(cpu)
        };

        for (name, enable) in extra_features {
            if *enable {
                feats.insert(name.clone());
                // Also add implied features
                if let Some(tf) = self.features.get(name.as_str()) {
                    for imp in &tf.implies {
                        feats.insert(imp.clone());
                    }
                }
            } else {
                feats.remove(name.as_str());
            }
        }

        let mut sorted: Vec<&String> = feats.iter().collect();
        sorted.sort();
        sorted
            .into_iter()
            .map(|s| format!("+{}", s))
            .collect::<Vec<_>>()
            .join(",")
    }

    /// Check if a feature exists.
    pub fn has_feature(&self, name: &str) -> bool {
        self.features.contains_key(name)
    }

    // ── X86 CPUs ────────────────────────────────────────────────────────

    fn register_x86_cpus(&mut self) {
        let x86_cpus: &[(&str, &[&str])] = &[
            ("pentium", &["mmx"]),
            ("pentium4", &["mmx", "sse", "sse2"]),
            ("prescott", &["mmx", "sse", "sse2", "sse3"]),
            ("nocona", &["mmx", "sse", "sse2", "sse3", "cx16"]),
            ("core2", &["mmx", "sse", "sse2", "sse3", "ssse3", "cx16"]),
            (
                "penryn",
                &["mmx", "sse", "sse2", "sse3", "ssse3", "sse4.1", "cx16"],
            ),
            (
                "nehalem",
                &[
                    "mmx", "sse", "sse2", "sse3", "ssse3", "sse4.1", "sse4.2", "popcnt", "cx16",
                ],
            ),
            (
                "sandybridge",
                &[
                    "mmx", "sse", "sse2", "sse3", "ssse3", "sse4.1", "sse4.2", "popcnt", "avx",
                    "cx16",
                ],
            ),
            (
                "ivybridge",
                &[
                    "mmx", "sse", "sse2", "sse3", "ssse3", "sse4.1", "sse4.2", "popcnt", "avx",
                    "cx16", "f16c",
                ],
            ),
            (
                "haswell",
                &[
                    "mmx", "sse", "sse2", "sse3", "ssse3", "sse4.1", "sse4.2", "popcnt", "avx",
                    "avx2", "fma", "bmi", "bmi2", "lzcnt", "cx16", "f16c", "movbe",
                ],
            ),
            (
                "broadwell",
                &[
                    "mmx", "sse", "sse2", "sse3", "ssse3", "sse4.1", "sse4.2", "popcnt", "avx",
                    "avx2", "fma", "bmi", "bmi2", "lzcnt", "cx16", "f16c", "movbe", "adx",
                    "rdseed",
                ],
            ),
            (
                "skylake",
                &[
                    "mmx",
                    "sse",
                    "sse2",
                    "sse3",
                    "ssse3",
                    "sse4.1",
                    "sse4.2",
                    "popcnt",
                    "avx",
                    "avx2",
                    "fma",
                    "bmi",
                    "bmi2",
                    "lzcnt",
                    "cx16",
                    "f16c",
                    "movbe",
                    "adx",
                    "rdseed",
                    "xsavec",
                    "xsaves",
                    "clflushopt",
                ],
            ),
            (
                "skylake-avx512",
                &[
                    "mmx",
                    "sse",
                    "sse2",
                    "sse3",
                    "ssse3",
                    "sse4.1",
                    "sse4.2",
                    "popcnt",
                    "avx",
                    "avx2",
                    "fma",
                    "bmi",
                    "bmi2",
                    "lzcnt",
                    "cx16",
                    "f16c",
                    "movbe",
                    "adx",
                    "rdseed",
                    "xsavec",
                    "xsaves",
                    "clflushopt",
                    "avx512f",
                    "avx512bw",
                    "avx512dq",
                    "avx512vl",
                ],
            ),
            (
                "cannonlake",
                &[
                    "mmx",
                    "sse",
                    "sse2",
                    "sse3",
                    "ssse3",
                    "sse4.1",
                    "sse4.2",
                    "popcnt",
                    "avx",
                    "avx2",
                    "fma",
                    "bmi",
                    "bmi2",
                    "lzcnt",
                    "cx16",
                    "f16c",
                    "movbe",
                    "adx",
                    "rdseed",
                    "xsavec",
                    "xsaves",
                    "clflushopt",
                    "avx512f",
                    "avx512bw",
                    "avx512dq",
                    "avx512vl",
                    "avx512vbmi",
                    "sha",
                ],
            ),
            (
                "icelake-client",
                &[
                    "mmx",
                    "sse",
                    "sse2",
                    "sse3",
                    "ssse3",
                    "sse4.1",
                    "sse4.2",
                    "popcnt",
                    "avx",
                    "avx2",
                    "fma",
                    "bmi",
                    "bmi2",
                    "lzcnt",
                    "cx16",
                    "f16c",
                    "movbe",
                    "adx",
                    "rdseed",
                    "xsavec",
                    "xsaves",
                    "clflushopt",
                    "avx512f",
                    "avx512bw",
                    "avx512dq",
                    "avx512vl",
                    "avx512vbmi",
                    "sha",
                    "avx512vbmi2",
                    "avx512bitalg",
                    "vaes",
                    "vpclmulqdq",
                    "gfni",
                ],
            ),
            (
                "znver1",
                &[
                    "mmx",
                    "sse",
                    "sse2",
                    "sse3",
                    "ssse3",
                    "sse4.1",
                    "sse4.2",
                    "popcnt",
                    "avx",
                    "avx2",
                    "fma",
                    "bmi",
                    "bmi2",
                    "lzcnt",
                    "cx16",
                    "f16c",
                    "movbe",
                    "adx",
                    "rdseed",
                    "xsavec",
                    "xsaves",
                    "clzero",
                    "clflushopt",
                    "mwaitx",
                    "sha",
                ],
            ),
            (
                "znver2",
                &[
                    "mmx",
                    "sse",
                    "sse2",
                    "sse3",
                    "ssse3",
                    "sse4.1",
                    "sse4.2",
                    "popcnt",
                    "avx",
                    "avx2",
                    "fma",
                    "bmi",
                    "bmi2",
                    "lzcnt",
                    "cx16",
                    "f16c",
                    "movbe",
                    "adx",
                    "rdseed",
                    "xsavec",
                    "xsaves",
                    "clzero",
                    "clflushopt",
                    "mwaitx",
                    "sha",
                    "wbnoinvd",
                ],
            ),
            (
                "znver3",
                &[
                    "mmx",
                    "sse",
                    "sse2",
                    "sse3",
                    "ssse3",
                    "sse4.1",
                    "sse4.2",
                    "popcnt",
                    "avx",
                    "avx2",
                    "fma",
                    "bmi",
                    "bmi2",
                    "lzcnt",
                    "cx16",
                    "f16c",
                    "movbe",
                    "adx",
                    "rdseed",
                    "xsavec",
                    "xsaves",
                    "clzero",
                    "clflushopt",
                    "mwaitx",
                    "sha",
                    "wbnoinvd",
                    "vaes",
                    "vpclmulqdq",
                    "avx512f",
                ],
            ),
        ];
        for (name, feats) in x86_cpus {
            self.cpus.insert(
                name.to_string(),
                feats.iter().map(|s| s.to_string()).collect(),
            );
        }
    }

    // ── AArch64 CPUs ────────────────────────────────────────────────────

    fn register_aarch64_cpus(&mut self) {
        let aarch64_cpus: &[(&str, &[&str])] = &[
            ("cortex-a53", &["fp", "neon", "crc", "crypto"]),
            (
                "cortex-a55",
                &["fp", "neon", "crc", "crypto", "dotprod", "rcpc"],
            ),
            ("cortex-a57", &["fp", "neon", "crc", "crypto"]),
            ("cortex-a72", &["fp", "neon", "crc", "crypto"]),
            ("cortex-a73", &["fp", "neon", "crc", "crypto"]),
            (
                "cortex-a75",
                &["fp", "neon", "crc", "crypto", "dotprod", "rcpc"],
            ),
            (
                "cortex-a76",
                &["fp", "neon", "crc", "crypto", "dotprod", "rcpc", "fp16"],
            ),
            (
                "cortex-a77",
                &["fp", "neon", "crc", "crypto", "dotprod", "rcpc", "fp16"],
            ),
            (
                "cortex-a78",
                &[
                    "fp", "neon", "crc", "crypto", "dotprod", "rcpc", "fp16", "i8mm",
                ],
            ),
            (
                "cortex-x1",
                &[
                    "fp", "neon", "crc", "crypto", "dotprod", "rcpc", "fp16", "i8mm",
                ],
            ),
            (
                "neoverse-n1",
                &["fp", "neon", "crc", "crypto", "dotprod", "rcpc", "fp16"],
            ),
            (
                "neoverse-n2",
                &[
                    "fp", "neon", "crc", "crypto", "dotprod", "rcpc", "fp16", "sve", "i8mm",
                ],
            ),
            (
                "neoverse-v1",
                &[
                    "fp", "neon", "crc", "crypto", "dotprod", "rcpc", "fp16", "sve", "i8mm",
                ],
            ),
            (
                "neoverse-v2",
                &[
                    "fp", "neon", "crc", "crypto", "dotprod", "rcpc", "fp16", "sve", "sve2", "i8mm",
                ],
            ),
            ("apple-a7", &["fp", "neon"]),
            ("apple-a8", &["fp", "neon"]),
            ("apple-a9", &["fp", "neon"]),
            ("apple-a10", &["fp", "neon", "crc"]),
            ("apple-a11", &["fp", "neon", "crc", "crypto"]),
            ("apple-a12", &["fp", "neon", "crc", "crypto", "fp16"]),
            (
                "apple-a13",
                &["fp", "neon", "crc", "crypto", "fp16", "dotprod"],
            ),
            (
                "apple-a14",
                &["fp", "neon", "crc", "crypto", "fp16", "dotprod"],
            ),
            (
                "apple-m1",
                &["fp", "neon", "crc", "crypto", "fp16", "dotprod", "lse"],
            ),
        ];
        for (name, feats) in aarch64_cpus {
            self.cpus.insert(
                name.to_string(),
                feats.iter().map(|s| s.to_string()).collect(),
            );
        }
    }

    // ── ARM (32-bit) CPUs ───────────────────────────────────────────────

    fn register_arm_cpus(&mut self) {
        let arm_cpus: &[(&str, &[&str])] = &[
            ("arm7tdmi", &[]),
            ("arm9", &[]),
            ("arm926ej-s", &[]),
            ("arm1136jf-s", &["vfp"]),
            ("cortex-a5", &["neon", "vfp4"]),
            ("cortex-a7", &["neon", "vfp4"]),
            ("cortex-a8", &["neon", "vfp3"]),
            ("cortex-a9", &["neon", "vfp3"]),
            ("cortex-a12", &["neon", "vfp4"]),
            ("cortex-a15", &["neon", "vfp4"]),
            ("cortex-a17", &["neon", "vfp4"]),
            ("cortex-m0", &[]),
            ("cortex-m3", &[]),
            ("cortex-m4", &["vfp4"]),
            ("cortex-m7", &["vfp5"]),
            ("cortex-r4", &[]),
            ("cortex-r5", &["vfp3"]),
            ("cortex-r7", &["vfp3"]),
        ];
        for (name, feats) in arm_cpus {
            self.cpus.insert(
                name.to_string(),
                feats.iter().map(|s| s.to_string()).collect(),
            );
        }
    }

    // ── RISC-V CPUs ─────────────────────────────────────────────────────

    fn register_riscv_cpus(&mut self) {
        let riscv_cpus: &[(&str, &[&str])] = &[
            ("sifive-e20", &["m"]),
            ("sifive-e21", &["m"]),
            ("sifive-e24", &["m"]),
            ("sifive-e31", &["m"]),
            ("sifive-e34", &["m"]),
            ("sifive-e76", &["m", "a", "c"]),
            ("sifive-s21", &["m", "a"]),
            ("sifive-s51", &["m", "a"]),
            ("sifive-s54", &["m", "a", "c"]),
            ("sifive-s76", &["m", "a", "c"]),
            ("sifive-u54", &["m", "a", "c", "f", "d"]),
            ("sifive-u74", &["m", "a", "c", "f", "d"]),
            ("rocket-rv32", &["m", "a", "c"]),
            ("rocket-rv64", &["m", "a", "c", "f", "d"]),
            ("boom-v2", &["m", "a", "c", "f", "d"]),
            ("xiangshan-nanhu", &["m", "a", "c", "f", "d"]),
        ];
        for (name, feats) in riscv_cpus {
            self.cpus.insert(
                name.to_string(),
                feats.iter().map(|s| s.to_string()).collect(),
            );
        }
    }

    // ── X86 feature definitions ─────────────────────────────────────────

    fn register_x86_features(&mut self) {
        let x86_feats: &[(&str, &str, bool, &[&str])] = &[
            ("mmx", "MMX SIMD instructions", true, &[]),
            ("sse", "SSE (Streaming SIMD Extensions)", true, &["mmx"]),
            ("sse2", "SSE2 instructions", true, &["sse"]),
            ("sse3", "SSE3 instructions", true, &["sse2"]),
            ("ssse3", "Supplemental SSE3", true, &["sse3"]),
            ("sse4.1", "SSE4.1 instructions", false, &["ssse3"]),
            ("sse4.2", "SSE4.2 instructions", false, &["sse4.1"]),
            ("popcnt", "POPCNT instruction", false, &["sse4.2"]),
            ("avx", "Advanced Vector Extensions", false, &["sse4.2"]),
            ("avx2", "AVX2 instructions", false, &["avx"]),
            ("fma", "FMA3 instructions", false, &["avx"]),
            ("bmi", "BMI instructions", false, &[]),
            ("bmi2", "BMI2 instructions", false, &["bmi"]),
            ("lzcnt", "LZCNT instruction", false, &[]),
            ("f16c", "F16C instructions", false, &["avx"]),
            ("movbe", "MOVBE instruction", false, &[]),
            ("adx", "ADCX/ADOX instructions", false, &[]),
            ("rdseed", "RDSEED instruction", false, &[]),
            ("cx16", "CMPXCHG16B instruction", true, &[]),
            ("xsavec", "XSAVEC instruction", false, &[]),
            ("xsaves", "XSAVES instruction", false, &["xsavec"]),
            ("clflushopt", "CLFLUSHOPT instruction", false, &[]),
            ("avx512f", "AVX-512 Foundation", false, &["avx2"]),
            ("avx512bw", "AVX-512 Byte/Word", false, &["avx512f"]),
            ("avx512dq", "AVX-512 DQ", false, &["avx512f"]),
            ("avx512vl", "AVX-512 Vector Length", false, &["avx512f"]),
            ("avx512vbmi", "AVX-512 VBMI", false, &["avx512bw"]),
            ("avx512vbmi2", "AVX-512 VBMI2", false, &["avx512vbmi"]),
            ("avx512bitalg", "AVX-512 BITALG", false, &["avx512bw"]),
            ("vaes", "VAES instructions", false, &["avx"]),
            ("vpclmulqdq", "VPCLMULQDQ", false, &["avx"]),
            ("gfni", "GFNI instructions", false, &["avx"]),
            ("sha", "SHA instructions", false, &["sse2"]),
            ("clzero", "CLZERO instruction", false, &[]),
            ("mwaitx", "MONITORX/MWAITX", false, &[]),
            ("wbnoinvd", "WBNOINVD instruction", false, &[]),
        ];
        for (name, desc, default, implies) in x86_feats {
            let mut f = TargetFeature::new(name, desc, *default);
            f.implies = implies.iter().map(|s| s.to_string()).collect();
            self.features.insert(name.to_string(), f);
        }
    }

    // ── AArch64 feature definitions ─────────────────────────────────────

    fn register_aarch64_features(&mut self) {
        let aarch64_feats: &[(&str, &str, bool, &[&str])] = &[
            ("fp", "Floating-point (base)", true, &[]),
            ("neon", "Advanced SIMD (NEON)", true, &["fp"]),
            ("crc", "CRC instructions", true, &[]),
            ("crypto", "Cryptographic extensions", false, &["neon"]),
            ("fp16", "Half-precision FP", false, &["fp"]),
            ("lse", "Large System Extensions", false, &[]),
            (
                "rcpc",
                "Release Consistent Processor Consistent",
                false,
                &[],
            ),
            ("dotprod", "Dot product instructions", false, &["neon"]),
            ("rdm", "Rounding Double Multiply", false, &["neon"]),
            ("sve", "Scalable Vector Extension", false, &["neon"]),
            ("sve2", "Scalable Vector Extension 2", false, &["sve"]),
            ("i8mm", "Integer 8-bit Matrix Multiply", false, &["neon"]),
            ("pauth", "Pointer Authentication", false, &[]),
            ("mte", "Memory Tagging Extension", false, &[]),
            ("bf16", "BFloat16 extension", false, &["neon"]),
        ];
        for (name, desc, default, implies) in aarch64_feats {
            let mut f = TargetFeature::new(name, desc, *default);
            f.implies = implies.iter().map(|s| s.to_string()).collect();
            self.features.insert(name.to_string(), f);
        }
    }

    // ── ARM (32-bit) feature definitions ────────────────────────────────

    fn register_arm_features(&mut self) {
        let arm_feats: &[(&str, &str, bool, &[&str])] = &[
            ("vfp2", "VFPv2 floating-point", false, &[]),
            ("vfp3", "VFPv3 floating-point", false, &["vfp2"]),
            ("vfp4", "VFPv4 floating-point", false, &["vfp3"]),
            ("vfp5", "VFPv5 floating-point", false, &["vfp4"]),
            ("neon", "NEON SIMD", false, &["vfp3"]),
            ("dsp", "DSP instructions", false, &[]),
            ("thumb2", "Thumb-2 instructions", true, &[]),
            ("aclass", "ARM Application-class", false, &[]),
        ];
        for (name, desc, default, implies) in arm_feats {
            let mut f = TargetFeature::new(name, desc, *default);
            f.implies = implies.iter().map(|s| s.to_string()).collect();
            self.features.insert(name.to_string(), f);
        }
    }

    // ── RISC-V feature definitions ──────────────────────────────────────

    fn register_riscv_features(&mut self) {
        let riscv_feats: &[(&str, &str, bool, &[&str])] = &[
            ("m", "Integer Multiplication/Division", false, &[]),
            ("a", "Atomic instructions", false, &[]),
            ("f", "Single-precision FP", false, &[]),
            ("d", "Double-precision FP", false, &["f"]),
            ("c", "Compressed instructions", false, &[]),
            ("v", "Vector extension", false, &["f"]),
            ("zicsr", "Control and Status Register", false, &[]),
            ("zifencei", "Instruction-Fetch Fence", false, &[]),
            ("zba", "Bit-manipulation Address generation", false, &[]),
            ("zbb", "Bit-manipulation Base", false, &[]),
            ("zbc", "Bit-manipulation Carry-less multiply", false, &[]),
            ("zbs", "Bit-manipulation Single-bit", false, &[]),
        ];
        for (name, desc, default, implies) in riscv_feats {
            let mut f = TargetFeature::new(name, desc, *default);
            f.implies = implies.iter().map(|s| s.to_string()).collect();
            self.features.insert(name.to_string(), f);
        }
    }
}

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

// ═══════════════════════════════════════════════════════════════════════════
// Clang Target Info  — unified target configuration from flags
// ═══════════════════════════════════════════════════════════════════════════

/// Clang-level target information, built from compiler flags.
///
/// This is the primary bridge from Clang driver flags to LLVM
/// `TargetMachine` configuration.
#[derive(Debug, Clone)]
pub struct ClangTargetInfo {
    /// The resolved target triple string.
    pub triple: String,
    /// Parsed triple for programmatic queries.
    pub parsed_triple: Triple,
    /// Architecture-specific codegen info.
    pub codegen_info: TargetCodeGenInfo,
    /// ABI specification.
    pub abi: ClangABI,
    /// CPU name (e.g. "cortex-a53", "skylake", "generic").
    pub cpu: String,
    /// Comma-separated feature string (+sse2,-avx).
    pub features: String,
    /// Code model.
    pub code_model: CodeModel,
    /// Relocation model.
    pub reloc_model: RelocModel,
    /// Optimisation level.
    pub opt_level: ClangOptLevel,
    /// Debug info kind.
    pub debug_info: DebugInfoKind,
    /// Stack protector level.
    pub stack_protector: StackProtectorLevel,
    /// Frame pointer policy.
    pub no_frame_pointer_elim: bool,
    /// Unsafe FP math (from `-ffast-math` or similar).
    pub unsafe_fp_math: bool,
    /// No signed zeros FP math.
    pub no_signed_zeros_fp_math: bool,
    /// No strict aliasing (`-fno-strict-aliasing`).
    pub no_strict_aliasing: bool,
    /// Position-independent code flag.
    pub position_independent: bool,
    /// Use local-exec TLS model.
    pub local_exec_tls: bool,
    /// Use soft-float.
    pub use_soft_float: bool,
    /// Emit unwind tables.
    pub emit_unwind_tables: bool,
    /// Stack alignment override.
    pub stack_alignment: u32,
    /// Thread model.
    pub thread_model: String,
    /// Function sections.
    pub function_sections: bool,
    /// Data sections.
    pub data_sections: bool,
    /// Integrated assembler.
    pub integrated_as: bool,
    /// CPU feature database for resolving CPU names.
    pub cpu_db: CpuFeatureDatabase,
}

impl ClangTargetInfo {
    /// Create a new target info from a target triple.
    pub fn new(triple: &str) -> Self {
        let t = Triple::parse(triple);
        let codegen_info = TargetCodeGenInfo::for_arch(t.arch);
        let abi = ClangABI::new(triple);
        Self {
            triple: triple.to_string(),
            parsed_triple: t,
            codegen_info,
            abi,
            cpu: String::from("generic"),
            features: String::new(),
            code_model: CodeModel::Small,
            reloc_model: RelocModel::Static,
            opt_level: ClangOptLevel::default(),
            debug_info: DebugInfoKind::default(),
            stack_protector: StackProtectorLevel::default(),
            no_frame_pointer_elim: false,
            unsafe_fp_math: false,
            no_signed_zeros_fp_math: false,
            no_strict_aliasing: false,
            position_independent: false,
            local_exec_tls: false,
            use_soft_float: false,
            emit_unwind_tables: true,
            stack_alignment: 0,
            thread_model: String::from("posix"),
            function_sections: false,
            data_sections: false,
            integrated_as: true,
            cpu_db: CpuFeatureDatabase::new(),
        }
    }

    /// Set the target triple.
    pub fn with_triple(mut self, triple: &str) -> Self {
        self.triple = triple.to_string();
        self.parsed_triple = Triple::parse(triple);
        self.codegen_info = TargetCodeGenInfo::for_arch(self.parsed_triple.arch);
        self.abi = ClangABI::new(triple);
        self
    }

    /// Set the CPU name  (`-mcpu=`, `--target-cpu`).
    pub fn with_cpu(mut self, cpu: &str) -> Self {
        self.cpu = cpu.to_string();
        self
    }

    /// Set the target feature string  (`-mattr=`, `--target-feature`).
    pub fn with_features(mut self, features: &str) -> Self {
        self.features = features.to_string();
        self
    }

    /// Add a single feature enable/disable.
    pub fn add_feature(&mut self, feature: &str, enable: bool) {
        if !self.features.is_empty() {
            self.features.push(',');
        }
        if enable {
            self.features.push('+');
        } else {
            self.features.push('-');
        }
        self.features.push_str(feature);
    }

    /// Set the ABI  (`-mabi=`).
    pub fn with_abi(mut self, abi: &str) -> Self {
        self.abi = self.abi.with_base_abi(abi);
        self
    }

    /// Set the float ABI  (`-mfloat-abi=`).
    pub fn with_float_abi(mut self, fa: &str) -> Self {
        self.abi = self.abi.with_float_abi(fa);
        self.use_soft_float = self.abi.is_soft_float();
        self
    }

    /// Set the code model  (`-mcmodel=`).
    pub fn with_code_model(mut self, model: CodeModel) -> Self {
        self.code_model = model;
        self
    }

    /// Set the relocation model  (`-fPIC`, `-fPIE`).
    pub fn with_reloc_model(mut self, model: RelocModel) -> Self {
        self.reloc_model = model;
        self.position_independent = model.is_pic();
        self
    }

    /// Set the optimisation level  (`-O0`…`-O3`, `-Os`, `-Oz`, `-Ofast`).
    pub fn with_opt_level(mut self, level: ClangOptLevel) -> Self {
        self.opt_level = level;
        if level.implies_fast_math() {
            self.unsafe_fp_math = true;
            self.no_signed_zeros_fp_math = true;
        }
        self
    }

    /// Set the debug-info kind  (`-g0`…`-g3`).
    pub fn with_debug_info(mut self, kind: DebugInfoKind) -> Self {
        self.debug_info = kind;
        self
    }

    /// Set the stack-protector level.
    pub fn with_stack_protector(mut self, level: StackProtectorLevel) -> Self {
        self.stack_protector = level;
        self
    }

    /// Enable/disable frame-pointer elimination  (`-fno-omit-frame-pointer`).
    pub fn with_frame_pointer_elim(mut self, elim: bool) -> Self {
        self.no_frame_pointer_elim = !elim;
        self
    }

    /// Enable unsafe FP math  (`-ffast-math` / `-funsafe-math-optimizations`).
    pub fn with_unsafe_fp_math(mut self, v: bool) -> Self {
        self.unsafe_fp_math = v;
        self
    }

    /// Enable no-signed-zeros FP math.
    pub fn with_no_signed_zeros(mut self, v: bool) -> Self {
        self.no_signed_zeros_fp_math = v;
        self
    }

    /// Enable/disable strict aliasing  (`-fno-strict-aliasing`).
    pub fn with_strict_aliasing(mut self, sa: bool) -> Self {
        self.no_strict_aliasing = !sa;
        self
    }

    /// Set the architecture (`-march=`).
    pub fn with_arch(mut self, arch: &str) -> Self {
        if arch == "native" {
            let mut detector = HostCpuDetector::new();
            let host_cpu = detector.host_cpu_name().to_string();
            self.cpu = host_cpu;
        } else {
            // Map -march names to CPU names
            let cpu = match arch {
                "x86-64" => "x86-64", // generic x86-64 baseline
                "armv6" => "arm1176jzf-s",
                "armv7-a" => "cortex-a8",
                "armv7ve" => "cortex-a7",
                "armv8-a" => "cortex-a53",
                "armv8.1-a" => "cortex-a55",
                "armv8.2-a" => "cortex-a75",
                "armv8.3-a" => "cortex-a76",
                "armv8.4-a" => "neoverse-n1",
                "armv8.5-a" => "neoverse-n2",
                "armv8.6-a" => "neoverse-v1",
                "armv9-a" => "neoverse-v2",
                "rv32i" => "rocket-rv32",
                "rv32imac" => "sifive-e76",
                "rv64gc" => "sifive-u74",
                "rv64imafdc" => "rocket-rv64",
                _ => "generic",
            };
            self.cpu = cpu.to_string();
        }
        self
    }

    /// Set the tune CPU  (`-mtune=`).  This is advisory and may map
    /// to the same CPU name in the simple case.
    pub fn with_tune_cpu(mut self, tune: &str) -> Self {
        // -mtune is often the same as -mcpu unless explicitly different
        if self.cpu == "generic" && tune != "generic" {
            self.cpu = tune.to_string();
        }
        self
    }

    /// Override target features  (`-mattr=+sse4.2,-avx`).
    pub fn with_mattr(mut self, attr: &str) -> Self {
        for part in attr.split(',') {
            let trimmed = part.trim();
            if trimmed.is_empty() {
                continue;
            }
            let enable = !trimmed.starts_with('-');
            let feat = if trimmed.starts_with('+') || trimmed.starts_with('-') {
                &trimmed[1..]
            } else {
                trimmed
            };
            self.add_feature(feat, enable);
        }
        self
    }

    /// Build an LLVM `TargetMachine` from this Clang-level target info.
    pub fn create_target_machine(&mut self) -> TargetMachine {
        let features = self.cpu_db.feature_string(&self.cpu, &[]);
        let mut combined = features;
        if !self.features.is_empty() {
            if !combined.is_empty() {
                combined.push(',');
            }
            combined.push_str(&self.features);
        }

        let opts = TargetOptions {
            triple: self.triple.clone(),
            cpu: self.cpu.clone(),
            features: combined,
            abi: self.abi.base_abi.clone(),
            opt_level: self.opt_level.to_llvm_opt(),
            reloc_model: self.reloc_model,
            code_model: self.code_model,
            float_abi: self.abi.to_llvm_float_abi(),
            position_independent: self.position_independent,
            use_local_exec_tls: self.local_exec_tls,
            use_soft_float: self.use_soft_float,
            disable_fp_elim: self.no_frame_pointer_elim,
            emit_unwind_tables: self.emit_unwind_tables,
            stack_alignment: self.stack_alignment,
            output_file: None,
            no_signed_zeros_fp_math: self.no_signed_zeros_fp_math,
            unsafe_fp_math: self.unsafe_fp_math,
            trap_unaligned: false,
            function_sections: self.function_sections,
            data_sections: self.data_sections,
            integrated_as: self.integrated_as,
            preserve_asm_comments: false,
            emit_compact_unwind: false,
            thread_model: self.thread_model.clone(),
        };

        TargetMachine::with_options(&self.triple, opts)
    }

    /// Get the data layout for the current target.
    pub fn data_layout(&self) -> DataLayout {
        data_layout_for_triple(&self.parsed_triple)
    }

    /// Whether the target is 64-bit.
    pub fn is_64bit(&self) -> bool {
        self.parsed_triple.is_64bit()
    }

    /// Whether the target is little-endian.
    pub fn is_little_endian(&self) -> bool {
        data_layout_for_triple(&self.parsed_triple).is_little_endian()
    }

    /// Pointer width in bits.
    pub fn pointer_width(&self) -> u32 {
        if self.is_64bit() {
            64
        } else {
            32
        }
    }

    /// Whether the target uses the Windows ABI (MSVC).
    pub fn is_windows_abi(&self) -> bool {
        self.parsed_triple.is_windows()
    }
}

impl Default for ClangTargetInfo {
    fn default() -> Self {
        Self::new("x86_64-unknown-linux-gnu")
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// DataLayout builder from Triple
// ═══════════════════════════════════════════════════════════════════════════

/// Build a DataLayout from a target Triple.
pub fn data_layout_for_triple(triple: &Triple) -> DataLayout {
    match triple.arch {
        Arch::X86_64 => DataLayout::parse(
            "e-m:e-p:64:64-i64:64-f80:128-n8:16:32:64-S128"
        ).unwrap_or_else(|_| DataLayout::x86_64_linux()),
        Arch::X86 => DataLayout::parse(
            "e-m:e-p:32:32-f64:32:64-f80:32-n8:16:32-S128"
        ).unwrap_or_else(|_| DataLayout::x86_64_linux()),
        Arch::AArch64 => DataLayout::aarch64_linux(),
        Arch::AArch64_32 => DataLayout::parse(
            "e-m:e-p:32:32-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128"
        ).unwrap_or_else(|_| DataLayout::aarch64_linux()),
        Arch::ARM | Arch::ARMeb | Arch::Thumb | Arch::Thumbeb => DataLayout::parse(
            "e-m:e-p:32:32-Fi8-f64:32:64-v64:32:64-v128:32:64-a:0:32-n32-S64"
        ).unwrap_or_else(|_| DataLayout::x86_64_linux()),
        Arch::RISCV64 => DataLayout::parse(
            "e-m:e-p:64:64-i64:64-i128:128-n64-S128"
        ).unwrap_or_else(|_| DataLayout::x86_64_linux()),
        Arch::RISCV32 => DataLayout::parse(
            "e-m:e-p:32:32-i64:64-n32-S128"
        ).unwrap_or_else(|_| DataLayout::x86_64_linux()),
        Arch::Mips | Arch::Mipsel => DataLayout::parse(
            "E-m:m-p:32:32-i8:8:32-i16:16:32-i64:64-n32:64-S128"
        ).unwrap_or_else(|_| DataLayout::x86_64_linux()),
        Arch::Mips64 | Arch::Mips64el => DataLayout::parse(
            "E-m:m-i8:8:32-i16:16:32-i64:64-n32:64-S128"
        ).unwrap_or_else(|_| DataLayout::x86_64_linux()),
        Arch::PowerPC => DataLayout::parse(
            "E-m:e-p:32:32-i64:64-n32"
        ).unwrap_or_else(|_| DataLayout::x86_64_linux()),
        Arch::PowerPC64 => DataLayout::parse(
            "E-m:e-i64:64-n32:64"
        ).unwrap_or_else(|_| DataLayout::x86_64_linux()),
        Arch::PowerPC64le => DataLayout::parse(
            "e-m:e-i64:64-n32:64"
        ).unwrap_or_else(|_| DataLayout::x86_64_linux()),
        Arch::Sparc | Arch::Sparcv9 => DataLayout::parse(
            "E-m:e-p:64:64-i64:64-f128:64-n32:64-S128"
        ).unwrap_or_else(|_| DataLayout::x86_64_linux()),
        Arch::SystemZ => DataLayout::parse(
            "E-m:e-i1:8:16-i8:8:16-i64:64-f128:64-a:8:16-n32:64"
        ).unwrap_or_else(|_| DataLayout::x86_64_linux()),
        Arch::BPF | Arch::BPFEB | Arch::BPF64 => DataLayout::parse(
            "e-m:e-p:64:64-i64:64-i128:128-n32:64-S128"
        ).unwrap_or_else(|_| DataLayout::x86_64_linux()),
        Arch::WebAssembly32 | Arch::WebAssembly64 => DataLayout::parse(
            "e-m:e-p:32:32-i64:64-n32:64-S128"
        ).unwrap_or_else(|_| DataLayout::x86_64_linux()),
        Arch::AVR => DataLayout::parse(
            "e-P1-p:16:8-i8:8-i16:8-i32:8-i64:8-f32:8-f64:8-n8-a:8"
        ).unwrap_or_else(|_| DataLayout::x86_64_linux()),
        Arch::MSP430 => DataLayout::parse(
            "e-m:e-p:16:16-i32:16:32-a:16-n8:16"
        ).unwrap_or_else(|_| DataLayout::x86_64_linux()),
        Arch::Hexagon => DataLayout::parse(
            "e-m:e-p:32:32:32-a:0-n16:32-i64:64:64-i32:32:32-i16:16:16-i1:8:8-f64:64:64-f32:32:32-v64:64:64-v32:32:32"
        ).unwrap_or_else(|_| DataLayout::x86_64_linux()),
        Arch::Lanai => DataLayout::parse(
            "E-m:e-p:32:32-i64:64-a:0:32-n32"
        ).unwrap_or_else(|_| DataLayout::x86_64_linux()),
        Arch::NVPTX | Arch::NVPTX64 => DataLayout::parse(
            "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:64-v128:128:128-n16:32:64"
        ).unwrap_or_else(|_| DataLayout::x86_64_linux()),
        Arch::AMDGPU => DataLayout::parse(
            "e-p:64:64-p1:64:64-p2:32:32-p3:32:32-p4:64:64-p5:32:32-p6:32:32-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64-S32-A5-G1"
        ).unwrap_or_else(|_| DataLayout::x86_64_linux()),
        Arch::ARC => DataLayout::parse(
            "e-m:e-p:32:32-i1:8:32-i8:8:32-i16:16:32-i32:32:32-f32:32:32-i64:32:32-f64:32:32-v64:32:32-v128:32:32-a:0:32-n32"
        ).unwrap_or_else(|_| DataLayout::x86_64_linux()),
        Arch::CSKY => DataLayout::parse(
            "e-m:e-p:32:32-i1:8:32-i8:8:32-i16:16:32-i32:32:32-f32:32:32-i64:32:32-f64:32:32-n32"
        ).unwrap_or_else(|_| DataLayout::x86_64_linux()),
        Arch::Xtensa => DataLayout::parse(
            "e-m:e-p:32:32-i8:8:32-i16:16:32-i32:32:32-f32:32:32-n32"
        ).unwrap_or_else(|_| DataLayout::x86_64_linux()),
        Arch::LoongArch64 => DataLayout::parse(
            "e-m:e-p:64:64-i64:64-i128:128-n64-S128"
        ).unwrap_or_else(|_| DataLayout::x86_64_linux()),
        _ => DataLayout::x86_64_linux(),
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Flag-to-Target Mapper: parse Clang driver flags into target config
// ═══════════════════════════════════════════════════════════════════════════

/// Structured representation of the target-related flags extracted from
/// a full Clang command line.
#[derive(Debug, Clone, Default)]
pub struct TargetFlags {
    pub target_triple: Option<String>,
    pub march: Option<String>,
    pub mcpu: Option<String>,
    pub mtune: Option<String>,
    pub mattr: Option<String>,
    pub mabi: Option<String>,
    pub mfloat_abi: Option<String>,
    pub mcmodel: Option<String>,
    pub fpic: bool,
    pub fpie: bool,
    pub fno_pic: bool,
    pub fstack_protector: Option<String>,
    pub fomit_frame_pointer: bool,
    pub fno_omit_frame_pointer: bool,
    pub ffast_math: bool,
    pub funsafe_math_optimizations: bool,
    pub fno_strict_aliasing: bool,
    pub g_level: u8,
    pub opt_level: Option<String>,
    pub m32: bool,
    pub m64: bool,
}

impl TargetFlags {
    /// Build the complete `ClangTargetInfo` from these flags.
    pub fn to_target_info(&self) -> ClangTargetInfo {
        let triple = self.resolve_triple();
        let mut info = ClangTargetInfo::new(&triple);

        // ── Architecture ────────────────────────────────────────────
        if let Some(ref march) = self.march {
            info = info.with_arch(march);
        }

        // ── CPU ─────────────────────────────────────────────────────
        if let Some(ref mcpu) = self.mcpu {
            info = info.with_cpu(mcpu);
        } else if let Some(ref mtune) = self.mtune {
            info = info.with_tune_cpu(mtune);
        }

        // ── Target features ─────────────────────────────────────────
        if let Some(ref mattr) = self.mattr {
            info = info.with_mattr(mattr);
        }

        // ── ABI ─────────────────────────────────────────────────────
        if let Some(ref mabi) = self.mabi {
            info = info.with_abi(mabi);
        }

        // ── Float ABI ──────────────────────────────────────────────
        if let Some(ref mfloat_abi) = self.mfloat_abi {
            info = info.with_float_abi(mfloat_abi);
        }

        // ── Code model ─────────────────────────────────────────────
        if let Some(ref mcmodel) = self.mcmodel {
            let model = match mcmodel.as_str() {
                "tiny" => CodeModel::Tiny,
                "small" => CodeModel::Small,
                "kernel" => CodeModel::Kernel,
                "medium" => CodeModel::Medium,
                "large" => CodeModel::Large,
                _ => CodeModel::default(),
            };
            info.code_model = model;
        }

        // ── Relocation model ───────────────────────────────────────
        if self.fno_pic {
            info = info.with_reloc_model(RelocModel::Static);
        } else if self.fpie {
            info = info.with_reloc_model(RelocModel::PIC);
            // PIE is PIC + executable relocation
        } else if self.fpic {
            info = info.with_reloc_model(RelocModel::PIC);
        }

        // ── Stack protector ────────────────────────────────────────
        if let Some(ref sp) = self.fstack_protector {
            info = info.with_stack_protector(StackProtectorLevel::from_flag(sp));
        }

        // ── Frame pointer ──────────────────────────────────────────
        if self.fno_omit_frame_pointer {
            info.no_frame_pointer_elim = true;
        } else if self.fomit_frame_pointer {
            info.no_frame_pointer_elim = false;
        }

        // ── FP math ────────────────────────────────────────────────
        if self.ffast_math || self.funsafe_math_optimizations {
            info.unsafe_fp_math = true;
        }

        // ── Strict aliasing ────────────────────────────────────────
        if self.fno_strict_aliasing {
            info.no_strict_aliasing = true;
        }

        // ── Debug info ─────────────────────────────────────────────
        info.debug_info = DebugInfoKind::from_flag(self.g_level);

        // ── Optimisation level ─────────────────────────────────────
        if let Some(ref opt) = self.opt_level {
            info.opt_level = ClangOptLevel::from_flag(opt);
        }

        info
    }

    /// Resolve the target triple from flags.
    fn resolve_triple(&self) -> String {
        if let Some(ref t) = self.target_triple {
            return t.clone();
        }
        // Infer from -m32/-m64 on a host-like basis
        if self.m32 {
            return String::from("i686-unknown-linux-gnu");
        }
        if self.m64 {
            return String::from("x86_64-unknown-linux-gnu");
        }
        // Default to host triple
        String::from("x86_64-unknown-linux-gnu")
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Function Attribute Mapping (Clang flags → LLVM function attributes)
// ═══════════════════════════════════════════════════════════════════════════

/// Maps Clang-level function-attribute flags onto LLVM IR function
/// attributes (the `"key"` / `"key"="value"` strings used in LLVM IR).
#[derive(Debug, Clone, Default)]
pub struct FunctionAttrMapper {
    /// Whether to add `"no-frame-pointer-elim"`.
    pub no_frame_pointer_elim: bool,
    /// Whether to add `"unsafe-fp-math"="true"`.
    pub unsafe_fp_math: bool,
    /// Whether to add `"no-signed-zeros-fp-math"="true"`.
    pub no_signed_zeros_fp_math: bool,
    /// Whether to add `"no-trapping-math"="true"`.
    pub no_trapping_math: bool,
    /// Whether to add `"approx-func-fp-math"="true"`.
    pub approx_func_fp_math: bool,
    /// Whether to add `"no-nans-fp-math"="true"`.
    pub no_nans_fp_math: bool,
    /// Whether to add `"no-infs-fp-math"="true"`.
    pub no_infs_fp_math: bool,
    /// Whether to add `"denormal-fp-math"="..."` attribute.
    pub denormal_fp_math_mode: String,
    /// Whether to add `"denormal-fp-math-f32"="..."` attribute.
    pub denormal_fp_math_f32_mode: String,
    /// Stack alignment in bytes (12 for 4 KiB, 16 for 64 KiB).
    pub stack_alignment: u32,
    /// Whether `"trap-func-name"="..."` attribute is set.
    pub trap_func_name: Option<String>,
    /// Whether `"target-cpu"` attribute is set.
    pub target_cpu: Option<String>,
    /// Whether `"target-features"` attribute is set.
    pub target_features: Option<String>,
}

impl FunctionAttrMapper {
    /// Build from `ClangTargetInfo`.
    pub fn from_target_info(ti: &ClangTargetInfo) -> Self {
        let mut mapper = Self::default();
        mapper.no_frame_pointer_elim = ti.no_frame_pointer_elim;
        mapper.unsafe_fp_math = ti.unsafe_fp_math;
        mapper.no_signed_zeros_fp_math = ti.no_signed_zeros_fp_math;
        mapper.stack_alignment = ti.stack_alignment;
        mapper.target_cpu = Some(ti.cpu.clone());
        mapper.target_features = Some(ti.features.clone());

        // Fast-math implies all FP relaxation flags
        if ti.unsafe_fp_math {
            mapper.no_trapping_math = true;
            mapper.approx_func_fp_math = true;
            mapper.no_nans_fp_math = true;
            mapper.no_infs_fp_math = true;
        }

        mapper
    }

    /// Emit the LLVM-IR function-attribute strings.
    pub fn emit_attributes(&self) -> Vec<String> {
        let mut attrs: Vec<String> = Vec::new();

        // ── FMF (Fast-Math Flags) ───────────────────────────────────
        if self.unsafe_fp_math {
            attrs.push(r#""unsafe-fp-math"="true""#.to_string());
        }
        if self.no_signed_zeros_fp_math {
            attrs.push(r#""no-signed-zeros-fp-math"="true""#.to_string());
        }
        if self.no_trapping_math {
            attrs.push(r#""no-trapping-math"="true""#.to_string());
        }
        if self.approx_func_fp_math {
            attrs.push(r#""approx-func-fp-math"="true""#.to_string());
        }
        if self.no_nans_fp_math {
            attrs.push(r#""no-nans-fp-math"="true""#.to_string());
        }
        if self.no_infs_fp_math {
            attrs.push(r#""no-infs-fp-math"="true""#.to_string());
        }

        // ── Frame pointer ──────────────────────────────────────────
        if self.no_frame_pointer_elim {
            attrs.push(r#""no-frame-pointer-elim"="true""#.to_string());
        }

        // ── Denormal handling ──────────────────────────────────────
        if !self.denormal_fp_math_mode.is_empty() {
            attrs.push(format!(
                r#""denormal-fp-math"="{}""#,
                self.denormal_fp_math_mode
            ));
        }
        if !self.denormal_fp_math_f32_mode.is_empty() {
            attrs.push(format!(
                r#""denormal-fp-math-f32"="{}""#,
                self.denormal_fp_math_f32_mode
            ));
        }

        // ── Trap function ──────────────────────────────────────────
        if let Some(ref trap_fn) = self.trap_func_name {
            attrs.push(format!(r#""trap-func-name"="{}""#, trap_fn));
        }

        // ── CPU / Features ─────────────────────────────────────────
        if let Some(ref cpu) = self.target_cpu {
            attrs.push(format!(r#""target-cpu"="{}""#, cpu));
        }
        if let Some(ref feats) = self.target_features {
            if !feats.is_empty() {
                attrs.push(format!(r#""target-features"="{}""#, feats));
            }
        }

        // ── Stack alignment ────────────────────────────────────────
        if self.stack_alignment > 0 {
            attrs.push(format!(r#""stack-alignment"="{}""#, self.stack_alignment));
        }

        attrs
    }

    /// Apply no-strict-aliasing attribute.
    pub fn with_no_strict_aliasing(self, v: bool) -> Self {
        // In LLVM IR, no strict aliasing is represented by the absence
        // of `"strict-aliasing"="true"`.  We don't emit it by default.
        let _ = v;
        self
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Target Registry — create TargetMachine for known architectures
// ═══════════════════════════════════════════════════════════════════════════

/// Convenience: create a TargetMachine for a given architecture
/// with Clang driver flag defaults.
pub fn create_target_machine(triple: &str, cpu: &str, features: &str) -> TargetMachine {
    let info = ClangTargetInfo::new(triple)
        .with_cpu(cpu)
        .with_features(features);
    let mut info = info;
    info.create_target_machine()
}

/// Create an X86-64 target machine with Clang defaults.
pub fn create_x86_64_machine(cpu: &str, features: &str) -> TargetMachine {
    create_target_machine("x86_64-unknown-linux-gnu", cpu, features)
}

/// Create an AArch64 target machine with Clang defaults.
pub fn create_aarch64_machine(cpu: &str, features: &str) -> TargetMachine {
    create_target_machine("aarch64-unknown-linux-gnu", cpu, features)
}

/// Create an ARM target machine with Clang defaults.
pub fn create_arm_machine(cpu: &str, features: &str) -> TargetMachine {
    create_target_machine("arm-unknown-linux-gnueabihf", cpu, features)
}

/// Create a RISC-V 64-bit target machine with Clang defaults.
pub fn create_riscv64_machine(cpu: &str, features: &str) -> TargetMachine {
    create_target_machine("riscv64-unknown-linux-gnu", cpu, features)
}

/// Create a RISC-V 32-bit target machine with Clang defaults.
pub fn create_riscv32_machine(cpu: &str, features: &str) -> TargetMachine {
    create_target_machine("riscv32-unknown-linux-gnu", cpu, features)
}

// ═══════════════════════════════════════════════════════════════════════════
// Tests
// ═══════════════════════════════════════════════════════════════════════════

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

    #[test]
    fn test_debug_info_from_flag() {
        assert_eq!(DebugInfoKind::from_flag(0), DebugInfoKind::NoDebug);
        assert_eq!(DebugInfoKind::from_flag(1), DebugInfoKind::LineTablesOnly);
        assert_eq!(DebugInfoKind::from_flag(2), DebugInfoKind::LimitedDebug);
        assert_eq!(DebugInfoKind::from_flag(3), DebugInfoKind::FullWithMacros);
    }

    #[test]
    fn test_stack_protector_from_flag() {
        assert_eq!(
            StackProtectorLevel::from_flag("none"),
            StackProtectorLevel::None
        );
        assert_eq!(
            StackProtectorLevel::from_flag("all"),
            StackProtectorLevel::All
        );
        assert_eq!(
            StackProtectorLevel::from_flag("strong"),
            StackProtectorLevel::Strong
        );
        assert_eq!(
            StackProtectorLevel::from_flag("default"),
            StackProtectorLevel::Basic
        );
    }

    #[test]
    fn test_clang_opt_level_from_flag() {
        assert_eq!(ClangOptLevel::from_flag("0"), ClangOptLevel::None);
        assert_eq!(ClangOptLevel::from_flag("1"), ClangOptLevel::Less);
        assert_eq!(ClangOptLevel::from_flag("2"), ClangOptLevel::Default);
        assert_eq!(ClangOptLevel::from_flag("3"), ClangOptLevel::Aggressive);
        assert_eq!(ClangOptLevel::from_flag("s"), ClangOptLevel::DefaultSize);
        assert_eq!(ClangOptLevel::from_flag("z"), ClangOptLevel::AggressiveSize);
        assert_eq!(ClangOptLevel::from_flag("fast"), ClangOptLevel::FastMath);
    }

    #[test]
    fn test_clang_abi_defaults() {
        let abi = ClangABI::new("x86_64-unknown-linux-gnu");
        assert_eq!(abi.base_abi, "lp64");
        assert!(!abi.is_soft_float());

        let abi2 = ClangABI::new("arm-unknown-linux-gnueabi");
        assert_eq!(abi2.base_abi, "ilp32");
    }

    #[test]
    fn test_clang_abi_override() {
        let abi = ClangABI::new("riscv64-unknown-linux-gnu")
            .with_base_abi("lp64")
            .with_float_abi("soft");
        assert_eq!(abi.base_abi, "lp64");
        assert!(abi.is_soft_float());
    }

    #[test]
    fn test_target_codegen_info_x86_64() {
        let info = TargetCodeGenInfo::for_arch(Arch::X86_64);
        assert!(info.uses_sret_demotion);
        assert!(info.indirect_struct_return);
        assert!(info.varargs_save_area);
        assert!(info.setjmp_returns_twice);
        assert_eq!(info.stack_alignment, 16);
    }

    #[test]
    fn test_target_codegen_info_arm_thumb() {
        let info = TargetCodeGenInfo::for_arch(Arch::Thumb);
        assert!(!info.uses_sret_demotion);
        assert_eq!(info.stack_alignment, 8);
    }

    #[test]
    fn test_target_codegen_info_wasm() {
        let info = TargetCodeGenInfo::for_arch(Arch::WebAssembly32);
        assert!(!info.varargs_save_area);
        assert!(!info.indirect_struct_return);
    }

    #[test]
    fn test_host_cpu_detector() {
        let mut detector = HostCpuDetector::new();
        let name = detector.host_cpu_name().to_string();
        assert!(!name.is_empty());
        let feats = detector.host_cpu_features();
        // On any platform we should get some features or empty set
        assert!(feats.len() >= 0);
    }

    #[test]
    fn test_cpu_feature_database_x86() {
        let mut db = CpuFeatureDatabase::new();
        let feats = db.resolve_cpu("haswell");
        assert!(feats.contains("avx2"));
        assert!(feats.contains("fma"));
        assert!(feats.contains("avx"));

        let feats2 = db.resolve_cpu("generic");
        assert!(feats2.is_empty());
    }

    #[test]
    fn test_cpu_feature_database_aarch64() {
        let mut db = CpuFeatureDatabase::new();
        let feats = db.resolve_cpu("cortex-a53");
        assert!(feats.contains("neon"));
        assert!(feats.contains("crc"));
    }

    #[test]
    fn test_cpu_feature_database_riscv() {
        let mut db = CpuFeatureDatabase::new();
        let feats = db.resolve_cpu("sifive-u74");
        assert!(feats.contains("m"));
        assert!(feats.contains("a"));
        assert!(feats.contains("c"));
        assert!(feats.contains("f"));
        assert!(feats.contains("d"));
        // 'd' implies 'f'
    }

    #[test]
    fn test_feature_string_generation() {
        let mut db = CpuFeatureDatabase::new();
        let s = db.feature_string(
            "cortex-a53",
            &[(String::from("sve"), false), (String::from("fp16"), true)],
        );
        // Should contain base features and fp16
        assert!(s.contains("+crc"));
        assert!(s.contains("+crypto"));
        assert!(s.contains("+fp16"));
        assert!(!s.contains("sve")); // we only add it if true
    }

    #[test]
    fn test_clang_target_info_basic() {
        let info = ClangTargetInfo::new("x86_64-unknown-linux-gnu");
        assert_eq!(info.triple, "x86_64-unknown-linux-gnu");
        assert!(!info.position_independent);
        assert!(info.emit_unwind_tables);
    }

    #[test]
    fn test_clang_target_info_with_flags() {
        let info = ClangTargetInfo::new("aarch64-unknown-linux-gnu")
            .with_cpu("cortex-a76")
            .with_opt_level(ClangOptLevel::Aggressive)
            .with_reloc_model(RelocModel::PIC)
            .with_debug_info(DebugInfoKind::FullDebug)
            .with_stack_protector(StackProtectorLevel::Strong)
            .with_frame_pointer_elim(false)
            .with_unsafe_fp_math(true);

        assert_eq!(info.cpu, "cortex-a76");
        assert_eq!(info.opt_level, ClangOptLevel::Aggressive);
        assert!(info.position_independent);
        assert_eq!(info.debug_info, DebugInfoKind::FullDebug);
        assert_eq!(info.stack_protector, StackProtectorLevel::Strong);
        assert!(info.no_frame_pointer_elim);
        assert!(info.unsafe_fp_math);
    }

    #[test]
    fn test_target_flags_to_target_info() {
        let flags = TargetFlags {
            target_triple: Some(String::from("arm-unknown-linux-gnueabihf")),
            mcpu: Some(String::from("cortex-a9")),
            mfloat_abi: Some(String::from("hard")),
            mcmodel: Some(String::from("small")),
            fpic: true,
            g_level: 2,
            opt_level: Some(String::from("3")),
            ..Default::default()
        };
        let info = flags.to_target_info();
        assert_eq!(info.triple, "arm-unknown-linux-gnueabihf");
        assert_eq!(info.cpu, "cortex-a9");
        assert!(!info.abi.is_soft_float());
        assert_eq!(info.code_model, CodeModel::Small);
        assert!(info.position_independent);
        assert_eq!(info.debug_info, DebugInfoKind::LimitedDebug);
        assert_eq!(info.opt_level, ClangOptLevel::Aggressive);
    }

    #[test]
    fn test_target_flags_defaults() {
        let flags = TargetFlags::default();
        assert!(flags.target_triple.is_none());
        assert!(flags.mcpu.is_none());
    }

    #[test]
    fn test_function_attr_mapper_basic() {
        let ti = ClangTargetInfo::new("x86_64-unknown-linux-gnu");
        let mapper = FunctionAttrMapper::from_target_info(&ti);
        let attrs = mapper.emit_attributes();
        assert!(!attrs.is_empty());
        // Should include target-cpu
        let has_cpu = attrs.iter().any(|a| a.contains("target-cpu"));
        assert!(has_cpu);
    }

    #[test]
    fn test_function_attr_mapper_fast_math() {
        let ti = ClangTargetInfo::new("x86_64-unknown-linux-gnu").with_unsafe_fp_math(true);
        let mapper = FunctionAttrMapper::from_target_info(&ti);
        let attrs = mapper.emit_attributes();
        let has_ufm = attrs.iter().any(|a| a.contains("unsafe-fp-math"));
        let has_ninf = attrs.iter().any(|a| a.contains("no-infs-fp-math"));
        assert!(has_ufm);
        assert!(has_ninf);
    }

    #[test]
    fn test_create_target_machine() {
        let tm = create_target_machine("x86_64-unknown-linux-gnu", "generic", "");
        assert_eq!(tm.triple(), "x86_64-unknown-linux-gnu");
    }

    #[test]
    fn test_create_x86_64_machine() {
        let tm = create_x86_64_machine("haswell", "+avx2");
        assert!(tm.triple().contains("x86_64"));
    }

    #[test]
    fn test_create_aarch64_machine() {
        let tm = create_aarch64_machine("cortex-a53", "+neon");
        assert!(tm.triple().contains("aarch64"));
    }

    #[test]
    fn test_create_arm_machine() {
        let tm = create_arm_machine("cortex-a9", "");
        assert!(tm.triple().contains("arm"));
    }

    #[test]
    fn test_create_riscv64_machine() {
        let tm = create_riscv64_machine("sifive-u74", "+m,+a,+c,+f,+d");
        assert!(tm.triple().contains("riscv64"));
    }

    #[test]
    fn test_clang_target_info_modify() {
        let mut info = ClangTargetInfo::new("x86_64-unknown-linux-gnu");
        info.add_feature("avx2", true);
        info.add_feature("sse3", false);
        let feats = info.features.clone();
        assert!(feats.contains("+avx2"));
        assert!(feats.contains("-sse3"));
    }

    #[test]
    fn test_clang_target_info_arch_mapping() {
        let info = ClangTargetInfo::new("aarch64-unknown-linux-gnu").with_arch("armv8.2-a");
        assert_eq!(info.cpu, "cortex-a75");

        let info2 = ClangTargetInfo::new("riscv64-unknown-linux-gnu").with_arch("rv64gc");
        assert_eq!(info2.cpu, "sifive-u74");
    }

    #[test]
    fn test_float_abi_mapping() {
        let info = ClangTargetInfo::new("arm-unknown-linux-gnueabi");
        assert!(info.abi.is_soft_float());

        let info = ClangTargetInfo::new("arm-unknown-linux-gnueabihf");
        assert!(!info.abi.is_soft_float());
    }

    #[test]
    fn test_code_model_mapping() {
        let info =
            ClangTargetInfo::new("x86_64-unknown-linux-gnu").with_code_model(CodeModel::Kernel);
        assert_eq!(info.code_model, CodeModel::Kernel);
    }

    #[test]
    fn test_target_flags_fast_math() {
        let flags = TargetFlags {
            ffast_math: true,
            ..Default::default()
        };
        let info = flags.to_target_info();
        assert!(info.unsafe_fp_math);
    }

    #[test]
    fn test_target_flags_no_strict_aliasing() {
        let flags = TargetFlags {
            fno_strict_aliasing: true,
            ..Default::default()
        };
        let info = flags.to_target_info();
        assert!(info.no_strict_aliasing);
    }

    #[test]
    fn test_target_flags_fno_omit_frame_pointer() {
        let flags = TargetFlags {
            fno_omit_frame_pointer: true,
            ..Default::default()
        };
        let info = flags.to_target_info();
        assert!(info.no_frame_pointer_elim);
    }

    #[test]
    fn test_clang_opt_level_is_size() {
        assert!(ClangOptLevel::DefaultSize.is_size_oriented());
        assert!(ClangOptLevel::AggressiveSize.is_size_oriented());
        assert!(!ClangOptLevel::None.is_size_oriented());
        assert!(!ClangOptLevel::Default.is_size_oriented());
    }

    #[test]
    fn test_clang_opt_level_to_llvm() {
        assert_eq!(ClangOptLevel::None.to_llvm_opt(), CodeGenOptLevel::None);
        assert_eq!(ClangOptLevel::Less.to_llvm_opt(), CodeGenOptLevel::Less);
        assert_eq!(
            ClangOptLevel::Default.to_llvm_opt(),
            CodeGenOptLevel::Default
        );
        assert_eq!(
            ClangOptLevel::Aggressive.to_llvm_opt(),
            CodeGenOptLevel::Aggressive
        );
    }

    #[test]
    fn test_target_codegen_indirect_pass() {
        let x86 = TargetCodeGenInfo::for_arch(Arch::X86_64);
        // A 64-byte struct should pass indirectly on x86-64 SysV
        assert!(x86.should_pass_indirectly(64));

        let wasm = TargetCodeGenInfo::for_arch(Arch::WebAssembly32);
        assert!(!wasm.should_pass_indirectly(64));
    }

    #[test]
    fn test_detect_host_cpu_stub() {
        #[cfg(target_arch = "x86_64")]
        {
            let cpu = HostCpuDetector::detect_host_cpu();
            assert!(!cpu.is_empty());
        }
    }
}