ferrugocc 0.4.0

An experimental C compiler and obfuscating compiler written in Rust, targeting x86_64 SysV ABI
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
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
//! TACKY IR 難読化パス
//!
//! TACKY → TACKY の変換を行う難読化パス(最適化の逆)。
//! `--fobfuscate` フラグで有効化される。
//!
//! # パス適用順序(TACKY IR レベル)
//! 1. **Library Function Obfuscation**(ライブラリ関数難読化)— `strlen`, `strcmp`, `strcpy`,
//!    `memcpy`, `memset`, `memcmp`, `strncmp`, `strncpy`, `strchr`, `strcat` の既知ライブラリ関数を
//!    等価な自前実装に差し替え、FLIRT シグネチャマッチングを無効化する
//! 2. **Function Inlining**(関数インライン展開)— 呼び出し先の本体を呼び出し元に埋め込む
//! 3. **Constant Encoding**(定数の間接化)— 即値を `a * b + c` の実行時計算に置換
//! 4. **Arithmetic Substitution**(算術置換)— Add/Subtract を多段計算に展開
//! 5. **Junk Code Insertion**(ジャンクコード挿入)— 4命令ごとに dead computation を挿入
//! 6. **Opaque Predicates**(不透明述語)— 4パターンの常真条件分岐で値生成命令を囲む
//!    - パターン 0: `x*(x+1) % 2 == 0`(連続整数の積は偶数)
//!    - パターン 1: `!(x² + 1 > 0)`(x²+1 は常に正)
//!    - パターン 2: `(x+1)² - x² - 1 - 2x == 0`(代数恒等式)
//!    - パターン 3: `(x³ - x) % 3 == 0`(連続3整数の積は3の倍数)
//! 7. **Function Outlining**(関数アウトライン化)— コード断片を新しい関数に切り出す
//! 8. **VM Virtualization**(VM仮想化)— 適格な関数をバイトコード+VMインタプリタに変換。
//!    `.data` にバイトコード配列とハンドラテーブルを配置し、ディスパッチループで間接実行
//! 9. **Control Flow Flattening**(制御フロー平坦化)— 基本ブロックをジャンプテーブル
//!    + 状態エンコードの dispatch ループに変換。IDA 等の CFG 復元を破壊する。
//!    - ジャンプテーブル: `.data` セクションにブロックラベルの配列を配置し `jmp *%rax` で分岐
//!    - 状態エンコード: `encoded = index * 37 + 0xCAFE` のアフィン変換で状態変数を符号化
//! 10. **String Encryption**(文字列暗号化)— 文字列リテラルを加算暗号化し main() で復号
//! 11. **OPSEC Sanitization**(OPSEC 衛生化)— シンボル名をリネームし、疑わしい文字列を警告
//!
//! Pass 10 は他のパスの後に適用する。復号コードが CFF 等で破壊されるのを防ぐため。
//! Pass 11(OPSEC)は全パスの最後に適用する。シンボルリネームが他のパスに影響しないよう。
//!
//! # ASM レベル難読化(codegen/mod.rs で適用、レジスタ割り当て後)
//! - **Stack Frame Obfuscation**: 偽のスタックスロットと偽の read/write 操作を挿入し偽ローカル変数を生成
//! - **Register Shuffle**: dead な `movq` を挿入し偽のレジスタ間依存関係を生成(R10/R11 使用)
//! - **Instruction Substitution**: 命令を意味的に等価な別の命令列に置換しパターンマッチングを妨害
//! - **Anti-Disassembly**: 無条件ジャンプ直後に `0xE8`(call opcode)を挿入し命令境界認識を破壊
//! - **Indirect Calls**: `call func` を `lea func(%rip), %r10; call *%r10` に変換

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

use super::tacky_ast::*;
use crate::error::CompileError;
use crate::obfuscation::{ObfuscationConfig, OpsecPolicy};
use crate::parse::ast::Type;

/// 難読化コンテキスト — temp 変数とラベルのカウンタを管理
struct ObfCtx {
    tmp_counter: usize,
    label_counter: usize,
    inline_counter: usize,
    outline_counter: usize,
    vm_counter: usize,
    opsec_counter: usize,
}

impl ObfCtx {
    fn new() -> Self {
        ObfCtx {
            tmp_counter: 0,
            label_counter: 0,
            inline_counter: 0,
            outline_counter: 0,
            vm_counter: 0,
            opsec_counter: 0,
        }
    }

    /// 新しい一時変数名を生成(`obf_tmp.N`)
    fn fresh_tmp(&mut self) -> String {
        let name = format!("obf_tmp.{}", self.tmp_counter);
        self.tmp_counter += 1;
        name
    }

    /// 新しいラベル名を生成(`.Lobf_N`)
    fn fresh_label(&mut self) -> String {
        let name = format!(".Lobf_{}", self.label_counter);
        self.label_counter += 1;
        name
    }
}

/// 難読化パスのエントリポイント
///
/// パス適用順序:
/// 1. Pass 15: ライブラリ関数難読化(自前実装が後続の全パスで難読化される)
/// 2. Pass 12: 関数インライン展開(インラインされたコードが後続パスで難読化される)
/// 3. Pass 1-4: 定数間接化・算術置換・ジャンクコード・不透明述語
/// 4. Pass 13: 関数アウトライン化(難読化済みコードが関数に切り出される)
/// 5. Pass 14: VM仮想化(適格な関数をバイトコード+VMインタプリタに変換)
/// 6. Pass 5: CFF(VMディスパッチループを含む全関数に適用 → 二重間接化)
/// 7. Pass 16a: OPSEC 文字列リーク警告(暗号化前に検査)
/// 8. Pass 6: 文字列暗号化(復号コードが CFF 等で破壊されるのを防ぐ)
/// 9. Pass 16b: OPSEC シンボル難読化(全パスの最後)
pub fn obfuscate(
    program: TackyProgram,
    config: &ObfuscationConfig,
) -> crate::error::Result<TackyProgram> {
    let mut program = program;

    let mut ctx = ObfCtx::new();

    // Pass 15: ライブラリ関数難読化(全パスの前 → 自前実装が後続の全パスで難読化される)
    if config.lib_obfuscate {
        replace_library_functions(&mut program, &mut ctx);
    }

    // Pass 12: 関数インライン展開(全パスの前 → インラインされたコードが後続で難読化される)
    if config.func_inline {
        inline_functions(&mut program, &mut ctx, config.func_inline_freq);
    }

    // Pass 1-4: 関数ごとの変換
    for func in &mut program.functions {
        // Pass 1: 定数の間接化
        if config.constant_encoding {
            func.body = constant_encoding(
                std::mem::take(&mut func.body),
                &mut ctx,
                &mut func.var_types,
            );
        }

        // Pass 2: 算術置換(Add/Subtract を多段計算に展開)
        if config.arith_subst {
            func.body = arithmetic_substitution(
                std::mem::take(&mut func.body),
                &mut ctx,
                &mut func.var_types,
                config.arith_freq,
            );
        }

        // Pass 3: ジャンクコード挿入
        if config.junk_code {
            func.body = junk_code_insertion(
                std::mem::take(&mut func.body),
                &mut ctx,
                &mut func.var_types,
                config.junk_freq,
            );
        }

        // Pass 4: 不透明述語(多様化パターン)
        if config.opaque_predicates {
            func.body = opaque_predicates(
                std::mem::take(&mut func.body),
                &mut ctx,
                &mut func.var_types,
                config.pred_freq,
            );
        }
    }

    // Pass 13: 関数アウトライン化(Pass 1-4 の後、CFF の前)
    if config.func_outline {
        outline_functions(&mut program, &mut ctx, config.func_outline_min_block);
    }

    // Pass 14: VM仮想化(適格な関数をバイトコード+VMインタプリタに変換)
    if config.vm_virtualize {
        vm_virtualize(&mut program, &mut ctx);
    }

    // Pass 5: CFF(VMディスパッチループを含む全関数に適用 → 二重間接化)
    for func in &mut program.functions {
        if config.cff {
            func.body = control_flow_flattening(
                std::mem::take(&mut func.body),
                &mut ctx,
                &mut func.var_types,
                &mut program.static_vars,
                config.cff_a,
                config.cff_b,
            );
        }
    }

    // Pass 16a: OPSEC 文字列リーク警告(暗号化前に検査)
    if config.opsec_warn
        && let Err(count) = opsec_warn_strings(&program, config.opsec_policy)
    {
        return Err(CompileError::OpsecViolation(format!(
            "{count} string violation(s) detected"
        )));
    }

    // Pass 6: 文字列暗号化(他のパスの後に適用 — 復号コードが CFF 等で壊されるのを防ぐ)
    if config.string_encryption {
        string_encryption(&mut program, &mut ctx, config.string_key);
    }

    // Pass 16b: OPSEC シンボル難読化(全パスの最後)
    if config.opsec {
        opsec_sanitize(
            &mut program,
            &mut ctx,
            config.opsec_strip,
            config.preserve_globals,
        );
    }

    Ok(program)
}

// ─────────────────────────────────────────────────────────────
// Pass 15: Library Function Obfuscation(ライブラリ関数難読化)
// ─────────────────────────────────────────────────────────────

/// ライブラリ関数の呼び出しを自前実装に差し替える。
///
/// FLIRT シグネチャ対策: `strlen` 等の既知ライブラリ関数を等価な
/// TACKY IR 実装に置換し、後続の難読化パスで認識不能にする。
fn replace_library_functions(program: &mut TackyProgram, ctx: &mut ObfCtx) {
    /// 差し替え対象のライブラリ関数名
    const TARGET_FUNCTIONS: &[&str] = &[
        "strlen", "strcmp", "strcpy", "memcpy", "memset", "memcmp", "strncmp", "strncpy", "strchr",
        "strcat",
    ];

    // 全 FunCall を走査し、対象関数名を収集
    let mut needed: HashSet<String> = HashSet::new();
    for func in &program.functions {
        for instr in &func.body {
            if let TackyInstruction::FunCall { name, .. } = instr
                && TARGET_FUNCTIONS.contains(&name.as_str())
            {
                needed.insert(name.clone());
            }
        }
    }

    if needed.is_empty() {
        return;
    }

    // 対象ごとに自前実装を生成(ソート済みで決定的な順序)
    let mut generated: HashMap<String, String> = HashMap::new(); // original -> obf name
    let mut new_functions: Vec<TackyFunction> = Vec::new();

    let mut needed_sorted: Vec<String> = needed.into_iter().collect();
    needed_sorted.sort();
    for name in &needed_sorted {
        match name.as_str() {
            "strlen" => {
                let obf_name = "_obf_strlen".to_string();
                new_functions.push(generate_strlen(ctx, &obf_name));
                generated.insert(name.clone(), obf_name);
            }
            "strcmp" => {
                let obf_name = "_obf_strcmp".to_string();
                new_functions.push(generate_strcmp(ctx, &obf_name));
                generated.insert(name.clone(), obf_name);
            }
            "strcpy" => {
                let obf_name = "_obf_strcpy".to_string();
                new_functions.push(generate_strcpy(ctx, &obf_name));
                generated.insert(name.clone(), obf_name);
            }
            "memcpy" => {
                let obf_name = "_obf_memcpy".to_string();
                new_functions.push(generate_memcpy(ctx, &obf_name));
                generated.insert(name.clone(), obf_name);
            }
            "memset" => {
                let obf_name = "_obf_memset".to_string();
                new_functions.push(generate_memset(ctx, &obf_name));
                generated.insert(name.clone(), obf_name);
            }
            "memcmp" => {
                let obf_name = "_obf_memcmp".to_string();
                new_functions.push(generate_memcmp(ctx, &obf_name));
                generated.insert(name.clone(), obf_name);
            }
            "strncmp" => {
                let obf_name = "_obf_strncmp".to_string();
                new_functions.push(generate_strncmp(ctx, &obf_name));
                generated.insert(name.clone(), obf_name);
            }
            "strncpy" => {
                let obf_name = "_obf_strncpy".to_string();
                new_functions.push(generate_strncpy(ctx, &obf_name));
                generated.insert(name.clone(), obf_name);
            }
            "strchr" => {
                let obf_name = "_obf_strchr".to_string();
                new_functions.push(generate_strchr(ctx, &obf_name));
                generated.insert(name.clone(), obf_name);
            }
            "strcat" => {
                let obf_name = "_obf_strcat".to_string();
                new_functions.push(generate_strcat(ctx, &obf_name));
                generated.insert(name.clone(), obf_name);
            }
            _ => {}
        }
    }

    // FunCall のターゲットを差し替え
    for func in &mut program.functions {
        for instr in &mut func.body {
            if let TackyInstruction::FunCall { name, .. } = instr
                && let Some(obf_name) = generated.get(name)
            {
                *name = obf_name.clone();
            }
        }
    }

    // 生成した関数を追加
    program.functions.extend(new_functions);
}

/// `strlen` の等価な TACKY IR 実装を生成する。
///
/// ```c
/// long _obf_strlen(const char *s) {
///     long len = 0;
///     while (s[len] != '\0')
///         len = len + 1;
///     return len;
/// }
/// ```
fn generate_strlen(ctx: &mut ObfCtx, name: &str) -> TackyFunction {
    let p = "p".to_string();
    let len = ctx.fresh_tmp(); // loop counter (Long)
    let ptr = ctx.fresh_tmp(); // ptr = s + len (Pointer(Char))
    let ch = ctx.fresh_tmp(); // *ptr (Char)
    let ci = ctx.fresh_tmp(); // zero-extended to Int

    let loop_start = ctx.fresh_label();
    let loop_end = ctx.fresh_label();

    let mut var_types = HashMap::new();
    var_types.insert(p.clone(), Type::Pointer(Box::new(Type::Char)));
    var_types.insert(len.clone(), Type::Long);
    var_types.insert(ptr.clone(), Type::Pointer(Box::new(Type::Char)));
    var_types.insert(ch.clone(), Type::Char);
    var_types.insert(ci.clone(), Type::Int);

    let body = vec![
        // len = 0
        TackyInstruction::Copy {
            src: TackyVal::Constant(TackyConst::Long(0)),
            dst: TackyVal::Var(len.clone()),
        },
        // loop_start:
        TackyInstruction::Label(loop_start.clone()),
        // ptr = s + len
        TackyInstruction::AddPtr {
            ptr: TackyVal::Var(p.clone()),
            index: TackyVal::Var(len.clone()),
            scale: 1,
            dst: TackyVal::Var(ptr.clone()),
        },
        // ch = *ptr
        TackyInstruction::Load {
            src_ptr: TackyVal::Var(ptr.clone()),
            dst: TackyVal::Var(ch.clone()),
        },
        // ci = (int)ch
        TackyInstruction::ZeroExtend {
            src: TackyVal::Var(ch.clone()),
            dst: TackyVal::Var(ci.clone()),
        },
        // if ci == 0, break
        TackyInstruction::JumpIfZero {
            condition: TackyVal::Var(ci.clone()),
            target: loop_end.clone(),
        },
        // len = len + 1
        TackyInstruction::Binary {
            op: TackyBinaryOp::Add,
            left: TackyVal::Var(len.clone()),
            right: TackyVal::Constant(TackyConst::Long(1)),
            dst: TackyVal::Var(len.clone()),
        },
        // goto loop_start
        TackyInstruction::Jump(loop_start),
        // loop_end:
        TackyInstruction::Label(loop_end),
        // return len
        TackyInstruction::Return(TackyVal::Var(len)),
    ];

    TackyFunction {
        name: name.to_string(),
        global: true,
        params: vec![p],
        body,
        return_type: Type::Long,
        var_types,
        is_variadic: false,
        static_var_names: HashSet::new(),
        has_sret: false,
    }
}

/// `strcmp` の等価な TACKY IR 実装を生成する。
///
/// ```c
/// int _obf_strcmp(const char *s1, const char *s2) {
///     long i = 0;
///     for (;;) {
///         char c1 = s1[i], c2 = s2[i];
///         int d = (int)c1 - (int)c2;
///         if (d != 0) return d;
///         if (c1 == '\0') return 0;
///         i = i + 1;
///     }
/// }
/// ```
fn generate_strcmp(ctx: &mut ObfCtx, name: &str) -> TackyFunction {
    let p1 = "p1".to_string();
    let p2 = "p2".to_string();
    let idx = ctx.fresh_tmp(); // loop index (Long)
    let ptr1 = ctx.fresh_tmp(); // s1 + idx
    let ptr2 = ctx.fresh_tmp(); // s2 + idx
    let ch1 = ctx.fresh_tmp(); // *ptr1 (Char)
    let ch2 = ctx.fresh_tmp(); // *ptr2 (Char)
    let ci1 = ctx.fresh_tmp(); // ZeroExtend ch1 → Int
    let ci2 = ctx.fresh_tmp(); // ZeroExtend ch2 → Int
    let diff = ctx.fresh_tmp(); // ci1 - ci2 (Int)

    let loop_start = ctx.fresh_label();
    let loop_end = ctx.fresh_label();
    let ret_diff = ctx.fresh_label();

    let ptr_char = Type::Pointer(Box::new(Type::Char));
    let mut var_types = HashMap::new();
    var_types.insert(p1.clone(), ptr_char.clone());
    var_types.insert(p2.clone(), ptr_char.clone());
    var_types.insert(idx.clone(), Type::Long);
    var_types.insert(ptr1.clone(), ptr_char.clone());
    var_types.insert(ptr2.clone(), ptr_char);
    var_types.insert(ch1.clone(), Type::Char);
    var_types.insert(ch2.clone(), Type::Char);
    var_types.insert(ci1.clone(), Type::Int);
    var_types.insert(ci2.clone(), Type::Int);
    var_types.insert(diff.clone(), Type::Int);

    let body = vec![
        // idx = 0
        TackyInstruction::Copy {
            src: TackyVal::Constant(TackyConst::Long(0)),
            dst: TackyVal::Var(idx.clone()),
        },
        // loop_start:
        TackyInstruction::Label(loop_start.clone()),
        // ptr1 = s1 + idx
        TackyInstruction::AddPtr {
            ptr: TackyVal::Var(p1.clone()),
            index: TackyVal::Var(idx.clone()),
            scale: 1,
            dst: TackyVal::Var(ptr1.clone()),
        },
        // ptr2 = s2 + idx
        TackyInstruction::AddPtr {
            ptr: TackyVal::Var(p2.clone()),
            index: TackyVal::Var(idx.clone()),
            scale: 1,
            dst: TackyVal::Var(ptr2.clone()),
        },
        // ch1 = *ptr1
        TackyInstruction::Load {
            src_ptr: TackyVal::Var(ptr1.clone()),
            dst: TackyVal::Var(ch1.clone()),
        },
        // ch2 = *ptr2
        TackyInstruction::Load {
            src_ptr: TackyVal::Var(ptr2.clone()),
            dst: TackyVal::Var(ch2.clone()),
        },
        // ci1 = (int)ch1
        TackyInstruction::ZeroExtend {
            src: TackyVal::Var(ch1.clone()),
            dst: TackyVal::Var(ci1.clone()),
        },
        // ci2 = (int)ch2
        TackyInstruction::ZeroExtend {
            src: TackyVal::Var(ch2.clone()),
            dst: TackyVal::Var(ci2.clone()),
        },
        // diff = ci1 - ci2
        TackyInstruction::Binary {
            op: TackyBinaryOp::Subtract,
            left: TackyVal::Var(ci1.clone()),
            right: TackyVal::Var(ci2.clone()),
            dst: TackyVal::Var(diff.clone()),
        },
        // if diff != 0, return diff
        TackyInstruction::JumpIfNotZero {
            condition: TackyVal::Var(diff.clone()),
            target: ret_diff.clone(),
        },
        // if ch1 == 0 (null terminator), return 0
        TackyInstruction::JumpIfZero {
            condition: TackyVal::Var(ci1.clone()),
            target: loop_end.clone(),
        },
        // idx++
        TackyInstruction::Binary {
            op: TackyBinaryOp::Add,
            left: TackyVal::Var(idx.clone()),
            right: TackyVal::Constant(TackyConst::Long(1)),
            dst: TackyVal::Var(idx.clone()),
        },
        TackyInstruction::Jump(loop_start),
        // ret_diff: return diff
        TackyInstruction::Label(ret_diff),
        TackyInstruction::Return(TackyVal::Var(diff)),
        // loop_end: return 0
        TackyInstruction::Label(loop_end),
        TackyInstruction::Return(TackyVal::Constant(TackyConst::Int(0))),
    ];

    TackyFunction {
        name: name.to_string(),
        global: true,
        params: vec![p1, p2],
        body,
        return_type: Type::Int,
        var_types,
        is_variadic: false,
        static_var_names: HashSet::new(),
        has_sret: false,
    }
}

