hotpy_2 / Python / trace_specialiser.c

   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
/* Trace Recorder */
/* This is the final stage of the pipeline.
 * It just records the instructions it receives */

#include "Python.h"
#include "opcode.h"
#include "optimiser.h"
#include "trace_opcode.h"

#ifdef Py_DEBUG
#define COMMENT(t) x->next->comment(x->next, t)
#define SHOW_FRAME(f) show_frame(x, f)
#define SHOW_STACK() show_stack(opt)
#else
#define COMMENT(t) ((void)0)
#define SHOW_FRAME(f) ((void)0)
#define SHOW_STACK()  ((void)0)
#endif

#define OUT_OF_LINE_GUARD(guard_type, object, key) ((void)0)

enum type_kind {
    TK_UNKNOWN,
    TK_TYPE,
    TK_VALUE,
    TK_TUPLE,
    TK_MAP,
    TK_FRAME,
    TK_FUNCTION,
    TK_BOUND
};

typedef struct type_info_object {
    PyObject_HEAD
    enum type_kind kind;
    PyObject *value;
} HotPyTypeInfo;

#define KIND(ti) (((HotPyTypeInfo *)(ti))->kind)
#define VALUE(ti) (((HotPyTypeInfo *)(ti))->value)

#ifdef Py_DEBUG
int _HotPy_allocated_type_info = 0;
int _HotPy_allocated_type_frame_info = 0;
#define INC_ALLOCATED_COUNT ++_HotPy_allocated_type_info;
#define DEC_ALLOCATED_COUNT --_HotPy_allocated_type_info;
#define INC_ALLOCATED_FRAME_COUNT ++_HotPy_allocated_type_frame_info;
#define DEC_ALLOCATED_FRAME_COUNT --_HotPy_allocated_type_frame_info;
#else
#define INC_ALLOCATED_COUNT
#define DEC_ALLOCATED_COUNT
#define INC_ALLOCATED_FRAME_COUNT
#define DEC_ALLOCATED_FRAME_COUNT
#endif

static void
typeinfo_dealloc(HotPyTypeInfo *info)
{
    DEC_ALLOCATED_COUNT
    Py_XDECREF(info->value);
    PyObject_DEL(info);
}

static PyTypeObject TypeInfo_Type = {
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
    "type-info",                                /* tp_name */
    sizeof(HotPyTypeInfo),                      /* tp_basicsize */
    0,                                          /* tp_itemsize */
    (destructor)typeinfo_dealloc,               /* tp_dealloc */
    0,                                          /* tp_print */
    0,                                          /* tp_getattr */
    0,                                          /* tp_setattr */
    0,                                          /* tp_reserved */
    0,                                          /* tp_repr */
    0,                                          /* tp_as_number */
    0,                                          /* tp_as_sequence */
    0,                                          /* tp_as_mapping */
    0,                                          /* tp_hash */
    0,                                          /* tp_call */
    0,                                          /* tp_str */
    PyObject_GenericGetAttr,                    /* tp_getattro */
    0,                                          /* tp_setattro */
    0,                                          /* tp_as_buffer */
    Py_TPFLAGS_DEFAULT,                         /* tp_flags */
    0,                                          /* tp_doc */
    0,                                          /* tp_traverse */
    0,                                          /* tp_clear */
    0,                                          /* tp_richcompare */
    0,                                          /* tp_weaklistoffset */
    0,                                          /* tp_iter */
    0,                                          /* tp_iternext */
    0,                                          /* tp_methods */
    0,                                          /* tp_members */
    0,                                          /* tp_getset */
    0,                                          /* tp_base */
    0,                                          /* tp_dict */
    0,                                          /* tp_descr_get */
    0,                                          /* tp_descr_set */
    0,                                          /* tp_dictoffset */
    0,                                          /* tp_init */
    0,                                          /* tp_alloc */
    0,                                          /* tp_new */
    PyObject_Del,                               /* tp_free */
};

/* Returns a borrowed reference */
static PyObject *
type_of(PyObject *x)
{
    HotPyTypeInfo *info = (HotPyTypeInfo *)x;
    assert(x != NULL);
    assert(Py_TYPE(x) == &TypeInfo_Type);
    switch(info->kind) {
    case TK_UNKNOWN:
        return Py_None;
    case TK_TYPE:
        return info->value;
    case TK_VALUE:
        return (PyObject *)Py_TYPE(info->value);
    case TK_TUPLE:
        return (PyObject *)&PyTuple_Type;
    case TK_MAP:
        return (PyObject *)&PyDict_Type;
    case TK_FRAME:
        return (PyObject *)&PyFrame_Type;
    case TK_FUNCTION:
        return (PyObject *)&PyFunction_Type;
    case TK_BOUND:
        return PyTuple_GET_ITEM(VALUE(info), 0);
    default:
        assert(0 && "Unknown type-info code");
        abort();
    }
}

/* Returns a borrowed reference */
static PyObject *
value_of(PyObject *x)
{
    HotPyTypeInfo *info = (HotPyTypeInfo *)x;
    assert(x != NULL);
    assert(Py_TYPE(x) == &TypeInfo_Type);
    if (info->kind == TK_VALUE)
        return info->value;
    else
        return NULL;
}

static HotPyTypeInfo *
new_type_info(void)
{
    INC_ALLOCATED_COUNT
    return PyObject_New(HotPyTypeInfo, &TypeInfo_Type);
}

static PyObject *
new_type(PyTypeObject *type)
{
    HotPyTypeInfo *info = new_type_info();
    Py_INCREF(type);
    info->kind = TK_TYPE;
    info->value = (PyObject *)type;
    return (PyObject*)info;
}

static PyObject *
new_bound(PyTypeObject *type, PyObject *func, PyObject *self)
{
    HotPyTypeInfo *info = new_type_info();
    PyObject *tuple = PyTuple_New(3);
    if (tuple == NULL) {
        Py_DECREF(info);
        return NULL;
    }
    info->kind = TK_BOUND;
    Py_INCREF(type);
    PyTuple_SET_ITEM(tuple, 0, (PyObject *)type);
    Py_INCREF(func);
    PyTuple_SET_ITEM(tuple, 1, (PyObject *)func);
    Py_INCREF(self);
    PyTuple_SET_ITEM(tuple, 2, (PyObject *)self);
    info->value = tuple;
    return (PyObject *)info;
}

static PyObject *
new_value(PyObject *value)
{
    HotPyTypeInfo *info = new_type_info();
    if (info) {
        info->kind = TK_VALUE;
        Py_INCREF(value);
        info->value = value;
    }
    return (PyObject*)info;
}

/* Steals a reference to value */
static PyObject *
new_tuple(PyObject *value)
{
    HotPyTypeInfo *info = new_type_info();
    if (info) {
        info->kind = TK_TUPLE;
        info->value = value;
    }
    return (PyObject*)info;
}

static PyObject *
new_function(PyObject *code_info)
{
    HotPyTypeInfo *info;
    PyObject *code = value_of(code_info);
    if (code) {
        info = new_type_info();
        if (info) {
            info->kind = TK_FUNCTION;
            Py_INCREF(code);
            info->value = code;
        }
        return (PyObject*)info;
    }
    return new_type(&PyFunction_Type);
}

static PyObject *
new_unknown(void)
{
    HotPyTypeInfo *info = new_type_info();
    if (info) {
        info->kind = TK_UNKNOWN;
        info->value = NULL;
    }
    return (PyObject*)info;
}

/* Steals a reference to dict */
static PyObject *
new_map(PyObject *dict)
{
    HotPyTypeInfo *info = new_type_info();
    assert(PyDict_CheckExact(dict));
    if (info) {
        info->kind = TK_MAP;
        info->value = dict;
        if (info->value == NULL)
            Py_CLEAR(info);
    }
    return (PyObject*)info;
}

static PyObject *
as_tuple(PyObject *x)
{
    HotPyTypeInfo *info = (HotPyTypeInfo *)x;
    assert(x != NULL);
    assert(Py_TYPE(x) == &TypeInfo_Type);
    switch(info->kind) {
    case TK_TUPLE:
        Py_INCREF(info->value);
        return info->value;
    case TK_VALUE:
        if (PyTuple_CheckExact(info->value)) {
            int i;
            PyObject *res = PyTuple_New(Py_SIZE(info->value));
            if (res == NULL)
                return NULL;
            for (i = 0; i < Py_SIZE(info->value); i++) {
                PyObject *o = new_value(PyTuple_GET_ITEM(info->value, i));
                if (o == NULL) {
                    Py_DECREF(res);
                    return NULL;
                }
                PyTuple_SET_ITEM(res, i, o);
            }
            return res;
        }
    default:
        return NULL;
    }
}

/* Returns a borrowed reference */
static PyObject *
as_map(PyObject *x)
{
    HotPyTypeInfo *info = (HotPyTypeInfo *)x;
    assert(x != NULL);
    assert(Py_TYPE(x) == &TypeInfo_Type);
    switch(info->kind) {
    case TK_MAP:
        return info->value;
    default:
        return NULL;
    }
}

static void
map_add(PyObject *map_info, PyObject *key_info, PyObject *val_info)
{
    PyObject *key = value_of(key_info);
    assert(map_info != NULL);
    if (key != NULL && KIND(map_info) == TK_MAP) {
        PyObject *dict = VALUE(map_info);
        PyDict_SetItem(dict, key, val_info);
    }
}

/* Steals references to all items in vector */
static PyObject *
build_tuple(int size, PyObject **vector)
{
    PyObject *tuple = PyTuple_New(size);
    int i;
    if (tuple != NULL) {
        for (i = 0; i < size; i++) {
            assert(vector[i] != NULL);
            assert(Py_TYPE(vector[i]) == &TypeInfo_Type);
            PyTuple_SET_ITEM(tuple, i, vector[i]);
        }
        return new_tuple(tuple);
    }
    else {
        for (i = 0; i < size; i++) {
            Py_XDECREF(vector[i]);
        }
    }
    return NULL;
}

static void
fix_type(PyObject *op, PyTypeObject* type)
{
    PyObject *tmp;
    HotPyTypeInfo *info = (HotPyTypeInfo *)op;
    assert(Py_TYPE(op) == &TypeInfo_Type);
    switch(info->kind) {
    case TK_VALUE:
        if (type == Py_TYPE(info->value))
            return;
        break;
    case TK_TUPLE:
        if (type == &PyTuple_Type)
            return;
        break;
    case TK_MAP:
        if (type == &PyDict_Type)
            return;
        break;
    case TK_FUNCTION:
        if (type == &PyFunction_Type)
            return;
        break;
    case TK_BOUND:
        if (type == (PyTypeObject *)PyTuple_GET_ITEM(VALUE(info), 0))
            return;
        break;
    case TK_TYPE: case TK_UNKNOWN: case TK_FRAME:
        break;
    }
    info->kind = TK_TYPE;
    tmp = info->value;
    Py_INCREF(type);
    info->value = (PyObject *)type;
    Py_XDECREF(tmp);
}

static void
fix_value(PyObject *op, PyObject* value)
{
    PyObject *tmp;
    HotPyTypeInfo *info = (HotPyTypeInfo *)op;
    assert(Py_TYPE(op) == &TypeInfo_Type);
    info->kind = TK_VALUE;
    tmp = info->value;
    Py_INCREF(value);
    info->value = value;
    Py_XDECREF(tmp);
}

