aboutsummaryrefslogtreecommitdiff
path: root/src/jdk/nashorn/internal/codegen/CodeGenerator.java
blob: 1d09e9c98e093f90bd77836e17488ae0c9c28365 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
/*
 * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

package jdk.nashorn.internal.codegen;

import static jdk.nashorn.internal.codegen.ClassEmitter.Flag.PRIVATE;
import static jdk.nashorn.internal.codegen.ClassEmitter.Flag.STATIC;
import static jdk.nashorn.internal.codegen.CompilerConstants.GET_MAP;
import static jdk.nashorn.internal.codegen.CompilerConstants.GET_STRING;
import static jdk.nashorn.internal.codegen.CompilerConstants.LEAF;
import static jdk.nashorn.internal.codegen.CompilerConstants.QUICK_PREFIX;
import static jdk.nashorn.internal.codegen.CompilerConstants.REGEX_PREFIX;
import static jdk.nashorn.internal.codegen.CompilerConstants.SCOPE;
import static jdk.nashorn.internal.codegen.CompilerConstants.SPLIT_ARRAY_ARG;
import static jdk.nashorn.internal.codegen.CompilerConstants.SPLIT_PREFIX;
import static jdk.nashorn.internal.codegen.CompilerConstants.constructorNoLookup;
import static jdk.nashorn.internal.codegen.CompilerConstants.interfaceCallNoLookup;
import static jdk.nashorn.internal.codegen.CompilerConstants.methodDescriptor;
import static jdk.nashorn.internal.codegen.CompilerConstants.staticCallNoLookup;
import static jdk.nashorn.internal.codegen.CompilerConstants.staticField;
import static jdk.nashorn.internal.codegen.CompilerConstants.typeDescriptor;
import static jdk.nashorn.internal.ir.Symbol.IS_INTERNAL;
import static jdk.nashorn.internal.ir.Symbol.IS_TEMP;
import static jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor.CALLSITE_FAST_SCOPE;
import static jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor.CALLSITE_SCOPE;
import static jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor.CALLSITE_STRICT;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import jdk.nashorn.internal.codegen.ClassEmitter.Flag;
import jdk.nashorn.internal.codegen.CompilerConstants.Call;
import jdk.nashorn.internal.codegen.RuntimeCallSite.SpecializedRuntimeNode;
import jdk.nashorn.internal.codegen.types.ArrayType;
import jdk.nashorn.internal.codegen.types.Type;
import jdk.nashorn.internal.ir.AccessNode;
import jdk.nashorn.internal.ir.BaseNode;
import jdk.nashorn.internal.ir.BinaryNode;
import jdk.nashorn.internal.ir.Block;
import jdk.nashorn.internal.ir.BreakNode;
import jdk.nashorn.internal.ir.CallNode;
import jdk.nashorn.internal.ir.CaseNode;
import jdk.nashorn.internal.ir.CatchNode;
import jdk.nashorn.internal.ir.ContinueNode;
import jdk.nashorn.internal.ir.DoWhileNode;
import jdk.nashorn.internal.ir.EmptyNode;
import jdk.nashorn.internal.ir.ExecuteNode;
import jdk.nashorn.internal.ir.ForNode;
import jdk.nashorn.internal.ir.FunctionNode;
import jdk.nashorn.internal.ir.FunctionNode.CompilationState;
import jdk.nashorn.internal.ir.IdentNode;
import jdk.nashorn.internal.ir.IfNode;
import jdk.nashorn.internal.ir.IndexNode;
import jdk.nashorn.internal.ir.LexicalContext;
import jdk.nashorn.internal.ir.LineNumberNode;
import jdk.nashorn.internal.ir.LiteralNode;
import jdk.nashorn.internal.ir.LiteralNode.ArrayLiteralNode;
import jdk.nashorn.internal.ir.LiteralNode.ArrayLiteralNode.ArrayUnit;
import jdk.nashorn.internal.ir.Node;
import jdk.nashorn.internal.ir.ObjectNode;
import jdk.nashorn.internal.ir.PropertyNode;
import jdk.nashorn.internal.ir.ReturnNode;
import jdk.nashorn.internal.ir.RuntimeNode;
import jdk.nashorn.internal.ir.RuntimeNode.Request;
import jdk.nashorn.internal.ir.SplitNode;
import jdk.nashorn.internal.ir.SwitchNode;
import jdk.nashorn.internal.ir.Symbol;
import jdk.nashorn.internal.ir.TernaryNode;
import jdk.nashorn.internal.ir.ThrowNode;
import jdk.nashorn.internal.ir.TryNode;
import jdk.nashorn.internal.ir.UnaryNode;
import jdk.nashorn.internal.ir.VarNode;
import jdk.nashorn.internal.ir.WhileNode;
import jdk.nashorn.internal.ir.WithNode;
import jdk.nashorn.internal.ir.debug.ASTWriter;
import jdk.nashorn.internal.ir.visitor.NodeOperatorVisitor;
import jdk.nashorn.internal.ir.visitor.NodeVisitor;
import jdk.nashorn.internal.parser.Lexer.RegexToken;
import jdk.nashorn.internal.parser.TokenType;
import jdk.nashorn.internal.runtime.Context;
import jdk.nashorn.internal.runtime.DebugLogger;
import jdk.nashorn.internal.runtime.ECMAException;
import jdk.nashorn.internal.runtime.Property;
import jdk.nashorn.internal.runtime.PropertyMap;
import jdk.nashorn.internal.runtime.RecompilableScriptFunctionData;
import jdk.nashorn.internal.runtime.Scope;
import jdk.nashorn.internal.runtime.ScriptFunction;
import jdk.nashorn.internal.runtime.ScriptObject;
import jdk.nashorn.internal.runtime.ScriptRuntime;
import jdk.nashorn.internal.runtime.Source;
import jdk.nashorn.internal.runtime.Undefined;
import jdk.nashorn.internal.runtime.linker.LinkerCallSite;

/**
 * This is the lowest tier of the code generator. It takes lowered ASTs emitted
 * from Lower and emits Java byte code. The byte code emission logic is broken
 * out into MethodEmitter. MethodEmitter works internally with a type stack, and
 * keeps track of the contents of the byte code stack. This way we avoid a large
 * number of special cases on the form
 * <pre>
 * if (type == INT) {
 *     visitInsn(ILOAD, slot);
 * } else if (type == DOUBLE) {
 *     visitInsn(DOUBLE, slot);
 * }
 * </pre>
 * This quickly became apparent when the code generator was generalized to work
 * with all types, and not just numbers or objects.
 * <p>
 * The CodeGenerator visits nodes only once, tags them as resolved and emits
 * bytecode for them.
 */
final class CodeGenerator extends NodeOperatorVisitor {

    /** Name of the Global object, cannot be referred to as .class, @see CodeGenerator */
    private static final String GLOBAL_OBJECT = Compiler.OBJECTS_PACKAGE + '/' + "Global";

    /** Name of the ScriptFunctionImpl, cannot be referred to as .class @see FunctionObjectCreator */
    private static final String SCRIPTFUNCTION_IMPL_OBJECT = Compiler.OBJECTS_PACKAGE + '/' + "ScriptFunctionImpl";

    /** Constant data & installation. The only reason the compiler keeps this is because it is assigned
     *  by reflection in class installation */
    private final Compiler compiler;

    /** Call site flags given to the code generator to be used for all generated call sites */
    private final int callSiteFlags;

    /** How many regexp fields have been emitted */
    private int regexFieldCount;

    /** Used for temporary signaling between enterCallNode and enterFunctionNode to handle the special case of calling
     * a just-defined anonymous function expression. */
    private boolean functionNodeIsCallee;

    /** Map of shared scope call sites */
    private final Map<SharedScopeCall, SharedScopeCall> scopeCalls = new HashMap<>();

    private final LexicalContext lexicalContext = new LexicalContext();

    /** When should we stop caching regexp expressions in fields to limit bytecode size? */
    private static final int MAX_REGEX_FIELDS = 2 * 1024;

    private static final DebugLogger LOG   = new DebugLogger("codegen", "nashorn.codegen.debug");

    /**
     * Constructor.
     *
     * @param compiler
     */
    CodeGenerator(final Compiler compiler) {
        this.compiler      = compiler;
        this.callSiteFlags = compiler.getEnv()._callsite_flags;
    }

    /**
     * Gets the call site flags, adding the strict flag if the current function
     * being generated is in strict mode
     *
     * @return the correct flags for a call site in the current function
     */
    int getCallSiteFlags() {
        return getCurrentFunctionNode().isStrictMode() ? callSiteFlags | CALLSITE_STRICT : callSiteFlags;
    }

    /**
     * Load an identity node
     *
     * @param identNode an identity node to load
     * @return the method generator used
     */
    private MethodEmitter loadIdent(final IdentNode identNode) {
        final Symbol symbol = identNode.getSymbol();

        if (!symbol.isScope()) {
            assert symbol.hasSlot() || symbol.isParam();
            return method.load(symbol);
        }

        final String name = symbol.getName();

        if (CompilerConstants.__FILE__.name().equals(name)) {
            return method.load(identNode.getSource().getName());
        } else if (CompilerConstants.__DIR__.name().equals(name)) {
            return method.load(identNode.getSource().getBase());
        } else if (CompilerConstants.__LINE__.name().equals(name)) {
            return method.load(identNode.getSource().getLine(identNode.position())).convert(Type.OBJECT);
        } else {
            assert identNode.getSymbol().isScope() : identNode + " is not in scope!";

            final int flags = CALLSITE_SCOPE | getCallSiteFlags();
            method.loadScope();

            if (isFastScope(symbol)) {
                // Only generate shared scope getter for fast-scope symbols so we know we can dial in correct scope.
                if (symbol.getUseCount() > SharedScopeCall.FAST_SCOPE_GET_THRESHOLD) {
                    return loadSharedScopeVar(identNode.getType(), symbol, flags);
                }
                return loadFastScopeVar(identNode.getType(), symbol, flags, identNode.isFunction());
            }
            return method.dynamicGet(identNode.getType(), identNode.getName(), flags, identNode.isFunction());
        }
    }

    /**
     * Check if this symbol can be accessed directly with a putfield or getfield or dynamic load
     *
     * @param function function to check for fast scope
     * @return true if fast scope
     */
    private boolean isFastScope(final Symbol symbol) {
        if (!symbol.isScope() || !symbol.getBlock().needsScope()) {
            return false;
        }
        // Allow fast scope access if no function contains with or eval
        for(final Iterator<FunctionNode> it = lexicalContext.getFunctions(getCurrentFunctionNode()); it.hasNext();) {
            final FunctionNode func = it.next();
            if (func.hasWith() || func.hasEval()) {
                return false;
            }
        }
        return true;
    }

    private MethodEmitter loadSharedScopeVar(final Type valueType, final Symbol symbol, final int flags) {
        method.load(isFastScope(symbol) ? getScopeProtoDepth(getCurrentBlock(), symbol) : -1);
        final SharedScopeCall scopeCall = getScopeGet(valueType, symbol, flags | CALLSITE_FAST_SCOPE);
        scopeCall.generateInvoke(method);
        return method;
    }

    private MethodEmitter loadFastScopeVar(final Type valueType, final Symbol symbol, final int flags, final boolean isMethod) {
        loadFastScopeProto(symbol, false);
        method.dynamicGet(valueType, symbol.getName(), flags | CALLSITE_FAST_SCOPE, isMethod);
        return method;
    }

    private MethodEmitter storeFastScopeVar(final Type valueType, final Symbol symbol, final int flags) {
        loadFastScopeProto(symbol, true);
        method.dynamicSet(valueType, symbol.getName(), flags | CALLSITE_FAST_SCOPE);
        return method;
    }

    private int getScopeProtoDepth(final Block startingBlock, final Symbol symbol) {
        int depth = 0;
        final Block definingBlock = symbol.getBlock();
        for(final Iterator<Block> blocks = lexicalContext.getBlocks(startingBlock); blocks.hasNext();) {
            final Block currentBlock = blocks.next();
            if (currentBlock == definingBlock) {
                return depth;
            }
            if (currentBlock.needsScope()) {
                ++depth;
            }
        }
        return -1;
    }