/// `strcpy` の等価な TACKY IR 実装を生成する。
///
/// ```c
/// char *_obf_strcpy(char *dst, const char *src) {
///     long i = 0;
///     for (;;) {
///         char ch = src[i];
///         dst[i] = ch;
///         if (ch == '\0') break;
///         i = i + 1;
///     }
///     return dst;
/// }
/// ```
fn generate_strcpy(ctx: &mut ObfCtx, name: &str) -> TackyFunction {
    let dst = "p_dst".to_string();
    let src = "p_src".to_string();
    let idx = ctx.fresh_tmp(); // loop index (Long)
    let src_ptr = ctx.fresh_tmp(); // src + idx
    let dst_ptr = ctx.fresh_tmp(); // dst + idx
    let ch = ctx.fresh_tmp(); // *src_ptr (Char)
    let ci = ctx.fresh_tmp(); // ZeroExtend ch → Int

    let loop_start = ctx.fresh_label();
    let loop_end = ctx.fresh_label();

    let ptr_char = Type::Pointer(Box::new(Type::Char));
    let mut var_types = HashMap::new();
    var_types.insert(dst.clone(), ptr_char.clone());
    var_types.insert(src.clone(), ptr_char.clone());
    var_types.insert(idx.clone(), Type::Long);
    var_types.insert(src_ptr.clone(), ptr_char.clone());
    var_types.insert(dst_ptr.clone(), ptr_char);
    var_types.insert(ch.clone(), Type::Char);
    var_types.insert(ci.clone(), Type::Int);

    let body = vec![
        // idx = 0
        TackyInstruction::Copy {
            src: TackyVal::Constant(TackyConst::Long(0)),
            dst: TackyVal::Var(idx.clone()),
        },
        // loop_start:
        TackyInstruction::Label(loop_start.clone()),
        // src_ptr = src + idx
        TackyInstruction::AddPtr {
            ptr: TackyVal::Var(src.clone()),
            index: TackyVal::Var(idx.clone()),
            scale: 1,
            dst: TackyVal::Var(src_ptr.clone()),
        },
        // ch = *src_ptr
        TackyInstruction::Load {
            src_ptr: TackyVal::Var(src_ptr.clone()),
            dst: TackyVal::Var(ch.clone()),
        },
        // dst_ptr = dst + idx
        TackyInstruction::AddPtr {
            ptr: TackyVal::Var(dst.clone()),
            index: TackyVal::Var(idx.clone()),
            scale: 1,
            dst: TackyVal::Var(dst_ptr.clone()),
        },
        // *dst_ptr = ch
        TackyInstruction::Store {
            src: TackyVal::Var(ch.clone()),
            dst_ptr: TackyVal::Var(dst_ptr.clone()),
        },
        // ci = (int)ch
        TackyInstruction::ZeroExtend {
            src: TackyVal::Var(ch.clone()),
            dst: TackyVal::Var(ci.clone()),
        },
        // if ci == 0, break
        TackyInstruction::JumpIfZero {
            condition: TackyVal::Var(ci.clone()),
            target: loop_end.clone(),
        },
        // idx++
        TackyInstruction::Binary {
            op: TackyBinaryOp::Add,
            left: TackyVal::Var(idx.clone()),
            right: TackyVal::Constant(TackyConst::Long(1)),
            dst: TackyVal::Var(idx.clone()),
        },
        TackyInstruction::Jump(loop_start),
        // loop_end:
        TackyInstruction::Label(loop_end),
        // return dst
        TackyInstruction::Return(TackyVal::Var(dst.clone())),
    ];

    TackyFunction {
        name: name.to_string(),
        global: true,
        params: vec![dst, src],
        body,
        return_type: Type::Pointer(Box::new(Type::Char)),
        var_types,
        is_variadic: false,
        static_var_names: HashSet::new(),
        has_sret: false,
    }
}

/// `memcpy` の等価な TACKY IR 実装を生成する。
///
/// ```c
/// void *_obf_memcpy(void *dst, void *src, long n) {
///     long i = 0;
///     while (i < n) {
///         ((char *)dst)[i] = ((char *)src)[i];
///         i = i + 1;
///     }
///     return dst;
/// }
/// ```
fn generate_memcpy(ctx: &mut ObfCtx, name: &str) -> TackyFunction {
    let dst = "p_dst".to_string();
    let src = "p_src".to_string();
    let n = "p_n".to_string();
    let idx = ctx.fresh_tmp(); // loop index (Long)
    let src_ptr = ctx.fresh_tmp(); // src + idx
    let dst_ptr = ctx.fresh_tmp(); // dst + idx
    let byte = ctx.fresh_tmp(); // loaded byte (Char)
    let cmp = ctx.fresh_tmp(); // idx < n (Int)

    let loop_start = ctx.fresh_label();
    let loop_end = ctx.fresh_label();

    let ptr_char = Type::Pointer(Box::new(Type::Char));
    let mut var_types = HashMap::new();
    var_types.insert(dst.clone(), ptr_char.clone());
    var_types.insert(src.clone(), ptr_char.clone());
    var_types.insert(n.clone(), Type::Long);
    var_types.insert(idx.clone(), Type::Long);
    var_types.insert(src_ptr.clone(), ptr_char.clone());
    var_types.insert(dst_ptr.clone(), ptr_char);
    var_types.insert(byte.clone(), Type::Char);
    var_types.insert(cmp.clone(), Type::Int);

    let body = vec![
        // idx = 0
        TackyInstruction::Copy {
            src: TackyVal::Constant(TackyConst::Long(0)),
            dst: TackyVal::Var(idx.clone()),
        },
        // loop_start:
        TackyInstruction::Label(loop_start.clone()),
        // cmp = (idx < n)
        TackyInstruction::Binary {
            op: TackyBinaryOp::LessThan,
            left: TackyVal::Var(idx.clone()),
            right: TackyVal::Var(n.clone()),
            dst: TackyVal::Var(cmp.clone()),
        },
        // if cmp == 0, break
        TackyInstruction::JumpIfZero {
            condition: TackyVal::Var(cmp.clone()),
            target: loop_end.clone(),
        },
        // src_ptr = src + idx
        TackyInstruction::AddPtr {
            ptr: TackyVal::Var(src.clone()),
            index: TackyVal::Var(idx.clone()),
            scale: 1,
            dst: TackyVal::Var(src_ptr.clone()),
        },
        // byte = *src_ptr
        TackyInstruction::Load {
            src_ptr: TackyVal::Var(src_ptr.clone()),
            dst: TackyVal::Var(byte.clone()),
        },
        // dst_ptr = dst + idx
        TackyInstruction::AddPtr {
            ptr: TackyVal::Var(dst.clone()),
            index: TackyVal::Var(idx.clone()),
            scale: 1,
            dst: TackyVal::Var(dst_ptr.clone()),
        },
        // *dst_ptr = byte
        TackyInstruction::Store {
            src: TackyVal::Var(byte.clone()),
            dst_ptr: TackyVal::Var(dst_ptr.clone()),
        },
        // idx++
        TackyInstruction::Binary {
            op: TackyBinaryOp::Add,
            left: TackyVal::Var(idx.clone()),
            right: TackyVal::Constant(TackyConst::Long(1)),
            dst: TackyVal::Var(idx.clone()),
        },
        TackyInstruction::Jump(loop_start),
        // loop_end:
        TackyInstruction::Label(loop_end),
        // return dst
        TackyInstruction::Return(TackyVal::Var(dst.clone())),
    ];

    TackyFunction {
        name: name.to_string(),
        global: true,
        params: vec![dst, src, n],
        body,
        return_type: Type::Pointer(Box::new(Type::Char)),
        var_types,
        is_variadic: false,
        static_var_names: HashSet::new(),
        has_sret: false,
    }
}

/// `memset` の等価な TACKY IR 実装を生成する。
///
/// ```c
/// void *_obf_memset(void *s, int c, long n) {
///     char b = (char)c;
///     long i = 0;
///     while (i < n) {
///         ((char *)s)[i] = b;
///         i = i + 1;
///     }
///     return s;
/// }
/// ```
fn generate_memset(ctx: &mut ObfCtx, name: &str) -> TackyFunction {
    let s = "p_s".to_string();
    let c = "p_c".to_string();
    let n = "p_n".to_string();
    let b = ctx.fresh_tmp(); // truncated byte (Char)
    let idx = ctx.fresh_tmp(); // loop index (Long)
    let dst_ptr = ctx.fresh_tmp(); // s + idx
    let cmp = ctx.fresh_tmp(); // idx < n (Int)

    let loop_start = ctx.fresh_label();
    let loop_end = ctx.fresh_label();

    let ptr_char = Type::Pointer(Box::new(Type::Char));
    let mut var_types = HashMap::new();
    var_types.insert(s.clone(), ptr_char.clone());
    var_types.insert(c.clone(), Type::Int);
    var_types.insert(n.clone(), Type::Long);
    var_types.insert(b.clone(), Type::Char);
    var_types.insert(idx.clone(), Type::Long);
    var_types.insert(dst_ptr.clone(), ptr_char);
    var_types.insert(cmp.clone(), Type::Int);

    let body = vec![
        // b = (char)c
        TackyInstruction::Truncate {
            src: TackyVal::Var(c.clone()),
            dst: TackyVal::Var(b.clone()),
        },
        // idx = 0
        TackyInstruction::Copy {
            src: TackyVal::Constant(TackyConst::Long(0)),
            dst: TackyVal::Var(idx.clone()),
        },
        // loop_start:
        TackyInstruction::Label(loop_start.clone()),
        // cmp = (idx < n)
        TackyInstruction::Binary {
            op: TackyBinaryOp::LessThan,
            left: TackyVal::Var(idx.clone()),
            right: TackyVal::Var(n.clone()),
            dst: TackyVal::Var(cmp.clone()),
        },
        // if cmp == 0, break
        TackyInstruction::JumpIfZero {
            condition: TackyVal::Var(cmp.clone()),
            target: loop_end.clone(),
        },
        // dst_ptr = s + idx
        TackyInstruction::AddPtr {
            ptr: TackyVal::Var(s.clone()),
            index: TackyVal::Var(idx.clone()),
            scale: 1,
            dst: TackyVal::Var(dst_ptr.clone()),
        },
        // *dst_ptr = b
        TackyInstruction::Store {
            src: TackyVal::Var(b.clone()),
            dst_ptr: TackyVal::Var(dst_ptr.clone()),
        },
        // idx++
        TackyInstruction::Binary {
            op: TackyBinaryOp::Add,
            left: TackyVal::Var(idx.clone()),
            right: TackyVal::Constant(TackyConst::Long(1)),
            dst: TackyVal::Var(idx.clone()),
        },
        TackyInstruction::Jump(loop_start),
        // loop_end:
        TackyInstruction::Label(loop_end),
        // return s
        TackyInstruction::Return(TackyVal::Var(s.clone())),
    ];

    TackyFunction {
        name: name.to_string(),
        global: true,
        params: vec![s, c, n],
        body,
        return_type: Type::Pointer(Box::new(Type::Char)),
        var_types,
        is_variadic: false,
        static_var_names: HashSet::new(),
        has_sret: false,
    }
}

/// `memcmp` の等価な TACKY IR 実装を生成する。
///
/// ```c
/// int _obf_memcmp(const char *s1, const char *s2, long n) {
///     long i = 0;
///     while (i < n) {
///         int d = (int)s1[i] - (int)s2[i];
///         if (d != 0) return d;
///         i = i + 1;
///     }
///     return 0;
/// }
/// ```
fn generate_memcmp(ctx: &mut ObfCtx, name: &str) -> TackyFunction {
    let p1 = "p1".to_string();
    let p2 = "p2".to_string();
    let n = "p_n".to_string();
    let idx = ctx.fresh_tmp();
    let cmp = ctx.fresh_tmp();
    let ptr1 = ctx.fresh_tmp();
    let ptr2 = ctx.fresh_tmp();
    let ch1 = ctx.fresh_tmp();
    let ch2 = ctx.fresh_tmp();
    let ci1 = ctx.fresh_tmp();
    let ci2 = ctx.fresh_tmp();
    let diff = ctx.fresh_tmp();

    let loop_start = ctx.fresh_label();
    let loop_end = ctx.fresh_label();
    let ret_diff = ctx.fresh_label();

    let ptr_char = Type::Pointer(Box::new(Type::Char));
    let mut var_types = HashMap::new();
    var_types.insert(p1.clone(), ptr_char.clone());
    var_types.insert(p2.clone(), ptr_char.clone());
    var_types.insert(n.clone(), Type::Long);
    var_types.insert(idx.clone(), Type::Long);
    var_types.insert(cmp.clone(), Type::Int);
    var_types.insert(ptr1.clone(), ptr_char.clone());
    var_types.insert(ptr2.clone(), ptr_char);
    var_types.insert(ch1.clone(), Type::Char);
    var_types.insert(ch2.clone(), Type::Char);
    var_types.insert(ci1.clone(), Type::Int);
    var_types.insert(ci2.clone(), Type::Int);
    var_types.insert(diff.clone(), Type::Int);

    let body = vec![
        TackyInstruction::Copy {
            src: TackyVal::Constant(TackyConst::Long(0)),
            dst: TackyVal::Var(idx.clone()),
        },
        TackyInstruction::Label(loop_start.clone()),
        TackyInstruction::Binary {
            op: TackyBinaryOp::LessThan,
            left: TackyVal::Var(idx.clone()),
            right: TackyVal::Var(n.clone()),
            dst: TackyVal::Var(cmp.clone()),
        },
        TackyInstruction::JumpIfZero {
            condition: TackyVal::Var(cmp.clone()),
            target: loop_end.clone(),
        },
        TackyInstruction::AddPtr {
            ptr: TackyVal::Var(p1.clone()),
            index: TackyVal::Var(idx.clone()),
            scale: 1,
            dst: TackyVal::Var(ptr1.clone()),
        },
        TackyInstruction::AddPtr {
            ptr: TackyVal::Var(p2.clone()),
            index: TackyVal::Var(idx.clone()),
            scale: 1,
            dst: TackyVal::Var(ptr2.clone()),
        },
        TackyInstruction::Load {
            src_ptr: TackyVal::Var(ptr1.clone()),
            dst: TackyVal::Var(ch1.clone()),
        },
        TackyInstruction::Load {
            src_ptr: TackyVal::Var(ptr2.clone()),
            dst: TackyVal::Var(ch2.clone()),
        },
        TackyInstruction::ZeroExtend {
            src: TackyVal::Var(ch1.clone()),
            dst: TackyVal::Var(ci1.clone()),
        },
        TackyInstruction::ZeroExtend {
            src: TackyVal::Var(ch2.clone()),
            dst: TackyVal::Var(ci2.clone()),
        },
        TackyInstruction::Binary {
            op: TackyBinaryOp::Subtract,
            left: TackyVal::Var(ci1.clone()),
            right: TackyVal::Var(ci2.clone()),
            dst: TackyVal::Var(diff.clone()),
        },
        TackyInstruction::JumpIfNotZero {
            condition: TackyVal::Var(diff.clone()),
            target: ret_diff.clone(),
        },
        TackyInstruction::Binary {
            op: TackyBinaryOp::Add,
            left: TackyVal::Var(idx.clone()),
            right: TackyVal::Constant(TackyConst::Long(1)),
            dst: TackyVal::Var(idx.clone()),
        },
        TackyInstruction::Jump(loop_start),
        TackyInstruction::Label(ret_diff),
        TackyInstruction::Return(TackyVal::Var(diff)),
        TackyInstruction::Label(loop_end),
        TackyInstruction::Return(TackyVal::Constant(TackyConst::Int(0))),
    ];

    TackyFunction {
        name: name.to_string(),
        global: true,
        params: vec![p1, p2, n],
        body,
        return_type: Type::Int,
        var_types,
        is_variadic: false,
        static_var_names: HashSet::new(),
        has_sret: false,
    }
}

/// `strncmp` の等価な TACKY IR 実装を生成する。
///
/// ```c
/// int _obf_strncmp(const char *s1, const char *s2, long n) {
///     long i = 0;
///     while (i < n) {
///         int d = (int)s1[i] - (int)s2[i];
///         if (d != 0) return d;
///         if (s1[i] == '\0') return 0;
///         i = i + 1;
///     }
///     return 0;
/// }
/// ```
fn generate_strncmp(ctx: &mut ObfCtx, name: &str) -> TackyFunction {
    let p1 = "p1".to_string();
    let p2 = "p2".to_string();
    let n = "p_n".to_string();
    let idx = ctx.fresh_tmp();
    let cmp = ctx.fresh_tmp();
    let ptr1 = ctx.fresh_tmp();
    let ptr2 = ctx.fresh_tmp();
    let ch1 = ctx.fresh_tmp();
    let ch2 = ctx.fresh_tmp();
    let ci1 = ctx.fresh_tmp();
    let ci2 = ctx.fresh_tmp();
    let diff = ctx.fresh_tmp();

    let loop_start = ctx.fresh_label();
    let loop_end = ctx.fresh_label();
    let ret_diff = ctx.fresh_label();

    let ptr_char = Type::Pointer(Box::new(Type::Char));
    let mut var_types = HashMap::new();
    var_types.insert(p1.clone(), ptr_char.clone());
    var_types.insert(p2.clone(), ptr_char.clone());
    var_types.insert(n.clone(), Type::Long);
    var_types.insert(idx.clone(), Type::Long);
    var_types.insert(cmp.clone(), Type::Int);
    var_types.insert(ptr1.clone(), ptr_char.clone());
    var_types.insert(ptr2.clone(), ptr_char);
    var_types.insert(ch1.clone(), Type::Char);
    var_types.insert(ch2.clone(), Type::Char);
    var_types.insert(ci1.clone(), Type::Int);
    var_types.insert(ci2.clone(), Type::Int);
    var_types.insert(diff.clone(), Type::Int);

    let body = vec![
        TackyInstruction::Copy {
            src: TackyVal::Constant(TackyConst::Long(0)),
            dst: TackyVal::Var(idx.clone()),
        },
        TackyInstruction::Label(loop_start.clone()),
        // if i >= n, return 0
        TackyInstruction::Binary {
            op: TackyBinaryOp::LessThan,
            left: TackyVal::Var(idx.clone()),
            right: TackyVal::Var(n.clone()),
            dst: TackyVal::Var(cmp.clone()),
        },
        TackyInstruction::JumpIfZero {
            condition: TackyVal::Var(cmp.clone()),
            target: loop_end.clone(),
        },
        TackyInstruction::AddPtr {
            ptr: TackyVal::Var(p1.clone()),
            index: TackyVal::Var(idx.clone()),
            scale: 1,
            dst: TackyVal::Var(ptr1.clone()),
        },
        TackyInstruction::AddPtr {
            ptr: TackyVal::Var(p2.clone()),
            index: TackyVal::Var(idx.clone()),
            scale: 1,
            dst: TackyVal::Var(ptr2.clone()),
        },
        TackyInstruction::Load {
            src_ptr: TackyVal::Var(ptr1.clone()),
            dst: TackyVal::Var(ch1.clone()),
        },
        TackyInstruction::Load {
            src_ptr: TackyVal::Var(ptr2.clone()),
            dst: TackyVal::Var(ch2.clone()),
        },
        TackyInstruction::ZeroExtend {
            src: TackyVal::Var(ch1.clone()),
            dst: TackyVal::Var(ci1.clone()),
        },
        TackyInstruction::ZeroExtend {
            src: TackyVal::Var(ch2.clone()),
            dst: TackyVal::Var(ci2.clone()),
        },
        TackyInstruction::Binary {
            op: TackyBinaryOp::Subtract,
            left: TackyVal::Var(ci1.clone()),
            right: TackyVal::Var(ci2.clone()),
            dst: TackyVal::Var(diff.clone()),
        },
        TackyInstruction::JumpIfNotZero {
            condition: TackyVal::Var(diff.clone()),
            target: ret_diff.clone(),
        },
        // if s1[i] == '\0', both are equal up to null
        TackyInstruction::JumpIfZero {
            condition: TackyVal::Var(ci1.clone()),
            target: loop_end.clone(),
        },
        TackyInstruction::Binary {
            op: TackyBinaryOp::Add,
            left: TackyVal::Var(idx.clone()),
            right: TackyVal::Constant(TackyConst::Long(1)),
            dst: TackyVal::Var(idx.clone()),
        },
        TackyInstruction::Jump(loop_start),
        TackyInstruction::Label(ret_diff),
        TackyInstruction::Return(TackyVal::Var(diff)),
        TackyInstruction::Label(loop_end),
        TackyInstruction::Return(TackyVal::Constant(TackyConst::Int(0))),
    ];

    TackyFunction {
        name: name.to_string(),
        global: true,
        params: vec![p1, p2, n],
        body,
        return_type: Type::Int,
        var_types,
        is_variadic: false,
        static_var_names: HashSet::new(),
        has_sret: false,
    }
}