typedef struct _specialiser_frame {
    PyObject_HEAD
    int lcount;
    PyObject *globals;
    PyObject *builtins;
    PyObject **locals;
    PyObject **stack_base;
    PyObject **stack_pointer;
} SpecialiserFrame;

/* Consumes a reference to f */
static PyObject *
frame_info(SpecialiserFrame *f)
{
    HotPyTypeInfo *info = new_type_info();
    info->kind = TK_FRAME;
    info->value = (PyObject *)f;
    return (PyObject*)info;
}

static void
frame_dealloc(SpecialiserFrame *f)
{
    int i;
    DEC_ALLOCATED_FRAME_COUNT
    for (i = 0; i < f->lcount; i++)
        Py_CLEAR(f->locals[i]);
    while (f->stack_pointer > f->stack_base) {
        f->stack_pointer--;
        Py_XDECREF(*f->stack_pointer);
    }
    Py_XDECREF(f->globals);
    Py_XDECREF(f->builtins);
    PyMem_Free(f->locals);
    f->locals = NULL;
    PyMem_Free(f->stack_base);
    f->stack_base = f->stack_pointer = NULL;
    PyObject_DEL(f);
}

static PyTypeObject SpecialiserFrame_Type = {
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
    "specialiser frame",                        /* tp_name */
    sizeof(SpecialiserFrame),             /* tp_basicsize */
    0,                                          /* tp_itemsize */
    (destructor)frame_dealloc,                  /* tp_dealloc */
    0,                                          /* tp_print */
    0,                                          /* tp_getattr */
    0,                                          /* tp_setattr */
    0,                                          /* tp_reserved */
    0,                                          /* tp_repr */
    0,                                          /* tp_as_number */
    0,                                          /* tp_as_sequence */
    0,                                          /* tp_as_mapping */
    0,                                          /* tp_hash */
    0,                                          /* tp_call */
    0,                                          /* tp_str */
    PyObject_GenericGetAttr,                    /* tp_getattro */
    0,                                          /* tp_setattro */
    0,                                          /* tp_as_buffer */
    Py_TPFLAGS_DEFAULT,                         /* tp_flags */
    0,                                          /* tp_doc */
    0,                                          /* tp_traverse */
    0,                                          /* tp_clear */
    0,                                          /* tp_richcompare */
    0,                                          /* tp_weaklistoffset */
    0,                                          /* tp_iter */
    0,                                          /* tp_iternext */
    0,                                          /* tp_methods */
    0,                                          /* tp_members */
    0,                                          /* tp_getset */
    0,                                          /* tp_base */
    0,                                          /* tp_dict */
    0,                                          /* tp_descr_get */
    0,                                          /* tp_descr_set */
    0,                                          /* tp_dictoffset */
    0,                                          /* tp_init */
    0,                                          /* tp_alloc */
    0,                                          /* tp_new */
    PyObject_Del,                               /* tp_free */
};

#define STACK_LIMIT 16

static SpecialiserFrame*
new_frame(int lcount)
{
    INC_ALLOCATED_FRAME_COUNT
    SpecialiserFrame *f = PyObject_New(SpecialiserFrame, &SpecialiserFrame_Type);
    if (f) {
        f->lcount = lcount;
        f->locals = PyMem_Malloc(sizeof(PyObject *) * lcount);
        if (f->locals == NULL) {
            Py_CLEAR(f);
        }
        else {
            memset(f->locals, 0, sizeof(PyObject *) * lcount);
            f->stack_pointer = f->stack_base = PyMem_Malloc(sizeof(PyObject *) * STACK_LIMIT);
            if (f->stack_pointer == NULL) {
                PyMem_Free(f->locals);
                Py_CLEAR(f);
            }
        }
        f->globals = NULL;
        f->builtins = NULL;
    }
    return f;
}

char *
show_info(char *out, PyObject *info)
{
    if (info == NULL) {
        out += sprintf(out, "null, ");
    }
    else {
        switch(KIND(info)) {
        case TK_UNKNOWN:
            out += sprintf(out, "unknown, ");
            break;
        case TK_TYPE:
            out += sprintf(out, "type %s, ", ((PyTypeObject *)VALUE(info))->tp_name);
            break;
        case TK_VALUE:
            if (Py_TYPE(VALUE(info)) == &PyBool_Type)
                if (VALUE(info) == Py_True)
                    out += sprintf(out, "True, ");
                else
                    out += sprintf(out, "False, ");
            else
                out += sprintf(out, "value %s, ", Py_TYPE(VALUE(info))->tp_name);
            break;
        case TK_TUPLE:
            {
                int i, len;
                len = PyTuple_Size(VALUE(info));
                out += sprintf(out, "(");
                for (i = 0; i < len; i++) {
                    out = show_info(out, PyTuple_GET_ITEM(VALUE(info), i));
                }
                out += sprintf(out, "), ");
            }
            break;
        case TK_MAP:
            out += sprintf(out, "dict, ");
            break;
        case TK_FRAME:
            out += sprintf(out, "frame, ");
            break;
        case TK_FUNCTION:
            out += sprintf(out, "function, ");
            break;
        case TK_BOUND:
            out += sprintf(out, "bound, ");
            break;
        default:
            assert(0 && "Unknown type-info code");
            abort();
        }
    }
    return out;
}

#ifdef Py_DEBUG
static void
show_frame(HotPyOptimiser *x, SpecialiserFrame *f)
{
    char buf[400];
    char *out = &buf[0];
    int i, lcount = f->lcount;
    out += sprintf(out, "Frame: ");
    for (i = 0; i < lcount; i++) {
        PyObject *info = f->locals[i];
        out = show_info(out, info);
    }
    out[0] = '\0';
    x->next->comment(x->next, buf);
}
#endif

int
is_type_info(PyObject *info)
{
    if (info == NULL)
        return 0;
    if (Py_TYPE(info) == &TypeInfo_Type)
        return 1;
    if (PyTuple_Check(info)) {
        if (Py_SIZE(info) == 0)
            return 0;
        return Py_TYPE(PyTuple_GET_ITEM(info, 0)) == &TypeInfo_Type;
    }
    if (PyDict_Check(info)) {
        PyObject *key, *value;
        Py_ssize_t i = 0;
        if (PyDict_Next(info, &i, &key, &value))
            return Py_TYPE(value) == &TypeInfo_Type;
    }
    return 0;
}

static SpecialiserFrame *
frame_from_frame(PyFrameObject *from)
{
    int i, lcount = from->f_code->co_nlocals;
    SpecialiserFrame* f = new_frame(lcount);
    if (f) {
        /* Locals will be either type-info objects or default values
           Ignore defaults for now, will need to add guard to function_set_defaults
           in order to use them (as constants)
        */
        for (i = 0; i < lcount; i++) {
            PyObject *l = from->f_localsplus[i];
            if (l != NULL) {
                if (is_type_info(l)) {
                    Py_INCREF(l);
                    if (PyTuple_Check(l))
                        l = new_tuple(l);
                    else if (PyDict_Check(l))
                        l = new_map(l);
                    f->locals[i] = l;
                }
                else {
                    f->locals[i] = new_value(l);

                }
            }
        }
        f->globals = new_value(from->f_globals);
        f->builtins = new_value(from->f_builtins);
    }
    return f;
}

typedef struct _trace_specialiser {
    HotPyOptimiser opt_base;
    PyObject *registers[HOTPY_REGISTER_COUNT];
    int err_occurred;
    HotPyTraceObject *trace;
    SpecialiserFrame *frame_stack[HOTPY_CONTEXT_DEPTH];
    SpecialiserFrame *top_frame;
    int frames;
} HotPySpecialiser;

#ifdef Py_DEBUG
static void
show_stack(HotPySpecialiser *opt)
{
    char buf[400];
    char *out = &buf[0];
    PyObject **ptr = opt->top_frame->stack_base;
    out += sprintf(out, "Stack: ");
    while (ptr < opt->top_frame->stack_pointer) {
        out = show_info(out, *ptr);
        ptr++;
    }
    out[0] = '\0';
    opt->opt_base.next->comment(opt->opt_base.next, buf);
}
#endif

static int
guard_type_attribute(HotPyOptimiser *x, PyObject *type, PyObject *name)
{
    HotPySpecialiser *opt = (HotPySpecialiser *)x;
    HotPyTraceObject *trace = opt->trace;
    int res = PyType_GuardAttribute((PyTypeObject *)type, name, (PyObject *)trace);
    if (res < 0)
        PyErr_Clear();
    else {
        if (trace->trace_guarded_by == NULL) {
            trace->trace_guarded_by = PySet_New(0);
            if (trace->trace_guarded_by == NULL) {
                PyErr_Clear();
                return 1;
            }
        }
        PySet_Add(trace->trace_guarded_by, type);
    }
    return 1;
}

#define STACK_DEPTH(f) ((f)->stack_pointer - (f)->stack_base)

/* XXX - If new_unknown fails need to set error_occurred & return non-null */
#define POP() ((opt->top_frame->stack_pointer > opt->top_frame->stack_base) ? \
               *(--opt->top_frame->stack_pointer) : new_unknown())

#define DROP() do { \
    if (opt->top_frame->stack_pointer > opt->top_frame->stack_base) { \
        --opt->top_frame->stack_pointer; \
        Py_DECREF(opt->top_frame->stack_pointer[0]); \
    } \
} while (0)

static void
push_down_stack(SpecialiserFrame *f)
{
    PyObject *tmp = f->stack_base[0];
    int i;
    for (i = 0; i < STACK_LIMIT - 1; i++) {
        f->stack_base[i] = f->stack_base[i+1];
    }
    Py_XDECREF(tmp);
    --f->stack_pointer;
    assert(STACK_DEPTH(f) == STACK_LIMIT-1);
}

#define PUSH(v) do { \
    PyObject *_tmp = (v); \
    if (_tmp == NULL) { \
        opt->err_occurred = 1; \
        assert(PyErr_Occurred()); \
        PyErr_Clear(); \
    } \
    else { \
        assert(STACK_DEPTH(opt->top_frame) <= STACK_LIMIT); \
        if (STACK_DEPTH(opt->top_frame) == STACK_LIMIT) \
            push_down_stack(opt->top_frame); \
        *(opt->top_frame->stack_pointer++) = _tmp; \
    } \
} while (0)

static PyObject *
freeze_frame(SpecialiserFrame *f) {
    /* Return a tuple (of up to 16) of locals, plus stack
       of types (or None if no type).
       Discard info about tuples of types, dicts and constants
       in order to save space.
    */
    Py_ssize_t depth, i, len;
    PyObject *t, *tuple;
    assert(f != NULL);
    assert(Py_TYPE(f) == &SpecialiserFrame_Type);
    len = 16 < f->lcount ? 16 : f->lcount;
    depth = STACK_DEPTH(f);
    tuple = PyTuple_New(len+depth+3);
    if (tuple == NULL) {
        Py_INCREF(Py_None);
        return Py_None;
    }
    assert(depth >= 0);
    PyTuple_SET_ITEM(tuple, 0, PyLong_FromLong(depth));
    for (i = 0; i < len; i++) {
        if (f->locals[i])
            t = type_of(f->locals[i]);
        else
            t = Py_None;
        Py_INCREF(t);
        PyTuple_SET_ITEM(tuple, i+1, t);
    }
    for (i = 0; i < depth; i++) {
        t = type_of(f->stack_base[i]);
        Py_INCREF(t);
        PyTuple_SET_ITEM(tuple, i+len+1, t);
    }
    if (f->globals == NULL)
        f->globals = new_unknown();
    Py_INCREF(f->globals);
    PyTuple_SET_ITEM(tuple, len+depth+1, f->globals);
    if (f->builtins == NULL)
        f->builtins = new_unknown();
    Py_INCREF(f->builtins);
    PyTuple_SET_ITEM(tuple, len+depth+2, f->builtins);
    return (PyObject*)tuple;
}