    private void loadFastScopeProto(final Symbol symbol, final boolean swap) {
        final int depth = getScopeProtoDepth(getCurrentBlock(), symbol);
        assert depth != -1;
        if(depth > 0) {
            if (swap) {
                method.swap();
            }
            for (int i = 0; i < depth; i++) {
                method.invoke(ScriptObject.GET_PROTO);
            }
            if (swap) {
                method.swap();
            }
        }
    }

    /**
     * Generate code that loads this node to the stack. This method is only
     * public to be accessible from the maps sub package. Do not call externally
     *
     * @param node node to load
     *
     * @return the method emitter used
     */
    MethodEmitter load(final Node node) {
        return load(node, false);
    }

    private MethodEmitter load(final Node node, final boolean baseAlreadyOnStack) {
        final Symbol symbol = node.getSymbol();

        // If we lack symbols, we just generate what we see.
        if (symbol == null) {
            node.accept(this);
            return method;
        }

        /*
         * The load may be of type IdentNode, e.g. "x", AccessNode, e.g. "x.y"
         * or IndexNode e.g. "x[y]". Both AccessNodes and IndexNodes are
         * BaseNodes and the logic for loading the base object is reused
         */
        final CodeGenerator codegen = this;

        node.accept(new NodeVisitor(getCurrentCompileUnit(), method) {
            @Override
            public Node enterIdentNode(final IdentNode identNode) {
                loadIdent(identNode);
                return null;
            }

            @Override
            public Node enterAccessNode(final AccessNode accessNode) {
                if (!baseAlreadyOnStack) {
                    load(accessNode.getBase()).convert(Type.OBJECT);
                }
                assert method.peekType().isObject();
                method.dynamicGet(node.getType(), accessNode.getProperty().getName(), getCallSiteFlags(), accessNode.isFunction());
                return null;
            }

            @Override
            public Node enterIndexNode(final IndexNode indexNode) {
                if (!baseAlreadyOnStack) {
                    load(indexNode.getBase()).convert(Type.OBJECT);
                    load(indexNode.getIndex());
                }
                method.dynamicGetIndex(node.getType(), getCallSiteFlags(), indexNode.isFunction());
                return null;
            }

            @Override
            public Node enterFunctionNode(FunctionNode functionNode) {
                // function nodes will always leave a constructed function object on stack, no need to load the symbol
                // separately as in enterDefault()
                functionNode.accept(codegen);
                return null;
            }

            @Override
            public Node enterDefault(final Node otherNode) {
                otherNode.accept(codegen); // generate code for whatever we are looking at.
                method.load(symbol); // load the final symbol to the stack (or nop if no slot, then result is already there)
                return null;
            }
        });

        return method;
    }

    @Override
    public Node enterAccessNode(final AccessNode accessNode) {
        if (accessNode.testResolved()) {
            return null;
        }

        load(accessNode);

        return null;
    }

    /**
     * Initialize a specific set of vars to undefined. This has to be done at
     * the start of each method for local variables that aren't passed as
     * parameters.
     *
     * @param symbols list of symbols.
     */
    private void initSymbols(final Iterable<Symbol> symbols) {
        final LinkedList<Symbol> numbers = new LinkedList<>();
        final LinkedList<Symbol> objects = new LinkedList<>();

        for (final Symbol symbol : symbols) {
            /*
             * The following symbols are guaranteed to be defined and thus safe
             * from having undefined written to them: parameters internals this
             *
             * Otherwise we must, unless we perform control/escape analysis,
             * assign them undefined.
             */
            final boolean isInternal = symbol.isParam() || symbol.isInternal() || symbol.isThis() || !symbol.canBeUndefined();

            if (symbol.hasSlot() && !isInternal) {
                assert symbol.getSymbolType().isNumber() || symbol.getSymbolType().isObject() : "no potentially undefined narrower local vars than doubles are allowed: " + symbol + " in " + getCurrentFunctionNode();
                if (symbol.getSymbolType().isNumber()) {
                    numbers.add(symbol);
                } else if (symbol.getSymbolType().isObject()) {
                    objects.add(symbol);
                }
            }
        }

        initSymbols(numbers, Type.NUMBER);
        initSymbols(objects, Type.OBJECT);
    }

    private void initSymbols(final LinkedList<Symbol> symbols, final Type type) {
        if (symbols.isEmpty()) {
            return;
        }

        method.loadUndefined(type);
        while (!symbols.isEmpty()) {
            final Symbol symbol = symbols.removeFirst();
            if (!symbols.isEmpty()) {
                method.dup();
            }
            method.store(symbol);
        }
    }

    /**
     * Create symbol debug information.
     *
     * @param block block containing symbols.
     */
    private void symbolInfo(final Block block) {
        for (final Symbol symbol : block.getFrame().getSymbols()) {
            method.localVariable(symbol, block.getEntryLabel(), block.getBreakLabel());
        }
    }

    @Override
    public Node enterBlock(final Block block) {
        if (block.testResolved()) {
            return null;
        }
        lexicalContext.push(block);

        method.label(block.getEntryLabel());
        initLocals(block);

        return block;
    }

    @Override
    public Node leaveBlock(final Block block) {
        method.label(block.getBreakLabel());
        symbolInfo(block);

        if (block.needsScope()) {
            popBlockScope(block);
        }
        lexicalContext.pop(block);
        return block;
    }

    private void popBlockScope(final Block block) {
        final Label exitLabel     = new Label("block_exit");
        final Label recoveryLabel = new Label("block_catch");
        final Label skipLabel     = new Label("skip_catch");

        /* pop scope a la try-finally */
        method.loadScope();
        method.invoke(ScriptObject.GET_PROTO);
        method.storeScope();
        method._goto(skipLabel);
        method.label(exitLabel);

        method._catch(recoveryLabel);
        method.loadScope();
        method.invoke(ScriptObject.GET_PROTO);
        method.storeScope();
        method.athrow();
        method.label(skipLabel);
        method._try(block.getEntryLabel(), exitLabel, recoveryLabel, Throwable.class);
    }

    @Override
    public Node enterBreakNode(final BreakNode breakNode) {
        if (breakNode.testResolved()) {
            return null;
        }

        for (int i = 0; i < breakNode.getScopeNestingLevel(); i++) {
            closeWith();
        }

        method.splitAwareGoto(breakNode.getTargetLabel());

        return null;
    }

    private int loadArgs(final List<Node> args) {
        return loadArgs(args, null, false, args.size());
    }

    private int loadArgs(final List<Node> args, final String signature, final boolean isVarArg, final int argCount) {
        // arg have already been converted to objects here.
        if (isVarArg || argCount > LinkerCallSite.ARGLIMIT) {
            loadArgsArray(args);
            return 1;
        }

        // pad with undefined if size is too short. argCount is the real number of args
        int n = 0;
        final Type[] params = signature == null ? null : Type.getMethodArguments(signature);
        for (final Node arg : args) {
            assert arg != null;
            load(arg);
            if (n >= argCount) {
                method.pop(); // we had to load the arg for its side effects
            } else if (params != null) {
                method.convert(params[n]);
            }
            n++;
        }

        while (n < argCount) {
            method.loadUndefined(Type.OBJECT);
            n++;
        }

        return argCount;
    }

    @Override
    public Node enterCallNode(final CallNode callNode) {
        if (callNode.testResolved()) {
            return null;
        }

        final List<Node>   args            = callNode.getArgs();
        final Node         function        = callNode.getFunction();
        final Block        currentBlock    = getCurrentBlock();

        function.accept(new NodeVisitor(getCurrentCompileUnit(), method) {

            private void sharedScopeCall(final IdentNode identNode, final int flags) {
                final Symbol symbol = identNode.getSymbol();
                int    scopeCallFlags = flags;
                method.loadScope();
                if (isFastScope(symbol)) {
                    method.load(getScopeProtoDepth(currentBlock, symbol));
                    scopeCallFlags |= CALLSITE_FAST_SCOPE;
                } else {
                    method.load(-1); // Bypass fast-scope code in shared callsite
                }
                loadArgs(args);
                final Type[] paramTypes = method.getTypesFromStack(args.size());
                final SharedScopeCall scopeCall = getScopeCall(symbol, identNode.getType(), callNode.getType(), paramTypes, scopeCallFlags);
                scopeCall.generateInvoke(method);
            }

            private void scopeCall(final IdentNode node, final int flags) {
                load(node);
                method.convert(Type.OBJECT); // foo() makes no sense if foo == 3
                // ScriptFunction will see CALLSITE_SCOPE and will bind scope accordingly.
                method.loadNull(); //the 'this'
                method.dynamicCall(callNode.getType(), 2 + loadArgs(args), flags);
            }

            private void evalCall(final IdentNode node, final int flags) {
                load(node);
                method.convert(Type.OBJECT); // foo() makes no sense if foo == 3

                final Label not_eval  = new Label("not_eval");
                final Label eval_done = new Label("eval_done");

                // check if this is the real built-in eval
                method.dup();
                globalIsEval();

                method.ifeq(not_eval);
                // We don't need ScriptFunction object for 'eval'
                method.pop();

                method.loadScope(); // Load up self (scope).

                final CallNode.EvalArgs evalArgs = callNode.getEvalArgs();
                // load evaluated code
                load(evalArgs.getCode());
                method.convert(Type.OBJECT);
                // special/extra 'eval' arguments
                load(evalArgs.getThis());
                method.load(evalArgs.getLocation());
                method.load(evalArgs.getStrictMode());
                method.convert(Type.OBJECT);

                // direct call to Global.directEval
                globalDirectEval();
                method.convert(callNode.getType());
                method._goto(eval_done);

                method.label(not_eval);
                // This is some scope 'eval' or global eval replaced by user
                // but not the built-in ECMAScript 'eval' function call
                method.loadNull();
                method.dynamicCall(callNode.getType(), 2 + loadArgs(args), flags);

                method.label(eval_done);
            }

            @Override
            public Node enterIdentNode(final IdentNode node) {
                final Symbol symbol = node.getSymbol();

                if (symbol.isScope()) {
                    final int flags = getCallSiteFlags() | CALLSITE_SCOPE;
                    final int useCount = symbol.getUseCount();

                    // Threshold for generating shared scope callsite is lower for fast scope symbols because we know
                    // we can dial in the correct scope. However, we als need to enable it for non-fast scopes to
                    // support huge scripts like mandreel.js.
                    if (callNode.isEval()) {
                        evalCall(node, flags);
                    } else if (useCount <= SharedScopeCall.FAST_SCOPE_CALL_THRESHOLD
                            || (!isFastScope(symbol) && useCount <= SharedScopeCall.SLOW_SCOPE_CALL_THRESHOLD)
                            || callNode.inWithBlock()) {
                        scopeCall(node, flags);
                    } else {
                        sharedScopeCall(node, flags);
                    }
                    assert method.peekType().equals(callNode.getType());
                } else {
                    enterDefault(node);
                }

                return null;
            }

            @Override
            public Node enterAccessNode(final AccessNode node) {
                load(node.getBase());
                method.convert(Type.OBJECT);
                method.dup();
                method.dynamicGet(node.getType(), node.getProperty().getName(), getCallSiteFlags(), true);
                method.swap();
                method.dynamicCall(callNode.getType(), 2 + loadArgs(args), getCallSiteFlags());
                assert method.peekType().equals(callNode.getType());

                return null;
            }

            @Override
            public Node enterFunctionNode(final FunctionNode callee) {
                final boolean      isVarArg = callee.isVarArg();
                final int          argCount = isVarArg ? -1 : callee.getParameters().size();

                final String signature = new FunctionSignature(true, callee.needsCallee(), callee.getReturnType(), isVarArg ? null : callee.getParameters()).toString();

                if (callee.needsCallee()) {
                    newFunctionObject(callee);
                }

                if (callee.isStrictMode()) { // self is undefined
                    method.loadUndefined(Type.OBJECT);
                } else { // get global from scope (which is the self)
                    globalInstance();
                }
                loadArgs(args, signature, isVarArg, argCount);
                method.invokestatic(callee.getCompileUnit().getUnitClassName(), callee.getName(), signature);
                assert method.peekType().equals(callee.getReturnType()) : method.peekType() + " != " + callee.getReturnType();
                functionNodeIsCallee = true;
                callee.accept(CodeGenerator.this);
                return null;
            }

            @Override
            public Node enterIndexNode(final IndexNode node) {
                load(node.getBase());
                method.convert(Type.OBJECT);
                method.dup();
                load(node.getIndex());
                final Type indexType = node.getIndex().getType();
                if (indexType.isObject() || indexType.isBoolean()) {
                    method.convert(Type.OBJECT); //TODO
                }
                method.dynamicGetIndex(node.getType(), getCallSiteFlags(), true);
                method.swap();
                method.dynamicCall(callNode.getType(), 2 + loadArgs(args), getCallSiteFlags());
                assert method.peekType().equals(callNode.getType());

                return null;
            }

            @Override
            protected Node enterDefault(final Node node) {
                // Load up function.
                load(function);
                method.convert(Type.OBJECT); //TODO, e.g. booleans can be used as functions
                method.loadNull(); // ScriptFunction will figure out the correct this when it sees CALLSITE_SCOPE
                method.dynamicCall(callNode.getType(), 2 + loadArgs(args), getCallSiteFlags() | CALLSITE_SCOPE);
                assert method.peekType().equals(callNode.getType());

                return null;
            }
        });

        method.store(callNode.getSymbol());

        return null;
    }

