stator_jse 0.1.4

Stator JavaScript engine core — parser, bytecode compiler, Maglev JIT, interpreter, GC
Documentation
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
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
//! Maglev IR node types.
//!
//! This module defines the typed intermediate representation (IR) used by the
//! Maglev optimising compiler tier.  Using typed enums eliminates runtime type
//! checks that would otherwise be required with an untyped node representation.
//!
//! # Structure
//!
//! - [`ValueNode`] — nodes that produce a value (inputs to other nodes).
//! - [`ControlNode`] — terminator instructions at the end of each block.
//! - [`BasicBlock`] — a straight-line sequence of [`ValueNode`]s followed by
//!   exactly one [`ControlNode`].
//! - [`MaglevGraph`] — the complete control-flow graph, owning all blocks.
//!
//! # Example
//!
//! ```
//! use stator_jse::compiler::maglev::ir::{
//!     BasicBlock, ControlNode, MaglevGraph, ValueNode,
//! };
//!
//! let mut graph = MaglevGraph::new(1);
//!
//! // entry block: return parameter 0
//! let mut entry = BasicBlock::new(0);
//! let param = entry.push_value(ValueNode::Parameter { index: 0 });
//! entry.set_control(ControlNode::Return { value: param });
//! graph.add_block(entry);
//! assert_eq!(graph.blocks().len(), 1);
//! ```

// ─────────────────────────────────────────────────────────────────────────────
// Node IDs
// ─────────────────────────────────────────────────────────────────────────────

/// Unique identifier for a [`ValueNode`] within a [`MaglevGraph`].
///
/// Graph-global IDs are assigned by [`MaglevGraph::add_value_node`].
/// Block-local IDs assigned by [`BasicBlock::push_value`] start at `0` per
/// block and are only unique within that block.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct NodeId(pub u32);

// ─────────────────────────────────────────────────────────────────────────────
// ValueNode
// ─────────────────────────────────────────────────────────────────────────────

/// A Maglev IR node that produces a typed value.
///
/// Each variant captures both the *kind* of computation and all data required
/// to perform it, eliminating the need for dynamic casts at compile time.
///
/// # Groupings
///
/// ## Constants
/// [`SmiConstant`](ValueNode::SmiConstant),
/// [`Float64Constant`](ValueNode::Float64Constant),
/// [`Int32Constant`](ValueNode::Int32Constant),
/// [`Uint32Constant`](ValueNode::Uint32Constant),
/// [`BigIntConstant`](ValueNode::BigIntConstant),
/// [`TrueConstant`](ValueNode::TrueConstant),
/// [`FalseConstant`](ValueNode::FalseConstant),
/// [`NullConstant`](ValueNode::NullConstant),
/// [`UndefinedConstant`](ValueNode::UndefinedConstant),
/// [`RootConstant`](ValueNode::RootConstant),
/// [`ExternalConstant`](ValueNode::ExternalConstant),
/// [`StringConstant`](ValueNode::StringConstant),
/// [`ConstantPoolEntry`](ValueNode::ConstantPoolEntry)
///
/// ## Parameters and registers
/// [`Parameter`](ValueNode::Parameter),
/// [`RegisterInput`](ValueNode::RegisterInput),
/// [`ArgumentsLength`](ValueNode::ArgumentsLength),
/// [`RestLength`](ValueNode::RestLength),
/// [`GetArgument`](ValueNode::GetArgument)
///
/// ## Arithmetic (Smi / Int32 / Uint32 / Float64 / tagged)
/// [`CheckedSmiAdd`](ValueNode::CheckedSmiAdd),
/// [`CheckedSmiSubtract`](ValueNode::CheckedSmiSubtract),
/// [`CheckedSmiMultiply`](ValueNode::CheckedSmiMultiply),
/// [`CheckedSmiDivide`](ValueNode::CheckedSmiDivide),
/// [`CheckedSmiModulus`](ValueNode::CheckedSmiModulus),
/// [`CheckedSmiIncrement`](ValueNode::CheckedSmiIncrement),
/// [`CheckedSmiDecrement`](ValueNode::CheckedSmiDecrement),
/// [`Int32Add`](ValueNode::Int32Add),
/// [`Int32Subtract`](ValueNode::Int32Subtract),
/// [`Int32Multiply`](ValueNode::Int32Multiply),
/// [`Int32Divide`](ValueNode::Int32Divide),
/// [`Int32Modulus`](ValueNode::Int32Modulus),
/// [`Int32Negate`](ValueNode::Int32Negate),
/// [`Int32Increment`](ValueNode::Int32Increment),
/// [`Int32Decrement`](ValueNode::Int32Decrement),
/// [`Int32BitwiseAnd`](ValueNode::Int32BitwiseAnd),
/// [`Int32BitwiseOr`](ValueNode::Int32BitwiseOr),
/// [`Int32BitwiseXor`](ValueNode::Int32BitwiseXor),
/// [`Int32ShiftLeft`](ValueNode::Int32ShiftLeft),
/// [`Int32ShiftRight`](ValueNode::Int32ShiftRight),
/// [`Int32ShiftRightLogical`](ValueNode::Int32ShiftRightLogical),
/// [`Uint32Add`](ValueNode::Uint32Add),
/// [`Uint32Subtract`](ValueNode::Uint32Subtract),
/// [`Uint32Multiply`](ValueNode::Uint32Multiply),
/// [`Uint32Divide`](ValueNode::Uint32Divide),
/// [`Uint32Modulus`](ValueNode::Uint32Modulus),
/// [`Float64Add`](ValueNode::Float64Add),
/// [`Float64Subtract`](ValueNode::Float64Subtract),
/// [`Float64Multiply`](ValueNode::Float64Multiply),
/// [`Float64Divide`](ValueNode::Float64Divide),
/// [`Float64Modulus`](ValueNode::Float64Modulus),
/// [`Float64Negate`](ValueNode::Float64Negate),
/// [`Float64Exponentiate`](ValueNode::Float64Exponentiate),
/// [`Float64Ieee754Unary`](ValueNode::Float64Ieee754Unary),
/// [`GenericAdd`](ValueNode::GenericAdd),
/// [`GenericSubtract`](ValueNode::GenericSubtract),
/// [`GenericMultiply`](ValueNode::GenericMultiply),
/// [`GenericDivide`](ValueNode::GenericDivide),
/// [`GenericModulus`](ValueNode::GenericModulus),
/// [`GenericExponentiate`](ValueNode::GenericExponentiate),
/// [`GenericBitwiseAnd`](ValueNode::GenericBitwiseAnd),
/// [`GenericBitwiseOr`](ValueNode::GenericBitwiseOr),
/// [`GenericBitwiseXor`](ValueNode::GenericBitwiseXor),
/// [`GenericShiftLeft`](ValueNode::GenericShiftLeft),
/// [`GenericShiftRight`](ValueNode::GenericShiftRight),
/// [`GenericShiftRightLogical`](ValueNode::GenericShiftRightLogical),
/// [`GenericBitwiseNot`](ValueNode::GenericBitwiseNot),
/// [`GenericNegate`](ValueNode::GenericNegate),
/// [`GenericIncrement`](ValueNode::GenericIncrement),
/// [`GenericDecrement`](ValueNode::GenericDecrement)
///
/// ## Comparisons
/// [`Int32Equal`](ValueNode::Int32Equal),
/// [`Int32StrictEqual`](ValueNode::Int32StrictEqual),
/// [`Int32LessThan`](ValueNode::Int32LessThan),
/// [`Int32LessThanOrEqual`](ValueNode::Int32LessThanOrEqual),
/// [`Int32GreaterThan`](ValueNode::Int32GreaterThan),
/// [`Int32GreaterThanOrEqual`](ValueNode::Int32GreaterThanOrEqual),
/// [`Float64Equal`](ValueNode::Float64Equal),
/// [`Float64LessThan`](ValueNode::Float64LessThan),
/// [`Float64LessThanOrEqual`](ValueNode::Float64LessThanOrEqual),
/// [`Float64GreaterThan`](ValueNode::Float64GreaterThan),
/// [`Float64GreaterThanOrEqual`](ValueNode::Float64GreaterThanOrEqual),
/// [`TaggedEqual`](ValueNode::TaggedEqual),
/// [`TaggedNotEqual`](ValueNode::TaggedNotEqual),
/// [`TestInstanceOf`](ValueNode::TestInstanceOf),
/// [`TestIn`](ValueNode::TestIn),
/// [`TestUndetectable`](ValueNode::TestUndetectable),
/// [`TestTypeOf`](ValueNode::TestTypeOf)
///
/// ## Type conversions
/// [`ChangeInt32ToFloat64`](ValueNode::ChangeInt32ToFloat64),
/// [`ChangeUint32ToFloat64`](ValueNode::ChangeUint32ToFloat64),
/// [`ChangeFloat64ToInt32`](ValueNode::ChangeFloat64ToInt32),
/// [`CheckedFloat64ToInt32`](ValueNode::CheckedFloat64ToInt32),
/// [`ChangeInt32ToTagged`](ValueNode::ChangeInt32ToTagged),
/// [`ChangeUint32ToTagged`](ValueNode::ChangeUint32ToTagged),
/// [`ChangeFloat64ToTagged`](ValueNode::ChangeFloat64ToTagged),
/// [`ChangeTaggedToInt32`](ValueNode::ChangeTaggedToInt32),
/// [`ChangeTaggedToUint32`](ValueNode::ChangeTaggedToUint32),
/// [`ChangeTaggedToFloat64`](ValueNode::ChangeTaggedToFloat64),
/// [`CheckedTaggedToInt32`](ValueNode::CheckedTaggedToInt32),
/// [`CheckedTaggedToFloat64`](ValueNode::CheckedTaggedToFloat64),
/// [`ToBoolean`](ValueNode::ToBoolean),
/// [`ToString`](ValueNode::ToString),
/// [`ToObject`](ValueNode::ToObject),
/// [`ToName`](ValueNode::ToName),
/// [`ToNumber`](ValueNode::ToNumber),
/// [`ToNumberOrNumeric`](ValueNode::ToNumberOrNumeric)
///
/// ## Checks / guards
/// [`CheckSmi`](ValueNode::CheckSmi),
/// [`CheckNumber`](ValueNode::CheckNumber),
/// [`CheckHeapObject`](ValueNode::CheckHeapObject),
/// [`CheckSymbol`](ValueNode::CheckSymbol),
/// [`CheckString`](ValueNode::CheckString),
/// [`CheckStringOrStringWrapper`](ValueNode::CheckStringOrStringWrapper),
/// [`CheckSeqOneByteString`](ValueNode::CheckSeqOneByteString),
/// [`CheckMaps`](ValueNode::CheckMaps),
/// [`CheckMapsWithMigration`](ValueNode::CheckMapsWithMigration),
/// [`CheckValue`](ValueNode::CheckValue),
/// [`CheckDynamicValue`](ValueNode::CheckDynamicValue),
/// [`CheckInt32IsSmi`](ValueNode::CheckInt32IsSmi),
/// [`CheckUint32IsSmi`](ValueNode::CheckUint32IsSmi),
/// [`CheckHoleyFloat64IsSmi`](ValueNode::CheckHoleyFloat64IsSmi),
/// [`CheckInt32Condition`](ValueNode::CheckInt32Condition),
/// [`CheckCacheIndicesNotCleared`](ValueNode::CheckCacheIndicesNotCleared),
/// [`CheckFloat64IsNan`](ValueNode::CheckFloat64IsNan)
///
/// ## Property / field access
/// [`LoadField`](ValueNode::LoadField),
/// [`StoreField`](ValueNode::StoreField),
/// [`LoadTaggedField`](ValueNode::LoadTaggedField),
/// [`LoadDoubleField`](ValueNode::LoadDoubleField),
/// [`LoadFixedArrayElement`](ValueNode::LoadFixedArrayElement),
/// [`LoadFixedDoubleArrayElement`](ValueNode::LoadFixedDoubleArrayElement),
/// [`LoadHoleyFixedDoubleArrayElement`](ValueNode::LoadHoleyFixedDoubleArrayElement),
/// [`StoreFixedArrayElement`](ValueNode::StoreFixedArrayElement),
/// [`StoreFixedDoubleArrayElement`](ValueNode::StoreFixedDoubleArrayElement),
/// [`LoadNamedGeneric`](ValueNode::LoadNamedGeneric),
/// [`StoreNamedGeneric`](ValueNode::StoreNamedGeneric),
/// [`LoadKeyedGeneric`](ValueNode::LoadKeyedGeneric),
/// [`StoreKeyedGeneric`](ValueNode::StoreKeyedGeneric),
/// [`LoadGlobal`](ValueNode::LoadGlobal),
/// [`StoreGlobal`](ValueNode::StoreGlobal),
/// [`LoadContextSlot`](ValueNode::LoadContextSlot),
/// [`StoreContextSlot`](ValueNode::StoreContextSlot),
/// [`LoadCurrentContextSlot`](ValueNode::LoadCurrentContextSlot),
/// [`StoreCurrentContextSlot`](ValueNode::StoreCurrentContextSlot)
///
/// ## Calls and constructs
/// [`Call`](ValueNode::Call),
/// [`CallKnownFunction`](ValueNode::CallKnownFunction),
/// [`CallBuiltin`](ValueNode::CallBuiltin),
/// [`CallRuntime`](ValueNode::CallRuntime),
/// [`CallWithSpread`](ValueNode::CallWithSpread),
/// [`Construct`](ValueNode::Construct),
/// [`ConstructWithSpread`](ValueNode::ConstructWithSpread)
///
/// ## Object / array creation
/// [`CreateObjectLiteral`](ValueNode::CreateObjectLiteral),
/// [`CreateObjectLiteralWithProperties`](ValueNode::CreateObjectLiteralWithProperties),
/// [`CreateArrayLiteral`](ValueNode::CreateArrayLiteral),
/// [`CreateShallowObjectLiteral`](ValueNode::CreateShallowObjectLiteral),
/// [`CreateShallowArrayLiteral`](ValueNode::CreateShallowArrayLiteral),
/// [`CreateFunctionContext`](ValueNode::CreateFunctionContext),
/// [`PushContext`](ValueNode::PushContext),
/// [`PopContext`](ValueNode::PopContext),
/// [`CreateBlockContext`](ValueNode::CreateBlockContext),
/// [`CreateCatchContext`](ValueNode::CreateCatchContext),
/// [`CreateWithContext`](ValueNode::CreateWithContext),
/// [`CreateClosure`](ValueNode::CreateClosure),
/// [`FastCreateClosure`](ValueNode::FastCreateClosure),
/// [`CreateEmptyObjectLiteral`](ValueNode::CreateEmptyObjectLiteral),
/// [`CreateRegExpLiteral`](ValueNode::CreateRegExpLiteral)
///
/// ## Control-value producers
/// [`Phi`](ValueNode::Phi),
/// [`ArgumentsElements`](ValueNode::ArgumentsElements),
/// [`RestElements`](ValueNode::RestElements),
/// [`VirtualObject`](ValueNode::VirtualObject)
///
/// ## Miscellaneous
/// [`GetTemplateObject`](ValueNode::GetTemplateObject),
/// [`HasInPrototypeChain`](ValueNode::HasInPrototypeChain),
/// [`DeleteProperty`](ValueNode::DeleteProperty),
/// [`ForInPrepare`](ValueNode::ForInPrepare),
/// [`ForInNext`](ValueNode::ForInNext),
/// [`LoadEnumCacheLength`](ValueNode::LoadEnumCacheLength),
/// [`StringAt`](ValueNode::StringAt),
/// [`StringLength`](ValueNode::StringLength),
/// [`StringConcat`](ValueNode::StringConcat),
/// [`StringEqual`](ValueNode::StringEqual),
/// [`NumberToString`](ValueNode::NumberToString),
/// [`TypeOf`](ValueNode::TypeOf),
/// [`Debugger`](ValueNode::Debugger),
/// [`Abort`](ValueNode::Abort)
#[derive(Debug, Clone, PartialEq)]
pub enum ValueNode {
    // ── Constants ────────────────────────────────────────────────────────────
    /// A small integer (Smi) constant.
    SmiConstant {
        /// The constant value.
        value: i32,
    },