static void
save_state_to_context(HotPyOptimiser *x, HotPyContext *context)
{
    int i;
    PyObject *t;
    HotPySpecialiser *opt = (HotPySpecialiser *)x;
    t = PyTuple_New(opt->frames);
    if (t == NULL) {
        Py_INCREF(Py_None);
        t = Py_None;
    }
    else {
        for (i = 0; i < opt->frames; i++) {
            PyTuple_SET_ITEM(t, i, freeze_frame(opt->frame_stack[i]));
        }
    }
    Py_CLEAR(context->cf_type_info);
    context->cf_type_info = t;
}

static SpecialiserFrame *
thaw_frame(PyObject *frozen)
{
    Py_ssize_t len, depth;
    int i;
    PyObject *t;
    SpecialiserFrame *f;
    assert(frozen != NULL);
    if (frozen == Py_None)
        return NULL;
    assert(PyTuple_CheckExact(frozen));
    depth = PyLong_AsLong(PyTuple_GET_ITEM(frozen, 0));
    len = Py_SIZE(frozen) - depth-3;
    f = new_frame(len);
    if (f == NULL)
        return NULL;
    f->stack_pointer = f->stack_base + depth;
    for (i = 0; i < len; i++) {
        PyObject *info;
        t = PyTuple_GET_ITEM(frozen, i+1);
        if (t == Py_None)
            info = NULL;
        else
            info = new_type((PyTypeObject *)t);
        f->locals[i] = info;
    }
    for (i = 0; i < depth; i++) {
        PyObject *info;
        t = PyTuple_GET_ITEM(frozen, len+i+1);
        if (t == Py_None)
            info = new_unknown();
        else
            info = new_type((PyTypeObject *)t);
        if (info == NULL) {
            Py_DECREF(f);
            return NULL;
        }
        f->stack_base[i] = info;
    }
    f->globals = PyTuple_GET_ITEM(frozen, len+depth+1);
    Py_INCREF(f->globals);
    f->builtins = PyTuple_GET_ITEM(frozen, len+depth+2);
    Py_INCREF(f->builtins);
    return f;
}

#define FAIL do { \
    opt->err_occurred = 1; \
    assert(PyErr_Occurred()); \
    PyErr_Clear(); \
    x->next->fail(x->next, 0, "Specialiser internal error"); \
} while (0)

#define CHECK_OK if (opt->err_occurred) return

#define CHECK_OK_NULL if (opt->err_occurred) return NULL

#define STACK_ITEM(n) opt->top_frame->stack_pointer[-(n)]

static void
push_constant(HotPyOptimiser *x, PyObject *value)
{
    HotPySpecialiser *opt = (HotPySpecialiser *)x;
    CHECK_OK;
    PUSH(new_value(value));
    x->next->push_constant(x->next, value);
}

static void comment(HotPyOptimiser *x, const char *text)
{
}

static void
pick(HotPyOptimiser *x, int depth)
{
    PyObject *info;
    HotPySpecialiser *opt = (HotPySpecialiser *)x;
    CHECK_OK;
    if (STACK_DEPTH(opt->top_frame) < depth-1 ||
        STACK_DEPTH(opt->top_frame) >= STACK_LIMIT - 1) {
        info = new_unknown();
    }
    else {
        if (STACK_DEPTH(opt->top_frame) == depth-1) {
            int i, n = STACK_DEPTH(opt->top_frame);
            for (i = 0; i < n; i++) {
                STACK_ITEM(i) = STACK_ITEM(i+1);
            }
            STACK_ITEM(n) = new_unknown();
            opt->top_frame->stack_pointer++;
        }
        info = STACK_ITEM(depth);
        Py_INCREF(info);
    }
    PUSH(info);
    x->next->pick(x->next, depth);
}

static HotPyContext *
require_type(HotPyOptimiser *x, PyTypeObject* type)
{
    HotPySpecialiser *opt = (HotPySpecialiser *)x;
    PyObject *info;
    HotPyContext *context = NULL;
    CHECK_OK_NULL;
    info = POP();
    if (type_of(info) == (PyObject *)type)
        x->next->opcode(x->next, POP_TOP);
    else {
        context = x->next->require_type(x->next, type);
        if (context)
            save_state_to_context(x, context);
        fix_type(info, type);
    }
    Py_DECREF(info);
    return context;
}

static HotPyContext *
require_value(HotPyOptimiser *x, PyObject* v)
{
    HotPySpecialiser *opt = (HotPySpecialiser *)x;
    PyObject *info;
    HotPyContext *context = NULL;
    CHECK_OK_NULL;
    info = POP();
    if (value_of(info) == v)
        x->next->opcode(x->next, POP_TOP);
    else {
        context = x->next->require_value(x->next, v);
        if (context)
            save_state_to_context(x, context);
        fix_value(info, v);
    }
    Py_DECREF(info);
    return context;
}

static int
guard_function(PyObject *func, HotPyTraceObject *trace)
{
    int res = PyFunction_Guard(func, (PyObject *)trace);
    if (res >= 0) {
        if (trace->trace_guarded_by == NULL) {
            trace->trace_guarded_by = PySet_New(0);
            if (trace->trace_guarded_by == NULL) {
                PyFunction_Unguard(func, (PyObject *)trace);
                return -1;
            }
        }
        res = PySet_Add(trace->trace_guarded_by, func);
    }
    return res;
}

static HotPyContext *
require_code(HotPyOptimiser *x, PyObject *obj)
{
    HotPySpecialiser *opt = (HotPySpecialiser *)x;
    PyObject *info, *v;
    HotPyContext *context = NULL;
    CHECK_OK_NULL;
    info = POP();
    v = value_of(info);
    /* XXX - To do -- Handle functions made on trace; no guard required */
    if (PyFunction_Check(obj)) {
        if (v == obj && guard_function(obj, opt->trace) >= 0) {
            x->next->opcode(x->next, POP_TOP);
        }
        else {
            context = x->next->require_code(x->next, obj);
            if (context)
                save_state_to_context(x, context);
        }
    }
    else {
        assert(PyGen_Check(obj));
        /* Any optimisation possible here? */
        context = x->next->require_code(x->next, obj);
        if (context)
            save_state_to_context(x, context);
    }
    Py_DECREF(info);
    return context;
}

static HotPyContext *
require_lasti(HotPyOptimiser *x, int lasti)
{
    HotPySpecialiser *opt = (HotPySpecialiser *)x;
    HotPyContext *context = NULL;
    CHECK_OK_NULL;
    /* XXX - If code object of generator (TOS) is known then
     * this can be eliminated if it has only one yield instruction */
    DROP();
    context = x->next->require_lasti(x->next, lasti);
    if (context)
        save_state_to_context(x, context);
    return context;
}

static HotPyContext *
require_boolean_or_int(HotPyOptimiser *x)
{
    HotPySpecialiser *opt = (HotPySpecialiser *)x;
    HotPyContext *context = NULL;
    PyObject *info;
    CHECK_OK_NULL;
    info = POP();
    if (type_of(info) != (PyObject *)&PyLong_Type &&
        type_of(info) != (PyObject *)&PyBool_Type) {
        context = x->next->require_boolean_or_int(x->next);
    } else
        x->next->opcode(x->next, POP_TOP);
    Py_DECREF(info);
    if (context)
        save_state_to_context(x, context);
    return context;
}

/* XXX - Need to fix this.
 * This is correct for at the moment, but may not remain so */
#define TYPE_STABLE(func) 1

static void
binary_op(HotPyOptimiser *x, int func, PyObject *res)
{
    HotPySpecialiser *opt = (HotPySpecialiser *)x;
    PyObject *l, *r;
    CHECK_OK;
    static int _is = 0, _is_not = 0;
    assert(res != NULL);
    if (_is == 0) {
        int index;
        index = BINARY_FUNCTION_INDEX(&PyLong_Type, &PyLong_Type);
        _is =_Py_operator_compare[PyCmp_IS].functions[index];
        _is_not =_Py_operator_compare[PyCmp_IS_NOT].functions[index];
        assert(_is && _is_not && "must be non-zero");
    }
    l = POP();
    r = POP();
    if (func == _is || func == _is_not) {
        PyObject *val = NULL;
        if (KIND(l) == TK_VALUE && KIND(r) == TK_VALUE) {
            if (func == _is)
                val = VALUE(l) == VALUE(r)  ? Py_True: Py_False;
            else
                val = VALUE(l) != VALUE(r)  ? Py_True: Py_False;
        }
        else if (type_of(l) != Py_None && type_of(r) != Py_None &&
                 type_of(l) != type_of(r))
            val = (func == _is_not) ? Py_True: Py_False;
        if (val) {
            x->next->opcode(x->next, POP_TOP);
            x->next->opcode(x->next, POP_TOP);
            PUSH(new_value(val));
            x->next->push_constant(x->next, val);
            goto cleanup;
        }
        else
            PUSH(new_type(&PyBool_Type));
    }
    else if (TYPE_STABLE(func))
        PUSH(new_type(Py_TYPE(res)));
    else
        PUSH(new_unknown());
    x->next->binary_op(x->next, func, res);
cleanup:
    SHOW_STACK();
    Py_DECREF(l);
    Py_DECREF(r);
}

static void
binary_op_kv(HotPyOptimiser *x, int func, PyObject *k, PyObject *res)
{
    /* This is just for completeness, don't bother optimising */
    HotPySpecialiser *opt = (HotPySpecialiser *)x;
    DROP();
    x->next->binary_op_kv(x->next, func, k, res);
    PUSH(new_unknown());
    return;
}

static void
binary_op_vk(HotPyOptimiser *x, int func, PyObject *k, PyObject *res)
{
    /* This is just for completeness, don't bother optimising */
    HotPySpecialiser *opt = (HotPySpecialiser *)x;
    DROP();
    x->next->binary_op_vk(x->next, func, k, res);
    PUSH(new_unknown());
    return;
}

static void
load_clear_register(HotPyOptimiser *x, int index)
{
    HotPySpecialiser *opt = (HotPySpecialiser *)x;
    CHECK_OK;
    PyObject *info = opt->registers[index];
    opt->registers[index] = NULL;
    /* The front end may call this even though we are
     * out of scope, to push the return value */
    if (opt->top_frame) {
        if (info == NULL)
            info = new_unknown();
        PUSH(info);
    }
    else
        Py_XDECREF(info);
    x->next->load_clear_register(x->next, index);
}

