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
|
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
* vim: set ts=8 sts=4 et sw=4 tw=99:
* 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 "vm/TypeInference-inl.h"
#include "mozilla/DebugOnly.h"
#include "mozilla/MemoryReporting.h"
#include "mozilla/PodOperations.h"
#include "mozilla/SizePrintfMacros.h"
#include "mozilla/Sprintf.h"
#include "jsapi.h"
#include "jscntxt.h"
#include "jsgc.h"
#include "jshashutil.h"
#include "jsobj.h"
#include "jsprf.h"
#include "jsscript.h"
#include "jsstr.h"
#include "gc/Marking.h"
#include "jit/BaselineJIT.h"
#include "jit/CompileInfo.h"
#include "jit/Ion.h"
#include "jit/IonAnalysis.h"
#include "jit/JitCompartment.h"
#include "jit/OptimizationTracking.h"
#include "js/MemoryMetrics.h"
#include "vm/HelperThreads.h"
#include "vm/Opcodes.h"
#include "vm/Shape.h"
#include "vm/Time.h"
#include "vm/UnboxedObject.h"
#include "jsatominlines.h"
#include "jsscriptinlines.h"
#include "vm/NativeObject-inl.h"
using namespace js;
using namespace js::gc;
using mozilla::DebugOnly;
using mozilla::Maybe;
using mozilla::PodArrayZero;
using mozilla::PodCopy;
using mozilla::PodZero;
#ifdef DEBUG
static inline jsid
id___proto__(JSContext* cx)
{
return NameToId(cx->names().proto);
}
static inline jsid
id_constructor(JSContext* cx)
{
return NameToId(cx->names().constructor);
}
static inline jsid
id_caller(JSContext* cx)
{
return NameToId(cx->names().caller);
}
const char*
js::TypeIdStringImpl(jsid id)
{
if (JSID_IS_VOID(id))
return "(index)";
if (JSID_IS_EMPTY(id))
return "(new)";
if (JSID_IS_SYMBOL(id))
return "(symbol)";
static char bufs[4][100];
static unsigned which = 0;
which = (which + 1) & 3;
PutEscapedString(bufs[which], 100, JSID_TO_FLAT_STRING(id), 0);
return bufs[which];
}
#endif
/////////////////////////////////////////////////////////////////////
// Logging
/////////////////////////////////////////////////////////////////////
/* static */ const char*
TypeSet::NonObjectTypeString(TypeSet::Type type)
{
if (type.isPrimitive()) {
switch (type.primitive()) {
case JSVAL_TYPE_UNDEFINED:
return "void";
case JSVAL_TYPE_NULL:
return "null";
case JSVAL_TYPE_BOOLEAN:
return "bool";
case JSVAL_TYPE_INT32:
return "int";
case JSVAL_TYPE_DOUBLE:
return "float";
case JSVAL_TYPE_STRING:
return "string";
case JSVAL_TYPE_SYMBOL:
return "symbol";
case JSVAL_TYPE_MAGIC:
return "lazyargs";
default:
MOZ_CRASH("Bad type");
}
}
if (type.isUnknown())
return "unknown";
MOZ_ASSERT(type.isAnyObject());
return "object";
}
/* static */ const char*
TypeSet::TypeString(TypeSet::Type type)
{
if (type.isPrimitive() || type.isUnknown() || type.isAnyObject())
return NonObjectTypeString(type);
static char bufs[4][40];
static unsigned which = 0;
which = (which + 1) & 3;
if (type.isSingleton()) {
JSObject* singleton = type.singletonNoBarrier();
snprintf(bufs[which], 40, "<%s %#" PRIxPTR ">",
singleton->getClass()->name, uintptr_t(singleton));
} else {
snprintf(bufs[which], 40, "[%s * %#" PRIxPTR "]", type.groupNoBarrier()->clasp()->name, uintptr_t(type.groupNoBarrier()));
}
return bufs[which];
}
/* static */ const char*
TypeSet::ObjectGroupString(ObjectGroup* group)
{
return TypeString(TypeSet::ObjectType(group));
}
#ifdef DEBUG
bool
js::InferSpewActive(SpewChannel channel)
{
static bool active[SPEW_COUNT];
static bool checked = false;
if (!checked) {
checked = true;
PodArrayZero(active);
const char* env = getenv("INFERFLAGS");
if (!env)
return false;
if (strstr(env, "ops"))
active[ISpewOps] = true;
if (strstr(env, "result"))
active[ISpewResult] = true;
if (strstr(env, "full")) {
for (unsigned i = 0; i < SPEW_COUNT; i++)
active[i] = true;
}
}
return active[channel];
}
static bool InferSpewColorable()
{
/* Only spew colors on xterm-color to not screw up emacs. */
static bool colorable = false;
static bool checked = false;
if (!checked) {
checked = true;
const char* env = getenv("TERM");
if (!env)
return false;
if (strcmp(env, "xterm-color") == 0 || strcmp(env, "xterm-256color") == 0)
colorable = true;
}
return colorable;
}
const char*
js::InferSpewColorReset()
{
if (!InferSpewColorable())
return "";
return "\x1b[0m";
}
const char*
js::InferSpewColor(TypeConstraint* constraint)
{
/* Type constraints are printed out using foreground colors. */
static const char * const colors[] = { "\x1b[31m", "\x1b[32m", "\x1b[33m",
"\x1b[34m", "\x1b[35m", "\x1b[36m",
"\x1b[37m" };
if (!InferSpewColorable())
return "";
return colors[DefaultHasher<TypeConstraint*>::hash(constraint) % 7];
}
const char*
js::InferSpewColor(TypeSet* types)
{
/* Type sets are printed out using bold colors. */
static const char * const colors[] = { "\x1b[1;31m", "\x1b[1;32m", "\x1b[1;33m",
"\x1b[1;34m", "\x1b[1;35m", "\x1b[1;36m",
"\x1b[1;37m" };
if (!InferSpewColorable())
return "";
return colors[DefaultHasher<TypeSet*>::hash(types) % 7];
}
#ifdef DEBUG
void
js::InferSpewImpl(const char* fmt, ...)
{
va_list ap;
va_start(ap, fmt);
fprintf(stderr, "[infer] ");
vfprintf(stderr, fmt, ap);
fprintf(stderr, "\n");
va_end(ap);
}
#endif
MOZ_NORETURN MOZ_COLD static void
MOZ_FORMAT_PRINTF(2, 3)
TypeFailure(JSContext* cx, const char* fmt, ...)
{
char msgbuf[1024]; /* Larger error messages will be truncated */
char errbuf[1024];
va_list ap;
va_start(ap, fmt);
VsprintfLiteral(errbuf, fmt, ap);
va_end(ap);
SprintfLiteral(msgbuf, "[infer failure] %s", errbuf);
/* Dump type state, even if INFERFLAGS is unset. */
PrintTypes(cx, cx->compartment(), true);
MOZ_ReportAssertionFailure(msgbuf, __FILE__, __LINE__);
MOZ_CRASH();
}
bool
js::ObjectGroupHasProperty(JSContext* cx, ObjectGroup* group, jsid id, const Value& value)
{
/*
* Check the correctness of the type information in the object's property
* against an actual value.
*/
if (!group->unknownProperties() && !value.isUndefined()) {
id = IdToTypeId(id);
/* Watch for properties which inference does not monitor. */
if (id == id___proto__(cx) || id == id_constructor(cx) || id == id_caller(cx))
return true;
TypeSet::Type type = TypeSet::GetValueType(value);
AutoEnterAnalysis enter(cx);
/*
* We don't track types for properties inherited from prototypes which
* haven't yet been accessed during analysis of the inheriting object.
* Don't do the property instantiation now.
*/
TypeSet* types = group->maybeGetProperty(id);
if (!types)
return true;
// Type set guards might miss when an object's group changes and its
// properties become unknown.
if (value.isObject()) {
if (types->unknownObject())
return true;
for (size_t i = 0; i < types->getObjectCount(); i++) {
if (TypeSet::ObjectKey* key = types->getObject(i)) {
if (key->unknownProperties())
return true;
}
}
JSObject* obj = &value.toObject();
if (!obj->hasLazyGroup() && obj->group()->maybeOriginalUnboxedGroup())
return true;
}
if (!types->hasType(type)) {
TypeFailure(cx, "Missing type in object %s %s: %s",
TypeSet::ObjectGroupString(group), TypeIdString(id),
TypeSet::TypeString(type));
}
}
return true;
}
#endif
/////////////////////////////////////////////////////////////////////
// TypeSet
/////////////////////////////////////////////////////////////////////
TemporaryTypeSet::TemporaryTypeSet(LifoAlloc* alloc, Type type)
{
if (type.isUnknown()) {
flags |= TYPE_FLAG_BASE_MASK;
} else if (type.isPrimitive()) {
flags = PrimitiveTypeFlag(type.primitive());
if (flags == TYPE_FLAG_DOUBLE)
flags |= TYPE_FLAG_INT32;
} else if (type.isAnyObject()) {
flags |= TYPE_FLAG_ANYOBJECT;
} else if (type.isGroup() && type.group()->unknownProperties()) {
flags |= TYPE_FLAG_ANYOBJECT;
} else {
setBaseObjectCount(1);
objectSet = reinterpret_cast<ObjectKey**>(type.objectKey());
if (type.isGroup()) {
ObjectGroup* ngroup = type.group();
if (ngroup->newScript() && ngroup->newScript()->initializedGroup())
addType(ObjectType(ngroup->newScript()->initializedGroup()), alloc);
}
}
}
bool
TypeSet::mightBeMIRType(jit::MIRType type) const
{
if (unknown())
return true;
if (type == jit::MIRType::Object)
return unknownObject() || baseObjectCount() != 0;
switch (type) {
case jit::MIRType::Undefined:
return baseFlags() & TYPE_FLAG_UNDEFINED;
case jit::MIRType::Null:
return baseFlags() & TYPE_FLAG_NULL;
case jit::MIRType::Boolean:
return baseFlags() & TYPE_FLAG_BOOLEAN;
case jit::MIRType::Int32:
return baseFlags() & TYPE_FLAG_INT32;
case jit::MIRType::Float32: // Fall through, there's no JSVAL for Float32.
case jit::MIRType::Double:
return baseFlags() & TYPE_FLAG_DOUBLE;
case jit::MIRType::String:
return baseFlags() & TYPE_FLAG_STRING;
case jit::MIRType::Symbol:
return baseFlags() & TYPE_FLAG_SYMBOL;
case jit::MIRType::MagicOptimizedArguments:
return baseFlags() & TYPE_FLAG_LAZYARGS;
case jit::MIRType::MagicHole:
case jit::MIRType::MagicIsConstructing:
// These magic constants do not escape to script and are not observed
// in the type sets.
//
// The reason we can return false here is subtle: if Ion is asking the
// type set if it has seen such a magic constant, then the MIR in
// question is the most generic type, MIRType::Value. A magic constant
// could only be emitted by a MIR of MIRType::Value if that MIR is a
// phi, and we check that different magic constants do not flow to the
// same join point in GuessPhiType.
return false;
default:
MOZ_CRASH("Bad MIR type");
}
}
bool
TypeSet::objectsAreSubset(TypeSet* other)
{
if (other->unknownObject())
return true;
if (unknownObject())
return false;
for (unsigned i = 0; i < getObjectCount(); i++) {
ObjectKey* key = getObject(i);
if (!key)
continue;
if (!other->hasType(ObjectType(key)))
return false;
}
return true;
}
bool
TypeSet::isSubset(const TypeSet* other) const
{
if ((baseFlags() & other->baseFlags()) != baseFlags())
return false;
if (unknownObject()) {
MOZ_ASSERT(other->unknownObject());
} else {
for (unsigned i = 0; i < getObjectCount(); i++) {
ObjectKey* key = getObject(i);
if (!key)
continue;
if (!other->hasType(ObjectType(key)))
return false;
}
}
return true;
}
bool
TypeSet::objectsIntersect(const TypeSet* other) const
{
if (unknownObject() || other->unknownObject())
return true;
for (unsigned i = 0; i < getObjectCount(); i++) {
ObjectKey* key = getObject(i);
if (!key)
continue;
if (other->hasType(ObjectType(key)))
return true;
}
return false;
}
template <class TypeListT>
bool
TypeSet::enumerateTypes(TypeListT* list) const
{
/* If any type is possible, there's no need to worry about specifics. */
if (flags & TYPE_FLAG_UNKNOWN)
return list->append(UnknownType());
/* Enqueue type set members stored as bits. */
for (TypeFlags flag = 1; flag < TYPE_FLAG_ANYOBJECT; flag <<= 1) {
if (flags & flag) {
Type type = PrimitiveType(TypeFlagPrimitive(flag));
if (!list->append(type))
return false;
}
}
/* If any object is possible, skip specifics. */
if (flags & TYPE_FLAG_ANYOBJECT)
return list->append(AnyObjectType());
/* Enqueue specific object types. */
unsigned count = getObjectCount();
for (unsigned i = 0; i < count; i++) {
ObjectKey* key = getObject(i);
if (key) {
if (!list->append(ObjectType(key)))
return false;
}
}
return true;
}
template bool TypeSet::enumerateTypes<TypeSet::TypeList>(TypeList* list) const;
template bool TypeSet::enumerateTypes<jit::TempTypeList>(jit::TempTypeList* list) const;
inline bool
TypeSet::addTypesToConstraint(JSContext* cx, TypeConstraint* constraint)
{
/*
* Build all types in the set into a vector before triggering the
* constraint, as doing so may modify this type set.
*/
TypeList types;
if (!enumerateTypes(&types))
return false;
for (unsigned i = 0; i < types.length(); i++)
constraint->newType(cx, this, types[i]);
return true;
}
#ifdef DEBUG
static inline bool
CompartmentsMatch(JSCompartment* a, JSCompartment* b)
{
return !a || !b || a == b;
}
#endif
bool
ConstraintTypeSet::addConstraint(JSContext* cx, TypeConstraint* constraint, bool callExisting)
{
if (!constraint) {
/* OOM failure while constructing the constraint. */
return false;
}
MOZ_ASSERT(cx->zone()->types.activeAnalysis);
MOZ_ASSERT(CompartmentsMatch(maybeCompartment(), constraint->maybeCompartment()));
InferSpew(ISpewOps, "addConstraint: %sT%p%s %sC%p%s %s",
InferSpewColor(this), this, InferSpewColorReset(),
InferSpewColor(constraint), constraint, InferSpewColorReset(),
constraint->kind());
MOZ_ASSERT(constraint->next == nullptr);
constraint->next = constraintList;
constraintList = constraint;
if (callExisting)
return addTypesToConstraint(cx, constraint);
return true;
}
void
TypeSet::clearObjects()
{
setBaseObjectCount(0);
objectSet = nullptr;
}
JSCompartment*
TypeSet::maybeCompartment()
{
if (unknownObject())
return nullptr;
unsigned objectCount = getObjectCount();
for (unsigned i = 0; i < objectCount; i++) {
ObjectKey* key = getObject(i);
if (!key)
continue;
JSCompartment* comp = key->maybeCompartment();
if (comp)
return comp;
}
return nullptr;
}
void
TypeSet::addType(Type type, LifoAlloc* alloc)
{
MOZ_ASSERT(CompartmentsMatch(maybeCompartment(), type.maybeCompartment()));
if (unknown())
return;
if (type.isUnknown()) {
flags |= TYPE_FLAG_BASE_MASK;
clearObjects();
MOZ_ASSERT(unknown());
return;
}
if (type.isPrimitive()) {
TypeFlags flag = PrimitiveTypeFlag(type.primitive());
if (flags & flag)
return;
/* If we add float to a type set it is also considered to contain int. */
if (flag == TYPE_FLAG_DOUBLE)
flag |= TYPE_FLAG_INT32;
flags |= flag;
return;
}
if (flags & TYPE_FLAG_ANYOBJECT)
return;
if (type.isAnyObject())
goto unknownObject;
{
uint32_t objectCount = baseObjectCount();
ObjectKey* key = type.objectKey();
ObjectKey** pentry = TypeHashSet::Insert<ObjectKey*, ObjectKey, ObjectKey>
(*alloc, objectSet, objectCount, key);
if (!pentry)
goto unknownObject;
if (*pentry)
return;
*pentry = key;
setBaseObjectCount(objectCount);
// Limit the number of objects we track. There is a different limit
// depending on whether the set only contains DOM objects, which can
// have many different classes and prototypes but are still optimizable
// by IonMonkey.
if (objectCount >= TYPE_FLAG_OBJECT_COUNT_LIMIT) {
JS_STATIC_ASSERT(TYPE_FLAG_DOMOBJECT_COUNT_LIMIT >= TYPE_FLAG_OBJECT_COUNT_LIMIT);
// Examining the entire type set is only required when we first hit
// the normal object limit.
if (objectCount == TYPE_FLAG_OBJECT_COUNT_LIMIT) {
for (unsigned i = 0; i < objectCount; i++) {
const Class* clasp = getObjectClass(i);
if (clasp && !clasp->isDOMClass())
goto unknownObject;
}
}
// Make sure the newly added object is also a DOM object.
if (!key->clasp()->isDOMClass())
goto unknownObject;
// Limit the number of DOM objects.
if (objectCount == TYPE_FLAG_DOMOBJECT_COUNT_LIMIT)
goto unknownObject;
}
}
if (type.isGroup()) {
ObjectGroup* ngroup = type.group();
MOZ_ASSERT(!ngroup->singleton());
if (ngroup->unknownProperties())
goto unknownObject;
// If we add a partially initialized group to a type set, add the
// corresponding fully initialized group, as an object's group may change
// from the former to the latter via the acquired properties analysis.
if (ngroup->newScript() && ngroup->newScript()->initializedGroup())
addType(ObjectType(ngroup->newScript()->initializedGroup()), alloc);
}
if (false) {
unknownObject:
flags |= TYPE_FLAG_ANYOBJECT;
clearObjects();
}
}
// This class is used for post barriers on type set contents. The only times
// when type sets contain nursery references is when a nursery object has its
// group dynamically changed to a singleton. In such cases the type set will
// need to be traced at the next minor GC.
//
// There is no barrier used for TemporaryTypeSets. These type sets are only
// used during Ion compilation, and if some ConstraintTypeSet contains nursery
// pointers then any number of TemporaryTypeSets might as well. Thus, if there
// are any such ConstraintTypeSets in existence, all off thread Ion
// compilations are canceled by the next minor GC.
class TypeSetRef : public BufferableRef
{
Zone* zone;
ConstraintTypeSet* types;
public:
TypeSetRef(Zone* zone, ConstraintTypeSet* types)
: zone(zone), types(types)
{}
void trace(JSTracer* trc) override {
types->trace(zone, trc);
}
};
void
ConstraintTypeSet::postWriteBarrier(ExclusiveContext* cx, Type type)
{
if (type.isSingletonUnchecked() && IsInsideNursery(type.singletonNoBarrier())) {
JSRuntime* rt = cx->asJSContext()->runtime();
rt->gc.storeBuffer.putGeneric(TypeSetRef(cx->zone(), this));
rt->gc.storeBuffer.setShouldCancelIonCompilations();
}
}
void
ConstraintTypeSet::addType(ExclusiveContext* cxArg, Type type)
{
MOZ_ASSERT(cxArg->zone()->types.activeAnalysis);
if (hasType(type))
return;
TypeSet::addType(type, &cxArg->typeLifoAlloc());
if (type.isObjectUnchecked() && unknownObject())
type = AnyObjectType();
postWriteBarrier(cxArg, type);
InferSpew(ISpewOps, "addType: %sT%p%s %s",
InferSpewColor(this), this, InferSpewColorReset(),
TypeString(type));
/* Propagate the type to all constraints. */
if (JSContext* cx = cxArg->maybeJSContext()) {
TypeConstraint* constraint = constraintList;
while (constraint) {
constraint->newType(cx, this, type);
constraint = constraint->next;
}
} else {
MOZ_ASSERT(!constraintList);
}
}
void
TypeSet::print(FILE* fp)
{
bool fromDebugger = !fp;
if (!fp)
fp = stderr;
if (flags & TYPE_FLAG_NON_DATA_PROPERTY)
fprintf(fp, " [non-data]");
if (flags & TYPE_FLAG_NON_WRITABLE_PROPERTY)
fprintf(fp, " [non-writable]");
if (definiteProperty())
fprintf(fp, " [definite:%d]", definiteSlot());
if (baseFlags() == 0 && !baseObjectCount()) {
fprintf(fp, " missing");
return;
}
if (flags & TYPE_FLAG_UNKNOWN)
fprintf(fp, " unknown");
if (flags & TYPE_FLAG_ANYOBJECT)
fprintf(fp, " object");
if (flags & TYPE_FLAG_UNDEFINED)
fprintf(fp, " void");
if (flags & TYPE_FLAG_NULL)
fprintf(fp, " null");
if (flags & TYPE_FLAG_BOOLEAN)
fprintf(fp, " bool");
if (flags & TYPE_FLAG_INT32)
fprintf(fp, " int");
if (flags & TYPE_FLAG_DOUBLE)
fprintf(fp, " float");
if (flags & TYPE_FLAG_STRING)
fprintf(fp, " string");
if (flags & TYPE_FLAG_SYMBOL)
fprintf(fp, " symbol");
if (flags & TYPE_FLAG_LAZYARGS)
fprintf(fp, " lazyargs");
uint32_t objectCount = baseObjectCount();
if (objectCount) {
fprintf(fp, " object[%u]", objectCount);
unsigned count = getObjectCount();
for (unsigned i = 0; i < count; i++) {
ObjectKey* key = getObject(i);
if (key)
fprintf(fp, " %s", TypeString(ObjectType(key)));
}
}
if (fromDebugger)
fprintf(fp, "\n");
}
/* static */ void
TypeSet::readBarrier(const TypeSet* types)
{
if (types->unknownObject())
return;
for (unsigned i = 0; i < types->getObjectCount(); i++) {
if (ObjectKey* key = types->getObject(i)) {
if (key->isSingleton())
(void) key->singleton();
else
(void) key->group();
}
}
}
/* static */ bool
TypeSet::IsTypeMarked(JSRuntime* rt, TypeSet::Type* v)
{
bool rv;
if (v->isSingletonUnchecked()) {
JSObject* obj = v->singletonNoBarrier();
rv = IsMarkedUnbarriered(rt, &obj);
*v = TypeSet::ObjectType(obj);
} else if (v->isGroupUnchecked()) {
ObjectGroup* group = v->groupNoBarrier();
rv = IsMarkedUnbarriered(rt, &group);
*v = TypeSet::ObjectType(group);
} else {
rv = true;
}
return rv;
}
/* static */ bool
TypeSet::IsTypeAllocatedDuringIncremental(TypeSet::Type v)
{
bool rv;
if (v.isSingletonUnchecked()) {
JSObject* obj = v.singletonNoBarrier();
rv = obj->isTenured() && obj->asTenured().arena()->allocatedDuringIncremental;
} else if (v.isGroupUnchecked()) {
ObjectGroup* group = v.groupNoBarrier();
rv = group->arena()->allocatedDuringIncremental;
} else {
rv = false;
}
return rv;
}
static inline bool
IsObjectKeyAboutToBeFinalized(TypeSet::ObjectKey** keyp)
{
TypeSet::ObjectKey* key = *keyp;
bool isAboutToBeFinalized;
if (key->isGroup()) {
ObjectGroup* group = key->groupNoBarrier();
isAboutToBeFinalized = IsAboutToBeFinalizedUnbarriered(&group);
if (!isAboutToBeFinalized)
*keyp = TypeSet::ObjectKey::get(group);
} else {
MOZ_ASSERT(key->isSingleton());
JSObject* singleton = key->singletonNoBarrier();
isAboutToBeFinalized = IsAboutToBeFinalizedUnbarriered(&singleton);
if (!isAboutToBeFinalized)
*keyp = TypeSet::ObjectKey::get(singleton);
}
return isAboutToBeFinalized;
}
bool
TypeSet::IsTypeAboutToBeFinalized(TypeSet::Type* v)
{
bool isAboutToBeFinalized;
if (v->isObjectUnchecked()) {
TypeSet::ObjectKey* key = v->objectKey();
isAboutToBeFinalized = IsObjectKeyAboutToBeFinalized(&key);
if (!isAboutToBeFinalized)
*v = TypeSet::ObjectType(key);
} else {
isAboutToBeFinalized = false;
}
return isAboutToBeFinalized;
}
bool
TypeSet::clone(LifoAlloc* alloc, TemporaryTypeSet* result) const
{
MOZ_ASSERT(result->empty());
unsigned objectCount = baseObjectCount();
unsigned capacity = (objectCount >= 2) ? TypeHashSet::Capacity(objectCount) : 0;
ObjectKey** newSet;
if (capacity) {
newSet = alloc->newArray<ObjectKey*>(capacity);
if (!newSet)
return false;
PodCopy(newSet, objectSet, capacity);
}
new(result) TemporaryTypeSet(flags, capacity ? newSet : objectSet);
return true;
}
TemporaryTypeSet*
TypeSet::clone(LifoAlloc* alloc) const
{
TemporaryTypeSet* res = alloc->new_<TemporaryTypeSet>();
if (!res || !clone(alloc, res))
return nullptr;
return res;
}
TemporaryTypeSet*
TypeSet::cloneObjectsOnly(LifoAlloc* alloc)
{
TemporaryTypeSet* res = clone(alloc);
if (!res)
return nullptr;
res->flags &= ~TYPE_FLAG_BASE_MASK | TYPE_FLAG_ANYOBJECT;
return res;
}
TemporaryTypeSet*
TypeSet::cloneWithoutObjects(LifoAlloc* alloc)
{
TemporaryTypeSet* res = alloc->new_<TemporaryTypeSet>();
if (!res)
return nullptr;
res->flags = flags & ~TYPE_FLAG_ANYOBJECT;
res->setBaseObjectCount(0);
return res;
}
/* static */ TemporaryTypeSet*
TypeSet::unionSets(TypeSet* a, TypeSet* b, LifoAlloc* alloc)
{
TemporaryTypeSet* res = alloc->new_<TemporaryTypeSet>(a->baseFlags() | b->baseFlags(),
static_cast<ObjectKey**>(nullptr));
if (!res)
return nullptr;
if (!res->unknownObject()) {
for (size_t i = 0; i < a->getObjectCount() && !res->unknownObject(); i++) {
if (ObjectKey* key = a->getObject(i))
res->addType(ObjectType(key), alloc);
}
for (size_t i = 0; i < b->getObjectCount() && !res->unknownObject(); i++) {
if (ObjectKey* key = b->getObject(i))
res->addType(ObjectType(key), alloc);
}
}
return res;
}
/* static */ TemporaryTypeSet*
TypeSet::removeSet(TemporaryTypeSet* input, TemporaryTypeSet* removal, LifoAlloc* alloc)
{
// Only allow removal of primitives and the "AnyObject" flag.
MOZ_ASSERT(!removal->unknown());
MOZ_ASSERT_IF(!removal->unknownObject(), removal->getObjectCount() == 0);
uint32_t flags = input->baseFlags() & ~removal->baseFlags();
TemporaryTypeSet* res =
alloc->new_<TemporaryTypeSet>(flags, static_cast<ObjectKey**>(nullptr));
if (!res)
return nullptr;
res->setBaseObjectCount(0);
if (removal->unknownObject() || input->unknownObject())
return res;
for (size_t i = 0; i < input->getObjectCount(); i++) {
if (!input->getObject(i))
continue;
res->addType(TypeSet::ObjectType(input->getObject(i)), alloc);
}
return res;
}
/* static */ TemporaryTypeSet*
TypeSet::intersectSets(TemporaryTypeSet* a, TemporaryTypeSet* b, LifoAlloc* alloc)
{
TemporaryTypeSet* res;
res = alloc->new_<TemporaryTypeSet>(a->baseFlags() & b->baseFlags(),
static_cast<ObjectKey**>(nullptr));
if (!res)
return nullptr;
res->setBaseObjectCount(0);
if (res->unknownObject())
return res;
MOZ_ASSERT(!a->unknownObject() || !b->unknownObject());
if (a->unknownObject()) {
for (size_t i = 0; i < b->getObjectCount(); i++) {
if (b->getObject(i))
res->addType(ObjectType(b->getObject(i)), alloc);
}
return res;
}
if (b->unknownObject()) {
for (size_t i = 0; i < a->getObjectCount(); i++) {
if (a->getObject(i))
res->addType(ObjectType(a->getObject(i)), alloc);
}
return res;
}
MOZ_ASSERT(!a->unknownObject() && !b->unknownObject());
for (size_t i = 0; i < a->getObjectCount(); i++) {
for (size_t j = 0; j < b->getObjectCount(); j++) {
if (b->getObject(j) != a->getObject(i))
continue;
if (!b->getObject(j))
continue;
res->addType(ObjectType(b->getObject(j)), alloc);
break;
}
}
return res;
}
/////////////////////////////////////////////////////////////////////
// Compiler constraints
/////////////////////////////////////////////////////////////////////
// Compiler constraints overview
//
// Constraints generated during Ion compilation capture assumptions made about
// heap properties that will trigger invalidation of the resulting Ion code if
// the constraint is violated. Constraints can only be attached to type sets on
// the main thread, so to allow compilation to occur almost entirely off thread
// the generation is split into two phases.
//
// During compilation, CompilerConstraint values are constructed in a list,
// recording the heap property type set which was read from and its expected
// contents, along with the assumption made about those contents.
//
// At the end of compilation, when linking the result on the main thread, the
// list of compiler constraints are read and converted to type constraints and
// attached to the type sets. If the property type sets have changed so that the
// assumptions no longer hold then the compilation is aborted and its result
// discarded.
// Superclass of all constraints generated during Ion compilation. These may
// be allocated off the main thread, using the current JIT context's allocator.
class CompilerConstraint
{
public:
// Property being queried by the compiler.
HeapTypeSetKey property;
// Contents of the property at the point when the query was performed. This
// may differ from the actual property types later in compilation as the
// main thread performs side effects.
TemporaryTypeSet* expected;
CompilerConstraint(LifoAlloc* alloc, const HeapTypeSetKey& property)
: property(property),
expected(property.maybeTypes() ? property.maybeTypes()->clone(alloc) : nullptr)
{}
// Generate the type constraint recording the assumption made by this
// compilation. Returns true if the assumption originally made still holds.
virtual bool generateTypeConstraint(JSContext* cx, RecompileInfo recompileInfo) = 0;
};
class js::CompilerConstraintList
{
public:
struct FrozenScript
{
JSScript* script;
TemporaryTypeSet* thisTypes;
TemporaryTypeSet* argTypes;
TemporaryTypeSet* bytecodeTypes;
};
private:
// OOM during generation of some constraint.
bool failed_;
// Allocator used for constraints.
LifoAlloc* alloc_;
// Constraints generated on heap properties.
Vector<CompilerConstraint*, 0, jit::JitAllocPolicy> constraints;
// Scripts whose stack type sets were frozen for the compilation.
Vector<FrozenScript, 1, jit::JitAllocPolicy> frozenScripts;
public:
explicit CompilerConstraintList(jit::TempAllocator& alloc)
: failed_(false),
alloc_(alloc.lifoAlloc()),
constraints(alloc),
frozenScripts(alloc)
{}
void add(CompilerConstraint* constraint) {
if (!constraint || !constraints.append(constraint))
setFailed();
}
void freezeScript(JSScript* script,
TemporaryTypeSet* thisTypes,
TemporaryTypeSet* argTypes,
TemporaryTypeSet* bytecodeTypes)
{
FrozenScript entry;
entry.script = script;
entry.thisTypes = thisTypes;
entry.argTypes = argTypes;
entry.bytecodeTypes = bytecodeTypes;
if (!frozenScripts.append(entry))
setFailed();
}
size_t length() {
return constraints.length();
}
CompilerConstraint* get(size_t i) {
return constraints[i];
}
size_t numFrozenScripts() {
return frozenScripts.length();
}
const FrozenScript& frozenScript(size_t i) {
return frozenScripts[i];
}
bool failed() {
return failed_;
}
void setFailed() {
failed_ = true;
}
LifoAlloc* alloc() const {
return alloc_;
}
};
CompilerConstraintList*
js::NewCompilerConstraintList(jit::TempAllocator& alloc)
{
return alloc.lifoAlloc()->new_<CompilerConstraintList>(alloc);
}
/* static */ bool
TypeScript::FreezeTypeSets(CompilerConstraintList* constraints, JSScript* script,
TemporaryTypeSet** pThisTypes,
TemporaryTypeSet** pArgTypes,
TemporaryTypeSet** pBytecodeTypes)
{
LifoAlloc* alloc = constraints->alloc();
StackTypeSet* existing = script->types()->typeArray();
size_t count = NumTypeSets(script);
TemporaryTypeSet* types = alloc->newArrayUninitialized<TemporaryTypeSet>(count);
if (!types)
return false;
PodZero(types, count);
for (size_t i = 0; i < count; i++) {
if (!existing[i].clone(alloc, &types[i]))
return false;
}
*pThisTypes = types + (ThisTypes(script) - existing);
*pArgTypes = (script->functionNonDelazifying() && script->functionNonDelazifying()->nargs())
? (types + (ArgTypes(script, 0) - existing))
: nullptr;
*pBytecodeTypes = types;
constraints->freezeScript(script, *pThisTypes, *pArgTypes, *pBytecodeTypes);
return true;
}
namespace {
template <typename T>
class CompilerConstraintInstance : public CompilerConstraint
{
T data;
public:
CompilerConstraintInstance<T>(LifoAlloc* alloc, const HeapTypeSetKey& property, const T& data)
: CompilerConstraint(alloc, property), data(data)
{}
bool generateTypeConstraint(JSContext* cx, RecompileInfo recompileInfo);
};
// Constraint generated from a CompilerConstraint when linking the compilation.
template <typename T>
class TypeCompilerConstraint : public TypeConstraint
{
// Compilation which this constraint may invalidate.
RecompileInfo compilation;
T data;
public:
TypeCompilerConstraint<T>(RecompileInfo compilation, const T& data)
: compilation(compilation), data(data)
{}
const char* kind() { return data.kind(); }
void newType(JSContext* cx, TypeSet* source, TypeSet::Type type) {
if (data.invalidateOnNewType(type))
cx->zone()->types.addPendingRecompile(cx, compilation);
}
void newPropertyState(JSContext* cx, TypeSet* source) {
if (data.invalidateOnNewPropertyState(source))
cx->zone()->types.addPendingRecompile(cx, compilation);
}
void newObjectState(JSContext* cx, ObjectGroup* group) {
// Note: Once the object has unknown properties, no more notifications
// will be sent on changes to its state, so always invalidate any
// associated compilations.
if (group->unknownProperties() || data.invalidateOnNewObjectState(group))
cx->zone()->types.addPendingRecompile(cx, compilation);
}
bool sweep(TypeZone& zone, TypeConstraint** res) {
if (data.shouldSweep() || compilation.shouldSweep(zone))
return false;
*res = zone.typeLifoAlloc.new_<TypeCompilerConstraint<T> >(compilation, data);
return true;
}
JSCompartment* maybeCompartment() {
return data.maybeCompartment();
}
};
template <typename T>
bool
CompilerConstraintInstance<T>::generateTypeConstraint(JSContext* cx, RecompileInfo recompileInfo)
{
if (property.object()->unknownProperties())
return false;
if (!property.instantiate(cx))
return false;
if (!data.constraintHolds(cx, property, expected))
return false;
return property.maybeTypes()->addConstraint(cx, cx->typeLifoAlloc().new_<TypeCompilerConstraint<T> >(recompileInfo, data),
/* callExisting = */ false);
}
} /* anonymous namespace */
const Class*
TypeSet::ObjectKey::clasp()
{
return isGroup() ? group()->clasp() : singleton()->getClass();
}
TaggedProto
TypeSet::ObjectKey::proto()
{
return isGroup() ? group()->proto() : singleton()->taggedProto();
}
TypeNewScript*
TypeSet::ObjectKey::newScript()
{
if (isGroup() && group()->newScript())
return group()->newScript();
return nullptr;
}
ObjectGroup*
TypeSet::ObjectKey::maybeGroup()
{
if (isGroup())
return group();
if (!singleton()->hasLazyGroup())
return singleton()->group();
return nullptr;
}
bool
TypeSet::ObjectKey::unknownProperties()
{
if (ObjectGroup* group = maybeGroup())
return group->unknownProperties();
return false;
}
HeapTypeSetKey
TypeSet::ObjectKey::property(jsid id)
{
MOZ_ASSERT(!unknownProperties());
HeapTypeSetKey property;
property.object_ = this;
property.id_ = id;
if (ObjectGroup* group = maybeGroup())
property.maybeTypes_ = group->maybeGetProperty(id);
return property;
}
void
TypeSet::ObjectKey::ensureTrackedProperty(JSContext* cx, jsid id)
{
// If we are accessing a lazily defined property which actually exists in
// the VM and has not been instantiated yet, instantiate it now if we are
// on the main thread and able to do so.
if (!JSID_IS_VOID(id) && !JSID_IS_EMPTY(id)) {
MOZ_ASSERT(CurrentThreadCanAccessRuntime(cx->runtime()));
if (isSingleton()) {
JSObject* obj = singleton();
if (obj->isNative() && obj->as<NativeObject>().containsPure(id))
EnsureTrackPropertyTypes(cx, obj, id);
}
}
}
void
js::EnsureTrackPropertyTypes(JSContext* cx, JSObject* obj, jsid id)
{
id = IdToTypeId(id);
if (obj->isSingleton()) {
AutoEnterAnalysis enter(cx);
if (obj->hasLazyGroup()) {
AutoEnterOOMUnsafeRegion oomUnsafe;
if (!obj->getGroup(cx)) {
oomUnsafe.crash("Could not allocate ObjectGroup in EnsureTrackPropertyTypes");
return;
}
}
if (!obj->group()->unknownProperties() && !obj->group()->getProperty(cx, obj, id)) {
MOZ_ASSERT(obj->group()->unknownProperties());
return;
}
}
MOZ_ASSERT(obj->group()->unknownProperties() || TrackPropertyTypes(cx, obj, id));
}
bool
HeapTypeSetKey::instantiate(JSContext* cx)
{
if (maybeTypes())
return true;
if (object()->isSingleton() && !object()->singleton()->getGroup(cx)) {
cx->clearPendingException();
return false;
}
JSObject* obj = object()->isSingleton() ? object()->singleton() : nullptr;
maybeTypes_ = object()->maybeGroup()->getProperty(cx, obj, id());
return maybeTypes_ != nullptr;
}
static bool
CheckFrozenTypeSet(JSContext* cx, TemporaryTypeSet* frozen, StackTypeSet* actual)
{
// Return whether the types frozen for a script during compilation are
// still valid. Also check for any new types added to the frozen set during
// compilation, and add them to the actual stack type sets. These new types
// indicate places where the compiler relaxed its possible inputs to be
// more tolerant of potential new types.
if (!actual->isSubset(frozen))
return false;
if (!frozen->isSubset(actual)) {
TypeSet::TypeList list;
frozen->enumerateTypes(&list);
for (size_t i = 0; i < list.length(); i++)
actual->addType(cx, list[i]);
}
return true;
}
namespace {
/*
* As for TypeConstraintFreeze, but describes an implicit freeze constraint
* added for stack types within a script. Applies to all compilations of the
* script, not just a single one.
*/
class TypeConstraintFreezeStack : public TypeConstraint
{
JSScript* script_;
public:
explicit TypeConstraintFreezeStack(JSScript* script)
: script_(script)
{}
const char* kind() { return "freezeStack"; }
void newType(JSContext* cx, TypeSet* source, TypeSet::Type type) {
/*
* Unlike TypeConstraintFreeze, triggering this constraint once does
* not disable it on future changes to the type set.
*/
cx->zone()->types.addPendingRecompile(cx, script_);
}
bool sweep(TypeZone& zone, TypeConstraint** res) {
if (IsAboutToBeFinalizedUnbarriered(&script_))
return false;
*res = zone.typeLifoAlloc.new_<TypeConstraintFreezeStack>(script_);
return true;
}
JSCompartment* maybeCompartment() {
return script_->compartment();
}
};
} /* anonymous namespace */
bool
js::FinishCompilation(JSContext* cx, HandleScript script, CompilerConstraintList* constraints,
RecompileInfo* precompileInfo, bool* isValidOut)
{
if (constraints->failed())
return false;
CompilerOutput co(script);
TypeZone& types = cx->zone()->types;
if (!types.compilerOutputs) {
types.compilerOutputs = cx->new_<TypeZone::CompilerOutputVector>();
if (!types.compilerOutputs)
return false;
}
#ifdef DEBUG
for (size_t i = 0; i < types.compilerOutputs->length(); i++) {
const CompilerOutput& co = (*types.compilerOutputs)[i];
MOZ_ASSERT_IF(co.isValid(), co.script() != script);
}
#endif
uint32_t index = types.compilerOutputs->length();
if (!types.compilerOutputs->append(co)) {
ReportOutOfMemory(cx);
return false;
}
*precompileInfo = RecompileInfo(index, types.generation);
bool succeeded = true;
for (size_t i = 0; i < constraints->length(); i++) {
CompilerConstraint* constraint = constraints->get(i);
if (!constraint->generateTypeConstraint(cx, *precompileInfo))
succeeded = false;
}
for (size_t i = 0; i < constraints->numFrozenScripts(); i++) {
const CompilerConstraintList::FrozenScript& entry = constraints->frozenScript(i);
if (!entry.script->types()) {
succeeded = false;
break;
}
// It could happen that one of the compiled scripts was made a
// debuggee mid-compilation (e.g., via setting a breakpoint). If so,
// throw away the compilation.
if (entry.script->isDebuggee()) {
succeeded = false;
break;
}
if (!CheckFrozenTypeSet(cx, entry.thisTypes, TypeScript::ThisTypes(entry.script)))
succeeded = false;
unsigned nargs = entry.script->functionNonDelazifying()
? entry.script->functionNonDelazifying()->nargs()
: 0;
for (size_t i = 0; i < nargs; i++) {
if (!CheckFrozenTypeSet(cx, &entry.argTypes[i], TypeScript::ArgTypes(entry.script, i)))
succeeded = false;
}
for (size_t i = 0; i < entry.script->nTypeSets(); i++) {
if (!CheckFrozenTypeSet(cx, &entry.bytecodeTypes[i], &entry.script->types()->typeArray()[i]))
succeeded = false;
}
// If necessary, add constraints to trigger invalidation on the script
// after any future changes to the stack type sets.
if (entry.script->hasFreezeConstraints())
continue;
size_t count = TypeScript::NumTypeSets(entry.script);
StackTypeSet* array = entry.script->types()->typeArray();
for (size_t i = 0; i < count; i++) {
if (!array[i].addConstraint(cx, cx->typeLifoAlloc().new_<TypeConstraintFreezeStack>(entry.script), false))
succeeded = false;
}
if (succeeded)
entry.script->setHasFreezeConstraints();
}
if (!succeeded || types.compilerOutputs->back().pendingInvalidation()) {
types.compilerOutputs->back().invalidate();
script->resetWarmUpCounter();
*isValidOut = false;
return true;
}
*isValidOut = true;
return true;
}
static void
CheckDefinitePropertiesTypeSet(JSContext* cx, TemporaryTypeSet* frozen, StackTypeSet* actual)
{
// The definite properties analysis happens on the main thread, so no new
// types can have been added to actual. The analysis may have updated the
// contents of |frozen| though with new speculative types, and these need
// to be reflected in |actual| for AddClearDefiniteFunctionUsesInScript
// to work.
if (!frozen->isSubset(actual)) {
TypeSet::TypeList list;
frozen->enumerateTypes(&list);
for (size_t i = 0; i < list.length(); i++)
actual->addType(cx, list[i]);
}
}
void
js::FinishDefinitePropertiesAnalysis(JSContext* cx, CompilerConstraintList* constraints)
{
#ifdef DEBUG
// Assert no new types have been added to the StackTypeSets. Do this before
// calling CheckDefinitePropertiesTypeSet, as it may add new types to the
// StackTypeSets and break these invariants if a script is inlined more
// than once. See also CheckDefinitePropertiesTypeSet.
for (size_t i = 0; i < constraints->numFrozenScripts(); i++) {
const CompilerConstraintList::FrozenScript& entry = constraints->frozenScript(i);
JSScript* script = entry.script;
MOZ_ASSERT(script->types());
MOZ_ASSERT(TypeScript::ThisTypes(script)->isSubset(entry.thisTypes));
unsigned nargs = entry.script->functionNonDelazifying()
? entry.script->functionNonDelazifying()->nargs()
: 0;
for (size_t j = 0; j < nargs; j++)
MOZ_ASSERT(TypeScript::ArgTypes(script, j)->isSubset(&entry.argTypes[j]));
for (size_t j = 0; j < script->nTypeSets(); j++)
MOZ_ASSERT(script->types()->typeArray()[j].isSubset(&entry.bytecodeTypes[j]));
}
#endif
for (size_t i = 0; i < constraints->numFrozenScripts(); i++) {
const CompilerConstraintList::FrozenScript& entry = constraints->frozenScript(i);
JSScript* script = entry.script;
if (!script->types())
MOZ_CRASH();
CheckDefinitePropertiesTypeSet(cx, entry.thisTypes, TypeScript::ThisTypes(script));
unsigned nargs = script->functionNonDelazifying()
? script->functionNonDelazifying()->nargs()
: 0;
for (size_t j = 0; j < nargs; j++)
CheckDefinitePropertiesTypeSet(cx, &entry.argTypes[j], TypeScript::ArgTypes(script, j));
for (size_t j = 0; j < script->nTypeSets(); j++)
CheckDefinitePropertiesTypeSet(cx, &entry.bytecodeTypes[j], &script->types()->typeArray()[j]);
}
}
namespace {
// Constraint which triggers recompilation of a script if any type is added to a type set. */
class ConstraintDataFreeze
{
public:
ConstraintDataFreeze() {}
const char* kind() { return "freeze"; }
bool invalidateOnNewType(TypeSet::Type type) { return true; }
bool invalidateOnNewPropertyState(TypeSet* property) { return true; }
bool invalidateOnNewObjectState(ObjectGroup* group) { return false; }
bool constraintHolds(JSContext* cx,
const HeapTypeSetKey& property, TemporaryTypeSet* expected)
{
return expected
? property.maybeTypes()->isSubset(expected)
: property.maybeTypes()->empty();
}
bool shouldSweep() { return false; }
JSCompartment* maybeCompartment() { return nullptr; }
};
} /* anonymous namespace */
void
HeapTypeSetKey::freeze(CompilerConstraintList* constraints)
{
LifoAlloc* alloc = constraints->alloc();
typedef CompilerConstraintInstance<ConstraintDataFreeze> T;
constraints->add(alloc->new_<T>(alloc, *this, ConstraintDataFreeze()));
}
static inline jit::MIRType
GetMIRTypeFromTypeFlags(TypeFlags flags)
{
switch (flags) {
case TYPE_FLAG_UNDEFINED:
return jit::MIRType::Undefined;
case TYPE_FLAG_NULL:
return jit::MIRType::Null;
case TYPE_FLAG_BOOLEAN:
return jit::MIRType::Boolean;
case TYPE_FLAG_INT32:
return jit::MIRType::Int32;
case (TYPE_FLAG_INT32 | TYPE_FLAG_DOUBLE):
return jit::MIRType::Double;
case TYPE_FLAG_STRING:
return jit::MIRType::String;
case TYPE_FLAG_SYMBOL:
return jit::MIRType::Symbol;
case TYPE_FLAG_LAZYARGS:
return jit::MIRType::MagicOptimizedArguments;
case TYPE_FLAG_ANYOBJECT:
return jit::MIRType::Object;
default:
return jit::MIRType::Value;
}
}
jit::MIRType
TemporaryTypeSet::getKnownMIRType()
{
TypeFlags flags = baseFlags();
jit::MIRType type;
if (baseObjectCount())
type = flags ? jit::MIRType::Value : jit::MIRType::Object;
else
type = GetMIRTypeFromTypeFlags(flags);
/*
* If the type set is totally empty then it will be treated as unknown,
* but we still need to record the dependency as adding a new type can give
* it a definite type tag. This is not needed if there are enough types
* that the exact tag is unknown, as it will stay unknown as more types are
* added to the set.
*/
DebugOnly<bool> empty = flags == 0 && baseObjectCount() == 0;
MOZ_ASSERT_IF(empty, type == jit::MIRType::Value);
return type;
}
jit::MIRType
HeapTypeSetKey::knownMIRType(CompilerConstraintList* constraints)
{
TypeSet* types = maybeTypes();
if (!types || types->unknown())
return jit::MIRType::Value;
TypeFlags flags = types->baseFlags() & ~TYPE_FLAG_ANYOBJECT;
jit::MIRType type;
if (types->unknownObject() || types->getObjectCount())
type = flags ? jit::MIRType::Value : jit::MIRType::Object;
else
type = GetMIRTypeFromTypeFlags(flags);
if (type != jit::MIRType::Value)
freeze(constraints);
/*
* If the type set is totally empty then it will be treated as unknown,
* but we still need to record the dependency as adding a new type can give
* it a definite type tag. This is not needed if there are enough types
* that the exact tag is unknown, as it will stay unknown as more types are
* added to the set.
*/
MOZ_ASSERT_IF(types->empty(), type == jit::MIRType::Value);
return type;
}
bool
HeapTypeSetKey::isOwnProperty(CompilerConstraintList* constraints,
bool allowEmptyTypesForGlobal/* = false*/)
{
if (maybeTypes() && (!maybeTypes()->empty() || maybeTypes()->nonDataProperty()))
return true;
if (object()->isSingleton()) {
JSObject* obj = object()->singleton();
MOZ_ASSERT(CanHaveEmptyPropertyTypesForOwnProperty(obj) == obj->is<GlobalObject>());
if (!allowEmptyTypesForGlobal) {
if (CanHaveEmptyPropertyTypesForOwnProperty(obj))
return true;
}
}
freeze(constraints);
return false;
}
bool
HeapTypeSetKey::knownSubset(CompilerConstraintList* constraints, const HeapTypeSetKey& other)
{
if (!maybeTypes() || maybeTypes()->empty()) {
freeze(constraints);
return true;
}
if (!other.maybeTypes() || !maybeTypes()->isSubset(other.maybeTypes()))
return false;
freeze(constraints);
return true;
}
JSObject*
TemporaryTypeSet::maybeSingleton()
{
if (baseFlags() != 0 || baseObjectCount() != 1)
return nullptr;
return getSingleton(0);
}
JSObject*
HeapTypeSetKey::singleton(CompilerConstraintList* constraints)
{
HeapTypeSet* types = maybeTypes();
if (!types || types->nonDataProperty() || types->baseFlags() != 0 || types->getObjectCount() != 1)
return nullptr;
JSObject* obj = types->getSingleton(0);
if (obj)
freeze(constraints);
return obj;
}
bool
HeapTypeSetKey::needsBarrier(CompilerConstraintList* constraints)
{
TypeSet* types = maybeTypes();
if (!types)
return false;
bool result = types->unknownObject()
|| types->getObjectCount() > 0
|| types->hasAnyFlag(TYPE_FLAG_STRING | TYPE_FLAG_SYMBOL);
if (!result)
freeze(constraints);
return result;
}
namespace {
// Constraint which triggers recompilation if an object acquires particular flags.
class ConstraintDataFreezeObjectFlags
{
public:
// Flags we are watching for on this object.
ObjectGroupFlags flags;
explicit ConstraintDataFreezeObjectFlags(ObjectGroupFlags flags)
: flags(flags)
{
MOZ_ASSERT(flags);
}
const char* kind() { return "freezeObjectFlags"; }
bool invalidateOnNewType(TypeSet::Type type) { return false; }
bool invalidateOnNewPropertyState(TypeSet* property) { return false; }
bool invalidateOnNewObjectState(ObjectGroup* group) {
return group->hasAnyFlags(flags);
}
bool constraintHolds(JSContext* cx,
const HeapTypeSetKey& property, TemporaryTypeSet* expected)
{
return !invalidateOnNewObjectState(property.object()->maybeGroup());
}
bool shouldSweep() { return false; }
JSCompartment* maybeCompartment() { return nullptr; }
};
} /* anonymous namespace */
bool
TypeSet::ObjectKey::hasFlags(CompilerConstraintList* constraints, ObjectGroupFlags flags)
{
MOZ_ASSERT(flags);
if (ObjectGroup* group = maybeGroup()) {
if (group->hasAnyFlags(flags))
return true;
}
HeapTypeSetKey objectProperty = property(JSID_EMPTY);
LifoAlloc* alloc = constraints->alloc();
typedef CompilerConstraintInstance<ConstraintDataFreezeObjectFlags> T;
constraints->add(alloc->new_<T>(alloc, objectProperty, ConstraintDataFreezeObjectFlags(flags)));
return false;
}
bool
TypeSet::ObjectKey::hasStableClassAndProto(CompilerConstraintList* constraints)
{
return !hasFlags(constraints, OBJECT_FLAG_UNKNOWN_PROPERTIES);
}
bool
TemporaryTypeSet::hasObjectFlags(CompilerConstraintList* constraints, ObjectGroupFlags flags)
{
if (unknownObject())
return true;
/*
* Treat type sets containing no objects as having all object flags,
* to spare callers from having to check this.
*/
if (baseObjectCount() == 0)
return true;
unsigned count = getObjectCount();
for (unsigned i = 0; i < count; i++) {
ObjectKey* key = getObject(i);
if (key && key->hasFlags(constraints, flags))
return true;
}
return false;
}
gc::InitialHeap
ObjectGroup::initialHeap(CompilerConstraintList* constraints)
{
// If this object is not required to be pretenured but could be in the
// future, add a constraint to trigger recompilation if the requirement
// changes.
if (shouldPreTenure())
return gc::TenuredHeap;
if (!canPreTenure())
return gc::DefaultHeap;
HeapTypeSetKey objectProperty = TypeSet::ObjectKey::get(this)->property(JSID_EMPTY);
LifoAlloc* alloc = constraints->alloc();
typedef CompilerConstraintInstance<ConstraintDataFreezeObjectFlags> T;
constraints->add(alloc->new_<T>(alloc, objectProperty, ConstraintDataFreezeObjectFlags(OBJECT_FLAG_PRE_TENURE)));
return gc::DefaultHeap;
}
namespace {
// Constraint which triggers recompilation on any type change in an inlined
// script. The freeze constraints added to stack type sets will only directly
// invalidate the script containing those stack type sets. To invalidate code
// for scripts into which the base script was inlined, ObjectStateChange is used.
class ConstraintDataFreezeObjectForInlinedCall
{
public:
ConstraintDataFreezeObjectForInlinedCall()
{}
const char* kind() { return "freezeObjectForInlinedCall"; }
bool invalidateOnNewType(TypeSet::Type type) { return false; }
bool invalidateOnNewPropertyState(TypeSet* property) { return false; }
bool invalidateOnNewObjectState(ObjectGroup* group) {
// We don't keep track of the exact dependencies the caller has on its
// inlined scripts' type sets, so always invalidate the caller.
return true;
}
bool constraintHolds(JSContext* cx,
const HeapTypeSetKey& property, TemporaryTypeSet* expected)
{
return true;
}
bool shouldSweep() { return false; }
JSCompartment* maybeCompartment() { return nullptr; }
};
// Constraint which triggers recompilation when a typed array's data becomes
// invalid.
class ConstraintDataFreezeObjectForTypedArrayData
{
NativeObject* obj;
uintptr_t viewData;
uint32_t length;
public:
explicit ConstraintDataFreezeObjectForTypedArrayData(TypedArrayObject& tarray)
: obj(&tarray),
viewData(tarray.viewDataEither().unwrapValue()),
length(tarray.length())
{
MOZ_ASSERT(tarray.isSingleton());
}
const char* kind() { return "freezeObjectForTypedArrayData"; }
bool invalidateOnNewType(TypeSet::Type type) { return false; }
bool invalidateOnNewPropertyState(TypeSet* property) { return false; }
bool invalidateOnNewObjectState(ObjectGroup* group) {
MOZ_ASSERT(obj->group() == group);
TypedArrayObject& tarr = obj->as<TypedArrayObject>();
return tarr.viewDataEither().unwrapValue() != viewData || tarr.length() != length;
}
bool constraintHolds(JSContext* cx,
const HeapTypeSetKey& property, TemporaryTypeSet* expected)
{
return !invalidateOnNewObjectState(property.object()->maybeGroup());
}
bool shouldSweep() {
// Note: |viewData| is only used for equality testing.
return IsAboutToBeFinalizedUnbarriered(&obj);
}
JSCompartment* maybeCompartment() {
return obj->compartment();
}
};
// Constraint which triggers recompilation if an unboxed object in some group
// is converted to a native object.
class ConstraintDataFreezeObjectForUnboxedConvertedToNative
{
public:
ConstraintDataFreezeObjectForUnboxedConvertedToNative()
{}
const char* kind() { return "freezeObjectForUnboxedConvertedToNative"; }
bool invalidateOnNewType(TypeSet::Type type) { return false; }
bool invalidateOnNewPropertyState(TypeSet* property) { return false; }
bool invalidateOnNewObjectState(ObjectGroup* group) {
return group->unboxedLayout().nativeGroup() != nullptr;
}
bool constraintHolds(JSContext* cx,
const HeapTypeSetKey& property, TemporaryTypeSet* expected)
{
return !invalidateOnNewObjectState(property.object()->maybeGroup());
}
bool shouldSweep() { return false; }
JSCompartment* maybeCompartment() { return nullptr; }
};
} /* anonymous namespace */
void
TypeSet::ObjectKey::watchStateChangeForInlinedCall(CompilerConstraintList* constraints)
{
HeapTypeSetKey objectProperty = property(JSID_EMPTY);
LifoAlloc* alloc = constraints->alloc();
typedef CompilerConstraintInstance<ConstraintDataFreezeObjectForInlinedCall> T;
constraints->add(alloc->new_<T>(alloc, objectProperty, ConstraintDataFreezeObjectForInlinedCall()));
}
void
TypeSet::ObjectKey::watchStateChangeForTypedArrayData(CompilerConstraintList* constraints)
{
TypedArrayObject& tarray = singleton()->as<TypedArrayObject>();
HeapTypeSetKey objectProperty = property(JSID_EMPTY);
LifoAlloc* alloc = constraints->alloc();
typedef CompilerConstraintInstance<ConstraintDataFreezeObjectForTypedArrayData> T;
constraints->add(alloc->new_<T>(alloc, objectProperty,
ConstraintDataFreezeObjectForTypedArrayData(tarray)));
}
void
TypeSet::ObjectKey::watchStateChangeForUnboxedConvertedToNative(CompilerConstraintList* constraints)
{
HeapTypeSetKey objectProperty = property(JSID_EMPTY);
LifoAlloc* alloc = constraints->alloc();
typedef CompilerConstraintInstance<ConstraintDataFreezeObjectForUnboxedConvertedToNative> T;
constraints->add(alloc->new_<T>(alloc, objectProperty,
ConstraintDataFreezeObjectForUnboxedConvertedToNative()));
}
static void
ObjectStateChange(ExclusiveContext* cxArg, ObjectGroup* group, bool markingUnknown)
{
if (group->unknownProperties())
return;
/* All constraints listening to state changes are on the empty id. */
HeapTypeSet* types = group->maybeGetProperty(JSID_EMPTY);
/* Mark as unknown after getting the types, to avoid assertion. */
if (markingUnknown)
group->addFlags(OBJECT_FLAG_DYNAMIC_MASK | OBJECT_FLAG_UNKNOWN_PROPERTIES);
if (types) {
if (JSContext* cx = cxArg->maybeJSContext()) {
TypeConstraint* constraint = types->constraintList;
while (constraint) {
constraint->newObjectState(cx, group);
constraint = constraint->next;
}
} else {
MOZ_ASSERT(!types->constraintList);
}
}
}
namespace {
class ConstraintDataFreezePropertyState
{
public:
enum Which {
NON_DATA,
NON_WRITABLE
} which;
explicit ConstraintDataFreezePropertyState(Which which)
: which(which)
{}
const char* kind() { return (which == NON_DATA) ? "freezeNonDataProperty" : "freezeNonWritableProperty"; }
bool invalidateOnNewType(TypeSet::Type type) { return false; }
bool invalidateOnNewPropertyState(TypeSet* property) {
return (which == NON_DATA)
? property->nonDataProperty()
: property->nonWritableProperty();
}
bool invalidateOnNewObjectState(ObjectGroup* group) { return false; }
bool constraintHolds(JSContext* cx,
const HeapTypeSetKey& property, TemporaryTypeSet* expected)
{
return !invalidateOnNewPropertyState(property.maybeTypes());
}
bool shouldSweep() { return false; }
JSCompartment* maybeCompartment() { return nullptr; }
};
} /* anonymous namespace */
bool
HeapTypeSetKey::nonData(CompilerConstraintList* constraints)
{
if (maybeTypes() && maybeTypes()->nonDataProperty())
return true;
LifoAlloc* alloc = constraints->alloc();
typedef CompilerConstraintInstance<ConstraintDataFreezePropertyState> T;
constraints->add(alloc->new_<T>(alloc, *this,
ConstraintDataFreezePropertyState(ConstraintDataFreezePropertyState::NON_DATA)));
return false;
}
bool
HeapTypeSetKey::nonWritable(CompilerConstraintList* constraints)
{
if (maybeTypes() && maybeTypes()->nonWritableProperty())
return true;
LifoAlloc* alloc = constraints->alloc();
typedef CompilerConstraintInstance<ConstraintDataFreezePropertyState> T;
constraints->add(alloc->new_<T>(alloc, *this,
ConstraintDataFreezePropertyState(ConstraintDataFreezePropertyState::NON_WRITABLE)));
return false;
}
namespace {
class ConstraintDataConstantProperty
{
public:
explicit ConstraintDataConstantProperty() {}
const char* kind() { return "constantProperty"; }
bool invalidateOnNewType(TypeSet::Type type) { return false; }
bool invalidateOnNewPropertyState(TypeSet* property) {
return property->nonConstantProperty();
}
bool invalidateOnNewObjectState(ObjectGroup* group) { return false; }
bool constraintHolds(JSContext* cx,
const HeapTypeSetKey& property, TemporaryTypeSet* expected)
{
return !invalidateOnNewPropertyState(property.maybeTypes());
}
bool shouldSweep() { return false; }
JSCompartment* maybeCompartment() { return nullptr; }
};
} /* anonymous namespace */
bool
HeapTypeSetKey::constant(CompilerConstraintList* constraints, Value* valOut)
{
if (nonData(constraints))
return false;
// Only singleton object properties can be marked as constants.
JSObject* obj = object()->singleton();
if (!obj || !obj->isNative())
return false;
if (maybeTypes() && maybeTypes()->nonConstantProperty())
return false;
// Get the current value of the property.
Shape* shape = obj->as<NativeObject>().lookupPure(id());
if (!shape || !shape->hasDefaultGetter() || !shape->hasSlot() || shape->hadOverwrite())
return false;
Value val = obj->as<NativeObject>().getSlot(shape->slot());
// If the value is a pointer to an object in the nursery, don't optimize.
if (val.isGCThing() && IsInsideNursery(val.toGCThing()))
return false;
// If the value is a string that's not atomic, don't optimize.
if (val.isString() && !val.toString()->isAtom())
return false;
*valOut = val;
LifoAlloc* alloc = constraints->alloc();
typedef CompilerConstraintInstance<ConstraintDataConstantProperty> T;
constraints->add(alloc->new_<T>(alloc, *this, ConstraintDataConstantProperty()));
return true;
}
// A constraint that never triggers recompilation.
class ConstraintDataInert
{
public:
explicit ConstraintDataInert() {}
const char* kind() { return "inert"; }
bool invalidateOnNewType(TypeSet::Type type) { return false; }
bool invalidateOnNewPropertyState(TypeSet* property) { return false; }
bool invalidateOnNewObjectState(ObjectGroup* group) { return false; }
bool constraintHolds(JSContext* cx,
const HeapTypeSetKey& property, TemporaryTypeSet* expected)
{
return true;
}
bool shouldSweep() { return false; }
JSCompartment* maybeCompartment() { return nullptr; }
};
bool
HeapTypeSetKey::couldBeConstant(CompilerConstraintList* constraints)
{
// Only singleton object properties can be marked as constants.
if (!object()->isSingleton())
return false;
if (!maybeTypes() || !maybeTypes()->nonConstantProperty())
return true;
// It is possible for a property that was not marked as constant to
// 'become' one, if we throw away the type property during a GC and
// regenerate it with the constant flag set. ObjectGroup::sweep only removes
// type properties if they have no constraints attached to them, so add
// inert constraints to pin these properties in place.
LifoAlloc* alloc = constraints->alloc();
typedef CompilerConstraintInstance<ConstraintDataInert> T;
constraints->add(alloc->new_<T>(alloc, *this, ConstraintDataInert()));
return false;
}
bool
TemporaryTypeSet::filtersType(const TemporaryTypeSet* other, Type filteredType) const
{
if (other->unknown())
return unknown();
for (TypeFlags flag = 1; flag < TYPE_FLAG_ANYOBJECT; flag <<= 1) {
Type type = PrimitiveType(TypeFlagPrimitive(flag));
if (type != filteredType && other->hasType(type) && !hasType(type))
return false;
}
if (other->unknownObject())
return unknownObject();
for (size_t i = 0; i < other->getObjectCount(); i++) {
ObjectKey* key = other->getObject(i);
if (key) {
Type type = ObjectType(key);
if (type != filteredType && !hasType(type))
return false;
}
}
return true;
}
TemporaryTypeSet::DoubleConversion
TemporaryTypeSet::convertDoubleElements(CompilerConstraintList* constraints)
{
if (unknownObject() || !getObjectCount())
return AmbiguousDoubleConversion;
bool alwaysConvert = true;
bool maybeConvert = false;
bool dontConvert = false;
for (unsigned i = 0; i < getObjectCount(); i++) {
ObjectKey* key = getObject(i);
if (!key)
continue;
if (key->unknownProperties()) {
alwaysConvert = false;
continue;
}
HeapTypeSetKey property = key->property(JSID_VOID);
property.freeze(constraints);
// We can't convert to double elements for objects which do not have
// double in their element types (as the conversion may render the type
// information incorrect), nor for non-array objects (as their elements
// may point to emptyObjectElements or emptyObjectElementsShared, which
// cannot be converted).
if (!property.maybeTypes() ||
!property.maybeTypes()->hasType(DoubleType()) ||
key->clasp() != &ArrayObject::class_)
{
dontConvert = true;
alwaysConvert = false;
continue;
}
// Only bother with converting known packed arrays whose possible
// element types are int or double. Other arrays require type tests
// when elements are accessed regardless of the conversion.
if (property.knownMIRType(constraints) == jit::MIRType::Double &&
!key->hasFlags(constraints, OBJECT_FLAG_NON_PACKED))
{
maybeConvert = true;
} else {
alwaysConvert = false;
}
}
MOZ_ASSERT_IF(alwaysConvert, maybeConvert);
if (maybeConvert && dontConvert)
return AmbiguousDoubleConversion;
if (alwaysConvert)
return AlwaysConvertToDoubles;
if (maybeConvert)
return MaybeConvertToDoubles;
return DontConvertToDoubles;
}
const Class*
TemporaryTypeSet::getKnownClass(CompilerConstraintList* constraints)
{
if (unknownObject())
return nullptr;
const Class* clasp = nullptr;
unsigned count = getObjectCount();
for (unsigned i = 0; i < count; i++) {
const Class* nclasp = getObjectClass(i);
if (!nclasp)
continue;
if (getObject(i)->unknownProperties())
return nullptr;
if (clasp && clasp != nclasp)
return nullptr;
clasp = nclasp;
}
if (clasp) {
for (unsigned i = 0; i < count; i++) {
ObjectKey* key = getObject(i);
if (key && !key->hasStableClassAndProto(constraints))
return nullptr;
}
}
return clasp;
}
void
TemporaryTypeSet::getTypedArraySharedness(CompilerConstraintList* constraints,
TypedArraySharedness* sharedness)
{
// In the future this will inspect the object set.
*sharedness = UnknownSharedness;
}
TemporaryTypeSet::ForAllResult
TemporaryTypeSet::forAllClasses(CompilerConstraintList* constraints,
bool (*func)(const Class* clasp))
{
if (unknownObject())
return ForAllResult::MIXED;
unsigned count = getObjectCount();
if (count == 0)
return ForAllResult::EMPTY;
bool true_results = false;
bool false_results = false;
for (unsigned i = 0; i < count; i++) {
const Class* clasp = getObjectClass(i);
if (!clasp)
continue;
if (!getObject(i)->hasStableClassAndProto(constraints))
return ForAllResult::MIXED;
if (func(clasp)) {
true_results = true;
if (false_results)
return ForAllResult::MIXED;
} else {
false_results = true;
if (true_results)
return ForAllResult::MIXED;
}
}
MOZ_ASSERT(true_results != false_results);
return true_results ? ForAllResult::ALL_TRUE : ForAllResult::ALL_FALSE;
}
Scalar::Type
TemporaryTypeSet::getTypedArrayType(CompilerConstraintList* constraints,
TypedArraySharedness* sharedness)
{
const Class* clasp = getKnownClass(constraints);
if (clasp && IsTypedArrayClass(clasp)) {
if (sharedness)
getTypedArraySharedness(constraints, sharedness);
return (Scalar::Type) (clasp - &TypedArrayObject::classes[0]);
}
return Scalar::MaxTypedArrayViewType;
}
bool
TemporaryTypeSet::isDOMClass(CompilerConstraintList* constraints)
{
if (unknownObject())
return false;
unsigned count = getObjectCount();
for (unsigned i = 0; i < count; i++) {
const Class* clasp = getObjectClass(i);
if (!clasp)
continue;
if (!clasp->isDOMClass() || !getObject(i)->hasStableClassAndProto(constraints))
return false;
}
return count > 0;
}
bool
TemporaryTypeSet::maybeCallable(CompilerConstraintList* constraints)
{
if (!maybeObject())
return false;
if (unknownObject())
return true;
unsigned count = getObjectCount();
for (unsigned i = 0; i < count; i++) {
const Class* clasp = getObjectClass(i);
if (!clasp)
continue;
if (clasp->isProxy() || clasp->nonProxyCallable())
return true;
if (!getObject(i)->hasStableClassAndProto(constraints))
return true;
}
return false;
}
bool
TemporaryTypeSet::maybeEmulatesUndefined(CompilerConstraintList* constraints)
{
if (!maybeObject())
return false;
if (unknownObject())
return true;
unsigned count = getObjectCount();
for (unsigned i = 0; i < count; i++) {
// The object emulates undefined if clasp->emulatesUndefined() or if
// it's a WrapperObject, see EmulatesUndefined. Since all wrappers are
// proxies, we can just check for that.
const Class* clasp = getObjectClass(i);
if (!clasp)
continue;
if (clasp->emulatesUndefined() || clasp->isProxy())
return true;
if (!getObject(i)->hasStableClassAndProto(constraints))
return true;
}
return false;
}
bool
TemporaryTypeSet::getCommonPrototype(CompilerConstraintList* constraints, JSObject** proto)
{
if (unknownObject())
return false;
*proto = nullptr;
bool isFirst = true;
unsigned count = getObjectCount();
for (unsigned i = 0; i < count; i++) {
ObjectKey* key = getObject(i);
if (!key)
continue;
if (key->unknownProperties())
return false;
TaggedProto nproto = key->proto();
if (isFirst) {
if (nproto.isDynamic())
return false;
*proto = nproto.toObjectOrNull();
isFirst = false;
} else {
if (nproto != TaggedProto(*proto))
return false;
}
}
// Guard against mutating __proto__.
for (unsigned i = 0; i < count; i++) {
if (ObjectKey* key = getObject(i))
JS_ALWAYS_TRUE(key->hasStableClassAndProto(constraints));
}
return true;
}
bool
TemporaryTypeSet::propertyNeedsBarrier(CompilerConstraintList* constraints, jsid id)
{
if (unknownObject())
return true;
for (unsigned i = 0; i < getObjectCount(); i++) {
ObjectKey* key = getObject(i);
if (!key)
continue;
if (key->unknownProperties())
return true;
HeapTypeSetKey property = key->property(id);
if (property.needsBarrier(constraints))
return true;
}
return false;
}
bool
js::ClassCanHaveExtraProperties(const Class* clasp)
{
if (clasp == &UnboxedPlainObject::class_ || clasp == &UnboxedArrayObject::class_)
return false;
return clasp->getResolve()
|| clasp->getOpsLookupProperty()
|| clasp->getOpsGetProperty()
|| IsTypedArrayClass(clasp);
}
void
TypeZone::processPendingRecompiles(FreeOp* fop, RecompileInfoVector& recompiles)
{
MOZ_ASSERT(!recompiles.empty());
/*
* Steal the list of scripts to recompile, to make sure we don't try to
* recursively recompile them.
*/
RecompileInfoVector pending;
for (size_t i = 0; i < recompiles.length(); i++) {
AutoEnterOOMUnsafeRegion oomUnsafe;
if (!pending.append(recompiles[i]))
oomUnsafe.crash("processPendingRecompiles");
}
recompiles.clear();
jit::Invalidate(*this, fop, pending);
MOZ_ASSERT(recompiles.empty());
}
void
TypeZone::addPendingRecompile(JSContext* cx, const RecompileInfo& info)
{
CompilerOutput* co = info.compilerOutput(cx);
if (!co || !co->isValid() || co->pendingInvalidation())
return;
InferSpew(ISpewOps, "addPendingRecompile: %p:%s:%" PRIuSIZE,
co->script(), co->script()->filename(), co->script()->lineno());
co->setPendingInvalidation();
AutoEnterOOMUnsafeRegion oomUnsafe;
if (!cx->zone()->types.activeAnalysis->pendingRecompiles.append(info))
oomUnsafe.crash("Could not update pendingRecompiles");
}
void
TypeZone::addPendingRecompile(JSContext* cx, JSScript* script)
{
MOZ_ASSERT(script);
CancelOffThreadIonCompile(script);
// Let the script warm up again before attempting another compile.
if (jit::IsBaselineEnabled(cx))
script->resetWarmUpCounter();
if (script->hasIonScript())
addPendingRecompile(cx, script->ionScript()->recompileInfo());
// When one script is inlined into another the caller listens to state
// changes on the callee's script, so trigger these to force recompilation
// of any such callers.
if (script->functionNonDelazifying() && !script->functionNonDelazifying()->hasLazyGroup())
ObjectStateChange(cx, script->functionNonDelazifying()->group(), false);
}
void
js::PrintTypes(JSContext* cx, JSCompartment* comp, bool force)
{
#ifdef DEBUG
gc::AutoSuppressGC suppressGC(cx);
JSAutoRequest request(cx);
Zone* zone = comp->zone();
AutoEnterAnalysis enter(nullptr, zone);
if (!force && !InferSpewActive(ISpewResult))
return;
RootedScript script(cx);
for (auto iter = zone->cellIter<JSScript>(); !iter.done(); iter.next()) {
script = iter;
if (script->types())
script->types()->printTypes(cx, script);
}
for (auto group = zone->cellIter<ObjectGroup>(); !group.done(); group.next())
group->print();
#endif
}
/////////////////////////////////////////////////////////////////////
// ObjectGroup
/////////////////////////////////////////////////////////////////////
static inline void
UpdatePropertyType(ExclusiveContext* cx, HeapTypeSet* types, NativeObject* obj, Shape* shape,
bool indexed)
{
MOZ_ASSERT(obj->isSingleton() && !obj->hasLazyGroup());
if (!shape->writable())
types->setNonWritableProperty(cx);
if (shape->hasGetterValue() || shape->hasSetterValue()) {
types->setNonDataProperty(cx);
types->TypeSet::addType(TypeSet::UnknownType(), &cx->typeLifoAlloc());
} else if (shape->hasDefaultGetter() && shape->hasSlot()) {
if (!indexed && types->canSetDefinite(shape->slot()))
types->setDefinite(shape->slot());
const Value& value = obj->getSlot(shape->slot());
/*
* Don't add initial undefined types for properties of global objects
* that are not collated into the JSID_VOID property (see propertySet
* comment).
*
* Also don't add untracked values (initial uninitialized lexical magic
* values and optimized out values) as appearing in CallObjects, module
* environments or the global lexical scope.
*/
MOZ_ASSERT_IF(TypeSet::IsUntrackedValue(value),
obj->is<CallObject>() ||
obj->is<ModuleEnvironmentObject>() ||
IsExtensibleLexicalEnvironment(obj));
if ((indexed || !value.isUndefined() || !CanHaveEmptyPropertyTypesForOwnProperty(obj)) &&
!TypeSet::IsUntrackedValue(value))
{
TypeSet::Type type = TypeSet::GetValueType(value);
types->TypeSet::addType(type, &cx->typeLifoAlloc());
types->postWriteBarrier(cx, type);
}
if (indexed || shape->hadOverwrite()) {
types->setNonConstantProperty(cx);
} else {
InferSpew(ISpewOps, "typeSet: %sT%p%s property %s %s - setConstant",
InferSpewColor(types), types, InferSpewColorReset(),
TypeSet::ObjectGroupString(obj->group()), TypeIdString(shape->propid()));
}
}
}
void
ObjectGroup::updateNewPropertyTypes(ExclusiveContext* cx, JSObject* objArg, jsid id, HeapTypeSet* types)
{
InferSpew(ISpewOps, "typeSet: %sT%p%s property %s %s",
InferSpewColor(types), types, InferSpewColorReset(),
TypeSet::ObjectGroupString(this), TypeIdString(id));
MOZ_ASSERT_IF(objArg, objArg->group() == this);
MOZ_ASSERT_IF(singleton(), objArg);
if (!singleton() || !objArg->isNative()) {
types->setNonConstantProperty(cx);
return;
}
NativeObject* obj = &objArg->as<NativeObject>();
/*
* Fill the property in with any type the object already has in an own
* property. We are only interested in plain native properties and
* dense elements which don't go through a barrier when read by the VM
* or jitcode.
*/
if (JSID_IS_VOID(id)) {
/* Go through all shapes on the object to get integer-valued properties. */
RootedShape shape(cx, obj->lastProperty());
while (!shape->isEmptyShape()) {
if (JSID_IS_VOID(IdToTypeId(shape->propid())))
UpdatePropertyType(cx, types, obj, shape, true);
shape = shape->previous();
}
/* Also get values of any dense elements in the object. */
for (size_t i = 0; i < obj->getDenseInitializedLength(); i++) {
const Value& value = obj->getDenseElement(i);
if (!value.isMagic(JS_ELEMENTS_HOLE)) {
TypeSet::Type type = TypeSet::GetValueType(value);
types->TypeSet::addType(type, &cx->typeLifoAlloc());
types->postWriteBarrier(cx, type);
}
}
} else if (!JSID_IS_EMPTY(id)) {
RootedId rootedId(cx, id);
Shape* shape = obj->lookup(cx, rootedId);
if (shape)
UpdatePropertyType(cx, types, obj, shape, false);
}
if (obj->watched()) {
/*
* Mark the property as non-data, to inhibit optimizations on it
* and avoid bypassing the watchpoint handler.
*/
types->setNonDataProperty(cx);
}
}
void
ObjectGroup::addDefiniteProperties(ExclusiveContext* cx, Shape* shape)
{
if (unknownProperties())
return;
// Mark all properties of shape as definite properties of this group.
AutoEnterAnalysis enter(cx);
while (!shape->isEmptyShape()) {
jsid id = IdToTypeId(shape->propid());
if (!JSID_IS_VOID(id)) {
MOZ_ASSERT_IF(shape->slot() >= shape->numFixedSlots(),
shape->numFixedSlots() == NativeObject::MAX_FIXED_SLOTS);
TypeSet* types = getProperty(cx, nullptr, id);
if (!types) {
MOZ_ASSERT(unknownProperties());
return;
}
if (types->canSetDefinite(shape->slot()))
types->setDefinite(shape->slot());
}
shape = shape->previous();
}
}
bool
ObjectGroup::matchDefiniteProperties(HandleObject obj)
{
unsigned count = getPropertyCount();
for (unsigned i = 0; i < count; i++) {
Property* prop = getProperty(i);
if (!prop)
continue;
if (prop->types.definiteProperty()) {
unsigned slot = prop->types.definiteSlot();
bool found = false;
Shape* shape = obj->as<NativeObject>().lastProperty();
while (!shape->isEmptyShape()) {
if (shape->slot() == slot && shape->propid() == prop->id) {
found = true;
break;
}
shape = shape->previous();
}
if (!found)
return false;
}
}
return true;
}
void
js::AddTypePropertyId(ExclusiveContext* cx, ObjectGroup* group, JSObject* obj, jsid id, TypeSet::Type type)
{
MOZ_ASSERT(id == IdToTypeId(id));
if (group->unknownProperties())
return;
AutoEnterAnalysis enter(cx);
HeapTypeSet* types = group->getProperty(cx, obj, id);
if (!types)
return;
// Clear any constant flag if it exists.
if (!types->empty() && !types->nonConstantProperty()) {
InferSpew(ISpewOps, "constantMutated: %sT%p%s %s",
InferSpewColor(types), types, InferSpewColorReset(), TypeSet::TypeString(type));
types->setNonConstantProperty(cx);
}
if (types->hasType(type))
return;
InferSpew(ISpewOps, "externalType: property %s %s: %s",
TypeSet::ObjectGroupString(group), TypeIdString(id), TypeSet::TypeString(type));
types->addType(cx, type);
// If this addType caused the type set to be marked as containing any
// object, make sure that is reflected in other type sets the addType is
// propagated to below.
if (type.isObjectUnchecked() && types->unknownObject())
type = TypeSet::AnyObjectType();
// Propagate new types from partially initialized groups to fully
// initialized groups for the acquired properties analysis. Note that we
// don't need to do this for other property changes, as these will also be
// reflected via shape changes on the object that will prevent the object
// from acquiring the fully initialized group.
if (group->newScript() && group->newScript()->initializedGroup())
AddTypePropertyId(cx, group->newScript()->initializedGroup(), nullptr, id, type);
// Maintain equivalent type information for unboxed object groups and their
// corresponding native group. Since type sets might contain the unboxed
// group but not the native group, this ensures optimizations based on the
// unboxed group are valid for the native group.
if (group->maybeUnboxedLayout() && group->maybeUnboxedLayout()->nativeGroup())
AddTypePropertyId(cx, group->maybeUnboxedLayout()->nativeGroup(), nullptr, id, type);
if (ObjectGroup* unboxedGroup = group->maybeOriginalUnboxedGroup())
AddTypePropertyId(cx, unboxedGroup, nullptr, id, type);
}
void
js::AddTypePropertyId(ExclusiveContext* cx, ObjectGroup* group, JSObject* obj, jsid id, const Value& value)
{
AddTypePropertyId(cx, group, obj, id, TypeSet::GetValueType(value));
}
void
ObjectGroup::markPropertyNonData(ExclusiveContext* cx, JSObject* obj, jsid id)
{
AutoEnterAnalysis enter(cx);
id = IdToTypeId(id);
HeapTypeSet* types = getProperty(cx, obj, id);
if (types)
types->setNonDataProperty(cx);
}
void
ObjectGroup::markPropertyNonWritable(ExclusiveContext* cx, JSObject* obj, jsid id)
{
AutoEnterAnalysis enter(cx);
id = IdToTypeId(id);
HeapTypeSet* types = getProperty(cx, obj, id);
if (types)
types->setNonWritableProperty(cx);
}
void
ObjectGroup::markStateChange(ExclusiveContext* cxArg)
{
if (unknownProperties())
return;
AutoEnterAnalysis enter(cxArg);
HeapTypeSet* types = maybeGetProperty(JSID_EMPTY);
if (types) {
if (JSContext* cx = cxArg->maybeJSContext()) {
TypeConstraint* constraint = types->constraintList;
while (constraint) {
constraint->newObjectState(cx, this);
constraint = constraint->next;
}
} else {
MOZ_ASSERT(!types->constraintList);
}
}
}
void
ObjectGroup::setFlags(ExclusiveContext* cx, ObjectGroupFlags flags)
{
if (hasAllFlags(flags))
return;
AutoEnterAnalysis enter(cx);
addFlags(flags);
InferSpew(ISpewOps, "%s: setFlags 0x%x", TypeSet::ObjectGroupString(this), flags);
ObjectStateChange(cx, this, false);
// Propagate flag changes from partially to fully initialized groups for the
// acquired properties analysis.
if (newScript() && newScript()->initializedGroup())
newScript()->initializedGroup()->setFlags(cx, flags);
// Propagate flag changes between unboxed and corresponding native groups.
if (maybeUnboxedLayout() && maybeUnboxedLayout()->nativeGroup())
maybeUnboxedLayout()->nativeGroup()->setFlags(cx, flags);
if (ObjectGroup* unboxedGroup = maybeOriginalUnboxedGroup())
unboxedGroup->setFlags(cx, flags);
}
void
ObjectGroup::markUnknown(ExclusiveContext* cx)
{
AutoEnterAnalysis enter(cx);
MOZ_ASSERT(cx->zone()->types.activeAnalysis);
MOZ_ASSERT(!unknownProperties());
InferSpew(ISpewOps, "UnknownProperties: %s", TypeSet::ObjectGroupString(this));
clearNewScript(cx);
ObjectStateChange(cx, this, true);
/*
* Existing constraints may have already been added to this object, which we need
* to do the right thing for. We can't ensure that we will mark all unknown
* objects before they have been accessed, as the __proto__ of a known object
* could be dynamically set to an unknown object, and we can decide to ignore
* properties of an object during analysis (i.e. hashmaps). Adding unknown for
* any properties accessed already accounts for possible values read from them.
*/
unsigned count = getPropertyCount();
for (unsigned i = 0; i < count; i++) {
Property* prop = getProperty(i);
if (prop) {
prop->types.addType(cx, TypeSet::UnknownType());
prop->types.setNonDataProperty(cx);
}
}
if (ObjectGroup* unboxedGroup = maybeOriginalUnboxedGroup())
MarkObjectGroupUnknownProperties(cx, unboxedGroup);
if (maybeUnboxedLayout() && maybeUnboxedLayout()->nativeGroup())
MarkObjectGroupUnknownProperties(cx, maybeUnboxedLayout()->nativeGroup());
if (ObjectGroup* unboxedGroup = maybeOriginalUnboxedGroup())
MarkObjectGroupUnknownProperties(cx, unboxedGroup);
}
TypeNewScript*
ObjectGroup::anyNewScript()
{
if (newScript())
return newScript();
if (maybeUnboxedLayout())
return unboxedLayout().newScript();
return nullptr;
}
void
ObjectGroup::detachNewScript(bool writeBarrier, ObjectGroup* replacement)
{
// Clear the TypeNewScript from this ObjectGroup and, if it has been
// analyzed, remove it from the newObjectGroups table so that it will not be
// produced by calling 'new' on the associated function anymore.
// The TypeNewScript is not actually destroyed.
TypeNewScript* newScript = anyNewScript();
MOZ_ASSERT(newScript);
if (newScript->analyzed()) {
ObjectGroupCompartment& objectGroups = newScript->function()->compartment()->objectGroups;
TaggedProto proto = this->proto();
if (proto.isObject() && IsForwarded(proto.toObject()))
proto = TaggedProto(Forwarded(proto.toObject()));
JSObject* associated = MaybeForwarded(newScript->function());
if (replacement) {
MOZ_ASSERT(replacement->newScript()->function() == newScript->function());
objectGroups.replaceDefaultNewGroup(nullptr, proto, associated, replacement);
} else {
objectGroups.removeDefaultNewGroup(nullptr, proto, associated);
}
} else {
MOZ_ASSERT(!replacement);
}
if (this->newScript())
setAddendum(Addendum_None, nullptr, writeBarrier);
else
unboxedLayout().setNewScript(nullptr, writeBarrier);
}
void
ObjectGroup::maybeClearNewScriptOnOOM()
{
MOZ_ASSERT(zone()->isGCSweepingOrCompacting());
if (!isMarked())
return;
TypeNewScript* newScript = anyNewScript();
if (!newScript)
return;
addFlags(OBJECT_FLAG_NEW_SCRIPT_CLEARED);
// This method is called during GC sweeping, so don't trigger pre barriers.
detachNewScript(/* writeBarrier = */ false, nullptr);
js_delete(newScript);
}
void
ObjectGroup::clearNewScript(ExclusiveContext* cx, ObjectGroup* replacement /* = nullptr*/)
{
TypeNewScript* newScript = anyNewScript();
if (!newScript)
return;
AutoEnterAnalysis enter(cx);
if (!replacement) {
// Invalidate any Ion code constructing objects of this type.
setFlags(cx, OBJECT_FLAG_NEW_SCRIPT_CLEARED);
// Mark the constructing function as having its 'new' script cleared, so we
// will not try to construct another one later.
if (!newScript->function()->setNewScriptCleared(cx))
cx->recoverFromOutOfMemory();
}
detachNewScript(/* writeBarrier = */ true, replacement);
if (cx->isJSContext()) {
bool found = newScript->rollbackPartiallyInitializedObjects(cx->asJSContext(), this);
// If we managed to rollback any partially initialized objects, then
// any definite properties we added due to analysis of the new script
// are now invalid, so remove them. If there weren't any partially
// initialized objects then we don't need to change type information,
// as no more objects of this type will be created and the 'new' script
// analysis was still valid when older objects were created.
if (found) {
for (unsigned i = 0; i < getPropertyCount(); i++) {
Property* prop = getProperty(i);
if (!prop)
continue;
if (prop->types.definiteProperty())
prop->types.setNonDataProperty(cx);
}
}
} else {
// Threads with an ExclusiveContext are not allowed to run scripts.
MOZ_ASSERT(!cx->perThreadData->runtimeIfOnOwnerThread() ||
!cx->perThreadData->runtimeIfOnOwnerThread()->activation());
}
js_delete(newScript);
markStateChange(cx);
}
void
ObjectGroup::print()
{
TaggedProto tagged(proto());
fprintf(stderr, "%s : %s",
TypeSet::ObjectGroupString(this),
tagged.isObject()
? TypeSet::TypeString(TypeSet::ObjectType(tagged.toObject()))
: tagged.isDynamic()
? "(dynamic)"
: "(null)");
if (unknownProperties()) {
fprintf(stderr, " unknown");
} else {
if (!hasAnyFlags(OBJECT_FLAG_SPARSE_INDEXES))
fprintf(stderr, " dense");
if (!hasAnyFlags(OBJECT_FLAG_NON_PACKED))
fprintf(stderr, " packed");
if (!hasAnyFlags(OBJECT_FLAG_LENGTH_OVERFLOW))
fprintf(stderr, " noLengthOverflow");
if (hasAnyFlags(OBJECT_FLAG_ITERATED))
fprintf(stderr, " iterated");
if (maybeInterpretedFunction())
fprintf(stderr, " ifun");
}
unsigned count = getPropertyCount();
if (count == 0) {
fprintf(stderr, " {}\n");
return;
}
fprintf(stderr, " {");
if (newScript()) {
if (newScript()->analyzed()) {
fprintf(stderr, "\n newScript %d properties",
(int) newScript()->templateObject()->slotSpan());
if (newScript()->initializedGroup()) {
fprintf(stderr, " initializedGroup %#" PRIxPTR " with %d properties",
uintptr_t(newScript()->initializedGroup()), int(newScript()->initializedShape()->slotSpan()));
}
} else {
fprintf(stderr, "\n newScript unanalyzed");
}
}
for (unsigned i = 0; i < count; i++) {
Property* prop = getProperty(i);
if (prop) {
fprintf(stderr, "\n %s:", TypeIdString(prop->id));
prop->types.print();
}
}
fprintf(stderr, "\n}\n");
}
/////////////////////////////////////////////////////////////////////
// Type Analysis
/////////////////////////////////////////////////////////////////////
/*
* Persistent constraint clearing out newScript and definite properties from
* an object should a property on another object get a getter or setter.
*/
class TypeConstraintClearDefiniteGetterSetter : public TypeConstraint
{
public:
ObjectGroup* group;
explicit TypeConstraintClearDefiniteGetterSetter(ObjectGroup* group)
: group(group)
{}
const char* kind() { return "clearDefiniteGetterSetter"; }
void newPropertyState(JSContext* cx, TypeSet* source) {
/*
* Clear out the newScript shape and definite property information from
* an object if the source type set could be a setter or could be
* non-writable.
*/
if (source->nonDataProperty() || source->nonWritableProperty())
group->clearNewScript(cx);
}
void newType(JSContext* cx, TypeSet* source, TypeSet::Type type) {}
bool sweep(TypeZone& zone, TypeConstraint** res) {
if (IsAboutToBeFinalizedUnbarriered(&group))
return false;
*res = zone.typeLifoAlloc.new_<TypeConstraintClearDefiniteGetterSetter>(group);
return true;
}
JSCompartment* maybeCompartment() {
return group->compartment();
}
};
bool
js::AddClearDefiniteGetterSetterForPrototypeChain(JSContext* cx, ObjectGroup* group, HandleId id)
{
/*
* Ensure that if the properties named here could have a getter, setter or
* a permanent property in any transitive prototype, the definite
* properties get cleared from the group.
*/
RootedObject proto(cx, group->proto().toObjectOrNull());
while (proto) {
ObjectGroup* protoGroup = proto->getGroup(cx);
if (!protoGroup) {
cx->recoverFromOutOfMemory();
return false;
}
if (protoGroup->unknownProperties())
return false;
HeapTypeSet* protoTypes = protoGroup->getProperty(cx, proto, id);
if (!protoTypes || protoTypes->nonDataProperty() || protoTypes->nonWritableProperty())
return false;
if (!protoTypes->addConstraint(cx, cx->typeLifoAlloc().new_<TypeConstraintClearDefiniteGetterSetter>(group)))
return false;
proto = proto->staticPrototype();
}
return true;
}
/*
* Constraint which clears definite properties on a group should a type set
* contain any types other than a single object.
*/
class TypeConstraintClearDefiniteSingle : public TypeConstraint
{
public:
ObjectGroup* group;
explicit TypeConstraintClearDefiniteSingle(ObjectGroup* group)
: group(group)
{}
const char* kind() { return "clearDefiniteSingle"; }
void newType(JSContext* cx, TypeSet* source, TypeSet::Type type) {
if (source->baseFlags() || source->getObjectCount() > 1)
group->clearNewScript(cx);
}
bool sweep(TypeZone& zone, TypeConstraint** res) {
if (IsAboutToBeFinalizedUnbarriered(&group))
return false;
*res = zone.typeLifoAlloc.new_<TypeConstraintClearDefiniteSingle>(group);
return true;
}
JSCompartment* maybeCompartment() {
return group->compartment();
}
};
bool
js::AddClearDefiniteFunctionUsesInScript(JSContext* cx, ObjectGroup* group,
JSScript* script, JSScript* calleeScript)
{
// Look for any uses of the specified calleeScript in type sets for
// |script|, and add constraints to ensure that if the type sets' contents
// change then the definite properties are cleared from the type.
// This ensures that the inlining performed when the definite properties
// analysis was done is stable. We only need to look at type sets which
// contain a single object, as IonBuilder does not inline polymorphic sites
// during the definite properties analysis.
TypeSet::ObjectKey* calleeKey =
TypeSet::ObjectType(calleeScript->functionNonDelazifying()).objectKey();
unsigned count = TypeScript::NumTypeSets(script);
StackTypeSet* typeArray = script->types()->typeArray();
for (unsigned i = 0; i < count; i++) {
StackTypeSet* types = &typeArray[i];
if (!types->unknownObject() && types->getObjectCount() == 1) {
if (calleeKey != types->getObject(0)) {
// Also check if the object is the Function.call or
// Function.apply native. IonBuilder uses the presence of these
// functions during inlining.
JSObject* singleton = types->getSingleton(0);
if (!singleton || !singleton->is<JSFunction>())
continue;
JSFunction* fun = &singleton->as<JSFunction>();
if (!fun->isNative())
continue;
if (fun->native() != fun_call && fun->native() != fun_apply)
continue;
}
// This is a type set that might have been used when inlining
// |calleeScript| into |script|.
if (!types->addConstraint(cx, cx->typeLifoAlloc().new_<TypeConstraintClearDefiniteSingle>(group)))
return false;
}
}
return true;
}
/////////////////////////////////////////////////////////////////////
// Interface functions
/////////////////////////////////////////////////////////////////////
void
js::TypeMonitorCallSlow(JSContext* cx, JSObject* callee, const CallArgs& args, bool constructing)
{
unsigned nargs = callee->as<JSFunction>().nargs();
JSScript* script = callee->as<JSFunction>().nonLazyScript();
if (!constructing)
TypeScript::SetThis(cx, script, args.thisv());
/*
* Add constraints going up to the minimum of the actual and formal count.
* If there are more actuals than formals the later values can only be
* accessed through the arguments object, which is monitored.
*/
unsigned arg = 0;
for (; arg < args.length() && arg < nargs; arg++)
TypeScript::SetArgument(cx, script, arg, args[arg]);
/* Watch for fewer actuals than formals to the call. */
for (; arg < nargs; arg++)
TypeScript::SetArgument(cx, script, arg, UndefinedValue());
}
void
js::FillBytecodeTypeMap(JSScript* script, uint32_t* bytecodeMap)
{
uint32_t added = 0;
for (jsbytecode* pc = script->code(); pc < script->codeEnd(); pc += GetBytecodeLength(pc)) {
JSOp op = JSOp(*pc);
if (CodeSpec[op].format & JOF_TYPESET) {
bytecodeMap[added++] = script->pcToOffset(pc);
if (added == script->nTypeSets())
break;
}
}
MOZ_ASSERT(added == script->nTypeSets());
}
void
js::TypeMonitorResult(JSContext* cx, JSScript* script, jsbytecode* pc, TypeSet::Type type)
{
assertSameCompartment(cx, script, type);
AutoEnterAnalysis enter(cx);
StackTypeSet* types = TypeScript::BytecodeTypes(script, pc);
if (types->hasType(type))
return;
InferSpew(ISpewOps, "bytecodeType: %p %05" PRIuSIZE ": %s",
script, script->pcToOffset(pc), TypeSet::TypeString(type));
types->addType(cx, type);
}
void
js::TypeMonitorResult(JSContext* cx, JSScript* script, jsbytecode* pc, const js::Value& rval)
{
/* Allow the non-TYPESET scenario to simplify stubs used in compound opcodes. */
if (!(CodeSpec[*pc].format & JOF_TYPESET))
return;
if (!script->hasBaselineScript())
return;
TypeMonitorResult(cx, script, pc, TypeSet::GetValueType(rval));
}
/////////////////////////////////////////////////////////////////////
// TypeScript
/////////////////////////////////////////////////////////////////////
bool
JSScript::makeTypes(JSContext* cx)
{
MOZ_ASSERT(!types_);
AutoEnterAnalysis enter(cx);
unsigned count = TypeScript::NumTypeSets(this);
TypeScript* typeScript = (TypeScript*)
zone()->pod_calloc<uint8_t>(TypeScript::SizeIncludingTypeArray(count));
if (!typeScript) {
ReportOutOfMemory(cx);
return false;
}
types_ = typeScript;
setTypesGeneration(cx->zone()->types.generation);
#ifdef DEBUG
StackTypeSet* typeArray = typeScript->typeArray();
for (unsigned i = 0; i < nTypeSets(); i++) {
InferSpew(ISpewOps, "typeSet: %sT%p%s bytecode%u %p",
InferSpewColor(&typeArray[i]), &typeArray[i], InferSpewColorReset(),
i, this);
}
TypeSet* thisTypes = TypeScript::ThisTypes(this);
InferSpew(ISpewOps, "typeSet: %sT%p%s this %p",
InferSpewColor(thisTypes), thisTypes, InferSpewColorReset(),
this);
unsigned nargs = functionNonDelazifying() ? functionNonDelazifying()->nargs() : 0;
for (unsigned i = 0; i < nargs; i++) {
TypeSet* types = TypeScript::ArgTypes(this, i);
InferSpew(ISpewOps, "typeSet: %sT%p%s arg%u %p",
InferSpewColor(types), types, InferSpewColorReset(),
i, this);
}
#endif
return true;
}
/* static */ bool
JSFunction::setTypeForScriptedFunction(ExclusiveContext* cx, HandleFunction fun,
bool singleton /* = false */)
{
if (singleton) {
if (!setSingleton(cx, fun))
return false;
} else {
RootedObject funProto(cx, fun->staticPrototype());
Rooted<TaggedProto> taggedProto(cx, TaggedProto(funProto));
ObjectGroup* group = ObjectGroupCompartment::makeGroup(cx, &JSFunction::class_,
taggedProto);
if (!group)
return false;
fun->setGroup(group);
group->setInterpretedFunction(fun);
}
return true;
}
/////////////////////////////////////////////////////////////////////
// PreliminaryObjectArray
/////////////////////////////////////////////////////////////////////
void
PreliminaryObjectArray::registerNewObject(JSObject* res)
{
// The preliminary object pointers are weak, and won't be swept properly
// during nursery collections, so the preliminary objects need to be
// initially tenured.
MOZ_ASSERT(!IsInsideNursery(res));
for (size_t i = 0; i < COUNT; i++) {
if (!objects[i]) {
objects[i] = res;
return;
}
}
MOZ_CRASH("There should be room for registering the new object");
}
void
PreliminaryObjectArray::unregisterObject(JSObject* obj)
{
for (size_t i = 0; i < COUNT; i++) {
if (objects[i] == obj) {
objects[i] = nullptr;
return;
}
}
MOZ_CRASH("The object should be in the array");
}
bool
PreliminaryObjectArray::full() const
{
for (size_t i = 0; i < COUNT; i++) {
if (!objects[i])
return false;
}
return true;
}
bool
PreliminaryObjectArray::empty() const
{
for (size_t i = 0; i < COUNT; i++) {
if (objects[i])
return false;
}
return true;
}
void
PreliminaryObjectArray::sweep()
{
// All objects in the array are weak, so clear any that are about to be
// destroyed.
for (size_t i = 0; i < COUNT; i++) {
JSObject** ptr = &objects[i];
if (*ptr && IsAboutToBeFinalizedUnbarriered(ptr)) {
// Before we clear this reference, change the object's group to the
// Object.prototype group. This is done to ensure JSObject::finalize
// sees a NativeObject Class even if we change the current group's
// Class to one of the unboxed object classes in the meantime. If
// the compartment's global is dead, we don't do anything as the
// group's Class is not going to change in that case.
JSObject* obj = *ptr;
GlobalObject* global = obj->compartment()->unsafeUnbarrieredMaybeGlobal();
if (global && !obj->isSingleton()) {
JSObject* objectProto = GetBuiltinPrototypePure(global, JSProto_Object);
obj->setGroup(objectProto->groupRaw());
MOZ_ASSERT(obj->is<NativeObject>());
MOZ_ASSERT(obj->getClass() == objectProto->getClass());
MOZ_ASSERT(!obj->getClass()->hasFinalize());
}
*ptr = nullptr;
}
}
}
void
PreliminaryObjectArrayWithTemplate::trace(JSTracer* trc)
{
TraceNullableEdge(trc, &shape_, "PreliminaryObjectArrayWithTemplate_shape");
}
/* static */ void
PreliminaryObjectArrayWithTemplate::writeBarrierPre(PreliminaryObjectArrayWithTemplate* objects)
{
Shape* shape = objects->shape();
if (!shape)
return;
JS::Zone* zone = shape->zoneFromAnyThread();
if (zone->needsIncrementalBarrier())
objects->trace(zone->barrierTracer());
}
// Return whether shape consists entirely of plain data properties.
static bool
OnlyHasDataProperties(Shape* shape)
{
MOZ_ASSERT(!shape->inDictionary());
while (!shape->isEmptyShape()) {
if (!shape->isDataDescriptor() ||
!shape->configurable() ||
!shape->enumerable() ||
!shape->writable() ||
!shape->hasSlot())
{
return false;
}
shape = shape->previous();
}
return true;
}
// Find the most recent common ancestor of two shapes, or an empty shape if
// the two shapes have no common ancestor.
static Shape*
CommonPrefix(Shape* first, Shape* second)
{
MOZ_ASSERT(OnlyHasDataProperties(first));
MOZ_ASSERT(OnlyHasDataProperties(second));
while (first->slotSpan() > second->slotSpan())
first = first->previous();
while (second->slotSpan() > first->slotSpan())
second = second->previous();
while (first != second && !first->isEmptyShape()) {
first = first->previous();
second = second->previous();
}
return first;
}
void
PreliminaryObjectArrayWithTemplate::maybeAnalyze(ExclusiveContext* cx, ObjectGroup* group, bool force)
{
// Don't perform the analyses until sufficient preliminary objects have
// been allocated.
if (!force && !full())
return;
AutoEnterAnalysis enter(cx);
ScopedJSDeletePtr<PreliminaryObjectArrayWithTemplate> preliminaryObjects(this);
group->detachPreliminaryObjects();
if (shape()) {
MOZ_ASSERT(shape()->slotSpan() != 0);
MOZ_ASSERT(OnlyHasDataProperties(shape()));
// Make sure all the preliminary objects reflect the properties originally
// in the template object.
for (size_t i = 0; i < PreliminaryObjectArray::COUNT; i++) {
JSObject* objBase = preliminaryObjects->get(i);
if (!objBase)
continue;
PlainObject* obj = &objBase->as<PlainObject>();
if (obj->inDictionaryMode() || !OnlyHasDataProperties(obj->lastProperty()))
return;
if (CommonPrefix(obj->lastProperty(), shape()) != shape())
return;
}
}
TryConvertToUnboxedLayout(cx, enter, shape(), group, preliminaryObjects);
if (group->maybeUnboxedLayout())
return;
if (shape()) {
// We weren't able to use an unboxed layout, but since the preliminary
// objects still reflect the template object's properties, and all
// objects in the future will be created with those properties, the
// properties can be marked as definite for objects in the group.
group->addDefiniteProperties(cx, shape());
}
}
/////////////////////////////////////////////////////////////////////
// TypeNewScript
/////////////////////////////////////////////////////////////////////
// Make a TypeNewScript for |group|, and set it up to hold the preliminary
// objects created with the group.
/* static */ bool
TypeNewScript::make(JSContext* cx, ObjectGroup* group, JSFunction* fun)
{
MOZ_ASSERT(cx->zone()->types.activeAnalysis);
MOZ_ASSERT(!group->newScript());
MOZ_ASSERT(!group->maybeUnboxedLayout());
if (group->unknownProperties())
return true;
ScopedJSDeletePtr<TypeNewScript> newScript(cx->new_<TypeNewScript>());
if (!newScript)
return false;
newScript->function_ = fun;
newScript->preliminaryObjects = group->zone()->new_<PreliminaryObjectArray>();
if (!newScript->preliminaryObjects)
return true;
group->setNewScript(newScript.forget());
gc::TraceTypeNewScript(group);
return true;
}
// Make a TypeNewScript with the same initializer list as |newScript| but with
// a new template object.
/* static */ TypeNewScript*
TypeNewScript::makeNativeVersion(JSContext* cx, TypeNewScript* newScript,
PlainObject* templateObject)
{
MOZ_ASSERT(cx->zone()->types.activeAnalysis);
ScopedJSDeletePtr<TypeNewScript> nativeNewScript(cx->new_<TypeNewScript>());
if (!nativeNewScript)
return nullptr;
nativeNewScript->function_ = newScript->function();
nativeNewScript->templateObject_ = templateObject;
Initializer* cursor = newScript->initializerList;
while (cursor->kind != Initializer::DONE) { cursor++; }
size_t initializerLength = cursor - newScript->initializerList + 1;
nativeNewScript->initializerList = cx->zone()->pod_calloc<Initializer>(initializerLength);
if (!nativeNewScript->initializerList) {
ReportOutOfMemory(cx);
return nullptr;
}
PodCopy(nativeNewScript->initializerList, newScript->initializerList, initializerLength);
return nativeNewScript.forget();
}
size_t
TypeNewScript::sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const
{
size_t n = mallocSizeOf(this);
n += mallocSizeOf(preliminaryObjects);
n += mallocSizeOf(initializerList);
return n;
}
void
TypeNewScript::registerNewObject(PlainObject* res)
{
MOZ_ASSERT(!analyzed());
// New script objects must have the maximum number of fixed slots, so that
// we can adjust their shape later to match the number of fixed slots used
// by the template object we eventually create.
MOZ_ASSERT(res->numFixedSlots() == NativeObject::MAX_FIXED_SLOTS);
preliminaryObjects->registerNewObject(res);
}
static bool
ChangeObjectFixedSlotCount(JSContext* cx, PlainObject* obj, gc::AllocKind allocKind)
{
MOZ_ASSERT(OnlyHasDataProperties(obj->lastProperty()));
Shape* newShape = ReshapeForAllocKind(cx, obj->lastProperty(), obj->taggedProto(), allocKind);
if (!newShape)
return false;
obj->setLastPropertyShrinkFixedSlots(newShape);
return true;
}
namespace {
struct DestroyTypeNewScript
{
JSContext* cx;
ObjectGroup* group;
DestroyTypeNewScript(JSContext* cx, ObjectGroup* group)
: cx(cx), group(group)
{}
~DestroyTypeNewScript() {
if (group)
group->clearNewScript(cx);
}
};
} // namespace
bool
TypeNewScript::maybeAnalyze(JSContext* cx, ObjectGroup* group, bool* regenerate, bool force)
{
// Perform the new script properties analysis if necessary, returning
// whether the new group table was updated and group needs to be refreshed.
MOZ_ASSERT(this == group->newScript());
// Make sure there aren't dead references in preliminaryObjects. This can
// clear out the new script information on OOM.
group->maybeSweep(nullptr);
if (!group->newScript())
return true;
if (regenerate)
*regenerate = false;
if (analyzed()) {
// The analyses have already been performed.
return true;
}
// Don't perform the analyses until sufficient preliminary objects have
// been allocated.
if (!force && !preliminaryObjects->full())
return true;
AutoEnterAnalysis enter(cx);
// Any failures after this point will clear out this TypeNewScript.
DestroyTypeNewScript destroyNewScript(cx, group);
// Compute the greatest common shape prefix and the largest slot span of
// the preliminary objects.
Shape* prefixShape = nullptr;
size_t maxSlotSpan = 0;
for (size_t i = 0; i < PreliminaryObjectArray::COUNT; i++) {
JSObject* objBase = preliminaryObjects->get(i);
if (!objBase)
continue;
PlainObject* obj = &objBase->as<PlainObject>();
// For now, we require all preliminary objects to have only simple
// lineages of plain data properties.
Shape* shape = obj->lastProperty();
if (shape->inDictionary() ||
!OnlyHasDataProperties(shape) ||
shape->getObjectFlags() != 0)
{
return true;
}
maxSlotSpan = Max<size_t>(maxSlotSpan, obj->slotSpan());
if (prefixShape) {
MOZ_ASSERT(shape->numFixedSlots() == prefixShape->numFixedSlots());
prefixShape = CommonPrefix(prefixShape, shape);
} else {
prefixShape = shape;
}
if (prefixShape->isEmptyShape()) {
// The preliminary objects don't have any common properties.
return true;
}
}
if (!prefixShape)
return true;
gc::AllocKind kind = gc::GetGCObjectKind(maxSlotSpan);
if (kind != gc::GetGCObjectKind(NativeObject::MAX_FIXED_SLOTS)) {
// The template object will have a different allocation kind from the
// preliminary objects that have already been constructed. Optimizing
// definite property accesses requires both that the property is
// definitely in a particular slot and that the object has a specific
// number of fixed slots. So, adjust the shape and slot layout of all
// the preliminary objects so that their structure matches that of the
// template object. Also recompute the prefix shape, as it reflects the
// old number of fixed slots.
Shape* newPrefixShape = nullptr;
for (size_t i = 0; i < PreliminaryObjectArray::COUNT; i++) {
JSObject* objBase = preliminaryObjects->get(i);
if (!objBase)
continue;
PlainObject* obj = &objBase->as<PlainObject>();
if (!ChangeObjectFixedSlotCount(cx, obj, kind))
return false;
if (newPrefixShape) {
MOZ_ASSERT(CommonPrefix(obj->lastProperty(), newPrefixShape) == newPrefixShape);
} else {
newPrefixShape = obj->lastProperty();
while (newPrefixShape->slotSpan() > prefixShape->slotSpan())
newPrefixShape = newPrefixShape->previous();
}
}
prefixShape = newPrefixShape;
}
RootedObjectGroup groupRoot(cx, group);
templateObject_ = NewObjectWithGroup<PlainObject>(cx, groupRoot, kind, TenuredObject);
if (!templateObject_)
return false;
Vector<Initializer> initializerVector(cx);
RootedPlainObject templateRoot(cx, templateObject());
if (!jit::AnalyzeNewScriptDefiniteProperties(cx, function(), group, templateRoot, &initializerVector))
return false;
if (!group->newScript())
return true;
MOZ_ASSERT(OnlyHasDataProperties(templateObject()->lastProperty()));
if (templateObject()->slotSpan() != 0) {
// Make sure that all definite properties found are reflected in the
// prefix shape. Otherwise, the constructor behaved differently before
// we baseline compiled it and started observing types. Compare
// property names rather than looking at the shapes directly, as the
// allocation kind and other non-property parts of the template and
// existing objects may differ.
if (templateObject()->slotSpan() > prefixShape->slotSpan())
return true;
{
Shape* shape = prefixShape;
while (shape->slotSpan() != templateObject()->slotSpan())
shape = shape->previous();
Shape* templateShape = templateObject()->lastProperty();
while (!shape->isEmptyShape()) {
if (shape->slot() != templateShape->slot())
return true;
if (shape->propid() != templateShape->propid())
return true;
shape = shape->previous();
templateShape = templateShape->previous();
}
if (!templateShape->isEmptyShape())
return true;
}
Initializer done(Initializer::DONE, 0);
if (!initializerVector.append(done))
return false;
initializerList = group->zone()->pod_calloc<Initializer>(initializerVector.length());
if (!initializerList) {
ReportOutOfMemory(cx);
return false;
}
PodCopy(initializerList, initializerVector.begin(), initializerVector.length());
}
// Try to use an unboxed representation for the group.
if (!TryConvertToUnboxedLayout(cx, enter, templateObject()->lastProperty(), group, preliminaryObjects))
return false;
js_delete(preliminaryObjects);
preliminaryObjects = nullptr;
if (group->maybeUnboxedLayout()) {
// An unboxed layout was constructed for the group, and this has already
// been hooked into it.
MOZ_ASSERT(group->unboxedLayout().newScript() == this);
destroyNewScript.group = nullptr;
// Clear out the template object, which is not used for TypeNewScripts
// with an unboxed layout. Currently it is a mutant object with a
// non-native group and native shape, so make it safe for GC by changing
// its group to the default for its prototype.
AutoEnterOOMUnsafeRegion oomUnsafe;
ObjectGroup* plainGroup = ObjectGroup::defaultNewGroup(cx, &PlainObject::class_,
group->proto());
if (!plainGroup)
oomUnsafe.crash("TypeNewScript::maybeAnalyze");
templateObject_->setGroup(plainGroup);
templateObject_ = nullptr;
return true;
}
if (prefixShape->slotSpan() == templateObject()->slotSpan()) {
// The definite properties analysis found exactly the properties that
// are held in common by the preliminary objects. No further analysis
// is needed.
group->addDefiniteProperties(cx, templateObject()->lastProperty());
destroyNewScript.group = nullptr;
return true;
}
// There are more properties consistently added to objects of this group
// than were discovered by the definite properties analysis. Use the
// existing group to represent fully initialized objects with all
// definite properties in the prefix shape, and make a new group to
// represent partially initialized objects.
MOZ_ASSERT(prefixShape->slotSpan() > templateObject()->slotSpan());
ObjectGroupFlags initialFlags = group->flags() & OBJECT_FLAG_DYNAMIC_MASK;
Rooted<TaggedProto> protoRoot(cx, group->proto());
ObjectGroup* initialGroup = ObjectGroupCompartment::makeGroup(cx, group->clasp(), protoRoot,
initialFlags);
if (!initialGroup)
return false;
initialGroup->addDefiniteProperties(cx, templateObject()->lastProperty());
group->addDefiniteProperties(cx, prefixShape);
cx->compartment()->objectGroups.replaceDefaultNewGroup(nullptr, group->proto(), function(),
initialGroup);
templateObject()->setGroup(initialGroup);
// Transfer this TypeNewScript from the fully initialized group to the
// partially initialized group.
group->setNewScript(nullptr);
initialGroup->setNewScript(this);
initializedShape_ = prefixShape;
initializedGroup_ = group;
destroyNewScript.group = nullptr;
if (regenerate)
*regenerate = true;
return true;
}
bool
TypeNewScript::rollbackPartiallyInitializedObjects(JSContext* cx, ObjectGroup* group)
{
// If we cleared this new script while in the middle of initializing an
// object, it will still have the new script's shape and reflect the no
// longer correct state of the object once its initialization is completed.
// We can't detect the possibility of this statically while remaining
// robust, but the new script keeps track of where each property is
// initialized so we can walk the stack and fix up any such objects.
// Return whether any objects were modified.
if (!initializerList)
return false;
bool found = false;
RootedFunction function(cx, this->function());
Vector<uint32_t, 32> pcOffsets(cx);
for (ScriptFrameIter iter(cx); !iter.done(); ++iter) {
{
AutoEnterOOMUnsafeRegion oomUnsafe;
if (!pcOffsets.append(iter.script()->pcToOffset(iter.pc())))
oomUnsafe.crash("rollbackPartiallyInitializedObjects");
}
if (!iter.isConstructing() || !iter.matchCallee(cx, function))
continue;
// Derived class constructors initialize their this-binding later and
// we shouldn't run the definite properties analysis on them.
MOZ_ASSERT(!iter.script()->isDerivedClassConstructor());
Value thisv = iter.thisArgument(cx);
if (!thisv.isObject() ||
thisv.toObject().hasLazyGroup() ||
thisv.toObject().group() != group)
{
continue;
}
if (thisv.toObject().is<UnboxedPlainObject>()) {
AutoEnterOOMUnsafeRegion oomUnsafe;
if (!UnboxedPlainObject::convertToNative(cx, &thisv.toObject()))
oomUnsafe.crash("rollbackPartiallyInitializedObjects");
}
// Found a matching frame.
RootedPlainObject obj(cx, &thisv.toObject().as<PlainObject>());
// Whether all identified 'new' properties have been initialized.
bool finished = false;
// If not finished, number of properties that have been added.
uint32_t numProperties = 0;
// Whether the current SETPROP is within an inner frame which has
// finished entirely.
bool pastProperty = false;
// Index in pcOffsets of the outermost frame.
int callDepth = pcOffsets.length() - 1;
// Index in pcOffsets of the frame currently being checked for a SETPROP.
int setpropDepth = callDepth;
for (Initializer* init = initializerList;; init++) {
if (init->kind == Initializer::SETPROP) {
if (!pastProperty && pcOffsets[setpropDepth] < init->offset) {
// Have not yet reached this setprop.
break;
}
// This setprop has executed, reset state for the next one.
numProperties++;
pastProperty = false;
setpropDepth = callDepth;
} else if (init->kind == Initializer::SETPROP_FRAME) {
if (!pastProperty) {
if (pcOffsets[setpropDepth] < init->offset) {
// Have not yet reached this inner call.
break;
} else if (pcOffsets[setpropDepth] > init->offset) {
// Have advanced past this inner call.
pastProperty = true;
} else if (setpropDepth == 0) {
// Have reached this call but not yet in it.
break;
} else {
// Somewhere inside this inner call.
setpropDepth--;
}
}
} else {
MOZ_ASSERT(init->kind == Initializer::DONE);
finished = true;
break;
}
}
if (!finished) {
(void) NativeObject::rollbackProperties(cx, obj, numProperties);
found = true;
}
}
return found;
}
void
TypeNewScript::trace(JSTracer* trc)
{
TraceEdge(trc, &function_, "TypeNewScript_function");
TraceNullableEdge(trc, &templateObject_, "TypeNewScript_templateObject");
TraceNullableEdge(trc, &initializedShape_, "TypeNewScript_initializedShape");
TraceNullableEdge(trc, &initializedGroup_, "TypeNewScript_initializedGroup");
}
/* static */ void
TypeNewScript::writeBarrierPre(TypeNewScript* newScript)
{
if (newScript->function()->runtimeFromAnyThread()->isHeapCollecting())
return;
JS::Zone* zone = newScript->function()->zoneFromAnyThread();
if (zone->needsIncrementalBarrier())
newScript->trace(zone->barrierTracer());
}
void
TypeNewScript::sweep()
{
if (preliminaryObjects)
preliminaryObjects->sweep();
}
/////////////////////////////////////////////////////////////////////
// Tracing
/////////////////////////////////////////////////////////////////////
static inline void
TraceObjectKey(JSTracer* trc, TypeSet::ObjectKey** keyp)
{
TypeSet::ObjectKey* key = *keyp;
if (key->isGroup()) {
ObjectGroup* group = key->groupNoBarrier();
TraceManuallyBarrieredEdge(trc, &group, "objectKey_group");
*keyp = TypeSet::ObjectKey::get(group);
} else {
JSObject* singleton = key->singletonNoBarrier();
TraceManuallyBarrieredEdge(trc, &singleton, "objectKey_singleton");
*keyp = TypeSet::ObjectKey::get(singleton);
}
}
void
ConstraintTypeSet::trace(Zone* zone, JSTracer* trc)
{
// ConstraintTypeSets only hold strong references during minor collections.
MOZ_ASSERT(zone->runtimeFromMainThread()->isHeapMinorCollecting());
unsigned objectCount = baseObjectCount();
if (objectCount >= 2) {
unsigned oldCapacity = TypeHashSet::Capacity(objectCount);
ObjectKey** oldArray = objectSet;
clearObjects();
objectCount = 0;
for (unsigned i = 0; i < oldCapacity; i++) {
ObjectKey* key = oldArray[i];
if (!key)
continue;
TraceObjectKey(trc, &key);
AutoEnterOOMUnsafeRegion oomUnsafe;
ObjectKey** pentry =
TypeHashSet::Insert<ObjectKey*, ObjectKey, ObjectKey>
(zone->types.typeLifoAlloc, objectSet, objectCount, key);
if (!pentry)
oomUnsafe.crash("ConstraintTypeSet::trace");
*pentry = key;
}
setBaseObjectCount(objectCount);
} else if (objectCount == 1) {
ObjectKey* key = (ObjectKey*) objectSet;
TraceObjectKey(trc, &key);
objectSet = reinterpret_cast<ObjectKey**>(key);
}
}
static inline void
AssertGCStateForSweep(Zone* zone)
{
MOZ_ASSERT(zone->isGCSweepingOrCompacting());
// IsAboutToBeFinalized doesn't work right on tenured objects when called
// during a minor collection.
MOZ_ASSERT(!zone->runtimeFromMainThread()->isHeapMinorCollecting());
}
void
ConstraintTypeSet::sweep(Zone* zone, AutoClearTypeInferenceStateOnOOM& oom)
{
AssertGCStateForSweep(zone);
/*
* Purge references to objects that are no longer live. Type sets hold
* only weak references. For type sets containing more than one object,
* live entries in the object hash need to be copied to the zone's
* new arena.
*/
unsigned objectCount = baseObjectCount();
if (objectCount >= 2) {
unsigned oldCapacity = TypeHashSet::Capacity(objectCount);
ObjectKey** oldArray = objectSet;
clearObjects();
objectCount = 0;
for (unsigned i = 0; i < oldCapacity; i++) {
ObjectKey* key = oldArray[i];
if (!key)
continue;
if (!IsObjectKeyAboutToBeFinalized(&key)) {
ObjectKey** pentry =
TypeHashSet::Insert<ObjectKey*, ObjectKey, ObjectKey>
(zone->types.typeLifoAlloc, objectSet, objectCount, key);
if (pentry) {
*pentry = key;
} else {
oom.setOOM();
flags |= TYPE_FLAG_ANYOBJECT;
clearObjects();
objectCount = 0;
break;
}
} else if (key->isGroup() &&
key->groupNoBarrier()->unknownPropertiesDontCheckGeneration()) {
// Object sets containing objects with unknown properties might
// not be complete. Mark the type set as unknown, which it will
// be treated as during Ion compilation.
//
// Note that we don't have to do this when the type set might
// be missing the native group corresponding to an unboxed
// object group. In this case, the native group points to the
// unboxed object group via its addendum, so as long as objects
// with either group exist, neither group will be finalized.
flags |= TYPE_FLAG_ANYOBJECT;
clearObjects();
objectCount = 0;
break;
}
}
setBaseObjectCount(objectCount);
} else if (objectCount == 1) {
ObjectKey* key = (ObjectKey*) objectSet;
if (!IsObjectKeyAboutToBeFinalized(&key)) {
objectSet = reinterpret_cast<ObjectKey**>(key);
} else {
// As above, mark type sets containing objects with unknown
// properties as unknown.
if (key->isGroup() && key->groupNoBarrier()->unknownPropertiesDontCheckGeneration())
flags |= TYPE_FLAG_ANYOBJECT;
objectSet = nullptr;
setBaseObjectCount(0);
}
}
/*
* Type constraints only hold weak references. Copy constraints referring
* to data that is still live into the zone's new arena.
*/
TypeConstraint* constraint = constraintList;
constraintList = nullptr;
while (constraint) {
MOZ_ASSERT(zone->types.sweepTypeLifoAlloc.contains(constraint));
TypeConstraint* copy;
if (constraint->sweep(zone->types, ©)) {
if (copy) {
MOZ_ASSERT(zone->types.typeLifoAlloc.contains(copy));
copy->next = constraintList;
constraintList = copy;
} else {
oom.setOOM();
}
}
constraint = constraint->next;
}
}
inline void
ObjectGroup::clearProperties()
{
setBasePropertyCount(0);
propertySet = nullptr;
}
static void
EnsureHasAutoClearTypeInferenceStateOnOOM(AutoClearTypeInferenceStateOnOOM*& oom, Zone* zone,
Maybe<AutoClearTypeInferenceStateOnOOM>& fallback)
{
if (!oom) {
if (zone->types.activeAnalysis) {
oom = &zone->types.activeAnalysis->oom;
} else {
fallback.emplace(zone);
oom = &fallback.ref();
}
}
}
/*
* Before sweeping the arenas themselves, scan all groups in a compartment to
* fixup weak references: property type sets referencing dead JS and type
* objects, and singleton JS objects whose type is not referenced elsewhere.
* This is done either incrementally as part of the sweep, or on demand as type
* objects are accessed before their contents have been swept.
*/
void
ObjectGroup::sweep(AutoClearTypeInferenceStateOnOOM* oom)
{
MOZ_ASSERT(generation() != zoneFromAnyThread()->types.generation);
setGeneration(zone()->types.generation);
AssertGCStateForSweep(zone());
Maybe<AutoClearTypeInferenceStateOnOOM> fallbackOOM;
EnsureHasAutoClearTypeInferenceStateOnOOM(oom, zone(), fallbackOOM);
if (maybeUnboxedLayout()) {
// Remove unboxed layouts that are about to be finalized from the
// compartment wide list while we are still on the main thread.
ObjectGroup* group = this;
if (IsAboutToBeFinalizedUnbarriered(&group))
unboxedLayout().detachFromCompartment();
if (unboxedLayout().newScript())
unboxedLayout().newScript()->sweep();
// Discard constructor code to avoid holding onto ExecutablePools.
if (zone()->isGCCompacting())
unboxedLayout().setConstructorCode(nullptr);
}
if (maybePreliminaryObjects())
maybePreliminaryObjects()->sweep();
if (newScript())
newScript()->sweep();
LifoAlloc& typeLifoAlloc = zone()->types.typeLifoAlloc;
/*
* Properties were allocated from the old arena, and need to be copied over
* to the new one.
*/
unsigned propertyCount = basePropertyCount();
if (propertyCount >= 2) {
unsigned oldCapacity = TypeHashSet::Capacity(propertyCount);
Property** oldArray = propertySet;
clearProperties();
propertyCount = 0;
for (unsigned i = 0; i < oldCapacity; i++) {
Property* prop = oldArray[i];
if (prop) {
if (singleton() && !prop->types.constraintList && !zone()->isPreservingCode()) {
/*
* Don't copy over properties of singleton objects when their
* presence will not be required by jitcode or type constraints
* (i.e. for the definite properties analysis). The contents of
* these type sets will be regenerated as necessary.
*/
continue;
}
Property* newProp = typeLifoAlloc.new_<Property>(*prop);
if (newProp) {
Property** pentry = TypeHashSet::Insert<jsid, Property, Property>
(typeLifoAlloc, propertySet, propertyCount, prop->id);
if (pentry) {
*pentry = newProp;
newProp->types.sweep(zone(), *oom);
continue;
}
}
oom->setOOM();
addFlags(OBJECT_FLAG_DYNAMIC_MASK | OBJECT_FLAG_UNKNOWN_PROPERTIES);
clearProperties();
return;
}
}
setBasePropertyCount(propertyCount);
} else if (propertyCount == 1) {
Property* prop = (Property*) propertySet;
if (singleton() && !prop->types.constraintList && !zone()->isPreservingCode()) {
// Skip, as above.
clearProperties();
} else {
Property* newProp = typeLifoAlloc.new_<Property>(*prop);
if (newProp) {
propertySet = (Property**) newProp;
newProp->types.sweep(zone(), *oom);
} else {
oom->setOOM();
addFlags(OBJECT_FLAG_DYNAMIC_MASK | OBJECT_FLAG_UNKNOWN_PROPERTIES);
clearProperties();
return;
}
}
}
}
/* static */ void
JSScript::maybeSweepTypes(AutoClearTypeInferenceStateOnOOM* oom)
{
if (!types_ || typesGeneration() == zone()->types.generation)
return;
setTypesGeneration(zone()->types.generation);
AssertGCStateForSweep(zone());
Maybe<AutoClearTypeInferenceStateOnOOM> fallbackOOM;
EnsureHasAutoClearTypeInferenceStateOnOOM(oom, zone(), fallbackOOM);
TypeZone& types = zone()->types;
// Destroy all type information attached to the script if desired. We can
// only do this if nothing has been compiled for the script, which will be
// the case unless the script has been compiled since we started sweeping.
if (types.sweepReleaseTypes &&
!hasBaselineScript() &&
!hasIonScript())
{
types_->destroy();
types_ = nullptr;
// Freeze constraints on stack type sets need to be regenerated the
// next time the script is analyzed.
hasFreezeConstraints_ = false;
return;
}
unsigned num = TypeScript::NumTypeSets(this);
StackTypeSet* typeArray = types_->typeArray();
// Remove constraints and references to dead objects from stack type sets.
for (unsigned i = 0; i < num; i++)
typeArray[i].sweep(zone(), *oom);
if (oom->hadOOM()) {
// It's possible we OOM'd while copying freeze constraints, so they
// need to be regenerated.
hasFreezeConstraints_ = false;
}
// Update the recompile indexes in any IonScripts still on the script.
if (hasIonScript())
ionScript()->recompileInfoRef().shouldSweep(types);
}
void
TypeScript::destroy()
{
js_free(this);
}
void
Zone::addSizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf,
size_t* typePool,
size_t* baselineStubsOptimized,
size_t* uniqueIdMap,
size_t* shapeTables)
{
*typePool += types.typeLifoAlloc.sizeOfExcludingThis(mallocSizeOf);
if (jitZone()) {
*baselineStubsOptimized +=
jitZone()->optimizedStubSpace()->sizeOfExcludingThis(mallocSizeOf);
}
*uniqueIdMap += uniqueIds_.sizeOfExcludingThis(mallocSizeOf);
*shapeTables += baseShapes.sizeOfExcludingThis(mallocSizeOf)
+ initialShapes.sizeOfExcludingThis(mallocSizeOf);
}
TypeZone::TypeZone(Zone* zone)
: zone_(zone),
typeLifoAlloc(TYPE_LIFO_ALLOC_PRIMARY_CHUNK_SIZE),
generation(0),
compilerOutputs(nullptr),
sweepTypeLifoAlloc(TYPE_LIFO_ALLOC_PRIMARY_CHUNK_SIZE),
sweepCompilerOutputs(nullptr),
sweepReleaseTypes(false),
activeAnalysis(nullptr)
{
}
TypeZone::~TypeZone()
{
js_delete(compilerOutputs);
js_delete(sweepCompilerOutputs);
}
void
TypeZone::beginSweep(FreeOp* fop, bool releaseTypes, AutoClearTypeInferenceStateOnOOM& oom)
{
MOZ_ASSERT(zone()->isGCSweepingOrCompacting());
MOZ_ASSERT(!sweepCompilerOutputs);
MOZ_ASSERT(!sweepReleaseTypes);
sweepReleaseTypes = releaseTypes;
// Clear the analysis pool, but don't release its data yet. While sweeping
// types any live data will be allocated into the pool.
sweepTypeLifoAlloc.steal(&typeLifoAlloc);
// Sweep any invalid or dead compiler outputs, and keep track of the new
// index for remaining live outputs.
if (compilerOutputs) {
CompilerOutputVector* newCompilerOutputs = nullptr;
for (size_t i = 0; i < compilerOutputs->length(); i++) {
CompilerOutput& output = (*compilerOutputs)[i];
if (output.isValid()) {
JSScript* script = output.script();
if (IsAboutToBeFinalizedUnbarriered(&script)) {
if (script->hasIonScript())
script->ionScript()->recompileInfoRef() = RecompileInfo();
output.invalidate();
} else {
CompilerOutput newOutput(script);
if (!newCompilerOutputs)
newCompilerOutputs = js_new<CompilerOutputVector>();
if (newCompilerOutputs && newCompilerOutputs->append(newOutput)) {
output.setSweepIndex(newCompilerOutputs->length() - 1);
} else {
oom.setOOM();
script->ionScript()->recompileInfoRef() = RecompileInfo();
output.invalidate();
}
}
}
}
sweepCompilerOutputs = compilerOutputs;
compilerOutputs = newCompilerOutputs;
}
// All existing RecompileInfos are stale and will be updated to the new
// compiler outputs list later during the sweep. Don't worry about overflow
// here, since stale indexes will persist only until the sweep finishes.
generation++;
}
void
TypeZone::endSweep(JSRuntime* rt)
{
js_delete(sweepCompilerOutputs);
sweepCompilerOutputs = nullptr;
sweepReleaseTypes = false;
rt->gc.freeAllLifoBlocksAfterSweeping(&sweepTypeLifoAlloc);
}
void
TypeZone::clearAllNewScriptsOnOOM()
{
for (auto iter = zone()->cellIter<ObjectGroup>(); !iter.done(); iter.next()) {
ObjectGroup* group = iter;
if (!IsAboutToBeFinalizedUnbarriered(&group))
group->maybeClearNewScriptOnOOM();
}
}
AutoClearTypeInferenceStateOnOOM::~AutoClearTypeInferenceStateOnOOM()
{
if (oom) {
JSRuntime* rt = zone->runtimeFromMainThread();
js::CancelOffThreadIonCompile(rt);
zone->setPreservingCode(false);
zone->discardJitCode(rt->defaultFreeOp(), /* discardBaselineCode = */ false);
zone->types.clearAllNewScriptsOnOOM();
}
}
#ifdef DEBUG
void
TypeScript::printTypes(JSContext* cx, HandleScript script) const
{
MOZ_ASSERT(script->types() == this);
if (!script->hasBaselineScript())
return;
AutoEnterAnalysis enter(nullptr, script->zone());
if (script->functionNonDelazifying())
fprintf(stderr, "Function");
else if (script->isForEval())
fprintf(stderr, "Eval");
else
fprintf(stderr, "Main");
fprintf(stderr, " %#" PRIxPTR " %s:%" PRIuSIZE " ",
uintptr_t(script.get()), script->filename(), script->lineno());
if (script->functionNonDelazifying()) {
if (JSAtom* name = script->functionNonDelazifying()->explicitName())
name->dumpCharsNoNewline();
}
fprintf(stderr, "\n this:");
TypeScript::ThisTypes(script)->print();
for (unsigned i = 0;
script->functionNonDelazifying() && i < script->functionNonDelazifying()->nargs();
i++)
{
fprintf(stderr, "\n arg%u:", i);
TypeScript::ArgTypes(script, i)->print();
}
fprintf(stderr, "\n");
for (jsbytecode* pc = script->code(); pc < script->codeEnd(); pc += GetBytecodeLength(pc)) {
{
fprintf(stderr, "%p:", script.get());
Sprinter sprinter(cx);
if (!sprinter.init())
return;
Disassemble1(cx, script, pc, script->pcToOffset(pc), true, &sprinter);
fprintf(stderr, "%s", sprinter.string());
}
if (CodeSpec[*pc].format & JOF_TYPESET) {
StackTypeSet* types = TypeScript::BytecodeTypes(script, pc);
fprintf(stderr, " typeset %u:", unsigned(types - typeArray()));
types->print();
fprintf(stderr, "\n");
}
}
fprintf(stderr, "\n");
}
#endif /* DEBUG */
JS::ubi::Node::Size
JS::ubi::Concrete<js::ObjectGroup>::size(mozilla::MallocSizeOf mallocSizeOf) const
{
Size size = js::gc::Arena::thingSize(get().asTenured().getAllocKind());
size += get().sizeOfExcludingThis(mallocSizeOf);
return size;
}
|