    /// A 64-bit floating-point constant.
    Float64Constant {
        /// The constant value.
        value: f64,
    },

    /// A 32-bit signed integer constant (unboxed).
    Int32Constant {
        /// The constant value.
        value: i32,
    },

    /// A 32-bit unsigned integer constant (unboxed).
    Uint32Constant {
        /// The constant value.
        value: u32,
    },

    /// A BigInt constant represented as a decimal string.
    BigIntConstant {
        /// Decimal string representation of the BigInt value.
        value: String,
    },

    /// The boolean `true` constant.
    TrueConstant,

    /// The boolean `false` constant.
    FalseConstant,

    /// The `null` constant.
    NullConstant,

    /// The `undefined` constant.
    UndefinedConstant,

    /// A reference to a well-known engine root object (e.g. the empty string).
    RootConstant {
        /// Index into the engine root table.
        index: u32,
    },

    /// A pointer-sized external constant (e.g. a C++ function address).
    ExternalConstant {
        /// Raw pointer value stored as a `u64`.
        address: u64,
    },

    /// A string constant (interned).
    StringConstant {
        /// The string value.
        value: String,
    },

    /// A reference to a constant-pool entry by index.
    ConstantPoolEntry {
        /// Zero-based index into the enclosing function's constant pool.
        index: u32,
    },

    // ── Parameters and registers ─────────────────────────────────────────────
    /// A function parameter (zero-based).
    Parameter {
        /// Zero-based parameter index.
        index: u32,
    },

    /// A physical register input at function entry.
    RegisterInput {
        /// Physical register number.
        reg: u32,
    },

    /// The number of actual arguments passed at the call site.
    ArgumentsLength,

    /// The number of rest-parameter elements.
    RestLength,

    /// Load a single argument by index from the arguments object.
    GetArgument {
        /// The argument to retrieve.
        index: NodeId,
    },

    // ── Smi arithmetic ───────────────────────────────────────────────────────
    /// Tagged Smi addition with overflow check (deopt on overflow).
    CheckedSmiAdd {
        /// Left operand.
        left: NodeId,
        /// Right operand.
        right: NodeId,
    },

    /// Tagged Smi subtraction with overflow check (deopt on overflow).
    CheckedSmiSubtract {
        /// Left operand.
        left: NodeId,
        /// Right operand.
        right: NodeId,
    },

    /// Tagged Smi multiplication with overflow check (deopt on overflow).
    CheckedSmiMultiply {
        /// Left operand.
        left: NodeId,
        /// Right operand.
        right: NodeId,
    },

    /// Tagged Smi division with overflow/zero check (deopt if not exact).
    CheckedSmiDivide {
        /// Dividend.
        left: NodeId,
        /// Divisor.
        right: NodeId,
    },

    /// Tagged Smi modulus with overflow/zero check (deopt on non-Smi result).
    CheckedSmiModulus {
        /// Dividend.
        left: NodeId,
        /// Divisor.
        right: NodeId,
    },

    /// Increment a Smi value by one, deopt on overflow.
    CheckedSmiIncrement {
        /// The value to increment.
        value: NodeId,
    },

    /// Decrement a Smi value by one, deopt on overflow.
    CheckedSmiDecrement {
        /// The value to decrement.
        value: NodeId,
    },

    // ── Int32 arithmetic ─────────────────────────────────────────────────────
    /// Unboxed 32-bit integer addition (wrapping).
    Int32Add {
        /// Left operand.
        left: NodeId,
        /// Right operand.
        right: NodeId,
    },

    /// Unboxed 32-bit integer subtraction (wrapping).
    Int32Subtract {
        /// Left operand.
        left: NodeId,
        /// Right operand.
        right: NodeId,
    },

    /// Unboxed 32-bit integer multiplication (wrapping).
    Int32Multiply {
        /// Left operand.
        left: NodeId,
        /// Right operand.
        right: NodeId,
    },

    /// Unboxed 32-bit integer division (truncating).
    Int32Divide {
        /// Dividend.
        left: NodeId,
        /// Divisor.
        right: NodeId,
    },

    /// Unboxed 32-bit integer modulus.
    Int32Modulus {
        /// Dividend.
        left: NodeId,
        /// Divisor.
        right: NodeId,
    },

    /// Unboxed 32-bit integer negation (wrapping).
    Int32Negate {
        /// The value to negate.
        value: NodeId,
    },

    /// Unboxed 32-bit integer increment by one (wrapping).
    Int32Increment {
        /// The value to increment.
        value: NodeId,
    },

    /// Unboxed 32-bit integer decrement by one (wrapping).
    Int32Decrement {
        /// The value to decrement.
        value: NodeId,
    },

    /// Unboxed 32-bit bitwise AND.
    Int32BitwiseAnd {
        /// Left operand.
        left: NodeId,
        /// Right operand.
        right: NodeId,
    },

    /// Unboxed 32-bit bitwise OR.
    Int32BitwiseOr {
        /// Left operand.
        left: NodeId,
        /// Right operand.
        right: NodeId,
    },

    /// Unboxed 32-bit bitwise XOR.
    Int32BitwiseXor {
        /// Left operand.
        left: NodeId,
        /// Right operand.
        right: NodeId,
    },

    /// Unboxed 32-bit left shift.
    Int32ShiftLeft {
        /// Value to shift.
        left: NodeId,
        /// Shift amount.
        right: NodeId,
    },

    /// Unboxed 32-bit arithmetic right shift.
    Int32ShiftRight {
        /// Value to shift.
        left: NodeId,
        /// Shift amount.
        right: NodeId,
    },