static void
load_register(HotPyOptimiser *x, int index)
{
    HotPySpecialiser *opt = (HotPySpecialiser *)x;
    CHECK_OK;
    PyObject *info = opt->registers[index];
    if (info == NULL)
        info = new_unknown();
    else
        Py_INCREF(info);
    PUSH(info);
    x->next->load_register(x->next, index);
}

static void
store_register(HotPyOptimiser *x, int index)
{
    HotPySpecialiser *opt = (HotPySpecialiser *)x;
    CHECK_OK;
    PyObject *info;
    assert(index < HOTPY_REGISTER_COUNT);
    info = opt->registers[index];
    opt->registers[index] = POP();
    Py_XDECREF(info);
    x->next->store_register(x->next, index);
}

static void
load_fast(HotPyOptimiser *x, int index)
{
    HotPySpecialiser *opt = (HotPySpecialiser *)x;
    CHECK_OK;
    PyObject *info;
    if (index >= opt->top_frame->lcount) {
        info = new_unknown();
    } else {
        info = opt->top_frame->locals[index];
        if (info == NULL)
            info = opt->top_frame->locals[index] = new_unknown();
        Py_INCREF(info);
    }
    PUSH(info);
    if (KIND(info) == TK_VALUE)
        x->next->push_constant(x->next, VALUE(info));
    else
        x->next->load_fast(x->next, index);
}

static void
store_fast(HotPyOptimiser *x, int index)
{
    HotPySpecialiser *opt = (HotPySpecialiser *)x;
    CHECK_OK;
    PyObject *info;
    if (index < opt->top_frame->lcount) {
        info = opt->top_frame->locals[index];
        opt->top_frame->locals[index] = POP();
        Py_XDECREF(info);
    }
    else {
        DROP();
    }
    x->next->store_fast(x->next, index);
}

static void
delete_fast(HotPyOptimiser *x, int index)
{
    HotPySpecialiser *opt = (HotPySpecialiser *)x;
    CHECK_OK;
    if (index < opt->top_frame->lcount) {
        Py_CLEAR(opt->top_frame->locals[index]);
    }
    x->next->delete_fast(x->next, index);
}

static void
get_globals(HotPyOptimiser *x)
{
    HotPySpecialiser *opt = (HotPySpecialiser *)x;
    CHECK_OK;
    if (opt->top_frame->globals == NULL)
        opt->top_frame->globals = new_unknown();
    if (opt->top_frame->builtins == NULL)
        opt->top_frame->builtins = new_unknown();
    if (value_of(opt->top_frame->globals) &&
        value_of(opt->top_frame->builtins)) {
        Py_INCREF(opt->top_frame->globals);
        PUSH(opt->top_frame->globals);
        x->next->push_constant(x->next, value_of(opt->top_frame->globals));
        Py_INCREF(opt->top_frame->builtins);
        PUSH(opt->top_frame->builtins);
        x->next->push_constant(x->next, value_of(opt->top_frame->builtins));
    }
    else {
        Py_INCREF(opt->top_frame->globals);
        PUSH(opt->top_frame->globals);
        Py_INCREF(opt->top_frame->builtins);
        PUSH(opt->top_frame->builtins);
        x->next->get_globals(x->next);
    }
}

static int
all_capitals(PyObject *name)
{
    Py_ssize_t i, len = PyUnicode_GET_LENGTH(name);
    void *data = PyUnicode_DATA(name);
    int kind = PyUnicode_KIND(name);
    int cased = 0;
    if (len > 80)
        return 0;
    for (i = 0; i < len; i++) {
        const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
        if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
            return 0;
        else if (!cased && Py_UNICODE_ISUPPER(ch))
            cased = 1;
    }
    return cased;
}

/* Use out-of-line guards to convert any global function or class to a constant
 */
static void
load_from_globals(HotPyOptimiser *x, PyObject *name)
{
    HotPySpecialiser *opt = (HotPySpecialiser *)x;
    PyObject *globals;
    PyObject *builtins;
    PyObject *const_val = NULL;
    CHECK_OK;
    builtins = value_of(POP());
    globals = value_of(POP());
    if (globals) {
        PyObject *value = PyDict_GetItem(globals, name);
        if (value && (PyFunction_Check(value) ||
                      PyType_Check(value) ||
                      PyCFunction_Check(value) || all_capitals(name))) {
            _PyDict_MakeGuarded(globals);
            if (_PyDict_AddGuard(globals, name, value, (PyObject *)opt->trace))
                const_val = value;
        }
        if (value == NULL) {
            if (builtins) {
                PyObject *value = PyDict_GetItem(builtins, name);
                if (value) {
                    _PyDict_MakeGuarded(globals);
                    _PyDict_MakeGuarded(builtins);
                    if (_PyDict_AddGuard(globals, name, NULL, (PyObject *)opt->trace) &&
                        _PyDict_AddGuard(builtins, name, value, (PyObject *)opt->trace))
                        const_val = value;
                }
            }
        }
    }
    if (const_val) {
        x->next->opcode(x->next, POP_TOP);
        x->next->opcode(x->next, POP_TOP);
        PUSH(new_value(const_val));
        x->next->push_constant(x->next, const_val);
    }
    else if (globals) {
        x->next->opcode(x->next, POP_TOP);
        x->next->opcode(x->next, POP_TOP);
        x->next->fast_load_from_globals(x->next, globals, name);
        PUSH(new_unknown());
    }
    else {
        x->next->load_from_globals(x->next, name);
        PUSH(new_unknown());
    }
}

static void
fast_load_from_globals(HotPyOptimiser *x, PyObject *globals, PyObject *name)
{
    HotPySpecialiser *opt = (HotPySpecialiser *)x;
    x->next->fast_load_from_globals(x->next, globals, name);
    PUSH(new_unknown());
}

static void
store_to_globals(HotPyOptimiser *x, PyObject *name)
{
    HotPySpecialiser *opt = (HotPySpecialiser *)x;
    CHECK_OK;
    /* TO DO -- Add out of line guard and convert to direct memory write */
    DROP();
    DROP();
    x->next->store_to_globals(x->next, name);
}

static void
has_special(HotPyOptimiser *x, PyObject *name)
{
    HotPySpecialiser *opt = (HotPySpecialiser *)x;
    PyObject *t, *info;
    CHECK_OK;
    info = POP();
    t = type_of(info);
    if (t != Py_None) {
        PyObject *attr = _PyType_Lookup((PyTypeObject *)t, name);
        /* t must be initialised */
        if (((PyTypeObject *)t)->tp_mro == NULL) {
            /* Uninitialised type */
#ifdef Py_DEBUG
            char msg[200];
            sprintf(msg, "(%s)->tp_mro is NULL. Was PyType_Ready() called?",
                    ((PyTypeObject *)t)->tp_name);
            Py_FatalError(msg);
#endif
        }
        else if (guard_type_attribute(x, t, name)) {
            x->next->opcode(x->next, POP_TOP);
            attr = attr ? Py_True : Py_False;
            x->next->push_constant(x->next, attr);
            PUSH(new_value(attr));
            Py_DECREF(info);
            return;
        }
    }
    PUSH(new_type(&PyBool_Type));
    Py_DECREF(info);
    x->next->has_special(x->next, name);
}

static void
fast_frame(HotPyOptimiser *x, int count, PyCodeObject *code)
{
    HotPySpecialiser *opt = (HotPySpecialiser *)x;
    CHECK_OK;
    SpecialiserFrame* f;
    PyObject *builtins = POP();
    PyObject *globals = POP();
    PyObject *co_info = POP();
    int i, lcount;
    CHECK_OK;
    lcount = code->co_nlocals;
    assert(lcount >= count);
    Py_DECREF(co_info);
    f = new_frame(lcount);
    if (f == NULL) {
        FAIL;
        Py_DECREF(builtins);
        Py_DECREF(globals);
        return;
    }
    f->globals = globals;
    f->builtins = builtins;
    if (count <= STACK_DEPTH(opt->top_frame)) {
        opt->top_frame->stack_pointer -= count;
        for (i = 0; i < count; i++) {
            f->locals[i] = STACK_ITEM(-i);
        }
    }
    else {
        for (i = STACK_DEPTH(opt->top_frame); i > 0; i--) {
            f->locals[count - i] = STACK_ITEM(i);
        }
        for (i = 0; i < count - STACK_DEPTH(opt->top_frame); i++) {
            f->locals[i] = NULL;
        }
        opt->top_frame->stack_pointer = opt->top_frame->stack_base;
    }
    PUSH(frame_info(f));
    x->next->fast_frame(x->next, count, code);
}

static HotPyContext *
make_frame(HotPyOptimiser *x, PyObject *function)
{
    HotPySpecialiser *opt = (HotPySpecialiser *)x;
    HotPyContext *context = NULL;
    CHECK_OK_NULL;
    PyObject *func_info = POP();
    PyObject *kws_info = POP();
    PyObject *args_info = POP();
    PyObject *kws = as_map(kws_info);
    PyObject *args = as_tuple(args_info);
    PyFrameObject *frame;
    SpecialiserFrame* f = NULL;
    PyObject *ex, *ty, *tb;
    assert(PyFunction_Check(function));
    if (kws && args &&
        (KIND(func_info) == TK_FUNCTION || value_of(func_info) == function)) {
        if (KIND(func_info) == TK_FUNCTION ||
            guard_function(function, opt->trace) >= 0) {
            PyErr_Fetch(&ty, &ex, &tb);
            frame = _PyEval_MakeFrame(function, args, kws);
            if (frame) {
                f = frame_from_frame(frame);
                Py_DECREF(frame);
            }
            PyErr_Restore(ty, ex, tb);
            x->next->make_frame_const(x->next, function);
        }
        else
            x->next->make_frame(x->next, function);
    }
    else
        x->next->make_frame(x->next, function);
    if (f)
        PUSH(frame_info(f));
    else
        PUSH(new_unknown());
    Py_DECREF(kws_info);
    Py_DECREF(args_info);
    Py_XDECREF(args);
    Py_DECREF(func_info);
    return context;
}

static void
make_frame_const(HotPyOptimiser *x, PyObject *function)
{
    HotPySpecialiser *opt = (HotPySpecialiser *)x;
    HotPyContext *context;
    PyObject *func_info = POP();
    fix_value(func_info, function);
    PUSH(func_info);
    context = make_frame(x, function);
    assert (context == NULL);
}

/* Consumes a reference to f */
static void push_frame(HotPySpecialiser *opt, SpecialiserFrame *f)
{
    int i;
    if (opt->frames == HOTPY_CONTEXT_DEPTH) {
        Py_CLEAR(opt->frame_stack[0]);
        for (i = 1; i < HOTPY_CONTEXT_DEPTH; i++)
            opt->frame_stack[i-1] = opt->frame_stack[i];
        opt->frames--;
    }
    opt->top_frame = opt->frame_stack[opt->frames] = f;
    opt->frames++;
}

static void
enter_frame(HotPyOptimiser *x, PyCodeObject *code)
{
    SpecialiserFrame *f;
    HotPySpecialiser *opt = (HotPySpecialiser *)x;
    PyObject *frame_info;
    CHECK_OK;
    frame_info = POP();
    if (KIND(frame_info) == TK_FRAME) {
        f = (SpecialiserFrame *)VALUE(frame_info);
        Py_INCREF(f);
    }
    else {
        f = new_frame(code->co_nlocals);
    }
    Py_DECREF(frame_info);
    push_frame(opt, f);
    SHOW_FRAME(f);
    x->next->enter_frame(x->next, code);
}

