1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
|
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
* vim: set ts=8 sts=2 et sw=2 tw=80:
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "jit/MIR.h"
#include "mozilla/CheckedInt.h"
#include "mozilla/EndianUtils.h"
#include "mozilla/FloatingPoint.h"
#include "mozilla/MathAlgorithms.h"
#include "mozilla/Maybe.h"
#include "mozilla/ScopeExit.h"
#include <array>
#include <utility>
#include "jslibmath.h"
#include "jsmath.h"
#include "jsnum.h"
#include "builtin/RegExp.h"
#include "jit/AtomicOperations.h"
#include "jit/CompileInfo.h"
#include "jit/KnownClass.h"
#include "jit/MIRGraph.h"
#include "jit/RangeAnalysis.h"
#include "jit/VMFunctions.h"
#include "jit/WarpBuilderShared.h"
#include "js/Conversions.h"
#include "js/experimental/JitInfo.h" // JSJitInfo, JSTypedMethodJitInfo
#include "js/ScalarType.h" // js::Scalar::Type
#include "util/Text.h"
#include "util/Unicode.h"
#include "vm/Iteration.h" // js::NativeIterator
#include "vm/PlainObject.h" // js::PlainObject
#include "vm/Uint8Clamped.h"
#include "wasm/WasmCode.h"
#include "wasm/WasmFeatures.h" // for wasm::ReportSimdAnalysis
#include "vm/JSAtomUtils-inl.h" // TypeName
#include "wasm/WasmInstance-inl.h"
using namespace js;
using namespace js::jit;
using JS::ToInt32;
using mozilla::CheckedInt;
using mozilla::DebugOnly;
using mozilla::IsFloat32Representable;
using mozilla::IsPowerOfTwo;
using mozilla::Maybe;
using mozilla::NumbersAreIdentical;
NON_GC_POINTER_TYPE_ASSERTIONS_GENERATED
#ifdef DEBUG
size_t MUse::index() const { return consumer()->indexOf(this); }
#endif
template <size_t Op>
static void ConvertDefinitionToDouble(TempAllocator& alloc, MDefinition* def,
MInstruction* consumer) {
MInstruction* replace = MToDouble::New(alloc, def);
consumer->replaceOperand(Op, replace);
consumer->block()->insertBefore(consumer, replace);
}
template <size_t Arity, size_t Index>
static void ConvertOperandToDouble(MAryInstruction<Arity>* def,
TempAllocator& alloc) {
static_assert(Index < Arity);
auto* operand = def->getOperand(Index);
if (operand->type() == MIRType::Float32) {
ConvertDefinitionToDouble<Index>(alloc, operand, def);
}
}
template <size_t Arity, size_t... ISeq>
static void ConvertOperandsToDouble(MAryInstruction<Arity>* def,
TempAllocator& alloc,
std::index_sequence<ISeq...>) {
(ConvertOperandToDouble<Arity, ISeq>(def, alloc), ...);
}
template <size_t Arity>
static void ConvertOperandsToDouble(MAryInstruction<Arity>* def,
TempAllocator& alloc) {
ConvertOperandsToDouble<Arity>(def, alloc, std::make_index_sequence<Arity>{});
}
template <size_t Arity, size_t... ISeq>
static bool AllOperandsCanProduceFloat32(MAryInstruction<Arity>* def,
std::index_sequence<ISeq...>) {
return (def->getOperand(ISeq)->canProduceFloat32() && ...);
}
template <size_t Arity>
static bool AllOperandsCanProduceFloat32(MAryInstruction<Arity>* def) {
return AllOperandsCanProduceFloat32<Arity>(def,
std::make_index_sequence<Arity>{});
}
static bool CheckUsesAreFloat32Consumers(const MInstruction* ins) {
if (ins->isImplicitlyUsed()) {
return false;
}
bool allConsumerUses = true;
for (MUseDefIterator use(ins); allConsumerUses && use; use++) {
allConsumerUses &= use.def()->canConsumeFloat32(use.use());
}
return allConsumerUses;
}
#ifdef JS_JITSPEW
static const char* OpcodeName(MDefinition::Opcode op) {
static const char* const names[] = {
# define NAME(x) #x,
MIR_OPCODE_LIST(NAME)
# undef NAME
};
return names[unsigned(op)];
}
void MDefinition::PrintOpcodeName(GenericPrinter& out, Opcode op) {
const char* name = OpcodeName(op);
size_t len = strlen(name);
for (size_t i = 0; i < len; i++) {
out.printf("%c", unicode::ToLowerCase(name[i]));
}
}
uint32_t js::jit::GetMBasicBlockId(const MBasicBlock* block) {
return block->id();
}
#endif
static MConstant* EvaluateInt64ConstantOperands(TempAllocator& alloc,
MBinaryInstruction* ins) {
MDefinition* left = ins->getOperand(0);
MDefinition* right = ins->getOperand(1);
if (!left->isConstant() || !right->isConstant()) {
return nullptr;
}
MOZ_ASSERT(left->type() == MIRType::Int64);
MOZ_ASSERT(right->type() == MIRType::Int64);
int64_t lhs = left->toConstant()->toInt64();
int64_t rhs = right->toConstant()->toInt64();
int64_t ret;
switch (ins->op()) {
case MDefinition::Opcode::BitAnd:
ret = lhs & rhs;
break;
case MDefinition::Opcode::BitOr:
ret = lhs | rhs;
break;
case MDefinition::Opcode::BitXor:
ret = lhs ^ rhs;
break;
case MDefinition::Opcode::Lsh:
ret = lhs << (rhs & 0x3F);
break;
case MDefinition::Opcode::Rsh:
ret = lhs >> (rhs & 0x3F);
break;
case MDefinition::Opcode::Ursh:
ret = uint64_t(lhs) >> (uint64_t(rhs) & 0x3F);
break;
case MDefinition::Opcode::Add:
ret = lhs + rhs;
break;
case MDefinition::Opcode::Sub:
ret = lhs - rhs;
break;
case MDefinition::Opcode::Mul:
ret = lhs * rhs;
break;
case MDefinition::Opcode::Div:
if (rhs == 0) {
// Division by zero will trap at runtime.
return nullptr;
}
if (ins->toDiv()->isUnsigned()) {
ret = int64_t(uint64_t(lhs) / uint64_t(rhs));
} else if (lhs == INT64_MIN || rhs == -1) {
// Overflow will trap at runtime.
return nullptr;
} else {
ret = lhs / rhs;
}
break;
case MDefinition::Opcode::Mod:
if (rhs == 0) {
// Division by zero will trap at runtime.
return nullptr;
}
if (!ins->toMod()->isUnsigned() && (lhs < 0 || rhs < 0)) {
// Handle all negative values at runtime, for simplicity.
return nullptr;
}
ret = int64_t(uint64_t(lhs) % uint64_t(rhs));
break;
default:
MOZ_CRASH("NYI");
}
return MConstant::NewInt64(alloc, ret);
}
static MConstant* EvaluateConstantOperands(TempAllocator& alloc,
MBinaryInstruction* ins,
bool* ptypeChange = nullptr) {
MDefinition* left = ins->getOperand(0);
MDefinition* right = ins->getOperand(1);
MOZ_ASSERT(IsTypeRepresentableAsDouble(left->type()));
MOZ_ASSERT(IsTypeRepresentableAsDouble(right->type()));
if (!left->isConstant() || !right->isConstant()) {
return nullptr;
}
MConstant* lhs = left->toConstant();
MConstant* rhs = right->toConstant();
double ret = JS::GenericNaN();
switch (ins->op()) {
case MDefinition::Opcode::BitAnd:
ret = double(lhs->toInt32() & rhs->toInt32());
break;
case MDefinition::Opcode::BitOr:
ret = double(lhs->toInt32() | rhs->toInt32());
break;
case MDefinition::Opcode::BitXor:
ret = double(lhs->toInt32() ^ rhs->toInt32());
break;
case MDefinition::Opcode::Lsh:
ret = double(uint32_t(lhs->toInt32()) << (rhs->toInt32() & 0x1F));
break;
case MDefinition::Opcode::Rsh:
ret = double(lhs->toInt32() >> (rhs->toInt32() & 0x1F));
break;
case MDefinition::Opcode::Ursh:
ret = double(uint32_t(lhs->toInt32()) >> (rhs->toInt32() & 0x1F));
break;
case MDefinition::Opcode::Add:
ret = lhs->numberToDouble() + rhs->numberToDouble();
break;
case MDefinition::Opcode::Sub:
ret = lhs->numberToDouble() - rhs->numberToDouble();
break;
case MDefinition::Opcode::Mul:
ret = lhs->numberToDouble() * rhs->numberToDouble();
break;
case MDefinition::Opcode::Div:
if (ins->toDiv()->isUnsigned()) {
if (rhs->isInt32(0)) {
if (ins->toDiv()->trapOnError()) {
return nullptr;
}
ret = 0.0;
} else {
ret = double(uint32_t(lhs->toInt32()) / uint32_t(rhs->toInt32()));
}
} else {
ret = NumberDiv(lhs->numberToDouble(), rhs->numberToDouble());
}
break;
case MDefinition::Opcode::Mod:
if (ins->toMod()->isUnsigned()) {
if (rhs->isInt32(0)) {
if (ins->toMod()->trapOnError()) {
return nullptr;
}
ret = 0.0;
} else {
ret = double(uint32_t(lhs->toInt32()) % uint32_t(rhs->toInt32()));
}
} else {
ret = NumberMod(lhs->numberToDouble(), rhs->numberToDouble());
}
break;
default:
MOZ_CRASH("NYI");
}
if (ins->type() == MIRType::Float32) {
return MConstant::NewFloat32(alloc, float(ret));
}
if (ins->type() == MIRType::Double) {
return MConstant::New(alloc, DoubleValue(ret));
}
Value retVal;
retVal.setNumber(JS::CanonicalizeNaN(ret));
// If this was an int32 operation but the result isn't an int32 (for
// example, a division where the numerator isn't evenly divisible by the
// denominator), decline folding.
MOZ_ASSERT(ins->type() == MIRType::Int32);
if (!retVal.isInt32()) {
if (ptypeChange) {
*ptypeChange = true;
}
return nullptr;
}
return MConstant::New(alloc, retVal);
}
static MMul* EvaluateExactReciprocal(TempAllocator& alloc, MDiv* ins) {
// we should fold only when it is a floating point operation
if (!IsFloatingPointType(ins->type())) {
return nullptr;
}
MDefinition* left = ins->getOperand(0);
MDefinition* right = ins->getOperand(1);
if (!right->isConstant()) {
return nullptr;
}
int32_t num;
if (!mozilla::NumberIsInt32(right->toConstant()->numberToDouble(), &num)) {
return nullptr;
}
// check if rhs is a power of two
if (mozilla::Abs(num) & (mozilla::Abs(num) - 1)) {
return nullptr;
}
Value ret;
ret.setDouble(1.0 / double(num));
MConstant* foldedRhs;
if (ins->type() == MIRType::Float32) {
foldedRhs = MConstant::NewFloat32(alloc, ret.toDouble());
} else {
foldedRhs = MConstant::New(alloc, ret);
}
MOZ_ASSERT(foldedRhs->type() == ins->type());
ins->block()->insertBefore(ins, foldedRhs);
MMul* mul = MMul::New(alloc, left, foldedRhs, ins->type());
mul->setMustPreserveNaN(ins->mustPreserveNaN());
return mul;
}
#ifdef JS_JITSPEW
const char* MDefinition::opName() const { return OpcodeName(op()); }
void MDefinition::printName(GenericPrinter& out) const {
PrintOpcodeName(out, op());
out.printf("%u", id());
}
#endif
HashNumber MDefinition::valueHash() const {
HashNumber out = HashNumber(op());
for (size_t i = 0, e = numOperands(); i < e; i++) {
out = addU32ToHash(out, getOperand(i)->id());
}
if (MDefinition* dep = dependency()) {
out = addU32ToHash(out, dep->id());
}
return out;
}
HashNumber MNullaryInstruction::valueHash() const {
HashNumber hash = HashNumber(op());
if (MDefinition* dep = dependency()) {
hash = addU32ToHash(hash, dep->id());
}
MOZ_ASSERT(hash == MDefinition::valueHash());
return hash;
}
HashNumber MUnaryInstruction::valueHash() const {
HashNumber hash = HashNumber(op());
hash = addU32ToHash(hash, getOperand(0)->id());
if (MDefinition* dep = dependency()) {
hash = addU32ToHash(hash, dep->id());
}
MOZ_ASSERT(hash == MDefinition::valueHash());
return hash;
}
HashNumber MBinaryInstruction::valueHash() const {
HashNumber hash = HashNumber(op());
hash = addU32ToHash(hash, getOperand(0)->id());
hash = addU32ToHash(hash, getOperand(1)->id());
if (MDefinition* dep = dependency()) {
hash = addU32ToHash(hash, dep->id());
}
MOZ_ASSERT(hash == MDefinition::valueHash());
return hash;
}
HashNumber MTernaryInstruction::valueHash() const {
HashNumber hash = HashNumber(op());
hash = addU32ToHash(hash, getOperand(0)->id());
hash = addU32ToHash(hash, getOperand(1)->id());
hash = addU32ToHash(hash, getOperand(2)->id());
if (MDefinition* dep = dependency()) {
hash = addU32ToHash(hash, dep->id());
}
MOZ_ASSERT(hash == MDefinition::valueHash());
return hash;
}
HashNumber MQuaternaryInstruction::valueHash() const {
HashNumber hash = HashNumber(op());
hash = addU32ToHash(hash, getOperand(0)->id());
hash = addU32ToHash(hash, getOperand(1)->id());
hash = addU32ToHash(hash, getOperand(2)->id());
hash = addU32ToHash(hash, getOperand(3)->id());
if (MDefinition* dep = dependency()) {
hash = addU32ToHash(hash, dep->id());
}
MOZ_ASSERT(hash == MDefinition::valueHash());
return hash;
}
const MDefinition* MDefinition::skipObjectGuards() const {
const MDefinition* result = this;
// These instructions don't modify the object and just guard specific
// properties.
while (true) {
if (result->isGuardShape()) {
result = result->toGuardShape()->object();
continue;
}
if (result->isGuardNullProto()) {
result = result->toGuardNullProto()->object();
continue;
}
if (result->isGuardProto()) {
result = result->toGuardProto()->object();
continue;
}
break;
}
return result;
}
bool MDefinition::congruentIfOperandsEqual(const MDefinition* ins) const {
if (op() != ins->op()) {
return false;
}
if (type() != ins->type()) {
return false;
}
if (isEffectful() || ins->isEffectful()) {
return false;
}
if (numOperands() != ins->numOperands()) {
return false;
}
for (size_t i = 0, e = numOperands(); i < e; i++) {
if (getOperand(i) != ins->getOperand(i)) {
return false;
}
}
return true;
}
MDefinition* MDefinition::foldsTo(TempAllocator& alloc) {
// In the default case, there are no constants to fold.
return this;
}
bool MDefinition::mightBeMagicType() const {
if (IsMagicType(type())) {
return true;
}
if (MIRType::Value != type()) {
return false;
}
return true;
}
bool MDefinition::definitelyType(std::initializer_list<MIRType> types) const {
#ifdef DEBUG
// Only support specialized, non-magic types.
auto isSpecializedNonMagic = [](MIRType type) {
return type <= MIRType::Object;
};
#endif
MOZ_ASSERT(types.size() > 0);
MOZ_ASSERT(std::all_of(types.begin(), types.end(), isSpecializedNonMagic));
if (type() == MIRType::Value) {
return false;
}
return std::find(types.begin(), types.end(), type()) != types.end();
}
MDefinition* MInstruction::foldsToStore(TempAllocator& alloc) {
if (!dependency()) {
return nullptr;
}
MDefinition* store = dependency();
if (mightAlias(store) != AliasType::MustAlias) {
return nullptr;
}
if (!store->block()->dominates(block())) {
return nullptr;
}
MDefinition* value;
switch (store->op()) {
case Opcode::StoreFixedSlot:
value = store->toStoreFixedSlot()->value();
break;
case Opcode::StoreDynamicSlot:
value = store->toStoreDynamicSlot()->value();
break;
case Opcode::StoreElement:
value = store->toStoreElement()->value();
break;
default:
MOZ_CRASH("unknown store");
}
// If the type are matching then we return the value which is used as
// argument of the store.
if (value->type() != type()) {
// If we expect to read a type which is more generic than the type seen
// by the store, then we box the value used by the store.
if (type() != MIRType::Value) {
return nullptr;
}
MOZ_ASSERT(value->type() < MIRType::Value);
MBox* box = MBox::New(alloc, value);
value = box;
}
return value;
}
void MDefinition::analyzeEdgeCasesForward() {}
void MDefinition::analyzeEdgeCasesBackward() {}
void MInstruction::setResumePoint(MResumePoint* resumePoint) {
MOZ_ASSERT(!resumePoint_);
resumePoint_ = resumePoint;
resumePoint_->setInstruction(this);
}
void MInstruction::stealResumePoint(MInstruction* other) {
MResumePoint* resumePoint = other->resumePoint_;
other->resumePoint_ = nullptr;
resumePoint->resetInstruction();
setResumePoint(resumePoint);
}
void MInstruction::moveResumePointAsEntry() {
MOZ_ASSERT(isNop());
block()->clearEntryResumePoint();
block()->setEntryResumePoint(resumePoint_);
resumePoint_->resetInstruction();
resumePoint_ = nullptr;
}
void MInstruction::clearResumePoint() {
resumePoint_->resetInstruction();
block()->discardPreAllocatedResumePoint(resumePoint_);
resumePoint_ = nullptr;
}
MDefinition* MTest::foldsDoubleNegation(TempAllocator& alloc) {
MDefinition* op = getOperand(0);
if (op->isNot()) {
// If the operand of the Not is itself a Not, they cancel out.
MDefinition* opop = op->getOperand(0);
if (opop->isNot()) {
return MTest::New(alloc, opop->toNot()->input(), ifTrue(), ifFalse());
}
return MTest::New(alloc, op->toNot()->input(), ifFalse(), ifTrue());
}
return nullptr;
}
MDefinition* MTest::foldsConstant(TempAllocator& alloc) {
MDefinition* op = getOperand(0);
if (MConstant* opConst = op->maybeConstantValue()) {
bool b;
if (opConst->valueToBoolean(&b)) {
return MGoto::New(alloc, b ? ifTrue() : ifFalse());
}
}
return nullptr;
}
MDefinition* MTest::foldsTypes(TempAllocator& alloc) {
MDefinition* op = getOperand(0);
switch (op->type()) {
case MIRType::Undefined:
case MIRType::Null:
return MGoto::New(alloc, ifFalse());
case MIRType::Symbol:
return MGoto::New(alloc, ifTrue());
default:
break;
}
return nullptr;
}
class UsesIterator {
MDefinition* def_;
public:
explicit UsesIterator(MDefinition* def) : def_(def) {}
auto begin() const { return def_->usesBegin(); }
auto end() const { return def_->usesEnd(); }
};
static bool AllInstructionsDeadIfUnused(MBasicBlock* block) {
for (auto* ins : *block) {
// Skip trivial instructions.
if (ins->isNop() || ins->isGoto()) {
continue;
}
// All uses must be within the current block.
for (auto* use : UsesIterator(ins)) {
if (use->consumer()->block() != block) {
return false;
}
}
// All instructions within this block must be dead if unused.
if (!DeadIfUnused(ins)) {
return false;
}
}
return true;
}
MDefinition* MTest::foldsNeedlessControlFlow(TempAllocator& alloc) {
// All instructions within both successors need be dead if unused.
if (!AllInstructionsDeadIfUnused(ifTrue()) ||
!AllInstructionsDeadIfUnused(ifFalse())) {
return nullptr;
}
// Both successors must have the same target successor.
if (ifTrue()->numSuccessors() != 1 || ifFalse()->numSuccessors() != 1) {
return nullptr;
}
if (ifTrue()->getSuccessor(0) != ifFalse()->getSuccessor(0)) {
return nullptr;
}
// The target successor's phis must be redundant. Redundant phis should have
// been removed in an earlier pass, so only check if any phis are present,
// which is a stronger condition.
if (ifTrue()->successorWithPhis()) {
return nullptr;
}
return MGoto::New(alloc, ifTrue());
}
// If a test is dominated by either the true or false path of a previous test of
// the same condition, then the test is redundant and can be converted into a
// goto true or goto false, respectively.
MDefinition* MTest::foldsRedundantTest(TempAllocator& alloc) {
MBasicBlock* myBlock = this->block();
MDefinition* originalInput = getOperand(0);
// Handle single and double negatives. This ensures that we do not miss a
// folding opportunity due to a condition being inverted.
MDefinition* newInput = input();
bool inverted = false;
if (originalInput->isNot()) {
newInput = originalInput->toNot()->input();
inverted = true;
if (originalInput->toNot()->input()->isNot()) {
newInput = originalInput->toNot()->input()->toNot()->input();
inverted = false;
}
}
// The specific order of traversal does not matter. If there are multiple
// dominating redundant tests, they will either agree on direction (in which
// case we will prune the same way regardless of order), or they will
// disagree, in which case we will eventually be marked entirely dead by the
// folding of the redundant parent.
for (MUseIterator i(newInput->usesBegin()), e(newInput->usesEnd()); i != e;
++i) {
if (!i->consumer()->isDefinition()) {
continue;
}
if (!i->consumer()->toDefinition()->isTest()) {
continue;
}
MTest* otherTest = i->consumer()->toDefinition()->toTest();
if (otherTest == this) {
continue;
}
if (otherTest->ifFalse()->dominates(myBlock)) {
// This test cannot be true, so fold to a goto false.
return MGoto::New(alloc, inverted ? ifTrue() : ifFalse());
}
if (otherTest->ifTrue()->dominates(myBlock)) {
// This test cannot be false, so fold to a goto true.
return MGoto::New(alloc, inverted ? ifFalse() : ifTrue());
}
}
return nullptr;
}
MDefinition* MTest::foldsTo(TempAllocator& alloc) {
if (MDefinition* def = foldsRedundantTest(alloc)) {
return def;
}
if (MDefinition* def = foldsDoubleNegation(alloc)) {
return def;
}
if (MDefinition* def = foldsConstant(alloc)) {
return def;
}
if (MDefinition* def = foldsTypes(alloc)) {
return def;
}
if (MDefinition* def = foldsNeedlessControlFlow(alloc)) {
return def;
}
return this;
}
AliasSet MThrow::getAliasSet() const {
return AliasSet::Store(AliasSet::ExceptionState);
}
AliasSet MThrowWithStack::getAliasSet() const {
return AliasSet::Store(AliasSet::ExceptionState);
}
AliasSet MNewArrayDynamicLength::getAliasSet() const {
return AliasSet::Store(AliasSet::ExceptionState);
}
AliasSet MNewTypedArrayDynamicLength::getAliasSet() const {
return AliasSet::Store(AliasSet::ExceptionState);
}
#ifdef JS_JITSPEW
void MDefinition::printOpcode(GenericPrinter& out) const {
PrintOpcodeName(out, op());
for (size_t j = 0, e = numOperands(); j < e; j++) {
out.printf(" ");
if (getUseFor(j)->hasProducer()) {
getOperand(j)->printName(out);
out.printf(":%s", StringFromMIRType(getOperand(j)->type()));
} else {
out.printf("(null)");
}
}
}
void MDefinition::dump(GenericPrinter& out) const {
printName(out);
out.printf(":%s", StringFromMIRType(type()));
out.printf(" = ");
printOpcode(out);
out.printf("\n");
if (isInstruction()) {
if (MResumePoint* resume = toInstruction()->resumePoint()) {
resume->dump(out);
}
}
}
void MDefinition::dump() const {
Fprinter out(stderr);
dump(out);
out.finish();
}
void MDefinition::dumpLocation(GenericPrinter& out) const {
MResumePoint* rp = nullptr;
const char* linkWord = nullptr;
if (isInstruction() && toInstruction()->resumePoint()) {
rp = toInstruction()->resumePoint();
linkWord = "at";
} else {
rp = block()->entryResumePoint();
linkWord = "after";
}
while (rp) {
JSScript* script = rp->block()->info().script();
uint32_t lineno = PCToLineNumber(rp->block()->info().script(), rp->pc());
out.printf(" %s %s:%u\n", linkWord, script->filename(), lineno);
rp = rp->caller();
linkWord = "in";
}
}
void MDefinition::dumpLocation() const {
Fprinter out(stderr);
dumpLocation(out);
out.finish();
}
#endif
#if defined(DEBUG) || defined(JS_JITSPEW)
size_t MDefinition::useCount() const {
size_t count = 0;
for (MUseIterator i(uses_.begin()); i != uses_.end(); i++) {
count++;
}
return count;
}
size_t MDefinition::defUseCount() const {
size_t count = 0;
for (MUseIterator i(uses_.begin()); i != uses_.end(); i++) {
if ((*i)->consumer()->isDefinition()) {
count++;
}
}
return count;
}
#endif
bool MDefinition::hasOneUse() const {
MUseIterator i(uses_.begin());
if (i == uses_.end()) {
return false;
}
i++;
return i == uses_.end();
}
bool MDefinition::hasOneDefUse() const {
bool hasOneDefUse = false;
for (MUseIterator i(uses_.begin()); i != uses_.end(); i++) {
if (!(*i)->consumer()->isDefinition()) {
continue;
}
// We already have a definition use. So 1+
if (hasOneDefUse) {
return false;
}
// We saw one definition. Loop to test if there is another.
hasOneDefUse = true;
}
return hasOneDefUse;
}
bool MDefinition::hasOneLiveDefUse() const {
bool hasOneDefUse = false;
for (MUseIterator i(uses_.begin()); i != uses_.end(); i++) {
if (!(*i)->consumer()->isDefinition()) {
continue;
}
MDefinition* def = (*i)->consumer()->toDefinition();
if (def->isRecoveredOnBailout()) {
continue;
}
// We already have a definition use. So 1+
if (hasOneDefUse) {
return false;
}
// We saw one definition. Loop to test if there is another.
hasOneDefUse = true;
}
return hasOneDefUse;
}
bool MDefinition::hasDefUses() const {
for (MUseIterator i(uses_.begin()); i != uses_.end(); i++) {
if ((*i)->consumer()->isDefinition()) {
return true;
}
}
return false;
}
bool MDefinition::hasLiveDefUses() const {
for (MUseIterator i(uses_.begin()); i != uses_.end(); i++) {
MNode* ins = (*i)->consumer();
if (ins->isDefinition()) {
if (!ins->toDefinition()->isRecoveredOnBailout()) {
return true;
}
} else {
MOZ_ASSERT(ins->isResumePoint());
if (!ins->toResumePoint()->isRecoverableOperand(*i)) {
return true;
}
}
}
return false;
}
MDefinition* MDefinition::maybeSingleDefUse() const {
MUseDefIterator use(this);
if (!use) {
// No def-uses.
return nullptr;
}
MDefinition* useDef = use.def();
use++;
if (use) {
// More than one def-use.
return nullptr;
}
return useDef;
}
MDefinition* MDefinition::maybeMostRecentlyAddedDefUse() const {
MUseDefIterator use(this);
if (!use) {
// No def-uses.
return nullptr;
}
MDefinition* mostRecentUse = use.def();
#ifdef DEBUG
// This function relies on addUse adding new uses to the front of the list.
// Check this invariant by asserting the next few uses are 'older'. Skip this
// for phis because setBackedge can add a new use for a loop phi even if the
// loop body has a use with an id greater than the loop phi's id.
if (!mostRecentUse->isPhi()) {
static constexpr size_t NumUsesToCheck = 3;
use++;
for (size_t i = 0; use && i < NumUsesToCheck; i++, use++) {
MOZ_ASSERT(use.def()->id() <= mostRecentUse->id());
}
}
#endif
return mostRecentUse;
}
void MDefinition::replaceAllUsesWith(MDefinition* dom) {
for (size_t i = 0, e = numOperands(); i < e; ++i) {
getOperand(i)->setImplicitlyUsedUnchecked();
}
justReplaceAllUsesWith(dom);
}
void MDefinition::justReplaceAllUsesWith(MDefinition* dom) {
MOZ_ASSERT(dom != nullptr);
MOZ_ASSERT(dom != this);
// Carry over the fact the value has uses which are no longer inspectable
// with the graph.
if (isImplicitlyUsed()) {
dom->setImplicitlyUsedUnchecked();
}
for (MUseIterator i(usesBegin()), e(usesEnd()); i != e; ++i) {
i->setProducerUnchecked(dom);
}
dom->uses_.takeElements(uses_);
}
bool MDefinition::optimizeOutAllUses(TempAllocator& alloc) {
for (MUseIterator i(usesBegin()), e(usesEnd()); i != e;) {
MUse* use = *i++;
MConstant* constant = use->consumer()->block()->optimizedOutConstant(alloc);
if (!alloc.ensureBallast()) {
return false;
}
// Update the resume point operand to use the optimized-out constant.
use->setProducerUnchecked(constant);
constant->addUseUnchecked(use);
}
// Remove dangling pointers.
this->uses_.clear();
return true;
}
void MDefinition::replaceAllLiveUsesWith(MDefinition* dom) {
for (MUseIterator i(usesBegin()), e(usesEnd()); i != e;) {
MUse* use = *i++;
MNode* consumer = use->consumer();
if (consumer->isResumePoint()) {
continue;
}
if (consumer->isDefinition() &&
consumer->toDefinition()->isRecoveredOnBailout()) {
continue;
}
// Update the operand to use the dominating definition.
use->replaceProducer(dom);
}
}
MConstant* MConstant::New(TempAllocator& alloc, const Value& v) {
return new (alloc) MConstant(alloc, v);
}
MConstant* MConstant::New(TempAllocator::Fallible alloc, const Value& v) {
return new (alloc) MConstant(alloc.alloc, v);
}
MConstant* MConstant::NewFloat32(TempAllocator& alloc, double d) {
MOZ_ASSERT(std::isnan(d) || d == double(float(d)));
return new (alloc) MConstant(float(d));
}
MConstant* MConstant::NewInt64(TempAllocator& alloc, int64_t i) {
return new (alloc) MConstant(MIRType::Int64, i);
}
MConstant* MConstant::NewIntPtr(TempAllocator& alloc, intptr_t i) {
return new (alloc) MConstant(MIRType::IntPtr, i);
}
MConstant* MConstant::New(TempAllocator& alloc, const Value& v, MIRType type) {
if (type == MIRType::Float32) {
return NewFloat32(alloc, v.toNumber());
}
MConstant* res = New(alloc, v);
MOZ_ASSERT(res->type() == type);
return res;
}
MConstant* MConstant::NewObject(TempAllocator& alloc, JSObject* v) {
return new (alloc) MConstant(v);
}
MConstant* MConstant::NewShape(TempAllocator& alloc, Shape* s) {
return new (alloc) MConstant(s);
}
static MIRType MIRTypeFromValue(const js::Value& vp) {
if (vp.isDouble()) {
return MIRType::Double;
}
if (vp.isMagic()) {
switch (vp.whyMagic()) {
case JS_OPTIMIZED_OUT:
return MIRType::MagicOptimizedOut;
case JS_ELEMENTS_HOLE:
return MIRType::MagicHole;
case JS_IS_CONSTRUCTING:
return MIRType::MagicIsConstructing;
case JS_UNINITIALIZED_LEXICAL:
return MIRType::MagicUninitializedLexical;
default:
MOZ_ASSERT_UNREACHABLE("Unexpected magic constant");
}
}
return MIRTypeFromValueType(vp.extractNonDoubleType());
}
MConstant::MConstant(TempAllocator& alloc, const js::Value& vp)
: MNullaryInstruction(classOpcode) {
setResultType(MIRTypeFromValue(vp));
MOZ_ASSERT(payload_.asBits == 0);
switch (type()) {
case MIRType::Undefined:
case MIRType::Null:
break;
case MIRType::Boolean:
payload_.b = vp.toBoolean();
break;
case MIRType::Int32:
payload_.i32 = vp.toInt32();
break;
case MIRType::Double:
payload_.d = vp.toDouble();
break;
case MIRType::String: {
JSString* str = vp.toString();
if (str->isAtomRef()) {
str = str->atom();
}
MOZ_ASSERT(!IsInsideNursery(str));
MOZ_ASSERT(str->isAtom());
payload_.str = vp.toString();
break;
}
case MIRType::Symbol:
payload_.sym = vp.toSymbol();
break;
case MIRType::BigInt:
MOZ_ASSERT(!IsInsideNursery(vp.toBigInt()));
payload_.bi = vp.toBigInt();
break;
case MIRType::Object:
MOZ_ASSERT(!IsInsideNursery(&vp.toObject()));
payload_.obj = &vp.toObject();
break;
case MIRType::MagicOptimizedOut:
case MIRType::MagicHole:
case MIRType::MagicIsConstructing:
case MIRType::MagicUninitializedLexical:
break;
default:
MOZ_CRASH("Unexpected type");
}
setMovable();
}
MConstant::MConstant(JSObject* obj) : MNullaryInstruction(classOpcode) {
MOZ_ASSERT(!IsInsideNursery(obj));
setResultType(MIRType::Object);
payload_.obj = obj;
setMovable();
}
MConstant::MConstant(Shape* shape) : MNullaryInstruction(classOpcode) {
setResultType(MIRType::Shape);
payload_.shape = shape;
setMovable();
}
MConstant::MConstant(float f) : MNullaryInstruction(classOpcode) {
setResultType(MIRType::Float32);
payload_.f = f;
setMovable();
}
MConstant::MConstant(MIRType type, int64_t i)
: MNullaryInstruction(classOpcode) {
MOZ_ASSERT(type == MIRType::Int64 || type == MIRType::IntPtr);
setResultType(type);
if (type == MIRType::Int64) {
payload_.i64 = i;
} else {
payload_.iptr = i;
}
setMovable();
}
#ifdef DEBUG
void MConstant::assertInitializedPayload() const {
// valueHash() and equals() expect the unused payload bits to be
// initialized to zero. Assert this in debug builds.
switch (type()) {
case MIRType::Int32:
case MIRType::Float32:
# if MOZ_LITTLE_ENDIAN()
MOZ_ASSERT((payload_.asBits >> 32) == 0);
# else
MOZ_ASSERT((payload_.asBits << 32) == 0);
# endif
break;
case MIRType::Boolean:
# if MOZ_LITTLE_ENDIAN()
MOZ_ASSERT((payload_.asBits >> 1) == 0);
# else
MOZ_ASSERT((payload_.asBits & ~(1ULL << 56)) == 0);
# endif
break;
case MIRType::Double:
case MIRType::Int64:
break;
case MIRType::String:
case MIRType::Object:
case MIRType::Symbol:
case MIRType::BigInt:
case MIRType::IntPtr:
case MIRType::Shape:
# if MOZ_LITTLE_ENDIAN()
MOZ_ASSERT_IF(JS_BITS_PER_WORD == 32, (payload_.asBits >> 32) == 0);
# else
MOZ_ASSERT_IF(JS_BITS_PER_WORD == 32, (payload_.asBits << 32) == 0);
# endif
break;
default:
MOZ_ASSERT(IsNullOrUndefined(type()) || IsMagicType(type()));
MOZ_ASSERT(payload_.asBits == 0);
break;
}
}
#endif
static HashNumber ConstantValueHash(MIRType type, uint64_t payload) {
// Build a 64-bit value holding both the payload and the type.
static const size_t TypeBits = 8;
static const size_t TypeShift = 64 - TypeBits;
MOZ_ASSERT(uintptr_t(type) <= (1 << TypeBits) - 1);
uint64_t bits = (uint64_t(type) << TypeShift) ^ payload;
// Fold all 64 bits into the 32-bit result. It's tempting to just discard
// half of the bits, as this is just a hash, however there are many common
// patterns of values where only the low or the high bits vary, so
// discarding either side would lead to excessive hash collisions.
return (HashNumber)bits ^ (HashNumber)(bits >> 32);
}
HashNumber MConstant::valueHash() const {
static_assert(sizeof(Payload) == sizeof(uint64_t),
"Code below assumes payload fits in 64 bits");
assertInitializedPayload();
return ConstantValueHash(type(), payload_.asBits);
}
HashNumber MConstantProto::valueHash() const {
HashNumber hash = protoObject()->valueHash();
const MDefinition* receiverObject = getReceiverObject();
if (receiverObject) {
hash = addU32ToHash(hash, receiverObject->id());
}
return hash;
}
bool MConstant::congruentTo(const MDefinition* ins) const {
return ins->isConstant() && equals(ins->toConstant());
}
#ifdef JS_JITSPEW
void MConstant::printOpcode(GenericPrinter& out) const {
PrintOpcodeName(out, op());
out.printf(" ");
switch (type()) {
case MIRType::Undefined:
out.printf("undefined");
break;
case MIRType::Null:
out.printf("null");
break;
case MIRType::Boolean:
out.printf(toBoolean() ? "true" : "false");
break;
case MIRType::Int32:
out.printf("0x%x", uint32_t(toInt32()));
break;
case MIRType::Int64:
out.printf("0x%" PRIx64, uint64_t(toInt64()));
break;
case MIRType::IntPtr:
out.printf("0x%" PRIxPTR, uintptr_t(toIntPtr()));
break;
case MIRType::Double:
out.printf("%.16g", toDouble());
break;
case MIRType::Float32: {
float val = toFloat32();
out.printf("%.16g", val);
break;
}
case MIRType::Object:
if (toObject().is<JSFunction>()) {
JSFunction* fun = &toObject().as<JSFunction>();
if (fun->maybePartialDisplayAtom()) {
out.put("function ");
EscapedStringPrinter(out, fun->maybePartialDisplayAtom(), 0);
} else {
out.put("unnamed function");
}
if (fun->hasBaseScript()) {
BaseScript* script = fun->baseScript();
out.printf(" (%s:%u)", script->filename() ? script->filename() : "",
script->lineno());
}
out.printf(" at %p", (void*)fun);
break;
}
out.printf("object %p (%s)", (void*)&toObject(),
toObject().getClass()->name);
break;
case MIRType::Symbol:
out.printf("symbol at %p", (void*)toSymbol());
break;
case MIRType::BigInt:
out.printf("BigInt at %p", (void*)toBigInt());
break;
case MIRType::String:
out.printf("string %p", (void*)toString());
break;
case MIRType::Shape:
out.printf("shape at %p", (void*)toShape());
break;
case MIRType::MagicHole:
out.printf("magic hole");
break;
case MIRType::MagicIsConstructing:
out.printf("magic is-constructing");
break;
case MIRType::MagicOptimizedOut:
out.printf("magic optimized-out");
break;
case MIRType::MagicUninitializedLexical:
out.printf("magic uninitialized-lexical");
break;
default:
MOZ_CRASH("unexpected type");
}
}
#endif
bool MConstant::canProduceFloat32() const {
if (!isTypeRepresentableAsDouble()) {
return false;
}
if (type() == MIRType::Int32) {
return IsFloat32Representable(static_cast<double>(toInt32()));
}
if (type() == MIRType::Double) {
return IsFloat32Representable(toDouble());
}
MOZ_ASSERT(type() == MIRType::Float32);
return true;
}
Value MConstant::toJSValue() const {
// Wasm has types like int64 that cannot be stored as js::Value. It also
// doesn't want the NaN canonicalization enforced by js::Value.
MOZ_ASSERT(!IsCompilingWasm());
switch (type()) {
case MIRType::Undefined:
return UndefinedValue();
case MIRType::Null:
return NullValue();
case MIRType::Boolean:
return BooleanValue(toBoolean());
case MIRType::Int32:
return Int32Value(toInt32());
case MIRType::Double:
return DoubleValue(toDouble());
case MIRType::Float32:
return Float32Value(toFloat32());
case MIRType::String:
return StringValue(toString());
case MIRType::Symbol:
return SymbolValue(toSymbol());
case MIRType::BigInt:
return BigIntValue(toBigInt());
case MIRType::Object:
return ObjectValue(toObject());
case MIRType::Shape:
return PrivateGCThingValue(toShape());
case MIRType::MagicOptimizedOut:
return MagicValue(JS_OPTIMIZED_OUT);
case MIRType::MagicHole:
return MagicValue(JS_ELEMENTS_HOLE);
case MIRType::MagicIsConstructing:
return MagicValue(JS_IS_CONSTRUCTING);
case MIRType::MagicUninitializedLexical:
return MagicValue(JS_UNINITIALIZED_LEXICAL);
default:
MOZ_CRASH("Unexpected type");
}
}
bool MConstant::valueToBoolean(bool* res) const {
switch (type()) {
case MIRType::Boolean:
*res = toBoolean();
return true;
case MIRType::Int32:
*res = toInt32() != 0;
return true;
case MIRType::Int64:
*res = toInt64() != 0;
return true;
case MIRType::Double:
*res = !std::isnan(toDouble()) && toDouble() != 0.0;
return true;
case MIRType::Float32:
*res = !std::isnan(toFloat32()) && toFloat32() != 0.0f;
return true;
case MIRType::Null:
case MIRType::Undefined:
*res = false;
return true;
case MIRType::Symbol:
*res = true;
return true;
case MIRType::BigInt:
*res = !toBigInt()->isZero();
return true;
case MIRType::String:
*res = toString()->length() != 0;
return true;
case MIRType::Object:
// TODO(Warp): Lazy groups have been removed.
// We have to call EmulatesUndefined but that reads obj->group->clasp
// and so it's racy when the object has a lazy group. The main callers
// of this (MTest, MNot) already know how to fold the object case, so
// just give up.
return false;
default:
MOZ_ASSERT(IsMagicType(type()));
return false;
}
}
HashNumber MWasmFloatConstant::valueHash() const {
#ifdef ENABLE_WASM_SIMD
return ConstantValueHash(type(), u.bits_[0] ^ u.bits_[1]);
#else
return ConstantValueHash(type(), u.bits_[0]);
#endif
}
bool MWasmFloatConstant::congruentTo(const MDefinition* ins) const {
return ins->isWasmFloatConstant() && type() == ins->type() &&
#ifdef ENABLE_WASM_SIMD
u.bits_[1] == ins->toWasmFloatConstant()->u.bits_[1] &&
#endif
u.bits_[0] == ins->toWasmFloatConstant()->u.bits_[0];
}
HashNumber MWasmNullConstant::valueHash() const {
return ConstantValueHash(MIRType::WasmAnyRef, 0);
}
#ifdef JS_JITSPEW
void MControlInstruction::printOpcode(GenericPrinter& out) const {
MDefinition::printOpcode(out);
for (size_t j = 0; j < numSuccessors(); j++) {
if (getSuccessor(j)) {
out.printf(" block%u", getSuccessor(j)->id());
} else {
out.printf(" (null-to-be-patched)");
}
}
}
void MCompare::printOpcode(GenericPrinter& out) const {
MDefinition::printOpcode(out);
out.printf(" %s", CodeName(jsop()));
}
void MTypeOfIs::printOpcode(GenericPrinter& out) const {
MDefinition::printOpcode(out);
out.printf(" %s", CodeName(jsop()));
const char* name = "";
switch (jstype()) {
case JSTYPE_UNDEFINED:
name = "undefined";
break;
case JSTYPE_OBJECT:
name = "object";
break;
case JSTYPE_FUNCTION:
name = "function";
break;
case JSTYPE_STRING:
name = "string";
break;
case JSTYPE_NUMBER:
name = "number";
break;
case JSTYPE_BOOLEAN:
name = "boolean";
break;
case JSTYPE_SYMBOL:
name = "symbol";
break;
case JSTYPE_BIGINT:
name = "bigint";
break;
# ifdef ENABLE_RECORD_TUPLE
case JSTYPE_RECORD:
case JSTYPE_TUPLE:
# endif
case JSTYPE_LIMIT:
MOZ_CRASH("Unexpected type");
}
out.printf(" '%s'", name);
}
void MLoadUnboxedScalar::printOpcode(GenericPrinter& out) const {
MDefinition::printOpcode(out);
out.printf(" %s", Scalar::name(storageType()));
}
void MLoadDataViewElement::printOpcode(GenericPrinter& out) const {
MDefinition::printOpcode(out);
out.printf(" %s", Scalar::name(storageType()));
}
void MAssertRange::printOpcode(GenericPrinter& out) const {
MDefinition::printOpcode(out);
out.put(" ");
assertedRange()->dump(out);
}
void MNearbyInt::printOpcode(GenericPrinter& out) const {
MDefinition::printOpcode(out);
const char* roundingModeStr = nullptr;
switch (roundingMode_) {
case RoundingMode::Up:
roundingModeStr = "(up)";
break;
case RoundingMode::Down:
roundingModeStr = "(down)";
break;
case RoundingMode::NearestTiesToEven:
roundingModeStr = "(nearest ties even)";
break;
case RoundingMode::TowardsZero:
roundingModeStr = "(towards zero)";
break;
}
out.printf(" %s", roundingModeStr);
}
#endif
AliasSet MRandom::getAliasSet() const { return AliasSet::Store(AliasSet::RNG); }
MDefinition* MSign::foldsTo(TempAllocator& alloc) {
MDefinition* input = getOperand(0);
if (!input->isConstant() ||
!input->toConstant()->isTypeRepresentableAsDouble()) {
return this;
}
double in = input->toConstant()->numberToDouble();
double out = js::math_sign_impl(in);
if (type() == MIRType::Int32) {
// Decline folding if this is an int32 operation, but the result type
// isn't an int32.
Value outValue = NumberValue(out);
if (!outValue.isInt32()) {
return this;
}
return MConstant::New(alloc, outValue);
}
return MConstant::New(alloc, DoubleValue(out));
}
const char* MMathFunction::FunctionName(UnaryMathFunction function) {
return GetUnaryMathFunctionName(function);
}
#ifdef JS_JITSPEW
void MMathFunction::printOpcode(GenericPrinter& out) const {
MDefinition::printOpcode(out);
out.printf(" %s", FunctionName(function()));
}
#endif
MDefinition* MMathFunction::foldsTo(TempAllocator& alloc) {
MDefinition* input = getOperand(0);
if (!input->isConstant() ||
!input->toConstant()->isTypeRepresentableAsDouble()) {
return this;
}
UnaryMathFunctionType funPtr = GetUnaryMathFunctionPtr(function());
double in = input->toConstant()->numberToDouble();
// The function pointer call can't GC.
JS::AutoSuppressGCAnalysis nogc;
double out = funPtr(in);
if (input->type() == MIRType::Float32) {
return MConstant::NewFloat32(alloc, out);
}
return MConstant::New(alloc, DoubleValue(out));
}
MDefinition* MAtomicIsLockFree::foldsTo(TempAllocator& alloc) {
MDefinition* input = getOperand(0);
if (!input->isConstant() || input->type() != MIRType::Int32) {
return this;
}
int32_t i = input->toConstant()->toInt32();
return MConstant::New(alloc, BooleanValue(AtomicOperations::isLockfreeJS(i)));
}
// Define |THIS_SLOT| as part of this translation unit, as it is used to
// specialized the parameterized |New| function calls introduced by
// TRIVIAL_NEW_WRAPPERS.
const int32_t MParameter::THIS_SLOT;
#ifdef JS_JITSPEW
void MParameter::printOpcode(GenericPrinter& out) const {
PrintOpcodeName(out, op());
if (index() == THIS_SLOT) {
out.printf(" THIS_SLOT");
} else {
out.printf(" %d", index());
}
}
#endif
HashNumber MParameter::valueHash() const {
HashNumber hash = MDefinition::valueHash();
hash = addU32ToHash(hash, index_);
return hash;
}
bool MParameter::congruentTo(const MDefinition* ins) const {
if (!ins->isParameter()) {
return false;
}
return ins->toParameter()->index() == index_;
}
WrappedFunction::WrappedFunction(JSFunction* nativeFun, uint16_t nargs,
FunctionFlags flags)
: nativeFun_(nativeFun), nargs_(nargs), flags_(flags) {
MOZ_ASSERT_IF(nativeFun, isNativeWithoutJitEntry());
#ifdef DEBUG
// If we are not running off-main thread we can assert that the
// metadata is consistent.
if (!CanUseExtraThreads() && nativeFun) {
MOZ_ASSERT(nativeFun->nargs() == nargs);
MOZ_ASSERT(nativeFun->isNativeWithoutJitEntry() ==
isNativeWithoutJitEntry());
MOZ_ASSERT(nativeFun->hasJitEntry() == hasJitEntry());
MOZ_ASSERT(nativeFun->isConstructor() == isConstructor());
MOZ_ASSERT(nativeFun->isClassConstructor() == isClassConstructor());
}
#endif
}
MCall* MCall::New(TempAllocator& alloc, WrappedFunction* target, size_t maxArgc,
size_t numActualArgs, bool construct, bool ignoresReturnValue,
bool isDOMCall, mozilla::Maybe<DOMObjectKind> objectKind) {
MOZ_ASSERT(isDOMCall == objectKind.isSome());
MOZ_ASSERT(maxArgc >= numActualArgs);
MCall* ins;
if (isDOMCall) {
MOZ_ASSERT(!construct);
ins = new (alloc) MCallDOMNative(target, numActualArgs, *objectKind);
} else {
ins =
new (alloc) MCall(target, numActualArgs, construct, ignoresReturnValue);
}
if (!ins->init(alloc, maxArgc + NumNonArgumentOperands)) {
return nullptr;
}
return ins;
}
AliasSet MCallDOMNative::getAliasSet() const {
const JSJitInfo* jitInfo = getJitInfo();
// If we don't know anything about the types of our arguments, we have to
// assume that type-coercions can have side-effects, so we need to alias
// everything.
if (jitInfo->aliasSet() == JSJitInfo::AliasEverything ||
!jitInfo->isTypedMethodJitInfo()) {
return AliasSet::Store(AliasSet::Any);
}
uint32_t argIndex = 0;
const JSTypedMethodJitInfo* methodInfo =
reinterpret_cast<const JSTypedMethodJitInfo*>(jitInfo);
for (const JSJitInfo::ArgType* argType = methodInfo->argTypes;
*argType != JSJitInfo::ArgTypeListEnd; ++argType, ++argIndex) {
if (argIndex >= numActualArgs()) {
// Passing through undefined can't have side-effects
continue;
}
// getArg(0) is "this", so skip it
MDefinition* arg = getArg(argIndex + 1);
MIRType actualType = arg->type();
// The only way to reliably avoid side-effects given the information we
// have here is if we're passing in a known primitive value to an
// argument that expects a primitive value.
//
// XXXbz maybe we need to communicate better information. For example,
// a sequence argument will sort of unavoidably have side effects, while
// a typed array argument won't have any, but both are claimed to be
// JSJitInfo::Object. But if we do that, we need to watch out for our
// movability/DCE-ability bits: if we have an arg type that can reliably
// throw an exception on conversion, that might not affect our alias set
// per se, but it should prevent us being moved or DCE-ed, unless we
// know the incoming things match that arg type and won't throw.
//
if ((actualType == MIRType::Value || actualType == MIRType::Object) ||
(*argType & JSJitInfo::Object)) {
return AliasSet::Store(AliasSet::Any);
}
}
// We checked all the args, and they check out. So we only alias DOM
// mutations or alias nothing, depending on the alias set in the jitinfo.
if (jitInfo->aliasSet() == JSJitInfo::AliasNone) {
return AliasSet::None();
}
MOZ_ASSERT(jitInfo->aliasSet() == JSJitInfo::AliasDOMSets);
return AliasSet::Load(AliasSet::DOMProperty);
}
void MCallDOMNative::computeMovable() {
// We are movable if the jitinfo says we can be and if we're also not
// effectful. The jitinfo can't check for the latter, since it depends on
// the types of our arguments.
const JSJitInfo* jitInfo = getJitInfo();
MOZ_ASSERT_IF(jitInfo->isMovable,
jitInfo->aliasSet() != JSJitInfo::AliasEverything);
if (jitInfo->isMovable && !isEffectful()) {
setMovable();
}
}
bool MCallDOMNative::congruentTo(const MDefinition* ins) const {
if (!isMovable()) {
return false;
}
if (!ins->isCall()) {
return false;
}
const MCall* call = ins->toCall();
if (!call->isCallDOMNative()) {
return false;
}
if (getSingleTarget() != call->getSingleTarget()) {
return false;
}
if (isConstructing() != call->isConstructing()) {
return false;
}
if (numActualArgs() != call->numActualArgs()) {
return false;
}
if (!congruentIfOperandsEqual(call)) {
return false;
}
// The other call had better be movable at this point!
MOZ_ASSERT(call->isMovable());
return true;
}
const JSJitInfo* MCallDOMNative::getJitInfo() const {
MOZ_ASSERT(getSingleTarget()->hasJitInfo());
return getSingleTarget()->jitInfo();
}
MCallClassHook* MCallClassHook::New(TempAllocator& alloc, JSNative target,
uint32_t argc, bool constructing) {
auto* ins = new (alloc) MCallClassHook(target, constructing);
// Add callee + |this| + (if constructing) newTarget.
uint32_t numOperands = 2 + argc + constructing;
if (!ins->init(alloc, numOperands)) {
return nullptr;
}
return ins;
}
MDefinition* MStringLength::foldsTo(TempAllocator& alloc) {
if (string()->isConstant()) {
JSString* str = string()->toConstant()->toString();
return MConstant::New(alloc, Int32Value(str->length()));
}
// MFromCharCode returns a one-element string.
if (string()->isFromCharCode()) {
return MConstant::New(alloc, Int32Value(1));
}
return this;
}
MDefinition* MConcat::foldsTo(TempAllocator& alloc) {
if (lhs()->isConstant() && lhs()->toConstant()->toString()->empty()) {
return rhs();
}
if (rhs()->isConstant() && rhs()->toConstant()->toString()->empty()) {
return lhs();
}
return this;
}
MDefinition* MStringConvertCase::foldsTo(TempAllocator& alloc) {
MDefinition* string = this->string();
// Handle the pattern |str[idx].toUpperCase()| and simplify it from
// |StringConvertCase(FromCharCode(CharCodeAt(str, idx)))| to just
// |CharCodeConvertCase(CharCodeAt(str, idx))|.
if (string->isFromCharCode()) {
auto* charCode = string->toFromCharCode()->code();
auto mode = mode_ == Mode::LowerCase ? MCharCodeConvertCase::LowerCase
: MCharCodeConvertCase::UpperCase;
return MCharCodeConvertCase::New(alloc, charCode, mode);
}
// Handle the pattern |num.toString(base).toUpperCase()| and simplify it to
// directly return the string representation in the correct case.
if (string->isInt32ToStringWithBase()) {
auto* toString = string->toInt32ToStringWithBase();
bool lowerCase = mode_ == Mode::LowerCase;
if (toString->lowerCase() == lowerCase) {
return toString;
}
return MInt32ToStringWithBase::New(alloc, toString->input(),
toString->base(), lowerCase);
}
return this;
}
static bool IsSubstrTo(MSubstr* substr, int32_t len) {
// We want to match this pattern:
//
// Substr(string, Constant(0), Min(Constant(length), StringLength(string)))
//
// which is generated for the self-hosted `String.p.{substring,slice,substr}`
// functions when called with constants `start` and `end` parameters.
auto isConstantZero = [](auto* def) {
return def->isConstant() && def->toConstant()->isInt32(0);
};
if (!isConstantZero(substr->begin())) {
return false;
}
auto* length = substr->length();
if (length->isBitOr()) {
// Unnecessary bit-ops haven't yet been removed.
auto* bitOr = length->toBitOr();
if (isConstantZero(bitOr->lhs())) {
length = bitOr->rhs();
} else if (isConstantZero(bitOr->rhs())) {
length = bitOr->lhs();
}
}
if (!length->isMinMax() || length->toMinMax()->isMax()) {
return false;
}
auto* min = length->toMinMax();
if (!min->lhs()->isConstant() && !min->rhs()->isConstant()) {
return false;
}
auto* minConstant = min->lhs()->isConstant() ? min->lhs()->toConstant()
: min->rhs()->toConstant();
auto* minOperand = min->lhs()->isConstant() ? min->rhs() : min->lhs();
if (!minOperand->isStringLength() ||
minOperand->toStringLength()->string() != substr->string()) {
return false;
}
// Ensure |len| matches the substring's length.
return minConstant->isInt32(len);
}
MDefinition* MSubstr::foldsTo(TempAllocator& alloc) {
// Fold |str.substring(0, 1)| to |str.charAt(0)|.
if (!IsSubstrTo(this, 1)) {
return this;
}
auto* charCode = MCharCodeAtOrNegative::New(alloc, string(), begin());
block()->insertBefore(this, charCode);
return MFromCharCodeEmptyIfNegative::New(alloc, charCode);
}
MDefinition* MCharCodeAt::foldsTo(TempAllocator& alloc) {
MDefinition* string = this->string();
if (!string->isConstant() && !string->isFromCharCode()) {
return this;
}
MDefinition* index = this->index();
if (index->isSpectreMaskIndex()) {
index = index->toSpectreMaskIndex()->index();
}
if (!index->isConstant()) {
return this;
}
int32_t idx = index->toConstant()->toInt32();
// Handle the pattern |s[idx].charCodeAt(0)|.
if (string->isFromCharCode()) {
if (idx != 0) {
return this;
}
// Simplify |CharCodeAt(FromCharCode(CharCodeAt(s, idx)), 0)| to just
// |CharCodeAt(s, idx)|.
auto* charCode = string->toFromCharCode()->code();
if (!charCode->isCharCodeAt()) {
return this;
}
return charCode;
}
JSLinearString* str = &string->toConstant()->toString()->asLinear();
if (idx < 0 || uint32_t(idx) >= str->length()) {
return this;
}
char16_t ch = str->latin1OrTwoByteChar(idx);
return MConstant::New(alloc, Int32Value(ch));
}
MDefinition* MCodePointAt::foldsTo(TempAllocator& alloc) {
MDefinition* string = this->string();
if (!string->isConstant() && !string->isFromCharCode()) {
return this;
}
MDefinition* index = this->index();
if (index->isSpectreMaskIndex()) {
index = index->toSpectreMaskIndex()->index();
}
if (!index->isConstant()) {
return this;
}
int32_t idx = index->toConstant()->toInt32();
// Handle the pattern |s[idx].codePointAt(0)|.
if (string->isFromCharCode()) {
if (idx != 0) {
return this;
}
// Simplify |CodePointAt(FromCharCode(CharCodeAt(s, idx)), 0)| to just
// |CharCodeAt(s, idx)|.
auto* charCode = string->toFromCharCode()->code();
if (!charCode->isCharCodeAt()) {
return this;
}
return charCode;
}
JSLinearString* str = &string->toConstant()->toString()->asLinear();
if (idx < 0 || uint32_t(idx) >= str->length()) {
return this;
}
char32_t first = str->latin1OrTwoByteChar(idx);
if (unicode::IsLeadSurrogate(first) && uint32_t(idx) + 1 < str->length()) {
char32_t second = str->latin1OrTwoByteChar(idx + 1);
if (unicode::IsTrailSurrogate(second)) {
first = unicode::UTF16Decode(first, second);
}
}
return MConstant::New(alloc, Int32Value(first));
}
MDefinition* MToRelativeStringIndex::foldsTo(TempAllocator& alloc) {
MDefinition* index = this->index();
MDefinition* length = this->length();
if (!index->isConstant()) {
return this;
}
if (!length->isStringLength() && !length->isConstant()) {
return this;
}
MOZ_ASSERT_IF(length->isConstant(), length->toConstant()->toInt32() >= 0);
int32_t relativeIndex = index->toConstant()->toInt32();
if (relativeIndex >= 0) {
return index;
}
// Safe to truncate because |length| is never negative.
return MAdd::New(alloc, index, length, TruncateKind::Truncate);
}
template <size_t Arity>
[[nodiscard]] static bool EnsureFloatInputOrConvert(
MAryInstruction<Arity>* owner, TempAllocator& alloc) {
MOZ_ASSERT(!IsFloatingPointType(owner->type()),
"Floating point types must check consumers");
if (AllOperandsCanProduceFloat32(owner)) {
return true;
}
ConvertOperandsToDouble(owner, alloc);
return false;
}
template <size_t Arity>
[[nodiscard]] static bool EnsureFloatConsumersAndInputOrConvert(
MAryInstruction<Arity>* owner, TempAllocator& alloc) {
MOZ_ASSERT(IsFloatingPointType(owner->type()),
"Integer types don't need to check consumers");
if (AllOperandsCanProduceFloat32(owner) &&
CheckUsesAreFloat32Consumers(owner)) {
return true;
}
ConvertOperandsToDouble(owner, alloc);
return false;
}
void MFloor::trySpecializeFloat32(TempAllocator& alloc) {
MOZ_ASSERT(type() == MIRType::Int32);
if (EnsureFloatInputOrConvert(this, alloc)) {
specialization_ = MIRType::Float32;
}
}
void MCeil::trySpecializeFloat32(TempAllocator& alloc) {
MOZ_ASSERT(type() == MIRType::Int32);
if (EnsureFloatInputOrConvert(this, alloc)) {
specialization_ = MIRType::Float32;
}
}
void MRound::trySpecializeFloat32(TempAllocator& alloc) {
MOZ_ASSERT(type() == MIRType::Int32);
if (EnsureFloatInputOrConvert(this, alloc)) {
specialization_ = MIRType::Float32;
}
}
void MTrunc::trySpecializeFloat32(TempAllocator& alloc) {
MOZ_ASSERT(type() == MIRType::Int32);
if (EnsureFloatInputOrConvert(this, alloc)) {
specialization_ = MIRType::Float32;
}
}
void MNearbyInt::trySpecializeFloat32(TempAllocator& alloc) {
if (EnsureFloatConsumersAndInputOrConvert(this, alloc)) {
specialization_ = MIRType::Float32;
setResultType(MIRType::Float32);
}
}
MGoto* MGoto::New(TempAllocator& alloc, MBasicBlock* target) {
return new (alloc) MGoto(target);
}
MGoto* MGoto::New(TempAllocator::Fallible alloc, MBasicBlock* target) {
MOZ_ASSERT(target);
return new (alloc) MGoto(target);
}
MGoto* MGoto::New(TempAllocator& alloc) { return new (alloc) MGoto(nullptr); }
MDefinition* MBox::foldsTo(TempAllocator& alloc) {
if (input()->isUnbox()) {
return input()->toUnbox()->input();
}
return this;
}
#ifdef JS_JITSPEW
void MUnbox::printOpcode(GenericPrinter& out) const {
PrintOpcodeName(out, op());
out.printf(" ");
getOperand(0)->printName(out);
out.printf(" ");
switch (type()) {
case MIRType::Int32:
out.printf("to Int32");
break;
case MIRType::Double:
out.printf("to Double");
break;
case MIRType::Boolean:
out.printf("to Boolean");
break;
case MIRType::String:
out.printf("to String");
break;
case MIRType::Symbol:
out.printf("to Symbol");
break;
case MIRType::BigInt:
out.printf("to BigInt");
break;
case MIRType::Object:
out.printf("to Object");
break;
default:
break;
}
switch (mode()) {
case Fallible:
out.printf(" (fallible)");
break;
case Infallible:
out.printf(" (infallible)");
break;
default:
break;
}
}
#endif
MDefinition* MUnbox::foldsTo(TempAllocator& alloc) {
if (input()->isBox()) {
MDefinition* unboxed = input()->toBox()->input();
// Fold MUnbox(MBox(x)) => x if types match.
if (unboxed->type() == type()) {
if (fallible()) {
unboxed->setImplicitlyUsedUnchecked();
}
return unboxed;
}
// Fold MUnbox(MBox(x)) => MToDouble(x) if possible.
if (type() == MIRType::Double &&
IsTypeRepresentableAsDouble(unboxed->type())) {
if (unboxed->isConstant()) {
return MConstant::New(
alloc, DoubleValue(unboxed->toConstant()->numberToDouble()));
}
return MToDouble::New(alloc, unboxed);
}
// MUnbox<Int32>(MBox<Double>(x)) will always fail, even if x can be
// represented as an Int32. Fold to avoid unnecessary bailouts.
if (type() == MIRType::Int32 && unboxed->type() == MIRType::Double) {
auto* folded = MToNumberInt32::New(alloc, unboxed,
IntConversionInputKind::NumbersOnly);
folded->setGuard();
return folded;
}
}
return this;
}
#ifdef DEBUG
void MPhi::assertLoopPhi() const {
// getLoopPredecessorOperand and getLoopBackedgeOperand rely on these
// predecessors being at known indices.
if (block()->numPredecessors() == 2) {
MBasicBlock* pred = block()->getPredecessor(0);
MBasicBlock* back = block()->getPredecessor(1);
MOZ_ASSERT(pred == block()->loopPredecessor());
MOZ_ASSERT(pred->successorWithPhis() == block());
MOZ_ASSERT(pred->positionInPhiSuccessor() == 0);
MOZ_ASSERT(back == block()->backedge());
MOZ_ASSERT(back->successorWithPhis() == block());
MOZ_ASSERT(back->positionInPhiSuccessor() == 1);
} else {
// After we remove fake loop predecessors for loop headers that
// are only reachable via OSR, the only predecessor is the
// loop backedge.
MOZ_ASSERT(block()->numPredecessors() == 1);
MOZ_ASSERT(block()->graph().osrBlock());
MOZ_ASSERT(!block()->graph().canBuildDominators());
MBasicBlock* back = block()->getPredecessor(0);
MOZ_ASSERT(back == block()->backedge());
MOZ_ASSERT(back->successorWithPhis() == block());
MOZ_ASSERT(back->positionInPhiSuccessor() == 0);
}
}
#endif
MDefinition* MPhi::getLoopPredecessorOperand() const {
// This should not be called after removing fake loop predecessors.
MOZ_ASSERT(block()->numPredecessors() == 2);
assertLoopPhi();
return getOperand(0);
}
MDefinition* MPhi::getLoopBackedgeOperand() const {
assertLoopPhi();
uint32_t idx = block()->numPredecessors() == 2 ? 1 : 0;
return getOperand(idx);
}
void MPhi::removeOperand(size_t index) {
MOZ_ASSERT(index < numOperands());
MOZ_ASSERT(getUseFor(index)->index() == index);
MOZ_ASSERT(getUseFor(index)->consumer() == this);
// If we have phi(..., a, b, c, d, ..., z) and we plan
// on removing a, then first shift downward so that we have
// phi(..., b, c, d, ..., z, z):
MUse* p = inputs_.begin() + index;
MUse* e = inputs_.end();
p->producer()->removeUse(p);
for (; p < e - 1; ++p) {
MDefinition* producer = (p + 1)->producer();
p->setProducerUnchecked(producer);
producer->replaceUse(p + 1, p);
}
// truncate the inputs_ list:
inputs_.popBack();
}
void MPhi::removeAllOperands() {
for (MUse& p : inputs_) {
p.producer()->removeUse(&p);
}
inputs_.clear();
}
MDefinition* MPhi::foldsTernary(TempAllocator& alloc) {
/* Look if this MPhi is a ternary construct.
* This is a very loose term as it actually only checks for
*
* MTest X
* / \
* ... ...
* \ /
* MPhi X Y
*
* Which we will simply call:
* x ? x : y or x ? y : x
*/
if (numOperands() != 2) {
return nullptr;
}
MOZ_ASSERT(block()->numPredecessors() == 2);
MBasicBlock* pred = block()->immediateDominator();
if (!pred || !pred->lastIns()->isTest()) {
return nullptr;
}
MTest* test = pred->lastIns()->toTest();
// True branch may only dominate one edge of MPhi.
if (test->ifTrue()->dominates(block()->getPredecessor(0)) ==
test->ifTrue()->dominates(block()->getPredecessor(1))) {
return nullptr;
}
// False branch may only dominate one edge of MPhi.
if (test->ifFalse()->dominates(block()->getPredecessor(0)) ==
test->ifFalse()->dominates(block()->getPredecessor(1))) {
return nullptr;
}
// True and false branch must dominate different edges of MPhi.
if (test->ifTrue()->dominates(block()->getPredecessor(0)) ==
test->ifFalse()->dominates(block()->getPredecessor(0))) {
return nullptr;
}
// We found a ternary construct.
bool firstIsTrueBranch =
test->ifTrue()->dominates(block()->getPredecessor(0));
MDefinition* trueDef = firstIsTrueBranch ? getOperand(0) : getOperand(1);
MDefinition* falseDef = firstIsTrueBranch ? getOperand(1) : getOperand(0);
// Accept either
// testArg ? testArg : constant or
// testArg ? constant : testArg
if (!trueDef->isConstant() && !falseDef->isConstant()) {
return nullptr;
}
MConstant* c =
trueDef->isConstant() ? trueDef->toConstant() : falseDef->toConstant();
MDefinition* testArg = (trueDef == c) ? falseDef : trueDef;
if (testArg != test->input()) {
return nullptr;
}
// This check should be a tautology, except that the constant might be the
// result of the removal of a branch. In such case the domination scope of
// the block which is holding the constant might be incomplete. This
// condition is used to prevent doing this optimization based on incomplete
// information.
//
// As GVN removed a branch, it will update the dominations rules before
// trying to fold this MPhi again. Thus, this condition does not inhibit
// this optimization.
MBasicBlock* truePred = block()->getPredecessor(firstIsTrueBranch ? 0 : 1);
MBasicBlock* falsePred = block()->getPredecessor(firstIsTrueBranch ? 1 : 0);
if (!trueDef->block()->dominates(truePred) ||
!falseDef->block()->dominates(falsePred)) {
return nullptr;
}
// If testArg is an int32 type we can:
// - fold testArg ? testArg : 0 to testArg
// - fold testArg ? 0 : testArg to 0
if (testArg->type() == MIRType::Int32 && c->numberToDouble() == 0) {
testArg->setGuardRangeBailoutsUnchecked();
// When folding to the constant we need to hoist it.
if (trueDef == c && !c->block()->dominates(block())) {
c->block()->moveBefore(pred->lastIns(), c);
}
return trueDef;
}
// If testArg is an double type we can:
// - fold testArg ? testArg : 0.0 to MNaNToZero(testArg)
if (testArg->type() == MIRType::Double &&
mozilla::IsPositiveZero(c->numberToDouble()) && c != trueDef) {
MNaNToZero* replace = MNaNToZero::New(alloc, testArg);
test->block()->insertBefore(test, replace);
return replace;
}
// If testArg is a string type we can:
// - fold testArg ? testArg : "" to testArg
// - fold testArg ? "" : testArg to ""
if (testArg->type() == MIRType::String &&
c->toString() == GetJitContext()->runtime->emptyString()) {
// When folding to the constant we need to hoist it.
if (trueDef == c && !c->block()->dominates(block())) {
c->block()->moveBefore(pred->lastIns(), c);
}
return trueDef;
}
return nullptr;
}
MDefinition* MPhi::operandIfRedundant() {
if (inputs_.length() == 0) {
return nullptr;
}
// If this phi is redundant (e.g., phi(a,a) or b=phi(a,this)),
// returns the operand that it will always be equal to (a, in
// those two cases).
MDefinition* first = getOperand(0);
for (size_t i = 1, e = numOperands(); i < e; i++) {
MDefinition* op = getOperand(i);
if (op != first && op != this) {
return nullptr;
}
}
return first;
}
MDefinition* MPhi::foldsTo(TempAllocator& alloc) {
if (MDefinition* def = operandIfRedundant()) {
return def;
}
if (MDefinition* def = foldsTernary(alloc)) {
return def;
}
return this;
}
bool MPhi::congruentTo(const MDefinition* ins) const {
if (!ins->isPhi()) {
return false;
}
// Phis in different blocks may have different control conditions.
// For example, these phis:
//
// if (p)
// goto a
// a:
// t = phi(x, y)
//
// if (q)
// goto b
// b:
// s = phi(x, y)
//
// have identical operands, but they are not equvalent because t is
// effectively p?x:y and s is effectively q?x:y.
//
// For now, consider phis in different blocks incongruent.
if (ins->block() != block()) {
return false;
}
return congruentIfOperandsEqual(ins);
}
void MPhi::updateForReplacement(MPhi* other) {
// This function is called to fix the current Phi flags using it as a
// replacement of the other Phi instruction |other|.
//
// When dealing with usage analysis, any Use will replace all other values,
// such as Unused and Unknown. Unless both are Unused, the merge would be
// Unknown.
if (usageAnalysis_ == PhiUsage::Used ||
other->usageAnalysis_ == PhiUsage::Used) {
usageAnalysis_ = PhiUsage::Used;
} else if (usageAnalysis_ != other->usageAnalysis_) {
// this == unused && other == unknown
// or this == unknown && other == unused
usageAnalysis_ = PhiUsage::Unknown;
} else {
// this == unused && other == unused
// or this == unknown && other = unknown
MOZ_ASSERT(usageAnalysis_ == PhiUsage::Unused ||
usageAnalysis_ == PhiUsage::Unknown);
MOZ_ASSERT(usageAnalysis_ == other->usageAnalysis_);
}
}
/* static */
bool MPhi::markIteratorPhis(const PhiVector& iterators) {
// Find and mark phis that must transitively hold an iterator live.
Vector<MPhi*, 8, SystemAllocPolicy> worklist;
for (MPhi* iter : iterators) {
if (!iter->isInWorklist()) {
if (!worklist.append(iter)) {
return false;
}
iter->setInWorklist();
}
}
while (!worklist.empty()) {
MPhi* phi = worklist.popCopy();
phi->setNotInWorklist();
phi->setIterator();
phi->setImplicitlyUsedUnchecked();
for (MUseDefIterator iter(phi); iter; iter++) {
MDefinition* use = iter.def();
if (!use->isInWorklist() && use->isPhi() && !use->toPhi()->isIterator()) {
if (!worklist.append(use->toPhi())) {
return false;
}
use->setInWorklist();
}
}
}
return true;
}
bool MPhi::typeIncludes(MDefinition* def) {
MOZ_ASSERT(!IsMagicType(def->type()));
if (def->type() == MIRType::Int32 && this->type() == MIRType::Double) {
return true;
}
if (def->type() == MIRType::Value) {
// This phi must be able to be any value.
return this->type() == MIRType::Value;
}
return this->mightBeType(def->type());
}
void MCallBase::addArg(size_t argnum, MDefinition* arg) {
// The operand vector is initialized in reverse order by WarpBuilder.
// It cannot be checked for consistency until all arguments are added.
// FixedList doesn't initialize its elements, so do an unchecked init.
initOperand(argnum + NumNonArgumentOperands, arg);
}
static inline bool IsConstant(MDefinition* def, double v) {
if (!def->isConstant()) {
return false;
}
return NumbersAreIdentical(def->toConstant()->numberToDouble(), v);
}
MDefinition* MBinaryBitwiseInstruction::foldsTo(TempAllocator& alloc) {
// Identity operations are removed (for int32 only) in foldUnnecessaryBitop.
if (type() == MIRType::Int32) {
if (MDefinition* folded = EvaluateConstantOperands(alloc, this)) {
return folded;
}
} else if (type() == MIRType::Int64) {
if (MDefinition* folded = EvaluateInt64ConstantOperands(alloc, this)) {
return folded;
}
}
return this;
}
MDefinition* MBinaryBitwiseInstruction::foldUnnecessaryBitop() {
// It's probably OK to perform this optimization only for int32, as it will
// have the greatest effect for asm.js code that is compiled with the JS
// pipeline, and that code will not see int64 values.
if (type() != MIRType::Int32) {
return this;
}
// Fold unsigned shift right operator when the second operand is zero and
// the only use is an unsigned modulo. Thus, the expression
// |(x >>> 0) % y| becomes |x % y|.
if (isUrsh() && IsUint32Type(this)) {
MDefinition* defUse = maybeSingleDefUse();
if (defUse && defUse->isMod() && defUse->toMod()->isUnsigned()) {
return getOperand(0);
}
}
// Eliminate bitwise operations that are no-ops when used on integer
// inputs, such as (x | 0).
MDefinition* lhs = getOperand(0);
MDefinition* rhs = getOperand(1);
if (IsConstant(lhs, 0)) {
return foldIfZero(0);
}
if (IsConstant(rhs, 0)) {
return foldIfZero(1);
}
if (IsConstant(lhs, -1)) {
return foldIfNegOne(0);
}
if (IsConstant(rhs, -1)) {
return foldIfNegOne(1);
}
if (lhs == rhs) {
return foldIfEqual();
}
if (maskMatchesRightRange) {
MOZ_ASSERT(lhs->isConstant());
MOZ_ASSERT(lhs->type() == MIRType::Int32);
return foldIfAllBitsSet(0);
}
if (maskMatchesLeftRange) {
MOZ_ASSERT(rhs->isConstant());
MOZ_ASSERT(rhs->type() == MIRType::Int32);
return foldIfAllBitsSet(1);
}
return this;
}
static inline bool CanProduceNegativeZero(MDefinition* def) {
// Test if this instruction can produce negative zero even when bailing out
// and changing types.
switch (def->op()) {
case MDefinition::Opcode::Constant:
if (def->type() == MIRType::Double &&
def->toConstant()->toDouble() == -0.0) {
return true;
}
[[fallthrough]];
case MDefinition::Opcode::BitAnd:
case MDefinition::Opcode::BitOr:
case MDefinition::Opcode::BitXor:
case MDefinition::Opcode::BitNot:
case MDefinition::Opcode::Lsh:
case MDefinition::Opcode::Rsh:
return false;
default:
return true;
}
}
static inline bool NeedNegativeZeroCheck(MDefinition* def) {
if (def->isGuard() || def->isGuardRangeBailouts()) {
return true;
}
// Test if all uses have the same semantics for -0 and 0
for (MUseIterator use = def->usesBegin(); use != def->usesEnd(); use++) {
if (use->consumer()->isResumePoint()) {
return true;
}
MDefinition* use_def = use->consumer()->toDefinition();
switch (use_def->op()) {
case MDefinition::Opcode::Add: {
// If add is truncating -0 and 0 are observed as the same.
if (use_def->toAdd()->isTruncated()) {
break;
}
// x + y gives -0, when both x and y are -0
// Figure out the order in which the addition's operands will
// execute. EdgeCaseAnalysis::analyzeLate has renumbered the MIR
// definitions for us so that this just requires comparing ids.
MDefinition* first = use_def->toAdd()->lhs();
MDefinition* second = use_def->toAdd()->rhs();
if (first->id() > second->id()) {
std::swap(first, second);
}
// Negative zero checks can be removed on the first executed
// operand only if it is guaranteed the second executed operand
// will produce a value other than -0. While the second is
// typed as an int32, a bailout taken between execution of the
// operands may change that type and cause a -0 to flow to the
// second.
//
// There is no way to test whether there are any bailouts
// between execution of the operands, so remove negative
// zero checks from the first only if the second's type is
// independent from type changes that may occur after bailing.
if (def == first && CanProduceNegativeZero(second)) {
return true;
}
// The negative zero check can always be removed on the second
// executed operand; by the time this executes the first will have
// been evaluated as int32 and the addition's result cannot be -0.
break;
}
case MDefinition::Opcode::Sub: {
// If sub is truncating -0 and 0 are observed as the same
if (use_def->toSub()->isTruncated()) {
break;
}
// x + y gives -0, when x is -0 and y is 0
// We can remove the negative zero check on the rhs, only if we
// are sure the lhs isn't negative zero.
// The lhs is typed as integer (i.e. not -0.0), but it can bailout
// and change type. This should be fine if the lhs is executed
// first. However if the rhs is executed first, the lhs can bail,
// change type and become -0.0 while the rhs has already been
// optimized to not make a difference between zero and negative zero.
MDefinition* lhs = use_def->toSub()->lhs();
MDefinition* rhs = use_def->toSub()->rhs();
if (rhs->id() < lhs->id() && CanProduceNegativeZero(lhs)) {
return true;
}
[[fallthrough]];
}
case MDefinition::Opcode::StoreElement:
case MDefinition::Opcode::StoreHoleValueElement:
case MDefinition::Opcode::LoadElement:
case MDefinition::Opcode::LoadElementHole:
case MDefinition::Opcode::LoadUnboxedScalar:
case MDefinition::Opcode::LoadDataViewElement:
case MDefinition::Opcode::LoadTypedArrayElementHole:
case MDefinition::Opcode::CharCodeAt:
case MDefinition::Opcode::Mod:
case MDefinition::Opcode::InArray:
// Only allowed to remove check when definition is the second operand
if (use_def->getOperand(0) == def) {
return true;
}
for (size_t i = 2, e = use_def->numOperands(); i < e; i++) {
if (use_def->getOperand(i) == def) {
return true;
}
}
break;
case MDefinition::Opcode::BoundsCheck:
// Only allowed to remove check when definition is the first operand
if (use_def->toBoundsCheck()->getOperand(1) == def) {
return true;
}
break;
case MDefinition::Opcode::ToString:
case MDefinition::Opcode::FromCharCode:
case MDefinition::Opcode::FromCodePoint:
case MDefinition::Opcode::TableSwitch:
case MDefinition::Opcode::Compare:
case MDefinition::Opcode::BitAnd:
case MDefinition::Opcode::BitOr:
case MDefinition::Opcode::BitXor:
case MDefinition::Opcode::Abs:
case MDefinition::Opcode::TruncateToInt32:
// Always allowed to remove check. No matter which operand.
break;
case MDefinition::Opcode::StoreElementHole:
case MDefinition::Opcode::StoreTypedArrayElementHole:
case MDefinition::Opcode::PostWriteElementBarrier:
// Only allowed to remove check when definition is the third operand.
for (size_t i = 0, e = use_def->numOperands(); i < e; i++) {
if (i == 2) {
continue;
}
if (use_def->getOperand(i) == def) {
return true;
}
}
break;
default:
return true;
}
}
return false;
}
#ifdef JS_JITSPEW
void MBinaryArithInstruction::printOpcode(GenericPrinter& out) const {
MDefinition::printOpcode(out);
switch (type()) {
case MIRType::Int32:
if (isDiv()) {
out.printf(" [%s]", toDiv()->isUnsigned() ? "uint32" : "int32");
} else if (isMod()) {
out.printf(" [%s]", toMod()->isUnsigned() ? "uint32" : "int32");
} else {
out.printf(" [int32]");
}
break;
case MIRType::Int64:
if (isDiv()) {
out.printf(" [%s]", toDiv()->isUnsigned() ? "uint64" : "int64");
} else if (isMod()) {
out.printf(" [%s]", toMod()->isUnsigned() ? "uint64" : "int64");
} else {
out.printf(" [int64]");
}
break;
case MIRType::Float32:
out.printf(" [float]");
break;
case MIRType::Double:
out.printf(" [double]");
break;
default:
break;
}
}
#endif
MDefinition* MRsh::foldsTo(TempAllocator& alloc) {
MDefinition* f = MBinaryBitwiseInstruction::foldsTo(alloc);
if (f != this) {
return f;
}
MDefinition* lhs = getOperand(0);
MDefinition* rhs = getOperand(1);
// It's probably OK to perform this optimization only for int32, as it will
// have the greatest effect for asm.js code that is compiled with the JS
// pipeline, and that code will not see int64 values.
if (!lhs->isLsh() || !rhs->isConstant() || rhs->type() != MIRType::Int32) {
return this;
}
if (!lhs->getOperand(1)->isConstant() ||
lhs->getOperand(1)->type() != MIRType::Int32) {
return this;
}
uint32_t shift = rhs->toConstant()->toInt32();
uint32_t shift_lhs = lhs->getOperand(1)->toConstant()->toInt32();
if (shift != shift_lhs) {
return this;
}
switch (shift) {
case 16:
return MSignExtendInt32::New(alloc, lhs->getOperand(0),
MSignExtendInt32::Half);
case 24:
return MSignExtendInt32::New(alloc, lhs->getOperand(0),
MSignExtendInt32::Byte);
}
return this;
}
MDefinition* MBinaryArithInstruction::foldsTo(TempAllocator& alloc) {
MOZ_ASSERT(IsNumberType(type()));
MDefinition* lhs = getOperand(0);
MDefinition* rhs = getOperand(1);
if (type() == MIRType::Int64) {
MOZ_ASSERT(!isTruncated());
if (MConstant* folded = EvaluateInt64ConstantOperands(alloc, this)) {
if (!folded->block()) {
block()->insertBefore(this, folded);
}
return folded;
}
if (isSub() || isDiv() || isMod()) {
return this;
}
if (rhs->isConstant() &&
rhs->toConstant()->toInt64() == int64_t(getIdentity())) {
return lhs;
}
if (lhs->isConstant() &&
lhs->toConstant()->toInt64() == int64_t(getIdentity())) {
return rhs;
}
return this;
}
if (MConstant* folded = EvaluateConstantOperands(alloc, this)) {
if (isTruncated()) {
if (!folded->block()) {
block()->insertBefore(this, folded);
}
if (folded->type() != MIRType::Int32) {
return MTruncateToInt32::New(alloc, folded);
}
}
return folded;
}
if (mustPreserveNaN_) {
return this;
}
// 0 + -0 = 0. So we can't remove addition
if (isAdd() && type() != MIRType::Int32) {
return this;
}
if (IsConstant(rhs, getIdentity())) {
if (isTruncated()) {
return MTruncateToInt32::New(alloc, lhs);
}
return lhs;
}
// subtraction isn't commutative. So we can't remove subtraction when lhs
// equals 0
if (isSub()) {
return this;
}
if (IsConstant(lhs, getIdentity())) {
if (isTruncated()) {
return MTruncateToInt32::New(alloc, rhs);
}
return rhs; // id op x => x
}
return this;
}
void MBinaryArithInstruction::trySpecializeFloat32(TempAllocator& alloc) {
MOZ_ASSERT(IsNumberType(type()));
// Do not use Float32 if we can use int32.
if (type() == MIRType::Int32) {
return;
}
if (EnsureFloatConsumersAndInputOrConvert(this, alloc)) {
setResultType(MIRType::Float32);
}
}
void MMinMax::trySpecializeFloat32(TempAllocator& alloc) {
if (type() == MIRType::Int32) {
return;
}
MDefinition* left = lhs();
MDefinition* right = rhs();
if ((left->canProduceFloat32() ||
(left->isMinMax() && left->type() == MIRType::Float32)) &&
(right->canProduceFloat32() ||
(right->isMinMax() && right->type() == MIRType::Float32))) {
setResultType(MIRType::Float32);
} else {
ConvertOperandsToDouble(this, alloc);
}
}
MDefinition* MMinMax::foldsTo(TempAllocator& alloc) {
MOZ_ASSERT(lhs()->type() == type());
MOZ_ASSERT(rhs()->type() == type());
if (lhs() == rhs()) {
return lhs();
}
auto foldConstants = [&alloc](MDefinition* lhs, MDefinition* rhs,
bool isMax) -> MConstant* {
MOZ_ASSERT(lhs->type() == rhs->type());
MOZ_ASSERT(lhs->toConstant()->isTypeRepresentableAsDouble());
MOZ_ASSERT(rhs->toConstant()->isTypeRepresentableAsDouble());
double lnum = lhs->toConstant()->numberToDouble();
double rnum = rhs->toConstant()->numberToDouble();
double result;
if (isMax) {
result = js::math_max_impl(lnum, rnum);
} else {
result = js::math_min_impl(lnum, rnum);
}
// The folded MConstant should maintain the same MIRType with the original
// inputs.
if (lhs->type() == MIRType::Int32) {
int32_t cast;
if (mozilla::NumberEqualsInt32(result, &cast)) {
return MConstant::New(alloc, Int32Value(cast));
}
return nullptr;
}
if (lhs->type() == MIRType::Float32) {
return MConstant::NewFloat32(alloc, result);
}
MOZ_ASSERT(lhs->type() == MIRType::Double);
return MConstant::New(alloc, DoubleValue(result));
};
// Try to fold the following patterns when |x| and |y| are constants.
//
// min(min(x, z), min(y, z)) = min(min(x, y), z)
// max(max(x, z), max(y, z)) = max(max(x, y), z)
// max(min(x, z), min(y, z)) = min(max(x, y), z)
// min(max(x, z), max(y, z)) = max(min(x, y), z)
if (lhs()->isMinMax() && rhs()->isMinMax()) {
do {
auto* left = lhs()->toMinMax();
auto* right = rhs()->toMinMax();
if (left->isMax() != right->isMax()) {
break;
}
MDefinition* x;
MDefinition* y;
MDefinition* z;
if (left->lhs() == right->lhs()) {
std::tie(x, y, z) = std::tuple{left->rhs(), right->rhs(), left->lhs()};
} else if (left->lhs() == right->rhs()) {
std::tie(x, y, z) = std::tuple{left->rhs(), right->lhs(), left->lhs()};
} else if (left->rhs() == right->lhs()) {
std::tie(x, y, z) = std::tuple{left->lhs(), right->rhs(), left->rhs()};
} else if (left->rhs() == right->rhs()) {
std::tie(x, y, z) = std::tuple{left->lhs(), right->lhs(), left->rhs()};
} else {
break;
}
if (!x->isConstant() || !x->toConstant()->isTypeRepresentableAsDouble() ||
!y->isConstant() || !y->toConstant()->isTypeRepresentableAsDouble()) {
break;
}
if (auto* folded = foldConstants(x, y, isMax())) {
block()->insertBefore(this, folded);
return MMinMax::New(alloc, folded, z, type(), left->isMax());
}
} while (false);
}
// Fold min/max operations with same inputs.
if (lhs()->isMinMax() || rhs()->isMinMax()) {
auto* other = lhs()->isMinMax() ? lhs()->toMinMax() : rhs()->toMinMax();
auto* operand = lhs()->isMinMax() ? rhs() : lhs();
if (operand == other->lhs() || operand == other->rhs()) {
if (isMax() == other->isMax()) {
// min(x, min(x, y)) = min(x, y)
// max(x, max(x, y)) = max(x, y)
return other;
}
if (!IsFloatingPointType(type())) {
// When neither value is NaN:
// max(x, min(x, y)) = x
// min(x, max(x, y)) = x
// Ensure that any bailouts that we depend on to guarantee that |y| is
// Int32 are not removed.
auto* otherOp = operand == other->lhs() ? other->rhs() : other->lhs();
otherOp->setGuardRangeBailoutsUnchecked();
return operand;
}
}
}
if (!lhs()->isConstant() && !rhs()->isConstant()) {
return this;
}
// Directly apply math utility to compare the rhs() and lhs() when
// they are both constants.
if (lhs()->isConstant() && rhs()->isConstant()) {
if (!lhs()->toConstant()->isTypeRepresentableAsDouble() ||
!rhs()->toConstant()->isTypeRepresentableAsDouble()) {
return this;
}
if (auto* folded = foldConstants(lhs(), rhs(), isMax())) {
return folded;
}
}
MDefinition* operand = lhs()->isConstant() ? rhs() : lhs();
MConstant* constant =
lhs()->isConstant() ? lhs()->toConstant() : rhs()->toConstant();
if (operand->isToDouble() &&
operand->getOperand(0)->type() == MIRType::Int32) {
// min(int32, cte >= INT32_MAX) = int32
if (!isMax() && constant->isTypeRepresentableAsDouble() &&
constant->numberToDouble() >= INT32_MAX) {
MLimitedTruncate* limit = MLimitedTruncate::New(
alloc, operand->getOperand(0), TruncateKind::NoTruncate);
block()->insertBefore(this, limit);
MToDouble* toDouble = MToDouble::New(alloc, limit);
return toDouble;
}
// max(int32, cte <= INT32_MIN) = int32
if (isMax() && constant->isTypeRepresentableAsDouble() &&
constant->numberToDouble() <= INT32_MIN) {
MLimitedTruncate* limit = MLimitedTruncate::New(
alloc, operand->getOperand(0), TruncateKind::NoTruncate);
block()->insertBefore(this, limit);
MToDouble* toDouble = MToDouble::New(alloc, limit);
return toDouble;
}
}
auto foldLength = [](MDefinition* operand, MConstant* constant,
bool isMax) -> MDefinition* {
if ((operand->isArrayLength() || operand->isArrayBufferViewLength() ||
operand->isArgumentsLength() || operand->isStringLength()) &&
constant->type() == MIRType::Int32) {
// (Array|ArrayBufferView|Arguments|String)Length is always >= 0.
// max(array.length, cte <= 0) = array.length
// min(array.length, cte <= 0) = cte
if (constant->toInt32() <= 0) {
return isMax ? operand : constant;
}
}
return nullptr;
};
if (auto* folded = foldLength(operand, constant, isMax())) {
return folded;
}
// Attempt to fold nested min/max operations which are produced by
// self-hosted built-in functions.
if (operand->isMinMax()) {
auto* other = operand->toMinMax();
MOZ_ASSERT(other->lhs()->type() == type());
MOZ_ASSERT(other->rhs()->type() == type());
MConstant* otherConstant = nullptr;
MDefinition* otherOperand = nullptr;
if (other->lhs()->isConstant()) {
otherConstant = other->lhs()->toConstant();
otherOperand = other->rhs();
} else if (other->rhs()->isConstant()) {
otherConstant = other->rhs()->toConstant();
otherOperand = other->lhs();
}
if (otherConstant && constant->isTypeRepresentableAsDouble() &&
otherConstant->isTypeRepresentableAsDouble()) {
if (isMax() == other->isMax()) {
// Fold min(x, min(y, z)) to min(min(x, y), z) with constant min(x, y).
// Fold max(x, max(y, z)) to max(max(x, y), z) with constant max(x, y).
if (auto* left = foldConstants(constant, otherConstant, isMax())) {
block()->insertBefore(this, left);
return MMinMax::New(alloc, left, otherOperand, type(), isMax());
}
} else {
// Fold min(x, max(y, z)) to max(min(x, y), min(x, z)).
// Fold max(x, min(y, z)) to min(max(x, y), max(x, z)).
//
// But only do this when min(x, z) can also be simplified.
if (auto* right = foldLength(otherOperand, constant, isMax())) {
if (auto* left = foldConstants(constant, otherConstant, isMax())) {
block()->insertBefore(this, left);
return MMinMax::New(alloc, left, right, type(), !isMax());
}
}
}
}
}
return this;
}
#ifdef JS_JITSPEW
void MMinMax::printOpcode(GenericPrinter& out) const {
MDefinition::printOpcode(out);
out.printf(" (%s)", isMax() ? "max" : "min");
}
void MMinMaxArray::printOpcode(GenericPrinter& out) const {
MDefinition::printOpcode(out);
out.printf(" (%s)", isMax() ? "max" : "min");
}
#endif
MDefinition* MPow::foldsConstant(TempAllocator& alloc) {
// Both `x` and `p` in `x^p` must be constants in order to precompute.
if (!input()->isConstant() || !power()->isConstant()) {
return nullptr;
}
if (!power()->toConstant()->isTypeRepresentableAsDouble()) {
return nullptr;
}
if (!input()->toConstant()->isTypeRepresentableAsDouble()) {
return nullptr;
}
double x = input()->toConstant()->numberToDouble();
double p = power()->toConstant()->numberToDouble();
double result = js::ecmaPow(x, p);
if (type() == MIRType::Int32) {
int32_t cast;
if (!mozilla::NumberIsInt32(result, &cast)) {
// Reject folding if the result isn't an int32, because we'll bail anyway.
return nullptr;
}
return MConstant::New(alloc, Int32Value(cast));
}
return MConstant::New(alloc, DoubleValue(result));
}
MDefinition* MPow::foldsConstantPower(TempAllocator& alloc) {
// If `p` in `x^p` isn't constant, we can't apply these folds.
if (!power()->isConstant()) {
return nullptr;
}
if (!power()->toConstant()->isTypeRepresentableAsDouble()) {
return nullptr;
}
MOZ_ASSERT(type() == MIRType::Double || type() == MIRType::Int32);
// NOTE: The optimizations must match the optimizations used in |js::ecmaPow|
// resp. |js::powi| to avoid differential testing issues.
double pow = power()->toConstant()->numberToDouble();
// Math.pow(x, 0.5) is a sqrt with edge-case detection.
if (pow == 0.5) {
MOZ_ASSERT(type() == MIRType::Double);
return MPowHalf::New(alloc, input());
}
// Math.pow(x, -0.5) == 1 / Math.pow(x, 0.5), even for edge cases.
if (pow == -0.5) {
MOZ_ASSERT(type() == MIRType::Double);
MPowHalf* half = MPowHalf::New(alloc, input());
block()->insertBefore(this, half);
MConstant* one = MConstant::New(alloc, DoubleValue(1.0));
block()->insertBefore(this, one);
return MDiv::New(alloc, one, half, MIRType::Double);
}
// Math.pow(x, 1) == x.
if (pow == 1.0) {
return input();
}
auto multiply = [this, &alloc](MDefinition* lhs, MDefinition* rhs) {
MMul* mul = MMul::New(alloc, lhs, rhs, type());
mul->setBailoutKind(bailoutKind());
// Multiplying the same number can't yield negative zero.
mul->setCanBeNegativeZero(lhs != rhs && canBeNegativeZero());
return mul;
};
// Math.pow(x, 2) == x*x.
if (pow == 2.0) {
return multiply(input(), input());
}
// Math.pow(x, 3) == x*x*x.
if (pow == 3.0) {
MMul* mul1 = multiply(input(), input());
block()->insertBefore(this, mul1);
return multiply(input(), mul1);
}
// Math.pow(x, 4) == y*y, where y = x*x.
if (pow == 4.0) {
MMul* y = multiply(input(), input());
block()->insertBefore(this, y);
return multiply(y, y);
}
// No optimization
return nullptr;
}
MDefinition* MPow::foldsTo(TempAllocator& alloc) {
if (MDefinition* def = foldsConstant(alloc)) {
return def;
}
if (MDefinition* def = foldsConstantPower(alloc)) {
return def;
}
return this;
}
MDefinition* MInt32ToIntPtr::foldsTo(TempAllocator& alloc) {
MDefinition* def = input();
if (def->isConstant()) {
int32_t i = def->toConstant()->toInt32();
return MConstant::NewIntPtr(alloc, intptr_t(i));
}
if (def->isNonNegativeIntPtrToInt32()) {
return def->toNonNegativeIntPtrToInt32()->input();
}
return this;
}
bool MAbs::fallible() const {
return !implicitTruncate_ && (!range() || !range()->hasInt32Bounds());
}
void MAbs::trySpecializeFloat32(TempAllocator& alloc) {
// Do not use Float32 if we can use int32.
if (input()->type() == MIRType::Int32) {
return;
}
if (EnsureFloatConsumersAndInputOrConvert(this, alloc)) {
setResultType(MIRType::Float32);
}
}
MDefinition* MDiv::foldsTo(TempAllocator& alloc) {
MOZ_ASSERT(IsNumberType(type()));
if (type() == MIRType::Int64) {
if (MDefinition* folded = EvaluateInt64ConstantOperands(alloc, this)) {
return folded;
}
return this;
}
if (MDefinition* folded = EvaluateConstantOperands(alloc, this)) {
return folded;
}
if (MDefinition* folded = EvaluateExactReciprocal(alloc, this)) {
return folded;
}
return this;
}
void MDiv::analyzeEdgeCasesForward() {
// This is only meaningful when doing integer division.
if (type() != MIRType::Int32) {
return;
}
MOZ_ASSERT(lhs()->type() == MIRType::Int32);
MOZ_ASSERT(rhs()->type() == MIRType::Int32);
// Try removing divide by zero check
if (rhs()->isConstant() && !rhs()->toConstant()->isInt32(0)) {
canBeDivideByZero_ = false;
}
// If lhs is a constant int != INT32_MIN, then
// negative overflow check can be skipped.
if (lhs()->isConstant() && !lhs()->toConstant()->isInt32(INT32_MIN)) {
canBeNegativeOverflow_ = false;
}
// If rhs is a constant int != -1, likewise.
if (rhs()->isConstant() && !rhs()->toConstant()->isInt32(-1)) {
canBeNegativeOverflow_ = false;
}
// If lhs is != 0, then negative zero check can be skipped.
if (lhs()->isConstant() && !lhs()->toConstant()->isInt32(0)) {
setCanBeNegativeZero(false);
}
// If rhs is >= 0, likewise.
if (rhs()->isConstant() && rhs()->type() == MIRType::Int32) {
if (rhs()->toConstant()->toInt32() >= 0) {
setCanBeNegativeZero(false);
}
}
}
void MDiv::analyzeEdgeCasesBackward() {
if (canBeNegativeZero() && !NeedNegativeZeroCheck(this)) {
setCanBeNegativeZero(false);
}
}
bool MDiv::fallible() const { return !isTruncated(); }
MDefinition* MMod::foldsTo(TempAllocator& alloc) {
MOZ_ASSERT(IsNumberType(type()));
if (type() == MIRType::Int64) {
if (MDefinition* folded = EvaluateInt64ConstantOperands(alloc, this)) {
return folded;
}
} else {
if (MDefinition* folded = EvaluateConstantOperands(alloc, this)) {
return folded;
}
}
return this;
}
void MMod::analyzeEdgeCasesForward() {
// These optimizations make sense only for integer division
if (type() != MIRType::Int32) {
return;
}
if (rhs()->isConstant() && !rhs()->toConstant()->isInt32(0)) {
canBeDivideByZero_ = false;
}
if (rhs()->isConstant()) {
int32_t n = rhs()->toConstant()->toInt32();
if (n > 0 && !IsPowerOfTwo(uint32_t(n))) {
canBePowerOfTwoDivisor_ = false;
}
}
}
bool MMod::fallible() const {
return !isTruncated() &&
(isUnsigned() || canBeDivideByZero() || canBeNegativeDividend());
}
void MMathFunction::trySpecializeFloat32(TempAllocator& alloc) {
if (EnsureFloatConsumersAndInputOrConvert(this, alloc)) {
setResultType(MIRType::Float32);
specialization_ = MIRType::Float32;
}
}
bool MMathFunction::isFloat32Commutative() const {
switch (function_) {
case UnaryMathFunction::Floor:
case UnaryMathFunction::Ceil:
case UnaryMathFunction::Round:
case UnaryMathFunction::Trunc:
return true;
default:
return false;
}
}
MHypot* MHypot::New(TempAllocator& alloc, const MDefinitionVector& vector) {
uint32_t length = vector.length();
MHypot* hypot = new (alloc) MHypot;
if (!hypot->init(alloc, length)) {
return nullptr;
}
for (uint32_t i = 0; i < length; ++i) {
hypot->initOperand(i, vector[i]);
}
return hypot;
}
bool MAdd::fallible() const {
// the add is fallible if range analysis does not say that it is finite, AND
// either the truncation analysis shows that there are non-truncated uses.
if (truncateKind() >= TruncateKind::IndirectTruncate) {
return false;
}
if (range() && range()->hasInt32Bounds()) {
return false;
}
return true;
}
bool MSub::fallible() const {
// see comment in MAdd::fallible()
if (truncateKind() >= TruncateKind::IndirectTruncate) {
return false;
}
if (range() && range()->hasInt32Bounds()) {
return false;
}
return true;
}
MDefinition* MSub::foldsTo(TempAllocator& alloc) {
MDefinition* out = MBinaryArithInstruction::foldsTo(alloc);
if (out != this) {
return out;
}
if (type() != MIRType::Int32) {
return this;
}
// Optimize X - X to 0. This optimization is only valid for Int32
// values. Subtracting a floating point value from itself returns
// NaN when the operand is either Infinity or NaN.
if (lhs() == rhs()) {
// Ensure that any bailouts that we depend on to guarantee that X
// is Int32 are not removed.
lhs()->setGuardRangeBailoutsUnchecked();
return MConstant::New(alloc, Int32Value(0));
}
return this;
}
MDefinition* MMul::foldsTo(TempAllocator& alloc) {
MDefinition* out = MBinaryArithInstruction::foldsTo(alloc);
if (out != this) {
return out;
}
if (type() != MIRType::Int32) {
return this;
}
if (lhs() == rhs()) {
setCanBeNegativeZero(false);
}
return this;
}
void MMul::analyzeEdgeCasesForward() {
// Try to remove the check for negative zero
// This only makes sense when using the integer multiplication
if (type() != MIRType::Int32) {
return;
}
// If lhs is > 0, no need for negative zero check.
if (lhs()->isConstant() && lhs()->type() == MIRType::Int32) {
if (lhs()->toConstant()->toInt32() > 0) {
setCanBeNegativeZero(false);
}
}
// If rhs is > 0, likewise.
if (rhs()->isConstant() && rhs()->type() == MIRType::Int32) {
if (rhs()->toConstant()->toInt32() > 0) {
setCanBeNegativeZero(false);
}
}
}
void MMul::analyzeEdgeCasesBackward() {
if (canBeNegativeZero() && !NeedNegativeZeroCheck(this)) {
setCanBeNegativeZero(false);
}
}
bool MMul::canOverflow() const {
if (isTruncated()) {
return false;
}
return !range() || !range()->hasInt32Bounds();
}
bool MUrsh::fallible() const {
if (bailoutsDisabled()) {
return false;
}
return !range() || !range()->hasInt32Bounds();
}
MIRType MCompare::inputType() {
switch (compareType_) {
case Compare_Undefined:
return MIRType::Undefined;
case Compare_Null:
return MIRType::Null;
case Compare_UInt32:
case Compare_Int32:
return MIRType::Int32;
case Compare_UIntPtr:
return MIRType::IntPtr;
case Compare_Double:
return MIRType::Double;
case Compare_Float32:
return MIRType::Float32;
case Compare_String:
return MIRType::String;
case Compare_Symbol:
return MIRType::Symbol;
case Compare_Object:
return MIRType::Object;
case Compare_BigInt:
case Compare_BigInt_Int32:
case Compare_BigInt_Double:
case Compare_BigInt_String:
return MIRType::BigInt;
default:
MOZ_CRASH("No known conversion");
}
}
static inline bool MustBeUInt32(MDefinition* def, MDefinition** pwrapped) {
if (def->isUrsh()) {
*pwrapped = def->toUrsh()->lhs();
MDefinition* rhs = def->toUrsh()->rhs();
return def->toUrsh()->bailoutsDisabled() && rhs->maybeConstantValue() &&
rhs->maybeConstantValue()->isInt32(0);
}
if (MConstant* defConst = def->maybeConstantValue()) {
*pwrapped = defConst;
return defConst->type() == MIRType::Int32 && defConst->toInt32() >= 0;
}
*pwrapped = nullptr; // silence GCC warning
return false;
}
/* static */
bool MBinaryInstruction::unsignedOperands(MDefinition* left,
MDefinition* right) {
MDefinition* replace;
if (!MustBeUInt32(left, &replace)) {
return false;
}
if (replace->type() != MIRType::Int32) {
return false;
}
if (!MustBeUInt32(right, &replace)) {
return false;
}
if (replace->type() != MIRType::Int32) {
return false;
}
return true;
}
bool MBinaryInstruction::unsignedOperands() {
return unsignedOperands(getOperand(0), getOperand(1));
}
void MBinaryInstruction::replaceWithUnsignedOperands() {
MOZ_ASSERT(unsignedOperands());
for (size_t i = 0; i < numOperands(); i++) {
MDefinition* replace;
MustBeUInt32(getOperand(i), &replace);
if (replace == getOperand(i)) {
continue;
}
getOperand(i)->setImplicitlyUsedUnchecked();
replaceOperand(i, replace);
}
}
MDefinition* MBitNot::foldsTo(TempAllocator& alloc) {
if (type() == MIRType::Int64) {
return this;
}
MOZ_ASSERT(type() == MIRType::Int32);
MDefinition* input = getOperand(0);
if (input->isConstant()) {
js::Value v = Int32Value(~(input->toConstant()->toInt32()));
return MConstant::New(alloc, v);
}
if (input->isBitNot()) {
MOZ_ASSERT(input->toBitNot()->type() == MIRType::Int32);
MOZ_ASSERT(input->toBitNot()->getOperand(0)->type() == MIRType::Int32);
return MTruncateToInt32::New(alloc,
input->toBitNot()->input()); // ~~x => x | 0
}
return this;
}
static void AssertKnownClass(TempAllocator& alloc, MInstruction* ins,
MDefinition* obj) {
#ifdef DEBUG
const JSClass* clasp = GetObjectKnownJSClass(obj);
MOZ_ASSERT(clasp);
auto* assert = MAssertClass::New(alloc, obj, clasp);
ins->block()->insertBefore(ins, assert);
#endif
}
MDefinition* MBoxNonStrictThis::foldsTo(TempAllocator& alloc) {
MDefinition* in = input();
if (in->isBox()) {
in = in->toBox()->input();
}
if (in->type() == MIRType::Object) {
return in;
}
return this;
}
AliasSet MLoadArgumentsObjectArg::getAliasSet() const {
return AliasSet::Load(AliasSet::Any);
}
AliasSet MLoadArgumentsObjectArgHole::getAliasSet() const {
return AliasSet::Load(AliasSet::Any);
}
AliasSet MInArgumentsObjectArg::getAliasSet() const {
// Loads |arguments.length|, but not the actual element, so we can use the
// same alias-set as MArgumentsObjectLength.
return AliasSet::Load(AliasSet::ObjectFields | AliasSet::FixedSlot |
AliasSet::DynamicSlot);
}
AliasSet MArgumentsObjectLength::getAliasSet() const {
return AliasSet::Load(AliasSet::ObjectFields | AliasSet::FixedSlot |
AliasSet::DynamicSlot);
}
bool MGuardArgumentsObjectFlags::congruentTo(const MDefinition* ins) const {
if (!ins->isGuardArgumentsObjectFlags() ||
ins->toGuardArgumentsObjectFlags()->flags() != flags()) {
return false;
}
return congruentIfOperandsEqual(ins);
}
AliasSet MGuardArgumentsObjectFlags::getAliasSet() const {
// The flags are packed with the length in a fixed private slot.
return AliasSet::Load(AliasSet::FixedSlot);
}
MDefinition* MIdToStringOrSymbol::foldsTo(TempAllocator& alloc) {
if (idVal()->isBox()) {
auto* input = idVal()->toBox()->input();
MIRType idType = input->type();
if (idType == MIRType::String || idType == MIRType::Symbol) {
return idVal();
}
if (idType == MIRType::Int32) {
auto* toString =
MToString::New(alloc, input, MToString::SideEffectHandling::Bailout);
block()->insertBefore(this, toString);
return MBox::New(alloc, toString);
}
}
return this;
}
MDefinition* MReturnFromCtor::foldsTo(TempAllocator& alloc) {
MDefinition* rval = value();
if (rval->isBox()) {
rval = rval->toBox()->input();
}
if (rval->type() == MIRType::Object) {
return rval;
}
if (rval->type() != MIRType::Value) {
return object();
}
return this;
}
MDefinition* MTypeOf::foldsTo(TempAllocator& alloc) {
MDefinition* unboxed = input();
if (unboxed->isBox()) {
unboxed = unboxed->toBox()->input();
}
JSType type;
switch (unboxed->type()) {
case MIRType::Double:
case MIRType::Float32:
case MIRType::Int32:
type = JSTYPE_NUMBER;
break;
case MIRType::String:
type = JSTYPE_STRING;
break;
case MIRType::Symbol:
type = JSTYPE_SYMBOL;
break;
case MIRType::BigInt:
type = JSTYPE_BIGINT;
break;
case MIRType::Null:
type = JSTYPE_OBJECT;
break;
case MIRType::Undefined:
type = JSTYPE_UNDEFINED;
break;
case MIRType::Boolean:
type = JSTYPE_BOOLEAN;
break;
case MIRType::Object: {
KnownClass known = GetObjectKnownClass(unboxed);
if (known != KnownClass::None) {
if (known == KnownClass::Function) {
type = JSTYPE_FUNCTION;
} else {
type = JSTYPE_OBJECT;
}
AssertKnownClass(alloc, this, unboxed);
break;
}
[[fallthrough]];
}
default:
return this;
}
return MConstant::New(alloc, Int32Value(static_cast<int32_t>(type)));
}
MDefinition* MTypeOfName::foldsTo(TempAllocator& alloc) {
MOZ_ASSERT(input()->type() == MIRType::Int32);
if (!input()->isConstant()) {
return this;
}
static_assert(JSTYPE_UNDEFINED == 0);
int32_t type = input()->toConstant()->toInt32();
MOZ_ASSERT(JSTYPE_UNDEFINED <= type && type < JSTYPE_LIMIT);
JSString* name =
TypeName(static_cast<JSType>(type), GetJitContext()->runtime->names());
return MConstant::New(alloc, StringValue(name));
}
MUrsh* MUrsh::NewWasm(TempAllocator& alloc, MDefinition* left,
MDefinition* right, MIRType type) {
MUrsh* ins = new (alloc) MUrsh(left, right, type);
// Since Ion has no UInt32 type, we use Int32 and we have a special
// exception to the type rules: we can return values in
// (INT32_MIN,UINT32_MAX] and still claim that we have an Int32 type
// without bailing out. This is necessary because Ion has no UInt32
// type and we can't have bailouts in wasm code.
ins->bailoutsDisabled_ = true;
return ins;
}
MResumePoint* MResumePoint::New(TempAllocator& alloc, MBasicBlock* block,
jsbytecode* pc, ResumeMode mode) {
MResumePoint* resume = new (alloc) MResumePoint(block, pc, mode);
if (!resume->init(alloc)) {
block->discardPreAllocatedResumePoint(resume);
return nullptr;
}
resume->inherit(block);
return resume;
}
MResumePoint::MResumePoint(MBasicBlock* block, jsbytecode* pc, ResumeMode mode)
: MNode(block, Kind::ResumePoint),
pc_(pc),
instruction_(nullptr),
mode_(mode) {
block->addResumePoint(this);
}
bool MResumePoint::init(TempAllocator& alloc) {
return operands_.init(alloc, block()->stackDepth());
}
MResumePoint* MResumePoint::caller() const {
return block()->callerResumePoint();
}
void MResumePoint::inherit(MBasicBlock* block) {
// FixedList doesn't initialize its elements, so do unchecked inits.
for (size_t i = 0; i < stackDepth(); i++) {
initOperand(i, block->getSlot(i));
}
}
void MResumePoint::addStore(TempAllocator& alloc, MDefinition* store,
const MResumePoint* cache) {
MOZ_ASSERT(block()->outerResumePoint() != this);
MOZ_ASSERT_IF(cache, !cache->stores_.empty());
if (cache && cache->stores_.begin()->operand == store) {
// If the last resume point had the same side-effect stack, then we can
// reuse the current side effect without cloning it. This is a simple
// way to share common context by making a spaghetti stack.
if (++cache->stores_.begin() == stores_.begin()) {
stores_.copy(cache->stores_);
return;
}
}
// Ensure that the store would not be deleted by DCE.
MOZ_ASSERT(store->isEffectful());
MStoreToRecover* top = new (alloc) MStoreToRecover(store);
stores_.push(top);
}
#ifdef JS_JITSPEW
void MResumePoint::dump(GenericPrinter& out) const {
out.printf("resumepoint mode=");
switch (mode()) {
case ResumeMode::ResumeAt:
if (instruction_) {
out.printf("ResumeAt(%u)", instruction_->id());
} else {
out.printf("ResumeAt");
}
break;
default:
out.put(ResumeModeToString(mode()));
break;
}
if (MResumePoint* c = caller()) {
out.printf(" (caller in block%u)", c->block()->id());
}
for (size_t i = 0; i < numOperands(); i++) {
out.printf(" ");
if (operands_[i].hasProducer()) {
getOperand(i)->printName(out);
} else {
out.printf("(null)");
}
}
out.printf("\n");
}
void MResumePoint::dump() const {
Fprinter out(stderr);
dump(out);
out.finish();
}
#endif
bool MResumePoint::isObservableOperand(MUse* u) const {
return isObservableOperand(indexOf(u));
}
bool MResumePoint::isObservableOperand(size_t index) const {
return block()->info().isObservableSlot(index);
}
bool MResumePoint::isRecoverableOperand(MUse* u) const {
return block()->info().isRecoverableOperand(indexOf(u));
}
MDefinition* MTruncateBigIntToInt64::foldsTo(TempAllocator& alloc) {
MDefinition* input = getOperand(0);
if (input->isBox()) {
input = input->getOperand(0);
}
// If the operand converts an I64 to BigInt, drop both conversions.
if (input->isInt64ToBigInt()) {
return input->getOperand(0);
}
// Fold this operation if the input operand is constant.
if (input->isConstant()) {
return MConstant::NewInt64(
alloc, BigInt::toInt64(input->toConstant()->toBigInt()));
}
return this;
}
MDefinition* MToInt64::foldsTo(TempAllocator& alloc) {
MDefinition* input = getOperand(0);
if (input->isBox()) {
input = input->getOperand(0);
}
// Unwrap MInt64ToBigInt: MToInt64(MInt64ToBigInt(int64)) = int64.
if (input->isInt64ToBigInt()) {
return input->getOperand(0);
}
// When the input is an Int64 already, just return it.
if (input->type() == MIRType::Int64) {
return input;
}
// Fold this operation if the input operand is constant.
if (input->isConstant()) {
switch (input->type()) {
case MIRType::Boolean:
return MConstant::NewInt64(alloc, input->toConstant()->toBoolean());
default:
break;
}
}
return this;
}
MDefinition* MToNumberInt32::foldsTo(TempAllocator& alloc) {
// Fold this operation if the input operand is constant.
if (MConstant* cst = input()->maybeConstantValue()) {
switch (cst->type()) {
case MIRType::Null:
if (conversion() == IntConversionInputKind::Any) {
return MConstant::New(alloc, Int32Value(0));
}
break;
case MIRType::Boolean:
if (conversion() == IntConversionInputKind::Any ||
conversion() == IntConversionInputKind::NumbersOrBoolsOnly) {
return MConstant::New(alloc, Int32Value(cst->toBoolean()));
}
break;
case MIRType::Int32:
return MConstant::New(alloc, Int32Value(cst->toInt32()));
case MIRType::Float32:
case MIRType::Double:
int32_t ival;
// Only the value within the range of Int32 can be substituted as
// constant.
if (mozilla::NumberIsInt32(cst->numberToDouble(), &ival)) {
return MConstant::New(alloc, Int32Value(ival));
}
break;
default:
break;
}
}
MDefinition* input = getOperand(0);
if (input->isBox()) {
input = input->toBox()->input();
}
// Do not fold the TruncateToInt32 node when the input is uint32 (e.g. ursh
// with a zero constant. Consider the test jit-test/tests/ion/bug1247880.js,
// where the relevant code is: |(imul(1, x >>> 0) % 2)|. The imul operator
// is folded to a MTruncateToInt32 node, which will result in this MIR:
// MMod(MTruncateToInt32(MUrsh(x, MConstant(0))), MConstant(2)). Note that
// the MUrsh node's type is int32 (since uint32 is not implemented), and
// that would fold the MTruncateToInt32 node. This will make the modulo
// unsigned, while is should have been signed.
if (input->type() == MIRType::Int32 && !IsUint32Type(input)) {
return input;
}
return this;
}
MDefinition* MBooleanToInt32::foldsTo(TempAllocator& alloc) {
MDefinition* input = getOperand(0);
MOZ_ASSERT(input->type() == MIRType::Boolean);
if (input->isConstant()) {
return MConstant::New(alloc, Int32Value(input->toConstant()->toBoolean()));
}
return this;
}
void MToNumberInt32::analyzeEdgeCasesBackward() {
if (!NeedNegativeZeroCheck(this)) {
setNeedsNegativeZeroCheck(false);
}
}
MDefinition* MTruncateToInt32::foldsTo(TempAllocator& alloc) {
MDefinition* input = getOperand(0);
if (input->isBox()) {
input = input->getOperand(0);
}
// Do not fold the TruncateToInt32 node when the input is uint32 (e.g. ursh
// with a zero constant. Consider the test jit-test/tests/ion/bug1247880.js,
// where the relevant code is: |(imul(1, x >>> 0) % 2)|. The imul operator
// is folded to a MTruncateToInt32 node, which will result in this MIR:
// MMod(MTruncateToInt32(MUrsh(x, MConstant(0))), MConstant(2)). Note that
// the MUrsh node's type is int32 (since uint32 is not implemented), and
// that would fold the MTruncateToInt32 node. This will make the modulo
// unsigned, while is should have been signed.
if (input->type() == MIRType::Int32 && !IsUint32Type(input)) {
return input;
}
if (input->type() == MIRType::Double && input->isConstant()) {
int32_t ret = ToInt32(input->toConstant()->toDouble());
return MConstant::New(alloc, Int32Value(ret));
}
return this;
}
MDefinition* MWasmTruncateToInt32::foldsTo(TempAllocator& alloc) {
MDefinition* input = getOperand(0);
if (input->type() == MIRType::Int32) {
return input;
}
if (input->type() == MIRType::Double && input->isConstant()) {
double d = input->toConstant()->toDouble();
if (std::isnan(d)) {
return this;
}
if (!isUnsigned() && d <= double(INT32_MAX) && d >= double(INT32_MIN)) {
return MConstant::New(alloc, Int32Value(ToInt32(d)));
}
if (isUnsigned() && d <= double(UINT32_MAX) && d >= 0) {
return MConstant::New(alloc, Int32Value(ToInt32(d)));
}
}
if (input->type() == MIRType::Float32 && input->isConstant()) {
double f = double(input->toConstant()->toFloat32());
if (std::isnan(f)) {
return this;
}
if (!isUnsigned() && f <= double(INT32_MAX) && f >= double(INT32_MIN)) {
return MConstant::New(alloc, Int32Value(ToInt32(f)));
}
if (isUnsigned() && f <= double(UINT32_MAX) && f >= 0) {
return MConstant::New(alloc, Int32Value(ToInt32(f)));
}
}
return this;
}
MDefinition* MWrapInt64ToInt32::foldsTo(TempAllocator& alloc) {
MDefinition* input = this->input();
if (input->isConstant()) {
uint64_t c = input->toConstant()->toInt64();
int32_t output = bottomHalf() ? int32_t(c) : int32_t(c >> 32);
return MConstant::New(alloc, Int32Value(output));
}
return this;
}
MDefinition* MExtendInt32ToInt64::foldsTo(TempAllocator& alloc) {
MDefinition* input = this->input();
if (input->isConstant()) {
int32_t c = input->toConstant()->toInt32();
int64_t res = isUnsigned() ? int64_t(uint32_t(c)) : int64_t(c);
return MConstant::NewInt64(alloc, res);
}
return this;
}
MDefinition* MSignExtendInt32::foldsTo(TempAllocator& alloc) {
MDefinition* input = this->input();
if (input->isConstant()) {
int32_t c = input->toConstant()->toInt32();
int32_t res;
switch (mode_) {
case Byte:
res = int32_t(int8_t(c & 0xFF));
break;
case Half:
res = int32_t(int16_t(c & 0xFFFF));
break;
}
return MConstant::New(alloc, Int32Value(res));
}
return this;
}
MDefinition* MSignExtendInt64::foldsTo(TempAllocator& alloc) {
MDefinition* input = this->input();
if (input->isConstant()) {
int64_t c = input->toConstant()->toInt64();
int64_t res;
switch (mode_) {
case Byte:
res = int64_t(int8_t(c & 0xFF));
break;
case Half:
res = int64_t(int16_t(c & 0xFFFF));
break;
case Word:
res = int64_t(int32_t(c & 0xFFFFFFFFU));
break;
}
return MConstant::NewInt64(alloc, res);
}
return this;
}
MDefinition* MToDouble::foldsTo(TempAllocator& alloc) {
MDefinition* input = getOperand(0);
if (input->isBox()) {
input = input->getOperand(0);
}
if (input->type() == MIRType::Double) {
return input;
}
if (input->isConstant() &&
input->toConstant()->isTypeRepresentableAsDouble()) {
return MConstant::New(alloc,
DoubleValue(input->toConstant()->numberToDouble()));
}
return this;
}
MDefinition* MToFloat32::foldsTo(TempAllocator& alloc) {
MDefinition* input = getOperand(0);
if (input->isBox()) {
input = input->getOperand(0);
}
if (input->type() == MIRType::Float32) {
return input;
}
// If x is a Float32, Float32(Double(x)) == x
if (!mustPreserveNaN_ && input->isToDouble() &&
input->toToDouble()->input()->type() == MIRType::Float32) {
return input->toToDouble()->input();
}
if (input->isConstant() &&
input->toConstant()->isTypeRepresentableAsDouble()) {
return MConstant::NewFloat32(alloc,
float(input->toConstant()->numberToDouble()));
}
// Fold ToFloat32(ToDouble(int32)) to ToFloat32(int32).
if (input->isToDouble() &&
input->toToDouble()->input()->type() == MIRType::Int32) {
return MToFloat32::New(alloc, input->toToDouble()->input());
}
return this;
}
MDefinition* MToString::foldsTo(TempAllocator& alloc) {
MDefinition* in = input();
if (in->isBox()) {
in = in->getOperand(0);
}
if (in->type() == MIRType::String) {
return in;
}
return this;
}
MDefinition* MClampToUint8::foldsTo(TempAllocator& alloc) {
if (MConstant* inputConst = input()->maybeConstantValue()) {
if (inputConst->isTypeRepresentableAsDouble()) {
int32_t clamped = ClampDoubleToUint8(inputConst->numberToDouble());
return MConstant::New(alloc, Int32Value(clamped));
}
}
return this;
}
bool MCompare::tryFoldEqualOperands(bool* result) {
if (lhs() != rhs()) {
return false;
}
// Intuitively somebody would think that if lhs === rhs,
// then we can just return true. (Or false for !==)
// However NaN !== NaN is true! So we spend some time trying
// to eliminate this case.
if (!IsStrictEqualityOp(jsop())) {
return false;
}
MOZ_ASSERT(
compareType_ == Compare_Undefined || compareType_ == Compare_Null ||
compareType_ == Compare_Int32 || compareType_ == Compare_UInt32 ||
compareType_ == Compare_UInt64 || compareType_ == Compare_Double ||
compareType_ == Compare_Float32 || compareType_ == Compare_UIntPtr ||
compareType_ == Compare_String || compareType_ == Compare_Object ||
compareType_ == Compare_Symbol || compareType_ == Compare_BigInt ||
compareType_ == Compare_BigInt_Int32 ||
compareType_ == Compare_BigInt_Double ||
compareType_ == Compare_BigInt_String);
if (isDoubleComparison() || isFloat32Comparison()) {
if (!operandsAreNeverNaN()) {
return false;
}
}
lhs()->setGuardRangeBailoutsUnchecked();
*result = (jsop() == JSOp::StrictEq);
return true;
}
static JSType TypeOfName(JSLinearString* str) {
static constexpr std::array types = {
JSTYPE_UNDEFINED, JSTYPE_OBJECT, JSTYPE_FUNCTION, JSTYPE_STRING,
JSTYPE_NUMBER, JSTYPE_BOOLEAN, JSTYPE_SYMBOL, JSTYPE_BIGINT,
#ifdef ENABLE_RECORD_TUPLE
JSTYPE_RECORD, JSTYPE_TUPLE,
#endif
};
static_assert(types.size() == JSTYPE_LIMIT);
const JSAtomState& names = GetJitContext()->runtime->names();
for (auto type : types) {
if (EqualStrings(str, TypeName(type, names))) {
return type;
}
}
return JSTYPE_LIMIT;
}
struct TypeOfCompareInput {
// The `typeof expr` side of the comparison.
// MTypeOfName for JSOp::Typeof/JSOp::TypeofExpr, and
// MTypeOf for JSOp::TypeofEq (same pointer as typeOf).
MDefinition* typeOfSide;
// The actual `typeof` operation.
MTypeOf* typeOf;
// The string side of the comparison.
JSType type;
// True if the comparison uses raw JSType (Generated for JSOp::TypeofEq).
bool isIntComparison;
TypeOfCompareInput(MDefinition* typeOfSide, MTypeOf* typeOf, JSType type,
bool isIntComparison)
: typeOfSide(typeOfSide),
typeOf(typeOf),
type(type),
isIntComparison(isIntComparison) {}
};
static mozilla::Maybe<TypeOfCompareInput> IsTypeOfCompare(MCompare* ins) {
if (!IsEqualityOp(ins->jsop())) {
return mozilla::Nothing();
}
if (ins->compareType() == MCompare::Compare_Int32) {
auto* lhs = ins->lhs();
auto* rhs = ins->rhs();
if (ins->type() != MIRType::Boolean || lhs->type() != MIRType::Int32 ||
rhs->type() != MIRType::Int32) {
return mozilla::Nothing();
}
// NOTE: The comparison is generated inside JIT, and typeof should always
// be in the LHS.
if (!lhs->isTypeOf() || !rhs->isConstant()) {
return mozilla::Nothing();
}
auto* typeOf = lhs->toTypeOf();
auto* constant = rhs->toConstant();
JSType type = JSType(constant->toInt32());
return mozilla::Some(TypeOfCompareInput(typeOf, typeOf, type, true));
}
if (ins->compareType() != MCompare::Compare_String) {
return mozilla::Nothing();
}
auto* lhs = ins->lhs();
auto* rhs = ins->rhs();
MOZ_ASSERT(ins->type() == MIRType::Boolean);
MOZ_ASSERT(lhs->type() == MIRType::String);
MOZ_ASSERT(rhs->type() == MIRType::String);
if (!lhs->isTypeOfName() && !rhs->isTypeOfName()) {
return mozilla::Nothing();
}
if (!lhs->isConstant() && !rhs->isConstant()) {
return mozilla::Nothing();
}
auto* typeOfName =
lhs->isTypeOfName() ? lhs->toTypeOfName() : rhs->toTypeOfName();
auto* typeOf = typeOfName->input()->toTypeOf();
auto* constant = lhs->isConstant() ? lhs->toConstant() : rhs->toConstant();
JSType type = TypeOfName(&constant->toString()->asLinear());
return mozilla::Some(TypeOfCompareInput(typeOfName, typeOf, type, false));
}
bool MCompare::tryFoldTypeOf(bool* result) {
auto typeOfCompare = IsTypeOfCompare(this);
if (!typeOfCompare) {
return false;
}
auto* typeOf = typeOfCompare->typeOf;
JSType type = typeOfCompare->type;
switch (type) {
case JSTYPE_BOOLEAN:
if (!typeOf->input()->mightBeType(MIRType::Boolean)) {
*result = (jsop() == JSOp::StrictNe || jsop() == JSOp::Ne);
return true;
}
break;
case JSTYPE_NUMBER:
if (!typeOf->input()->mightBeType(MIRType::Int32) &&
!typeOf->input()->mightBeType(MIRType::Float32) &&
!typeOf->input()->mightBeType(MIRType::Double)) {
*result = (jsop() == JSOp::StrictNe || jsop() == JSOp::Ne);
return true;
}
break;
case JSTYPE_STRING:
if (!typeOf->input()->mightBeType(MIRType::String)) {
*result = (jsop() == JSOp::StrictNe || jsop() == JSOp::Ne);
return true;
}
break;
case JSTYPE_SYMBOL:
if (!typeOf->input()->mightBeType(MIRType::Symbol)) {
*result = (jsop() == JSOp::StrictNe || jsop() == JSOp::Ne);
return true;
}
break;
case JSTYPE_BIGINT:
if (!typeOf->input()->mightBeType(MIRType::BigInt)) {
*result = (jsop() == JSOp::StrictNe || jsop() == JSOp::Ne);
return true;
}
break;
case JSTYPE_OBJECT:
if (!typeOf->input()->mightBeType(MIRType::Object) &&
!typeOf->input()->mightBeType(MIRType::Null)) {
*result = (jsop() == JSOp::StrictNe || jsop() == JSOp::Ne);
return true;
}
break;
case JSTYPE_UNDEFINED:
if (!typeOf->input()->mightBeType(MIRType::Object) &&
!typeOf->input()->mightBeType(MIRType::Undefined)) {
*result = (jsop() == JSOp::StrictNe || jsop() == JSOp::Ne);
return true;
}
break;
case JSTYPE_FUNCTION:
if (!typeOf->input()->mightBeType(MIRType::Object)) {
*result = (jsop() == JSOp::StrictNe || jsop() == JSOp::Ne);
return true;
}
break;
case JSTYPE_LIMIT:
*result = (jsop() == JSOp::StrictNe || jsop() == JSOp::Ne);
return true;
#ifdef ENABLE_RECORD_TUPLE
case JSTYPE_RECORD:
case JSTYPE_TUPLE:
MOZ_CRASH("Records and Tuples are not supported yet.");
#endif
}
return false;
}
bool MCompare::tryFold(bool* result) {
JSOp op = jsop();
if (tryFoldEqualOperands(result)) {
return true;
}
if (tryFoldTypeOf(result)) {
return true;
}
if (compareType_ == Compare_Null || compareType_ == Compare_Undefined) {
// The LHS is the value we want to test against null or undefined.
if (IsStrictEqualityOp(op)) {
if (lhs()->type() == inputType()) {
*result = (op == JSOp::StrictEq);
return true;
}
if (!lhs()->mightBeType(inputType())) {
*result = (op == JSOp::StrictNe);
return true;
}
} else {
MOZ_ASSERT(IsLooseEqualityOp(op));
if (IsNullOrUndefined(lhs()->type())) {
*result = (op == JSOp::Eq);
return true;
}
if (!lhs()->mightBeType(MIRType::Null) &&
!lhs()->mightBeType(MIRType::Undefined) &&
!lhs()->mightBeType(MIRType::Object)) {
*result = (op == JSOp::Ne);
return true;
}
}
return false;
}
return false;
}
template <typename T>
static bool FoldComparison(JSOp op, T left, T right) {
switch (op) {
case JSOp::Lt:
return left < right;
case JSOp::Le:
return left <= right;
case JSOp::Gt:
return left > right;
case JSOp::Ge:
return left >= right;
case JSOp::StrictEq:
case JSOp::Eq:
return left == right;
case JSOp::StrictNe:
case JSOp::Ne:
return left != right;
default:
MOZ_CRASH("Unexpected op.");
}
}
bool MCompare::evaluateConstantOperands(TempAllocator& alloc, bool* result) {
if (type() != MIRType::Boolean && type() != MIRType::Int32) {
return false;
}
MDefinition* left = getOperand(0);
MDefinition* right = getOperand(1);
if (compareType() == Compare_Double) {
// Optimize "MCompare MConstant (MToDouble SomethingInInt32Range).
// In most cases the MToDouble was added, because the constant is
// a double.
// e.g. v < 9007199254740991, where v is an int32 is always true.
if (!lhs()->isConstant() && !rhs()->isConstant()) {
return false;
}
MDefinition* operand = left->isConstant() ? right : left;
MConstant* constant =
left->isConstant() ? left->toConstant() : right->toConstant();
MOZ_ASSERT(constant->type() == MIRType::Double);
double cte = constant->toDouble();
if (operand->isToDouble() &&
operand->getOperand(0)->type() == MIRType::Int32) {
bool replaced = false;
switch (jsop_) {
case JSOp::Lt:
if (cte > INT32_MAX || cte < INT32_MIN) {
*result = !((constant == lhs()) ^ (cte < INT32_MIN));
replaced = true;
}
break;
case JSOp::Le:
if (constant == lhs()) {
if (cte > INT32_MAX || cte <= INT32_MIN) {
*result = (cte <= INT32_MIN);
replaced = true;
}
} else {
if (cte >= INT32_MAX || cte < INT32_MIN) {
*result = (cte >= INT32_MIN);
replaced = true;
}
}
break;
case JSOp::Gt:
if (cte > INT32_MAX || cte < INT32_MIN) {
*result = !((constant == rhs()) ^ (cte < INT32_MIN));
replaced = true;
}
break;
case JSOp::Ge:
if (constant == lhs()) {
if (cte >= INT32_MAX || cte < INT32_MIN) {
*result = (cte >= INT32_MAX);
replaced = true;
}
} else {
if (cte > INT32_MAX || cte <= INT32_MIN) {
*result = (cte <= INT32_MIN);
replaced = true;
}
}
break;
case JSOp::StrictEq: // Fall through.
case JSOp::Eq:
if (cte > INT32_MAX || cte < INT32_MIN) {
*result = false;
replaced = true;
}
break;
case JSOp::StrictNe: // Fall through.
case JSOp::Ne:
if (cte > INT32_MAX || cte < INT32_MIN) {
*result = true;
replaced = true;
}
break;
default:
MOZ_CRASH("Unexpected op.");
}
if (replaced) {
MLimitedTruncate* limit = MLimitedTruncate::New(
alloc, operand->getOperand(0), TruncateKind::NoTruncate);
limit->setGuardUnchecked();
block()->insertBefore(this, limit);
return true;
}
}
// Optimize comparison against NaN.
if (std::isnan(cte)) {
switch (jsop_) {
case JSOp::Lt:
case JSOp::Le:
case JSOp::Gt:
case JSOp::Ge:
case JSOp::Eq:
case JSOp::StrictEq:
*result = false;
break;
case JSOp::Ne:
case JSOp::StrictNe:
*result = true;
break;
default:
MOZ_CRASH("Unexpected op.");
}
return true;
}
}
if (!left->isConstant() || !right->isConstant()) {
return false;
}
MConstant* lhs = left->toConstant();
MConstant* rhs = right->toConstant();
// Fold away some String equality comparisons.
if (lhs->type() == MIRType::String && rhs->type() == MIRType::String) {
int32_t comp = 0; // Default to equal.
if (left != right) {
comp = CompareStrings(&lhs->toString()->asLinear(),
&rhs->toString()->asLinear());
}
*result = FoldComparison(jsop_, comp, 0);
return true;
}
if (compareType_ == Compare_UInt32) {
*result = FoldComparison(jsop_, uint32_t(lhs->toInt32()),
uint32_t(rhs->toInt32()));
return true;
}
if (compareType_ == Compare_Int64) {
*result = FoldComparison(jsop_, lhs->toInt64(), rhs->toInt64());
return true;
}
if (compareType_ == Compare_UInt64) {
*result = FoldComparison(jsop_, uint64_t(lhs->toInt64()),
uint64_t(rhs->toInt64()));
return true;
}
if (lhs->isTypeRepresentableAsDouble() &&
rhs->isTypeRepresentableAsDouble()) {
*result =
FoldComparison(jsop_, lhs->numberToDouble(), rhs->numberToDouble());
return true;
}
return false;
}
MDefinition* MCompare::tryFoldTypeOf(TempAllocator& alloc) {
auto typeOfCompare = IsTypeOfCompare(this);
if (!typeOfCompare) {
return this;
}
auto* typeOf = typeOfCompare->typeOf;
JSType type = typeOfCompare->type;
auto* input = typeOf->input();
MOZ_ASSERT(input->type() == MIRType::Value ||
input->type() == MIRType::Object);
// Constant typeof folding handles the other cases.
MOZ_ASSERT_IF(input->type() == MIRType::Object, type == JSTYPE_UNDEFINED ||
type == JSTYPE_OBJECT ||
type == JSTYPE_FUNCTION);
MOZ_ASSERT(type != JSTYPE_LIMIT, "unknown typeof strings folded earlier");
// If there's only a single use, assume this |typeof| is used in a simple
// comparison context.
//
// if (typeof thing === "number") { ... }
//
// It'll be compiled into something similar to:
//
// if (IsNumber(thing)) { ... }
//
// This heuristic can go wrong when repeated |typeof| are used in consecutive
// if-statements.
//
// if (typeof thing === "number") { ... }
// else if (typeof thing === "string") { ... }
// ... repeated for all possible types
//
// In that case it'd more efficient to emit MTypeOf compared to MTypeOfIs. We
// don't yet handle that case, because it'd require a separate optimization
// pass to correctly detect it.
if (typeOfCompare->typeOfSide->hasOneUse()) {
return MTypeOfIs::New(alloc, input, jsop(), type);
}
if (typeOfCompare->isIntComparison) {
// Already optimized.
return this;
}
MConstant* cst = MConstant::New(alloc, Int32Value(type));
block()->insertBefore(this, cst);
return MCompare::New(alloc, typeOf, cst, jsop(), MCompare::Compare_Int32);
}
MDefinition* MCompare::tryFoldCharCompare(TempAllocator& alloc) {
if (compareType() != Compare_String) {
return this;
}
MDefinition* left = lhs();
MOZ_ASSERT(left->type() == MIRType::String);
MDefinition* right = rhs();
MOZ_ASSERT(right->type() == MIRType::String);
// |str[i]| is compiled as |MFromCharCode(MCharCodeAt(str, i))|.
// Out-of-bounds access is compiled as
// |FromCharCodeEmptyIfNegative(CharCodeAtOrNegative(str, i))|.
auto isCharAccess = [](MDefinition* ins) {
if (ins->isFromCharCode()) {
return ins->toFromCharCode()->code()->isCharCodeAt();
}
if (ins->isFromCharCodeEmptyIfNegative()) {
auto* fromCharCode = ins->toFromCharCodeEmptyIfNegative();
return fromCharCode->code()->isCharCodeAtOrNegative();
}
return false;
};
auto charAccessCode = [](MDefinition* ins) {
if (ins->isFromCharCode()) {
return ins->toFromCharCode()->code();
}
return ins->toFromCharCodeEmptyIfNegative()->code();
};
if (left->isConstant() || right->isConstant()) {
// Try to optimize |MConstant(string) <compare> (MFromCharCode MCharCodeAt)|
// as |MConstant(charcode) <compare> MCharCodeAt|.
MConstant* constant;
MDefinition* operand;
if (left->isConstant()) {
constant = left->toConstant();
operand = right;
} else {
constant = right->toConstant();
operand = left;
}
if (constant->toString()->length() != 1 || !isCharAccess(operand)) {
return this;
}
char16_t charCode = constant->toString()->asLinear().latin1OrTwoByteChar(0);
MConstant* charCodeConst = MConstant::New(alloc, Int32Value(charCode));
block()->insertBefore(this, charCodeConst);
MDefinition* charCodeAt = charAccessCode(operand);
if (left->isConstant()) {
left = charCodeConst;
right = charCodeAt;
} else {
left = charCodeAt;
right = charCodeConst;
}
} else if (isCharAccess(left) && isCharAccess(right)) {
// Try to optimize |(MFromCharCode MCharCodeAt) <compare> (MFromCharCode
// MCharCodeAt)| as |MCharCodeAt <compare> MCharCodeAt|.
left = charAccessCode(left);
right = charAccessCode(right);
} else {
return this;
}
return MCompare::New(alloc, left, right, jsop(), MCompare::Compare_Int32);
}
MDefinition* MCompare::tryFoldStringCompare(TempAllocator& alloc) {
if (compareType() != Compare_String) {
return this;
}
MDefinition* left = lhs();
MOZ_ASSERT(left->type() == MIRType::String);
MDefinition* right = rhs();
MOZ_ASSERT(right->type() == MIRType::String);
if (!left->isConstant() && !right->isConstant()) {
return this;
}
// Try to optimize |string <compare> MConstant("")| as |MStringLength(string)
// <compare> MConstant(0)|.
MConstant* constant =
left->isConstant() ? left->toConstant() : right->toConstant();
if (!constant->toString()->empty()) {
return this;
}
MDefinition* operand = left->isConstant() ? right : left;
auto* strLength = MStringLength::New(alloc, operand);
block()->insertBefore(this, strLength);
auto* zero = MConstant::New(alloc, Int32Value(0));
block()->insertBefore(this, zero);
if (left->isConstant()) {
left = zero;
right = strLength;
} else {
left = strLength;
right = zero;
}
return MCompare::New(alloc, left, right, jsop(), MCompare::Compare_Int32);
}
MDefinition* MCompare::tryFoldStringSubstring(TempAllocator& alloc) {
if (compareType() != Compare_String) {
return this;
}
if (!IsEqualityOp(jsop())) {
return this;
}
auto* left = lhs();
MOZ_ASSERT(left->type() == MIRType::String);
auto* right = rhs();
MOZ_ASSERT(right->type() == MIRType::String);
// One operand must be a constant string.
if (!left->isConstant() && !right->isConstant()) {
return this;
}
// The constant string must be non-empty.
auto* constant =
left->isConstant() ? left->toConstant() : right->toConstant();
if (constant->toString()->empty()) {
return this;
}
// The other operand must be a substring operation.
auto* operand = left->isConstant() ? right : left;
if (!operand->isSubstr()) {
return this;
}
auto* substr = operand->toSubstr();
static_assert(JSString::MAX_LENGTH < INT32_MAX,
"string length can be casted to int32_t");
if (!IsSubstrTo(substr, int32_t(constant->toString()->length()))) {
return this;
}
// Now fold code like |str.substring(0, 2) == "aa"| to |str.startsWith("aa")|.
auto* startsWith = MStringStartsWith::New(alloc, substr->string(), constant);
if (jsop() == JSOp::Eq || jsop() == JSOp::StrictEq) {
return startsWith;
}
// Invert for inequality.
MOZ_ASSERT(jsop() == JSOp::Ne || jsop() == JSOp::StrictNe);
block()->insertBefore(this, startsWith);
return MNot::New(alloc, startsWith);
}
MDefinition* MCompare::tryFoldStringIndexOf(TempAllocator& alloc) {
if (compareType() != Compare_Int32) {
return this;
}
if (!IsEqualityOp(jsop())) {
return this;
}
auto* left = lhs();
MOZ_ASSERT(left->type() == MIRType::Int32);
auto* right = rhs();
MOZ_ASSERT(right->type() == MIRType::Int32);
// One operand must be a constant integer.
if (!left->isConstant() && !right->isConstant()) {
return this;
}
// The constant must be zero.
auto* constant =
left->isConstant() ? left->toConstant() : right->toConstant();
if (!constant->isInt32(0)) {
return this;
}
// The other operand must be an indexOf operation.
auto* operand = left->isConstant() ? right : left;
if (!operand->isStringIndexOf()) {
return this;
}
// Fold |str.indexOf(searchStr) == 0| to |str.startsWith(searchStr)|.
auto* indexOf = operand->toStringIndexOf();
auto* startsWith =
MStringStartsWith::New(alloc, indexOf->string(), indexOf->searchString());
if (jsop() == JSOp::Eq || jsop() == JSOp::StrictEq) {
return startsWith;
}
// Invert for inequality.
MOZ_ASSERT(jsop() == JSOp::Ne || jsop() == JSOp::StrictNe);
block()->insertBefore(this, startsWith);
return MNot::New(alloc, startsWith);
}
MDefinition* MCompare::foldsTo(TempAllocator& alloc) {
bool result;
if (tryFold(&result) || evaluateConstantOperands(alloc, &result)) {
if (type() == MIRType::Int32) {
return MConstant::New(alloc, Int32Value(result));
}
MOZ_ASSERT(type() == MIRType::Boolean);
return MConstant::New(alloc, BooleanValue(result));
}
if (MDefinition* folded = tryFoldTypeOf(alloc); folded != this) {
return folded;
}
if (MDefinition* folded = tryFoldCharCompare(alloc); folded != this) {
return folded;
}
if (MDefinition* folded = tryFoldStringCompare(alloc); folded != this) {
return folded;
}
if (MDefinition* folded = tryFoldStringSubstring(alloc); folded != this) {
return folded;
}
if (MDefinition* folded = tryFoldStringIndexOf(alloc); folded != this) {
return folded;
}
return this;
}
void MCompare::trySpecializeFloat32(TempAllocator& alloc) {
if (AllOperandsCanProduceFloat32(this) && compareType_ == Compare_Double) {
compareType_ = Compare_Float32;
} else {
ConvertOperandsToDouble(this, alloc);
}
}
MDefinition* MNot::foldsTo(TempAllocator& alloc) {
// Fold if the input is constant
if (MConstant* inputConst = input()->maybeConstantValue()) {
bool b;
if (inputConst->valueToBoolean(&b)) {
if (type() == MIRType::Int32 || type() == MIRType::Int64) {
return MConstant::New(alloc, Int32Value(!b));
}
return MConstant::New(alloc, BooleanValue(!b));
}
}
// If the operand of the Not is itself a Not, they cancel out. But we can't
// always convert Not(Not(x)) to x because that may loose the conversion to
// boolean. We can simplify Not(Not(Not(x))) to Not(x) though.
MDefinition* op = getOperand(0);
if (op->isNot()) {
MDefinition* opop = op->getOperand(0);
if (opop->isNot()) {
return opop;
}
}
// Not of an undefined or null value is always true
if (input()->type() == MIRType::Undefined ||
input()->type() == MIRType::Null) {
return MConstant::New(alloc, BooleanValue(true));
}
// Not of a symbol is always false.
if (input()->type() == MIRType::Symbol) {
return MConstant::New(alloc, BooleanValue(false));
}
return this;
}
void MNot::trySpecializeFloat32(TempAllocator& alloc) {
(void)EnsureFloatInputOrConvert(this, alloc);
}
#ifdef JS_JITSPEW
void MBeta::printOpcode(GenericPrinter& out) const {
MDefinition::printOpcode(out);
out.printf(" ");
comparison_->dump(out);
}
#endif
AliasSet MCreateThis::getAliasSet() const {
return AliasSet::Load(AliasSet::Any);
}
bool MGetArgumentsObjectArg::congruentTo(const MDefinition* ins) const {
if (!ins->isGetArgumentsObjectArg()) {
return false;
}
if (ins->toGetArgumentsObjectArg()->argno() != argno()) {
return false;
}
return congruentIfOperandsEqual(ins);
}
AliasSet MGetArgumentsObjectArg::getAliasSet() const {
return AliasSet::Load(AliasSet::Any);
}
AliasSet MSetArgumentsObjectArg::getAliasSet() const {
return AliasSet::Store(AliasSet::Any);
}
MObjectState::MObjectState(MObjectState* state)
: MVariadicInstruction(classOpcode),
numSlots_(state->numSlots_),
numFixedSlots_(state->numFixedSlots_) {
// This instruction is only used as a summary for bailout paths.
setResultType(MIRType::Object);
setRecoveredOnBailout();
}
MObjectState::MObjectState(JSObject* templateObject)
: MObjectState(templateObject->as<NativeObject>().shape()) {}
MObjectState::MObjectState(const Shape* shape)
: MVariadicInstruction(classOpcode) {
// This instruction is only used as a summary for bailout paths.
setResultType(MIRType::Object);
setRecoveredOnBailout();
numSlots_ = shape->asShared().slotSpan();
numFixedSlots_ = shape->asShared().numFixedSlots();
}
/* static */
JSObject* MObjectState::templateObjectOf(MDefinition* obj) {
// MNewPlainObject uses a shape constant, not an object.
MOZ_ASSERT(!obj->isNewPlainObject());
if (obj->isNewObject()) {
return obj->toNewObject()->templateObject();
} else if (obj->isNewCallObject()) {
return obj->toNewCallObject()->templateObject();
} else if (obj->isNewIterator()) {
return obj->toNewIterator()->templateObject();
}
MOZ_CRASH("unreachable");
}
bool MObjectState::init(TempAllocator& alloc, MDefinition* obj) {
if (!MVariadicInstruction::init(alloc, numSlots() + 1)) {
return false;
}
// +1, for the Object.
initOperand(0, obj);
return true;
}
void MObjectState::initFromTemplateObject(TempAllocator& alloc,
MDefinition* undefinedVal) {
if (object()->isNewPlainObject()) {
MOZ_ASSERT(object()->toNewPlainObject()->shape()->asShared().slotSpan() ==
numSlots());
for (size_t i = 0; i < numSlots(); i++) {
initSlot(i, undefinedVal);
}
return;
}
JSObject* templateObject = templateObjectOf(object());
// Initialize all the slots of the object state with the value contained in
// the template object. This is needed to account values which are baked in
// the template objects and not visible in IonMonkey, such as the
// uninitialized-lexical magic value of call objects.
MOZ_ASSERT(templateObject->is<NativeObject>());
NativeObject& nativeObject = templateObject->as<NativeObject>();
MOZ_ASSERT(nativeObject.slotSpan() == numSlots());
for (size_t i = 0; i < numSlots(); i++) {
Value val = nativeObject.getSlot(i);
MDefinition* def = undefinedVal;
if (!val.isUndefined()) {
MConstant* ins = MConstant::New(alloc, val);
block()->insertBefore(this, ins);
def = ins;
}
initSlot(i, def);
}
}
MObjectState* MObjectState::New(TempAllocator& alloc, MDefinition* obj) {
MObjectState* res;
if (obj->isNewPlainObject()) {
const Shape* shape = obj->toNewPlainObject()->shape();
res = new (alloc) MObjectState(shape);
} else {
JSObject* templateObject = templateObjectOf(obj);
MOZ_ASSERT(templateObject, "Unexpected object creation.");
res = new (alloc) MObjectState(templateObject);
}
if (!res || !res->init(alloc, obj)) {
return nullptr;
}
return res;
}
MObjectState* MObjectState::Copy(TempAllocator& alloc, MObjectState* state) {
MObjectState* res = new (alloc) MObjectState(state);
if (!res || !res->init(alloc, state->object())) {
return nullptr;
}
for (size_t i = 0; i < res->numSlots(); i++) {
res->initSlot(i, state->getSlot(i));
}
return res;
}
MArrayState::MArrayState(MDefinition* arr) : MVariadicInstruction(classOpcode) {
// This instruction is only used as a summary for bailout paths.
setResultType(MIRType::Object);
setRecoveredOnBailout();
if (arr->isNewArrayObject()) {
numElements_ = arr->toNewArrayObject()->length();
} else {
numElements_ = arr->toNewArray()->length();
}
}
bool MArrayState::init(TempAllocator& alloc, MDefinition* obj,
MDefinition* len) {
if (!MVariadicInstruction::init(alloc, numElements() + 2)) {
return false;
}
// +1, for the Array object.
initOperand(0, obj);
// +1, for the length value of the array.
initOperand(1, len);
return true;
}
void MArrayState::initFromTemplateObject(TempAllocator& alloc,
MDefinition* undefinedVal) {
for (size_t i = 0; i < numElements(); i++) {
initElement(i, undefinedVal);
}
}
MArrayState* MArrayState::New(TempAllocator& alloc, MDefinition* arr,
MDefinition* initLength) {
MArrayState* res = new (alloc) MArrayState(arr);
if (!res || !res->init(alloc, arr, initLength)) {
return nullptr;
}
return res;
}
MArrayState* MArrayState::Copy(TempAllocator& alloc, MArrayState* state) {
MDefinition* arr = state->array();
MDefinition* len = state->initializedLength();
MArrayState* res = new (alloc) MArrayState(arr);
if (!res || !res->init(alloc, arr, len)) {
return nullptr;
}
for (size_t i = 0; i < res->numElements(); i++) {
res->initElement(i, state->getElement(i));
}
return res;
}
MNewArray::MNewArray(uint32_t length, MConstant* templateConst,
gc::Heap initialHeap, bool vmCall)
: MUnaryInstruction(classOpcode, templateConst),
length_(length),
initialHeap_(initialHeap),
vmCall_(vmCall) {
setResultType(MIRType::Object);
}
MDefinition::AliasType MLoadFixedSlot::mightAlias(
const MDefinition* def) const {
if (def->isStoreFixedSlot()) {
const MStoreFixedSlot* store = def->toStoreFixedSlot();
if (store->slot() != slot()) {
return AliasType::NoAlias;
}
if (store->object() != object()) {
return AliasType::MayAlias;
}
return AliasType::MustAlias;
}
return AliasType::MayAlias;
}
MDefinition* MLoadFixedSlot::foldsTo(TempAllocator& alloc) {
if (MDefinition* def = foldsToStore(alloc)) {
return def;
}
return this;
}
MDefinition::AliasType MLoadFixedSlotAndUnbox::mightAlias(
const MDefinition* def) const {
if (def->isStoreFixedSlot()) {
const MStoreFixedSlot* store = def->toStoreFixedSlot();
if (store->slot() != slot()) {
return AliasType::NoAlias;
}
if (store->object() != object()) {
return AliasType::MayAlias;
}
return AliasType::MustAlias;
}
return AliasType::MayAlias;
}
MDefinition* MLoadFixedSlotAndUnbox::foldsTo(TempAllocator& alloc) {
if (MDefinition* def = foldsToStore(alloc)) {
return def;
}
return this;
}
MDefinition* MWasmExtendU32Index::foldsTo(TempAllocator& alloc) {
MDefinition* input = this->input();
if (input->isConstant()) {
return MConstant::NewInt64(
alloc, int64_t(uint32_t(input->toConstant()->toInt32())));
}
return this;
}
MDefinition* MWasmWrapU32Index::foldsTo(TempAllocator& alloc) {
MDefinition* input = this->input();
if (input->isConstant()) {
return MConstant::New(
alloc, Int32Value(int32_t(uint32_t(input->toConstant()->toInt64()))));
}
return this;
}
// Some helpers for folding wasm and/or/xor on int32/64 values. Rather than
// duplicating these for 32 and 64-bit values, all folding is done on 64-bit
// values and masked for the 32-bit case.
const uint64_t Low32Mask = uint64_t(0xFFFFFFFFULL);
// Routines to check and disassemble values.
static bool IsIntegralConstant(const MDefinition* def) {
return def->isConstant() &&
(def->type() == MIRType::Int32 || def->type() == MIRType::Int64);
}
static uint64_t GetIntegralConstant(const MDefinition* def) {
if (def->type() == MIRType::Int32) {
return uint64_t(def->toConstant()->toInt32()) & Low32Mask;
}
return uint64_t(def->toConstant()->toInt64());
}
static bool IsIntegralConstantZero(const MDefinition* def) {
return IsIntegralConstant(def) && GetIntegralConstant(def) == 0;
}
static bool IsIntegralConstantOnes(const MDefinition* def) {
uint64_t ones = def->type() == MIRType::Int32 ? Low32Mask : ~uint64_t(0);
return IsIntegralConstant(def) && GetIntegralConstant(def) == ones;
}
// Routines to create values.
static MDefinition* ToIntegralConstant(TempAllocator& alloc, MIRType ty,
uint64_t val) {
switch (ty) {
case MIRType::Int32:
return MConstant::New(alloc,
Int32Value(int32_t(uint32_t(val & Low32Mask))));
case MIRType::Int64:
return MConstant::NewInt64(alloc, int64_t(val));
default:
MOZ_CRASH();
}
}
static MDefinition* ZeroOfType(TempAllocator& alloc, MIRType ty) {
return ToIntegralConstant(alloc, ty, 0);
}
static MDefinition* OnesOfType(TempAllocator& alloc, MIRType ty) {
return ToIntegralConstant(alloc, ty, ~uint64_t(0));
}
MDefinition* MWasmBinaryBitwise::foldsTo(TempAllocator& alloc) {
MOZ_ASSERT(op() == Opcode::WasmBinaryBitwise);
MOZ_ASSERT(type() == MIRType::Int32 || type() == MIRType::Int64);
MDefinition* argL = getOperand(0);
MDefinition* argR = getOperand(1);
MOZ_ASSERT(argL->type() == type() && argR->type() == type());
// The args are the same (SSA name)
if (argL == argR) {
switch (subOpcode()) {
case SubOpcode::And:
case SubOpcode::Or:
return argL;
case SubOpcode::Xor:
return ZeroOfType(alloc, type());
default:
MOZ_CRASH();
}
}
// Both args constant
if (IsIntegralConstant(argL) && IsIntegralConstant(argR)) {
uint64_t valL = GetIntegralConstant(argL);
uint64_t valR = GetIntegralConstant(argR);
uint64_t val = valL;
switch (subOpcode()) {
case SubOpcode::And:
val &= valR;
break;
case SubOpcode::Or:
val |= valR;
break;
case SubOpcode::Xor:
val ^= valR;
break;
default:
MOZ_CRASH();
}
return ToIntegralConstant(alloc, type(), val);
}
// Left arg is zero
if (IsIntegralConstantZero(argL)) {
switch (subOpcode()) {
case SubOpcode::And:
return ZeroOfType(alloc, type());
case SubOpcode::Or:
case SubOpcode::Xor:
return argR;
default:
MOZ_CRASH();
}
}
// Right arg is zero
if (IsIntegralConstantZero(argR)) {
switch (subOpcode()) {
case SubOpcode::And:
return ZeroOfType(alloc, type());
case SubOpcode::Or:
case SubOpcode::Xor:
return argL;
default:
MOZ_CRASH();
}
}
// Left arg is ones
if (IsIntegralConstantOnes(argL)) {
switch (subOpcode()) {
case SubOpcode::And:
return argR;
case SubOpcode::Or:
return OnesOfType(alloc, type());
case SubOpcode::Xor:
return MBitNot::New(alloc, argR);
default:
MOZ_CRASH();
}
}
// Right arg is ones
if (IsIntegralConstantOnes(argR)) {
switch (subOpcode()) {
case SubOpcode::And:
return argL;
case SubOpcode::Or:
return OnesOfType(alloc, type());
case SubOpcode::Xor:
return MBitNot::New(alloc, argL);
default:
MOZ_CRASH();
}
}
return this;
}
MDefinition* MWasmAddOffset::foldsTo(TempAllocator& alloc) {
MDefinition* baseArg = base();
if (!baseArg->isConstant()) {
return this;
}
if (baseArg->type() == MIRType::Int32) {
CheckedInt<uint32_t> ptr = baseArg->toConstant()->toInt32();
ptr += offset();
if (!ptr.isValid()) {
return this;
}
return MConstant::New(alloc, Int32Value(ptr.value()));
}
MOZ_ASSERT(baseArg->type() == MIRType::Int64);
CheckedInt<uint64_t> ptr = baseArg->toConstant()->toInt64();
ptr += offset();
if (!ptr.isValid()) {
return this;
}
return MConstant::NewInt64(alloc, ptr.value());
}
bool MWasmAlignmentCheck::congruentTo(const MDefinition* ins) const {
if (!ins->isWasmAlignmentCheck()) {
return false;
}
const MWasmAlignmentCheck* check = ins->toWasmAlignmentCheck();
return byteSize_ == check->byteSize() && congruentIfOperandsEqual(check);
}
MDefinition::AliasType MAsmJSLoadHeap::mightAlias(
const MDefinition* def) const {
if (def->isAsmJSStoreHeap()) {
const MAsmJSStoreHeap* store = def->toAsmJSStoreHeap();
if (store->accessType() != accessType()) {
return AliasType::MayAlias;
}
if (!base()->isConstant() || !store->base()->isConstant()) {
return AliasType::MayAlias;
}
const MConstant* otherBase = store->base()->toConstant();
if (base()->toConstant()->equals(otherBase)) {
return AliasType::MayAlias;
}
return AliasType::NoAlias;
}
return AliasType::MayAlias;
}
bool MAsmJSLoadHeap::congruentTo(const MDefinition* ins) const {
if (!ins->isAsmJSLoadHeap()) {
return false;
}
const MAsmJSLoadHeap* load = ins->toAsmJSLoadHeap();
return load->accessType() == accessType() && congruentIfOperandsEqual(load);
}
MDefinition::AliasType MWasmLoadInstanceDataField::mightAlias(
const MDefinition* def) const {
if (def->isWasmStoreInstanceDataField()) {
const MWasmStoreInstanceDataField* store =
def->toWasmStoreInstanceDataField();
return store->instanceDataOffset() == instanceDataOffset_
? AliasType::MayAlias
: AliasType::NoAlias;
}
return AliasType::MayAlias;
}
MDefinition::AliasType MWasmLoadGlobalCell::mightAlias(
const MDefinition* def) const {
if (def->isWasmStoreGlobalCell()) {
// No globals of different type can alias. See bug 1467415 comment 3.
if (type() != def->toWasmStoreGlobalCell()->value()->type()) {
return AliasType::NoAlias;
}
// We could do better here. We're dealing with two indirect globals.
// If at at least one of them is created in this module, then they
// can't alias -- in other words they can only alias if they are both
// imported. That would require having a flag on globals to indicate
// which are imported. See bug 1467415 comment 3, 4th rule.
}
return AliasType::MayAlias;
}
HashNumber MWasmLoadInstanceDataField::valueHash() const {
// Same comment as in MWasmLoadInstanceDataField::congruentTo() applies here.
HashNumber hash = MDefinition::valueHash();
hash = addU32ToHash(hash, instanceDataOffset_);
return hash;
}
bool MWasmLoadInstanceDataField::congruentTo(const MDefinition* ins) const {
if (!ins->isWasmLoadInstanceDataField()) {
return false;
}
const MWasmLoadInstanceDataField* other = ins->toWasmLoadInstanceDataField();
// We don't need to consider the isConstant_ markings here, because
// equivalence of offsets implies equivalence of constness.
bool sameOffsets = instanceDataOffset_ == other->instanceDataOffset_;
MOZ_ASSERT_IF(sameOffsets, isConstant_ == other->isConstant_);
// We omit checking congruence of the operands. There is only one
// operand, the instance pointer, and it only ever has one value within the
// domain of optimization. If that should ever change then operand
// congruence checking should be reinstated.
return sameOffsets /* && congruentIfOperandsEqual(other) */;
}
MDefinition* MWasmLoadInstanceDataField::foldsTo(TempAllocator& alloc) {
if (!dependency() || !dependency()->isWasmStoreInstanceDataField()) {
return this;
}
MWasmStoreInstanceDataField* store =
dependency()->toWasmStoreInstanceDataField();
if (!store->block()->dominates(block())) {
return this;
}
if (store->instanceDataOffset() != instanceDataOffset()) {
return this;
}
if (store->value()->type() != type()) {
return this;
}
return store->value();
}
bool MWasmLoadGlobalCell::congruentTo(const MDefinition* ins) const {
if (!ins->isWasmLoadGlobalCell()) {
return false;
}
const MWasmLoadGlobalCell* other = ins->toWasmLoadGlobalCell();
return congruentIfOperandsEqual(other);
}
#ifdef ENABLE_WASM_SIMD
MDefinition* MWasmTernarySimd128::foldsTo(TempAllocator& alloc) {
if (simdOp() == wasm::SimdOp::V128Bitselect) {
if (v2()->op() == MDefinition::Opcode::WasmFloatConstant) {
int8_t shuffle[16];
if (specializeBitselectConstantMaskAsShuffle(shuffle)) {
return BuildWasmShuffleSimd128(alloc, shuffle, v0(), v1());
}
} else if (canRelaxBitselect()) {
return MWasmTernarySimd128::New(alloc, v0(), v1(), v2(),
wasm::SimdOp::I8x16RelaxedLaneSelect);
}
}
return this;
}
inline static bool MatchSpecificShift(MDefinition* instr,
wasm::SimdOp simdShiftOp,
int shiftValue) {
return instr->isWasmShiftSimd128() &&
instr->toWasmShiftSimd128()->simdOp() == simdShiftOp &&
instr->toWasmShiftSimd128()->rhs()->isConstant() &&
instr->toWasmShiftSimd128()->rhs()->toConstant()->toInt32() ==
shiftValue;
}
// Matches MIR subtree that represents PMADDUBSW instruction generated by
// emscripten. The a and b parameters return subtrees that correspond
// operands of the instruction, if match is found.
static bool MatchPmaddubswSequence(MWasmBinarySimd128* lhs,
MWasmBinarySimd128* rhs, MDefinition** a,
MDefinition** b) {
MOZ_ASSERT(lhs->simdOp() == wasm::SimdOp::I16x8Mul &&
rhs->simdOp() == wasm::SimdOp::I16x8Mul);
// The emscripten/LLVM produced the following sequence for _mm_maddubs_epi16:
//
// return _mm_adds_epi16(
// _mm_mullo_epi16(
// _mm_and_si128(__a, _mm_set1_epi16(0x00FF)),
// _mm_srai_epi16(_mm_slli_epi16(__b, 8), 8)),
// _mm_mullo_epi16(_mm_srli_epi16(__a, 8), _mm_srai_epi16(__b, 8)));
//
// This will roughly correspond the following MIR:
// MWasmBinarySimd128[I16x8AddSatS]
// |-- lhs: MWasmBinarySimd128[I16x8Mul] (lhs)
// | |-- lhs: MWasmBinarySimd128WithConstant[V128And] (op0)
// | | |-- lhs: a
// | | -- rhs: SimdConstant::SplatX8(0x00FF)
// | -- rhs: MWasmShiftSimd128[I16x8ShrS] (op1)
// | |-- lhs: MWasmShiftSimd128[I16x8Shl]
// | | |-- lhs: b
// | | -- rhs: MConstant[8]
// | -- rhs: MConstant[8]
// -- rhs: MWasmBinarySimd128[I16x8Mul] (rhs)
// |-- lhs: MWasmShiftSimd128[I16x8ShrU] (op2)
// | |-- lhs: a
// | |-- rhs: MConstant[8]
// -- rhs: MWasmShiftSimd128[I16x8ShrS] (op3)
// |-- lhs: b
// -- rhs: MConstant[8]
// The I16x8AddSatS and I16x8Mul are commutative, so their operands
// may be swapped. Rearrange op0, op1, op2, op3 to be in the order
// noted above.
MDefinition *op0 = lhs->lhs(), *op1 = lhs->rhs(), *op2 = rhs->lhs(),
*op3 = rhs->rhs();
if (op1->isWasmBinarySimd128WithConstant()) {
// Move MWasmBinarySimd128WithConstant[V128And] as first operand in lhs.
std::swap(op0, op1);
} else if (op3->isWasmBinarySimd128WithConstant()) {
// Move MWasmBinarySimd128WithConstant[V128And] as first operand in rhs.
std::swap(op2, op3);
}
if (op2->isWasmBinarySimd128WithConstant()) {
// The lhs and rhs are swapped.
// Make MWasmBinarySimd128WithConstant[V128And] to be op0.
std::swap(op0, op2);
std::swap(op1, op3);
}
if (op2->isWasmShiftSimd128() &&
op2->toWasmShiftSimd128()->simdOp() == wasm::SimdOp::I16x8ShrS) {
// The op2 and op3 appears to be in wrong order, swap.
std::swap(op2, op3);
}
// Check all instructions SIMD code and constant values for assigned
// names op0, op1, op2, op3 (see diagram above).
const uint16_t const00FF[8] = {255, 255, 255, 255, 255, 255, 255, 255};
if (!op0->isWasmBinarySimd128WithConstant() ||
op0->toWasmBinarySimd128WithConstant()->simdOp() !=
wasm::SimdOp::V128And ||
memcmp(op0->toWasmBinarySimd128WithConstant()->rhs().bytes(), const00FF,
16) != 0 ||
!MatchSpecificShift(op1, wasm::SimdOp::I16x8ShrS, 8) ||
!MatchSpecificShift(op2, wasm::SimdOp::I16x8ShrU, 8) ||
!MatchSpecificShift(op3, wasm::SimdOp::I16x8ShrS, 8) ||
!MatchSpecificShift(op1->toWasmShiftSimd128()->lhs(),
wasm::SimdOp::I16x8Shl, 8)) {
return false;
}
// Check if the instructions arguments that are subtrees match the
// a and b assignments. May depend on GVN behavior.
MDefinition* maybeA = op0->toWasmBinarySimd128WithConstant()->lhs();
MDefinition* maybeB = op3->toWasmShiftSimd128()->lhs();
if (maybeA != op2->toWasmShiftSimd128()->lhs() ||
maybeB != op1->toWasmShiftSimd128()->lhs()->toWasmShiftSimd128()->lhs()) {
return false;
}
*a = maybeA;
*b = maybeB;
return true;
}
MDefinition* MWasmBinarySimd128::foldsTo(TempAllocator& alloc) {
if (simdOp() == wasm::SimdOp::I8x16Swizzle && rhs()->isWasmFloatConstant()) {
// Specialize swizzle(v, constant) as shuffle(mask, v, zero) to trigger all
// our shuffle optimizations. We don't report this rewriting as the report
// will be overwritten by the subsequent shuffle analysis.
int8_t shuffleMask[16];
memcpy(shuffleMask, rhs()->toWasmFloatConstant()->toSimd128().bytes(), 16);
for (int i = 0; i < 16; i++) {
// Out-of-bounds lanes reference the zero vector; in many cases, the zero
// vector is removed by subsequent optimizations.
if (shuffleMask[i] < 0 || shuffleMask[i] > 15) {
shuffleMask[i] = 16;
}
}
MWasmFloatConstant* zero =
MWasmFloatConstant::NewSimd128(alloc, SimdConstant::SplatX4(0));
if (!zero) {
return nullptr;
}
block()->insertBefore(this, zero);
return BuildWasmShuffleSimd128(alloc, shuffleMask, lhs(), zero);
}
// Specialize var OP const / const OP var when possible.
//
// As the LIR layer can't directly handle v128 constants as part of its normal
// machinery we specialize some nodes here if they have single-use v128
// constant arguments. The purpose is to generate code that inlines the
// constant in the instruction stream, using either a rip-relative load+op or
// quickly-synthesized constant in a scratch on x64. There is a general
// assumption here that that is better than generating the constant into an
// allocatable register, since that register value could not be reused. (This
// ignores the possibility that the constant load could be hoisted).
if (lhs()->isWasmFloatConstant() != rhs()->isWasmFloatConstant() &&
specializeForConstantRhs()) {
if (isCommutative() && lhs()->isWasmFloatConstant() && lhs()->hasOneUse()) {
return MWasmBinarySimd128WithConstant::New(
alloc, rhs(), lhs()->toWasmFloatConstant()->toSimd128(), simdOp());
}
if (rhs()->isWasmFloatConstant() && rhs()->hasOneUse()) {
return MWasmBinarySimd128WithConstant::New(
alloc, lhs(), rhs()->toWasmFloatConstant()->toSimd128(), simdOp());
}
}
// Check special encoding for PMADDUBSW.
if (canPmaddubsw() && simdOp() == wasm::SimdOp::I16x8AddSatS &&
lhs()->isWasmBinarySimd128() && rhs()->isWasmBinarySimd128() &&
lhs()->toWasmBinarySimd128()->simdOp() == wasm::SimdOp::I16x8Mul &&
rhs()->toWasmBinarySimd128()->simdOp() == wasm::SimdOp::I16x8Mul) {
MDefinition *a, *b;
if (MatchPmaddubswSequence(lhs()->toWasmBinarySimd128(),
rhs()->toWasmBinarySimd128(), &a, &b)) {
return MWasmBinarySimd128::New(alloc, a, b, /* commutative = */ false,
wasm::SimdOp::MozPMADDUBSW);
}
}
return this;
}
MDefinition* MWasmScalarToSimd128::foldsTo(TempAllocator& alloc) {
# ifdef DEBUG
auto logging = mozilla::MakeScopeExit([&] {
js::wasm::ReportSimdAnalysis("scalar-to-simd128 -> constant folded");
});
# endif
if (input()->isConstant()) {
MConstant* c = input()->toConstant();
switch (simdOp()) {
case wasm::SimdOp::I8x16Splat:
return MWasmFloatConstant::NewSimd128(
alloc, SimdConstant::SplatX16(c->toInt32()));
case wasm::SimdOp::I16x8Splat:
return MWasmFloatConstant::NewSimd128(
alloc, SimdConstant::SplatX8(c->toInt32()));
case wasm::SimdOp::I32x4Splat:
return MWasmFloatConstant::NewSimd128(
alloc, SimdConstant::SplatX4(c->toInt32()));
case wasm::SimdOp::I64x2Splat:
return MWasmFloatConstant::NewSimd128(
alloc, SimdConstant::SplatX2(c->toInt64()));
default:
# ifdef DEBUG
logging.release();
# endif
return this;
}
}
if (input()->isWasmFloatConstant()) {
MWasmFloatConstant* c = input()->toWasmFloatConstant();
switch (simdOp()) {
case wasm::SimdOp::F32x4Splat:
return MWasmFloatConstant::NewSimd128(
alloc, SimdConstant::SplatX4(c->toFloat32()));
case wasm::SimdOp::F64x2Splat:
return MWasmFloatConstant::NewSimd128(
alloc, SimdConstant::SplatX2(c->toDouble()));
default:
# ifdef DEBUG
logging.release();
# endif
return this;
}
}
# ifdef DEBUG
logging.release();
# endif
return this;
}
template <typename T>
static bool AllTrue(const T& v) {
constexpr size_t count = sizeof(T) / sizeof(*v);
static_assert(count == 16 || count == 8 || count == 4 || count == 2);
bool result = true;
for (unsigned i = 0; i < count; i++) {
result = result && v[i] != 0;
}
return result;
}
template <typename T>
static int32_t Bitmask(const T& v) {
constexpr size_t count = sizeof(T) / sizeof(*v);
constexpr size_t shift = 8 * sizeof(*v) - 1;
static_assert(shift == 7 || shift == 15 || shift == 31 || shift == 63);
int32_t result = 0;
for (unsigned i = 0; i < count; i++) {
result = result | int32_t(((v[i] >> shift) & 1) << i);
}
return result;
}
MDefinition* MWasmReduceSimd128::foldsTo(TempAllocator& alloc) {
# ifdef DEBUG
auto logging = mozilla::MakeScopeExit([&] {
js::wasm::ReportSimdAnalysis("simd128-to-scalar -> constant folded");
});
# endif
if (input()->isWasmFloatConstant()) {
SimdConstant c = input()->toWasmFloatConstant()->toSimd128();
int32_t i32Result = 0;
switch (simdOp()) {
case wasm::SimdOp::V128AnyTrue:
i32Result = !c.isZeroBits();
break;
case wasm::SimdOp::I8x16AllTrue:
i32Result = AllTrue(
SimdConstant::CreateSimd128((int8_t*)c.bytes()).asInt8x16());
break;
case wasm::SimdOp::I8x16Bitmask:
i32Result = Bitmask(
SimdConstant::CreateSimd128((int8_t*)c.bytes()).asInt8x16());
break;
case wasm::SimdOp::I16x8AllTrue:
i32Result = AllTrue(
SimdConstant::CreateSimd128((int16_t*)c.bytes()).asInt16x8());
break;
case wasm::SimdOp::I16x8Bitmask:
i32Result = Bitmask(
SimdConstant::CreateSimd128((int16_t*)c.bytes()).asInt16x8());
break;
case wasm::SimdOp::I32x4AllTrue:
i32Result = AllTrue(
SimdConstant::CreateSimd128((int32_t*)c.bytes()).asInt32x4());
break;
case wasm::SimdOp::I32x4Bitmask:
i32Result = Bitmask(
SimdConstant::CreateSimd128((int32_t*)c.bytes()).asInt32x4());
break;
case wasm::SimdOp::I64x2AllTrue:
i32Result = AllTrue(
SimdConstant::CreateSimd128((int64_t*)c.bytes()).asInt64x2());
break;
case wasm::SimdOp::I64x2Bitmask:
i32Result = Bitmask(
SimdConstant::CreateSimd128((int64_t*)c.bytes()).asInt64x2());
break;
case wasm::SimdOp::I8x16ExtractLaneS:
i32Result =
SimdConstant::CreateSimd128((int8_t*)c.bytes()).asInt8x16()[imm()];
break;
case wasm::SimdOp::I8x16ExtractLaneU:
i32Result = int32_t(SimdConstant::CreateSimd128((int8_t*)c.bytes())
.asInt8x16()[imm()]) &
0xFF;
break;
case wasm::SimdOp::I16x8ExtractLaneS:
i32Result =
SimdConstant::CreateSimd128((int16_t*)c.bytes()).asInt16x8()[imm()];
break;
case wasm::SimdOp::I16x8ExtractLaneU:
i32Result = int32_t(SimdConstant::CreateSimd128((int16_t*)c.bytes())
.asInt16x8()[imm()]) &
0xFFFF;
break;
case wasm::SimdOp::I32x4ExtractLane:
i32Result =
SimdConstant::CreateSimd128((int32_t*)c.bytes()).asInt32x4()[imm()];
break;
case wasm::SimdOp::I64x2ExtractLane:
return MConstant::NewInt64(
alloc, SimdConstant::CreateSimd128((int64_t*)c.bytes())
.asInt64x2()[imm()]);
case wasm::SimdOp::F32x4ExtractLane:
return MWasmFloatConstant::NewFloat32(
alloc, SimdConstant::CreateSimd128((float*)c.bytes())
.asFloat32x4()[imm()]);
case wasm::SimdOp::F64x2ExtractLane:
return MWasmFloatConstant::NewDouble(
alloc, SimdConstant::CreateSimd128((double*)c.bytes())
.asFloat64x2()[imm()]);
default:
# ifdef DEBUG
logging.release();
# endif
return this;
}
return MConstant::New(alloc, Int32Value(i32Result), MIRType::Int32);
}
# ifdef DEBUG
logging.release();
# endif
return this;
}
#endif // ENABLE_WASM_SIMD
MDefinition::AliasType MLoadDynamicSlot::mightAlias(
const MDefinition* def) const {
if (def->isStoreDynamicSlot()) {
const MStoreDynamicSlot* store = def->toStoreDynamicSlot();
if (store->slot() != slot()) {
return AliasType::NoAlias;
}
if (store->slots() != slots()) {
return AliasType::MayAlias;
}
return AliasType::MustAlias;
}
return AliasType::MayAlias;
}
HashNumber MLoadDynamicSlot::valueHash() const {
HashNumber hash = MDefinition::valueHash();
hash = addU32ToHash(hash, slot_);
return hash;
}
MDefinition* MLoadDynamicSlot::foldsTo(TempAllocator& alloc) {
if (MDefinition* def = foldsToStore(alloc)) {
return def;
}
return this;
}
#ifdef JS_JITSPEW
void MLoadDynamicSlot::printOpcode(GenericPrinter& out) const {
MDefinition::printOpcode(out);
out.printf(" (slot %u)", slot());
}
void MLoadDynamicSlotAndUnbox::printOpcode(GenericPrinter& out) const {
MDefinition::printOpcode(out);
out.printf(" (slot %zu)", slot());
}
void MStoreDynamicSlot::printOpcode(GenericPrinter& out) const {
MDefinition::printOpcode(out);
out.printf(" (slot %u)", slot());
}
void MLoadFixedSlot::printOpcode(GenericPrinter& out) const {
MDefinition::printOpcode(out);
out.printf(" (slot %zu)", slot());
}
void MLoadFixedSlotAndUnbox::printOpcode(GenericPrinter& out) const {
MDefinition::printOpcode(out);
out.printf(" (slot %zu)", slot());
}
void MStoreFixedSlot::printOpcode(GenericPrinter& out) const {
MDefinition::printOpcode(out);
out.printf(" (slot %zu)", slot());
}
#endif
MDefinition* MGuardFunctionScript::foldsTo(TempAllocator& alloc) {
MDefinition* in = input();
if (in->isLambda() &&
in->toLambda()->templateFunction()->baseScript() == expected()) {
return in;
}
return this;
}
MDefinition* MFunctionEnvironment::foldsTo(TempAllocator& alloc) {
if (input()->isLambda()) {
return input()->toLambda()->environmentChain();
}
if (input()->isFunctionWithProto()) {
return input()->toFunctionWithProto()->environmentChain();
}
return this;
}
static bool AddIsANonZeroAdditionOf(MAdd* add, MDefinition* ins) {
if (add->lhs() != ins && add->rhs() != ins) {
return false;
}
MDefinition* other = (add->lhs() == ins) ? add->rhs() : add->lhs();
if (!IsNumberType(other->type())) {
return false;
}
if (!other->isConstant()) {
return false;
}
if (other->toConstant()->numberToDouble() == 0) {
return false;
}
return true;
}
// Skip over instructions that usually appear between the actual index
// value being used and the MLoadElement.
// They don't modify the index value in a meaningful way.
static MDefinition* SkipUninterestingInstructions(MDefinition* ins) {
// Drop the MToNumberInt32 added by the TypePolicy for double and float
// values.
if (ins->isToNumberInt32()) {
return SkipUninterestingInstructions(ins->toToNumberInt32()->input());
}
// Ignore the bounds check, which don't modify the index.
if (ins->isBoundsCheck()) {
return SkipUninterestingInstructions(ins->toBoundsCheck()->index());
}
// Masking the index for Spectre-mitigation is not observable.
if (ins->isSpectreMaskIndex()) {
return SkipUninterestingInstructions(ins->toSpectreMaskIndex()->index());
}
return ins;
}
static bool DefinitelyDifferentValue(MDefinition* ins1, MDefinition* ins2) {
ins1 = SkipUninterestingInstructions(ins1);
ins2 = SkipUninterestingInstructions(ins2);
if (ins1 == ins2) {
return false;
}
// For constants check they are not equal.
if (ins1->isConstant() && ins2->isConstant()) {
MConstant* cst1 = ins1->toConstant();
MConstant* cst2 = ins2->toConstant();
if (!cst1->isTypeRepresentableAsDouble() ||
!cst2->isTypeRepresentableAsDouble()) {
return false;
}
// Be conservative and only allow values that fit into int32.
int32_t n1, n2;
if (!mozilla::NumberIsInt32(cst1->numberToDouble(), &n1) ||
!mozilla::NumberIsInt32(cst2->numberToDouble(), &n2)) {
return false;
}
return n1 != n2;
}
// Check if "ins1 = ins2 + cte", which would make both instructions
// have different values.
if (ins1->isAdd()) {
if (AddIsANonZeroAdditionOf(ins1->toAdd(), ins2)) {
return true;
}
}
if (ins2->isAdd()) {
if (AddIsANonZeroAdditionOf(ins2->toAdd(), ins1)) {
return true;
}
}
return false;
}
MDefinition::AliasType MLoadElement::mightAlias(const MDefinition* def) const {
if (def->isStoreElement()) {
const MStoreElement* store = def->toStoreElement();
if (store->index() != index()) {
if (DefinitelyDifferentValue(store->index(), index())) {
return AliasType::NoAlias;
}
return AliasType::MayAlias;
}
if (store->elements() != elements()) {
return AliasType::MayAlias;
}
return AliasType::MustAlias;
}
return AliasType::MayAlias;
}
MDefinition* MLoadElement::foldsTo(TempAllocator& alloc) {
if (MDefinition* def = foldsToStore(alloc)) {
return def;
}
return this;
}
MDefinition* MWasmUnsignedToDouble::foldsTo(TempAllocator& alloc) {
if (input()->isConstant()) {
return MConstant::New(
alloc, DoubleValue(uint32_t(input()->toConstant()->toInt32())));
}
return this;
}
MDefinition* MWasmUnsignedToFloat32::foldsTo(TempAllocator& alloc) {
if (input()->isConstant()) {
double dval = double(uint32_t(input()->toConstant()->toInt32()));
if (IsFloat32Representable(dval)) {
return MConstant::NewFloat32(alloc, float(dval));
}
}
return this;
}
MWasmCallCatchable* MWasmCallCatchable::New(TempAllocator& alloc,
const wasm::CallSiteDesc& desc,
const wasm::CalleeDesc& callee,
const Args& args,
uint32_t stackArgAreaSizeUnaligned,
const MWasmCallTryDesc& tryDesc,
MDefinition* tableIndexOrRef) {
MOZ_ASSERT(tryDesc.inTry);
MWasmCallCatchable* call = new (alloc) MWasmCallCatchable(
desc, callee, stackArgAreaSizeUnaligned, tryDesc.tryNoteIndex);
call->setSuccessor(FallthroughBranchIndex, tryDesc.fallthroughBlock);
call->setSuccessor(PrePadBranchIndex, tryDesc.prePadBlock);
MOZ_ASSERT_IF(callee.isTable() || callee.isFuncRef(), tableIndexOrRef);
if (!call->initWithArgs(alloc, call, args, tableIndexOrRef)) {
return nullptr;
}
return call;
}
MWasmCallCatchable* MWasmCallCatchable::NewBuiltinInstanceMethodCall(
TempAllocator& alloc, const wasm::CallSiteDesc& desc,
const wasm::SymbolicAddress builtin, wasm::FailureMode failureMode,
const ABIArg& instanceArg, const Args& args,
uint32_t stackArgAreaSizeUnaligned, const MWasmCallTryDesc& tryDesc) {
auto callee = wasm::CalleeDesc::builtinInstanceMethod(builtin);
MWasmCallCatchable* call = MWasmCallCatchable::New(
alloc, desc, callee, args, stackArgAreaSizeUnaligned, tryDesc, nullptr);
if (!call) {
return nullptr;
}
MOZ_ASSERT(instanceArg != ABIArg());
call->instanceArg_ = instanceArg;
call->builtinMethodFailureMode_ = failureMode;
return call;
}
MWasmCallUncatchable* MWasmCallUncatchable::New(
TempAllocator& alloc, const wasm::CallSiteDesc& desc,
const wasm::CalleeDesc& callee, const Args& args,
uint32_t stackArgAreaSizeUnaligned, MDefinition* tableIndexOrRef) {
MWasmCallUncatchable* call =
new (alloc) MWasmCallUncatchable(desc, callee, stackArgAreaSizeUnaligned);
MOZ_ASSERT_IF(callee.isTable() || callee.isFuncRef(), tableIndexOrRef);
if (!call->initWithArgs(alloc, call, args, tableIndexOrRef)) {
return nullptr;
}
return call;
}
MWasmCallUncatchable* MWasmCallUncatchable::NewBuiltinInstanceMethodCall(
TempAllocator& alloc, const wasm::CallSiteDesc& desc,
const wasm::SymbolicAddress builtin, wasm::FailureMode failureMode,
const ABIArg& instanceArg, const Args& args,
uint32_t stackArgAreaSizeUnaligned) {
auto callee = wasm::CalleeDesc::builtinInstanceMethod(builtin);
MWasmCallUncatchable* call = MWasmCallUncatchable::New(
alloc, desc, callee, args, stackArgAreaSizeUnaligned, nullptr);
if (!call) {
return nullptr;
}
MOZ_ASSERT(instanceArg != ABIArg());
call->instanceArg_ = instanceArg;
call->builtinMethodFailureMode_ = failureMode;
return call;
}
MWasmReturnCall* MWasmReturnCall::New(TempAllocator& alloc,
const wasm::CallSiteDesc& desc,
const wasm::CalleeDesc& callee,
const Args& args,
uint32_t stackArgAreaSizeUnaligned,
MDefinition* tableIndexOrRef) {
MWasmReturnCall* call =
new (alloc) MWasmReturnCall(desc, callee, stackArgAreaSizeUnaligned);
MOZ_ASSERT_IF(callee.isTable() || callee.isFuncRef(), tableIndexOrRef);
if (!call->initWithArgs(alloc, call, args, tableIndexOrRef)) {
return nullptr;
}
return call;
}
void MSqrt::trySpecializeFloat32(TempAllocator& alloc) {
if (EnsureFloatConsumersAndInputOrConvert(this, alloc)) {
setResultType(MIRType::Float32);
specialization_ = MIRType::Float32;
}
}
MDefinition* MClz::foldsTo(TempAllocator& alloc) {
if (num()->isConstant()) {
MConstant* c = num()->toConstant();
if (type() == MIRType::Int32) {
int32_t n = c->toInt32();
if (n == 0) {
return MConstant::New(alloc, Int32Value(32));
}
return MConstant::New(alloc,
Int32Value(mozilla::CountLeadingZeroes32(n)));
}
int64_t n = c->toInt64();
if (n == 0) {
return MConstant::NewInt64(alloc, int64_t(64));
}
return MConstant::NewInt64(alloc,
int64_t(mozilla::CountLeadingZeroes64(n)));
}
return this;
}
MDefinition* MCtz::foldsTo(TempAllocator& alloc) {
if (num()->isConstant()) {
MConstant* c = num()->toConstant();
if (type() == MIRType::Int32) {
int32_t n = num()->toConstant()->toInt32();
if (n == 0) {
return MConstant::New(alloc, Int32Value(32));
}
return MConstant::New(alloc,
Int32Value(mozilla::CountTrailingZeroes32(n)));
}
int64_t n = c->toInt64();
if (n == 0) {
return MConstant::NewInt64(alloc, int64_t(64));
}
return MConstant::NewInt64(alloc,
int64_t(mozilla::CountTrailingZeroes64(n)));
}
return this;
}
MDefinition* MPopcnt::foldsTo(TempAllocator& alloc) {
if (num()->isConstant()) {
MConstant* c = num()->toConstant();
if (type() == MIRType::Int32) {
int32_t n = num()->toConstant()->toInt32();
return MConstant::New(alloc, Int32Value(mozilla::CountPopulation32(n)));
}
int64_t n = c->toInt64();
return MConstant::NewInt64(alloc, int64_t(mozilla::CountPopulation64(n)));
}
return this;
}
MDefinition* MBoundsCheck::foldsTo(TempAllocator& alloc) {
if (type() == MIRType::Int32 && index()->isConstant() &&
length()->isConstant()) {
uint32_t len = length()->toConstant()->toInt32();
uint32_t idx = index()->toConstant()->toInt32();
if (idx + uint32_t(minimum()) < len && idx + uint32_t(maximum()) < len) {
return index();
}
}
return this;
}
MDefinition* MTableSwitch::foldsTo(TempAllocator& alloc) {
MDefinition* op = getOperand(0);
// If we only have one successor, convert to a plain goto to the only
// successor. TableSwitch indices are numeric; other types will always go to
// the only successor.
if (numSuccessors() == 1 ||
(op->type() != MIRType::Value && !IsNumberType(op->type()))) {
return MGoto::New(alloc, getDefault());
}
if (MConstant* opConst = op->maybeConstantValue()) {
if (op->type() == MIRType::Int32) {
int32_t i = opConst->toInt32() - low_;
MBasicBlock* target;
if (size_t(i) < numCases()) {
target = getCase(size_t(i));
} else {
target = getDefault();
}
MOZ_ASSERT(target);
return MGoto::New(alloc, target);
}
}
return this;
}
MDefinition* MArrayJoin::foldsTo(TempAllocator& alloc) {
MDefinition* arr = array();
if (!arr->isStringSplit()) {
return this;
}
setRecoveredOnBailout();
if (arr->hasLiveDefUses()) {
setNotRecoveredOnBailout();
return this;
}
// The MStringSplit won't generate any code.
arr->setRecoveredOnBailout();
// We're replacing foo.split(bar).join(baz) by
// foo.replace(bar, baz). MStringSplit could be recovered by
// a bailout. As we are removing its last use, and its result
// could be captured by a resume point, this MStringSplit will
// be executed on the bailout path.
MDefinition* string = arr->toStringSplit()->string();
MDefinition* pattern = arr->toStringSplit()->separator();
MDefinition* replacement = sep();
MStringReplace* substr =
MStringReplace::New(alloc, string, pattern, replacement);
substr->setFlatReplacement();
return substr;
}
MDefinition* MGetFirstDollarIndex::foldsTo(TempAllocator& alloc) {
MDefinition* strArg = str();
if (!strArg->isConstant()) {
return this;
}
JSLinearString* str = &strArg->toConstant()->toString()->asLinear();
int32_t index = GetFirstDollarIndexRawFlat(str);
return MConstant::New(alloc, Int32Value(index));
}
AliasSet MThrowRuntimeLexicalError::getAliasSet() const {
return AliasSet::Store(AliasSet::ExceptionState);
}
AliasSet MSlots::getAliasSet() const {
return AliasSet::Load(AliasSet::ObjectFields);
}
MDefinition::AliasType MSlots::mightAlias(const MDefinition* store) const {
// ArrayPush only modifies object elements, but not object slots.
if (store->isArrayPush()) {
return AliasType::NoAlias;
}
return MInstruction::mightAlias(store);
}
AliasSet MElements::getAliasSet() const {
return AliasSet::Load(AliasSet::ObjectFields);
}
AliasSet MInitializedLength::getAliasSet() const {
return AliasSet::Load(AliasSet::ObjectFields);
}
AliasSet MSetInitializedLength::getAliasSet() const {
return AliasSet::Store(AliasSet::ObjectFields);
}
AliasSet MObjectKeysLength::getAliasSet() const {
return AliasSet::Load(AliasSet::ObjectFields);
}
AliasSet MArrayLength::getAliasSet() const {
return AliasSet::Load(AliasSet::ObjectFields);
}
AliasSet MSetArrayLength::getAliasSet() const {
return AliasSet::Store(AliasSet::ObjectFields);
}
AliasSet MFunctionLength::getAliasSet() const {
return AliasSet::Load(AliasSet::ObjectFields | AliasSet::FixedSlot |
AliasSet::DynamicSlot);
}
AliasSet MFunctionName::getAliasSet() const {
return AliasSet::Load(AliasSet::ObjectFields | AliasSet::FixedSlot |
AliasSet::DynamicSlot);
}
AliasSet MArrayBufferByteLength::getAliasSet() const {
return AliasSet::Load(AliasSet::FixedSlot);
}
AliasSet MArrayBufferViewLength::getAliasSet() const {
return AliasSet::Load(AliasSet::ArrayBufferViewLengthOrOffset);
}
AliasSet MArrayBufferViewByteOffset::getAliasSet() const {
return AliasSet::Load(AliasSet::ArrayBufferViewLengthOrOffset);
}
AliasSet MArrayBufferViewElements::getAliasSet() const {
return AliasSet::Load(AliasSet::ObjectFields);
}
AliasSet MGuardHasAttachedArrayBuffer::getAliasSet() const {
return AliasSet::Load(AliasSet::ObjectFields | AliasSet::FixedSlot);
}
AliasSet MResizableTypedArrayByteOffsetMaybeOutOfBounds::getAliasSet() const {
// Loads the byteOffset and additionally checks for detached buffers, so the
// alias set also has to include |ObjectFields| and |FixedSlot|.
return AliasSet::Load(AliasSet::ArrayBufferViewLengthOrOffset |
AliasSet::ObjectFields | AliasSet::FixedSlot);
}
AliasSet MResizableTypedArrayLength::getAliasSet() const {
// Loads the length and byteOffset slots, the shared-elements flag, the
// auto-length fixed slot, and the shared raw-buffer length.
auto flags = AliasSet::ArrayBufferViewLengthOrOffset |
AliasSet::ObjectFields | AliasSet::FixedSlot |
AliasSet::SharedArrayRawBufferLength;
// When a barrier is needed make the instruction effectful by giving it a
// "store" effect. Also prevent reordering LoadUnboxedScalar before this
// instruction by including |UnboxedElement| in the alias set.
if (requiresMemoryBarrier() == MemoryBarrierRequirement::Required) {
return AliasSet::Store(flags | AliasSet::UnboxedElement);
}
return AliasSet::Load(flags);
}
bool MResizableTypedArrayLength::congruentTo(const MDefinition* ins) const {
if (requiresMemoryBarrier() == MemoryBarrierRequirement::Required) {
return false;
}
return congruentIfOperandsEqual(ins);
}
AliasSet MResizableDataViewByteLength::getAliasSet() const {
// Loads the length and byteOffset slots, the shared-elements flag, the
// auto-length fixed slot, and the shared raw-buffer length.
auto flags = AliasSet::ArrayBufferViewLengthOrOffset |
AliasSet::ObjectFields | AliasSet::FixedSlot |
AliasSet::SharedArrayRawBufferLength;
// When a barrier is needed make the instruction effectful by giving it a
// "store" effect. Also prevent reordering LoadUnboxedScalar before this
// instruction by including |UnboxedElement| in the alias set.
if (requiresMemoryBarrier() == MemoryBarrierRequirement::Required) {
return AliasSet::Store(flags | AliasSet::UnboxedElement);
}
return AliasSet::Load(flags);
}
bool MResizableDataViewByteLength::congruentTo(const MDefinition* ins) const {
if (requiresMemoryBarrier() == MemoryBarrierRequirement::Required) {
return false;
}
return congruentIfOperandsEqual(ins);
}
AliasSet MGrowableSharedArrayBufferByteLength::getAliasSet() const {
// Requires a barrier, so make the instruction effectful by giving it a
// "store" effect. Also prevent reordering LoadUnboxedScalar before this
// instruction by including |UnboxedElement| in the alias set.
return AliasSet::Store(AliasSet::FixedSlot |
AliasSet::SharedArrayRawBufferLength |
AliasSet::UnboxedElement);
}
AliasSet MGuardResizableArrayBufferViewInBounds::getAliasSet() const {
// Additionally reads the |initialLength| and |initialByteOffset| slots, but
// since these can't change after construction, we don't need to track them.
return AliasSet::Load(AliasSet::ArrayBufferViewLengthOrOffset);
}
AliasSet MGuardResizableArrayBufferViewInBoundsOrDetached::getAliasSet() const {
// Loads the byteOffset and additionally checks for detached buffers, so the
// alias set also has to include |ObjectFields| and |FixedSlot|.
return AliasSet::Load(AliasSet::ArrayBufferViewLengthOrOffset |
AliasSet::ObjectFields | AliasSet::FixedSlot);
}
AliasSet MArrayPush::getAliasSet() const {
return AliasSet::Store(AliasSet::ObjectFields | AliasSet::Element);
}
MDefinition* MGuardNumberToIntPtrIndex::foldsTo(TempAllocator& alloc) {
MDefinition* input = this->input();
if (input->isToDouble() && input->getOperand(0)->type() == MIRType::Int32) {
return MInt32ToIntPtr::New(alloc, input->getOperand(0));
}
if (!input->isConstant()) {
return this;
}
// Fold constant double representable as intptr to intptr.
int64_t ival;
if (!mozilla::NumberEqualsInt64(input->toConstant()->toDouble(), &ival)) {
// If not representable as an int64, this access is equal to an OOB access.
// So replace it with a known int64/intptr value which also produces an OOB
// access. If we don't support OOB accesses we have to bail out.
if (!supportOOB()) {
return this;
}
ival = -1;
}
if (ival < INTPTR_MIN || ival > INTPTR_MAX) {
return this;
}
return MConstant::NewIntPtr(alloc, intptr_t(ival));
}
MDefinition* MIsObject::foldsTo(TempAllocator& alloc) {
if (!object()->isBox()) {
return this;
}
MDefinition* unboxed = object()->getOperand(0);
if (unboxed->type() == MIRType::Object) {
return MConstant::New(alloc, BooleanValue(true));
}
return this;
}
MDefinition* MIsNullOrUndefined::foldsTo(TempAllocator& alloc) {
MDefinition* input = value();
if (input->isBox()) {
input = input->toBox()->input();
}
if (input->definitelyType({MIRType::Null, MIRType::Undefined})) {
return MConstant::New(alloc, BooleanValue(true));
}
if (!input->mightBeType(MIRType::Null) &&
!input->mightBeType(MIRType::Undefined)) {
return MConstant::New(alloc, BooleanValue(false));
}
return this;
}
AliasSet MHomeObjectSuperBase::getAliasSet() const {
return AliasSet::Load(AliasSet::ObjectFields);
}
MDefinition* MGuardValue::foldsTo(TempAllocator& alloc) {
if (MConstant* cst = value()->maybeConstantValue()) {
if (cst->toJSValue() == expected()) {
return value();
}
}
return this;
}
MDefinition* MGuardNullOrUndefined::foldsTo(TempAllocator& alloc) {
MDefinition* input = value();
if (input->isBox()) {
input = input->toBox()->input();
}
if (input->definitelyType({MIRType::Null, MIRType::Undefined})) {
return value();
}
return this;
}
MDefinition* MGuardIsNotObject::foldsTo(TempAllocator& alloc) {
MDefinition* input = value();
if (input->isBox()) {
input = input->toBox()->input();
}
if (!input->mightBeType(MIRType::Object)) {
return value();
}
return this;
}
MDefinition* MGuardObjectIdentity::foldsTo(TempAllocator& alloc) {
if (object()->isConstant() && expected()->isConstant()) {
JSObject* obj = &object()->toConstant()->toObject();
JSObject* other = &expected()->toConstant()->toObject();
if (!bailOnEquality()) {
if (obj == other) {
return object();
}
} else {
if (obj != other) {
return object();
}
}
}
if (!bailOnEquality() && object()->isNurseryObject() &&
expected()->isNurseryObject()) {
uint32_t objIndex = object()->toNurseryObject()->nurseryIndex();
uint32_t otherIndex = expected()->toNurseryObject()->nurseryIndex();
if (objIndex == otherIndex) {
return object();
}
}
return this;
}
MDefinition* MGuardSpecificFunction::foldsTo(TempAllocator& alloc) {
if (function()->isConstant() && expected()->isConstant()) {
JSObject* fun = &function()->toConstant()->toObject();
JSObject* other = &expected()->toConstant()->toObject();
if (fun == other) {
return function();
}
}
if (function()->isNurseryObject() && expected()->isNurseryObject()) {
uint32_t funIndex = function()->toNurseryObject()->nurseryIndex();
uint32_t otherIndex = expected()->toNurseryObject()->nurseryIndex();
if (funIndex == otherIndex) {
return function();
}
}
return this;
}
MDefinition* MGuardSpecificAtom::foldsTo(TempAllocator& alloc) {
if (str()->isConstant()) {
JSString* s = str()->toConstant()->toString();
if (s->isAtom()) {
JSAtom* cstAtom = &s->asAtom();
if (cstAtom == atom()) {
return str();
}
}
}
return this;
}
MDefinition* MGuardSpecificSymbol::foldsTo(TempAllocator& alloc) {
if (symbol()->isConstant()) {
if (symbol()->toConstant()->toSymbol() == expected()) {
return symbol();
}
}
return this;
}
MDefinition* MGuardSpecificInt32::foldsTo(TempAllocator& alloc) {
if (num()->isConstant() && num()->toConstant()->isInt32(expected())) {
return num();
}
return this;
}
bool MCallBindVar::congruentTo(const MDefinition* ins) const {
if (!ins->isCallBindVar()) {
return false;
}
return congruentIfOperandsEqual(ins);
}
bool MGuardShape::congruentTo(const MDefinition* ins) const {
if (!ins->isGuardShape()) {
return false;
}
if (shape() != ins->toGuardShape()->shape()) {
return false;
}
return congruentIfOperandsEqual(ins);
}
AliasSet MGuardShape::getAliasSet() const {
return AliasSet::Load(AliasSet::ObjectFields);
}
MDefinition::AliasType MGuardShape::mightAlias(const MDefinition* store) const {
// These instructions only modify object elements, but not the shape.
if (store->isStoreElementHole() || store->isArrayPush()) {
return AliasType::NoAlias;
}
if (object()->isConstantProto()) {
const MDefinition* receiverObject =
object()->toConstantProto()->getReceiverObject();
switch (store->op()) {
case MDefinition::Opcode::StoreFixedSlot:
if (store->toStoreFixedSlot()->object()->skipObjectGuards() ==
receiverObject) {
return AliasType::NoAlias;
}
break;
case MDefinition::Opcode::StoreDynamicSlot:
if (store->toStoreDynamicSlot()
->slots()
->toSlots()
->object()
->skipObjectGuards() == receiverObject) {
return AliasType::NoAlias;
}
break;
case MDefinition::Opcode::AddAndStoreSlot:
if (store->toAddAndStoreSlot()->object()->skipObjectGuards() ==
receiverObject) {
return AliasType::NoAlias;
}
break;
case MDefinition::Opcode::AllocateAndStoreSlot:
if (store->toAllocateAndStoreSlot()->object()->skipObjectGuards() ==
receiverObject) {
return AliasType::NoAlias;
}
break;
default:
break;
}
}
return MInstruction::mightAlias(store);
}
bool MGuardFuse::congruentTo(const MDefinition* ins) const {
if (!ins->isGuardFuse()) {
return false;
}
if (fuseIndex() != ins->toGuardFuse()->fuseIndex()) {
return false;
}
return congruentIfOperandsEqual(ins);
}
AliasSet MGuardFuse::getAliasSet() const {
// The alias set below reflects the set of operations which could cause a fuse
// to be popped, and therefore MGuardFuse aliases with.
return AliasSet::Load(AliasSet::ObjectFields | AliasSet::DynamicSlot |
AliasSet::FixedSlot |
AliasSet::GlobalGenerationCounter);
}
AliasSet MGuardMultipleShapes::getAliasSet() const {
// Note: This instruction loads the elements of the ListObject used to
// store the list of shapes, but that object is internal and not exposed
// to script, so it doesn't have to be in the alias set.
return AliasSet::Load(AliasSet::ObjectFields);
}
AliasSet MGuardGlobalGeneration::getAliasSet() const {
return AliasSet::Load(AliasSet::GlobalGenerationCounter);
}
bool MGuardGlobalGeneration::congruentTo(const MDefinition* ins) const {
return ins->isGuardGlobalGeneration() &&
ins->toGuardGlobalGeneration()->expected() == expected() &&
ins->toGuardGlobalGeneration()->generationAddr() == generationAddr();
}
MDefinition* MGuardIsNotProxy::foldsTo(TempAllocator& alloc) {
KnownClass known = GetObjectKnownClass(object());
if (known == KnownClass::None) {
return this;
}
MOZ_ASSERT(!GetObjectKnownJSClass(object())->isProxyObject());
AssertKnownClass(alloc, this, object());
return object();
}
AliasSet MMegamorphicLoadSlotByValue::getAliasSet() const {
return AliasSet::Load(AliasSet::ObjectFields | AliasSet::FixedSlot |
AliasSet::DynamicSlot);
}
MDefinition* MMegamorphicLoadSlotByValue::foldsTo(TempAllocator& alloc) {
MDefinition* input = idVal();
if (input->isBox()) {
input = input->toBox()->input();
}
MDefinition* result = this;
if (input->isConstant()) {
MConstant* constant = input->toConstant();
if (constant->type() == MIRType::Symbol) {
PropertyKey id = PropertyKey::Symbol(constant->toSymbol());
result = MMegamorphicLoadSlot::New(alloc, object(), id);
}
if (constant->type() == MIRType::String) {
JSString* str = constant->toString();
if (str->isAtom() && !str->asAtom().isIndex()) {
PropertyKey id = PropertyKey::NonIntAtom(str);
result = MMegamorphicLoadSlot::New(alloc, object(), id);
}
}
}
if (result != this) {
result->setDependency(dependency());
}
return result;
}
bool MMegamorphicLoadSlot::congruentTo(const MDefinition* ins) const {
if (!ins->isMegamorphicLoadSlot()) {
return false;
}
if (ins->toMegamorphicLoadSlot()->name() != name()) {
return false;
}
return congruentIfOperandsEqual(ins);
}
AliasSet MMegamorphicLoadSlot::getAliasSet() const {
return AliasSet::Load(AliasSet::ObjectFields | AliasSet::FixedSlot |
AliasSet::DynamicSlot);
}
bool MSmallObjectVariableKeyHasProp::congruentTo(const MDefinition* ins) const {
if (!ins->isSmallObjectVariableKeyHasProp()) {
return false;
}
if (ins->toSmallObjectVariableKeyHasProp()->shape() != shape()) {
return false;
}
return congruentIfOperandsEqual(ins);
}
AliasSet MSmallObjectVariableKeyHasProp::getAliasSet() const {
return AliasSet::Load(AliasSet::ObjectFields | AliasSet::FixedSlot |
AliasSet::DynamicSlot);
}
bool MMegamorphicHasProp::congruentTo(const MDefinition* ins) const {
if (!ins->isMegamorphicHasProp()) {
return false;
}
if (ins->toMegamorphicHasProp()->hasOwn() != hasOwn()) {
return false;
}
return congruentIfOperandsEqual(ins);
}
AliasSet MMegamorphicHasProp::getAliasSet() const {
return AliasSet::Load(AliasSet::ObjectFields | AliasSet::FixedSlot |
AliasSet::DynamicSlot);
}
bool MNurseryObject::congruentTo(const MDefinition* ins) const {
if (!ins->isNurseryObject()) {
return false;
}
return nurseryIndex() == ins->toNurseryObject()->nurseryIndex();
}
AliasSet MGuardFunctionIsNonBuiltinCtor::getAliasSet() const {
return AliasSet::Load(AliasSet::ObjectFields);
}
bool MGuardFunctionKind::congruentTo(const MDefinition* ins) const {
if (!ins->isGuardFunctionKind()) {
return false;
}
if (expected() != ins->toGuardFunctionKind()->expected()) {
return false;
}
if (bailOnEquality() != ins->toGuardFunctionKind()->bailOnEquality()) {
return false;
}
return congruentIfOperandsEqual(ins);
}
AliasSet MGuardFunctionKind::getAliasSet() const {
return AliasSet::Load(AliasSet::ObjectFields);
}
bool MGuardFunctionScript::congruentTo(const MDefinition* ins) const {
if (!ins->isGuardFunctionScript()) {
return false;
}
if (expected() != ins->toGuardFunctionScript()->expected()) {
return false;
}
return congruentIfOperandsEqual(ins);
}
AliasSet MGuardFunctionScript::getAliasSet() const {
// A JSFunction's BaseScript pointer is immutable. Relazification of
// top-level/named self-hosted functions is an exception to this, but we don't
// use this guard for those self-hosted functions.
// See IRGenerator::emitCalleeGuard.
MOZ_ASSERT_IF(flags_.isSelfHostedOrIntrinsic(), flags_.isLambda());
return AliasSet::None();
}
bool MGuardSpecificAtom::congruentTo(const MDefinition* ins) const {
if (!ins->isGuardSpecificAtom()) {
return false;
}
if (atom() != ins->toGuardSpecificAtom()->atom()) {
return false;
}
return congruentIfOperandsEqual(ins);
}
MDefinition* MGuardStringToIndex::foldsTo(TempAllocator& alloc) {
if (!string()->isConstant()) {
return this;
}
JSString* str = string()->toConstant()->toString();
int32_t index = GetIndexFromString(str);
if (index < 0) {
return this;
}
return MConstant::New(alloc, Int32Value(index));
}
MDefinition* MGuardStringToInt32::foldsTo(TempAllocator& alloc) {
if (!string()->isConstant()) {
return this;
}
JSLinearString* str = &string()->toConstant()->toString()->asLinear();
double number = LinearStringToNumber(str);
int32_t n;
if (!mozilla::NumberIsInt32(number, &n)) {
return this;
}
return MConstant::New(alloc, Int32Value(n));
}
MDefinition* MGuardStringToDouble::foldsTo(TempAllocator& alloc) {
if (!string()->isConstant()) {
return this;
}
JSLinearString* str = &string()->toConstant()->toString()->asLinear();
double number = LinearStringToNumber(str);
return MConstant::New(alloc, DoubleValue(number));
}
AliasSet MGuardNoDenseElements::getAliasSet() const {
return AliasSet::Load(AliasSet::ObjectFields);
}
AliasSet MIteratorHasIndices::getAliasSet() const {
return AliasSet::Load(AliasSet::ObjectFields);
}
AliasSet MAllocateAndStoreSlot::getAliasSet() const {
return AliasSet::Store(AliasSet::ObjectFields | AliasSet::DynamicSlot);
}
AliasSet MLoadDOMExpandoValue::getAliasSet() const {
return AliasSet::Load(AliasSet::DOMProxyExpando);
}
AliasSet MLoadDOMExpandoValueIgnoreGeneration::getAliasSet() const {
return AliasSet::Load(AliasSet::DOMProxyExpando);
}
bool MGuardDOMExpandoMissingOrGuardShape::congruentTo(
const MDefinition* ins) const {
if (!ins->isGuardDOMExpandoMissingOrGuardShape()) {
return false;
}
if (shape() != ins->toGuardDOMExpandoMissingOrGuardShape()->shape()) {
return false;
}
return congruentIfOperandsEqual(ins);
}
AliasSet MGuardDOMExpandoMissingOrGuardShape::getAliasSet() const {
return AliasSet::Load(AliasSet::ObjectFields);
}
MDefinition* MGuardToClass::foldsTo(TempAllocator& alloc) {
const JSClass* clasp = GetObjectKnownJSClass(object());
if (!clasp || getClass() != clasp) {
return this;
}
AssertKnownClass(alloc, this, object());
return object();
}
MDefinition* MGuardToEitherClass::foldsTo(TempAllocator& alloc) {
const JSClass* clasp = GetObjectKnownJSClass(object());
if (!clasp || (getClass1() != clasp && getClass2() != clasp)) {
return this;
}
AssertKnownClass(alloc, this, object());
return object();
}
MDefinition* MGuardToFunction::foldsTo(TempAllocator& alloc) {
if (GetObjectKnownClass(object()) != KnownClass::Function) {
return this;
}
AssertKnownClass(alloc, this, object());
return object();
}
MDefinition* MHasClass::foldsTo(TempAllocator& alloc) {
const JSClass* clasp = GetObjectKnownJSClass(object());
if (!clasp) {
return this;
}
AssertKnownClass(alloc, this, object());
return MConstant::New(alloc, BooleanValue(getClass() == clasp));
}
MDefinition* MIsCallable::foldsTo(TempAllocator& alloc) {
if (input()->type() != MIRType::Object) {
return this;
}
KnownClass known = GetObjectKnownClass(input());
if (known == KnownClass::None) {
return this;
}
AssertKnownClass(alloc, this, input());
return MConstant::New(alloc, BooleanValue(known == KnownClass::Function));
}
MDefinition* MIsArray::foldsTo(TempAllocator& alloc) {
if (input()->type() != MIRType::Object) {
return this;
}
KnownClass known = GetObjectKnownClass(input());
if (known == KnownClass::None) {
return this;
}
AssertKnownClass(alloc, this, input());
return MConstant::New(alloc, BooleanValue(known == KnownClass::Array));
}
AliasSet MObjectClassToString::getAliasSet() const {
return AliasSet::Load(AliasSet::ObjectFields | AliasSet::FixedSlot |
AliasSet::DynamicSlot);
}
MDefinition* MGuardIsNotArrayBufferMaybeShared::foldsTo(TempAllocator& alloc) {
switch (GetObjectKnownClass(object())) {
case KnownClass::PlainObject:
case KnownClass::Array:
case KnownClass::Function:
case KnownClass::RegExp:
case KnownClass::ArrayIterator:
case KnownClass::StringIterator:
case KnownClass::RegExpStringIterator: {
AssertKnownClass(alloc, this, object());
return object();
}
case KnownClass::None:
break;
}
return this;
}
MDefinition* MCheckIsObj::foldsTo(TempAllocator& alloc) {
if (!input()->isBox()) {
return this;
}
MDefinition* unboxed = input()->getOperand(0);
if (unboxed->type() == MIRType::Object) {
return unboxed;
}
return this;
}
AliasSet MCheckIsObj::getAliasSet() const {
return AliasSet::Store(AliasSet::ExceptionState);
}
#ifdef JS_PUNBOX64
AliasSet MCheckScriptedProxyGetResult::getAliasSet() const {
return AliasSet::Store(AliasSet::ExceptionState);
}
#endif
static bool IsBoxedObject(MDefinition* def) {
MOZ_ASSERT(def->type() == MIRType::Value);
if (def->isBox()) {
return def->toBox()->input()->type() == MIRType::Object;
}
// Construct calls are always returning a boxed object.
//
// TODO: We should consider encoding this directly in the graph instead of
// having to special case it here.
if (def->isCall()) {
return def->toCall()->isConstructing();
}
if (def->isConstructArray()) {
return true;
}
if (def->isConstructArgs()) {
return true;
}
return false;
}
MDefinition* MCheckReturn::foldsTo(TempAllocator& alloc) {
auto* returnVal = returnValue();
if (!returnVal->isBox()) {
return this;
}
auto* unboxedReturnVal = returnVal->toBox()->input();
if (unboxedReturnVal->type() == MIRType::Object) {
return returnVal;
}
if (unboxedReturnVal->type() != MIRType::Undefined) {
return this;
}
auto* thisVal = thisValue();
if (IsBoxedObject(thisVal)) {
return thisVal;
}
return this;
}
MDefinition* MCheckThis::foldsTo(TempAllocator& alloc) {
MDefinition* input = thisValue();
if (!input->isBox()) {
return this;
}
MDefinition* unboxed = input->getOperand(0);
if (unboxed->mightBeMagicType()) {
return this;
}
return input;
}
MDefinition* MCheckThisReinit::foldsTo(TempAllocator& alloc) {
MDefinition* input = thisValue();
if (!input->isBox()) {
return this;
}
MDefinition* unboxed = input->getOperand(0);
if (unboxed->type() != MIRType::MagicUninitializedLexical) {
return this;
}
return input;
}
MDefinition* MCheckObjCoercible::foldsTo(TempAllocator& alloc) {
MDefinition* input = checkValue();
if (!input->isBox()) {
return this;
}
MDefinition* unboxed = input->getOperand(0);
if (unboxed->mightBeType(MIRType::Null) ||
unboxed->mightBeType(MIRType::Undefined)) {
return this;
}
return input;
}
AliasSet MCheckObjCoercible::getAliasSet() const {
return AliasSet::Store(AliasSet::ExceptionState);
}
AliasSet MCheckReturn::getAliasSet() const {
return AliasSet::Store(AliasSet::ExceptionState);
}
AliasSet MCheckThis::getAliasSet() const {
return AliasSet::Store(AliasSet::ExceptionState);
}
AliasSet MCheckThisReinit::getAliasSet() const {
return AliasSet::Store(AliasSet::ExceptionState);
}
AliasSet MIsPackedArray::getAliasSet() const {
return AliasSet::Load(AliasSet::ObjectFields);
}
AliasSet MGuardArrayIsPacked::getAliasSet() const {
return AliasSet::Load(AliasSet::ObjectFields);
}
AliasSet MSuperFunction::getAliasSet() const {
return AliasSet::Load(AliasSet::ObjectFields);
}
AliasSet MInitHomeObject::getAliasSet() const {
return AliasSet::Store(AliasSet::ObjectFields);
}
AliasSet MLoadWrapperTarget::getAliasSet() const {
return AliasSet::Load(AliasSet::Any);
}
bool MLoadWrapperTarget::congruentTo(const MDefinition* ins) const {
if (!ins->isLoadWrapperTarget()) {
return false;
}
if (ins->toLoadWrapperTarget()->fallible() != fallible()) {
return false;
}
return congruentIfOperandsEqual(ins);
}
AliasSet MGuardHasGetterSetter::getAliasSet() const {
return AliasSet::Load(AliasSet::ObjectFields);
}
bool MGuardHasGetterSetter::congruentTo(const MDefinition* ins) const {
if (!ins->isGuardHasGetterSetter()) {
return false;
}
if (ins->toGuardHasGetterSetter()->propId() != propId()) {
return false;
}
if (ins->toGuardHasGetterSetter()->getterSetter() != getterSetter()) {
return false;
}
return congruentIfOperandsEqual(ins);
}
AliasSet MGuardIsExtensible::getAliasSet() const {
return AliasSet::Load(AliasSet::ObjectFields);
}
AliasSet MGuardIndexIsNotDenseElement::getAliasSet() const {
return AliasSet::Load(AliasSet::ObjectFields | AliasSet::Element);
}
AliasSet MGuardIndexIsValidUpdateOrAdd::getAliasSet() const {
return AliasSet::Load(AliasSet::ObjectFields);
}
AliasSet MCallObjectHasSparseElement::getAliasSet() const {
return AliasSet::Load(AliasSet::Element | AliasSet::ObjectFields |
AliasSet::FixedSlot | AliasSet::DynamicSlot);
}
AliasSet MLoadSlotByIteratorIndex::getAliasSet() const {
return AliasSet::Load(AliasSet::ObjectFields | AliasSet::FixedSlot |
AliasSet::DynamicSlot | AliasSet::Element);
}
AliasSet MStoreSlotByIteratorIndex::getAliasSet() const {
return AliasSet::Store(AliasSet::ObjectFields | AliasSet::FixedSlot |
AliasSet::DynamicSlot | AliasSet::Element);
}
MDefinition* MGuardInt32IsNonNegative::foldsTo(TempAllocator& alloc) {
MOZ_ASSERT(index()->type() == MIRType::Int32);
MDefinition* input = index();
if (!input->isConstant() || input->toConstant()->toInt32() < 0) {
return this;
}
return input;
}
MDefinition* MGuardInt32Range::foldsTo(TempAllocator& alloc) {
MOZ_ASSERT(input()->type() == MIRType::Int32);
MOZ_ASSERT(minimum() <= maximum());
MDefinition* in = input();
if (!in->isConstant()) {
return this;
}
int32_t cst = in->toConstant()->toInt32();
if (cst < minimum() || cst > maximum()) {
return this;
}
return in;
}
MDefinition* MGuardNonGCThing::foldsTo(TempAllocator& alloc) {
if (!input()->isBox()) {
return this;
}
MDefinition* unboxed = input()->getOperand(0);
if (!IsNonGCThing(unboxed->type())) {
return this;
}
return input();
}
AliasSet MSetObjectHasNonBigInt::getAliasSet() const {
return AliasSet::Load(AliasSet::MapOrSetHashTable);
}
AliasSet MSetObjectHasBigInt::getAliasSet() const {
return AliasSet::Load(AliasSet::MapOrSetHashTable);
}
AliasSet MSetObjectHasValue::getAliasSet() const {
return AliasSet::Load(AliasSet::MapOrSetHashTable);
}
AliasSet MSetObjectHasValueVMCall::getAliasSet() const {
return AliasSet::Load(AliasSet::MapOrSetHashTable);
}
AliasSet MSetObjectSize::getAliasSet() const {
return AliasSet::Load(AliasSet::MapOrSetHashTable);
}
AliasSet MMapObjectHasNonBigInt::getAliasSet() const {
return AliasSet::Load(AliasSet::MapOrSetHashTable);
}
AliasSet MMapObjectHasBigInt::getAliasSet() const {
return AliasSet::Load(AliasSet::MapOrSetHashTable);
}
AliasSet MMapObjectHasValue::getAliasSet() const {
return AliasSet::Load(AliasSet::MapOrSetHashTable);
}
AliasSet MMapObjectHasValueVMCall::getAliasSet() const {
return AliasSet::Load(AliasSet::MapOrSetHashTable);
}
AliasSet MMapObjectGetNonBigInt::getAliasSet() const {
return AliasSet::Load(AliasSet::MapOrSetHashTable);
}
AliasSet MMapObjectGetBigInt::getAliasSet() const {
return AliasSet::Load(AliasSet::MapOrSetHashTable);
}
AliasSet MMapObjectGetValue::getAliasSet() const {
return AliasSet::Load(AliasSet::MapOrSetHashTable);
}
AliasSet MMapObjectGetValueVMCall::getAliasSet() const {
return AliasSet::Load(AliasSet::MapOrSetHashTable);
}
AliasSet MMapObjectSize::getAliasSet() const {
return AliasSet::Load(AliasSet::MapOrSetHashTable);
}
MIonToWasmCall* MIonToWasmCall::New(TempAllocator& alloc,
WasmInstanceObject* instanceObj,
const wasm::FuncExport& funcExport) {
const wasm::FuncType& funcType =
instanceObj->instance().metadata().getFuncExportType(funcExport);
const wasm::ValTypeVector& results = funcType.results();
MIRType resultType = MIRType::Value;
// At the JS boundary some wasm types must be represented as a Value, and in
// addition a void return requires an Undefined value.
if (results.length() > 0 && !results[0].isEncodedAsJSValueOnEscape()) {
MOZ_ASSERT(results.length() == 1,
"multiple returns not implemented for inlined Wasm calls");
resultType = results[0].toMIRType();
}
auto* ins = new (alloc) MIonToWasmCall(instanceObj, resultType, funcExport);
if (!ins->init(alloc, funcType.args().length())) {
return nullptr;
}
return ins;
}
MBindFunction* MBindFunction::New(TempAllocator& alloc, MDefinition* target,
uint32_t argc, JSObject* templateObj) {
auto* ins = new (alloc) MBindFunction(templateObj);
if (!ins->init(alloc, NumNonArgumentOperands + argc)) {
return nullptr;
}
ins->initOperand(0, target);
return ins;
}
#ifdef DEBUG
bool MIonToWasmCall::isConsistentFloat32Use(MUse* use) const {
const wasm::FuncType& funcType =
instance()->metadata().getFuncExportType(funcExport_);
return funcType.args()[use->index()].kind() == wasm::ValType::F32;
}
#endif
MCreateInlinedArgumentsObject* MCreateInlinedArgumentsObject::New(
TempAllocator& alloc, MDefinition* callObj, MDefinition* callee,
MDefinitionVector& args, ArgumentsObject* templateObj) {
MCreateInlinedArgumentsObject* ins =
new (alloc) MCreateInlinedArgumentsObject(templateObj);
uint32_t argc = args.length();
MOZ_ASSERT(argc <= ArgumentsObject::MaxInlinedArgs);
if (!ins->init(alloc, argc + NumNonArgumentOperands)) {
return nullptr;
}
ins->initOperand(0, callObj);
ins->initOperand(1, callee);
for (uint32_t i = 0; i < argc; i++) {
ins->initOperand(i + NumNonArgumentOperands, args[i]);
}
return ins;
}
MGetInlinedArgument* MGetInlinedArgument::New(
TempAllocator& alloc, MDefinition* index,
MCreateInlinedArgumentsObject* args) {
MGetInlinedArgument* ins = new (alloc) MGetInlinedArgument();
uint32_t argc = args->numActuals();
MOZ_ASSERT(argc <= ArgumentsObject::MaxInlinedArgs);
if (!ins->init(alloc, argc + NumNonArgumentOperands)) {
return nullptr;
}
ins->initOperand(0, index);
for (uint32_t i = 0; i < argc; i++) {
ins->initOperand(i + NumNonArgumentOperands, args->getArg(i));
}
return ins;
}
MGetInlinedArgument* MGetInlinedArgument::New(TempAllocator& alloc,
MDefinition* index,
const CallInfo& callInfo) {
MGetInlinedArgument* ins = new (alloc) MGetInlinedArgument();
uint32_t argc = callInfo.argc();
MOZ_ASSERT(argc <= ArgumentsObject::MaxInlinedArgs);
if (!ins->init(alloc, argc + NumNonArgumentOperands)) {
return nullptr;
}
ins->initOperand(0, index);
for (uint32_t i = 0; i < argc; i++) {
ins->initOperand(i + NumNonArgumentOperands, callInfo.getArg(i));
}
return ins;
}
MDefinition* MGetInlinedArgument::foldsTo(TempAllocator& alloc) {
MDefinition* indexDef = SkipUninterestingInstructions(index());
if (!indexDef->isConstant() || indexDef->type() != MIRType::Int32) {
return this;
}
int32_t indexConst = indexDef->toConstant()->toInt32();
if (indexConst < 0 || uint32_t(indexConst) >= numActuals()) {
return this;
}
MDefinition* arg = getArg(indexConst);
if (arg->type() != MIRType::Value) {
arg = MBox::New(alloc, arg);
}
return arg;
}
MGetInlinedArgumentHole* MGetInlinedArgumentHole::New(
TempAllocator& alloc, MDefinition* index,
MCreateInlinedArgumentsObject* args) {
auto* ins = new (alloc) MGetInlinedArgumentHole();
uint32_t argc = args->numActuals();
MOZ_ASSERT(argc <= ArgumentsObject::MaxInlinedArgs);
if (!ins->init(alloc, argc + NumNonArgumentOperands)) {
return nullptr;
}
ins->initOperand(0, index);
for (uint32_t i = 0; i < argc; i++) {
ins->initOperand(i + NumNonArgumentOperands, args->getArg(i));
}
return ins;
}
MDefinition* MGetInlinedArgumentHole::foldsTo(TempAllocator& alloc) {
MDefinition* indexDef = SkipUninterestingInstructions(index());
if (!indexDef->isConstant() || indexDef->type() != MIRType::Int32) {
return this;
}
int32_t indexConst = indexDef->toConstant()->toInt32();
if (indexConst < 0) {
return this;
}
MDefinition* arg;
if (uint32_t(indexConst) < numActuals()) {
arg = getArg(indexConst);
if (arg->type() != MIRType::Value) {
arg = MBox::New(alloc, arg);
}
} else {
auto* undefined = MConstant::New(alloc, UndefinedValue());
block()->insertBefore(this, undefined);
arg = MBox::New(alloc, undefined);
}
return arg;
}
MInlineArgumentsSlice* MInlineArgumentsSlice::New(
TempAllocator& alloc, MDefinition* begin, MDefinition* count,
MCreateInlinedArgumentsObject* args, JSObject* templateObj,
gc::Heap initialHeap) {
auto* ins = new (alloc) MInlineArgumentsSlice(templateObj, initialHeap);
uint32_t argc = args->numActuals();
MOZ_ASSERT(argc <= ArgumentsObject::MaxInlinedArgs);
if (!ins->init(alloc, argc + NumNonArgumentOperands)) {
return nullptr;
}
ins->initOperand(0, begin);
ins->initOperand(1, count);
for (uint32_t i = 0; i < argc; i++) {
ins->initOperand(i + NumNonArgumentOperands, args->getArg(i));
}
return ins;
}
MDefinition* MArrayLength::foldsTo(TempAllocator& alloc) {
// Object.keys() is potentially effectful, in case of Proxies. Otherwise, when
// it is only computed for its length property, there is no need to
// materialize the Array which results from it and it can be marked as
// recovered on bailout as long as no properties are added to / removed from
// the object.
MDefinition* elems = elements();
if (!elems->isElements()) {
return this;
}
MDefinition* guardshape = elems->toElements()->object();
if (!guardshape->isGuardShape()) {
return this;
}
// The Guard shape is guarding the shape of the object returned by
// Object.keys, this guard can be removed as knowing the function is good
// enough to infer that we are returning an array.
MDefinition* keys = guardshape->toGuardShape()->object();
if (!keys->isObjectKeys()) {
return this;
}
// Object.keys() inline cache guards against proxies when creating the IC. We
// rely on this here as we are looking to elide `Object.keys(...)` call, which
// is only possible if we know for sure that no side-effect might have
// happened.
MDefinition* noproxy = keys->toObjectKeys()->object();
if (!noproxy->isGuardIsNotProxy()) {
// The guard might have been replaced by an assertion, in case the class is
// known at compile time. IF the guard has been removed check whether check
// has been removed.
MOZ_RELEASE_ASSERT(GetObjectKnownClass(noproxy) != KnownClass::None);
MOZ_RELEASE_ASSERT(!GetObjectKnownJSClass(noproxy)->isProxyObject());
}
// Check if both the elements and the Object.keys() have a single use. We only
// check for live uses, and are ok if a branch which was previously using the
// keys array has been removed since.
if (!elems->hasOneLiveDefUse() || !guardshape->hasOneLiveDefUse() ||
!keys->hasOneLiveDefUse()) {
return this;
}
// Check that the latest active resume point is the one from Object.keys(), in
// order to steal it. If this is not the latest active resume point then some
// side-effect might happen which updates the content of the object, making
// any recovery of the keys exhibit a different behavior than expected.
if (keys->toObjectKeys()->resumePoint() != block()->activeResumePoint(this)) {
return this;
}
// Verify whether any resume point captures the keys array after any aliasing
// mutations. If this were to be the case the recovery of ObjectKeys on
// bailout might compute a version which might not match with the elided
// result.
//
// Iterate over the resume point uses of ObjectKeys, and check whether the
// instructions they are attached to are aliasing Object fields. If so, skip
// this optimization.
AliasSet enumKeysAliasSet = AliasSet::Load(AliasSet::Flag::ObjectFields);
for (auto* use : UsesIterator(keys)) {
if (!use->consumer()->isResumePoint()) {
// There is only a single use, and this is the length computation as
// asserted with `hasOneLiveDefUse`.
continue;
}
MResumePoint* rp = use->consumer()->toResumePoint();
if (!rp->instruction()) {
// If there is no instruction, this is a resume point which is attached to
// the entry of a block. Thus no risk of mutating the object on which the
// keys are queried.
continue;
}
MInstruction* ins = rp->instruction();
if (ins == keys) {
continue;
}
// Check whether the instruction can potentially alias the object fields of
// the object from which we are querying the keys.
AliasSet mightAlias = ins->getAliasSet() & enumKeysAliasSet;
if (!mightAlias.isNone()) {
return this;
}
}
// Flag every instructions since Object.keys(..) as recovered on bailout, and
// make Object.keys(..) be the recovered value in-place of the shape guard.
setRecoveredOnBailout();
elems->setRecoveredOnBailout();
guardshape->replaceAllUsesWith(keys);
guardshape->block()->discard(guardshape->toGuardShape());
keys->setRecoveredOnBailout();
// Steal the resume point from Object.keys, which is ok as we confirmed that
// there is no other resume point in-between.
MObjectKeysLength* keysLength = MObjectKeysLength::New(alloc, noproxy);
keysLength->stealResumePoint(keys->toObjectKeys());
return keysLength;
}
MDefinition* MNormalizeSliceTerm::foldsTo(TempAllocator& alloc) {
auto* length = this->length();
if (!length->isConstant() && !length->isArgumentsLength()) {
return this;
}
if (length->isConstant()) {
int32_t lengthConst = length->toConstant()->toInt32();
MOZ_ASSERT(lengthConst >= 0);
// Result is always zero when |length| is zero.
if (lengthConst == 0) {
return length;
}
auto* value = this->value();
if (value->isConstant()) {
int32_t valueConst = value->toConstant()->toInt32();
int32_t normalized;
if (valueConst < 0) {
normalized = std::max(valueConst + lengthConst, 0);
} else {
normalized = std::min(valueConst, lengthConst);
}
if (normalized == valueConst) {
return value;
}
if (normalized == lengthConst) {
return length;
}
return MConstant::New(alloc, Int32Value(normalized));
}
return this;
}
auto* value = this->value();
if (value->isConstant()) {
int32_t valueConst = value->toConstant()->toInt32();
// Minimum of |value| and |length|.
if (valueConst > 0) {
bool isMax = false;
return MMinMax::New(alloc, value, length, MIRType::Int32, isMax);
}
// Maximum of |value + length| and zero.
if (valueConst < 0) {
// Safe to truncate because |length| is never negative.
auto* add = MAdd::New(alloc, value, length, TruncateKind::Truncate);
block()->insertBefore(this, add);
auto* zero = MConstant::New(alloc, Int32Value(0));
block()->insertBefore(this, zero);
bool isMax = true;
return MMinMax::New(alloc, add, zero, MIRType::Int32, isMax);
}
// Directly return the value when it's zero.
return value;
}
// Normalizing MArgumentsLength is a no-op.
if (value->isArgumentsLength()) {
return value;
}
return this;
}
bool MInt32ToStringWithBase::congruentTo(const MDefinition* ins) const {
if (!ins->isInt32ToStringWithBase()) {
return false;
}
if (ins->toInt32ToStringWithBase()->lowerCase() != lowerCase()) {
return false;
}
return congruentIfOperandsEqual(ins);
}
bool MWasmShiftSimd128::congruentTo(const MDefinition* ins) const {
if (!ins->isWasmShiftSimd128()) {
return false;
}
return ins->toWasmShiftSimd128()->simdOp() == simdOp_ &&
congruentIfOperandsEqual(ins);
}
bool MWasmShuffleSimd128::congruentTo(const MDefinition* ins) const {
if (!ins->isWasmShuffleSimd128()) {
return false;
}
return ins->toWasmShuffleSimd128()->shuffle().equals(&shuffle_) &&
congruentIfOperandsEqual(ins);
}
bool MWasmUnarySimd128::congruentTo(const MDefinition* ins) const {
if (!ins->isWasmUnarySimd128()) {
return false;
}
return ins->toWasmUnarySimd128()->simdOp() == simdOp_ &&
congruentIfOperandsEqual(ins);
}
#ifdef ENABLE_WASM_SIMD
MWasmShuffleSimd128* jit::BuildWasmShuffleSimd128(TempAllocator& alloc,
const int8_t* control,
MDefinition* lhs,
MDefinition* rhs) {
SimdShuffle s =
AnalyzeSimdShuffle(SimdConstant::CreateX16(control), lhs, rhs);
switch (s.opd) {
case SimdShuffle::Operand::LEFT:
// When SimdShuffle::Operand is LEFT the right operand is not used,
// lose reference to rhs.
rhs = lhs;
break;
case SimdShuffle::Operand::RIGHT:
// When SimdShuffle::Operand is RIGHT the left operand is not used,
// lose reference to lhs.
lhs = rhs;
break;
default:
break;
}
return MWasmShuffleSimd128::New(alloc, lhs, rhs, s);
}
#endif // ENABLE_WASM_SIMD
static MDefinition* FoldTrivialWasmCasts(TempAllocator& alloc,
wasm::RefType sourceType,
wasm::RefType destType) {
// Upcasts are trivially valid.
if (wasm::RefType::isSubTypeOf(sourceType, destType)) {
return MConstant::New(alloc, Int32Value(1), MIRType::Int32);
}
// If two types are completely disjoint, then all casts between them are
// impossible.
if (!wasm::RefType::castPossible(destType, sourceType)) {
return MConstant::New(alloc, Int32Value(0), MIRType::Int32);
}
return nullptr;
}
MDefinition* MWasmRefIsSubtypeOfAbstract::foldsTo(TempAllocator& alloc) {
MDefinition* folded = FoldTrivialWasmCasts(alloc, sourceType(), destType());
if (folded) {
return folded;
}
return this;
}
MDefinition* MWasmRefIsSubtypeOfConcrete::foldsTo(TempAllocator& alloc) {
MDefinition* folded = FoldTrivialWasmCasts(alloc, sourceType(), destType());
if (folded) {
return folded;
}
return this;
}
|