    /// Unboxed 32-bit logical right shift.
    Int32ShiftRightLogical {
        /// Value to shift.
        left: NodeId,
        /// Shift amount.
        right: NodeId,
    },

    // ── Uint32 arithmetic ────────────────────────────────────────────────────
    /// Unboxed 32-bit unsigned integer addition (wrapping).
    Uint32Add {
        /// Left operand.
        left: NodeId,
        /// Right operand.
        right: NodeId,
    },

    /// Unboxed 32-bit unsigned integer subtraction (wrapping).
    Uint32Subtract {
        /// Left operand.
        left: NodeId,
        /// Right operand.
        right: NodeId,
    },

    /// Unboxed 32-bit unsigned integer multiplication (wrapping).
    Uint32Multiply {
        /// Left operand.
        left: NodeId,
        /// Right operand.
        right: NodeId,
    },

    /// Unboxed 32-bit unsigned integer division (truncating).
    Uint32Divide {
        /// Dividend.
        left: NodeId,
        /// Divisor.
        right: NodeId,
    },

    /// Unboxed 32-bit unsigned integer modulus.
    Uint32Modulus {
        /// Dividend.
        left: NodeId,
        /// Divisor.
        right: NodeId,
    },

    // ── Float64 arithmetic ───────────────────────────────────────────────────
    /// Unboxed 64-bit float addition.
    Float64Add {
        /// Left operand.
        left: NodeId,
        /// Right operand.
        right: NodeId,
    },

    /// Unboxed 64-bit float subtraction.
    Float64Subtract {
        /// Left operand.
        left: NodeId,
        /// Right operand.
        right: NodeId,
    },

    /// Unboxed 64-bit float multiplication.
    Float64Multiply {
        /// Left operand.
        left: NodeId,
        /// Right operand.
        right: NodeId,
    },

    /// Unboxed 64-bit float division.
    Float64Divide {
        /// Dividend.
        left: NodeId,
        /// Divisor.
        right: NodeId,
    },

    /// Unboxed 64-bit float modulus (IEEE 754 remainder).
    Float64Modulus {
        /// Dividend.
        left: NodeId,
        /// Divisor.
        right: NodeId,
    },

    /// Unboxed 64-bit float negation.
    Float64Negate {
        /// The value to negate.
        value: NodeId,
    },

    /// Unboxed 64-bit float exponentiation (`left ** right`).
    Float64Exponentiate {
        /// Base.
        left: NodeId,
        /// Exponent.
        right: NodeId,
    },

    /// Apply an IEEE 754 unary math function (e.g. `Math.sqrt`).
    Float64Ieee754Unary {
        /// The input value.
        value: NodeId,
        /// Index identifying which IEEE 754 function to apply.
        function_id: u32,
    },

    // ── Generic (slow-path) arithmetic ───────────────────────────────────────
    /// Generic (possibly slow-path) addition with feedback.
    GenericAdd {
        /// Left operand.
        left: NodeId,
        /// Right operand.
        right: NodeId,
        /// Feedback vector slot index.
        feedback_slot: u32,
    },

    /// Generic subtraction with feedback.
    GenericSubtract {
        /// Left operand.
        left: NodeId,
        /// Right operand.
        right: NodeId,
        /// Feedback vector slot index.
        feedback_slot: u32,
    },

    /// Generic multiplication with feedback.
    GenericMultiply {
        /// Left operand.
        left: NodeId,
        /// Right operand.
        right: NodeId,
        /// Feedback vector slot index.
        feedback_slot: u32,
    },

    /// Generic division with feedback.
    GenericDivide {
        /// Dividend.
        left: NodeId,
        /// Divisor.
        right: NodeId,
        /// Feedback vector slot index.
        feedback_slot: u32,
    },

    /// Generic modulus with feedback.
    GenericModulus {
        /// Dividend.
        left: NodeId,
        /// Divisor.
        right: NodeId,
        /// Feedback vector slot index.
        feedback_slot: u32,
    },

    /// Generic exponentiation with feedback.
    GenericExponentiate {
        /// Base.
        left: NodeId,
        /// Exponent.
        right: NodeId,
        /// Feedback vector slot index.
        feedback_slot: u32,
    },

    /// Generic bitwise AND with feedback.
    GenericBitwiseAnd {
        /// Left operand.
        left: NodeId,
        /// Right operand.
        right: NodeId,
        /// Feedback vector slot index.
        feedback_slot: u32,
    },

    /// Generic bitwise OR with feedback.
    GenericBitwiseOr {
        /// Left operand.
        left: NodeId,
        /// Right operand.
        right: NodeId,
        /// Feedback vector slot index.
        feedback_slot: u32,
    },

    /// Generic bitwise XOR with feedback.
    GenericBitwiseXor {
        /// Left operand.
        left: NodeId,
        /// Right operand.
        right: NodeId,
        /// Feedback vector slot index.
        feedback_slot: u32,
    },

    /// Generic left shift with feedback.
    GenericShiftLeft {
        /// Value to shift.
        left: NodeId,
        /// Shift amount.
        right: NodeId,
        /// Feedback vector slot index.
        feedback_slot: u32,
    },

    /// Generic arithmetic right shift with feedback.
    GenericShiftRight {
        /// Value to shift.
        left: NodeId,
        /// Shift amount.
        right: NodeId,
        /// Feedback vector slot index.
        feedback_slot: u32,
    },

    /// Generic logical right shift with feedback.
    GenericShiftRightLogical {
        /// Value to shift.
        left: NodeId,
        /// Shift amount.
        right: NodeId,
        /// Feedback vector slot index.
        feedback_slot: u32,
    },

    /// Generic bitwise NOT with feedback.
    GenericBitwiseNot {
        /// The value to complement.
        value: NodeId,
        /// Feedback vector slot index.
        feedback_slot: u32,
    },

    /// Generic negation with feedback.
    GenericNegate {
        /// The value to negate.
        value: NodeId,
        /// Feedback vector slot index.
        feedback_slot: u32,
    },

    /// Generic increment with feedback.
    GenericIncrement {
        /// The value to increment.
        value: NodeId,
        /// Feedback vector slot index.
        feedback_slot: u32,
    },

    /// Generic decrement with feedback.
    GenericDecrement {
        /// The value to decrement.
        value: NodeId,
        /// Feedback vector slot index.
        feedback_slot: u32,
    },

    // ── Int32 comparisons ────────────────────────────────────────────────────
    /// Unboxed 32-bit integer equality check.
    Int32Equal {
        /// Left operand.
        left: NodeId,
        /// Right operand.
        right: NodeId,
    },

    /// Unboxed 32-bit integer strict equality check.
    Int32StrictEqual {
        /// Left operand.
        left: NodeId,
        /// Right operand.
        right: NodeId,
    },

    /// Unboxed 32-bit integer less-than check.
    Int32LessThan {
        /// Left operand.
        left: NodeId,
        /// Right operand.
        right: NodeId,
    },

    /// Unboxed 32-bit integer less-than-or-equal check.
    Int32LessThanOrEqual {
        /// Left operand.
        left: NodeId,
        /// Right operand.
        right: NodeId,
    },

    /// Unboxed 32-bit integer greater-than check.
    Int32GreaterThan {
        /// Left operand.
        left: NodeId,
        /// Right operand.
        right: NodeId,
    },

    /// Unboxed 32-bit integer greater-than-or-equal check.
    Int32GreaterThanOrEqual {
        /// Left operand.
        left: NodeId,
        /// Right operand.
        right: NodeId,
    },

    // ── Float64 comparisons ──────────────────────────────────────────────────
    /// Unboxed 64-bit float equality check (NaN-safe per IEEE 754).
    Float64Equal {
        /// Left operand.
        left: NodeId,
        /// Right operand.
        right: NodeId,
    },

    /// Unboxed 64-bit float less-than check.
    Float64LessThan {
        /// Left operand.
        left: NodeId,
        /// Right operand.
        right: NodeId,
    },

    /// Unboxed 64-bit float less-than-or-equal check.
    Float64LessThanOrEqual {
        /// Left operand.
        left: NodeId,
        /// Right operand.
        right: NodeId,
    },

    /// Unboxed 64-bit float greater-than check.
    Float64GreaterThan {
        /// Left operand.
        left: NodeId,
        /// Right operand.
        right: NodeId,
    },

    /// Unboxed 64-bit float greater-than-or-equal check.
    Float64GreaterThanOrEqual {
        /// Left operand.
        left: NodeId,
        /// Right operand.
        right: NodeId,
    },

    // ── Tagged comparisons ───────────────────────────────────────────────────
    /// Abstract equality (`==`) on tagged values.
    TaggedEqual {
        /// Left operand.
        left: NodeId,
        /// Right operand.
        right: NodeId,
        /// Feedback vector slot index.
        feedback_slot: u32,
    },

    /// Abstract inequality (`!=`) on tagged values.
    TaggedNotEqual {
        /// Left operand.
        left: NodeId,
        /// Right operand.
        right: NodeId,
        /// Feedback vector slot index.
        feedback_slot: u32,
    },

    /// `instanceof` test.
    TestInstanceOf {
        /// The object being tested.
        object: NodeId,
        /// The constructor to test against.
        callable: NodeId,
        /// Feedback vector slot index.
        feedback_slot: u32,
    },

    /// `in` operator test.
    TestIn {
        /// The property key.
        key: NodeId,
        /// The object to search.
        object: NodeId,
        /// Feedback vector slot index.
        feedback_slot: u32,
    },

    /// Tests whether a value is undetectable (e.g. `document.all`).
    TestUndetectable {
        /// The value to test.
        value: NodeId,
    },

    /// Tests whether a value is `null` or `undefined`.
    ///
    /// Returns a JIT boolean (`JIT_TRUE` / `JIT_FALSE`).  Used by the
    /// nullish coalescing (`??`) and optional chaining (`?.`) operators
    /// which must distinguish null/undefined from other falsy values.
    TestNullOrUndefined {
        /// The value to test.
        value: NodeId,
    },

    /// Tests the typeof result against a literal type string.
    TestTypeOf {
        /// The value to test.
        value: NodeId,
        /// Index into the type-string table.
        literal_flag: u32,
    },

    // ── Type conversions ─────────────────────────────────────────────────────
    /// Lossless widening from unboxed `i32` to unboxed `f64`.
    ChangeInt32ToFloat64 {
        /// The input integer.
        input: NodeId,
    },

    /// Lossless widening from unboxed `u32` to unboxed `f64`.
    ChangeUint32ToFloat64 {
        /// The input unsigned integer.
        input: NodeId,
    },

    /// Truncating narrowing from unboxed `f64` to unboxed `i32`.
    ChangeFloat64ToInt32 {
        /// The input float.
        input: NodeId,
    },