static void
gen_enter(HotPyOptimiser *x, PyCodeObject *code)
{
    SpecialiserFrame *f;
    HotPySpecialiser *opt = (HotPySpecialiser *)x;
    /* XXX - Do this properly, can maybe attach frame to generator
     * if optimising a loop? */
    PyObject *gen;
    CHECK_OK;
    gen = POP();
    f = new_frame(code->co_nlocals);
    Py_DECREF(gen);
    push_frame(opt, f);
    x->next->gen_enter(x->next, code);
}

static void leave_frame_common(HotPyOptimiser *x)
{
    HotPySpecialiser *opt = (HotPySpecialiser *)x;
    SpecialiserFrame *f = opt->top_frame;
    CHECK_OK;
    assert(opt->frames > 0);
    opt->frames--;
    if (opt->frames)
        opt->top_frame = opt->frame_stack[opt->frames-1];
    else
        opt->top_frame = NULL;
    assert(f == opt->frame_stack[opt->frames]);
    opt->frame_stack[opt->frames] = NULL;
    Py_DECREF(f);
}

static void leave_frame(HotPyOptimiser *x)
{
    leave_frame_common(x);
    x->next->leave_frame(x->next);
}

static void leave_gen_frame(HotPyOptimiser *x)
{
    leave_frame_common(x);
    x->next->leave_gen_frame(x->next);
}

static HotPyContext*
prepare_call_cfunction1(HotPyOptimiser *x, int flags)
{
    switch(flags & ~(METH_CLASS | METH_STATIC | METH_COEXIST)) {
    case METH_VARARGS: case METH_O: case METH_NOARGS:
        x->next->pick(x->next, 3);
        return x->next->opcode_with_exit(x->next, NO_KEYWORDS);
    case METH_VARARGS | METH_KEYWORDS:
        return NULL;
    default:
        abort();
    }
}

static HotPyContext*
prepare_call_cfunction2(HotPyOptimiser *x, int flags)
{
    switch(flags & ~(METH_CLASS | METH_STATIC | METH_COEXIST)) {
    case METH_VARARGS:
        x->next->opcode(x->next, ROT_TWO);
        x->next->opcode(x->next, POP_TOP);
        return NULL;
    case METH_VARARGS | METH_KEYWORDS:
        x->next->opcode(x->next, ROT_THREE);
        x->next->opcode(x->next, ROT_THREE);
        x->next->opcode(x->next, POP_TOP);
        return NULL;
    case METH_O:
        return x->next->opcode_with_exit(x->next, ONE_ARG);
    case METH_NOARGS:
        return x->next->opcode_with_exit(x->next, NO_ARGS);
    default:
        abort();
    }
}

static HotPyContext*
prepare_call_cmethod2(HotPyOptimiser *x, int flags)
{
    switch(flags & ~(METH_CLASS | METH_STATIC | METH_COEXIST)) {
    case METH_VARARGS:
        return x->next->opcode_with_exit(x->next, ONE_PLUS_ARGS);
    case METH_VARARGS | METH_KEYWORDS:
    {
       HotPyContext *context;
       x->next->opcode(x->next, ROT_THREE);
       context = x->next->opcode_with_exit(x->next, ONE_PLUS_ARGS);
       x->next->opcode(x->next, ROT_THREE);
       x->next->opcode(x->next, ROT_THREE);
       return context;
    }
    case METH_O:
        return x->next->opcode_with_exit(x->next, TWO_ARGS);
    case METH_NOARGS:
        return x->next->opcode_with_exit(x->next, ONE_ARG);
    default:
        abort();
    }
}

static HotPyContext*
call_cmethod(HotPyOptimiser *x, PyObject *m, int args)
{
    HotPySpecialiser *opt = (HotPySpecialiser *)x;
    while (args--)
        DROP();
    PUSH(new_unknown());
    return x->next->call_cmethod(x->next, m, args);
}

static HotPyContext*
call_cfunction(HotPyOptimiser *x, PyObject *f, int args)
{
    HotPySpecialiser *opt = (HotPySpecialiser *)x;
    while (args--)
        DROP();
    PUSH(new_unknown());
    return x->next->call_cfunction(x->next, f, args);
}

static HotPyContext*
call_wrapper(HotPyOptimiser *x, int opcode, PyObject *w)
{
    HotPySpecialiser *opt = (HotPySpecialiser *)x;
    int proc = 0;
    switch (opcode) {
    case CALL_WRAPPER_TRINARY_PROC:
        DROP();
    case CALL_WRAPPER_BINARY_NULL_PROC:
        proc = 1;
    case CALL_WRAPPER_BINARY:
        DROP();
    case CALL_WRAPPER_NEXT: case CALL_WRAPPER_UNARY:
        DROP();
        break;
    default:
        assert("Unknown opcode" && 0);
    }
    if (!proc)
        PUSH(new_unknown());
    return x->next->call_wrapper(x->next, opcode, w);
}

static HotPyContext *
customise_call_cmethod(HotPyOptimiser *x, PyObject *m, int flags)
{
    HotPySpecialiser *opt = (HotPySpecialiser *)x;
    PUSH(new_unknown());
    switch(flags & ~(METH_CLASS | METH_STATIC | METH_COEXIST)) {
    case METH_VARARGS: case METH_O:
        return x->next->call_cmethod(x->next, m, 1);
    case METH_VARARGS | METH_KEYWORDS:
        return x->next->call_cmethod(x->next, m, 2);
    case METH_NOARGS:
        return x->next->call_cmethod(x->next, m, 0);
    }
    abort();
}

static HotPyContext*
customise_call_cfunction(HotPyOptimiser *x, PyObject *f, int flags)
{
    HotPySpecialiser *opt = (HotPySpecialiser *)x;
    PUSH(new_unknown());
    switch(flags & ~(METH_CLASS | METH_STATIC | METH_COEXIST)) {
    case METH_VARARGS: case METH_O:
        return x->next->call_cfunction(x->next, f, 1);
    case METH_VARARGS | METH_KEYWORDS:
        return x->next->call_cfunction(x->next, f, 2);
    case METH_NOARGS:
        return x->next->call_cfunction(x->next, f, 0);
    }
    abort();
}

static HotPyContext*
prepare_call_wrapper1(HotPyOptimiser *x, PyObject *callable)
{
    struct wrapperbase *base = ((PyWrapperDescrObject *)callable)->d_base;
    switch(base->offset) {
    case offsetof(PyTypeObject, tp_iter): /* __iter__ */
    case offsetof(PyTypeObject, tp_iternext): /* __next__ */
    case offsetof(PyHeapTypeObject, as_number.nb_add): /* __add__ */
    case offsetof(PyHeapTypeObject, as_mapping.mp_subscript): /* __getitem__ */
    case offsetof(PyHeapTypeObject, as_mapping.mp_ass_subscript): /* __setitem__ */
        x->next->pick(x->next, 3);
        return x->next->opcode_with_exit(x->next, NO_KEYWORDS);
    default:
        return NULL;
    }
}

static HotPyContext*
prepare_call_wrapper2(HotPyOptimiser *x, PyObject *callable)
{
    struct wrapperbase *base = ((PyWrapperDescrObject *)callable)->d_base;
    switch(base->offset) {
    case offsetof(PyTypeObject, tp_iter): /* __iter__ */
        return x->next->opcode_with_exit(x->next, ONE_ARG);
    case offsetof(PyTypeObject, tp_iternext): /* __next__ */
        return x->next->opcode_with_exit(x->next, ONE_ARG);
    case offsetof(PyHeapTypeObject, as_number.nb_add): /* __add__ */
    case offsetof(PyHeapTypeObject, as_mapping.mp_subscript): /* __getitem__ */
        return x->next->opcode_with_exit(x->next, TWO_ARGS);
    case offsetof(PyHeapTypeObject, as_mapping.mp_ass_subscript): /* __setitem__ */
        if (base->name[2] == 's') {
            assert(strcmp(base->name, "__setitem__") == 0);
            return x->next->opcode_with_exit(x->next, THREE_ARGS);
        }
        else {
            assert(strcmp(base->name, "__delitem__") == 0);
            return x->next->opcode_with_exit(x->next, TWO_ARGS);
        }
    default:
        return NULL;
    }
}

static HotPyContext*
customise_call_wrapper(HotPyOptimiser *x, PyObject *callable)
{
    char buf[200];
    HotPySpecialiser *opt = (HotPySpecialiser *)x;
    HotPyContext* context;
    struct wrapperbase *base = ((PyWrapperDescrObject *)callable)->d_base;
    int opcode;
    /* Would be useful for know types */
    PUSH(new_unknown());
    switch(base->offset) {
    case offsetof(PyTypeObject, tp_iter): /* __iter__ */
        opcode = CALL_WRAPPER_UNARY;
        break;
    case offsetof(PyTypeObject, tp_iternext): /* __next__ */
        opcode = CALL_WRAPPER_NEXT;
        break;
    case offsetof(PyHeapTypeObject, as_mapping.mp_subscript): /* __getitem__ */
        /* If values are both constants and type is bytes, unicode or tuple
         * then result is a constant */
    case offsetof(PyHeapTypeObject, as_number.nb_add): /* __add__ */
        opcode = CALL_WRAPPER_BINARY;
        break;
    case offsetof(PyHeapTypeObject, as_mapping.mp_ass_subscript): /* __setitem__ */
        if (base->name[2] == 's')
            opcode = CALL_WRAPPER_TRINARY_PROC;
        else {
            opcode = CALL_WRAPPER_BINARY_NULL_PROC;
        }
        break;
    default:
        sprintf(buf, "Failed to specialise call_wrapper for %s at %d", base->name, base->offset);
        x->next->comment(x->next, buf);
        return x->next->call_object(x->next);
    }
    context = x->next->call_wrapper(x->next, opcode, callable);
    if (opcode == CALL_WRAPPER_TRINARY_PROC || opcode == CALL_WRAPPER_BINARY_NULL_PROC)
        x->next->push_constant(x->next, Py_None);
    return context;
}

static HotPyContext *
prepare_call1(HotPyOptimiser *x)
{
    HotPySpecialiser *opt = (HotPySpecialiser *)x;
    HotPyContext* context = NULL;
    PyObject *f, *f_t, *f_v;
    if (STACK_DEPTH(opt->top_frame) < 3) {
        /* Can do nothing here */
        return NULL;
    }
    f = STACK_ITEM(3);
    f_t = type_of(f);
    f_v = value_of(f);
    if (f_t == (PyObject *)&PyCFunction_Type) {
        if (f_v) {
            int flags;
            flags = PyCFunction_GET_FLAGS(f_v);
            context = prepare_call_cfunction1(x, flags);
        }
    }
    else if (f_t == (PyObject *)&PyMethodDescr_Type && f_v) {
        int flags = ((PyMethodDescrObject *)f_v)->d_method->ml_flags;
        context = prepare_call_cfunction1(x, flags);
    }
    else if (f_t == (PyObject *)&PyWrapperDescr_Type && f_v) {
        context = prepare_call_wrapper1(x, f_v);
    }
    if (context)
        save_state_to_context(x, context);
    return context;
}