    @Override
    public Node enterContinueNode(final ContinueNode continueNode) {
        if (continueNode.testResolved()) {
            return null;
        }

        for (int i = 0; i < continueNode.getScopeNestingLevel(); i++) {
            closeWith();
        }

        method.splitAwareGoto(continueNode.getTargetLabel());

        return null;
    }

    @Override
    public Node enterDoWhileNode(final DoWhileNode doWhileNode) {
        return enterWhileNode(doWhileNode);
    }

    @Override
    public Node enterEmptyNode(final EmptyNode emptyNode) {
        return null;
    }

    @Override
    public Node enterExecuteNode(final ExecuteNode executeNode) {
        if (executeNode.testResolved()) {
            return null;
        }

        final Node expression = executeNode.getExpression();
        expression.accept(this);

        return null;
    }

    @Override
    public Node enterForNode(final ForNode forNode) {
        if (forNode.testResolved()) {
            return null;
        }

        final Node  test   = forNode.getTest();
        final Block body   = forNode.getBody();
        final Node  modify = forNode.getModify();

        final Label breakLabel    = forNode.getBreakLabel();
        final Label continueLabel = forNode.getContinueLabel();
        final Label loopLabel     = new Label("loop");

        Node init = forNode.getInit();

        if (forNode.isForIn()) {
            final Symbol iter = forNode.getIterator();

            // We have to evaluate the optional initializer expression
            // of the iterator variable of the for-in statement.
            if (init instanceof VarNode) {
                init.accept(this);
                init = ((VarNode)init).getName();
            }

            load(modify);
            assert modify.getType().isObject();
            method.invoke(forNode.isForEach() ? ScriptRuntime.TO_VALUE_ITERATOR : ScriptRuntime.TO_PROPERTY_ITERATOR);
            method.store(iter);
            method._goto(continueLabel);
            method.label(loopLabel);

            new Store<Node>(init) {
                @Override
                protected void evaluate() {
                    method.load(iter);
                    method.invoke(interfaceCallNoLookup(Iterator.class, "next", Object.class));
                }
            }.store();

            body.accept(this);

            method.label(continueLabel);
            method.load(iter);
            method.invoke(interfaceCallNoLookup(Iterator.class, "hasNext", boolean.class));
            method.ifne(loopLabel);
            method.label(breakLabel);
        } else {
            if (init != null) {
                init.accept(this);
            }

            final Label testLabel = new Label("test");

            method._goto(testLabel);
            method.label(loopLabel);
            body.accept(this);
            method.label(continueLabel);

            if (!body.isTerminal() && modify != null) {
                load(modify);
            }

            method.label(testLabel);
            if (test != null) {
                new BranchOptimizer(this, method).execute(test, loopLabel, true);
            } else {
                method._goto(loopLabel);
            }

            method.label(breakLabel);
        }

        return null;
    }

    /**
     * Initialize the slots in a frame to undefined.
     *
     * @param block block with local vars.
     */
    private void initLocals(final Block block) {
        final FunctionNode function       = lexicalContext.getFunction(block);
        final boolean      isFunctionNode = block == function;

        /*
         * Get the symbols from the frame and realign the frame so that all
         * slots get correct numbers. The slot numbering is not fixed until
         * after initLocals has been run
         */
        final Frame        frame   = block.getFrame();
        final List<Symbol> symbols = frame.getSymbols();

        /* Fix the predefined slots so they have numbers >= 0, like varargs. */
        frame.realign();

        if (isFunctionNode) {
            if (function.needsParentScope()) {
                initParentScope();
            }
            if (function.needsArguments()) {
                initArguments(function);
            }
        }

        /*
         * Determine if block needs scope, if not, just do initSymbols for this block.
         */
        if (block.needsScope()) {
            /*
             * Determine if function is varargs and consequently variables have to
             * be in the scope.
             */
            final boolean varsInScope = function.allVarsInScope();

            // TODO for LET we can do better: if *block* does not contain any eval/with, we don't need its vars in scope.

            final List<String> nameList = new ArrayList<>();
            final List<Symbol> locals   = new ArrayList<>();


            // Initalize symbols and values
            final List<Symbol> newSymbols = new ArrayList<>();
            final List<Symbol> values     = new ArrayList<>();

            final boolean hasArguments = function.needsArguments();
            for (final Symbol symbol : symbols) {
                if (symbol.isInternal() || symbol.isThis()) {
                    continue;
                }

                if (symbol.isVar()) {
                    if(varsInScope || symbol.isScope()) {
                        nameList.add(symbol.getName());
                        newSymbols.add(symbol);
                        values.add(null);
                        assert symbol.isScope()   : "scope for " + symbol + " should have been set in Lower already " + function.getName();
                        assert !symbol.hasSlot()  : "slot for " + symbol + " should have been removed in Lower already" + function.getName();
                    } else {
                        assert symbol.hasSlot() : symbol + " should have a slot only, no scope";
                        locals.add(symbol);
                    }
                } else if (symbol.isParam() && (varsInScope || hasArguments || symbol.isScope())) {
                    nameList.add(symbol.getName());
                    newSymbols.add(symbol);
                    values.add(hasArguments ? null : symbol);
                    assert symbol.isScope()   : "scope for " + symbol + " should have been set in Lower already " + function.getName() + " varsInScope="+varsInScope+" hasArguments="+hasArguments+" symbol.isScope()=" + symbol.isScope();
                    assert !(hasArguments && symbol.hasSlot())  : "slot for " + symbol + " should have been removed in Lower already " + function.getName();
                }
            }

            /* Correct slot numbering again */
            frame.realign();

            // we may have locals that need to be initialized
            initSymbols(locals);

            /*
             * Create a new object based on the symbols and values, generate
             * bootstrap code for object
             */
            final FieldObjectCreator<Symbol> foc = new FieldObjectCreator<Symbol>(this, nameList, newSymbols, values, true, hasArguments) {
                @Override
                protected Type getValueType(final Symbol value) {
                    return value.getSymbolType();
                }

                @Override
                protected void loadValue(final Symbol value) {
                    method.load(value);
                }

                @Override
                protected void loadScope(MethodEmitter m) {
                    if(function.needsParentScope()) {
                        m.loadScope();
                    } else {
                        m.loadNull();
                    }
                }
            };
            foc.makeObject(method);

            // runScript(): merge scope into global
            if (isFunctionNode && function.isProgram()) {
                method.invoke(ScriptRuntime.MERGE_SCOPE);
            }

            method.storeScope();
        } else {
            // Since we don't have a scope, parameters didn't get assigned array indices by the FieldObjectCreator, so
            // we need to assign them separately here.
            int nextParam = 0;
            if (isFunctionNode && function.isVarArg()) {
                for (final IdentNode param : function.getParameters()) {
                    param.getSymbol().setFieldIndex(nextParam++);
                }
            }
            initSymbols(symbols);
        }

        // Debugging: print symbols? @see --print-symbols flag
        printSymbols(block, (isFunctionNode ? "Function " : "Block in ") + (function.getIdent() == null ? "<anonymous>" : function.getIdent().getName()));
    }

    private void initArguments(final FunctionNode function) {
        method.loadVarArgs();
        if(function.needsCallee()) {
            method.loadCallee();
        } else {
            // If function is strict mode, "arguments.callee" is not populated, so we don't necessarily need the
            // caller.
            assert function.isStrictMode();
            method.loadNull();
        }
        method.load(function.getParameters().size());
        globalAllocateArguments();
        method.storeArguments();
    }

    private void initParentScope() {
        method.loadCallee();
        method.invoke(ScriptFunction.GET_SCOPE);
        method.storeScope();
    }

    @Override
    public Node enterFunctionNode(final FunctionNode functionNode) {
        final boolean isCallee = functionNodeIsCallee;
        functionNodeIsCallee = false;

        if (functionNode.testResolved()) {
            return null;
        }

        if(!(isCallee || functionNode == compiler.getFunctionNode())) {
            newFunctionObject(functionNode);
        }

        if (functionNode.isLazy()) {
            return null;
        }

        LOG.info("=== BEGIN " + functionNode.getName());
        lexicalContext.push(functionNode);

        setCurrentCompileUnit(functionNode.getCompileUnit());
        assert getCurrentCompileUnit() != null;

        setCurrentMethodEmitter(getCurrentCompileUnit().getClassEmitter().method(functionNode));
        functionNode.setMethodEmitter(method);
        // Mark end for variable tables.
        method.begin();
        method.label(functionNode.getEntryLabel());

        initLocals(functionNode);
        functionNode.setState(CompilationState.EMITTED);

        return functionNode;
    }

    @Override
    public Node leaveFunctionNode(final FunctionNode functionNode) {
        // Mark end for variable tables.
        method.label(functionNode.getBreakLabel());

        if (!functionNode.needsScope()) {
            method.markerVariable(LEAF.tag(), functionNode.getEntryLabel(), functionNode.getBreakLabel());
        }

        symbolInfo(functionNode);
        try {
            method.end(); // wrap up this method
        } catch (final Throwable t) {
            Context.printStackTrace(t);
            final VerifyError e = new VerifyError("Code generation bug in \"" + functionNode.getName() + "\": likely stack misaligned: " + t + " " + functionNode.getSource().getName());
            e.initCause(t);
            throw e;
        }

        lexicalContext.pop(functionNode);
        LOG.info("=== END " + functionNode.getName());
        return functionNode;
    }

    @Override
    public Node enterIdentNode(final IdentNode identNode) {
        return null;
    }

    @Override
    public Node enterIfNode(final IfNode ifNode) {
        if (ifNode.testResolved()) {
            return null;
        }

        final Node  test = ifNode.getTest();
        final Block pass = ifNode.getPass();
        final Block fail = ifNode.getFail();

        final Label failLabel  = new Label("if_fail");
        final Label afterLabel = fail == null ? failLabel : new Label("if_done");

        new BranchOptimizer(this, method).execute(test, failLabel, false);

        boolean passTerminal = false;
        boolean failTerminal = false;

        pass.accept(this);
        if (!pass.hasTerminalFlags()) {
            method._goto(afterLabel); //don't fallthru to fail block
        } else {
            passTerminal = pass.isTerminal();
        }

        if (fail != null) {
            method.label(failLabel);
            fail.accept(this);
            failTerminal = fail.isTerminal();
        }

        //if if terminates, put the after label there
        if (!passTerminal || !failTerminal) {
            method.label(afterLabel);
        }

        return null;
    }

    @Override
    public Node enterIndexNode(final IndexNode indexNode) {
        if (indexNode.testResolved()) {
            return null;
        }

        load(indexNode);

        return null;
    }

    @Override
    public Node enterLineNumberNode(final LineNumberNode lineNumberNode) {
        if (lineNumberNode.testResolved()) {
            return null;
        }

        final Label label = new Label("line:" + lineNumberNode.getLineNumber() + " (" + getCurrentFunctionNode().getName() + ")");
        method.label(label);
        method.lineNumber(lineNumberNode.getLineNumber(), label);
        return null;
    }