    /// Checked narrowing from unboxed `f64` to unboxed `i32`; deopt if lossy.
    CheckedFloat64ToInt32 {
        /// The input float.
        input: NodeId,
    },

    /// Tag an unboxed `i32` as a Smi or heap number.
    ChangeInt32ToTagged {
        /// The input integer.
        input: NodeId,
    },

    /// Tag an unboxed `u32` as a Smi or heap number.
    ChangeUint32ToTagged {
        /// The input unsigned integer.
        input: NodeId,
    },

    /// Tag an unboxed `f64` as a heap number.
    ChangeFloat64ToTagged {
        /// The input float.
        input: NodeId,
    },

    /// Untag a tagged Smi to an unboxed `i32`; deopt if not Smi.
    ChangeTaggedToInt32 {
        /// The tagged value.
        input: NodeId,
    },

    /// Untag a tagged Smi to an unboxed `u32`; deopt if not Smi.
    ChangeTaggedToUint32 {
        /// The tagged value.
        input: NodeId,
    },

    /// Unbox a tagged Smi or heap number to an unboxed `f64`.
    ChangeTaggedToFloat64 {
        /// The tagged value.
        input: NodeId,
    },

    /// Checked untag to `i32`; deopt if the value cannot be represented.
    CheckedTaggedToInt32 {
        /// The tagged value.
        input: NodeId,
    },

    /// Checked untag to `f64`; deopt if the value is not numeric.
    CheckedTaggedToFloat64 {
        /// The tagged value.
        input: NodeId,
    },

    /// Convert any value to a boolean (`ToBoolean` abstract operation).
    ToBoolean {
        /// The value to convert.
        value: NodeId,
    },

    /// Convert any value to a string (`ToString` abstract operation).
    ToString {
        /// The value to convert.
        value: NodeId,
        /// Feedback vector slot index.
        feedback_slot: u32,
    },

    /// Convert any value to an object (`ToObject` abstract operation).
    ToObject {
        /// The value to convert.
        value: NodeId,
        /// Feedback vector slot index.
        feedback_slot: u32,
    },

    /// Convert any value to a property name (`ToName` abstract operation).
    ToName {
        /// The value to convert.
        value: NodeId,
        /// Feedback vector slot index.
        feedback_slot: u32,
    },

    /// Convert any value to a number (`ToNumber` abstract operation).
    ToNumber {
        /// The value to convert.
        value: NodeId,
        /// Feedback vector slot index.
        feedback_slot: u32,
    },

    /// Convert any value to a number or BigInt.
    ToNumberOrNumeric {
        /// The value to convert.
        value: NodeId,
        /// Feedback vector slot index.
        feedback_slot: u32,
    },

    // ── Checks / guards ──────────────────────────────────────────────────────
    /// Guard: the value must be a Smi; deopt otherwise.
    CheckSmi {
        /// The value to check.
        receiver: NodeId,
    },

    /// Guard: the value must be numeric (Smi or heap number); deopt otherwise.
    CheckNumber {
        /// The value to check.
        receiver: NodeId,
    },

    /// Guard: the value must be a heap object (not a Smi); deopt otherwise.
    CheckHeapObject {
        /// The value to check.
        receiver: NodeId,
    },

    /// Guard: the value must be a Symbol; deopt otherwise.
    CheckSymbol {
        /// The value to check.
        receiver: NodeId,
    },

    /// Guard: the value must be a String; deopt otherwise.
    CheckString {
        /// The value to check.
        receiver: NodeId,
    },

    /// Guard: the value must be a String or StringWrapper; deopt otherwise.
    CheckStringOrStringWrapper {
        /// The value to check.
        receiver: NodeId,
    },

    /// Guard: the value must be a sequential one-byte String; deopt otherwise.
    CheckSeqOneByteString {
        /// The value to check.
        receiver: NodeId,
    },

    /// Guard: the value's map must be in the given set; deopt otherwise.
    CheckMaps {
        /// The object whose map is checked.
        receiver: NodeId,
        /// Feedback vector slot holding the expected map set.
        feedback_slot: u32,
    },

    /// Guard: the value's map must be in the given set; may migrate the object.
    CheckMapsWithMigration {
        /// The object whose map is checked.
        receiver: NodeId,
        /// Feedback vector slot holding the expected map set.
        feedback_slot: u32,
    },

    /// Guard: the value must be a specific constant; deopt otherwise.
    CheckValue {
        /// The value to check.
        receiver: NodeId,
        /// Index of the expected constant in the constant pool.
        expected: u32,
    },

    /// Guard: the value must equal another dynamic node; deopt otherwise.
    CheckDynamicValue {
        /// The value to check.
        receiver: NodeId,
        /// The expected value node.
        expected: NodeId,
    },

    /// Guard: the unboxed `i32` must fit in a Smi; deopt otherwise.
    CheckInt32IsSmi {
        /// The integer to check.
        input: NodeId,
    },

    /// Guard: the unboxed `u32` must fit in a Smi; deopt otherwise.
    CheckUint32IsSmi {
        /// The unsigned integer to check.
        input: NodeId,
    },

    /// Guard: a holey-float64 element is a valid Smi; deopt otherwise.
    CheckHoleyFloat64IsSmi {
        /// The float to check.
        input: NodeId,
    },

    /// Guard: checks a condition on two `i32` values; deopt if false.
    CheckInt32Condition {
        /// Left operand.
        left: NodeId,
        /// Right operand.
        right: NodeId,
        /// Condition code index.
        condition: u32,
    },

    /// Guard: the for-in cache indices have not been cleared; deopt otherwise.
    CheckCacheIndicesNotCleared {
        /// The for-in state object.
        receiver: NodeId,
        /// The cache indices being validated.
        indices: NodeId,
    },

    /// Guard: the float64 value is NaN; deopt otherwise.
    CheckFloat64IsNan {
        /// The float to check.
        input: NodeId,
    },

    // ── Property / field access ───────────────────────────────────────────────
    /// Load an in-object property at a fixed byte offset.
    LoadField {
        /// The object to load from.
        object: NodeId,
        /// Byte offset of the field within the object.
        offset: u32,
    },

    /// Store an in-object property at a fixed byte offset.
    StoreField {
        /// The object to store into.
        object: NodeId,
        /// Byte offset of the field within the object.
        offset: u32,
        /// The value to store.
        value: NodeId,
    },

    /// Load a tagged field (pointer-sized, GC-traced) at a fixed byte offset.
    LoadTaggedField {
        /// The object to load from.
        object: NodeId,
        /// Byte offset of the field.
        offset: u32,
    },

    /// Load a double-precision float field at a fixed byte offset.
    LoadDoubleField {
        /// The object to load from.
        object: NodeId,
        /// Byte offset of the field.
        offset: u32,
    },

    /// Load an element from a FixedArray at a known integer index.
    LoadFixedArrayElement {
        /// The FixedArray object.
        elements: NodeId,
        /// The zero-based element index.
        index: NodeId,
    },

    /// Load an element from a FixedDoubleArray at a known integer index.
    LoadFixedDoubleArrayElement {
        /// The FixedDoubleArray object.
        elements: NodeId,
        /// The zero-based element index.
        index: NodeId,
    },

    /// Load a possibly-hole element from a FixedDoubleArray.
    LoadHoleyFixedDoubleArrayElement {
        /// The FixedDoubleArray object.
        elements: NodeId,
        /// The zero-based element index.
        index: NodeId,
    },

    /// Store an element into a FixedArray at a known integer index.
    StoreFixedArrayElement {
        /// The FixedArray object.
        elements: NodeId,
        /// The zero-based element index.
        index: NodeId,
        /// The value to store.
        value: NodeId,
    },

    /// Store an element into a FixedDoubleArray at a known integer index.
    StoreFixedDoubleArrayElement {
        /// The FixedDoubleArray object.
        elements: NodeId,
        /// The zero-based element index.
        index: NodeId,
        /// The float value to store.
        value: NodeId,
    },

    /// Generic named property load with IC feedback.
    LoadNamedGeneric {
        /// The object to load from.
        object: NodeId,
        /// Index of the name in the constant pool.
        name: u32,
        /// Feedback vector slot index.
        feedback_slot: u32,
    },

    /// Generic named property store with IC feedback.
    StoreNamedGeneric {
        /// The object to store into.
        object: NodeId,
        /// Index of the name in the constant pool.
        name: u32,
        /// The value to store.
        value: NodeId,
        /// Feedback vector slot index.
        feedback_slot: u32,
    },

    /// Generic keyed property load with IC feedback.
    LoadKeyedGeneric {
        /// The object to load from.
        object: NodeId,
        /// The property key.
        key: NodeId,
        /// Feedback vector slot index.
        feedback_slot: u32,
    },

    /// Generic keyed property store with IC feedback.
    StoreKeyedGeneric {
        /// The object to store into.
        object: NodeId,
        /// The property key.
        key: NodeId,
        /// The value to store.
        value: NodeId,
        /// Feedback vector slot index.
        feedback_slot: u32,
    },

    /// Load a global variable by name.
    LoadGlobal {
        /// Index of the name in the constant pool.
        name: u32,
        /// Feedback vector slot index.
        feedback_slot: u32,
    },

    /// Store a value into a global variable by name.
    StoreGlobal {
        /// Index of the name in the constant pool.
        name: u32,
        /// The value to store.
        value: NodeId,
        /// Feedback vector slot index.
        feedback_slot: u32,
    },

    /// Load a value from a scope-context slot.
    LoadContextSlot {
        /// The context object.
        context: NodeId,
        /// Scope depth.
        depth: u32,
        /// Slot index.
        slot: u32,
    },

    /// Store a value into a scope-context slot.
    StoreContextSlot {
        /// The context object.
        context: NodeId,
        /// Scope depth.
        depth: u32,
        /// Slot index.
        slot: u32,
        /// The value to store.
        value: NodeId,
    },

    /// Load from the current (innermost) context slot.
    LoadCurrentContextSlot {
        /// Slot index in the current context.
        slot: u32,
    },

    /// Store into the current (innermost) context slot.
    StoreCurrentContextSlot {
        /// Slot index in the current context.
        slot: u32,
        /// The value to store.
        value: NodeId,
    },

    // ── Calls and constructs ─────────────────────────────────────────────────
    /// Generic function call.
    Call {
        /// The function to call.
        callee: NodeId,
        /// The receiver (`this`).
        receiver: NodeId,
        /// Ordered argument list.
        args: Vec<NodeId>,
        /// Feedback vector slot index.
        feedback_slot: u32,
    },

    /// Specialized `Array.prototype.push` call with a single argument.
    ///
    /// Lowered from `CallProperty1` when the property name is `"push"`.
    /// Unlike generic [`Call`](Self::Call), this is **not** treated as a
    /// user-visible call for global-promotion purposes because native
    /// `push` does not read or write script globals.
    CallArrayPush {
        /// The loaded push method (kept for correctness guard).
        callee: NodeId,
        /// The array receiver (`this`).
        receiver: NodeId,
        /// Single-element argument list (the value to push).
        args: Vec<NodeId>,
        /// Feedback vector slot index.
        feedback_slot: u32,
    },