static HotPyContext *
prepare_call2(HotPyOptimiser *x)
{
    HotPySpecialiser *opt = (HotPySpecialiser *)x;
    HotPyContext* context = NULL;
    PyObject *f, *f_t, *f_v;
    if (STACK_DEPTH(opt->top_frame) < 3) {
        /* Can do nothing here */
        return NULL;
    }
    f = STACK_ITEM(3);
    f_t = type_of(f);
    f_v = value_of(f);
    if (f_t == (PyObject *)&PyCFunction_Type && f_v) {
        int flags;
        flags = PyCFunction_GET_FLAGS(f_v);
        context = prepare_call_cfunction2(x, flags);
    }
    else if (f_t == (PyObject *)&PyMethodDescr_Type && f_v) {
        int flags = ((PyMethodDescrObject *)f_v)->d_method->ml_flags;
        context = prepare_call_cmethod2(x, flags);
    }
    else if (f_t == (PyObject *)&PyWrapperDescr_Type && f_v) {
        context = prepare_call_wrapper2(x, f_v);
    }
    if (context)
        save_state_to_context(x, context);
    return context;
}

static HotPyContext *
call_object(HotPyOptimiser *x)
{
    HotPySpecialiser *opt = (HotPySpecialiser *)x;
    PyObject *f, *f_t, *f_v, *args;
    HotPyContext* context;
    DROP(); /* kws */
    args = POP();
    f = POP();
    f_t = type_of(f);
    f_v = value_of(f);
    if (f_t == (PyObject *)&PyCFunction_Type) {
        if (f_v) {
            int flags;
            flags = PyCFunction_GET_FLAGS(f_v);
            context = customise_call_cfunction(x, f_v, flags);
        }
        else {
            PUSH(new_unknown());
            context = x->next->call_object(x->next);
            x->next->comment(x->next, "Failed to specialise call_object for CFunction");
        }
    }
    else if (f_t == (PyObject *)&PyWrapperDescr_Type && f_v) {
        context = customise_call_wrapper(x, f_v);
    } else if (f_t == (PyObject *)&PyMethodDescr_Type && f_v) {
        int flags = ((PyMethodDescrObject *)f_v)->d_method->ml_flags;
        context = customise_call_cmethod(x, f_v, flags);
    }
    else {
        PUSH(new_unknown());
        context = x->next->call_object(x->next);
        if (f_t == Py_None)
            x->next->comment(x->next,
                "Failed to specialise call_object for unknown");
        else {
           char buf[80];
           snprintf(buf, 79, "Failed to specialise call_object for %s",
                    ((PyTypeObject *)f_t)->tp_name);
           x->next->comment(x->next, "buf");
        }
    }
    if (context)
        save_state_to_context(x, context);
    Py_DECREF(f);
    Py_DECREF(args);
    return context;
}

static PyObject *
descriptor_get_bound(PyObject *desc, PyObject *obj, PyObject *fall_back)
{
    assert(KIND(obj) == TK_BOUND);
    if (Py_TYPE(desc) == &PyMemberDescr_Type) {
        PyMemberDef *l;
        l = ((PyMemberDescrObject *)desc)->d_member;
        if (strcmp(l->name, "__self__") == 0) {
            Py_INCREF(PyTuple_GET_ITEM(VALUE(obj), 2));
            return PyTuple_GET_ITEM(VALUE(obj), 2);
        }
        else if (strcmp(l->name, "__func__") == 0) {
            Py_INCREF(PyTuple_GET_ITEM(VALUE(obj), 1));
            return PyTuple_GET_ITEM(VALUE(obj), 1);
        }
    }
    return fall_back;
}

static HotPyContext *
opcode_with_exit(HotPyOptimiser *x, int op)
{
    HotPySpecialiser *opt = (HotPySpecialiser *)x;
    PyObject *info;
    HotPyContext *context = NULL;
    CHECK_OK_NULL;
    switch(op) {
    case VALUE_FROM_OBJECT_DICT_OR_EXIT:
    {
        PyObject *obj, *key, *type;
        PyDictKeysObject *keys;
        /* XXX - Check keys & use indexed access */
        obj = POP(); /* The object */
        info = POP(); /* The key */
        PUSH(new_unknown());
        key = value_of(info);
        type = type_of(obj);
        if (key && type != Py_None &&
            (((PyTypeObject *)type)->tp_flags & Py_TPFLAGS_HEAPTYPE) &&
            (keys = ((PyHeapTypeObject *)type)->ht_cached_keys)) {
            int index = _PyDictKeysObject_IndexOf(keys, key);
            if (index >= 0 && ((PyTypeObject *)type)->tp_dictoffset > 0) {
                x->next->opcode(x->next, ROT_TWO);
                x->next->opcode(x->next, POP_TOP);
                context = x->next->from_object_dict_fast(x->next,
                    ((PyTypeObject *)type)->tp_dictoffset, keys, key);
                Py_DECREF(info);
                if (context)
                    save_state_to_context(x, context);
                return context;
            }
        }
        Py_DECREF(info);
        break;
    }
    case EXIT_IF_VALUE_IN_OBJECT_DICT:
    {
        PyObject *type;
        /* XXX - Check keys */
        info = POP();
        DROP();
        type = type_of(info);
        if (type != Py_None && Py_TYPE(type)->tp_dictoffset == 0) {
            x->next->opcode(x->next, POP_TOP);
            x->next->opcode(x->next, POP_TOP);
            return NULL;
        }
        break;
    }
    case EXIT:
        break;
    case POP_EXIT_IF_FALSE:
        /* Value must be an int or bool */
        info = POP();
        if (KIND(info) == TK_VALUE) {
            assert(PyObject_IsTrue(VALUE(info)));
            x->next->opcode(x->next, POP_TOP);
            Py_DECREF(info);
            return NULL;
        }
        if (type_of(info) == (PyObject *)&PyBool_Type)
            fix_value(info, Py_True);
        Py_DECREF(info);
        break;
    case POP_EXIT_IF_TRUE:
        /* Popped value must be False or 0 */
        info = POP();
        if (KIND(info) == TK_VALUE) {
            assert(PyObject_Not(VALUE(info)));
            x->next->opcode(x->next, POP_TOP);
            Py_DECREF(info);
            return NULL;
        }
        if (type_of(info) == (PyObject *)&PyBool_Type)
            fix_value(info, Py_False);
        else if (type_of(info) == (PyObject *)&PyLong_Type)
            fix_value(info, PyLong_FromLong(0));
        Py_DECREF(info);
        break;
    case TRACE_DESCRIPTOR_GET:
        {
            PyObject *desc;
            PyObject *info = NULL;
            PyMemberDef *def = NULL;
            PyTypeObject *bound_type = NULL;
            PyObject *v, *w, *t;
            v = POP();
            w = POP();
            desc = value_of(w);
            t = type_of(w);
            if (desc && t == (PyObject *)&PyMemberDescr_Type) {
                PyTypeObject *t = PyMember_Type(desc);
                def = ((PyMemberDescrObject *)desc)->d_member;
                if (t)
                    info = new_type(t);
            }
            if (desc && KIND(v) == TK_BOUND) {
                info = descriptor_get_bound(desc, v, info);
            }
            else if (desc) {
                if (t == (PyObject *)&PyMethodDescr_Type)
                    bound_type = &PyCMethod_Type;
                else if (t == (PyObject *)&PyWrapperDescr_Type)
                    bound_type = &_PyMethodWrapper_Type;
                else if (t == (PyObject *)&PyFunction_Type)
                    bound_type = &PyMethod_Type;
                if (bound_type)
                    info = new_bound(bound_type, w, v);

            }
            if (info)
                PUSH(info);
            else
                PUSH(new_unknown());
            Py_DECREF(v);
            Py_DECREF(w);
            if (def) {
                x->next->opcode(x->next, ROT_TWO);
                x->next->opcode(x->next, POP_TOP);
                context = x->next->load_member(x->next, (PyMemberDescrObject *)desc);
                if (context)
                    save_state_to_context(x, context);
                return context;
            }
            if (bound_type) {
                x->next->bind_callable(x->next, bound_type);
                return NULL;
            }
            break;
        }
    case TRACE_DESCRIPTOR_SET:
        {
            PyObject *desc;
            PyObject *u, *v, *w, *t;
            PyMemberDef *def = NULL;
            u = POP();
            v = POP();
            w = POP();
            desc = value_of(w);
            t = type_of(w);
            if (desc && t == (PyObject *)&PyMemberDescr_Type) {
                def = ((PyMemberDescrObject *)desc)->d_member;
            }
            Py_DECREF(u);
            Py_DECREF(v);
            Py_DECREF(w);
            if (def && def->flags != READONLY && def->offset < (1 << 16) &&
                (def->type == T_OBJECT || def->type == T_OBJECT_EX)) {
                context = x->next->store_member(x->next, def);
                if (context)
                    save_state_to_context(x, context);
                return context;
            }
            break;
        }
    default:
        fprintf(stderr, "Unexpected opcode in specialiser %d\n", op);
        abort();
    }
    context = x->next->opcode_with_exit(x->next, op);
    if (context)
        save_state_to_context(x, context);
    SHOW_STACK();
    return context;
}

static void
tuple_concat(HotPyOptimiser *x)
{
    HotPySpecialiser *opt = (HotPySpecialiser *)x;
    PyObject *l, *r;
    PyObject *res = NULL;
    CHECK_OK;
    r = POP();
    l = POP();
    if (KIND(l) == TK_VALUE && PyTuple_CheckExact(VALUE(l)) &&
        Py_SIZE(VALUE(l)) == 0) {
        Py_INCREF(r);
        res = r;
    }
    else if (KIND(r) == TK_VALUE && PyTuple_CheckExact(VALUE(r)) &&
        Py_SIZE(VALUE(r)) == 0) {
        Py_INCREF(l);
        res = l;
    }
    else if (KIND(l) == TK_VALUE && KIND(r) == TK_VALUE) {
        PyObject *t;
        assert(PyTuple_CheckExact(value_of(l)) &&
               PyTuple_CheckExact(value_of(r)));
        t = PyNumber_Add(VALUE(l), VALUE(r));
        if (t)
            res = new_value(t);
        Py_XDECREF(t);
    }
    else if (KIND(l) == TK_TUPLE && KIND(r) == TK_TUPLE) {
        PyObject *t = PyNumber_Add(VALUE(l), VALUE(r));
        if (t)
            res = new_tuple(t);
    }
    if (res && value_of(res)) {
        x->next->opcode(x->next, POP_TOP);
        x->next->opcode(x->next, POP_TOP);
        PUSH(res);
        x->next->push_constant(x->next, value_of(res));
        goto cleanup;
    }
    if (res)
        PUSH(res);
    else
        PUSH(new_type(&PyTuple_Type));
    x->next->tuple_concat(x->next);
    SHOW_STACK();
cleanup:
    Py_DECREF(l);
    Py_DECREF(r);
}


static void
clear(HotPyOptimiser *x)
{
    HotPySpecialiser *opt = (HotPySpecialiser *)x;
    CHECK_OK;
    opt->top_frame = NULL;
    while (opt->frames) {
        opt->frames--;
        Py_CLEAR(opt->frame_stack[opt->frames]);
    }
    Py_CLEAR(opt->trace);
    x->next->clear(x->next);
}