    /**
     * Load a list of nodes as an array of a specific type
     * The array will contain the visited nodes.
     *
     * @param arrayLiteralNode the array of contents
     * @param arrayType        the type of the array, e.g. ARRAY_NUMBER or ARRAY_OBJECT
     *
     * @return the method generator that was used
     */
    private MethodEmitter loadArray(final ArrayLiteralNode arrayLiteralNode, final ArrayType arrayType) {
        assert arrayType == Type.INT_ARRAY || arrayType == Type.NUMBER_ARRAY || arrayType == Type.OBJECT_ARRAY;

        final Node[]          nodes    = arrayLiteralNode.getValue();
        final Object          presets  = arrayLiteralNode.getPresets();
        final int[]           postsets = arrayLiteralNode.getPostsets();
        final Class<?>        type     = arrayType.getTypeClass();
        final List<ArrayUnit> units    = arrayLiteralNode.getUnits();

        loadConstant(presets);

        final Type elementType = arrayType.getElementType();

        if (units != null) {
            final CompileUnit   savedCompileUnit = getCurrentCompileUnit();
            final MethodEmitter savedMethod      = getCurrentMethodEmitter();

            try {
                for (final ArrayUnit unit : units) {
                    setCurrentCompileUnit(unit.getCompileUnit());

                    final String className = getCurrentCompileUnit().getUnitClassName();
                    final String name      = getCurrentFunctionNode().uniqueName(SPLIT_PREFIX.tag());
                    final String signature = methodDescriptor(type, Object.class, ScriptFunction.class, ScriptObject.class, type);

                    setCurrentMethodEmitter(getCurrentCompileUnit().getClassEmitter().method(EnumSet.of(Flag.PUBLIC, Flag.STATIC), name, signature));
                    method.setFunctionNode(getCurrentFunctionNode());
                    method.begin();

                    fixScopeSlot();

                    method.load(arrayType, SPLIT_ARRAY_ARG.slot());

                    for (int i = unit.getLo(); i < unit.getHi(); i++) {
                        storeElement(nodes, elementType, postsets[i]);
                    }

                    method._return();
                    method.end();

                    savedMethod.loadThis();
                    savedMethod.swap();
                    savedMethod.loadCallee();
                    savedMethod.swap();
                    savedMethod.loadScope();
                    savedMethod.swap();
                    savedMethod.invokestatic(className, name, signature);
                }
            } finally {
                setCurrentCompileUnit(savedCompileUnit);
                setCurrentMethodEmitter(savedMethod);
            }

            return method;
        }

        for (final int postset : postsets) {
            storeElement(nodes, elementType, postset);
        }

        return method;
    }

    private void storeElement(final Node[] nodes, final Type elementType, final int index) {
        method.dup();
        method.load(index);

        final Node element = nodes[index];

        if (element == null) {
            method.loadEmpty(elementType);
        } else {
            assert elementType.isEquivalentTo(element.getType()) : "array element type doesn't match array type";
            load(element);
        }

        method.arraystore();
    }

    private MethodEmitter loadArgsArray(final List<Node> args) {
        final Object[] array = new Object[args.size()];
        loadConstant(array);

        for (int i = 0; i < args.size(); i++) {
            method.dup();
            method.load(i);
            load(args.get(i)).convert(Type.OBJECT); //has to be upcast to object or we fail
            method.arraystore();
        }

        return method;
    }

    /**
     * Load a constant from the constant array. This is only public to be callable from the objects
     * subpackage. Do not call directly.
     *
     * @param string string to load
     */
    void loadConstant(final String string) {
        final String       unitClassName = getCurrentCompileUnit().getUnitClassName();
        final ClassEmitter classEmitter  = getCurrentCompileUnit().getClassEmitter();
        final int          index         = compiler.getConstantData().add(string);

        method.load(index);
        method.invokestatic(unitClassName, GET_STRING.tag(), methodDescriptor(String.class, int.class));
        classEmitter.needGetConstantMethod(String.class);
    }

    /**
     * Load a constant from the constant array. This is only public to be callable from the objects
     * subpackage. Do not call directly.
     *
     * @param object object to load
     */
    void loadConstant(final Object object) {
        final String       unitClassName = getCurrentCompileUnit().getUnitClassName();
        final ClassEmitter classEmitter  = getCurrentCompileUnit().getClassEmitter();
        final int          index         = compiler.getConstantData().add(object);
        final Class<?>     cls           = object.getClass();

        if (cls == PropertyMap.class) {
            method.load(index);
            method.invokestatic(unitClassName, GET_MAP.tag(), methodDescriptor(PropertyMap.class, int.class));
            classEmitter.needGetConstantMethod(PropertyMap.class);
        } else if (cls.isArray()) {
            method.load(index);
            final String methodName = ClassEmitter.getArrayMethodName(cls);
            method.invokestatic(unitClassName, methodName, methodDescriptor(cls, int.class));
            classEmitter.needGetConstantMethod(cls);
        } else {
            method.loadConstants().load(index).arrayload();
            if (cls != Object.class) {
                method.checkcast(cls);
            }
        }
    }

    // literal values
    private MethodEmitter load(final LiteralNode<?> node) {
        final Object value = node.getValue();

        if (value == null) {
            method.loadNull();
        } else if (value instanceof Undefined) {
            method.loadUndefined(Type.OBJECT);
        } else if (value instanceof String) {
            final String string = (String)value;

            if (string.length() > (MethodEmitter.LARGE_STRING_THRESHOLD / 3)) { // 3 == max bytes per encoded char
                loadConstant(string);
            } else {
                method.load(string);
            }
        } else if (value instanceof RegexToken) {
            loadRegex((RegexToken)value);
        } else if (value instanceof Boolean) {
            method.load((Boolean)value);
        } else if (value instanceof Integer) {
            method.load((Integer)value);
        } else if (value instanceof Long) {
            method.load((Long)value);
        } else if (value instanceof Double) {
            method.load((Double)value);
        } else if (node instanceof ArrayLiteralNode) {
            final ArrayType type = (ArrayType)node.getType();
            loadArray((ArrayLiteralNode)node, type);
            globalAllocateArray(type);
        } else {
            assert false : "Unknown literal for " + node.getClass() + " " + value.getClass() + " " + value;
        }

        return method;
    }

    private MethodEmitter loadRegexToken(final RegexToken value) {
        method.load(value.getExpression());
        method.load(value.getOptions());
        return globalNewRegExp();
    }

    private MethodEmitter loadRegex(final RegexToken regexToken) {
        if (regexFieldCount > MAX_REGEX_FIELDS) {
            return loadRegexToken(regexToken);
        }
        // emit field
        final String       regexName    = getCurrentFunctionNode().uniqueName(REGEX_PREFIX.tag());
        final ClassEmitter classEmitter = getCurrentCompileUnit().getClassEmitter();

        classEmitter.field(EnumSet.of(PRIVATE, STATIC), regexName, Object.class);
        regexFieldCount++;

        // get field, if null create new regex, finally clone regex object
        method.getStatic(getCurrentCompileUnit().getUnitClassName(), regexName, typeDescriptor(Object.class));
        method.dup();
        final Label cachedLabel = new Label("cached");
        method.ifnonnull(cachedLabel);

        method.pop();
        loadRegexToken(regexToken);
        method.dup();
        method.putStatic(getCurrentCompileUnit().getUnitClassName(), regexName, typeDescriptor(Object.class));

        method.label(cachedLabel);
        globalRegExpCopy();

        return method;
    }

    @SuppressWarnings("rawtypes")
    @Override
    public Node enterLiteralNode(final LiteralNode literalNode) {
        assert literalNode.getSymbol() != null : literalNode + " has no symbol";
        load(literalNode).store(literalNode.getSymbol());
        return null;
    }

    @Override
    public Node enterObjectNode(final ObjectNode objectNode) {
        if (objectNode.testResolved()) {
            return null;
        }

        final List<Node> elements = objectNode.getElements();
        final int        size     = elements.size();

        final List<String> keys    = new ArrayList<>();
        final List<Symbol> symbols = new ArrayList<>();
        final List<Node>   values  = new ArrayList<>();

        boolean hasGettersSetters = false;

        for (int i = 0; i < size; i++) {
            final PropertyNode propertyNode = (PropertyNode)elements.get(i);
            final Node         value        = propertyNode.getValue();
            final String       key          = propertyNode.getKeyName();
            final Symbol       symbol       = value == null ? null : propertyNode.getSymbol();

            if (value == null) {
                hasGettersSetters = true;
            }

            keys.add(key);
            symbols.add(symbol);
            values.add(value);
        }

        new FieldObjectCreator<Node>(this, keys, symbols, values) {
            @Override
            protected Type getValueType(final Node node) {
                return node.getType();
            }

            @Override
            protected void loadValue(final Node node) {
                load(node);
            }

            /**
             * Ensure that the properties start out as object types so that
             * we can do putfield initializations instead of dynamicSetIndex
             * which would be the case to determine initial property type
             * otherwise.
             *
             * Use case, it's very expensive to do a million var x = {a:obj, b:obj}
             * just to have to invalidate them immediately on initialization
             *
             * see NASHORN-594
             */
            @Override
            protected MapCreator newMapCreator(final Class<?> fieldObjectClass) {
                return new MapCreator(fieldObjectClass, keys, symbols) {
                    @Override
                    protected int getPropertyFlags(final Symbol symbol, final boolean isVarArg) {
                        return super.getPropertyFlags(symbol, isVarArg) | Property.IS_ALWAYS_OBJECT;
                    }
                };
            }

        }.makeObject(method);

        method.dup();
        globalObjectPrototype();
        method.invoke(ScriptObject.SET_PROTO);

        if (!hasGettersSetters) {
            method.store(objectNode.getSymbol());
            return null;
        }

        for (final Node element : elements) {
            final PropertyNode propertyNode = (PropertyNode)element;
            final Object       key          = propertyNode.getKey();
            final FunctionNode getter       = (FunctionNode)propertyNode.getGetter();
            final FunctionNode setter       = (FunctionNode)propertyNode.getSetter();

            if (getter == null && setter == null) {
                continue;
            }

            method.dup().loadKey(key);

            if (getter == null) {
                method.loadNull();
            } else {
                getter.accept(this);
            }

            if (setter == null) {
                method.loadNull();
            } else {
                setter.accept(this);
            }

            method.invoke(ScriptObject.SET_USER_ACCESSORS);
        }

        method.store(objectNode.getSymbol());

        return null;
    }

    @Override
    public Node enterReturnNode(final ReturnNode returnNode) {
        if (returnNode.testResolved()) {
            return null;
        }

        // Set the split return flag in the scope if this is a split method fragment.
        if (method.getSplitNode() != null) {
            assert method.getSplitNode().hasReturn() : "unexpected return in split node";

            method.loadScope();
            method.checkcast(Scope.class);
            method.load(0);
            method.invoke(Scope.SET_SPLIT_STATE);
        }

        final Node expression = returnNode.getExpression();
        if (expression != null) {
            load(expression);
        } else {
            method.loadUndefined(getCurrentFunctionNode().getReturnType());
        }

        method._return(getCurrentFunctionNode().getReturnType());

        return null;
    }

    private static boolean isNullLiteral(final Node node) {
        return node instanceof LiteralNode<?> && ((LiteralNode<?>) node).isNull();
    }

    private boolean nullCheck(final RuntimeNode runtimeNode, final List<Node> args, final String signature) {
        final Request request = runtimeNode.getRequest();

        if (!Request.isEQ(request) && !Request.isNE(request)) {
            return false;
        }

        assert args.size() == 2 : "EQ or NE or TYPEOF need two args";

        Node lhs = args.get(0);
        Node rhs = args.get(1);

        if (isNullLiteral(lhs)) {
            final Node tmp = lhs;
            lhs = rhs;
            rhs = tmp;
        }

        if (isNullLiteral(rhs)) {
            final Label trueLabel  = new Label("trueLabel");
            final Label falseLabel = new Label("falseLabel");
            final Label endLabel   = new Label("end");

            load(lhs);
            method.dup();
            if (Request.isEQ(request)) {
                method.ifnull(trueLabel);
            } else if (Request.isNE(request)) {
                method.ifnonnull(trueLabel);
            } else {
                assert false : "Invalid request " + request;
            }

            method.label(falseLabel);
            load(rhs);
            method.invokestatic(CompilerConstants.className(ScriptRuntime.class), request.toString(), signature);
            method._goto(endLabel);

            method.label(trueLabel);
            // if NE (not strict) this can be "undefined != null" which is supposed to be false
            if (request == Request.NE) {
                method.loadUndefined(Type.OBJECT);
                final Label isUndefined = new Label("isUndefined");
                final Label afterUndefinedCheck = new Label("afterUndefinedCheck");
                method.if_acmpeq(isUndefined);
                // not undefined
                method.load(true);
                method._goto(afterUndefinedCheck);
                method.label(isUndefined);
                method.load(false);
                method.label(afterUndefinedCheck);
            } else {
                method.pop();
                method.load(true);
            }
            method.label(endLabel);
            method.convert(runtimeNode.getType());
            method.store(runtimeNode.getSymbol());

            return true;
        }

        return false;
    }