/// `strncpy` の等価な TACKY IR 実装を生成する。
///
/// ```c
/// char *_obf_strncpy(char *dst, const char *src, long n) {
///     long i = 0;
///     while (i < n) {
///         char ch = src[i];
///         dst[i] = ch;
///         if (ch == '\0') break;
///         i = i + 1;
///     }
///     // 残りをゼロ埋め
///     while (i < n) {
///         dst[i] = '\0';
///         i = i + 1;
///     }
///     return dst;
/// }
/// ```
fn generate_strncpy(ctx: &mut ObfCtx, name: &str) -> TackyFunction {
    let dst = "p_dst".to_string();
    let src = "p_src".to_string();
    let n = "p_n".to_string();
    let idx = ctx.fresh_tmp();
    let cmp = ctx.fresh_tmp();
    let src_ptr = ctx.fresh_tmp();
    let dst_ptr = ctx.fresh_tmp();
    let ch = ctx.fresh_tmp();
    let ci = ctx.fresh_tmp();

    let loop1_start = ctx.fresh_label();
    let loop1_end = ctx.fresh_label();
    let loop2_start = ctx.fresh_label();
    let loop2_end = ctx.fresh_label();

    let ptr_char = Type::Pointer(Box::new(Type::Char));
    let mut var_types = HashMap::new();
    var_types.insert(dst.clone(), ptr_char.clone());
    var_types.insert(src.clone(), ptr_char.clone());
    var_types.insert(n.clone(), Type::Long);
    var_types.insert(idx.clone(), Type::Long);
    var_types.insert(cmp.clone(), Type::Int);
    var_types.insert(src_ptr.clone(), ptr_char.clone());
    var_types.insert(dst_ptr.clone(), ptr_char);
    var_types.insert(ch.clone(), Type::Char);
    var_types.insert(ci.clone(), Type::Int);

    let body = vec![
        // idx = 0
        TackyInstruction::Copy {
            src: TackyVal::Constant(TackyConst::Long(0)),
            dst: TackyVal::Var(idx.clone()),
        },
        // ── loop 1: copy src chars ──
        TackyInstruction::Label(loop1_start.clone()),
        TackyInstruction::Binary {
            op: TackyBinaryOp::LessThan,
            left: TackyVal::Var(idx.clone()),
            right: TackyVal::Var(n.clone()),
            dst: TackyVal::Var(cmp.clone()),
        },
        TackyInstruction::JumpIfZero {
            condition: TackyVal::Var(cmp.clone()),
            target: loop2_end.clone(), // n reached, skip pad loop too
        },
        TackyInstruction::AddPtr {
            ptr: TackyVal::Var(src.clone()),
            index: TackyVal::Var(idx.clone()),
            scale: 1,
            dst: TackyVal::Var(src_ptr.clone()),
        },
        TackyInstruction::Load {
            src_ptr: TackyVal::Var(src_ptr.clone()),
            dst: TackyVal::Var(ch.clone()),
        },
        TackyInstruction::AddPtr {
            ptr: TackyVal::Var(dst.clone()),
            index: TackyVal::Var(idx.clone()),
            scale: 1,
            dst: TackyVal::Var(dst_ptr.clone()),
        },
        TackyInstruction::Store {
            src: TackyVal::Var(ch.clone()),
            dst_ptr: TackyVal::Var(dst_ptr.clone()),
        },
        TackyInstruction::ZeroExtend {
            src: TackyVal::Var(ch.clone()),
            dst: TackyVal::Var(ci.clone()),
        },
        TackyInstruction::JumpIfZero {
            condition: TackyVal::Var(ci.clone()),
            target: loop1_end.clone(), // null found, go to pad loop
        },
        TackyInstruction::Binary {
            op: TackyBinaryOp::Add,
            left: TackyVal::Var(idx.clone()),
            right: TackyVal::Constant(TackyConst::Long(1)),
            dst: TackyVal::Var(idx.clone()),
        },
        TackyInstruction::Jump(loop1_start),
        // ── null hit; idx already incremented past null ──
        TackyInstruction::Label(loop1_end.clone()),
        TackyInstruction::Binary {
            op: TackyBinaryOp::Add,
            left: TackyVal::Var(idx.clone()),
            right: TackyVal::Constant(TackyConst::Long(1)),
            dst: TackyVal::Var(idx.clone()),
        },
        // ── loop 2: zero-pad remaining ──
        TackyInstruction::Label(loop2_start.clone()),
        TackyInstruction::Binary {
            op: TackyBinaryOp::LessThan,
            left: TackyVal::Var(idx.clone()),
            right: TackyVal::Var(n.clone()),
            dst: TackyVal::Var(cmp.clone()),
        },
        TackyInstruction::JumpIfZero {
            condition: TackyVal::Var(cmp.clone()),
            target: loop2_end.clone(),
        },
        TackyInstruction::AddPtr {
            ptr: TackyVal::Var(dst.clone()),
            index: TackyVal::Var(idx.clone()),
            scale: 1,
            dst: TackyVal::Var(dst_ptr.clone()),
        },
        TackyInstruction::Store {
            src: TackyVal::Constant(TackyConst::Char(0)),
            dst_ptr: TackyVal::Var(dst_ptr.clone()),
        },
        TackyInstruction::Binary {
            op: TackyBinaryOp::Add,
            left: TackyVal::Var(idx.clone()),
            right: TackyVal::Constant(TackyConst::Long(1)),
            dst: TackyVal::Var(idx.clone()),
        },
        TackyInstruction::Jump(loop2_start),
        // ── done ──
        TackyInstruction::Label(loop2_end),
        TackyInstruction::Return(TackyVal::Var(dst.clone())),
    ];

    TackyFunction {
        name: name.to_string(),
        global: true,
        params: vec![dst, src, n],
        body,
        return_type: Type::Pointer(Box::new(Type::Char)),
        var_types,
        is_variadic: false,
        static_var_names: HashSet::new(),
        has_sret: false,
    }
}

/// `strchr` の等価な TACKY IR 実装を生成する。
///
/// ```c
/// char *_obf_strchr(const char *s, int c) {
///     char target = (char)c;
///     long i = 0;
///     for (;;) {
///         char ch = s[i];
///         if (ch == target) return s + i;
///         if (ch == '\0') return (char *)0;
///         i = i + 1;
///     }
/// }
/// ```
fn generate_strchr(ctx: &mut ObfCtx, name: &str) -> TackyFunction {
    let s = "p_s".to_string();
    let c = "p_c".to_string();
    let target = ctx.fresh_tmp(); // Truncate(c) → Char
    let idx = ctx.fresh_tmp(); // Long
    let ptr = ctx.fresh_tmp(); // s + idx
    let ch = ctx.fresh_tmp(); // Char
    let ci = ctx.fresh_tmp(); // ZeroExtend(ch) → Int
    let ti = ctx.fresh_tmp(); // ZeroExtend(target) → Int
    let eq = ctx.fresh_tmp(); // ci == ti (Int)

    let loop_start = ctx.fresh_label();
    let ret_found = ctx.fresh_label();
    let ret_null = ctx.fresh_label();

    let ptr_char = Type::Pointer(Box::new(Type::Char));
    let mut var_types = HashMap::new();
    var_types.insert(s.clone(), ptr_char.clone());
    var_types.insert(c.clone(), Type::Int);
    var_types.insert(target.clone(), Type::Char);
    var_types.insert(idx.clone(), Type::Long);
    var_types.insert(ptr.clone(), ptr_char);
    var_types.insert(ch.clone(), Type::Char);
    var_types.insert(ci.clone(), Type::Int);
    var_types.insert(ti.clone(), Type::Int);
    var_types.insert(eq.clone(), Type::Int);

    let body = vec![
        // target = (char)c
        TackyInstruction::Truncate {
            src: TackyVal::Var(c.clone()),
            dst: TackyVal::Var(target.clone()),
        },
        TackyInstruction::ZeroExtend {
            src: TackyVal::Var(target.clone()),
            dst: TackyVal::Var(ti.clone()),
        },
        TackyInstruction::Copy {
            src: TackyVal::Constant(TackyConst::Long(0)),
            dst: TackyVal::Var(idx.clone()),
        },
        TackyInstruction::Label(loop_start.clone()),
        TackyInstruction::AddPtr {
            ptr: TackyVal::Var(s.clone()),
            index: TackyVal::Var(idx.clone()),
            scale: 1,
            dst: TackyVal::Var(ptr.clone()),
        },
        TackyInstruction::Load {
            src_ptr: TackyVal::Var(ptr.clone()),
            dst: TackyVal::Var(ch.clone()),
        },
        TackyInstruction::ZeroExtend {
            src: TackyVal::Var(ch.clone()),
            dst: TackyVal::Var(ci.clone()),
        },
        // if ch == target → return ptr
        TackyInstruction::Binary {
            op: TackyBinaryOp::Equal,
            left: TackyVal::Var(ci.clone()),
            right: TackyVal::Var(ti.clone()),
            dst: TackyVal::Var(eq.clone()),
        },
        TackyInstruction::JumpIfNotZero {
            condition: TackyVal::Var(eq.clone()),
            target: ret_found.clone(),
        },
        // if ch == '\0' → return NULL
        TackyInstruction::JumpIfZero {
            condition: TackyVal::Var(ci.clone()),
            target: ret_null.clone(),
        },
        TackyInstruction::Binary {
            op: TackyBinaryOp::Add,
            left: TackyVal::Var(idx.clone()),
            right: TackyVal::Constant(TackyConst::Long(1)),
            dst: TackyVal::Var(idx.clone()),
        },
        TackyInstruction::Jump(loop_start),
        // ret_found: return s + idx (= ptr)
        TackyInstruction::Label(ret_found),
        TackyInstruction::Return(TackyVal::Var(ptr.clone())),
        // ret_null: return 0 (NULL)
        TackyInstruction::Label(ret_null),
        TackyInstruction::Return(TackyVal::Constant(TackyConst::Long(0))),
    ];

    TackyFunction {
        name: name.to_string(),
        global: true,
        params: vec![s, c],
        body,
        return_type: Type::Pointer(Box::new(Type::Char)),
        var_types,
        is_variadic: false,
        static_var_names: HashSet::new(),
        has_sret: false,
    }
}

/// `strcat` の等価な TACKY IR 実装を生成する。
///
/// ```c
/// char *_obf_strcat(char *dst, const char *src) {
///     // Phase 1: dst の末尾を探す
///     long di = 0;
///     while (dst[di] != '\0') di = di + 1;
///     // Phase 2: src をコピー
///     long si = 0;
///     for (;;) {
///         char ch = src[si];
///         dst[di] = ch;
///         if (ch == '\0') break;
///         di = di + 1; si = si + 1;
///     }
///     return dst;
/// }
/// ```
fn generate_strcat(ctx: &mut ObfCtx, name: &str) -> TackyFunction {
    let dst = "p_dst".to_string();
    let src = "p_src".to_string();
    let di = ctx.fresh_tmp(); // dst index (Long)
    let si = ctx.fresh_tmp(); // src index (Long)
    let dptr = ctx.fresh_tmp(); // dst + di
    let sptr = ctx.fresh_tmp(); // src + si
    let ch = ctx.fresh_tmp(); // Char
    let ci = ctx.fresh_tmp(); // Int

    let find_start = ctx.fresh_label();
    let find_end = ctx.fresh_label();
    let copy_start = ctx.fresh_label();
    let copy_end = ctx.fresh_label();

    let ptr_char = Type::Pointer(Box::new(Type::Char));
    let mut var_types = HashMap::new();
    var_types.insert(dst.clone(), ptr_char.clone());
    var_types.insert(src.clone(), ptr_char.clone());
    var_types.insert(di.clone(), Type::Long);
    var_types.insert(si.clone(), Type::Long);
    var_types.insert(dptr.clone(), ptr_char.clone());
    var_types.insert(sptr.clone(), ptr_char);
    var_types.insert(ch.clone(), Type::Char);
    var_types.insert(ci.clone(), Type::Int);

    let body = vec![
        // ── Phase 1: find end of dst ──
        TackyInstruction::Copy {
            src: TackyVal::Constant(TackyConst::Long(0)),
            dst: TackyVal::Var(di.clone()),
        },
        TackyInstruction::Label(find_start.clone()),
        TackyInstruction::AddPtr {
            ptr: TackyVal::Var(dst.clone()),
            index: TackyVal::Var(di.clone()),
            scale: 1,
            dst: TackyVal::Var(dptr.clone()),
        },
        TackyInstruction::Load {
            src_ptr: TackyVal::Var(dptr.clone()),
            dst: TackyVal::Var(ch.clone()),
        },
        TackyInstruction::ZeroExtend {
            src: TackyVal::Var(ch.clone()),
            dst: TackyVal::Var(ci.clone()),
        },
        TackyInstruction::JumpIfZero {
            condition: TackyVal::Var(ci.clone()),
            target: find_end.clone(),
        },
        TackyInstruction::Binary {
            op: TackyBinaryOp::Add,
            left: TackyVal::Var(di.clone()),
            right: TackyVal::Constant(TackyConst::Long(1)),
            dst: TackyVal::Var(di.clone()),
        },
        TackyInstruction::Jump(find_start),
        TackyInstruction::Label(find_end.clone()),
        // ── Phase 2: copy src to dst+di ──
        TackyInstruction::Copy {
            src: TackyVal::Constant(TackyConst::Long(0)),
            dst: TackyVal::Var(si.clone()),
        },
        TackyInstruction::Label(copy_start.clone()),
        TackyInstruction::AddPtr {
            ptr: TackyVal::Var(src.clone()),
            index: TackyVal::Var(si.clone()),
            scale: 1,
            dst: TackyVal::Var(sptr.clone()),
        },
        TackyInstruction::Load {
            src_ptr: TackyVal::Var(sptr.clone()),
            dst: TackyVal::Var(ch.clone()),
        },
        TackyInstruction::AddPtr {
            ptr: TackyVal::Var(dst.clone()),
            index: TackyVal::Var(di.clone()),
            scale: 1,
            dst: TackyVal::Var(dptr.clone()),
        },
        TackyInstruction::Store {
            src: TackyVal::Var(ch.clone()),
            dst_ptr: TackyVal::Var(dptr.clone()),
        },
        TackyInstruction::ZeroExtend {
            src: TackyVal::Var(ch.clone()),
            dst: TackyVal::Var(ci.clone()),
        },
        TackyInstruction::JumpIfZero {
            condition: TackyVal::Var(ci.clone()),
            target: copy_end.clone(),
        },
        TackyInstruction::Binary {
            op: TackyBinaryOp::Add,
            left: TackyVal::Var(di.clone()),
            right: TackyVal::Constant(TackyConst::Long(1)),
            dst: TackyVal::Var(di.clone()),
        },
        TackyInstruction::Binary {
            op: TackyBinaryOp::Add,
            left: TackyVal::Var(si.clone()),
            right: TackyVal::Constant(TackyConst::Long(1)),
            dst: TackyVal::Var(si.clone()),
        },
        TackyInstruction::Jump(copy_start),
        TackyInstruction::Label(copy_end),
        TackyInstruction::Return(TackyVal::Var(dst.clone())),
    ];

    TackyFunction {
        name: name.to_string(),
        global: true,
        params: vec![dst, src],
        body,
        return_type: Type::Pointer(Box::new(Type::Char)),
        var_types,
        is_variadic: false,
        static_var_names: HashSet::new(),
        has_sret: false,
    }
}

// ─────────────────────────────────────────────────────────────
// Pass 12: Function Inlining(関数インライン展開)
// ─────────────────────────────────────────────────────────────

/// 関数呼び出しを呼び出し先の関数本体で置換する。
/// コールグラフを破壊し、元の関数構造の復元を困難にする。
fn inline_functions(program: &mut TackyProgram, ctx: &mut ObfCtx, freq: usize) {
    // 静的変数・静的定数の名前を収集(リネーム対象外)
    let static_names: HashSet<String> = program
        .static_vars
        .iter()
        .map(|v| v.name.clone())
        .chain(program.static_constants.iter().map(|c| c.name.clone()))
        .collect();

    // 全関数を clone して callee_map を構築(可変借用と不変借用の衝突を回避)
    let callee_map: HashMap<String, TackyFunction> = program
        .functions
        .iter()
        .map(|f| (f.name.clone(), f.clone()))
        .collect();

    for func in &mut program.functions {
        let mut new_body = Vec::new();
        let mut eligible_count = 0usize;

        for instr in std::mem::take(&mut func.body) {
            if let TackyInstruction::FunCall {
                ref name,
                ref args,
                ref dst,
                ref dst_type,
                is_variadic: _,
            } = instr
                && let Some(callee) = callee_map.get(name)
                && is_inline_eligible(callee, name, dst_type, &static_names)
            {
                eligible_count += 1;
                if freq > 0 && eligible_count.is_multiple_of(freq) {
                    // インライン展開を実行
                    let prefix = format!("_inline_{}", ctx.inline_counter);
                    ctx.inline_counter += 1;
                    let end_label = format!("{}_end", prefix);

                    // 引数→リネームされたパラメータへの Copy
                    for (param, arg) in callee.params.iter().zip(args.iter()) {
                        let renamed_param = format!("{}_{}", prefix, param);
                        new_body.push(TackyInstruction::Copy {
                            src: arg.clone(),
                            dst: TackyVal::Var(renamed_param),
                        });
                    }

                    // リネームされた本体を挿入
                    for callee_instr in &callee.body {
                        match callee_instr {
                            TackyInstruction::Return(val) => {
                                if !matches!(callee.return_type, Type::Void) {
                                    new_body.push(TackyInstruction::Copy {
                                        src: rename_val(val, &prefix, &static_names),
                                        dst: dst.clone(),
                                    });
                                }
                                new_body.push(TackyInstruction::Jump(end_label.clone()));
                            }
                            TackyInstruction::ReturnVoid => {
                                new_body.push(TackyInstruction::Jump(end_label.clone()));
                            }
                            _ => {
                                new_body.push(rename_instruction(
                                    callee_instr,
                                    &prefix,
                                    &static_names,
                                    dst,
                                    &end_label,
                                    &callee.return_type,
                                ));
                            }
                        }
                    }

                    // end ラベル
                    new_body.push(TackyInstruction::Label(end_label.clone()));

                    // リネームされた変数を呼び出し元の var_types に追加
                    for (var_name, var_type) in &callee.var_types {
                        if !static_names.contains(var_name) {
                            let renamed = format!("{}_{}", prefix, var_name);
                            func.var_types.insert(renamed, var_type.clone());
                        }
                    }

                    continue;
                }
            }
            new_body.push(instr);
        }

        func.body = new_body;
    }
}

/// インライン適格条件を判定する
fn is_inline_eligible(
    callee: &TackyFunction,
    callee_name: &str,
    dst_type: &Type,
    static_names: &HashSet<String>,
) -> bool {
    // 1. main() でない
    if callee_name == "main" {
        return false;
    }
    // 2. 本体が空でない
    if callee.body.is_empty() {
        return false;
    }
    // 3. 本体が ≤ 50 命令
    if callee.body.len() > 50 {
        return false;
    }
    // 4. 戻り値型が Struct でない
    if matches!(dst_type, Type::Struct { .. }) {
        return false;
    }
    // 5. 可変長引数関数でない(VaStart/VaArg は呼び出し元にインライン化できない)
    if callee.is_variadic {
        return false;
    }
    // 6. 直接再帰でない
    if is_directly_recursive(callee) {
        return false;
    }
    // 6. パラメータの GetAddress を含まない
    if has_param_address_taken(callee, static_names) {
        return false;
    }
    // 7. 間接呼び出し(CallExpr 由来の __call_expr.N)を含まない
    // FunCall.name が実際にはローカル変数(関数ポインタ)の場合、
    // インライン化すると name がリネームされず未解決シンボルになる。
    if callee.body.iter().any(|instr| {
        matches!(instr, TackyInstruction::FunCall { name, .. } if name.starts_with("__call_expr."))
    }) {
        return false;
    }
    true
}

/// 関数本体に自身への FunCall があるか判定する
fn is_directly_recursive(func: &TackyFunction) -> bool {
    func.body
        .iter()
        .any(|instr| matches!(instr, TackyInstruction::FunCall { name, .. } if name == &func.name))
}

/// GetAddress の src がパラメータか判定する
fn has_param_address_taken(func: &TackyFunction, static_names: &HashSet<String>) -> bool {
    let params: HashSet<&str> = func.params.iter().map(|s| s.as_str()).collect();
    func.body.iter().any(|instr| {
        if let TackyInstruction::GetAddress {
            src: TackyVal::Var(name),
            ..
        } = instr
        {
            // 静的変数はパラメータではない
            !static_names.contains(name) && params.contains(name.as_str())
        } else {
            false
        }
    })
}

/// TackyVal のリネーム。Var をリネームし Constant はそのまま。
fn rename_val(val: &TackyVal, prefix: &str, static_names: &HashSet<String>) -> TackyVal {
    match val {
        TackyVal::Var(name) => {
            if static_names.contains(name) {
                val.clone()
            } else {
                TackyVal::Var(format!("{}_{}", prefix, name))
            }
        }
        TackyVal::Constant(_) => val.clone(),
    }
}

/// ラベル名のリネーム
fn rename_label(label: &str, prefix: &str) -> String {
    format!("{}_{}", prefix, label)
}

