summaryrefslogtreecommitdiffstats
path: root/js/src/jit/CacheIR.cpp
blob: 68163e7d6cf1723b0ede3d1d9fb79f0455950f18 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
 * vim: set ts=8 sts=2 et sw=2 tw=80:
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "jit/CacheIR.h"

#include "mozilla/DebugOnly.h"
#include "mozilla/FloatingPoint.h"

#include "jsapi.h"
#include "jsmath.h"

#include "builtin/DataViewObject.h"
#include "builtin/MapObject.h"
#include "builtin/ModuleObject.h"
#include "builtin/Object.h"
#include "jit/BaselineIC.h"
#include "jit/CacheIRCloner.h"
#include "jit/CacheIRCompiler.h"
#include "jit/CacheIRGenerator.h"
#include "jit/CacheIRSpewer.h"
#include "jit/CacheIRWriter.h"
#include "jit/InlinableNatives.h"
#include "jit/JitContext.h"
#include "jit/JitRealm.h"
#include "js/experimental/JitInfo.h"  // JSJitInfo
#include "js/friend/DOMProxy.h"       // JS::ExpandoAndGeneration
#include "js/friend/WindowProxy.h"  // js::IsWindow, js::IsWindowProxy, js::ToWindowIfWindowProxy
#include "js/friend/XrayJitInfo.h"  // js::jit::GetXrayJitInfo, JS::XrayJitInfo
#include "js/GCAPI.h"               // JS::AutoSuppressGCAnalysis
#include "js/RegExpFlags.h"         // JS::RegExpFlags
#include "js/ScalarType.h"          // js::Scalar::Type
#include "js/Wrapper.h"
#include "proxy/DOMProxy.h"  // js::GetDOMProxyHandlerFamily
#include "util/DifferentialTesting.h"
#include "util/Unicode.h"
#include "vm/ArrayBufferObject.h"
#include "vm/BoundFunctionObject.h"
#include "vm/BytecodeUtil.h"
#include "vm/Compartment.h"
#include "vm/Iteration.h"
#include "vm/PlainObject.h"  // js::PlainObject
#include "vm/ProxyObject.h"
#include "vm/RegExpObject.h"
#include "vm/SelfHosting.h"
#include "vm/ThrowMsgKind.h"  // ThrowCondition
#include "vm/Watchtower.h"
#include "wasm/WasmInstance.h"

#include "jit/BaselineFrame-inl.h"
#include "jit/MacroAssembler-inl.h"
#include "vm/ArrayBufferObject-inl.h"
#include "vm/BytecodeUtil-inl.h"
#include "vm/EnvironmentObject-inl.h"
#include "vm/JSContext-inl.h"
#include "vm/JSFunction-inl.h"
#include "vm/JSObject-inl.h"
#include "vm/JSScript-inl.h"
#include "vm/NativeObject-inl.h"
#include "vm/PlainObject-inl.h"
#include "vm/StringObject-inl.h"
#include "wasm/WasmInstance-inl.h"

using namespace js;
using namespace js::jit;

using mozilla::DebugOnly;
using mozilla::Maybe;

using JS::DOMProxyShadowsResult;
using JS::ExpandoAndGeneration;

const char* const js::jit::CacheKindNames[] = {
#define DEFINE_KIND(kind) #kind,
    CACHE_IR_KINDS(DEFINE_KIND)
#undef DEFINE_KIND
};

const char* const js::jit::CacheIROpNames[] = {
#define OPNAME(op, ...) #op,
    CACHE_IR_OPS(OPNAME)
#undef OPNAME
};

const CacheIROpInfo js::jit::CacheIROpInfos[] = {
#define OPINFO(op, len, transpile, ...) {len, transpile},
    CACHE_IR_OPS(OPINFO)
#undef OPINFO
};

const uint32_t js::jit::CacheIROpHealth[] = {
#define OPHEALTH(op, len, transpile, health) health,
    CACHE_IR_OPS(OPHEALTH)
#undef OPHEALTH
};

size_t js::jit::NumInputsForCacheKind(CacheKind kind) {
  switch (kind) {
    case CacheKind::NewArray:
    case CacheKind::NewObject:
    case CacheKind::GetIntrinsic:
      return 0;
    case CacheKind::GetProp:
    case CacheKind::TypeOf:
    case CacheKind::ToPropertyKey:
    case CacheKind::GetIterator:
    case CacheKind::ToBool:
    case CacheKind::UnaryArith:
    case CacheKind::GetName:
    case CacheKind::BindName:
    case CacheKind::Call:
    case CacheKind::OptimizeSpreadCall:
    case CacheKind::CloseIter:
      return 1;
    case CacheKind::Compare:
    case CacheKind::GetElem:
    case CacheKind::GetPropSuper:
    case CacheKind::SetProp:
    case CacheKind::In:
    case CacheKind::HasOwn:
    case CacheKind::CheckPrivateField:
    case CacheKind::InstanceOf:
    case CacheKind::BinaryArith:
      return 2;
    case CacheKind::GetElemSuper:
    case CacheKind::SetElem:
      return 3;
  }
  MOZ_CRASH("Invalid kind");
}

#ifdef DEBUG
void CacheIRWriter::assertSameCompartment(JSObject* obj) {
  cx_->debugOnlyCheck(obj);
}
void CacheIRWriter::assertSameZone(Shape* shape) {
  MOZ_ASSERT(cx_->zone() == shape->zone());
}
#endif

StubField CacheIRWriter::readStubField(uint32_t offset,
                                       StubField::Type type) const {
  size_t index = 0;
  size_t currentOffset = 0;

  // If we've seen an offset earlier than this before, we know we can start the
  // search there at least, otherwise, we start the search from the beginning.
  if (lastOffset_ < offset) {
    currentOffset = lastOffset_;
    index = lastIndex_;
  }

  while (currentOffset != offset) {
    currentOffset += StubField::sizeInBytes(stubFields_[index].type());
    index++;
    MOZ_ASSERT(index < stubFields_.length());
  }

  MOZ_ASSERT(stubFields_[index].type() == type);

  lastOffset_ = currentOffset;
  lastIndex_ = index;

  return stubFields_[index];
}

CacheIRCloner::CacheIRCloner(ICCacheIRStub* stub)
    : stubInfo_(stub->stubInfo()), stubData_(stub->stubDataStart()) {}

void CacheIRCloner::cloneOp(CacheOp op, CacheIRReader& reader,
                            CacheIRWriter& writer) {
  switch (op) {
#define DEFINE_OP(op, ...)     \
  case CacheOp::op:            \
    clone##op(reader, writer); \
    break;
    CACHE_IR_OPS(DEFINE_OP)
#undef DEFINE_OP
    default:
      MOZ_CRASH("Invalid op");
  }
}

uintptr_t CacheIRCloner::readStubWord(uint32_t offset) {
  return stubInfo_->getStubRawWord(stubData_, offset);
}
int64_t CacheIRCloner::readStubInt64(uint32_t offset) {
  return stubInfo_->getStubRawInt64(stubData_, offset);
}

Shape* CacheIRCloner::getShapeField(uint32_t stubOffset) {
  return reinterpret_cast<Shape*>(readStubWord(stubOffset));
}
GetterSetter* CacheIRCloner::getGetterSetterField(uint32_t stubOffset) {
  return reinterpret_cast<GetterSetter*>(readStubWord(stubOffset));
}
JSObject* CacheIRCloner::getObjectField(uint32_t stubOffset) {
  return reinterpret_cast<JSObject*>(readStubWord(stubOffset));
}
JSString* CacheIRCloner::getStringField(uint32_t stubOffset) {
  return reinterpret_cast<JSString*>(readStubWord(stubOffset));
}
JSAtom* CacheIRCloner::getAtomField(uint32_t stubOffset) {
  return reinterpret_cast<JSAtom*>(readStubWord(stubOffset));
}
JS::Symbol* CacheIRCloner::getSymbolField(uint32_t stubOffset) {
  return reinterpret_cast<JS::Symbol*>(readStubWord(stubOffset));
}
BaseScript* CacheIRCloner::getBaseScriptField(uint32_t stubOffset) {
  return reinterpret_cast<BaseScript*>(readStubWord(stubOffset));
}
JitCode* CacheIRCloner::getJitCodeField(uint32_t stubOffset) {
  return reinterpret_cast<JitCode*>(readStubWord(stubOffset));
}
uint32_t CacheIRCloner::getRawInt32Field(uint32_t stubOffset) {
  return uint32_t(reinterpret_cast<uintptr_t>(readStubWord(stubOffset)));
}
const void* CacheIRCloner::getRawPointerField(uint32_t stubOffset) {
  return reinterpret_cast<const void*>(readStubWord(stubOffset));
}
uint64_t CacheIRCloner::getRawInt64Field(uint32_t stubOffset) {
  return static_cast<uint64_t>(readStubInt64(stubOffset));
}
gc::AllocSite* CacheIRCloner::getAllocSiteField(uint32_t stubOffset) {
  return reinterpret_cast<gc::AllocSite*>(readStubWord(stubOffset));
}

jsid CacheIRCloner::getIdField(uint32_t stubOffset) {
  return jsid::fromRawBits(readStubWord(stubOffset));
}
const Value CacheIRCloner::getValueField(uint32_t stubOffset) {
  return Value::fromRawBits(uint64_t(readStubInt64(stubOffset)));
}
double CacheIRCloner::getDoubleField(uint32_t stubOffset) {
  uint64_t bits = uint64_t(readStubInt64(stubOffset));
  return mozilla::BitwiseCast<double>(bits);
}

IRGenerator::IRGenerator(JSContext* cx, HandleScript script, jsbytecode* pc,
                         CacheKind cacheKind, ICState state)
    : writer(cx),
      cx_(cx),
      script_(script),
      pc_(pc),
      cacheKind_(cacheKind),
      mode_(state.mode()),
      isFirstStub_(state.newStubIsFirstStub()) {}

GetPropIRGenerator::GetPropIRGenerator(JSContext* cx, HandleScript script,
                                       jsbytecode* pc, ICState state,
                                       CacheKind cacheKind, HandleValue val,
                                       HandleValue idVal)
    : IRGenerator(cx, script, pc, cacheKind, state), val_(val), idVal_(idVal) {}

static void EmitLoadSlotResult(CacheIRWriter& writer, ObjOperandId holderId,
                               NativeObject* holder, PropertyInfo prop) {
  if (holder->isFixedSlot(prop.slot())) {
    writer.loadFixedSlotResult(holderId,
                               NativeObject::getFixedSlotOffset(prop.slot()));
  } else {
    size_t dynamicSlotOffset =
        holder->dynamicSlotIndex(prop.slot()) * sizeof(Value);
    writer.loadDynamicSlotResult(holderId, dynamicSlotOffset);
  }
}

// DOM proxies
// -----------
//
// DOM proxies are proxies that are used to implement various DOM objects like
// HTMLDocument and NodeList. DOM proxies may have an expando object - a native
// object that stores extra properties added to the object. The following
// CacheIR instructions are only used with DOM proxies:
//
// * LoadDOMExpandoValue: returns the Value in the proxy's expando slot. This
//   returns either an UndefinedValue (no expando), ObjectValue (the expando
//   object), or PrivateValue(ExpandoAndGeneration*).
//
// * LoadDOMExpandoValueGuardGeneration: guards the Value in the proxy's expando
//   slot is the same PrivateValue(ExpandoAndGeneration*), then guards on its
//   generation, then returns expandoAndGeneration->expando. This Value is
//   either an UndefinedValue or ObjectValue.
//
// * LoadDOMExpandoValueIgnoreGeneration: assumes the Value in the proxy's
//   expando slot is a PrivateValue(ExpandoAndGeneration*), unboxes it, and
//   returns the expandoAndGeneration->expando Value.
//
// * GuardDOMExpandoMissingOrGuardShape: takes an expando Value as input, then
//   guards it's either UndefinedValue or an object with the expected shape.

enum class ProxyStubType {
  None,
  DOMExpando,
  DOMShadowed,
  DOMUnshadowed,
  Generic
};

static bool IsCacheableDOMProxy(ProxyObject* obj) {
  const BaseProxyHandler* handler = obj->handler();
  if (handler->family() != GetDOMProxyHandlerFamily()) {
    return false;
  }

  // Some DOM proxies have dynamic prototypes.  We can't really cache those very
  // well.
  return obj->hasStaticPrototype();
}

static ProxyStubType GetProxyStubType(JSContext* cx, HandleObject obj,
                                      HandleId id) {
  if (!obj->is<ProxyObject>()) {
    return ProxyStubType::None;
  }
  auto proxy = obj.as<ProxyObject>();

  if (!IsCacheableDOMProxy(proxy)) {
    return ProxyStubType::Generic;
  }

  DOMProxyShadowsResult shadows = GetDOMProxyShadowsCheck()(cx, proxy, id);
  if (shadows == DOMProxyShadowsResult::ShadowCheckFailed) {
    cx->clearPendingException();
    return ProxyStubType::None;
  }

  if (DOMProxyIsShadowing(shadows)) {
    if (shadows == DOMProxyShadowsResult::ShadowsViaDirectExpando ||
        shadows == DOMProxyShadowsResult::ShadowsViaIndirectExpando) {
      return ProxyStubType::DOMExpando;
    }
    return ProxyStubType::DOMShadowed;
  }

  MOZ_ASSERT(shadows == DOMProxyShadowsResult::DoesntShadow ||
             shadows == DOMProxyShadowsResult::DoesntShadowUnique);
  return ProxyStubType::DOMUnshadowed;
}

static bool ValueToNameOrSymbolId(JSContext* cx, HandleValue idVal,
                                  MutableHandleId id, bool* nameOrSymbol) {
  *nameOrSymbol = false;

  if (!idVal.isString() && !idVal.isSymbol() && !idVal.isUndefined() &&
      !idVal.isNull()) {
    return true;
  }

  if (!PrimitiveValueToId<CanGC>(cx, idVal, id)) {
    return false;
  }

  if (!id.isAtom() && !id.isSymbol()) {
    id.set(JS::PropertyKey::Void());
    return true;
  }

  if (id.isAtom() && id.toAtom()->isIndex()) {
    id.set(JS::PropertyKey::Void());
    return true;
  }

  *nameOrSymbol = true;
  return true;
}

AttachDecision GetPropIRGenerator::tryAttachStub() {
  AutoAssertNoPendingException aanpe(cx_);

  ValOperandId valId(writer.setInputOperandId(0));
  if (cacheKind_ != CacheKind::GetProp) {
    MOZ_ASSERT_IF(cacheKind_ == CacheKind::GetPropSuper,
                  getSuperReceiverValueId().id() == 1);
    MOZ_ASSERT_IF(cacheKind_ != CacheKind::GetPropSuper,
                  getElemKeyValueId().id() == 1);
    writer.setInputOperandId(1);
  }
  if (cacheKind_ == CacheKind::GetElemSuper) {
    MOZ_ASSERT(getSuperReceiverValueId().id() == 2);
    writer.setInputOperandId(2);
  }

  RootedId id(cx_);
  bool nameOrSymbol;
  if (!ValueToNameOrSymbolId(cx_, idVal_, &id, &nameOrSymbol)) {
    cx_->clearPendingException();
    return AttachDecision::NoAction;
  }

  // |super.prop| getter calls use a |this| value that differs from lookup
  // object.
  ValOperandId receiverId = isSuper() ? getSuperReceiverValueId() : valId;

  if (val_.isObject()) {
    RootedObject obj(cx_, &val_.toObject());
    ObjOperandId objId = writer.guardToObject(valId);
    if (nameOrSymbol) {
      TRY_ATTACH(tryAttachObjectLength(obj, objId, id));
      TRY_ATTACH(tryAttachTypedArray(obj, objId, id));
      TRY_ATTACH(tryAttachDataView(obj, objId, id));
      TRY_ATTACH(tryAttachArrayBufferMaybeShared(obj, objId, id));
      TRY_ATTACH(tryAttachRegExp(obj, objId, id));
      TRY_ATTACH(tryAttachMap(obj, objId, id));
      TRY_ATTACH(tryAttachSet(obj, objId, id));
      TRY_ATTACH(tryAttachNative(obj, objId, id, receiverId));
      TRY_ATTACH(tryAttachModuleNamespace(obj, objId, id));
      TRY_ATTACH(tryAttachWindowProxy(obj, objId, id));
      TRY_ATTACH(tryAttachCrossCompartmentWrapper(obj, objId, id));
      TRY_ATTACH(
          tryAttachXrayCrossCompartmentWrapper(obj, objId, id, receiverId));
      TRY_ATTACH(tryAttachFunction(obj, objId, id));
      TRY_ATTACH(tryAttachArgumentsObjectIterator(obj, objId, id));
      TRY_ATTACH(tryAttachArgumentsObjectCallee(obj, objId, id));
      TRY_ATTACH(tryAttachProxy(obj, objId, id, receiverId));

      trackAttached(IRGenerator::NotAttached);
      return AttachDecision::NoAction;
    }

    MOZ_ASSERT(cacheKind_ == CacheKind::GetElem ||
               cacheKind_ == CacheKind::GetElemSuper);

    TRY_ATTACH(tryAttachProxyElement(obj, objId));
    TRY_ATTACH(tryAttachTypedArrayElement(obj, objId));

    uint32_t index;
    Int32OperandId indexId;
    if (maybeGuardInt32Index(idVal_, getElemKeyValueId(), &index, &indexId)) {
      TRY_ATTACH(tryAttachDenseElement(obj, objId, index, indexId));
      TRY_ATTACH(tryAttachDenseElementHole(obj, objId, index, indexId));
      TRY_ATTACH(tryAttachSparseElement(obj, objId, index, indexId));
      TRY_ATTACH(tryAttachArgumentsObjectArg(obj, objId, index, indexId));
      TRY_ATTACH(tryAttachArgumentsObjectArgHole(obj, objId, index, indexId));
      TRY_ATTACH(
          tryAttachGenericElement(obj, objId, index, indexId, receiverId));

      trackAttached(IRGenerator::NotAttached);
      return AttachDecision::NoAction;
    }

    trackAttached(IRGenerator::NotAttached);
    return AttachDecision::NoAction;
  }

  if (nameOrSymbol) {
    TRY_ATTACH(tryAttachPrimitive(valId, id));
    TRY_ATTACH(tryAttachStringLength(valId, id));

    trackAttached(IRGenerator::NotAttached);
    return AttachDecision::NoAction;
  }

  if (idVal_.isInt32()) {
    ValOperandId indexId = getElemKeyValueId();
    TRY_ATTACH(tryAttachStringChar(valId, indexId));

    trackAttached(IRGenerator::NotAttached);
    return AttachDecision::NoAction;
  }

  trackAttached(IRGenerator::NotAttached);
  return AttachDecision::NoAction;
}

#ifdef DEBUG
// Any property lookups performed when trying to attach ICs must be pure, i.e.
// must use LookupPropertyPure() or similar functions. Pure lookups are
// guaranteed to never modify the prototype chain. This ensures that the holder
// object can always be found on the prototype chain.
static bool IsCacheableProtoChain(NativeObject* obj, NativeObject* holder) {
  while (obj != holder) {
    JSObject* proto = obj->staticPrototype();
    if (!proto || !proto->is<NativeObject>()) {
      return false;
    }
    obj = &proto->as<NativeObject>();
  }
  return true;
}
#endif

static bool IsCacheableGetPropSlot(NativeObject* obj, NativeObject* holder,
                                   PropertyInfo prop) {
  MOZ_ASSERT(IsCacheableProtoChain(obj, holder));

  return prop.isDataProperty();
}

enum class NativeGetPropKind {
  None,
  Missing,
  Slot,
  NativeGetter,
  ScriptedGetter,
};

static NativeGetPropKind IsCacheableGetPropCall(NativeObject* obj,
                                                NativeObject* holder,
                                                PropertyInfo prop) {
  MOZ_ASSERT(IsCacheableProtoChain(obj, holder));

  if (!prop.isAccessorProperty()) {
    return NativeGetPropKind::None;
  }

  JSObject* getterObject = holder->getGetter(prop);
  if (!getterObject || !getterObject->is<JSFunction>()) {
    return NativeGetPropKind::None;
  }

  JSFunction& getter = getterObject->as<JSFunction>();

  if (getter.isClassConstructor()) {
    return NativeGetPropKind::None;
  }

  // Scripted functions and natives with JIT entry can use the scripted path.
  if (getter.hasJitEntry()) {
    return NativeGetPropKind::ScriptedGetter;
  }

  MOZ_ASSERT(getter.isNativeWithoutJitEntry());
  return NativeGetPropKind::NativeGetter;
}

static bool CheckHasNoSuchOwnProperty(JSContext* cx, JSObject* obj, jsid id) {
  if (!obj->is<NativeObject>()) {
    return false;
  }
  // Don't handle objects with resolve hooks.
  if (ClassMayResolveId(cx->names(), obj->getClass(), id, obj)) {
    return false;
  }
  if (obj->as<NativeObject>().contains(cx, id)) {
    return false;
  }
  return true;
}

static bool CheckHasNoSuchProperty(JSContext* cx, JSObject* obj, jsid id) {
  JSObject* curObj = obj;
  do {
    if (!CheckHasNoSuchOwnProperty(cx, curObj, id)) {
      return false;
    }

    curObj = curObj->staticPrototype();
  } while (curObj);

  return true;
}

static bool IsCacheableNoProperty(JSContext* cx, NativeObject* obj,
                                  NativeObject* holder, jsid id,
                                  jsbytecode* pc) {
  MOZ_ASSERT(!holder);

  // If we're doing a name lookup, we have to throw a ReferenceError.
  if (JSOp(*pc) == JSOp::GetBoundName) {
    return false;
  }

  return CheckHasNoSuchProperty(cx, obj, id);
}

static NativeGetPropKind CanAttachNativeGetProp(JSContext* cx, JSObject* obj,
                                                PropertyKey id,
                                                NativeObject** holder,
                                                Maybe<PropertyInfo>* propInfo,
                                                jsbytecode* pc) {
  MOZ_ASSERT(id.isString() || id.isSymbol());
  MOZ_ASSERT(!*holder);

  // The lookup needs to be universally pure, otherwise we risk calling hooks
  // out of turn. We don't mind doing this even when purity isn't required,
  // because we only miss out on shape hashification, which is only a temporary
  // perf cost. The limits were arbitrarily set, anyways.
  NativeObject* baseHolder = nullptr;
  PropertyResult prop;
  if (!LookupPropertyPure(cx, obj, id, &baseHolder, &prop)) {
    return NativeGetPropKind::None;
  }
  auto* nobj = &obj->as<NativeObject>();

  if (prop.isNativeProperty()) {
    MOZ_ASSERT(baseHolder);
    *holder = baseHolder;
    *propInfo = mozilla::Some(prop.propertyInfo());

    if (IsCacheableGetPropSlot(nobj, *holder, propInfo->ref())) {
      return NativeGetPropKind::Slot;
    }

    return IsCacheableGetPropCall(nobj, *holder, propInfo->ref());
  }

  if (!prop.isFound()) {
    if (IsCacheableNoProperty(cx, nobj, *holder, id, pc)) {
      return NativeGetPropKind::Missing;
    }
  }

  return NativeGetPropKind::None;
}

static void GuardReceiverProto(CacheIRWriter& writer, NativeObject* obj,
                               ObjOperandId objId) {
  // Note: we guard on the actual prototype and not on the shape because this is
  // used for sparse elements where we expect shape changes.

  if (JSObject* proto = obj->staticPrototype()) {
    writer.guardProto(objId, proto);
  } else {
    writer.guardNullProto(objId);
  }
}

// Guard that a given object has same class and same OwnProperties (excluding
// dense elements and dynamic properties).
static void TestMatchingNativeReceiver(CacheIRWriter& writer, NativeObject* obj,
                                       ObjOperandId objId) {
  writer.guardShapeForOwnProperties(objId, obj->shape());
}

// Similar to |TestMatchingNativeReceiver|, but specialized for ProxyObject.
static void TestMatchingProxyReceiver(CacheIRWriter& writer, ProxyObject* obj,
                                      ObjOperandId objId) {
  writer.guardShapeForClass(objId, obj->shape());
}

static void GeneratePrototypeGuards(CacheIRWriter& writer, JSObject* obj,
                                    NativeObject* holder, ObjOperandId objId) {
  // Assuming target property is on |holder|, generate appropriate guards to
  // ensure |holder| is still on the prototype chain of |obj| and we haven't
  // introduced any shadowing definitions.
  //
  // For each item in the proto chain before holder, we must ensure that
  // [[GetPrototypeOf]] still has the expected result, and that
  // [[GetOwnProperty]] has no definition of the target property.
  //
  //
  // [SMDOC] Shape Teleporting Optimization
  // --------------------------------------
  //
  // Starting with the assumption (and guideline to developers) that mutating
  // prototypes is an uncommon and fair-to-penalize operation we move cost
  // from the access side to the mutation side.
  //
  // Consider the following proto chain, with B defining a property 'x':
  //
  //      D  ->  C  ->  B{x: 3}  ->  A  -> null
  //
  // When accessing |D.x| we refer to D as the "receiver", and B as the
  // "holder". To optimize this access we need to ensure that neither D nor C
  // has since defined a shadowing property 'x'. Since C is a prototype that
  // we assume is rarely mutated we would like to avoid checking each time if
  // new properties are added. To do this we require that whenever C starts
  // shadowing a property on its proto chain, we invalidate (and opt out of) the
  // teleporting optimization by setting the InvalidatedTeleporting flag on the
  // object we're shadowing, triggering a shape change of that object. As a
  // result, checking the shape of D and B is sufficient. Note that we do not
  // care if the shape or properties of A change since the lookup of 'x' will
  // stop at B.
  //
  // The second condition we must verify is that the prototype chain was not
  // mutated. The same mechanism as above is used. When the prototype link is
  // changed, we generate a new shape for the object. If the object whose
  // link we are mutating is itself a prototype, we regenerate shapes down
  // the chain by setting the InvalidatedTeleporting flag on them. This means
  // the same two shape checks as above are sufficient.
  //
  // Once the InvalidatedTeleporting flag is set, it means the shape will no
  // longer be changed by ReshapeForProtoMutation and ReshapeForShadowedProp.
  // In this case we can no longer apply the optimization.
  //
  // See:
  //  - ReshapeForProtoMutation
  //  - ReshapeForShadowedProp

  MOZ_ASSERT(holder);
  MOZ_ASSERT(obj != holder);

  // Receiver guards (see TestMatchingReceiver) ensure the receiver's proto is
  // unchanged so peel off the receiver.
  JSObject* pobj = obj->staticPrototype();
  MOZ_ASSERT(pobj->isUsedAsPrototype());

  // If teleporting is supported for this holder, we are done.
  if (!holder->hasInvalidatedTeleporting()) {
    return;
  }

  // If already at the holder, no further proto checks are needed.
  if (pobj == holder) {
    return;
  }

  // Synchronize pobj and protoId.
  MOZ_ASSERT(pobj == obj->staticPrototype());
  ObjOperandId protoId = writer.loadProto(objId);

  // Shape guard each prototype object between receiver and holder. This guards
  // against both proto changes and shadowing properties.
  while (pobj != holder) {
    writer.guardShape(protoId, pobj->shape());

    pobj = pobj->staticPrototype();
    protoId = writer.loadProto(protoId);
  }
}

static void GeneratePrototypeHoleGuards(CacheIRWriter& writer,
                                        NativeObject* obj, ObjOperandId objId,
                                        bool alwaysGuardFirstProto) {
  if (alwaysGuardFirstProto) {
    GuardReceiverProto(writer, obj, objId);
  }

  JSObject* pobj = obj->staticPrototype();
  while (pobj) {
    ObjOperandId protoId = writer.loadObject(pobj);

    // Make sure the shape matches, to ensure the proto is unchanged and to
    // avoid non-dense elements or anything else that is being checked by
    // CanAttachDenseElementHole.
    MOZ_ASSERT(pobj->is<NativeObject>());
    writer.guardShape(protoId, pobj->shape());

    // Also make sure there are no dense elements.
    writer.guardNoDenseElements(protoId);

    pobj = pobj->staticPrototype();
  }
}

// Similar to |TestMatchingReceiver|, but for the holder object (when it
// differs from the receiver). The holder may also be the expando of the
// receiver if it exists.
static void TestMatchingHolder(CacheIRWriter& writer, NativeObject* obj,
                               ObjOperandId objId) {
  // The GeneratePrototypeGuards + TestMatchingHolder checks only support
  // prototype chains composed of NativeObject (excluding the receiver
  // itself).
  writer.guardShapeForOwnProperties(objId, obj->shape());
}

enum class IsCrossCompartment { No, Yes };

// Emit a shape guard for all objects on the proto chain. This does NOT include
// the receiver; callers must ensure the receiver's proto is the first proto by
// either emitting a shape guard or a prototype guard for |objId|.
//
// Note: this relies on shape implying proto.
template <IsCrossCompartment MaybeCrossCompartment = IsCrossCompartment::No>
static void ShapeGuardProtoChain(CacheIRWriter& writer, NativeObject* obj,
                                 ObjOperandId objId) {
  uint32_t depth = 0;
  static const uint32_t MAX_CACHED_LOADS = 4;
  ObjOperandId receiverObjId = objId;

  while (true) {
    JSObject* proto = obj->staticPrototype();
    if (!proto) {
      return;
    }

    obj = &proto->as<NativeObject>();

    // After guarding the shape of an object, we can safely bake that
    // object's proto into the stub data. Compared to LoadProto, this
    // takes one load instead of three (object -> shape -> baseshape
    // -> proto). We cap the depth to avoid bloating the size of the
    // stub data. To avoid compartment mismatch, we skip this optimization
    // in the cross-compartment case.
    if (depth < MAX_CACHED_LOADS &&
        MaybeCrossCompartment == IsCrossCompartment::No) {
      objId = writer.loadProtoObject(obj, receiverObjId);
    } else {
      objId = writer.loadProto(objId);
    }
    depth++;

    writer.guardShape(objId, obj->shape());
  }
}

// For cross compartment guards we shape-guard the prototype chain to avoid
// referencing the holder object.
//
// This peels off the first layer because it's guarded against obj == holder.
//
// Returns the holder's OperandId.
static ObjOperandId ShapeGuardProtoChainForCrossCompartmentHolder(
    CacheIRWriter& writer, NativeObject* obj, ObjOperandId objId,
    NativeObject* holder) {
  MOZ_ASSERT(obj != holder);
  MOZ_ASSERT(holder);
  while (true) {
    MOZ_ASSERT(obj->staticPrototype());
    obj = &obj->staticPrototype()->as<NativeObject>();

    objId = writer.loadProto(objId);
    if (obj == holder) {
      TestMatchingHolder(writer, obj, objId);
      return objId;
    }
    writer.guardShapeForOwnProperties(objId, obj->shape());
  }
}

// Emit guards for reading a data property on |holder|. Returns the holder's
// OperandId.
template <IsCrossCompartment MaybeCrossCompartment = IsCrossCompartment::No>
static ObjOperandId EmitReadSlotGuard(CacheIRWriter& writer, NativeObject* obj,
                                      NativeObject* holder,
                                      ObjOperandId objId) {
  MOZ_ASSERT(holder);
  TestMatchingNativeReceiver(writer, obj, objId);

  if (obj == holder) {
    return objId;
  }

  if (MaybeCrossCompartment == IsCrossCompartment::Yes) {
    // Guard proto chain integrity.
    // We use a variant of guards that avoid baking in any cross-compartment
    // object pointers.
    return ShapeGuardProtoChainForCrossCompartmentHolder(writer, obj, objId,
                                                         holder);
  }

  // Guard proto chain integrity.
  GeneratePrototypeGuards(writer, obj, holder, objId);

  // Guard on the holder's shape.
  ObjOperandId holderId = writer.loadObject(holder);
  TestMatchingHolder(writer, holder, holderId);
  return holderId;
}

template <IsCrossCompartment MaybeCrossCompartment = IsCrossCompartment::No>
static void EmitMissingPropGuard(CacheIRWriter& writer, NativeObject* obj,
                                 ObjOperandId objId) {
  TestMatchingNativeReceiver(writer, obj, objId);

  // The property does not exist. Guard on everything in the prototype
  // chain. This is guaranteed to see only Native objects because of
  // CanAttachNativeGetProp().
  ShapeGuardProtoChain<MaybeCrossCompartment>(writer, obj, objId);
}

template <IsCrossCompartment MaybeCrossCompartment = IsCrossCompartment::No>
static void EmitReadSlotResult(CacheIRWriter& writer, NativeObject* obj,
                               NativeObject* holder, PropertyInfo prop,
                               ObjOperandId objId) {
  MOZ_ASSERT(holder);

  ObjOperandId holderId =
      EmitReadSlotGuard<MaybeCrossCompartment>(writer, obj, holder, objId);

  MOZ_ASSERT(holderId.valid());
  EmitLoadSlotResult(writer, holderId, holder, prop);
}

template <IsCrossCompartment MaybeCrossCompartment = IsCrossCompartment::No>
static void EmitMissingPropResult(CacheIRWriter& writer, NativeObject* obj,
                                  ObjOperandId objId) {
  EmitMissingPropGuard<MaybeCrossCompartment>(writer, obj, objId);
  writer.loadUndefinedResult();
}

static void EmitCallGetterResultNoGuards(JSContext* cx, CacheIRWriter& writer,
                                         NativeGetPropKind kind,
                                         NativeObject* obj,
                                         NativeObject* holder,
                                         PropertyInfo prop,
                                         ValOperandId receiverId) {
  MOZ_ASSERT(IsCacheableGetPropCall(obj, holder, prop) == kind);

  JSFunction* target = &holder->getGetter(prop)->as<JSFunction>();
  bool sameRealm = cx->realm() == target->realm();

  switch (kind) {
    case NativeGetPropKind::NativeGetter: {
      writer.callNativeGetterResult(receiverId, target, sameRealm);
      writer.returnFromIC();
      break;
    }
    case NativeGetPropKind::ScriptedGetter: {
      writer.callScriptedGetterResult(receiverId, target, sameRealm);
      writer.returnFromIC();
      break;
    }
    default:
      // CanAttachNativeGetProp guarantees that the getter is either a native or
      // a scripted function.
      MOZ_ASSERT_UNREACHABLE("Can't attach getter");
      break;
  }
}

// See the SMDOC comment in vm/GetterSetter.h for more info on Getter/Setter
// properties
static void EmitGuardGetterSetterSlot(CacheIRWriter& writer,
                                      NativeObject* holder, PropertyInfo prop,
                                      ObjOperandId holderId,
                                      bool holderIsConstant = false) {
  // If the holder is guaranteed to be the same object, and it never had a
  // slot holding a GetterSetter mutated or deleted, its Shape will change when
  // that does happen so we don't need to guard on the GetterSetter.
  if (holderIsConstant && !holder->hadGetterSetterChange()) {
    return;
  }

  size_t slot = prop.slot();
  Value slotVal = holder->getSlot(slot);
  MOZ_ASSERT(slotVal.isPrivateGCThing());

  if (holder->isFixedSlot(slot)) {
    size_t offset = NativeObject::getFixedSlotOffset(slot);
    writer.guardFixedSlotValue(holderId, offset, slotVal);
  } else {
    size_t offset = holder->dynamicSlotIndex(slot) * sizeof(Value);
    writer.guardDynamicSlotValue(holderId, offset, slotVal);
  }
}

static void EmitCallGetterResultGuards(CacheIRWriter& writer, NativeObject* obj,
                                       NativeObject* holder, HandleId id,
                                       PropertyInfo prop, ObjOperandId objId,
                                       ICState::Mode mode) {
  // Use the megamorphic guard if we're in megamorphic mode, except if |obj|
  // is a Window as GuardHasGetterSetter doesn't support this yet (Window may
  // require outerizing).

  MOZ_ASSERT(holder->containsPure(id, prop));

  if (mode == ICState::Mode::Specialized || IsWindow(obj)) {
    TestMatchingNativeReceiver(writer, obj, objId);

    if (obj != holder) {
      GeneratePrototypeGuards(writer, obj, holder, objId);

      // Guard on the holder's shape.
      ObjOperandId holderId = writer.loadObject(holder);
      TestMatchingHolder(writer, holder, holderId);

      EmitGuardGetterSetterSlot(writer, holder, prop, holderId,
                                /* holderIsConstant = */ true);
    } else {
      EmitGuardGetterSetterSlot(writer, holder, prop, objId);
    }
  } else {
    GetterSetter* gs = holder->getGetterSetter(prop);
    writer.guardHasGetterSetter(objId, id, gs);
  }
}

static void EmitCallGetterResult(JSContext* cx, CacheIRWriter& writer,
                                 NativeGetPropKind kind, NativeObject* obj,
                                 NativeObject* holder, HandleId id,
                                 PropertyInfo prop, ObjOperandId objId,
                                 ValOperandId receiverId, ICState::Mode mode) {
  EmitCallGetterResultGuards(writer, obj, holder, id, prop, objId, mode);
  EmitCallGetterResultNoGuards(cx, writer, kind, obj, holder, prop, receiverId);
}

static bool CanAttachDOMCall(JSContext* cx, JSJitInfo::OpType type,
                             JSObject* obj, JSFunction* fun,
                             ICState::Mode mode) {
  MOZ_ASSERT(type == JSJitInfo::Getter || type == JSJitInfo::Setter ||
             type == JSJitInfo::Method);

  if (mode != ICState::Mode::Specialized) {
    return false;
  }

  if (!fun->hasJitInfo()) {
    return false;
  }

  if (cx->realm() != fun->realm()) {
    return false;
  }

  const JSJitInfo* jitInfo = fun->jitInfo();
  if (jitInfo->type() != type) {
    return false;
  }

  MOZ_ASSERT_IF(IsWindow(obj), !jitInfo->needsOuterizedThisObject());

  const JSClass* clasp = obj->getClass();
  if (!clasp->isDOMClass()) {
    return false;
  }

  if (type != JSJitInfo::Method && clasp->isProxyObject()) {
    return false;
  }

  // Ion codegen expects DOM_OBJECT_SLOT to be a fixed slot in LoadDOMPrivate.
  // It can be a dynamic slot if we transplanted this reflector object with a
  // proxy.
  if (obj->is<NativeObject>() && obj->as<NativeObject>().numFixedSlots() == 0) {
    return false;
  }

  // Tell the analysis the |DOMInstanceClassHasProtoAtDepth| hook can't GC.
  JS::AutoSuppressGCAnalysis nogc;

  DOMInstanceClassHasProtoAtDepth instanceChecker =
      cx->runtime()->DOMcallbacks->instanceClassMatchesProto;
  return instanceChecker(clasp, jitInfo->protoID, jitInfo->depth);
}

static bool CanAttachDOMGetterSetter(JSContext* cx, JSJitInfo::OpType type,
                                     NativeObject* obj, NativeObject* holder,
                                     PropertyInfo prop, ICState::Mode mode) {
  MOZ_ASSERT(type == JSJitInfo::Getter || type == JSJitInfo::Setter);

  JSObject* accessor = type == JSJitInfo::Getter ? holder->getGetter(prop)
                                                 : holder->getSetter(prop);
  JSFunction* fun = &accessor->as<JSFunction>();

  return CanAttachDOMCall(cx, type, obj, fun, mode);
}

static void EmitCallDOMGetterResultNoGuards(CacheIRWriter& writer,
                                            NativeObject* holder,
                                            PropertyInfo prop,
                                            ObjOperandId objId) {
  JSFunction* getter = &holder->getGetter(prop)->as<JSFunction>();
  writer.callDOMGetterResult(objId, getter->jitInfo());
  writer.returnFromIC();
}

static void EmitCallDOMGetterResult(JSContext* cx, CacheIRWriter& writer,
                                    NativeObject* obj, NativeObject* holder,
                                    HandleId id, PropertyInfo prop,
                                    ObjOperandId objId) {
  // Note: this relies on EmitCallGetterResultGuards emitting a shape guard
  // for specialized stubs.
  // The shape guard ensures the receiver's Class is valid for this DOM getter.
  EmitCallGetterResultGuards(writer, obj, holder, id, prop, objId,
                             ICState::Mode::Specialized);
  EmitCallDOMGetterResultNoGuards(writer, holder, prop, objId);
}

void GetPropIRGenerator::attachMegamorphicNativeSlot(ObjOperandId objId,
                                                     jsid id) {
  MOZ_ASSERT(mode_ == ICState::Mode::Megamorphic);

  // We don't support GetBoundName because environment objects have
  // lookupProperty hooks and GetBoundName is usually not megamorphic.
  MOZ_ASSERT(JSOp(*pc_) != JSOp::GetBoundName);

  if (cacheKind_ == CacheKind::GetProp ||
      cacheKind_ == CacheKind::GetPropSuper) {
    writer.megamorphicLoadSlotResult(objId, id);
  } else {
    MOZ_ASSERT(cacheKind_ == CacheKind::GetElem ||
               cacheKind_ == CacheKind::GetElemSuper);
    writer.megamorphicLoadSlotByValueResult(objId, getElemKeyValueId());
  }
  writer.returnFromIC();

  trackAttached("GetProp.MegamorphicNativeSlot");
}

AttachDecision GetPropIRGenerator::tryAttachNative(HandleObject obj,
                                                   ObjOperandId objId,
                                                   HandleId id,
                                                   ValOperandId receiverId) {
  Maybe<PropertyInfo> prop;
  NativeObject* holder = nullptr;

  NativeGetPropKind kind =
      CanAttachNativeGetProp(cx_, obj, id, &holder, &prop, pc_);
  switch (kind) {
    case NativeGetPropKind::None:
      return AttachDecision::NoAction;
    case NativeGetPropKind::Missing:
    case NativeGetPropKind::Slot: {
      auto* nobj = &obj->as<NativeObject>();

      if (mode_ == ICState::Mode::Megamorphic &&
          JSOp(*pc_) != JSOp::GetBoundName) {
        attachMegamorphicNativeSlot(objId, id);
        return AttachDecision::Attach;
      }

      maybeEmitIdGuard(id);
      if (kind == NativeGetPropKind::Slot) {
        EmitReadSlotResult(writer, nobj, holder, *prop, objId);
        writer.returnFromIC();
        trackAttached("GetProp.NativeSlot");
      } else {
        EmitMissingPropResult(writer, nobj, objId);
        writer.returnFromIC();
        trackAttached("GetProp.Missing");
      }
      return AttachDecision::Attach;
    }
    case NativeGetPropKind::ScriptedGetter:
    case NativeGetPropKind::NativeGetter: {
      auto* nobj = &obj->as<NativeObject>();

      maybeEmitIdGuard(id);

      if (!isSuper() && CanAttachDOMGetterSetter(cx_, JSJitInfo::Getter, nobj,
                                                 holder, *prop, mode_)) {
        EmitCallDOMGetterResult(cx_, writer, nobj, holder, id, *prop, objId);

        trackAttached("GetProp.DOMGetter");
        return AttachDecision::Attach;
      }

      EmitCallGetterResult(cx_, writer, kind, nobj, holder, id, *prop, objId,
                           receiverId, mode_);

      trackAttached("GetProp.NativeGetter");
      return AttachDecision::Attach;
    }
  }

  MOZ_CRASH("Bad NativeGetPropKind");
}

// Returns whether obj is a WindowProxy wrapping the script's global.
static bool IsWindowProxyForScriptGlobal(JSScript* script, JSObject* obj) {
  if (!IsWindowProxy(obj)) {
    return false;
  }

  MOZ_ASSERT(obj->getClass() ==
             script->runtimeFromMainThread()->maybeWindowProxyClass());

  JSObject* window = ToWindowIfWindowProxy(obj);

  // Ion relies on the WindowProxy's group changing (and the group getting
  // marked as having unknown properties) on navigation. If we ever stop
  // transplanting same-compartment WindowProxies, this assert will fail and we
  // need to fix that code.
  MOZ_ASSERT(window == &obj->nonCCWGlobal());

  // This must be a WindowProxy for a global in this compartment. Else it would
  // be a cross-compartment wrapper and IsWindowProxy returns false for
  // those.
  MOZ_ASSERT(script->compartment() == obj->compartment());

  // Only optimize lookups on the WindowProxy for the current global. Other
  // WindowProxies in the compartment may require security checks (based on
  // mutable document.domain). See bug 1516775.
  return window == &script->global();
}

// Guards objId is a WindowProxy for windowObj. Returns the window's operand id.
static ObjOperandId GuardAndLoadWindowProxyWindow(CacheIRWriter& writer,
                                                  ObjOperandId objId,
                                                  GlobalObject* windowObj) {
  writer.guardClass(objId, GuardClassKind::WindowProxy);
  ObjOperandId windowObjId = writer.loadWrapperTarget(objId);
  writer.guardSpecificObject(windowObjId, windowObj);
  return windowObjId;
}

// Whether a getter/setter on the global should have the WindowProxy as |this|
// value instead of the Window (the global object). This always returns true for
// scripted functions.
static bool GetterNeedsWindowProxyThis(NativeObject* holder,
                                       PropertyInfo prop) {
  JSFunction* callee = &holder->getGetter(prop)->as<JSFunction>();
  return !callee->hasJitInfo() || callee->jitInfo()->needsOuterizedThisObject();
}
static bool SetterNeedsWindowProxyThis(NativeObject* holder,
                                       PropertyInfo prop) {
  JSFunction* callee = &holder->getSetter(prop)->as<JSFunction>();
  return !callee->hasJitInfo() || callee->jitInfo()->needsOuterizedThisObject();
}

AttachDecision GetPropIRGenerator::tryAttachWindowProxy(HandleObject obj,
                                                        ObjOperandId objId,
                                                        HandleId id) {
  // Attach a stub when the receiver is a WindowProxy and we can do the lookup
  // on the Window (the global object).

  if (!IsWindowProxyForScriptGlobal(script_, obj)) {
    return AttachDecision::NoAction;
  }

  // If we're megamorphic prefer a generic proxy stub that handles a lot more
  // cases.
  if (mode_ == ICState::Mode::Megamorphic) {
    return AttachDecision::NoAction;
  }

  // Now try to do the lookup on the Window (the current global).
  GlobalObject* windowObj = cx_->global();
  NativeObject* holder = nullptr;
  Maybe<PropertyInfo> prop;
  NativeGetPropKind kind =
      CanAttachNativeGetProp(cx_, windowObj, id, &holder, &prop, pc_);
  switch (kind) {
    case NativeGetPropKind::None:
      return AttachDecision::NoAction;

    case NativeGetPropKind::Slot: {
      maybeEmitIdGuard(id);
      ObjOperandId windowObjId =
          GuardAndLoadWindowProxyWindow(writer, objId, windowObj);
      EmitReadSlotResult(writer, windowObj, holder, *prop, windowObjId);
      writer.returnFromIC();

      trackAttached("GetProp.WindowProxySlot");
      return AttachDecision::Attach;
    }

    case NativeGetPropKind::Missing: {
      maybeEmitIdGuard(id);
      ObjOperandId windowObjId =
          GuardAndLoadWindowProxyWindow(writer, objId, windowObj);
      EmitMissingPropResult(writer, windowObj, windowObjId);
      writer.returnFromIC();

      trackAttached("GetProp.WindowProxyMissing");
      return AttachDecision::Attach;
    }

    case NativeGetPropKind::NativeGetter:
    case NativeGetPropKind::ScriptedGetter: {
      // If a |super| access, it is not worth the complexity to attach an IC.
      if (isSuper()) {
        return AttachDecision::NoAction;
      }

      bool needsWindowProxy = GetterNeedsWindowProxyThis(holder, *prop);

      // Guard the incoming object is a WindowProxy and inline a getter call
      // based on the Window object.
      maybeEmitIdGuard(id);
      ObjOperandId windowObjId =
          GuardAndLoadWindowProxyWindow(writer, objId, windowObj);

      if (CanAttachDOMGetterSetter(cx_, JSJitInfo::Getter, windowObj, holder,
                                   *prop, mode_)) {
        MOZ_ASSERT(!needsWindowProxy);
        EmitCallDOMGetterResult(cx_, writer, windowObj, holder, id, *prop,
                                windowObjId);
        trackAttached("GetProp.WindowProxyDOMGetter");
      } else {
        ValOperandId receiverId =
            writer.boxObject(needsWindowProxy ? objId : windowObjId);
        EmitCallGetterResult(cx_, writer, kind, windowObj, holder, id, *prop,
                             windowObjId, receiverId, mode_);
        trackAttached("GetProp.WindowProxyGetter");
      }

      return AttachDecision::Attach;
    }
  }

  MOZ_CRASH("Unreachable");
}

AttachDecision GetPropIRGenerator::tryAttachCrossCompartmentWrapper(
    HandleObject obj, ObjOperandId objId, HandleId id) {
  // We can only optimize this very wrapper-handler, because others might
  // have a security policy.
  if (!IsWrapper(obj) ||
      Wrapper::wrapperHandler(obj) != &CrossCompartmentWrapper::singleton) {
    return AttachDecision::NoAction;
  }

  // If we're megamorphic prefer a generic proxy stub that handles a lot more
  // cases.
  if (mode_ == ICState::Mode::Megamorphic) {
    return AttachDecision::NoAction;
  }

  RootedObject unwrapped(cx_, Wrapper::wrappedObject(obj));
  MOZ_ASSERT(unwrapped == UnwrapOneCheckedStatic(obj));
  MOZ_ASSERT(!IsCrossCompartmentWrapper(unwrapped),
             "CCWs must not wrap other CCWs");

  // If we allowed different zones we would have to wrap strings.
  if (unwrapped->compartment()->zone() != cx_->compartment()->zone()) {
    return AttachDecision::NoAction;
  }

  // Take the unwrapped object's global, and wrap in a
  // this-compartment wrapper. This is what will be stored in the IC
  // keep the compartment alive.
  RootedObject wrappedTargetGlobal(cx_, &unwrapped->nonCCWGlobal());
  if (!cx_->compartment()->wrap(cx_, &wrappedTargetGlobal)) {
    cx_->clearPendingException();
    return AttachDecision::NoAction;
  }

  NativeObject* holder = nullptr;
  Maybe<PropertyInfo> prop;

  // Enter realm of target to prevent failing compartment assertions when doing
  // the lookup.
  {
    AutoRealm ar(cx_, unwrapped);

    NativeGetPropKind kind =
        CanAttachNativeGetProp(cx_, unwrapped, id, &holder, &prop, pc_);
    if (kind != NativeGetPropKind::Slot && kind != NativeGetPropKind::Missing) {
      return AttachDecision::NoAction;
    }
  }
  auto* unwrappedNative = &unwrapped->as<NativeObject>();

  maybeEmitIdGuard(id);
  writer.guardIsProxy(objId);
  writer.guardHasProxyHandler(objId, Wrapper::wrapperHandler(obj));

  // Load the object wrapped by the CCW
  ObjOperandId wrapperTargetId = writer.loadWrapperTarget(objId);

  // If the compartment of the wrapped object is different we should fail.
  writer.guardCompartment(wrapperTargetId, wrappedTargetGlobal,
                          unwrappedNative->compartment());

  ObjOperandId unwrappedId = wrapperTargetId;
  if (holder) {
    EmitReadSlotResult<IsCrossCompartment::Yes>(writer, unwrappedNative, holder,
                                                *prop, unwrappedId);
    writer.wrapResult();
    writer.returnFromIC();
    trackAttached("GetProp.CCWSlot");
  } else {
    EmitMissingPropResult<IsCrossCompartment::Yes>(writer, unwrappedNative,
                                                   unwrappedId);
    writer.returnFromIC();
    trackAttached("GetProp.CCWMissing");
  }
  return AttachDecision::Attach;
}

static JSObject* NewWrapperWithObjectShape(JSContext* cx,
                                           Handle<NativeObject*> obj);

static bool GetXrayExpandoShapeWrapper(JSContext* cx, HandleObject xray,
                                       MutableHandleObject wrapper) {
  Value v = GetProxyReservedSlot(xray, GetXrayJitInfo()->xrayHolderSlot);
  if (v.isObject()) {
    NativeObject* holder = &v.toObject().as<NativeObject>();
    v = holder->getFixedSlot(GetXrayJitInfo()->holderExpandoSlot);
    if (v.isObject()) {
      Rooted<NativeObject*> expando(
          cx, &UncheckedUnwrap(&v.toObject())->as<NativeObject>());
      wrapper.set(NewWrapperWithObjectShape(cx, expando));
      return wrapper != nullptr;
    }
  }
  wrapper.set(nullptr);
  return true;
}

AttachDecision GetPropIRGenerator::tryAttachXrayCrossCompartmentWrapper(
    HandleObject obj, ObjOperandId objId, HandleId id,
    ValOperandId receiverId) {
  if (!obj->is<ProxyObject>()) {
    return AttachDecision::NoAction;
  }

  JS::XrayJitInfo* info = GetXrayJitInfo();
  if (!info || !info->isCrossCompartmentXray(GetProxyHandler(obj))) {
    return AttachDecision::NoAction;
  }

  if (!info->compartmentHasExclusiveExpandos(obj)) {
    return AttachDecision::NoAction;
  }

  RootedObject target(cx_, UncheckedUnwrap(obj));

  RootedObject expandoShapeWrapper(cx_);
  if (!GetXrayExpandoShapeWrapper(cx_, obj, &expandoShapeWrapper)) {
    cx_->recoverFromOutOfMemory();
    return AttachDecision::NoAction;
  }

  // Look for a getter we can call on the xray or its prototype chain.
  Rooted<Maybe<PropertyDescriptor>> desc(cx_);
  RootedObject holder(cx_, obj);
  RootedObjectVector prototypes(cx_);
  RootedObjectVector prototypeExpandoShapeWrappers(cx_);
  while (true) {
    if (!GetOwnPropertyDescriptor(cx_, holder, id, &desc)) {
      cx_->clearPendingException();
      return AttachDecision::NoAction;
    }
    if (desc.isSome()) {
      break;
    }
    if (!GetPrototype(cx_, holder, &holder)) {
      cx_->clearPendingException();
      return AttachDecision::NoAction;
    }
    if (!holder || !holder->is<ProxyObject>() ||
        !info->isCrossCompartmentXray(GetProxyHandler(holder))) {
      return AttachDecision::NoAction;
    }
    RootedObject prototypeExpandoShapeWrapper(cx_);
    if (!GetXrayExpandoShapeWrapper(cx_, holder,
                                    &prototypeExpandoShapeWrapper) ||
        !prototypes.append(holder) ||
        !prototypeExpandoShapeWrappers.append(prototypeExpandoShapeWrapper)) {
      cx_->recoverFromOutOfMemory();
      return AttachDecision::NoAction;
    }
  }
  if (!desc->isAccessorDescriptor()) {
    return AttachDecision::NoAction;
  }

  RootedObject getter(cx_, desc->getter());
  if (!getter || !getter->is<JSFunction>() ||
      !getter->as<JSFunction>().isNativeWithoutJitEntry()) {
    return AttachDecision::NoAction;
  }

  maybeEmitIdGuard(id);
  writer.guardIsProxy(objId);
  writer.guardHasProxyHandler(objId, GetProxyHandler(obj));

  // Load the object wrapped by the CCW
  ObjOperandId wrapperTargetId = writer.loadWrapperTarget(objId);

  // Test the wrapped object's class. The properties held by xrays or their
  // prototypes will be invariant for objects of a given class, except for
  // changes due to xray expandos or xray prototype mutations.
  writer.guardAnyClass(wrapperTargetId, target->getClass());

  // Make sure the expandos on the xray and its prototype chain match up with
  // what we expect. The expando shape needs to be consistent, to ensure it
  // has not had any shadowing properties added, and the expando cannot have
  // any custom prototype (xray prototypes are stable otherwise).
  //
  // We can only do this for xrays with exclusive access to their expandos
  // (as we checked earlier), which store a pointer to their expando
  // directly. Xrays in other compartments may share their expandos with each
  // other and a VM call is needed just to find the expando.
  if (expandoShapeWrapper) {
    writer.guardXrayExpandoShapeAndDefaultProto(objId, expandoShapeWrapper);
  } else {
    writer.guardXrayNoExpando(objId);
  }
  for (size_t i = 0; i < prototypes.length(); i++) {
    JSObject* proto = prototypes[i];
    ObjOperandId protoId = writer.loadObject(proto);
    if (JSObject* protoShapeWrapper = prototypeExpandoShapeWrappers[i]) {
      writer.guardXrayExpandoShapeAndDefaultProto(protoId, protoShapeWrapper);
    } else {
      writer.guardXrayNoExpando(protoId);
    }
  }

  bool sameRealm = cx_->realm() == getter->as<JSFunction>().realm();
  writer.callNativeGetterResult(receiverId, &getter->as<JSFunction>(),
                                sameRealm);
  writer.returnFromIC();

  trackAttached("GetProp.XrayCCW");
  return AttachDecision::Attach;
}

AttachDecision GetPropIRGenerator::tryAttachGenericProxy(
    Handle<ProxyObject*> obj, ObjOperandId objId, HandleId id,
    bool handleDOMProxies) {
  writer.guardIsProxy(objId);

  if (!handleDOMProxies) {
    // Ensure that the incoming object is not a DOM proxy, so that we can get to
    // the specialized stubs
    writer.guardIsNotDOMProxy(objId);
  }

  if (cacheKind_ == CacheKind::GetProp || mode_ == ICState::Mode::Specialized) {
    MOZ_ASSERT(!isSuper());
    maybeEmitIdGuard(id);
    writer.proxyGetResult(objId, id);
  } else {
    // Attach a stub that handles every id.
    MOZ_ASSERT(cacheKind_ == CacheKind::GetElem);
    MOZ_ASSERT(mode_ == ICState::Mode::Megamorphic);
    MOZ_ASSERT(!isSuper());
    writer.proxyGetByValueResult(objId, getElemKeyValueId());
  }

  writer.returnFromIC();

  trackAttached("GetProp.GenericProxy");
  return AttachDecision::Attach;
}

static bool ValueIsInt64Index(const Value& val, int64_t* index) {
  // Try to convert the Value to a TypedArray index or DataView offset.

  if (val.isInt32()) {
    *index = val.toInt32();
    return true;
  }

  if (val.isDouble()) {
    // Use NumberEqualsInt64 because ToPropertyKey(-0) is 0.
    return mozilla::NumberEqualsInt64(val.toDouble(), index);
  }

  return false;
}

IntPtrOperandId IRGenerator::guardToIntPtrIndex(const Value& index,
                                                ValOperandId indexId,
                                                bool supportOOB) {
#ifdef DEBUG
  int64_t indexInt64;
  MOZ_ASSERT_IF(!supportOOB, ValueIsInt64Index(index, &indexInt64));
#endif

  if (index.isInt32()) {
    Int32OperandId int32IndexId = writer.guardToInt32(indexId);
    return writer.int32ToIntPtr(int32IndexId);
  }

  MOZ_ASSERT(index.isNumber());
  NumberOperandId numberIndexId = writer.guardIsNumber(indexId);
  return writer.guardNumberToIntPtrIndex(numberIndexId, supportOOB);
}

ObjOperandId IRGenerator::guardDOMProxyExpandoObjectAndShape(
    ProxyObject* obj, ObjOperandId objId, const Value& expandoVal,
    NativeObject* expandoObj) {
  MOZ_ASSERT(IsCacheableDOMProxy(obj));

  TestMatchingProxyReceiver(writer, obj, objId);

  // Shape determines Class, so now it must be a DOM proxy.
  ValOperandId expandoValId;
  if (expandoVal.isObject()) {
    expandoValId = writer.loadDOMExpandoValue(objId);
  } else {
    expandoValId = writer.loadDOMExpandoValueIgnoreGeneration(objId);
  }

  // Guard the expando is an object and shape guard.
  ObjOperandId expandoObjId = writer.guardToObject(expandoValId);
  TestMatchingHolder(writer, expandoObj, expandoObjId);
  return expandoObjId;
}

AttachDecision GetPropIRGenerator::tryAttachDOMProxyExpando(
    Handle<ProxyObject*> obj, ObjOperandId objId, HandleId id,
    ValOperandId receiverId) {
  MOZ_ASSERT(IsCacheableDOMProxy(obj));

  Value expandoVal = GetProxyPrivate(obj);
  JSObject* expandoObj;
  if (expandoVal.isObject()) {
    expandoObj = &expandoVal.toObject();
  } else {
    MOZ_ASSERT(!expandoVal.isUndefined(),
               "How did a missing expando manage to shadow things?");
    auto expandoAndGeneration =
        static_cast<ExpandoAndGeneration*>(expandoVal.toPrivate());
    MOZ_ASSERT(expandoAndGeneration);
    expandoObj = &expandoAndGeneration->expando.toObject();
  }

  // Try to do the lookup on the expando object.
  NativeObject* holder = nullptr;
  Maybe<PropertyInfo> prop;
  NativeGetPropKind kind =
      CanAttachNativeGetProp(cx_, expandoObj, id, &holder, &prop, pc_);
  if (kind == NativeGetPropKind::None) {
    return AttachDecision::NoAction;
  }
  if (!holder) {
    return AttachDecision::NoAction;
  }
  auto* nativeExpandoObj = &expandoObj->as<NativeObject>();

  MOZ_ASSERT(holder == nativeExpandoObj);

  maybeEmitIdGuard(id);
  ObjOperandId expandoObjId = guardDOMProxyExpandoObjectAndShape(
      obj, objId, expandoVal, nativeExpandoObj);

  if (kind == NativeGetPropKind::Slot) {
    // Load from the expando's slots.
    EmitLoadSlotResult(writer, expandoObjId, nativeExpandoObj, *prop);
    writer.returnFromIC();
  } else {
    // Call the getter. Note that we pass objId, the DOM proxy, as |this|
    // and not the expando object.
    MOZ_ASSERT(kind == NativeGetPropKind::NativeGetter ||
               kind == NativeGetPropKind::ScriptedGetter);
    EmitGuardGetterSetterSlot(writer, nativeExpandoObj, *prop, expandoObjId);
    EmitCallGetterResultNoGuards(cx_, writer, kind, nativeExpandoObj,
                                 nativeExpandoObj, *prop, receiverId);
  }

  trackAttached("GetProp.DOMProxyExpando");
  return AttachDecision::Attach;
}

AttachDecision GetPropIRGenerator::tryAttachDOMProxyShadowed(
    Handle<ProxyObject*> obj, ObjOperandId objId, HandleId id) {
  MOZ_ASSERT(!isSuper());
  MOZ_ASSERT(IsCacheableDOMProxy(obj));

  maybeEmitIdGuard(id);
  TestMatchingProxyReceiver(writer, obj, objId);
  writer.proxyGetResult(objId, id);
  writer.returnFromIC();

  trackAttached("GetProp.DOMProxyShadowed");
  return AttachDecision::Attach;
}

// Callers are expected to have already guarded on the shape of the
// object, which guarantees the object is a DOM proxy.
static void CheckDOMProxyExpandoDoesNotShadow(CacheIRWriter& writer,
                                              ProxyObject* obj, jsid id,
                                              ObjOperandId objId) {
  MOZ_ASSERT(IsCacheableDOMProxy(obj));

  Value expandoVal = GetProxyPrivate(obj);

  ValOperandId expandoId;
  if (!expandoVal.isObject() && !expandoVal.isUndefined()) {
    auto expandoAndGeneration =
        static_cast<ExpandoAndGeneration*>(expandoVal.toPrivate());
    uint64_t generation = expandoAndGeneration->generation;
    expandoId = writer.loadDOMExpandoValueGuardGeneration(
        objId, expandoAndGeneration, generation);
    expandoVal = expandoAndGeneration->expando;
  } else {
    expandoId = writer.loadDOMExpandoValue(objId);
  }

  if (expandoVal.isUndefined()) {
    // Guard there's no expando object.
    writer.guardNonDoubleType(expandoId, ValueType::Undefined);
  } else if (expandoVal.isObject()) {
    // Guard the proxy either has no expando object or, if it has one, that
    // the shape matches the current expando object.
    NativeObject& expandoObj = expandoVal.toObject().as<NativeObject>();
    MOZ_ASSERT(!expandoObj.containsPure(id));
    writer.guardDOMExpandoMissingOrGuardShape(expandoId, expandoObj.shape());
  } else {
    MOZ_CRASH("Invalid expando value");
  }
}

AttachDecision GetPropIRGenerator::tryAttachDOMProxyUnshadowed(
    Handle<ProxyObject*> obj, ObjOperandId objId, HandleId id,
    ValOperandId receiverId) {
  MOZ_ASSERT(IsCacheableDOMProxy(obj));

  JSObject* checkObj = obj->staticPrototype();
  if (!checkObj) {
    return AttachDecision::NoAction;
  }

  NativeObject* holder = nullptr;
  Maybe<PropertyInfo> prop;
  NativeGetPropKind kind =
      CanAttachNativeGetProp(cx_, checkObj, id, &holder, &prop, pc_);
  if (kind == NativeGetPropKind::None) {
    return AttachDecision::NoAction;
  }
  auto* nativeCheckObj = &checkObj->as<NativeObject>();

  maybeEmitIdGuard(id);

  // Guard that our expando object hasn't started shadowing this property.
  TestMatchingProxyReceiver(writer, obj, objId);
  CheckDOMProxyExpandoDoesNotShadow(writer, obj, id, objId);

  if (holder) {
    // Found the property on the prototype chain. Treat it like a native
    // getprop.
    GeneratePrototypeGuards(writer, obj, holder, objId);

    // Guard on the holder of the property.
    ObjOperandId holderId = writer.loadObject(holder);
    TestMatchingHolder(writer, holder, holderId);

    if (kind == NativeGetPropKind::Slot) {
      EmitLoadSlotResult(writer, holderId, holder, *prop);
      writer.returnFromIC();
    } else {
      // EmitCallGetterResultNoGuards expects |obj| to be the object the
      // property is on to do some checks. Since we actually looked at
      // checkObj, and no extra guards will be generated, we can just
      // pass that instead.
      MOZ_ASSERT(kind == NativeGetPropKind::NativeGetter ||
                 kind == NativeGetPropKind::ScriptedGetter);
      MOZ_ASSERT(!isSuper());
      EmitGuardGetterSetterSlot(writer, holder, *prop, holderId,
                                /* holderIsConstant = */ true);
      EmitCallGetterResultNoGuards(cx_, writer, kind, nativeCheckObj, holder,
                                   *prop, receiverId);
    }
  } else {
    // Property was not found on the prototype chain. Deoptimize down to
    // proxy get call.
    MOZ_ASSERT(kind == NativeGetPropKind::Missing);
    MOZ_ASSERT(!isSuper());
    writer.proxyGetResult(objId, id);
    writer.returnFromIC();
  }

  trackAttached("GetProp.DOMProxyUnshadowed");
  return AttachDecision::Attach;
}

AttachDecision GetPropIRGenerator::tryAttachProxy(HandleObject obj,
                                                  ObjOperandId objId,
                                                  HandleId id,
                                                  ValOperandId receiverId) {
  ProxyStubType type = GetProxyStubType(cx_, obj, id);
  if (type == ProxyStubType::None) {
    return AttachDecision::NoAction;
  }
  auto proxy = obj.as<ProxyObject>();

  // The proxy stubs don't currently support |super| access.
  if (isSuper()) {
    return AttachDecision::NoAction;
  }

  if (mode_ == ICState::Mode::Megamorphic) {
    return tryAttachGenericProxy(proxy, objId, id,
                                 /* handleDOMProxies = */ true);
  }

  switch (type) {
    case ProxyStubType::None:
      break;
    case ProxyStubType::DOMExpando:
      TRY_ATTACH(tryAttachDOMProxyExpando(proxy, objId, id, receiverId));
      [[fallthrough]];  // Fall through to the generic shadowed case.
    case ProxyStubType::DOMShadowed:
      return tryAttachDOMProxyShadowed(proxy, objId, id);
    case ProxyStubType::DOMUnshadowed:
      TRY_ATTACH(tryAttachDOMProxyUnshadowed(proxy, objId, id, receiverId));
      return tryAttachGenericProxy(proxy, objId, id,
                                   /* handleDOMProxies = */ true);
    case ProxyStubType::Generic:
      return tryAttachGenericProxy(proxy, objId, id,
                                   /* handleDOMProxies = */ false);
  }

  MOZ_CRASH("Unexpected ProxyStubType");
}

// Guards the class of an object. Because shape implies class, and a shape guard
// is faster than a class guard, if this is our first time attaching a stub, we
// instead generate a shape guard.
void IRGenerator::emitOptimisticClassGuard(ObjOperandId objId, JSObject* obj,
                                           GuardClassKind kind) {
#ifdef DEBUG
  switch (kind) {
    case GuardClassKind::Array:
      MOZ_ASSERT(obj->is<ArrayObject>());
      break;
    case GuardClassKind::PlainObject:
      MOZ_ASSERT(obj->is<PlainObject>());
      break;
    case GuardClassKind::ArrayBuffer:
      MOZ_ASSERT(obj->is<ArrayBufferObject>());
      break;
    case GuardClassKind::SharedArrayBuffer:
      MOZ_ASSERT(obj->is<SharedArrayBufferObject>());
      break;
    case GuardClassKind::DataView:
      MOZ_ASSERT(obj->is<DataViewObject>());
      break;
    case GuardClassKind::Set:
      MOZ_ASSERT(obj->is<SetObject>());
      break;
    case GuardClassKind::Map:
      MOZ_ASSERT(obj->is<MapObject>());
      break;

    case GuardClassKind::MappedArguments:
    case GuardClassKind::UnmappedArguments:
    case GuardClassKind::JSFunction:
    case GuardClassKind::BoundFunction:
    case GuardClassKind::WindowProxy:
      // Arguments, functions, and the global object have
      // less consistent shapes.
      MOZ_CRASH("GuardClassKind not supported");
  }
#endif

  if (isFirstStub_) {
    writer.guardShapeForClass(objId, obj->shape());
  } else {
    writer.guardClass(objId, kind);
  }
}

static void AssertArgumentsCustomDataProp(ArgumentsObject* obj,
                                          PropertyKey key) {
#ifdef DEBUG
  // The property must still be a custom data property if it has been resolved.
  // If this assertion fails, we're probably missing a call to mark this
  // property overridden.
  Maybe<PropertyInfo> prop = obj->lookupPure(key);
  MOZ_ASSERT_IF(prop, prop->isCustomDataProperty());
#endif
}

AttachDecision GetPropIRGenerator::tryAttachObjectLength(HandleObject obj,
                                                         ObjOperandId objId,
                                                         HandleId id) {
  if (!id.isAtom(cx_->names().length)) {
    return AttachDecision::NoAction;
  }

  if (obj->is<ArrayObject>()) {
    if (obj->as<ArrayObject>().length() > INT32_MAX) {
      return AttachDecision::NoAction;
    }

    maybeEmitIdGuard(id);
    emitOptimisticClassGuard(objId, obj, GuardClassKind::Array);
    writer.loadInt32ArrayLengthResult(objId);
    writer.returnFromIC();

    trackAttached("GetProp.ArrayLength");
    return AttachDecision::Attach;
  }

  if (obj->is<ArgumentsObject>() &&
      !obj->as<ArgumentsObject>().hasOverriddenLength()) {
    AssertArgumentsCustomDataProp(&obj->as<ArgumentsObject>(), id);
    maybeEmitIdGuard(id);
    if (obj->is<MappedArgumentsObject>()) {
      writer.guardClass(objId, GuardClassKind::MappedArguments);
    } else {
      MOZ_ASSERT(obj->is<UnmappedArgumentsObject>());
      writer.guardClass(objId, GuardClassKind::UnmappedArguments);
    }
    writer.loadArgumentsObjectLengthResult(objId);
    writer.returnFromIC();

    trackAttached("GetProp.ArgumentsObjectLength");
    return AttachDecision::Attach;
  }

  return AttachDecision::NoAction;
}

AttachDecision GetPropIRGenerator::tryAttachTypedArray(HandleObject obj,
                                                       ObjOperandId objId,
                                                       HandleId id) {
  if (!obj->is<TypedArrayObject>()) {
    return AttachDecision::NoAction;
  }

  if (mode_ != ICState::Mode::Specialized) {
    return AttachDecision::NoAction;
  }

  // Receiver should be the object.
  if (isSuper()) {
    return AttachDecision::NoAction;
  }

  bool isLength = id.isAtom(cx_->names().length);
  bool isByteOffset = id.isAtom(cx_->names().byteOffset);
  if (!isLength && !isByteOffset && !id.isAtom(cx_->names().byteLength)) {
    return AttachDecision::NoAction;
  }

  NativeObject* holder = nullptr;
  Maybe<PropertyInfo> prop;
  NativeGetPropKind kind =
      CanAttachNativeGetProp(cx_, obj, id, &holder, &prop, pc_);
  if (kind != NativeGetPropKind::NativeGetter) {
    return AttachDecision::NoAction;
  }

  JSFunction& fun = holder->getGetter(*prop)->as<JSFunction>();
  if (isLength) {
    if (!TypedArrayObject::isOriginalLengthGetter(fun.native())) {
      return AttachDecision::NoAction;
    }
  } else if (isByteOffset) {
    if (!TypedArrayObject::isOriginalByteOffsetGetter(fun.native())) {
      return AttachDecision::NoAction;
    }
  } else {
    if (!TypedArrayObject::isOriginalByteLengthGetter(fun.native())) {
      return AttachDecision::NoAction;
    }
  }

  auto* tarr = &obj->as<TypedArrayObject>();

  maybeEmitIdGuard(id);
  // Emit all the normal guards for calling this native, but specialize
  // callNativeGetterResult.
  EmitCallGetterResultGuards(writer, tarr, holder, id, *prop, objId, mode_);
  if (isLength) {
    if (tarr->length() <= INT32_MAX) {
      writer.loadArrayBufferViewLengthInt32Result(objId);
    } else {
      writer.loadArrayBufferViewLengthDoubleResult(objId);
    }
    trackAttached("GetProp.TypedArrayLength");
  } else if (isByteOffset) {
    if (tarr->byteOffset() <= INT32_MAX) {
      writer.arrayBufferViewByteOffsetInt32Result(objId);
    } else {
      writer.arrayBufferViewByteOffsetDoubleResult(objId);
    }
    trackAttached("GetProp.TypedArrayByteOffset");
  } else {
    if (tarr->byteLength() <= INT32_MAX) {
      writer.typedArrayByteLengthInt32Result(objId);
    } else {
      writer.typedArrayByteLengthDoubleResult(objId);
    }
    trackAttached("GetProp.TypedArrayByteLength");
  }
  writer.returnFromIC();

  return AttachDecision::Attach;
}

AttachDecision GetPropIRGenerator::tryAttachDataView(HandleObject obj,
                                                     ObjOperandId objId,
                                                     HandleId id) {
  if (!obj->is<DataViewObject>()) {
    return AttachDecision::NoAction;
  }
  auto* dv = &obj->as<DataViewObject>();

  if (mode_ != ICState::Mode::Specialized) {
    return AttachDecision::NoAction;
  }

  // Receiver should be the object.
  if (isSuper()) {
    return AttachDecision::NoAction;
  }

  bool isByteOffset = id.isAtom(cx_->names().byteOffset);
  if (!isByteOffset && !id.isAtom(cx_->names().byteLength)) {
    return AttachDecision::NoAction;
  }

  // byteOffset and byteLength both throw when the ArrayBuffer is detached.
  if (dv->hasDetachedBuffer()) {
    return AttachDecision::NoAction;
  }

  NativeObject* holder = nullptr;
  Maybe<PropertyInfo> prop;
  NativeGetPropKind kind =
      CanAttachNativeGetProp(cx_, obj, id, &holder, &prop, pc_);
  if (kind != NativeGetPropKind::NativeGetter) {
    return AttachDecision::NoAction;
  }

  auto& fun = holder->getGetter(*prop)->as<JSFunction>();
  if (isByteOffset) {
    if (!DataViewObject::isOriginalByteOffsetGetter(fun.native())) {
      return AttachDecision::NoAction;
    }
  } else {
    if (!DataViewObject::isOriginalByteLengthGetter(fun.native())) {
      return AttachDecision::NoAction;
    }
  }

  maybeEmitIdGuard(id);
  // Emit all the normal guards for calling this native, but specialize
  // callNativeGetterResult.
  EmitCallGetterResultGuards(writer, dv, holder, id, *prop, objId, mode_);
  writer.guardHasAttachedArrayBuffer(objId);
  if (isByteOffset) {
    if (dv->byteOffset() <= INT32_MAX) {
      writer.arrayBufferViewByteOffsetInt32Result(objId);
    } else {
      writer.arrayBufferViewByteOffsetDoubleResult(objId);
    }
    trackAttached("GetProp.DataViewByteOffset");
  } else {
    if (dv->byteLength() <= INT32_MAX) {
      writer.loadArrayBufferViewLengthInt32Result(objId);
    } else {
      writer.loadArrayBufferViewLengthDoubleResult(objId);
    }
    trackAttached("GetProp.DataViewByteLength");
  }
  writer.returnFromIC();

  return AttachDecision::Attach;
}

AttachDecision GetPropIRGenerator::tryAttachArrayBufferMaybeShared(
    HandleObject obj, ObjOperandId objId, HandleId id) {
  if (!obj->is<ArrayBufferObjectMaybeShared>()) {
    return AttachDecision::NoAction;
  }
  auto* buf = &obj->as<ArrayBufferObjectMaybeShared>();

  if (mode_ != ICState::Mode::Specialized) {
    return AttachDecision::NoAction;
  }

  // Receiver should be the object.
  if (isSuper()) {
    return AttachDecision::NoAction;
  }

  if (!id.isAtom(cx_->names().byteLength)) {
    return AttachDecision::NoAction;
  }

  NativeObject* holder = nullptr;
  Maybe<PropertyInfo> prop;
  NativeGetPropKind kind =
      CanAttachNativeGetProp(cx_, obj, id, &holder, &prop, pc_);
  if (kind != NativeGetPropKind::NativeGetter) {
    return AttachDecision::NoAction;
  }

  auto& fun = holder->getGetter(*prop)->as<JSFunction>();
  if (buf->is<ArrayBufferObject>()) {
    if (!ArrayBufferObject::isOriginalByteLengthGetter(fun.native())) {
      return AttachDecision::NoAction;
    }
  } else {
    if (!SharedArrayBufferObject::isOriginalByteLengthGetter(fun.native())) {
      return AttachDecision::NoAction;
    }
  }

  maybeEmitIdGuard(id);
  // Emit all the normal guards for calling this native, but specialize
  // callNativeGetterResult.
  EmitCallGetterResultGuards(writer, buf, holder, id, *prop, objId, mode_);
  if (buf->byteLength() <= INT32_MAX) {
    writer.loadArrayBufferByteLengthInt32Result(objId);
  } else {
    writer.loadArrayBufferByteLengthDoubleResult(objId);
  }
  writer.returnFromIC();

  trackAttached("GetProp.ArrayBufferMaybeSharedByteLength");
  return AttachDecision::Attach;
}

AttachDecision GetPropIRGenerator::tryAttachRegExp(HandleObject obj,
                                                   ObjOperandId objId,
                                                   HandleId id) {
  if (!obj->is<RegExpObject>()) {
    return AttachDecision::NoAction;
  }
  auto* regExp = &obj->as<RegExpObject>();

  if (mode_ != ICState::Mode::Specialized) {
    return AttachDecision::NoAction;
  }

  // Receiver should be the object.
  if (isSuper()) {
    return AttachDecision::NoAction;
  }

  NativeObject* holder = nullptr;
  Maybe<PropertyInfo> prop;
  NativeGetPropKind kind =
      CanAttachNativeGetProp(cx_, obj, id, &holder, &prop, pc_);
  if (kind != NativeGetPropKind::NativeGetter) {
    return AttachDecision::NoAction;
  }

  auto& fun = holder->getGetter(*prop)->as<JSFunction>();
  JS::RegExpFlags flags = JS::RegExpFlag::NoFlags;
  if (!RegExpObject::isOriginalFlagGetter(fun.native(), &flags)) {
    return AttachDecision::NoAction;
  }

  maybeEmitIdGuard(id);
  // Emit all the normal guards for calling this native, but specialize
  // callNativeGetterResult.
  EmitCallGetterResultGuards(writer, regExp, holder, id, *prop, objId, mode_);

  writer.regExpFlagResult(objId, flags.value());
  writer.returnFromIC();

  trackAttached("GetProp.RegExpFlag");
  return AttachDecision::Attach;
}

AttachDecision GetPropIRGenerator::tryAttachMap(HandleObject obj,
                                                ObjOperandId objId,
                                                HandleId id) {
  if (!obj->is<MapObject>()) {
    return AttachDecision::NoAction;
  }
  auto* mapObj = &obj->as<MapObject>();

  if (mode_ != ICState::Mode::Specialized) {
    return AttachDecision::NoAction;
  }

  // Receiver should be the object.
  if (isSuper()) {
    return AttachDecision::NoAction;
  }

  if (!id.isAtom(cx_->names().size)) {
    return AttachDecision::NoAction;
  }

  NativeObject* holder = nullptr;
  Maybe<PropertyInfo> prop;
  NativeGetPropKind kind =
      CanAttachNativeGetProp(cx_, obj, id, &holder, &prop, pc_);
  if (kind != NativeGetPropKind::NativeGetter) {
    return AttachDecision::NoAction;
  }

  auto& fun = holder->getGetter(*prop)->as<JSFunction>();
  if (!MapObject::isOriginalSizeGetter(fun.native())) {
    return AttachDecision::NoAction;
  }

  maybeEmitIdGuard(id);

  // Emit all the normal guards for calling this native, but specialize
  // callNativeGetterResult.
  EmitCallGetterResultGuards(writer, mapObj, holder, id, *prop, objId, mode_);

  writer.mapSizeResult(objId);
  writer.returnFromIC();

  trackAttached("GetProp.MapSize");
  return AttachDecision::Attach;
}

AttachDecision GetPropIRGenerator::tryAttachSet(HandleObject obj,
                                                ObjOperandId objId,
                                                HandleId id) {
  if (!obj->is<SetObject>()) {
    return AttachDecision::NoAction;
  }
  auto* setObj = &obj->as<SetObject>();

  if (mode_ != ICState::Mode::Specialized) {
    return AttachDecision::NoAction;
  }

  // Receiver should be the object.
  if (isSuper()) {
    return AttachDecision::NoAction;
  }

  if (!id.isAtom(cx_->names().size)) {
    return AttachDecision::NoAction;
  }

  NativeObject* holder = nullptr;
  Maybe<PropertyInfo> prop;
  NativeGetPropKind kind =
      CanAttachNativeGetProp(cx_, obj, id, &holder, &prop, pc_);
  if (kind != NativeGetPropKind::NativeGetter) {
    return AttachDecision::NoAction;
  }

  auto& fun = holder->getGetter(*prop)->as<JSFunction>();
  if (!SetObject::isOriginalSizeGetter(fun.native())) {
    return AttachDecision::NoAction;
  }

  maybeEmitIdGuard(id);

  // Emit all the normal guards for calling this native, but specialize
  // callNativeGetterResult.
  EmitCallGetterResultGuards(writer, setObj, holder, id, *prop, objId, mode_);

  writer.setSizeResult(objId);
  writer.returnFromIC();

  trackAttached("GetProp.SetSize");
  return AttachDecision::Attach;
}

AttachDecision GetPropIRGenerator::tryAttachFunction(HandleObject obj,
                                                     ObjOperandId objId,
                                                     HandleId id) {
  // Function properties are lazily resolved so they might not be defined yet.
  // And we might end up in a situation where we always have a fresh function
  // object during the IC generation.
  if (!obj->is<JSFunction>()) {
    return AttachDecision::NoAction;
  }

  bool isLength = id.isAtom(cx_->names().length);
  if (!isLength && !id.isAtom(cx_->names().name)) {
    return AttachDecision::NoAction;
  }

  NativeObject* holder = nullptr;
  PropertyResult prop;
  // If this property exists already, don't attach the stub.
  if (LookupPropertyPure(cx_, obj, id, &holder, &prop)) {
    return AttachDecision::NoAction;
  }

  JSFunction* fun = &obj->as<JSFunction>();

  if (isLength) {
    // length was probably deleted from the function.
    if (fun->hasResolvedLength()) {
      return AttachDecision::NoAction;
    }

    // Lazy functions don't store the length.
    if (!fun->hasBytecode()) {
      return AttachDecision::NoAction;
    }
  } else {
    // name was probably deleted from the function.
    if (fun->hasResolvedName()) {
      return AttachDecision::NoAction;
    }
  }

  maybeEmitIdGuard(id);
  writer.guardClass(objId, GuardClassKind::JSFunction);
  if (isLength) {
    writer.loadFunctionLengthResult(objId);
    writer.returnFromIC();
    trackAttached("GetProp.FunctionLength");
  } else {
    writer.loadFunctionNameResult(objId);
    writer.returnFromIC();
    trackAttached("GetProp.FunctionName");
  }
  return AttachDecision::Attach;
}

AttachDecision GetPropIRGenerator::tryAttachArgumentsObjectIterator(
    HandleObject obj, ObjOperandId objId, HandleId id) {
  if (!obj->is<ArgumentsObject>()) {
    return AttachDecision::NoAction;
  }

  if (!id.isWellKnownSymbol(JS::SymbolCode::iterator)) {
    return AttachDecision::NoAction;
  }

  Handle<ArgumentsObject*> args = obj.as<ArgumentsObject>();
  if (args->hasOverriddenIterator()) {
    return AttachDecision::NoAction;
  }

  AssertArgumentsCustomDataProp(args, id);

  RootedValue iterator(cx_);
  if (!ArgumentsObject::getArgumentsIterator(cx_, &iterator)) {
    cx_->recoverFromOutOfMemory();
    return AttachDecision::NoAction;
  }
  MOZ_ASSERT(iterator.isObject());

  maybeEmitIdGuard(id);
  if (args->is<MappedArgumentsObject>()) {
    writer.guardClass(objId, GuardClassKind::MappedArguments);
  } else {
    MOZ_ASSERT(args->is<UnmappedArgumentsObject>());
    writer.guardClass(objId, GuardClassKind::UnmappedArguments);
  }
  uint32_t flags = ArgumentsObject::ITERATOR_OVERRIDDEN_BIT;
  writer.guardArgumentsObjectFlags(objId, flags);

  ObjOperandId iterId = writer.loadObject(&iterator.toObject());
  writer.loadObjectResult(iterId);
  writer.returnFromIC();

  trackAttached("GetProp.ArgumentsObjectIterator");
  return AttachDecision::Attach;
}

AttachDecision GetPropIRGenerator::tryAttachModuleNamespace(HandleObject obj,
                                                            ObjOperandId objId,
                                                            HandleId id) {
  if (!obj->is<ModuleNamespaceObject>()) {
    return AttachDecision::NoAction;
  }

  auto* ns = &obj->as<ModuleNamespaceObject>();
  ModuleEnvironmentObject* env = nullptr;
  Maybe<PropertyInfo> prop;
  if (!ns->bindings().lookup(id, &env, &prop)) {
    return AttachDecision::NoAction;
  }

  // Don't emit a stub until the target binding has been initialized.
  if (env->getSlot(prop->slot()).isMagic(JS_UNINITIALIZED_LEXICAL)) {
    return AttachDecision::NoAction;
  }

  // Check for the specific namespace object.
  maybeEmitIdGuard(id);
  writer.guardSpecificObject(objId, ns);

  ObjOperandId envId = writer.loadObject(env);
  EmitLoadSlotResult(writer, envId, env, *prop);
  writer.returnFromIC();

  trackAttached("GetProp.ModuleNamespace");
  return AttachDecision::Attach;
}

AttachDecision GetPropIRGenerator::tryAttachPrimitive(ValOperandId valId,
                                                      HandleId id) {
  MOZ_ASSERT(!isSuper(), "SuperBase is guaranteed to be an object");

  JSProtoKey protoKey;
  switch (val_.type()) {
    case ValueType::String:
      if (id.isAtom(cx_->names().length)) {
        // String length is special-cased, see js::GetProperty.
        return AttachDecision::NoAction;
      }
      protoKey = JSProto_String;
      break;
    case ValueType::Int32:
    case ValueType::Double:
      protoKey = JSProto_Number;
      break;
    case ValueType::Boolean:
      protoKey = JSProto_Boolean;
      break;
    case ValueType::Symbol:
      protoKey = JSProto_Symbol;
      break;
    case ValueType::BigInt:
      protoKey = JSProto_BigInt;
      break;
    case ValueType::Null:
    case ValueType::Undefined:
    case ValueType::Magic:
      return AttachDecision::NoAction;
#ifdef ENABLE_RECORD_TUPLE
    case ValueType::ExtendedPrimitive:
#endif
    case ValueType::Object:
    case ValueType::PrivateGCThing:
      MOZ_CRASH("unexpected type");
  }

  JSObject* proto = cx_->global()->maybeGetPrototype(protoKey);
  if (!proto) {
    return AttachDecision::NoAction;
  }

  NativeObject* holder = nullptr;
  Maybe<PropertyInfo> prop;
  NativeGetPropKind kind =
      CanAttachNativeGetProp(cx_, proto, id, &holder, &prop, pc_);
  switch (kind) {
    case NativeGetPropKind::None:
      return AttachDecision::NoAction;
    case NativeGetPropKind::Missing:
    case NativeGetPropKind::Slot: {
      auto* nproto = &proto->as<NativeObject>();

      if (val_.isNumber()) {
        writer.guardIsNumber(valId);
      } else {
        writer.guardNonDoubleType(valId, val_.type());
      }
      maybeEmitIdGuard(id);

      ObjOperandId protoId = writer.loadObject(nproto);
      if (kind == NativeGetPropKind::Slot) {
        EmitReadSlotResult(writer, nproto, holder, *prop, protoId);
        writer.returnFromIC();
        trackAttached("GetProp.PrimitiveSlot");
      } else {
        EmitMissingPropResult(writer, nproto, protoId);
        writer.returnFromIC();
        trackAttached("GetProp.PrimitiveMissing");
      }
      return AttachDecision::Attach;
    }
    case NativeGetPropKind::ScriptedGetter:
    case NativeGetPropKind::NativeGetter: {
      auto* nproto = &proto->as<NativeObject>();

      if (val_.isNumber()) {
        writer.guardIsNumber(valId);
      } else {
        writer.guardNonDoubleType(valId, val_.type());
      }
      maybeEmitIdGuard(id);

      ObjOperandId protoId = writer.loadObject(nproto);
      EmitCallGetterResult(cx_, writer, kind, nproto, holder, id, *prop,
                           protoId, valId, mode_);

      trackAttached("GetProp.PrimitiveGetter");
      return AttachDecision::Attach;
    }
  }

  MOZ_CRASH("Bad NativeGetPropKind");
}

AttachDecision GetPropIRGenerator::tryAttachStringLength(ValOperandId valId,
                                                         HandleId id) {
  if (!val_.isString() || !id.isAtom(cx_->names().length)) {
    return AttachDecision::NoAction;
  }

  StringOperandId strId = writer.guardToString(valId);
  maybeEmitIdGuard(id);
  writer.loadStringLengthResult(strId);
  writer.returnFromIC();

  trackAttached("GetProp.StringLength");
  return AttachDecision::Attach;
}

enum class AttachStringChar { No, Yes, Linearize, OutOfBounds };

static AttachStringChar CanAttachStringChar(const Value& val,
                                            const Value& idVal) {
  if (!val.isString() || !idVal.isInt32()) {
    return AttachStringChar::No;
  }

  int32_t index = idVal.toInt32();
  if (index < 0) {
    return AttachStringChar::OutOfBounds;
  }

  JSString* str = val.toString();
  if (size_t(index) >= str->length()) {
    return AttachStringChar::OutOfBounds;
  }

  // This follows JSString::getChar and MacroAssembler::loadStringChar.
  if (str->isRope()) {
    JSRope* rope = &str->asRope();
    if (size_t(index) < rope->leftChild()->length()) {
      str = rope->leftChild();
    } else {
      str = rope->rightChild();
    }
  }

  if (!str->isLinear()) {
    return AttachStringChar::Linearize;
  }

  return AttachStringChar::Yes;
}

AttachDecision GetPropIRGenerator::tryAttachStringChar(ValOperandId valId,
                                                       ValOperandId indexId) {
  MOZ_ASSERT(idVal_.isInt32());

  auto attach = CanAttachStringChar(val_, idVal_);
  if (attach == AttachStringChar::No) {
    return AttachDecision::NoAction;
  }

  // Can't attach for out-of-bounds access without guarding that indexed
  // properties aren't present along the prototype chain of |String.prototype|.
  if (attach == AttachStringChar::OutOfBounds) {
    return AttachDecision::NoAction;
  }

  StringOperandId strId = writer.guardToString(valId);
  Int32OperandId int32IndexId = writer.guardToInt32Index(indexId);
  if (attach == AttachStringChar::Linearize) {
    strId = writer.linearizeForCharAccess(strId, int32IndexId);
  }
  writer.loadStringCharResult(strId, int32IndexId, /* handleOOB = */ false);
  writer.returnFromIC();

  trackAttached("GetProp.StringChar");
  return AttachDecision::Attach;
}

static bool ClassCanHaveExtraProperties(const JSClass* clasp) {
  return clasp->getResolve() || clasp->getOpsLookupProperty() ||
         clasp->getOpsGetProperty() || IsTypedArrayClass(clasp);
}

enum class OwnProperty : bool { No, Yes };
enum class AllowIndexedReceiver : bool { No, Yes };
enum class AllowExtraReceiverProperties : bool { No, Yes };

static bool CanAttachDenseElementHole(
    NativeObject* obj, OwnProperty ownProp,
    AllowIndexedReceiver allowIndexedReceiver = AllowIndexedReceiver::No,
    AllowExtraReceiverProperties allowExtraReceiverProperties =
        AllowExtraReceiverProperties::No) {
  // Make sure the objects on the prototype don't have any indexed properties
  // or that such properties can't appear without a shape change.
  // Otherwise returning undefined for holes would obviously be incorrect,
  // because we would have to lookup a property on the prototype instead.
  do {
    // The first two checks are also relevant to the receiver object.
    if (allowIndexedReceiver == AllowIndexedReceiver::No && obj->isIndexed()) {
      return false;
    }
    allowIndexedReceiver = AllowIndexedReceiver::No;

    if (allowExtraReceiverProperties == AllowExtraReceiverProperties::No &&
        ClassCanHaveExtraProperties(obj->getClass())) {
      return false;
    }
    allowExtraReceiverProperties = AllowExtraReceiverProperties::No;

    // Don't need to check prototype for OwnProperty checks
    if (ownProp == OwnProperty::Yes) {
      return true;
    }

    JSObject* proto = obj->staticPrototype();
    if (!proto) {
      break;
    }

    if (!proto->is<NativeObject>()) {
      return false;
    }

    // Make sure objects on the prototype don't have dense elements.
    if (proto->as<NativeObject>().getDenseInitializedLength() != 0) {
      return false;
    }

    obj = &proto->as<NativeObject>();
  } while (true);

  return true;
}

AttachDecision GetPropIRGenerator::tryAttachArgumentsObjectArg(
    HandleObject obj, ObjOperandId objId, uint32_t index,
    Int32OperandId indexId) {
  if (!obj->is<ArgumentsObject>()) {
    return AttachDecision::NoAction;
  }
  auto* args = &obj->as<ArgumentsObject>();

  // No elements must have been overridden or deleted.
  if (args->hasOverriddenElement()) {
    return AttachDecision::NoAction;
  }

  // Check bounds.
  if (index >= args->initialLength()) {
    return AttachDecision::NoAction;
  }

  AssertArgumentsCustomDataProp(args, PropertyKey::Int(index));

  // And finally also check that the argument isn't forwarded.
  if (args->argIsForwarded(index)) {
    return AttachDecision::NoAction;
  }

  if (args->is<MappedArgumentsObject>()) {
    writer.guardClass(objId, GuardClassKind::MappedArguments);
  } else {
    MOZ_ASSERT(args->is<UnmappedArgumentsObject>());
    writer.guardClass(objId, GuardClassKind::UnmappedArguments);
  }

  writer.loadArgumentsObjectArgResult(objId, indexId);
  writer.returnFromIC();

  trackAttached("GetProp.ArgumentsObjectArg");
  return AttachDecision::Attach;
}

AttachDecision GetPropIRGenerator::tryAttachArgumentsObjectArgHole(
    HandleObject obj, ObjOperandId objId, uint32_t index,
    Int32OperandId indexId) {
  if (!obj->is<ArgumentsObject>()) {
    return AttachDecision::NoAction;
  }
  auto* args = &obj->as<ArgumentsObject>();

  // No elements must have been overridden or deleted.
  if (args->hasOverriddenElement()) {
    return AttachDecision::NoAction;
  }

  // And also check that the argument isn't forwarded.
  if (index < args->initialLength() && args->argIsForwarded(index)) {
    return AttachDecision::NoAction;
  }

  if (!CanAttachDenseElementHole(args, OwnProperty::No,
                                 AllowIndexedReceiver::Yes,
                                 AllowExtraReceiverProperties::Yes)) {
    return AttachDecision::NoAction;
  }

  // We don't need to guard on the shape, because we check if any element is
  // overridden. Elements are marked as overridden iff any element is defined,
  // irrespective of whether the element is in-bounds or out-of-bounds. So when
  // that flag isn't set, we can guarantee that the arguments object doesn't
  // have any additional own elements.

  if (args->is<MappedArgumentsObject>()) {
    writer.guardClass(objId, GuardClassKind::MappedArguments);
  } else {
    MOZ_ASSERT(args->is<UnmappedArgumentsObject>());
    writer.guardClass(objId, GuardClassKind::UnmappedArguments);
  }

  GeneratePrototypeHoleGuards(writer, args, objId,
                              /* alwaysGuardFirstProto = */ true);

  writer.loadArgumentsObjectArgHoleResult(objId, indexId);
  writer.returnFromIC();

  trackAttached("GetProp.ArgumentsObjectArgHole");
  return AttachDecision::Attach;
}

AttachDecision GetPropIRGenerator::tryAttachArgumentsObjectCallee(
    HandleObject obj, ObjOperandId objId, HandleId id) {
  // Only mapped arguments objects have a `callee` property.
  if (!obj->is<MappedArgumentsObject>()) {
    return AttachDecision::NoAction;
  }

  if (!id.isAtom(cx_->names().callee)) {
    return AttachDecision::NoAction;
  }

  // The callee must not have been overridden or deleted.
  MappedArgumentsObject* args = &obj->as<MappedArgumentsObject>();
  if (args->hasOverriddenCallee()) {
    return AttachDecision::NoAction;
  }

  AssertArgumentsCustomDataProp(args, id);

  maybeEmitIdGuard(id);
  writer.guardClass(objId, GuardClassKind::MappedArguments);

  uint32_t flags = ArgumentsObject::CALLEE_OVERRIDDEN_BIT;
  writer.guardArgumentsObjectFlags(objId, flags);

  writer.loadFixedSlotResult(objId,
                             MappedArgumentsObject::getCalleeSlotOffset());
  writer.returnFromIC();

  trackAttached("GetProp.ArgumentsObjectCallee");
  return AttachDecision::Attach;
}

AttachDecision GetPropIRGenerator::tryAttachDenseElement(
    HandleObject obj, ObjOperandId objId, uint32_t index,
    Int32OperandId indexId) {
  if (!obj->is<NativeObject>()) {
    return AttachDecision::NoAction;
  }

  NativeObject* nobj = &obj->as<NativeObject>();
  if (!nobj->containsDenseElement(index)) {
    return AttachDecision::NoAction;
  }

  if (mode_ == ICState::Mode::Megamorphic) {
    writer.guardIsNativeObject(objId);
  } else {
    TestMatchingNativeReceiver(writer, nobj, objId);
  }
  writer.loadDenseElementResult(objId, indexId);
  writer.returnFromIC();

  trackAttached("GetProp.DenseElement");
  return AttachDecision::Attach;
}

AttachDecision GetPropIRGenerator::tryAttachDenseElementHole(
    HandleObject obj, ObjOperandId objId, uint32_t index,
    Int32OperandId indexId) {
  if (!obj->is<NativeObject>()) {
    return AttachDecision::NoAction;
  }

  NativeObject* nobj = &obj->as<NativeObject>();
  if (nobj->containsDenseElement(index)) {
    return AttachDecision::NoAction;
  }
  if (!CanAttachDenseElementHole(nobj, OwnProperty::No)) {
    return AttachDecision::NoAction;
  }

  // Guard on the shape, to prevent non-dense elements from appearing.
  TestMatchingNativeReceiver(writer, nobj, objId);
  GeneratePrototypeHoleGuards(writer, nobj, objId,
                              /* alwaysGuardFirstProto = */ false);
  writer.loadDenseElementHoleResult(objId, indexId);
  writer.returnFromIC();

  trackAttached("GetProp.DenseElementHole");
  return AttachDecision::Attach;
}

AttachDecision GetPropIRGenerator::tryAttachSparseElement(
    HandleObject obj, ObjOperandId objId, uint32_t index,
    Int32OperandId indexId) {
  if (!obj->is<NativeObject>()) {
    return AttachDecision::NoAction;
  }
  NativeObject* nobj = &obj->as<NativeObject>();

  // Stub doesn't handle negative indices.
  if (index > INT32_MAX) {
    return AttachDecision::NoAction;
  }

  // The object must have sparse elements.
  if (!nobj->isIndexed()) {
    return AttachDecision::NoAction;
  }

  // The index must not be for a dense element.
  if (nobj->containsDenseElement(index)) {
    return AttachDecision::NoAction;
  }

  // Only handle ArrayObject and PlainObject in this stub.
  if (!nobj->is<ArrayObject>() && !nobj->is<PlainObject>()) {
    return AttachDecision::NoAction;
  }

  // GetSparseElementHelper assumes that the target and the receiver
  // are the same.
  if (isSuper()) {
    return AttachDecision::NoAction;
  }

  // Here, we ensure that the prototype chain does not define any sparse
  // indexed properties on the shape lineage. This allows us to guard on
  // the shapes up the prototype chain to ensure that no indexed properties
  // exist outside of the dense elements.
  //
  // The `GeneratePrototypeHoleGuards` call below will guard on the shapes,
  // as well as ensure that no prototypes contain dense elements, allowing
  // us to perform a pure shape-search for out-of-bounds integer-indexed
  // properties on the receiver object.
  if (PrototypeMayHaveIndexedProperties(nobj)) {
    return AttachDecision::NoAction;
  }

  // Ensure that obj is an ArrayObject or PlainObject.
  if (nobj->is<ArrayObject>()) {
    writer.guardClass(objId, GuardClassKind::Array);
  } else {
    MOZ_ASSERT(nobj->is<PlainObject>());
    writer.guardClass(objId, GuardClassKind::PlainObject);
  }

  // The helper we are going to call only applies to non-dense elements.
  writer.guardIndexIsNotDenseElement(objId, indexId);

  // Ensures we are able to efficiently able to map to an integral jsid.
  writer.guardInt32IsNonNegative(indexId);

  // Shape guard the prototype chain to avoid shadowing indexes from appearing.
  // The helper function also ensures that the index does not appear within the
  // dense element set of the prototypes.
  GeneratePrototypeHoleGuards(writer, nobj, objId,
                              /* alwaysGuardFirstProto = */ true);

  // At this point, we are guaranteed that the indexed property will not
  // be found on one of the prototypes. We are assured that we only have
  // to check that the receiving object has the property.

  writer.callGetSparseElementResult(objId, indexId);
  writer.returnFromIC();

  trackAttached("GetProp.SparseElement");
  return AttachDecision::Attach;
}

// For Uint32Array we let the stub return an Int32 if we have not seen a
// double, to allow better codegen in Warp while avoiding bailout loops.
static bool ForceDoubleForUint32Array(TypedArrayObject* tarr, uint64_t index) {
  MOZ_ASSERT(index < tarr->length());

  if (tarr->type() != Scalar::Type::Uint32) {
    // Return value is only relevant for Uint32Array.
    return false;
  }

  Value res;
  MOZ_ALWAYS_TRUE(tarr->getElementPure(index, &res));
  MOZ_ASSERT(res.isNumber());
  return res.isDouble();
}

AttachDecision GetPropIRGenerator::tryAttachTypedArrayElement(
    HandleObject obj, ObjOperandId objId) {
  if (!obj->is<TypedArrayObject>()) {
    return AttachDecision::NoAction;
  }

  if (!idVal_.isNumber()) {
    return AttachDecision::NoAction;
  }

  TypedArrayObject* tarr = &obj->as<TypedArrayObject>();

  bool handleOOB = false;
  int64_t indexInt64;
  if (!ValueIsInt64Index(idVal_, &indexInt64) || indexInt64 < 0 ||
      uint64_t(indexInt64) >= tarr->length()) {
    handleOOB = true;
  }

  // If the number is not representable as an integer the result will be
  // |undefined| so we leave |forceDoubleForUint32| as false.
  bool forceDoubleForUint32 = false;
  if (!handleOOB) {
    uint64_t index = uint64_t(indexInt64);
    forceDoubleForUint32 = ForceDoubleForUint32Array(tarr, index);
  }

  writer.guardShapeForClass(objId, tarr->shape());

  ValOperandId keyId = getElemKeyValueId();
  IntPtrOperandId intPtrIndexId = guardToIntPtrIndex(idVal_, keyId, handleOOB);

  writer.loadTypedArrayElementResult(objId, intPtrIndexId, tarr->type(),
                                     handleOOB, forceDoubleForUint32);
  writer.returnFromIC();

  trackAttached("GetProp.TypedElement");
  return AttachDecision::Attach;
}

AttachDecision GetPropIRGenerator::tryAttachGenericElement(
    HandleObject obj, ObjOperandId objId, uint32_t index,
    Int32OperandId indexId, ValOperandId receiverId) {
  if (!obj->is<NativeObject>()) {
    return AttachDecision::NoAction;
  }

#ifdef JS_CODEGEN_X86
  if (isSuper()) {
    // There aren't enough registers available on x86.
    return AttachDecision::NoAction;
  }
#endif

  // To allow other types to attach in the non-megamorphic case we test the
  // specific matching native receiver; however, once megamorphic we can attach
  // for any native
  if (mode_ == ICState::Mode::Megamorphic) {
    writer.guardIsNativeObject(objId);
  } else {
    NativeObject* nobj = &obj->as<NativeObject>();
    TestMatchingNativeReceiver(writer, nobj, objId);
  }
  writer.guardIndexIsNotDenseElement(objId, indexId);
  if (isSuper()) {
    writer.callNativeGetElementSuperResult(objId, indexId, receiverId);
  } else {
    writer.callNativeGetElementResult(objId, indexId);
  }
  writer.returnFromIC();

  trackAttached(mode_ == ICState::Mode::Megamorphic
                    ? "GenericElementMegamorphic"
                    : "GenericElement");
  return AttachDecision::Attach;
}

AttachDecision GetPropIRGenerator::tryAttachProxyElement(HandleObject obj,
                                                         ObjOperandId objId) {
  if (!obj->is<ProxyObject>()) {
    return AttachDecision::NoAction;
  }

  // The proxy stubs don't currently support |super| access.
  if (isSuper()) {
    return AttachDecision::NoAction;
  }

  writer.guardIsProxy(objId);

  // We are not guarding against DOM proxies here, because there is no other
  // specialized DOM IC we could attach.
  // We could call maybeEmitIdGuard here and then emit ProxyGetResult,
  // but for GetElem we prefer to attach a stub that can handle any Value
  // so we don't attach a new stub for every id.
  MOZ_ASSERT(cacheKind_ == CacheKind::GetElem);
  MOZ_ASSERT(!isSuper());
  writer.proxyGetByValueResult(objId, getElemKeyValueId());
  writer.returnFromIC();

  trackAttached("GetProp.ProxyElement");
  return AttachDecision::Attach;
}

void GetPropIRGenerator::trackAttached(const char* name) {
  stubName_ = name ? name : "NotAttached";
#ifdef JS_CACHEIR_SPEW
  if (const CacheIRSpewer::Guard& sp = CacheIRSpewer::Guard(*this, name)) {
    sp.valueProperty("base", val_);
    sp.valueProperty("property", idVal_);
  }
#endif
}

void IRGenerator::emitIdGuard(ValOperandId valId, const Value& idVal, jsid id) {
  if (id.isSymbol()) {
    MOZ_ASSERT(idVal.toSymbol() == id.toSymbol());
    SymbolOperandId symId = writer.guardToSymbol(valId);
    writer.guardSpecificSymbol(symId, id.toSymbol());
  } else {
    MOZ_ASSERT(id.isAtom());
    if (idVal.isUndefined()) {
      MOZ_ASSERT(id.isAtom(cx_->names().undefined));
      writer.guardIsUndefined(valId);
    } else if (idVal.isNull()) {
      MOZ_ASSERT(id.isAtom(cx_->names().null));
      writer.guardIsNull(valId);
    } else {
      MOZ_ASSERT(idVal.isString());
      StringOperandId strId = writer.guardToString(valId);
      writer.guardSpecificAtom(strId, id.toAtom());
    }
  }
}

void GetPropIRGenerator::maybeEmitIdGuard(jsid id) {
  if (cacheKind_ == CacheKind::GetProp ||
      cacheKind_ == CacheKind::GetPropSuper) {
    // Constant PropertyName, no guards necessary.
    MOZ_ASSERT(&idVal_.toString()->asAtom() == id.toAtom());
    return;
  }

  MOZ_ASSERT(cacheKind_ == CacheKind::GetElem ||
             cacheKind_ == CacheKind::GetElemSuper);
  emitIdGuard(getElemKeyValueId(), idVal_, id);
}

void SetPropIRGenerator::maybeEmitIdGuard(jsid id) {
  if (cacheKind_ == CacheKind::SetProp) {
    // Constant PropertyName, no guards necessary.
    MOZ_ASSERT(&idVal_.toString()->asAtom() == id.toAtom());
    return;
  }

  MOZ_ASSERT(cacheKind_ == CacheKind::SetElem);
  emitIdGuard(setElemKeyValueId(), idVal_, id);
}

GetNameIRGenerator::GetNameIRGenerator(JSContext* cx, HandleScript script,
                                       jsbytecode* pc, ICState state,
                                       HandleObject env,
                                       Handle<PropertyName*> name)
    : IRGenerator(cx, script, pc, CacheKind::GetName, state),
      env_(env),
      name_(name) {}

AttachDecision GetNameIRGenerator::tryAttachStub() {
  MOZ_ASSERT(cacheKind_ == CacheKind::GetName);

  AutoAssertNoPendingException aanpe(cx_);

  ObjOperandId envId(writer.setInputOperandId(0));
  RootedId id(cx_, NameToId(name_));

  TRY_ATTACH(tryAttachGlobalNameValue(envId, id));
  TRY_ATTACH(tryAttachGlobalNameGetter(envId, id));
  TRY_ATTACH(tryAttachEnvironmentName(envId, id));

  trackAttached(IRGenerator::NotAttached);
  return AttachDecision::NoAction;
}

static bool CanAttachGlobalName(JSContext* cx,
                                GlobalLexicalEnvironmentObject* globalLexical,
                                PropertyKey id, NativeObject** holder,
                                Maybe<PropertyInfo>* prop) {
  // The property must be found, and it must be found as a normal data property.
  NativeObject* current = globalLexical;
  while (true) {
    *prop = current->lookup(cx, id);
    if (prop->isSome()) {
      break;
    }

    if (current == globalLexical) {
      current = &globalLexical->global();
    } else {
      // In the browser the global prototype chain should be immutable.
      if (!current->staticPrototypeIsImmutable()) {
        return false;
      }

      JSObject* proto = current->staticPrototype();
      if (!proto || !proto->is<NativeObject>()) {
        return false;
      }

      current = &proto->as<NativeObject>();
    }
  }

  *holder = current;
  return true;
}

AttachDecision GetNameIRGenerator::tryAttachGlobalNameValue(ObjOperandId objId,
                                                            HandleId id) {
  if (!IsGlobalOp(JSOp(*pc_))) {
    return AttachDecision::NoAction;
  }
  MOZ_ASSERT(!script_->hasNonSyntacticScope());

  auto* globalLexical = &env_->as<GlobalLexicalEnvironmentObject>();

  NativeObject* holder = nullptr;
  Maybe<PropertyInfo> prop;
  if (!CanAttachGlobalName(cx_, globalLexical, id, &holder, &prop)) {
    return AttachDecision::NoAction;
  }

  // The property must be found, and it must be found as a normal data property.
  if (!prop->isDataProperty()) {
    return AttachDecision::NoAction;
  }

  // This might still be an uninitialized lexical.
  if (holder->getSlot(prop->slot()).isMagic()) {
    return AttachDecision::NoAction;
  }

  if (holder == globalLexical) {
    // There is no need to guard on the shape. Lexical bindings are
    // non-configurable, and this stub cannot be shared across globals.
    size_t dynamicSlotOffset =
        holder->dynamicSlotIndex(prop->slot()) * sizeof(Value);
    writer.loadDynamicSlotResult(objId, dynamicSlotOffset);
  } else if (holder == &globalLexical->global()) {
    MOZ_ASSERT(globalLexical->global().isGenerationCountedGlobal());
    writer.guardGlobalGeneration(
        globalLexical->global().generationCount(),
        globalLexical->global().addressOfGenerationCount());
    ObjOperandId holderId = writer.loadObject(holder);
#ifdef DEBUG
    writer.assertPropertyLookup(holderId, id, prop->slot());
#endif
    EmitLoadSlotResult(writer, holderId, holder, *prop);
  } else {
    // Check the prototype chain from the global to the holder
    // prototype. Ignore the global lexical scope as it doesn't figure
    // into the prototype chain. We guard on the global lexical
    // scope's shape independently.
    if (!IsCacheableGetPropSlot(&globalLexical->global(), holder, *prop)) {
      return AttachDecision::NoAction;
    }

    // Shape guard for global lexical.
    writer.guardShape(objId, globalLexical->shape());

    // Guard on the shape of the GlobalObject.
    ObjOperandId globalId = writer.loadObject(&globalLexical->global());
    writer.guardShape(globalId, globalLexical->global().shape());

    // Shape guard holder.
    ObjOperandId holderId = writer.loadObject(holder);
    writer.guardShape(holderId, holder->shape());

    EmitLoadSlotResult(writer, holderId, holder, *prop);
  }

  writer.returnFromIC();

  trackAttached("GetName.GlobalNameValue");
  return AttachDecision::Attach;
}

AttachDecision GetNameIRGenerator::tryAttachGlobalNameGetter(ObjOperandId objId,
                                                             HandleId id) {
  if (!IsGlobalOp(JSOp(*pc_))) {
    return AttachDecision::NoAction;
  }
  MOZ_ASSERT(!script_->hasNonSyntacticScope());

  Handle<GlobalLexicalEnvironmentObject*> globalLexical =
      env_.as<GlobalLexicalEnvironmentObject>();
  MOZ_ASSERT(globalLexical->isGlobal());

  NativeObject* holder = nullptr;
  Maybe<PropertyInfo> prop;
  if (!CanAttachGlobalName(cx_, globalLexical, id, &holder, &prop)) {
    return AttachDecision::NoAction;
  }

  if (holder == globalLexical) {
    return AttachDecision::NoAction;
  }

  GlobalObject* global = &globalLexical->global();

  NativeGetPropKind kind = IsCacheableGetPropCall(global, holder, *prop);
  if (kind != NativeGetPropKind::NativeGetter &&
      kind != NativeGetPropKind::ScriptedGetter) {
    return AttachDecision::NoAction;
  }

  bool needsWindowProxy =
      IsWindow(global) && GetterNeedsWindowProxyThis(holder, *prop);

  // Shape guard for global lexical.
  writer.guardShape(objId, globalLexical->shape());

  // Guard on the shape of the GlobalObject.
  ObjOperandId globalId = writer.loadEnclosingEnvironment(objId);
  writer.guardShape(globalId, global->shape());

  if (holder != global) {
    // Shape guard holder.
    ObjOperandId holderId = writer.loadObject(holder);
    writer.guardShape(holderId, holder->shape());
    EmitGuardGetterSetterSlot(writer, holder, *prop, holderId,
                              /* holderIsConstant = */ true);
  } else {
    // Note: pass true for |holderIsConstant| because the holder must be the
    // current global object.
    EmitGuardGetterSetterSlot(writer, holder, *prop, globalId,
                              /* holderIsConstant = */ true);
  }

  if (CanAttachDOMGetterSetter(cx_, JSJitInfo::Getter, global, holder, *prop,
                               mode_)) {
    // The global shape guard above ensures the instance JSClass is correct.
    MOZ_ASSERT(!needsWindowProxy);
    EmitCallDOMGetterResultNoGuards(writer, holder, *prop, globalId);
    trackAttached("GetName.GlobalNameDOMGetter");
  } else {
    ObjOperandId receiverObjId;
    if (needsWindowProxy) {
      MOZ_ASSERT(cx_->global()->maybeWindowProxy());
      receiverObjId = writer.loadObject(cx_->global()->maybeWindowProxy());
    } else {
      receiverObjId = globalId;
    }
    ValOperandId receiverId = writer.boxObject(receiverObjId);
    EmitCallGetterResultNoGuards(cx_, writer, kind, global, holder, *prop,
                                 receiverId);
    trackAttached("GetName.GlobalNameGetter");
  }

  return AttachDecision::Attach;
}

static bool NeedEnvironmentShapeGuard(JSContext* cx, JSObject* envObj) {
  if (!envObj->is<CallObject>()) {
    return true;
  }

  // We can skip a guard on the call object if the script's bindings are
  // guaranteed to be immutable (and thus cannot introduce shadowing variables).
  // If the function is a relazified self-hosted function it has no BaseScript
  // and we pessimistically create the guard.
  CallObject* callObj = &envObj->as<CallObject>();
  JSFunction* fun = &callObj->callee();
  if (!fun->hasBaseScript() || fun->baseScript()->funHasExtensibleScope() ||
      DebugEnvironments::hasDebugEnvironment(cx, *callObj)) {
    return true;
  }

  return false;
}

static ValOperandId EmitLoadEnvironmentSlot(CacheIRWriter& writer,
                                            NativeObject* holder,
                                            ObjOperandId holderId,
                                            uint32_t slot) {
  if (holder->isFixedSlot(slot)) {
    return writer.loadFixedSlot(holderId,
                                NativeObject::getFixedSlotOffset(slot));
  }
  size_t dynamicSlotIndex = holder->dynamicSlotIndex(slot);
  return writer.loadDynamicSlot(holderId, dynamicSlotIndex);
}

AttachDecision GetNameIRGenerator::tryAttachEnvironmentName(ObjOperandId objId,
                                                            HandleId id) {
  if (IsGlobalOp(JSOp(*pc_)) || script_->hasNonSyntacticScope()) {
    return AttachDecision::NoAction;
  }

  JSObject* env = env_;
  Maybe<PropertyInfo> prop;
  NativeObject* holder = nullptr;

  while (env) {
    if (env->is<GlobalObject>()) {
      prop = env->as<GlobalObject>().lookup(cx_, id);
      if (prop.isSome()) {
        break;
      }
      return AttachDecision::NoAction;
    }

    if (!env->is<EnvironmentObject>() || env->is<WithEnvironmentObject>()) {
      return AttachDecision::NoAction;
    }

    // Check for an 'own' property on the env. There is no need to
    // check the prototype as non-with scopes do not inherit properties
    // from any prototype.
    prop = env->as<NativeObject>().lookup(cx_, id);
    if (prop.isSome()) {
      break;
    }

    env = env->enclosingEnvironment();
  }

  holder = &env->as<NativeObject>();
  if (!IsCacheableGetPropSlot(holder, holder, *prop)) {
    return AttachDecision::NoAction;
  }
  if (holder->getSlot(prop->slot()).isMagic()) {
    MOZ_ASSERT(holder->is<EnvironmentObject>());
    return AttachDecision::NoAction;
  }

  ObjOperandId lastObjId = objId;
  env = env_;
  while (env) {
    if (NeedEnvironmentShapeGuard(cx_, env)) {
      writer.guardShape(lastObjId, env->shape());
    }

    if (env == holder) {
      break;
    }

    lastObjId = writer.loadEnclosingEnvironment(lastObjId);
    env = env->enclosingEnvironment();
  }

  ValOperandId resId =
      EmitLoadEnvironmentSlot(writer, holder, lastObjId, prop->slot());
  if (holder->is<EnvironmentObject>()) {
    writer.guardIsNotUninitializedLexical(resId);
  }
  writer.loadOperandResult(resId);
  writer.returnFromIC();

  trackAttached("GetName.EnvironmentName");
  return AttachDecision::Attach;
}

void GetNameIRGenerator::trackAttached(const char* name) {
  stubName_ = name ? name : "NotAttached";
#ifdef JS_CACHEIR_SPEW
  if (const CacheIRSpewer::Guard& sp = CacheIRSpewer::Guard(*this, name)) {
    sp.valueProperty("base", ObjectValue(*env_));
    sp.valueProperty("property", StringValue(name_));
  }
#endif
}

BindNameIRGenerator::BindNameIRGenerator(JSContext* cx, HandleScript script,
                                         jsbytecode* pc, ICState state,
                                         HandleObject env,
                                         Handle<PropertyName*> name)
    : IRGenerator(cx, script, pc, CacheKind::BindName, state),
      env_(env),
      name_(name) {}

AttachDecision BindNameIRGenerator::tryAttachStub() {
  MOZ_ASSERT(cacheKind_ == CacheKind::BindName);

  AutoAssertNoPendingException aanpe(cx_);

  ObjOperandId envId(writer.setInputOperandId(0));
  RootedId id(cx_, NameToId(name_));

  TRY_ATTACH(tryAttachGlobalName(envId, id));
  TRY_ATTACH(tryAttachEnvironmentName(envId, id));

  trackAttached(IRGenerator::NotAttached);
  return AttachDecision::NoAction;
}

AttachDecision BindNameIRGenerator::tryAttachGlobalName(ObjOperandId objId,
                                                        HandleId id) {
  if (!IsGlobalOp(JSOp(*pc_))) {
    return AttachDecision::NoAction;
  }
  MOZ_ASSERT(!script_->hasNonSyntacticScope());

  Handle<GlobalLexicalEnvironmentObject*> globalLexical =
      env_.as<GlobalLexicalEnvironmentObject>();
  MOZ_ASSERT(globalLexical->isGlobal());

  JSObject* result = nullptr;
  if (Maybe<PropertyInfo> prop = globalLexical->lookup(cx_, id)) {
    // If this is an uninitialized lexical or a const, we need to return a
    // RuntimeLexicalErrorObject.
    if (globalLexical->getSlot(prop->slot()).isMagic() || !prop->writable()) {
      return AttachDecision::NoAction;
    }
    result = globalLexical;
  } else {
    result = &globalLexical->global();
  }

  if (result == globalLexical) {
    // Lexical bindings are non-configurable so we can just return the
    // global lexical.
    writer.loadObjectResult(objId);
  } else {
    // If the property exists on the global and is non-configurable, it cannot
    // be shadowed by the lexical scope so we can just return the global without
    // a shape guard.
    Maybe<PropertyInfo> prop = result->as<GlobalObject>().lookup(cx_, id);
    if (prop.isNothing() || prop->configurable()) {
      writer.guardShape(objId, globalLexical->shape());
    }
    ObjOperandId globalId = writer.loadEnclosingEnvironment(objId);
    writer.loadObjectResult(globalId);
  }
  writer.returnFromIC();

  trackAttached("BindName.GlobalName");
  return AttachDecision::Attach;
}

AttachDecision BindNameIRGenerator::tryAttachEnvironmentName(ObjOperandId objId,
                                                             HandleId id) {
  if (IsGlobalOp(JSOp(*pc_)) || script_->hasNonSyntacticScope()) {
    return AttachDecision::NoAction;
  }

  JSObject* env = env_;
  Maybe<PropertyInfo> prop;
  while (true) {
    if (!env->is<GlobalObject>() && !env->is<EnvironmentObject>()) {
      return AttachDecision::NoAction;
    }
    if (env->is<WithEnvironmentObject>()) {
      return AttachDecision::NoAction;
    }

    // When we reach an unqualified variables object (like the global) we
    // have to stop looking and return that object.
    if (env->isUnqualifiedVarObj()) {
      break;
    }

    // Check for an 'own' property on the env. There is no need to
    // check the prototype as non-with scopes do not inherit properties
    // from any prototype.
    prop = env->as<NativeObject>().lookup(cx_, id);
    if (prop.isSome()) {
      break;
    }

    env = env->enclosingEnvironment();
  }

  // If this is an uninitialized lexical or a const, we need to return a
  // RuntimeLexicalErrorObject.
  auto* holder = &env->as<NativeObject>();
  if (prop.isSome() && holder->is<EnvironmentObject>() &&
      (holder->getSlot(prop->slot()).isMagic() || !prop->writable())) {
    return AttachDecision::NoAction;
  }

  ObjOperandId lastObjId = objId;
  env = env_;
  while (env) {
    if (NeedEnvironmentShapeGuard(cx_, env) && !env->is<GlobalObject>()) {
      writer.guardShape(lastObjId, env->shape());
    }

    if (env == holder) {
      break;
    }

    lastObjId = writer.loadEnclosingEnvironment(lastObjId);
    env = env->enclosingEnvironment();
  }

  if (prop.isSome() && holder->is<EnvironmentObject>()) {
    ValOperandId valId =
        EmitLoadEnvironmentSlot(writer, holder, lastObjId, prop->slot());
    writer.guardIsNotUninitializedLexical(valId);
  }

  writer.loadObjectResult(lastObjId);
  writer.returnFromIC();

  trackAttached("BindName.EnvironmentName");
  return AttachDecision::Attach;
}

void BindNameIRGenerator::trackAttached(const char* name) {
  stubName_ = name ? name : "NotAttached";
#ifdef JS_CACHEIR_SPEW
  if (const CacheIRSpewer::Guard& sp = CacheIRSpewer::Guard(*this, name)) {
    sp.valueProperty("base", ObjectValue(*env_));
    sp.valueProperty("property", StringValue(name_));
  }
#endif
}

HasPropIRGenerator::HasPropIRGenerator(JSContext* cx, HandleScript script,
                                       jsbytecode* pc, ICState state,
                                       CacheKind cacheKind, HandleValue idVal,
                                       HandleValue val)
    : IRGenerator(cx, script, pc, cacheKind, state), val_(val), idVal_(idVal) {}

AttachDecision HasPropIRGenerator::tryAttachDense(HandleObject obj,
                                                  ObjOperandId objId,
                                                  uint32_t index,
                                                  Int32OperandId indexId) {
  if (!obj->is<NativeObject>()) {
    return AttachDecision::NoAction;
  }

  NativeObject* nobj = &obj->as<NativeObject>();
  if (!nobj->containsDenseElement(index)) {
    return AttachDecision::NoAction;
  }

  if (mode_ == ICState::Mode::Megamorphic) {
    writer.guardIsNativeObject(objId);
  } else {
    // Guard shape to ensure object class is NativeObject.
    TestMatchingNativeReceiver(writer, nobj, objId);
  }
  writer.loadDenseElementExistsResult(objId, indexId);
  writer.returnFromIC();

  trackAttached("HasProp.Dense");
  return AttachDecision::Attach;
}

AttachDecision HasPropIRGenerator::tryAttachDenseHole(HandleObject obj,
                                                      ObjOperandId objId,
                                                      uint32_t index,
                                                      Int32OperandId indexId) {
  bool hasOwn = (cacheKind_ == CacheKind::HasOwn);
  OwnProperty ownProp = hasOwn ? OwnProperty::Yes : OwnProperty::No;

  if (!obj->is<NativeObject>()) {
    return AttachDecision::NoAction;
  }

  NativeObject* nobj = &obj->as<NativeObject>();
  if (nobj->containsDenseElement(index)) {
    return AttachDecision::NoAction;
  }
  if (!CanAttachDenseElementHole(nobj, ownProp)) {
    return AttachDecision::NoAction;
  }

  // Guard shape to ensure class is NativeObject and to prevent non-dense
  // elements being added. Also ensures prototype doesn't change if dynamic
  // checks aren't emitted.
  TestMatchingNativeReceiver(writer, nobj, objId);

  // Generate prototype guards if needed. This includes monitoring that
  // properties were not added in the chain.
  if (!hasOwn) {
    GeneratePrototypeHoleGuards(writer, nobj, objId,
                                /* alwaysGuardFirstProto = */ false);
  }

  writer.loadDenseElementHoleExistsResult(objId, indexId);
  writer.returnFromIC();

  trackAttached("HasProp.DenseHole");
  return AttachDecision::Attach;
}

AttachDecision HasPropIRGenerator::tryAttachSparse(HandleObject obj,
                                                   ObjOperandId objId,
                                                   Int32OperandId indexId) {
  bool hasOwn = (cacheKind_ == CacheKind::HasOwn);
  OwnProperty ownProp = hasOwn ? OwnProperty::Yes : OwnProperty::No;

  if (!obj->is<NativeObject>()) {
    return AttachDecision::NoAction;
  }
  auto* nobj = &obj->as<NativeObject>();

  if (!nobj->isIndexed()) {
    return AttachDecision::NoAction;
  }
  if (!CanAttachDenseElementHole(nobj, ownProp, AllowIndexedReceiver::Yes)) {
    return AttachDecision::NoAction;
  }

  // Guard that this is a native object.
  writer.guardIsNativeObject(objId);

  // Generate prototype guards if needed. This includes monitoring that
  // properties were not added in the chain.
  if (!hasOwn) {
    GeneratePrototypeHoleGuards(writer, nobj, objId,
                                /* alwaysGuardFirstProto = */ true);
  }

  // Because of the prototype guard we know that the prototype chain
  // does not include any dense or sparse (i.e indexed) properties.
  writer.callObjectHasSparseElementResult(objId, indexId);
  writer.returnFromIC();

  trackAttached("HasProp.Sparse");
  return AttachDecision::Attach;
}

AttachDecision HasPropIRGenerator::tryAttachArgumentsObjectArg(
    HandleObject obj, ObjOperandId objId, Int32OperandId indexId) {
  bool hasOwn = (cacheKind_ == CacheKind::HasOwn);
  OwnProperty ownProp = hasOwn ? OwnProperty::Yes : OwnProperty::No;

  if (!obj->is<ArgumentsObject>()) {
    return AttachDecision::NoAction;
  }
  auto* args = &obj->as<ArgumentsObject>();

  // No elements must have been overridden or deleted.
  if (args->hasOverriddenElement()) {
    return AttachDecision::NoAction;
  }

  if (!CanAttachDenseElementHole(args, ownProp, AllowIndexedReceiver::Yes,
                                 AllowExtraReceiverProperties::Yes)) {
    return AttachDecision::NoAction;
  }

  if (args->is<MappedArgumentsObject>()) {
    writer.guardClass(objId, GuardClassKind::MappedArguments);
  } else {
    MOZ_ASSERT(args->is<UnmappedArgumentsObject>());
    writer.guardClass(objId, GuardClassKind::UnmappedArguments);
  }

  if (!hasOwn) {
    GeneratePrototypeHoleGuards(writer, args, objId,
                                /* alwaysGuardFirstProto = */ true);
  }

  writer.loadArgumentsObjectArgExistsResult(objId, indexId);
  writer.returnFromIC();

  trackAttached("HasProp.ArgumentsObjectArg");
  return AttachDecision::Attach;
}

AttachDecision HasPropIRGenerator::tryAttachNamedProp(HandleObject obj,
                                                      ObjOperandId objId,
                                                      HandleId key,
                                                      ValOperandId keyId) {
  bool hasOwn = (cacheKind_ == CacheKind::HasOwn);

  NativeObject* holder = nullptr;
  PropertyResult prop;

  if (hasOwn) {
    if (!LookupOwnPropertyPure(cx_, obj, key, &prop)) {
      return AttachDecision::NoAction;
    }

    holder = &obj->as<NativeObject>();
  } else {
    if (!LookupPropertyPure(cx_, obj, key, &holder, &prop)) {
      return AttachDecision::NoAction;
    }
  }
  if (prop.isNotFound()) {
    return AttachDecision::NoAction;
  }
  auto* nobj = &obj->as<NativeObject>();

  TRY_ATTACH(tryAttachMegamorphic(objId, keyId));
  TRY_ATTACH(tryAttachNative(nobj, objId, key, keyId, prop, holder));

  return AttachDecision::NoAction;
}

AttachDecision HasPropIRGenerator::tryAttachMegamorphic(ObjOperandId objId,
                                                        ValOperandId keyId) {
  bool hasOwn = (cacheKind_ == CacheKind::HasOwn);

  if (mode_ != ICState::Mode::Megamorphic) {
    return AttachDecision::NoAction;
  }

  writer.megamorphicHasPropResult(objId, keyId, hasOwn);
  writer.returnFromIC();
  trackAttached("HasProp.Megamorphic");
  return AttachDecision::Attach;
}

AttachDecision HasPropIRGenerator::tryAttachNative(NativeObject* obj,
                                                   ObjOperandId objId, jsid key,
                                                   ValOperandId keyId,
                                                   PropertyResult prop,
                                                   NativeObject* holder) {
  MOZ_ASSERT(IsCacheableProtoChain(obj, holder));

  if (!prop.isNativeProperty()) {
    return AttachDecision::NoAction;
  }

  emitIdGuard(keyId, idVal_, key);
  EmitReadSlotGuard(writer, obj, holder, objId);
  writer.loadBooleanResult(true);
  writer.returnFromIC();

  trackAttached("HasProp.Native");
  return AttachDecision::Attach;
}

AttachDecision HasPropIRGenerator::tryAttachTypedArray(HandleObject obj,
                                                       ObjOperandId objId,
                                                       ValOperandId keyId) {
  if (!obj->is<TypedArrayObject>()) {
    return AttachDecision::NoAction;
  }

  int64_t index;
  if (!ValueIsInt64Index(idVal_, &index)) {
    return AttachDecision::NoAction;
  }

  writer.guardIsTypedArray(objId);
  IntPtrOperandId intPtrIndexId =
      guardToIntPtrIndex(idVal_, keyId, /* supportOOB = */ true);
  writer.loadTypedArrayElementExistsResult(objId, intPtrIndexId);
  writer.returnFromIC();

  trackAttached("HasProp.TypedArrayObject");
  return AttachDecision::Attach;
}

AttachDecision HasPropIRGenerator::tryAttachSlotDoesNotExist(
    NativeObject* obj, ObjOperandId objId, jsid key, ValOperandId keyId) {
  bool hasOwn = (cacheKind_ == CacheKind::HasOwn);

  emitIdGuard(keyId, idVal_, key);
  if (hasOwn) {
    TestMatchingNativeReceiver(writer, obj, objId);
  } else {
    EmitMissingPropGuard(writer, obj, objId);
  }
  writer.loadBooleanResult(false);
  writer.returnFromIC();

  trackAttached("HasProp.DoesNotExist");
  return AttachDecision::Attach;
}

AttachDecision HasPropIRGenerator::tryAttachDoesNotExist(HandleObject obj,
                                                         ObjOperandId objId,
                                                         HandleId key,
                                                         ValOperandId keyId) {
  bool hasOwn = (cacheKind_ == CacheKind::HasOwn);

  // Check that property doesn't exist on |obj| or it's prototype chain. These
  // checks allow NativeObjects with a NativeObject prototype chain. They return
  // NoAction if unknown such as resolve hooks or proxies.
  if (hasOwn) {
    if (!CheckHasNoSuchOwnProperty(cx_, obj, key)) {
      return AttachDecision::NoAction;
    }
  } else {
    if (!CheckHasNoSuchProperty(cx_, obj, key)) {
      return AttachDecision::NoAction;
    }
  }
  auto* nobj = &obj->as<NativeObject>();

  TRY_ATTACH(tryAttachMegamorphic(objId, keyId));
  TRY_ATTACH(tryAttachSlotDoesNotExist(nobj, objId, key, keyId));

  return AttachDecision::NoAction;
}

AttachDecision HasPropIRGenerator::tryAttachProxyElement(HandleObject obj,
                                                         ObjOperandId objId,
                                                         ValOperandId keyId) {
  bool hasOwn = (cacheKind_ == CacheKind::HasOwn);

  if (!obj->is<ProxyObject>()) {
    return AttachDecision::NoAction;
  }

  writer.guardIsProxy(objId);
  writer.proxyHasPropResult(objId, keyId, hasOwn);
  writer.returnFromIC();

  trackAttached("HasProp.ProxyElement");
  return AttachDecision::Attach;
}

AttachDecision HasPropIRGenerator::tryAttachStub() {
  MOZ_ASSERT(cacheKind_ == CacheKind::In || cacheKind_ == CacheKind::HasOwn);

  AutoAssertNoPendingException aanpe(cx_);

  // NOTE: Argument order is PROPERTY, OBJECT
  ValOperandId keyId(writer.setInputOperandId(0));
  ValOperandId valId(writer.setInputOperandId(1));

  if (!val_.isObject()) {
    trackAttached(IRGenerator::NotAttached);
    return AttachDecision::NoAction;
  }
  RootedObject obj(cx_, &val_.toObject());
  ObjOperandId objId = writer.guardToObject(valId);

  // Optimize Proxies
  TRY_ATTACH(tryAttachProxyElement(obj, objId, keyId));

  RootedId id(cx_);
  bool nameOrSymbol;
  if (!ValueToNameOrSymbolId(cx_, idVal_, &id, &nameOrSymbol)) {
    cx_->clearPendingException();
    return AttachDecision::NoAction;
  }

  if (nameOrSymbol) {
    TRY_ATTACH(tryAttachNamedProp(obj, objId, id, keyId));
    TRY_ATTACH(tryAttachDoesNotExist(obj, objId, id, keyId));

    trackAttached(IRGenerator::NotAttached);
    return AttachDecision::NoAction;
  }

  TRY_ATTACH(tryAttachTypedArray(obj, objId, keyId));

  uint32_t index;
  Int32OperandId indexId;
  if (maybeGuardInt32Index(idVal_, keyId, &index, &indexId)) {
    TRY_ATTACH(tryAttachDense(obj, objId, index, indexId));
    TRY_ATTACH(tryAttachDenseHole(obj, objId, index, indexId));
    TRY_ATTACH(tryAttachSparse(obj, objId, indexId));
    TRY_ATTACH(tryAttachArgumentsObjectArg(obj, objId, indexId));

    trackAttached(IRGenerator::NotAttached);
    return AttachDecision::NoAction;
  }

  trackAttached(IRGenerator::NotAttached);
  return AttachDecision::NoAction;
}

void HasPropIRGenerator::trackAttached(const char* name) {
  stubName_ = name ? name : "NotAttached";
#ifdef JS_CACHEIR_SPEW
  if (const CacheIRSpewer::Guard& sp = CacheIRSpewer::Guard(*this, name)) {
    sp.valueProperty("base", val_);
    sp.valueProperty("property", idVal_);
  }
#endif
}

CheckPrivateFieldIRGenerator::CheckPrivateFieldIRGenerator(
    JSContext* cx, HandleScript script, jsbytecode* pc, ICState state,
    CacheKind cacheKind, HandleValue idVal, HandleValue val)
    : IRGenerator(cx, script, pc, cacheKind, state), val_(val), idVal_(idVal) {
  MOZ_ASSERT(idVal.isSymbol() && idVal.toSymbol()->isPrivateName());
}

AttachDecision CheckPrivateFieldIRGenerator::tryAttachStub() {
  AutoAssertNoPendingException aanpe(cx_);

  ValOperandId valId(writer.setInputOperandId(0));
  ValOperandId keyId(writer.setInputOperandId(1));

  if (!val_.isObject()) {
    trackAttached(IRGenerator::NotAttached);
    return AttachDecision::NoAction;
  }
  JSObject* obj = &val_.toObject();
  ObjOperandId objId = writer.guardToObject(valId);
  PropertyKey key = PropertyKey::Symbol(idVal_.toSymbol());

  ThrowCondition condition;
  ThrowMsgKind msgKind;
  GetCheckPrivateFieldOperands(pc_, &condition, &msgKind);

  PropertyResult prop;
  if (!LookupOwnPropertyPure(cx_, obj, key, &prop)) {
    return AttachDecision::NoAction;
  }

  if (CheckPrivateFieldWillThrow(condition, prop.isFound())) {
    // Don't attach a stub if the operation will throw.
    return AttachDecision::NoAction;
  }

  auto* nobj = &obj->as<NativeObject>();

  TRY_ATTACH(tryAttachNative(nobj, objId, key, keyId, prop));

  return AttachDecision::NoAction;
}

AttachDecision CheckPrivateFieldIRGenerator::tryAttachNative(
    NativeObject* obj, ObjOperandId objId, jsid key, ValOperandId keyId,
    PropertyResult prop) {
  MOZ_ASSERT(prop.isNativeProperty() || prop.isNotFound());

  emitIdGuard(keyId, idVal_, key);
  TestMatchingNativeReceiver(writer, obj, objId);
  writer.loadBooleanResult(prop.isFound());
  writer.returnFromIC();

  trackAttached("CheckPrivateField.Native");
  return AttachDecision::Attach;
}

void CheckPrivateFieldIRGenerator::trackAttached(const char* name) {
  stubName_ = name ? name : "NotAttached";
#ifdef JS_CACHEIR_SPEW
  if (const CacheIRSpewer::Guard& sp = CacheIRSpewer::Guard(*this, name)) {
    sp.valueProperty("base", val_);
    sp.valueProperty("property", idVal_);
  }
#endif
}

bool IRGenerator::maybeGuardInt32Index(const Value& index, ValOperandId indexId,
                                       uint32_t* int32Index,
                                       Int32OperandId* int32IndexId) {
  if (index.isNumber()) {
    int32_t indexSigned;
    if (index.isInt32()) {
      indexSigned = index.toInt32();
    } else {
      // We allow negative zero here.
      if (!mozilla::NumberEqualsInt32(index.toDouble(), &indexSigned)) {
        return false;
      }
    }

    if (indexSigned < 0) {
      return false;
    }

    *int32Index = uint32_t(indexSigned);
    *int32IndexId = writer.guardToInt32Index(indexId);
    return true;
  }

  if (index.isString()) {
    int32_t indexSigned = GetIndexFromString(index.toString());
    if (indexSigned < 0) {
      return false;
    }

    StringOperandId strId = writer.guardToString(indexId);
    *int32Index = uint32_t(indexSigned);
    *int32IndexId = writer.guardStringToIndex(strId);
    return true;
  }

  return false;
}

SetPropIRGenerator::SetPropIRGenerator(JSContext* cx, HandleScript script,
                                       jsbytecode* pc, CacheKind cacheKind,
                                       ICState state, HandleValue lhsVal,
                                       HandleValue idVal, HandleValue rhsVal)
    : IRGenerator(cx, script, pc, cacheKind, state),
      lhsVal_(lhsVal),
      idVal_(idVal),
      rhsVal_(rhsVal) {}

AttachDecision SetPropIRGenerator::tryAttachStub() {
  AutoAssertNoPendingException aanpe(cx_);

  ValOperandId objValId(writer.setInputOperandId(0));
  ValOperandId rhsValId;
  if (cacheKind_ == CacheKind::SetProp) {
    rhsValId = ValOperandId(writer.setInputOperandId(1));
  } else {
    MOZ_ASSERT(cacheKind_ == CacheKind::SetElem);
    MOZ_ASSERT(setElemKeyValueId().id() == 1);
    writer.setInputOperandId(1);
    rhsValId = ValOperandId(writer.setInputOperandId(2));
  }

  RootedId id(cx_);
  bool nameOrSymbol;
  if (!ValueToNameOrSymbolId(cx_, idVal_, &id, &nameOrSymbol)) {
    cx_->clearPendingException();
    return AttachDecision::NoAction;
  }

  if (lhsVal_.isObject()) {
    RootedObject obj(cx_, &lhsVal_.toObject());

    ObjOperandId objId = writer.guardToObject(objValId);
    if (IsPropertySetOp(JSOp(*pc_))) {
      TRY_ATTACH(tryAttachMegamorphicSetElement(obj, objId, rhsValId));
    }
    if (nameOrSymbol) {
      TRY_ATTACH(tryAttachNativeSetSlot(obj, objId, id, rhsValId));
      if (IsPropertySetOp(JSOp(*pc_))) {
        TRY_ATTACH(tryAttachSetArrayLength(obj, objId, id, rhsValId));
        TRY_ATTACH(tryAttachSetter(obj, objId, id, rhsValId));
        TRY_ATTACH(tryAttachWindowProxy(obj, objId, id, rhsValId));
        TRY_ATTACH(tryAttachProxy(obj, objId, id, rhsValId));
        TRY_ATTACH(tryAttachMegamorphicSetSlot(obj, objId, id, rhsValId));
      }
      if (canAttachAddSlotStub(obj, id)) {
        deferType_ = DeferType::AddSlot;
        return AttachDecision::Deferred;
      }
      return AttachDecision::NoAction;
    }

    MOZ_ASSERT(cacheKind_ == CacheKind::SetElem);

    if (IsPropertySetOp(JSOp(*pc_))) {
      TRY_ATTACH(tryAttachProxyElement(obj, objId, rhsValId));
    }

    TRY_ATTACH(tryAttachSetTypedArrayElement(obj, objId, rhsValId));

    uint32_t index;
    Int32OperandId indexId;
    if (maybeGuardInt32Index(idVal_, setElemKeyValueId(), &index, &indexId)) {
      TRY_ATTACH(
          tryAttachSetDenseElement(obj, objId, index, indexId, rhsValId));
      TRY_ATTACH(
          tryAttachSetDenseElementHole(obj, objId, index, indexId, rhsValId));
      TRY_ATTACH(tryAttachAddOrUpdateSparseElement(obj, objId, index, indexId,
                                                   rhsValId));
      return AttachDecision::NoAction;
    }
  }
  return AttachDecision::NoAction;
}

static void EmitStoreSlotAndReturn(CacheIRWriter& writer, ObjOperandId objId,
                                   NativeObject* nobj, PropertyInfo prop,
                                   ValOperandId rhsId) {
  if (nobj->isFixedSlot(prop.slot())) {
    size_t offset = NativeObject::getFixedSlotOffset(prop.slot());
    writer.storeFixedSlot(objId, offset, rhsId);
  } else {
    size_t offset = nobj->dynamicSlotIndex(prop.slot()) * sizeof(Value);
    writer.storeDynamicSlot(objId, offset, rhsId);
  }
  writer.returnFromIC();
}

static Maybe<PropertyInfo> LookupShapeForSetSlot(JSOp op, NativeObject* obj,
                                                 jsid id) {
  Maybe<PropertyInfo> prop = obj->lookupPure(id);
  if (prop.isNothing() || !prop->isDataProperty() || !prop->writable()) {
    return mozilla::Nothing();
  }

  // If this is a property init operation, the property's attributes may have to
  // be changed too, so make sure the current flags match.
  if (IsPropertyInitOp(op)) {
    // Don't support locked init operations.
    if (IsLockedInitOp(op)) {
      return mozilla::Nothing();
    }

    // Can't redefine a non-configurable property.
    if (!prop->configurable()) {
      return mozilla::Nothing();
    }

    // Make sure the enumerable flag matches the init operation.
    if (IsHiddenInitOp(op) == prop->enumerable()) {
      return mozilla::Nothing();
    }
  }

  return prop;
}

static bool CanAttachNativeSetSlot(JSOp op, JSObject* obj, PropertyKey id,
                                   Maybe<PropertyInfo>* prop) {
  if (!obj->is<NativeObject>()) {
    return false;
  }

  *prop = LookupShapeForSetSlot(op, &obj->as<NativeObject>(), id);
  return prop->isSome();
}

// There is no need to guard on the shape. Global lexical bindings are
// non-configurable and can not be shadowed.
static bool IsGlobalLexicalSetGName(JSOp op, NativeObject* obj,
                                    PropertyInfo prop) {
  // Ensure that the env can't change.
  if (op != JSOp::SetGName && op != JSOp::StrictSetGName) {
    return false;
  }

  if (!obj->is<GlobalLexicalEnvironmentObject>()) {
    return false;
  }

  // Uninitialized let bindings use a RuntimeLexicalErrorObject.
  MOZ_ASSERT(!obj->getSlot(prop.slot()).isMagic());
  MOZ_ASSERT(prop.writable());
  MOZ_ASSERT(!prop.configurable());
  return true;
}

AttachDecision SetPropIRGenerator::tryAttachNativeSetSlot(HandleObject obj,
                                                          ObjOperandId objId,
                                                          HandleId id,
                                                          ValOperandId rhsId) {
  Maybe<PropertyInfo> prop;
  if (!CanAttachNativeSetSlot(JSOp(*pc_), obj, id, &prop)) {
    return AttachDecision::NoAction;
  }

  if (mode_ == ICState::Mode::Megamorphic && cacheKind_ == CacheKind::SetProp &&
      IsPropertySetOp(JSOp(*pc_))) {
    return AttachDecision::NoAction;
  }

  maybeEmitIdGuard(id);

  NativeObject* nobj = &obj->as<NativeObject>();
  if (!IsGlobalLexicalSetGName(JSOp(*pc_), nobj, *prop)) {
    TestMatchingNativeReceiver(writer, nobj, objId);
  }
  EmitStoreSlotAndReturn(writer, objId, nobj, *prop, rhsId);

  trackAttached("SetProp.NativeSlot");
  return AttachDecision::Attach;
}

OperandId IRGenerator::emitNumericGuard(ValOperandId valId, Scalar::Type type) {
  switch (type) {
    case Scalar::Int8:
    case Scalar::Uint8:
    case Scalar::Int16:
    case Scalar::Uint16:
    case Scalar::Int32:
    case Scalar::Uint32:
      return writer.guardToInt32ModUint32(valId);

    case Scalar::Float32:
    case Scalar::Float64:
      return writer.guardIsNumber(valId);

    case Scalar::Uint8Clamped:
      return writer.guardToUint8Clamped(valId);

    case Scalar::BigInt64:
    case Scalar::BigUint64:
      return writer.guardToBigInt(valId);

    case Scalar::MaxTypedArrayViewType:
    case Scalar::Int64:
    case Scalar::Simd128:
      break;
  }
  MOZ_CRASH("Unsupported TypedArray type");
}

static bool ValueIsNumeric(Scalar::Type type, const Value& val) {
  if (Scalar::isBigIntType(type)) {
    return val.isBigInt();
  }
  return val.isNumber();
}

void SetPropIRGenerator::trackAttached(const char* name) {
  stubName_ = name ? name : "NotAttached";
#ifdef JS_CACHEIR_SPEW
  if (const CacheIRSpewer::Guard& sp = CacheIRSpewer::Guard(*this, name)) {
    sp.opcodeProperty("op", JSOp(*pc_));
    sp.valueProperty("base", lhsVal_);
    sp.valueProperty("property", idVal_);
    sp.valueProperty("value", rhsVal_);
  }
#endif
}

static bool IsCacheableSetPropCallNative(NativeObject* obj,
                                         NativeObject* holder,
                                         PropertyInfo prop) {
  MOZ_ASSERT(IsCacheableProtoChain(obj, holder));

  if (!prop.isAccessorProperty()) {
    return false;
  }

  JSObject* setterObject = holder->getSetter(prop);
  if (!setterObject || !setterObject->is<JSFunction>()) {
    return false;
  }

  JSFunction& setter = setterObject->as<JSFunction>();
  if (!setter.isNativeWithoutJitEntry()) {
    return false;
  }

  if (setter.isClassConstructor()) {
    return false;
  }

  return true;
}

static bool IsCacheableSetPropCallScripted(NativeObject* obj,
                                           NativeObject* holder,
                                           PropertyInfo prop) {
  MOZ_ASSERT(IsCacheableProtoChain(obj, holder));

  if (!prop.isAccessorProperty()) {
    return false;
  }

  JSObject* setterObject = holder->getSetter(prop);
  if (!setterObject || !setterObject->is<JSFunction>()) {
    return false;
  }

  JSFunction& setter = setterObject->as<JSFunction>();
  if (setter.isClassConstructor()) {
    return false;
  }

  // Scripted functions and natives with JIT entry can use the scripted path.
  return setter.hasJitEntry();
}

static bool CanAttachSetter(JSContext* cx, jsbytecode* pc, JSObject* obj,
                            PropertyKey id, NativeObject** holder,
                            Maybe<PropertyInfo>* propInfo) {
  // Don't attach a setter stub for ops like JSOp::InitElem.
  MOZ_ASSERT(IsPropertySetOp(JSOp(*pc)));

  PropertyResult prop;
  if (!LookupPropertyPure(cx, obj, id, holder, &prop)) {
    return false;
  }
  auto* nobj = &obj->as<NativeObject>();

  if (!prop.isNativeProperty()) {
    return false;
  }

  if (!IsCacheableSetPropCallScripted(nobj, *holder, prop.propertyInfo()) &&
      !IsCacheableSetPropCallNative(nobj, *holder, prop.propertyInfo())) {
    return false;
  }

  *propInfo = mozilla::Some(prop.propertyInfo());
  return true;
}

static void EmitCallSetterNoGuards(JSContext* cx, CacheIRWriter& writer,
                                   NativeObject* obj, NativeObject* holder,
                                   PropertyInfo prop, ObjOperandId receiverId,
                                   ValOperandId rhsId) {
  JSFunction* target = &holder->getSetter(prop)->as<JSFunction>();
  bool sameRealm = cx->realm() == target->realm();

  if (target->isNativeWithoutJitEntry()) {
    MOZ_ASSERT(IsCacheableSetPropCallNative(obj, holder, prop));
    writer.callNativeSetter(receiverId, target, rhsId, sameRealm);
    writer.returnFromIC();
    return;
  }

  MOZ_ASSERT(IsCacheableSetPropCallScripted(obj, holder, prop));
  writer.callScriptedSetter(receiverId, target, rhsId, sameRealm);
  writer.returnFromIC();
}

static void EmitCallDOMSetterNoGuards(JSContext* cx, CacheIRWriter& writer,
                                      NativeObject* holder, PropertyInfo prop,
                                      ObjOperandId objId, ValOperandId rhsId) {
  JSFunction* setter = &holder->getSetter(prop)->as<JSFunction>();
  MOZ_ASSERT(cx->realm() == setter->realm());

  writer.callDOMSetter(objId, setter->jitInfo(), rhsId);
  writer.returnFromIC();
}

AttachDecision SetPropIRGenerator::tryAttachSetter(HandleObject obj,
                                                   ObjOperandId objId,
                                                   HandleId id,
                                                   ValOperandId rhsId) {
  // Don't attach a setter stub for ops like JSOp::InitElem.
  MOZ_ASSERT(IsPropertySetOp(JSOp(*pc_)));

  NativeObject* holder = nullptr;
  Maybe<PropertyInfo> prop;
  if (!CanAttachSetter(cx_, pc_, obj, id, &holder, &prop)) {
    return AttachDecision::NoAction;
  }
  auto* nobj = &obj->as<NativeObject>();

  bool needsWindowProxy =
      IsWindow(nobj) && SetterNeedsWindowProxyThis(holder, *prop);

  maybeEmitIdGuard(id);

  // Use the megamorphic guard if we're in megamorphic mode, except if |obj|
  // is a Window as GuardHasGetterSetter doesn't support this yet (Window may
  // require outerizing).
  if (mode_ == ICState::Mode::Specialized || IsWindow(nobj)) {
    TestMatchingNativeReceiver(writer, nobj, objId);

    if (nobj != holder) {
      GeneratePrototypeGuards(writer, nobj, holder, objId);

      // Guard on the holder's shape.
      ObjOperandId holderId = writer.loadObject(holder);
      TestMatchingHolder(writer, holder, holderId);

      EmitGuardGetterSetterSlot(writer, holder, *prop, holderId,
                                /* holderIsConstant = */ true);
    } else {
      EmitGuardGetterSetterSlot(writer, holder, *prop, objId);
    }
  } else {
    GetterSetter* gs = holder->getGetterSetter(*prop);
    writer.guardHasGetterSetter(objId, id, gs);
  }

  if (CanAttachDOMGetterSetter(cx_, JSJitInfo::Setter, nobj, holder, *prop,
                               mode_)) {
    MOZ_ASSERT(!needsWindowProxy);
    EmitCallDOMSetterNoGuards(cx_, writer, holder, *prop, objId, rhsId);

    trackAttached("SetProp.DOMSetter");
    return AttachDecision::Attach;
  }

  ObjOperandId receiverId;
  if (needsWindowProxy) {
    MOZ_ASSERT(cx_->global()->maybeWindowProxy());
    receiverId = writer.loadObject(cx_->global()->maybeWindowProxy());
  } else {
    receiverId = objId;
  }
  EmitCallSetterNoGuards(cx_, writer, nobj, holder, *prop, receiverId, rhsId);

  trackAttached("SetProp.Setter");
  return AttachDecision::Attach;
}

AttachDecision SetPropIRGenerator::tryAttachSetArrayLength(HandleObject obj,
                                                           ObjOperandId objId,
                                                           HandleId id,
                                                           ValOperandId rhsId) {
  // Don't attach an array length stub for ops like JSOp::InitElem.
  MOZ_ASSERT(IsPropertySetOp(JSOp(*pc_)));

  if (!obj->is<ArrayObject>() || !id.isAtom(cx_->names().length) ||
      !obj->as<ArrayObject>().lengthIsWritable()) {
    return AttachDecision::NoAction;
  }

  maybeEmitIdGuard(id);
  emitOptimisticClassGuard(objId, obj, GuardClassKind::Array);
  writer.callSetArrayLength(objId, IsStrictSetPC(pc_), rhsId);
  writer.returnFromIC();

  trackAttached("SetProp.ArrayLength");
  return AttachDecision::Attach;
}

AttachDecision SetPropIRGenerator::tryAttachSetDenseElement(
    HandleObject obj, ObjOperandId objId, uint32_t index,
    Int32OperandId indexId, ValOperandId rhsId) {
  if (!obj->is<NativeObject>()) {
    return AttachDecision::NoAction;
  }

  NativeObject* nobj = &obj->as<NativeObject>();
  if (!nobj->containsDenseElement(index) || nobj->denseElementsAreFrozen()) {
    return AttachDecision::NoAction;
  }

  // Setting holes requires extra code for marking the elements non-packed.
  MOZ_ASSERT(!rhsVal_.isMagic(JS_ELEMENTS_HOLE));

  JSOp op = JSOp(*pc_);

  // We don't currently emit locked init for any indexed properties.
  MOZ_ASSERT(!IsLockedInitOp(op));

  // We don't currently emit hidden init for any existing indexed properties.
  MOZ_ASSERT(!IsHiddenInitOp(op));

  // Don't optimize InitElem (DefineProperty) on non-extensible objects: when
  // the elements are sealed, we have to throw an exception. Note that we have
  // to check !isExtensible instead of denseElementsAreSealed because sealing
  // a (non-extensible) object does not necessarily trigger a Shape change.
  if (IsPropertyInitOp(op) && !nobj->isExtensible()) {
    return AttachDecision::NoAction;
  }

  TestMatchingNativeReceiver(writer, nobj, objId);

  writer.storeDenseElement(objId, indexId, rhsId);
  writer.returnFromIC();

  trackAttached("SetProp.DenseElement");
  return AttachDecision::Attach;
}

static bool CanAttachAddElement(NativeObject* obj, bool isInit,
                                AllowIndexedReceiver allowIndexedReceiver) {
  // Make sure the receiver doesn't have any indexed properties and that such
  // properties can't appear without a shape change.
  if (allowIndexedReceiver == AllowIndexedReceiver::No && obj->isIndexed()) {
    return false;
  }

  do {
    // This check is also relevant for the receiver object.
    const JSClass* clasp = obj->getClass();
    if (clasp != &ArrayObject::class_ &&
        (clasp->getAddProperty() || clasp->getResolve() ||
         clasp->getOpsLookupProperty() || clasp->getOpsSetProperty())) {
      return false;
    }

    // If we're initializing a property instead of setting one, the objects
    // on the prototype are not relevant.
    if (isInit) {
      break;
    }

    JSObject* proto = obj->staticPrototype();
    if (!proto) {
      break;
    }

    if (!proto->is<NativeObject>()) {
      return false;
    }

    NativeObject* nproto = &proto->as<NativeObject>();
    if (nproto->isIndexed()) {
      return false;
    }

    // We have to make sure the proto has no non-writable (frozen) elements
    // because we're not allowed to shadow them.
    if (nproto->denseElementsAreFrozen() &&
        nproto->getDenseInitializedLength() > 0) {
      return false;
    }

    obj = nproto;
  } while (true);

  return true;
}

AttachDecision SetPropIRGenerator::tryAttachSetDenseElementHole(
    HandleObject obj, ObjOperandId objId, uint32_t index,
    Int32OperandId indexId, ValOperandId rhsId) {
  if (!obj->is<NativeObject>()) {
    return AttachDecision::NoAction;
  }

  // Setting holes requires extra code for marking the elements non-packed.
  if (rhsVal_.isMagic(JS_ELEMENTS_HOLE)) {
    return AttachDecision::NoAction;
  }

  JSOp op = JSOp(*pc_);
  MOZ_ASSERT(IsPropertySetOp(op) || IsPropertyInitOp(op));

  // We don't currently emit locked init for any indexed properties.
  MOZ_ASSERT(!IsLockedInitOp(op));

  // Hidden init can be emitted for absent indexed properties.
  if (IsHiddenInitOp(op)) {
    MOZ_ASSERT(op == JSOp::InitHiddenElem);
    return AttachDecision::NoAction;
  }

  NativeObject* nobj = &obj->as<NativeObject>();
  if (!nobj->isExtensible()) {
    return AttachDecision::NoAction;
  }

  MOZ_ASSERT(!nobj->denseElementsAreFrozen(),
             "Extensible objects should not have frozen elements");

  uint32_t initLength = nobj->getDenseInitializedLength();

  // Optimize if we're adding an element at initLength or writing to a hole.
  //
  // In the case where index > initLength, we need noteHasDenseAdd to be called
  // to ensure Ion is aware that writes have occurred to-out-of-bound indexes
  // before.
  //
  // TODO(post-Warp): noteHasDenseAdd (nee: noteArrayWriteHole) no longer exists
  bool isAdd = index == initLength;
  bool isHoleInBounds =
      index < initLength && !nobj->containsDenseElement(index);
  if (!isAdd && !isHoleInBounds) {
    return AttachDecision::NoAction;
  }

  // Can't add new elements to arrays with non-writable length.
  if (isAdd && nobj->is<ArrayObject>() &&
      !nobj->as<ArrayObject>().lengthIsWritable()) {
    return AttachDecision::NoAction;
  }

  // Typed arrays don't have dense elements.
  if (nobj->is<TypedArrayObject>()) {
    return AttachDecision::NoAction;
  }

  // Check for other indexed properties or class hooks.
  if (!CanAttachAddElement(nobj, IsPropertyInitOp(op),
                           AllowIndexedReceiver::No)) {
    return AttachDecision::NoAction;
  }

  TestMatchingNativeReceiver(writer, nobj, objId);

  // Also shape guard the proto chain, unless this is an InitElem.
  if (IsPropertySetOp(op)) {
    ShapeGuardProtoChain(writer, nobj, objId);
  }

  writer.storeDenseElementHole(objId, indexId, rhsId, isAdd);
  writer.returnFromIC();

  trackAttached(isAdd ? "AddDenseElement" : "StoreDenseElementHole");
  return AttachDecision::Attach;
}

// Add an IC for adding or updating a sparse element.
AttachDecision SetPropIRGenerator::tryAttachAddOrUpdateSparseElement(
    HandleObject obj, ObjOperandId objId, uint32_t index,
    Int32OperandId indexId, ValOperandId rhsId) {
  JSOp op = JSOp(*pc_);
  MOZ_ASSERT(IsPropertySetOp(op) || IsPropertyInitOp(op));

  if (op != JSOp::SetElem && op != JSOp::StrictSetElem) {
    return AttachDecision::NoAction;
  }

  if (!obj->is<NativeObject>()) {
    return AttachDecision::NoAction;
  }
  NativeObject* nobj = &obj->as<NativeObject>();

  // We cannot attach a stub to a non-extensible object
  if (!nobj->isExtensible()) {
    return AttachDecision::NoAction;
  }

  // Stub doesn't handle negative indices.
  if (index > INT32_MAX) {
    return AttachDecision::NoAction;
  }

  // The index must not be for a dense element.
  if (nobj->containsDenseElement(index)) {
    return AttachDecision::NoAction;
  }

  // Only handle ArrayObject and PlainObject in this stub.
  if (!nobj->is<ArrayObject>() && !nobj->is<PlainObject>()) {
    return AttachDecision::NoAction;
  }

  // Don't attach if we're adding to an array with non-writable length.
  if (nobj->is<ArrayObject>()) {
    ArrayObject* aobj = &nobj->as<ArrayObject>();
    bool isAdd = (index >= aobj->length());
    if (isAdd && !aobj->lengthIsWritable()) {
      return AttachDecision::NoAction;
    }
  }

  // Check for class hooks or indexed properties on the prototype chain that
  // we're not allowed to shadow.
  if (!CanAttachAddElement(nobj, /* isInit = */ false,
                           AllowIndexedReceiver::Yes)) {
    return AttachDecision::NoAction;
  }

  // Ensure that obj is an ArrayObject or PlainObject.
  if (nobj->is<ArrayObject>()) {
    writer.guardClass(objId, GuardClassKind::Array);
  } else {
    MOZ_ASSERT(nobj->is<PlainObject>());
    writer.guardClass(objId, GuardClassKind::PlainObject);
  }

  // The helper we are going to call only applies to non-dense elements.
  writer.guardIndexIsNotDenseElement(objId, indexId);

  // Guard extensible: We may be trying to add a new element, and so we'd best
  // be able to do so safely.
  writer.guardIsExtensible(objId);

  // Ensures we are able to efficiently able to map to an integral jsid.
  writer.guardInt32IsNonNegative(indexId);

  // Shape guard the prototype chain to avoid shadowing indexes from appearing.
  // Guard the prototype of the receiver explicitly, because the receiver's
  // shape is not being guarded as a proxy for that.
  GuardReceiverProto(writer, nobj, objId);

  // Dense elements may appear on the prototype chain (and prototypes may
  // have a different notion of which elements are dense), but they can
  // only be data properties, so our specialized Set handler is ok to bind
  // to them.
  if (IsPropertySetOp(op)) {
    ShapeGuardProtoChain(writer, nobj, objId);
  }

  // Ensure that if we're adding an element to the object, the object's
  // length is writable.
  if (nobj->is<ArrayObject>()) {
    writer.guardIndexIsValidUpdateOrAdd(objId, indexId);
  }

  writer.callAddOrUpdateSparseElementHelper(
      objId, indexId, rhsId,
      /* strict = */ op == JSOp::StrictSetElem);
  writer.returnFromIC();

  trackAttached("SetProp.AddOrUpdateSparseElement");
  return AttachDecision::Attach;
}

AttachDecision SetPropIRGenerator::tryAttachSetTypedArrayElement(
    HandleObject obj, ObjOperandId objId, ValOperandId rhsId) {
  if (!obj->is<TypedArrayObject>()) {
    return AttachDecision::NoAction;
  }
  if (!idVal_.isNumber()) {
    return AttachDecision::NoAction;
  }

  TypedArrayObject* tarr = &obj->as<TypedArrayObject>();
  Scalar::Type elementType = tarr->type();

  // Don't attach if the input type doesn't match the guard added below.
  if (!ValueIsNumeric(elementType, rhsVal_)) {
    return AttachDecision::NoAction;
  }

  bool handleOOB = false;
  int64_t indexInt64;
  if (!ValueIsInt64Index(idVal_, &indexInt64) || indexInt64 < 0 ||
      uint64_t(indexInt64) >= tarr->length()) {
    handleOOB = true;
  }

  JSOp op = JSOp(*pc_);

  // The only expected property init operation is InitElem.
  MOZ_ASSERT_IF(IsPropertyInitOp(op), op == JSOp::InitElem);

  // InitElem (DefineProperty) has to throw an exception on out-of-bounds.
  if (handleOOB && IsPropertyInitOp(op)) {
    return AttachDecision::NoAction;
  }

  writer.guardShapeForClass(objId, tarr->shape());

  OperandId rhsValId = emitNumericGuard(rhsId, elementType);

  ValOperandId keyId = setElemKeyValueId();
  IntPtrOperandId indexId = guardToIntPtrIndex(idVal_, keyId, handleOOB);

  writer.storeTypedArrayElement(objId, elementType, indexId, rhsValId,
                                handleOOB);
  writer.returnFromIC();

  trackAttached(handleOOB ? "SetTypedElementOOB" : "SetTypedElement");
  return AttachDecision::Attach;
}

AttachDecision SetPropIRGenerator::tryAttachGenericProxy(
    Handle<ProxyObject*> obj, ObjOperandId objId, HandleId id,
    ValOperandId rhsId, bool handleDOMProxies) {
  // Don't attach a proxy stub for ops like JSOp::InitElem.
  MOZ_ASSERT(IsPropertySetOp(JSOp(*pc_)));

  writer.guardIsProxy(objId);

  if (!handleDOMProxies) {
    // Ensure that the incoming object is not a DOM proxy, so that we can
    // get to the specialized stubs. If handleDOMProxies is true, we were
    // unable to attach a specialized DOM stub, so we just handle all
    // proxies here.
    writer.guardIsNotDOMProxy(objId);
  }

  if (cacheKind_ == CacheKind::SetProp || mode_ == ICState::Mode::Specialized) {
    maybeEmitIdGuard(id);
    writer.proxySet(objId, id, rhsId, IsStrictSetPC(pc_));
  } else {
    // Attach a stub that handles every id.
    MOZ_ASSERT(cacheKind_ == CacheKind::SetElem);
    MOZ_ASSERT(mode_ == ICState::Mode::Megamorphic);
    writer.proxySetByValue(objId, setElemKeyValueId(), rhsId,
                           IsStrictSetPC(pc_));
  }

  writer.returnFromIC();

  trackAttached("SetProp.GenericProxy");
  return AttachDecision::Attach;
}

AttachDecision SetPropIRGenerator::tryAttachDOMProxyShadowed(
    Handle<ProxyObject*> obj, ObjOperandId objId, HandleId id,
    ValOperandId rhsId) {
  // Don't attach a proxy stub for ops like JSOp::InitElem.
  MOZ_ASSERT(IsPropertySetOp(JSOp(*pc_)));

  MOZ_ASSERT(IsCacheableDOMProxy(obj));

  maybeEmitIdGuard(id);
  TestMatchingProxyReceiver(writer, obj, objId);
  writer.proxySet(objId, id, rhsId, IsStrictSetPC(pc_));
  writer.returnFromIC();

  trackAttached("SetProp.DOMProxyShadowed");
  return AttachDecision::Attach;
}

AttachDecision SetPropIRGenerator::tryAttachDOMProxyUnshadowed(
    Handle<ProxyObject*> obj, ObjOperandId objId, HandleId id,
    ValOperandId rhsId) {
  // Don't attach a proxy stub for ops like JSOp::InitElem.
  MOZ_ASSERT(IsPropertySetOp(JSOp(*pc_)));

  MOZ_ASSERT(IsCacheableDOMProxy(obj));

  JSObject* proto = obj->staticPrototype();
  if (!proto) {
    return AttachDecision::NoAction;
  }

  NativeObject* holder = nullptr;
  Maybe<PropertyInfo> prop;
  if (!CanAttachSetter(cx_, pc_, proto, id, &holder, &prop)) {
    return AttachDecision::NoAction;
  }
  auto* nproto = &proto->as<NativeObject>();

  maybeEmitIdGuard(id);

  // Guard that our expando object hasn't started shadowing this property.
  TestMatchingProxyReceiver(writer, obj, objId);
  CheckDOMProxyExpandoDoesNotShadow(writer, obj, id, objId);

  GeneratePrototypeGuards(writer, obj, holder, objId);

  // Guard on the holder of the property.
  ObjOperandId holderId = writer.loadObject(holder);
  TestMatchingHolder(writer, holder, holderId);

  EmitGuardGetterSetterSlot(writer, holder, *prop, holderId,
                            /* holderIsConstant = */ true);

  // EmitCallSetterNoGuards expects |obj| to be the object the property is
  // on to do some checks. Since we actually looked at proto, and no extra
  // guards will be generated, we can just pass that instead.
  EmitCallSetterNoGuards(cx_, writer, nproto, holder, *prop, objId, rhsId);

  trackAttached("SetProp.DOMProxyUnshadowed");
  return AttachDecision::Attach;
}

AttachDecision SetPropIRGenerator::tryAttachDOMProxyExpando(
    Handle<ProxyObject*> obj, ObjOperandId objId, HandleId id,
    ValOperandId rhsId) {
  // Don't attach a proxy stub for ops like JSOp::InitElem.
  MOZ_ASSERT(IsPropertySetOp(JSOp(*pc_)));

  MOZ_ASSERT(IsCacheableDOMProxy(obj));

  Value expandoVal = GetProxyPrivate(obj);
  JSObject* expandoObj;
  if (expandoVal.isObject()) {
    expandoObj = &expandoVal.toObject();
  } else {
    MOZ_ASSERT(!expandoVal.isUndefined(),
               "How did a missing expando manage to shadow things?");
    auto expandoAndGeneration =
        static_cast<ExpandoAndGeneration*>(expandoVal.toPrivate());
    MOZ_ASSERT(expandoAndGeneration);
    expandoObj = &expandoAndGeneration->expando.toObject();
  }

  Maybe<PropertyInfo> prop;
  if (CanAttachNativeSetSlot(JSOp(*pc_), expandoObj, id, &prop)) {
    auto* nativeExpandoObj = &expandoObj->as<NativeObject>();

    maybeEmitIdGuard(id);
    ObjOperandId expandoObjId = guardDOMProxyExpandoObjectAndShape(
        obj, objId, expandoVal, nativeExpandoObj);

    EmitStoreSlotAndReturn(writer, expandoObjId, nativeExpandoObj, *prop,
                           rhsId);
    trackAttached("SetProp.DOMProxyExpandoSlot");
    return AttachDecision::Attach;
  }

  NativeObject* holder = nullptr;
  if (CanAttachSetter(cx_, pc_, expandoObj, id, &holder, &prop)) {
    auto* nativeExpandoObj = &expandoObj->as<NativeObject>();

    // Call the setter. Note that we pass objId, the DOM proxy, as |this|
    // and not the expando object.
    maybeEmitIdGuard(id);
    ObjOperandId expandoObjId = guardDOMProxyExpandoObjectAndShape(
        obj, objId, expandoVal, nativeExpandoObj);

    MOZ_ASSERT(holder == nativeExpandoObj);
    EmitGuardGetterSetterSlot(writer, nativeExpandoObj, *prop, expandoObjId);
    EmitCallSetterNoGuards(cx_, writer, nativeExpandoObj, nativeExpandoObj,
                           *prop, objId, rhsId);
    trackAttached("SetProp.DOMProxyExpandoSetter");
    return AttachDecision::Attach;
  }

  return AttachDecision::NoAction;
}

AttachDecision SetPropIRGenerator::tryAttachProxy(HandleObject obj,
                                                  ObjOperandId objId,
                                                  HandleId id,
                                                  ValOperandId rhsId) {
  // Don't attach a proxy stub for ops like JSOp::InitElem.
  MOZ_ASSERT(IsPropertySetOp(JSOp(*pc_)));

  ProxyStubType type = GetProxyStubType(cx_, obj, id);
  if (type == ProxyStubType::None) {
    return AttachDecision::NoAction;
  }
  auto proxy = obj.as<ProxyObject>();

  if (mode_ == ICState::Mode::Megamorphic) {
    return tryAttachGenericProxy(proxy, objId, id, rhsId,
                                 /* handleDOMProxies = */ true);
  }

  switch (type) {
    case ProxyStubType::None:
      break;
    case ProxyStubType::DOMExpando:
      TRY_ATTACH(tryAttachDOMProxyExpando(proxy, objId, id, rhsId));
      [[fallthrough]];  // Fall through to the generic shadowed case.
    case ProxyStubType::DOMShadowed:
      return tryAttachDOMProxyShadowed(proxy, objId, id, rhsId);
    case ProxyStubType::DOMUnshadowed:
      TRY_ATTACH(tryAttachDOMProxyUnshadowed(proxy, objId, id, rhsId));
      return tryAttachGenericProxy(proxy, objId, id, rhsId,
                                   /* handleDOMProxies = */ true);
    case ProxyStubType::Generic:
      return tryAttachGenericProxy(proxy, objId, id, rhsId,
                                   /* handleDOMProxies = */ false);
  }

  MOZ_CRASH("Unexpected ProxyStubType");
}

AttachDecision SetPropIRGenerator::tryAttachProxyElement(HandleObject obj,
                                                         ObjOperandId objId,
                                                         ValOperandId rhsId) {
  // Don't attach a proxy stub for ops like JSOp::InitElem.
  MOZ_ASSERT(IsPropertySetOp(JSOp(*pc_)));

  if (!obj->is<ProxyObject>()) {
    return AttachDecision::NoAction;
  }

  writer.guardIsProxy(objId);

  // Like GetPropIRGenerator::tryAttachProxyElement, don't check for DOM
  // proxies here as we don't have specialized DOM stubs for this.
  MOZ_ASSERT(cacheKind_ == CacheKind::SetElem);
  writer.proxySetByValue(objId, setElemKeyValueId(), rhsId, IsStrictSetPC(pc_));
  writer.returnFromIC();

  trackAttached("SetProp.ProxyElement");
  return AttachDecision::Attach;
}

AttachDecision SetPropIRGenerator::tryAttachMegamorphicSetElement(
    HandleObject obj, ObjOperandId objId, ValOperandId rhsId) {
  MOZ_ASSERT(IsPropertySetOp(JSOp(*pc_)));

  if (mode_ != ICState::Mode::Megamorphic || cacheKind_ != CacheKind::SetElem) {
    return AttachDecision::NoAction;
  }

  // The generic proxy stubs are faster.
  if (obj->is<ProxyObject>()) {
    return AttachDecision::NoAction;
  }

  writer.megamorphicSetElement(objId, setElemKeyValueId(), rhsId,
                               IsStrictSetPC(pc_));
  writer.returnFromIC();

  trackAttached("SetProp.MegamorphicSetElement");
  return AttachDecision::Attach;
}

AttachDecision SetPropIRGenerator::tryAttachMegamorphicSetSlot(
    HandleObject obj, ObjOperandId objId, HandleId id, ValOperandId rhsId) {
  if (mode_ != ICState::Mode::Megamorphic || cacheKind_ != CacheKind::SetProp) {
    return AttachDecision::NoAction;
  }

  writer.megamorphicStoreSlot(objId, id, rhsId, IsStrictSetPC(pc_));
  writer.returnFromIC();
  trackAttached("SetProp.MegamorphicNativeSlot");
  return AttachDecision::Attach;
}

AttachDecision SetPropIRGenerator::tryAttachWindowProxy(HandleObject obj,
                                                        ObjOperandId objId,
                                                        HandleId id,
                                                        ValOperandId rhsId) {
  // Don't attach a window proxy stub for ops like JSOp::InitElem.
  MOZ_ASSERT(IsPropertySetOp(JSOp(*pc_)));

  // Attach a stub when the receiver is a WindowProxy and we can do the set
  // on the Window (the global object).

  if (!IsWindowProxyForScriptGlobal(script_, obj)) {
    return AttachDecision::NoAction;
  }

  // If we're megamorphic prefer a generic proxy stub that handles a lot more
  // cases.
  if (mode_ == ICState::Mode::Megamorphic) {
    return AttachDecision::NoAction;
  }

  // Now try to do the set on the Window (the current global).
  GlobalObject* windowObj = cx_->global();

  Maybe<PropertyInfo> prop;
  if (!CanAttachNativeSetSlot(JSOp(*pc_), windowObj, id, &prop)) {
    return AttachDecision::NoAction;
  }

  maybeEmitIdGuard(id);

  ObjOperandId windowObjId =
      GuardAndLoadWindowProxyWindow(writer, objId, windowObj);
  writer.guardShape(windowObjId, windowObj->shape());

  EmitStoreSlotAndReturn(writer, windowObjId, windowObj, *prop, rhsId);

  trackAttached("SetProp.WindowProxySlot");
  return AttachDecision::Attach;
}

// Detect if |id| refers to the 'prototype' property of a function object. This
// property is special-cased in canAttachAddSlotStub().
static bool IsFunctionPrototype(const JSAtomState& names, JSObject* obj,
                                PropertyKey id) {
  return obj->is<JSFunction>() && id.isAtom(names.prototype);
}

bool SetPropIRGenerator::canAttachAddSlotStub(HandleObject obj, HandleId id) {
  if (!obj->is<NativeObject>()) {
    return false;
  }
  auto* nobj = &obj->as<NativeObject>();

  // Special-case JSFunction resolve hook to allow redefining the 'prototype'
  // property without triggering lazy expansion of property and object
  // allocation.
  if (IsFunctionPrototype(cx_->names(), nobj, id)) {
    MOZ_ASSERT(ClassMayResolveId(cx_->names(), nobj->getClass(), id, nobj));

    // We're only interested in functions that have a builtin .prototype
    // property (needsPrototypeProperty). The stub will guard on this because
    // the builtin .prototype property is non-configurable/non-enumerable and it
    // would be wrong to add a property with those attributes to a function that
    // doesn't have a builtin .prototype.
    //
    // Inlining needsPrototypeProperty in JIT code is complicated so we use
    // isNonBuiltinConstructor as a stronger condition that's easier to check
    // from JIT code.
    JSFunction* fun = &nobj->as<JSFunction>();
    if (!fun->isNonBuiltinConstructor()) {
      return false;
    }
    MOZ_ASSERT(fun->needsPrototypeProperty());

    // If property exists this isn't an "add".
    if (fun->lookupPure(id)) {
      return false;
    }
  } else {
    // Normal Case: If property exists this isn't an "add"
    PropertyResult prop;
    if (!LookupOwnPropertyPure(cx_, nobj, id, &prop)) {
      return false;
    }
    if (prop.isFound()) {
      return false;
    }
  }

  // For now we don't optimize Watchtower-monitored objects.
  if (Watchtower::watchesPropertyAdd(nobj)) {
    return false;
  }

  // Object must be extensible, or we must be initializing a private
  // elem.
  bool canAddNewProperty = nobj->isExtensible() || id.isPrivateName();
  if (!canAddNewProperty) {
    return false;
  }

  JSOp op = JSOp(*pc_);
  if (IsPropertyInitOp(op)) {
    return true;
  }

  MOZ_ASSERT(IsPropertySetOp(op));

  // Walk up the object prototype chain and ensure that all prototypes are
  // native, and that all prototypes have no setter defined on the property.
  for (JSObject* proto = nobj->staticPrototype(); proto;
       proto = proto->staticPrototype()) {
    if (!proto->is<NativeObject>()) {
      return false;
    }

    // If prototype defines this property in a non-plain way, don't optimize.
    Maybe<PropertyInfo> protoProp = proto->as<NativeObject>().lookup(cx_, id);
    if (protoProp.isSome() && !protoProp->isDataProperty()) {
      return false;
    }

    // Otherwise, if there's no such property, watch out for a resolve hook
    // that would need to be invoked and thus prevent inlining of property
    // addition. Allow the JSFunction resolve hook as it only defines plain
    // data properties and we don't need to invoke it for objects on the
    // proto chain.
    if (ClassMayResolveId(cx_->names(), proto->getClass(), id, proto) &&
        !proto->is<JSFunction>()) {
      return false;
    }
  }

  return true;
}

static PropertyFlags SetPropertyFlags(JSOp op, bool isFunctionPrototype) {
  // Locked properties are non-writable, non-enumerable, and non-configurable.
  if (IsLockedInitOp(op)) {
    return {};
  }

  // Hidden properties are writable, non-enumerable, and configurable.
  if (IsHiddenInitOp(op)) {
    return {
        PropertyFlag::Writable,
        PropertyFlag::Configurable,
    };
  }

  // This is a special case to overwrite an unresolved function.prototype
  // property. The initial property flags of this property are writable,
  // non-enumerable, and non-configurable. See canAttachAddSlotStub.
  if (isFunctionPrototype) {
    return {
        PropertyFlag::Writable,
    };
  }

  // Other properties are writable, enumerable, and configurable.
  return PropertyFlags::defaultDataPropFlags;
}

AttachDecision SetPropIRGenerator::tryAttachAddSlotStub(
    Handle<Shape*> oldShape) {
  ValOperandId objValId(writer.setInputOperandId(0));
  ValOperandId rhsValId;
  if (cacheKind_ == CacheKind::SetProp) {
    rhsValId = ValOperandId(writer.setInputOperandId(1));
  } else {
    MOZ_ASSERT(cacheKind_ == CacheKind::SetElem);
    MOZ_ASSERT(setElemKeyValueId().id() == 1);
    writer.setInputOperandId(1);
    rhsValId = ValOperandId(writer.setInputOperandId(2));
  }

  RootedId id(cx_);
  bool nameOrSymbol;
  if (!ValueToNameOrSymbolId(cx_, idVal_, &id, &nameOrSymbol)) {
    cx_->clearPendingException();
    return AttachDecision::NoAction;
  }

  if (!lhsVal_.isObject() || !nameOrSymbol) {
    return AttachDecision::NoAction;
  }

  JSObject* obj = &lhsVal_.toObject();

  PropertyResult prop;
  if (!LookupOwnPropertyPure(cx_, obj, id, &prop)) {
    return AttachDecision::NoAction;
  }
  if (prop.isNotFound()) {
    return AttachDecision::NoAction;
  }

  if (!obj->is<NativeObject>()) {
    return AttachDecision::NoAction;
  }
  auto* nobj = &obj->as<NativeObject>();

  PropertyInfo propInfo = prop.propertyInfo();
  NativeObject* holder = nobj;

  if (holder->inDictionaryMode()) {
    return AttachDecision::NoAction;
  }

  SharedShape* oldSharedShape = &oldShape->asShared();

  // The property must be the last added property of the object.
  SharedShape* newShape = holder->sharedShape();
  MOZ_RELEASE_ASSERT(newShape->lastProperty() == propInfo);

#ifdef DEBUG
  // Verify exactly one property was added by comparing the property map
  // lengths.
  if (oldSharedShape->propMapLength() == PropMap::Capacity) {
    MOZ_ASSERT(newShape->propMapLength() == 1);
  } else {
    MOZ_ASSERT(newShape->propMapLength() ==
               oldSharedShape->propMapLength() + 1);
  }
#endif

  bool isFunctionPrototype = IsFunctionPrototype(cx_->names(), nobj, id);

  JSOp op = JSOp(*pc_);
  PropertyFlags flags = SetPropertyFlags(op, isFunctionPrototype);

  // Basic property checks.
  if (!propInfo.isDataProperty() || propInfo.flags() != flags) {
    return AttachDecision::NoAction;
  }

  ObjOperandId objId = writer.guardToObject(objValId);
  maybeEmitIdGuard(id);

  // Shape guard the object.
  writer.guardShape(objId, oldShape);

  // If this is the special function.prototype case, we need to guard the
  // function is a non-builtin constructor. See canAttachAddSlotStub.
  if (isFunctionPrototype) {
    MOZ_ASSERT(nobj->as<JSFunction>().isNonBuiltinConstructor());
    writer.guardFunctionIsNonBuiltinCtor(objId);
  }

  // Also shape guard the proto chain, unless this is an InitElem.
  if (IsPropertySetOp(op)) {
    ShapeGuardProtoChain(writer, nobj, objId);
  }

  // If the JSClass has an addProperty hook, we need to call a VM function to
  // invoke this hook. Ignore the Array addProperty hook, because it doesn't do
  // anything for non-index properties.
  DebugOnly<uint32_t> index;
  MOZ_ASSERT_IF(obj->is<ArrayObject>(), !IdIsIndex(id, &index));
  bool mustCallAddPropertyHook =
      obj->getClass()->getAddProperty() && !obj->is<ArrayObject>();

  if (mustCallAddPropertyHook) {
    writer.addSlotAndCallAddPropHook(objId, rhsValId, newShape);
    trackAttached("SetProp.AddSlotWithAddPropertyHook");
  } else if (holder->isFixedSlot(propInfo.slot())) {
    size_t offset = NativeObject::getFixedSlotOffset(propInfo.slot());
    writer.addAndStoreFixedSlot(objId, offset, rhsValId, newShape);
    trackAttached("SetProp.AddSlotFixed");
  } else {
    size_t offset = holder->dynamicSlotIndex(propInfo.slot()) * sizeof(Value);
    uint32_t numOldSlots = NativeObject::calculateDynamicSlots(oldSharedShape);
    uint32_t numNewSlots = holder->numDynamicSlots();
    if (numOldSlots == numNewSlots) {
      writer.addAndStoreDynamicSlot(objId, offset, rhsValId, newShape);
      trackAttached("SetProp.AddSlotDynamic");
    } else {
      MOZ_ASSERT(numNewSlots > numOldSlots);
      writer.allocateAndStoreDynamicSlot(objId, offset, rhsValId, newShape,
                                         numNewSlots);
      trackAttached("SetProp.AllocateSlot");
    }
  }
  writer.returnFromIC();

  return AttachDecision::Attach;
}

InstanceOfIRGenerator::InstanceOfIRGenerator(JSContext* cx, HandleScript script,
                                             jsbytecode* pc, ICState state,
                                             HandleValue lhs, HandleObject rhs)
    : IRGenerator(cx, script, pc, CacheKind::InstanceOf, state),
      lhsVal_(lhs),
      rhsObj_(rhs) {}

AttachDecision InstanceOfIRGenerator::tryAttachStub() {
  MOZ_ASSERT(cacheKind_ == CacheKind::InstanceOf);
  AutoAssertNoPendingException aanpe(cx_);

  // Ensure RHS is a function -- could be a Proxy, which the IC isn't prepared
  // to handle.
  if (!rhsObj_->is<JSFunction>()) {
    trackAttached(IRGenerator::NotAttached);
    return AttachDecision::NoAction;
  }

  HandleFunction fun = rhsObj_.as<JSFunction>();

  // Look up the @@hasInstance property, and check that Function.__proto__ is
  // the property holder, and that no object further down the prototype chain
  // (including this function) has shadowed it; together with the fact that
  // Function.__proto__[@@hasInstance] is immutable, this ensures that the
  // hasInstance hook will not change without the need to guard on the actual
  // property value.
  PropertyResult hasInstanceProp;
  NativeObject* hasInstanceHolder = nullptr;
  jsid hasInstanceID = PropertyKey::Symbol(cx_->wellKnownSymbols().hasInstance);
  if (!LookupPropertyPure(cx_, fun, hasInstanceID, &hasInstanceHolder,
                          &hasInstanceProp) ||
      !hasInstanceProp.isNativeProperty()) {
    trackAttached(IRGenerator::NotAttached);
    return AttachDecision::NoAction;
  }

  JSObject& funProto = cx_->global()->getPrototype(JSProto_Function);
  if (hasInstanceHolder != &funProto) {
    trackAttached(IRGenerator::NotAttached);
    return AttachDecision::NoAction;
  }

  // If the above succeeded, then these should be true about @@hasInstance,
  // because the property on Function.__proto__ is an immutable data property:
  MOZ_ASSERT(hasInstanceProp.propertyInfo().isDataProperty());
  MOZ_ASSERT(!hasInstanceProp.propertyInfo().configurable());
  MOZ_ASSERT(!hasInstanceProp.propertyInfo().writable());

  MOZ_ASSERT(IsCacheableProtoChain(fun, hasInstanceHolder));

  // Ensure that the function's prototype slot is the same.
  Maybe<PropertyInfo> prop = fun->lookupPure(cx_->names().prototype);
  if (prop.isNothing() || !prop->isDataProperty()) {
    trackAttached(IRGenerator::NotAttached);
    return AttachDecision::NoAction;
  }

  uint32_t slot = prop->slot();
  MOZ_ASSERT(slot >= fun->numFixedSlots(), "Stub code relies on this");
  if (!fun->getSlot(slot).isObject()) {
    trackAttached(IRGenerator::NotAttached);
    return AttachDecision::NoAction;
  }

  // Abstract Objects
  ValOperandId lhs(writer.setInputOperandId(0));
  ValOperandId rhs(writer.setInputOperandId(1));

  ObjOperandId rhsId = writer.guardToObject(rhs);
  writer.guardShape(rhsId, fun->shape());

  // Ensure that the shapes up the prototype chain for the RHS remain the same
  // so that @@hasInstance is not shadowed by some intermediate prototype
  // object.
  if (hasInstanceHolder != fun) {
    GeneratePrototypeGuards(writer, fun, hasInstanceHolder, rhsId);
    ObjOperandId holderId = writer.loadObject(hasInstanceHolder);
    TestMatchingHolder(writer, hasInstanceHolder, holderId);
  }

  // Load the .prototype value and ensure it's an object.
  ValOperandId protoValId =
      writer.loadDynamicSlot(rhsId, slot - fun->numFixedSlots());
  ObjOperandId protoId = writer.guardToObject(protoValId);

  // Needn't guard LHS is object, because the actual stub can handle that
  // and correctly return false.
  writer.loadInstanceOfObjectResult(lhs, protoId);
  writer.returnFromIC();
  trackAttached("InstanceOf");
  return AttachDecision::Attach;
}

void InstanceOfIRGenerator::trackAttached(const char* name) {
  stubName_ = name ? name : "NotAttached";
#ifdef JS_CACHEIR_SPEW
  if (const CacheIRSpewer::Guard& sp = CacheIRSpewer::Guard(*this, name)) {
    sp.valueProperty("lhs", lhsVal_);
    sp.valueProperty("rhs", ObjectValue(*rhsObj_));
  }
#else
  // Silence Clang -Wunused-private-field warning.
  (void)lhsVal_;
#endif
}

TypeOfIRGenerator::TypeOfIRGenerator(JSContext* cx, HandleScript script,
                                     jsbytecode* pc, ICState state,
                                     HandleValue value)
    : IRGenerator(cx, script, pc, CacheKind::TypeOf, state), val_(value) {}

void TypeOfIRGenerator::trackAttached(const char* name) {
  stubName_ = name ? name : "NotAttached";
#ifdef JS_CACHEIR_SPEW
  if (const CacheIRSpewer::Guard& sp = CacheIRSpewer::Guard(*this, name)) {
    sp.valueProperty("val", val_);
  }
#endif
}

AttachDecision TypeOfIRGenerator::tryAttachStub() {
  MOZ_ASSERT(cacheKind_ == CacheKind::TypeOf);

  AutoAssertNoPendingException aanpe(cx_);

  ValOperandId valId(writer.setInputOperandId(0));

  TRY_ATTACH(tryAttachPrimitive(valId));
  TRY_ATTACH(tryAttachObject(valId));

  MOZ_ASSERT_UNREACHABLE("Failed to attach TypeOf");
  return AttachDecision::NoAction;
}

AttachDecision TypeOfIRGenerator::tryAttachPrimitive(ValOperandId valId) {
  if (!val_.isPrimitive()) {
    return AttachDecision::NoAction;
  }

  // Note: we don't use GuardIsNumber for int32 values because it's less
  // efficient in Warp (unboxing to double instead of int32).
  if (val_.isDouble()) {
    writer.guardIsNumber(valId);
  } else {
    writer.guardNonDoubleType(valId, val_.type());
  }

  writer.loadConstantStringResult(
      TypeName(js::TypeOfValue(val_), cx_->names()));
  writer.returnFromIC();
  writer.setTypeData(TypeData(JSValueType(val_.type())));
  trackAttached("TypeOf.Primitive");
  return AttachDecision::Attach;
}

AttachDecision TypeOfIRGenerator::tryAttachObject(ValOperandId valId) {
  if (!val_.isObject()) {
    return AttachDecision::NoAction;
  }

  ObjOperandId objId = writer.guardToObject(valId);
  writer.loadTypeOfObjectResult(objId);
  writer.returnFromIC();
  writer.setTypeData(TypeData(JSValueType(val_.type())));
  trackAttached("TypeOf.Object");
  return AttachDecision::Attach;
}

GetIteratorIRGenerator::GetIteratorIRGenerator(JSContext* cx,
                                               HandleScript script,
                                               jsbytecode* pc, ICState state,
                                               HandleValue value)
    : IRGenerator(cx, script, pc, CacheKind::GetIterator, state), val_(value) {}

AttachDecision GetIteratorIRGenerator::tryAttachStub() {
  MOZ_ASSERT(cacheKind_ == CacheKind::GetIterator);

  AutoAssertNoPendingException aanpe(cx_);

  ValOperandId valId(writer.setInputOperandId(0));

  TRY_ATTACH(tryAttachObject(valId));
  TRY_ATTACH(tryAttachNullOrUndefined(valId));
  TRY_ATTACH(tryAttachGeneric(valId));

  trackAttached(IRGenerator::NotAttached);
  return AttachDecision::NoAction;
}

AttachDecision GetIteratorIRGenerator::tryAttachObject(ValOperandId valId) {
  if (!val_.isObject()) {
    return AttachDecision::NoAction;
  }

  MOZ_ASSERT(val_.toObject().compartment() == cx_->compartment());

  ObjOperandId objId = writer.guardToObject(valId);
  writer.objectToIteratorResult(objId, cx_->compartment()->enumeratorsAddr());
  writer.returnFromIC();

  trackAttached("GetIterator.Object");
  return AttachDecision::Attach;
}

AttachDecision GetIteratorIRGenerator::tryAttachNullOrUndefined(
    ValOperandId valId) {
  MOZ_ASSERT(JSOp(*pc_) == JSOp::Iter);

  // For null/undefined we can simply return the empty iterator singleton. This
  // works because this iterator is unlinked and immutable.

  if (!val_.isNullOrUndefined()) {
    return AttachDecision::NoAction;
  }

  PropertyIteratorObject* emptyIter = cx_->global()->maybeEmptyIterator();
  if (!emptyIter) {
    return AttachDecision::NoAction;
  }

  writer.guardIsNullOrUndefined(valId);

  ObjOperandId iterId = writer.loadObject(emptyIter);
  writer.loadObjectResult(iterId);
  writer.returnFromIC();

  trackAttached("GetIterator.NullOrUndefined");
  return AttachDecision::Attach;
}

AttachDecision GetIteratorIRGenerator::tryAttachGeneric(ValOperandId valId) {
  writer.valueToIteratorResult(valId);
  writer.returnFromIC();

  trackAttached("GetIterator.Generic");
  return AttachDecision::Attach;
}

void GetIteratorIRGenerator::trackAttached(const char* name) {
  stubName_ = name ? name : "NotAttached";
#ifdef JS_CACHEIR_SPEW
  if (const CacheIRSpewer::Guard& sp = CacheIRSpewer::Guard(*this, name)) {
    sp.valueProperty("val", val_);
  }
#endif
}

OptimizeSpreadCallIRGenerator::OptimizeSpreadCallIRGenerator(
    JSContext* cx, HandleScript script, jsbytecode* pc, ICState state,
    HandleValue value)
    : IRGenerator(cx, script, pc, CacheKind::OptimizeSpreadCall, state),
      val_(value) {}

AttachDecision OptimizeSpreadCallIRGenerator::tryAttachStub() {
  MOZ_ASSERT(cacheKind_ == CacheKind::OptimizeSpreadCall);

  AutoAssertNoPendingException aanpe(cx_);

  TRY_ATTACH(tryAttachArray());
  TRY_ATTACH(tryAttachArguments());
  TRY_ATTACH(tryAttachNotOptimizable());

  trackAttached(IRGenerator::NotAttached);
  return AttachDecision::NoAction;
}

static bool IsArrayPrototypeOptimizable(JSContext* cx, ArrayObject* arr,
                                        NativeObject** arrProto, uint32_t* slot,
                                        JSFunction** iterFun) {
  // Prototype must be Array.prototype.
  auto* proto = cx->global()->maybeGetArrayPrototype();
  if (!proto || arr->staticPrototype() != proto) {
    return false;
  }
  *arrProto = proto;

  // The object must not have an own @@iterator property.
  PropertyKey iteratorKey =
      PropertyKey::Symbol(cx->wellKnownSymbols().iterator);
  if (arr->lookupPure(iteratorKey)) {
    return false;
  }

  // Ensure that Array.prototype's @@iterator slot is unchanged.
  Maybe<PropertyInfo> prop = proto->lookupPure(iteratorKey);
  if (prop.isNothing() || !prop->isDataProperty()) {
    return false;
  }

  *slot = prop->slot();
  MOZ_ASSERT(proto->numFixedSlots() == 0, "Stub code relies on this");

  const Value& iterVal = proto->getSlot(*slot);
  if (!iterVal.isObject() || !iterVal.toObject().is<JSFunction>()) {
    return false;
  }

  *iterFun = &iterVal.toObject().as<JSFunction>();
  return IsSelfHostedFunctionWithName(*iterFun, cx->names().ArrayValues);
}

static bool IsArrayIteratorPrototypeOptimizable(JSContext* cx,
                                                NativeObject** arrIterProto,
                                                uint32_t* slot,
                                                JSFunction** nextFun) {
  auto* proto = cx->global()->maybeGetArrayIteratorPrototype();
  if (!proto) {
    return false;
  }
  *arrIterProto = proto;

  // Ensure that %ArrayIteratorPrototype%'s "next" slot is unchanged.
  Maybe<PropertyInfo> prop = proto->lookupPure(cx->names().next);
  if (prop.isNothing() || !prop->isDataProperty()) {
    return false;
  }

  *slot = prop->slot();
  MOZ_ASSERT(proto->numFixedSlots() == 0, "Stub code relies on this");

  const Value& nextVal = proto->getSlot(*slot);
  if (!nextVal.isObject() || !nextVal.toObject().is<JSFunction>()) {
    return false;
  }

  *nextFun = &nextVal.toObject().as<JSFunction>();
  return IsSelfHostedFunctionWithName(*nextFun, cx->names().ArrayIteratorNext);
}

AttachDecision OptimizeSpreadCallIRGenerator::tryAttachArray() {
  if (!isFirstStub_) {
    return AttachDecision::NoAction;
  }

  // The value must be a packed array.
  if (!val_.isObject()) {
    return AttachDecision::NoAction;
  }
  JSObject* obj = &val_.toObject();
  if (!IsPackedArray(obj)) {
    return AttachDecision::NoAction;
  }

  // Prototype must be Array.prototype and Array.prototype[@@iterator] must not
  // be modified.
  NativeObject* arrProto;
  uint32_t arrProtoIterSlot;
  JSFunction* iterFun;
  if (!IsArrayPrototypeOptimizable(cx_, &obj->as<ArrayObject>(), &arrProto,
                                   &arrProtoIterSlot, &iterFun)) {
    return AttachDecision::NoAction;
  }

  // %ArrayIteratorPrototype%.next must not be modified.
  NativeObject* arrayIteratorProto;
  uint32_t iterNextSlot;
  JSFunction* nextFun;
  if (!IsArrayIteratorPrototypeOptimizable(cx_, &arrayIteratorProto,
                                           &iterNextSlot, &nextFun)) {
    return AttachDecision::NoAction;
  }

  ValOperandId valId(writer.setInputOperandId(0));
  ObjOperandId objId = writer.guardToObject(valId);

  // Guard the object is a packed array with Array.prototype as proto.
  MOZ_ASSERT(obj->is<ArrayObject>());
  writer.guardShape(objId, obj->shape());
  writer.guardArrayIsPacked(objId);

  // Guard on Array.prototype[@@iterator].
  ObjOperandId arrProtoId = writer.loadObject(arrProto);
  ObjOperandId iterId = writer.loadObject(iterFun);
  writer.guardShape(arrProtoId, arrProto->shape());
  writer.guardDynamicSlotIsSpecificObject(arrProtoId, iterId, arrProtoIterSlot);

  // Guard on %ArrayIteratorPrototype%.next.
  ObjOperandId iterProtoId = writer.loadObject(arrayIteratorProto);
  ObjOperandId nextId = writer.loadObject(nextFun);
  writer.guardShape(iterProtoId, arrayIteratorProto->shape());
  writer.guardDynamicSlotIsSpecificObject(iterProtoId, nextId, iterNextSlot);

  writer.loadObjectResult(objId);
  writer.returnFromIC();

  trackAttached("OptimizeSpreadCall.Array");
  return AttachDecision::Attach;
}

AttachDecision OptimizeSpreadCallIRGenerator::tryAttachArguments() {
  // The value must be an arguments object.
  if (!val_.isObject()) {
    return AttachDecision::NoAction;
  }
  RootedObject obj(cx_, &val_.toObject());
  if (!obj->is<ArgumentsObject>()) {
    return AttachDecision::NoAction;
  }
  auto args = obj.as<ArgumentsObject>();

  // Ensure neither elements, nor the length, nor the iterator has been
  // overridden. Also ensure no args are forwarded to allow reading them
  // directly from the frame.
  if (args->hasOverriddenElement() || args->hasOverriddenLength() ||
      args->hasOverriddenIterator() || args->anyArgIsForwarded()) {
    return AttachDecision::NoAction;
  }

  Rooted<Shape*> shape(cx_, GlobalObject::getArrayShapeWithDefaultProto(cx_));
  if (!shape) {
    cx_->clearPendingException();
    return AttachDecision::NoAction;
  }

  NativeObject* arrayIteratorProto;
  uint32_t slot;
  JSFunction* nextFun;
  if (!IsArrayIteratorPrototypeOptimizable(cx_, &arrayIteratorProto, &slot,
                                           &nextFun)) {
    return AttachDecision::NoAction;
  }

  ValOperandId valId(writer.setInputOperandId(0));
  ObjOperandId objId = writer.guardToObject(valId);

  if (args->is<MappedArgumentsObject>()) {
    writer.guardClass(objId, GuardClassKind::MappedArguments);
  } else {
    MOZ_ASSERT(args->is<UnmappedArgumentsObject>());
    writer.guardClass(objId, GuardClassKind::UnmappedArguments);
  }
  uint8_t flags = ArgumentsObject::ELEMENT_OVERRIDDEN_BIT |
                  ArgumentsObject::LENGTH_OVERRIDDEN_BIT |
                  ArgumentsObject::ITERATOR_OVERRIDDEN_BIT |
                  ArgumentsObject::FORWARDED_ARGUMENTS_BIT;
  writer.guardArgumentsObjectFlags(objId, flags);

  ObjOperandId protoId = writer.loadObject(arrayIteratorProto);
  ObjOperandId nextId = writer.loadObject(nextFun);

  writer.guardShape(protoId, arrayIteratorProto->shape());

  // Ensure that proto[slot] == nextFun.
  writer.guardDynamicSlotIsSpecificObject(protoId, nextId, slot);

  writer.arrayFromArgumentsObjectResult(objId, shape);
  writer.returnFromIC();

  trackAttached("OptimizeSpreadCall.Arguments");
  return AttachDecision::Attach;
}

AttachDecision OptimizeSpreadCallIRGenerator::tryAttachNotOptimizable() {
  ValOperandId valId(writer.setInputOperandId(0));

  writer.loadUndefinedResult();
  writer.returnFromIC();

  trackAttached("OptimizeSpreadCall.NotOptimizable");
  return AttachDecision::Attach;
}

void OptimizeSpreadCallIRGenerator::trackAttached(const char* name) {
  stubName_ = name ? name : "NotAttached";
#ifdef JS_CACHEIR_SPEW
  if (const CacheIRSpewer::Guard& sp = CacheIRSpewer::Guard(*this, name)) {
    sp.valueProperty("val", val_);
  }
#endif
}

CallIRGenerator::CallIRGenerator(JSContext* cx, HandleScript script,
                                 jsbytecode* pc, JSOp op, ICState state,
                                 uint32_t argc, HandleValue callee,
                                 HandleValue thisval, HandleValue newTarget,
                                 HandleValueArray args)
    : IRGenerator(cx, script, pc, CacheKind::Call, state),
      op_(op),
      argc_(argc),
      callee_(callee),
      thisval_(thisval),
      newTarget_(newTarget),
      args_(args) {}

void InlinableNativeIRGenerator::emitNativeCalleeGuard() {
  // Note: we rely on GuardSpecificFunction to also guard against the same
  // native from a different realm.
  MOZ_ASSERT(callee_->isNativeWithoutJitEntry());

  ObjOperandId calleeObjId;
  if (flags_.getArgFormat() == CallFlags::Standard) {
    ValOperandId calleeValId =
        writer.loadArgumentFixedSlot(ArgumentKind::Callee, argc_, flags_);
    calleeObjId = writer.guardToObject(calleeValId);
  } else if (flags_.getArgFormat() == CallFlags::Spread) {
    ValOperandId calleeValId =
        writer.loadArgumentFixedSlot(ArgumentKind::Callee, argc_, flags_);
    calleeObjId = writer.guardToObject(calleeValId);
  } else if (flags_.getArgFormat() == CallFlags::FunCall) {
    MOZ_ASSERT(generator_.writer.numOperandIds() > 0, "argcId is initialized");

    Int32OperandId argcId(0);
    calleeObjId = generator_.emitFunCallOrApplyGuard(argcId);
  } else {
    MOZ_ASSERT(flags_.getArgFormat() == CallFlags::FunApplyArray);
    MOZ_ASSERT(generator_.writer.numOperandIds() > 0, "argcId is initialized");

    Int32OperandId argcId(0);
    calleeObjId = generator_.emitFunApplyGuard(argcId);
  }

  writer.guardSpecificFunction(calleeObjId, callee_);

  // If we're constructing we also need to guard newTarget == callee.
  if (flags_.isConstructing()) {
    MOZ_ASSERT(flags_.getArgFormat() == CallFlags::Standard);
    MOZ_ASSERT(&newTarget_.toObject() == callee_);

    ValOperandId newTargetValId =
        writer.loadArgumentFixedSlot(ArgumentKind::NewTarget, argc_, flags_);
    ObjOperandId newTargetObjId = writer.guardToObject(newTargetValId);
    writer.guardSpecificFunction(newTargetObjId, callee_);
  }
}

ObjOperandId InlinableNativeIRGenerator::emitLoadArgsArray() {
  if (flags_.getArgFormat() == CallFlags::Spread) {
    return writer.loadSpreadArgs();
  }

  MOZ_ASSERT(flags_.getArgFormat() == CallFlags::FunApplyArray);
  return generator_.emitFunApplyArgsGuard(flags_.getArgFormat()).ref();
}

void IRGenerator::emitCalleeGuard(ObjOperandId calleeId, JSFunction* callee) {
  // Guarding on the callee JSFunction* is most efficient, but doesn't work well
  // for lambda clones (multiple functions with the same BaseScript). We guard
  // on the function's BaseScript if the callee is scripted and this isn't the
  // first IC stub.
  if (isFirstStub_ || !callee->hasBaseScript() ||
      callee->isSelfHostedBuiltin()) {
    writer.guardSpecificFunction(calleeId, callee);
  } else {
    writer.guardClass(calleeId, GuardClassKind::JSFunction);
    writer.guardFunctionScript(calleeId, callee->baseScript());
  }
}

ObjOperandId CallIRGenerator::emitFunCallOrApplyGuard(Int32OperandId argcId) {
  JSFunction* callee = &callee_.toObject().as<JSFunction>();
  MOZ_ASSERT(callee->native() == fun_call || callee->native() == fun_apply);

  // Guard that callee is the |fun_call| or |fun_apply| native function.
  ValOperandId calleeValId =
      writer.loadArgumentDynamicSlot(ArgumentKind::Callee, argcId);
  ObjOperandId calleeObjId = writer.guardToObject(calleeValId);
  writer.guardSpecificFunction(calleeObjId, callee);

  // Guard that |this| is an object.
  ValOperandId thisValId =
      writer.loadArgumentDynamicSlot(ArgumentKind::This, argcId);
  return writer.guardToObject(thisValId);
}

ObjOperandId CallIRGenerator::emitFunCallGuard(Int32OperandId argcId) {
  MOZ_ASSERT(callee_.toObject().as<JSFunction>().native() == fun_call);

  return emitFunCallOrApplyGuard(argcId);
}

ObjOperandId CallIRGenerator::emitFunApplyGuard(Int32OperandId argcId) {
  MOZ_ASSERT(callee_.toObject().as<JSFunction>().native() == fun_apply);

  return emitFunCallOrApplyGuard(argcId);
}

Maybe<ObjOperandId> CallIRGenerator::emitFunApplyArgsGuard(
    CallFlags::ArgFormat format) {
  MOZ_ASSERT(argc_ == 2);

  ValOperandId argValId =
      writer.loadArgumentFixedSlot(ArgumentKind::Arg1, argc_);

  if (format == CallFlags::FunApplyArgsObj) {
    ObjOperandId argObjId = writer.guardToObject(argValId);
    if (args_[1].toObject().is<MappedArgumentsObject>()) {
      writer.guardClass(argObjId, GuardClassKind::MappedArguments);
    } else {
      MOZ_ASSERT(args_[1].toObject().is<UnmappedArgumentsObject>());
      writer.guardClass(argObjId, GuardClassKind::UnmappedArguments);
    }
    uint8_t flags = ArgumentsObject::ELEMENT_OVERRIDDEN_BIT |
                    ArgumentsObject::FORWARDED_ARGUMENTS_BIT;
    writer.guardArgumentsObjectFlags(argObjId, flags);
    return mozilla::Some(argObjId);
  }

  if (format == CallFlags::FunApplyArray) {
    ObjOperandId argObjId = writer.guardToObject(argValId);
    emitOptimisticClassGuard(argObjId, &args_[1].toObject(),
                             GuardClassKind::Array);
    writer.guardArrayIsPacked(argObjId);
    return mozilla::Some(argObjId);
  }

  MOZ_ASSERT(format == CallFlags::FunApplyNullUndefined);
  writer.guardIsNullOrUndefined(argValId);
  return mozilla::Nothing();
}

AttachDecision InlinableNativeIRGenerator::tryAttachArrayPush() {
  // Only optimize on obj.push(val);
  if (argc_ != 1 || !thisval_.isObject()) {
    return AttachDecision::NoAction;
  }

  // Where |obj| is a native array.
  JSObject* thisobj = &thisval_.toObject();
  if (!thisobj->is<ArrayObject>()) {
    return AttachDecision::NoAction;
  }

  auto* thisarray = &thisobj->as<ArrayObject>();

  // Check for other indexed properties or class hooks.
  if (!CanAttachAddElement(thisarray, /* isInit = */ false,
                           AllowIndexedReceiver::No)) {
    return AttachDecision::NoAction;
  }

  // Can't add new elements to arrays with non-writable length.
  if (!thisarray->lengthIsWritable()) {
    return AttachDecision::NoAction;
  }

  // Check that array is extensible.
  if (!thisarray->isExtensible()) {
    return AttachDecision::NoAction;
  }

  // Check that the array is completely initialized (no holes).
  if (thisarray->getDenseInitializedLength() != thisarray->length()) {
    return AttachDecision::NoAction;
  }

  MOZ_ASSERT(!thisarray->denseElementsAreFrozen(),
             "Extensible arrays should not have frozen elements");

  // After this point, we can generate code fine.

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee is the 'push' native function.
  emitNativeCalleeGuard();

  // Guard this is an array object.
  ValOperandId thisValId =
      writer.loadArgumentFixedSlot(ArgumentKind::This, argc_);
  ObjOperandId thisObjId = writer.guardToObject(thisValId);

  // Guard that the shape matches.
  TestMatchingNativeReceiver(writer, thisarray, thisObjId);

  // Guard proto chain shapes.
  ShapeGuardProtoChain(writer, thisarray, thisObjId);

  // arr.push(x) is equivalent to arr[arr.length] = x for regular arrays.
  ValOperandId argId = writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
  writer.arrayPush(thisObjId, argId);

  writer.returnFromIC();

  trackAttached("ArrayPush");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachArrayPopShift(
    InlinableNative native) {
  // Expecting no arguments.
  if (argc_ != 0) {
    return AttachDecision::NoAction;
  }

  // Only optimize if |this| is a packed array.
  if (!thisval_.isObject() || !IsPackedArray(&thisval_.toObject())) {
    return AttachDecision::NoAction;
  }

  // Other conditions:
  //
  // * The array length needs to be writable because we're changing it.
  // * The array must be extensible. Non-extensible arrays require preserving
  //   the |initializedLength == capacity| invariant on ObjectElements.
  //   See NativeObject::shrinkCapacityToInitializedLength.
  //   This also ensures the elements aren't sealed/frozen.
  // * There must not be a for-in iterator for the elements because the IC stub
  //   does not suppress deleted properties.
  ArrayObject* arr = &thisval_.toObject().as<ArrayObject>();
  if (!arr->lengthIsWritable() || !arr->isExtensible() ||
      arr->denseElementsHaveMaybeInIterationFlag()) {
    return AttachDecision::NoAction;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee is the 'pop' or 'shift' native function.
  emitNativeCalleeGuard();

  ValOperandId thisValId =
      writer.loadArgumentFixedSlot(ArgumentKind::This, argc_);
  ObjOperandId objId = writer.guardToObject(thisValId);
  emitOptimisticClassGuard(objId, arr, GuardClassKind::Array);

  if (native == InlinableNative::ArrayPop) {
    writer.packedArrayPopResult(objId);
  } else {
    MOZ_ASSERT(native == InlinableNative::ArrayShift);
    writer.packedArrayShiftResult(objId);
  }

  writer.returnFromIC();

  trackAttached("ArrayPopShift");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachArrayJoin() {
  // Only handle argc <= 1.
  if (argc_ > 1) {
    return AttachDecision::NoAction;
  }

  // Only optimize if |this| is an array.
  if (!thisval_.isObject() || !thisval_.toObject().is<ArrayObject>()) {
    return AttachDecision::NoAction;
  }

  // The separator argument must be a string, if present.
  if (argc_ > 0 && !args_[0].isString()) {
    return AttachDecision::NoAction;
  }

  // IC stub code can handle non-packed array.

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee is the 'join' native function.
  emitNativeCalleeGuard();

  // Guard this is an array object.
  ValOperandId thisValId =
      writer.loadArgumentFixedSlot(ArgumentKind::This, argc_);
  ObjOperandId thisObjId = writer.guardToObject(thisValId);
  emitOptimisticClassGuard(thisObjId, &thisval_.toObject(),
                           GuardClassKind::Array);

  StringOperandId sepId;
  if (argc_ == 1) {
    // If argcount is 1, guard that the argument is a string.
    ValOperandId argValId =
        writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
    sepId = writer.guardToString(argValId);
  } else {
    sepId = writer.loadConstantString(cx_->names().comma);
  }

  // Do the join.
  writer.arrayJoinResult(thisObjId, sepId);

  writer.returnFromIC();

  trackAttached("ArrayJoin");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachArraySlice() {
  // Only handle argc <= 2.
  if (argc_ > 2) {
    return AttachDecision::NoAction;
  }

  // Only optimize if |this| is a packed array or an arguments object.
  if (!thisval_.isObject()) {
    return AttachDecision::NoAction;
  }

  bool isPackedArray = IsPackedArray(&thisval_.toObject());
  if (!isPackedArray) {
    if (!thisval_.toObject().is<ArgumentsObject>()) {
      return AttachDecision::NoAction;
    }
    auto* args = &thisval_.toObject().as<ArgumentsObject>();

    // No elements must have been overridden or deleted.
    if (args->hasOverriddenElement()) {
      return AttachDecision::NoAction;
    }

    // The length property mustn't be overridden.
    if (args->hasOverriddenLength()) {
      return AttachDecision::NoAction;
    }

    // And finally also check that no argument is forwarded.
    if (args->anyArgIsForwarded()) {
      return AttachDecision::NoAction;
    }
  }

  // Arguments for the sliced region must be integers.
  if (argc_ > 0 && !args_[0].isInt32()) {
    return AttachDecision::NoAction;
  }
  if (argc_ > 1 && !args_[1].isInt32()) {
    return AttachDecision::NoAction;
  }

  JSObject* templateObj = NewDenseFullyAllocatedArray(cx_, 0, TenuredObject);
  if (!templateObj) {
    cx_->recoverFromOutOfMemory();
    return AttachDecision::NoAction;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee is the 'slice' native function.
  emitNativeCalleeGuard();

  ValOperandId thisValId =
      writer.loadArgumentFixedSlot(ArgumentKind::This, argc_);
  ObjOperandId objId = writer.guardToObject(thisValId);

  if (isPackedArray) {
    emitOptimisticClassGuard(objId, &thisval_.toObject(),
                             GuardClassKind::Array);
  } else {
    auto* args = &thisval_.toObject().as<ArgumentsObject>();

    if (args->is<MappedArgumentsObject>()) {
      writer.guardClass(objId, GuardClassKind::MappedArguments);
    } else {
      MOZ_ASSERT(args->is<UnmappedArgumentsObject>());
      writer.guardClass(objId, GuardClassKind::UnmappedArguments);
    }

    uint8_t flags = ArgumentsObject::ELEMENT_OVERRIDDEN_BIT |
                    ArgumentsObject::LENGTH_OVERRIDDEN_BIT |
                    ArgumentsObject::FORWARDED_ARGUMENTS_BIT;
    writer.guardArgumentsObjectFlags(objId, flags);
  }

  Int32OperandId int32BeginId;
  if (argc_ > 0) {
    ValOperandId beginId =
        writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
    int32BeginId = writer.guardToInt32(beginId);
  } else {
    int32BeginId = writer.loadInt32Constant(0);
  }

  Int32OperandId int32EndId;
  if (argc_ > 1) {
    ValOperandId endId =
        writer.loadArgumentFixedSlot(ArgumentKind::Arg1, argc_);
    int32EndId = writer.guardToInt32(endId);
  } else if (isPackedArray) {
    int32EndId = writer.loadInt32ArrayLength(objId);
  } else {
    int32EndId = writer.loadArgumentsObjectLength(objId);
  }

  if (isPackedArray) {
    writer.packedArraySliceResult(templateObj, objId, int32BeginId, int32EndId);
  } else {
    writer.argumentsSliceResult(templateObj, objId, int32BeginId, int32EndId);
  }
  writer.returnFromIC();

  trackAttached(isPackedArray ? "ArraySlice" : "ArgumentsSlice");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachArrayIsArray() {
  // Need a single argument.
  if (argc_ != 1) {
    return AttachDecision::NoAction;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee is the 'isArray' native function.
  emitNativeCalleeGuard();

  // Check if the argument is an Array and return result.
  ValOperandId argId = writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
  writer.isArrayResult(argId);
  writer.returnFromIC();

  trackAttached("ArrayIsArray");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachDataViewGet(
    Scalar::Type type) {
  // Ensure |this| is a DataViewObject.
  if (!thisval_.isObject() || !thisval_.toObject().is<DataViewObject>()) {
    return AttachDecision::NoAction;
  }

  // Expected arguments: offset (number), optional littleEndian (boolean).
  if (argc_ < 1 || argc_ > 2) {
    return AttachDecision::NoAction;
  }
  int64_t offsetInt64;
  if (!ValueIsInt64Index(args_[0], &offsetInt64)) {
    return AttachDecision::NoAction;
  }
  if (argc_ > 1 && !args_[1].isBoolean()) {
    return AttachDecision::NoAction;
  }

  DataViewObject* dv = &thisval_.toObject().as<DataViewObject>();

  // Bounds check the offset.
  if (offsetInt64 < 0 ||
      !dv->offsetIsInBounds(Scalar::byteSize(type), offsetInt64)) {
    return AttachDecision::NoAction;
  }

  // For getUint32 we let the stub return an Int32 if we have not seen a
  // double, to allow better codegen in Warp while avoiding bailout loops.
  bool forceDoubleForUint32 = false;
  if (type == Scalar::Uint32) {
    bool isLittleEndian = argc_ > 1 && args_[1].toBoolean();
    uint32_t res = dv->read<uint32_t>(offsetInt64, isLittleEndian);
    forceDoubleForUint32 = res >= INT32_MAX;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee is this DataView native function.
  emitNativeCalleeGuard();

  // Guard |this| is a DataViewObject.
  ValOperandId thisValId =
      writer.loadArgumentFixedSlot(ArgumentKind::This, argc_);
  ObjOperandId objId = writer.guardToObject(thisValId);
  emitOptimisticClassGuard(objId, &thisval_.toObject(),
                           GuardClassKind::DataView);

  // Convert offset to intPtr.
  ValOperandId offsetId =
      writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
  IntPtrOperandId intPtrOffsetId =
      guardToIntPtrIndex(args_[0], offsetId, /* supportOOB = */ false);

  BooleanOperandId boolLittleEndianId;
  if (argc_ > 1) {
    ValOperandId littleEndianId =
        writer.loadArgumentFixedSlot(ArgumentKind::Arg1, argc_);
    boolLittleEndianId = writer.guardToBoolean(littleEndianId);
  } else {
    boolLittleEndianId = writer.loadBooleanConstant(false);
  }

  writer.loadDataViewValueResult(objId, intPtrOffsetId, boolLittleEndianId,
                                 type, forceDoubleForUint32);
  writer.returnFromIC();

  trackAttached("DataViewGet");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachDataViewSet(
    Scalar::Type type) {
  // Ensure |this| is a DataViewObject.
  if (!thisval_.isObject() || !thisval_.toObject().is<DataViewObject>()) {
    return AttachDecision::NoAction;
  }

  // Expected arguments: offset (number), value, optional littleEndian (boolean)
  if (argc_ < 2 || argc_ > 3) {
    return AttachDecision::NoAction;
  }
  int64_t offsetInt64;
  if (!ValueIsInt64Index(args_[0], &offsetInt64)) {
    return AttachDecision::NoAction;
  }
  if (!ValueIsNumeric(type, args_[1])) {
    return AttachDecision::NoAction;
  }
  if (argc_ > 2 && !args_[2].isBoolean()) {
    return AttachDecision::NoAction;
  }

  DataViewObject* dv = &thisval_.toObject().as<DataViewObject>();

  // Bounds check the offset.
  if (offsetInt64 < 0 ||
      !dv->offsetIsInBounds(Scalar::byteSize(type), offsetInt64)) {
    return AttachDecision::NoAction;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee is this DataView native function.
  emitNativeCalleeGuard();

  // Guard |this| is a DataViewObject.
  ValOperandId thisValId =
      writer.loadArgumentFixedSlot(ArgumentKind::This, argc_);
  ObjOperandId objId = writer.guardToObject(thisValId);
  emitOptimisticClassGuard(objId, &thisval_.toObject(),
                           GuardClassKind::DataView);

  // Convert offset to intPtr.
  ValOperandId offsetId =
      writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
  IntPtrOperandId intPtrOffsetId =
      guardToIntPtrIndex(args_[0], offsetId, /* supportOOB = */ false);

  // Convert value to number or BigInt.
  ValOperandId valueId =
      writer.loadArgumentFixedSlot(ArgumentKind::Arg1, argc_);
  OperandId numericValueId = emitNumericGuard(valueId, type);

  BooleanOperandId boolLittleEndianId;
  if (argc_ > 2) {
    ValOperandId littleEndianId =
        writer.loadArgumentFixedSlot(ArgumentKind::Arg2, argc_);
    boolLittleEndianId = writer.guardToBoolean(littleEndianId);
  } else {
    boolLittleEndianId = writer.loadBooleanConstant(false);
  }

  writer.storeDataViewValueResult(objId, intPtrOffsetId, numericValueId,
                                  boolLittleEndianId, type);
  writer.returnFromIC();

  trackAttached("DataViewSet");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachUnsafeGetReservedSlot(
    InlinableNative native) {
  // Self-hosted code calls this with (object, int32) arguments.
  MOZ_ASSERT(argc_ == 2);
  MOZ_ASSERT(args_[0].isObject());
  MOZ_ASSERT(args_[1].isInt32());
  MOZ_ASSERT(args_[1].toInt32() >= 0);

  uint32_t slot = uint32_t(args_[1].toInt32());
  if (slot >= NativeObject::MAX_FIXED_SLOTS) {
    return AttachDecision::NoAction;
  }
  size_t offset = NativeObject::getFixedSlotOffset(slot);

  // Initialize the input operand.
  initializeInputOperand();

  // Note: we don't need to call emitNativeCalleeGuard for intrinsics.

  // Guard that the first argument is an object.
  ValOperandId arg0Id = writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
  ObjOperandId objId = writer.guardToObject(arg0Id);

  // BytecodeEmitter::assertSelfHostedUnsafeGetReservedSlot ensures that the
  // slot argument is constant. (At least for direct calls)

  switch (native) {
    case InlinableNative::IntrinsicUnsafeGetReservedSlot:
      writer.loadFixedSlotResult(objId, offset);
      break;
    case InlinableNative::IntrinsicUnsafeGetObjectFromReservedSlot:
      writer.loadFixedSlotTypedResult(objId, offset, ValueType::Object);
      break;
    case InlinableNative::IntrinsicUnsafeGetInt32FromReservedSlot:
      writer.loadFixedSlotTypedResult(objId, offset, ValueType::Int32);
      break;
    case InlinableNative::IntrinsicUnsafeGetStringFromReservedSlot:
      writer.loadFixedSlotTypedResult(objId, offset, ValueType::String);
      break;
    default:
      MOZ_CRASH("unexpected native");
  }

  writer.returnFromIC();

  trackAttached("UnsafeGetReservedSlot");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachUnsafeSetReservedSlot() {
  // Self-hosted code calls this with (object, int32, value) arguments.
  MOZ_ASSERT(argc_ == 3);
  MOZ_ASSERT(args_[0].isObject());
  MOZ_ASSERT(args_[1].isInt32());
  MOZ_ASSERT(args_[1].toInt32() >= 0);

  uint32_t slot = uint32_t(args_[1].toInt32());
  if (slot >= NativeObject::MAX_FIXED_SLOTS) {
    return AttachDecision::NoAction;
  }
  size_t offset = NativeObject::getFixedSlotOffset(slot);

  // Initialize the input operand.
  initializeInputOperand();

  // Note: we don't need to call emitNativeCalleeGuard for intrinsics.

  // Guard that the first argument is an object.
  ValOperandId arg0Id = writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
  ObjOperandId objId = writer.guardToObject(arg0Id);

  // BytecodeEmitter::assertSelfHostedUnsafeSetReservedSlot ensures that the
  // slot argument is constant. (At least for direct calls)

  // Get the value to set.
  ValOperandId valId = writer.loadArgumentFixedSlot(ArgumentKind::Arg2, argc_);

  // Set the fixed slot and return undefined.
  writer.storeFixedSlotUndefinedResult(objId, offset, valId);

  // This stub always returns undefined.
  writer.returnFromIC();

  trackAttached("UnsafeSetReservedSlot");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachIsSuspendedGenerator() {
  // The IsSuspendedGenerator intrinsic is only called in
  // self-hosted code, so it's safe to assume we have a single
  // argument and the callee is our intrinsic.

  MOZ_ASSERT(argc_ == 1);

  initializeInputOperand();

  // Stack layout here is (bottom to top):
  //  2: Callee
  //  1: ThisValue
  //  0: Arg <-- Top of stack.
  // We only care about the argument.
  ValOperandId valId = writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);

  // Check whether the argument is a suspended generator.
  // We don't need guards, because IsSuspendedGenerator returns
  // false for values that are not generator objects.
  writer.callIsSuspendedGeneratorResult(valId);
  writer.returnFromIC();

  trackAttached("IsSuspendedGenerator");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachToObject() {
  // Self-hosted code calls this with a single argument.
  MOZ_ASSERT(argc_ == 1);

  // Need a single object argument.
  // TODO(Warp): Support all or more conversions to object.
  if (!args_[0].isObject()) {
    return AttachDecision::NoAction;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Note: we don't need to call emitNativeCalleeGuard for intrinsics.

  // Guard that the argument is an object.
  ValOperandId argId = writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
  ObjOperandId objId = writer.guardToObject(argId);

  // Return the object.
  writer.loadObjectResult(objId);
  writer.returnFromIC();

  trackAttached("ToObject");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachToInteger() {
  // Self-hosted code calls this with a single argument.
  MOZ_ASSERT(argc_ == 1);

  // Need a single int32 argument.
  // TODO(Warp): Support all or more conversions to integer.
  // Make sure to update this code correctly if we ever start
  // returning non-int32 integers.
  if (!args_[0].isInt32()) {
    return AttachDecision::NoAction;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Note: we don't need to call emitNativeCalleeGuard for intrinsics.

  // Guard that the argument is an int32.
  ValOperandId argId = writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
  Int32OperandId int32Id = writer.guardToInt32(argId);

  // Return the int32.
  writer.loadInt32Result(int32Id);
  writer.returnFromIC();

  trackAttached("ToInteger");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachToLength() {
  // Self-hosted code calls this with a single argument.
  MOZ_ASSERT(argc_ == 1);

  // Need a single int32 argument.
  if (!args_[0].isInt32()) {
    return AttachDecision::NoAction;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Note: we don't need to call emitNativeCalleeGuard for intrinsics.

  // ToLength(int32) is equivalent to max(int32, 0).
  ValOperandId argId = writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
  Int32OperandId int32ArgId = writer.guardToInt32(argId);
  Int32OperandId zeroId = writer.loadInt32Constant(0);
  bool isMax = true;
  Int32OperandId maxId = writer.int32MinMax(isMax, int32ArgId, zeroId);
  writer.loadInt32Result(maxId);
  writer.returnFromIC();

  trackAttached("ToLength");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachIsObject() {
  // Self-hosted code calls this with a single argument.
  MOZ_ASSERT(argc_ == 1);

  // Initialize the input operand.
  initializeInputOperand();

  // Note: we don't need to call emitNativeCalleeGuard for intrinsics.

  // Type check the argument and return result.
  ValOperandId argId = writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
  writer.isObjectResult(argId);
  writer.returnFromIC();

  trackAttached("IsObject");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachIsPackedArray() {
  // Self-hosted code calls this with a single object argument.
  MOZ_ASSERT(argc_ == 1);
  MOZ_ASSERT(args_[0].isObject());

  // Initialize the input operand.
  initializeInputOperand();

  // Note: we don't need to call emitNativeCalleeGuard for intrinsics.

  // Check if the argument is packed and return result.
  ValOperandId argId = writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
  ObjOperandId objArgId = writer.guardToObject(argId);
  writer.isPackedArrayResult(objArgId);
  writer.returnFromIC();

  trackAttached("IsPackedArray");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachIsCallable() {
  // Self-hosted code calls this with a single argument.
  MOZ_ASSERT(argc_ == 1);

  // Initialize the input operand.
  initializeInputOperand();

  // Note: we don't need to call emitNativeCalleeGuard for intrinsics.

  // Check if the argument is callable and return result.
  ValOperandId argId = writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
  writer.isCallableResult(argId);
  writer.returnFromIC();

  trackAttached("IsCallable");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachIsConstructor() {
  // Self-hosted code calls this with a single argument.
  MOZ_ASSERT(argc_ == 1);

  // Need a single object argument.
  if (!args_[0].isObject()) {
    return AttachDecision::NoAction;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Note: we don't need to call emitNativeCalleeGuard for intrinsics.

  // Guard that the argument is an object.
  ValOperandId argId = writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
  ObjOperandId objId = writer.guardToObject(argId);

  // Check if the argument is a constructor and return result.
  writer.isConstructorResult(objId);
  writer.returnFromIC();

  trackAttached("IsConstructor");
  return AttachDecision::Attach;
}

AttachDecision
InlinableNativeIRGenerator::tryAttachIsCrossRealmArrayConstructor() {
  // Self-hosted code calls this with an object argument.
  MOZ_ASSERT(argc_ == 1);
  MOZ_ASSERT(args_[0].isObject());

  if (args_[0].toObject().is<ProxyObject>()) {
    return AttachDecision::NoAction;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Note: we don't need to call emitNativeCalleeGuard for intrinsics.

  ValOperandId argId = writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
  ObjOperandId objId = writer.guardToObject(argId);
  writer.guardIsNotProxy(objId);
  writer.isCrossRealmArrayConstructorResult(objId);
  writer.returnFromIC();

  trackAttached("IsCrossRealmArrayConstructor");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachGuardToClass(
    InlinableNative native) {
  // Self-hosted code calls this with an object argument.
  MOZ_ASSERT(argc_ == 1);
  MOZ_ASSERT(args_[0].isObject());

  // Class must match.
  const JSClass* clasp = InlinableNativeGuardToClass(native);
  if (args_[0].toObject().getClass() != clasp) {
    return AttachDecision::NoAction;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Note: we don't need to call emitNativeCalleeGuard for intrinsics.

  // Guard that the argument is an object.
  ValOperandId argId = writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
  ObjOperandId objId = writer.guardToObject(argId);

  // Guard that the object has the correct class.
  writer.guardAnyClass(objId, clasp);

  // Return the object.
  writer.loadObjectResult(objId);
  writer.returnFromIC();

  trackAttached("GuardToClass");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachHasClass(
    const JSClass* clasp, bool isPossiblyWrapped) {
  // Self-hosted code calls this with an object argument.
  MOZ_ASSERT(argc_ == 1);
  MOZ_ASSERT(args_[0].isObject());

  // Only optimize when the object isn't a proxy.
  if (isPossiblyWrapped && args_[0].toObject().is<ProxyObject>()) {
    return AttachDecision::NoAction;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Note: we don't need to call emitNativeCalleeGuard for intrinsics.

  // Perform the Class check.
  ValOperandId argId = writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
  ObjOperandId objId = writer.guardToObject(argId);

  if (isPossiblyWrapped) {
    writer.guardIsNotProxy(objId);
  }

  writer.hasClassResult(objId, clasp);
  writer.returnFromIC();

  trackAttached("HasClass");
  return AttachDecision::Attach;
}

// Returns whether the .lastIndex property is a non-negative int32 value and is
// still writable.
static bool HasOptimizableLastIndexSlot(RegExpObject* regexp, JSContext* cx) {
  auto lastIndexProp = regexp->lookupPure(cx->names().lastIndex);
  MOZ_ASSERT(lastIndexProp->isDataProperty());
  if (!lastIndexProp->writable()) {
    return false;
  }
  Value lastIndex = regexp->getLastIndex();
  if (!lastIndex.isInt32() || lastIndex.toInt32() < 0) {
    return false;
  }
  return true;
}

// Returns the RegExp stub used by the optimized code path for this intrinsic.
// We store a pointer to this in the IC stub to ensure GC doesn't discard it.
static JitCode* GetOrCreateRegExpStub(JSContext* cx, InlinableNative native) {
  JitCode* code;
  switch (native) {
    case InlinableNative::IntrinsicRegExpBuiltinExecForTest:
    case InlinableNative::IntrinsicRegExpExecForTest:
      code = cx->realm()->jitRealm()->ensureRegExpExecTestStubExists(cx);
      break;
    case InlinableNative::IntrinsicRegExpBuiltinExec:
    case InlinableNative::IntrinsicRegExpExec:
      code = cx->realm()->jitRealm()->ensureRegExpExecMatchStubExists(cx);
      break;
    case InlinableNative::RegExpMatcher:
      code = cx->realm()->jitRealm()->ensureRegExpMatcherStubExists(cx);
      break;
    case InlinableNative::RegExpSearcher:
      code = cx->realm()->jitRealm()->ensureRegExpSearcherStubExists(cx);
      break;
    default:
      MOZ_CRASH("Unexpected native");
  }
  if (!code) {
    cx->recoverFromOutOfMemory();
    return nullptr;
  }
  return code;
}

static void EmitGuardLastIndexIsNonNegativeInt32(CacheIRWriter& writer,
                                                 ObjOperandId regExpId) {
  size_t offset =
      NativeObject::getFixedSlotOffset(RegExpObject::lastIndexSlot());
  ValOperandId lastIndexValId = writer.loadFixedSlot(regExpId, offset);
  Int32OperandId lastIndexId = writer.guardToInt32(lastIndexValId);
  writer.guardInt32IsNonNegative(lastIndexId);
}

AttachDecision InlinableNativeIRGenerator::tryAttachIntrinsicRegExpBuiltinExec(
    InlinableNative native) {
  // Self-hosted code calls this with (regexp, string) arguments.
  MOZ_ASSERT(argc_ == 2);
  MOZ_ASSERT(args_[0].isObject());
  MOZ_ASSERT(args_[1].isString());

  JitCode* stub = GetOrCreateRegExpStub(cx_, native);
  if (!stub) {
    return AttachDecision::NoAction;
  }

  RegExpObject* re = &args_[0].toObject().as<RegExpObject>();
  if (!HasOptimizableLastIndexSlot(re, cx_)) {
    return AttachDecision::NoAction;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Note: we don't need to call emitNativeCalleeGuard for intrinsics.

  ValOperandId arg0Id = writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
  ObjOperandId regExpId = writer.guardToObject(arg0Id);
  writer.guardShape(regExpId, re->shape());
  EmitGuardLastIndexIsNonNegativeInt32(writer, regExpId);

  ValOperandId arg1Id = writer.loadArgumentFixedSlot(ArgumentKind::Arg1, argc_);
  StringOperandId inputId = writer.guardToString(arg1Id);

  if (native == InlinableNative::IntrinsicRegExpBuiltinExecForTest) {
    writer.regExpBuiltinExecTestResult(regExpId, inputId, stub);
  } else {
    writer.regExpBuiltinExecMatchResult(regExpId, inputId, stub);
  }
  writer.returnFromIC();

  trackAttached("IntrinsicRegExpBuiltinExec");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachIntrinsicRegExpExec(
    InlinableNative native) {
  // Self-hosted code calls this with (object, string) arguments.
  MOZ_ASSERT(argc_ == 2);
  MOZ_ASSERT(args_[0].isObject());
  MOZ_ASSERT(args_[1].isString());

  if (!args_[0].toObject().is<RegExpObject>()) {
    return AttachDecision::NoAction;
  }

  JitCode* stub = GetOrCreateRegExpStub(cx_, native);
  if (!stub) {
    return AttachDecision::NoAction;
  }

  RegExpObject* re = &args_[0].toObject().as<RegExpObject>();
  if (!HasOptimizableLastIndexSlot(re, cx_)) {
    return AttachDecision::NoAction;
  }

  // Ensure regexp.exec is the original RegExp.prototype.exec function on the
  // prototype.
  if (re->containsPure(cx_->names().exec)) {
    return AttachDecision::NoAction;
  }
  MOZ_ASSERT(cx_->global()->maybeGetRegExpPrototype());
  auto* regExpProto =
      &cx_->global()->maybeGetRegExpPrototype()->as<NativeObject>();
  if (re->staticPrototype() != regExpProto) {
    return AttachDecision::NoAction;
  }
  auto execProp = regExpProto->as<NativeObject>().lookupPure(cx_->names().exec);
  if (!execProp || !execProp->isDataProperty()) {
    return AttachDecision::NoAction;
  }
  // It should be stored in a dynamic slot. We assert this in
  // FinishRegExpClassInit.
  if (regExpProto->isFixedSlot(execProp->slot())) {
    return AttachDecision::NoAction;
  }
  Value execVal = regExpProto->getSlot(execProp->slot());
  PropertyName* execName = cx_->names().RegExp_prototype_Exec;
  if (!IsSelfHostedFunctionWithName(execVal, execName)) {
    return AttachDecision::NoAction;
  }
  JSFunction* execFunction = &execVal.toObject().as<JSFunction>();

  // Initialize the input operand.
  initializeInputOperand();

  // Note: we don't need to call emitNativeCalleeGuard for intrinsics.

  ValOperandId arg0Id = writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
  ObjOperandId regExpId = writer.guardToObject(arg0Id);
  writer.guardShape(regExpId, re->shape());
  EmitGuardLastIndexIsNonNegativeInt32(writer, regExpId);

  // Emit guards for the RegExp.prototype.exec property.
  ObjOperandId regExpProtoId = writer.loadObject(regExpProto);
  writer.guardShape(regExpProtoId, regExpProto->shape());
  size_t offset =
      regExpProto->dynamicSlotIndex(execProp->slot()) * sizeof(Value);
  writer.guardDynamicSlotValue(regExpProtoId, offset,
                               ObjectValue(*execFunction));

  ValOperandId arg1Id = writer.loadArgumentFixedSlot(ArgumentKind::Arg1, argc_);
  StringOperandId inputId = writer.guardToString(arg1Id);

  if (native == InlinableNative::IntrinsicRegExpExecForTest) {
    writer.regExpBuiltinExecTestResult(regExpId, inputId, stub);
  } else {
    writer.regExpBuiltinExecMatchResult(regExpId, inputId, stub);
  }
  writer.returnFromIC();

  trackAttached("IntrinsicRegExpExec");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachRegExpMatcherSearcher(
    InlinableNative native) {
  // Self-hosted code calls this with (object, string, number) arguments.
  MOZ_ASSERT(argc_ == 3);
  MOZ_ASSERT(args_[0].isObject());
  MOZ_ASSERT(args_[1].isString());
  MOZ_ASSERT(args_[2].isNumber());

  // It's not guaranteed that the JITs have typed |lastIndex| as an Int32.
  if (!args_[2].isInt32()) {
    return AttachDecision::NoAction;
  }

  JitCode* stub = GetOrCreateRegExpStub(cx_, native);
  if (!stub) {
    return AttachDecision::NoAction;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Note: we don't need to call emitNativeCalleeGuard for intrinsics.

  // Guard argument types.
  ValOperandId arg0Id = writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
  ObjOperandId reId = writer.guardToObject(arg0Id);

  ValOperandId arg1Id = writer.loadArgumentFixedSlot(ArgumentKind::Arg1, argc_);
  StringOperandId inputId = writer.guardToString(arg1Id);

  ValOperandId arg2Id = writer.loadArgumentFixedSlot(ArgumentKind::Arg2, argc_);
  Int32OperandId lastIndexId = writer.guardToInt32(arg2Id);

  switch (native) {
    case InlinableNative::RegExpMatcher:
      writer.callRegExpMatcherResult(reId, inputId, lastIndexId, stub);
      writer.returnFromIC();
      trackAttached("RegExpMatcher");
      break;

    case InlinableNative::RegExpSearcher:
      writer.callRegExpSearcherResult(reId, inputId, lastIndexId, stub);
      writer.returnFromIC();
      trackAttached("RegExpSearcher");
      break;

    default:
      MOZ_CRASH("Unexpected native");
  }

  return AttachDecision::Attach;
}

AttachDecision
InlinableNativeIRGenerator::tryAttachRegExpPrototypeOptimizable() {
  // Self-hosted code calls this with a single object argument.
  MOZ_ASSERT(argc_ == 1);
  MOZ_ASSERT(args_[0].isObject());

  // Initialize the input operand.
  initializeInputOperand();

  // Note: we don't need to call emitNativeCalleeGuard for intrinsics.

  ValOperandId arg0Id = writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
  ObjOperandId protoId = writer.guardToObject(arg0Id);

  writer.regExpPrototypeOptimizableResult(protoId);
  writer.returnFromIC();

  trackAttached("RegExpPrototypeOptimizable");
  return AttachDecision::Attach;
}

AttachDecision
InlinableNativeIRGenerator::tryAttachRegExpInstanceOptimizable() {
  // Self-hosted code calls this with two object arguments.
  MOZ_ASSERT(argc_ == 2);
  MOZ_ASSERT(args_[0].isObject());
  MOZ_ASSERT(args_[1].isObject());

  // Initialize the input operand.
  initializeInputOperand();

  // Note: we don't need to call emitNativeCalleeGuard for intrinsics.

  ValOperandId arg0Id = writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
  ObjOperandId regexpId = writer.guardToObject(arg0Id);

  ValOperandId arg1Id = writer.loadArgumentFixedSlot(ArgumentKind::Arg1, argc_);
  ObjOperandId protoId = writer.guardToObject(arg1Id);

  writer.regExpInstanceOptimizableResult(regexpId, protoId);
  writer.returnFromIC();

  trackAttached("RegExpInstanceOptimizable");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachGetFirstDollarIndex() {
  // Self-hosted code calls this with a single string argument.
  MOZ_ASSERT(argc_ == 1);
  MOZ_ASSERT(args_[0].isString());

  // Initialize the input operand.
  initializeInputOperand();

  // Note: we don't need to call emitNativeCalleeGuard for intrinsics.

  ValOperandId arg0Id = writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
  StringOperandId strId = writer.guardToString(arg0Id);

  writer.getFirstDollarIndexResult(strId);
  writer.returnFromIC();

  trackAttached("GetFirstDollarIndex");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachSubstringKernel() {
  // Self-hosted code calls this with (string, int32, int32) arguments.
  MOZ_ASSERT(argc_ == 3);
  MOZ_ASSERT(args_[0].isString());
  MOZ_ASSERT(args_[1].isInt32());
  MOZ_ASSERT(args_[2].isInt32());

  // Initialize the input operand.
  initializeInputOperand();

  // Note: we don't need to call emitNativeCalleeGuard for intrinsics.

  ValOperandId arg0Id = writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
  StringOperandId strId = writer.guardToString(arg0Id);

  ValOperandId arg1Id = writer.loadArgumentFixedSlot(ArgumentKind::Arg1, argc_);
  Int32OperandId beginId = writer.guardToInt32(arg1Id);

  ValOperandId arg2Id = writer.loadArgumentFixedSlot(ArgumentKind::Arg2, argc_);
  Int32OperandId lengthId = writer.guardToInt32(arg2Id);

  writer.callSubstringKernelResult(strId, beginId, lengthId);
  writer.returnFromIC();

  trackAttached("SubstringKernel");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachObjectHasPrototype() {
  // Self-hosted code calls this with (object, object) arguments.
  MOZ_ASSERT(argc_ == 2);
  MOZ_ASSERT(args_[0].isObject());
  MOZ_ASSERT(args_[1].isObject());

  auto* obj = &args_[0].toObject().as<NativeObject>();
  auto* proto = &args_[1].toObject().as<NativeObject>();

  // Only attach when obj.__proto__ is proto.
  if (obj->staticPrototype() != proto) {
    return AttachDecision::NoAction;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Note: we don't need to call emitNativeCalleeGuard for intrinsics.

  ValOperandId arg0Id = writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
  ObjOperandId objId = writer.guardToObject(arg0Id);

  writer.guardProto(objId, proto);
  writer.loadBooleanResult(true);
  writer.returnFromIC();

  trackAttached("ObjectHasPrototype");
  return AttachDecision::Attach;
}

static bool CanConvertToString(const Value& v) {
  return v.isString() || v.isNumber() || v.isBoolean() || v.isNullOrUndefined();
}

AttachDecision InlinableNativeIRGenerator::tryAttachString() {
  // Need a single argument that is or can be converted to a string.
  if (argc_ != 1 || !CanConvertToString(args_[0])) {
    return AttachDecision::NoAction;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee is the 'String' function.
  emitNativeCalleeGuard();

  // Guard that the argument is a string or can be converted to one.
  ValOperandId argId = writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
  StringOperandId strId = emitToStringGuard(argId, args_[0]);

  // Return the string.
  writer.loadStringResult(strId);
  writer.returnFromIC();

  trackAttached("String");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachStringConstructor() {
  // Need a single argument that is or can be converted to a string.
  if (argc_ != 1 || !CanConvertToString(args_[0])) {
    return AttachDecision::NoAction;
  }

  RootedString emptyString(cx_, cx_->runtime()->emptyString);
  JSObject* templateObj = StringObject::create(
      cx_, emptyString, /* proto = */ nullptr, TenuredObject);
  if (!templateObj) {
    cx_->recoverFromOutOfMemory();
    return AttachDecision::NoAction;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee is the 'String' function.
  emitNativeCalleeGuard();

  // Guard on number and convert to string.
  ValOperandId argId =
      writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_, flags_);
  StringOperandId strId = emitToStringGuard(argId, args_[0]);

  writer.newStringObjectResult(templateObj, strId);
  writer.returnFromIC();

  trackAttached("StringConstructor");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachStringToStringValueOf() {
  // Expecting no arguments.
  if (argc_ != 0) {
    return AttachDecision::NoAction;
  }

  // Ensure |this| is a primitive string value.
  if (!thisval_.isString()) {
    return AttachDecision::NoAction;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee is the 'toString' OR 'valueOf' native function.
  emitNativeCalleeGuard();

  // Guard |this| is a string.
  ValOperandId thisValId =
      writer.loadArgumentFixedSlot(ArgumentKind::This, argc_);
  StringOperandId strId = writer.guardToString(thisValId);

  // Return the string
  writer.loadStringResult(strId);
  writer.returnFromIC();

  trackAttached("StringToStringValueOf");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachStringReplaceString() {
  // Self-hosted code calls this with (string, string, string) arguments.
  MOZ_ASSERT(argc_ == 3);
  MOZ_ASSERT(args_[0].isString());
  MOZ_ASSERT(args_[1].isString());
  MOZ_ASSERT(args_[2].isString());

  // Initialize the input operand.
  initializeInputOperand();

  // Note: we don't need to call emitNativeCalleeGuard for intrinsics.

  ValOperandId arg0Id = writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
  StringOperandId strId = writer.guardToString(arg0Id);

  ValOperandId arg1Id = writer.loadArgumentFixedSlot(ArgumentKind::Arg1, argc_);
  StringOperandId patternId = writer.guardToString(arg1Id);

  ValOperandId arg2Id = writer.loadArgumentFixedSlot(ArgumentKind::Arg2, argc_);
  StringOperandId replacementId = writer.guardToString(arg2Id);

  writer.stringReplaceStringResult(strId, patternId, replacementId);
  writer.returnFromIC();

  trackAttached("StringReplaceString");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachStringSplitString() {
  // Self-hosted code calls this with (string, string) arguments.
  MOZ_ASSERT(argc_ == 2);
  MOZ_ASSERT(args_[0].isString());
  MOZ_ASSERT(args_[1].isString());

  // Initialize the input operand.
  initializeInputOperand();

  // Note: we don't need to call emitNativeCalleeGuard for intrinsics.

  ValOperandId arg0Id = writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
  StringOperandId strId = writer.guardToString(arg0Id);

  ValOperandId arg1Id = writer.loadArgumentFixedSlot(ArgumentKind::Arg1, argc_);
  StringOperandId separatorId = writer.guardToString(arg1Id);

  writer.stringSplitStringResult(strId, separatorId);
  writer.returnFromIC();

  trackAttached("StringSplitString");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachStringChar(
    StringChar kind) {
  // Need one argument.
  if (argc_ != 1) {
    return AttachDecision::NoAction;
  }

  auto attach = CanAttachStringChar(thisval_, args_[0]);
  if (attach == AttachStringChar::No) {
    return AttachDecision::NoAction;
  }

  bool handleOOB = attach == AttachStringChar::OutOfBounds;

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee is the 'charCodeAt' or 'charAt' native function.
  emitNativeCalleeGuard();

  // Guard this is a string.
  ValOperandId thisValId =
      writer.loadArgumentFixedSlot(ArgumentKind::This, argc_);
  StringOperandId strId = writer.guardToString(thisValId);

  // Guard int32 index.
  ValOperandId indexId =
      writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
  Int32OperandId int32IndexId = writer.guardToInt32Index(indexId);

  // Linearize the string.
  //
  // AttachStringChar doesn't have a separate state when OOB access happens on
  // a string which needs to be linearized, so just linearize unconditionally
  // for out-of-bounds accesses.
  if (attach == AttachStringChar::Linearize ||
      attach == AttachStringChar::OutOfBounds) {
    strId = writer.linearizeForCharAccess(strId, int32IndexId);
  }

  // Load string char or code.
  if (kind == StringChar::CodeAt) {
    writer.loadStringCharCodeResult(strId, int32IndexId, handleOOB);
  } else {
    writer.loadStringCharResult(strId, int32IndexId, handleOOB);
  }

  writer.returnFromIC();

  if (kind == StringChar::CodeAt) {
    trackAttached("StringCharCodeAt");
  } else {
    trackAttached("StringCharAt");
  }

  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachStringCharCodeAt() {
  return tryAttachStringChar(StringChar::CodeAt);
}

AttachDecision InlinableNativeIRGenerator::tryAttachStringCharAt() {
  return tryAttachStringChar(StringChar::At);
}

AttachDecision InlinableNativeIRGenerator::tryAttachStringFromCharCode() {
  // Need one number argument.
  if (argc_ != 1 || !args_[0].isNumber()) {
    return AttachDecision::NoAction;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee is the 'fromCharCode' native function.
  emitNativeCalleeGuard();

  // Guard int32 argument.
  ValOperandId argId = writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
  Int32OperandId codeId;
  if (args_[0].isInt32()) {
    codeId = writer.guardToInt32(argId);
  } else {
    // 'fromCharCode' performs ToUint16 on its input. We can use Uint32
    // semantics, because ToUint16(ToUint32(v)) == ToUint16(v).
    codeId = writer.guardToInt32ModUint32(argId);
  }

  // Return string created from code.
  writer.stringFromCharCodeResult(codeId);
  writer.returnFromIC();

  trackAttached("StringFromCharCode");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachStringFromCodePoint() {
  // Need one int32 argument.
  if (argc_ != 1 || !args_[0].isInt32()) {
    return AttachDecision::NoAction;
  }

  // String.fromCodePoint throws for invalid code points.
  int32_t codePoint = args_[0].toInt32();
  if (codePoint < 0 || codePoint > int32_t(unicode::NonBMPMax)) {
    return AttachDecision::NoAction;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee is the 'fromCodePoint' native function.
  emitNativeCalleeGuard();

  // Guard int32 argument.
  ValOperandId argId = writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
  Int32OperandId codeId = writer.guardToInt32(argId);

  // Return string created from code point.
  writer.stringFromCodePointResult(codeId);
  writer.returnFromIC();

  trackAttached("StringFromCodePoint");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachStringIndexOf() {
  // Need one string argument.
  if (argc_ != 1 || !args_[0].isString()) {
    return AttachDecision::NoAction;
  }

  // Ensure |this| is a primitive string value.
  if (!thisval_.isString()) {
    return AttachDecision::NoAction;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee is the 'indexOf' native function.
  emitNativeCalleeGuard();

  // Guard this is a string.
  ValOperandId thisValId =
      writer.loadArgumentFixedSlot(ArgumentKind::This, argc_);
  StringOperandId strId = writer.guardToString(thisValId);

  // Guard string argument.
  ValOperandId argId = writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
  StringOperandId searchStrId = writer.guardToString(argId);

  writer.stringIndexOfResult(strId, searchStrId);
  writer.returnFromIC();

  trackAttached("StringIndexOf");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachStringStartsWith() {
  // Need one string argument.
  if (argc_ != 1 || !args_[0].isString()) {
    return AttachDecision::NoAction;
  }

  // Ensure |this| is a primitive string value.
  if (!thisval_.isString()) {
    return AttachDecision::NoAction;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee is the 'startsWith' native function.
  emitNativeCalleeGuard();

  // Guard this is a string.
  ValOperandId thisValId =
      writer.loadArgumentFixedSlot(ArgumentKind::This, argc_);
  StringOperandId strId = writer.guardToString(thisValId);

  // Guard string argument.
  ValOperandId argId = writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
  StringOperandId searchStrId = writer.guardToString(argId);

  writer.stringStartsWithResult(strId, searchStrId);
  writer.returnFromIC();

  trackAttached("StringStartsWith");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachStringEndsWith() {
  // Need one string argument.
  if (argc_ != 1 || !args_[0].isString()) {
    return AttachDecision::NoAction;
  }

  // Ensure |this| is a primitive string value.
  if (!thisval_.isString()) {
    return AttachDecision::NoAction;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee is the 'endsWith' native function.
  emitNativeCalleeGuard();

  // Guard this is a string.
  ValOperandId thisValId =
      writer.loadArgumentFixedSlot(ArgumentKind::This, argc_);
  StringOperandId strId = writer.guardToString(thisValId);

  // Guard string argument.
  ValOperandId argId = writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
  StringOperandId searchStrId = writer.guardToString(argId);

  writer.stringEndsWithResult(strId, searchStrId);
  writer.returnFromIC();

  trackAttached("StringEndsWith");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachStringToLowerCase() {
  // Expecting no arguments.
  if (argc_ != 0) {
    return AttachDecision::NoAction;
  }

  // Ensure |this| is a primitive string value.
  if (!thisval_.isString()) {
    return AttachDecision::NoAction;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee is the 'toLowerCase' native function.
  emitNativeCalleeGuard();

  // Guard this is a string.
  ValOperandId thisValId =
      writer.loadArgumentFixedSlot(ArgumentKind::This, argc_);
  StringOperandId strId = writer.guardToString(thisValId);

  // Return string converted to lower-case.
  writer.stringToLowerCaseResult(strId);
  writer.returnFromIC();

  trackAttached("StringToLowerCase");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachStringToUpperCase() {
  // Expecting no arguments.
  if (argc_ != 0) {
    return AttachDecision::NoAction;
  }

  // Ensure |this| is a primitive string value.
  if (!thisval_.isString()) {
    return AttachDecision::NoAction;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee is the 'toUpperCase' native function.
  emitNativeCalleeGuard();

  // Guard this is a string.
  ValOperandId thisValId =
      writer.loadArgumentFixedSlot(ArgumentKind::This, argc_);
  StringOperandId strId = writer.guardToString(thisValId);

  // Return string converted to upper-case.
  writer.stringToUpperCaseResult(strId);
  writer.returnFromIC();

  trackAttached("StringToUpperCase");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachMathRandom() {
  // Expecting no arguments.
  if (argc_ != 0) {
    return AttachDecision::NoAction;
  }

  MOZ_ASSERT(cx_->realm() == callee_->realm(),
             "Shouldn't inline cross-realm Math.random because per-realm RNG");

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee is the 'random' native function.
  emitNativeCalleeGuard();

  mozilla::non_crypto::XorShift128PlusRNG* rng =
      &cx_->realm()->getOrCreateRandomNumberGenerator();
  writer.mathRandomResult(rng);

  writer.returnFromIC();

  trackAttached("MathRandom");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachMathAbs() {
  // Need one argument.
  if (argc_ != 1) {
    return AttachDecision::NoAction;
  }

  if (!args_[0].isNumber()) {
    return AttachDecision::NoAction;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee is the 'abs' native function.
  emitNativeCalleeGuard();

  ValOperandId argumentId =
      writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);

  // abs(INT_MIN) is a double.
  if (args_[0].isInt32() && args_[0].toInt32() != INT_MIN) {
    Int32OperandId int32Id = writer.guardToInt32(argumentId);
    writer.mathAbsInt32Result(int32Id);
  } else {
    NumberOperandId numberId = writer.guardIsNumber(argumentId);
    writer.mathAbsNumberResult(numberId);
  }

  writer.returnFromIC();

  trackAttached("MathAbs");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachMathClz32() {
  // Need one (number) argument.
  if (argc_ != 1 || !args_[0].isNumber()) {
    return AttachDecision::NoAction;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee is the 'clz32' native function.
  emitNativeCalleeGuard();

  ValOperandId argId = writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);

  Int32OperandId int32Id;
  if (args_[0].isInt32()) {
    int32Id = writer.guardToInt32(argId);
  } else {
    MOZ_ASSERT(args_[0].isDouble());
    NumberOperandId numId = writer.guardIsNumber(argId);
    int32Id = writer.truncateDoubleToUInt32(numId);
  }
  writer.mathClz32Result(int32Id);
  writer.returnFromIC();

  trackAttached("MathClz32");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachMathSign() {
  // Need one (number) argument.
  if (argc_ != 1 || !args_[0].isNumber()) {
    return AttachDecision::NoAction;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee is the 'sign' native function.
  emitNativeCalleeGuard();

  ValOperandId argId = writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);

  if (args_[0].isInt32()) {
    Int32OperandId int32Id = writer.guardToInt32(argId);
    writer.mathSignInt32Result(int32Id);
  } else {
    // Math.sign returns a double only if the input is -0 or NaN so try to
    // optimize the common Number => Int32 case.
    double d = math_sign_impl(args_[0].toDouble());
    int32_t unused;
    bool resultIsInt32 = mozilla::NumberIsInt32(d, &unused);

    NumberOperandId numId = writer.guardIsNumber(argId);
    if (resultIsInt32) {
      writer.mathSignNumberToInt32Result(numId);
    } else {
      writer.mathSignNumberResult(numId);
    }
  }

  writer.returnFromIC();

  trackAttached("MathSign");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachMathImul() {
  // Need two (number) arguments.
  if (argc_ != 2 || !args_[0].isNumber() || !args_[1].isNumber()) {
    return AttachDecision::NoAction;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee is the 'imul' native function.
  emitNativeCalleeGuard();

  ValOperandId arg0Id = writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
  ValOperandId arg1Id = writer.loadArgumentFixedSlot(ArgumentKind::Arg1, argc_);

  Int32OperandId int32Arg0Id, int32Arg1Id;
  if (args_[0].isInt32() && args_[1].isInt32()) {
    int32Arg0Id = writer.guardToInt32(arg0Id);
    int32Arg1Id = writer.guardToInt32(arg1Id);
  } else {
    // Treat both arguments as numbers if at least one of them is non-int32.
    NumberOperandId numArg0Id = writer.guardIsNumber(arg0Id);
    NumberOperandId numArg1Id = writer.guardIsNumber(arg1Id);
    int32Arg0Id = writer.truncateDoubleToUInt32(numArg0Id);
    int32Arg1Id = writer.truncateDoubleToUInt32(numArg1Id);
  }
  writer.mathImulResult(int32Arg0Id, int32Arg1Id);
  writer.returnFromIC();

  trackAttached("MathImul");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachMathFloor() {
  // Need one (number) argument.
  if (argc_ != 1 || !args_[0].isNumber()) {
    return AttachDecision::NoAction;
  }

  // Check if the result fits in int32.
  double res = math_floor_impl(args_[0].toNumber());
  int32_t unused;
  bool resultIsInt32 = mozilla::NumberIsInt32(res, &unused);

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee is the 'floor' native function.
  emitNativeCalleeGuard();

  ValOperandId argumentId =
      writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);

  if (args_[0].isInt32()) {
    MOZ_ASSERT(resultIsInt32);

    // Use an indirect truncation to inform the optimizer it needs to preserve
    // a bailout when the input can't be represented as an int32, even if the
    // final result is fully truncated.
    Int32OperandId intId = writer.guardToInt32(argumentId);
    writer.indirectTruncateInt32Result(intId);
  } else {
    NumberOperandId numberId = writer.guardIsNumber(argumentId);

    if (resultIsInt32) {
      writer.mathFloorToInt32Result(numberId);
    } else {
      writer.mathFloorNumberResult(numberId);
    }
  }

  writer.returnFromIC();

  trackAttached("MathFloor");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachMathCeil() {
  // Need one (number) argument.
  if (argc_ != 1 || !args_[0].isNumber()) {
    return AttachDecision::NoAction;
  }

  // Check if the result fits in int32.
  double res = math_ceil_impl(args_[0].toNumber());
  int32_t unused;
  bool resultIsInt32 = mozilla::NumberIsInt32(res, &unused);

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee is the 'ceil' native function.
  emitNativeCalleeGuard();

  ValOperandId argumentId =
      writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);

  if (args_[0].isInt32()) {
    MOZ_ASSERT(resultIsInt32);

    // Use an indirect truncation to inform the optimizer it needs to preserve
    // a bailout when the input can't be represented as an int32, even if the
    // final result is fully truncated.
    Int32OperandId intId = writer.guardToInt32(argumentId);
    writer.indirectTruncateInt32Result(intId);
  } else {
    NumberOperandId numberId = writer.guardIsNumber(argumentId);

    if (resultIsInt32) {
      writer.mathCeilToInt32Result(numberId);
    } else {
      writer.mathCeilNumberResult(numberId);
    }
  }

  writer.returnFromIC();

  trackAttached("MathCeil");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachMathTrunc() {
  // Need one (number) argument.
  if (argc_ != 1 || !args_[0].isNumber()) {
    return AttachDecision::NoAction;
  }

  // Check if the result fits in int32.
  double res = math_trunc_impl(args_[0].toNumber());
  int32_t unused;
  bool resultIsInt32 = mozilla::NumberIsInt32(res, &unused);

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee is the 'trunc' native function.
  emitNativeCalleeGuard();

  ValOperandId argumentId =
      writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);

  if (args_[0].isInt32()) {
    MOZ_ASSERT(resultIsInt32);

    // We don't need an indirect truncation barrier here, because Math.trunc
    // always truncates, but never rounds its input away from zero.
    Int32OperandId intId = writer.guardToInt32(argumentId);
    writer.loadInt32Result(intId);
  } else {
    NumberOperandId numberId = writer.guardIsNumber(argumentId);

    if (resultIsInt32) {
      writer.mathTruncToInt32Result(numberId);
    } else {
      writer.mathTruncNumberResult(numberId);
    }
  }

  writer.returnFromIC();

  trackAttached("MathTrunc");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachMathRound() {
  // Need one (number) argument.
  if (argc_ != 1 || !args_[0].isNumber()) {
    return AttachDecision::NoAction;
  }

  // Check if the result fits in int32.
  double res = math_round_impl(args_[0].toNumber());
  int32_t unused;
  bool resultIsInt32 = mozilla::NumberIsInt32(res, &unused);

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee is the 'round' native function.
  emitNativeCalleeGuard();

  ValOperandId argumentId =
      writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);

  if (args_[0].isInt32()) {
    MOZ_ASSERT(resultIsInt32);

    // Use an indirect truncation to inform the optimizer it needs to preserve
    // a bailout when the input can't be represented as an int32, even if the
    // final result is fully truncated.
    Int32OperandId intId = writer.guardToInt32(argumentId);
    writer.indirectTruncateInt32Result(intId);
  } else {
    NumberOperandId numberId = writer.guardIsNumber(argumentId);

    if (resultIsInt32) {
      writer.mathRoundToInt32Result(numberId);
    } else {
      writer.mathFunctionNumberResult(numberId, UnaryMathFunction::Round);
    }
  }

  writer.returnFromIC();

  trackAttached("MathRound");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachMathSqrt() {
  // Need one (number) argument.
  if (argc_ != 1 || !args_[0].isNumber()) {
    return AttachDecision::NoAction;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee is the 'sqrt' native function.
  emitNativeCalleeGuard();

  ValOperandId argumentId =
      writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
  NumberOperandId numberId = writer.guardIsNumber(argumentId);
  writer.mathSqrtNumberResult(numberId);
  writer.returnFromIC();

  trackAttached("MathSqrt");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachMathFRound() {
  // Need one (number) argument.
  if (argc_ != 1 || !args_[0].isNumber()) {
    return AttachDecision::NoAction;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee is the 'fround' native function.
  emitNativeCalleeGuard();

  ValOperandId argumentId =
      writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
  NumberOperandId numberId = writer.guardIsNumber(argumentId);
  writer.mathFRoundNumberResult(numberId);
  writer.returnFromIC();

  trackAttached("MathFRound");
  return AttachDecision::Attach;
}

static bool CanAttachInt32Pow(const Value& baseVal, const Value& powerVal) {
  auto valToInt32 = [](const Value& v) {
    if (v.isInt32()) {
      return v.toInt32();
    }
    if (v.isBoolean()) {
      return int32_t(v.toBoolean());
    }
    MOZ_ASSERT(v.isNull());
    return 0;
  };
  int32_t base = valToInt32(baseVal);
  int32_t power = valToInt32(powerVal);

  // x^y where y < 0 is most of the time not an int32, except when x is 1 or y
  // gets large enough. It's hard to determine when exactly y is "large enough",
  // so we don't use Int32PowResult when x != 1 and y < 0.
  // Note: it's important for this condition to match the code generated by
  // MacroAssembler::pow32 to prevent failure loops.
  if (power < 0) {
    return base == 1;
  }

  double res = powi(base, power);
  int32_t unused;
  return mozilla::NumberIsInt32(res, &unused);
}

AttachDecision InlinableNativeIRGenerator::tryAttachMathPow() {
  // Need two number arguments.
  if (argc_ != 2 || !args_[0].isNumber() || !args_[1].isNumber()) {
    return AttachDecision::NoAction;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee is the 'pow' function.
  emitNativeCalleeGuard();

  ValOperandId baseId = writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
  ValOperandId exponentId =
      writer.loadArgumentFixedSlot(ArgumentKind::Arg1, argc_);

  if (args_[0].isInt32() && args_[1].isInt32() &&
      CanAttachInt32Pow(args_[0], args_[1])) {
    Int32OperandId baseInt32Id = writer.guardToInt32(baseId);
    Int32OperandId exponentInt32Id = writer.guardToInt32(exponentId);
    writer.int32PowResult(baseInt32Id, exponentInt32Id);
  } else {
    NumberOperandId baseNumberId = writer.guardIsNumber(baseId);
    NumberOperandId exponentNumberId = writer.guardIsNumber(exponentId);
    writer.doublePowResult(baseNumberId, exponentNumberId);
  }

  writer.returnFromIC();

  trackAttached("MathPow");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachMathHypot() {
  // Only optimize if there are 2-4 arguments.
  if (argc_ < 2 || argc_ > 4) {
    return AttachDecision::NoAction;
  }

  for (size_t i = 0; i < argc_; i++) {
    if (!args_[i].isNumber()) {
      return AttachDecision::NoAction;
    }
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee is the 'hypot' native function.
  emitNativeCalleeGuard();

  ValOperandId firstId =
      writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
  ValOperandId secondId =
      writer.loadArgumentFixedSlot(ArgumentKind::Arg1, argc_);

  NumberOperandId firstNumId = writer.guardIsNumber(firstId);
  NumberOperandId secondNumId = writer.guardIsNumber(secondId);

  ValOperandId thirdId;
  ValOperandId fourthId;
  NumberOperandId thirdNumId;
  NumberOperandId fourthNumId;

  switch (argc_) {
    case 2:
      writer.mathHypot2NumberResult(firstNumId, secondNumId);
      break;
    case 3:
      thirdId = writer.loadArgumentFixedSlot(ArgumentKind::Arg2, argc_);
      thirdNumId = writer.guardIsNumber(thirdId);
      writer.mathHypot3NumberResult(firstNumId, secondNumId, thirdNumId);
      break;
    case 4:
      thirdId = writer.loadArgumentFixedSlot(ArgumentKind::Arg2, argc_);
      fourthId = writer.loadArgumentFixedSlot(ArgumentKind::Arg3, argc_);
      thirdNumId = writer.guardIsNumber(thirdId);
      fourthNumId = writer.guardIsNumber(fourthId);
      writer.mathHypot4NumberResult(firstNumId, secondNumId, thirdNumId,
                                    fourthNumId);
      break;
    default:
      MOZ_CRASH("Unexpected number of arguments to hypot function.");
  }

  writer.returnFromIC();

  trackAttached("MathHypot");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachMathATan2() {
  // Requires two numbers as arguments.
  if (argc_ != 2 || !args_[0].isNumber() || !args_[1].isNumber()) {
    return AttachDecision::NoAction;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee is the 'atan2' native function.
  emitNativeCalleeGuard();

  ValOperandId yId = writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
  ValOperandId xId = writer.loadArgumentFixedSlot(ArgumentKind::Arg1, argc_);

  NumberOperandId yNumberId = writer.guardIsNumber(yId);
  NumberOperandId xNumberId = writer.guardIsNumber(xId);

  writer.mathAtan2NumberResult(yNumberId, xNumberId);
  writer.returnFromIC();

  trackAttached("MathAtan2");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachMathMinMax(bool isMax) {
  // For now only optimize if there are 1-4 arguments.
  if (argc_ < 1 || argc_ > 4) {
    return AttachDecision::NoAction;
  }

  // Ensure all arguments are numbers.
  bool allInt32 = true;
  for (size_t i = 0; i < argc_; i++) {
    if (!args_[i].isNumber()) {
      return AttachDecision::NoAction;
    }
    if (!args_[i].isInt32()) {
      allInt32 = false;
    }
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee is this Math function.
  emitNativeCalleeGuard();

  if (allInt32) {
    ValOperandId valId =
        writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
    Int32OperandId resId = writer.guardToInt32(valId);
    for (size_t i = 1; i < argc_; i++) {
      ValOperandId argId =
          writer.loadArgumentFixedSlot(ArgumentKindForArgIndex(i), argc_);
      Int32OperandId argInt32Id = writer.guardToInt32(argId);
      resId = writer.int32MinMax(isMax, resId, argInt32Id);
    }
    writer.loadInt32Result(resId);
  } else {
    ValOperandId valId =
        writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
    NumberOperandId resId = writer.guardIsNumber(valId);
    for (size_t i = 1; i < argc_; i++) {
      ValOperandId argId =
          writer.loadArgumentFixedSlot(ArgumentKindForArgIndex(i), argc_);
      NumberOperandId argNumId = writer.guardIsNumber(argId);
      resId = writer.numberMinMax(isMax, resId, argNumId);
    }
    writer.loadDoubleResult(resId);
  }

  writer.returnFromIC();

  trackAttached(isMax ? "MathMax" : "MathMin");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachSpreadMathMinMax(
    bool isMax) {
  MOZ_ASSERT(flags_.getArgFormat() == CallFlags::Spread ||
             flags_.getArgFormat() == CallFlags::FunApplyArray);

  // The result will be an int32 if there is at least one argument,
  // and all the arguments are int32.
  bool int32Result = args_.length() > 0;
  for (size_t i = 0; i < args_.length(); i++) {
    if (!args_[i].isNumber()) {
      return AttachDecision::NoAction;
    }
    if (!args_[i].isInt32()) {
      int32Result = false;
    }
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee is this Math function.
  emitNativeCalleeGuard();

  // Load the argument array.
  ObjOperandId argsId = emitLoadArgsArray();

  if (int32Result) {
    writer.int32MinMaxArrayResult(argsId, isMax);
  } else {
    writer.numberMinMaxArrayResult(argsId, isMax);
  }

  writer.returnFromIC();

  trackAttached(isMax ? "MathMaxArray" : "MathMinArray");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachMathFunction(
    UnaryMathFunction fun) {
  // Need one argument.
  if (argc_ != 1) {
    return AttachDecision::NoAction;
  }

  if (!args_[0].isNumber()) {
    return AttachDecision::NoAction;
  }

  if (math_use_fdlibm_for_sin_cos_tan() ||
      callee_->realm()->behaviors().shouldResistFingerprinting()) {
    switch (fun) {
      case UnaryMathFunction::SinNative:
        fun = UnaryMathFunction::SinFdlibm;
        break;
      case UnaryMathFunction::CosNative:
        fun = UnaryMathFunction::CosFdlibm;
        break;
      case UnaryMathFunction::TanNative:
        fun = UnaryMathFunction::TanFdlibm;
        break;
      default:
        break;
    }
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee is this Math function.
  emitNativeCalleeGuard();

  ValOperandId argumentId =
      writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
  NumberOperandId numberId = writer.guardIsNumber(argumentId);
  writer.mathFunctionNumberResult(numberId, fun);
  writer.returnFromIC();

  trackAttached("MathFunction");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachNumber() {
  // Expect a single string argument.
  if (argc_ != 1 || !args_[0].isString()) {
    return AttachDecision::NoAction;
  }

  double num;
  if (!StringToNumber(cx_, args_[0].toString(), &num)) {
    cx_->recoverFromOutOfMemory();
    return AttachDecision::NoAction;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee is the `Number` function.
  emitNativeCalleeGuard();

  // Guard that the argument is a string.
  ValOperandId argId = writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
  StringOperandId strId = writer.guardToString(argId);

  // Return either an Int32 or Double result.
  int32_t unused;
  if (mozilla::NumberIsInt32(num, &unused)) {
    Int32OperandId resultId = writer.guardStringToInt32(strId);
    writer.loadInt32Result(resultId);
  } else {
    NumberOperandId resultId = writer.guardStringToNumber(strId);
    writer.loadDoubleResult(resultId);
  }
  writer.returnFromIC();

  trackAttached("Number");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachNumberParseInt() {
  // Expected arguments: input (string or number), optional radix (int32).
  if (argc_ < 1 || argc_ > 2) {
    return AttachDecision::NoAction;
  }
  if (!args_[0].isString() && !args_[0].isNumber()) {
    return AttachDecision::NoAction;
  }
  if (args_[0].isDouble()) {
    double d = args_[0].toDouble();

    // See num_parseInt for why we have to reject numbers smaller than 1.0e-6.
    // Negative numbers in the exclusive range (-1, -0) return -0.
    bool canTruncateToInt32 =
        (DOUBLE_DECIMAL_IN_SHORTEST_LOW <= d && d <= double(INT32_MAX)) ||
        (double(INT32_MIN) <= d && d <= -1.0) || (d == 0.0);
    if (!canTruncateToInt32) {
      return AttachDecision::NoAction;
    }
  }
  if (argc_ > 1 && !args_[1].isInt32(10)) {
    return AttachDecision::NoAction;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee is the 'parseInt' native function.
  emitNativeCalleeGuard();

  auto guardRadix = [&]() {
    ValOperandId radixId =
        writer.loadArgumentFixedSlot(ArgumentKind::Arg1, argc_);
    Int32OperandId intRadixId = writer.guardToInt32(radixId);
    writer.guardSpecificInt32(intRadixId, 10);
    return intRadixId;
  };

  ValOperandId inputId =
      writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);

  if (args_[0].isString()) {
    StringOperandId strId = writer.guardToString(inputId);

    Int32OperandId intRadixId;
    if (argc_ > 1) {
      intRadixId = guardRadix();
    } else {
      intRadixId = writer.loadInt32Constant(0);
    }

    writer.numberParseIntResult(strId, intRadixId);
  } else if (args_[0].isInt32()) {
    Int32OperandId intId = writer.guardToInt32(inputId);
    if (argc_ > 1) {
      guardRadix();
    }
    writer.loadInt32Result(intId);
  } else {
    MOZ_ASSERT(args_[0].isDouble());

    NumberOperandId numId = writer.guardIsNumber(inputId);
    if (argc_ > 1) {
      guardRadix();
    }
    writer.doubleParseIntResult(numId);
  }

  writer.returnFromIC();

  trackAttached("NumberParseInt");
  return AttachDecision::Attach;
}

StringOperandId IRGenerator::emitToStringGuard(ValOperandId id,
                                               const Value& v) {
  MOZ_ASSERT(CanConvertToString(v));
  if (v.isString()) {
    return writer.guardToString(id);
  }
  if (v.isBoolean()) {
    BooleanOperandId boolId = writer.guardToBoolean(id);
    return writer.booleanToString(boolId);
  }
  if (v.isNull()) {
    writer.guardIsNull(id);
    return writer.loadConstantString(cx_->names().null);
  }
  if (v.isUndefined()) {
    writer.guardIsUndefined(id);
    return writer.loadConstantString(cx_->names().undefined);
  }
  if (v.isInt32()) {
    Int32OperandId intId = writer.guardToInt32(id);
    return writer.callInt32ToString(intId);
  }
  // At this point we are creating an IC that will handle
  // both Int32 and Double cases.
  MOZ_ASSERT(v.isNumber());
  NumberOperandId numId = writer.guardIsNumber(id);
  return writer.callNumberToString(numId);
}

AttachDecision InlinableNativeIRGenerator::tryAttachNumberToString() {
  // Expecting no arguments or a single int32 argument.
  if (argc_ > 1) {
    return AttachDecision::NoAction;
  }
  if (argc_ == 1 && !args_[0].isInt32()) {
    return AttachDecision::NoAction;
  }

  // Ensure |this| is a primitive number value.
  if (!thisval_.isNumber()) {
    return AttachDecision::NoAction;
  }

  // No arguments means base 10.
  int32_t base = 10;
  if (argc_ > 0) {
    base = args_[0].toInt32();
    if (base < 2 || base > 36) {
      return AttachDecision::NoAction;
    }

    // Non-decimal bases currently only support int32 inputs.
    if (base != 10 && !thisval_.isInt32()) {
      return AttachDecision::NoAction;
    }
  }
  MOZ_ASSERT(2 <= base && base <= 36);

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee is the 'toString' native function.
  emitNativeCalleeGuard();

  // Initialize the |this| operand.
  ValOperandId thisValId =
      writer.loadArgumentFixedSlot(ArgumentKind::This, argc_);

  // Guard on number and convert to string.
  if (base == 10) {
    // If an explicit base was passed, guard its value.
    if (argc_ > 0) {
      // Guard the `base` argument is an int32.
      ValOperandId baseId =
          writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
      Int32OperandId intBaseId = writer.guardToInt32(baseId);

      // Guard `base` is 10 for decimal toString representation.
      writer.guardSpecificInt32(intBaseId, 10);
    }

    StringOperandId strId = emitToStringGuard(thisValId, thisval_);

    // Return the string.
    writer.loadStringResult(strId);
  } else {
    MOZ_ASSERT(argc_ > 0);

    // Guard the |this| value is an int32.
    Int32OperandId thisIntId = writer.guardToInt32(thisValId);

    // Guard the `base` argument is an int32.
    ValOperandId baseId =
        writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
    Int32OperandId intBaseId = writer.guardToInt32(baseId);

    // Return the string.
    writer.int32ToStringWithBaseResult(thisIntId, intBaseId);
  }

  writer.returnFromIC();

  trackAttached("NumberToString");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachReflectGetPrototypeOf() {
  // Need one argument.
  if (argc_ != 1) {
    return AttachDecision::NoAction;
  }

  if (!args_[0].isObject()) {
    return AttachDecision::NoAction;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee is the 'getPrototypeOf' native function.
  emitNativeCalleeGuard();

  ValOperandId argumentId =
      writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
  ObjOperandId objId = writer.guardToObject(argumentId);

  writer.reflectGetPrototypeOfResult(objId);
  writer.returnFromIC();

  trackAttached("ReflectGetPrototypeOf");
  return AttachDecision::Attach;
}

static bool AtomicsMeetsPreconditions(TypedArrayObject* typedArray,
                                      const Value& index) {
  switch (typedArray->type()) {
    case Scalar::Int8:
    case Scalar::Uint8:
    case Scalar::Int16:
    case Scalar::Uint16:
    case Scalar::Int32:
    case Scalar::Uint32:
    case Scalar::BigInt64:
    case Scalar::BigUint64:
      break;

    case Scalar::Float32:
    case Scalar::Float64:
    case Scalar::Uint8Clamped:
      // Exclude floating types and Uint8Clamped.
      return false;

    case Scalar::MaxTypedArrayViewType:
    case Scalar::Int64:
    case Scalar::Simd128:
      MOZ_CRASH("Unsupported TypedArray type");
  }

  // Bounds check the index argument.
  int64_t indexInt64;
  if (!ValueIsInt64Index(index, &indexInt64)) {
    return false;
  }
  if (indexInt64 < 0 || uint64_t(indexInt64) >= typedArray->length()) {
    return false;
  }

  return true;
}

AttachDecision InlinableNativeIRGenerator::tryAttachAtomicsCompareExchange() {
  if (!JitSupportsAtomics()) {
    return AttachDecision::NoAction;
  }

  // Need four arguments.
  if (argc_ != 4) {
    return AttachDecision::NoAction;
  }

  // Arguments: typedArray, index (number), expected, replacement.
  if (!args_[0].isObject() || !args_[0].toObject().is<TypedArrayObject>()) {
    return AttachDecision::NoAction;
  }
  if (!args_[1].isNumber()) {
    return AttachDecision::NoAction;
  }

  auto* typedArray = &args_[0].toObject().as<TypedArrayObject>();
  if (!AtomicsMeetsPreconditions(typedArray, args_[1])) {
    return AttachDecision::NoAction;
  }

  Scalar::Type elementType = typedArray->type();
  if (!ValueIsNumeric(elementType, args_[2])) {
    return AttachDecision::NoAction;
  }
  if (!ValueIsNumeric(elementType, args_[3])) {
    return AttachDecision::NoAction;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee is the `compareExchange` native function.
  emitNativeCalleeGuard();

  ValOperandId arg0Id = writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
  ObjOperandId objId = writer.guardToObject(arg0Id);
  writer.guardShapeForClass(objId, typedArray->shape());

  // Convert index to intPtr.
  ValOperandId indexId =
      writer.loadArgumentFixedSlot(ArgumentKind::Arg1, argc_);
  IntPtrOperandId intPtrIndexId =
      guardToIntPtrIndex(args_[1], indexId, /* supportOOB = */ false);

  // Convert expected value to int32/BigInt.
  ValOperandId expectedId =
      writer.loadArgumentFixedSlot(ArgumentKind::Arg2, argc_);
  OperandId numericExpectedId = emitNumericGuard(expectedId, elementType);

  // Convert replacement value to int32/BigInt.
  ValOperandId replacementId =
      writer.loadArgumentFixedSlot(ArgumentKind::Arg3, argc_);
  OperandId numericReplacementId = emitNumericGuard(replacementId, elementType);

  writer.atomicsCompareExchangeResult(objId, intPtrIndexId, numericExpectedId,
                                      numericReplacementId, typedArray->type());
  writer.returnFromIC();

  trackAttached("AtomicsCompareExchange");
  return AttachDecision::Attach;
}

bool InlinableNativeIRGenerator::canAttachAtomicsReadWriteModify() {
  if (!JitSupportsAtomics()) {
    return false;
  }

  // Need three arguments.
  if (argc_ != 3) {
    return false;
  }

  // Arguments: typedArray, index (number), value.
  if (!args_[0].isObject() || !args_[0].toObject().is<TypedArrayObject>()) {
    return false;
  }
  if (!args_[1].isNumber()) {
    return false;
  }

  auto* typedArray = &args_[0].toObject().as<TypedArrayObject>();
  if (!AtomicsMeetsPreconditions(typedArray, args_[1])) {
    return false;
  }
  if (!ValueIsNumeric(typedArray->type(), args_[2])) {
    return false;
  }
  return true;
}

InlinableNativeIRGenerator::AtomicsReadWriteModifyOperands
InlinableNativeIRGenerator::emitAtomicsReadWriteModifyOperands() {
  MOZ_ASSERT(canAttachAtomicsReadWriteModify());

  auto* typedArray = &args_[0].toObject().as<TypedArrayObject>();

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee is this Atomics function.
  emitNativeCalleeGuard();

  ValOperandId arg0Id = writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
  ObjOperandId objId = writer.guardToObject(arg0Id);
  writer.guardShapeForClass(objId, typedArray->shape());

  // Convert index to intPtr.
  ValOperandId indexId =
      writer.loadArgumentFixedSlot(ArgumentKind::Arg1, argc_);
  IntPtrOperandId intPtrIndexId =
      guardToIntPtrIndex(args_[1], indexId, /* supportOOB = */ false);

  // Convert value to int32/BigInt.
  ValOperandId valueId =
      writer.loadArgumentFixedSlot(ArgumentKind::Arg2, argc_);
  OperandId numericValueId = emitNumericGuard(valueId, typedArray->type());

  return {objId, intPtrIndexId, numericValueId};
}

AttachDecision InlinableNativeIRGenerator::tryAttachAtomicsExchange() {
  if (!canAttachAtomicsReadWriteModify()) {
    return AttachDecision::NoAction;
  }

  auto [objId, intPtrIndexId, numericValueId] =
      emitAtomicsReadWriteModifyOperands();

  auto* typedArray = &args_[0].toObject().as<TypedArrayObject>();

  writer.atomicsExchangeResult(objId, intPtrIndexId, numericValueId,
                               typedArray->type());
  writer.returnFromIC();

  trackAttached("AtomicsExchange");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachAtomicsAdd() {
  if (!canAttachAtomicsReadWriteModify()) {
    return AttachDecision::NoAction;
  }

  auto [objId, intPtrIndexId, numericValueId] =
      emitAtomicsReadWriteModifyOperands();

  auto* typedArray = &args_[0].toObject().as<TypedArrayObject>();
  bool forEffect = ignoresResult();

  writer.atomicsAddResult(objId, intPtrIndexId, numericValueId,
                          typedArray->type(), forEffect);
  writer.returnFromIC();

  trackAttached("AtomicsAdd");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachAtomicsSub() {
  if (!canAttachAtomicsReadWriteModify()) {
    return AttachDecision::NoAction;
  }

  auto [objId, intPtrIndexId, numericValueId] =
      emitAtomicsReadWriteModifyOperands();

  auto* typedArray = &args_[0].toObject().as<TypedArrayObject>();
  bool forEffect = ignoresResult();

  writer.atomicsSubResult(objId, intPtrIndexId, numericValueId,
                          typedArray->type(), forEffect);
  writer.returnFromIC();

  trackAttached("AtomicsSub");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachAtomicsAnd() {
  if (!canAttachAtomicsReadWriteModify()) {
    return AttachDecision::NoAction;
  }

  auto [objId, intPtrIndexId, numericValueId] =
      emitAtomicsReadWriteModifyOperands();

  auto* typedArray = &args_[0].toObject().as<TypedArrayObject>();
  bool forEffect = ignoresResult();

  writer.atomicsAndResult(objId, intPtrIndexId, numericValueId,
                          typedArray->type(), forEffect);
  writer.returnFromIC();

  trackAttached("AtomicsAnd");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachAtomicsOr() {
  if (!canAttachAtomicsReadWriteModify()) {
    return AttachDecision::NoAction;
  }

  auto [objId, intPtrIndexId, numericValueId] =
      emitAtomicsReadWriteModifyOperands();

  auto* typedArray = &args_[0].toObject().as<TypedArrayObject>();
  bool forEffect = ignoresResult();

  writer.atomicsOrResult(objId, intPtrIndexId, numericValueId,
                         typedArray->type(), forEffect);
  writer.returnFromIC();

  trackAttached("AtomicsOr");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachAtomicsXor() {
  if (!canAttachAtomicsReadWriteModify()) {
    return AttachDecision::NoAction;
  }

  auto [objId, intPtrIndexId, numericValueId] =
      emitAtomicsReadWriteModifyOperands();

  auto* typedArray = &args_[0].toObject().as<TypedArrayObject>();
  bool forEffect = ignoresResult();

  writer.atomicsXorResult(objId, intPtrIndexId, numericValueId,
                          typedArray->type(), forEffect);
  writer.returnFromIC();

  trackAttached("AtomicsXor");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachAtomicsLoad() {
  if (!JitSupportsAtomics()) {
    return AttachDecision::NoAction;
  }

  // Need two arguments.
  if (argc_ != 2) {
    return AttachDecision::NoAction;
  }

  // Arguments: typedArray, index (number).
  if (!args_[0].isObject() || !args_[0].toObject().is<TypedArrayObject>()) {
    return AttachDecision::NoAction;
  }
  if (!args_[1].isNumber()) {
    return AttachDecision::NoAction;
  }

  auto* typedArray = &args_[0].toObject().as<TypedArrayObject>();
  if (!AtomicsMeetsPreconditions(typedArray, args_[1])) {
    return AttachDecision::NoAction;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee is the `load` native function.
  emitNativeCalleeGuard();

  ValOperandId arg0Id = writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
  ObjOperandId objId = writer.guardToObject(arg0Id);
  writer.guardShapeForClass(objId, typedArray->shape());

  // Convert index to intPtr.
  ValOperandId indexId =
      writer.loadArgumentFixedSlot(ArgumentKind::Arg1, argc_);
  IntPtrOperandId intPtrIndexId =
      guardToIntPtrIndex(args_[1], indexId, /* supportOOB = */ false);

  writer.atomicsLoadResult(objId, intPtrIndexId, typedArray->type());
  writer.returnFromIC();

  trackAttached("AtomicsLoad");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachAtomicsStore() {
  if (!JitSupportsAtomics()) {
    return AttachDecision::NoAction;
  }

  // Need three arguments.
  if (argc_ != 3) {
    return AttachDecision::NoAction;
  }

  // Atomics.store() is annoying because it returns the result of converting the
  // value by ToInteger(), not the input value, nor the result of converting the
  // value by ToInt32(). It is especially annoying because almost nobody uses
  // the result value.
  //
  // As an expedient compromise, therefore, we inline only if the result is
  // obviously unused or if the argument is already Int32 and thus requires no
  // conversion.

  // Arguments: typedArray, index (number), value.
  if (!args_[0].isObject() || !args_[0].toObject().is<TypedArrayObject>()) {
    return AttachDecision::NoAction;
  }
  if (!args_[1].isNumber()) {
    return AttachDecision::NoAction;
  }

  auto* typedArray = &args_[0].toObject().as<TypedArrayObject>();
  if (!AtomicsMeetsPreconditions(typedArray, args_[1])) {
    return AttachDecision::NoAction;
  }

  Scalar::Type elementType = typedArray->type();
  if (!ValueIsNumeric(elementType, args_[2])) {
    return AttachDecision::NoAction;
  }

  bool guardIsInt32 = !Scalar::isBigIntType(elementType) && !ignoresResult();

  if (guardIsInt32 && !args_[2].isInt32()) {
    return AttachDecision::NoAction;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee is the `store` native function.
  emitNativeCalleeGuard();

  ValOperandId arg0Id = writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
  ObjOperandId objId = writer.guardToObject(arg0Id);
  writer.guardShapeForClass(objId, typedArray->shape());

  // Convert index to intPtr.
  ValOperandId indexId =
      writer.loadArgumentFixedSlot(ArgumentKind::Arg1, argc_);
  IntPtrOperandId intPtrIndexId =
      guardToIntPtrIndex(args_[1], indexId, /* supportOOB = */ false);

  // Ensure value is int32 or BigInt.
  ValOperandId valueId =
      writer.loadArgumentFixedSlot(ArgumentKind::Arg2, argc_);
  OperandId numericValueId;
  if (guardIsInt32) {
    numericValueId = writer.guardToInt32(valueId);
  } else {
    numericValueId = emitNumericGuard(valueId, elementType);
  }

  writer.atomicsStoreResult(objId, intPtrIndexId, numericValueId,
                            typedArray->type());
  writer.returnFromIC();

  trackAttached("AtomicsStore");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachAtomicsIsLockFree() {
  // Need one argument.
  if (argc_ != 1) {
    return AttachDecision::NoAction;
  }

  if (!args_[0].isInt32()) {
    return AttachDecision::NoAction;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee is the `isLockFree` native function.
  emitNativeCalleeGuard();

  // Ensure value is int32.
  ValOperandId valueId =
      writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
  Int32OperandId int32ValueId = writer.guardToInt32(valueId);

  writer.atomicsIsLockFreeResult(int32ValueId);
  writer.returnFromIC();

  trackAttached("AtomicsIsLockFree");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachBoolean() {
  // Need zero or one argument.
  if (argc_ > 1) {
    return AttachDecision::NoAction;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee is the 'Boolean' native function.
  emitNativeCalleeGuard();

  if (argc_ == 0) {
    writer.loadBooleanResult(false);
  } else {
    ValOperandId valId =
        writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);

    writer.loadValueTruthyResult(valId);
  }

  writer.returnFromIC();

  trackAttached("Boolean");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachBailout() {
  // Expecting no arguments.
  if (argc_ != 0) {
    return AttachDecision::NoAction;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee is the 'bailout' native function.
  emitNativeCalleeGuard();

  writer.bailout();
  writer.loadUndefinedResult();
  writer.returnFromIC();

  trackAttached("Bailout");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachAssertFloat32() {
  // Expecting two arguments.
  if (argc_ != 2) {
    return AttachDecision::NoAction;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee is the 'assertFloat32' native function.
  emitNativeCalleeGuard();

  // TODO: Warp doesn't yet optimize Float32 (bug 1655773).

  // NOP when not in IonMonkey.
  writer.loadUndefinedResult();
  writer.returnFromIC();

  trackAttached("AssertFloat32");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachAssertRecoveredOnBailout() {
  // Expecting two arguments.
  if (argc_ != 2) {
    return AttachDecision::NoAction;
  }

  // (Fuzzing unsafe) testing function which must be called with a constant
  // boolean as its second argument.
  bool mustBeRecovered = args_[1].toBoolean();

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee is the 'assertRecoveredOnBailout' native function.
  emitNativeCalleeGuard();

  ValOperandId valId = writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);

  writer.assertRecoveredOnBailoutResult(valId, mustBeRecovered);
  writer.returnFromIC();

  trackAttached("AssertRecoveredOnBailout");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachObjectIs() {
  // Need two arguments.
  if (argc_ != 2) {
    return AttachDecision::NoAction;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee is the `is` native function.
  emitNativeCalleeGuard();

  ValOperandId lhsId = writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
  ValOperandId rhsId = writer.loadArgumentFixedSlot(ArgumentKind::Arg1, argc_);

  HandleValue lhs = args_[0];
  HandleValue rhs = args_[1];

  if (!isFirstStub()) {
    writer.sameValueResult(lhsId, rhsId);
  } else if (lhs.isNumber() && rhs.isNumber() &&
             !(lhs.isInt32() && rhs.isInt32())) {
    NumberOperandId lhsNumId = writer.guardIsNumber(lhsId);
    NumberOperandId rhsNumId = writer.guardIsNumber(rhsId);
    writer.compareDoubleSameValueResult(lhsNumId, rhsNumId);
  } else if (!SameType(lhs, rhs)) {
    // Compare tags for strictly different types.
    ValueTagOperandId lhsTypeId = writer.loadValueTag(lhsId);
    ValueTagOperandId rhsTypeId = writer.loadValueTag(rhsId);
    writer.guardTagNotEqual(lhsTypeId, rhsTypeId);
    writer.loadBooleanResult(false);
  } else {
    MOZ_ASSERT(lhs.type() == rhs.type());
    MOZ_ASSERT(lhs.type() != JS::ValueType::Double);

    switch (lhs.type()) {
      case JS::ValueType::Int32: {
        Int32OperandId lhsIntId = writer.guardToInt32(lhsId);
        Int32OperandId rhsIntId = writer.guardToInt32(rhsId);
        writer.compareInt32Result(JSOp::StrictEq, lhsIntId, rhsIntId);
        break;
      }
      case JS::ValueType::Boolean: {
        Int32OperandId lhsIntId = writer.guardBooleanToInt32(lhsId);
        Int32OperandId rhsIntId = writer.guardBooleanToInt32(rhsId);
        writer.compareInt32Result(JSOp::StrictEq, lhsIntId, rhsIntId);
        break;
      }
      case JS::ValueType::Undefined: {
        writer.guardIsUndefined(lhsId);
        writer.guardIsUndefined(rhsId);
        writer.loadBooleanResult(true);
        break;
      }
      case JS::ValueType::Null: {
        writer.guardIsNull(lhsId);
        writer.guardIsNull(rhsId);
        writer.loadBooleanResult(true);
        break;
      }
      case JS::ValueType::String: {
        StringOperandId lhsStrId = writer.guardToString(lhsId);
        StringOperandId rhsStrId = writer.guardToString(rhsId);
        writer.compareStringResult(JSOp::StrictEq, lhsStrId, rhsStrId);
        break;
      }
      case JS::ValueType::Symbol: {
        SymbolOperandId lhsSymId = writer.guardToSymbol(lhsId);
        SymbolOperandId rhsSymId = writer.guardToSymbol(rhsId);
        writer.compareSymbolResult(JSOp::StrictEq, lhsSymId, rhsSymId);
        break;
      }
      case JS::ValueType::BigInt: {
        BigIntOperandId lhsBigIntId = writer.guardToBigInt(lhsId);
        BigIntOperandId rhsBigIntId = writer.guardToBigInt(rhsId);
        writer.compareBigIntResult(JSOp::StrictEq, lhsBigIntId, rhsBigIntId);
        break;
      }
      case JS::ValueType::Object: {
        ObjOperandId lhsObjId = writer.guardToObject(lhsId);
        ObjOperandId rhsObjId = writer.guardToObject(rhsId);
        writer.compareObjectResult(JSOp::StrictEq, lhsObjId, rhsObjId);
        break;
      }

#ifdef ENABLE_RECORD_TUPLE
      case ValueType::ExtendedPrimitive:
#endif
      case JS::ValueType::Double:
      case JS::ValueType::Magic:
      case JS::ValueType::PrivateGCThing:
        MOZ_CRASH("Unexpected type");
    }
  }

  writer.returnFromIC();

  trackAttached("ObjectIs");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachObjectIsPrototypeOf() {
  // Ensure |this| is an object.
  if (!thisval_.isObject()) {
    return AttachDecision::NoAction;
  }

  // Need a single argument.
  if (argc_ != 1) {
    return AttachDecision::NoAction;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee is the `isPrototypeOf` native function.
  emitNativeCalleeGuard();

  // Guard that |this| is an object.
  ValOperandId thisValId =
      writer.loadArgumentFixedSlot(ArgumentKind::This, argc_);
  ObjOperandId thisObjId = writer.guardToObject(thisValId);

  ValOperandId argId = writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);

  writer.loadInstanceOfObjectResult(argId, thisObjId);
  writer.returnFromIC();

  trackAttached("ObjectIsPrototypeOf");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachObjectToString() {
  // Expecting no arguments.
  if (argc_ != 0) {
    return AttachDecision::NoAction;
  }

  // Ensure |this| is an object.
  if (!thisval_.isObject()) {
    return AttachDecision::NoAction;
  }

  // Don't attach if the object has @@toStringTag or is a proxy.
  if (!ObjectClassToString(cx_, &thisval_.toObject())) {
    return AttachDecision::NoAction;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee is the 'toString' native function.
  emitNativeCalleeGuard();

  // Guard that |this| is an object.
  ValOperandId thisValId =
      writer.loadArgumentFixedSlot(ArgumentKind::This, argc_);
  ObjOperandId thisObjId = writer.guardToObject(thisValId);

  writer.objectToStringResult(thisObjId);
  writer.returnFromIC();

  trackAttached("ObjectToString");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachBigIntAsIntN() {
  // Need two arguments (Int32, BigInt).
  if (argc_ != 2 || !args_[0].isInt32() || !args_[1].isBigInt()) {
    return AttachDecision::NoAction;
  }

  // Negative bits throws an error.
  if (args_[0].toInt32() < 0) {
    return AttachDecision::NoAction;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee is the 'BigInt.asIntN' native function.
  emitNativeCalleeGuard();

  // Convert bits to int32.
  ValOperandId bitsId = writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
  Int32OperandId int32BitsId = writer.guardToInt32Index(bitsId);

  // Number of bits mustn't be negative.
  writer.guardInt32IsNonNegative(int32BitsId);

  ValOperandId arg1Id = writer.loadArgumentFixedSlot(ArgumentKind::Arg1, argc_);
  BigIntOperandId bigIntId = writer.guardToBigInt(arg1Id);

  writer.bigIntAsIntNResult(int32BitsId, bigIntId);
  writer.returnFromIC();

  trackAttached("BigIntAsIntN");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachBigIntAsUintN() {
  // Need two arguments (Int32, BigInt).
  if (argc_ != 2 || !args_[0].isInt32() || !args_[1].isBigInt()) {
    return AttachDecision::NoAction;
  }

  // Negative bits throws an error.
  if (args_[0].toInt32() < 0) {
    return AttachDecision::NoAction;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee is the 'BigInt.asUintN' native function.
  emitNativeCalleeGuard();

  // Convert bits to int32.
  ValOperandId bitsId = writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
  Int32OperandId int32BitsId = writer.guardToInt32Index(bitsId);

  // Number of bits mustn't be negative.
  writer.guardInt32IsNonNegative(int32BitsId);

  ValOperandId arg1Id = writer.loadArgumentFixedSlot(ArgumentKind::Arg1, argc_);
  BigIntOperandId bigIntId = writer.guardToBigInt(arg1Id);

  writer.bigIntAsUintNResult(int32BitsId, bigIntId);
  writer.returnFromIC();

  trackAttached("BigIntAsUintN");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachSetHas() {
  // Ensure |this| is a SetObject.
  if (!thisval_.isObject() || !thisval_.toObject().is<SetObject>()) {
    return AttachDecision::NoAction;
  }

  // Need a single argument.
  if (argc_ != 1) {
    return AttachDecision::NoAction;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee is the 'has' native function.
  emitNativeCalleeGuard();

  // Guard |this| is a SetObject.
  ValOperandId thisValId =
      writer.loadArgumentFixedSlot(ArgumentKind::This, argc_);
  ObjOperandId objId = writer.guardToObject(thisValId);
  emitOptimisticClassGuard(objId, &thisval_.toObject(), GuardClassKind::Set);

  ValOperandId argId = writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);

#ifndef JS_CODEGEN_X86
  // Assume the hash key will likely always have the same type when attaching
  // the first stub. If the call is polymorphic on the hash key, attach a stub
  // which handles any value.
  if (isFirstStub()) {
    switch (args_[0].type()) {
      case ValueType::Double:
      case ValueType::Int32:
      case ValueType::Boolean:
      case ValueType::Undefined:
      case ValueType::Null: {
        writer.guardToNonGCThing(argId);
        writer.setHasNonGCThingResult(objId, argId);
        break;
      }
      case ValueType::String: {
        StringOperandId strId = writer.guardToString(argId);
        writer.setHasStringResult(objId, strId);
        break;
      }
      case ValueType::Symbol: {
        SymbolOperandId symId = writer.guardToSymbol(argId);
        writer.setHasSymbolResult(objId, symId);
        break;
      }
      case ValueType::BigInt: {
        BigIntOperandId bigIntId = writer.guardToBigInt(argId);
        writer.setHasBigIntResult(objId, bigIntId);
        break;
      }
      case ValueType::Object: {
        // Currently only supported on 64-bit platforms.
#  ifdef JS_PUNBOX64
        ObjOperandId valId = writer.guardToObject(argId);
        writer.setHasObjectResult(objId, valId);
#  else
        writer.setHasResult(objId, argId);
#  endif
        break;
      }

#  ifdef ENABLE_RECORD_TUPLE
      case ValueType::ExtendedPrimitive:
#  endif
      case ValueType::Magic:
      case ValueType::PrivateGCThing:
        MOZ_CRASH("Unexpected type");
    }
  } else {
    writer.setHasResult(objId, argId);
  }
#else
  // The optimized versions require too many registers on x86.
  writer.setHasResult(objId, argId);
#endif

  writer.returnFromIC();

  trackAttached("SetHas");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachMapHas() {
  // Ensure |this| is a MapObject.
  if (!thisval_.isObject() || !thisval_.toObject().is<MapObject>()) {
    return AttachDecision::NoAction;
  }

  // Need a single argument.
  if (argc_ != 1) {
    return AttachDecision::NoAction;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee is the 'has' native function.
  emitNativeCalleeGuard();

  // Guard |this| is a MapObject.
  ValOperandId thisValId =
      writer.loadArgumentFixedSlot(ArgumentKind::This, argc_);
  ObjOperandId objId = writer.guardToObject(thisValId);
  emitOptimisticClassGuard(objId, &thisval_.toObject(), GuardClassKind::Map);

  ValOperandId argId = writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);

#ifndef JS_CODEGEN_X86
  // Assume the hash key will likely always have the same type when attaching
  // the first stub. If the call is polymorphic on the hash key, attach a stub
  // which handles any value.
  if (isFirstStub()) {
    switch (args_[0].type()) {
      case ValueType::Double:
      case ValueType::Int32:
      case ValueType::Boolean:
      case ValueType::Undefined:
      case ValueType::Null: {
        writer.guardToNonGCThing(argId);
        writer.mapHasNonGCThingResult(objId, argId);
        break;
      }
      case ValueType::String: {
        StringOperandId strId = writer.guardToString(argId);
        writer.mapHasStringResult(objId, strId);
        break;
      }
      case ValueType::Symbol: {
        SymbolOperandId symId = writer.guardToSymbol(argId);
        writer.mapHasSymbolResult(objId, symId);
        break;
      }
      case ValueType::BigInt: {
        BigIntOperandId bigIntId = writer.guardToBigInt(argId);
        writer.mapHasBigIntResult(objId, bigIntId);
        break;
      }
      case ValueType::Object: {
        // Currently only supported on 64-bit platforms.
#  ifdef JS_PUNBOX64
        ObjOperandId valId = writer.guardToObject(argId);
        writer.mapHasObjectResult(objId, valId);
#  else
        writer.mapHasResult(objId, argId);
#  endif
        break;
      }

#  ifdef ENABLE_RECORD_TUPLE
      case ValueType::ExtendedPrimitive:
#  endif
      case ValueType::Magic:
      case ValueType::PrivateGCThing:
        MOZ_CRASH("Unexpected type");
    }
  } else {
    writer.mapHasResult(objId, argId);
  }
#else
  // The optimized versions require too many registers on x86.
  writer.mapHasResult(objId, argId);
#endif

  writer.returnFromIC();

  trackAttached("MapHas");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachMapGet() {
  // Ensure |this| is a MapObject.
  if (!thisval_.isObject() || !thisval_.toObject().is<MapObject>()) {
    return AttachDecision::NoAction;
  }

  // Need a single argument.
  if (argc_ != 1) {
    return AttachDecision::NoAction;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee is the 'get' native function.
  emitNativeCalleeGuard();

  // Guard |this| is a MapObject.
  ValOperandId thisValId =
      writer.loadArgumentFixedSlot(ArgumentKind::This, argc_);
  ObjOperandId objId = writer.guardToObject(thisValId);
  emitOptimisticClassGuard(objId, &thisval_.toObject(), GuardClassKind::Map);

  ValOperandId argId = writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);

#ifndef JS_CODEGEN_X86
  // Assume the hash key will likely always have the same type when attaching
  // the first stub. If the call is polymorphic on the hash key, attach a stub
  // which handles any value.
  if (isFirstStub()) {
    switch (args_[0].type()) {
      case ValueType::Double:
      case ValueType::Int32:
      case ValueType::Boolean:
      case ValueType::Undefined:
      case ValueType::Null: {
        writer.guardToNonGCThing(argId);
        writer.mapGetNonGCThingResult(objId, argId);
        break;
      }
      case ValueType::String: {
        StringOperandId strId = writer.guardToString(argId);
        writer.mapGetStringResult(objId, strId);
        break;
      }
      case ValueType::Symbol: {
        SymbolOperandId symId = writer.guardToSymbol(argId);
        writer.mapGetSymbolResult(objId, symId);
        break;
      }
      case ValueType::BigInt: {
        BigIntOperandId bigIntId = writer.guardToBigInt(argId);
        writer.mapGetBigIntResult(objId, bigIntId);
        break;
      }
      case ValueType::Object: {
        // Currently only supported on 64-bit platforms.
#  ifdef JS_PUNBOX64
        ObjOperandId valId = writer.guardToObject(argId);
        writer.mapGetObjectResult(objId, valId);
#  else
        writer.mapGetResult(objId, argId);
#  endif
        break;
      }

#  ifdef ENABLE_RECORD_TUPLE
      case ValueType::ExtendedPrimitive:
#  endif
      case ValueType::Magic:
      case ValueType::PrivateGCThing:
        MOZ_CRASH("Unexpected type");
    }
  } else {
    writer.mapGetResult(objId, argId);
  }
#else
  // The optimized versions require too many registers on x86.
  writer.mapGetResult(objId, argId);
#endif

  writer.returnFromIC();

  trackAttached("MapGet");
  return AttachDecision::Attach;
}

AttachDecision CallIRGenerator::tryAttachFunCall(HandleFunction callee) {
  MOZ_ASSERT(callee->isNativeWithoutJitEntry());

  if (callee->native() != fun_call) {
    return AttachDecision::NoAction;
  }

  if (!thisval_.isObject() || !thisval_.toObject().is<JSFunction>()) {
    return AttachDecision::NoAction;
  }
  RootedFunction target(cx_, &thisval_.toObject().as<JSFunction>());

  bool isScripted = target->hasJitEntry();
  MOZ_ASSERT_IF(!isScripted, target->isNativeWithoutJitEntry());

  if (target->isClassConstructor()) {
    return AttachDecision::NoAction;
  }
  Int32OperandId argcId(writer.setInputOperandId(0));

  CallFlags targetFlags(CallFlags::FunCall);
  if (mode_ == ICState::Mode::Specialized) {
    if (cx_->realm() == target->realm()) {
      targetFlags.setIsSameRealm();
    }
  }

  if (mode_ == ICState::Mode::Specialized && !isScripted && argc_ > 0) {
    // The stack layout is already in the correct form for calls with at least
    // one argument.
    //
    // clang-format off
    //
    // *** STACK LAYOUT (bottom to top) ***   *** INDEX ***
    //   Callee                               <-- argc+1
    //   ThisValue                            <-- argc
    //   Args: | Arg0 |                       <-- argc-1
    //         | Arg1 |                       <-- argc-2
    //         | ...  |                       <-- ...
    //         | ArgN |                       <-- 0
    //
    // When passing |argc-1| as the number of arguments, we get:
    //
    // *** STACK LAYOUT (bottom to top) ***   *** INDEX ***
    //   Callee                               <-- (argc-1)+1 = argc   = ThisValue
    //   ThisValue                            <-- (argc-1)   = argc-1 = Arg0
    //   Args: | Arg0   |                     <-- (argc-1)-1 = argc-2 = Arg1
    //         | Arg1   |                     <-- (argc-1)-2 = argc-3 = Arg2
    //         | ...    |                     <-- ...
    //
    // clang-format on
    //
    // This allows to call |loadArgumentFixedSlot(ArgumentKind::Arg0)| and we
    // still load the correct argument index from |ArgumentKind::Arg1|.
    //
    // When no arguments are passed, i.e. |argc==0|, we have to replace
    // |ArgumentKind::Arg0| with the undefined value. But we don't yet support
    // this case.
    HandleValue newTarget = NullHandleValue;
    HandleValue thisValue = args_[0];
    HandleValueArray args =
        HandleValueArray::subarray(args_, 1, args_.length() - 1);

    // Check for specific native-function optimizations.
    InlinableNativeIRGenerator nativeGen(*this, target, newTarget, thisValue,
                                         args, targetFlags);
    TRY_ATTACH(nativeGen.tryAttachStub());
  }

  ObjOperandId thisObjId = emitFunCallGuard(argcId);

  if (mode_ == ICState::Mode::Specialized) {
    // Ensure that |this| is the expected target function.
    emitCalleeGuard(thisObjId, target);

    if (isScripted) {
      writer.callScriptedFunction(thisObjId, argcId, targetFlags,
                                  ClampFixedArgc(argc_));
    } else {
      writer.callNativeFunction(thisObjId, argcId, op_, target, targetFlags,
                                ClampFixedArgc(argc_));
    }
  } else {
    // Guard that |this| is a function.
    writer.guardClass(thisObjId, GuardClassKind::JSFunction);

    // Guard that function is not a class constructor.
    writer.guardNotClassConstructor(thisObjId);

    if (isScripted) {
      writer.guardFunctionHasJitEntry(thisObjId, /*isConstructing =*/false);
      writer.callScriptedFunction(thisObjId, argcId, targetFlags,
                                  ClampFixedArgc(argc_));
    } else {
      writer.guardFunctionHasNoJitEntry(thisObjId);
      writer.callAnyNativeFunction(thisObjId, argcId, targetFlags,
                                   ClampFixedArgc(argc_));
    }
  }

  writer.returnFromIC();

  if (isScripted) {
    trackAttached("Scripted fun_call");
  } else {
    trackAttached("Native fun_call");
  }

  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachIsTypedArray(
    bool isPossiblyWrapped) {
  // Self-hosted code calls this with a single object argument.
  MOZ_ASSERT(argc_ == 1);
  MOZ_ASSERT(args_[0].isObject());

  // Initialize the input operand.
  initializeInputOperand();

  // Note: we don't need to call emitNativeCalleeGuard for intrinsics.

  ValOperandId argId = writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
  ObjOperandId objArgId = writer.guardToObject(argId);
  writer.isTypedArrayResult(objArgId, isPossiblyWrapped);
  writer.returnFromIC();

  trackAttached(isPossiblyWrapped ? "IsPossiblyWrappedTypedArray"
                                  : "IsTypedArray");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachIsTypedArrayConstructor() {
  // Self-hosted code calls this with a single object argument.
  MOZ_ASSERT(argc_ == 1);
  MOZ_ASSERT(args_[0].isObject());

  // Initialize the input operand.
  initializeInputOperand();

  // Note: we don't need to call emitNativeCalleeGuard for intrinsics.

  ValOperandId argId = writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
  ObjOperandId objArgId = writer.guardToObject(argId);
  writer.isTypedArrayConstructorResult(objArgId);
  writer.returnFromIC();

  trackAttached("IsTypedArrayConstructor");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachTypedArrayByteOffset() {
  // Self-hosted code calls this with a single TypedArrayObject argument.
  MOZ_ASSERT(argc_ == 1);
  MOZ_ASSERT(args_[0].isObject());
  MOZ_ASSERT(args_[0].toObject().is<TypedArrayObject>());

  auto* tarr = &args_[0].toObject().as<TypedArrayObject>();

  // Initialize the input operand.
  initializeInputOperand();

  // Note: we don't need to call emitNativeCalleeGuard for intrinsics.

  ValOperandId argId = writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
  ObjOperandId objArgId = writer.guardToObject(argId);
  if (tarr->byteOffset() <= INT32_MAX) {
    writer.arrayBufferViewByteOffsetInt32Result(objArgId);
  } else {
    writer.arrayBufferViewByteOffsetDoubleResult(objArgId);
  }
  writer.returnFromIC();

  trackAttached("IntrinsicTypedArrayByteOffset");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachTypedArrayElementSize() {
  // Self-hosted code calls this with a single TypedArrayObject argument.
  MOZ_ASSERT(argc_ == 1);
  MOZ_ASSERT(args_[0].isObject());
  MOZ_ASSERT(args_[0].toObject().is<TypedArrayObject>());

  // Initialize the input operand.
  initializeInputOperand();

  // Note: we don't need to call emitNativeCalleeGuard for intrinsics.

  ValOperandId argId = writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
  ObjOperandId objArgId = writer.guardToObject(argId);
  writer.typedArrayElementSizeResult(objArgId);
  writer.returnFromIC();

  trackAttached("TypedArrayElementSize");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachTypedArrayLength(
    bool isPossiblyWrapped) {
  // Self-hosted code calls this with a single, possibly wrapped,
  // TypedArrayObject argument.
  MOZ_ASSERT(argc_ == 1);
  MOZ_ASSERT(args_[0].isObject());

  // Only optimize when the object isn't a wrapper.
  if (isPossiblyWrapped && IsWrapper(&args_[0].toObject())) {
    return AttachDecision::NoAction;
  }

  MOZ_ASSERT(args_[0].toObject().is<TypedArrayObject>());

  auto* tarr = &args_[0].toObject().as<TypedArrayObject>();

  // Initialize the input operand.
  initializeInputOperand();

  // Note: we don't need to call emitNativeCalleeGuard for intrinsics.

  ValOperandId argId = writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
  ObjOperandId objArgId = writer.guardToObject(argId);

  if (isPossiblyWrapped) {
    writer.guardIsNotProxy(objArgId);
  }

  if (tarr->length() <= INT32_MAX) {
    writer.loadArrayBufferViewLengthInt32Result(objArgId);
  } else {
    writer.loadArrayBufferViewLengthDoubleResult(objArgId);
  }
  writer.returnFromIC();

  trackAttached("IntrinsicTypedArrayLength");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachArrayBufferByteLength(
    bool isPossiblyWrapped) {
  // Self-hosted code calls this with a single, possibly wrapped,
  // ArrayBufferObject argument.
  MOZ_ASSERT(argc_ == 1);
  MOZ_ASSERT(args_[0].isObject());

  // Only optimize when the object isn't a wrapper.
  if (isPossiblyWrapped && IsWrapper(&args_[0].toObject())) {
    return AttachDecision::NoAction;
  }

  MOZ_ASSERT(args_[0].toObject().is<ArrayBufferObject>());

  auto* buffer = &args_[0].toObject().as<ArrayBufferObject>();

  // Initialize the input operand.
  initializeInputOperand();

  // Note: we don't need to call emitNativeCalleeGuard for intrinsics.

  ValOperandId argId = writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
  ObjOperandId objArgId = writer.guardToObject(argId);

  if (isPossiblyWrapped) {
    writer.guardIsNotProxy(objArgId);
  }

  if (buffer->byteLength() <= INT32_MAX) {
    writer.loadArrayBufferByteLengthInt32Result(objArgId);
  } else {
    writer.loadArrayBufferByteLengthDoubleResult(objArgId);
  }
  writer.returnFromIC();

  trackAttached("ArrayBufferByteLength");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachIsConstructing() {
  // Self-hosted code calls this with no arguments in function scripts.
  MOZ_ASSERT(argc_ == 0);
  MOZ_ASSERT(script()->isFunction());

  // Initialize the input operand.
  initializeInputOperand();

  // Note: we don't need to call emitNativeCalleeGuard for intrinsics.

  writer.frameIsConstructingResult();
  writer.returnFromIC();

  trackAttached("IsConstructing");
  return AttachDecision::Attach;
}

AttachDecision
InlinableNativeIRGenerator::tryAttachGetNextMapSetEntryForIterator(bool isMap) {
  // Self-hosted code calls this with two objects.
  MOZ_ASSERT(argc_ == 2);
  if (isMap) {
    MOZ_ASSERT(args_[0].toObject().is<MapIteratorObject>());
  } else {
    MOZ_ASSERT(args_[0].toObject().is<SetIteratorObject>());
  }
  MOZ_ASSERT(args_[1].toObject().is<ArrayObject>());

  // Initialize the input operand.
  initializeInputOperand();

  // Note: we don't need to call emitNativeCalleeGuard for intrinsics.

  ValOperandId iterId = writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
  ObjOperandId objIterId = writer.guardToObject(iterId);

  ValOperandId resultArrId =
      writer.loadArgumentFixedSlot(ArgumentKind::Arg1, argc_);
  ObjOperandId objResultArrId = writer.guardToObject(resultArrId);

  writer.getNextMapSetEntryForIteratorResult(objIterId, objResultArrId, isMap);
  writer.returnFromIC();

  trackAttached("GetNextMapSetEntryForIterator");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachNewArrayIterator() {
  // Self-hosted code calls this without any arguments
  MOZ_ASSERT(argc_ == 0);

  JSObject* templateObj = NewArrayIteratorTemplate(cx_);
  if (!templateObj) {
    cx_->recoverFromOutOfMemory();
    return AttachDecision::NoAction;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Note: we don't need to call emitNativeCalleeGuard for intrinsics.

  writer.newArrayIteratorResult(templateObj);
  writer.returnFromIC();

  trackAttached("NewArrayIterator");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachNewStringIterator() {
  // Self-hosted code calls this without any arguments
  MOZ_ASSERT(argc_ == 0);

  JSObject* templateObj = NewStringIteratorTemplate(cx_);
  if (!templateObj) {
    cx_->recoverFromOutOfMemory();
    return AttachDecision::NoAction;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Note: we don't need to call emitNativeCalleeGuard for intrinsics.

  writer.newStringIteratorResult(templateObj);
  writer.returnFromIC();

  trackAttached("NewStringIterator");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachNewRegExpStringIterator() {
  // Self-hosted code calls this without any arguments
  MOZ_ASSERT(argc_ == 0);

  JSObject* templateObj = NewRegExpStringIteratorTemplate(cx_);
  if (!templateObj) {
    cx_->recoverFromOutOfMemory();
    return AttachDecision::NoAction;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Note: we don't need to call emitNativeCalleeGuard for intrinsics.

  writer.newRegExpStringIteratorResult(templateObj);
  writer.returnFromIC();

  trackAttached("NewRegExpStringIterator");
  return AttachDecision::Attach;
}

AttachDecision
InlinableNativeIRGenerator::tryAttachArrayIteratorPrototypeOptimizable() {
  // Self-hosted code calls this without any arguments
  MOZ_ASSERT(argc_ == 0);

  if (!isFirstStub()) {
    // Attach only once to prevent slowdowns for polymorphic calls.
    return AttachDecision::NoAction;
  }

  NativeObject* arrayIteratorProto;
  uint32_t slot;
  JSFunction* nextFun;
  if (!IsArrayIteratorPrototypeOptimizable(cx_, &arrayIteratorProto, &slot,
                                           &nextFun)) {
    return AttachDecision::NoAction;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Note: we don't need to call emitNativeCalleeGuard for intrinsics.

  ObjOperandId protoId = writer.loadObject(arrayIteratorProto);
  ObjOperandId nextId = writer.loadObject(nextFun);

  writer.guardShape(protoId, arrayIteratorProto->shape());

  // Ensure that proto[slot] == nextFun.
  writer.guardDynamicSlotIsSpecificObject(protoId, nextId, slot);
  writer.loadBooleanResult(true);
  writer.returnFromIC();

  trackAttached("ArrayIteratorPrototypeOptimizable");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachObjectCreate() {
  // Need a single object-or-null argument.
  if (argc_ != 1 || !args_[0].isObjectOrNull()) {
    return AttachDecision::NoAction;
  }

  if (!isFirstStub()) {
    // Attach only once to prevent slowdowns for polymorphic calls.
    return AttachDecision::NoAction;
  }

  RootedObject proto(cx_, args_[0].toObjectOrNull());
  JSObject* templateObj = ObjectCreateImpl(cx_, proto, TenuredObject);
  if (!templateObj) {
    cx_->recoverFromOutOfMemory();
    return AttachDecision::NoAction;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee is the 'create' native function.
  emitNativeCalleeGuard();

  // Guard on the proto argument.
  ValOperandId argId = writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);
  if (proto) {
    ObjOperandId protoId = writer.guardToObject(argId);
    writer.guardSpecificObject(protoId, proto);
  } else {
    writer.guardIsNull(argId);
  }

  writer.objectCreateResult(templateObj);
  writer.returnFromIC();

  trackAttached("ObjectCreate");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachObjectConstructor() {
  // Expecting no arguments or a single object argument.
  // TODO(Warp): Support all or more conversions to object.
  if (argc_ > 1) {
    return AttachDecision::NoAction;
  }
  if (argc_ == 1 && !args_[0].isObject()) {
    return AttachDecision::NoAction;
  }

  PlainObject* templateObj = nullptr;
  if (argc_ == 0) {
    // Stub doesn't support metadata builder
    if (cx_->realm()->hasAllocationMetadataBuilder()) {
      return AttachDecision::NoAction;
    }

    // Create a temporary object to act as the template object.
    templateObj = NewPlainObjectWithAllocKind(cx_, NewObjectGCKind());
    if (!templateObj) {
      cx_->recoverFromOutOfMemory();
      return AttachDecision::NoAction;
    }
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee and newTarget (if constructing) are this Object constructor
  // function.
  emitNativeCalleeGuard();

  if (argc_ == 0) {
    // TODO: Support pre-tenuring.
    gc::AllocSite* site =
        script()->zone()->unknownAllocSite(JS::TraceKind::Object);
    MOZ_ASSERT(site);

    uint32_t numFixedSlots = templateObj->numUsedFixedSlots();
    uint32_t numDynamicSlots = templateObj->numDynamicSlots();
    gc::AllocKind allocKind = templateObj->allocKindForTenure();
    Shape* shape = templateObj->shape();

    writer.guardNoAllocationMetadataBuilder(
        cx_->realm()->addressOfMetadataBuilder());
    writer.newPlainObjectResult(numFixedSlots, numDynamicSlots, allocKind,
                                shape, site);
  } else {
    // Use standard call flags when this is an inline Function.prototype.call(),
    // because GetIndexOfArgument() doesn't yet support |CallFlags::FunCall|.
    CallFlags flags = flags_;
    if (flags.getArgFormat() == CallFlags::FunCall) {
      flags = CallFlags(CallFlags::Standard);
    }

    // Guard that the argument is an object.
    ValOperandId argId =
        writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_, flags);
    ObjOperandId objId = writer.guardToObject(argId);

    // Return the object.
    writer.loadObjectResult(objId);
  }

  writer.returnFromIC();

  trackAttached("ObjectConstructor");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachArrayConstructor() {
  // Only optimize the |Array()| and |Array(n)| cases (with or without |new|)
  // for now. Note that self-hosted code calls this without |new| via std_Array.
  if (argc_ > 1) {
    return AttachDecision::NoAction;
  }
  if (argc_ == 1 && !args_[0].isInt32()) {
    return AttachDecision::NoAction;
  }

  int32_t length = (argc_ == 1) ? args_[0].toInt32() : 0;
  if (length < 0 || uint32_t(length) > ArrayObject::EagerAllocationMaxLength) {
    return AttachDecision::NoAction;
  }

  // We allow inlining this function across realms so make sure the template
  // object is allocated in that realm. See CanInlineNativeCrossRealm.
  JSObject* templateObj;
  {
    AutoRealm ar(cx_, callee_);
    templateObj = NewDenseFullyAllocatedArray(cx_, length, TenuredObject);
    if (!templateObj) {
      cx_->clearPendingException();
      return AttachDecision::NoAction;
    }
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee and newTarget (if constructing) are this Array constructor
  // function.
  emitNativeCalleeGuard();

  Int32OperandId lengthId;
  if (argc_ == 1) {
    // Use standard call flags when this is an inline Function.prototype.call(),
    // because GetIndexOfArgument() doesn't yet support |CallFlags::FunCall|.
    CallFlags flags = flags_;
    if (flags.getArgFormat() == CallFlags::FunCall) {
      flags = CallFlags(CallFlags::Standard);
    }

    ValOperandId arg0Id =
        writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_, flags);
    lengthId = writer.guardToInt32(arg0Id);
  } else {
    MOZ_ASSERT(argc_ == 0);
    lengthId = writer.loadInt32Constant(0);
  }

  writer.newArrayFromLengthResult(templateObj, lengthId);
  writer.returnFromIC();

  trackAttached("ArrayConstructor");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachTypedArrayConstructor() {
  MOZ_ASSERT(flags_.isConstructing());

  if (argc_ == 0 || argc_ > 3) {
    return AttachDecision::NoAction;
  }

  if (!isFirstStub()) {
    // Attach only once to prevent slowdowns for polymorphic calls.
    return AttachDecision::NoAction;
  }

  // The first argument must be int32 or a non-proxy object.
  if (!args_[0].isInt32() && !args_[0].isObject()) {
    return AttachDecision::NoAction;
  }
  if (args_[0].isObject() && args_[0].toObject().is<ProxyObject>()) {
    return AttachDecision::NoAction;
  }

#ifdef JS_CODEGEN_X86
  // Unfortunately NewTypedArrayFromArrayBufferResult needs more registers than
  // we can easily support on 32-bit x86 for now.
  if (args_[0].isObject() &&
      args_[0].toObject().is<ArrayBufferObjectMaybeShared>()) {
    return AttachDecision::NoAction;
  }
#endif

  RootedObject templateObj(cx_);
  if (!TypedArrayObject::GetTemplateObjectForNative(cx_, callee_->native(),
                                                    args_, &templateObj)) {
    cx_->recoverFromOutOfMemory();
    return AttachDecision::NoAction;
  }

  if (!templateObj) {
    // This can happen for large length values.
    MOZ_ASSERT(args_[0].isInt32());
    return AttachDecision::NoAction;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee and newTarget are this TypedArray constructor function.
  emitNativeCalleeGuard();

  ValOperandId arg0Id =
      writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_, flags_);

  if (args_[0].isInt32()) {
    // From length.
    Int32OperandId lengthId = writer.guardToInt32(arg0Id);
    writer.newTypedArrayFromLengthResult(templateObj, lengthId);
  } else {
    JSObject* obj = &args_[0].toObject();
    ObjOperandId objId = writer.guardToObject(arg0Id);

    if (obj->is<ArrayBufferObjectMaybeShared>()) {
      // From ArrayBuffer.
      if (obj->is<ArrayBufferObject>()) {
        writer.guardClass(objId, GuardClassKind::ArrayBuffer);
      } else {
        MOZ_ASSERT(obj->is<SharedArrayBufferObject>());
        writer.guardClass(objId, GuardClassKind::SharedArrayBuffer);
      }
      ValOperandId byteOffsetId;
      if (argc_ > 1) {
        byteOffsetId =
            writer.loadArgumentFixedSlot(ArgumentKind::Arg1, argc_, flags_);
      } else {
        byteOffsetId = writer.loadUndefined();
      }
      ValOperandId lengthId;
      if (argc_ > 2) {
        lengthId =
            writer.loadArgumentFixedSlot(ArgumentKind::Arg2, argc_, flags_);
      } else {
        lengthId = writer.loadUndefined();
      }
      writer.newTypedArrayFromArrayBufferResult(templateObj, objId,
                                                byteOffsetId, lengthId);
    } else {
      // From Array-like.
      writer.guardIsNotArrayBufferMaybeShared(objId);
      writer.guardIsNotProxy(objId);
      writer.newTypedArrayFromArrayResult(templateObj, objId);
    }
  }

  writer.returnFromIC();

  trackAttached("TypedArrayConstructor");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachSpecializedFunctionBind(
    Handle<JSObject*> target, Handle<BoundFunctionObject*> templateObj) {
  // Try to attach a faster stub that's more specialized than what we emit in
  // tryAttachFunctionBind. This lets us allocate and initialize a bound
  // function object in Ion without calling into C++.
  //
  // We can do this if:
  //
  // * The target's prototype is Function.prototype, because that's the proto we
  //   use for the template object.
  // * All bound arguments can be stored inline.
  // * The `.name`, `.length`, and `IsConstructor` values match `target`.
  //
  // We initialize the template object with the bound function's name, length,
  // and flags. At runtime we then only have to clone the template object and
  // initialize the slots for the target, the bound `this` and the bound
  // arguments.

  if (!isFirstStub()) {
    return AttachDecision::NoAction;
  }
  if (!target->is<JSFunction>() && !target->is<BoundFunctionObject>()) {
    return AttachDecision::NoAction;
  }
  if (target->staticPrototype() != &cx_->global()->getFunctionPrototype()) {
    return AttachDecision::NoAction;
  }
  size_t numBoundArgs = argc_ > 0 ? argc_ - 1 : 0;
  if (numBoundArgs > BoundFunctionObject::MaxInlineBoundArgs) {
    return AttachDecision::NoAction;
  }

  const bool targetIsConstructor = target->isConstructor();
  Rooted<JSAtom*> targetName(cx_);
  uint32_t targetLength = 0;

  if (target->is<JSFunction>()) {
    Rooted<JSFunction*> fun(cx_, &target->as<JSFunction>());
    if (fun->isNativeFun()) {
      return AttachDecision::NoAction;
    }
    if (fun->hasResolvedLength() || fun->hasResolvedName()) {
      return AttachDecision::NoAction;
    }
    uint16_t len;
    if (!JSFunction::getUnresolvedLength(cx_, fun, &len)) {
      cx_->clearPendingException();
      return AttachDecision::NoAction;
    }
    targetName = fun->infallibleGetUnresolvedName(cx_);
    targetLength = len;
  } else {
    BoundFunctionObject* bound = &target->as<BoundFunctionObject>();
    if (!targetIsConstructor) {
      // Only support constructors for now. This lets us use
      // GuardBoundFunctionIsConstructor.
      return AttachDecision::NoAction;
    }
    Shape* initialShape =
        cx_->global()->maybeBoundFunctionShapeWithDefaultProto();
    if (bound->shape() != initialShape) {
      return AttachDecision::NoAction;
    }
    Value lenVal = bound->getLengthForInitialShape();
    Value nameVal = bound->getNameForInitialShape();
    if (!lenVal.isInt32() || lenVal.toInt32() < 0 || !nameVal.isString() ||
        !nameVal.toString()->isAtom()) {
      return AttachDecision::NoAction;
    }
    targetName = &nameVal.toString()->asAtom();
    targetLength = uint32_t(lenVal.toInt32());
  }

  if (!templateObj->initTemplateSlotsForSpecializedBind(
          cx_, numBoundArgs, targetIsConstructor, targetLength, targetName)) {
    cx_->recoverFromOutOfMemory();
    return AttachDecision::NoAction;
  }

  initializeInputOperand();
  emitNativeCalleeGuard();

  ValOperandId thisValId =
      writer.loadArgumentFixedSlot(ArgumentKind::This, argc_);
  ObjOperandId targetId = writer.guardToObject(thisValId);

  // Ensure the JSClass and proto match, and that the `length` and `name`
  // properties haven't been redefined.
  writer.guardShape(targetId, target->shape());

  // Emit guards for the `IsConstructor`, `.length`, and `.name` values.
  if (target->is<JSFunction>()) {
    // Guard on:
    // * The BaseScript (because that's what JSFunction uses for the `length`).
    //   Because MGuardFunctionScript doesn't support self-hosted functions yet,
    //   we use GuardSpecificFunction instead in this case.
    //   See assertion in MGuardFunctionScript::getAliasSet.
    // * The flags slot (for the CONSTRUCTOR, RESOLVED_NAME, RESOLVED_LENGTH,
    //   HAS_INFERRED_NAME, and HAS_GUESSED_ATOM flags).
    // * The atom slot.
    JSFunction* fun = &target->as<JSFunction>();
    if (fun->isSelfHostedBuiltin()) {
      writer.guardSpecificFunction(targetId, fun);
    } else {
      writer.guardFunctionScript(targetId, fun->baseScript());
    }
    writer.guardFixedSlotValue(
        targetId, JSFunction::offsetOfFlagsAndArgCount(),
        fun->getReservedSlot(JSFunction::FlagsAndArgCountSlot));
    writer.guardFixedSlotValue(targetId, JSFunction::offsetOfAtom(),
                               fun->getReservedSlot(JSFunction::AtomSlot));
  } else {
    BoundFunctionObject* bound = &target->as<BoundFunctionObject>();
    writer.guardBoundFunctionIsConstructor(targetId);
    writer.guardFixedSlotValue(targetId,
                               BoundFunctionObject::offsetOfLengthSlot(),
                               bound->getLengthForInitialShape());
    writer.guardFixedSlotValue(targetId,
                               BoundFunctionObject::offsetOfNameSlot(),
                               bound->getNameForInitialShape());
  }

  writer.specializedBindFunctionResult(targetId, argc_, templateObj);
  writer.returnFromIC();

  trackAttached("SpecializedFunctionBind");
  return AttachDecision::Attach;
}

AttachDecision InlinableNativeIRGenerator::tryAttachFunctionBind() {
  // Ensure |this| (the target) is a function object or a bound function object.
  // We could support other callables too, but note that we rely on the target
  // having a static prototype in BoundFunctionObject::functionBindImpl.
  if (!thisval_.isObject()) {
    return AttachDecision::NoAction;
  }
  Rooted<JSObject*> target(cx_, &thisval_.toObject());
  if (!target->is<JSFunction>() && !target->is<BoundFunctionObject>()) {
    return AttachDecision::NoAction;
  }

  // Only support standard, non-spread calls.
  if (flags_.getArgFormat() != CallFlags::Standard) {
    return AttachDecision::NoAction;
  }

  // Only optimize if the number of arguments is small. This ensures we don't
  // compile a lot of different stubs (because we bake in argc) and that we
  // don't get anywhere near ARGS_LENGTH_MAX.
  static constexpr size_t MaxArguments = 6;
  if (argc_ > MaxArguments) {
    return AttachDecision::NoAction;
  }

  Rooted<BoundFunctionObject*> templateObj(
      cx_, BoundFunctionObject::createTemplateObject(cx_));
  if (!templateObj) {
    cx_->recoverFromOutOfMemory();
    return AttachDecision::NoAction;
  }

  TRY_ATTACH(tryAttachSpecializedFunctionBind(target, templateObj));

  initializeInputOperand();

  emitNativeCalleeGuard();

  // Guard |this| is a function object or a bound function object.
  ValOperandId thisValId =
      writer.loadArgumentFixedSlot(ArgumentKind::This, argc_);
  ObjOperandId targetId = writer.guardToObject(thisValId);
  if (target->is<JSFunction>()) {
    writer.guardClass(targetId, GuardClassKind::JSFunction);
  } else {
    MOZ_ASSERT(target->is<BoundFunctionObject>());
    writer.guardClass(targetId, GuardClassKind::BoundFunction);
  }

  writer.bindFunctionResult(targetId, argc_, templateObj);
  writer.returnFromIC();

  trackAttached("FunctionBind");
  return AttachDecision::Attach;
}

AttachDecision CallIRGenerator::tryAttachFunApply(HandleFunction calleeFunc) {
  MOZ_ASSERT(calleeFunc->isNativeWithoutJitEntry());

  if (calleeFunc->native() != fun_apply) {
    return AttachDecision::NoAction;
  }

  if (argc_ > 2) {
    return AttachDecision::NoAction;
  }

  if (!thisval_.isObject() || !thisval_.toObject().is<JSFunction>()) {
    return AttachDecision::NoAction;
  }
  Rooted<JSFunction*> target(cx_, &thisval_.toObject().as<JSFunction>());

  bool isScripted = target->hasJitEntry();
  MOZ_ASSERT_IF(!isScripted, target->isNativeWithoutJitEntry());

  if (target->isClassConstructor()) {
    return AttachDecision::NoAction;
  }

  CallFlags::ArgFormat format = CallFlags::Standard;
  if (argc_ < 2) {
    // |fun.apply()| and |fun.apply(thisValue)| are equivalent to |fun.call()|
    // resp. |fun.call(thisValue)|.
    format = CallFlags::FunCall;
  } else if (args_[1].isNullOrUndefined()) {
    // |fun.apply(thisValue, null)| and |fun.apply(thisValue, undefined)| are
    // also equivalent to |fun.call(thisValue)|, but we can't use FunCall
    // because we have to discard the second argument.
    format = CallFlags::FunApplyNullUndefined;
  } else if (args_[1].isObject() && args_[1].toObject().is<ArgumentsObject>()) {
    auto* argsObj = &args_[1].toObject().as<ArgumentsObject>();
    if (argsObj->hasOverriddenElement() || argsObj->anyArgIsForwarded() ||
        argsObj->hasOverriddenLength() ||
        argsObj->initialLength() > JIT_ARGS_LENGTH_MAX) {
      return AttachDecision::NoAction;
    }
    format = CallFlags::FunApplyArgsObj;
  } else if (args_[1].isObject() && args_[1].toObject().is<ArrayObject>() &&
             args_[1].toObject().as<ArrayObject>().length() <=
                 JIT_ARGS_LENGTH_MAX &&
             IsPackedArray(&args_[1].toObject())) {
    format = CallFlags::FunApplyArray;
  } else {
    return AttachDecision::NoAction;
  }

  Int32OperandId argcId(writer.setInputOperandId(0));

  CallFlags targetFlags(format);
  if (mode_ == ICState::Mode::Specialized) {
    if (cx_->realm() == target->realm()) {
      targetFlags.setIsSameRealm();
    }
  }

  if (mode_ == ICState::Mode::Specialized && !isScripted &&
      format == CallFlags::FunApplyArray) {
    HandleValue newTarget = NullHandleValue;
    HandleValue thisValue = args_[0];
    Rooted<ArrayObject*> aobj(cx_, &args_[1].toObject().as<ArrayObject>());
    HandleValueArray args = HandleValueArray::fromMarkedLocation(
        aobj->length(), aobj->getDenseElements());

    // Check for specific native-function optimizations.
    InlinableNativeIRGenerator nativeGen(*this, target, newTarget, thisValue,
                                         args, targetFlags);
    TRY_ATTACH(nativeGen.tryAttachStub());
  }

  // Don't inline when no arguments are passed, cf. |tryAttachFunCall()|.
  if (mode_ == ICState::Mode::Specialized && !isScripted &&
      format == CallFlags::FunCall && argc_ > 0) {
    MOZ_ASSERT(argc_ == 1);

    HandleValue newTarget = NullHandleValue;
    HandleValue thisValue = args_[0];
    HandleValueArray args = HandleValueArray::empty();

    // Check for specific native-function optimizations.
    InlinableNativeIRGenerator nativeGen(*this, target, newTarget, thisValue,
                                         args, targetFlags);
    TRY_ATTACH(nativeGen.tryAttachStub());
  }

  ObjOperandId thisObjId = emitFunApplyGuard(argcId);

  uint32_t fixedArgc;
  if (format == CallFlags::FunApplyArray ||
      format == CallFlags::FunApplyArgsObj ||
      format == CallFlags::FunApplyNullUndefined) {
    emitFunApplyArgsGuard(format);

    // We always use MaxUnrolledArgCopy here because the fixed argc is
    // meaningless in a FunApply case.
    fixedArgc = MaxUnrolledArgCopy;
  } else {
    MOZ_ASSERT(format == CallFlags::FunCall);

    // Whereas for the FunCall case we need to use the actual fixed argc value.
    fixedArgc = ClampFixedArgc(argc_);
  }

  if (mode_ == ICState::Mode::Specialized) {
    // Ensure that |this| is the expected target function.
    emitCalleeGuard(thisObjId, target);

    if (isScripted) {
      writer.callScriptedFunction(thisObjId, argcId, targetFlags, fixedArgc);
    } else {
      writer.callNativeFunction(thisObjId, argcId, op_, target, targetFlags,
                                fixedArgc);
    }
  } else {
    // Guard that |this| is a function.
    writer.guardClass(thisObjId, GuardClassKind::JSFunction);

    // Guard that function is not a class constructor.
    writer.guardNotClassConstructor(thisObjId);

    if (isScripted) {
      // Guard that function is scripted.
      writer.guardFunctionHasJitEntry(thisObjId, /*constructing =*/false);
      writer.callScriptedFunction(thisObjId, argcId, targetFlags, fixedArgc);
    } else {
      // Guard that function is native.
      writer.guardFunctionHasNoJitEntry(thisObjId);
      writer.callAnyNativeFunction(thisObjId, argcId, targetFlags, fixedArgc);
    }
  }

  writer.returnFromIC();

  if (isScripted) {
    trackAttached("Call.ScriptedFunApply");
  } else {
    trackAttached("Call.NativeFunApply");
  }

  return AttachDecision::Attach;
}

AttachDecision CallIRGenerator::tryAttachWasmCall(HandleFunction calleeFunc) {
  // Try to optimize calls into Wasm code by emitting the CallWasmFunction
  // CacheIR op. Baseline ICs currently treat this as a CallScriptedFunction op
  // (calling Wasm's JitEntry stub) but Warp transpiles it to a more direct call
  // into Wasm code.
  //
  // Note: some code refers to these optimized Wasm calls as "inlined" calls.

  MOZ_ASSERT(calleeFunc->isWasmWithJitEntry());

  if (!JitOptions.enableWasmIonFastCalls) {
    return AttachDecision::NoAction;
  }
  if (!isFirstStub_) {
    return AttachDecision::NoAction;
  }
  JSOp op = JSOp(*pc_);
  if (op != JSOp::Call && op != JSOp::CallContent &&
      op != JSOp::CallIgnoresRv) {
    return AttachDecision::NoAction;
  }
  if (cx_->realm() != calleeFunc->realm()) {
    return AttachDecision::NoAction;
  }

  wasm::Instance& inst = wasm::ExportedFunctionToInstance(calleeFunc);
  uint32_t funcIndex = inst.code().getFuncIndex(calleeFunc);

  auto bestTier = inst.code().bestTier();
  const wasm::FuncExport& funcExport =
      inst.metadata(bestTier).lookupFuncExport(funcIndex);
  const wasm::FuncType& sig = inst.metadata().getFuncExportType(funcExport);

  MOZ_ASSERT(!IsInsideNursery(inst.object()));
  MOZ_ASSERT(sig.canHaveJitEntry(), "Function should allow a Wasm JitEntry");

  // If there are too many arguments, don't optimize (we won't be able to store
  // the arguments in the LIR node).
  static_assert(wasm::MaxArgsForJitInlineCall <= ArgumentKindArgIndexLimit);
  if (sig.args().length() > wasm::MaxArgsForJitInlineCall ||
      argc_ > ArgumentKindArgIndexLimit) {
    return AttachDecision::NoAction;
  }

  // If there are too many results, don't optimize as Warp currently doesn't
  // have code to handle this.
  if (sig.results().length() > wasm::MaxResultsForJitInlineCall) {
    return AttachDecision::NoAction;
  }

  // Bug 1631656 - Don't try to optimize with I64 args on 32-bit platforms
  // because it is more difficult (because it requires multiple LIR arguments
  // per I64).
  //
  // Bug 1631650 - On 64-bit platforms, we also give up optimizing for I64 args
  // spilled to the stack because it causes problems with register allocation.
#ifdef JS_64BIT
  constexpr bool optimizeWithI64 = true;
#else
  constexpr bool optimizeWithI64 = false;
#endif
  ABIArgGenerator abi;
  for (const auto& valType : sig.args()) {
    MIRType mirType = valType.toMIRType();
    ABIArg abiArg = abi.next(mirType);
    if (mirType != MIRType::Int64) {
      continue;
    }
    if (!optimizeWithI64 || abiArg.kind() == ABIArg::Stack) {
      return AttachDecision::NoAction;
    }
  }

  // Check that all arguments can be converted to the Wasm type in Warp code
  // without bailing out.
  for (size_t i = 0; i < sig.args().length(); i++) {
    Value argVal = i < argc_ ? args_[i] : UndefinedValue();
    switch (sig.args()[i].kind()) {
      case wasm::ValType::I32:
      case wasm::ValType::F32:
      case wasm::ValType::F64:
        if (!argVal.isNumber() && !argVal.isBoolean() &&
            !argVal.isUndefined()) {
          return AttachDecision::NoAction;
        }
        break;
      case wasm::ValType::I64:
        if (!argVal.isBigInt() && !argVal.isBoolean() && !argVal.isString()) {
          return AttachDecision::NoAction;
        }
        break;
      case wasm::ValType::V128:
        MOZ_CRASH("Function should not have a Wasm JitEntry");
      case wasm::ValType::Ref:
        // canHaveJitEntry restricts args to externref, where all JS values are
        // valid and can be boxed.
        MOZ_ASSERT(sig.args()[i].refType().isExtern(),
                   "Unexpected type for Wasm JitEntry");
        break;
    }
  }

  CallFlags flags(/* isConstructing = */ false, /* isSpread = */ false,
                  /* isSameRealm = */ true);

  // Load argc.
  Int32OperandId argcId(writer.setInputOperandId(0));

  // Load the callee and ensure it is an object
  ValOperandId calleeValId =
      writer.loadArgumentFixedSlot(ArgumentKind::Callee, argc_, flags);
  ObjOperandId calleeObjId = writer.guardToObject(calleeValId);

  // Ensure the callee is this Wasm function.
  emitCalleeGuard(calleeObjId, calleeFunc);

  // Guard the argument types.
  uint32_t guardedArgs = std::min<uint32_t>(sig.args().length(), argc_);
  for (uint32_t i = 0; i < guardedArgs; i++) {
    ArgumentKind argKind = ArgumentKindForArgIndex(i);
    ValOperandId argId = writer.loadArgumentFixedSlot(argKind, argc_, flags);
    writer.guardWasmArg(argId, sig.args()[i].kind());
  }

  writer.callWasmFunction(calleeObjId, argcId, flags, ClampFixedArgc(argc_),
                          &funcExport, inst.object());
  writer.returnFromIC();

  trackAttached("Call.WasmCall");

  return AttachDecision::Attach;
}

AttachDecision CallIRGenerator::tryAttachInlinableNative(HandleFunction callee,
                                                         CallFlags flags) {
  MOZ_ASSERT(mode_ == ICState::Mode::Specialized);
  MOZ_ASSERT(callee->isNativeWithoutJitEntry());
  MOZ_ASSERT(flags.getArgFormat() == CallFlags::Standard ||
             flags.getArgFormat() == CallFlags::Spread);

  // Special case functions are only optimized for normal calls.
  if (op_ != JSOp::Call && op_ != JSOp::CallContent && op_ != JSOp::New &&
      op_ != JSOp::NewContent && op_ != JSOp::CallIgnoresRv &&
      op_ != JSOp::SpreadCall) {
    return AttachDecision::NoAction;
  }

  InlinableNativeIRGenerator nativeGen(*this, callee, newTarget_, thisval_,
                                       args_, flags);
  return nativeGen.tryAttachStub();
}

#ifdef FUZZING_JS_FUZZILLI
AttachDecision InlinableNativeIRGenerator::tryAttachFuzzilliHash() {
  if (argc_ != 1) {
    return AttachDecision::NoAction;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Guard callee is the 'fuzzilli_hash' native function.
  emitNativeCalleeGuard();

  ValOperandId argValId =
      writer.loadArgumentFixedSlot(ArgumentKind::Arg0, argc_);

  writer.fuzzilliHashResult(argValId);
  writer.returnFromIC();

  trackAttached("FuzzilliHash");
  return AttachDecision::Attach;
}
#endif

AttachDecision InlinableNativeIRGenerator::tryAttachStub() {
  if (!callee_->hasJitInfo() ||
      callee_->jitInfo()->type() != JSJitInfo::InlinableNative) {
    return AttachDecision::NoAction;
  }

  InlinableNative native = callee_->jitInfo()->inlinableNative;

  // Not all natives can be inlined cross-realm.
  if (cx_->realm() != callee_->realm() && !CanInlineNativeCrossRealm(native)) {
    return AttachDecision::NoAction;
  }

  // Check for special-cased native constructors.
  if (flags_.isConstructing()) {
    MOZ_ASSERT(flags_.getArgFormat() == CallFlags::Standard);

    // newTarget must match the callee. CacheIR for this is emitted in
    // emitNativeCalleeGuard.
    if (ObjectValue(*callee_) != newTarget_) {
      return AttachDecision::NoAction;
    }
    switch (native) {
      case InlinableNative::Array:
        return tryAttachArrayConstructor();
      case InlinableNative::TypedArrayConstructor:
        return tryAttachTypedArrayConstructor();
      case InlinableNative::String:
        return tryAttachStringConstructor();
      case InlinableNative::Object:
        return tryAttachObjectConstructor();
      default:
        break;
    }
    return AttachDecision::NoAction;
  }

  // Check for special-cased native spread calls.
  if (flags_.getArgFormat() == CallFlags::Spread ||
      flags_.getArgFormat() == CallFlags::FunApplyArray) {
    switch (native) {
      case InlinableNative::MathMin:
        return tryAttachSpreadMathMinMax(/*isMax = */ false);
      case InlinableNative::MathMax:
        return tryAttachSpreadMathMinMax(/*isMax = */ true);
      default:
        break;
    }
    return AttachDecision::NoAction;
  }

  MOZ_ASSERT(flags_.getArgFormat() == CallFlags::Standard ||
             flags_.getArgFormat() == CallFlags::FunCall);

  // Check for special-cased native functions.
  switch (native) {
    // Array natives.
    case InlinableNative::Array:
      return tryAttachArrayConstructor();
    case InlinableNative::ArrayPush:
      return tryAttachArrayPush();
    case InlinableNative::ArrayPop:
    case InlinableNative::ArrayShift:
      return tryAttachArrayPopShift(native);
    case InlinableNative::ArrayJoin:
      return tryAttachArrayJoin();
    case InlinableNative::ArraySlice:
      return tryAttachArraySlice();
    case InlinableNative::ArrayIsArray:
      return tryAttachArrayIsArray();

    // DataView natives.
    case InlinableNative::DataViewGetInt8:
      return tryAttachDataViewGet(Scalar::Int8);
    case InlinableNative::DataViewGetUint8:
      return tryAttachDataViewGet(Scalar::Uint8);
    case InlinableNative::DataViewGetInt16:
      return tryAttachDataViewGet(Scalar::Int16);
    case InlinableNative::DataViewGetUint16:
      return tryAttachDataViewGet(Scalar::Uint16);
    case InlinableNative::DataViewGetInt32:
      return tryAttachDataViewGet(Scalar::Int32);
    case InlinableNative::DataViewGetUint32:
      return tryAttachDataViewGet(Scalar::Uint32);
    case InlinableNative::DataViewGetFloat32:
      return tryAttachDataViewGet(Scalar::Float32);
    case InlinableNative::DataViewGetFloat64:
      return tryAttachDataViewGet(Scalar::Float64);
    case InlinableNative::DataViewGetBigInt64:
      return tryAttachDataViewGet(Scalar::BigInt64);
    case InlinableNative::DataViewGetBigUint64:
      return tryAttachDataViewGet(Scalar::BigUint64);
    case InlinableNative::DataViewSetInt8:
      return tryAttachDataViewSet(Scalar::Int8);
    case InlinableNative::DataViewSetUint8:
      return tryAttachDataViewSet(Scalar::Uint8);
    case InlinableNative::DataViewSetInt16:
      return tryAttachDataViewSet(Scalar::Int16);
    case InlinableNative::DataViewSetUint16:
      return tryAttachDataViewSet(Scalar::Uint16);
    case InlinableNative::DataViewSetInt32:
      return tryAttachDataViewSet(Scalar::Int32);
    case InlinableNative::DataViewSetUint32:
      return tryAttachDataViewSet(Scalar::Uint32);
    case InlinableNative::DataViewSetFloat32:
      return tryAttachDataViewSet(Scalar::Float32);
    case InlinableNative::DataViewSetFloat64:
      return tryAttachDataViewSet(Scalar::Float64);
    case InlinableNative::DataViewSetBigInt64:
      return tryAttachDataViewSet(Scalar::BigInt64);
    case InlinableNative::DataViewSetBigUint64:
      return tryAttachDataViewSet(Scalar::BigUint64);

    // Function natives.
    case InlinableNative::FunctionBind:
      return tryAttachFunctionBind();

    // Intl natives.
    case InlinableNative::IntlGuardToCollator:
    case InlinableNative::IntlGuardToDateTimeFormat:
    case InlinableNative::IntlGuardToDisplayNames:
    case InlinableNative::IntlGuardToListFormat:
    case InlinableNative::IntlGuardToNumberFormat:
    case InlinableNative::IntlGuardToPluralRules:
    case InlinableNative::IntlGuardToRelativeTimeFormat:
      return tryAttachGuardToClass(native);

    // Slot intrinsics.
    case InlinableNative::IntrinsicUnsafeGetReservedSlot:
    case InlinableNative::IntrinsicUnsafeGetObjectFromReservedSlot:
    case InlinableNative::IntrinsicUnsafeGetInt32FromReservedSlot:
    case InlinableNative::IntrinsicUnsafeGetStringFromReservedSlot:
      return tryAttachUnsafeGetReservedSlot(native);
    case InlinableNative::IntrinsicUnsafeSetReservedSlot:
      return tryAttachUnsafeSetReservedSlot();

    // Intrinsics.
    case InlinableNative::IntrinsicIsSuspendedGenerator:
      return tryAttachIsSuspendedGenerator();
    case InlinableNative::IntrinsicToObject:
      return tryAttachToObject();
    case InlinableNative::IntrinsicToInteger:
      return tryAttachToInteger();
    case InlinableNative::IntrinsicToLength:
      return tryAttachToLength();
    case InlinableNative::IntrinsicIsObject:
      return tryAttachIsObject();
    case InlinableNative::IntrinsicIsPackedArray:
      return tryAttachIsPackedArray();
    case InlinableNative::IntrinsicIsCallable:
      return tryAttachIsCallable();
    case InlinableNative::IntrinsicIsConstructor:
      return tryAttachIsConstructor();
    case InlinableNative::IntrinsicIsCrossRealmArrayConstructor:
      return tryAttachIsCrossRealmArrayConstructor();
    case InlinableNative::IntrinsicGuardToArrayIterator:
    case InlinableNative::IntrinsicGuardToMapIterator:
    case InlinableNative::IntrinsicGuardToSetIterator:
    case InlinableNative::IntrinsicGuardToStringIterator:
    case InlinableNative::IntrinsicGuardToRegExpStringIterator:
    case InlinableNative::IntrinsicGuardToWrapForValidIterator:
    case InlinableNative::IntrinsicGuardToIteratorHelper:
    case InlinableNative::IntrinsicGuardToAsyncIteratorHelper:
      return tryAttachGuardToClass(native);
    case InlinableNative::IntrinsicSubstringKernel:
      return tryAttachSubstringKernel();
    case InlinableNative::IntrinsicIsConstructing:
      return tryAttachIsConstructing();
    case InlinableNative::IntrinsicNewArrayIterator:
      return tryAttachNewArrayIterator();
    case InlinableNative::IntrinsicNewStringIterator:
      return tryAttachNewStringIterator();
    case InlinableNative::IntrinsicNewRegExpStringIterator:
      return tryAttachNewRegExpStringIterator();
    case InlinableNative::IntrinsicArrayIteratorPrototypeOptimizable:
      return tryAttachArrayIteratorPrototypeOptimizable();
    case InlinableNative::IntrinsicObjectHasPrototype:
      return tryAttachObjectHasPrototype();

    // RegExp natives.
    case InlinableNative::IsRegExpObject:
      return tryAttachHasClass(&RegExpObject::class_,
                               /* isPossiblyWrapped = */ false);
    case InlinableNative::IsPossiblyWrappedRegExpObject:
      return tryAttachHasClass(&RegExpObject::class_,
                               /* isPossiblyWrapped = */ true);
    case InlinableNative::RegExpMatcher:
    case InlinableNative::RegExpSearcher:
      return tryAttachRegExpMatcherSearcher(native);
    case InlinableNative::RegExpPrototypeOptimizable:
      return tryAttachRegExpPrototypeOptimizable();
    case InlinableNative::RegExpInstanceOptimizable:
      return tryAttachRegExpInstanceOptimizable();
    case InlinableNative::GetFirstDollarIndex:
      return tryAttachGetFirstDollarIndex();
    case InlinableNative::IntrinsicRegExpBuiltinExec:
    case InlinableNative::IntrinsicRegExpBuiltinExecForTest:
      return tryAttachIntrinsicRegExpBuiltinExec(native);
    case InlinableNative::IntrinsicRegExpExec:
    case InlinableNative::IntrinsicRegExpExecForTest:
      return tryAttachIntrinsicRegExpExec(native);

    // String natives.
    case InlinableNative::String:
      return tryAttachString();
    case InlinableNative::StringToString:
    case InlinableNative::StringValueOf:
      return tryAttachStringToStringValueOf();
    case InlinableNative::StringCharCodeAt:
      return tryAttachStringCharCodeAt();
    case InlinableNative::StringCharAt:
      return tryAttachStringCharAt();
    case InlinableNative::StringFromCharCode:
      return tryAttachStringFromCharCode();
    case InlinableNative::StringFromCodePoint:
      return tryAttachStringFromCodePoint();
    case InlinableNative::StringIndexOf:
      return tryAttachStringIndexOf();
    case InlinableNative::StringStartsWith:
      return tryAttachStringStartsWith();
    case InlinableNative::StringEndsWith:
      return tryAttachStringEndsWith();
    case InlinableNative::StringToLowerCase:
      return tryAttachStringToLowerCase();
    case InlinableNative::StringToUpperCase:
      return tryAttachStringToUpperCase();
    case InlinableNative::IntrinsicStringReplaceString:
      return tryAttachStringReplaceString();
    case InlinableNative::IntrinsicStringSplitString:
      return tryAttachStringSplitString();

    // Math natives.
    case InlinableNative::MathRandom:
      return tryAttachMathRandom();
    case InlinableNative::MathAbs:
      return tryAttachMathAbs();
    case InlinableNative::MathClz32:
      return tryAttachMathClz32();
    case InlinableNative::MathSign:
      return tryAttachMathSign();
    case InlinableNative::MathImul:
      return tryAttachMathImul();
    case InlinableNative::MathFloor:
      return tryAttachMathFloor();
    case InlinableNative::MathCeil:
      return tryAttachMathCeil();
    case InlinableNative::MathTrunc:
      return tryAttachMathTrunc();
    case InlinableNative::MathRound:
      return tryAttachMathRound();
    case InlinableNative::MathSqrt:
      return tryAttachMathSqrt();
    case InlinableNative::MathFRound:
      return tryAttachMathFRound();
    case InlinableNative::MathHypot:
      return tryAttachMathHypot();
    case InlinableNative::MathATan2:
      return tryAttachMathATan2();
    case InlinableNative::MathSin:
      return tryAttachMathFunction(UnaryMathFunction::SinNative);
    case InlinableNative::MathTan:
      return tryAttachMathFunction(UnaryMathFunction::TanNative);
    case InlinableNative::MathCos:
      return tryAttachMathFunction(UnaryMathFunction::CosNative);
    case InlinableNative::MathExp:
      return tryAttachMathFunction(UnaryMathFunction::Exp);
    case InlinableNative::MathLog:
      return tryAttachMathFunction(UnaryMathFunction::Log);
    case InlinableNative::MathASin:
      return tryAttachMathFunction(UnaryMathFunction::ASin);
    case InlinableNative::MathATan:
      return tryAttachMathFunction(UnaryMathFunction::ATan);
    case InlinableNative::MathACos:
      return tryAttachMathFunction(UnaryMathFunction::ACos);
    case InlinableNative::MathLog10:
      return tryAttachMathFunction(UnaryMathFunction::Log10);
    case InlinableNative::MathLog2:
      return tryAttachMathFunction(UnaryMathFunction::Log2);
    case InlinableNative::MathLog1P:
      return tryAttachMathFunction(UnaryMathFunction::Log1P);
    case InlinableNative::MathExpM1:
      return tryAttachMathFunction(UnaryMathFunction::ExpM1);
    case InlinableNative::MathCosH:
      return tryAttachMathFunction(UnaryMathFunction::CosH);
    case InlinableNative::MathSinH:
      return tryAttachMathFunction(UnaryMathFunction::SinH);
    case InlinableNative::MathTanH:
      return tryAttachMathFunction(UnaryMathFunction::TanH);
    case InlinableNative::MathACosH:
      return tryAttachMathFunction(UnaryMathFunction::ACosH);
    case InlinableNative::MathASinH:
      return tryAttachMathFunction(UnaryMathFunction::ASinH);
    case InlinableNative::MathATanH:
      return tryAttachMathFunction(UnaryMathFunction::ATanH);
    case InlinableNative::MathCbrt:
      return tryAttachMathFunction(UnaryMathFunction::Cbrt);
    case InlinableNative::MathPow:
      return tryAttachMathPow();
    case InlinableNative::MathMin:
      return tryAttachMathMinMax(/* isMax = */ false);
    case InlinableNative::MathMax:
      return tryAttachMathMinMax(/* isMax = */ true);

    // Map intrinsics.
    case InlinableNative::IntrinsicGuardToMapObject:
      return tryAttachGuardToClass(native);
    case InlinableNative::IntrinsicGetNextMapEntryForIterator:
      return tryAttachGetNextMapSetEntryForIterator(/* isMap = */ true);

    // Number natives.
    case InlinableNative::Number:
      return tryAttachNumber();
    case InlinableNative::NumberParseInt:
      return tryAttachNumberParseInt();
    case InlinableNative::NumberToString:
      return tryAttachNumberToString();

    // Object natives.
    case InlinableNative::Object:
      return tryAttachObjectConstructor();
    case InlinableNative::ObjectCreate:
      return tryAttachObjectCreate();
    case InlinableNative::ObjectIs:
      return tryAttachObjectIs();
    case InlinableNative::ObjectIsPrototypeOf:
      return tryAttachObjectIsPrototypeOf();
    case InlinableNative::ObjectToString:
      return tryAttachObjectToString();

    // Set intrinsics.
    case InlinableNative::IntrinsicGuardToSetObject:
      return tryAttachGuardToClass(native);
    case InlinableNative::IntrinsicGetNextSetEntryForIterator:
      return tryAttachGetNextMapSetEntryForIterator(/* isMap = */ false);

    // ArrayBuffer intrinsics.
    case InlinableNative::IntrinsicGuardToArrayBuffer:
      return tryAttachGuardToClass(native);
    case InlinableNative::IntrinsicArrayBufferByteLength:
      return tryAttachArrayBufferByteLength(/* isPossiblyWrapped = */ false);
    case InlinableNative::IntrinsicPossiblyWrappedArrayBufferByteLength:
      return tryAttachArrayBufferByteLength(/* isPossiblyWrapped = */ true);

    // SharedArrayBuffer intrinsics.
    case InlinableNative::IntrinsicGuardToSharedArrayBuffer:
      return tryAttachGuardToClass(native);

    // TypedArray intrinsics.
    case InlinableNative::TypedArrayConstructor:
      return AttachDecision::NoAction;  // Not callable.
    case InlinableNative::IntrinsicIsTypedArray:
      return tryAttachIsTypedArray(/* isPossiblyWrapped = */ false);
    case InlinableNative::IntrinsicIsPossiblyWrappedTypedArray:
      return tryAttachIsTypedArray(/* isPossiblyWrapped = */ true);
    case InlinableNative::IntrinsicIsTypedArrayConstructor:
      return tryAttachIsTypedArrayConstructor();
    case InlinableNative::IntrinsicTypedArrayByteOffset:
      return tryAttachTypedArrayByteOffset();
    case InlinableNative::IntrinsicTypedArrayElementSize:
      return tryAttachTypedArrayElementSize();
    case InlinableNative::IntrinsicTypedArrayLength:
      return tryAttachTypedArrayLength(/* isPossiblyWrapped = */ false);
    case InlinableNative::IntrinsicPossiblyWrappedTypedArrayLength:
      return tryAttachTypedArrayLength(/* isPossiblyWrapped = */ true);

    // Reflect natives.
    case InlinableNative::ReflectGetPrototypeOf:
      return tryAttachReflectGetPrototypeOf();

    // Atomics intrinsics:
    case InlinableNative::AtomicsCompareExchange:
      return tryAttachAtomicsCompareExchange();
    case InlinableNative::AtomicsExchange:
      return tryAttachAtomicsExchange();
    case InlinableNative::AtomicsAdd:
      return tryAttachAtomicsAdd();
    case InlinableNative::AtomicsSub:
      return tryAttachAtomicsSub();
    case InlinableNative::AtomicsAnd:
      return tryAttachAtomicsAnd();
    case InlinableNative::AtomicsOr:
      return tryAttachAtomicsOr();
    case InlinableNative::AtomicsXor:
      return tryAttachAtomicsXor();
    case InlinableNative::AtomicsLoad:
      return tryAttachAtomicsLoad();
    case InlinableNative::AtomicsStore:
      return tryAttachAtomicsStore();
    case InlinableNative::AtomicsIsLockFree:
      return tryAttachAtomicsIsLockFree();

    // BigInt natives.
    case InlinableNative::BigIntAsIntN:
      return tryAttachBigIntAsIntN();
    case InlinableNative::BigIntAsUintN:
      return tryAttachBigIntAsUintN();

    // Boolean natives.
    case InlinableNative::Boolean:
      return tryAttachBoolean();

    // Set natives.
    case InlinableNative::SetHas:
      return tryAttachSetHas();

    // Map natives.
    case InlinableNative::MapHas:
      return tryAttachMapHas();
    case InlinableNative::MapGet:
      return tryAttachMapGet();

    // Testing functions.
    case InlinableNative::TestBailout:
      if (js::SupportDifferentialTesting()) {
        return AttachDecision::NoAction;
      }
      return tryAttachBailout();
    case InlinableNative::TestAssertFloat32:
      return tryAttachAssertFloat32();
    case InlinableNative::TestAssertRecoveredOnBailout:
      if (js::SupportDifferentialTesting()) {
        return AttachDecision::NoAction;
      }
      return tryAttachAssertRecoveredOnBailout();

#ifdef FUZZING_JS_FUZZILLI
    // Fuzzilli function
    case InlinableNative::FuzzilliHash:
      return tryAttachFuzzilliHash();
#endif

    case InlinableNative::Limit:
      break;
  }

  MOZ_CRASH("Shouldn't get here");
}

// Remember the shape of the this object for any script being called as a
// constructor, for later use during Ion compilation.
ScriptedThisResult CallIRGenerator::getThisShapeForScripted(
    HandleFunction calleeFunc, Handle<JSObject*> newTarget,
    MutableHandle<Shape*> result) {
  // Some constructors allocate their own |this| object.
  if (calleeFunc->constructorNeedsUninitializedThis()) {
    return ScriptedThisResult::UninitializedThis;
  }

  // Only attach a stub if the newTarget is a function with a
  // nonconfigurable prototype.
  if (!newTarget->is<JSFunction>() ||
      !newTarget->as<JSFunction>().hasNonConfigurablePrototypeDataProperty()) {
    return ScriptedThisResult::NoAction;
  }

  AutoRealm ar(cx_, calleeFunc);
  Shape* thisShape = ThisShapeForFunction(cx_, calleeFunc, newTarget);
  if (!thisShape) {
    cx_->clearPendingException();
    return ScriptedThisResult::NoAction;
  }

  MOZ_ASSERT(thisShape->realm() == calleeFunc->realm());
  result.set(thisShape);
  return ScriptedThisResult::PlainObjectShape;
}

static bool CanOptimizeScriptedCall(JSFunction* callee, bool isConstructing) {
  if (!callee->hasJitEntry()) {
    return false;
  }

  // If callee is not an interpreted constructor, we have to throw.
  if (isConstructing && !callee->isConstructor()) {
    return false;
  }

  // Likewise, if the callee is a class constructor, we have to throw.
  if (!isConstructing && callee->isClassConstructor()) {
    return false;
  }

  return true;
}

void CallIRGenerator::emitCallScriptedGuards(ObjOperandId calleeObjId,
                                             JSFunction* calleeFunc,
                                             Int32OperandId argcId,
                                             CallFlags flags, Shape* thisShape,
                                             bool isBoundFunction) {
  bool isConstructing = flags.isConstructing();

  if (mode_ == ICState::Mode::Specialized) {
    MOZ_ASSERT_IF(isConstructing, thisShape || flags.needsUninitializedThis());

    // Ensure callee matches this stub's callee
    emitCalleeGuard(calleeObjId, calleeFunc);
    if (thisShape) {
      // Emit guards to ensure the newTarget's .prototype property is what we
      // expect. Note that getThisForScripted checked newTarget is a function
      // with a non-configurable .prototype data property.

      JSFunction* newTarget;
      ObjOperandId newTargetObjId;
      if (isBoundFunction) {
        newTarget = calleeFunc;
        newTargetObjId = calleeObjId;
      } else {
        newTarget = &newTarget_.toObject().as<JSFunction>();
        ValOperandId newTargetValId = writer.loadArgumentDynamicSlot(
            ArgumentKind::NewTarget, argcId, flags);
        newTargetObjId = writer.guardToObject(newTargetValId);
      }

      Maybe<PropertyInfo> prop = newTarget->lookupPure(cx_->names().prototype);
      MOZ_ASSERT(prop.isSome());
      uint32_t slot = prop->slot();
      MOZ_ASSERT(slot >= newTarget->numFixedSlots(),
                 "Stub code relies on this");

      writer.guardShape(newTargetObjId, newTarget->shape());

      const Value& value = newTarget->getSlot(slot);
      if (value.isObject()) {
        JSObject* prototypeObject = &value.toObject();

        ObjOperandId protoId = writer.loadObject(prototypeObject);
        writer.guardDynamicSlotIsSpecificObject(
            newTargetObjId, protoId, slot - newTarget->numFixedSlots());
      } else {
        writer.guardDynamicSlotIsNotObject(newTargetObjId,
                                           slot - newTarget->numFixedSlots());
      }

      // Call metaScriptedThisShape before emitting the call, so that Warp can
      // use the shape to create the |this| object before transpiling the call.
      writer.metaScriptedThisShape(thisShape);
    }
  } else {
    // Guard that object is a scripted function
    writer.guardClass(calleeObjId, GuardClassKind::JSFunction);
    writer.guardFunctionHasJitEntry(calleeObjId, isConstructing);

    if (isConstructing) {
      // If callee is not a constructor, we have to throw.
      writer.guardFunctionIsConstructor(calleeObjId);
    } else {
      // If callee is a class constructor, we have to throw.
      writer.guardNotClassConstructor(calleeObjId);
    }
  }
}

AttachDecision CallIRGenerator::tryAttachCallScripted(
    HandleFunction calleeFunc) {
  MOZ_ASSERT(calleeFunc->hasJitEntry());

  if (calleeFunc->isWasmWithJitEntry()) {
    TRY_ATTACH(tryAttachWasmCall(calleeFunc));
  }

  bool isSpecialized = mode_ == ICState::Mode::Specialized;

  bool isConstructing = IsConstructPC(pc_);
  bool isSpread = IsSpreadPC(pc_);
  bool isSameRealm = isSpecialized && cx_->realm() == calleeFunc->realm();
  CallFlags flags(isConstructing, isSpread, isSameRealm);

  if (!CanOptimizeScriptedCall(calleeFunc, isConstructing)) {
    return AttachDecision::NoAction;
  }

  if (isConstructing && !calleeFunc->hasJitScript()) {
    // If we're constructing, require the callee to have a JitScript. This isn't
    // required for correctness but avoids allocating a template object below
    // for constructors that aren't hot. See bug 1419758.
    return AttachDecision::TemporarilyUnoptimizable;
  }

  // Verify that spread calls have a reasonable number of arguments.
  if (isSpread && args_.length() > JIT_ARGS_LENGTH_MAX) {
    return AttachDecision::NoAction;
  }

  Rooted<Shape*> thisShape(cx_);
  if (isConstructing && isSpecialized) {
    Rooted<JSObject*> newTarget(cx_, &newTarget_.toObject());
    switch (getThisShapeForScripted(calleeFunc, newTarget, &thisShape)) {
      case ScriptedThisResult::PlainObjectShape:
        break;
      case ScriptedThisResult::UninitializedThis:
        flags.setNeedsUninitializedThis();
        break;
      case ScriptedThisResult::NoAction:
        return AttachDecision::NoAction;
    }
  }

  // Load argc.
  Int32OperandId argcId(writer.setInputOperandId(0));

  // Load the callee and ensure it is an object
  ValOperandId calleeValId =
      writer.loadArgumentDynamicSlot(ArgumentKind::Callee, argcId, flags);
  ObjOperandId calleeObjId = writer.guardToObject(calleeValId);

  emitCallScriptedGuards(calleeObjId, calleeFunc, argcId, flags, thisShape,
                         /* isBoundFunction = */ false);

  writer.callScriptedFunction(calleeObjId, argcId, flags,
                              ClampFixedArgc(argc_));
  writer.returnFromIC();

  if (isSpecialized) {
    trackAttached("Call.CallScripted");
  } else {
    trackAttached("Call.CallAnyScripted");
  }

  return AttachDecision::Attach;
}

AttachDecision CallIRGenerator::tryAttachCallNative(HandleFunction calleeFunc) {
  MOZ_ASSERT(calleeFunc->isNativeWithoutJitEntry());

  bool isSpecialized = mode_ == ICState::Mode::Specialized;

  bool isSpread = IsSpreadPC(pc_);
  bool isSameRealm = isSpecialized && cx_->realm() == calleeFunc->realm();
  bool isConstructing = IsConstructPC(pc_);
  CallFlags flags(isConstructing, isSpread, isSameRealm);

  if (isConstructing && !calleeFunc->isConstructor()) {
    return AttachDecision::NoAction;
  }

  // Verify that spread calls have a reasonable number of arguments.
  if (isSpread && args_.length() > JIT_ARGS_LENGTH_MAX) {
    return AttachDecision::NoAction;
  }

  // Check for specific native-function optimizations.
  if (isSpecialized) {
    TRY_ATTACH(tryAttachInlinableNative(calleeFunc, flags));
  }

  // Load argc.
  Int32OperandId argcId(writer.setInputOperandId(0));

  // Load the callee and ensure it is an object
  ValOperandId calleeValId =
      writer.loadArgumentDynamicSlot(ArgumentKind::Callee, argcId, flags);
  ObjOperandId calleeObjId = writer.guardToObject(calleeValId);

  // DOM calls need an additional guard so only try optimizing the first stub.
  // Can only optimize normal (non-spread) calls.
  if (isFirstStub_ && !isSpread && thisval_.isObject() &&
      CanAttachDOMCall(cx_, JSJitInfo::Method, &thisval_.toObject(), calleeFunc,
                       mode_)) {
    MOZ_ASSERT(!isConstructing, "DOM functions are not constructors");

    // Guard that |this| is an object.
    ValOperandId thisValId =
        writer.loadArgumentDynamicSlot(ArgumentKind::This, argcId, flags);
    ObjOperandId thisObjId = writer.guardToObject(thisValId);

    // Guard on the |this| shape to make sure it's the right instance. This also
    // ensures DOM_OBJECT_SLOT is stored in a fixed slot. See CanAttachDOMCall.
    writer.guardShape(thisObjId, thisval_.toObject().shape());

    // Ensure callee matches this stub's callee
    writer.guardSpecificFunction(calleeObjId, calleeFunc);
    writer.callDOMFunction(calleeObjId, argcId, thisObjId, calleeFunc, flags,
                           ClampFixedArgc(argc_));

    trackAttached("Call.CallDOM");
  } else if (isSpecialized) {
    // Ensure callee matches this stub's callee
    writer.guardSpecificFunction(calleeObjId, calleeFunc);
    writer.callNativeFunction(calleeObjId, argcId, op_, calleeFunc, flags,
                              ClampFixedArgc(argc_));

    trackAttached("Call.CallNative");
  } else {
    // Guard that object is a native function
    writer.guardClass(calleeObjId, GuardClassKind::JSFunction);
    writer.guardFunctionHasNoJitEntry(calleeObjId);

    if (isConstructing) {
      // If callee is not a constructor, we have to throw.
      writer.guardFunctionIsConstructor(calleeObjId);
    } else {
      // If callee is a class constructor, we have to throw.
      writer.guardNotClassConstructor(calleeObjId);
    }
    writer.callAnyNativeFunction(calleeObjId, argcId, flags,
                                 ClampFixedArgc(argc_));

    trackAttached("Call.CallAnyNative");
  }

  writer.returnFromIC();

  return AttachDecision::Attach;
}

AttachDecision CallIRGenerator::tryAttachCallHook(HandleObject calleeObj) {
  if (mode_ != ICState::Mode::Specialized) {
    // We do not have megamorphic call hook stubs.
    // TODO: Should we attach specialized call hook stubs in
    // megamorphic mode to avoid going generic?
    return AttachDecision::NoAction;
  }

  bool isSpread = IsSpreadPC(pc_);
  bool isConstructing = IsConstructPC(pc_);
  CallFlags flags(isConstructing, isSpread);
  JSNative hook =
      isConstructing ? calleeObj->constructHook() : calleeObj->callHook();
  if (!hook) {
    return AttachDecision::NoAction;
  }

  // Bound functions have a JSClass construct hook but are not always
  // constructors.
  if (isConstructing && !calleeObj->isConstructor()) {
    return AttachDecision::NoAction;
  }

  // We don't support spread calls in the transpiler yet.
  if (isSpread) {
    return AttachDecision::NoAction;
  }

  // Load argc.
  Int32OperandId argcId(writer.setInputOperandId(0));

  // Load the callee and ensure it is an object
  ValOperandId calleeValId =
      writer.loadArgumentDynamicSlot(ArgumentKind::Callee, argcId, flags);
  ObjOperandId calleeObjId = writer.guardToObject(calleeValId);

  // Ensure the callee's class matches the one in this stub.
  writer.guardAnyClass(calleeObjId, calleeObj->getClass());

  if (isConstructing && calleeObj->is<BoundFunctionObject>()) {
    writer.guardBoundFunctionIsConstructor(calleeObjId);
  }

  writer.callClassHook(calleeObjId, argcId, hook, flags, ClampFixedArgc(argc_));
  writer.returnFromIC();

  trackAttached("Call.CallHook");

  return AttachDecision::Attach;
}

AttachDecision CallIRGenerator::tryAttachBoundFunction(
    Handle<BoundFunctionObject*> calleeObj) {
  // The target must be a JSFunction with a JitEntry.
  if (!calleeObj->getTarget()->is<JSFunction>()) {
    return AttachDecision::NoAction;
  }

  bool isSpread = IsSpreadPC(pc_);
  bool isConstructing = IsConstructPC(pc_);

  // Spread calls are not supported yet.
  if (isSpread) {
    return AttachDecision::NoAction;
  }

  Rooted<JSFunction*> target(cx_, &calleeObj->getTarget()->as<JSFunction>());
  if (!CanOptimizeScriptedCall(target, isConstructing)) {
    return AttachDecision::NoAction;
  }

  // Limit the number of bound arguments to prevent us from compiling many
  // different stubs (we bake in numBoundArgs and it's usually very small).
  static constexpr size_t MaxBoundArgs = 10;
  size_t numBoundArgs = calleeObj->numBoundArgs();
  if (numBoundArgs > MaxBoundArgs) {
    return AttachDecision::NoAction;
  }

  // Ensure we don't exceed JIT_ARGS_LENGTH_MAX.
  if (numBoundArgs + argc_ > JIT_ARGS_LENGTH_MAX) {
    return AttachDecision::NoAction;
  }

  CallFlags flags(isConstructing, isSpread);

  if (mode_ == ICState::Mode::Specialized) {
    if (cx_->realm() == target->realm()) {
      flags.setIsSameRealm();
    }
  }

  Rooted<Shape*> thisShape(cx_);
  if (isConstructing) {
    // Only optimize if newTarget == callee. This is the common case and ensures
    // we can always pass the bound function's target as newTarget.
    if (newTarget_ != ObjectValue(*calleeObj)) {
      return AttachDecision::NoAction;
    }

    if (mode_ == ICState::Mode::Specialized) {
      Handle<JSFunction*> newTarget = target;
      switch (getThisShapeForScripted(target, newTarget, &thisShape)) {
        case ScriptedThisResult::PlainObjectShape:
          break;
        case ScriptedThisResult::UninitializedThis:
          flags.setNeedsUninitializedThis();
          break;
        case ScriptedThisResult::NoAction:
          return AttachDecision::NoAction;
      }
    }
  }

  // Load argc.
  Int32OperandId argcId(writer.setInputOperandId(0));

  // Load the callee and ensure it's a bound function.
  ValOperandId calleeValId =
      writer.loadArgumentDynamicSlot(ArgumentKind::Callee, argcId, flags);
  ObjOperandId calleeObjId = writer.guardToObject(calleeValId);
  writer.guardClass(calleeObjId, GuardClassKind::BoundFunction);

  // Ensure numBoundArgs matches.
  Int32OperandId numBoundArgsId = writer.loadBoundFunctionNumArgs(calleeObjId);
  writer.guardSpecificInt32(numBoundArgsId, numBoundArgs);

  if (isConstructing) {
    // Guard newTarget == callee. We depend on this in CallBoundScriptedFunction
    // and in emitCallScriptedGuards by using boundTarget as newTarget.
    ValOperandId newTargetValId =
        writer.loadArgumentDynamicSlot(ArgumentKind::NewTarget, argcId, flags);
    ObjOperandId newTargetObjId = writer.guardToObject(newTargetValId);
    writer.guardObjectIdentity(newTargetObjId, calleeObjId);
  }

  ObjOperandId targetId = writer.loadBoundFunctionTarget(calleeObjId);

  emitCallScriptedGuards(targetId, target, argcId, flags, thisShape,
                         /* isBoundFunction = */ true);

  writer.callBoundScriptedFunction(calleeObjId, targetId, argcId, flags,
                                   numBoundArgs);
  writer.returnFromIC();

  trackAttached("Call.BoundFunction");
  return AttachDecision::Attach;
}

AttachDecision CallIRGenerator::tryAttachStub() {
  AutoAssertNoPendingException aanpe(cx_);

  // Some opcodes are not yet supported.
  switch (op_) {
    case JSOp::Call:
    case JSOp::CallContent:
    case JSOp::CallIgnoresRv:
    case JSOp::CallIter:
    case JSOp::CallContentIter:
    case JSOp::SpreadCall:
    case JSOp::New:
    case JSOp::NewContent:
    case JSOp::SpreadNew:
    case JSOp::SuperCall:
    case JSOp::SpreadSuperCall:
      break;
    default:
      return AttachDecision::NoAction;
  }

  MOZ_ASSERT(mode_ != ICState::Mode::Generic);

  // Ensure callee is a function.
  if (!callee_.isObject()) {
    return AttachDecision::NoAction;
  }

  RootedObject calleeObj(cx_, &callee_.toObject());
  if (calleeObj->is<BoundFunctionObject>()) {
    TRY_ATTACH(tryAttachBoundFunction(calleeObj.as<BoundFunctionObject>()));
  }
  if (!calleeObj->is<JSFunction>()) {
    return tryAttachCallHook(calleeObj);
  }

  HandleFunction calleeFunc = calleeObj.as<JSFunction>();

  // Check for scripted optimizations.
  if (calleeFunc->hasJitEntry()) {
    return tryAttachCallScripted(calleeFunc);
  }

  // Check for native-function optimizations.
  MOZ_ASSERT(calleeFunc->isNativeWithoutJitEntry());

  // Try inlining Function.prototype.{call,apply}. We don't use the
  // InlinableNative mechanism for this because we want to optimize these more
  // aggressively than other natives.
  if (op_ == JSOp::Call || op_ == JSOp::CallContent ||
      op_ == JSOp::CallIgnoresRv) {
    TRY_ATTACH(tryAttachFunCall(calleeFunc));
    TRY_ATTACH(tryAttachFunApply(calleeFunc));
  }

  return tryAttachCallNative(calleeFunc);
}

void CallIRGenerator::trackAttached(const char* name) {
  stubName_ = name ? name : "NotAttached";
#ifdef JS_CACHEIR_SPEW
  if (const CacheIRSpewer::Guard& sp = CacheIRSpewer::Guard(*this, name)) {
    sp.valueProperty("callee", callee_);
    sp.valueProperty("thisval", thisval_);
    sp.valueProperty("argc", Int32Value(argc_));

    // Try to log the first two arguments.
    if (args_.length() >= 1) {
      sp.valueProperty("arg0", args_[0]);
    }
    if (args_.length() >= 2) {
      sp.valueProperty("arg1", args_[1]);
    }
  }
#endif
}

// Class which holds a shape pointer for use when caches might reference data in
// other zones.
static const JSClass shapeContainerClass = {"ShapeContainer",
                                            JSCLASS_HAS_RESERVED_SLOTS(1)};

static const size_t SHAPE_CONTAINER_SLOT = 0;

static JSObject* NewWrapperWithObjectShape(JSContext* cx,
                                           Handle<NativeObject*> obj) {
  MOZ_ASSERT(cx->compartment() != obj->compartment());

  RootedObject wrapper(cx);
  {
    AutoRealm ar(cx, obj);
    wrapper = NewBuiltinClassInstance(cx, &shapeContainerClass);
    if (!wrapper) {
      return nullptr;
    }
    wrapper->as<NativeObject>().setReservedSlot(
        SHAPE_CONTAINER_SLOT, PrivateGCThingValue(obj->shape()));
  }
  if (!JS_WrapObject(cx, &wrapper)) {
    return nullptr;
  }
  MOZ_ASSERT(IsWrapper(wrapper));
  return wrapper;
}

void jit::LoadShapeWrapperContents(MacroAssembler& masm, Register obj,
                                   Register dst, Label* failure) {
  masm.loadPtr(Address(obj, ProxyObject::offsetOfReservedSlots()), dst);
  Address privateAddr(dst,
                      js::detail::ProxyReservedSlots::offsetOfPrivateSlot());
  masm.fallibleUnboxObject(privateAddr, dst, failure);
  masm.unboxNonDouble(
      Address(dst, NativeObject::getFixedSlotOffset(SHAPE_CONTAINER_SLOT)), dst,
      JSVAL_TYPE_PRIVATE_GCTHING);
}

static bool CanConvertToInt32ForToNumber(const Value& v) {
  return v.isInt32() || v.isBoolean() || v.isNull();
}

static Int32OperandId EmitGuardToInt32ForToNumber(CacheIRWriter& writer,
                                                  ValOperandId id,
                                                  const Value& v) {
  if (v.isInt32()) {
    return writer.guardToInt32(id);
  }
  if (v.isNull()) {
    writer.guardIsNull(id);
    return writer.loadInt32Constant(0);
  }
  MOZ_ASSERT(v.isBoolean());
  return writer.guardBooleanToInt32(id);
}

static bool CanConvertToDoubleForToNumber(const Value& v) {
  return v.isNumber() || v.isBoolean() || v.isNullOrUndefined();
}

static NumberOperandId EmitGuardToDoubleForToNumber(CacheIRWriter& writer,
                                                    ValOperandId id,
                                                    const Value& v) {
  if (v.isNumber()) {
    return writer.guardIsNumber(id);
  }
  if (v.isBoolean()) {
    BooleanOperandId boolId = writer.guardToBoolean(id);
    return writer.booleanToNumber(boolId);
  }
  if (v.isNull()) {
    writer.guardIsNull(id);
    return writer.loadDoubleConstant(0.0);
  }
  MOZ_ASSERT(v.isUndefined());
  writer.guardIsUndefined(id);
  return writer.loadDoubleConstant(JS::GenericNaN());
}

CompareIRGenerator::CompareIRGenerator(JSContext* cx, HandleScript script,
                                       jsbytecode* pc, ICState state, JSOp op,
                                       HandleValue lhsVal, HandleValue rhsVal)
    : IRGenerator(cx, script, pc, CacheKind::Compare, state),
      op_(op),
      lhsVal_(lhsVal),
      rhsVal_(rhsVal) {}

AttachDecision CompareIRGenerator::tryAttachString(ValOperandId lhsId,
                                                   ValOperandId rhsId) {
  if (!lhsVal_.isString() || !rhsVal_.isString()) {
    return AttachDecision::NoAction;
  }

  StringOperandId lhsStrId = writer.guardToString(lhsId);
  StringOperandId rhsStrId = writer.guardToString(rhsId);
  writer.compareStringResult(op_, lhsStrId, rhsStrId);
  writer.returnFromIC();

  trackAttached("Compare.String");
  return AttachDecision::Attach;
}

AttachDecision CompareIRGenerator::tryAttachObject(ValOperandId lhsId,
                                                   ValOperandId rhsId) {
  MOZ_ASSERT(IsEqualityOp(op_));

  if (!lhsVal_.isObject() || !rhsVal_.isObject()) {
    return AttachDecision::NoAction;
  }

  ObjOperandId lhsObjId = writer.guardToObject(lhsId);
  ObjOperandId rhsObjId = writer.guardToObject(rhsId);
  writer.compareObjectResult(op_, lhsObjId, rhsObjId);
  writer.returnFromIC();

  trackAttached("Compare.Object");
  return AttachDecision::Attach;
}

AttachDecision CompareIRGenerator::tryAttachSymbol(ValOperandId lhsId,
                                                   ValOperandId rhsId) {
  MOZ_ASSERT(IsEqualityOp(op_));

  if (!lhsVal_.isSymbol() || !rhsVal_.isSymbol()) {
    return AttachDecision::NoAction;
  }

  SymbolOperandId lhsSymId = writer.guardToSymbol(lhsId);
  SymbolOperandId rhsSymId = writer.guardToSymbol(rhsId);
  writer.compareSymbolResult(op_, lhsSymId, rhsSymId);
  writer.returnFromIC();

  trackAttached("Compare.Symbol");
  return AttachDecision::Attach;
}

AttachDecision CompareIRGenerator::tryAttachStrictDifferentTypes(
    ValOperandId lhsId, ValOperandId rhsId) {
  MOZ_ASSERT(IsEqualityOp(op_));

  if (op_ != JSOp::StrictEq && op_ != JSOp::StrictNe) {
    return AttachDecision::NoAction;
  }

  // Probably can't hit some of these.
  if (SameType(lhsVal_, rhsVal_) ||
      (lhsVal_.isNumber() && rhsVal_.isNumber())) {
    return AttachDecision::NoAction;
  }

  // Compare tags
  ValueTagOperandId lhsTypeId = writer.loadValueTag(lhsId);
  ValueTagOperandId rhsTypeId = writer.loadValueTag(rhsId);
  writer.guardTagNotEqual(lhsTypeId, rhsTypeId);

  // Now that we've passed the guard, we know differing types, so return the
  // bool result.
  writer.loadBooleanResult(op_ == JSOp::StrictNe ? true : false);
  writer.returnFromIC();

  trackAttached("Compare.StrictDifferentTypes");
  return AttachDecision::Attach;
}

AttachDecision CompareIRGenerator::tryAttachInt32(ValOperandId lhsId,
                                                  ValOperandId rhsId) {
  if (!CanConvertToInt32ForToNumber(lhsVal_) ||
      !CanConvertToInt32ForToNumber(rhsVal_)) {
    return AttachDecision::NoAction;
  }

  // Strictly different types should have been handed by
  // tryAttachStrictDifferentTypes.
  MOZ_ASSERT_IF(op_ == JSOp::StrictEq || op_ == JSOp::StrictNe,
                lhsVal_.type() == rhsVal_.type());

  // Should have been handled by tryAttachAnyNullUndefined.
  MOZ_ASSERT_IF(lhsVal_.isNull() || rhsVal_.isNull(), !IsEqualityOp(op_));

  Int32OperandId lhsIntId = EmitGuardToInt32ForToNumber(writer, lhsId, lhsVal_);
  Int32OperandId rhsIntId = EmitGuardToInt32ForToNumber(writer, rhsId, rhsVal_);

  writer.compareInt32Result(op_, lhsIntId, rhsIntId);
  writer.returnFromIC();

  trackAttached("Compare.Int32");
  return AttachDecision::Attach;
}

AttachDecision CompareIRGenerator::tryAttachNumber(ValOperandId lhsId,
                                                   ValOperandId rhsId) {
  if (!CanConvertToDoubleForToNumber(lhsVal_) ||
      !CanConvertToDoubleForToNumber(rhsVal_)) {
    return AttachDecision::NoAction;
  }

  // Strictly different types should have been handed by
  // tryAttachStrictDifferentTypes.
  MOZ_ASSERT_IF(op_ == JSOp::StrictEq || op_ == JSOp::StrictNe,
                lhsVal_.type() == rhsVal_.type() ||
                    (lhsVal_.isNumber() && rhsVal_.isNumber()));

  // Should have been handled by tryAttachAnyNullUndefined.
  MOZ_ASSERT_IF(lhsVal_.isNullOrUndefined() || rhsVal_.isNullOrUndefined(),
                !IsEqualityOp(op_));

  NumberOperandId lhs = EmitGuardToDoubleForToNumber(writer, lhsId, lhsVal_);
  NumberOperandId rhs = EmitGuardToDoubleForToNumber(writer, rhsId, rhsVal_);
  writer.compareDoubleResult(op_, lhs, rhs);
  writer.returnFromIC();

  trackAttached("Compare.Number");
  return AttachDecision::Attach;
}

AttachDecision CompareIRGenerator::tryAttachBigInt(ValOperandId lhsId,
                                                   ValOperandId rhsId) {
  if (!lhsVal_.isBigInt() || !rhsVal_.isBigInt()) {
    return AttachDecision::NoAction;
  }

  BigIntOperandId lhs = writer.guardToBigInt(lhsId);
  BigIntOperandId rhs = writer.guardToBigInt(rhsId);

  writer.compareBigIntResult(op_, lhs, rhs);
  writer.returnFromIC();

  trackAttached("Compare.BigInt");
  return AttachDecision::Attach;
}

AttachDecision CompareIRGenerator::tryAttachAnyNullUndefined(
    ValOperandId lhsId, ValOperandId rhsId) {
  MOZ_ASSERT(IsEqualityOp(op_));

  // Either RHS or LHS needs to be null/undefined.
  if (!lhsVal_.isNullOrUndefined() && !rhsVal_.isNullOrUndefined()) {
    return AttachDecision::NoAction;
  }

  // We assume that the side with null/undefined is usually constant, in
  // code like `if (x === undefined) { x = {}; }`.
  // That is why we don't attach when both sides are undefined/null,
  // because we would basically need to decide by chance which side is
  // the likely constant.
  // The actual generated code however handles null/undefined of course.
  if (lhsVal_.isNullOrUndefined() && rhsVal_.isNullOrUndefined()) {
    return AttachDecision::NoAction;
  }

  if (rhsVal_.isNullOrUndefined()) {
    if (rhsVal_.isNull()) {
      writer.guardIsNull(rhsId);
      writer.compareNullUndefinedResult(op_, /* isUndefined */ false, lhsId);
      trackAttached("Compare.AnyNull");
    } else {
      writer.guardIsUndefined(rhsId);
      writer.compareNullUndefinedResult(op_, /* isUndefined */ true, lhsId);
      trackAttached("Compare.AnyUndefined");
    }
  } else {
    if (lhsVal_.isNull()) {
      writer.guardIsNull(lhsId);
      writer.compareNullUndefinedResult(op_, /* isUndefined */ false, rhsId);
      trackAttached("Compare.NullAny");
    } else {
      writer.guardIsUndefined(lhsId);
      writer.compareNullUndefinedResult(op_, /* isUndefined */ true, rhsId);
      trackAttached("Compare.UndefinedAny");
    }
  }

  writer.returnFromIC();
  return AttachDecision::Attach;
}

// Handle {null/undefined} x {null,undefined} equality comparisons
AttachDecision CompareIRGenerator::tryAttachNullUndefined(ValOperandId lhsId,
                                                          ValOperandId rhsId) {
  if (!lhsVal_.isNullOrUndefined() || !rhsVal_.isNullOrUndefined()) {
    return AttachDecision::NoAction;
  }

  if (op_ == JSOp::Eq || op_ == JSOp::Ne) {
    writer.guardIsNullOrUndefined(lhsId);
    writer.guardIsNullOrUndefined(rhsId);
    // Sloppy equality means we actually only care about the op:
    writer.loadBooleanResult(op_ == JSOp::Eq);
    trackAttached("Compare.SloppyNullUndefined");
  } else {
    // Strict equality only hits this branch, and only in the
    // undef {!,=}==  undef and null {!,=}== null cases.
    // The other cases should have hit tryAttachStrictDifferentTypes.
    MOZ_ASSERT(lhsVal_.isNull() == rhsVal_.isNull());
    lhsVal_.isNull() ? writer.guardIsNull(lhsId)
                     : writer.guardIsUndefined(lhsId);
    rhsVal_.isNull() ? writer.guardIsNull(rhsId)
                     : writer.guardIsUndefined(rhsId);
    writer.loadBooleanResult(op_ == JSOp::StrictEq);
    trackAttached("Compare.StrictNullUndefinedEquality");
  }

  writer.returnFromIC();
  return AttachDecision::Attach;
}

AttachDecision CompareIRGenerator::tryAttachStringNumber(ValOperandId lhsId,
                                                         ValOperandId rhsId) {
  // Ensure String x {Number, Boolean, Null, Undefined}
  if (!(lhsVal_.isString() && CanConvertToDoubleForToNumber(rhsVal_)) &&
      !(rhsVal_.isString() && CanConvertToDoubleForToNumber(lhsVal_))) {
    return AttachDecision::NoAction;
  }

  // Case should have been handled by tryAttachStrictDifferentTypes
  MOZ_ASSERT(op_ != JSOp::StrictEq && op_ != JSOp::StrictNe);

  auto createGuards = [&](const Value& v, ValOperandId vId) {
    if (v.isString()) {
      StringOperandId strId = writer.guardToString(vId);
      return writer.guardStringToNumber(strId);
    }
    return EmitGuardToDoubleForToNumber(writer, vId, v);
  };

  NumberOperandId lhsGuardedId = createGuards(lhsVal_, lhsId);
  NumberOperandId rhsGuardedId = createGuards(rhsVal_, rhsId);
  writer.compareDoubleResult(op_, lhsGuardedId, rhsGuardedId);
  writer.returnFromIC();

  trackAttached("Compare.StringNumber");
  return AttachDecision::Attach;
}

AttachDecision CompareIRGenerator::tryAttachPrimitiveSymbol(
    ValOperandId lhsId, ValOperandId rhsId) {
  MOZ_ASSERT(IsEqualityOp(op_));

  // The set of primitive cases we want to handle here (excluding null,
  // undefined, and symbol)
  auto isPrimitive = [](const Value& x) {
    return x.isString() || x.isBoolean() || x.isNumber() || x.isBigInt();
  };

  // Ensure Symbol x {String, Bool, Number, BigInt}.
  if (!(lhsVal_.isSymbol() && isPrimitive(rhsVal_)) &&
      !(rhsVal_.isSymbol() && isPrimitive(lhsVal_))) {
    return AttachDecision::NoAction;
  }

  auto guardPrimitive = [&](const Value& v, ValOperandId id) {
    MOZ_ASSERT(isPrimitive(v));
    if (v.isNumber()) {
      writer.guardIsNumber(id);
      return;
    }
    switch (v.extractNonDoubleType()) {
      case JSVAL_TYPE_STRING:
        writer.guardToString(id);
        return;
      case JSVAL_TYPE_BOOLEAN:
        writer.guardToBoolean(id);
        return;
      case JSVAL_TYPE_BIGINT:
        writer.guardToBigInt(id);
        return;
      default:
        MOZ_CRASH("unexpected type");
        return;
    }
  };

  if (lhsVal_.isSymbol()) {
    writer.guardToSymbol(lhsId);
    guardPrimitive(rhsVal_, rhsId);
  } else {
    guardPrimitive(lhsVal_, lhsId);
    writer.guardToSymbol(rhsId);
  }

  // Comparing a primitive with symbol will always be true for Ne/StrictNe, and
  // always be false for other compare ops.
  writer.loadBooleanResult(op_ == JSOp::Ne || op_ == JSOp::StrictNe);
  writer.returnFromIC();

  trackAttached("Compare.PrimitiveSymbol");
  return AttachDecision::Attach;
}

AttachDecision CompareIRGenerator::tryAttachBigIntInt32(ValOperandId lhsId,
                                                        ValOperandId rhsId) {
  // Ensure BigInt x {Int32, Boolean, Null}.
  if (!(lhsVal_.isBigInt() && CanConvertToInt32ForToNumber(rhsVal_)) &&
      !(rhsVal_.isBigInt() && CanConvertToInt32ForToNumber(lhsVal_))) {
    return AttachDecision::NoAction;
  }

  // Case should have been handled by tryAttachStrictDifferentTypes
  MOZ_ASSERT(op_ != JSOp::StrictEq && op_ != JSOp::StrictNe);

  if (lhsVal_.isBigInt()) {
    BigIntOperandId bigIntId = writer.guardToBigInt(lhsId);
    Int32OperandId intId = EmitGuardToInt32ForToNumber(writer, rhsId, rhsVal_);

    writer.compareBigIntInt32Result(op_, bigIntId, intId);
  } else {
    Int32OperandId intId = EmitGuardToInt32ForToNumber(writer, lhsId, lhsVal_);
    BigIntOperandId bigIntId = writer.guardToBigInt(rhsId);

    writer.compareBigIntInt32Result(ReverseCompareOp(op_), bigIntId, intId);
  }
  writer.returnFromIC();

  trackAttached("Compare.BigIntInt32");
  return AttachDecision::Attach;
}

AttachDecision CompareIRGenerator::tryAttachBigIntNumber(ValOperandId lhsId,
                                                         ValOperandId rhsId) {
  // Ensure BigInt x {Number, Undefined}.
  if (!(lhsVal_.isBigInt() && CanConvertToDoubleForToNumber(rhsVal_)) &&
      !(rhsVal_.isBigInt() && CanConvertToDoubleForToNumber(lhsVal_))) {
    return AttachDecision::NoAction;
  }

  // Case should have been handled by tryAttachStrictDifferentTypes
  MOZ_ASSERT(op_ != JSOp::StrictEq && op_ != JSOp::StrictNe);

  // Case should have been handled by tryAttachBigIntInt32.
  MOZ_ASSERT(!CanConvertToInt32ForToNumber(lhsVal_));
  MOZ_ASSERT(!CanConvertToInt32ForToNumber(rhsVal_));

  if (lhsVal_.isBigInt()) {
    BigIntOperandId bigIntId = writer.guardToBigInt(lhsId);
    NumberOperandId numId =
        EmitGuardToDoubleForToNumber(writer, rhsId, rhsVal_);

    writer.compareBigIntNumberResult(op_, bigIntId, numId);
  } else {
    NumberOperandId numId =
        EmitGuardToDoubleForToNumber(writer, lhsId, lhsVal_);
    BigIntOperandId bigIntId = writer.guardToBigInt(rhsId);

    writer.compareBigIntNumberResult(ReverseCompareOp(op_), bigIntId, numId);
  }
  writer.returnFromIC();

  trackAttached("Compare.BigIntNumber");
  return AttachDecision::Attach;
}

AttachDecision CompareIRGenerator::tryAttachBigIntString(ValOperandId lhsId,
                                                         ValOperandId rhsId) {
  // Ensure BigInt x String.
  if (!(lhsVal_.isBigInt() && rhsVal_.isString()) &&
      !(rhsVal_.isBigInt() && lhsVal_.isString())) {
    return AttachDecision::NoAction;
  }

  // Case should have been handled by tryAttachStrictDifferentTypes
  MOZ_ASSERT(op_ != JSOp::StrictEq && op_ != JSOp::StrictNe);

  if (lhsVal_.isBigInt()) {
    BigIntOperandId bigIntId = writer.guardToBigInt(lhsId);
    StringOperandId strId = writer.guardToString(rhsId);

    writer.compareBigIntStringResult(op_, bigIntId, strId);
  } else {
    StringOperandId strId = writer.guardToString(lhsId);
    BigIntOperandId bigIntId = writer.guardToBigInt(rhsId);

    writer.compareBigIntStringResult(ReverseCompareOp(op_), bigIntId, strId);
  }
  writer.returnFromIC();

  trackAttached("Compare.BigIntString");
  return AttachDecision::Attach;
}

AttachDecision CompareIRGenerator::tryAttachStub() {
  MOZ_ASSERT(cacheKind_ == CacheKind::Compare);
  MOZ_ASSERT(IsEqualityOp(op_) || IsRelationalOp(op_));

  AutoAssertNoPendingException aanpe(cx_);

  constexpr uint8_t lhsIndex = 0;
  constexpr uint8_t rhsIndex = 1;

  ValOperandId lhsId(writer.setInputOperandId(lhsIndex));
  ValOperandId rhsId(writer.setInputOperandId(rhsIndex));

  // For sloppy equality ops, there are cases this IC does not handle:
  // - {Object} x {String, Symbol, Bool, Number, BigInt}.
  //
  // For relational comparison ops, these cases aren't handled:
  // - Object x {String, Bool, Number, BigInt, Object, Null, Undefined}.
  // Note: |Symbol x any| always throws, so it doesn't need to be handled.
  //
  // (The above lists omits the equivalent case {B} x {A} when {A} x {B} is
  // already present.)

  if (IsEqualityOp(op_)) {
    TRY_ATTACH(tryAttachObject(lhsId, rhsId));
    TRY_ATTACH(tryAttachSymbol(lhsId, rhsId));

    // Handles any (non null or undefined) comparison with null/undefined.
    TRY_ATTACH(tryAttachAnyNullUndefined(lhsId, rhsId));

    // This covers -strict- equality/inequality using a type tag check, so
    // catches all different type pairs outside of Numbers, which cannot be
    // checked on tags alone.
    TRY_ATTACH(tryAttachStrictDifferentTypes(lhsId, rhsId));

    TRY_ATTACH(tryAttachNullUndefined(lhsId, rhsId));

    TRY_ATTACH(tryAttachPrimitiveSymbol(lhsId, rhsId));
  }

  // We want these to be last, to allow us to bypass the
  // strictly-different-types cases in the below attachment code
  TRY_ATTACH(tryAttachInt32(lhsId, rhsId));
  TRY_ATTACH(tryAttachNumber(lhsId, rhsId));
  TRY_ATTACH(tryAttachBigInt(lhsId, rhsId));
  TRY_ATTACH(tryAttachString(lhsId, rhsId));

  TRY_ATTACH(tryAttachStringNumber(lhsId, rhsId));

  TRY_ATTACH(tryAttachBigIntInt32(lhsId, rhsId));
  TRY_ATTACH(tryAttachBigIntNumber(lhsId, rhsId));
  TRY_ATTACH(tryAttachBigIntString(lhsId, rhsId));

  // Strict equality is always supported.
  MOZ_ASSERT(!IsStrictEqualityOp(op_));

  // Other operations are unsupported iff at least one operand is an object.
  MOZ_ASSERT(lhsVal_.isObject() || rhsVal_.isObject());

  trackAttached(IRGenerator::NotAttached);
  return AttachDecision::NoAction;
}

void CompareIRGenerator::trackAttached(const char* name) {
  stubName_ = name ? name : "NotAttached";
#ifdef JS_CACHEIR_SPEW
  if (const CacheIRSpewer::Guard& sp = CacheIRSpewer::Guard(*this, name)) {
    sp.valueProperty("lhs", lhsVal_);
    sp.valueProperty("rhs", rhsVal_);
    sp.opcodeProperty("op", op_);
  }
#endif
}

ToBoolIRGenerator::ToBoolIRGenerator(JSContext* cx, HandleScript script,
                                     jsbytecode* pc, ICState state,
                                     HandleValue val)
    : IRGenerator(cx, script, pc, CacheKind::ToBool, state), val_(val) {}

void ToBoolIRGenerator::trackAttached(const char* name) {
  stubName_ = name ? name : "NotAttached";
#ifdef JS_CACHEIR_SPEW
  if (const CacheIRSpewer::Guard& sp = CacheIRSpewer::Guard(*this, name)) {
    sp.valueProperty("val", val_);
  }
#endif
}

AttachDecision ToBoolIRGenerator::tryAttachStub() {
  AutoAssertNoPendingException aanpe(cx_);
  writer.setTypeData(TypeData(JSValueType(val_.type())));

  TRY_ATTACH(tryAttachBool());
  TRY_ATTACH(tryAttachInt32());
  TRY_ATTACH(tryAttachNumber());
  TRY_ATTACH(tryAttachString());
  TRY_ATTACH(tryAttachNullOrUndefined());
  TRY_ATTACH(tryAttachObject());
  TRY_ATTACH(tryAttachSymbol());
  TRY_ATTACH(tryAttachBigInt());

  trackAttached(IRGenerator::NotAttached);
  return AttachDecision::NoAction;
}

AttachDecision ToBoolIRGenerator::tryAttachBool() {
  if (!val_.isBoolean()) {
    return AttachDecision::NoAction;
  }

  ValOperandId valId(writer.setInputOperandId(0));
  writer.guardNonDoubleType(valId, ValueType::Boolean);
  writer.loadOperandResult(valId);
  writer.returnFromIC();
  trackAttached("ToBool.Bool");
  return AttachDecision::Attach;
}

AttachDecision ToBoolIRGenerator::tryAttachInt32() {
  if (!val_.isInt32()) {
    return AttachDecision::NoAction;
  }

  ValOperandId valId(writer.setInputOperandId(0));
  writer.guardNonDoubleType(valId, ValueType::Int32);
  writer.loadInt32TruthyResult(valId);
  writer.returnFromIC();
  trackAttached("ToBool.Int32");
  return AttachDecision::Attach;
}

AttachDecision ToBoolIRGenerator::tryAttachNumber() {
  if (!val_.isNumber()) {
    return AttachDecision::NoAction;
  }

  ValOperandId valId(writer.setInputOperandId(0));
  NumberOperandId numId = writer.guardIsNumber(valId);
  writer.loadDoubleTruthyResult(numId);
  writer.returnFromIC();
  trackAttached("ToBool.Number");
  return AttachDecision::Attach;
}

AttachDecision ToBoolIRGenerator::tryAttachSymbol() {
  if (!val_.isSymbol()) {
    return AttachDecision::NoAction;
  }

  ValOperandId valId(writer.setInputOperandId(0));
  writer.guardNonDoubleType(valId, ValueType::Symbol);
  writer.loadBooleanResult(true);
  writer.returnFromIC();
  trackAttached("ToBool.Symbol");
  return AttachDecision::Attach;
}

AttachDecision ToBoolIRGenerator::tryAttachString() {
  if (!val_.isString()) {
    return AttachDecision::NoAction;
  }

  ValOperandId valId(writer.setInputOperandId(0));
  StringOperandId strId = writer.guardToString(valId);
  writer.loadStringTruthyResult(strId);
  writer.returnFromIC();
  trackAttached("ToBool.String");
  return AttachDecision::Attach;
}

AttachDecision ToBoolIRGenerator::tryAttachNullOrUndefined() {
  if (!val_.isNullOrUndefined()) {
    return AttachDecision::NoAction;
  }

  ValOperandId valId(writer.setInputOperandId(0));
  writer.guardIsNullOrUndefined(valId);
  writer.loadBooleanResult(false);
  writer.returnFromIC();
  trackAttached("ToBool.NullOrUndefined");
  return AttachDecision::Attach;
}

AttachDecision ToBoolIRGenerator::tryAttachObject() {
  if (!val_.isObject()) {
    return AttachDecision::NoAction;
  }

  ValOperandId valId(writer.setInputOperandId(0));
  ObjOperandId objId = writer.guardToObject(valId);
  writer.loadObjectTruthyResult(objId);
  writer.returnFromIC();
  trackAttached("ToBool.Object");
  return AttachDecision::Attach;
}

AttachDecision ToBoolIRGenerator::tryAttachBigInt() {
  if (!val_.isBigInt()) {
    return AttachDecision::NoAction;
  }

  ValOperandId valId(writer.setInputOperandId(0));
  BigIntOperandId bigIntId = writer.guardToBigInt(valId);
  writer.loadBigIntTruthyResult(bigIntId);
  writer.returnFromIC();
  trackAttached("ToBool.BigInt");
  return AttachDecision::Attach;
}

GetIntrinsicIRGenerator::GetIntrinsicIRGenerator(JSContext* cx,
                                                 HandleScript script,
                                                 jsbytecode* pc, ICState state,
                                                 HandleValue val)
    : IRGenerator(cx, script, pc, CacheKind::GetIntrinsic, state), val_(val) {}

void GetIntrinsicIRGenerator::trackAttached(const char* name) {
  stubName_ = name ? name : "NotAttached";
#ifdef JS_CACHEIR_SPEW
  if (const CacheIRSpewer::Guard& sp = CacheIRSpewer::Guard(*this, name)) {
    sp.valueProperty("val", val_);
  }
#endif
}

AttachDecision GetIntrinsicIRGenerator::tryAttachStub() {
  AutoAssertNoPendingException aanpe(cx_);
  writer.loadValueResult(val_);
  writer.returnFromIC();
  trackAttached("GetIntrinsic");
  return AttachDecision::Attach;
}

UnaryArithIRGenerator::UnaryArithIRGenerator(JSContext* cx, HandleScript script,
                                             jsbytecode* pc, ICState state,
                                             JSOp op, HandleValue val,
                                             HandleValue res)
    : IRGenerator(cx, script, pc, CacheKind::UnaryArith, state),
      op_(op),
      val_(val),
      res_(res) {}

void UnaryArithIRGenerator::trackAttached(const char* name) {
  stubName_ = name ? name : "NotAttached";
#ifdef JS_CACHEIR_SPEW
  if (const CacheIRSpewer::Guard& sp = CacheIRSpewer::Guard(*this, name)) {
    sp.valueProperty("val", val_);
    sp.valueProperty("res", res_);
  }
#endif
}

AttachDecision UnaryArithIRGenerator::tryAttachStub() {
  AutoAssertNoPendingException aanpe(cx_);
  TRY_ATTACH(tryAttachInt32());
  TRY_ATTACH(tryAttachNumber());
  TRY_ATTACH(tryAttachBitwise());
  TRY_ATTACH(tryAttachBigInt());
  TRY_ATTACH(tryAttachStringInt32());
  TRY_ATTACH(tryAttachStringNumber());

  trackAttached(IRGenerator::NotAttached);
  return AttachDecision::NoAction;
}

AttachDecision UnaryArithIRGenerator::tryAttachInt32() {
  if (op_ == JSOp::BitNot) {
    return AttachDecision::NoAction;
  }
  if (!CanConvertToInt32ForToNumber(val_) || !res_.isInt32()) {
    return AttachDecision::NoAction;
  }

  ValOperandId valId(writer.setInputOperandId(0));

  Int32OperandId intId = EmitGuardToInt32ForToNumber(writer, valId, val_);
  switch (op_) {
    case JSOp::Pos:
      writer.loadInt32Result(intId);
      trackAttached("UnaryArith.Int32Pos");
      break;
    case JSOp::Neg:
      writer.int32NegationResult(intId);
      trackAttached("UnaryArith.Int32Neg");
      break;
    case JSOp::Inc:
      writer.int32IncResult(intId);
      trackAttached("UnaryArith.Int32Inc");
      break;
    case JSOp::Dec:
      writer.int32DecResult(intId);
      trackAttached("UnaryArith.Int32Dec");
      break;
    case JSOp::ToNumeric:
      writer.loadInt32Result(intId);
      trackAttached("UnaryArith.Int32ToNumeric");
      break;
    default:
      MOZ_CRASH("unexpected OP");
  }

  writer.returnFromIC();
  return AttachDecision::Attach;
}

AttachDecision UnaryArithIRGenerator::tryAttachNumber() {
  if (op_ == JSOp::BitNot) {
    return AttachDecision::NoAction;
  }
  if (!CanConvertToDoubleForToNumber(val_)) {
    return AttachDecision::NoAction;
  }
  MOZ_ASSERT(res_.isNumber());

  ValOperandId valId(writer.setInputOperandId(0));
  NumberOperandId numId = EmitGuardToDoubleForToNumber(writer, valId, val_);

  switch (op_) {
    case JSOp::Pos:
      writer.loadDoubleResult(numId);
      trackAttached("UnaryArith.DoublePos");
      break;
    case JSOp::Neg:
      writer.doubleNegationResult(numId);
      trackAttached("UnaryArith.DoubleNeg");
      break;
    case JSOp::Inc:
      writer.doubleIncResult(numId);
      trackAttached("UnaryArith.DoubleInc");
      break;
    case JSOp::Dec:
      writer.doubleDecResult(numId);
      trackAttached("UnaryArith.DoubleDec");
      break;
    case JSOp::ToNumeric:
      writer.loadDoubleResult(numId);
      trackAttached("UnaryArith.DoubleToNumeric");
      break;
    default:
      MOZ_CRASH("Unexpected OP");
  }

  writer.returnFromIC();
  return AttachDecision::Attach;
}

static bool CanTruncateToInt32(const Value& val) {
  return val.isNumber() || val.isBoolean() || val.isNullOrUndefined() ||
         val.isString();
}

// Convert type into int32 for the bitwise/shift operands.
static Int32OperandId EmitTruncateToInt32Guard(CacheIRWriter& writer,
                                               ValOperandId id,
                                               const Value& val) {
  MOZ_ASSERT(CanTruncateToInt32(val));
  if (val.isInt32()) {
    return writer.guardToInt32(id);
  }
  if (val.isBoolean()) {
    return writer.guardBooleanToInt32(id);
  }
  if (val.isNullOrUndefined()) {
    writer.guardIsNullOrUndefined(id);
    return writer.loadInt32Constant(0);
  }
  NumberOperandId numId;
  if (val.isString()) {
    StringOperandId strId = writer.guardToString(id);
    numId = writer.guardStringToNumber(strId);
  } else {
    MOZ_ASSERT(val.isDouble());
    numId = writer.guardIsNumber(id);
  }
  return writer.truncateDoubleToUInt32(numId);
}

AttachDecision UnaryArithIRGenerator::tryAttachBitwise() {
  // Only bitwise operators.
  if (op_ != JSOp::BitNot) {
    return AttachDecision::NoAction;
  }

  // Check guard conditions
  if (!CanTruncateToInt32(val_)) {
    return AttachDecision::NoAction;
  }

  // Bitwise operators always produce Int32 values.
  MOZ_ASSERT(res_.isInt32());

  ValOperandId valId(writer.setInputOperandId(0));
  Int32OperandId intId = EmitTruncateToInt32Guard(writer, valId, val_);
  writer.int32NotResult(intId);
  trackAttached("UnaryArith.BitwiseBitNot");

  writer.returnFromIC();
  return AttachDecision::Attach;
}

AttachDecision UnaryArithIRGenerator::tryAttachBigInt() {
  if (!val_.isBigInt()) {
    return AttachDecision::NoAction;
  }
  MOZ_ASSERT(res_.isBigInt());

  MOZ_ASSERT(op_ != JSOp::Pos,
             "Applying the unary + operator on BigInt values throws an error");

  ValOperandId valId(writer.setInputOperandId(0));
  BigIntOperandId bigIntId = writer.guardToBigInt(valId);
  switch (op_) {
    case JSOp::BitNot:
      writer.bigIntNotResult(bigIntId);
      trackAttached("UnaryArith.BigIntNot");
      break;
    case JSOp::Neg:
      writer.bigIntNegationResult(bigIntId);
      trackAttached("UnaryArith.BigIntNeg");
      break;
    case JSOp::Inc:
      writer.bigIntIncResult(bigIntId);
      trackAttached("UnaryArith.BigIntInc");
      break;
    case JSOp::Dec:
      writer.bigIntDecResult(bigIntId);
      trackAttached("UnaryArith.BigIntDec");
      break;
    case JSOp::ToNumeric:
      writer.loadBigIntResult(bigIntId);
      trackAttached("UnaryArith.BigIntToNumeric");
      break;
    default:
      MOZ_CRASH("Unexpected OP");
  }

  writer.returnFromIC();
  return AttachDecision::Attach;
}

AttachDecision UnaryArithIRGenerator::tryAttachStringInt32() {
  if (!val_.isString()) {
    return AttachDecision::NoAction;
  }
  MOZ_ASSERT(res_.isNumber());

  // Case should have been handled by tryAttachBitwise.
  MOZ_ASSERT(op_ != JSOp::BitNot);

  if (!res_.isInt32()) {
    return AttachDecision::NoAction;
  }

  ValOperandId valId(writer.setInputOperandId(0));
  StringOperandId stringId = writer.guardToString(valId);
  Int32OperandId intId = writer.guardStringToInt32(stringId);

  switch (op_) {
    case JSOp::Pos:
      writer.loadInt32Result(intId);
      trackAttached("UnaryArith.StringInt32Pos");
      break;
    case JSOp::Neg:
      writer.int32NegationResult(intId);
      trackAttached("UnaryArith.StringInt32Neg");
      break;
    case JSOp::Inc:
      writer.int32IncResult(intId);
      trackAttached("UnaryArith.StringInt32Inc");
      break;
    case JSOp::Dec:
      writer.int32DecResult(intId);
      trackAttached("UnaryArith.StringInt32Dec");
      break;
    case JSOp::ToNumeric:
      writer.loadInt32Result(intId);
      trackAttached("UnaryArith.StringInt32ToNumeric");
      break;
    default:
      MOZ_CRASH("Unexpected OP");
  }

  writer.returnFromIC();
  return AttachDecision::Attach;
}

AttachDecision UnaryArithIRGenerator::tryAttachStringNumber() {
  if (!val_.isString()) {
    return AttachDecision::NoAction;
  }
  MOZ_ASSERT(res_.isNumber());

  // Case should have been handled by tryAttachBitwise.
  MOZ_ASSERT(op_ != JSOp::BitNot);

  ValOperandId valId(writer.setInputOperandId(0));
  StringOperandId stringId = writer.guardToString(valId);
  NumberOperandId numId = writer.guardStringToNumber(stringId);

  Int32OperandId truncatedId;
  switch (op_) {
    case JSOp::Pos:
      writer.loadDoubleResult(numId);
      trackAttached("UnaryArith.StringNumberPos");
      break;
    case JSOp::Neg:
      writer.doubleNegationResult(numId);
      trackAttached("UnaryArith.StringNumberNeg");
      break;
    case JSOp::Inc:
      writer.doubleIncResult(numId);
      trackAttached("UnaryArith.StringNumberInc");
      break;
    case JSOp::Dec:
      writer.doubleDecResult(numId);
      trackAttached("UnaryArith.StringNumberDec");
      break;
    case JSOp::ToNumeric:
      writer.loadDoubleResult(numId);
      trackAttached("UnaryArith.StringNumberToNumeric");
      break;
    default:
      MOZ_CRASH("Unexpected OP");
  }

  writer.returnFromIC();
  return AttachDecision::Attach;
}

ToPropertyKeyIRGenerator::ToPropertyKeyIRGenerator(JSContext* cx,
                                                   HandleScript script,
                                                   jsbytecode* pc,
                                                   ICState state,
                                                   HandleValue val)
    : IRGenerator(cx, script, pc, CacheKind::ToPropertyKey, state), val_(val) {}

void ToPropertyKeyIRGenerator::trackAttached(const char* name) {
  stubName_ = name ? name : "NotAttached";
#ifdef JS_CACHEIR_SPEW
  if (const CacheIRSpewer::Guard& sp = CacheIRSpewer::Guard(*this, name)) {
    sp.valueProperty("val", val_);
  }
#endif
}

AttachDecision ToPropertyKeyIRGenerator::tryAttachStub() {
  AutoAssertNoPendingException aanpe(cx_);
  TRY_ATTACH(tryAttachInt32());
  TRY_ATTACH(tryAttachNumber());
  TRY_ATTACH(tryAttachString());
  TRY_ATTACH(tryAttachSymbol());

  trackAttached(IRGenerator::NotAttached);
  return AttachDecision::NoAction;
}

AttachDecision ToPropertyKeyIRGenerator::tryAttachInt32() {
  if (!val_.isInt32()) {
    return AttachDecision::NoAction;
  }

  ValOperandId valId(writer.setInputOperandId(0));

  Int32OperandId intId = writer.guardToInt32(valId);
  writer.loadInt32Result(intId);
  writer.returnFromIC();

  trackAttached("ToPropertyKey.Int32");
  return AttachDecision::Attach;
}

AttachDecision ToPropertyKeyIRGenerator::tryAttachNumber() {
  if (!val_.isNumber()) {
    return AttachDecision::NoAction;
  }

  // We allow negative zero here because ToPropertyKey(-0.0) is 0.
  int32_t unused;
  if (!mozilla::NumberEqualsInt32(val_.toNumber(), &unused)) {
    return AttachDecision::NoAction;
  }

  ValOperandId valId(writer.setInputOperandId(0));

  Int32OperandId intId = writer.guardToInt32Index(valId);
  writer.loadInt32Result(intId);
  writer.returnFromIC();

  trackAttached("ToPropertyKey.Number");
  return AttachDecision::Attach;
}

AttachDecision ToPropertyKeyIRGenerator::tryAttachString() {
  if (!val_.isString()) {
    return AttachDecision::NoAction;
  }

  ValOperandId valId(writer.setInputOperandId(0));

  StringOperandId strId = writer.guardToString(valId);
  writer.loadStringResult(strId);
  writer.returnFromIC();

  trackAttached("ToPropertyKey.String");
  return AttachDecision::Attach;
}

AttachDecision ToPropertyKeyIRGenerator::tryAttachSymbol() {
  if (!val_.isSymbol()) {
    return AttachDecision::NoAction;
  }

  ValOperandId valId(writer.setInputOperandId(0));

  SymbolOperandId strId = writer.guardToSymbol(valId);
  writer.loadSymbolResult(strId);
  writer.returnFromIC();

  trackAttached("ToPropertyKey.Symbol");
  return AttachDecision::Attach;
}

BinaryArithIRGenerator::BinaryArithIRGenerator(JSContext* cx,
                                               HandleScript script,
                                               jsbytecode* pc, ICState state,
                                               JSOp op, HandleValue lhs,
                                               HandleValue rhs, HandleValue res)
    : IRGenerator(cx, script, pc, CacheKind::BinaryArith, state),
      op_(op),
      lhs_(lhs),
      rhs_(rhs),
      res_(res) {}

void BinaryArithIRGenerator::trackAttached(const char* name) {
  stubName_ = name ? name : "NotAttached";
#ifdef JS_CACHEIR_SPEW
  if (const CacheIRSpewer::Guard& sp = CacheIRSpewer::Guard(*this, name)) {
    sp.opcodeProperty("op", op_);
    sp.valueProperty("rhs", rhs_);
    sp.valueProperty("lhs", lhs_);
  }
#endif
}

AttachDecision BinaryArithIRGenerator::tryAttachStub() {
  AutoAssertNoPendingException aanpe(cx_);
  // Arithmetic operations with Int32 operands
  TRY_ATTACH(tryAttachInt32());

  // Bitwise operations with Int32/Double/Boolean/Null/Undefined/String
  // operands.
  TRY_ATTACH(tryAttachBitwise());

  // Arithmetic operations with Double operands. This needs to come after
  // tryAttachInt32, as the guards overlap, and we'd prefer to attach the
  // more specialized Int32 IC if it is possible.
  TRY_ATTACH(tryAttachDouble());

  // String x {String,Number,Boolean,Null,Undefined}
  TRY_ATTACH(tryAttachStringConcat());

  // String x Object
  TRY_ATTACH(tryAttachStringObjectConcat());

  // Arithmetic operations or bitwise operations with BigInt operands
  TRY_ATTACH(tryAttachBigInt());

  // Arithmetic operations (without addition) with String x Int32.
  TRY_ATTACH(tryAttachStringInt32Arith());

  trackAttached(IRGenerator::NotAttached);
  return AttachDecision::NoAction;
}

AttachDecision BinaryArithIRGenerator::tryAttachBitwise() {
  // Only bit-wise and shifts.
  if (op_ != JSOp::BitOr && op_ != JSOp::BitXor && op_ != JSOp::BitAnd &&
      op_ != JSOp::Lsh && op_ != JSOp::Rsh && op_ != JSOp::Ursh) {
    return AttachDecision::NoAction;
  }

  // Check guard conditions
  if (!CanTruncateToInt32(lhs_) || !CanTruncateToInt32(rhs_)) {
    return AttachDecision::NoAction;
  }

  // All ops, with the exception of Ursh, produce Int32 values.
  MOZ_ASSERT_IF(op_ != JSOp::Ursh, res_.isInt32());

  ValOperandId lhsId(writer.setInputOperandId(0));
  ValOperandId rhsId(writer.setInputOperandId(1));

  Int32OperandId lhsIntId = EmitTruncateToInt32Guard(writer, lhsId, lhs_);
  Int32OperandId rhsIntId = EmitTruncateToInt32Guard(writer, rhsId, rhs_);

  switch (op_) {
    case JSOp::BitOr:
      writer.int32BitOrResult(lhsIntId, rhsIntId);
      trackAttached("BinaryArith.BitwiseBitOr");
      break;
    case JSOp::BitXor:
      writer.int32BitXorResult(lhsIntId, rhsIntId);
      trackAttached("BinaryArith.BitwiseBitXor");
      break;
    case JSOp::BitAnd:
      writer.int32BitAndResult(lhsIntId, rhsIntId);
      trackAttached("BinaryArith.BitwiseBitAnd");
      break;
    case JSOp::Lsh:
      writer.int32LeftShiftResult(lhsIntId, rhsIntId);
      trackAttached("BinaryArith.BitwiseLeftShift");
      break;
    case JSOp::Rsh:
      writer.int32RightShiftResult(lhsIntId, rhsIntId);
      trackAttached("BinaryArith.BitwiseRightShift");
      break;
    case JSOp::Ursh:
      writer.int32URightShiftResult(lhsIntId, rhsIntId, res_.isDouble());
      trackAttached("BinaryArith.BitwiseUnsignedRightShift");
      break;
    default:
      MOZ_CRASH("Unhandled op in tryAttachBitwise");
  }

  writer.returnFromIC();
  return AttachDecision::Attach;
}

AttachDecision BinaryArithIRGenerator::tryAttachDouble() {
  // Check valid opcodes
  if (op_ != JSOp::Add && op_ != JSOp::Sub && op_ != JSOp::Mul &&
      op_ != JSOp::Div && op_ != JSOp::Mod && op_ != JSOp::Pow) {
    return AttachDecision::NoAction;
  }

  // Check guard conditions.
  if (!CanConvertToDoubleForToNumber(lhs_) ||
      !CanConvertToDoubleForToNumber(rhs_)) {
    return AttachDecision::NoAction;
  }

  ValOperandId lhsId(writer.setInputOperandId(0));
  ValOperandId rhsId(writer.setInputOperandId(1));

  NumberOperandId lhs = EmitGuardToDoubleForToNumber(writer, lhsId, lhs_);
  NumberOperandId rhs = EmitGuardToDoubleForToNumber(writer, rhsId, rhs_);

  switch (op_) {
    case JSOp::Add:
      writer.doubleAddResult(lhs, rhs);
      trackAttached("BinaryArith.DoubleAdd");
      break;
    case JSOp::Sub:
      writer.doubleSubResult(lhs, rhs);
      trackAttached("BinaryArith.DoubleSub");
      break;
    case JSOp::Mul:
      writer.doubleMulResult(lhs, rhs);
      trackAttached("BinaryArith.DoubleMul");
      break;
    case JSOp::Div:
      writer.doubleDivResult(lhs, rhs);
      trackAttached("BinaryArith.DoubleDiv");
      break;
    case JSOp::Mod:
      writer.doubleModResult(lhs, rhs);
      trackAttached("BinaryArith.DoubleMod");
      break;
    case JSOp::Pow:
      writer.doublePowResult(lhs, rhs);
      trackAttached("BinaryArith.DoublePow");
      break;
    default:
      MOZ_CRASH("Unhandled Op");
  }
  writer.returnFromIC();
  return AttachDecision::Attach;
}

AttachDecision BinaryArithIRGenerator::tryAttachInt32() {
  // Check guard conditions.
  if (!CanConvertToInt32ForToNumber(lhs_) ||
      !CanConvertToInt32ForToNumber(rhs_)) {
    return AttachDecision::NoAction;
  }

  // These ICs will failure() if result can't be encoded in an Int32:
  // If sample result is not Int32, we should avoid IC.
  if (!res_.isInt32()) {
    return AttachDecision::NoAction;
  }

  if (op_ != JSOp::Add && op_ != JSOp::Sub && op_ != JSOp::Mul &&
      op_ != JSOp::Div && op_ != JSOp::Mod && op_ != JSOp::Pow) {
    return AttachDecision::NoAction;
  }

  if (op_ == JSOp::Pow && !CanAttachInt32Pow(lhs_, rhs_)) {
    return AttachDecision::NoAction;
  }

  ValOperandId lhsId(writer.setInputOperandId(0));
  ValOperandId rhsId(writer.setInputOperandId(1));

  Int32OperandId lhsIntId = EmitGuardToInt32ForToNumber(writer, lhsId, lhs_);
  Int32OperandId rhsIntId = EmitGuardToInt32ForToNumber(writer, rhsId, rhs_);

  switch (op_) {
    case JSOp::Add:
      writer.int32AddResult(lhsIntId, rhsIntId);
      trackAttached("BinaryArith.Int32Add");
      break;
    case JSOp::Sub:
      writer.int32SubResult(lhsIntId, rhsIntId);
      trackAttached("BinaryArith.Int32Sub");
      break;
    case JSOp::Mul:
      writer.int32MulResult(lhsIntId, rhsIntId);
      trackAttached("BinaryArith.Int32Mul");
      break;
    case JSOp::Div:
      writer.int32DivResult(lhsIntId, rhsIntId);
      trackAttached("BinaryArith.Int32Div");
      break;
    case JSOp::Mod:
      writer.int32ModResult(lhsIntId, rhsIntId);
      trackAttached("BinaryArith.Int32Mod");
      break;
    case JSOp::Pow:
      writer.int32PowResult(lhsIntId, rhsIntId);
      trackAttached("BinaryArith.Int32Pow");
      break;
    default:
      MOZ_CRASH("Unhandled op in tryAttachInt32");
  }

  writer.returnFromIC();
  return AttachDecision::Attach;
}

AttachDecision BinaryArithIRGenerator::tryAttachStringConcat() {
  // Only Addition
  if (op_ != JSOp::Add) {
    return AttachDecision::NoAction;
  }

  // One side must be a string, the other side a primitive value we can easily
  // convert to a string.
  if (!(lhs_.isString() && CanConvertToString(rhs_)) &&
      !(CanConvertToString(lhs_) && rhs_.isString())) {
    return AttachDecision::NoAction;
  }

  ValOperandId lhsId(writer.setInputOperandId(0));
  ValOperandId rhsId(writer.setInputOperandId(1));

  StringOperandId lhsStrId = emitToStringGuard(lhsId, lhs_);
  StringOperandId rhsStrId = emitToStringGuard(rhsId, rhs_);

  writer.callStringConcatResult(lhsStrId, rhsStrId);

  writer.returnFromIC();
  trackAttached("BinaryArith.StringConcat");
  return AttachDecision::Attach;
}

AttachDecision BinaryArithIRGenerator::tryAttachStringObjectConcat() {
  // Only Addition
  if (op_ != JSOp::Add) {
    return AttachDecision::NoAction;
  }

  // Check Guards
  if (!(lhs_.isObject() && rhs_.isString()) &&
      !(lhs_.isString() && rhs_.isObject()))
    return AttachDecision::NoAction;

  ValOperandId lhsId(writer.setInputOperandId(0));
  ValOperandId rhsId(writer.setInputOperandId(1));

  // This guard is actually overly tight, as the runtime
  // helper can handle lhs or rhs being a string, so long
  // as the other is an object.
  if (lhs_.isString()) {
    writer.guardToString(lhsId);
    writer.guardToObject(rhsId);
  } else {
    writer.guardToObject(lhsId);
    writer.guardToString(rhsId);
  }

  writer.callStringObjectConcatResult(lhsId, rhsId);

  writer.returnFromIC();
  trackAttached("BinaryArith.StringObjectConcat");
  return AttachDecision::Attach;
}

AttachDecision BinaryArithIRGenerator::tryAttachBigInt() {
  // Check Guards
  if (!lhs_.isBigInt() || !rhs_.isBigInt()) {
    return AttachDecision::NoAction;
  }

  switch (op_) {
    case JSOp::Add:
    case JSOp::Sub:
    case JSOp::Mul:
    case JSOp::Div:
    case JSOp::Mod:
    case JSOp::Pow:
      // Arithmetic operations.
      break;

    case JSOp::BitOr:
    case JSOp::BitXor:
    case JSOp::BitAnd:
    case JSOp::Lsh:
    case JSOp::Rsh:
      // Bitwise operations.
      break;

    default:
      return AttachDecision::NoAction;
  }

  ValOperandId lhsId(writer.setInputOperandId(0));
  ValOperandId rhsId(writer.setInputOperandId(1));

  BigIntOperandId lhsBigIntId = writer.guardToBigInt(lhsId);
  BigIntOperandId rhsBigIntId = writer.guardToBigInt(rhsId);

  switch (op_) {
    case JSOp::Add:
      writer.bigIntAddResult(lhsBigIntId, rhsBigIntId);
      trackAttached("BinaryArith.BigIntAdd");
      break;
    case JSOp::Sub:
      writer.bigIntSubResult(lhsBigIntId, rhsBigIntId);
      trackAttached("BinaryArith.BigIntSub");
      break;
    case JSOp::Mul:
      writer.bigIntMulResult(lhsBigIntId, rhsBigIntId);
      trackAttached("BinaryArith.BigIntMul");
      break;
    case JSOp::Div:
      writer.bigIntDivResult(lhsBigIntId, rhsBigIntId);
      trackAttached("BinaryArith.BigIntDiv");
      break;
    case JSOp::Mod:
      writer.bigIntModResult(lhsBigIntId, rhsBigIntId);
      trackAttached("BinaryArith.BigIntMod");
      break;
    case JSOp::Pow:
      writer.bigIntPowResult(lhsBigIntId, rhsBigIntId);
      trackAttached("BinaryArith.BigIntPow");
      break;
    case JSOp::BitOr:
      writer.bigIntBitOrResult(lhsBigIntId, rhsBigIntId);
      trackAttached("BinaryArith.BigIntBitOr");
      break;
    case JSOp::BitXor:
      writer.bigIntBitXorResult(lhsBigIntId, rhsBigIntId);
      trackAttached("BinaryArith.BigIntBitXor");
      break;
    case JSOp::BitAnd:
      writer.bigIntBitAndResult(lhsBigIntId, rhsBigIntId);
      trackAttached("BinaryArith.BigIntBitAnd");
      break;
    case JSOp::Lsh:
      writer.bigIntLeftShiftResult(lhsBigIntId, rhsBigIntId);
      trackAttached("BinaryArith.BigIntLeftShift");
      break;
    case JSOp::Rsh:
      writer.bigIntRightShiftResult(lhsBigIntId, rhsBigIntId);
      trackAttached("BinaryArith.BigIntRightShift");
      break;
    default:
      MOZ_CRASH("Unhandled op in tryAttachBigInt");
  }

  writer.returnFromIC();
  return AttachDecision::Attach;
}

AttachDecision BinaryArithIRGenerator::tryAttachStringInt32Arith() {
  // Check for either int32 x string or string x int32.
  if (!(lhs_.isInt32() && rhs_.isString()) &&
      !(lhs_.isString() && rhs_.isInt32())) {
    return AttachDecision::NoAction;
  }

  // The created ICs will fail if the result can't be encoded as as int32.
  // Thus skip this IC, if the sample result is not an int32.
  if (!res_.isInt32()) {
    return AttachDecision::NoAction;
  }

  // Must _not_ support Add, because it would be string concatenation instead.
  // For Pow we can't easily determine the CanAttachInt32Pow conditions so we
  // reject that as well.
  if (op_ != JSOp::Sub && op_ != JSOp::Mul && op_ != JSOp::Div &&
      op_ != JSOp::Mod) {
    return AttachDecision::NoAction;
  }

  ValOperandId lhsId(writer.setInputOperandId(0));
  ValOperandId rhsId(writer.setInputOperandId(1));

  auto guardToInt32 = [&](ValOperandId id, const Value& v) {
    if (v.isInt32()) {
      return writer.guardToInt32(id);
    }

    MOZ_ASSERT(v.isString());
    StringOperandId strId = writer.guardToString(id);
    return writer.guardStringToInt32(strId);
  };

  Int32OperandId lhsIntId = guardToInt32(lhsId, lhs_);
  Int32OperandId rhsIntId = guardToInt32(rhsId, rhs_);

  switch (op_) {
    case JSOp::Sub:
      writer.int32SubResult(lhsIntId, rhsIntId);
      trackAttached("BinaryArith.StringInt32Sub");
      break;
    case JSOp::Mul:
      writer.int32MulResult(lhsIntId, rhsIntId);
      trackAttached("BinaryArith.StringInt32Mul");
      break;
    case JSOp::Div:
      writer.int32DivResult(lhsIntId, rhsIntId);
      trackAttached("BinaryArith.StringInt32Div");
      break;
    case JSOp::Mod:
      writer.int32ModResult(lhsIntId, rhsIntId);
      trackAttached("BinaryArith.StringInt32Mod");
      break;
    default:
      MOZ_CRASH("Unhandled op in tryAttachStringInt32Arith");
  }

  writer.returnFromIC();
  return AttachDecision::Attach;
}

NewArrayIRGenerator::NewArrayIRGenerator(JSContext* cx, HandleScript script,
                                         jsbytecode* pc, ICState state, JSOp op,
                                         HandleObject templateObj,
                                         BaselineFrame* frame)
    : IRGenerator(cx, script, pc, CacheKind::NewArray, state),
#ifdef JS_CACHEIR_SPEW
      op_(op),
#endif
      templateObject_(templateObj),
      frame_(frame) {
  MOZ_ASSERT(templateObject_);
}

void NewArrayIRGenerator::trackAttached(const char* name) {
  stubName_ = name ? name : "NotAttached";
#ifdef JS_CACHEIR_SPEW
  if (const CacheIRSpewer::Guard& sp = CacheIRSpewer::Guard(*this, name)) {
    sp.opcodeProperty("op", op_);
  }
#endif
}

// Allocation sites are usually created during baseline compilation, but we also
// need to created them when an IC stub is added to a baseline compiled script
// and when trial inlining.
static gc::AllocSite* MaybeCreateAllocSite(jsbytecode* pc,
                                           BaselineFrame* frame) {
  MOZ_ASSERT(BytecodeOpCanHaveAllocSite(JSOp(*pc)));

  JSScript* outerScript = frame->outerScript();
  bool inInterpreter = frame->runningInInterpreter();
  bool isInlined = frame->icScript()->isInlined();

  if (inInterpreter && !isInlined) {
    return outerScript->zone()->unknownAllocSite(JS::TraceKind::Object);
  }

  return outerScript->createAllocSite();
}

AttachDecision NewArrayIRGenerator::tryAttachArrayObject() {
  ArrayObject* arrayObj = &templateObject_->as<ArrayObject>();

  MOZ_ASSERT(arrayObj->numUsedFixedSlots() == 0);
  MOZ_ASSERT(arrayObj->numDynamicSlots() == 0);
  MOZ_ASSERT(!arrayObj->isSharedMemory());

  // The macro assembler only supports creating arrays with fixed elements.
  if (arrayObj->hasDynamicElements()) {
    return AttachDecision::NoAction;
  }

  // Stub doesn't support metadata builder
  if (cx_->realm()->hasAllocationMetadataBuilder()) {
    return AttachDecision::NoAction;
  }

  writer.guardNoAllocationMetadataBuilder(
      cx_->realm()->addressOfMetadataBuilder());

  gc::AllocSite* site = MaybeCreateAllocSite(pc_, frame_);
  if (!site) {
    return AttachDecision::NoAction;
  }

  Shape* shape = arrayObj->shape();
  uint32_t length = arrayObj->length();

  writer.newArrayObjectResult(length, shape, site);

  writer.returnFromIC();

  trackAttached("NewArray.Object");
  return AttachDecision::Attach;
}

AttachDecision NewArrayIRGenerator::tryAttachStub() {
  AutoAssertNoPendingException aanpe(cx_);

  TRY_ATTACH(tryAttachArrayObject());

  trackAttached(IRGenerator::NotAttached);
  return AttachDecision::NoAction;
}

NewObjectIRGenerator::NewObjectIRGenerator(JSContext* cx, HandleScript script,
                                           jsbytecode* pc, ICState state,
                                           JSOp op, HandleObject templateObj,
                                           BaselineFrame* frame)
    : IRGenerator(cx, script, pc, CacheKind::NewObject, state),
#ifdef JS_CACHEIR_SPEW
      op_(op),
#endif
      templateObject_(templateObj),
      frame_(frame) {
  MOZ_ASSERT(templateObject_);
}

void NewObjectIRGenerator::trackAttached(const char* name) {
  stubName_ = name ? name : "NotAttached";
#ifdef JS_CACHEIR_SPEW
  if (const CacheIRSpewer::Guard& sp = CacheIRSpewer::Guard(*this, name)) {
    sp.opcodeProperty("op", op_);
  }
#endif
}

AttachDecision NewObjectIRGenerator::tryAttachPlainObject() {
  // Don't optimize allocations with too many dynamic slots. We use an unrolled
  // loop when initializing slots and this avoids generating too much code.
  static const uint32_t MaxDynamicSlotsToOptimize = 64;

  NativeObject* nativeObj = &templateObject_->as<NativeObject>();
  MOZ_ASSERT(nativeObj->is<PlainObject>());

  // Stub doesn't support metadata builder
  if (cx_->realm()->hasAllocationMetadataBuilder()) {
    return AttachDecision::NoAction;
  }

  if (nativeObj->numDynamicSlots() > MaxDynamicSlotsToOptimize) {
    return AttachDecision::NoAction;
  }

  MOZ_ASSERT(!nativeObj->hasDynamicElements());
  MOZ_ASSERT(!nativeObj->isSharedMemory());

  gc::AllocSite* site = MaybeCreateAllocSite(pc_, frame_);
  if (!site) {
    return AttachDecision::NoAction;
  }

  uint32_t numFixedSlots = nativeObj->numUsedFixedSlots();
  uint32_t numDynamicSlots = nativeObj->numDynamicSlots();
  gc::AllocKind allocKind = nativeObj->allocKindForTenure();
  Shape* shape = nativeObj->shape();

  writer.guardNoAllocationMetadataBuilder(
      cx_->realm()->addressOfMetadataBuilder());
  writer.newPlainObjectResult(numFixedSlots, numDynamicSlots, allocKind, shape,
                              site);

  writer.returnFromIC();

  trackAttached("NewObject.PlainObject");
  return AttachDecision::Attach;
}

AttachDecision NewObjectIRGenerator::tryAttachStub() {
  AutoAssertNoPendingException aanpe(cx_);

  TRY_ATTACH(tryAttachPlainObject());

  trackAttached(IRGenerator::NotAttached);
  return AttachDecision::NoAction;
}

CloseIterIRGenerator::CloseIterIRGenerator(JSContext* cx, HandleScript script,
                                           jsbytecode* pc, ICState state,
                                           HandleObject iter,
                                           CompletionKind kind)
    : IRGenerator(cx, script, pc, CacheKind::CloseIter, state),
      iter_(iter),
      kind_(kind) {}

void CloseIterIRGenerator::trackAttached(const char* name) {
#ifdef JS_CACHEIR_SPEW
  if (const CacheIRSpewer::Guard& sp = CacheIRSpewer::Guard(*this, name)) {
    sp.valueProperty("iter", ObjectValue(*iter_));
  }
#endif
}

AttachDecision CloseIterIRGenerator::tryAttachNoReturnMethod() {
  Maybe<PropertyInfo> prop;
  NativeObject* holder = nullptr;

  // If we can guard that the iterator does not have a |return| method,
  // then this CloseIter is a no-op.
  NativeGetPropKind kind = CanAttachNativeGetProp(
      cx_, iter_, NameToId(cx_->names().return_), &holder, &prop, pc_);
  if (kind != NativeGetPropKind::Missing) {
    return AttachDecision::NoAction;
  }
  MOZ_ASSERT(!holder);

  ObjOperandId objId(writer.setInputOperandId(0));

  EmitMissingPropGuard(writer, &iter_->as<NativeObject>(), objId);

  // There is no return method, so we don't have to do anything.
  writer.returnFromIC();

  trackAttached("CloseIter.NoReturn");
  return AttachDecision::Attach;
}

AttachDecision CloseIterIRGenerator::tryAttachScriptedReturn() {
  Maybe<PropertyInfo> prop;
  NativeObject* holder = nullptr;

  NativeGetPropKind kind = CanAttachNativeGetProp(
      cx_, iter_, NameToId(cx_->names().return_), &holder, &prop, pc_);
  if (kind != NativeGetPropKind::Slot) {
    return AttachDecision::NoAction;
  }
  MOZ_ASSERT(holder);
  MOZ_ASSERT(prop->isDataProperty());

  size_t slot = prop->slot();
  Value calleeVal = holder->getSlot(slot);
  if (!calleeVal.isObject() || !calleeVal.toObject().is<JSFunction>()) {
    return AttachDecision::NoAction;
  }

  JSFunction* callee = &calleeVal.toObject().as<JSFunction>();
  if (!callee->hasJitEntry()) {
    return AttachDecision::NoAction;
  }
  if (callee->isClassConstructor()) {
    return AttachDecision::NoAction;
  }

  // We don't support cross-realm |return|.
  if (cx_->realm() != callee->realm()) {
    return AttachDecision::NoAction;
  }

  ObjOperandId objId(writer.setInputOperandId(0));

  ObjOperandId holderId =
      EmitReadSlotGuard(writer, &iter_->as<NativeObject>(), holder, objId);

  ValOperandId calleeValId;
  if (holder->isFixedSlot(slot)) {
    size_t offset = NativeObject::getFixedSlotOffset(slot);
    calleeValId = writer.loadFixedSlot(holderId, offset);
  } else {
    size_t index = holder->dynamicSlotIndex(slot);
    calleeValId = writer.loadDynamicSlot(holderId, index);
  }
  ObjOperandId calleeId = writer.guardToObject(calleeValId);
  emitCalleeGuard(calleeId, callee);

  writer.closeIterScriptedResult(objId, calleeId, kind_, callee->nargs());

  writer.returnFromIC();
  trackAttached("CloseIter.ScriptedReturn");

  return AttachDecision::Attach;
}

AttachDecision CloseIterIRGenerator::tryAttachStub() {
  AutoAssertNoPendingException aanpe(cx_);

  TRY_ATTACH(tryAttachNoReturnMethod());
  TRY_ATTACH(tryAttachScriptedReturn());

  trackAttached(IRGenerator::NotAttached);
  return AttachDecision::NoAction;
}

#ifdef JS_SIMULATOR
bool js::jit::CallAnyNative(JSContext* cx, unsigned argc, Value* vp) {
  CallArgs args = CallArgsFromVp(argc, vp);
  JSObject* calleeObj = &args.callee();

  MOZ_ASSERT(calleeObj->is<JSFunction>());
  auto* calleeFunc = &calleeObj->as<JSFunction>();
  MOZ_ASSERT(calleeFunc->isNativeWithoutJitEntry());

  JSNative native = calleeFunc->native();
  return native(cx, args.length(), args.base());
}
#endif