    private boolean specializationCheck(final RuntimeNode.Request request, final Node node, final List<Node> args) {
        if (!request.canSpecialize()) {
            return false;
        }

        assert args.size() == 2;
        final Node lhs = args.get(0);
        final Node rhs = args.get(1);

        final Type returnType = node.getType();
        load(lhs);
        load(rhs);

        Request finalRequest = request;

        final Request reverse = Request.reverse(request);
        if (method.peekType().isObject() && reverse != null) {
            if (!method.peekType(1).isObject()) {
                method.swap();
                finalRequest = reverse;
            }
        }

        method.dynamicRuntimeCall(
                new SpecializedRuntimeNode(
                    finalRequest,
                    new Type[] {
                        method.peekType(1),
                        method.peekType()
                    },
                    returnType).getInitialName(),
                returnType,
                finalRequest);

        method.convert(node.getType());
        method.store(node.getSymbol());

        return true;
    }

    private static boolean isReducible(final Request request) {
        return Request.isComparison(request) || request == Request.ADD;
    }

    @Override
    public Node enterRuntimeNode(final RuntimeNode runtimeNode) {
        if (runtimeNode.testResolved()) {
            return null;
        }

        /*
         * First check if this should be something other than a runtime node
         * AccessSpecializer might have changed the type
         *
         * TODO - remove this - Access Specializer will always know after Attr/Lower
         */
        if (runtimeNode.isPrimitive() && !runtimeNode.isFinal() && isReducible(runtimeNode.getRequest())) {
            final Node lhs = runtimeNode.getArgs().get(0);
            assert runtimeNode.getArgs().size() > 1 : runtimeNode + " must have two args";
            final Node rhs = runtimeNode.getArgs().get(1);

            final Type   type   = runtimeNode.getType();
            final Symbol symbol = runtimeNode.getSymbol();

            switch (runtimeNode.getRequest()) {
            case EQ:
            case EQ_STRICT:
                return enterCmp(lhs, rhs, Condition.EQ, type, symbol);
            case NE:
            case NE_STRICT:
                return enterCmp(lhs, rhs, Condition.NE, type, symbol);
            case LE:
                return enterCmp(lhs, rhs, Condition.LE, type, symbol);
            case LT:
                return enterCmp(lhs, rhs, Condition.LT, type, symbol);
            case GE:
                return enterCmp(lhs, rhs, Condition.GE, type, symbol);
            case GT:
                return enterCmp(lhs, rhs, Condition.GT, type, symbol);
            case ADD:
                Type widest = Type.widest(lhs.getType(), rhs.getType());
                load(lhs);
                method.convert(widest);
                load(rhs);
                method.convert(widest);
                method.add();
                method.convert(type);
                method.store(symbol);
                return null;
            default:
                // it's ok to send this one on with only primitive arguments, maybe INSTANCEOF(true, true) or similar
                // assert false : runtimeNode + " has all primitive arguments. This is an inconsistent state";
                break;
            }
        }

        // Get the request arguments.
        final List<Node> args = runtimeNode.getArgs();

        if (nullCheck(runtimeNode, args, new FunctionSignature(false, false, runtimeNode.getType(), args).toString())) {
            return null;
        }

        if (!runtimeNode.isFinal() && specializationCheck(runtimeNode.getRequest(), runtimeNode, args)) {
            return null;
        }

        for (final Node arg : runtimeNode.getArgs()) {
            load(arg).convert(Type.OBJECT); //TODO this should not be necessary below Lower
        }

        method.invokestatic(
            CompilerConstants.className(ScriptRuntime.class),
            runtimeNode.getRequest().toString(),
            new FunctionSignature(
                false,
                false,
                runtimeNode.getType(),
                runtimeNode.getArgs().size()).toString());
        method.convert(runtimeNode.getType());
        method.store(runtimeNode.getSymbol());

        return null;
    }

    @Override
    public Node enterSplitNode(final SplitNode splitNode) {
        if (splitNode.testResolved()) {
            return null;
        }

        final CompileUnit splitCompileUnit = splitNode.getCompileUnit();

        final FunctionNode fn   = getCurrentFunctionNode();
        final String className  = splitCompileUnit.getUnitClassName();
        final String name       = splitNode.getName();

        final Class<?>   rtype  = fn.getReturnType().getTypeClass();
        final boolean needsArguments = fn.needsArguments();
        final Class<?>[] ptypes = needsArguments ?
                new Class<?>[] {ScriptFunction.class, Object.class, ScriptObject.class, Object.class} :
                new Class<?>[] {ScriptFunction.class, Object.class, ScriptObject.class};

        setCurrentCompileUnit(splitCompileUnit);
        splitNode.setCompileUnit(splitCompileUnit);

        final Call splitCall = staticCallNoLookup(
            className,
            name,
            methodDescriptor(rtype, ptypes));

        setCurrentMethodEmitter(
            splitCompileUnit.getClassEmitter().method(
                EnumSet.of(Flag.PUBLIC, Flag.STATIC),
                name,
                rtype,
                ptypes));

        method.setFunctionNode(fn);
        method.setSplitNode(splitNode);
        splitNode.setMethodEmitter(method);

        final MethodEmitter caller = splitNode.getCaller();
        if(fn.needsCallee()) {
            caller.loadCallee();
        } else {
            caller.loadNull();
        }
        caller.loadThis();
        caller.loadScope();
        if (needsArguments) {
            caller.loadArguments();
        }
        caller.invoke(splitCall);
        caller.storeResult();

        method.begin();

        method.loadUndefined(fn.getReturnType());
        method.storeResult();

        fixScopeSlot();

        return splitNode;
    }

    private void fixScopeSlot() {
        if (getCurrentFunctionNode().getScopeNode().getSymbol().getSlot() != SCOPE.slot()) {
            // TODO hack to move the scope to the expected slot (that's needed because split methods reuse the same slots as the root method)
            method.load(Type.typeFor(ScriptObject.class), SCOPE.slot());
            method.storeScope();
        }
    }

    @Override
    public Node leaveSplitNode(final SplitNode splitNode) {
        try {
            // Wrap up this method.
            method.loadResult();
            method._return(getCurrentFunctionNode().getReturnType());
            method.end();
        } catch (final Throwable t) {
            Context.printStackTrace(t);
            final VerifyError e = new VerifyError("Code generation bug in \"" + splitNode.getName() + "\": likely stack misaligned: " + t + " " + getCurrentFunctionNode().getSource().getName());
            e.initCause(t);
            throw e;
        }

        // Handle return from split method if there was one.
        final MethodEmitter caller      = splitNode.getCaller();
        final List<Label>   targets     = splitNode.getExternalTargets();
        final int           targetCount = targets.size();

        if (splitNode.hasReturn() || targetCount > 0) {

            caller.loadScope();
            caller.checkcast(Scope.class);
            caller.invoke(Scope.GET_SPLIT_STATE);

            // Split state is -1 for no split state, 0 for return, 1..n+1 for break/continue
            final Label   breakLabel = new Label("no_split_state");
            final int     low        = splitNode.hasReturn() ? 0 : 1;
            final int     labelCount = targetCount + 1 - low;
            final Label[] labels     = new Label[labelCount];

            for (int i = 0; i < labelCount; i++) {
                labels[i] = new Label("split_state_" + i);
            }

            caller.tableswitch(low, targetCount, breakLabel, labels);
            for (int i = low; i <= targetCount; i++) {
                caller.label(labels[i - low]);
                if (i == 0) {
                    caller.loadResult();
                    caller._return(getCurrentFunctionNode().getReturnType());
                } else {
                    // Clear split state.
                    caller.loadScope();
                    caller.checkcast(Scope.class);
                    caller.load(-1);
                    caller.invoke(Scope.SET_SPLIT_STATE);
                    caller.splitAwareGoto(targets.get(i - 1));
                }
            }

            caller.label(breakLabel);
        }

        return splitNode;
    }

    @Override
    public Node enterSwitchNode(final SwitchNode switchNode) {
        if (switchNode.testResolved()) {
            return null;
        }

        final Node           expression  = switchNode.getExpression();
        final Symbol         tag         = switchNode.getTag();
        final boolean        allInteger  = tag.getSymbolType().isInteger();
        final List<CaseNode> cases       = switchNode.getCases();
        final CaseNode       defaultCase = switchNode.getDefaultCase();
        final Label          breakLabel  = switchNode.getBreakLabel();

        Label defaultLabel = breakLabel;
        boolean hasDefault = false;

        if (defaultCase != null) {
            defaultLabel = defaultCase.getEntry();
            hasDefault = true;
        }

        if (cases.isEmpty()) {
            method.label(breakLabel);
            return null;
        }

        if (allInteger) {
            // Tree for sorting values.
            final TreeMap<Integer, Label> tree = new TreeMap<>();

            // Build up sorted tree.
            for (final CaseNode caseNode : cases) {
                final Node test = caseNode.getTest();

                if (test != null) {
                    final Integer value = (Integer)((LiteralNode<?>)test).getValue();
                    final Label   entry = caseNode.getEntry();

                    // Take first duplicate.
                    if (!(tree.containsKey(value))) {
                        tree.put(value, entry);
                    }
                }
            }

            // Copy values and labels to arrays.
            final int       size   = tree.size();
            final Integer[] values = tree.keySet().toArray(new Integer[size]);
            final Label[]   labels = tree.values().toArray(new Label[size]);

            // Discern low, high and range.
            final int lo    = values[0];
            final int hi    = values[size - 1];
            final int range = hi - lo + 1;

            // Find an unused value for default.
            int deflt = Integer.MIN_VALUE;
            for (final int value : values) {
                if (deflt == value) {
                    deflt++;
                } else if (deflt < value) {
                    break;
                }
            }

            // Load switch expression.
            load(expression);
            final Type type = expression.getType();

            // If expression not int see if we can convert, if not use deflt to trigger default.
            if (!type.isInteger()) {
                method.load(deflt);
                method.invoke(staticCallNoLookup(ScriptRuntime.class, "switchTagAsInt", int.class, type.getTypeClass(), int.class));
            }

            // If reasonable size and not too sparse (80%), use table otherwise use lookup.
            if (range > 0 && range < 4096 && range < (size * 5 / 4)) {
                final Label[] table = new Label[range];
                Arrays.fill(table, defaultLabel);

                for (int i = 0; i < size; i++) {
                    final int value = values[i];
                    table[value - lo] = labels[i];
                }

                method.tableswitch(lo, hi, defaultLabel, table);
            } else {
                final int[] ints = new int[size];

                for (int i = 0; i < size; i++) {
                    ints[i] = values[i];
                }

                method.lookupswitch(defaultLabel, ints, labels);
            }
        } else {
            load(expression);

            if (expression.getType().isInteger()) {
                method.convert(Type.NUMBER).dup();
                method.store(tag);
                method.conditionalJump(Condition.NE, true, defaultLabel);
            } else {
                method.store(tag);
            }

            for (final CaseNode caseNode : cases) {
                final Node test = caseNode.getTest();

                if (test != null) {
                    method.load(tag);
                    load(test);
                    method.invoke(ScriptRuntime.EQ_STRICT);
                    method.ifne(caseNode.getEntry());
                }
            }

            method._goto(hasDefault ? defaultLabel : breakLabel);
        }

        for (final CaseNode caseNode : cases) {
            method.label(caseNode.getEntry());
            caseNode.getBody().accept(this);
        }

        if (!switchNode.isTerminal()) {
            method.label(breakLabel);
        }

        return null;
    }