/// 命令全体のリネーム。全 TackyInstruction バリアントの変数・ラベルをリネームする。
/// Return / ReturnVoid は call_dst への Copy + Jump(end_label) に変換する。
fn rename_instruction(
    instr: &TackyInstruction,
    prefix: &str,
    static_names: &HashSet<String>,
    call_dst: &TackyVal,
    end_label: &str,
    return_type: &Type,
) -> TackyInstruction {
    let rv = |v: &TackyVal| rename_val(v, prefix, static_names);
    let rl = |l: &str| rename_label(l, prefix);

    // Return を特別処理するためマクロ的に書かない
    match instr {
        // Return(val) → Copy { src: rename(val), dst: call_dst } + Jump(end_label)
        // ただしここでは1命令しか返せないので、呼び出し側で特別処理が必要。
        // 実際には rename_instruction は inline_functions 内のループで呼ばれるので、
        // Return は呼び出し側で展開する。ここでは Copy に変換する。
        TackyInstruction::Return(val) => {
            if matches!(return_type, Type::Void) {
                TackyInstruction::Jump(end_label.to_string())
            } else {
                // Return は2命令に展開する必要があるが、1命令しか返せないので
                // Copy として返し、呼び出し側で Jump を追加する設計にする。
                // → 実際には inline_functions 内で直接展開するべき。
                // ここでは placeholder として Copy + Jump の最初の命令を返す。
                TackyInstruction::Copy {
                    src: rv(val),
                    dst: call_dst.clone(),
                }
            }
        }
        TackyInstruction::ReturnVoid => TackyInstruction::Jump(end_label.to_string()),

        TackyInstruction::Unary { op, src, dst } => TackyInstruction::Unary {
            op: *op,
            src: rv(src),
            dst: rv(dst),
        },
        TackyInstruction::Binary {
            op,
            left,
            right,
            dst,
        } => TackyInstruction::Binary {
            op: *op,
            left: rv(left),
            right: rv(right),
            dst: rv(dst),
        },
        TackyInstruction::Copy { src, dst } => TackyInstruction::Copy {
            src: rv(src),
            dst: rv(dst),
        },
        TackyInstruction::Jump(target) => TackyInstruction::Jump(rl(target)),
        TackyInstruction::JumpIfZero { condition, target } => TackyInstruction::JumpIfZero {
            condition: rv(condition),
            target: rl(target),
        },
        TackyInstruction::JumpIfNotZero { condition, target } => TackyInstruction::JumpIfNotZero {
            condition: rv(condition),
            target: rl(target),
        },
        TackyInstruction::Label(name) => TackyInstruction::Label(rl(name)),
        TackyInstruction::FunCall {
            name,
            args,
            dst,
            dst_type,
            is_variadic,
        } => TackyInstruction::FunCall {
            name: name.clone(), // 関数名はリネームしない
            args: args.iter().map(rv).collect(),
            dst: rv(dst),
            dst_type: dst_type.clone(),
            is_variadic: *is_variadic,
        },
        TackyInstruction::SignExtend { src, dst } => TackyInstruction::SignExtend {
            src: rv(src),
            dst: rv(dst),
        },
        TackyInstruction::ZeroExtend { src, dst } => TackyInstruction::ZeroExtend {
            src: rv(src),
            dst: rv(dst),
        },
        TackyInstruction::Truncate { src, dst } => TackyInstruction::Truncate {
            src: rv(src),
            dst: rv(dst),
        },
        TackyInstruction::IntToDouble { src, dst } => TackyInstruction::IntToDouble {
            src: rv(src),
            dst: rv(dst),
        },
        TackyInstruction::DoubleToInt { src, dst } => TackyInstruction::DoubleToInt {
            src: rv(src),
            dst: rv(dst),
        },
        TackyInstruction::UIntToDouble { src, dst } => TackyInstruction::UIntToDouble {
            src: rv(src),
            dst: rv(dst),
        },
        TackyInstruction::DoubleToUInt { src, dst } => TackyInstruction::DoubleToUInt {
            src: rv(src),
            dst: rv(dst),
        },
        TackyInstruction::FloatToDouble { src, dst } => TackyInstruction::FloatToDouble {
            src: rv(src),
            dst: rv(dst),
        },
        TackyInstruction::DoubleToFloat { src, dst } => TackyInstruction::DoubleToFloat {
            src: rv(src),
            dst: rv(dst),
        },
        TackyInstruction::IntToFloat { src, dst } => TackyInstruction::IntToFloat {
            src: rv(src),
            dst: rv(dst),
        },
        TackyInstruction::FloatToInt { src, dst } => TackyInstruction::FloatToInt {
            src: rv(src),
            dst: rv(dst),
        },
        TackyInstruction::UIntToFloat { src, dst } => TackyInstruction::UIntToFloat {
            src: rv(src),
            dst: rv(dst),
        },
        TackyInstruction::FloatToUInt { src, dst } => TackyInstruction::FloatToUInt {
            src: rv(src),
            dst: rv(dst),
        },
        TackyInstruction::GetAddress { src, dst } => TackyInstruction::GetAddress {
            src: rv(src),
            dst: rv(dst),
        },
        TackyInstruction::Load { src_ptr, dst } => TackyInstruction::Load {
            src_ptr: rv(src_ptr),
            dst: rv(dst),
        },
        TackyInstruction::Store { src, dst_ptr } => TackyInstruction::Store {
            src: rv(src),
            dst_ptr: rv(dst_ptr),
        },
        TackyInstruction::AddPtr {
            ptr,
            index,
            scale,
            dst,
        } => TackyInstruction::AddPtr {
            ptr: rv(ptr),
            index: rv(index),
            scale: *scale,
            dst: rv(dst),
        },
        TackyInstruction::CopyToOffset { src, dst, offset } => TackyInstruction::CopyToOffset {
            src: rv(src),
            dst: if static_names.contains(dst) {
                dst.clone()
            } else {
                format!("{}_{}", prefix, dst)
            },
            offset: *offset,
        },
        TackyInstruction::CopyFromOffset { src, offset, dst } => TackyInstruction::CopyFromOffset {
            src: if static_names.contains(src) {
                src.clone()
            } else {
                format!("{}_{}", prefix, src)
            },
            offset: *offset,
            dst: rv(dst),
        },
        TackyInstruction::CopyStruct { src, dst, size } => TackyInstruction::CopyStruct {
            src: rv(src),
            dst: rv(dst),
            size: *size,
        },
        TackyInstruction::JumpIndirect {
            target,
            possible_targets,
        } => TackyInstruction::JumpIndirect {
            target: rv(target),
            possible_targets: possible_targets.iter().map(|l| rl(l)).collect(),
        },
        TackyInstruction::VaStart {
            ap,
            gp_offset_init,
            fp_offset_init,
        } => TackyInstruction::VaStart {
            ap: rv(ap),
            gp_offset_init: *gp_offset_init,
            fp_offset_init: *fp_offset_init,
        },
        TackyInstruction::VaArg { ap, dst, arg_type } => TackyInstruction::VaArg {
            ap: rv(ap),
            dst: rv(dst),
            arg_type: arg_type.clone(),
        },
        TackyInstruction::VaEnd => TackyInstruction::VaEnd,
    }
}

// ─────────────────────────────────────────────────────────────
// Pass 13: Function Outlining(関数アウトライン化)
// ─────────────────────────────────────────────────────────────

/// コード断片を新しい関数に切り出す。
/// 偽の関数が大量に出現し、元の関数構造の復元を困難にする。
fn outline_functions(program: &mut TackyProgram, ctx: &mut ObfCtx, min_block_size: usize) {
    let mut new_functions: Vec<TackyFunction> = Vec::new();
    // 1関数あたりの最大アウトライン数(CFF の実行時オーバーヘッドを抑制)
    const MAX_OUTLINES_PER_FUNC: usize = 30;

    for func in &mut program.functions {
        let mut new_body: Vec<TackyInstruction> = Vec::new();
        let body = std::mem::take(&mut func.body);
        let mut i = 0;
        let mut outline_count = 0usize;

        while i < body.len() {
            // アウトライン候補ブロックを検索(上限チェック付き)
            if outline_count < MAX_OUTLINES_PER_FUNC
                && let Some(block_len) = find_outline_candidate(&body, i, min_block_size)
            {
                let block = &body[i..i + block_len];

                if let Some((inputs, output_name, intermediates)) =
                    analyze_block(block, &body, i, &func.var_types)
                {
                    // 入力変数 ≤ 6(整数レジスタ呼出規約の上限)
                    if inputs.len() <= 6 {
                        // Double / Struct / Array 型の入出力を除外
                        let output_type = func
                            .var_types
                            .get(&output_name)
                            .cloned()
                            .unwrap_or(Type::Int);
                        let has_bad_type = matches!(
                            output_type,
                            Type::Float | Type::Double | Type::Struct { .. } | Type::Array(_, _)
                        ) || inputs.iter().any(|name| {
                            let ty = func.var_types.get(name).unwrap_or(&Type::Int);
                            matches!(
                                ty,
                                Type::Float
                                    | Type::Double
                                    | Type::Struct { .. }
                                    | Type::Array(_, _)
                            )
                        });

                        if !has_bad_type {
                            // 新関数を構築
                            let outlined_func = build_outlined_function(
                                ctx,
                                block,
                                &inputs,
                                &output_name,
                                &intermediates,
                                &output_type,
                                &func.var_types,
                            );
                            let func_name = outlined_func.name.clone();

                            // 元の位置に FunCall を挿入
                            let call_args: Vec<TackyVal> = inputs
                                .iter()
                                .map(|name| TackyVal::Var(name.clone()))
                                .collect();
                            new_body.push(TackyInstruction::FunCall {
                                name: func_name,
                                args: call_args,
                                dst: TackyVal::Var(output_name),
                                dst_type: output_type,
                                is_variadic: false,
                            });

                            new_functions.push(outlined_func);
                            outline_count += 1;
                            i += block_len;
                            continue;
                        }
                    }
                }
            }

            new_body.push(body[i].clone());
            i += 1;
        }

        func.body = new_body;
    }

    // 新しく生成された関数をプログラムに追加
    program.functions.extend(new_functions);
}

/// アウトライン候補ブロックを検出する。
/// pos から始まる連続する Copy / Binary / Unary 命令のブロックを探す。
fn find_outline_candidate(body: &[TackyInstruction], pos: usize, min_size: usize) -> Option<usize> {
    let mut len = 0;
    for instr in &body[pos..] {
        match instr {
            TackyInstruction::Copy { .. }
            | TackyInstruction::Binary { .. }
            | TackyInstruction::Unary { .. } => {
                len += 1;
            }
            _ => break,
        }
    }
    if len >= min_size { Some(len) } else { None }
}

/// ブロックの入出力を解析する。
/// 成功時: (入力変数名リスト, 出力変数名, 中間変数名集合) を返す。
/// 安全でない場合は None を返す。
///
/// `full_body` は関数本体全体、`block_start` はブロックの開始位置。
/// 安全性チェックではブロック外の全命令(ブロック前+ブロック後)を走査する。
/// これによりループの後方ジャンプで使われる変数も正しく検出される。
fn analyze_block(
    block: &[TackyInstruction],
    full_body: &[TackyInstruction],
    block_start: usize,
    var_types: &HashMap<String, Type>,
) -> Option<(Vec<String>, String, HashSet<String>)> {
    let mut inputs: Vec<String> = Vec::new();
    let mut input_set: HashSet<String> = HashSet::new();
    let mut written: HashSet<String> = HashSet::new();

    for instr in block {
        // ソースオペランドを収集
        for src_val in instruction_sources(instr) {
            if let TackyVal::Var(name) = src_val
                && !written.contains(name)
                && !input_set.contains(name)
            {
                inputs.push(name.clone());
                input_set.insert(name.clone());
            }
        }
        // dst を written に追加
        if let Some(dst_name) = instruction_dst_name(instr) {
            written.insert(dst_name);
        }
    }

    // 出力 = 最後の命令の dst
    let output = instruction_dst_name(block.last()?)?;

    // 中間変数 = written - {output}
    let mut intermediates = written;
    intermediates.remove(&output);

    // 安全性チェック: 中間変数がブロック外(前方+後方)で使われていないか
    // ループの後方ジャンプで参照される変数を見逃さないよう全体を走査する
    if !intermediates.is_empty() {
        let block_end = block_start + block.len();
        for (idx, instr) in full_body.iter().enumerate() {
            // ブロック内の命令はスキップ
            if idx >= block_start && idx < block_end {
                continue;
            }
            for operand in instruction_all_operands(instr) {
                if let TackyVal::Var(name) = operand
                    && intermediates.contains(name)
                {
                    return None; // 中間変数がブロック外で使われている
                }
            }
            // FunCall.name / CopyToOffset.dst / CopyFromOffset.src は
            // String フィールドであり instruction_all_operands に含まれないため
            // 別途チェックする(間接呼び出し変数の漏れ防止)
            match instr {
                TackyInstruction::FunCall { name, .. } => {
                    if intermediates.contains(name) {
                        return None;
                    }
                }
                TackyInstruction::CopyToOffset { dst, .. } => {
                    if intermediates.contains(dst) {
                        return None;
                    }
                }
                TackyInstruction::CopyFromOffset { src, .. } => {
                    if intermediates.contains(src) {
                        return None;
                    }
                }
                _ => {}
            }
        }
    }

    // 入力変数の型チェック(Double / Struct / Array を除外)
    let _ = var_types; // 型チェックは呼び出し側で行う

    Some((inputs, output, intermediates))
}

/// 命令のソースオペランド(読まれる TackyVal)を返す
fn instruction_sources(instr: &TackyInstruction) -> Vec<&TackyVal> {
    match instr {
        TackyInstruction::Copy { src, .. } => vec![src],
        TackyInstruction::Unary { src, .. } => vec![src],
        TackyInstruction::Binary { left, right, .. } => vec![left, right],
        _ => vec![],
    }
}

/// 命令の dst 変数名を返す
fn instruction_dst_name(instr: &TackyInstruction) -> Option<String> {
    match instr {
        TackyInstruction::Copy {
            dst: TackyVal::Var(name),
            ..
        }
        | TackyInstruction::Unary {
            dst: TackyVal::Var(name),
            ..
        }
        | TackyInstruction::Binary {
            dst: TackyVal::Var(name),
            ..
        } => Some(name.clone()),
        _ => None,
    }
}

/// 命令の全オペランド(ソース+dst)を返す(中間変数の使用チェック用)
fn instruction_all_operands(instr: &TackyInstruction) -> Vec<&TackyVal> {
    match instr {
        TackyInstruction::Return(val) => vec![val],
        TackyInstruction::ReturnVoid => vec![],
        TackyInstruction::Unary { src, dst, .. } => vec![src, dst],
        TackyInstruction::Binary {
            left, right, dst, ..
        } => vec![left, right, dst],
        TackyInstruction::Copy { src, dst } => vec![src, dst],
        TackyInstruction::Jump(_) => vec![],
        TackyInstruction::JumpIfZero { condition, .. }
        | TackyInstruction::JumpIfNotZero { condition, .. } => vec![condition],
        TackyInstruction::Label(_) => vec![],
        TackyInstruction::FunCall { args, dst, .. } => {
            let mut v: Vec<&TackyVal> = args.iter().collect();
            v.push(dst);
            v
        }
        TackyInstruction::SignExtend { src, dst }
        | TackyInstruction::ZeroExtend { src, dst }
        | TackyInstruction::Truncate { src, dst }
        | TackyInstruction::IntToDouble { src, dst }
        | TackyInstruction::DoubleToInt { src, dst }
        | TackyInstruction::UIntToDouble { src, dst }
        | TackyInstruction::DoubleToUInt { src, dst }
        | TackyInstruction::FloatToDouble { src, dst }
        | TackyInstruction::DoubleToFloat { src, dst }
        | TackyInstruction::IntToFloat { src, dst }
        | TackyInstruction::FloatToInt { src, dst }
        | TackyInstruction::UIntToFloat { src, dst }
        | TackyInstruction::FloatToUInt { src, dst } => vec![src, dst],
        TackyInstruction::GetAddress { src, dst } => vec![src, dst],
        TackyInstruction::Load { src_ptr, dst } => vec![src_ptr, dst],
        TackyInstruction::Store { src, dst_ptr } => vec![src, dst_ptr],
        TackyInstruction::AddPtr {
            ptr, index, dst, ..
        } => vec![ptr, index, dst],
        TackyInstruction::CopyToOffset { src, .. } => vec![src],
        TackyInstruction::CopyFromOffset { dst, .. } => vec![dst],
        TackyInstruction::CopyStruct { src, dst, .. } => vec![src, dst],
        TackyInstruction::JumpIndirect { target, .. } => vec![target],
        TackyInstruction::VaStart { ap, .. } => vec![ap],
        TackyInstruction::VaArg { ap, dst, .. } => vec![ap, dst],
        TackyInstruction::VaEnd => vec![],
    }
}

/// 新関数を構築する
fn build_outlined_function(
    ctx: &mut ObfCtx,
    block: &[TackyInstruction],
    inputs: &[String],
    output_name: &str,
    intermediates: &HashSet<String>,
    output_type: &Type,
    caller_var_types: &HashMap<String, Type>,
) -> TackyFunction {
    let func_name = format!("_obf_outlined_{}", ctx.outline_counter);
    ctx.outline_counter += 1;

    // 入力変数→パラメータ名のマッピング
    let mut input_to_param: HashMap<String, String> = HashMap::new();
    let mut params: Vec<String> = Vec::new();
    let mut var_types: HashMap<String, Type> = HashMap::new();

    for input_name in inputs {
        let param_name = ctx.fresh_tmp();
        let ty = caller_var_types
            .get(input_name)
            .cloned()
            .unwrap_or(Type::Int);
        var_types.insert(param_name.clone(), ty);
        input_to_param.insert(input_name.clone(), param_name.clone());
        params.push(param_name);
    }

    // 中間変数→新名前のマッピング(ソート済みで決定的な順序)
    let mut intermediate_to_new: HashMap<String, String> = HashMap::new();
    let mut intermediates_sorted: Vec<&String> = intermediates.iter().collect();
    intermediates_sorted.sort();
    for name in intermediates_sorted {
        let new_name = ctx.fresh_tmp();
        let ty = caller_var_types.get(name).cloned().unwrap_or(Type::Int);
        var_types.insert(new_name.clone(), ty);
        intermediate_to_new.insert(name.clone(), new_name);
    }

    // 出力変数→新名前
    let output_new = ctx.fresh_tmp();
    var_types.insert(output_new.clone(), output_type.clone());

    // 出力変数が入力変数でもある場合の処理:
    // rename で input_to_param が優先されると output_new が未定義になるため、
    // output_name を input_to_param から除外し、関数本体先頭で
    // Copy { param → output_new } を挿入して初期値を渡す。
    let output_init_copy: Option<TackyInstruction> =
        input_to_param
            .remove(output_name)
            .map(|param_for_output| TackyInstruction::Copy {
                src: TackyVal::Var(param_for_output),
                dst: TackyVal::Var(output_new.clone()),
            });

    // 命令のリネーム
    let rename = |val: &TackyVal| -> TackyVal {
        match val {
            TackyVal::Var(name) => {
                if let Some(param) = input_to_param.get(name) {
                    TackyVal::Var(param.clone())
                } else if let Some(new_name) = intermediate_to_new.get(name) {
                    TackyVal::Var(new_name.clone())
                } else if name == output_name {
                    TackyVal::Var(output_new.clone())
                } else {
                    val.clone()
                }
            }
            TackyVal::Constant(_) => val.clone(),
        }
    };

    let mut body: Vec<TackyInstruction> = Vec::new();
    // 出力変数が入力でもある場合、パラメータから output_new への初期化コピーを挿入
    if let Some(init_copy) = output_init_copy {
        body.push(init_copy);
    }
    for instr in block {
        let new_instr = match instr {
            TackyInstruction::Copy { src, dst } => TackyInstruction::Copy {
                src: rename(src),
                dst: rename(dst),
            },
            TackyInstruction::Unary { op, src, dst } => TackyInstruction::Unary {
                op: *op,
                src: rename(src),
                dst: rename(dst),
            },
            TackyInstruction::Binary {
                op,
                left,
                right,
                dst,
            } => TackyInstruction::Binary {
                op: *op,
                left: rename(left),
                right: rename(right),
                dst: rename(dst),
            },
            _ => instr.clone(),
        };
        body.push(new_instr);
    }

    // Return(output)
    body.push(TackyInstruction::Return(TackyVal::Var(output_new)));

    TackyFunction {
        name: func_name,
        global: false,
        params,
        body,
        return_type: output_type.clone(),
        var_types,
        is_variadic: false,
        static_var_names: HashSet::new(),
        has_sret: false,
    }
}

// ─────────────────────────────────────────────────────────────
// Pass 6: String Encryption(文字列暗号化)
// ─────────────────────────────────────────────────────────────

/// 文字列定数を暗号化し、main() の先頭に復号コードを挿入する。
///
/// 1. static_constants から StringInit を抽出し、バイト列を加算暗号化
/// 2. 暗号化バイト列を ByteArrayInit として static_vars に移動(.data、書き込み可能)
/// 3. main() の先頭にアンロール復号コードを挿入:
///    各バイトを Load → Subtract(key) → Store で復号
fn string_encryption(program: &mut TackyProgram, ctx: &mut ObfCtx, key: u8) {
    // 暗号化対象の文字列定数を収集
    let mut encrypted_strings: Vec<(String, Vec<u8>, usize)> = Vec::new(); // (label, encrypted_bytes, original_len_with_null)

    program.static_constants.retain(|sc| {
        if let TackyStaticInit::StringInit(content, byte_len) = &sc.init {
            // 各バイトをキーで加算暗号化(null 終端含む)
            let mut encrypted: Vec<u8> = content
                .as_bytes()
                .iter()
                .map(|b| b.wrapping_add(key))
                .collect();
            // null 終端も暗号化
            encrypted.push(0u8.wrapping_add(key));

            encrypted_strings.push((sc.name.clone(), encrypted, *byte_len));
            false // static_constants から除去
        } else {
            true // StringInit 以外はそのまま残す
        }
    });

    if encrypted_strings.is_empty() {
        return;
    }

    // 暗号化バイト列を static_vars に追加(.data セクション、書き込み可能)
    for (label, encrypted_bytes, byte_len) in &encrypted_strings {
        program.static_vars.push(TackyStaticVar {
            name: label.clone(),
            global: false,
            var_type: Type::Array(Box::new(Type::Char), *byte_len),
            init: TackyStaticInit::ByteArrayInit(encrypted_bytes.clone()),
        });
    }

    // main() を探して先頭に復号コードを挿入
    if let Some(main_func) = program.functions.iter_mut().find(|f| f.name == "main") {
        let mut decrypt_instrs = Vec::new();

        for (label, _, byte_len) in &encrypted_strings {
            // base_ptr = &encrypted_string
            let base_ptr = ctx.fresh_tmp();
            main_func
                .var_types
                .insert(base_ptr.clone(), Type::Pointer(Box::new(Type::Char)));

            decrypt_instrs.push(TackyInstruction::GetAddress {
                src: TackyVal::Var(label.clone()),
                dst: TackyVal::Var(base_ptr.clone()),
            });

            // 各バイトを復号(アンロール)
            for i in 0..*byte_len {
                let byte_ptr = ctx.fresh_tmp();
                let enc_byte = ctx.fresh_tmp();
                let enc_int = ctx.fresh_tmp();
                let dec_int = ctx.fresh_tmp();
                let dec_byte = ctx.fresh_tmp();
                main_func
                    .var_types
                    .insert(byte_ptr.clone(), Type::Pointer(Box::new(Type::Char)));
                main_func.var_types.insert(enc_byte.clone(), Type::Char);
                main_func.var_types.insert(enc_int.clone(), Type::Int);
                main_func.var_types.insert(dec_int.clone(), Type::Int);
                main_func.var_types.insert(dec_byte.clone(), Type::Char);

                // byte_ptr = base_ptr + i
                decrypt_instrs.push(TackyInstruction::AddPtr {
                    ptr: TackyVal::Var(base_ptr.clone()),
                    index: TackyVal::Constant(TackyConst::Int(i as i32)),
                    scale: 1,
                    dst: TackyVal::Var(byte_ptr.clone()),
                });

                // enc_byte = *byte_ptr
                decrypt_instrs.push(TackyInstruction::Load {
                    src_ptr: TackyVal::Var(byte_ptr.clone()),
                    dst: TackyVal::Var(enc_byte.clone()),
                });

                // enc_int = sign_extend(enc_byte)
                decrypt_instrs.push(TackyInstruction::SignExtend {
                    src: TackyVal::Var(enc_byte),
                    dst: TackyVal::Var(enc_int.clone()),
                });

                // dec_int = enc_int - KEY
                decrypt_instrs.push(TackyInstruction::Binary {
                    op: TackyBinaryOp::Subtract,
                    left: TackyVal::Var(enc_int),
                    right: TackyVal::Constant(TackyConst::Int(key as i32)),
                    dst: TackyVal::Var(dec_int.clone()),
                });

                // dec_byte = truncate(dec_int)
                decrypt_instrs.push(TackyInstruction::Truncate {
                    src: TackyVal::Var(dec_int),
                    dst: TackyVal::Var(dec_byte.clone()),
                });

                // *byte_ptr = dec_byte
                decrypt_instrs.push(TackyInstruction::Store {
                    src: TackyVal::Var(dec_byte),
                    dst_ptr: TackyVal::Var(byte_ptr),
                });
            }
        }

        // main() の先頭に復号コードを挿入
        decrypt_instrs.append(&mut main_func.body);
        main_func.body = decrypt_instrs;
    }
}