    /// Call to a statically-known function.
    CallKnownFunction {
        /// The function to call.
        callee: NodeId,
        /// The receiver (`this`).
        receiver: NodeId,
        /// Ordered argument list.
        args: Vec<NodeId>,
    },

    /// Speculative call-loop fusion: replaces a counted loop that calls
    /// `callee()` N times and uses the last result.  The runtime analyses
    /// the callee's bytecode; for simple context-slot increments it
    /// computes the closed form in O(1).  If any check fails (wrong
    /// bytecode shape, non-Smi slot, overflow) it returns JIT_DEOPT and
    /// the interpreter re-runs the loop.
    ///
    /// When `resolved_slot` and `resolved_k` are `Some`, the optimizer
    /// has analysed the callee's bytecodes at JIT compile time and
    /// embedded the fusion pattern constants.  The codegen can then use
    /// a global inline cache to bypass the runtime resolve stub entirely
    /// on cache hit — yielding a zero-call fast path.
    SpeculativeCallFusion {
        /// The closure/function to call.
        callee: NodeId,
        /// Number of times the callee would be called.
        trip_count: u32,
        /// Context-slot index from compile-time bytecode analysis.
        resolved_slot: Option<u32>,
        /// Increment constant `k` from compile-time bytecode analysis.
        resolved_k: Option<i64>,
    },

    /// Speculative replacement for `for (i=0; i<arr.length; i++) sum += arr[i]`.
    ///
    /// Emits a call to a native Rust function that sums all Smi elements
    /// of the array in a tight loop (LLVM-optimised).  Deopts if any
    /// element is not a Smi or the receiver is not an Array.
    SpeculativeSumFusion {
        /// The array to sum over (`JsValue::Array` heap handle).
        array: NodeId,
    },

    /// Speculative replacement for `for (i=0; i<N; i++) arr.push(i)`.
    ///
    /// Emits a call to a native Rust function that pushes a sequential
    /// range of Smi values into the array.  Deopts if the receiver is
    /// not a `JsValue::Array`.
    SpeculativePushFusion {
        /// The array to push into (`JsValue::Array` heap handle).
        array: NodeId,
        /// Number of sequential Smi values to push (0..count).
        count: u32,
    },

    /// Speculative replacement for `for (i=0; i<count; i++) arr[i] = true`.
    ///
    /// Emits a call to a native Rust function that fills a freshly-created
    /// array with `true` values. Deopts if the receiver is not an empty array
    /// or the count is not a non-negative small integer.
    SpeculativeFillTrueFusion {
        /// The array to fill (`JsValue::Array` heap handle).
        array: NodeId,
        /// Number of `true` values to write.
        count: NodeId,
    },

    /// Speculative replacement for `for (i=0; i<count; i++) if (arr[i]) n++`.
    ///
    /// Emits a call to a native Rust function that counts boolean-`true`
    /// elements in a tight loop. Deopts if the receiver is not an array, the
    /// count is not a non-negative small integer, or an inspected element is
    /// not a boolean.
    SpeculativeCountTruthyFusion {
        /// The array to count (`JsValue::Array` heap handle).
        array: NodeId,
        /// Number of elements to inspect.
        count: NodeId,
    },

    /// Call to a builtin function by ID.
    CallBuiltin {
        /// Zero-based builtin function identifier.
        builtin_id: u32,
        /// Ordered argument list.
        args: Vec<NodeId>,
    },

    /// Call to a runtime helper function by ID.
    CallRuntime {
        /// Zero-based runtime function identifier.
        function_id: u32,
        /// Ordered argument list.
        args: Vec<NodeId>,
    },

    /// Generic function call with spread (`f(...args)`).
    CallWithSpread {
        /// The function to call.
        callee: NodeId,
        /// The receiver (`this`).
        receiver: NodeId,
        /// Argument list (last element is the spread).
        args: Vec<NodeId>,
        /// Feedback vector slot index.
        feedback_slot: u32,
    },

    /// Generic `new` expression.
    Construct {
        /// The constructor function.
        constructor: NodeId,
        /// Ordered argument list.
        args: Vec<NodeId>,
        /// Feedback vector slot index.
        feedback_slot: u32,
    },

    /// `new` expression with spread (`new F(...args)`).
    ConstructWithSpread {
        /// The constructor function.
        constructor: NodeId,
        /// Argument list (last element is the spread).
        args: Vec<NodeId>,
        /// Feedback vector slot index.
        feedback_slot: u32,
    },

    // ── Object / array creation ───────────────────────────────────────────────
    /// Create an object literal from a boilerplate.
    CreateObjectLiteral {
        /// Index of the boilerplate descriptor in the constant pool.
        boilerplate_descriptor: u32,
        /// Feedback vector slot index.
        feedback_slot: u32,
        /// Creation flags (e.g. `SHALLOW_PROPERTIES`).
        flags: u32,
    },

    /// Create an object literal and fill its properties in a single call.
    ///
    /// Produced by the optimizer when a [`CreateObjectLiteral`] is
    /// immediately followed by sequential [`StoreNamedGeneric`] stores
    /// whose `object` operand is the literal just created.  Fusing these
    /// into one node eliminates N separate stub calls (and N TLS lookups)
    /// on the hot path.
    ///
    /// At most [`MAX_FUSED_OBJECT_PROPS`] properties are supported; longer
    /// sequences keep the trailing stores as individual nodes.
    ///
    /// [`MAX_FUSED_OBJECT_PROPS`]: crate::compiler::maglev::optimizer::MAX_FUSED_OBJECT_PROPS
    CreateObjectLiteralWithProperties {
        /// Feedback vector slot index.
        feedback_slot: u32,
        /// Creation flags.
        flags: u32,
        /// Constant-pool indices of property names, in template order.
        names: Vec<u32>,
        /// The values to store, in template order.
        values: Vec<NodeId>,
    },

    /// Create an array literal from a boilerplate.
    CreateArrayLiteral {
        /// Index of the boilerplate in the constant pool.
        constant_elements: u32,
        /// Feedback vector slot index.
        feedback_slot: u32,
        /// Creation flags.
        flags: u32,
    },

    /// Create a shallow copy of an object literal.
    CreateShallowObjectLiteral {
        /// Index of the boilerplate descriptor in the constant pool.
        boilerplate_descriptor: u32,
        /// Feedback vector slot index.
        feedback_slot: u32,
        /// Creation flags.
        flags: u32,
    },

    /// Create a shallow copy of an array literal.
    CreateShallowArrayLiteral {
        /// Index of the boilerplate in the constant pool.
        constant_elements: u32,
        /// Feedback vector slot index.
        feedback_slot: u32,
        /// Creation flags.
        flags: u32,
    },

    /// Allocate a new function context.
    CreateFunctionContext {
        /// Index of the scope info in the constant pool.
        scope_info: u32,
        /// Number of context slots.
        slot_count: u32,
    },

    /// Push a new context as the active closure context.
    ///
    /// Takes the new context from [`CreateFunctionContext`] or
    /// [`CreateBlockContext`] and installs it as `RT_CONTEXT`, returning
    /// the previous context so the caller can save it in a register.
    PushContext {
        /// The new context to push.
        context: NodeId,
    },

    /// Pop (restore) a previously saved context as the active closure
    /// context.
    PopContext {
        /// The saved context to restore.
        context: NodeId,
    },

    /// Allocate a new block scope context.
    CreateBlockContext {
        /// Index of the scope info in the constant pool.
        scope_info: u32,
    },

    /// Allocate a new catch scope context.
    CreateCatchContext {
        /// The caught exception value.
        exception: NodeId,
        /// Index of the scope info in the constant pool.
        scope_info: u32,
    },

    /// Allocate a new `with` scope context.
    CreateWithContext {
        /// The `with` object.
        object: NodeId,
        /// Index of the scope info in the constant pool.
        scope_info: u32,
    },

    /// Create a new closure (slow path).
    CreateClosure {
        /// Index of the shared function info in the constant pool.
        shared_function_info: u32,
        /// Feedback vector slot index.
        feedback_slot: u32,
        /// Closure flags.
        flags: u32,
    },

    /// Create a new closure (fast path using feedback).
    FastCreateClosure {
        /// Index of the shared function info in the constant pool.
        shared_function_info: u32,
        /// Feedback vector slot index.
        feedback_slot: u32,
    },

    /// Allocate an empty object literal (`{}`).
    CreateEmptyObjectLiteral,

    /// Allocate an empty array literal (`[]`).
    CreateEmptyArrayLiteral {
        /// Feedback vector slot index.
        feedback_slot: u32,
    },

    /// Create a mapped `arguments` object for sloppy-mode functions.
    CreateMappedArguments,

    /// Create an unmapped `arguments` object for strict-mode functions.
    CreateUnmappedArguments,

    /// Create the rest-parameter array from surplus arguments.
    CreateRestParameter,

    /// Create a RegExp literal.
    CreateRegExpLiteral {
        /// Index of the pattern string in the constant pool.
        pattern: u32,
        /// Feedback vector slot index.
        feedback_slot: u32,
        /// RegExp flags bitmask.
        flags: u32,
    },

    // ── Control-value producers ───────────────────────────────────────────────
    /// SSA Φ-node: selects among values depending on which predecessor was
    /// taken.  The `inputs` list must have the same length as the number of
    /// predecessors of the containing block.
    Phi {
        /// One input [`NodeId`] per predecessor basic block, in predecessor
        /// order.
        inputs: Vec<NodeId>,
    },

    /// Materialise the `arguments` object as a FixedArray.
    ArgumentsElements {
        /// Type of arguments mapping (0 = mapped, 1 = unmapped).
        kind: u32,
    },

    /// Materialise the rest-parameter tail as a FixedArray.
    RestElements {
        /// Zero-based index of the first rest parameter.
        formal_parameter_count: u32,
    },

    /// A virtual (not yet allocated) object used for escape analysis.
    VirtualObject {
        /// Map index identifying the object's shape.
        map: u32,
    },

    // ── Miscellaneous ─────────────────────────────────────────────────────────
    /// Load a template object for a tagged template literal.
    GetTemplateObject {
        /// Index of the template descriptor in the constant pool.
        description: u32,
        /// Feedback vector slot index.
        feedback_slot: u32,
    },

    /// Check whether an object is present in a prototype chain.
    HasInPrototypeChain {
        /// The object to test.
        object: NodeId,
        /// The prototype to search for.
        prototype: NodeId,
    },

    /// Delete a named property (`delete obj.key`).
    DeleteProperty {
        /// The object to modify.
        object: NodeId,
        /// The property key.
        key: NodeId,
        /// Feedback vector slot index.
        feedback_slot: u32,
    },