    @Override
    public Node enterThrowNode(final ThrowNode throwNode) {
        if (throwNode.testResolved()) {
            return null;
        }

        method._new(ECMAException.class).dup();

        final Node   expression = throwNode.getExpression();
        final Source source     = throwNode.getSource();
        final int    position   = throwNode.position();
        final int    line       = source.getLine(position);
        final int    column     = source.getColumn(position);

        load(expression);
        assert expression.getType().isObject();

        method.load(source.getName());
        method.load(line);
        method.load(column);
        method.invoke(ECMAException.THROW_INIT);

        method.athrow();

        return null;
    }

    @Override
    public Node enterTryNode(final TryNode tryNode) {
        if (tryNode.testResolved()) {
            return null;
        }

        final Block       body        = tryNode.getBody();
        final List<Block> catchBlocks = tryNode.getCatchBlocks();
        final Symbol      symbol      = tryNode.getException();
        final Label       entry       = new Label("try");
        final Label       recovery    = new Label("catch");
        final Label       exit        = tryNode.getExit();
        final Label       skip        = new Label("skip");

        method.label(entry);

        body.accept(this);

        if (!body.hasTerminalFlags()) {
            method._goto(skip);
        }

        method.label(exit);

        method._catch(recovery);
        method.store(symbol);

        for (int i = 0; i < catchBlocks.size(); i++) {
            final Block saveBlock = getCurrentBlock();
            final Block catchBlock = catchBlocks.get(i);

            setCurrentBlock(catchBlock);

            try {
                enterBlock(catchBlock);

                final CatchNode catchNode          = (CatchNode)catchBlocks.get(i).getStatements().get(0);
                final IdentNode exception          = catchNode.getException();
                final Node      exceptionCondition = catchNode.getExceptionCondition();
                final Block     catchBody          = catchNode.getBody();

                if (catchNode.isSyntheticRethrow()) {
                    // Generate catch body (inlined finally) and rethrow exception
                    catchBody.accept(this);
                    method.load(symbol).athrow();
                    lexicalContext.pop(catchBlock);
                    continue;
                }

                new Store<IdentNode>(exception) {
                    @Override
                    protected void evaluate() {
                        /*
                         * If caught object is an instance of ECMAException, then
                         * bind obj.thrown to the script catch var. Or else bind the
                         * caught object itself to the script catch var.
                         */
                        final Label notEcmaException = new Label("no_ecma_exception");

                        method.load(symbol).dup()._instanceof(ECMAException.class).ifeq(notEcmaException);
                        method.checkcast(ECMAException.class); //TODO is this necessary?
                        method.getField(ECMAException.THROWN);
                        method.label(notEcmaException);
                    }
                }.store();

                final Label next;

                if (exceptionCondition != null) {
                    next = new Label("next");
                    load(exceptionCondition).convert(Type.BOOLEAN).ifeq(next);
                } else {
                    next = null;
                }

                catchBody.accept(this);

                if (i + 1 != catchBlocks.size() && !catchBody.hasTerminalFlags()) {
                    method._goto(skip);
                }

                if (next != null) {
                    if (i + 1 == catchBlocks.size()) {
                        // no next catch block - rethrow if condition failed
                        method._goto(skip);
                        method.label(next);
                        method.load(symbol).athrow();
                    } else {
                        method.label(next);
                    }
                }

                leaveBlock(catchBlock);
            } finally {
                setCurrentBlock(saveBlock);
            }
        }

        method.label(skip);
        method._try(entry, exit, recovery, Throwable.class);

        // Finally body is always inlined elsewhere so it doesn't need to be emitted

        return null;
    }

    @Override
    public Node enterVarNode(final VarNode varNode) {
        final Node init = varNode.getInit();

        if (varNode.testResolved() || init == null) {
            return null;
        }

        final Symbol varSymbol = varNode.getSymbol();
        assert varSymbol != null : "variable node " + varNode + " requires a symbol";

        assert method != null;

        final boolean needsScope = varSymbol.isScope();
        if (needsScope) {
            method.loadScope();
        }
        load(init);

        if (needsScope) {
            int flags = CALLSITE_SCOPE | getCallSiteFlags();
            final IdentNode identNode = varNode.getName();
            final Type type = identNode.getType();
            if (isFastScope(varSymbol)) {
                storeFastScopeVar(type, varSymbol, flags);
            } else {
                method.dynamicSet(type, identNode.getName(), flags);
            }
        } else {
            assert varNode.getType() == varNode.getName().getType() : "varNode type=" + varNode.getType() + " nametype=" + varNode.getName().getType() + " inittype=" + init.getType();

            method.convert(varNode.getType()); // aw: convert moved here
            method.store(varSymbol);
        }

        return null;
    }

    @Override
    public Node enterWhileNode(final WhileNode whileNode) {
        if (whileNode.testResolved()) {
            return null;
        }

        final Node  test          = whileNode.getTest();
        final Block body          = whileNode.getBody();
        final Label breakLabel    = whileNode.getBreakLabel();
        final Label continueLabel = whileNode.getContinueLabel();
        final Label loopLabel     = new Label("loop");

        if (!(whileNode instanceof DoWhileNode)) {
            method._goto(continueLabel);
        }

        method.label(loopLabel);
        body.accept(this);
        if (!whileNode.isTerminal()) {
            method.label(continueLabel);
            new BranchOptimizer(this, method).execute(test, loopLabel, true);
            method.label(breakLabel);
        }

        return null;
    }

    private void closeWith() {
        method.loadScope();
        method.invoke(ScriptRuntime.CLOSE_WITH);
        method.storeScope();
    }

    @Override
    public Node enterWithNode(final WithNode withNode) {
        if (withNode.testResolved()) {
            return null;
        }

        final Node expression = withNode.getExpression();
        final Node body       = withNode.getBody();

        final Label tryLabel   = new Label("with_try");
        final Label endLabel   = new Label("with_end");
        final Label catchLabel = new Label("with_catch");
        final Label exitLabel  = new Label("with_exit");

        method.label(tryLabel);

        method.loadScope();
        load(expression);

        assert expression.getType().isObject() : "with expression needs to be object: " + expression;

        method.invoke(ScriptRuntime.OPEN_WITH);
        method.storeScope();

        body.accept(this);

        if (!body.isTerminal()) {
            closeWith();
            method._goto(exitLabel);
        }

        method.label(endLabel);

        method._catch(catchLabel);
        closeWith();
        method.athrow();

        method.label(exitLabel);

        method._try(tryLabel, endLabel, catchLabel);

        return null;
    }

    @Override
    public Node enterADD(final UnaryNode unaryNode) {
        if (unaryNode.testResolved()) {
            return null;
        }

        load(unaryNode.rhs());
        assert unaryNode.rhs().getType().isNumber();
        method.store(unaryNode.getSymbol());

        return null;
    }

    @Override
    public Node enterBIT_NOT(final UnaryNode unaryNode) {
        if (unaryNode.testResolved()) {
            return null;
        }

        load(unaryNode.rhs()).convert(Type.INT).load(-1).xor().store(unaryNode.getSymbol());

        return null;
    }

    // do this better with convert calls to method. TODO
    @Override
    public Node enterCONVERT(final UnaryNode unaryNode) {
        if (unaryNode.testResolved()) {
            return null;
        }

        final Node rhs = unaryNode.rhs();
        final Type to  = unaryNode.getType();

        if (to.isObject() && rhs instanceof LiteralNode) {
            final LiteralNode<?> literalNode = (LiteralNode<?>)rhs;
            final Object value = literalNode.getValue();

            if (value instanceof Number) {
                assert !to.isArray() : "type hygiene - cannot convert number to array: (" + to.getTypeClass().getSimpleName() + ')' + value;
                if (value instanceof Integer) {
                    method.load((Integer)value);
                } else if (value instanceof Long) {
                    method.load((Long)value);
                } else if (value instanceof Double) {
                    method.load((Double)value);
                } else {
                    assert false;
                }
                method.convert(Type.OBJECT);
            } else if (value instanceof Boolean) {
                method.getField(staticField(Boolean.class, value.toString().toUpperCase(), Boolean.class));
            } else {
                load(rhs);
                method.convert(unaryNode.getType());
            }
        } else {
            load(rhs);
            method.convert(unaryNode.getType());
        }

        method.store(unaryNode.getSymbol());

        return null;
    }

    @Override
    public Node enterDECINC(final UnaryNode unaryNode) {
        if (unaryNode.testResolved()) {
            return null;
        }

        final Node      rhs         = unaryNode.rhs();
        final Type      type        = unaryNode.getType();
        final TokenType tokenType   = unaryNode.tokenType();
        final boolean   isPostfix   = tokenType == TokenType.DECPOSTFIX || tokenType == TokenType.INCPOSTFIX;
        final boolean   isIncrement = tokenType == TokenType.INCPREFIX || tokenType == TokenType.INCPOSTFIX;

        assert !type.isObject();

        new SelfModifyingStore<UnaryNode>(unaryNode, rhs) {

            @Override
            protected void evaluate() {
                load(rhs, true);

                method.convert(type);
                if (!isPostfix) {
                    if (type.isInteger()) {
                        method.load(isIncrement ? 1 : -1);
                    } else if (type.isLong()) {
                        method.load(isIncrement ? 1L : -1L);
                    } else {
                        method.load(isIncrement ? 1.0 : -1.0);
                    }
                    method.add();
                }
            }

            @Override
            protected void storeNonDiscard() {
                super.storeNonDiscard();
                if (isPostfix) {
                    if (type.isInteger()) {
                        method.load(isIncrement ? 1 : -1);
                    } else if (type.isLong()) {
                        method.load(isIncrement ? 1L : 1L);
                    } else {
                        method.load(isIncrement ? 1.0 : -1.0);
                    }
                    method.add();
                }
            }
        }.store();

        return null;
    }

    @Override
    public Node enterDISCARD(final UnaryNode unaryNode) {
        if (unaryNode.testResolved()) {
            return null;
        }

        final Node rhs = unaryNode.rhs();

        load(rhs);

        if (rhs.shouldDiscard()) {
            method.pop();
        }

        return null;
    }

    @Override
    public Node enterNEW(final UnaryNode unaryNode) {
        if (unaryNode.testResolved()) {
            return null;
        }

        final CallNode callNode = (CallNode)unaryNode.rhs();
        final List<Node> args   = callNode.getArgs();

        // Load function reference.
        load(callNode.getFunction()).convert(Type.OBJECT); // must detect type error

        method.dynamicNew(1 + loadArgs(args), getCallSiteFlags());
        method.store(unaryNode.getSymbol());

        return null;
    }

    @Override
    public Node enterNOT(final UnaryNode unaryNode) {
        if (unaryNode.testResolved()) {
            return null;
        }

        final Node rhs = unaryNode.rhs();

        load(rhs);

        final Label trueLabel  = new Label("true");
        final Label afterLabel = new Label("after");

        method.convert(Type.BOOLEAN);
        method.ifne(trueLabel);
        method.load(true);
        method._goto(afterLabel);
        method.label(trueLabel);
        method.load(false);
        method.label(afterLabel);
        method.store(unaryNode.getSymbol());

        return null;
    }

    @Override
    public Node enterSUB(final UnaryNode unaryNode) {
        if (unaryNode.testResolved()) {
            return null;
        }

        load(unaryNode.rhs()).neg().store(unaryNode.getSymbol());

        return null;
    }

    private Node enterNumericAdd(final Node lhs, final Node rhs, final Type type, final Symbol symbol) {
        assert lhs.getType().equals(rhs.getType()) && lhs.getType().equals(type) : lhs.getType() + " != " + rhs.getType() + " != " + type + " " + new ASTWriter(lhs) + " " + new ASTWriter(rhs);
        load(lhs);
        load(rhs);
        method.add();
        method.store(symbol);
        return null;
    }

    @Override
    public Node enterADD(final BinaryNode binaryNode) {
        if (binaryNode.testResolved()) {
            return null;
        }

        final Node lhs = binaryNode.lhs();
        final Node rhs = binaryNode.rhs();

        final Type type = binaryNode.getType();
        if (type.isNumeric()) {
            enterNumericAdd(lhs, rhs, type, binaryNode.getSymbol());
        } else {
            load(lhs).convert(Type.OBJECT);
            load(rhs).convert(Type.OBJECT);
            method.add();
            method.store(binaryNode.getSymbol());
        }

        return null;
    }