// ─────────────────────────────────────────────────────────────
// Pass 1: Constant Encoding(定数の間接化)
// ─────────────────────────────────────────────────────────────

/// 定数 Copy を実行時計算に置換する。
/// `Copy { src: Constant(42), dst }` → `a * b + c` の演算に分解。
/// Double は精度問題があるためスキップ。
fn constant_encoding(
    instrs: Vec<TackyInstruction>,
    ctx: &mut ObfCtx,
    var_types: &mut std::collections::HashMap<String, Type>,
) -> Vec<TackyInstruction> {
    let mut result = Vec::new();

    for instr in instrs {
        match &instr {
            TackyInstruction::Copy {
                src: TackyVal::Constant(c),
                dst,
            } => {
                if let Some(encoded) = encode_constant(c, dst, ctx, var_types) {
                    result.extend(encoded);
                    continue;
                }
                result.push(instr);
            }
            _ => result.push(instr),
        }
    }

    result
}

/// 定数を `a * b + c` の形に分解する命令列を生成する。
fn encode_constant(
    c: &TackyConst,
    dst: &TackyVal,
    ctx: &mut ObfCtx,
    var_types: &mut std::collections::HashMap<String, Type>,
) -> Option<Vec<TackyInstruction>> {
    match c {
        TackyConst::Int(v) => Some(encode_int_constant(
            *v as i64,
            Type::Int,
            dst,
            ctx,
            var_types,
            |x| TackyConst::Int(x as i32),
        )),
        TackyConst::Long(v) => Some(encode_int_constant(
            *v,
            Type::Long,
            dst,
            ctx,
            var_types,
            TackyConst::Long,
        )),
        TackyConst::UInt(v) => Some(encode_int_constant(
            *v as i64,
            Type::UInt,
            dst,
            ctx,
            var_types,
            |x| TackyConst::UInt(x as u32),
        )),
        TackyConst::ULong(v) => Some(encode_int_constant(
            *v as i64,
            Type::ULong,
            dst,
            ctx,
            var_types,
            |x| TackyConst::ULong(x as u64),
        )),
        TackyConst::Char(v) => Some(encode_int_constant(
            *v as i64,
            Type::Char,
            dst,
            ctx,
            var_types,
            |x| TackyConst::Char(x as i8),
        )),
        TackyConst::UChar(v) => Some(encode_int_constant(
            *v as i64,
            Type::UChar,
            dst,
            ctx,
            var_types,
            |x| TackyConst::UChar(x as u8),
        )),
        // Float/Double は精度問題があるためスキップ
        TackyConst::Float(_) | TackyConst::Double(_) => None,
    }
}

/// 整数値を `a * b + c == value` に分解する命令列を生成する。
fn encode_int_constant<F>(
    value: i64,
    ty: Type,
    dst: &TackyVal,
    ctx: &mut ObfCtx,
    var_types: &mut std::collections::HashMap<String, Type>,
    make_const: F,
) -> Vec<TackyInstruction>
where
    F: Fn(i64) -> TackyConst,
{
    let mut instrs = Vec::new();

    if value == 0 {
        // 0 → a - a パターン
        let tmp_a = ctx.fresh_tmp();
        var_types.insert(tmp_a.clone(), ty.clone());

        instrs.push(TackyInstruction::Copy {
            src: TackyVal::Constant(make_const(7)),
            dst: TackyVal::Var(tmp_a.clone()),
        });
        instrs.push(TackyInstruction::Binary {
            op: TackyBinaryOp::Subtract,
            left: TackyVal::Var(tmp_a.clone()),
            right: TackyVal::Var(tmp_a),
            dst: dst.clone(),
        });
    } else {
        // value → a * b + c
        // 因数を見つける(簡易: 小さな因数で割る)
        let (a, b, c) = decompose_value(value);

        let tmp_a = ctx.fresh_tmp();
        let tmp_b = ctx.fresh_tmp();
        let tmp_mul = ctx.fresh_tmp();
        var_types.insert(tmp_a.clone(), ty.clone());
        var_types.insert(tmp_b.clone(), ty.clone());
        var_types.insert(tmp_mul.clone(), ty.clone());

        instrs.push(TackyInstruction::Copy {
            src: TackyVal::Constant(make_const(a)),
            dst: TackyVal::Var(tmp_a.clone()),
        });
        instrs.push(TackyInstruction::Copy {
            src: TackyVal::Constant(make_const(b)),
            dst: TackyVal::Var(tmp_b.clone()),
        });
        instrs.push(TackyInstruction::Binary {
            op: TackyBinaryOp::Multiply,
            left: TackyVal::Var(tmp_a),
            right: TackyVal::Var(tmp_b),
            dst: TackyVal::Var(tmp_mul.clone()),
        });

        if c == 0 {
            instrs.push(TackyInstruction::Copy {
                src: TackyVal::Var(tmp_mul),
                dst: dst.clone(),
            });
        } else {
            let tmp_c = ctx.fresh_tmp();
            var_types.insert(tmp_c.clone(), ty);

            instrs.push(TackyInstruction::Copy {
                src: TackyVal::Constant(make_const(c)),
                dst: TackyVal::Var(tmp_c.clone()),
            });
            instrs.push(TackyInstruction::Binary {
                op: TackyBinaryOp::Add,
                left: TackyVal::Var(tmp_mul),
                right: TackyVal::Var(tmp_c),
                dst: dst.clone(),
            });
        }
    }

    instrs
}

/// 値を `a * b + c` に分解する。a, b は小さめの因数。
fn decompose_value(value: i64) -> (i64, i64, i64) {
    let factors = [7, 5, 3, 11, 13, 6, 9];
    for &f in &factors {
        if value % f == 0 && value / f != 1 && value / f != 0 {
            return (f, value / f, 0);
        }
    }
    // 割り切れない場合: value = f * (value / f) + (value % f)
    let f = 7i64;
    let q = value / f;
    let r = value - f * q; // use value - f*q to handle negative values correctly
    if q != 0 {
        (f, q, r)
    } else {
        // 非常に小さな値(-6..6): 3 * 1 + (value - 3) など
        (3, 1, value - 3)
    }
}

// ─────────────────────────────────────────────────────────────
// Pass 2: Arithmetic Substitution(算術置換)
// ─────────────────────────────────────────────────────────────

/// Add/Subtract を数学的に等価な多段計算に置換する。
/// デコンパイラでの式復元を困難にする。
///
/// - Add → パターン0(アフィン変換)or パターン1(係数展開)をローテーション
/// - Subtract → パターン2(アフィン変換)or パターン3(係数展開)をローテーション
/// - Multiply, Divide, Double系 → スキップ(オーバーフロー・精度問題)
/// - `obf_tmp.*` 変数への操作 → スキップ(定数間接化との無限展開防止)
fn arithmetic_substitution(
    instrs: Vec<TackyInstruction>,
    ctx: &mut ObfCtx,
    var_types: &mut std::collections::HashMap<String, Type>,
    freq: usize,
) -> Vec<TackyInstruction> {
    let mut result = Vec::new();
    let mut candidate_count = 0;

    for instr in instrs {
        match &instr {
            TackyInstruction::Binary {
                op,
                left,
                right,
                dst,
            } => {
                // obf_tmp.* 変数への操作はスキップ(カスケード防止)
                let dst_is_obf = if let TackyVal::Var(name) = dst {
                    name.starts_with("obf_tmp.")
                } else {
                    false
                };

                if !dst_is_obf {
                    match op {
                        TackyBinaryOp::Add => {
                            candidate_count += 1;
                            if candidate_count % freq == 0 {
                                // パターン0/1 をローテーション
                                let pattern = ctx.label_counter % 2;
                                ctx.label_counter += 1;
                                match pattern {
                                    0 => result
                                        .extend(arith_add_affine(left, right, dst, ctx, var_types)),
                                    _ => result
                                        .extend(arith_add_coeff(left, right, dst, ctx, var_types)),
                                }
                                continue;
                            }
                        }
                        TackyBinaryOp::Subtract => {
                            candidate_count += 1;
                            if candidate_count % freq == 0 {
                                // パターン2/3 をローテーション
                                let pattern = ctx.label_counter % 2;
                                ctx.label_counter += 1;
                                match pattern {
                                    0 => result
                                        .extend(arith_sub_affine(left, right, dst, ctx, var_types)),
                                    _ => result
                                        .extend(arith_sub_coeff(left, right, dst, ctx, var_types)),
                                }
                                continue;
                            }
                        }
                        // Multiply, Divide, Double系はスキップ
                        _ => {}
                    }
                }

                result.push(instr);
            }
            _ => result.push(instr),
        }
    }

    result
}

/// dst の型を var_types から取得する。見つからなければ Int を返す。
fn get_dst_type(dst: &TackyVal, var_types: &std::collections::HashMap<String, Type>) -> Type {
    if let TackyVal::Var(name) = dst {
        var_types.get(name).cloned().unwrap_or(Type::Int)
    } else {
        Type::Int
    }
}

/// パターン0 — アフィン変換(Add):
/// `dst = a + b` → `tmp1 = a + K; tmp2 = b - K; dst = tmp1 + tmp2`
fn arith_add_affine(
    left: &TackyVal,
    right: &TackyVal,
    dst: &TackyVal,
    ctx: &mut ObfCtx,
    var_types: &mut std::collections::HashMap<String, Type>,
) -> Vec<TackyInstruction> {
    let ty = get_dst_type(dst, var_types);
    let k = ((ctx.label_counter as i64).wrapping_mul(0x9E37) ^ 0x1F2D) & 0x7FFF;
    let k_const = make_typed_const(&ty, k);
    let k_const2 = make_typed_const(&ty, k);

    let tmp1 = ctx.fresh_tmp();
    let tmp2 = ctx.fresh_tmp();
    var_types.insert(tmp1.clone(), ty.clone());
    var_types.insert(tmp2.clone(), ty);

    vec![
        // tmp1 = a + K
        TackyInstruction::Binary {
            op: TackyBinaryOp::Add,
            left: left.clone(),
            right: TackyVal::Constant(k_const),
            dst: TackyVal::Var(tmp1.clone()),
        },
        // tmp2 = b - K
        TackyInstruction::Binary {
            op: TackyBinaryOp::Subtract,
            left: right.clone(),
            right: TackyVal::Constant(k_const2),
            dst: TackyVal::Var(tmp2.clone()),
        },
        // dst = tmp1 + tmp2
        TackyInstruction::Binary {
            op: TackyBinaryOp::Add,
            left: TackyVal::Var(tmp1),
            right: TackyVal::Var(tmp2),
            dst: dst.clone(),
        },
    ]
}

/// パターン1 — 係数展開(Add):
/// `dst = a + b` → `dst = 3(a+b) - 2a - 2b = a + b`
fn arith_add_coeff(
    left: &TackyVal,
    right: &TackyVal,
    dst: &TackyVal,
    ctx: &mut ObfCtx,
    var_types: &mut std::collections::HashMap<String, Type>,
) -> Vec<TackyInstruction> {
    let ty = get_dst_type(dst, var_types);
    let three = make_typed_const(&ty, 3);
    let three2 = make_typed_const(&ty, 3);
    let two = make_typed_const(&ty, 2);
    let two2 = make_typed_const(&ty, 2);

    let tmp1 = ctx.fresh_tmp(); // a * 3
    let tmp2 = ctx.fresh_tmp(); // b * 3
    let tmp3 = ctx.fresh_tmp(); // 3a + 3b
    let tmp4 = ctx.fresh_tmp(); // a * 2
    let tmp5 = ctx.fresh_tmp(); // b * 2
    let tmp6 = ctx.fresh_tmp(); // 2a + 2b
    for t in [&tmp1, &tmp2, &tmp3, &tmp4, &tmp5, &tmp6] {
        var_types.insert(t.clone(), ty.clone());
    }

    vec![
        TackyInstruction::Binary {
            op: TackyBinaryOp::Multiply,
            left: left.clone(),
            right: TackyVal::Constant(three),
            dst: TackyVal::Var(tmp1.clone()),
        },
        TackyInstruction::Binary {
            op: TackyBinaryOp::Multiply,
            left: right.clone(),
            right: TackyVal::Constant(three2),
            dst: TackyVal::Var(tmp2.clone()),
        },
        TackyInstruction::Binary {
            op: TackyBinaryOp::Add,
            left: TackyVal::Var(tmp1),
            right: TackyVal::Var(tmp2),
            dst: TackyVal::Var(tmp3.clone()),
        },
        TackyInstruction::Binary {
            op: TackyBinaryOp::Multiply,
            left: left.clone(),
            right: TackyVal::Constant(two),
            dst: TackyVal::Var(tmp4.clone()),
        },
        TackyInstruction::Binary {
            op: TackyBinaryOp::Multiply,
            left: right.clone(),
            right: TackyVal::Constant(two2),
            dst: TackyVal::Var(tmp5.clone()),
        },
        TackyInstruction::Binary {
            op: TackyBinaryOp::Add,
            left: TackyVal::Var(tmp4),
            right: TackyVal::Var(tmp5),
            dst: TackyVal::Var(tmp6.clone()),
        },
        TackyInstruction::Binary {
            op: TackyBinaryOp::Subtract,
            left: TackyVal::Var(tmp3),
            right: TackyVal::Var(tmp6),
            dst: dst.clone(),
        },
    ]
}

/// パターン2 — アフィン変換(Subtract):
/// `dst = a - b` → `tmp1 = a + K; tmp2 = b + K; dst = tmp1 - tmp2`
fn arith_sub_affine(
    left: &TackyVal,
    right: &TackyVal,
    dst: &TackyVal,
    ctx: &mut ObfCtx,
    var_types: &mut std::collections::HashMap<String, Type>,
) -> Vec<TackyInstruction> {
    let ty = get_dst_type(dst, var_types);
    let k = ((ctx.label_counter as i64).wrapping_mul(0xA3B7) ^ 0x2E4C) & 0x7FFF;
    let k_const = make_typed_const(&ty, k);
    let k_const2 = make_typed_const(&ty, k);

    let tmp1 = ctx.fresh_tmp();
    let tmp2 = ctx.fresh_tmp();
    var_types.insert(tmp1.clone(), ty.clone());
    var_types.insert(tmp2.clone(), ty);

    vec![
        // tmp1 = a + K
        TackyInstruction::Binary {
            op: TackyBinaryOp::Add,
            left: left.clone(),
            right: TackyVal::Constant(k_const),
            dst: TackyVal::Var(tmp1.clone()),
        },
        // tmp2 = b + K
        TackyInstruction::Binary {
            op: TackyBinaryOp::Add,
            left: right.clone(),
            right: TackyVal::Constant(k_const2),
            dst: TackyVal::Var(tmp2.clone()),
        },
        // dst = tmp1 - tmp2
        TackyInstruction::Binary {
            op: TackyBinaryOp::Subtract,
            left: TackyVal::Var(tmp1),
            right: TackyVal::Var(tmp2),
            dst: dst.clone(),
        },
    ]
}

/// パターン3 — 係数展開(Subtract):
/// `dst = a - b` → `dst = 3a - 3b - (2a - 2b)`
fn arith_sub_coeff(
    left: &TackyVal,
    right: &TackyVal,
    dst: &TackyVal,
    ctx: &mut ObfCtx,
    var_types: &mut std::collections::HashMap<String, Type>,
) -> Vec<TackyInstruction> {
    let ty = get_dst_type(dst, var_types);
    let three = make_typed_const(&ty, 3);
    let three2 = make_typed_const(&ty, 3);
    let two = make_typed_const(&ty, 2);
    let two2 = make_typed_const(&ty, 2);

    let tmp1 = ctx.fresh_tmp(); // a * 3
    let tmp2 = ctx.fresh_tmp(); // b * 3
    let tmp3 = ctx.fresh_tmp(); // 3a - 3b
    let tmp4 = ctx.fresh_tmp(); // a * 2
    let tmp5 = ctx.fresh_tmp(); // b * 2
    let tmp6 = ctx.fresh_tmp(); // 2a - 2b
    for t in [&tmp1, &tmp2, &tmp3, &tmp4, &tmp5, &tmp6] {
        var_types.insert(t.clone(), ty.clone());
    }

    vec![
        TackyInstruction::Binary {
            op: TackyBinaryOp::Multiply,
            left: left.clone(),
            right: TackyVal::Constant(three),
            dst: TackyVal::Var(tmp1.clone()),
        },
        TackyInstruction::Binary {
            op: TackyBinaryOp::Multiply,
            left: right.clone(),
            right: TackyVal::Constant(three2),
            dst: TackyVal::Var(tmp2.clone()),
        },
        TackyInstruction::Binary {
            op: TackyBinaryOp::Subtract,
            left: TackyVal::Var(tmp1),
            right: TackyVal::Var(tmp2),
            dst: TackyVal::Var(tmp3.clone()),
        },
        TackyInstruction::Binary {
            op: TackyBinaryOp::Multiply,
            left: left.clone(),
            right: TackyVal::Constant(two),
            dst: TackyVal::Var(tmp4.clone()),
        },
        TackyInstruction::Binary {
            op: TackyBinaryOp::Multiply,
            left: right.clone(),
            right: TackyVal::Constant(two2),
            dst: TackyVal::Var(tmp5.clone()),
        },
        TackyInstruction::Binary {
            op: TackyBinaryOp::Subtract,
            left: TackyVal::Var(tmp4),
            right: TackyVal::Var(tmp5),
            dst: TackyVal::Var(tmp6.clone()),
        },
        TackyInstruction::Binary {
            op: TackyBinaryOp::Subtract,
            left: TackyVal::Var(tmp3),
            right: TackyVal::Var(tmp6),
            dst: dst.clone(),
        },
    ]
}

/// 型に応じた定数を生成する。
fn make_typed_const(ty: &Type, value: i64) -> TackyConst {
    match ty {
        Type::Int => TackyConst::Int(value as i32),
        Type::Long => TackyConst::Long(value),
        Type::UInt => TackyConst::UInt(value as u32),
        Type::ULong => TackyConst::ULong(value as u64),
        Type::Char => TackyConst::Char(value as i8),
        Type::UChar => TackyConst::UChar(value as u8),
        _ => TackyConst::Int(value as i32),
    }
}

// ─────────────────────────────────────────────────────────────
// Pass 3: Junk Code Insertion(ジャンクコード挿入)
// ─────────────────────────────────────────────────────────────

/// N命令ごとに dead computation(結果が使われない計算)を挿入する。
/// Label の直前には挿入しない。
fn junk_code_insertion(
    instrs: Vec<TackyInstruction>,
    ctx: &mut ObfCtx,
    var_types: &mut std::collections::HashMap<String, Type>,
    freq: usize,
) -> Vec<TackyInstruction> {
    let mut result = Vec::new();

    for (count, (i, instr)) in instrs.iter().enumerate().enumerate() {
        // N命令ごとにジャンクコードを挿入(ただし Label の直前は避ける)
        if count > 0 && count % freq == 0 {
            let next_is_label = instrs
                .get(i)
                .is_some_and(|next| matches!(next, TackyInstruction::Label(_)));
            if !next_is_label {
                result.extend(generate_junk(ctx, var_types));
            }
        }

        result.push(instr.clone());
    }

    result
}

/// ジャンクコード(dead computation)を3命令生成する。
fn generate_junk(
    ctx: &mut ObfCtx,
    var_types: &mut std::collections::HashMap<String, Type>,
) -> Vec<TackyInstruction> {
    let tmp_x = ctx.fresh_tmp();
    let tmp_y = ctx.fresh_tmp();
    let tmp_z = ctx.fresh_tmp();
    var_types.insert(tmp_x.clone(), Type::Int);
    var_types.insert(tmp_y.clone(), Type::Int);
    var_types.insert(tmp_z.clone(), Type::Int);

    vec![
        TackyInstruction::Copy {
            src: TackyVal::Constant(TackyConst::Int(0x1234)),
            dst: TackyVal::Var(tmp_x.clone()),
        },
        TackyInstruction::Copy {
            src: TackyVal::Constant(TackyConst::Int(0x5678)),
            dst: TackyVal::Var(tmp_y.clone()),
        },
        TackyInstruction::Binary {
            op: TackyBinaryOp::Add,
            left: TackyVal::Var(tmp_x),
            right: TackyVal::Var(tmp_y),
            dst: TackyVal::Var(tmp_z),
        },
    ]
}