    /// Prepare a for-in enumeration (returns cache array and length).
    ForInPrepare {
        /// The object being enumerated.
        enumerator: NodeId,
        /// Feedback vector slot index.
        feedback_slot: u32,
    },

    /// Produce the next key during a for-in loop.
    ForInNext {
        /// The object being enumerated.
        receiver: NodeId,
        /// The cache index.
        cache_index: NodeId,
        /// The cache array.
        cache_array: NodeId,
        /// Feedback vector slot index.
        feedback_slot: u32,
    },

    /// Load the length of the enumeration cache.
    LoadEnumCacheLength {
        /// The map object whose cache length is read.
        map: NodeId,
    },

    /// Load a character code from a string at an integer index.
    StringAt {
        /// The string object.
        string: NodeId,
        /// The character index.
        index: NodeId,
    },

    /// Load the `length` property of a string.
    StringLength {
        /// The string object.
        string: NodeId,
    },

    /// Concatenate two strings.
    StringConcat {
        /// The left string.
        left: NodeId,
        /// The right string.
        right: NodeId,
    },

    /// Test whether two strings are equal.
    StringEqual {
        /// The left string.
        left: NodeId,
        /// The right string.
        right: NodeId,
    },

    /// Convert a number to its string representation.
    NumberToString {
        /// The number to convert.
        value: NodeId,
        /// Feedback vector slot index.
        feedback_slot: u32,
    },

    /// The `typeof` operator.
    TypeOf {
        /// The value to inspect.
        value: NodeId,
    },

    /// A `debugger` statement (no-op unless a debugger is attached).
    Debugger,

    /// An unconditional abort — emitted after a deopt bailout.
    Abort {
        /// Reason code (indexes into an engine-internal reason table).
        reason: u32,
    },
}

// ─────────────────────────────────────────────────────────────────────────────
// ControlNode
// ─────────────────────────────────────────────────────────────────────────────

/// A Maglev IR terminator node that ends a [`BasicBlock`].
///
/// Every basic block has exactly one `ControlNode` as its last instruction.
#[derive(Debug, Clone, PartialEq)]
pub enum ControlNode {
    /// Unconditional jump to `target`.
    Jump {
        /// Index of the target [`BasicBlock`] within the graph.
        target: u32,
    },

    /// Conditional branch: if `condition` is truthy jump to `if_true`,
    /// otherwise fall through to `if_false`.
    Branch {
        /// The boolean-valued condition node.
        condition: NodeId,
        /// Block index taken when the condition is true.
        if_true: u32,
        /// Block index taken when the condition is false.
        if_false: u32,
    },

    /// Trigger a deoptimisation.  Control transfers back to the interpreter at
    /// `bytecode_offset` with the given `reason`.
    Deoptimize {
        /// Byte offset in the bytecode array at which to resume interpretation.
        bytecode_offset: u32,
        /// Reason code (indexes into an engine-internal reason table).
        reason: u32,
    },

    /// Return from the function with `value` as the return value.
    Return {
        /// The value to return.
        value: NodeId,
    },
}

// ─────────────────────────────────────────────────────────────────────────────
// BasicBlock
// ─────────────────────────────────────────────────────────────────────────────

/// A Maglev basic block: a straight-line list of [`ValueNode`]s terminated by
/// a single [`ControlNode`].
///
/// # Invariants
///
/// - [`BasicBlock::control`] is `None` during construction and must be set
///   exactly once via [`BasicBlock::set_control`] before the block is
///   considered complete.
/// - Node IDs are graph-global; they are assigned by the owning
///   [`MaglevGraph`] during graph construction.
#[derive(Debug, Clone)]
pub struct BasicBlock {
    /// Zero-based index of this block within the graph.
    pub id: u32,

    /// The value-producing nodes of this block, in execution order.
    pub nodes: Vec<(NodeId, ValueNode)>,

    /// The terminator instruction (set exactly once).
    pub control: Option<ControlNode>,

    /// Predecessor block indices (filled in during CFG construction).
    pub predecessors: Vec<u32>,

    /// Whether this block is a loop header (has at least one back-edge
    /// predecessor).  Set by the optimizer so codegen can align it.
    pub is_loop_header: bool,
}

impl BasicBlock {
    /// Create a new, empty block with the given `id`.
    pub fn new(id: u32) -> Self {
        Self {
            id,
            nodes: Vec::new(),
            control: None,
            predecessors: Vec::new(),
            is_loop_header: false,
        }
    }

    /// Append a [`ValueNode`] to this block with a block-local [`NodeId`] and
    /// return it.
    ///
    /// IDs are assigned sequentially starting at `0` *within this block*,
    /// so they are only unique within the block itself.  When nodes from
    /// multiple blocks must be referenced (e.g. [`ValueNode::Phi`] inputs),
    /// use [`MaglevGraph::add_value_node`] instead, which issues graph-global
    /// [`NodeId`]s.
    pub fn push_value(&mut self, node: ValueNode) -> NodeId {
        let id = NodeId(self.nodes.len() as u32);
        self.nodes.push((id, node));
        id
    }

    /// Append a [`ValueNode`] with an explicit, caller-supplied [`NodeId`].
    ///
    /// This is the low-level primitive used by [`MaglevGraph::add_value_node`]
    /// to attach graph-global IDs.  Callers must ensure that `id` is unique
    /// across the entire graph.
    pub fn push_with_id(&mut self, id: NodeId, node: ValueNode) {
        self.nodes.push((id, node));
    }

    /// Set the terminator [`ControlNode`] for this block.
    ///
    /// # Panics
    ///
    /// Panics if a control node has already been set.
    pub fn set_control(&mut self, control: ControlNode) {
        assert!(
            self.control.is_none(),
            "BasicBlock {}: control node already set",
            self.id
        );
        self.control = Some(control);
    }

    /// Returns `true` if the block has a terminator.
    pub fn is_complete(&self) -> bool {
        self.control.is_some()
    }

    /// Returns the terminator control node, if set.
    pub fn control(&self) -> Option<&ControlNode> {
        self.control.as_ref()
    }

