summaryrefslogtreecommitdiffstats
path: root/js/src/jit/BaselineBailouts.cpp
blob: c82a05d0ea2f1a6fa2c01556f997b6f7a50e28dc (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
/* -*- 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 "mozilla/Assertions.h"
#include "mozilla/ScopeExit.h"

#include "builtin/ModuleObject.h"
#include "debugger/DebugAPI.h"
#include "gc/GC.h"
#include "jit/Bailouts.h"
#include "jit/BaselineFrame.h"
#include "jit/BaselineIC.h"
#include "jit/BaselineJIT.h"
#include "jit/CalleeToken.h"
#include "jit/Invalidation.h"
#include "jit/Ion.h"
#include "jit/IonScript.h"
#include "jit/JitFrames.h"
#include "jit/JitRuntime.h"
#include "jit/JitSpewer.h"
#include "jit/JitZone.h"
#include "jit/RematerializedFrame.h"
#include "jit/SharedICRegisters.h"
#include "jit/Simulator.h"
#include "js/friend/StackLimits.h"  // js::AutoCheckRecursionLimit, js::ReportOverRecursed
#include "js/Utility.h"
#include "util/Memory.h"
#include "vm/ArgumentsObject.h"
#include "vm/BytecodeUtil.h"
#include "vm/JitActivation.h"

#include "jit/JitFrames-inl.h"
#include "vm/JSContext-inl.h"
#include "vm/JSScript-inl.h"

using namespace js;
using namespace js::jit;

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

// BaselineStackBuilder may reallocate its buffer if the current one is too
// small. To avoid dangling pointers, BufferPointer represents a pointer into
// this buffer as a pointer to the header and a fixed offset.
template <typename T>
class BufferPointer {
  const UniquePtr<BaselineBailoutInfo>& header_;
  size_t offset_;
  bool heap_;

 public:
  BufferPointer(const UniquePtr<BaselineBailoutInfo>& header, size_t offset,
                bool heap)
      : header_(header), offset_(offset), heap_(heap) {}

  T* get() const {
    BaselineBailoutInfo* header = header_.get();
    if (!heap_) {
      return (T*)(header->incomingStack + offset_);
    }

    uint8_t* p = header->copyStackTop - offset_;
    MOZ_ASSERT(p >= header->copyStackBottom && p < header->copyStackTop);
    return (T*)p;
  }

  void set(const T& value) { *get() = value; }

  // Note: we return a copy instead of a reference, to avoid potential memory
  // safety hazards when the underlying buffer gets resized.
  const T operator*() const { return *get(); }
  T* operator->() const { return get(); }
};

/**
 * BaselineStackBuilder helps abstract the process of rebuilding the C stack on
 * the heap. It takes a bailout iterator and keeps track of the point on the C
 * stack from which the reconstructed frames will be written.
 *
 * It exposes methods to write data into the heap memory storing the
 * reconstructed stack.  It also exposes method to easily calculate addresses.
 * This includes both the virtual address that a particular value will be at
 * when it's eventually copied onto the stack, as well as the current actual
 * address of that value (whether on the heap allocated portion being
 * constructed or the existing stack).
 *
 * The abstraction handles transparent re-allocation of the heap memory when it
 * needs to be enlarged to accommodate new data.  Similarly to the C stack, the
 * data that's written to the reconstructed stack grows from high to low in
 * memory.
 *
 * The lowest region of the allocated memory contains a BaselineBailoutInfo
 * structure that points to the start and end of the written data.
 */
class MOZ_STACK_CLASS BaselineStackBuilder {
  JSContext* cx_;
  JitFrameLayout* frame_ = nullptr;
  SnapshotIterator& iter_;
  RootedValueVector outermostFrameFormals_;

  size_t bufferTotal_ = 1024;
  size_t bufferAvail_ = 0;
  size_t bufferUsed_ = 0;
  size_t framePushed_ = 0;

  UniquePtr<BaselineBailoutInfo> header_;

  JSScript* script_;
  JSFunction* fun_;
  const ExceptionBailoutInfo* excInfo_;
  ICScript* icScript_;

  jsbytecode* pc_ = nullptr;
  JSOp op_ = JSOp::Nop;
  mozilla::Maybe<ResumeMode> resumeMode_;
  uint32_t exprStackSlots_ = 0;
  void* prevFramePtr_ = nullptr;
  Maybe<BufferPointer<BaselineFrame>> blFrame_;

  size_t frameNo_ = 0;
  JSFunction* nextCallee_ = nullptr;

  BailoutKind bailoutKind_;

  // The baseline frames we will reconstruct on the heap are not
  // rooted, so GC must be suppressed.
  gc::AutoSuppressGC suppress_;

 public:
  BaselineStackBuilder(JSContext* cx, const JSJitFrameIter& frameIter,
                       SnapshotIterator& iter,
                       const ExceptionBailoutInfo* excInfo,
                       BailoutReason reason);

  [[nodiscard]] bool init() {
    MOZ_ASSERT(!header_);
    MOZ_ASSERT(bufferUsed_ == 0);

    uint8_t* bufferRaw = cx_->pod_calloc<uint8_t>(bufferTotal_);
    if (!bufferRaw) {
      return false;
    }
    bufferAvail_ = bufferTotal_ - sizeof(BaselineBailoutInfo);

    header_.reset(new (bufferRaw) BaselineBailoutInfo());
    header_->incomingStack = reinterpret_cast<uint8_t*>(frame_);
    header_->copyStackTop = bufferRaw + bufferTotal_;
    header_->copyStackBottom = header_->copyStackTop;
    return true;
  }

  [[nodiscard]] bool buildOneFrame();
  bool done();
  void nextFrame();

  JSScript* script() const { return script_; }
  size_t frameNo() const { return frameNo_; }
  bool isOutermostFrame() const { return frameNo_ == 0; }
  MutableHandleValueVector outermostFrameFormals() {
    return &outermostFrameFormals_;
  }
  BailoutKind bailoutKind() const { return bailoutKind_; }

  inline JitFrameLayout* startFrame() { return frame_; }

  BaselineBailoutInfo* info() {
    MOZ_ASSERT(header_);
    return header_.get();
  }

  BaselineBailoutInfo* takeBuffer() {
    MOZ_ASSERT(header_);
    return header_.release();
  }

 private:
  [[nodiscard]] bool initFrame();
  [[nodiscard]] bool buildBaselineFrame();
  [[nodiscard]] bool buildArguments();
  [[nodiscard]] bool buildFixedSlots();
  [[nodiscard]] bool fixUpCallerArgs(MutableHandleValueVector savedCallerArgs,
                                     bool* fixedUp);
  [[nodiscard]] bool buildFinallyException();
  [[nodiscard]] bool buildExpressionStack();
  [[nodiscard]] bool finishLastFrame();

  [[nodiscard]] bool prepareForNextFrame(HandleValueVector savedCallerArgs);
  [[nodiscard]] bool finishOuterFrame();
  [[nodiscard]] bool buildStubFrame(uint32_t frameSize,
                                    HandleValueVector savedCallerArgs);
  [[nodiscard]] bool buildRectifierFrame(uint32_t actualArgc,
                                         size_t endOfBaselineStubArgs);

#ifdef DEBUG
  [[nodiscard]] bool validateFrame();
#endif

#ifdef DEBUG
  bool envChainSlotCanBeOptimized();
#endif

  bool isPrologueBailout();
  jsbytecode* getResumePC();
  void* getStubReturnAddress();

  uint32_t exprStackSlots() const { return exprStackSlots_; }

  // Returns true if we're bailing out to a catch or finally block in this frame
  bool catchingException() const {
    return excInfo_ && excInfo_->catchingException() &&
           excInfo_->frameNo() == frameNo_;
  }

  // Returns true if we're bailing out to a finally block in this frame.
  bool resumingInFinallyBlock() const {
    return catchingException() && excInfo_->isFinally();
  }

  bool forcedReturn() const { return excInfo_ && excInfo_->forcedReturn(); }

  // Returns true if we're bailing out in place for debug mode
  bool propagatingIonExceptionForDebugMode() const {
    return excInfo_ && excInfo_->propagatingIonExceptionForDebugMode();
  }

  void* prevFramePtr() const {
    MOZ_ASSERT(prevFramePtr_);
    return prevFramePtr_;
  }
  BufferPointer<BaselineFrame>& blFrame() { return blFrame_.ref(); }

  void setNextCallee(JSFunction* nextCallee,
                     TrialInliningState trialInliningState);
  JSFunction* nextCallee() const { return nextCallee_; }

  jsbytecode* pc() const { return pc_; }
  bool resumeAfter() const {
    return !catchingException() && iter_.resumeAfter();
  }

  ResumeMode resumeMode() const { return *resumeMode_; }

  bool needToSaveCallerArgs() const {
    return resumeMode() == ResumeMode::InlinedAccessor;
  }

  [[nodiscard]] bool enlarge() {
    MOZ_ASSERT(header_ != nullptr);
    if (bufferTotal_ & mozilla::tl::MulOverflowMask<2>::value) {
      ReportOutOfMemory(cx_);
      return false;
    }

    size_t newSize = bufferTotal_ * 2;
    uint8_t* newBufferRaw = cx_->pod_calloc<uint8_t>(newSize);
    if (!newBufferRaw) {
      return false;
    }

    // Initialize the new buffer.
    //
    //   Before:
    //
    //     [ Header | .. | Payload ]
    //
    //   After:
    //
    //     [ Header | ............... | Payload ]
    //
    // Size of Payload is |bufferUsed_|.
    //
    // We need to copy from the old buffer and header to the new buffer before
    // we set header_ (this deletes the old buffer).
    //
    // We also need to update |copyStackBottom| and |copyStackTop| because these
    // fields point to the Payload's start and end, respectively.
    using BailoutInfoPtr = UniquePtr<BaselineBailoutInfo>;
    BailoutInfoPtr newHeader(new (newBufferRaw) BaselineBailoutInfo(*header_));
    newHeader->copyStackTop = newBufferRaw + newSize;
    newHeader->copyStackBottom = newHeader->copyStackTop - bufferUsed_;
    memcpy(newHeader->copyStackBottom, header_->copyStackBottom, bufferUsed_);
    bufferTotal_ = newSize;
    bufferAvail_ = newSize - (sizeof(BaselineBailoutInfo) + bufferUsed_);
    header_ = std::move(newHeader);
    return true;
  }

  void resetFramePushed() { framePushed_ = 0; }

  size_t framePushed() const { return framePushed_; }

  [[nodiscard]] bool subtract(size_t size, const char* info = nullptr) {
    // enlarge the buffer if need be.
    while (size > bufferAvail_) {
      if (!enlarge()) {
        return false;
      }
    }

    // write out element.
    header_->copyStackBottom -= size;
    bufferAvail_ -= size;
    bufferUsed_ += size;
    framePushed_ += size;
    if (info) {
      JitSpew(JitSpew_BaselineBailouts, "      SUB_%03d   %p/%p %-15s",
              (int)size, header_->copyStackBottom,
              virtualPointerAtStackOffset(0), info);
    }
    return true;
  }

  template <typename T>
  [[nodiscard]] bool write(const T& t) {
    MOZ_ASSERT(!(uintptr_t(&t) >= uintptr_t(header_->copyStackBottom) &&
                 uintptr_t(&t) < uintptr_t(header_->copyStackTop)),
               "Should not reference memory that can be freed");
    if (!subtract(sizeof(T))) {
      return false;
    }
    memcpy(header_->copyStackBottom, &t, sizeof(T));
    return true;
  }

  template <typename T>
  [[nodiscard]] bool writePtr(T* t, const char* info) {
    if (!write<T*>(t)) {
      return false;
    }
    if (info) {
      JitSpew(JitSpew_BaselineBailouts, "      WRITE_PTR %p/%p %-15s %p",
              header_->copyStackBottom, virtualPointerAtStackOffset(0), info,
              t);
    }
    return true;
  }

  [[nodiscard]] bool writeWord(size_t w, const char* info) {
    if (!write<size_t>(w)) {
      return false;
    }
    if (info) {
      if (sizeof(size_t) == 4) {
        JitSpew(JitSpew_BaselineBailouts, "      WRITE_WRD %p/%p %-15s %08zx",
                header_->copyStackBottom, virtualPointerAtStackOffset(0), info,
                w);
      } else {
        JitSpew(JitSpew_BaselineBailouts, "      WRITE_WRD %p/%p %-15s %016zx",
                header_->copyStackBottom, virtualPointerAtStackOffset(0), info,
                w);
      }
    }
    return true;
  }

  [[nodiscard]] bool writeValue(const Value& val, const char* info) {
    if (!write<Value>(val)) {
      return false;
    }
    if (info) {
      JitSpew(JitSpew_BaselineBailouts,
              "      WRITE_VAL %p/%p %-15s %016" PRIx64,
              header_->copyStackBottom, virtualPointerAtStackOffset(0), info,
              *((uint64_t*)&val));
    }
    return true;
  }

  [[nodiscard]] bool maybeWritePadding(size_t alignment, size_t after,
                                       const char* info) {
    MOZ_ASSERT(framePushed_ % sizeof(Value) == 0);
    MOZ_ASSERT(after % sizeof(Value) == 0);
    size_t offset = ComputeByteAlignment(after, alignment);
    while (framePushed_ % alignment != offset) {
      if (!writeValue(MagicValue(JS_ARG_POISON), info)) {
        return false;
      }
    }

    return true;
  }

  void setResumeFramePtr(void* resumeFramePtr) {
    header_->resumeFramePtr = resumeFramePtr;
  }

  void setResumeAddr(void* resumeAddr) { header_->resumeAddr = resumeAddr; }

  template <typename T>
  BufferPointer<T> pointerAtStackOffset(size_t offset) {
    if (offset < bufferUsed_) {
      // Calculate offset from copyStackTop.
      offset = header_->copyStackTop - (header_->copyStackBottom + offset);
      return BufferPointer<T>(header_, offset, /* heap = */ true);
    }

    return BufferPointer<T>(header_, offset - bufferUsed_, /* heap = */ false);
  }

  BufferPointer<Value> valuePointerAtStackOffset(size_t offset) {
    return pointerAtStackOffset<Value>(offset);
  }

  inline uint8_t* virtualPointerAtStackOffset(size_t offset) {
    if (offset < bufferUsed_) {
      return reinterpret_cast<uint8_t*>(frame_) - (bufferUsed_ - offset);
    }
    return reinterpret_cast<uint8_t*>(frame_) + (offset - bufferUsed_);
  }
};

BaselineStackBuilder::BaselineStackBuilder(JSContext* cx,
                                           const JSJitFrameIter& frameIter,
                                           SnapshotIterator& iter,
                                           const ExceptionBailoutInfo* excInfo,
                                           BailoutReason reason)
    : cx_(cx),
      frame_(static_cast<JitFrameLayout*>(frameIter.current())),
      iter_(iter),
      outermostFrameFormals_(cx),
      script_(frameIter.script()),
      fun_(frameIter.maybeCallee()),
      excInfo_(excInfo),
      icScript_(script_->jitScript()->icScript()),
      bailoutKind_(iter.bailoutKind()),
      suppress_(cx) {
  MOZ_ASSERT(bufferTotal_ >= sizeof(BaselineBailoutInfo));
  if (reason == BailoutReason::Invalidate) {
    bailoutKind_ = BailoutKind::OnStackInvalidation;
  }
}

bool BaselineStackBuilder::initFrame() {
  // Get the pc and ResumeMode. If we are handling an exception, resume at the
  // pc of the catch or finally block.
  if (catchingException()) {
    pc_ = excInfo_->resumePC();
    resumeMode_ = mozilla::Some(ResumeMode::ResumeAt);
  } else {
    pc_ = script_->offsetToPC(iter_.pcOffset());
    resumeMode_ = mozilla::Some(iter_.resumeMode());
  }
  op_ = JSOp(*pc_);

  // If we are catching an exception, we are bailing out to a catch or
  // finally block and this is the frame where we will resume. Usually the
  // expression stack should be empty in this case but there can be
  // iterators on the stack.
  if (catchingException()) {
    exprStackSlots_ = excInfo_->numExprSlots();
  } else {
    uint32_t totalFrameSlots = iter_.numAllocations();
    uint32_t fixedSlots = script_->nfixed();
    uint32_t argSlots = CountArgSlots(script_, fun_);
    uint32_t intermediates = NumIntermediateValues(resumeMode());
    exprStackSlots_ = totalFrameSlots - fixedSlots - argSlots - intermediates;

    // Verify that there was no underflow.
    MOZ_ASSERT(exprStackSlots_ <= totalFrameSlots);
  }

  JitSpew(JitSpew_BaselineBailouts, "      Unpacking %s:%u:%u",
          script_->filename(), script_->lineno(), script_->column());
  JitSpew(JitSpew_BaselineBailouts, "      [BASELINE-JS FRAME]");

  // Write the previous frame pointer value. For the outermost frame we reuse
  // the value in the JitFrameLayout already on the stack. Record the virtual
  // stack offset at this location. Later on, if we end up writing out a
  // BaselineStub frame for the next callee, we'll need to save the address.
  if (!isOutermostFrame()) {
    if (!writePtr(prevFramePtr(), "PrevFramePtr")) {
      return false;
    }
  }
  prevFramePtr_ = virtualPointerAtStackOffset(0);

  resetFramePushed();

  return true;
}

void BaselineStackBuilder::setNextCallee(
    JSFunction* nextCallee, TrialInliningState trialInliningState) {
  nextCallee_ = nextCallee;

  if (trialInliningState == TrialInliningState::Inlined) {
    // Update icScript_ to point to the icScript of nextCallee
    const uint32_t pcOff = script_->pcToOffset(pc_);
    icScript_ = icScript_->findInlinedChild(pcOff);
  } else {
    // If we don't know for certain that it's TrialInliningState::Inlined,
    // just use the callee's own ICScript. We could still have the trial
    // inlined ICScript available, but we also could not if we transitioned
    // to TrialInliningState::Failure after being monomorphic inlined.
    icScript_ = nextCallee->nonLazyScript()->jitScript()->icScript();
  }
}

bool BaselineStackBuilder::done() {
  if (!iter_.moreFrames()) {
    MOZ_ASSERT(!nextCallee_);
    return true;
  }
  return catchingException();
}

void BaselineStackBuilder::nextFrame() {
  MOZ_ASSERT(nextCallee_);
  fun_ = nextCallee_;
  script_ = fun_->nonLazyScript();
  nextCallee_ = nullptr;

  // Scripts with an IonScript must also have a BaselineScript.
  MOZ_ASSERT(script_->hasBaselineScript());

  frameNo_++;
  iter_.nextInstruction();
}

// Build the BaselineFrame struct
bool BaselineStackBuilder::buildBaselineFrame() {
  if (!subtract(BaselineFrame::Size(), "BaselineFrame")) {
    return false;
  }
  blFrame_.reset();
  blFrame_.emplace(pointerAtStackOffset<BaselineFrame>(0));

  uint32_t flags = BaselineFrame::RUNNING_IN_INTERPRETER;

  // If we are bailing to a script whose execution is observed, mark the
  // baseline frame as a debuggee frame. This is to cover the case where we
  // don't rematerialize the Ion frame via the Debugger.
  if (script_->isDebuggee()) {
    flags |= BaselineFrame::DEBUGGEE;
  }

  // Get |envChain|.
  JSObject* envChain = nullptr;
  Value envChainSlot = iter_.read();
  if (envChainSlot.isObject()) {
    // The env slot has been updated from UndefinedValue. It must be the
    // complete initial environment.
    envChain = &envChainSlot.toObject();

    // Set the HAS_INITIAL_ENV flag if needed. See IsFrameInitialEnvironment.
    MOZ_ASSERT(!script_->isForEval());
    if (fun_ && fun_->needsFunctionEnvironmentObjects()) {
      MOZ_ASSERT(fun_->nonLazyScript()->initialEnvironmentShape());
      flags |= BaselineFrame::HAS_INITIAL_ENV;
    }
  } else {
    MOZ_ASSERT(envChainSlot.isUndefined() ||
               envChainSlot.isMagic(JS_OPTIMIZED_OUT));
    MOZ_ASSERT(envChainSlotCanBeOptimized());

    // The env slot has been optimized out.
    // Get it from the function or script.
    if (fun_) {
      envChain = fun_->environment();
    } else if (script_->isModule()) {
      envChain = script_->module()->environment();
    } else {
      // For global scripts without a non-syntactic env the env
      // chain is the script's global lexical environment. (We do
      // not compile scripts with a non-syntactic global scope).
      // Also note that it's invalid to resume into the prologue in
      // this case because the prologue expects the env chain in R1
      // for eval and global scripts.
      MOZ_ASSERT(!script_->isForEval());
      MOZ_ASSERT(!script_->hasNonSyntacticScope());
      envChain = &(script_->global().lexicalEnvironment());
    }
  }

  // Write |envChain|.
  MOZ_ASSERT(envChain);
  JitSpew(JitSpew_BaselineBailouts, "      EnvChain=%p", envChain);
  blFrame()->setEnvironmentChain(envChain);

  // Get |returnValue| if present.
  Value returnValue = UndefinedValue();
  if (script_->noScriptRval()) {
    // Don't use the return value (likely a JS_OPTIMIZED_OUT MagicValue) to
    // not confuse Baseline.
    iter_.skip();
  } else {
    returnValue = iter_.read();
    flags |= BaselineFrame::HAS_RVAL;
  }

  // Write |returnValue|.
  JitSpew(JitSpew_BaselineBailouts, "      ReturnValue=%016" PRIx64,
          *((uint64_t*)&returnValue));
  blFrame()->setReturnValue(returnValue);

  // Get |argsObj| if present.
  ArgumentsObject* argsObj = nullptr;
  if (script_->needsArgsObj()) {
    Value maybeArgsObj = iter_.read();
    MOZ_ASSERT(maybeArgsObj.isObject() || maybeArgsObj.isUndefined() ||
               maybeArgsObj.isMagic(JS_OPTIMIZED_OUT));
    if (maybeArgsObj.isObject()) {
      argsObj = &maybeArgsObj.toObject().as<ArgumentsObject>();
    }
  }

  // Note: we do not need to initialize the scratchValue field in BaselineFrame.

  // Write |flags|.
  blFrame()->setFlags(flags);

  // Write |icScript|.
  JitSpew(JitSpew_BaselineBailouts, "      ICScript=%p", icScript_);
  blFrame()->setICScript(icScript_);

  // initArgsObjUnchecked modifies the frame's flags, so call it after setFlags.
  if (argsObj) {
    blFrame()->initArgsObjUnchecked(*argsObj);
  }
  return true;
}

// Overwrite the pushed args present in the calling frame with
// the unpacked |thisv| and argument values.
bool BaselineStackBuilder::buildArguments() {
  Value thisv = iter_.read();
  JitSpew(JitSpew_BaselineBailouts, "      Is function!");
  JitSpew(JitSpew_BaselineBailouts, "      thisv=%016" PRIx64,
          *((uint64_t*)&thisv));

  size_t thisvOffset = framePushed() + JitFrameLayout::offsetOfThis();
  valuePointerAtStackOffset(thisvOffset).set(thisv);

  MOZ_ASSERT(iter_.numAllocations() >= CountArgSlots(script_, fun_));
  JitSpew(JitSpew_BaselineBailouts,
          "      frame slots %u, nargs %zu, nfixed %zu", iter_.numAllocations(),
          fun_->nargs(), script_->nfixed());

  bool shouldStoreOutermostFormals =
      isOutermostFrame() && !script_->argsObjAliasesFormals();
  if (shouldStoreOutermostFormals) {
    // This is the first (outermost) frame and we don't have an
    // arguments object aliasing the formals. Due to UCE and phi
    // elimination, we could store an UndefinedValue() here for
    // formals we think are unused, but locals may still reference the
    // original argument slot (MParameter/LArgument) and expect the
    // original Value. To avoid this problem, store the formals in a
    // Vector until we are done.
    MOZ_ASSERT(outermostFrameFormals().empty());
    if (!outermostFrameFormals().resize(fun_->nargs())) {
      return false;
    }
  }

  for (uint32_t i = 0; i < fun_->nargs(); i++) {
    Value arg = iter_.read();
    JitSpew(JitSpew_BaselineBailouts, "      arg %d = %016" PRIx64, (int)i,
            *((uint64_t*)&arg));
    if (!isOutermostFrame()) {
      size_t argOffset = framePushed() + JitFrameLayout::offsetOfActualArg(i);
      valuePointerAtStackOffset(argOffset).set(arg);
    } else if (shouldStoreOutermostFormals) {
      outermostFrameFormals()[i].set(arg);
    } else {
      // When the arguments object aliases the formal arguments, then
      // JSOp::SetArg mutates the argument object. In such cases, the
      // list of arguments reported by the snapshot are only aliases
      // of argument object slots which are optimized to only store
      // differences compared to arguments which are on the stack.
    }
  }
  return true;
}

bool BaselineStackBuilder::buildFixedSlots() {
  for (uint32_t i = 0; i < script_->nfixed(); i++) {
    Value slot = iter_.read();
    if (!writeValue(slot, "FixedValue")) {
      return false;
    }
  }
  return true;
}

// The caller side of inlined js::fun_call and accessors must look
// like the function wasn't inlined.
bool BaselineStackBuilder::fixUpCallerArgs(
    MutableHandleValueVector savedCallerArgs, bool* fixedUp) {
  MOZ_ASSERT(!*fixedUp);

  // Inlining of SpreadCall-like frames not currently supported.
  MOZ_ASSERT(!IsSpreadOp(op_));

  if (resumeMode() != ResumeMode::InlinedFunCall && !needToSaveCallerArgs()) {
    return true;
  }

  // Calculate how many arguments are consumed by the inlined call.
  // All calls pass |callee| and |this|.
  uint32_t inlinedArgs = 2;
  if (resumeMode() == ResumeMode::InlinedFunCall) {
    // The first argument to an inlined FunCall becomes |this|,
    // if it exists. The rest are passed normally.
    MOZ_ASSERT(IsInvokeOp(op_));
    inlinedArgs += GET_ARGC(pc_) > 0 ? GET_ARGC(pc_) - 1 : 0;
  } else {
    MOZ_ASSERT(resumeMode() == ResumeMode::InlinedAccessor);
    MOZ_ASSERT(IsIonInlinableGetterOrSetterOp(op_));
    // Setters are passed one argument. Getters are passed none.
    if (IsSetPropOp(op_)) {
      inlinedArgs++;
    }
  }

  // Calculate how many values are live on the stack across the call,
  // and push them.
  MOZ_ASSERT(inlinedArgs <= exprStackSlots());
  uint32_t liveStackSlots = exprStackSlots() - inlinedArgs;

  JitSpew(JitSpew_BaselineBailouts,
          "      pushing %u expression stack slots before fixup",
          liveStackSlots);
  for (uint32_t i = 0; i < liveStackSlots; i++) {
    Value v = iter_.read();
    if (!writeValue(v, "StackValue")) {
      return false;
    }
  }

  // When we inline js::fun_call, we bypass the native and inline the
  // target directly. When rebuilding the stack, we need to fill in
  // the right number of slots to make it look like the js_native was
  // actually called.
  if (resumeMode() == ResumeMode::InlinedFunCall) {
    // We must transform the stack from |target, this, args| to
    // |js_fun_call, target, this, args|. The value of |js_fun_call|
    // will never be observed, so we push |undefined| for it, followed
    // by the remaining arguments.
    JitSpew(JitSpew_BaselineBailouts,
            "      pushing undefined to fixup funcall");
    if (!writeValue(UndefinedValue(), "StackValue")) {
      return false;
    }
    if (GET_ARGC(pc_) > 0) {
      JitSpew(JitSpew_BaselineBailouts,
              "      pushing %u expression stack slots", inlinedArgs);
      for (uint32_t i = 0; i < inlinedArgs; i++) {
        Value arg = iter_.read();
        if (!writeValue(arg, "StackValue")) {
          return false;
        }
      }
    } else {
      // When we inline FunCall with no arguments, we push an extra
      // |undefined| value for |this|. That value should not appear
      // in the rebuilt baseline frame.
      JitSpew(JitSpew_BaselineBailouts, "      pushing target of funcall");
      Value target = iter_.read();
      if (!writeValue(target, "StackValue")) {
        return false;
      }
      // Skip |this|.
      iter_.skip();
    }
  }

  if (needToSaveCallerArgs()) {
    // Save the actual arguments. They are needed to rebuild the callee frame.
    if (!savedCallerArgs.resize(inlinedArgs)) {
      return false;
    }
    for (uint32_t i = 0; i < inlinedArgs; i++) {
      savedCallerArgs[i].set(iter_.read());
    }

    if (IsSetPropOp(op_)) {
      // The RHS argument to SetProp remains on the stack after the
      // operation and is observable, so we have to fill it in.
      Value initialArg = savedCallerArgs[inlinedArgs - 1];
      JitSpew(JitSpew_BaselineBailouts,
              "     pushing setter's initial argument");
      if (!writeValue(initialArg, "StackValue")) {
        return false;
      }
    }
  }

  *fixedUp = true;
  return true;
}

bool BaselineStackBuilder::buildExpressionStack() {
  JitSpew(JitSpew_BaselineBailouts, "      pushing %u expression stack slots",
          exprStackSlots());
  for (uint32_t i = 0; i < exprStackSlots(); i++) {
    Value v;
    // If we are in the middle of propagating an exception from Ion by
    // bailing to baseline due to debug mode, we might not have all
    // the stack if we are at the newest frame.
    //
    // For instance, if calling |f()| pushed an Ion frame which threw,
    // the snapshot expects the return value to be pushed, but it's
    // possible nothing was pushed before we threw.
    //
    // We therefore use a fallible read here.
    if (!iter_.tryRead(&v)) {
      MOZ_ASSERT(propagatingIonExceptionForDebugMode() && !iter_.moreFrames());
      v = MagicValue(JS_OPTIMIZED_OUT);
    }
    if (!writeValue(v, "StackValue")) {
      return false;
    }
  }

  if (resumeMode() == ResumeMode::ResumeAfterCheckIsObject) {
    JitSpew(JitSpew_BaselineBailouts,
            "      Checking that intermediate value is an object");
    Value returnVal;
    if (iter_.tryRead(&returnVal) && !returnVal.isObject()) {
      MOZ_ASSERT(!returnVal.isMagic());
      JitSpew(JitSpew_BaselineBailouts,
              "      Not an object! Overwriting bailout kind");
      bailoutKind_ = BailoutKind::ThrowCheckIsObject;
    }
  }

  return true;
}

bool BaselineStackBuilder::buildFinallyException() {
  MOZ_ASSERT(resumingInFinallyBlock());

  if (!writeValue(excInfo_->finallyException(), "Exception")) {
    return false;
  }
  if (!writeValue(BooleanValue(true), "throwing")) {
    return false;
  }

  return true;
}

bool BaselineStackBuilder::prepareForNextFrame(
    HandleValueVector savedCallerArgs) {
  const uint32_t frameSize = framePushed();

  // Write out descriptor and return address for the baseline frame.
  // The icEntry in question MUST have an inlinable fallback stub.
  if (!finishOuterFrame()) {
    return false;
  }

  return buildStubFrame(frameSize, savedCallerArgs);
}

bool BaselineStackBuilder::finishOuterFrame() {
  // .               .
  // |  Descr(BLJS)  |
  // +---------------+
  // |  ReturnAddr   |
  // +===============+

  const BaselineInterpreter& baselineInterp =
      cx_->runtime()->jitRuntime()->baselineInterpreter();

  blFrame()->setInterpreterFields(script_, pc_);

  // Write out descriptor of BaselineJS frame.
  size_t baselineFrameDescr = MakeFrameDescriptor(FrameType::BaselineJS);
  if (!writeWord(baselineFrameDescr, "Descriptor")) {
    return false;
  }

  uint8_t* retAddr = baselineInterp.retAddrForIC(op_);
  return writePtr(retAddr, "ReturnAddr");
}

bool BaselineStackBuilder::buildStubFrame(uint32_t frameSize,
                                          HandleValueVector savedCallerArgs) {
  // Build baseline stub frame:
  // +===============+
  // |   FramePtr    |
  // +---------------+
  // |    StubPtr    |
  // +---------------+
  // |   Padding?    |
  // +---------------+
  // |     ArgA      |
  // +---------------+
  // |     ...       |
  // +---------------+
  // |     Arg0      |
  // +---------------+
  // |     ThisV     |
  // +---------------+
  // |  CalleeToken  |
  // +---------------+
  // | Descr(BLStub) |
  // +---------------+
  // |  ReturnAddr   |
  // +===============+

  JitSpew(JitSpew_BaselineBailouts, "      [BASELINE-STUB FRAME]");

  // Write previous frame pointer (saved earlier).
  if (!writePtr(prevFramePtr(), "PrevFramePtr")) {
    return false;
  }
  prevFramePtr_ = virtualPointerAtStackOffset(0);

  // Write stub pointer.
  uint32_t pcOff = script_->pcToOffset(pc_);
  JitScript* jitScript = script_->jitScript();
  const ICEntry& icEntry = jitScript->icEntryFromPCOffset(pcOff);
  ICFallbackStub* fallback = jitScript->fallbackStubForICEntry(&icEntry);
  if (!writePtr(fallback, "StubPtr")) {
    return false;
  }

  // Write out the arguments, copied from the baseline frame. The order
  // of the arguments is reversed relative to the baseline frame's stack
  // values.
  MOZ_ASSERT(IsIonInlinableOp(op_));
  bool pushedNewTarget = IsConstructPC(pc_);
  unsigned actualArgc;
  Value callee;
  if (needToSaveCallerArgs()) {
    // For accessors, the arguments are not on the stack anymore,
    // but they are copied in a vector and are written here.
    callee = savedCallerArgs[0];
    actualArgc = IsSetPropOp(op_) ? 1 : 0;

    // Align the stack based on the number of arguments.
    size_t afterFrameSize =
        (actualArgc + 1) * sizeof(Value) + JitFrameLayout::Size();
    if (!maybeWritePadding(JitStackAlignment, afterFrameSize, "Padding")) {
      return false;
    }

    // Push arguments.
    MOZ_ASSERT(actualArgc + 2 <= exprStackSlots());
    MOZ_ASSERT(savedCallerArgs.length() == actualArgc + 2);
    for (unsigned i = 0; i < actualArgc + 1; i++) {
      size_t arg = savedCallerArgs.length() - (i + 1);
      if (!writeValue(savedCallerArgs[arg], "ArgVal")) {
        return false;
      }
    }
  } else if (resumeMode() == ResumeMode::InlinedFunCall && GET_ARGC(pc_) == 0) {
    // When calling FunCall with 0 arguments, we push |undefined|
    // for this. See BaselineCacheIRCompiler::pushFunCallArguments.
    MOZ_ASSERT(!pushedNewTarget);
    actualArgc = 0;
    // Align the stack based on pushing |this| and 0 arguments.
    size_t afterFrameSize = sizeof(Value) + JitFrameLayout::Size();
    if (!maybeWritePadding(JitStackAlignment, afterFrameSize, "Padding")) {
      return false;
    }
    // Push an undefined value for |this|.
    if (!writeValue(UndefinedValue(), "ThisValue")) {
      return false;
    }
    size_t calleeSlot = blFrame()->numValueSlots(frameSize) - 1;
    callee = *blFrame()->valueSlot(calleeSlot);

  } else {
    MOZ_ASSERT(resumeMode() == ResumeMode::InlinedStandardCall ||
               resumeMode() == ResumeMode::InlinedFunCall);
    actualArgc = GET_ARGC(pc_);
    if (resumeMode() == ResumeMode::InlinedFunCall) {
      // See BaselineCacheIRCompiler::pushFunCallArguments.
      MOZ_ASSERT(actualArgc > 0);
      actualArgc--;
    }

    // In addition to the formal arguments, we must also push |this|.
    // When calling a constructor, we must also push |newTarget|.
    uint32_t numArguments = actualArgc + 1 + pushedNewTarget;

    // Align the stack based on the number of arguments.
    size_t afterFrameSize =
        numArguments * sizeof(Value) + JitFrameLayout::Size();
    if (!maybeWritePadding(JitStackAlignment, afterFrameSize, "Padding")) {
      return false;
    }

    // Copy the arguments and |this| from the BaselineFrame, in reverse order.
    size_t valueSlot = blFrame()->numValueSlots(frameSize) - 1;
    size_t calleeSlot = valueSlot - numArguments;

    for (size_t i = valueSlot; i > calleeSlot; i--) {
      Value v = *blFrame()->valueSlot(i);
      if (!writeValue(v, "ArgVal")) {
        return false;
      }
    }

    callee = *blFrame()->valueSlot(calleeSlot);
  }

  // In case these arguments need to be copied on the stack again for a
  // rectifier frame, save the framePushed values here for later use.
  size_t endOfBaselineStubArgs = framePushed();

  // Push callee token (must be a JS Function)
  JitSpew(JitSpew_BaselineBailouts, "      Callee = %016" PRIx64,
          callee.asRawBits());

  JSFunction* calleeFun = &callee.toObject().as<JSFunction>();
  if (!writePtr(CalleeToToken(calleeFun, pushedNewTarget), "CalleeToken")) {
    return false;
  }
  const ICEntry& icScriptEntry = icScript_->icEntryFromPCOffset(pcOff);
  ICFallbackStub* icScriptFallback =
      icScript_->fallbackStubForICEntry(&icScriptEntry);
  setNextCallee(calleeFun, icScriptFallback->trialInliningState());

  // Push BaselineStub frame descriptor
  size_t baselineStubFrameDescr =
      MakeFrameDescriptorForJitCall(FrameType::BaselineStub, actualArgc);
  if (!writeWord(baselineStubFrameDescr, "Descriptor")) {
    return false;
  }

  // Push return address into ICCall_Scripted stub, immediately after the call.
  void* baselineCallReturnAddr = getStubReturnAddress();
  MOZ_ASSERT(baselineCallReturnAddr);
  if (!writePtr(baselineCallReturnAddr, "ReturnAddr")) {
    return false;
  }

  // The stack must be aligned after the callee pushes the frame pointer.
  MOZ_ASSERT((framePushed() + sizeof(void*)) % JitStackAlignment == 0);

  // Build a rectifier frame if necessary
  if (actualArgc < calleeFun->nargs() &&
      !buildRectifierFrame(actualArgc, endOfBaselineStubArgs)) {
    return false;
  }

  return true;
}

bool BaselineStackBuilder::buildRectifierFrame(uint32_t actualArgc,
                                               size_t endOfBaselineStubArgs) {
  // Push a reconstructed rectifier frame.
  // +===============+
  // |   Padding?    |
  // +---------------+
  // |  UndefinedU   |
  // +---------------+
  // |     ...       |
  // +---------------+
  // |  Undefined0   |
  // +---------------+
  // |     ArgA      |
  // +---------------+
  // |     ...       |
  // +---------------+
  // |     Arg0      |
  // +---------------+
  // |     ThisV     |
  // +---------------+
  // |  CalleeToken  |
  // +---------------+
  // |  Descr(Rect)  |
  // +---------------+
  // |  ReturnAddr   |
  // +===============+

  JitSpew(JitSpew_BaselineBailouts, "      [RECTIFIER FRAME]");
  bool pushedNewTarget = IsConstructPC(pc_);

  if (!writePtr(prevFramePtr(), "PrevFramePtr")) {
    return false;
  }
  prevFramePtr_ = virtualPointerAtStackOffset(0);

  // Align the stack based on the number of arguments.
  size_t afterFrameSize =
      (nextCallee()->nargs() + 1 + pushedNewTarget) * sizeof(Value) +
      RectifierFrameLayout::Size();
  if (!maybeWritePadding(JitStackAlignment, afterFrameSize, "Padding")) {
    return false;
  }

  // Copy new.target, if necessary.
  if (pushedNewTarget) {
    size_t newTargetOffset = (framePushed() - endOfBaselineStubArgs) +
                             (actualArgc + 1) * sizeof(Value);
    Value newTargetValue = *valuePointerAtStackOffset(newTargetOffset);
    if (!writeValue(newTargetValue, "CopiedNewTarget")) {
      return false;
    }
  }

  // Push undefined for missing arguments.
  for (unsigned i = 0; i < (nextCallee()->nargs() - actualArgc); i++) {
    if (!writeValue(UndefinedValue(), "FillerVal")) {
      return false;
    }
  }

  // Copy arguments + thisv from BaselineStub frame.
  if (!subtract((actualArgc + 1) * sizeof(Value), "CopiedArgs")) {
    return false;
  }
  BufferPointer<uint8_t> stubArgsEnd =
      pointerAtStackOffset<uint8_t>(framePushed() - endOfBaselineStubArgs);
  JitSpew(JitSpew_BaselineBailouts, "      MemCpy from %p", stubArgsEnd.get());
  memcpy(pointerAtStackOffset<uint8_t>(0).get(), stubArgsEnd.get(),
         (actualArgc + 1) * sizeof(Value));

  // Push calleeToken again.
  if (!writePtr(CalleeToToken(nextCallee(), pushedNewTarget), "CalleeToken")) {
    return false;
  }

  // Push rectifier frame descriptor
  size_t rectifierFrameDescr =
      MakeFrameDescriptorForJitCall(FrameType::Rectifier, actualArgc);
  if (!writeWord(rectifierFrameDescr, "Descriptor")) {
    return false;
  }

  // Push return address into the ArgumentsRectifier code, immediately after the
  // ioncode call.
  void* rectReturnAddr =
      cx_->runtime()->jitRuntime()->getArgumentsRectifierReturnAddr().value;
  MOZ_ASSERT(rectReturnAddr);
  if (!writePtr(rectReturnAddr, "ReturnAddr")) {
    return false;
  }

  // The stack must be aligned after the callee pushes the frame pointer.
  MOZ_ASSERT((framePushed() + sizeof(void*)) % JitStackAlignment == 0);

  return true;
}

bool BaselineStackBuilder::finishLastFrame() {
  const BaselineInterpreter& baselineInterp =
      cx_->runtime()->jitRuntime()->baselineInterpreter();

  setResumeFramePtr(prevFramePtr());

  // Compute the native address (within the Baseline Interpreter) that we will
  // resume at and initialize the frame's interpreter fields.
  uint8_t* resumeAddr;
  if (isPrologueBailout()) {
    JitSpew(JitSpew_BaselineBailouts, "      Resuming into prologue.");
    MOZ_ASSERT(pc_ == script_->code());
    blFrame()->setInterpreterFieldsForPrologue(script_);
    resumeAddr = baselineInterp.bailoutPrologueEntryAddr();
  } else if (propagatingIonExceptionForDebugMode()) {
    // When propagating an exception for debug mode, set the
    // resume pc to the throwing pc, so that Debugger hooks report
    // the correct pc offset of the throwing op instead of its
    // successor.
    jsbytecode* throwPC = script_->offsetToPC(iter_.pcOffset());
    blFrame()->setInterpreterFields(script_, throwPC);
    resumeAddr = baselineInterp.interpretOpAddr().value;
  } else {
    jsbytecode* resumePC = getResumePC();
    blFrame()->setInterpreterFields(script_, resumePC);
    resumeAddr = baselineInterp.interpretOpAddr().value;
  }
  setResumeAddr(resumeAddr);
  JitSpew(JitSpew_BaselineBailouts, "      Set resumeAddr=%p", resumeAddr);

  if (cx_->runtime()->geckoProfiler().enabled()) {
    // Register bailout with profiler.
    const char* filename = script_->filename();
    if (filename == nullptr) {
      filename = "<unknown>";
    }
    unsigned len = strlen(filename) + 200;
    UniqueChars buf(js_pod_malloc<char>(len));
    if (buf == nullptr) {
      ReportOutOfMemory(cx_);
      return false;
    }
    snprintf(buf.get(), len, "%s %s %s on line %u of %s:%u",
             BailoutKindString(bailoutKind()), resumeAfter() ? "after" : "at",
             CodeName(op_), PCToLineNumber(script_, pc_), filename,
             script_->lineno());
    cx_->runtime()->geckoProfiler().markEvent("Bailout", buf.get());
  }

  return true;
}

#ifdef DEBUG
// The |envChain| slot must not be optimized out if the currently
// active scope requires any EnvironmentObjects beyond what is
// available at body scope. This checks that scope chain does not
// require any such EnvironmentObjects.
// See also: |CompileInfo::isObservableFrameSlot|
bool BaselineStackBuilder::envChainSlotCanBeOptimized() {
  jsbytecode* pc = script_->offsetToPC(iter_.pcOffset());
  Scope* scopeIter = script_->innermostScope(pc);
  while (scopeIter != script_->bodyScope()) {
    if (!scopeIter || scopeIter->hasEnvironment()) {
      return false;
    }
    scopeIter = scopeIter->enclosing();
  }
  return true;
}

bool jit::AssertBailoutStackDepth(JSContext* cx, JSScript* script,
                                  jsbytecode* pc, ResumeMode mode,
                                  uint32_t exprStackSlots) {
  if (IsResumeAfter(mode)) {
    pc = GetNextPc(pc);
  }

  uint32_t expectedDepth;
  bool reachablePC;
  if (!ReconstructStackDepth(cx, script, pc, &expectedDepth, &reachablePC)) {
    return false;
  }
  if (!reachablePC) {
    return true;
  }

  JSOp op = JSOp(*pc);

  if (mode == ResumeMode::InlinedFunCall) {
    // For inlined fun.call(this, ...); the reconstructed stack depth will
    // include the |this|, but the exprStackSlots won't.
    // Exception: if there are no arguments, the depths do match.
    MOZ_ASSERT(IsInvokeOp(op));
    if (GET_ARGC(pc) > 0) {
      MOZ_ASSERT(expectedDepth == exprStackSlots + 1);
    } else {
      MOZ_ASSERT(expectedDepth == exprStackSlots);
    }
    return true;
  }

  if (mode == ResumeMode::InlinedAccessor) {
    // Accessors coming out of ion are inlined via a complete lie perpetrated by
    // the compiler internally. Ion just rearranges the stack, and pretends that
    // it looked like a call all along.
    // This means that the depth is actually one *more* than expected by the
    // interpreter, as there is now a JSFunction, |this| and [arg], rather than
    // the expected |this| and [arg].
    // If the inlined accessor is a GetElem operation, the numbers do match, but
    // that's just because GetElem expects one more item on the stack. Note that
    // none of that was pushed, but it's still reflected in exprStackSlots.
    MOZ_ASSERT(IsIonInlinableGetterOrSetterOp(op));
    if (IsGetElemOp(op)) {
      MOZ_ASSERT(exprStackSlots == expectedDepth);
    } else {
      MOZ_ASSERT(exprStackSlots == expectedDepth + 1);
    }
    return true;
  }

  // In all other cases, the depth must match.
  MOZ_ASSERT(exprStackSlots == expectedDepth);
  return true;
}

bool BaselineStackBuilder::validateFrame() {
  const uint32_t frameSize = framePushed();
  blFrame()->setDebugFrameSize(frameSize);
  JitSpew(JitSpew_BaselineBailouts, "      FrameSize=%u", frameSize);

  // debugNumValueSlots() is based on the frame size, do some sanity checks.
  MOZ_ASSERT(blFrame()->debugNumValueSlots() >= script_->nfixed());
  MOZ_ASSERT(blFrame()->debugNumValueSlots() <= script_->nslots());

  uint32_t expectedSlots = exprStackSlots();
  if (resumingInFinallyBlock()) {
    // If we are resuming in a finally block, we push two extra values on the
    // stack (the exception, and |throwing|), so the depth at the resume PC
    // should be the depth at the fault PC plus two.
    expectedSlots += 2;
  }
  return AssertBailoutStackDepth(cx_, script_, pc_, resumeMode(),
                                 expectedSlots);
}
#endif

void* BaselineStackBuilder::getStubReturnAddress() {
  const BaselineICFallbackCode& code =
      cx_->runtime()->jitRuntime()->baselineICFallbackCode();

  if (IsGetPropOp(op_)) {
    return code.bailoutReturnAddr(BailoutReturnKind::GetProp);
  }
  if (IsSetPropOp(op_)) {
    return code.bailoutReturnAddr(BailoutReturnKind::SetProp);
  }
  if (IsGetElemOp(op_)) {
    return code.bailoutReturnAddr(BailoutReturnKind::GetElem);
  }

  // This should be a call op of some kind, now.
  MOZ_ASSERT(IsInvokeOp(op_) && !IsSpreadOp(op_));
  if (IsConstructOp(op_)) {
    return code.bailoutReturnAddr(BailoutReturnKind::New);
  }
  return code.bailoutReturnAddr(BailoutReturnKind::Call);
}

static inline jsbytecode* GetNextNonLoopHeadPc(jsbytecode* pc) {
  JSOp op = JSOp(*pc);
  switch (op) {
    case JSOp::Goto:
      return pc + GET_JUMP_OFFSET(pc);

    case JSOp::LoopHead:
    case JSOp::Nop:
      return GetNextPc(pc);

    default:
      return pc;
  }
}

// Returns the pc to resume execution at in Baseline after a bailout.
jsbytecode* BaselineStackBuilder::getResumePC() {
  if (resumeAfter()) {
    return GetNextPc(pc_);
  }

  // If we are resuming at a LoopHead op, resume at the next op to avoid
  // a bailout -> enter Ion -> bailout loop with --ion-eager.
  //
  // Cycles can cause the loop below to not terminate. Empty loops are one
  // such example:
  //
  //   L: loophead
  //      goto L
  //
  // We do cycle detection below with the "tortoise and the hare" algorithm.
  jsbytecode* slowerPc = pc_;
  jsbytecode* fasterPc = pc_;
  while (true) {
    // Advance fasterPc twice as fast as slowerPc.
    slowerPc = GetNextNonLoopHeadPc(slowerPc);
    fasterPc = GetNextNonLoopHeadPc(fasterPc);
    fasterPc = GetNextNonLoopHeadPc(fasterPc);

    // Break on cycles or at the end of goto sequences.
    if (fasterPc == slowerPc) {
      break;
    }
  }

  return slowerPc;
}

bool BaselineStackBuilder::isPrologueBailout() {
  // If we are propagating an exception for debug mode, we will not resume
  // into baseline code, but instead into HandleExceptionBaseline (i.e.,
  // never before the prologue).
  return iter_.pcOffset() == 0 && !iter_.resumeAfter() &&
         !propagatingIonExceptionForDebugMode();
}

// Build a baseline stack frame.
bool BaselineStackBuilder::buildOneFrame() {
  // Build a baseline frame:
  // +===============+
  // | PrevFramePtr  | <-- initFrame()
  // +---------------+
  // |   Baseline    | <-- buildBaselineFrame()
  // |    Frame      |
  // +---------------+
  // |    Fixed0     | <-- buildFixedSlots()
  // +---------------+
  // |     ...       |
  // +---------------+
  // |    FixedF     |
  // +---------------+
  // |    Stack0     | <-- buildExpressionStack() -or- fixupCallerArgs()
  // +---------------+
  // |     ...       |
  // +---------------+     If we are building the frame in which we will
  // |    StackS     | <-- resume, we stop here.
  // +---------------+     finishLastFrame() sets up the interpreter fields.
  // .               .
  // .               .
  // .               . <-- If there are additional frames inlined into this
  // |  Descr(BLJS)  |     one, we finish this frame. We generate a stub
  // +---------------+     frame (and maybe also a rectifier frame) between
  // |  ReturnAddr   |     this frame and the inlined frame.
  // +===============+     See: prepareForNextFrame()

  if (!initFrame()) {
    return false;
  }

  if (!buildBaselineFrame()) {
    return false;
  }

  if (fun_ && !buildArguments()) {
    return false;
  }

  if (!buildFixedSlots()) {
    return false;
  }

  bool fixedUp = false;
  RootedValueVector savedCallerArgs(cx_);
  if (iter_.moreFrames() && !fixUpCallerArgs(&savedCallerArgs, &fixedUp)) {
    return false;
  }

  if (!fixedUp) {
    if (!buildExpressionStack()) {
      return false;
    }
    if (resumingInFinallyBlock() && !buildFinallyException()) {
      return false;
    }
  }

#ifdef DEBUG
  if (!validateFrame()) {
    return false;
  }
#endif

#ifdef JS_JITSPEW
  const uint32_t pcOff = script_->pcToOffset(pc());
  JitSpew(JitSpew_BaselineBailouts,
          "      Resuming %s pc offset %d (op %s) (line %u) of %s:%u:%u",
          resumeAfter() ? "after" : "at", (int)pcOff, CodeName(op_),
          PCToLineNumber(script_, pc()), script_->filename(), script_->lineno(),
          script_->column());
  JitSpew(JitSpew_BaselineBailouts, "      Bailout kind: %s",
          BailoutKindString(bailoutKind()));
#endif

  // If this was the last inline frame, or we are bailing out to a catch or
  // finally block in this frame, then unpacking is almost done.
  if (done()) {
    return finishLastFrame();
  }

  // Otherwise, this is an outer frame for an inlined call or
  // accessor. We will be building an inner frame. Before that,
  // we must create a stub frame, and potentially a rectifier frame.
  return prepareForNextFrame(savedCallerArgs);
}

bool jit::BailoutIonToBaseline(JSContext* cx, JitActivation* activation,
                               const JSJitFrameIter& iter,
                               BaselineBailoutInfo** bailoutInfo,
                               const ExceptionBailoutInfo* excInfo,
                               BailoutReason reason) {
  MOZ_ASSERT(bailoutInfo != nullptr);
  MOZ_ASSERT(*bailoutInfo == nullptr);
  MOZ_ASSERT(iter.isBailoutJS());

  // Caller should have saved the exception while we perform the bailout.
  MOZ_ASSERT(!cx->isExceptionPending());

  // Ion bailout can fail due to overrecursion and OOM. In such cases we
  // cannot honor any further Debugger hooks on the frame, and need to
  // ensure that its Debugger.Frame entry is cleaned up.
  auto guardRemoveRematerializedFramesFromDebugger =
      mozilla::MakeScopeExit([&] {
        activation->removeRematerializedFramesFromDebugger(cx, iter.fp());
      });

  // Always remove the RInstructionResults from the JitActivation, even in
  // case of failures as the stack frame is going away after the bailout.
  auto removeIonFrameRecovery = mozilla::MakeScopeExit(
      [&] { activation->removeIonFrameRecovery(iter.jsFrame()); });

  // The caller of the top frame must be one of the following:
  //      IonJS - Ion calling into Ion.
  //      BaselineStub - Baseline calling into Ion.
  //      Entry / WasmToJSJit - Interpreter or other (wasm) calling into Ion.
  //      Rectifier - Arguments rectifier calling into Ion.
  //      BaselineJS - Resume'd Baseline, then likely OSR'd into Ion.
  MOZ_ASSERT(iter.isBailoutJS());
#if defined(DEBUG) || defined(JS_JITSPEW)
  FrameType prevFrameType = iter.prevType();
  MOZ_ASSERT(JSJitFrameIter::isEntry(prevFrameType) ||
             prevFrameType == FrameType::IonJS ||
             prevFrameType == FrameType::BaselineStub ||
             prevFrameType == FrameType::Rectifier ||
             prevFrameType == FrameType::IonICCall ||
             prevFrameType == FrameType::BaselineJS ||
             prevFrameType == FrameType::BaselineInterpreterEntry);
#endif

  // All incoming frames are going to look like this:
  //
  //      +---------------+
  //      |     ...       |
  //      +---------------+
  //      |     Args      |
  //      |     ...       |
  //      +---------------+
  //      |    ThisV      |
  //      +---------------+
  //      |  ActualArgC   |
  //      +---------------+
  //      |  CalleeToken  |
  //      +---------------+
  //      |  Descriptor   |
  //      +---------------+
  //      |  ReturnAddr   |
  //      +---------------+
  //      |    |||||      | <---- Overwrite starting here.
  //      |    |||||      |
  //      |    |||||      |
  //      +---------------+

  JitSpew(JitSpew_BaselineBailouts,
          "Bailing to baseline %s:%u:%u (IonScript=%p) (FrameType=%d)",
          iter.script()->filename(), iter.script()->lineno(),
          iter.script()->column(), (void*)iter.ionScript(), (int)prevFrameType);

  if (excInfo) {
    if (excInfo->catchingException()) {
      JitSpew(JitSpew_BaselineBailouts, "Resuming in catch or finally block");
    }
    if (excInfo->propagatingIonExceptionForDebugMode()) {
      JitSpew(JitSpew_BaselineBailouts, "Resuming in-place for debug mode");
    }
  }

  JitSpew(JitSpew_BaselineBailouts,
          "  Reading from snapshot offset %u size %zu", iter.snapshotOffset(),
          iter.ionScript()->snapshotsListSize());

  iter.script()->updateJitCodeRaw(cx->runtime());

  // Under a bailout, there is no need to invalidate the frame after
  // evaluating the recover instruction, as the invalidation is only needed in
  // cases where the frame is introspected ahead of the bailout.
  MaybeReadFallback recoverBailout(cx, activation, &iter,
                                   MaybeReadFallback::Fallback_DoNothing);

  // Ensure that all value locations are readable from the SnapshotIterator.
  // Get the RInstructionResults from the JitActivation if the frame got
  // recovered ahead of the bailout.
  SnapshotIterator snapIter(iter, activation->bailoutData()->machineState());
  if (!snapIter.initInstructionResults(recoverBailout)) {
    return false;
  }

#ifdef TRACK_SNAPSHOTS
  snapIter.spewBailingFrom();
#endif

  BaselineStackBuilder builder(cx, iter, snapIter, excInfo, reason);
  if (!builder.init()) {
    return false;
  }

  JitSpew(JitSpew_BaselineBailouts, "  Incoming frame ptr = %p",
          builder.startFrame());
  if (iter.maybeCallee()) {
    JitSpew(JitSpew_BaselineBailouts, "  Callee function (%s:%u:%u)",
            iter.script()->filename(), iter.script()->lineno(),
            iter.script()->column());
  } else {
    JitSpew(JitSpew_BaselineBailouts, "  No callee!");
  }

  if (iter.isConstructing()) {
    JitSpew(JitSpew_BaselineBailouts, "  Constructing!");
  } else {
    JitSpew(JitSpew_BaselineBailouts, "  Not constructing!");
  }

  JitSpew(JitSpew_BaselineBailouts, "  Restoring frames:");

  while (true) {
    // Skip recover instructions as they are already recovered by
    // |initInstructionResults|.
    snapIter.settleOnFrame();

    JitSpew(JitSpew_BaselineBailouts, "    FrameNo %zu", builder.frameNo());

    if (!builder.buildOneFrame()) {
      MOZ_ASSERT(cx->isExceptionPending());
      return false;
    }

    if (builder.done()) {
      break;
    }

    builder.nextFrame();
  }
  JitSpew(JitSpew_BaselineBailouts, "  Done restoring frames");

  BailoutKind bailoutKind = builder.bailoutKind();

  if (!builder.outermostFrameFormals().empty()) {
    // Set the first frame's formals, see the comment in InitFromBailout.
    Value* argv = builder.startFrame()->actualArgs();
    mozilla::PodCopy(argv, builder.outermostFrameFormals().begin(),
                     builder.outermostFrameFormals().length());
  }

  // Do stack check.
  bool overRecursed = false;
  BaselineBailoutInfo* info = builder.info();
  size_t numBytesToPush = info->copyStackTop - info->copyStackBottom;
  MOZ_ASSERT((numBytesToPush % sizeof(uintptr_t)) == 0);
  uint8_t* newsp = info->incomingStack - numBytesToPush;
#ifdef JS_SIMULATOR
  if (Simulator::Current()->overRecursed(uintptr_t(newsp))) {
    overRecursed = true;
  }
#else
  AutoCheckRecursionLimit recursion(cx);
  if (!recursion.checkWithStackPointerDontReport(cx, newsp)) {
    overRecursed = true;
  }
#endif
  if (overRecursed) {
    JitSpew(JitSpew_BaselineBailouts, "  Overrecursion check failed!");
    ReportOverRecursed(cx);
    return false;
  }

  // Take the reconstructed baseline stack so it doesn't get freed when builder
  // destructs.
  info = builder.takeBuffer();
  info->numFrames = builder.frameNo() + 1;
  info->bailoutKind.emplace(bailoutKind);
  *bailoutInfo = info;
  guardRemoveRematerializedFramesFromDebugger.release();
  return true;
}

static void InvalidateAfterBailout(JSContext* cx, HandleScript outerScript,
                                   const char* reason) {
  // In some cases, the computation of recover instruction can invalidate the
  // Ion script before we reach the end of the bailout. Thus, if the outer
  // script no longer have any Ion script attached, then we just skip the
  // invalidation.
  //
  // For example, such case can happen if the template object for an unboxed
  // objects no longer match the content of its properties (see Bug 1174547)
  if (!outerScript->hasIonScript()) {
    JitSpew(JitSpew_BaselineBailouts, "Ion script is already invalidated");
    return;
  }

  MOZ_ASSERT(!outerScript->ionScript()->invalidated());

  JitSpew(JitSpew_BaselineBailouts, "Invalidating due to %s", reason);
  Invalidate(cx, outerScript);
}

static void HandleLexicalCheckFailure(JSContext* cx, HandleScript outerScript,
                                      HandleScript innerScript) {
  JitSpew(JitSpew_IonBailouts,
          "Lexical check failure %s:%u:%u, inlined into %s:%u:%u",
          innerScript->filename(), innerScript->lineno(), innerScript->column(),
          outerScript->filename(), outerScript->lineno(),
          outerScript->column());

  if (!innerScript->failedLexicalCheck()) {
    innerScript->setFailedLexicalCheck();
  }

  InvalidateAfterBailout(cx, outerScript, "lexical check failure");
  if (innerScript->hasIonScript()) {
    Invalidate(cx, innerScript);
  }
}

static bool CopyFromRematerializedFrame(JSContext* cx, JitActivation* act,
                                        uint8_t* fp, size_t inlineDepth,
                                        BaselineFrame* frame) {
  RematerializedFrame* rematFrame =
      act->lookupRematerializedFrame(fp, inlineDepth);

  // We might not have rematerialized a frame if the user never requested a
  // Debugger.Frame for it.
  if (!rematFrame) {
    return true;
  }

  MOZ_ASSERT(rematFrame->script() == frame->script());
  MOZ_ASSERT(rematFrame->numActualArgs() == frame->numActualArgs());

  frame->setEnvironmentChain(rematFrame->environmentChain());

  if (frame->isFunctionFrame()) {
    frame->thisArgument() = rematFrame->thisArgument();
  }

  for (unsigned i = 0; i < frame->numActualArgs(); i++) {
    frame->argv()[i] = rematFrame->argv()[i];
  }

  for (size_t i = 0; i < frame->script()->nfixed(); i++) {
    *frame->valueSlot(i) = rematFrame->locals()[i];
  }

  if (frame->script()->noScriptRval()) {
    frame->setReturnValue(UndefinedValue());
  } else {
    frame->setReturnValue(rematFrame->returnValue());
  }

  // Don't copy over the hasCachedSavedFrame bit. The new BaselineFrame we're
  // building has a different AbstractFramePtr, so it won't be found in the
  // LiveSavedFrameCache if we look there.

  JitSpew(JitSpew_BaselineBailouts,
          "  Copied from rematerialized frame at (%p,%zu)", fp, inlineDepth);

  // Propagate the debuggee frame flag. For the case where the Debugger did
  // not rematerialize an Ion frame, the baseline frame has its debuggee
  // flag set iff its script is considered a debuggee. See the debuggee case
  // in InitFromBailout.
  if (rematFrame->isDebuggee()) {
    frame->setIsDebuggee();
    return DebugAPI::handleIonBailout(cx, rematFrame, frame);
  }

  return true;
}

enum class BailoutAction {
  InvalidateImmediately,
  InvalidateIfFrequent,
  DisableIfFrequent,
  NoAction
};

bool jit::FinishBailoutToBaseline(BaselineBailoutInfo* bailoutInfoArg) {
  JitSpew(JitSpew_BaselineBailouts, "  Done restoring frames");

  // Use UniquePtr to free the bailoutInfo before we return.
  UniquePtr<BaselineBailoutInfo> bailoutInfo(bailoutInfoArg);
  bailoutInfoArg = nullptr;

  MOZ_DIAGNOSTIC_ASSERT(*bailoutInfo->bailoutKind != BailoutKind::Unreachable);

  JSContext* cx = TlsContext.get();

  // jit::Bailout(), jit::InvalidationBailout(), and jit::HandleException()
  // should have reset the counter to zero.
  MOZ_ASSERT(!cx->isInUnsafeRegion());

  BaselineFrame* topFrame = GetTopBaselineFrame(cx);

  // We have to get rid of the rematerialized frame, whether it is
  // restored or unwound.
  uint8_t* incomingStack = bailoutInfo->incomingStack;
  auto guardRemoveRematerializedFramesFromDebugger =
      mozilla::MakeScopeExit([&] {
        JitActivation* act = cx->activation()->asJit();
        act->removeRematerializedFramesFromDebugger(cx, incomingStack);
      });

  // Ensure the frame has a call object if it needs one.
  if (!EnsureHasEnvironmentObjects(cx, topFrame)) {
    return false;
  }

  // Create arguments objects for bailed out frames, to maintain the invariant
  // that script->needsArgsObj() implies frame->hasArgsObj().
  RootedScript innerScript(cx, nullptr);
  RootedScript outerScript(cx, nullptr);

  MOZ_ASSERT(cx->currentlyRunningInJit());
  JSJitFrameIter iter(cx->activation()->asJit());
  uint8_t* outerFp = nullptr;

  // Iter currently points at the exit frame.  Get the previous frame
  // (which must be a baseline frame), and set it as the last profiling
  // frame.
  if (cx->runtime()->jitRuntime()->isProfilerInstrumentationEnabled(
          cx->runtime())) {
    MOZ_ASSERT(iter.prevType() == FrameType::BaselineJS);
    JitFrameLayout* fp = reinterpret_cast<JitFrameLayout*>(iter.prevFp());
    cx->jitActivation->setLastProfilingFrame(fp);
  }

  uint32_t numFrames = bailoutInfo->numFrames;
  MOZ_ASSERT(numFrames > 0);

  uint32_t frameno = 0;
  while (frameno < numFrames) {
    MOZ_ASSERT(!iter.isIonJS());

    if (iter.isBaselineJS()) {
      BaselineFrame* frame = iter.baselineFrame();
      MOZ_ASSERT(frame->script()->hasBaselineScript());

      // If the frame doesn't even have a env chain set yet, then it's resuming
      // into the the prologue before the env chain is initialized.  Any
      // necessary args object will also be initialized there.
      if (frame->environmentChain() && frame->script()->needsArgsObj()) {
        ArgumentsObject* argsObj;
        if (frame->hasArgsObj()) {
          argsObj = &frame->argsObj();
        } else {
          argsObj = ArgumentsObject::createExpected(cx, frame);
          if (!argsObj) {
            return false;
          }
        }

        // The arguments is a local binding and needsArgsObj does not
        // check if it is clobbered. Ensure that the local binding
        // restored during bailout before storing the arguments object
        // to the slot.
        RootedScript script(cx, frame->script());
        SetFrameArgumentsObject(cx, frame, script, argsObj);
      }

      if (frameno == 0) {
        innerScript = frame->script();
      }

      if (frameno == numFrames - 1) {
        outerScript = frame->script();
        outerFp = iter.fp();
        MOZ_ASSERT(outerFp == incomingStack);
      }

      frameno++;
    }

    ++iter;
  }

  MOZ_ASSERT(innerScript);
  MOZ_ASSERT(outerScript);
  MOZ_ASSERT(outerFp);

  // If we rematerialized Ion frames due to debug mode toggling, copy their
  // values into the baseline frame. We need to do this even when debug mode
  // is off, as we should respect the mutations made while debug mode was
  // on.
  JitActivation* act = cx->activation()->asJit();
  if (act->hasRematerializedFrame(outerFp)) {
    JSJitFrameIter iter(act);
    size_t inlineDepth = numFrames;
    bool ok = true;
    while (inlineDepth > 0) {
      if (iter.isBaselineJS()) {
        // We must attempt to copy all rematerialized frames over,
        // even if earlier ones failed, to invoke the proper frame
        // cleanup in the Debugger.
        if (!CopyFromRematerializedFrame(cx, act, outerFp, --inlineDepth,
                                         iter.baselineFrame())) {
          ok = false;
        }
      }
      ++iter;
    }

    if (!ok) {
      return false;
    }

    // After copying from all the rematerialized frames, remove them from
    // the table to keep the table up to date.
    guardRemoveRematerializedFramesFromDebugger.release();
    act->removeRematerializedFrame(outerFp);
  }

  // If we are unwinding for an exception, we need to unwind scopes.
  // See |SettleOnTryNote|
  if (bailoutInfo->faultPC) {
    EnvironmentIter ei(cx, topFrame, bailoutInfo->faultPC);
    UnwindEnvironment(cx, ei, bailoutInfo->tryPC);
  }

  // Check for interrupts now because we might miss an interrupt check in JIT
  // code when resuming in the prologue, after the stack/interrupt check.
  if (!cx->isExceptionPending()) {
    if (!CheckForInterrupt(cx)) {
      return false;
    }
  }

  BailoutKind bailoutKind = *bailoutInfo->bailoutKind;
  JitSpew(JitSpew_BaselineBailouts,
          "  Restored outerScript=(%s:%u:%u,%u) innerScript=(%s:%u:%u,%u) "
          "(bailoutKind=%u)",
          outerScript->filename(), outerScript->lineno(), outerScript->column(),
          outerScript->getWarmUpCount(), innerScript->filename(),
          innerScript->lineno(), innerScript->column(),
          innerScript->getWarmUpCount(), (unsigned)bailoutKind);

  BailoutAction action = BailoutAction::InvalidateImmediately;
  DebugOnly<bool> saveFailedICHash = false;
  switch (bailoutKind) {
    case BailoutKind::TranspiledCacheIR:
      // A transpiled guard failed. If this happens often enough, we will
      // invalidate and recompile.
      action = BailoutAction::InvalidateIfFrequent;
      saveFailedICHash = true;
      break;

    case BailoutKind::MonomorphicInlinedStubFolding:
      action = BailoutAction::InvalidateIfFrequent;
      saveFailedICHash = true;
      if (innerScript != outerScript) {
        // In the case where this instruction comes from a monomorphic-inlined
        // ICScript, we need to ensure that we note the connection between the
        // inner script and the outer script, so that we can properly track if
        // we add a new case to the folded stub and avoid invalidating the
        // outer script.
        cx->zone()->jitZone()->noteStubFoldingBailout(innerScript, outerScript);
      }
      break;

    case BailoutKind::SpeculativePhi:
      // A value of an unexpected type flowed into a phi.
      MOZ_ASSERT(!outerScript->hadSpeculativePhiBailout());
      outerScript->setHadSpeculativePhiBailout();
      InvalidateAfterBailout(cx, outerScript, "phi specialization failure");
      break;

    case BailoutKind::TypePolicy:
      // A conversion inserted by a type policy failed.
      // We will invalidate and disable recompilation if this happens too often.
      action = BailoutAction::DisableIfFrequent;
      break;

    case BailoutKind::LICM:
      // LICM may cause spurious bailouts by hoisting unreachable
      // guards past branches.  To prevent bailout loops, when an
      // instruction hoisted by LICM bails out, we update the
      // IonScript and resume in baseline. If the guard would have
      // been executed anyway, then we will hit the baseline fallback,
      // and call noteBaselineFallback. If that does not happen,
      // then the next time we reach this point, we will disable LICM
      // for this script.
      MOZ_ASSERT(!outerScript->hadLICMInvalidation());
      if (outerScript->hasIonScript()) {
        switch (outerScript->ionScript()->licmState()) {
          case IonScript::LICMState::NeverBailed:
            outerScript->ionScript()->setHadLICMBailout();
            action = BailoutAction::NoAction;
            break;
          case IonScript::LICMState::Bailed:
            outerScript->setHadLICMInvalidation();
            InvalidateAfterBailout(cx, outerScript, "LICM failure");
            break;
          case IonScript::LICMState::BailedAndHitFallback:
            // This bailout is not due to LICM. Treat it like a
            // regular TranspiledCacheIR bailout.
            action = BailoutAction::InvalidateIfFrequent;
            break;
        }
      }
      break;

    case BailoutKind::InstructionReordering:
      // An instruction moved up by instruction reordering bailed out.
      outerScript->setHadReorderingBailout();
      action = BailoutAction::InvalidateIfFrequent;
      break;

    case BailoutKind::HoistBoundsCheck:
      // An instruction hoisted or generated by tryHoistBoundsCheck bailed out.
      MOZ_ASSERT(!outerScript->failedBoundsCheck());
      outerScript->setFailedBoundsCheck();
      InvalidateAfterBailout(cx, outerScript, "bounds check failure");
      break;

    case BailoutKind::EagerTruncation:
      // An eager truncation generated by range analysis bailed out.
      // To avoid bailout loops, we set a flag to avoid generating
      // eager truncations next time we recompile.
      MOZ_ASSERT(!outerScript->hadEagerTruncationBailout());
      outerScript->setHadEagerTruncationBailout();
      InvalidateAfterBailout(cx, outerScript, "eager range analysis failure");
      break;

    case BailoutKind::UnboxFolding:
      // An unbox that was hoisted to fold with a load bailed out.
      // To avoid bailout loops, we set a flag to avoid folding
      // loads with unboxes next time we recompile.
      MOZ_ASSERT(!outerScript->hadUnboxFoldingBailout());
      outerScript->setHadUnboxFoldingBailout();
      InvalidateAfterBailout(cx, outerScript, "unbox folding failure");
      break;

    case BailoutKind::TooManyArguments:
      // A funapply or spread call had more than JIT_ARGS_LENGTH_MAX arguments.
      // We will invalidate and disable recompilation if this happens too often.
      action = BailoutAction::DisableIfFrequent;
      break;

    case BailoutKind::DuringVMCall:
      if (cx->isExceptionPending()) {
        // We are bailing out to catch an exception. We will invalidate
        // and disable recompilation if this happens too often.
        action = BailoutAction::DisableIfFrequent;
      }
      break;

    case BailoutKind::Finally:
      // We are bailing out for a finally block. We will invalidate
      // and disable recompilation if this happens too often.
      action = BailoutAction::DisableIfFrequent;
      break;

    case BailoutKind::Inevitable:
    case BailoutKind::Debugger:
      // Do nothing.
      action = BailoutAction::NoAction;
      break;

    case BailoutKind::FirstExecution:
      // We reached an instruction that had not been executed yet at
      // the time we compiled. If this happens often enough, we will
      // invalidate and recompile.
      action = BailoutAction::InvalidateIfFrequent;
      saveFailedICHash = true;
      break;

    case BailoutKind::UninitializedLexical:
      HandleLexicalCheckFailure(cx, outerScript, innerScript);
      break;

    case BailoutKind::ThrowCheckIsObject:
      MOZ_ASSERT(!cx->isExceptionPending());
      return ThrowCheckIsObject(cx, CheckIsObjectKind::IteratorReturn);

    case BailoutKind::IonExceptionDebugMode:
      // Return false to resume in HandleException with reconstructed
      // baseline frame.
      return false;

    case BailoutKind::OnStackInvalidation:
      // The script has already been invalidated. There is nothing left to do.
      action = BailoutAction::NoAction;
      break;

    default:
      MOZ_CRASH("Unknown bailout kind!");
  }

#ifdef DEBUG
  if (MOZ_UNLIKELY(cx->runtime()->jitRuntime()->ionBailAfterEnabled())) {
    action = BailoutAction::NoAction;
  }
#endif

  if (outerScript->hasIonScript()) {
    IonScript* ionScript = outerScript->ionScript();
    switch (action) {
      case BailoutAction::InvalidateImmediately:
        // The IonScript should already have been invalidated.
        MOZ_ASSERT(false);
        break;
      case BailoutAction::InvalidateIfFrequent:
        ionScript->incNumFixableBailouts();
        if (ionScript->shouldInvalidate()) {
#ifdef DEBUG
          if (saveFailedICHash && !JitOptions.disableBailoutLoopCheck) {
            outerScript->jitScript()->setFailedICHash(ionScript->icHash());
          }
#endif
          InvalidateAfterBailout(cx, outerScript, "fixable bailouts");
        }
        break;
      case BailoutAction::DisableIfFrequent:
        ionScript->incNumUnfixableBailouts();
        if (ionScript->shouldInvalidateAndDisable()) {
          InvalidateAfterBailout(cx, outerScript, "unfixable bailouts");
          outerScript->disableIon();
        }
        break;
      case BailoutAction::NoAction:
        break;
    }
  }

  return true;
}