// ─────────────────────────────────────────────────────────────
// Pass 4: Opaque Predicates(不透明述語)
// ─────────────────────────────────────────────────────────────

/// N回に1回、値生成命令を常に真の条件分岐で囲む。
/// `x * (x + 1) % 2 == 0` は任意の整数 x で常に真(連続整数の積は偶数)。
fn opaque_predicates(
    instrs: Vec<TackyInstruction>,
    ctx: &mut ObfCtx,
    var_types: &mut std::collections::HashMap<String, Type>,
    freq: usize,
) -> Vec<TackyInstruction> {
    let mut result = Vec::new();
    let mut candidate_count = 0;

    for instr in instrs.iter() {
        if is_value_producing(instr) {
            candidate_count += 1;
            if candidate_count % freq == 0 {
                result.extend(wrap_with_opaque_predicate(instr.clone(), ctx, var_types));
                continue;
            }
        }
        result.push(instr.clone());
    }

    result
}

/// 値を生成する命令かどうか判定する。
/// 副作用のある命令(FunCall, Store, Return)や制御フロー命令(Jump, Label)は除外。
fn is_value_producing(instr: &TackyInstruction) -> bool {
    matches!(
        instr,
        TackyInstruction::Copy { .. }
            | TackyInstruction::Unary { .. }
            | TackyInstruction::Binary { .. }
            | TackyInstruction::SignExtend { .. }
            | TackyInstruction::ZeroExtend { .. }
            | TackyInstruction::Truncate { .. }
    )
}

/// 不透明述語で命令を囲む(Feature 5: 多様化パターン)。
///
/// カウンタの mod 4 で使用するパターンを選択し、パターンマッチによる自動除去を防ぐ。
///
/// ```text
/// <predicate computation>   // pred == 0(常に真)
/// JumpIfZero(pred, .Lobf_real)
/// <偽コード>
/// Jump(.Lobf_end)
/// .Lobf_real:
/// <本物の命令>
/// .Lobf_end:
/// ```
fn wrap_with_opaque_predicate(
    real_instr: TackyInstruction,
    ctx: &mut ObfCtx,
    var_types: &mut std::collections::HashMap<String, Type>,
) -> Vec<TackyInstruction> {
    let mut instrs = Vec::new();

    // Use ".Lpred_" prefix so CFF treats these as block-internal labels
    let label_real = format!(".Lpred_{}", ctx.label_counter);
    ctx.label_counter += 1;
    let label_end = format!(".Lpred_{}", ctx.label_counter);
    ctx.label_counter += 1;

    // パターン選択(label_counter をローテーション)
    let pattern = ctx.label_counter % 4;

    let pred_var = match pattern {
        0 => generate_predicate_0(ctx, var_types, &mut instrs),
        1 => generate_predicate_1(ctx, var_types, &mut instrs),
        2 => generate_predicate_2(ctx, var_types, &mut instrs),
        3 => generate_predicate_3(ctx, var_types, &mut instrs),
        _ => unreachable!(),
    };

    // if pred == 0 goto real (always taken — all predicates produce 0)
    instrs.push(TackyInstruction::JumpIfZero {
        condition: TackyVal::Var(pred_var),
        target: label_real.clone(),
    });

    // 偽コード(到達不能)— ジャンク代入
    let tmp_fake = ctx.fresh_tmp();
    var_types.insert(tmp_fake.clone(), Type::Int);
    instrs.push(TackyInstruction::Copy {
        src: TackyVal::Constant(TackyConst::Int(0xDEAD)),
        dst: TackyVal::Var(tmp_fake),
    });
    instrs.push(TackyInstruction::Jump(label_end.clone()));

    // .Lobf_real:
    instrs.push(TackyInstruction::Label(label_real));

    // 本物の命令
    instrs.push(real_instr);

    // .Lobf_end:
    instrs.push(TackyInstruction::Label(label_end));

    instrs
}

/// パターン 0: `x*(x+1) % 2 == 0`(連続整数の積は偶数)
fn generate_predicate_0(
    ctx: &mut ObfCtx,
    var_types: &mut std::collections::HashMap<String, Type>,
    instrs: &mut Vec<TackyInstruction>,
) -> String {
    let tmp_x = ctx.fresh_tmp();
    let tmp_x_plus_1 = ctx.fresh_tmp();
    let tmp_prod = ctx.fresh_tmp();
    let tmp_pred = ctx.fresh_tmp();
    var_types.insert(tmp_x.clone(), Type::Int);
    var_types.insert(tmp_x_plus_1.clone(), Type::Int);
    var_types.insert(tmp_prod.clone(), Type::Int);
    var_types.insert(tmp_pred.clone(), Type::Int);

    instrs.push(TackyInstruction::Copy {
        src: TackyVal::Constant(TackyConst::Int(42)),
        dst: TackyVal::Var(tmp_x.clone()),
    });
    instrs.push(TackyInstruction::Binary {
        op: TackyBinaryOp::Add,
        left: TackyVal::Var(tmp_x.clone()),
        right: TackyVal::Constant(TackyConst::Int(1)),
        dst: TackyVal::Var(tmp_x_plus_1.clone()),
    });
    instrs.push(TackyInstruction::Binary {
        op: TackyBinaryOp::Multiply,
        left: TackyVal::Var(tmp_x),
        right: TackyVal::Var(tmp_x_plus_1),
        dst: TackyVal::Var(tmp_prod.clone()),
    });
    instrs.push(TackyInstruction::Binary {
        op: TackyBinaryOp::Remainder,
        left: TackyVal::Var(tmp_prod),
        right: TackyVal::Constant(TackyConst::Int(2)),
        dst: TackyVal::Var(tmp_pred.clone()),
    });

    tmp_pred
}

/// パターン 1: `x*x + 1 > 0` を `!(x*x + 1 > 0)` で表現 → 常に 0
/// x²≥0 なので x²+1≥1 > 0 は常に真。`!(true)` = 0。
fn generate_predicate_1(
    ctx: &mut ObfCtx,
    var_types: &mut std::collections::HashMap<String, Type>,
    instrs: &mut Vec<TackyInstruction>,
) -> String {
    let tmp_x = ctx.fresh_tmp();
    let tmp_sq = ctx.fresh_tmp();
    let tmp_sq_plus_1 = ctx.fresh_tmp();
    let tmp_gt = ctx.fresh_tmp();
    let tmp_pred = ctx.fresh_tmp();
    var_types.insert(tmp_x.clone(), Type::Int);
    var_types.insert(tmp_sq.clone(), Type::Int);
    var_types.insert(tmp_sq_plus_1.clone(), Type::Int);
    var_types.insert(tmp_gt.clone(), Type::Int);
    var_types.insert(tmp_pred.clone(), Type::Int);

    // x = 17
    instrs.push(TackyInstruction::Copy {
        src: TackyVal::Constant(TackyConst::Int(17)),
        dst: TackyVal::Var(tmp_x.clone()),
    });
    // sq = x * x
    instrs.push(TackyInstruction::Binary {
        op: TackyBinaryOp::Multiply,
        left: TackyVal::Var(tmp_x.clone()),
        right: TackyVal::Var(tmp_x),
        dst: TackyVal::Var(tmp_sq.clone()),
    });
    // sq_plus_1 = sq + 1
    instrs.push(TackyInstruction::Binary {
        op: TackyBinaryOp::Add,
        left: TackyVal::Var(tmp_sq),
        right: TackyVal::Constant(TackyConst::Int(1)),
        dst: TackyVal::Var(tmp_sq_plus_1.clone()),
    });
    // gt = sq_plus_1 > 0  (always 1)
    instrs.push(TackyInstruction::Binary {
        op: TackyBinaryOp::GreaterThan,
        left: TackyVal::Var(tmp_sq_plus_1),
        right: TackyVal::Constant(TackyConst::Int(0)),
        dst: TackyVal::Var(tmp_gt.clone()),
    });
    // pred = !gt  (always 0)
    instrs.push(TackyInstruction::Unary {
        op: TackyUnaryOp::Not,
        src: TackyVal::Var(tmp_gt),
        dst: TackyVal::Var(tmp_pred.clone()),
    });

    tmp_pred
}

/// パターン 2: `(x+1)² - x² - 1 == 2*x` — 展開すると恒等式
/// `(x+1)² - x² - 1 - 2*x` = `x² + 2x + 1 - x² - 1 - 2x` = 0
fn generate_predicate_2(
    ctx: &mut ObfCtx,
    var_types: &mut std::collections::HashMap<String, Type>,
    instrs: &mut Vec<TackyInstruction>,
) -> String {
    let tmp_x = ctx.fresh_tmp();
    let tmp_x1 = ctx.fresh_tmp();
    let tmp_x1_sq = ctx.fresh_tmp();
    let tmp_x_sq = ctx.fresh_tmp();
    let tmp_sub1 = ctx.fresh_tmp();
    let tmp_sub2 = ctx.fresh_tmp();
    let tmp_2x = ctx.fresh_tmp();
    let tmp_pred = ctx.fresh_tmp();
    var_types.insert(tmp_x.clone(), Type::Int);
    var_types.insert(tmp_x1.clone(), Type::Int);
    var_types.insert(tmp_x1_sq.clone(), Type::Int);
    var_types.insert(tmp_x_sq.clone(), Type::Int);
    var_types.insert(tmp_sub1.clone(), Type::Int);
    var_types.insert(tmp_sub2.clone(), Type::Int);
    var_types.insert(tmp_2x.clone(), Type::Int);
    var_types.insert(tmp_pred.clone(), Type::Int);

    // x = 13
    instrs.push(TackyInstruction::Copy {
        src: TackyVal::Constant(TackyConst::Int(13)),
        dst: TackyVal::Var(tmp_x.clone()),
    });
    // x1 = x + 1
    instrs.push(TackyInstruction::Binary {
        op: TackyBinaryOp::Add,
        left: TackyVal::Var(tmp_x.clone()),
        right: TackyVal::Constant(TackyConst::Int(1)),
        dst: TackyVal::Var(tmp_x1.clone()),
    });
    // x1_sq = x1 * x1
    instrs.push(TackyInstruction::Binary {
        op: TackyBinaryOp::Multiply,
        left: TackyVal::Var(tmp_x1.clone()),
        right: TackyVal::Var(tmp_x1),
        dst: TackyVal::Var(tmp_x1_sq.clone()),
    });
    // x_sq = x * x
    instrs.push(TackyInstruction::Binary {
        op: TackyBinaryOp::Multiply,
        left: TackyVal::Var(tmp_x.clone()),
        right: TackyVal::Var(tmp_x.clone()),
        dst: TackyVal::Var(tmp_x_sq.clone()),
    });
    // sub1 = x1_sq - x_sq
    instrs.push(TackyInstruction::Binary {
        op: TackyBinaryOp::Subtract,
        left: TackyVal::Var(tmp_x1_sq),
        right: TackyVal::Var(tmp_x_sq),
        dst: TackyVal::Var(tmp_sub1.clone()),
    });
    // sub2 = sub1 - 1
    instrs.push(TackyInstruction::Binary {
        op: TackyBinaryOp::Subtract,
        left: TackyVal::Var(tmp_sub1),
        right: TackyVal::Constant(TackyConst::Int(1)),
        dst: TackyVal::Var(tmp_sub2.clone()),
    });
    // 2x = 2 * x
    instrs.push(TackyInstruction::Binary {
        op: TackyBinaryOp::Multiply,
        left: TackyVal::Constant(TackyConst::Int(2)),
        right: TackyVal::Var(tmp_x),
        dst: TackyVal::Var(tmp_2x.clone()),
    });
    // pred = sub2 - 2x  (always 0)
    instrs.push(TackyInstruction::Binary {
        op: TackyBinaryOp::Subtract,
        left: TackyVal::Var(tmp_sub2),
        right: TackyVal::Var(tmp_2x),
        dst: TackyVal::Var(tmp_pred.clone()),
    });

    tmp_pred
}

/// パターン 3: `(x³ - x) % 3 == 0`(連続3整数の積は3の倍数)
/// x*(x-1)*(x+1) = x³ - x は 3 の倍数。
fn generate_predicate_3(
    ctx: &mut ObfCtx,
    var_types: &mut std::collections::HashMap<String, Type>,
    instrs: &mut Vec<TackyInstruction>,
) -> String {
    let tmp_x = ctx.fresh_tmp();
    let tmp_x_sq = ctx.fresh_tmp();
    let tmp_x_cubed = ctx.fresh_tmp();
    let tmp_diff = ctx.fresh_tmp();
    let tmp_pred = ctx.fresh_tmp();
    var_types.insert(tmp_x.clone(), Type::Int);
    var_types.insert(tmp_x_sq.clone(), Type::Int);
    var_types.insert(tmp_x_cubed.clone(), Type::Int);
    var_types.insert(tmp_diff.clone(), Type::Int);
    var_types.insert(tmp_pred.clone(), Type::Int);

    // x = 7
    instrs.push(TackyInstruction::Copy {
        src: TackyVal::Constant(TackyConst::Int(7)),
        dst: TackyVal::Var(tmp_x.clone()),
    });
    // x_sq = x * x
    instrs.push(TackyInstruction::Binary {
        op: TackyBinaryOp::Multiply,
        left: TackyVal::Var(tmp_x.clone()),
        right: TackyVal::Var(tmp_x.clone()),
        dst: TackyVal::Var(tmp_x_sq.clone()),
    });
    // x_cubed = x_sq * x
    instrs.push(TackyInstruction::Binary {
        op: TackyBinaryOp::Multiply,
        left: TackyVal::Var(tmp_x_sq),
        right: TackyVal::Var(tmp_x.clone()),
        dst: TackyVal::Var(tmp_x_cubed.clone()),
    });
    // diff = x_cubed - x
    instrs.push(TackyInstruction::Binary {
        op: TackyBinaryOp::Subtract,
        left: TackyVal::Var(tmp_x_cubed),
        right: TackyVal::Var(tmp_x),
        dst: TackyVal::Var(tmp_diff.clone()),
    });
    // pred = diff % 3  (always 0)
    instrs.push(TackyInstruction::Binary {
        op: TackyBinaryOp::Remainder,
        left: TackyVal::Var(tmp_diff),
        right: TackyVal::Constant(TackyConst::Int(3)),
        dst: TackyVal::Var(tmp_pred.clone()),
    });

    tmp_pred
}

// ─────────────────────────────────────────────────────────────
// Pass 14: VM Virtualization(VM仮想化 — コード仮想化)
// ─────────────────────────────────────────────────────────────

/// VM仮想化の適格性を判定する。
///
/// 以下の条件をすべて満たす関数が適格:
/// - `main` でない(文字列暗号化の復号コードとの干渉を回避)
/// - `Double` 型の変数がない
/// - 浮動小数点変換命令がない(IntToDouble, DoubleToInt, UIntToDouble, DoubleToUInt)
/// - 構造体操作命令がない(CopyToOffset, CopyFromOffset, CopyStruct)
/// - 本体が 2 命令以上
fn is_vm_eligible(func: &TackyFunction) -> bool {
    if func.name == "main" {
        return false;
    }
    if func.body.len() < 2 {
        return false;
    }
    if func
        .var_types
        .values()
        .any(|t| matches!(t, Type::Float | Type::Double))
    {
        return false;
    }
    for instr in &func.body {
        match instr {
            TackyInstruction::IntToDouble { .. }
            | TackyInstruction::DoubleToInt { .. }
            | TackyInstruction::UIntToDouble { .. }
            | TackyInstruction::DoubleToUInt { .. }
            | TackyInstruction::FloatToDouble { .. }
            | TackyInstruction::DoubleToFloat { .. }
            | TackyInstruction::IntToFloat { .. }
            | TackyInstruction::FloatToInt { .. }
            | TackyInstruction::UIntToFloat { .. }
            | TackyInstruction::FloatToUInt { .. }
            | TackyInstruction::CopyToOffset { .. }
            | TackyInstruction::CopyFromOffset { .. }
            | TackyInstruction::CopyStruct { .. } => return false,
            _ => {}
        }
    }
    true
}

/// 適格な関数をバイトコード+VMインタプリタに変換する。
///
/// 各TACKY命令を個別のハンドラに配置し、バイトコード配列とハンドラテーブルを
/// `.data` セクションに配置する。ディスパッチループが `bytecode[PC]` をフェッチし
/// ハンドラテーブルから間接ジャンプすることで元の命令列を実行する。
///
/// 元のTACKY変数・型はそのまま保持し、命令単位の細粒度ディスパッチにより
/// 静的解析でのCFG復元を極めて困難にする。
fn vm_virtualize(program: &mut TackyProgram, ctx: &mut ObfCtx) {
    let func_count = program.functions.len();
    for fi in 0..func_count {
        if !is_vm_eligible(&program.functions[fi]) {
            continue;
        }

        let func = &program.functions[fi];
        let original_body = func.body.clone();
        let n = original_body.len();
        if n == 0 {
            continue;
        }

        // Step 1: ラベル → PC マッピング構築
        let mut label_to_pc: HashMap<String, usize> = HashMap::new();
        for (i, instr) in original_body.iter().enumerate() {
            if let TackyInstruction::Label(name) = instr {
                label_to_pc.insert(name.clone(), i);
            }
        }

        // Step 2: ハンドララベル生成
        let dispatch_label = ctx.fresh_label();
        let handler_labels: Vec<String> = (0..n).map(|_| ctx.fresh_label()).collect();

        // Step 3: バイトコード配列(ByteArrayInit)
        // 各命令のハンドラインデックスを u32 LE で格納(初期状態: 命令 i → ハンドラ i)
        let mut bc_bytes: Vec<u8> = Vec::new();
        for i in 0..n {
            bc_bytes.extend_from_slice(&(i as u32).to_le_bytes());
        }
        let bc_name = format!(".Lobf_vm_bc_{}", ctx.vm_counter);
        program.static_vars.push(TackyStaticVar {
            name: bc_name.clone(),
            global: false,
            var_type: Type::Array(Box::new(Type::UChar), bc_bytes.len()),
            init: TackyStaticInit::ByteArrayInit(bc_bytes),
        });

        // Step 4: ハンドラテーブル(PointerArrayInit)
        let jt_name = format!(".Lobf_vm_jt_{}", ctx.vm_counter);
        program.static_vars.push(TackyStaticVar {
            name: jt_name.clone(),
            global: false,
            var_type: Type::Array(Box::new(Type::Long), n),
            init: TackyStaticInit::PointerArrayInit(handler_labels.clone()),
        });

        ctx.vm_counter += 1;

        // Step 5: 新しい関数本体を生成
        let var_types = &mut program.functions[fi].var_types;
        let mut new_body: Vec<TackyInstruction> = Vec::new();

        // VM ローカル変数を登録
        // NOTE: pc_var は Long(64ビット)にする。AddPtr の codegen が index を
        // 常に Quadword (movq) で読み込むため、Int (32ビット) だとスタック上の
        // 隣接データをゴミとして読み込んでしまう。
        let pc_var = ctx.fresh_tmp();
        let bc_ptr_var = ctx.fresh_tmp();
        let jt_ptr_var = ctx.fresh_tmp();
        var_types.insert(pc_var.clone(), Type::Long);
        var_types.insert(bc_ptr_var.clone(), Type::Pointer(Box::new(Type::UChar)));
        var_types.insert(jt_ptr_var.clone(), Type::Pointer(Box::new(Type::Long)));

        // ── 初期化 ──
        // _vm_pc = 0
        new_body.push(TackyInstruction::Copy {
            src: TackyVal::Constant(TackyConst::Long(0)),
            dst: TackyVal::Var(pc_var.clone()),
        });
        // _vm_bc_ptr = &bytecode_data
        new_body.push(TackyInstruction::GetAddress {
            src: TackyVal::Var(bc_name),
            dst: TackyVal::Var(bc_ptr_var.clone()),
        });
        // _vm_jt_ptr = &handler_table
        new_body.push(TackyInstruction::GetAddress {
            src: TackyVal::Var(jt_name),
            dst: TackyVal::Var(jt_ptr_var.clone()),
        });
        // Jump(dispatch)
        new_body.push(TackyInstruction::Jump(dispatch_label.clone()));

        // ── ディスパッチループ ──
        new_body.push(TackyInstruction::Label(dispatch_label.clone()));

        // ディスパッチ用一時変数
        let fetch_ptr_var = ctx.fresh_tmp();
        let handler_idx_var = ctx.fresh_tmp();
        let handler_addr_ptr_var = ctx.fresh_tmp();
        let handler_addr_var = ctx.fresh_tmp();
        var_types.insert(fetch_ptr_var.clone(), Type::Pointer(Box::new(Type::Int)));
        var_types.insert(handler_idx_var.clone(), Type::Int);
        var_types.insert(
            handler_addr_ptr_var.clone(),
            Type::Pointer(Box::new(Type::Long)),
        );
        var_types.insert(handler_addr_var.clone(), Type::Long);

        // fetch_ptr = AddPtr(bc_ptr, pc, scale=4)  — bytecode[pc] のアドレス
        new_body.push(TackyInstruction::AddPtr {
            ptr: TackyVal::Var(bc_ptr_var.clone()),
            index: TackyVal::Var(pc_var.clone()),
            scale: 4,
            dst: TackyVal::Var(fetch_ptr_var.clone()),
        });

        // handler_idx = Load(fetch_ptr)  — u32 ハンドラインデックス
        new_body.push(TackyInstruction::Load {
            src_ptr: TackyVal::Var(fetch_ptr_var),
            dst: TackyVal::Var(handler_idx_var.clone()),
        });

        // pc = pc + 1
        new_body.push(TackyInstruction::Binary {
            op: TackyBinaryOp::Add,
            left: TackyVal::Var(pc_var.clone()),
            right: TackyVal::Constant(TackyConst::Long(1)),
            dst: TackyVal::Var(pc_var.clone()),
        });

        // handler_idx は Int (32ビット) なので AddPtr の前に Long に拡張する
        let handler_idx_long_var = ctx.fresh_tmp();
        var_types.insert(handler_idx_long_var.clone(), Type::Long);
        new_body.push(TackyInstruction::SignExtend {
            src: TackyVal::Var(handler_idx_var),
            dst: TackyVal::Var(handler_idx_long_var.clone()),
        });

        // handler_addr_ptr = AddPtr(jt_ptr, handler_idx_long, scale=8)
        new_body.push(TackyInstruction::AddPtr {
            ptr: TackyVal::Var(jt_ptr_var.clone()),
            index: TackyVal::Var(handler_idx_long_var),
            scale: 8,
            dst: TackyVal::Var(handler_addr_ptr_var.clone()),
        });

        // handler_addr = Load(handler_addr_ptr)
        new_body.push(TackyInstruction::Load {
            src_ptr: TackyVal::Var(handler_addr_ptr_var),
            dst: TackyVal::Var(handler_addr_var.clone()),
        });

        // JumpIndirect(handler_addr, all_handler_labels)
        new_body.push(TackyInstruction::JumpIndirect {
            target: TackyVal::Var(handler_addr_var),
            possible_targets: handler_labels.clone(),
        });

        // ── ハンドラ群(元の各命令に対応) ──
        for (i, instr) in original_body.iter().enumerate() {
            new_body.push(TackyInstruction::Label(handler_labels[i].clone()));

            match instr {
                // Label: ノーオペ → dispatch に戻る
                TackyInstruction::Label(_) => {
                    new_body.push(TackyInstruction::Jump(dispatch_label.clone()));
                }

                // Jump(target): PC を即値で設定 → dispatch に戻る
                TackyInstruction::Jump(target) => {
                    if let Some(&target_pc) = label_to_pc.get(target) {
                        new_body.push(TackyInstruction::Copy {
                            src: TackyVal::Constant(TackyConst::Long(target_pc as i64)),
                            dst: TackyVal::Var(pc_var.clone()),
                        });
                    }
                    new_body.push(TackyInstruction::Jump(dispatch_label.clone()));
                }

                // JumpIfZero { condition, target }:
                // condition==0 で target_pc に設定、非ゼロなら PC そのまま
                TackyInstruction::JumpIfZero { condition, target } => {
                    if let Some(&target_pc) = label_to_pc.get(target) {
                        let skip = ctx.fresh_label();
                        new_body.push(TackyInstruction::JumpIfNotZero {
                            condition: condition.clone(),
                            target: skip.clone(),
                        });
                        // ゼロ → PC を target_pc に設定
                        new_body.push(TackyInstruction::Copy {
                            src: TackyVal::Constant(TackyConst::Long(target_pc as i64)),
                            dst: TackyVal::Var(pc_var.clone()),
                        });
                        new_body.push(TackyInstruction::Label(skip));
                    }
                    new_body.push(TackyInstruction::Jump(dispatch_label.clone()));
                }

                // JumpIfNotZero { condition, target }:
                // condition!=0 で target_pc に設定、ゼロなら PC そのまま
                TackyInstruction::JumpIfNotZero { condition, target } => {
                    if let Some(&target_pc) = label_to_pc.get(target) {
                        let skip = ctx.fresh_label();
                        new_body.push(TackyInstruction::JumpIfZero {
                            condition: condition.clone(),
                            target: skip.clone(),
                        });
                        // 非ゼロ → PC を target_pc に設定
                        new_body.push(TackyInstruction::Copy {
                            src: TackyVal::Constant(TackyConst::Long(target_pc as i64)),
                            dst: TackyVal::Var(pc_var.clone()),
                        });
                        new_body.push(TackyInstruction::Label(skip));
                    }
                    new_body.push(TackyInstruction::Jump(dispatch_label.clone()));
                }

                // Return / ReturnVoid: そのまま出力(dispatch に戻らない)
                TackyInstruction::Return(_) | TackyInstruction::ReturnVoid => {
                    new_body.push(instr.clone());
                }

                // その他全命令: そのまま出力 + dispatch に戻る
                _ => {
                    new_body.push(instr.clone());
                    new_body.push(TackyInstruction::Jump(dispatch_label.clone()));
                }
            }
        }

        program.functions[fi].body = new_body;
    }
}