    /// Add a predecessor block index.
    pub fn add_predecessor(&mut self, pred: u32) {
        self.predecessors.push(pred);
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// MaglevGraph
// ─────────────────────────────────────────────────────────────────────────────

/// The complete Maglev control-flow graph for a single JavaScript function.
///
/// Owns all [`BasicBlock`]s and manages the graph-wide [`NodeId`] counter.
///
/// # Block indices
///
/// Block indices (`u32`) used in [`ControlNode::Jump`],
/// [`ControlNode::Branch`], and [`BasicBlock::predecessors`] are zero-based
/// indices into [`MaglevGraph::blocks`].
///
/// # Node IDs
///
/// Use [`MaglevGraph::add_value_node`] to insert nodes with graph-global
/// [`NodeId`]s when cross-block references (e.g. [`ValueNode::Phi`] inputs)
/// are needed.  [`BasicBlock::push_value`] assigns block-local IDs and is
/// sufficient for single-block graphs.
///
/// # Example
///
/// ```
/// use stator_jse::compiler::maglev::ir::{
///     BasicBlock, ControlNode, MaglevGraph, ValueNode,
/// };
///
/// let mut graph = MaglevGraph::new(2);
///
/// // block 0: load param 0 and jump to block 1
/// graph.add_block(BasicBlock::new(0));
/// let _p0 = graph.add_value_node(0, ValueNode::Parameter { index: 0 });
/// graph.block_mut(0).unwrap().set_control(ControlNode::Jump { target: 1 });
///
/// // block 1: return undefined
/// graph.add_block(BasicBlock::new(1));
/// let undef = graph.add_value_node(1, ValueNode::UndefinedConstant).unwrap();
/// graph.block_mut(1).unwrap().set_control(ControlNode::Return { value: undef });
///
/// assert_eq!(graph.blocks().len(), 2);
/// assert_eq!(graph.parameter_count(), 2);
/// ```
#[derive(Debug, Clone)]
pub struct MaglevGraph {
    /// All basic blocks, in insertion order.
    blocks: Vec<BasicBlock>,

    /// Number of formal parameters for the compiled function.
    parameter_count: u32,

    /// Graph-wide node counter, incremented by [`MaglevGraph::add_value_node`].
    next_node_id: u32,

    /// Number of call sites identified as inlining candidates by the
    /// optimizer's inlining analysis pass.
    inline_candidates: u32,

    /// Pre-analysed fusion patterns for closures created in this function.
    ///
    /// Maps a constant-pool index (`shared_function_info` from
    /// [`ValueNode::CreateClosure`] / [`ValueNode::FastCreateClosure`])
    /// to the `(slot_index, k_value)` pair extracted by
    /// [`analyze_fusion_pattern`](crate::compiler::baseline::compiler::jit_runtime::analyze_fusion_pattern)
    /// at graph-build time.  The optimizer consults this table when
    /// creating [`ValueNode::SpeculativeCallFusion`] nodes to embed the
    /// pattern constants directly in the IR.
    closure_fusion_patterns: std::collections::HashMap<u32, (u32, i64)>,

    /// Pre-analysed fusion patterns for *factory* functions — functions that
    /// return a closure matching the fusion pattern.
    ///
    /// When the optimizer detects a loop like:
    /// ```text
    /// var counter = make_counter();
    /// for (...) counter();
    /// ```
    /// and `make_counter` (at CP index K) doesn't match the fusion pattern
    /// itself but returns an inner closure that does, this map stores the
    /// inner closure's `(slot_index, k_value)` keyed by K.
    factory_fusion_patterns: std::collections::HashMap<u32, (u32, i64)>,
}

impl MaglevGraph {
    /// Create an empty graph for a function with `parameter_count` formal
    /// parameters.
    pub fn new(parameter_count: u32) -> Self {
        Self {
            blocks: Vec::new(),
            parameter_count,
            next_node_id: 0,
            inline_candidates: 0,
            closure_fusion_patterns: std::collections::HashMap::new(),
            factory_fusion_patterns: std::collections::HashMap::new(),
        }
    }

    /// Append a [`BasicBlock`] to the graph.
    ///
    /// The block's `id` field should match its final index in the graph; this
    /// is not enforced but callers are expected to maintain the invariant.
    pub fn add_block(&mut self, block: BasicBlock) {
        self.blocks.push(block);
    }

    /// Append a [`ValueNode`] to block `block_idx` using a graph-global
    /// [`NodeId`] and return the assigned ID.
    ///
    /// The returned [`NodeId`] is unique across the entire graph and can be
    /// safely used as an input to nodes in *other* blocks (e.g.
    /// [`ValueNode::Phi`] inputs).
    ///
    /// Returns `None` if `block_idx` is out-of-range.
    pub fn add_value_node(&mut self, block_idx: u32, node: ValueNode) -> Option<NodeId> {
        let id = NodeId(self.next_node_id);
        self.next_node_id += 1;
        let block = self.blocks.get_mut(block_idx as usize)?;
        block.push_with_id(id, node);
        Some(id)
    }

    /// Allocate a fresh graph-global [`NodeId`] without inserting a node.
    ///
    /// The caller is responsible for inserting a node with this ID into the
    /// appropriate block (e.g. via [`BasicBlock::push_with_id`] or
    /// `nodes.insert`).
    pub fn alloc_node_id(&mut self) -> NodeId {
        let id = NodeId(self.next_node_id);
        self.next_node_id += 1;
        id
    }

    /// Return an immutable slice of all blocks.
    pub fn blocks(&self) -> &[BasicBlock] {
        &self.blocks
    }

    /// Return a mutable slice of all blocks.
    pub fn blocks_mut(&mut self) -> &mut [BasicBlock] {
        &mut self.blocks
    }

    /// Return the number of formal parameters.
    pub fn parameter_count(&self) -> u32 {
        self.parameter_count
    }

    /// Look up a block by its index.  Returns `None` if the index is
    /// out-of-range.
    pub fn block(&self, index: u32) -> Option<&BasicBlock> {
        self.blocks.get(index as usize)
    }

    /// Look up a block mutably by its index.  Returns `None` if the index is
    /// out-of-range.
    pub fn block_mut(&mut self, index: u32) -> Option<&mut BasicBlock> {
        self.blocks.get_mut(index as usize)
    }

    /// Return the entry block (block 0), if present.
    pub fn entry_block(&self) -> Option<&BasicBlock> {
        self.blocks.first()
    }

    /// Return `true` if the graph is *degenerate*: the entry block
    /// immediately deoptimises without performing any meaningful
    /// computation.  Compiling such a graph produces JIT code that
    /// always returns `JIT_DEOPT`, which cascades deoptimisation to
    /// callers and severely degrades performance.
    ///
    /// A graph is considered degenerate when the entry block's
    /// terminator is [`ControlNode::Deoptimize`] and the block contains
    /// no value nodes other than constants.
    pub fn is_degenerate(&self) -> bool {
        let Some(entry) = self.entry_block() else {
            return true;
        };
        let Some(ctrl) = entry.control() else {
            return false;
        };
        if !matches!(ctrl, ControlNode::Deoptimize { .. }) {
            return false;
        }
        // Entry block immediately deoptimises — check that there are
        // no real value nodes (constants don't count).
        entry.nodes.iter().all(|(_, n)| {
            matches!(
                n,
                ValueNode::SmiConstant { .. }
                    | ValueNode::Float64Constant { .. }
                    | ValueNode::UndefinedConstant
                    | ValueNode::TrueConstant
                    | ValueNode::FalseConstant
                    | ValueNode::NullConstant
            )
        })
    }

    /// Set the number of inlining candidate call sites identified by the
    /// optimizer.
    pub fn set_inline_candidates(&mut self, count: u32) {
        self.inline_candidates = count;
    }

    /// Return the number of inlining candidate call sites.
    pub fn inline_candidates(&self) -> u32 {
        self.inline_candidates
    }

    /// Return the pre-analysed fusion patterns for closures in this function.
    pub fn closure_fusion_patterns(&self) -> &std::collections::HashMap<u32, (u32, i64)> {
        &self.closure_fusion_patterns
    }

    /// Record a fusion pattern `(slot_index, k_value)` for the closure
    /// whose `shared_function_info` lives at constant-pool index `cp_idx`.
    pub fn set_closure_fusion_pattern(&mut self, cp_idx: u32, slot: u32, k: i64) {
        self.closure_fusion_patterns.insert(cp_idx, (slot, k));
    }

    /// Return the pre-analysed factory fusion patterns.
    pub fn factory_fusion_patterns(&self) -> &std::collections::HashMap<u32, (u32, i64)> {
        &self.factory_fusion_patterns
    }

    /// Record a factory fusion pattern: calling the function at `cp_idx`
    /// returns a closure whose body matches `(slot, k)`.
    pub fn set_factory_fusion_pattern(&mut self, cp_idx: u32, slot: u32, k: i64) {
        self.factory_fusion_patterns.insert(cp_idx, (slot, k));
    }

    /// Look up a [`ValueNode`] by its [`NodeId`].
    ///
    /// Performs a linear scan of all blocks; intended for compile-time
    /// lookups, not hot-path code.
    pub fn node(&self, id: NodeId) -> Option<&ValueNode> {
        for block in &self.blocks {
            for (nid, node) in &block.nodes {
                if *nid == id {
                    return Some(node);
                }
            }
        }
        None
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Tests
// ─────────────────────────────────────────────────────────────────────────────

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

    // ── Helper ───────────────────────────────────────────────────────────────

    /// Build a minimal one-block graph that returns `undefined`.
    fn single_block_graph() -> MaglevGraph {
        let mut graph = MaglevGraph::new(0);
        let mut block = BasicBlock::new(0);
        let undef = block.push_value(ValueNode::UndefinedConstant);
        block.set_control(ControlNode::Return { value: undef });
        graph.add_block(block);
        graph
    }

    // ── BasicBlock ────────────────────────────────────────────────────────────

    #[test]
    fn test_basic_block_starts_empty() {
        let block = BasicBlock::new(7);
        assert_eq!(block.id, 7);
        assert!(block.nodes.is_empty());
        assert!(block.control.is_none());
        assert!(!block.is_complete());
    }

    #[test]
    fn test_basic_block_push_assigns_sequential_ids() {
        let mut block = BasicBlock::new(0);
        let a = block.push_value(ValueNode::SmiConstant { value: 1 });
        let b = block.push_value(ValueNode::SmiConstant { value: 2 });
        let c = block.push_value(ValueNode::SmiConstant { value: 3 });
        assert_eq!(a, NodeId(0));
        assert_eq!(b, NodeId(1));
        assert_eq!(c, NodeId(2));
        assert_eq!(block.nodes.len(), 3);
    }

    #[test]
    fn test_basic_block_set_control_completes_block() {
        let mut block = BasicBlock::new(0);
        let undef = block.push_value(ValueNode::UndefinedConstant);
        assert!(!block.is_complete());
        block.set_control(ControlNode::Return { value: undef });
        assert!(block.is_complete());
    }

    #[test]
    #[should_panic(expected = "control node already set")]
    fn test_basic_block_set_control_twice_panics() {
        let mut block = BasicBlock::new(0);
        let undef = block.push_value(ValueNode::UndefinedConstant);
        block.set_control(ControlNode::Return { value: undef });
        // Second call must panic.
        block.set_control(ControlNode::Return { value: NodeId(0) });
    }

    #[test]
    fn test_basic_block_predecessors() {
        let mut block = BasicBlock::new(3);
        block.add_predecessor(0);
        block.add_predecessor(1);
        assert_eq!(block.predecessors, vec![0, 1]);
    }

    // ── MaglevGraph ───────────────────────────────────────────────────────────

    #[test]
    fn test_graph_new_empty() {
        let graph = MaglevGraph::new(3);
        assert_eq!(graph.parameter_count(), 3);
        assert!(graph.blocks().is_empty());
        assert!(graph.entry_block().is_none());
        assert!(graph.block(0).is_none());
    }

    #[test]
    fn test_graph_add_and_retrieve_blocks() {
        let graph = single_block_graph();
        assert_eq!(graph.blocks().len(), 1);
        let entry = graph.entry_block().unwrap();
        assert_eq!(entry.id, 0);
    }

    #[test]
    fn test_graph_block_out_of_range_returns_none() {
        let graph = single_block_graph();
        assert!(graph.block(99).is_none());
    }

    // ── ValueNode — constants ─────────────────────────────────────────────────

    #[test]
    fn test_smi_constant_node() {
        let mut block = BasicBlock::new(0);
        let id = block.push_value(ValueNode::SmiConstant { value: 42 });
        let (nid, node) = &block.nodes[0];
        assert_eq!(*nid, id);
        assert_eq!(*node, ValueNode::SmiConstant { value: 42 });
    }

    #[test]
    fn test_float64_constant_node() {
        let mut block = BasicBlock::new(0);
        let id = block.push_value(ValueNode::Float64Constant { value: 3.14 });
        let (_, node) = &block.nodes[0];
        assert_eq!(id, NodeId(0));
        if let ValueNode::Float64Constant { value } = node {
            assert!((value - 3.14).abs() < f64::EPSILON);
        } else {
            panic!("expected Float64Constant");
        }
    }

    #[test]
    fn test_true_false_null_undefined_constants() {
        let mut block = BasicBlock::new(0);
        block.push_value(ValueNode::TrueConstant);
        block.push_value(ValueNode::FalseConstant);
        block.push_value(ValueNode::NullConstant);
        block.push_value(ValueNode::UndefinedConstant);
        assert_eq!(block.nodes.len(), 4);
        assert_eq!(block.nodes[0].1, ValueNode::TrueConstant);
        assert_eq!(block.nodes[1].1, ValueNode::FalseConstant);
        assert_eq!(block.nodes[2].1, ValueNode::NullConstant);
        assert_eq!(block.nodes[3].1, ValueNode::UndefinedConstant);
    }

    #[test]
    fn test_string_constant_node() {
        let mut block = BasicBlock::new(0);
        block.push_value(ValueNode::StringConstant {
            value: "hello".to_string(),
        });
        if let ValueNode::StringConstant { value } = &block.nodes[0].1 {
            assert_eq!(value, "hello");
        } else {
            panic!("expected StringConstant");
        }
    }

    // ── ValueNode — parameters ────────────────────────────────────────────────

    #[test]
    fn test_parameter_node() {
        let mut block = BasicBlock::new(0);
        let id = block.push_value(ValueNode::Parameter { index: 2 });
        assert_eq!(id, NodeId(0));
        assert_eq!(block.nodes[0].1, ValueNode::Parameter { index: 2 });
    }

    // ── ValueNode — arithmetic ────────────────────────────────────────────────

    #[test]
    fn test_checked_smi_add_node() {
        let mut block = BasicBlock::new(0);
        let a = block.push_value(ValueNode::SmiConstant { value: 10 });
        let b = block.push_value(ValueNode::SmiConstant { value: 20 });
        let sum = block.push_value(ValueNode::CheckedSmiAdd { left: a, right: b });
        assert_eq!(sum, NodeId(2));
        if let ValueNode::CheckedSmiAdd { left, right } = block.nodes[2].1 {
            assert_eq!(left, a);
            assert_eq!(right, b);
        } else {
            panic!("expected CheckedSmiAdd");
        }
    }

    #[test]
    fn test_float64_arithmetic_nodes() {
        let mut block = BasicBlock::new(0);
        let x = block.push_value(ValueNode::Float64Constant { value: 1.0 });
        let y = block.push_value(ValueNode::Float64Constant { value: 2.0 });
        let add = block.push_value(ValueNode::Float64Add { left: x, right: y });
        let sub = block.push_value(ValueNode::Float64Subtract { left: x, right: y });
        let mul = block.push_value(ValueNode::Float64Multiply { left: x, right: y });
        let div = block.push_value(ValueNode::Float64Divide { left: x, right: y });
        assert_eq!(add, NodeId(2));
        assert_eq!(sub, NodeId(3));
        assert_eq!(mul, NodeId(4));
        assert_eq!(div, NodeId(5));
    }

    // ── ValueNode — Phi ───────────────────────────────────────────────────────

    #[test]
    fn test_phi_node() {
        // A Φ with two inputs (one per predecessor).
        let mut block = BasicBlock::new(2);
        let a = NodeId(0);
        let b = NodeId(1);
        let phi = block.push_value(ValueNode::Phi { inputs: vec![a, b] });
        assert_eq!(phi, NodeId(0));
        if let ValueNode::Phi { inputs } = &block.nodes[0].1 {
            assert_eq!(inputs, &[NodeId(0), NodeId(1)]);
        } else {
            panic!("expected Phi");
        }
    }

    // ── ValueNode — load/store ─────────────────────────────────────────────────

    #[test]
    fn test_load_field_node() {
        let mut block = BasicBlock::new(0);
        let obj = block.push_value(ValueNode::Parameter { index: 0 });
        let field = block.push_value(ValueNode::LoadField {
            object: obj,
            offset: 8,
        });
        assert_eq!(field, NodeId(1));
        assert_eq!(
            block.nodes[1].1,
            ValueNode::LoadField {
                object: obj,
                offset: 8
            }
        );
    }

    #[test]
    fn test_store_field_node() {
        let mut block = BasicBlock::new(0);
        let obj = block.push_value(ValueNode::Parameter { index: 0 });
        let val = block.push_value(ValueNode::SmiConstant { value: 99 });
        let store = block.push_value(ValueNode::StoreField {
            object: obj,
            offset: 16,
            value: val,
        });
        assert_eq!(store, NodeId(2));
    }

    // ── ValueNode — Call ──────────────────────────────────────────────────────

    #[test]
    fn test_call_node() {
        let mut block = BasicBlock::new(0);
        let callee = block.push_value(ValueNode::Parameter { index: 0 });
        let recv = block.push_value(ValueNode::UndefinedConstant);
        let arg0 = block.push_value(ValueNode::SmiConstant { value: 1 });
        let call = block.push_value(ValueNode::Call {
            callee,
            receiver: recv,
            args: vec![arg0],
            feedback_slot: 0,
        });
        assert_eq!(call, NodeId(3));
        if let ValueNode::Call { args, .. } = &block.nodes[3].1 {
            assert_eq!(args.len(), 1);
            assert_eq!(args[0], arg0);
        } else {
            panic!("expected Call");
        }
    }

    // ── ControlNode ───────────────────────────────────────────────────────────

    #[test]
    fn test_control_jump() {
        let mut block = BasicBlock::new(0);
        block.push_value(ValueNode::UndefinedConstant);
        block.set_control(ControlNode::Jump { target: 1 });
        assert_eq!(block.control, Some(ControlNode::Jump { target: 1 }));
    }

    #[test]
    fn test_control_branch() {
        let mut block = BasicBlock::new(0);
        let cond = block.push_value(ValueNode::TrueConstant);
        block.set_control(ControlNode::Branch {
            condition: cond,
            if_true: 1,
            if_false: 2,
        });
        if let Some(ControlNode::Branch {
            condition,
            if_true,
            if_false,
        }) = block.control
        {
            assert_eq!(condition, cond);
            assert_eq!(if_true, 1);
            assert_eq!(if_false, 2);
        } else {
            panic!("expected Branch");
        }
    }

    #[test]
    fn test_control_deoptimize() {
        let mut block = BasicBlock::new(0);
        block.push_value(ValueNode::UndefinedConstant);
        block.set_control(ControlNode::Deoptimize {
            bytecode_offset: 42,
            reason: 7,
        });
        assert_eq!(
            block.control,
            Some(ControlNode::Deoptimize {
                bytecode_offset: 42,
                reason: 7,
            })
        );
    }

    #[test]
    fn test_control_return() {
        let mut block = BasicBlock::new(0);
        let undef = block.push_value(ValueNode::UndefinedConstant);
        block.set_control(ControlNode::Return { value: undef });
        assert_eq!(
            block.control,
            Some(ControlNode::Return { value: NodeId(0) })
        );
    }

    // ── Full graph construction ───────────────────────────────────────────────

    #[test]
    fn test_construct_return_parameter_graph() {
        // graph: entry block returns parameter 0
        let mut graph = MaglevGraph::new(1);
        let mut entry = BasicBlock::new(0);
        let p0 = entry.push_value(ValueNode::Parameter { index: 0 });
        entry.set_control(ControlNode::Return { value: p0 });
        graph.add_block(entry);

        assert_eq!(graph.blocks().len(), 1);
        let b = graph.block(0).unwrap();
        assert_eq!(b.nodes.len(), 1);
        assert!(b.is_complete());
    }

    #[test]
    fn test_construct_two_block_graph_with_jump() {
        // block 0 → jump → block 1 → return
        let mut graph = MaglevGraph::new(0);

        let mut b0 = BasicBlock::new(0);
        b0.push_value(ValueNode::UndefinedConstant);
        b0.set_control(ControlNode::Jump { target: 1 });
        graph.add_block(b0);

        let mut b1 = BasicBlock::new(1);
        let undef = b1.push_value(ValueNode::UndefinedConstant);
        b1.set_control(ControlNode::Return { value: undef });
        graph.add_block(b1);

        assert_eq!(graph.blocks().len(), 2);
        assert_eq!(
            graph.block(0).unwrap().control,
            Some(ControlNode::Jump { target: 1 })
        );
    }

    #[test]
    fn test_construct_branch_graph() {
        // block 0: branch on param0 → block 1 (true) / block 2 (false)
        // block 1: return SmiConstant(1)
        // block 2: return SmiConstant(0)
        let mut graph = MaglevGraph::new(1);

        let mut b0 = BasicBlock::new(0);
        let cond = b0.push_value(ValueNode::Parameter { index: 0 });
        b0.set_control(ControlNode::Branch {
            condition: cond,
            if_true: 1,
            if_false: 2,
        });
        graph.add_block(b0);

        let mut b1 = BasicBlock::new(1);
        let one = b1.push_value(ValueNode::SmiConstant { value: 1 });
        b1.set_control(ControlNode::Return { value: one });
        b1.add_predecessor(0);
        graph.add_block(b1);

        let mut b2 = BasicBlock::new(2);
        let zero = b2.push_value(ValueNode::SmiConstant { value: 0 });
        b2.set_control(ControlNode::Return { value: zero });
        b2.add_predecessor(0);
        graph.add_block(b2);

        assert_eq!(graph.blocks().len(), 3);
        assert_eq!(graph.block(1).unwrap().predecessors, vec![0]);
        assert_eq!(graph.block(2).unwrap().predecessors, vec![0]);
    }

    #[test]
    fn test_construct_diamond_with_phi() {
        // Classic SSA diamond using graph-global NodeIds so that the Phi inputs
        // from different blocks are unambiguous.
        //
        //   entry → if-true / if-false → merge (Φ) → return
        let mut graph = MaglevGraph::new(1);

        // block 0: entry – branch on param0
        graph.add_block(BasicBlock::new(0));
        let cond = graph
            .add_value_node(0, ValueNode::Parameter { index: 0 })
            .unwrap();
        graph
            .block_mut(0)
            .unwrap()
            .set_control(ControlNode::Branch {
                condition: cond,
                if_true: 1,
                if_false: 2,
            });

        // block 1: if-true – produce SmiConstant(1) → jump merge
        graph.add_block(BasicBlock::new(1));
        graph.block_mut(1).unwrap().add_predecessor(0);
        let one = graph
            .add_value_node(1, ValueNode::SmiConstant { value: 1 })
            .unwrap();
        graph
            .block_mut(1)
            .unwrap()
            .set_control(ControlNode::Jump { target: 3 });

        // block 2: if-false – produce SmiConstant(0) → jump merge
        graph.add_block(BasicBlock::new(2));
        graph.block_mut(2).unwrap().add_predecessor(0);
        let zero = graph
            .add_value_node(2, ValueNode::SmiConstant { value: 0 })
            .unwrap();
        graph
            .block_mut(2)
            .unwrap()
            .set_control(ControlNode::Jump { target: 3 });

        // block 3: merge – Φ([one, zero]) → return
        graph.add_block(BasicBlock::new(3));
        graph.block_mut(3).unwrap().add_predecessor(1);
        graph.block_mut(3).unwrap().add_predecessor(2);
        let phi = graph
            .add_value_node(
                3,
                ValueNode::Phi {
                    inputs: vec![one, zero],
                },
            )
            .unwrap();
        graph
            .block_mut(3)
            .unwrap()
            .set_control(ControlNode::Return { value: phi });

        // The four global IDs must be distinct.
        assert_ne!(cond, one);
        assert_ne!(cond, zero);
        assert_ne!(one, zero);
        assert_ne!(phi, one);
        assert_ne!(phi, zero);

        assert_eq!(graph.blocks().len(), 4);
        let merge = graph.block(3).unwrap();
        assert_eq!(merge.predecessors, vec![1, 2]);
        if let ValueNode::Phi { inputs } = &merge.nodes[0].1 {
            assert_eq!(inputs, &[one, zero]);
        } else {
            panic!("expected Phi in merge block");
        }
    }

    #[test]
    fn test_add_value_node_global_ids_are_unique_across_blocks() {
        // Nodes in different blocks must receive distinct graph-global IDs.
        let mut graph = MaglevGraph::new(0);
        graph.add_block(BasicBlock::new(0));
        graph.add_block(BasicBlock::new(1));

        let a = graph
            .add_value_node(0, ValueNode::UndefinedConstant)
            .unwrap();
        let b = graph
            .add_value_node(0, ValueNode::UndefinedConstant)
            .unwrap();
        let c = graph
            .add_value_node(1, ValueNode::UndefinedConstant)
            .unwrap();

        assert_ne!(a, b);
        assert_ne!(a, c);
        assert_ne!(b, c);
    }

    #[test]
    fn test_add_value_node_out_of_range_returns_none() {
        let mut graph = MaglevGraph::new(0);
        assert!(
            graph
                .add_value_node(99, ValueNode::UndefinedConstant)
                .is_none()
        );
    }

    #[test]
    fn test_graph_blocks_mut() {
        let mut graph = single_block_graph();
        graph.blocks_mut()[0].id = 99;
        assert_eq!(graph.block(0).unwrap().id, 99);
    }

    #[test]
    fn test_graph_block_mut() {
        let mut graph = single_block_graph();
        {
            let b = graph.block_mut(0).unwrap();
            b.add_predecessor(5);
        }
        assert_eq!(graph.block(0).unwrap().predecessors, vec![5]);
    }
}