    private Node enterAND_OR(final BinaryNode binaryNode) {
        if (binaryNode.testResolved()) {
            return null;
        }

        final Node lhs = binaryNode.lhs();
        final Node rhs = binaryNode.rhs();

        final Label skip = new Label("skip");

        load(lhs).convert(Type.OBJECT).dup().convert(Type.BOOLEAN);

        if (binaryNode.tokenType() == TokenType.AND) {
            method.ifeq(skip);
        } else {
            method.ifne(skip);
        }

        method.pop();
        load(rhs).convert(Type.OBJECT);
        method.label(skip);
        method.store(binaryNode.getSymbol());

        return null;
    }

    @Override
    public Node enterAND(final BinaryNode binaryNode) {
        return enterAND_OR(binaryNode);
    }

    @Override
    public Node enterASSIGN(final BinaryNode binaryNode) {
        if (binaryNode.testResolved()) {
            return null;
        }

        final Node lhs = binaryNode.lhs();
        final Node rhs = binaryNode.rhs();

        final Type lhsType = lhs.getType();
        final Type rhsType = rhs.getType();

        if (!lhsType.isEquivalentTo(rhsType)) {
            //this is OK if scoped, only locals are wrong
            assert !(lhs instanceof IdentNode) || lhs.getSymbol().isScope() : new ASTWriter(binaryNode);
        }

        new Store<BinaryNode>(binaryNode, lhs) {
            @Override
            protected void evaluate() {
                load(rhs);
            }
        }.store();

        return null;
    }

    /**
     * Helper class for assignment ops, e.g. *=, += and so on..
     */
    private abstract class AssignOp extends SelfModifyingStore<BinaryNode> {

        /** The type of the resulting operation */
        private final Type opType;

        /**
         * Constructor
         *
         * @param node the assign op node
         */
        AssignOp(final BinaryNode node) {
            this(node.getType(), node);
        }

        /**
         * Constructor
         *
         * @param opType type of the computation - overriding the type of the node
         * @param node the assign op node
         */
        AssignOp(final Type opType, final BinaryNode node) {
            super(node, node.lhs());
            this.opType = opType;
        }

        @Override
        public void store() {
            if (assignNode.testResolved()) {
                return;
            }
            super.store();
        }

        protected abstract void op();

        @Override
        protected void evaluate() {
            load(assignNode.lhs(), true).convert(opType);
            load(assignNode.rhs()).convert(opType);
            op();
            method.convert(assignNode.getType());
        }
    }

    @Override
    public Node enterASSIGN_ADD(final BinaryNode binaryNode) {
        assert RuntimeNode.Request.ADD.canSpecialize();
        final boolean specialize = binaryNode.getType() == Type.OBJECT;

        new AssignOp(binaryNode) {
            @Override
            protected boolean isSelfModifying() {
                return !specialize;
            }

            @Override
            protected void op() {
                method.add();
            }

            @Override
            protected void evaluate() {
                if (specialize && specializationCheck(Request.ADD, assignNode, Arrays.asList(assignNode.lhs(), assignNode.rhs()))) {
                    return;
                }
                super.evaluate();
            }
        }.store();

        return null;
    }

    @Override
    public Node enterASSIGN_BIT_AND(final BinaryNode binaryNode) {
        new AssignOp(Type.INT, binaryNode) {
            @Override
            protected void op() {
                method.and();
            }
        }.store();

        return null;
    }

    @Override
    public Node enterASSIGN_BIT_OR(final BinaryNode binaryNode) {
        new AssignOp(Type.INT, binaryNode) {
            @Override
            protected void op() {
                method.or();
            }
        }.store();

        return null;
    }

    @Override
    public Node enterASSIGN_BIT_XOR(final BinaryNode binaryNode) {
        new AssignOp(Type.INT, binaryNode) {
            @Override
            protected void op() {
                method.xor();
            }
        }.store();

        return null;
    }

    @Override
    public Node enterASSIGN_DIV(final BinaryNode binaryNode) {
        new AssignOp(binaryNode) {
            @Override
            protected void op() {
                method.div();
            }
        }.store();

        return null;
    }

    @Override
    public Node enterASSIGN_MOD(final BinaryNode binaryNode) {
        new AssignOp(binaryNode) {
            @Override
            protected void op() {
                method.rem();
            }
        }.store();

        return null;
    }

    @Override
    public Node enterASSIGN_MUL(final BinaryNode binaryNode) {
        new AssignOp(binaryNode) {
            @Override
            protected void op() {
                method.mul();
            }
        }.store();

        return null;
    }

    @Override
    public Node enterASSIGN_SAR(final BinaryNode binaryNode) {
        new AssignOp(Type.INT, binaryNode) {
            @Override
            protected void op() {
                method.sar();
            }
        }.store();

        return null;
    }

    @Override
    public Node enterASSIGN_SHL(final BinaryNode binaryNode) {
        new AssignOp(Type.INT, binaryNode) {
            @Override
            protected void op() {
                method.shl();
            }
        }.store();

        return null;
    }

    @Override
    public Node enterASSIGN_SHR(final BinaryNode binaryNode) {
        new AssignOp(Type.INT, binaryNode) {
            @Override
            protected void op() {
                method.shr();
                method.convert(Type.LONG).load(0xffff_ffffL).and();
            }
        }.store();

        return null;
    }

    @Override
    public Node enterASSIGN_SUB(final BinaryNode binaryNode) {
        new AssignOp(binaryNode) {
            @Override
            protected void op() {
                method.sub();
            }
        }.store();

        return null;
    }

    /**
     * Helper class for binary arithmetic ops
     */
    private abstract class BinaryArith {

        protected abstract void op();

        protected void evaluate(final BinaryNode node) {
            if (node.testResolved()) {
                return;
            }
            load(node.lhs());
            load(node.rhs());
            op();
            method.store(node.getSymbol());
        }
    }

    @Override
    public Node enterBIT_AND(final BinaryNode binaryNode) {
        new BinaryArith() {
            @Override
            protected void op() {
                method.and();
            }
        }.evaluate(binaryNode);

        return null;
    }

    @Override
    public Node enterBIT_OR(final BinaryNode binaryNode) {
        new BinaryArith() {
            @Override
            protected void op() {
                method.or();
            }
        }.evaluate(binaryNode);

        return null;
    }

    @Override
    public Node enterBIT_XOR(final BinaryNode binaryNode) {
        new BinaryArith() {
            @Override
            protected void op() {
                method.xor();
            }
        }.evaluate(binaryNode);

        return null;
    }

    private Node enterComma(final BinaryNode binaryNode) {
        if (binaryNode.testResolved()) {
            return null;
        }

        final Node lhs = binaryNode.lhs();
        final Node rhs = binaryNode.rhs();

        load(lhs);
        load(rhs);
        method.store(binaryNode.getSymbol());

        return null;
    }

    @Override
    public Node enterCOMMARIGHT(final BinaryNode binaryNode) {
        return enterComma(binaryNode);
    }

    @Override
    public Node enterCOMMALEFT(final BinaryNode binaryNode) {
        return enterComma(binaryNode);
    }

    @Override
    public Node enterDIV(final BinaryNode binaryNode) {
        new BinaryArith() {
            @Override
            protected void op() {
                method.div();
            }
        }.evaluate(binaryNode);

        return null;
    }

    private Node enterCmp(final Node lhs, final Node rhs, final Condition cond, final Type type, final Symbol symbol) {
        final Type lhsType = lhs.getType();
        final Type rhsType = rhs.getType();

        final Type widest = Type.widest(lhsType, rhsType);
        assert widest.isNumeric() || widest.isBoolean() : widest;

        load(lhs);
        method.convert(widest);
        load(rhs);
        method.convert(widest);

        final Label trueLabel  = new Label("trueLabel");
        final Label afterLabel = new Label("skip");

        method.conditionalJump(cond, trueLabel);

        method.load(Boolean.FALSE);
        method._goto(afterLabel);
        method.label(trueLabel);
        method.load(Boolean.TRUE);
        method.label(afterLabel);

        method.convert(type);
        method.store(symbol);

        return null;
    }

    private Node enterCmp(final BinaryNode binaryNode, final Condition cond) {
        if (binaryNode.testResolved()) {
            return null;
        }
        return enterCmp(binaryNode.lhs(), binaryNode.rhs(), cond, binaryNode.getType(), binaryNode.getSymbol());
    }

    @Override
    public Node enterEQ(final BinaryNode binaryNode) {
        return enterCmp(binaryNode, Condition.EQ);
    }

    @Override
    public Node enterEQ_STRICT(final BinaryNode binaryNode) {
        return enterCmp(binaryNode, Condition.EQ);
    }

    @Override
    public Node enterGE(final BinaryNode binaryNode) {
        return enterCmp(binaryNode, Condition.GE);
    }

    @Override
    public Node enterGT(final BinaryNode binaryNode) {
        return enterCmp(binaryNode, Condition.GT);
    }

    @Override
    public Node enterLE(final BinaryNode binaryNode) {
        return enterCmp(binaryNode, Condition.LE);
    }

    @Override
    public Node enterLT(final BinaryNode binaryNode) {
        return enterCmp(binaryNode, Condition.LT);
    }

    @Override
    public Node enterMOD(final BinaryNode binaryNode) {
        new BinaryArith() {
            @Override
            protected void op() {
                method.rem();
            }
        }.evaluate(binaryNode);

        return null;
    }

    @Override
    public Node enterMUL(final BinaryNode binaryNode) {
        new BinaryArith() {
            @Override
            protected void op() {
                method.mul();
            }
        }.evaluate(binaryNode);

        return null;
    }

    @Override
    public Node enterNE(final BinaryNode binaryNode) {
        return enterCmp(binaryNode, Condition.NE);
    }

    @Override
    public Node enterNE_STRICT(final BinaryNode binaryNode) {
        return enterCmp(binaryNode, Condition.NE);
    }

    @Override
    public Node enterOR(final BinaryNode binaryNode) {
        return enterAND_OR(binaryNode);
    }

    @Override
    public Node enterSAR(final BinaryNode binaryNode) {
        new BinaryArith() {
            @Override
            protected void op() {
                method.sar();
            }
        }.evaluate(binaryNode);

        return null;
    }

    @Override
    public Node enterSHL(final BinaryNode binaryNode) {
        new BinaryArith() {
            @Override
            protected void op() {
                method.shl();
            }
        }.evaluate(binaryNode);

        return null;
    }

    @Override
    public Node enterSHR(final BinaryNode binaryNode) {
        new BinaryArith() {
            @Override
            protected void op() {
                method.shr();
                method.convert(Type.LONG).load(0xffff_ffffL).and();
            }
        }.evaluate(binaryNode);

        return null;
    }

    @Override
    public Node enterSUB(final BinaryNode binaryNode) {
        new BinaryArith() {
            @Override
            protected void op() {
                method.sub();
            }
        }.evaluate(binaryNode);

        return null;
    }

    /*
     * Ternary visits.
     */
    @Override
    public Node enterTernaryNode(final TernaryNode ternaryNode) {
        if (ternaryNode.testResolved()) {
            return null;
        }

        final Node lhs   = ternaryNode.lhs();
        final Node rhs   = ternaryNode.rhs();
        final Node third = ternaryNode.third();

        final Symbol symbol     = ternaryNode.getSymbol();
        final Label  falseLabel = new Label("ternary_false");
        final Label  exitLabel  = new Label("ternary_exit");

        Type widest = Type.widest(rhs.getType(), third.getType());
        if (rhs.getType().isArray() || third.getType().isArray()) { //loadArray creates a Java array type on the stack, calls global allocate, which creates a native array type
            widest = Type.OBJECT;
        }

        load(lhs);
        assert lhs.getType().isBoolean() : "lhs in ternary must be boolean";

        // we still keep the conversion here as the AccessSpecializer can have separated the types, e.g. var y = x ? x=55 : 17
        // will left as (Object)x=55 : (Object)17 by Lower. Then the first term can be {I}x=55 of type int, which breaks the
        // symmetry for the temporary slot for this TernaryNode. This is evidence that we assign types and explicit conversions
        // to early, or Apply the AccessSpecializer too late. We are mostly probably looking for a separate type pass to
        // do this property. Then we never need any conversions in CodeGenerator
        method.ifeq(falseLabel);
        load(rhs);
        method.convert(widest);
        method._goto(exitLabel);
        method.label(falseLabel);
        load(third);
        method.convert(widest);
        method.label(exitLabel);
        method.store(symbol);

        return null;
    }