// ─────────────────────────────────────────────────────────────
// Pass 5: Control Flow Flattening(制御フロー平坦化)
// ─────────────────────────────────────────────────────────────

/// 関数本体を基本ブロックに分割し、ジャンプテーブル + 状態エンコードの dispatch ループに変換する。
///
/// Feature 1: ジャンプテーブルによる間接ジャンプ(IDA の CFG 復元を破壊)
/// Feature 4: 状態変数の算術エンコード(ステートマシン復元を妨害)
///
/// ```text
/// obf_state = 0 * A + B     // encoded initial state
/// .Lobf_dispatch:
///   decoded = (obf_state - B) / A
///   ptr = jt_base + decoded * 8
///   JumpIndirect(Load(ptr))
/// block_0: <元のコード> obf_state = next_encoded; goto dispatch
/// block_1: ...
/// ```
fn control_flow_flattening(
    instrs: Vec<TackyInstruction>,
    ctx: &mut ObfCtx,
    var_types: &mut std::collections::HashMap<String, Type>,
    static_vars: &mut Vec<TackyStaticVar>,
    cff_a: i32,
    cff_b: i32,
) -> Vec<TackyInstruction> {
    if instrs.is_empty() {
        return instrs;
    }

    // 基本ブロックに分割
    let blocks = split_into_blocks(&instrs);

    // 単一ブロック関数はスキップ
    if blocks.len() <= 1 {
        return instrs;
    }

    // variadic 関数呼び出しを含む関数は CFF をスキップ
    // (CFF の dispatch ループが variadic ABI のレジスタ設定と干渉する)
    let has_variadic_call = instrs.iter().any(|i| {
        matches!(
            i,
            TackyInstruction::FunCall {
                is_variadic: true,
                ..
            }
        )
    });
    if has_variadic_call {
        return instrs;
    }

    // ラベル → ブロックインデックスのマッピングを構築
    let mut label_to_block: std::collections::HashMap<String, usize> =
        std::collections::HashMap::new();
    for (i, block) in blocks.iter().enumerate() {
        if let Some(TackyInstruction::Label(label)) = block.first() {
            label_to_block.insert(label.clone(), i);
        }
    }

    let state_var = ctx.fresh_tmp();
    var_types.insert(state_var.clone(), Type::Int);

    let dispatch_label = ctx.fresh_label();
    let exit_label = ctx.fresh_label();

    let mut result = Vec::new();

    // 各ブロック用のラベルを生成
    let block_labels: Vec<String> = (0..blocks.len()).map(|_| ctx.fresh_label()).collect();

    // ── ジャンプテーブルを静的変数として登録(Feature 1)──
    let jt_name = format!(".Lobf_jt_{}", ctx.label_counter);
    ctx.label_counter += 1;

    static_vars.push(TackyStaticVar {
        name: jt_name.clone(),
        global: false,
        var_type: Type::Array(Box::new(Type::Long), blocks.len()),
        init: TackyStaticInit::PointerArrayInit(block_labels.clone()),
    });

    // ── エンコード関数: index → index * A + B ──
    let encode = |index: usize| -> i32 { (index as i32).wrapping_mul(cff_a).wrapping_add(cff_b) };

    // obf_state = encode(0) = 0 * A + B = B
    result.push(TackyInstruction::Copy {
        src: TackyVal::Constant(TackyConst::Int(encode(0))),
        dst: TackyVal::Var(state_var.clone()),
    });

    // goto dispatch
    result.push(TackyInstruction::Jump(dispatch_label.clone()));

    // ── Dispatch: デコード + ジャンプテーブル間接ジャンプ ──
    result.push(TackyInstruction::Label(dispatch_label.clone()));

    // decoded = (state - B) / A
    let tmp_sub = ctx.fresh_tmp();
    let decoded_index = ctx.fresh_tmp();
    var_types.insert(tmp_sub.clone(), Type::Int);
    var_types.insert(decoded_index.clone(), Type::Int);

    result.push(TackyInstruction::Binary {
        op: TackyBinaryOp::Subtract,
        left: TackyVal::Var(state_var.clone()),
        right: TackyVal::Constant(TackyConst::Int(cff_b)),
        dst: TackyVal::Var(tmp_sub.clone()),
    });
    result.push(TackyInstruction::Binary {
        op: TackyBinaryOp::Divide,
        left: TackyVal::Var(tmp_sub),
        right: TackyVal::Constant(TackyConst::Int(cff_a)),
        dst: TackyVal::Var(decoded_index.clone()),
    });

    // base = &jump_table
    let jt_base = ctx.fresh_tmp();
    var_types.insert(jt_base.clone(), Type::Pointer(Box::new(Type::Long)));

    result.push(TackyInstruction::GetAddress {
        src: TackyVal::Var(jt_name),
        dst: TackyVal::Var(jt_base.clone()),
    });

    // ptr = base + decoded_index * 8
    let jt_ptr = ctx.fresh_tmp();
    var_types.insert(jt_ptr.clone(), Type::Pointer(Box::new(Type::Long)));

    result.push(TackyInstruction::AddPtr {
        ptr: TackyVal::Var(jt_base),
        index: TackyVal::Var(decoded_index),
        scale: 8,
        dst: TackyVal::Var(jt_ptr.clone()),
    });

    // addr = *ptr
    let jt_addr = ctx.fresh_tmp();
    var_types.insert(jt_addr.clone(), Type::Long);

    result.push(TackyInstruction::Load {
        src_ptr: TackyVal::Var(jt_ptr),
        dst: TackyVal::Var(jt_addr.clone()),
    });

    // JumpIndirect(addr) — possible_targets で生存解析に正しい CFG 後続を通知
    result.push(TackyInstruction::JumpIndirect {
        target: TackyVal::Var(jt_addr),
        possible_targets: block_labels.clone(),
    });

    // ── Block bodies ──
    for (i, block) in blocks.iter().enumerate() {
        result.push(TackyInstruction::Label(block_labels[i].clone()));

        // ブロック内の命令を出力
        for instr in block {
            match instr {
                // 元のラベルは保持(CFF ブロックラベルに加えて残す。
                // VM仮想化のハンドラテーブル等 .data セクションから参照される可能性がある)
                TackyInstruction::Label(_) => {
                    result.push(instr.clone());
                }

                // Return はそのまま出力(関数から直接脱出)
                TackyInstruction::Return(_) | TackyInstruction::ReturnVoid => {
                    result.push(instr.clone());
                }

                // Jump → encoded state 設定 + dispatch へ戻る
                TackyInstruction::Jump(target) => {
                    if let Some(&target_block) = label_to_block.get(target) {
                        result.push(TackyInstruction::Copy {
                            src: TackyVal::Constant(TackyConst::Int(encode(target_block))),
                            dst: TackyVal::Var(state_var.clone()),
                        });
                        result.push(TackyInstruction::Jump(dispatch_label.clone()));
                    } else {
                        // ターゲットが見つからない場合はそのまま
                        result.push(instr.clone());
                    }
                }

                // JumpIfZero → 条件付き encoded state 設定
                TackyInstruction::JumpIfZero { condition, target } => {
                    if let Some(&target_block) = label_to_block.get(target) {
                        let fallthrough_block = i + 1;
                        let tmp_is_zero = ctx.fresh_tmp();
                        var_types.insert(tmp_is_zero.clone(), Type::Int);

                        result.push(TackyInstruction::Binary {
                            op: TackyBinaryOp::Equal,
                            left: condition.clone(),
                            right: TackyVal::Constant(TackyConst::Int(0)),
                            dst: TackyVal::Var(tmp_is_zero.clone()),
                        });
                        result.push(TackyInstruction::JumpIfNotZero {
                            condition: TackyVal::Var(tmp_is_zero),
                            target: format!("{}_taken", block_labels[i]),
                        });

                        // Not taken: state = encode(fallthrough)
                        if fallthrough_block < blocks.len() {
                            result.push(TackyInstruction::Copy {
                                src: TackyVal::Constant(TackyConst::Int(encode(fallthrough_block))),
                                dst: TackyVal::Var(state_var.clone()),
                            });
                        }
                        result.push(TackyInstruction::Jump(dispatch_label.clone()));

                        // Taken: state = encode(target)
                        result.push(TackyInstruction::Label(format!(
                            "{}_taken",
                            block_labels[i]
                        )));
                        result.push(TackyInstruction::Copy {
                            src: TackyVal::Constant(TackyConst::Int(encode(target_block))),
                            dst: TackyVal::Var(state_var.clone()),
                        });
                        result.push(TackyInstruction::Jump(dispatch_label.clone()));
                    } else {
                        result.push(instr.clone());
                    }
                }

                // JumpIfNotZero → 条件付き encoded state 設定
                TackyInstruction::JumpIfNotZero { condition, target } => {
                    if let Some(&target_block) = label_to_block.get(target) {
                        let fallthrough_block = i + 1;

                        result.push(TackyInstruction::JumpIfNotZero {
                            condition: condition.clone(),
                            target: format!("{}_taken", block_labels[i]),
                        });

                        // Not taken: state = encode(fallthrough)
                        if fallthrough_block < blocks.len() {
                            result.push(TackyInstruction::Copy {
                                src: TackyVal::Constant(TackyConst::Int(encode(fallthrough_block))),
                                dst: TackyVal::Var(state_var.clone()),
                            });
                        }
                        result.push(TackyInstruction::Jump(dispatch_label.clone()));

                        // Taken: state = encode(target)
                        result.push(TackyInstruction::Label(format!(
                            "{}_taken",
                            block_labels[i]
                        )));
                        result.push(TackyInstruction::Copy {
                            src: TackyVal::Constant(TackyConst::Int(encode(target_block))),
                            dst: TackyVal::Var(state_var.clone()),
                        });
                        result.push(TackyInstruction::Jump(dispatch_label.clone()));
                    } else {
                        result.push(instr.clone());
                    }
                }

                // その他の命令はそのまま
                _ => {
                    result.push(instr.clone());
                }
            }
        }

        // ブロックの最後が制御フロー命令でない場合、次のブロックへフォールスルー
        let last = block.last();
        let is_terminator = last.is_some_and(|l| {
            matches!(
                l,
                TackyInstruction::Jump(_)
                    | TackyInstruction::JumpIfZero { .. }
                    | TackyInstruction::JumpIfNotZero { .. }
                    | TackyInstruction::Return(_)
                    | TackyInstruction::ReturnVoid
            )
        });

        if !is_terminator {
            let next_block = i + 1;
            if next_block < blocks.len() {
                result.push(TackyInstruction::Copy {
                    src: TackyVal::Constant(TackyConst::Int(encode(next_block))),
                    dst: TackyVal::Var(state_var.clone()),
                });
                result.push(TackyInstruction::Jump(dispatch_label.clone()));
            }
        }
    }

    // ── Exit label ──
    result.push(TackyInstruction::Label(exit_label));

    result
}

/// 命令列を基本ブロックに分割する。
///
/// ブロック境界の定義:
/// - **ブロックの先頭**: 関数の先頭、ラベル命令、ジャンプ/リターンの直後
/// - **ブロックの末尾**: ジャンプ/リターン命令、次のラベルの直前
fn split_into_blocks(instrs: &[TackyInstruction]) -> Vec<Vec<TackyInstruction>> {
    if instrs.is_empty() {
        return vec![];
    }

    let mut blocks: Vec<Vec<TackyInstruction>> = Vec::new();
    let mut current_block: Vec<TackyInstruction> = Vec::new();

    // Helper: check if a jump/label is an opaque predicate internal target
    let is_pred_label = |label: &str| label.starts_with(".Lpred_");

    for instr in instrs {
        match instr {
            TackyInstruction::Label(label) if is_pred_label(label) => {
                // Opaque predicate internal label — keep in current block
                current_block.push(instr.clone());
            }
            TackyInstruction::Label(_) => {
                // ラベルは新しいブロックの先頭
                if !current_block.is_empty() {
                    blocks.push(std::mem::take(&mut current_block));
                }
                current_block.push(instr.clone());
            }
            TackyInstruction::Jump(target) if is_pred_label(target) => {
                current_block.push(instr.clone());
            }
            TackyInstruction::JumpIfZero { target, .. } if is_pred_label(target) => {
                current_block.push(instr.clone());
            }
            TackyInstruction::JumpIfNotZero { target, .. } if is_pred_label(target) => {
                current_block.push(instr.clone());
            }
            TackyInstruction::Jump(_)
            | TackyInstruction::JumpIfZero { .. }
            | TackyInstruction::JumpIfNotZero { .. }
            | TackyInstruction::Return(_)
            | TackyInstruction::ReturnVoid => {
                current_block.push(instr.clone());
                blocks.push(std::mem::take(&mut current_block));
            }
            _ => {
                current_block.push(instr.clone());
            }
        }
    }

    if !current_block.is_empty() {
        blocks.push(current_block);
    }

    blocks
}

// ─────────────────────────────────────────────────────────────
// Pass 16: OPSEC 衛生化(シンボルリネーム + 文字列リーク警告)
// ─────────────────────────────────────────────────────────────

/// OPSEC 文字列リーク警告 — 文字列リテラルに疑わしいパターンが含まれていれば stderr に警告
///
/// 検出対象:
/// - IP アドレスパターン
/// - ファイルパス
/// - URL
/// - デバッグ系キーワード
/// - 資格情報関連キーワード
fn opsec_warn_strings(
    program: &TackyProgram,
    policy: OpsecPolicy,
) -> std::result::Result<(), usize> {
    let tag = match policy {
        OpsecPolicy::Warn => "OPSEC WARNING",
        OpsecPolicy::Deny => "OPSEC ERROR",
    };

    let mut violations: Vec<String> = Vec::new();

    for sc in &program.static_constants {
        if let TackyStaticInit::StringInit(content, _) = &sc.init {
            let lower = content.to_lowercase();

            // IP アドレスパターン(簡易マッチ: N.N.N.N)
            if contains_ip_pattern(content) {
                violations.push(format!(
                    "[{tag}] String literal may contain IP address: \"{}\"",
                    truncate_str(content, 60)
                ));
            }

            // ファイルパス
            if content.contains("/home/")
                || content.contains("/tmp/")
                || content.contains("/etc/")
                || content.contains("C:\\")
                || content.contains("\\\\")
            {
                violations.push(format!(
                    "[{tag}] String literal may contain file path: \"{}\"",
                    truncate_str(content, 60)
                ));
            }

            // URL
            if lower.contains("http://") || lower.contains("https://") || lower.contains("ftp://") {
                violations.push(format!(
                    "[{tag}] String literal may contain URL: \"{}\"",
                    truncate_str(content, 60)
                ));
            }

            // デバッグ系キーワード
            for keyword in &["debug", "todo", "fixme"] {
                if lower.contains(keyword) {
                    violations.push(format!(
                        "[{tag}] String literal contains debug keyword \"{}\": \"{}\"",
                        keyword,
                        truncate_str(content, 60)
                    ));
                    break;
                }
            }

            // 資格情報関連キーワード
            for keyword in &[
                "password",
                "passwd",
                "secret",
                "api_key",
                "token",
                "credential",
            ] {
                if lower.contains(keyword) {
                    violations.push(format!(
                        "[{tag}] String literal contains sensitive keyword \"{}\": \"{}\"",
                        keyword,
                        truncate_str(content, 60)
                    ));
                    break;
                }
            }
        }
    }

    // 一括出力
    for v in &violations {
        eprintln!("{v}");
    }

    if policy == OpsecPolicy::Deny && !violations.is_empty() {
        Err(violations.len())
    } else {
        Ok(())
    }
}

/// 文字列中に IP アドレスパターン(N.N.N.N)が含まれるか簡易判定
fn contains_ip_pattern(s: &str) -> bool {
    let bytes = s.as_bytes();
    let len = bytes.len();
    let mut i = 0;
    while i < len {
        // 数字の開始位置を探す
        if bytes[i].is_ascii_digit() {
            let mut dots = 0;
            let mut j = i;
            let mut valid = true;
            // N.N.N.N の4つのオクテットを検証
            for _ in 0..4 {
                if j >= len || !bytes[j].is_ascii_digit() {
                    valid = false;
                    break;
                }
                // 1〜3桁の数字を読む
                let start = j;
                while j < len && bytes[j].is_ascii_digit() {
                    j += 1;
                }
                if j - start > 3 {
                    valid = false;
                    break;
                }
                dots += 1;
                if dots < 4 {
                    if j >= len || bytes[j] != b'.' {
                        valid = false;
                        break;
                    }
                    j += 1; // skip '.'
                }
            }
            if valid && dots == 4 {
                return true;
            }
        }
        i += 1;
    }
    false
}

/// 文字列を最大 max_len 文字(char 単位)に切り詰める
fn truncate_str(s: &str, max_len: usize) -> String {
    if s.chars().count() <= max_len {
        s.to_string()
    } else {
        let truncated: String = s.chars().take(max_len).collect();
        format!("{truncated}...")
    }
}