static void
finish(HotPyOptimiser *x)
{
    x->next->finish(x->next);
}

static int
start(HotPyOptimiser *x, HotPyTraceObject *trace,
      PyFrameObject *f, HotPyContext* context, char *reason)
{
    int i;
    HotPySpecialiser *opt = (HotPySpecialiser *)x;
    opt->err_occurred = 0;
    assert(opt->trace == NULL);
    Py_INCREF(trace);
    opt->trace = trace;
    assert(opt->top_frame == NULL);
    assert(opt->frames == 0);
    assert(opt->frame_stack[0] == NULL);
    if (context->cf_type_info == Py_None) {
        opt->top_frame = new_frame(f->f_code->co_nlocals);
        opt->frames = 1;
        opt->frame_stack[0] = opt->top_frame;
    }
    else {
        assert(PyTuple_CheckExact(context->cf_type_info));
        opt->frames = PyTuple_GET_SIZE(context->cf_type_info);
        assert(opt->frames <= HOTPY_CONTEXT_DEPTH);
        for (i = 0; i < opt->frames; i++) {
            opt->frame_stack[i] = thaw_frame(PyTuple_GET_ITEM(context->cf_type_info, i));
        }
        opt->top_frame = opt->frame_stack[opt->frames-1];
    }
    assert(opt->top_frame);
    return x->next->start(x->next, trace, f, context, reason);
}

/* 1 refers to TOS, 2 NOS, etc.
  Shape is read such that TOS is on the left (ignoring leading 0) */
static void
stack(PyObject ***sp, unsigned pop, unsigned new_shape) {
    PyObject *popped[4];
    int i;
    for (i = 1; i <= pop; i++) {
        (*sp)--;
        popped[i] = **sp;
    }
    while (new_shape) {
        unsigned push = new_shape & 7;
        new_shape >>= 3;
        Py_XINCREF(popped[push]);
        **sp = popped[push];
        (*sp)++;
    }
    for (i = 1; i <= pop; i++) {
        Py_XDECREF(popped[i]);
    }
}

static void
kw_dict_merge(PyObject *into_info, PyObject *from_info)
{
    Py_ssize_t i;
    PyObject *from, *into;
    PyObject *key, *value;
    assert(Py_TYPE(into_info) == & TypeInfo_Type);
    assert(Py_TYPE(from_info) == & TypeInfo_Type);
    from = VALUE(from_info);
    into = VALUE(into_info);
    if (KIND(from_info) != TK_MAP || KIND(into_info) != TK_MAP)
        goto fail;
    i = 0;
    while (PyDict_Next(from, &i, &key, &value)) {
        if (PyDict_GetItem(into, key))
            goto fail;
        if (PyDict_SetItem(into, key, value))
            goto fail;
    }
    return;
fail:
    Py_INCREF(&PyDict_Type);
    KIND(into_info) = TK_TYPE;
    VALUE(into_info) = (PyObject *)&PyDict_Type;
    Py_DECREF(into);
}

#define STACK_OP(n, s) do { \
    if (STACK_DEPTH(opt->top_frame) < n) { \
        assert(STACK_DEPTH(opt->top_frame) >= 0); \
        COMMENT("Insufficient stack depth"); \
        while (STACK_DEPTH(opt->top_frame)) \
            DROP(); \
    } \
    else \
        stack(&opt->top_frame->stack_pointer, n, s); \
} while (0)

static void
opcode(HotPyOptimiser *x, int op)
{
    HotPySpecialiser *opt = (HotPySpecialiser *)x;
    PyObject *t, *v, *w;
    PyObject *name;
    CHECK_OK;
    assert(op == RETURN_VALUE || STACK_DEPTH(opt->top_frame) >= 0);
    switch (op) {
    case POP_TOP:
        STACK_OP(1, 0);
        break;
    case ROT_TWO:
        STACK_OP(2, 021);
        break;
    case ROT_THREE:
        STACK_OP(3, 0231);
        break;
    case DUP_TOP:
        STACK_OP(1, 011);
        break;
    case DUP_TOP_TWO:
        STACK_OP(2, 01212);
        break;
    case VALUE_NOP:
    case NOP:
        return;
    case GET_CLASS_ATTR:
        w = POP();
        v = POP();
        t = value_of(v);
        name = value_of(w);
        if (t && PyType_Check(t) && name) {
            PyObject *attr = _PyType_Lookup((PyTypeObject *)t, name);
            if (attr && guard_type_attribute(x, t, name)) {
                x->next->opcode(x->next, POP_TOP);
                x->next->opcode(x->next, POP_TOP);
                x->next->push_constant(x->next, attr);
                PUSH(new_value(attr));
                Py_DECREF(w);
                Py_DECREF(v);
                return;
            }
        }
        PUSH(new_unknown());
        Py_DECREF(v);
        Py_DECREF(w);
        break;
    case HAS_CLASS_ATTR:
        w = POP();
        v = POP();
        t = value_of(v);
        name = value_of(w);
        if (t && PyType_Check(t) && name) {
            PyObject *attr = _PyType_Lookup((PyTypeObject *)t, name);
            if (guard_type_attribute(x, t, name)) {
                x->next->opcode(x->next, POP_TOP);
                x->next->opcode(x->next, POP_TOP);
                attr = attr ? Py_True : Py_False;
                x->next->push_constant(x->next, attr);
                PUSH(new_value(attr));
                Py_DECREF(w);
                Py_DECREF(v);
                return;
            }
        }
        PUSH(new_type(&PyBool_Type));
        Py_DECREF(v);
        Py_DECREF(w);
        break;
    case HAS_DICT:
        w = POP();
        t = type_of(w);
        if (t != Py_None) {
            int has_dict = _PyObject_GetDictPtr(t) != NULL;
            PUSH(new_value(has_dict ? Py_True : Py_False));
            x->next->opcode(x->next, POP_TOP);
            x->next->push_constant(x->next, has_dict ? Py_True : Py_False);
            Py_DECREF(w);
            return;
        }
        PUSH(new_type(&PyBool_Type));
        Py_DECREF(w);
        break;
    case GET_TYPE:
        assert(0 && "Should be removed by recording interpreter");
        break;
    case POP_BLOCK: case POP_CALLER_BLOCK:
        break;
    case SET_IN_OBJECT_DICT:
    {
        PyObject *obj, *key, *type;
        PyObject *info;
        PyDictKeysObject *keys;
        obj = POP(); /* The object */
        info = POP(); /* The key */
        DROP(); /* The value */
        key = value_of(info);
        type = type_of(obj);
        if (key && type != Py_None &&
            (((PyTypeObject *)type)->tp_flags & Py_TPFLAGS_HEAPTYPE) &&
            (keys = ((PyHeapTypeObject *)type)->ht_cached_keys)) {
            int index = _PyDictKeysObject_IndexOf(keys, key);
            if (index >= 0 && ((PyTypeObject *)type)->tp_dictoffset > 0) {
                x->next->opcode(x->next, ROT_TWO);
                x->next->opcode(x->next, POP_TOP);
                x->next->set_in_object_dict_fast(x->next,
                    ((PyTypeObject *)type)->tp_dictoffset, keys, key);
                Py_DECREF(info);
                return;
            }
        }
        Py_DECREF(info);
        break;
    }
    case GEN_EXIT:
        DROP();
        break;
    case GEN_CLEAR:
        break;
    case GEN_STARTED:
        DROP();
        PUSH(new_type(&PyBool_Type));
        break;
    case NEW_CLOSURE:
        DROP();
        w = POP();
        DROP();
        PUSH(new_function(w));
        Py_DECREF(w);
        break;
    case NEW_FUNCTION:
        DROP();
        w = POP();
        PUSH(new_function(w));
        Py_DECREF(w);
        break;
    case OVERRIDES:
        {
            PyObject *u, *tu, *tv;
            int res = -1;
            w = POP();
            v = POP();
            u = POP();
            tv = type_of(v);
            tu = type_of(u);
            name = value_of(w);
            if (name && tu != Py_None && tv != Py_None) {
                if (tu == tv)
                    res = 0;
                else if (!PyType_IsSubtype((PyTypeObject *)tv,
                                           (PyTypeObject *)tu))
                    res = 0;
                else {
                    PyObject *ua = _PyType_Lookup((PyTypeObject *)tu, name);
                    PyObject *va = _PyType_Lookup((PyTypeObject *)tv, name);
                    if (guard_type_attribute(x, tu, name) &&
                        guard_type_attribute(x, tv, name))
                        res = ua != va;
                }
            }
            Py_DECREF(u);
            Py_DECREF(v);
            Py_DECREF(w);
            if (res == -1) {
                PUSH(new_type(&PyBool_Type));
                break;
            }
            PUSH(new_value(res ? Py_True : Py_False));
            x->next->opcode(x->next, POP_TOP);
            x->next->opcode(x->next, POP_TOP);
            x->next->opcode(x->next, POP_TOP);
            x->next->push_constant(x->next, res ? Py_True : Py_False);
            return;
        }
    case OVERRIDES_GENERIC_GETATTRIBUTE:
        name = PyUnicode_FromString("__getattribute__");
        w = POP();
        t = type_of(w);
        if (t != Py_None) {
            if (guard_type_attribute(x, t, name)) {
                int res = ((PyTypeObject *)t)->tp_getattro != PyObject_GenericGetAttr;
                PUSH(new_value(res ? Py_True : Py_False));
                x->next->opcode(x->next, POP_TOP);
                x->next->push_constant(x->next, res ? Py_True : Py_False);
                Py_DECREF(w);
                Py_DECREF(name);
                return;
            }
        }
        Py_DECREF(w);
        Py_DECREF(name);
        PUSH(new_type(&PyBool_Type));
        break;
    case OVERRIDES_GENERIC_SETATTR:
        name = PyUnicode_FromString("__setattr__");
        w = POP();
        t = type_of(w);
        if (t != Py_None) {
            if (guard_type_attribute(x, t, name)) {
                int res = ((PyTypeObject *)t)->tp_setattro != PyObject_GenericSetAttr;
                PUSH(new_value(res ? Py_True : Py_False));
                x->next->opcode(x->next, POP_TOP);
                x->next->push_constant(x->next, res ? Py_True : Py_False);
                Py_DECREF(w);
                Py_DECREF(name);
                return;
            }
        }
        Py_DECREF(w);
        Py_DECREF(name);
        PUSH(new_type(&PyBool_Type));
        break;
    case STOP_ITERATION_OR_RERAISE:
        break;
    case STORE_MAP:
        t = POP();  /* dict */
        w = POP();  /* key */
        v = POP();  /* value */
        map_add(t, w, v);
        fix_type(t, &PyDict_Type);
        PUSH(t);
        Py_XDECREF(w);
        Py_XDECREF(v);
        break;
    case UNARY_NOT:
        {
            PyObject *info = POP();
            PyObject *val = value_of(info);
            if (val) {
                int n = PyObject_Not(val);
                val = n ? Py_True : Py_False;
                x->next->opcode(x->next, POP_TOP);
                push_constant(x, val);
                Py_DECREF(info);
                return;
            }
            PUSH(new_type(&PyBool_Type));
            Py_DECREF(info);
            break;
        }

    case AS_TUPLE:
        {
            PyObject *info = POP();
            if (type_of(info) == (PyObject *)&PyTuple_Type) {
                PUSH(info);
                return;
            }
            Py_DECREF(info);
            PUSH(new_type(&PyTuple_Type));
            break;
        }
    case KW_DICT_MERGE:
        {
            PyObject* func = POP();
            PyObject* from = POP();
            PyObject* into = POP();
            kw_dict_merge(into, from);
            Py_DECREF(func);
            Py_DECREF(from);
            PUSH(into);
            break;
        }
    case SUB_TYPE:
        {
            PyObject *tos = POP();
            PyObject *nos = POP();
            int res = -1;
            if (KIND(tos) == TK_VALUE && KIND(nos) == TK_VALUE) {
                PyObject *super = VALUE(tos);
                PyObject *sub = VALUE(nos);
                if (PyType_Check(super) &&  PyType_Check(sub))
                    res = PyType_IsSubtype((PyTypeObject *)sub,
                                           (PyTypeObject *)super);
            }
            Py_DECREF(tos);
            Py_DECREF(nos);
            if (res < 0) {
                PUSH(new_type(&PyBool_Type));
                break;
            }
            x->next->opcode(x->next, POP_TOP);
            x->next->opcode(x->next, POP_TOP);
            push_constant(x, res ? Py_True : Py_False);
            return;
        }
    case MAKE_GENERATOR:
        DROP();
        PUSH(new_type(&PyGen_Type));
        break;
    case SWAP_EXC_STATE: case SAVE_EXC_STATE: case RESTORE_CLEAR_EXC_STATE:
        break;
    case SIZE:
        v = POP();
        if (KIND(v) == TK_TUPLE) {
            w = PyLong_FromSsize_t(PyTuple_Size(VALUE(v)));
            x->next->opcode(x->next, POP_TOP);
            push_constant(x, w);
            Py_DECREF(v);
            return;
        }
        w = value_of(v);
        if (w) {
             w = PyLong_FromSsize_t(Py_SIZE(w));
            x->next->opcode(x->next, POP_TOP);
            push_constant(x, w);
            Py_DECREF(v);
            return;
        }
        PUSH(new_type(&PyLong_Type));
        Py_DECREF(v);
        break;
    case ALLOCATE:
        v = POP();
        t = value_of(v);
        if (t && PyType_Check(t))
            PUSH(new_type((PyTypeObject *)t));
        else
            PUSH(new_unknown());
        Py_DECREF(v);
        break;
    case CLEAR_FRAME: case POP_EXCEPT:
        while STACK_DEPTH(opt->top_frame)
            DROP();
        break;
    case RETURN_VALUE:
        break;
    default:
        fprintf(stderr, "Specialiser not implemented: %s\n", _HotPy_Instruction_Names[op]);
        exit(-1);
    }
    x->next->opcode(x->next, op);
}