    /**
     * Generate all shared scope calls generated during codegen.
     */
    protected void generateScopeCalls() {
        for (final SharedScopeCall scopeAccess : scopeCalls.values()) {
            scopeAccess.generateScopeCall();
        }
    }

    /**
     * Get a shared static method representing a dynamic scope callsite.
     *
     * @param symbol the symbol
     * @param valueType the value type of the symbol
     * @param returnType the return type
     * @param paramTypes the parameter types
     * @param flags the callsite flags
     * @return an object representing a shared scope call
     */
    private SharedScopeCall getScopeCall(final Symbol symbol, final Type valueType, final Type returnType,
                                         final Type[] paramTypes, final int flags) {

        final SharedScopeCall scopeCall = new SharedScopeCall(symbol, valueType, returnType, paramTypes, flags);
        if (scopeCalls.containsKey(scopeCall)) {
            return scopeCalls.get(scopeCall);
        }
        scopeCall.setClassAndName(getCurrentCompileUnit(), getCurrentFunctionNode().uniqueName("scopeCall"));
        scopeCalls.put(scopeCall, scopeCall);
        return scopeCall;
    }

    /**
     * Get a shared static method representing a dynamic scope get access.
     *
     * @param type the type of the variable
     * @param symbol the symbol
     * @param flags the callsite flags
     * @return an object representing a shared scope call
     */
    private SharedScopeCall getScopeGet(final Type type, final Symbol symbol, final int flags) {

        final SharedScopeCall scopeCall = new SharedScopeCall(symbol, type, type, null, flags);
        if (scopeCalls.containsKey(scopeCall)) {
            return scopeCalls.get(scopeCall);
        }
        scopeCall.setClassAndName(getCurrentCompileUnit(), getCurrentFunctionNode().uniqueName("scopeCall"));
        scopeCalls.put(scopeCall, scopeCall);
        return scopeCall;
    }

    /**
     * Debug code used to print symbols
     *
     * @param block the block we are in
     * @param ident identifier for block or function where applicable
     */
    private void printSymbols(final Block block, final String ident) {
        if (!compiler.getEnv()._print_symbols) {
            return;
        }

        @SuppressWarnings("resource")
        final PrintWriter out = compiler.getEnv().getErr();
        out.println("[BLOCK in '" + ident + "']");
        if (!block.printSymbols(out)) {
            out.println("<no symbols>");
        }
        out.println();
    }


    /**
     * The difference between a store and a self modifying store is that
     * the latter may load part of the target on the stack, e.g. the base
     * of an AccessNode or the base and index of an IndexNode. These are used
     * both as target and as an extra source. Previously it was problematic
     * for self modifying stores if the target/lhs didn't belong to one
     * of three trivial categories: IdentNode, AcessNodes, IndexNodes. In that
     * case it was evaluated and tagged as "resolved", which meant at the second
     * time the lhs of this store was read (e.g. in a = a (second) + b for a += b,
     * it would be evaluated to a nop in the scope and cause stack underflow
     *
     * see NASHORN-703
     *
     * @param <T>
     */
    private abstract class SelfModifyingStore<T extends Node> extends Store<T> {
        protected SelfModifyingStore(final T assignNode, final Node target) {
            super(assignNode, target);
        }

        @Override
        protected boolean isSelfModifying() {
            return true;
        }
    }

    /**
     * Helper class to generate stores
     */
    private abstract class Store<T extends Node> {

        /** An assignment node, e.g. x += y */
        protected final T assignNode;

        /** The target node to store to, e.g. x */
        private final Node target;

        /** Should the result always be discarded, no matter what? */
        private final boolean alwaysDiscard;

        /** How deep on the stack do the arguments go if this generates an indy call */
        private int depth;

        /** If we have too many arguments, we need temporary storage, this is stored in 'quick' */
        private Symbol quick;

        /**
         * Constructor
         *
         * @param assignNode the node representing the whole assignment
         * @param target     the target node of the assignment (destination)
         */
        protected Store(final T assignNode, final Node target) {
            this.assignNode = assignNode;
            this.target = target;
            this.alwaysDiscard = assignNode == target;
        }

        /**
         * Constructor
         *
         * @param assignNode the node representing the whole assignment
         */
        protected Store(final T assignNode) {
            this(assignNode, assignNode);
        }

        /**
         * Is this a self modifying store operation, e.g. *= or ++
         * @return true if self modifying store
         */
        protected boolean isSelfModifying() {
            return false;
        }

        private void prologue() {
            final Symbol targetSymbol = target.getSymbol();
            final Symbol scopeSymbol  = getCurrentFunctionNode().getScopeNode().getSymbol();

            /**
             * This loads the parts of the target, e.g base and index. they are kept
             * on the stack throughout the store and used at the end to execute it
             */

            target.accept(new NodeVisitor(getCurrentCompileUnit(), method) {
                @Override
                public Node enterIdentNode(final IdentNode node) {
                    if (targetSymbol.isScope()) {
                        method.load(scopeSymbol);
                        depth++;
                    }
                    return null;
                }

                private void enterBaseNode() {
                    assert target instanceof BaseNode : "error - base node " + target + " must be instanceof BaseNode";
                    final BaseNode baseNode = (BaseNode)target;
                    final Node     base     = baseNode.getBase();

                    load(base);
                    method.convert(Type.OBJECT);
                    depth += Type.OBJECT.getSlots();

                    if (isSelfModifying()) {
                        method.dup();
                    }
                }

                @Override
                public Node enterAccessNode(final AccessNode node) {
                    enterBaseNode();
                    return null;
                }

                @Override
                public Node enterIndexNode(final IndexNode node) {
                    enterBaseNode();

                    final Node index = node.getIndex();
                    // could be boolean here as well
                    load(index);
                    if (!index.getType().isNumeric()) {
                        method.convert(Type.OBJECT);
                    }
                    depth += index.getType().getSlots();

                    if (isSelfModifying()) {
                        //convert "base base index" to "base index base index"
                        method.dup(1);
                    }

                    return null;
                }

            });
        }

        private Symbol quickSymbol(final Type type) {
            return quickSymbol(type, QUICK_PREFIX.tag());
        }

        /**
         * Quick symbol generates an extra local variable, always using the same
         * slot, one that is available after the end of the frame.
         *
         * @param type the type of the symbol
         * @param prefix the prefix for the variable name for the symbol
         *
         * @return the quick symbol
         */
        private Symbol quickSymbol(final Type type, final String prefix) {
            final String name = getCurrentFunctionNode().uniqueName(prefix);
            final Symbol symbol = new Symbol(name, IS_TEMP | IS_INTERNAL, null, null);

            symbol.setType(type);
            symbol.setSlot(getCurrentBlock().getFrame().getSlotCount());

            return symbol;
        }

        // store the result that "lives on" after the op, e.g. "i" in i++ postfix.
        protected void storeNonDiscard() {
            if (assignNode.shouldDiscard() || alwaysDiscard) {
                assignNode.setDiscard(false);
                return;
            }

            final Symbol symbol = assignNode.getSymbol();
            if (symbol.hasSlot()) {
                method.dup().store(symbol);
                return;
            }

            if (method.dup(depth) == null) {
                method.dup();
                this.quick = quickSymbol(method.peekType());
                method.store(quick);
            }
        }

        private void epilogue() {
            /**
             * Take the original target args from the stack and use them
             * together with the value to be stored to emit the store code
             *
             * The case that targetSymbol is in scope (!hasSlot) and we actually
             * need to do a conversion on non-equivalent types exists, but is
             * very rare. See for example test/script/basic/access-specializer.js
             */
            method.convert(target.getType());

            target.accept(new NodeVisitor(getCurrentCompileUnit(), method) {
                @Override
                protected Node enterDefault(Node node) {
                    throw new AssertionError("Unexpected node " + node + " in store epilogue");
                }

                @Override
                public Node enterUnaryNode(final UnaryNode node) {
                    if(node.tokenType() == TokenType.CONVERT && node.getSymbol() != null) {
                        method.convert(node.rhs().getType());
                    }
                    return node;
                }

                @Override
                public Node enterIdentNode(final IdentNode node) {
                    final Symbol symbol = node.getSymbol();
                    assert symbol != null;
                    if (symbol.isScope()) {
                        if (isFastScope(symbol)) {
                            storeFastScopeVar(node.getType(), symbol, CALLSITE_SCOPE | getCallSiteFlags());
                        } else {
                            method.dynamicSet(node.getType(), node.getName(), CALLSITE_SCOPE | getCallSiteFlags());
                        }
                    } else {
                        method.store(symbol);
                    }
                    return null;

                }

                @Override
                public Node enterAccessNode(final AccessNode node) {
                    method.dynamicSet(node.getProperty().getType(), node.getProperty().getName(), getCallSiteFlags());
                    return null;
                }

                @Override
                public Node enterIndexNode(final IndexNode node) {
                    method.dynamicSetIndex(getCallSiteFlags());
                    return null;
                }
            });


            // whatever is on the stack now is the final answer
        }

        protected abstract void evaluate();

        void store() {
            prologue();
            evaluate(); // leaves an operation of whatever the operationType was on the stack
            storeNonDiscard();
            epilogue();
            if (quick != null) {
                method.load(quick);
            }
        }

    }

    private void newFunctionObject(final FunctionNode functionNode) {
        final boolean isLazy  = functionNode.isLazy();

        new ObjectCreator(this, new ArrayList<String>(), new ArrayList<Symbol>(), false, false) {
            @Override
            protected void makeObject(final MethodEmitter m) {
                final String className = SCRIPTFUNCTION_IMPL_OBJECT;

                m._new(className).dup();
                loadConstant(new RecompilableScriptFunctionData(functionNode, compiler.getCodeInstaller(), Compiler.binaryName(getClassName()), makeMap()));

                if (isLazy || functionNode.needsParentScope()) {
                    m.loadScope();
                } else {
                    m.loadNull();
                }
                m.invoke(constructorNoLookup(className, RecompilableScriptFunctionData.class, ScriptObject.class));
            }
        }.makeObject(method);
    }

    /*
     * Globals are special. We cannot refer to any Global (or NativeObject) class by .class, as they are different
     * for different contexts. As far as I can tell, the only NativeObject that we need to deal with like this
     * is from the code pipeline is Global
     */
    private MethodEmitter globalInstance() {
        return method.invokestatic(GLOBAL_OBJECT, "instance", "()L" + GLOBAL_OBJECT + ';');
    }

    private MethodEmitter globalObjectPrototype() {
        return method.invokestatic(GLOBAL_OBJECT, "objectPrototype", methodDescriptor(ScriptObject.class));
    }

    private MethodEmitter globalAllocateArguments() {
        return method.invokestatic(GLOBAL_OBJECT, "allocateArguments", methodDescriptor(ScriptObject.class, Object[].class, Object.class, int.class));
    }

    private MethodEmitter globalNewRegExp() {
        return method.invokestatic(GLOBAL_OBJECT, "newRegExp", methodDescriptor(Object.class, String.class, String.class));
    }

    private MethodEmitter globalRegExpCopy() {
        return method.invokestatic(GLOBAL_OBJECT, "regExpCopy", methodDescriptor(Object.class, Object.class));
    }

    private MethodEmitter globalAllocateArray(final ArrayType type) {
        //make sure the native array is treated as an array type
        return method.invokestatic(GLOBAL_OBJECT, "allocate", "(" + type.getDescriptor() + ")Ljdk/nashorn/internal/objects/NativeArray;");
    }

    private MethodEmitter globalIsEval() {
        return method.invokestatic(GLOBAL_OBJECT, "isEval", methodDescriptor(boolean.class, Object.class));
    }

    private MethodEmitter globalDirectEval() {
        return method.invokestatic(GLOBAL_OBJECT, "directEval",
                methodDescriptor(Object.class, Object.class, Object.class, Object.class, Object.class, Object.class));
    }
}