/// OPSEC シンボル難読化 — 関数名・グローバル変数名・静的定数名をリネーム
///
/// リネーム対象外:
/// - `main`(エントリポイント)
/// - 外部関数(定義がなく宣言のみ: `printf`, `strcmp` 等)
/// - ラベル名(`.L` プレフィックス)
fn opsec_sanitize(
    program: &mut TackyProgram,
    ctx: &mut ObfCtx,
    strip: bool,
    preserve_globals: bool,
) {
    let mut rename_map: HashMap<String, String> = HashMap::new();

    // 定義済み関数の名前セットを構築(外部関数の判定に使用)
    let defined_funcs: HashSet<String> = program.functions.iter().map(|f| f.name.clone()).collect();

    // 関数名のリネームマップ構築
    // preserve_globals=true: multi-file でリンク可視性が必要なため global 関数を保持
    for func in &program.functions {
        if func.name == "main" || (preserve_globals && func.global) {
            continue;
        }
        let new_name = format!("_f{}", ctx.opsec_counter);
        ctx.opsec_counter += 1;
        rename_map.insert(func.name.clone(), new_name);
    }

    // グローバル変数名のリネームマップ構築
    for sv in &program.static_vars {
        if (preserve_globals && sv.global) || rename_map.contains_key(&sv.name) {
            continue;
        }
        let new_name = format!("_v{}", ctx.opsec_counter);
        ctx.opsec_counter += 1;
        rename_map.insert(sv.name.clone(), new_name);
    }

    // 静的定数名のリネームマップ構築
    for sc in &program.static_constants {
        if !rename_map.contains_key(&sc.name) {
            let new_name = format!("_c{}", ctx.opsec_counter);
            ctx.opsec_counter += 1;
            rename_map.insert(sc.name.clone(), new_name);
        }
    }

    // グローバル変数名の集合(var_types rename 時にローカル変数を除外するため)
    let static_var_names: HashSet<String> = program
        .static_vars
        .iter()
        .map(|sv| sv.name.clone())
        .collect();

    // 関数名をリネーム
    for func in &mut program.functions {
        if let Some(new_name) = rename_map.get(&func.name) {
            func.name = new_name.clone();
        }
        // body 内の全命令を走査してリネーム
        opsec_rename_body(&mut func.body, &rename_map, &defined_funcs);
        // var_types のキーもリネーム(グローバル変数のみ — ローカル変数を誤 rename しない)
        for sv_name in static_var_names.iter() {
            if let Some(new_name) = rename_map.get(sv_name)
                && let Some(ty) = func.var_types.remove(sv_name)
            {
                func.var_types.insert(new_name.clone(), ty);
            }
        }
    }

    // グローバル変数名をリネーム
    for sv in &mut program.static_vars {
        if let Some(new_name) = rename_map.get(&sv.name) {
            sv.name = new_name.clone();
        }
        // PointerArrayInit 内のラベル参照もリネーム
        opsec_rename_init(&mut sv.init, &rename_map);
    }

    // 静的定数名をリネーム
    for sc in &mut program.static_constants {
        if let Some(new_name) = rename_map.get(&sc.name) {
            sc.name = new_name.clone();
        }
    }

    // .globl 抑制: main 以外の全シンボルを internal linkage にする
    // preserve_globals 時は元から global だったシンボルを保持(multi-file リンク用)
    if strip {
        for func in &mut program.functions {
            if func.name == "main" || (preserve_globals && func.global) {
                continue;
            }
            func.global = false;
        }
        for sv in &mut program.static_vars {
            if preserve_globals && sv.global {
                continue;
            }
            sv.global = false;
        }
    }
}

/// TackyVal 内の変数名をリネームマップに従って置換
fn opsec_rename_val(val: &mut TackyVal, rename_map: &HashMap<String, String>) {
    if let TackyVal::Var(name) = val
        && let Some(new_name) = rename_map.get(name.as_str())
    {
        *name = new_name.clone();
    }
}

/// 静的初期化子内のラベル参照をリネーム
fn opsec_rename_init(init: &mut TackyStaticInit, rename_map: &HashMap<String, String>) {
    match init {
        TackyStaticInit::PointerArrayInit(labels) => {
            for label in labels {
                if let Some(new_name) = rename_map.get(label.as_str()) {
                    *label = new_name.clone();
                }
            }
        }
        TackyStaticInit::ArrayInit(inits) => {
            for sub in inits {
                opsec_rename_init(sub, rename_map);
            }
        }
        _ => {}
    }
}

/// 命令列中の関数呼び出し・変数参照をリネーム
fn opsec_rename_body(
    body: &mut [TackyInstruction],
    rename_map: &HashMap<String, String>,
    defined_funcs: &HashSet<String>,
) {
    for instr in body.iter_mut() {
        match instr {
            TackyInstruction::Return(val) => {
                opsec_rename_val(val, rename_map);
            }
            TackyInstruction::ReturnVoid => {}
            TackyInstruction::Unary { src, dst, .. } => {
                opsec_rename_val(src, rename_map);
                opsec_rename_val(dst, rename_map);
            }
            TackyInstruction::Binary {
                left, right, dst, ..
            } => {
                opsec_rename_val(left, rename_map);
                opsec_rename_val(right, rename_map);
                opsec_rename_val(dst, rename_map);
            }
            TackyInstruction::Copy { src, dst } => {
                opsec_rename_val(src, rename_map);
                opsec_rename_val(dst, rename_map);
            }
            TackyInstruction::Jump(_) => {}
            TackyInstruction::JumpIfZero { condition, .. } => {
                opsec_rename_val(condition, rename_map);
            }
            TackyInstruction::JumpIfNotZero { condition, .. } => {
                opsec_rename_val(condition, rename_map);
            }
            TackyInstruction::Label(_) => {}
            TackyInstruction::FunCall {
                name, args, dst, ..
            } => {
                // 外部関数(定義がない)はリネームしない
                if defined_funcs.contains(name.as_str())
                    && let Some(new_name) = rename_map.get(name.as_str())
                {
                    *name = new_name.clone();
                }
                for arg in args {
                    opsec_rename_val(arg, rename_map);
                }
                opsec_rename_val(dst, rename_map);
            }
            TackyInstruction::SignExtend { src, dst }
            | TackyInstruction::ZeroExtend { src, dst }
            | TackyInstruction::Truncate { src, dst }
            | TackyInstruction::IntToDouble { src, dst }
            | TackyInstruction::DoubleToInt { src, dst }
            | TackyInstruction::UIntToDouble { src, dst }
            | TackyInstruction::DoubleToUInt { src, dst }
            | TackyInstruction::FloatToDouble { src, dst }
            | TackyInstruction::DoubleToFloat { src, dst }
            | TackyInstruction::IntToFloat { src, dst }
            | TackyInstruction::FloatToInt { src, dst }
            | TackyInstruction::UIntToFloat { src, dst }
            | TackyInstruction::FloatToUInt { src, dst } => {
                opsec_rename_val(src, rename_map);
                opsec_rename_val(dst, rename_map);
            }
            TackyInstruction::GetAddress { src, dst } => {
                opsec_rename_val(src, rename_map);
                opsec_rename_val(dst, rename_map);
            }
            TackyInstruction::Load { src_ptr, dst } => {
                opsec_rename_val(src_ptr, rename_map);
                opsec_rename_val(dst, rename_map);
            }
            TackyInstruction::Store { src, dst_ptr } => {
                opsec_rename_val(src, rename_map);
                opsec_rename_val(dst_ptr, rename_map);
            }
            TackyInstruction::AddPtr {
                ptr, index, dst, ..
            } => {
                opsec_rename_val(ptr, rename_map);
                opsec_rename_val(index, rename_map);
                opsec_rename_val(dst, rename_map);
            }
            TackyInstruction::CopyToOffset { src, dst, .. } => {
                opsec_rename_val(src, rename_map);
                if let Some(new_name) = rename_map.get(dst.as_str()) {
                    *dst = new_name.clone();
                }
            }
            TackyInstruction::CopyFromOffset { src, dst, .. } => {
                if let Some(new_name) = rename_map.get(src.as_str()) {
                    *src = new_name.clone();
                }
                opsec_rename_val(dst, rename_map);
            }
            TackyInstruction::CopyStruct { src, dst, .. } => {
                opsec_rename_val(src, rename_map);
                opsec_rename_val(dst, rename_map);
            }
            TackyInstruction::JumpIndirect { target, .. } => {
                opsec_rename_val(target, rename_map);
            }
            TackyInstruction::VaStart { ap, .. } => {
                opsec_rename_val(ap, rename_map);
            }
            TackyInstruction::VaArg { ap, dst, .. } => {
                opsec_rename_val(ap, rename_map);
                opsec_rename_val(dst, rename_map);
            }
            TackyInstruction::VaEnd => {}
        }
    }
}

// ─────────────────────────────────────────────────────────────
// ユニットテスト
// ─────────────────────────────────────────────────────────────

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

    fn make_int_var(name: &str) -> TackyVal {
        TackyVal::Var(name.to_string())
    }

    fn make_var_types(names: &[&str]) -> HashMap<String, Type> {
        names.iter().map(|n| (n.to_string(), Type::Int)).collect()
    }

    #[test]
    fn test_constant_encoding_replaces_int_constants() {
        let instrs = vec![
            TackyInstruction::Copy {
                src: TackyVal::Constant(TackyConst::Int(42)),
                dst: make_int_var("x"),
            },
            TackyInstruction::Return(make_int_var("x")),
        ];
        let mut ctx = ObfCtx::new();
        let mut var_types = make_var_types(&["x"]);

        let result = constant_encoding(instrs, &mut ctx, &mut var_types);

        // 定数 42 が直接 Copy されていないこと
        let has_direct_42 = result.iter().any(|i| matches!(i,
            TackyInstruction::Copy { src: TackyVal::Constant(TackyConst::Int(42)), .. }
            if !matches!(i, TackyInstruction::Copy { dst: TackyVal::Var(n), .. } if n.starts_with("obf_tmp."))
        ));
        assert!(!has_direct_42, "constant 42 should be encoded");

        // Binary 演算(Multiply)が含まれていること
        let has_multiply = result.iter().any(|i| {
            matches!(
                i,
                TackyInstruction::Binary {
                    op: TackyBinaryOp::Multiply,
                    ..
                }
            )
        });
        assert!(has_multiply, "should contain a multiply operation");
    }

    #[test]
    fn test_constant_encoding_zero_uses_subtract() {
        let instrs = vec![TackyInstruction::Copy {
            src: TackyVal::Constant(TackyConst::Int(0)),
            dst: make_int_var("x"),
        }];
        let mut ctx = ObfCtx::new();
        let mut var_types = make_var_types(&["x"]);

        let result = constant_encoding(instrs, &mut ctx, &mut var_types);

        let has_subtract = result.iter().any(|i| {
            matches!(
                i,
                TackyInstruction::Binary {
                    op: TackyBinaryOp::Subtract,
                    ..
                }
            )
        });
        assert!(has_subtract, "zero should use a-a subtract pattern");
    }

    #[test]
    fn test_constant_encoding_skips_double() {
        let instrs = vec![TackyInstruction::Copy {
            src: TackyVal::Constant(TackyConst::Double(3.15)),
            dst: make_int_var("x"),
        }];
        let mut ctx = ObfCtx::new();
        let mut var_types = make_var_types(&["x"]);

        let result = constant_encoding(instrs, &mut ctx, &mut var_types);

        // Double はそのまま残る
        assert_eq!(result.len(), 1);
        assert!(matches!(
            &result[0],
            TackyInstruction::Copy {
                src: TackyVal::Constant(TackyConst::Double(_)),
                ..
            }
        ));
    }

    #[test]
    fn test_junk_code_increases_instruction_count() {
        let instrs = vec![
            TackyInstruction::Copy {
                src: TackyVal::Constant(TackyConst::Int(1)),
                dst: make_int_var("a"),
            },
            TackyInstruction::Copy {
                src: TackyVal::Constant(TackyConst::Int(2)),
                dst: make_int_var("b"),
            },
            TackyInstruction::Copy {
                src: TackyVal::Constant(TackyConst::Int(3)),
                dst: make_int_var("c"),
            },
            TackyInstruction::Copy {
                src: TackyVal::Constant(TackyConst::Int(4)),
                dst: make_int_var("d"),
            },
            TackyInstruction::Return(make_int_var("d")),
        ];
        let original_len = instrs.len();
        let mut ctx = ObfCtx::new();
        let mut var_types = make_var_types(&["a", "b", "c", "d"]);

        let result = junk_code_insertion(instrs, &mut ctx, &mut var_types, 4);

        assert!(
            result.len() > original_len,
            "junk code should increase instruction count"
        );
    }

    #[test]
    fn test_opaque_predicates_inserts_branches() {
        // 5つ以上の値生成命令があると、不透明述語が挿入される
        let instrs = vec![
            TackyInstruction::Copy {
                src: TackyVal::Constant(TackyConst::Int(1)),
                dst: make_int_var("a"),
            },
            TackyInstruction::Copy {
                src: TackyVal::Constant(TackyConst::Int(2)),
                dst: make_int_var("b"),
            },
            TackyInstruction::Copy {
                src: TackyVal::Constant(TackyConst::Int(3)),
                dst: make_int_var("c"),
            },
            TackyInstruction::Copy {
                src: TackyVal::Constant(TackyConst::Int(4)),
                dst: make_int_var("d"),
            },
            TackyInstruction::Copy {
                src: TackyVal::Constant(TackyConst::Int(5)),
                dst: make_int_var("e"),
            },
            TackyInstruction::Return(make_int_var("e")),
        ];
        let mut ctx = ObfCtx::new();
        let mut var_types = make_var_types(&["a", "b", "c", "d", "e"]);

        let result = opaque_predicates(instrs, &mut ctx, &mut var_types, 5);

        // JumpIfZero(不透明述語の分岐)が挿入されていること
        let has_jump_if_zero = result
            .iter()
            .any(|i| matches!(i, TackyInstruction::JumpIfZero { .. }));
        assert!(
            has_jump_if_zero,
            "opaque predicates should insert conditional branches"
        );
    }

    #[test]
    fn test_control_flow_flattening_adds_dispatch() {
        let instrs = vec![
            TackyInstruction::Copy {
                src: TackyVal::Constant(TackyConst::Int(1)),
                dst: make_int_var("x"),
            },
            TackyInstruction::JumpIfZero {
                condition: make_int_var("x"),
                target: ".L_else".to_string(),
            },
            TackyInstruction::Copy {
                src: TackyVal::Constant(TackyConst::Int(10)),
                dst: make_int_var("r"),
            },
            TackyInstruction::Jump(".L_end".to_string()),
            TackyInstruction::Label(".L_else".to_string()),
            TackyInstruction::Copy {
                src: TackyVal::Constant(TackyConst::Int(20)),
                dst: make_int_var("r"),
            },
            TackyInstruction::Label(".L_end".to_string()),
            TackyInstruction::Return(make_int_var("r")),
        ];
        let mut ctx = ObfCtx::new();
        let mut var_types = make_var_types(&["x", "r"]);
        let mut static_vars = Vec::new();

        let result = control_flow_flattening(
            instrs,
            &mut ctx,
            &mut var_types,
            &mut static_vars,
            37,
            0xCAFE,
        );

        // dispatch ラベル(.Lobf_)が存在すること
        let has_dispatch_label = result.iter().any(|i| {
            if let TackyInstruction::Label(l) = i {
                l.starts_with(".Lobf_")
            } else {
                false
            }
        });
        assert!(has_dispatch_label, "CFF should add dispatch labels");

        // state 変数(obf_tmp.)が使用されていること
        let has_state_var = result.iter().any(|i| {
            if let TackyInstruction::Copy {
                dst: TackyVal::Var(n),
                ..
            } = i
            {
                n.starts_with("obf_tmp.")
            } else {
                false
            }
        });
        assert!(has_state_var, "CFF should use obf_tmp state variable");

        // ジャンプテーブルが static_vars に追加されていること(Feature 1)
        assert!(
            !static_vars.is_empty(),
            "CFF should create jump table static var"
        );
        let jt_var = &static_vars[0];
        assert!(
            matches!(&jt_var.init, TackyStaticInit::PointerArrayInit(_)),
            "jump table should use PointerArrayInit"
        );

        // JumpIndirect が存在すること(Feature 1)
        let has_jump_indirect = result
            .iter()
            .any(|i| matches!(i, TackyInstruction::JumpIndirect { .. }));
        assert!(
            has_jump_indirect,
            "CFF should use JumpIndirect for dispatch"
        );

        // 状態エンコード定数(CFF_B = 0xCAFE)が使用されていること(Feature 4)
        let has_cafe = result.iter().any(|i| {
            if let TackyInstruction::Copy {
                src: TackyVal::Constant(TackyConst::Int(v)),
                ..
            } = i
            {
                *v == 0xCAFE_u16 as i32
            } else {
                false
            }
        });
        assert!(has_cafe, "CFF should use encoded state values (0xCAFE)");
    }

    #[test]
    fn test_opaque_predicate_diversification() {
        // Feature 5: 4つの異なるパターンが使用されることを確認
        let mut ctx = ObfCtx::new();
        let mut var_types = make_var_types(&[]);

        // 各パターンが使われることを確認(label_counter % 4 で選択)
        for i in 0..4 {
            ctx.label_counter = i;
            let instr = TackyInstruction::Copy {
                src: TackyVal::Constant(TackyConst::Int(42)),
                dst: make_int_var("test_dst"),
            };
            let result = wrap_with_opaque_predicate(instr, &mut ctx, &mut var_types);

            // JumpIfZero が必ず含まれること
            let has_jump = result
                .iter()
                .any(|i| matches!(i, TackyInstruction::JumpIfZero { .. }));
            assert!(has_jump, "pattern {i} should generate JumpIfZero");
        }
    }

    #[test]
    fn test_arith_subst_expands_add() {
        // freq=1 で全ての Add が置換されることを確認
        let instrs = vec![TackyInstruction::Binary {
            op: TackyBinaryOp::Add,
            left: make_int_var("a"),
            right: make_int_var("b"),
            dst: make_int_var("c"),
        }];
        let mut ctx = ObfCtx::new();
        let mut var_types = make_var_types(&["a", "b", "c"]);

        let result = arithmetic_substitution(instrs, &mut ctx, &mut var_types, 1);

        // 元の1命令が3命令以上に展開されること
        assert!(
            result.len() >= 3,
            "Add should be expanded to 3+ instructions, got {}",
            result.len()
        );
        // 元のAdd命令がそのまま残っていないこと
        let has_original = result.len() == 1;
        assert!(!has_original, "original Add should be replaced");
    }

    #[test]
    fn test_arith_subst_expands_subtract() {
        let instrs = vec![TackyInstruction::Binary {
            op: TackyBinaryOp::Subtract,
            left: make_int_var("a"),
            right: make_int_var("b"),
            dst: make_int_var("c"),
        }];
        let mut ctx = ObfCtx::new();
        let mut var_types = make_var_types(&["a", "b", "c"]);

        let result = arithmetic_substitution(instrs, &mut ctx, &mut var_types, 1);

        assert!(
            result.len() >= 3,
            "Subtract should be expanded to 3+ instructions, got {}",
            result.len()
        );
    }

    #[test]
    fn test_arith_subst_skips_multiply() {
        let instrs = vec![TackyInstruction::Binary {
            op: TackyBinaryOp::Multiply,
            left: make_int_var("a"),
            right: make_int_var("b"),
            dst: make_int_var("c"),
        }];
        let mut ctx = ObfCtx::new();
        let mut var_types = make_var_types(&["a", "b", "c"]);

        let result = arithmetic_substitution(instrs, &mut ctx, &mut var_types, 1);

        // Multiply はそのまま残る
        assert_eq!(result.len(), 1, "Multiply should not be expanded");
    }

    #[test]
    fn test_arith_subst_skips_obf_tmp() {
        // obf_tmp.* への操作はカスケード防止でスキップされる
        let instrs = vec![TackyInstruction::Binary {
            op: TackyBinaryOp::Add,
            left: make_int_var("a"),
            right: make_int_var("b"),
            dst: TackyVal::Var("obf_tmp.0".to_string()),
        }];
        let mut ctx = ObfCtx::new();
        let mut var_types = make_var_types(&["a", "b"]);
        var_types.insert("obf_tmp.0".to_string(), Type::Int);

        let result = arithmetic_substitution(instrs, &mut ctx, &mut var_types, 1);

        // obf_tmp への Add はスキップされる
        assert_eq!(result.len(), 1, "Add to obf_tmp should not be expanded");
    }

    #[test]
    fn test_arith_subst_respects_frequency() {
        // freq=2 だと 2回目の Add のみ置換される
        let instrs = vec![
            TackyInstruction::Binary {
                op: TackyBinaryOp::Add,
                left: make_int_var("a"),
                right: make_int_var("b"),
                dst: make_int_var("c"),
            },
            TackyInstruction::Binary {
                op: TackyBinaryOp::Add,
                left: make_int_var("c"),
                right: make_int_var("a"),
                dst: make_int_var("d"),
            },
        ];
        let mut ctx = ObfCtx::new();
        let mut var_types = make_var_types(&["a", "b", "c", "d"]);

        let result = arithmetic_substitution(instrs, &mut ctx, &mut var_types, 2);

        // 最初の Add はそのまま、2番目が展開される → 1 + 3+ = 4+ 命令
        assert!(
            result.len() >= 4,
            "only every 2nd Add should be expanded, got {} instructions",
            result.len()
        );
        // 最初の命令は元の Add のままであること
        assert!(
            matches!(
                &result[0],
                TackyInstruction::Binary {
                    op: TackyBinaryOp::Add,
                    ..
                }
            ),
            "first Add should remain unchanged"
        );
    }

    #[test]
    fn test_state_encoding_consistency() {
        // Feature 4: エンコード/デコードの一貫性を検証
        let cff_a: i32 = 37;
        let cff_b: i32 = 0xCAFE;
        for i in 0i32..20 {
            let encoded = i.wrapping_mul(cff_a).wrapping_add(cff_b);
            let decoded = (encoded.wrapping_sub(cff_b)) / cff_a;
            assert_eq!(
                decoded, i,
                "encode/decode should be consistent for index {i}"
            );
        }
    }
}