static void
setup_block(HotPyOptimiser *x, int op, int a, int b)
{
     x->next->setup_block(x->next, op, a, b);
}


static void
opcode_with_arg(HotPyOptimiser *x, int op, int oparg)
{
    int i;
    HotPySpecialiser *opt = (HotPySpecialiser *)x;
    CHECK_OK;
    PyObject *v;
    assert(STACK_DEPTH(opt->top_frame) >= 0);
    switch (op) {
    case LIST_APPEND:
        v = POP();
        DROP();
        fix_type(v, &PyList_Type);
        Py_DECREF(v);
        break;
    case SET_ADD:
        v = POP();
        DROP();
        fix_type(v, &PySet_Type);
        Py_DECREF(v);
        break;
    case DELETE_DEREF:
        break;
    case LOAD_DEREF:
        PUSH(new_unknown());
        break;
    case STORE_DEREF:
        DROP();
        break;
    case BUILD_TUPLE:
        if (STACK_DEPTH(opt->top_frame) < oparg) {
            COMMENT("Insufficient stack depth");
            while (STACK_DEPTH(opt->top_frame))
                DROP();
            PUSH(new_type(&PyTuple_Type));
        } else {
            opt->top_frame->stack_pointer -= oparg;
            PUSH(build_tuple(oparg, opt->top_frame->stack_pointer));
        }
        break;
    case BUILD_LIST:
        if (STACK_DEPTH(opt->top_frame) < oparg)
            COMMENT("Insufficient stack depth");
        for (i = 0; i < oparg; i++)
            DROP();
        PUSH(new_type(&PyList_Type));
        break;
    case BUILD_SET:
        if (STACK_DEPTH(opt->top_frame) < oparg)
            COMMENT("Insufficient stack depth");
        for (i = 0; i < oparg; i++)
            DROP();
        PUSH(new_type(&PySet_Type));
        break;
    case BUILD_MAP:
        PUSH(new_map(PyDict_New()));
        break;
    case BUILD_SLICE:
        DROP();
        DROP();
        if (oparg == 3)
            DROP();
        PUSH(new_type(&PySlice_Type));
        break;
    case LOAD_CLOSURE:
        PUSH(new_unknown());
        break;
    case UNPACK_SEQUENCE:
        {
            PyObject *seq = POP();
            for (i = 0; i < oparg; i++)
                PUSH(new_unknown());
            Py_XDECREF(seq);
            break;
        }
    default:
        fprintf(stderr, "Specialiser not implmented: %s\n", _HotPy_Instruction_Names[op]);
        exit(-1);
    }
    x->next->opcode_with_arg(x->next, op, oparg);
    SHOW_STACK();
}

static void
set_lasti(HotPyOptimiser *x, int line)
{
    return x->next->set_lasti(x->next, line);
}

static void
fail(HotPyOptimiser *x, int op, char *msg)
{
    return x->next->fail(x->next, op, msg);
}

static void unrolling(HotPyOptimiser *x)
{
    /* XXX - Record type-info for loop header */
    return x->next->unrolling(x->next);
}

static HotPyContext *
current_context(HotPyOptimiser *x)
{
    HotPyContext *context = x->next->current_context(x->next);
    if (context)
        save_state_to_context(x, context);
    return context;
}

static void
dead_locals(HotPyOptimiser *x)
{
    x->next->dead_locals(x->next);
}

/* These are already specialised, so we don't expect to see these.
 * Just pass them on */
static void
bind_callable(HotPyOptimiser *x, PyTypeObject *bound_type)
{
    x->next->bind_callable(x->next, bound_type);
}

static HotPyContext *
load_member(HotPyOptimiser *x, PyMemberDescrObject *desc)
{
    HotPySpecialiser *opt = (HotPySpecialiser *)x;
    HotPyContext *context;
    PyObject *v, *w;
    w = POP();
    v = value_of(w);
    context = x->next->load_member(x->next, desc);
    if (context)
        save_state_to_context(x, context);
    PUSH(new_unknown());
    Py_DECREF(w);
    return context;
}

static HotPyContext *
store_member(HotPyOptimiser *x, PyMemberDef *def)
{
    HotPySpecialiser *opt = (HotPySpecialiser *)x;
    HotPyContext *context;
    PyObject *v;
    v = POP();
    Py_DECREF(v);
    v = POP();
    Py_DECREF(v);
    context = x->next->store_member(x->next, def);
    if (context)
        save_state_to_context(x, context);
    return context;
}

static HotPyContext *
from_object_dict_fast(HotPyOptimiser *x, int dict_offset, PyDictKeysObject *keys, PyObject *key)
{
    HotPySpecialiser *opt = (HotPySpecialiser *)x;
    DROP();
    PUSH(new_unknown());
    return x->next->from_object_dict_fast(x->next, dict_offset, keys, key);
}

static void
set_in_object_dict_fast(HotPyOptimiser *x, int dict_offset, PyDictKeysObject *keys, PyObject *key)
{
    HotPySpecialiser *opt = (HotPySpecialiser *)x;
    DROP();
    DROP();
    x->next->set_in_object_dict_fast(x->next, dict_offset, keys, key);
}

HotPyOptimiser *HotPySpecialiser_New(HotPyOptimiser * next) {
    HotPySpecialiser *x = PyMem_Malloc(sizeof(HotPySpecialiser));
    int i;
    x->opt_base.opt_name = "type specialiser";
    x->opt_base.next = next;
    x->opt_base.push_constant = push_constant;
    x->opt_base.require_type = require_type;
    x->opt_base.require_lasti = require_lasti;
    x->opt_base.require_value = require_value;
    x->opt_base.require_code = require_code;
    x->opt_base.require_boolean_or_int = require_boolean_or_int;
    x->opt_base.opcode_with_exit = opcode_with_exit;
    x->opt_base.clear = clear;
    x->opt_base.comment = comment;
    x->opt_base.start = start;
    x->opt_base.finish = finish;
    x->opt_base.set_lasti = set_lasti;
    x->opt_base.unrolling = unrolling;
    x->opt_base.fail = fail;
    x->opt_base.binary_op = binary_op;
    x->opt_base.binary_op_kv = binary_op_kv;
    x->opt_base.binary_op_vk = binary_op_vk;
    x->opt_base.load_fast = load_fast;
    x->opt_base.store_fast = store_fast;
    x->opt_base.delete_fast = delete_fast;
    x->opt_base.get_globals = get_globals;
    x->opt_base.load_from_globals = load_from_globals;
    x->opt_base.fast_load_from_globals = fast_load_from_globals;
    x->opt_base.store_to_globals = store_to_globals;
    x->opt_base.has_special = has_special;
    x->opt_base.load_register = load_register;
    x->opt_base.load_clear_register = load_clear_register;
    x->opt_base.store_register = store_register;
    x->opt_base.set_lasti = set_lasti;
    x->opt_base.fast_frame = fast_frame;
    x->opt_base.make_frame = make_frame;
    x->opt_base.make_frame_const = make_frame_const;
    x->opt_base.enter_frame = enter_frame;
    x->opt_base.gen_enter = gen_enter;
    x->opt_base.leave_gen_frame = leave_gen_frame;
    x->opt_base.leave_frame = leave_frame;
    x->opt_base.tuple_concat = tuple_concat;
    x->opt_base.setup_block = setup_block;
    x->opt_base.pick = pick;
    x->opt_base.opcode = opcode;
    x->opt_base.bind_callable = bind_callable;
    x->opt_base.load_member = load_member;
    x->opt_base.store_member = store_member;
    x->opt_base.call_object = call_object;
    x->opt_base.call_cfunction = call_cfunction;
    x->opt_base.call_cmethod = call_cmethod;
    x->opt_base.call_wrapper = call_wrapper;
    x->opt_base.prepare_call1 = prepare_call1;
    x->opt_base.prepare_call2 = prepare_call2;
    x->opt_base.opcode_with_arg = opcode_with_arg;
    x->opt_base.current_context = current_context;
    x->opt_base.dead_locals = dead_locals;
    x->opt_base.set_in_object_dict_fast = set_in_object_dict_fast;
    x->opt_base.from_object_dict_fast = from_object_dict_fast;
    x->top_frame = NULL;
    x->trace = NULL;
    x->frames = 0;
    for (i = 0; i < HOTPY_CONTEXT_DEPTH; i++)
        x->frame_stack[i] = NULL;
    for (i = 0; i < HOTPY_REGISTER_COUNT; i++)
        x->registers[i] = NULL;
    x->err_occurred = 0;
    return (HotPyOptimiser *)x;
}
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.