Debian Codegraph @

js/src/frontend/BytecodeEmitter.cpp

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sts=2 et sw=2 tw=80:
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 /*
8 * JS bytecode generation.
9 */
10
11 #include "frontend/BytecodeEmitter.h"
12
13 #include "mozilla/Casting.h" // mozilla::AssertedCast
14 #include "mozilla/DebugOnly.h" // mozilla::DebugOnly
15 #include "mozilla/FloatingPoint.h" // mozilla::NumberEqualsInt32, mozilla::NumberIsInt32
16 #include "mozilla/HashTable.h" // mozilla::HashSet
17 #include "mozilla/Maybe.h" // mozilla::{Maybe,Nothing,Some}
18 #include "mozilla/Saturate.h"
19 #include "mozilla/Variant.h" // mozilla::AsVariant
20
21 #include <algorithm>
22 #include <iterator>
23 #include <string.h>
24
25 #include "jstypes.h" // JS_BIT
26
27 #include "frontend/AbstractScopePtr.h" // ScopeIndex
28 #include "frontend/BytecodeControlStructures.h" // NestableControl, BreakableControl, LabelControl, LoopControl, TryFinallyControl
29 #include "frontend/CallOrNewEmitter.h" // CallOrNewEmitter
30 #include "frontend/CForEmitter.h" // CForEmitter
31 #include "frontend/DecoratorEmitter.h" // DecoratorEmitter
32 #include "frontend/DefaultEmitter.h" // DefaultEmitter
33 #include "frontend/DoWhileEmitter.h" // DoWhileEmitter
34 #include "frontend/ElemOpEmitter.h" // ElemOpEmitter
35 #include "frontend/EmitterScope.h" // EmitterScope
36 #include "frontend/ExpressionStatementEmitter.h" // ExpressionStatementEmitter
37 #include "frontend/ForInEmitter.h" // ForInEmitter
38 #include "frontend/ForOfEmitter.h" // ForOfEmitter
39 #include "frontend/FunctionEmitter.h" // FunctionEmitter, FunctionScriptEmitter, FunctionParamsEmitter
40 #include "frontend/IfEmitter.h" // IfEmitter, InternalIfEmitter, CondEmitter
41 #include "frontend/LabelEmitter.h" // LabelEmitter
42 #include "frontend/LexicalScopeEmitter.h" // LexicalScopeEmitter
43 #include "frontend/ModuleSharedContext.h" // ModuleSharedContext
44 #include "frontend/NameAnalysisTypes.h" // PrivateNameKind
45 #include "frontend/NameFunctions.h" // NameFunctions
46 #include "frontend/NameOpEmitter.h" // NameOpEmitter
47 #include "frontend/ObjectEmitter.h" // PropertyEmitter, ObjectEmitter, ClassEmitter
48 #include "frontend/OptionalEmitter.h" // OptionalEmitter
49 #include "frontend/ParseContext.h" // ParseContext::Scope
50 #include "frontend/ParseNode.h" // ParseNodeKind, ParseNode and subclasses
51 #include "frontend/Parser.h" // Parser
52 #include "frontend/ParserAtom.h" // ParserAtomsTable, ParserAtom
53 #include "frontend/PrivateOpEmitter.h" // PrivateOpEmitter
54 #include "frontend/PropOpEmitter.h" // PropOpEmitter
55 #include "frontend/SourceNotes.h" // SrcNote, SrcNoteType, SrcNoteWriter
56 #include "frontend/SwitchEmitter.h" // SwitchEmitter
57 #include "frontend/TaggedParserAtomIndexHasher.h" // TaggedParserAtomIndexHasher
58 #include "frontend/TDZCheckCache.h" // TDZCheckCache
59 #include "frontend/TryEmitter.h" // TryEmitter
60 #include "frontend/UsingEmitter.h" // UsingEmitter
61 #include "frontend/WhileEmitter.h" // WhileEmitter
62 #include "js/ColumnNumber.h" // JS::LimitedColumnNumberOneOrigin, JS::ColumnNumberOffset
63 #include "js/friend/ErrorMessages.h" // JSMSG_*
64 #include "js/friend/StackLimits.h" // AutoCheckRecursionLimit
65 #include "util/StringBuilder.h" // StringBuilder
66 #include "vm/BytecodeUtil.h" // JOF_*, IsArgOp, IsLocalOp, SET_UINT24, SET_ICINDEX, BytecodeFallsThrough, BytecodeIsJumpTarget
67 #include "vm/CompletionKind.h" // CompletionKind
68 #include "vm/ConstantCompareOperand.h" // ConstantCompareOperand
69 #include "vm/FunctionPrefixKind.h" // FunctionPrefixKind
70 #include "vm/GeneratorObject.h" // AbstractGeneratorObject
71 #include "vm/Opcodes.h" // JSOp, JSOpLength_*
72 #include "vm/PropMap.h" // SharedPropMap::MaxPropsForNonDictionary
73 #include "vm/Scope.h" // GetScopeDataTrailingNames
74 #include "vm/SharedStencil.h" // ScopeNote
75 #include "vm/ThrowMsgKind.h" // ThrowMsgKind
76 #include "vm/TypeofEqOperand.h" // TypeofEqOperand
77
78 using namespace js;
79 using namespace js::frontend;
80
81 using mozilla::AssertedCast;
82 using mozilla::AsVariant;
83 using mozilla::DebugOnly;
84 using mozilla::Maybe;
85 using mozilla::Nothing;
86 using mozilla::NumberEqualsInt32;
87 using mozilla::NumberIsInt32;
88 using mozilla::Some;
89
90 static bool ParseNodeRequiresSpecialLineNumberNotes(ParseNode* pn) {
91 // The few node types listed below are exceptions to the usual
92 // location-source-note-emitting code in BytecodeEmitter::emitTree().
93 // Single-line `while` loops and C-style `for` loops require careful
94 // handling to avoid strange stepping behavior.
95 // Functions usually shouldn't have location information (bug 1431202).
96
97 ParseNodeKind kind = pn->getKind();
98 return kind == ParseNodeKind::WhileStmt || kind == ParseNodeKind::ForStmt ||
99 kind == ParseNodeKind::Function;
100 }
101
102 static bool NeedsFieldInitializer(ParseNode* member, bool inStaticContext) {
103 // For the purposes of bytecode emission, StaticClassBlocks are treated as if
104 // they were static initializers.
105 return (member->is<StaticClassBlock>() && inStaticContext) ||
106 (member->is<ClassField>() &&
107 member->as<ClassField>().isStatic() == inStaticContext);
108 }
109
110 static bool NeedsAccessorInitializer(ParseNode* member, bool isStatic) {
111 if (isStatic) {
112 return false;
113 }
114 return member->is<ClassMethod>() &&
115 member->as<ClassMethod>().name().isKind(ParseNodeKind::PrivateName) &&
116 !member->as<ClassMethod>().isStatic() &&
117 member->as<ClassMethod>().accessorType() != AccessorType::None;
118 }
119
120 static bool ShouldSuppressBreakpointsAndSourceNotes(
121 SharedContext* sc, BytecodeEmitter::EmitterMode emitterMode) {
122 // Suppress for all self-hosting code.
123 if (emitterMode == BytecodeEmitter::EmitterMode::SelfHosting) {
124 return true;
125 }
126
127 // Suppress for synthesized class constructors.
128 if (sc->isFunctionBox()) {
129 FunctionBox* funbox = sc->asFunctionBox();
130 return funbox->isSyntheticFunction() && funbox->isClassConstructor();
131 }
132
133 return false;
134 }
135
136 BytecodeEmitter::BytecodeEmitter(BytecodeEmitter* parent, FrontendContext* fc,
137 SharedContext* sc,
138 const ErrorReporter& errorReporter,
139 CompilationState& compilationState,
140 EmitterMode emitterMode)
141 : sc(sc),
142 fc(fc),
143 parent(parent),
144 bytecodeSection_(fc, sc->extent().lineno,
145 JS::LimitedColumnNumberOneOrigin(sc->extent().column)),
146 perScriptData_(fc, compilationState),
147 errorReporter_(errorReporter),
148 compilationState(compilationState),
149 suppressBreakpointsAndSourceNotes(
150 ShouldSuppressBreakpointsAndSourceNotes(sc, emitterMode)),
151 emitterMode(emitterMode) {
152 MOZ_ASSERT_IF(parent, fc == parent->fc);
153 }
154
155 BytecodeEmitter::BytecodeEmitter(BytecodeEmitter* parent, SharedContext* sc)
156 : BytecodeEmitter(parent, parent->fc, sc, parent->errorReporter_,
157 parent->compilationState, parent->emitterMode) {}
158
159 BytecodeEmitter::BytecodeEmitter(FrontendContext* fc,
160 const EitherParser& parser, SharedContext* sc,
161 CompilationState& compilationState,
162 EmitterMode emitterMode)
163 : BytecodeEmitter(nullptr, fc, sc, parser.errorReporter(), compilationState,
164 emitterMode) {
165 ep_.emplace(parser);
166 }
167
168 void BytecodeEmitter::initFromBodyPosition(TokenPos bodyPosition) {
169 setScriptStartOffsetIfUnset(bodyPosition.begin);
170 setFunctionBodyEndPos(bodyPosition.end);
171 }
172
173 bool BytecodeEmitter::init() {
174 if (!parent) {
175 if (!compilationState.prepareSharedDataStorage(fc)) {
176 return false;
177 }
178 }
179 return perScriptData_.init(fc);
180 }
181
182 bool BytecodeEmitter::init(TokenPos bodyPosition) {
183 initFromBodyPosition(bodyPosition);
184 return init();
185 }
186
187 template <typename T>
188 T* BytecodeEmitter::findInnermostNestableControl() const {
189 return NestableControl::findNearest<T>(innermostNestableControl);
190 }
191
192 template <typename T, typename Predicate /* (T*) -> bool */>
193 T* BytecodeEmitter::findInnermostNestableControl(Predicate predicate) const {
194 return NestableControl::findNearest<T>(innermostNestableControl, predicate);
195 }
196
197 NameLocation BytecodeEmitter::lookupName(TaggedParserAtomIndex name) {
198 return innermostEmitterScope()->lookup(this, name);
199 }
200
201 void BytecodeEmitter::lookupPrivate(TaggedParserAtomIndex name,
202 NameLocation& loc,
203 Maybe<NameLocation>& brandLoc) {
204 innermostEmitterScope()->lookupPrivate(this, name, loc, brandLoc);
205 }
206
207 Maybe<NameLocation> BytecodeEmitter::locationOfNameBoundInScope(
208 TaggedParserAtomIndex name, EmitterScope* target) {
209 return innermostEmitterScope()->locationBoundInScope(name, target);
210 }
211
212 template <typename T>
213 Maybe<NameLocation> BytecodeEmitter::locationOfNameBoundInScopeType(
214 TaggedParserAtomIndex name, EmitterScope* source) {
215 EmitterScope* aScope = source;
216 while (!aScope->scope(this).is<T>()) {
217 aScope = aScope->enclosingInFrame();
218 }
219 return source->locationBoundInScope(name, aScope);
220 }
221
222 bool BytecodeEmitter::markStepBreakpoint() {
223 if (skipBreakpointSrcNotes()) {
224 return true;
225 }
226
227 if (!newSrcNote(SrcNoteType::BreakpointStepSep)) {
228 return false;
229 }
230
231 // We track the location of the most recent separator for use in
232 // markSimpleBreakpoint. Note that this means that the position must already
233 // be set before markStepBreakpoint is called.
234 bytecodeSection().updateSeparatorPosition();
235
236 return true;
237 }
238
239 bool BytecodeEmitter::markSimpleBreakpoint() {
240 if (skipBreakpointSrcNotes()) {
241 return true;
242 }
243
244 // If a breakable call ends up being the same location as the most recent
245 // expression start, we need to skip marking it breakable in order to avoid
246 // having two breakpoints with the same line/column position.
247 // Note: This assumes that the position for the call has already been set.
248 if (!bytecodeSection().isDuplicateLocation()) {
249 if (!newSrcNote(SrcNoteType::Breakpoint)) {
250 return false;
251 }
252 }
253
254 return true;
255 }
256
257 bool BytecodeEmitter::emitCheck(JSOp op, ptrdiff_t delta,
258 BytecodeOffset* offset) {
259 size_t oldLength = bytecodeSection().code().length();
260 *offset = BytecodeOffset(oldLength);
261
262 size_t newLength = oldLength + size_t(delta);
263 if (MOZ_UNLIKELY(newLength > MaxBytecodeLength)) {
264 ReportAllocationOverflow(fc);
265 return false;
266 }
267
268 if (!bytecodeSection().code().growByUninitialized(delta)) {
269 return false;
270 }
271
272 if (BytecodeOpHasIC(op)) {
273 // Even if every bytecode op is a JOF_IC op and the function has ARGC_LIMIT
274 // arguments, numICEntries cannot overflow.
275 static_assert(MaxBytecodeLength + 1 /* this */ + ARGC_LIMIT <= UINT32_MAX,
276 "numICEntries must not overflow");
277 bytecodeSection().incrementNumICEntries();
278 }
279
280 return true;
281 }
282
283 #ifdef DEBUG
284 bool BytecodeEmitter::checkStrictOrSloppy(JSOp op) const {
285 if (IsCheckStrictOp(op) && !sc->strict()) {
286 return false;
287 }
288 if (IsCheckSloppyOp(op) && sc->strict()) {
289 return false;
290 }
291 return true;
292 }
293 #endif
294
295 bool BytecodeEmitter::emit1(JSOp op) {
296 MOZ_ASSERT(checkStrictOrSloppy(op));
297 MOZ_ASSERT(GetOpLength(op) == 1);
298
299 BytecodeOffset offset;
300 if (!emitCheck(op, 1, &offset)) {
301 return false;
302 }
303
304 jsbytecode* code = bytecodeSection().code(offset);
305 code[0] = jsbytecode(op);
306 bytecodeSection().updateDepth(op, offset);
307 return true;
308 }
309
310 bool BytecodeEmitter::emit2(JSOp op, uint8_t op1) {
311 MOZ_ASSERT(checkStrictOrSloppy(op));
312 MOZ_ASSERT(GetOpLength(op) == 2);
313
314 BytecodeOffset offset;
315 if (!emitCheck(op, 2, &offset)) {
316 return false;
317 }
318
319 jsbytecode* code = bytecodeSection().code(offset);
320 code[0] = jsbytecode(op);
321 code[1] = jsbytecode(op1);
322 bytecodeSection().updateDepth(op, offset);
323 return true;
324 }
325
326 bool BytecodeEmitter::emit3(JSOp op, jsbytecode op1, jsbytecode op2) {
327 MOZ_ASSERT(checkStrictOrSloppy(op));
328 MOZ_ASSERT(GetOpLength(op) == 3);
329
330 /* These should filter through emitVarOp. */
331 MOZ_ASSERT(!IsArgOp(op));
332 MOZ_ASSERT(!IsLocalOp(op));
333
334 BytecodeOffset offset;
335 if (!emitCheck(op, 3, &offset)) {
336 return false;
337 }
338
339 jsbytecode* code = bytecodeSection().code(offset);
340 code[0] = jsbytecode(op);
341 code[1] = op1;
342 code[2] = op2;
343 bytecodeSection().updateDepth(op, offset);
344 return true;
345 }
346
347 bool BytecodeEmitter::emitN(JSOp op, size_t extra, BytecodeOffset* offset) {
348 MOZ_ASSERT(checkStrictOrSloppy(op));
349 ptrdiff_t length = 1 + ptrdiff_t(extra);
350
351 BytecodeOffset off;
352 if (!emitCheck(op, length, &off)) {
353 return false;
354 }
355
356 jsbytecode* code = bytecodeSection().code(off);
357 code[0] = jsbytecode(op);
358 /* The remaining |extra| bytes are set by the caller */
359
360 /*
361 * Don't updateDepth if op's use-count comes from the immediate
362 * operand yet to be stored in the extra bytes after op.
363 */
364 if (CodeSpec(op).nuses >= 0) {
365 bytecodeSection().updateDepth(op, off);
366 }
367
368 if (offset) {
369 *offset = off;
370 }
371 return true;
372 }
373
374 bool BytecodeEmitter::emitJumpTargetOp(JSOp op, BytecodeOffset* off) {
375 MOZ_ASSERT(BytecodeIsJumpTarget(op));
376
377 // Record the current IC-entry index at start of this op.
378 uint32_t numEntries = bytecodeSection().numICEntries();
379
380 size_t n = GetOpLength(op) - 1;
381 MOZ_ASSERT(GetOpLength(op) >= 1 + ICINDEX_LEN);
382
383 if (!emitN(op, n, off)) {
384 return false;
385 }
386
387 SET_ICINDEX(bytecodeSection().code(*off), numEntries);
388 return true;
389 }
390
391 bool BytecodeEmitter::emitJumpTarget(JumpTarget* target) {
392 BytecodeOffset off = bytecodeSection().offset();
393
394 // Alias consecutive jump targets.
395 if (bytecodeSection().lastTargetOffset().valid() &&
396 off == bytecodeSection().lastTargetOffset() +
397 BytecodeOffsetDiff(JSOpLength_JumpTarget)) {
398 target->offset = bytecodeSection().lastTargetOffset();
399 return true;
400 }
401
402 target->offset = off;
403 bytecodeSection().setLastTargetOffset(off);
404
405 BytecodeOffset opOff;
406 return emitJumpTargetOp(JSOp::JumpTarget, &opOff);
407 }
408
409 bool BytecodeEmitter::emitJumpNoFallthrough(JSOp op, JumpList* jump) {
410 BytecodeOffset offset;
411 if (!emitCheck(op, 5, &offset)) {
412 return false;
413 }
414
415 jsbytecode* code = bytecodeSection().code(offset);
416 code[0] = jsbytecode(op);
417 MOZ_ASSERT(!jump->offset.valid() ||
418 (0 <= jump->offset.value() && jump->offset < offset));
419 jump->push(bytecodeSection().code(BytecodeOffset(0)), offset);
420 bytecodeSection().updateDepth(op, offset);
421 return true;
422 }
423
424 bool BytecodeEmitter::emitJump(JSOp op, JumpList* jump) {
425 if (!emitJumpNoFallthrough(op, jump)) {
426 return false;
427 }
428 if (BytecodeFallsThrough(op)) {
429 JumpTarget fallthrough;
430 if (!emitJumpTarget(&fallthrough)) {
431 return false;
432 }
433 }
434 return true;
435 }
436
437 void BytecodeEmitter::patchJumpsToTarget(JumpList jump, JumpTarget target) {
438 MOZ_ASSERT(
439 !jump.offset.valid() ||
440 (0 <= jump.offset.value() && jump.offset <= bytecodeSection().offset()));
441 MOZ_ASSERT(0 <= target.offset.value() &&
442 target.offset <= bytecodeSection().offset());
443 MOZ_ASSERT_IF(
444 jump.offset.valid() &&
445 target.offset + BytecodeOffsetDiff(4) <= bytecodeSection().offset(),
446 BytecodeIsJumpTarget(JSOp(*bytecodeSection().code(target.offset))));
447 jump.patchAll(bytecodeSection().code(BytecodeOffset(0)), target);
448 }
449
450 bool BytecodeEmitter::emitJumpTargetAndPatch(JumpList jump) {
451 if (!jump.offset.valid()) {
452 return true;
453 }
454 JumpTarget target;
455 if (!emitJumpTarget(&target)) {
456 return false;
457 }
458 patchJumpsToTarget(jump, target);
459 return true;
460 }
461
462 bool BytecodeEmitter::emitCall(JSOp op, uint16_t argc,
463 const Maybe<uint32_t>& sourceCoordOffset) {
464 if (sourceCoordOffset.isSome()) {
465 if (!updateSourceCoordNotes(*sourceCoordOffset)) {
466 return false;
467 }
468 }
469 return emit3(op, ARGC_LO(argc), ARGC_HI(argc));
470 }
471
472 bool BytecodeEmitter::emitCall(JSOp op, uint16_t argc, ParseNode* pn) {
473 return emitCall(op, argc, pn ? Some(pn->pn_pos.begin) : Nothing());
474 }
475
476 bool BytecodeEmitter::emitDupAt(unsigned slotFromTop, unsigned count) {
477 MOZ_ASSERT(slotFromTop < unsigned(bytecodeSection().stackDepth()));
478 MOZ_ASSERT(slotFromTop + 1 >= count);
479
480 if (slotFromTop == 0 && count == 1) {
481 return emit1(JSOp::Dup);
482 }
483
484 if (slotFromTop == 1 && count == 2) {
485 return emit1(JSOp::Dup2);
486 }
487
488 if (slotFromTop >= Bit(24)) {
489 reportError(nullptr, JSMSG_TOO_MANY_LOCALS);
490 return false;
491 }
492
493 for (unsigned i = 0; i < count; i++) {
494 BytecodeOffset off;
495 if (!emitN(JSOp::DupAt, 3, &off)) {
496 return false;
497 }
498
499 jsbytecode* pc = bytecodeSection().code(off);
500 SET_UINT24(pc, slotFromTop);
501 }
502
503 return true;
504 }
505
506 bool BytecodeEmitter::emitPopN(unsigned n) {
507 MOZ_ASSERT(n != 0);
508
509 if (n == 1) {
510 return emit1(JSOp::Pop);
511 }
512
513 // 2 JSOp::Pop instructions (2 bytes) are shorter than JSOp::PopN (3 bytes).
514 if (n == 2) {
515 return emit1(JSOp::Pop) && emit1(JSOp::Pop);
516 }
517
518 return emitUint16Operand(JSOp::PopN, n);
519 }
520
521 bool BytecodeEmitter::emitPickN(uint8_t n) {
522 MOZ_ASSERT(n != 0);
523
524 if (n == 1) {
525 return emit1(JSOp::Swap);
526 }
527
528 return emit2(JSOp::Pick, n);
529 }
530
531 bool BytecodeEmitter::emitUnpickN(uint8_t n) {
532 MOZ_ASSERT(n != 0);
533
534 if (n == 1) {
535 return emit1(JSOp::Swap);
536 }
537
538 return emit2(JSOp::Unpick, n);
539 }
540
541 bool BytecodeEmitter::emitCheckIsObj(CheckIsObjectKind kind) {
542 return emit2(JSOp::CheckIsObj, uint8_t(kind));
543 }
544
545 bool BytecodeEmitter::emitBuiltinObject(BuiltinObjectKind kind) {
546 return emit2(JSOp::BuiltinObject, uint8_t(kind));
547 }
548
549 /* Updates line number notes, not column notes. */
550 bool BytecodeEmitter::updateLineNumberNotes(uint32_t offset) {
551 if (skipLocationSrcNotes()) {
552 return true;
553 }
554
555 const ErrorReporter& er = errorReporter();
556 std::optional<bool> onThisLineStatus =
557 er.isOnThisLine(offset, bytecodeSection().currentLine());
558 if (!onThisLineStatus.has_value()) {
559 er.errorNoOffset(JSMSG_OUT_OF_MEMORY);
560 return false;
561 }
562
563 bool onThisLine = *onThisLineStatus;
564
565 if (!onThisLine) {
566 unsigned line = er.lineAt(offset);
567 unsigned delta = line - bytecodeSection().currentLine();
568
569 // If we use a `SetLine` note below, we want it to be relative to the
570 // scripts initial line number for better chance of sharing.
571 unsigned initialLine = sc->extent().lineno;
572 MOZ_ASSERT(line >= initialLine);
573
574 /*
575 * Encode any change in the current source line number by using
576 * either several SrcNoteType::NewLine notes or just one
577 * SrcNoteType::SetLine note, whichever consumes less space.
578 *
579 * NB: We handle backward line number deltas (possible with for
580 * loops where the update part is emitted after the body, but its
581 * line number is <= any line number in the body) here by letting
582 * unsigned delta_ wrap to a very large number, which triggers a
583 * SrcNoteType::SetLine.
584 */
585 bytecodeSection().setCurrentLine(line, offset);
586 if (delta >= SrcNote::SetLine::lengthFor(line, initialLine)) {
587 if (!newSrcNote2(SrcNoteType::SetLine,
588 SrcNote::SetLine::toOperand(line, initialLine))) {
589 return false;
590 }
591 } else {
592 do {
593 if (!newSrcNote(SrcNoteType::NewLine)) {
594 return false;
595 }
596 } while (--delta != 0);
597 }
598
599 bytecodeSection().updateSeparatorPositionIfPresent();
600 }
601 return true;
602 }
603
604 /* Updates the line number and column number information in the source notes. */
605 bool BytecodeEmitter::updateSourceCoordNotes(uint32_t offset) {
606 if (skipLocationSrcNotes()) {
607 return true;
608 }
609
610 if (!updateLineNumberNotes(offset)) {
611 return false;
612 }
613
614 JS::LimitedColumnNumberOneOrigin columnIndex =
615 errorReporter().columnAt(offset);
616
617 // Assert colspan is always representable.
618 static_assert((0 - ptrdiff_t(JS::LimitedColumnNumberOneOrigin::Limit)) >=
619 SrcNote::ColSpan::MinColSpan);
620 static_assert((ptrdiff_t(JS::LimitedColumnNumberOneOrigin::Limit) - 0) <=
621 SrcNote::ColSpan::MaxColSpan);
622
623 JS::ColumnNumberOffset colspan = columnIndex - bytecodeSection().lastColumn();
624
625 if (colspan != JS::ColumnNumberOffset::zero()) {
626 if (lastLineOnlySrcNoteIndex != LastSrcNoteIsNotLineOnly) {
627 MOZ_ASSERT(bytecodeSection().lastColumn() ==
628 JS::LimitedColumnNumberOneOrigin());
629
630 const SrcNotesVector& notes = bytecodeSection().notes();
631 SrcNoteType type = notes[lastLineOnlySrcNoteIndex].type();
632 if (type == SrcNoteType::NewLine) {
633 if (!convertLastNewLineToNewLineColumn(columnIndex)) {
634 return false;
635 }
636 } else {
637 MOZ_ASSERT(type == SrcNoteType::SetLine);
638 if (!convertLastSetLineToSetLineColumn(columnIndex)) {
639 return false;
640 }
641 }
642 } else {
643 if (!newSrcNote2(SrcNoteType::ColSpan,
644 SrcNote::ColSpan::toOperand(colspan))) {
645 return false;
646 }
647 }
648 bytecodeSection().setLastColumn(columnIndex, offset);
649 bytecodeSection().updateSeparatorPositionIfPresent();
650 }
651 return true;
652 }
653
654 bool BytecodeEmitter::updateSourceCoordNotesIfNonLiteral(ParseNode* node) {
655 if (node->isLiteral()) {
656 return true;
657 }
658 return updateSourceCoordNotes(node->pn_pos.begin);
659 }
660
661 uint32_t BytecodeEmitter::getOffsetForLoop(ParseNode* nextpn) const {
662 // Try to give the JSOp::LoopHead the same line number as the next
663 // instruction. nextpn is often a block, in which case the next instruction
664 // typically comes from the first statement inside.
665 if (nextpn->is<LexicalScopeNode>()) {
666 nextpn = nextpn->as<LexicalScopeNode>().scopeBody();
667 }
668 if (nextpn->isKind(ParseNodeKind::StatementList)) {
669 if (ParseNode* firstStatement = nextpn->as<ListNode>().head()) {
670 nextpn = firstStatement;
671 }
672 }
673
674 return nextpn->pn_pos.begin;
675 }
676
677 bool BytecodeEmitter::emitUint16Operand(JSOp op, uint32_t operand) {
678 MOZ_ASSERT(operand <= UINT16_MAX);
679 if (!emit3(op, UINT16_LO(operand), UINT16_HI(operand))) {
680 return false;
681 }
682 return true;
683 }
684
685 bool BytecodeEmitter::emitUint32Operand(JSOp op, uint32_t operand) {
686 BytecodeOffset off;
687 if (!emitN(op, 4, &off)) {
688 return false;
689 }
690 SET_UINT32(bytecodeSection().code(off), operand);
691 return true;
692 }
693
694 bool BytecodeEmitter::emitGoto(NestableControl* target, GotoKind kind) {
695 NonLocalExitControl nle(this, kind == GotoKind::Continue
696 ? NonLocalExitKind::Continue
697 : NonLocalExitKind::Break);
698 return nle.emitNonLocalJump(target);
699 }
700
701 AbstractScopePtr BytecodeEmitter::innermostScope() const {
702 return innermostEmitterScope()->scope(this);
703 }
704
705 ScopeIndex BytecodeEmitter::innermostScopeIndex() const {
706 return *innermostEmitterScope()->scopeIndex(this);
707 }
708
709 bool BytecodeEmitter::emitGCIndexOp(JSOp op, GCThingIndex index) {
710 MOZ_ASSERT(checkStrictOrSloppy(op));
711
712 constexpr size_t OpLength = 1 + GCTHING_INDEX_LEN;
713 MOZ_ASSERT(GetOpLength(op) == OpLength);
714
715 BytecodeOffset offset;
716 if (!emitCheck(op, OpLength, &offset)) {
717 return false;
718 }
719
720 jsbytecode* code = bytecodeSection().code(offset);
721 code[0] = jsbytecode(op);
722 SET_GCTHING_INDEX(code, index);
723 bytecodeSection().updateDepth(op, offset);
724 return true;
725 }
726
727 bool BytecodeEmitter::emitAtomOp(JSOp op, TaggedParserAtomIndex atom) {
728 MOZ_ASSERT(atom);
729
730 // .generator lookups should be emitted as JSOp::GetAliasedVar instead of
731 // JSOp::GetName etc, to bypass |with| objects on the scope chain.
732 // It's safe to emit .this lookups though because |with| objects skip
733 // those.
734 MOZ_ASSERT_IF(op == JSOp::GetName || op == JSOp::GetGName,
735 atom != TaggedParserAtomIndex::WellKnown::dot_generator_());
736
737 GCThingIndex index;
738 if (!makeAtomIndex(atom, ParserAtom::Atomize::Yes, &index)) {
739 return false;
740 }
741
742 return emitAtomOp(op, index);
743 }
744
745 bool BytecodeEmitter::emitAtomOp(JSOp op, GCThingIndex atomIndex) {
746 MOZ_ASSERT(JOF_OPTYPE(op) == JOF_ATOM);
747 #ifdef DEBUG
748 auto atom = perScriptData().gcThingList().getAtom(atomIndex);
749 MOZ_ASSERT(compilationState.parserAtoms.isInstantiatedAsJSAtom(atom));
750 #endif
751 return emitGCIndexOp(op, atomIndex);
752 }
753
754 bool BytecodeEmitter::emitStringOp(JSOp op, TaggedParserAtomIndex atom) {
755 MOZ_ASSERT(atom);
756 GCThingIndex index;
757 if (!makeAtomIndex(atom, ParserAtom::Atomize::No, &index)) {
758 return false;
759 }
760
761 return emitStringOp(op, index);
762 }
763
764 bool BytecodeEmitter::emitStringOp(JSOp op, GCThingIndex atomIndex) {
765 MOZ_ASSERT(JOF_OPTYPE(op) == JOF_STRING);
766 return emitGCIndexOp(op, atomIndex);
767 }
768
769 bool BytecodeEmitter::emitInternedScopeOp(GCThingIndex index, JSOp op) {
770 MOZ_ASSERT(JOF_OPTYPE(op) == JOF_SCOPE);
771 MOZ_ASSERT(index < perScriptData().gcThingList().length());
772 return emitGCIndexOp(op, index);
773 }
774
775 bool BytecodeEmitter::emitInternedObjectOp(GCThingIndex index, JSOp op) {
776 MOZ_ASSERT(JOF_OPTYPE(op) == JOF_OBJECT);
777 MOZ_ASSERT(index < perScriptData().gcThingList().length());
778 return emitGCIndexOp(op, index);
779 }
780
781 bool BytecodeEmitter::emitRegExp(GCThingIndex index) {
782 return emitGCIndexOp(JSOp::RegExp, index);
783 }
784
785 bool BytecodeEmitter::emitLocalOp(JSOp op, uint32_t slot) {
786 MOZ_ASSERT(JOF_OPTYPE(op) != JOF_ENVCOORD);
787 MOZ_ASSERT(IsLocalOp(op));
788
789 BytecodeOffset off;
790 if (!emitN(op, LOCALNO_LEN, &off)) {
791 return false;
792 }
793
794 SET_LOCALNO(bytecodeSection().code(off), slot);
795 return true;
796 }
797
798 bool BytecodeEmitter::emitArgOp(JSOp op, uint16_t slot) {
799 MOZ_ASSERT(IsArgOp(op));
800 BytecodeOffset off;
801 if (!emitN(op, ARGNO_LEN, &off)) {
802 return false;
803 }
804
805 SET_ARGNO(bytecodeSection().code(off), slot);
806 return true;
807 }
808
809 bool BytecodeEmitter::emitEnvCoordOp(JSOp op, EnvironmentCoordinate ec) {
810 MOZ_ASSERT(JOF_OPTYPE(op) == JOF_ENVCOORD ||
811 JOF_OPTYPE(op) == JOF_DEBUGCOORD);
812
813 constexpr size_t N = ENVCOORD_HOPS_LEN + ENVCOORD_SLOT_LEN;
814 MOZ_ASSERT(GetOpLength(op) == 1 + N);
815
816 BytecodeOffset off;
817 if (!emitN(op, N, &off)) {
818 return false;
819 }
820
821 jsbytecode* pc = bytecodeSection().code(off);
822 SET_ENVCOORD_HOPS(pc, ec.hops());
823 pc += ENVCOORD_HOPS_LEN;
824 SET_ENVCOORD_SLOT(pc, ec.slot());
825 pc += ENVCOORD_SLOT_LEN;
826 return true;
827 }
828
829 bool BytecodeEmitter::checkSideEffects(ParseNode* pn, bool* answer) const {
830 AutoCheckRecursionLimit recursion(fc);
831 if (!recursion.check(fc)) {
832 return false;
833 }
834
835 restart:
836
837 switch (pn->getKind()) {
838 // Trivial cases with no side effects.
839 case ParseNodeKind::EmptyStmt:
840 case ParseNodeKind::TrueExpr:
841 case ParseNodeKind::FalseExpr:
842 case ParseNodeKind::NullExpr:
843 case ParseNodeKind::RawUndefinedExpr:
844 case ParseNodeKind::Elision:
845 case ParseNodeKind::Generator:
846 MOZ_ASSERT(pn->is<NullaryNode>());
847 *answer = false;
848 return true;
849
850 case ParseNodeKind::ObjectPropertyName:
851 case ParseNodeKind::PrivateName: // no side effects, unlike
852 // ParseNodeKind::Name
853 case ParseNodeKind::StringExpr:
854 case ParseNodeKind::TemplateStringExpr:
855 MOZ_ASSERT(pn->is<NameNode>());
856 *answer = false;
857 return true;
858
859 case ParseNodeKind::RegExpExpr:
860 MOZ_ASSERT(pn->is<RegExpLiteral>());
861 *answer = false;
862 return true;
863
864 case ParseNodeKind::NumberExpr:
865 MOZ_ASSERT(pn->is<NumericLiteral>());
866 *answer = false;
867 return true;
868
869 case ParseNodeKind::BigIntExpr:
870 MOZ_ASSERT(pn->is<BigIntLiteral>());
871 *answer = false;
872 return true;
873
874 // |this| can throw in derived class constructors, including nested arrow
875 // functions or eval.
876 case ParseNodeKind::ThisExpr:
877 MOZ_ASSERT(pn->is<UnaryNode>());
878 *answer = sc->needsThisTDZChecks();
879 return true;
880
881 // |new.target| doesn't have any side-effects.
882 case ParseNodeKind::NewTargetExpr: {
883 MOZ_ASSERT(pn->is<NewTargetNode>());
884 *answer = false;
885 return true;
886 }
887
888 // Trivial binary nodes with more token pos holders.
889 case ParseNodeKind::ImportMetaExpr: {
890 MOZ_ASSERT(pn->as<BinaryNode>().left()->isKind(ParseNodeKind::PosHolder));
891 MOZ_ASSERT(
892 pn->as<BinaryNode>().right()->isKind(ParseNodeKind::PosHolder));
893 *answer = false;
894 return true;
895 }
896
897 case ParseNodeKind::BreakStmt:
898 MOZ_ASSERT(pn->is<BreakStatement>());
899 *answer = true;
900 return true;
901
902 case ParseNodeKind::ContinueStmt:
903 MOZ_ASSERT(pn->is<ContinueStatement>());
904 *answer = true;
905 return true;
906
907 case ParseNodeKind::DebuggerStmt:
908 MOZ_ASSERT(pn->is<DebuggerStatement>());
909 *answer = true;
910 return true;
911
912 // Watch out for getters!
913 case ParseNodeKind::OptionalDotExpr:
914 case ParseNodeKind::DotExpr:
915 case ParseNodeKind::ArgumentsLength:
916 MOZ_ASSERT(pn->is<BinaryNode>());
917 *answer = true;
918 return true;
919
920 // Unary cases with side effects only if the child has them.
921 case ParseNodeKind::TypeOfExpr:
922 case ParseNodeKind::VoidExpr:
923 case ParseNodeKind::NotExpr:
924 return checkSideEffects(pn->as<UnaryNode>().kid(), answer);
925
926 // Even if the name expression is effect-free, performing ToPropertyKey on
927 // it might not be effect-free:
928 //
929 // RegExp.prototype.toString = () => { throw 42; };
930 // ({ [/regex/]: 0 }); // ToPropertyKey(/regex/) throws 42
931 //
932 // function Q() {
933 // ({ [new.target]: 0 });
934 // }
935 // Q.toString = () => { throw 17; };
936 // new Q; // new.target will be Q, ToPropertyKey(Q) throws 17
937 case ParseNodeKind::ComputedName:
938 MOZ_ASSERT(pn->is<UnaryNode>());
939 *answer = true;
940 return true;
941
942 // Looking up or evaluating the associated name could throw.
943 case ParseNodeKind::TypeOfNameExpr:
944 MOZ_ASSERT(pn->is<UnaryNode>());
945 *answer = true;
946 return true;
947
948 // This unary case has side effects on the enclosing object, sure. But
949 // that's not the question this function answers: it's whether the
950 // operation may have a side effect on something *other* than the result
951 // of the overall operation in which it's embedded. The answer to that
952 // is no, because an object literal having a mutated prototype only
953 // produces a value, without affecting anything else.
954 case ParseNodeKind::MutateProto:
955 return checkSideEffects(pn->as<UnaryNode>().kid(), answer);
956
957 // Unary cases with obvious side effects.
958 case ParseNodeKind::PreIncrementExpr:
959 case ParseNodeKind::PostIncrementExpr:
960 case ParseNodeKind::PreDecrementExpr:
961 case ParseNodeKind::PostDecrementExpr:
962 case ParseNodeKind::ThrowStmt:
963 MOZ_ASSERT(pn->is<UnaryNode>());
964 *answer = true;
965 return true;
966
967 // These might invoke valueOf/toString, even with a subexpression without
968 // side effects! Consider |+{ valueOf: null, toString: null }|.
969 case ParseNodeKind::BitNotExpr:
970 case ParseNodeKind::PosExpr:
971 case ParseNodeKind::NegExpr:
972 MOZ_ASSERT(pn->is<UnaryNode>());
973 *answer = true;
974 return true;
975
976 // This invokes the (user-controllable) iterator protocol.
977 case ParseNodeKind::Spread:
978 MOZ_ASSERT(pn->is<UnaryNode>());
979 *answer = true;
980 return true;
981
982 case ParseNodeKind::InitialYield:
983 case ParseNodeKind::YieldStarExpr:
984 case ParseNodeKind::YieldExpr:
985 case ParseNodeKind::AwaitExpr:
986 MOZ_ASSERT(pn->is<UnaryNode>());
987 *answer = true;
988 return true;
989
990 // Deletion generally has side effects, even if isolated cases have none.
991 case ParseNodeKind::DeleteNameExpr:
992 case ParseNodeKind::DeletePropExpr:
993 case ParseNodeKind::DeleteElemExpr:
994 case ParseNodeKind::DeleteOptionalChainExpr:
995 MOZ_ASSERT(pn->is<UnaryNode>());
996 *answer = true;
997 return true;
998
999 // Deletion of a non-Reference expression has side effects only through
1000 // evaluating the expression.
1001 case ParseNodeKind::DeleteExpr: {
1002 ParseNode* expr = pn->as<UnaryNode>().kid();
1003 return checkSideEffects(expr, answer);
1004 }
1005
1006 case ParseNodeKind::ExpressionStmt:
1007 return checkSideEffects(pn->as<UnaryNode>().kid(), answer);
1008
1009 // Binary cases with obvious side effects.
1010 case ParseNodeKind::InitExpr:
1011 *answer = true;
1012 return true;
1013
1014 case ParseNodeKind::AssignExpr:
1015 case ParseNodeKind::AddAssignExpr:
1016 case ParseNodeKind::SubAssignExpr:
1017 case ParseNodeKind::CoalesceAssignExpr:
1018 case ParseNodeKind::OrAssignExpr:
1019 case ParseNodeKind::AndAssignExpr:
1020 case ParseNodeKind::BitOrAssignExpr:
1021 case ParseNodeKind::BitXorAssignExpr:
1022 case ParseNodeKind::BitAndAssignExpr:
1023 case ParseNodeKind::LshAssignExpr:
1024 case ParseNodeKind::RshAssignExpr:
1025 case ParseNodeKind::UrshAssignExpr:
1026 case ParseNodeKind::MulAssignExpr:
1027 case ParseNodeKind::DivAssignExpr:
1028 case ParseNodeKind::ModAssignExpr:
1029 case ParseNodeKind::PowAssignExpr:
1030 MOZ_ASSERT(pn->is<AssignmentNode>());
1031 *answer = true;
1032 return true;
1033
1034 case ParseNodeKind::SetThis:
1035 MOZ_ASSERT(pn->is<BinaryNode>());
1036 *answer = true;
1037 return true;
1038
1039 case ParseNodeKind::StatementList:
1040 // Strict equality operations and short circuit operators are well-behaved
1041 // and perform no conversions.
1042 case ParseNodeKind::CoalesceExpr:
1043 case ParseNodeKind::OrExpr:
1044 case ParseNodeKind::AndExpr:
1045 case ParseNodeKind::StrictEqExpr:
1046 case ParseNodeKind::StrictNeExpr:
1047 // Any subexpression of a comma expression could be effectful.
1048 case ParseNodeKind::CommaExpr:
1049 MOZ_ASSERT(!pn->as<ListNode>().empty());
1050 [[fallthrough]];
1051 // Subcomponents of a literal may be effectful.
1052 case ParseNodeKind::ArrayExpr:
1053 case ParseNodeKind::ObjectExpr:
1054 for (ParseNode* item : pn->as<ListNode>().contents()) {
1055 if (!checkSideEffects(item, answer)) {
1056 return false;
1057 }
1058 if (*answer) {
1059 return true;
1060 }
1061 }
1062 return true;
1063
1064 #ifdef ENABLE_DECORATORS
1065 case ParseNodeKind::DecoratorList:
1066 MOZ_CRASH("Decorators are not supported yet");
1067 #endif
1068
1069 #ifdef ENABLE_EXPLICIT_RESOURCE_MANAGEMENT
1070 case ParseNodeKind::UsingDecl:
1071 case ParseNodeKind::AwaitUsingDecl:
1072 MOZ_CRASH("Using declarations are not supported yet");
1073 #endif
1074
1075 // Most other binary operations (parsed as lists in SpiderMonkey) may
1076 // perform conversions triggering side effects. Math operations perform
1077 // ToNumber and may fail invoking invalid user-defined toString/valueOf:
1078 // |5 < { toString: null }|. |instanceof| throws if provided a
1079 // non-object constructor: |null instanceof null|. |in| throws if given
1080 // a non-object RHS: |5 in null|.
1081 case ParseNodeKind::BitOrExpr:
1082 case ParseNodeKind::BitXorExpr:
1083 case ParseNodeKind::BitAndExpr:
1084 case ParseNodeKind::EqExpr:
1085 case ParseNodeKind::NeExpr:
1086 case ParseNodeKind::LtExpr:
1087 case ParseNodeKind::LeExpr:
1088 case ParseNodeKind::GtExpr:
1089 case ParseNodeKind::GeExpr:
1090 case ParseNodeKind::InstanceOfExpr:
1091 case ParseNodeKind::InExpr:
1092 case ParseNodeKind::PrivateInExpr:
1093 case ParseNodeKind::LshExpr:
1094 case ParseNodeKind::RshExpr:
1095 case ParseNodeKind::UrshExpr:
1096 case ParseNodeKind::AddExpr:
1097 case ParseNodeKind::SubExpr:
1098 case ParseNodeKind::MulExpr:
1099 case ParseNodeKind::DivExpr:
1100 case ParseNodeKind::ModExpr:
1101 case ParseNodeKind::PowExpr:
1102 MOZ_ASSERT(pn->as<ListNode>().count() >= 2);
1103 *answer = true;
1104 return true;
1105
1106 case ParseNodeKind::PropertyDefinition:
1107 case ParseNodeKind::Case: {
1108 BinaryNode* node = &pn->as<BinaryNode>();
1109 if (!checkSideEffects(node->left(), answer)) {
1110 return false;
1111 }
1112 if (*answer) {
1113 return true;
1114 }
1115 return checkSideEffects(node->right(), answer);
1116 }
1117
1118 // More getters.
1119 case ParseNodeKind::ElemExpr:
1120 case ParseNodeKind::OptionalElemExpr:
1121 MOZ_ASSERT(pn->is<BinaryNode>());
1122 *answer = true;
1123 return true;
1124
1125 // Throws if the operand is not of the right class. Can also call a private
1126 // getter.
1127 case ParseNodeKind::PrivateMemberExpr:
1128 case ParseNodeKind::OptionalPrivateMemberExpr:
1129 *answer = true;
1130 return true;
1131
1132 // These affect visible names in this code, or in other code.
1133 case ParseNodeKind::ImportDecl:
1134 case ParseNodeKind::ExportFromStmt:
1135 case ParseNodeKind::ExportDefaultStmt:
1136 MOZ_ASSERT(pn->is<BinaryNode>());
1137 *answer = true;
1138 return true;
1139
1140 // Likewise.
1141 case ParseNodeKind::ExportStmt:
1142 MOZ_ASSERT(pn->is<UnaryNode>());
1143 *answer = true;
1144 return true;
1145
1146 case ParseNodeKind::CallImportExpr:
1147 case ParseNodeKind::CallImportSpec:
1148 MOZ_ASSERT(pn->is<BinaryNode>());
1149 *answer = true;
1150 return true;
1151
1152 // Every part of a loop might be effect-free, but looping infinitely *is*
1153 // an effect. (Language lawyer trivia: C++ says threads can be assumed
1154 // to exit or have side effects, C++14 [intro.multithread]p27, so a C++
1155 // implementation's equivalent of the below could set |*answer = false;|
1156 // if all loop sub-nodes set |*answer = false|!)
1157 case ParseNodeKind::DoWhileStmt:
1158 case ParseNodeKind::WhileStmt:
1159 case ParseNodeKind::ForStmt:
1160 MOZ_ASSERT(pn->is<BinaryNode>());
1161 *answer = true;
1162 return true;
1163
1164 // Declarations affect the name set of the relevant scope.
1165 case ParseNodeKind::VarStmt:
1166 case ParseNodeKind::ConstDecl:
1167 case ParseNodeKind::LetDecl:
1168 MOZ_ASSERT(pn->is<ListNode>());
1169 *answer = true;
1170 return true;
1171
1172 case ParseNodeKind::IfStmt:
1173 case ParseNodeKind::ConditionalExpr: {
1174 TernaryNode* node = &pn->as<TernaryNode>();
1175 if (!checkSideEffects(node->kid1(), answer)) {
1176 return false;
1177 }
1178 if (*answer) {
1179 return true;
1180 }
1181 if (!checkSideEffects(node->kid2(), answer)) {
1182 return false;
1183 }
1184 if (*answer) {
1185 return true;
1186 }
1187 if ((pn = node->kid3())) {
1188 goto restart;
1189 }
1190 return true;
1191 }
1192
1193 // Function calls can invoke non-local code.
1194 case ParseNodeKind::NewExpr:
1195 case ParseNodeKind::CallExpr:
1196 case ParseNodeKind::OptionalCallExpr:
1197 case ParseNodeKind::TaggedTemplateExpr:
1198 case ParseNodeKind::SuperCallExpr:
1199 MOZ_ASSERT(pn->is<BinaryNode>());
1200 *answer = true;
1201 return true;
1202
1203 // Function arg lists can contain arbitrary expressions. Technically
1204 // this only causes side-effects if one of the arguments does, but since
1205 // the call being made will always trigger side-effects, it isn't needed.
1206 case ParseNodeKind::Arguments:
1207 MOZ_ASSERT(pn->is<ListNode>());
1208 *answer = true;
1209 return true;
1210
1211 case ParseNodeKind::OptionalChain:
1212 MOZ_ASSERT(pn->is<UnaryNode>());
1213 *answer = true;
1214 return true;
1215
1216 // Classes typically introduce names. Even if no name is introduced,
1217 // the heritage and/or class body (through computed property names)
1218 // usually have effects.
1219 case ParseNodeKind::ClassDecl:
1220 MOZ_ASSERT(pn->is<ClassNode>());
1221 *answer = true;
1222 return true;
1223
1224 // |with| calls |ToObject| on its expression and so throws if that value
1225 // is null/undefined.
1226 case ParseNodeKind::WithStmt:
1227 MOZ_ASSERT(pn->is<BinaryNode>());
1228 *answer = true;
1229 return true;
1230
1231 case ParseNodeKind::ReturnStmt:
1232 MOZ_ASSERT(pn->is<BinaryNode>());
1233 *answer = true;
1234 return true;
1235
1236 case ParseNodeKind::Name:
1237 MOZ_ASSERT(pn->is<NameNode>());
1238 *answer = true;
1239 return true;
1240
1241 // Shorthands could trigger getters: the |x| in the object literal in
1242 // |with ({ get x() { throw 42; } }) ({ x });|, for example, triggers
1243 // one. (Of course, it isn't necessary to use |with| for a shorthand to
1244 // trigger a getter.)
1245 case ParseNodeKind::Shorthand:
1246 MOZ_ASSERT(pn->is<BinaryNode>());
1247 *answer = true;
1248 return true;
1249
1250 case ParseNodeKind::Function:
1251 MOZ_ASSERT(pn->is<FunctionNode>());
1252 /*
1253 * A named function, contrary to ES3, is no longer effectful, because
1254 * we bind its name lexically (using JSOp::Callee) instead of creating
1255 * an Object instance and binding a readonly, permanent property in it
1256 * (the object and binding can be detected and hijacked or captured).
1257 * This is a bug fix to ES3; it is fixed in ES3.1 drafts.
1258 */
1259 *answer = false;
1260 return true;
1261
1262 case ParseNodeKind::Module:
1263 *answer = false;
1264 return true;
1265
1266 case ParseNodeKind::TryStmt: {
1267 TryNode* tryNode = &pn->as<TryNode>();
1268 if (!checkSideEffects(tryNode->body(), answer)) {
1269 return false;
1270 }
1271 if (*answer) {
1272 return true;
1273 }
1274 if (LexicalScopeNode* catchScope = tryNode->catchScope()) {
1275 if (!checkSideEffects(catchScope, answer)) {
1276 return false;
1277 }
1278 if (*answer) {
1279 return true;
1280 }
1281 }
1282 if (ParseNode* finallyBlock = tryNode->finallyBlock()) {
1283 if (!checkSideEffects(finallyBlock, answer)) {
1284 return false;
1285 }
1286 }
1287 return true;
1288 }
1289
1290 case ParseNodeKind::Catch: {
1291 BinaryNode* catchClause = &pn->as<BinaryNode>();
1292 if (ParseNode* name = catchClause->left()) {
1293 if (!checkSideEffects(name, answer)) {
1294 return false;
1295 }
1296 if (*answer) {
1297 return true;
1298 }
1299 }
1300 return checkSideEffects(catchClause->right(), answer);
1301 }
1302
1303 case ParseNodeKind::SwitchStmt: {
1304 SwitchStatement* switchStmt = &pn->as<SwitchStatement>();
1305 if (!checkSideEffects(&switchStmt->discriminant(), answer)) {
1306 return false;
1307 }
1308 return *answer ||
1309 checkSideEffects(&switchStmt->lexicalForCaseList(), answer);
1310 }
1311
1312 case ParseNodeKind::LabelStmt:
1313 return checkSideEffects(pn->as<LabeledStatement>().statement(), answer);
1314
1315 case ParseNodeKind::LexicalScope:
1316 return checkSideEffects(pn->as<LexicalScopeNode>().scopeBody(), answer);
1317
1318 // We could methodically check every interpolated expression, but it's
1319 // probably not worth the trouble. Treat template strings as effect-free
1320 // only if they don't contain any substitutions.
1321 case ParseNodeKind::TemplateStringListExpr: {
1322 ListNode* list = &pn->as<ListNode>();
1323 MOZ_ASSERT(!list->empty());
1324 MOZ_ASSERT((list->count() % 2) == 1,
1325 "template strings must alternate template and substitution "
1326 "parts");
1327 *answer = list->count() > 1;
1328 return true;
1329 }
1330
1331 // This should be unreachable but is left as-is for now.
1332 case ParseNodeKind::ParamsBody:
1333 *answer = true;
1334 return true;
1335
1336 case ParseNodeKind::ForIn: // by ParseNodeKind::For
1337 case ParseNodeKind::ForOf: // by ParseNodeKind::For
1338 case ParseNodeKind::ForHead: // by ParseNodeKind::For
1339 case ParseNodeKind::DefaultConstructor: // by ParseNodeKind::ClassDecl
1340 case ParseNodeKind::ClassBodyScope: // by ParseNodeKind::ClassDecl
1341 case ParseNodeKind::ClassMethod: // by ParseNodeKind::ClassDecl
1342 case ParseNodeKind::ClassField: // by ParseNodeKind::ClassDecl
1343 case ParseNodeKind::ClassNames: // by ParseNodeKind::ClassDecl
1344 case ParseNodeKind::StaticClassBlock: // by ParseNodeKind::ClassDecl
1345 case ParseNodeKind::ClassMemberList: // by ParseNodeKind::ClassDecl
1346 case ParseNodeKind::ImportSpecList: // by ParseNodeKind::Import
1347 case ParseNodeKind::ImportSpec: // by ParseNodeKind::Import
1348 case ParseNodeKind::ImportNamespaceSpec: // by ParseNodeKind::Import
1349 case ParseNodeKind::ImportAttribute: // by ParseNodeKind::Import
1350 case ParseNodeKind::ImportAttributeList: // by ParseNodeKind::Import
1351 case ParseNodeKind::ImportModuleRequest: // by ParseNodeKind::Import
1352 case ParseNodeKind::ExportBatchSpecStmt: // by ParseNodeKind::Export
1353 case ParseNodeKind::ExportSpecList: // by ParseNodeKind::Export
1354 case ParseNodeKind::ExportSpec: // by ParseNodeKind::Export
1355 case ParseNodeKind::ExportNamespaceSpec: // by ParseNodeKind::Export
1356 case ParseNodeKind::CallSiteObj: // by ParseNodeKind::TaggedTemplate
1357 case ParseNodeKind::PosHolder: // by ParseNodeKind::NewTarget
1358 case ParseNodeKind::SuperBase: // by ParseNodeKind::Elem and others
1359 case ParseNodeKind::PropertyNameExpr: // by ParseNodeKind::Dot
1360 MOZ_CRASH("handled by parent nodes");
1361
1362 case ParseNodeKind::LastUnused:
1363 case ParseNodeKind::Limit:
1364 MOZ_CRASH("invalid node kind");
1365 }
1366
1367 MOZ_CRASH(
1368 "invalid, unenumerated ParseNodeKind value encountered in "
1369 "BytecodeEmitter::checkSideEffects");
1370 }
1371
1372 bool BytecodeEmitter::isInLoop() const {
1373 return findInnermostNestableControl<LoopControl>();
1374 }
1375
1376 bool BytecodeEmitter::checkSingletonContext() const {
1377 MOZ_ASSERT_IF(sc->treatAsRunOnce(), sc->isTopLevelContext());
1378 return sc->treatAsRunOnce() && !isInLoop();
1379 }
1380
1381 bool BytecodeEmitter::needsImplicitThis() const {
1382 // Short-circuit if there is an enclosing 'with' scope.
1383 if (sc->inWith()) {
1384 return true;
1385 }
1386
1387 // Otherwise see if the current point is under a 'with'.
1388 for (EmitterScope* es = innermostEmitterScope(); es;
1389 es = es->enclosingInFrame()) {
1390 if (es->scope(this).kind() == ScopeKind::With) {
1391 return true;
1392 }
1393 }
1394
1395 return false;
1396 }
1397
1398 size_t BytecodeEmitter::countThisEnvironmentHops() const {
1399 unsigned numHops = 0;
1400
1401 for (const auto* current = this; current; current = current->parent) {
1402 for (EmitterScope* es = current->innermostEmitterScope(); es;
1403 es = es->enclosingInFrame()) {
1404 if (es->scope(current).is<FunctionScope>()) {
1405 if (!es->scope(current).isArrow()) {
1406 // The Parser is responsible for marking the environment as either
1407 // closed-over or used-by-eval which ensure that is must exist.
1408 MOZ_ASSERT(es->scope(current).hasEnvironment());
1409 return numHops;
1410 }
1411 }
1412 if (es->scope(current).hasEnvironment()) {
1413 numHops++;
1414 }
1415 }
1416 }
1417
1418 // The "this" environment exists outside of the compilation, but the
1419 // `ScopeContext` recorded the number of additional hops needed, so add
1420 // those in now.
1421 MOZ_ASSERT(sc->allowSuperProperty());
1422 numHops += compilationState.scopeContext.enclosingThisEnvironmentHops;
1423 return numHops;
1424 }
1425
1426 bool BytecodeEmitter::emitThisEnvironmentCallee() {
1427 // Get the innermost enclosing function that has a |this| binding.
1428
1429 // Directly load callee from the frame if possible.
1430 if (sc->isFunctionBox() && !sc->asFunctionBox()->isArrow()) {
1431 return emit1(JSOp::Callee);
1432 }
1433
1434 // We have to load the callee from the environment chain.
1435 size_t numHops = countThisEnvironmentHops();
1436
1437 static_assert(
1438 ENVCOORD_HOPS_LIMIT - 1 <= UINT8_MAX,
1439 "JSOp::EnvCallee operand size should match ENVCOORD_HOPS_LIMIT");
1440
1441 MOZ_ASSERT(numHops < ENVCOORD_HOPS_LIMIT - 1);
1442
1443 return emit2(JSOp::EnvCallee, numHops);
1444 }
1445
1446 bool BytecodeEmitter::emitSuperBase() {
1447 if (!emitThisEnvironmentCallee()) {
1448 return false;
1449 }
1450
1451 return emit1(JSOp::SuperBase);
1452 }
1453
1454 void BytecodeEmitter::reportError(ParseNode* pn, unsigned errorNumber,
1455 ...) const {
1456 uint32_t offset = pn ? pn->pn_pos.begin : *scriptStartOffset;
1457
1458 va_list args;
1459 va_start(args, errorNumber);
1460
1461 errorReporter().errorWithNotesAtVA(nullptr, AsVariant(offset), errorNumber,
1462 &args);
1463
1464 va_end(args);
1465 }
1466
1467 void BytecodeEmitter::reportError(uint32_t offset, unsigned errorNumber,
1468 ...) const {
1469 va_list args;
1470 va_start(args, errorNumber);
1471
1472 errorReporter().errorWithNotesAtVA(nullptr, AsVariant(offset), errorNumber,
1473 &args);
1474
1475 va_end(args);
1476 }
1477
1478 bool BytecodeEmitter::addObjLiteralData(ObjLiteralWriter& writer,
1479 GCThingIndex* outIndex) {
1480 if (!writer.checkForDuplicatedNames(fc)) {
1481 return false;
1482 }
1483
1484 size_t len = writer.getCode().size();
1485 auto* code = compilationState.alloc.newArrayUninitialized<uint8_t>(len);
1486 if (!code) {
1487 js::ReportOutOfMemory(fc);
1488 return false;
1489 }
1490 memcpy(code, writer.getCode().data(), len);
1491
1492 ObjLiteralIndex objIndex(compilationState.objLiteralData.length());
1493 if (uint32_t(objIndex) >= TaggedScriptThingIndex::IndexLimit) {
1494 ReportAllocationOverflow(fc);
1495 return false;
1496 }
1497 if (!compilationState.objLiteralData.emplaceBack(code, len, writer.getKind(),
1498 writer.getFlags(),
1499 writer.getPropertyCount())) {
1500 js::ReportOutOfMemory(fc);
1501 return false;
1502 }
1503
1504 return perScriptData().gcThingList().append(objIndex, outIndex);
1505 }
1506
1507 bool BytecodeEmitter::emitPrepareIteratorResult() {
1508 constexpr JSOp op = JSOp::NewObject;
1509
1510 ObjLiteralWriter writer;
1511 writer.beginShape(op);
1512
1513 writer.setPropNameNoDuplicateCheck(parserAtoms(),
1514 TaggedParserAtomIndex::WellKnown::value());
1515 if (!writer.propWithUndefinedValue(fc)) {
1516 return false;
1517 }
1518 writer.setPropNameNoDuplicateCheck(parserAtoms(),
1519 TaggedParserAtomIndex::WellKnown::done());
1520 if (!writer.propWithUndefinedValue(fc)) {
1521 return false;
1522 }
1523
1524 GCThingIndex shape;
1525 if (!addObjLiteralData(writer, &shape)) {
1526 return false;
1527 }
1528
1529 return emitGCIndexOp(op, shape);
1530 }
1531
1532 bool BytecodeEmitter::emitFinishIteratorResult(bool done) {
1533 if (!emitAtomOp(JSOp::InitProp, TaggedParserAtomIndex::WellKnown::value())) {
1534 return false;
1535 }
1536 if (!emit1(done ? JSOp::True : JSOp::False)) {
1537 return false;
1538 }
1539 if (!emitAtomOp(JSOp::InitProp, TaggedParserAtomIndex::WellKnown::done())) {
1540 return false;
1541 }
1542 return true;
1543 }
1544
1545 bool BytecodeEmitter::emitGetNameAtLocation(TaggedParserAtomIndex name,
1546 const NameLocation& loc) {
1547 NameOpEmitter noe(this, name, loc, NameOpEmitter::Kind::Get);
1548 if (!noe.emitGet()) {
1549 return false;
1550 }
1551
1552 return true;
1553 }
1554
1555 bool BytecodeEmitter::emitGetName(NameNode* name) {
1556 MOZ_ASSERT(name->isKind(ParseNodeKind::Name));
1557
1558 return emitGetName(name->name());
1559 }
1560
1561 bool BytecodeEmitter::emitGetPrivateName(NameNode* name) {
1562 MOZ_ASSERT(name->isKind(ParseNodeKind::PrivateName));
1563 return emitGetPrivateName(name->name());
1564 }
1565
1566 bool BytecodeEmitter::emitGetPrivateName(TaggedParserAtomIndex nameAtom) {
1567 // The parser ensures the private name is present on the environment chain,
1568 // but its location can be Dynamic or Global when emitting debugger
1569 // eval-in-frame code.
1570 NameLocation location = lookupName(nameAtom);
1571 MOZ_ASSERT(location.kind() == NameLocation::Kind::FrameSlot ||
1572 location.kind() == NameLocation::Kind::EnvironmentCoordinate ||
1573 location.kind() == NameLocation::Kind::Dynamic ||
1574 location.kind() == NameLocation::Kind::Global);
1575
1576 return emitGetNameAtLocation(nameAtom, location);
1577 }
1578
1579 bool BytecodeEmitter::emitTDZCheckIfNeeded(TaggedParserAtomIndex name,
1580 const NameLocation& loc,
1581 ValueIsOnStack isOnStack) {
1582 // Dynamic accesses have TDZ checks built into their VM code and should
1583 // never emit explicit TDZ checks.
1584 MOZ_ASSERT(loc.hasKnownSlot());
1585 MOZ_ASSERT(loc.isLexical() || loc.isPrivateMethod() || loc.isSynthetic());
1586
1587 // Private names are implemented as lexical bindings, but it's just an
1588 // implementation detail. Per spec there's no TDZ check when using them.
1589 if (parserAtoms().isPrivateName(name)) {
1590 return true;
1591 }
1592
1593 Maybe<MaybeCheckTDZ> check =
1594 innermostTDZCheckCache->needsTDZCheck(this, name);
1595 if (!check) {
1596 return false;
1597 }
1598
1599 // We've already emitted a check in this basic block.
1600 if (*check == DontCheckTDZ) {
1601 return true;
1602 }
1603
1604 // If the value is not on the stack, we have to load it first.
1605 if (isOnStack == ValueIsOnStack::No) {
1606 if (loc.kind() == NameLocation::Kind::FrameSlot) {
1607 if (!emitLocalOp(JSOp::GetLocal, loc.frameSlot())) {
1608 return false;
1609 }
1610 } else {
1611 if (!emitEnvCoordOp(JSOp::GetAliasedVar, loc.environmentCoordinate())) {
1612 return false;
1613 }
1614 }
1615 }
1616
1617 // Emit the lexical check.
1618 if (loc.kind() == NameLocation::Kind::FrameSlot) {
1619 if (!emitLocalOp(JSOp::CheckLexical, loc.frameSlot())) {
1620 return false;
1621 }
1622 } else {
1623 if (!emitEnvCoordOp(JSOp::CheckAliasedLexical,
1624 loc.environmentCoordinate())) {
1625 return false;
1626 }
1627 }
1628
1629 // Pop the value if needed.
1630 if (isOnStack == ValueIsOnStack::No) {
1631 if (!emit1(JSOp::Pop)) {
1632 return false;
1633 }
1634 }
1635
1636 return innermostTDZCheckCache->noteTDZCheck(this, name, DontCheckTDZ);
1637 }
1638
1639 bool BytecodeEmitter::emitPropLHS(PropertyAccess* prop) {
1640 MOZ_ASSERT(!prop->isSuper());
1641
1642 ParseNode* expr = &prop->expression();
1643
1644 if (!expr->is<PropertyAccess>() || expr->as<PropertyAccess>().isSuper()) {
1645 // The non-optimized case.
1646 return emitTree(expr);
1647 }
1648
1649 // If the object operand is also a dotted property reference, reverse the
1650 // list linked via expression() temporarily so we can iterate over it from
1651 // the bottom up (reversing again as we go), to avoid excessive recursion.
1652 PropertyAccess* pndot = &expr->as<PropertyAccess>();
1653 ParseNode* pnup = nullptr;
1654 ParseNode* pndown;
1655 for (;;) {
1656 // Reverse pndot->expression() to point up, not down.
1657 pndown = &pndot->expression();
1658 pndot->setExpression(pnup);
1659 if (!pndown->is<PropertyAccess>() ||
1660 pndown->as<PropertyAccess>().isSuper()) {
1661 break;
1662 }
1663 pnup = pndot;
1664 pndot = &pndown->as<PropertyAccess>();
1665 }
1666
1667 // pndown is a primary expression, not a dotted property reference.
1668 if (!emitTree(pndown)) {
1669 return false;
1670 }
1671
1672 while (true) {
1673 // Walk back up the list, emitting annotated name ops.
1674 if (!emitAtomOp(JSOp::GetProp, pndot->key().atom())) {
1675 return false;
1676 }
1677
1678 // Reverse the pndot->expression() link again.
1679 pnup = pndot->maybeExpression();
1680 pndot->setExpression(pndown);
1681 pndown = pndot;
1682 if (!pnup) {
1683 break;
1684 }
1685 pndot = &pnup->as<PropertyAccess>();
1686 }
1687 return true;
1688 }
1689
1690 bool BytecodeEmitter::emitPropIncDec(UnaryNode* incDec, ValueUsage valueUsage) {
1691 PropertyAccess* prop = &incDec->kid()->as<PropertyAccess>();
1692 bool isSuper = prop->isSuper();
1693 ParseNodeKind kind = incDec->getKind();
1694 PropOpEmitter poe(
1695 this,
1696 kind == ParseNodeKind::PostIncrementExpr
1697 ? PropOpEmitter::Kind::PostIncrement
1698 : kind == ParseNodeKind::PreIncrementExpr
1699 ? PropOpEmitter::Kind::PreIncrement
1700 : kind == ParseNodeKind::PostDecrementExpr
1701 ? PropOpEmitter::Kind::PostDecrement
1702 : PropOpEmitter::Kind::PreDecrement,
1703 isSuper ? PropOpEmitter::ObjKind::Super : PropOpEmitter::ObjKind::Other);
1704 if (!poe.prepareForObj()) {
1705 return false;
1706 }
1707 if (isSuper) {
1708 UnaryNode* base = &prop->expression().as<UnaryNode>();
1709 if (!emitGetThisForSuperBase(base)) {
1710 // [stack] THIS
1711 return false;
1712 }
1713 } else {
1714 if (!emitPropLHS(prop)) {
1715 // [stack] OBJ
1716 return false;
1717 }
1718 }
1719 if (!poe.emitIncDec(prop->key().atom(), valueUsage)) {
1720 // [stack] RESULT
1721 return false;
1722 }
1723
1724 return true;
1725 }
1726
1727 bool BytecodeEmitter::emitNameIncDec(UnaryNode* incDec, ValueUsage valueUsage) {
1728 MOZ_ASSERT(incDec->kid()->isKind(ParseNodeKind::Name));
1729
1730 ParseNodeKind kind = incDec->getKind();
1731 NameNode* name = &incDec->kid()->as<NameNode>();
1732 NameOpEmitter noe(this, name->atom(),
1733 kind == ParseNodeKind::PostIncrementExpr
1734 ? NameOpEmitter::Kind::PostIncrement
1735 : kind == ParseNodeKind::PreIncrementExpr
1736 ? NameOpEmitter::Kind::PreIncrement
1737 : kind == ParseNodeKind::PostDecrementExpr
1738 ? NameOpEmitter::Kind::PostDecrement
1739 : NameOpEmitter::Kind::PreDecrement);
1740 if (!noe.emitIncDec(valueUsage)) {
1741 return false;
1742 }
1743
1744 return true;
1745 }
1746
1747 bool BytecodeEmitter::emitElemObjAndKey(PropertyByValue* elem,
1748 ElemOpEmitter& eoe) {
1749 ParseNode* exprOrSuper = &elem->expression();
1750 ParseNode* key = &elem->key();
1751
1752 if (!eoe.prepareForObj()) {
1753 // [stack]
1754 return false;
1755 }
1756
1757 if (elem->isSuper()) {
1758 auto* base = &exprOrSuper->as<UnaryNode>();
1759 if (!emitGetThisForSuperBase(base)) {
1760 // [stack] THIS
1761 return false;
1762 }
1763 } else {
1764 if (!emitTree(exprOrSuper)) {
1765 // [stack] OBJ
1766 return false;
1767 }
1768 }
1769
1770 if (!eoe.prepareForKey()) {
1771 // [stack] # if Super
1772 // [stack] THIS? THIS
1773 // [stack] # otherwise
1774 // [stack] OBJ? OBJ
1775 return false;
1776 }
1777
1778 if (!emitTree(key)) {
1779 // [stack] # if Super
1780 // [stack] THIS? THIS KEY
1781 // [stack] # otherwise
1782 // [stack] OBJ? OBJ KEY
1783 return false;
1784 }
1785
1786 return true;
1787 }
1788
1789 bool BytecodeEmitter::emitElemOpBase(JSOp op) {
1790 if (!emit1(op)) {
1791 return false;
1792 }
1793
1794 return true;
1795 }
1796
1797 static ElemOpEmitter::Kind ConvertIncDecKind(ParseNodeKind kind) {
1798 switch (kind) {
1799 case ParseNodeKind::PostIncrementExpr:
1800 return ElemOpEmitter::Kind::PostIncrement;
1801 case ParseNodeKind::PreIncrementExpr:
1802 return ElemOpEmitter::Kind::PreIncrement;
1803 case ParseNodeKind::PostDecrementExpr:
1804 return ElemOpEmitter::Kind::PostDecrement;
1805 case ParseNodeKind::PreDecrementExpr:
1806 return ElemOpEmitter::Kind::PreDecrement;
1807 default:
1808 MOZ_CRASH("unexpected inc/dec node kind");
1809 }
1810 }
1811
1812 static PrivateOpEmitter::Kind PrivateConvertIncDecKind(ParseNodeKind kind) {
1813 switch (kind) {
1814 case ParseNodeKind::PostIncrementExpr:
1815 return PrivateOpEmitter::Kind::PostIncrement;
1816 case ParseNodeKind::PreIncrementExpr:
1817 return PrivateOpEmitter::Kind::PreIncrement;
1818 case ParseNodeKind::PostDecrementExpr:
1819 return PrivateOpEmitter::Kind::PostDecrement;
1820 case ParseNodeKind::PreDecrementExpr:
1821 return PrivateOpEmitter::Kind::PreDecrement;
1822 default:
1823 MOZ_CRASH("unexpected inc/dec node kind");
1824 }
1825 }
1826
1827 bool BytecodeEmitter::emitElemIncDec(UnaryNode* incDec, ValueUsage valueUsage) {
1828 PropertyByValue* elemExpr = &incDec->kid()->as<PropertyByValue>();
1829 bool isSuper = elemExpr->isSuper();
1830 MOZ_ASSERT(!elemExpr->key().isKind(ParseNodeKind::PrivateName));
1831 ParseNodeKind kind = incDec->getKind();
1832 ElemOpEmitter eoe(
1833 this, ConvertIncDecKind(kind),
1834 isSuper ? ElemOpEmitter::ObjKind::Super : ElemOpEmitter::ObjKind::Other);
1835 if (!emitElemObjAndKey(elemExpr, eoe)) {
1836 // [stack] # if Super
1837 // [stack] THIS KEY
1838 // [stack] # otherwise
1839 // [stack] OBJ KEY
1840 return false;
1841 }
1842 if (!eoe.emitIncDec(valueUsage)) {
1843 // [stack] RESULT
1844 return false;
1845 }
1846
1847 return true;
1848 }
1849
1850 bool BytecodeEmitter::emitCallIncDec(UnaryNode* incDec) {
1851 MOZ_ASSERT(incDec->isKind(ParseNodeKind::PreIncrementExpr) ||
1852 incDec->isKind(ParseNodeKind::PostIncrementExpr) ||
1853 incDec->isKind(ParseNodeKind::PreDecrementExpr) ||
1854 incDec->isKind(ParseNodeKind::PostDecrementExpr));
1855
1856 ParseNode* call = incDec->kid();
1857 MOZ_ASSERT(call->isKind(ParseNodeKind::CallExpr));
1858 if (!emitTree(call)) {
1859 // [stack] CALLRESULT
1860 return false;
1861 }
1862 if (!emit1(JSOp::ToNumeric)) {
1863 // [stack] N
1864 return false;
1865 }
1866
1867 // The increment/decrement has no side effects, so proceed to throw for
1868 // invalid assignment target.
1869 return emit2(JSOp::ThrowMsg, uint8_t(ThrowMsgKind::AssignToCall));
1870 }
1871
1872 bool BytecodeEmitter::emitPrivateIncDec(UnaryNode* incDec,
1873 ValueUsage valueUsage) {
1874 PrivateMemberAccess* privateExpr = &incDec->kid()->as<PrivateMemberAccess>();
1875 ParseNodeKind kind = incDec->getKind();
1876 PrivateOpEmitter xoe(this, PrivateConvertIncDecKind(kind),
1877 privateExpr->privateName().name());
1878 if (!emitTree(&privateExpr->expression())) {
1879 // [stack] OBJ
1880 return false;
1881 }
1882 if (!xoe.emitReference()) {
1883 // [stack] OBJ NAME
1884 return false;
1885 }
1886 if (!xoe.emitIncDec(valueUsage)) {
1887 // [stack] RESULT
1888 return false;
1889 }
1890
1891 return true;
1892 }
1893
1894 bool BytecodeEmitter::emitDouble(double d) {
1895 BytecodeOffset offset;
1896 if (!emitCheck(JSOp::Double, 9, &offset)) {
1897 return false;
1898 }
1899
1900 jsbytecode* code = bytecodeSection().code(offset);
1901 code[0] = jsbytecode(JSOp::Double);
1902 SET_INLINE_VALUE(code, DoubleValue(d));
1903 bytecodeSection().updateDepth(JSOp::Double, offset);
1904 return true;
1905 }
1906
1907 bool BytecodeEmitter::emitNumberOp(double dval) {
1908 int32_t ival;
1909 if (NumberIsInt32(dval, &ival)) {
1910 if (ival == 0) {
1911 return emit1(JSOp::Zero);
1912 }
1913 if (ival == 1) {
1914 return emit1(JSOp::One);
1915 }
1916 if ((int)(int8_t)ival == ival) {
1917 return emit2(JSOp::Int8, uint8_t(int8_t(ival)));
1918 }
1919
1920 uint32_t u = uint32_t(ival);
1921 if (u < Bit(16)) {
1922 if (!emitUint16Operand(JSOp::Uint16, u)) {
1923 return false;
1924 }
1925 } else if (u < Bit(24)) {
1926 BytecodeOffset off;
1927 if (!emitN(JSOp::Uint24, 3, &off)) {
1928 return false;
1929 }
1930 SET_UINT24(bytecodeSection().code(off), u);
1931 } else {
1932 BytecodeOffset off;
1933 if (!emitN(JSOp::Int32, 4, &off)) {
1934 return false;
1935 }
1936 SET_INT32(bytecodeSection().code(off), ival);
1937 }
1938 return true;
1939 }
1940
1941 return emitDouble(dval);
1942 }
1943
1944 /*
1945 * Using MOZ_NEVER_INLINE in here is a workaround for llvm.org/pr14047.
1946 * LLVM is deciding to inline this function which uses a lot of stack space
1947 * into emitTree which is recursive and uses relatively little stack space.
1948 */
1949 MOZ_NEVER_INLINE bool BytecodeEmitter::emitSwitch(SwitchStatement* switchStmt) {
1950 LexicalScopeNode& lexical = switchStmt->lexicalForCaseList();
1951 MOZ_ASSERT(lexical.isKind(ParseNodeKind::LexicalScope));
1952 ListNode* cases = &lexical.scopeBody()->as<ListNode>();
1953 MOZ_ASSERT(cases->isKind(ParseNodeKind::StatementList));
1954
1955 SwitchEmitter se(this);
1956 if (!se.emitDiscriminant(switchStmt->discriminant().pn_pos.begin)) {
1957 return false;
1958 }
1959
1960 if (!markStepBreakpoint()) {
1961 return false;
1962 }
1963 if (!emitTree(&switchStmt->discriminant())) {
1964 return false;
1965 }
1966
1967 // Enter the scope before pushing the switch BreakableControl since all
1968 // breaks are under this scope.
1969
1970 if (!lexical.isEmptyScope()) {
1971 if (!se.emitLexical(lexical.scopeBindings())) {
1972 return false;
1973 }
1974
1975 // A switch statement may contain hoisted functions inside its
1976 // cases. The hasTopLevelFunctionDeclarations flag is propagated from the
1977 // StatementList bodies of the cases to the case list.
1978 if (cases->hasTopLevelFunctionDeclarations()) {
1979 for (ParseNode* item : cases->contents()) {
1980 CaseClause* caseClause = &item->as<CaseClause>();
1981 ListNode* statements = caseClause->statementList();
1982 if (statements->hasTopLevelFunctionDeclarations()) {
1983 if (!emitHoistedFunctionsInList(statements)) {
1984 return false;
1985 }
1986 }
1987 }
1988 }
1989 } else {
1990 MOZ_ASSERT(!cases->hasTopLevelFunctionDeclarations());
1991 }
1992
1993 SwitchEmitter::TableGenerator tableGen(this);
1994 uint32_t caseCount = cases->count() - (switchStmt->hasDefault() ? 1 : 0);
1995 if (caseCount == 0) {
1996 tableGen.finish(0);
1997 } else {
1998 for (ParseNode* item : cases->contents()) {
1999 CaseClause* caseClause = &item->as<CaseClause>();
2000 if (caseClause->isDefault()) {
2001 continue;
2002 }
2003
2004 ParseNode* caseValue = caseClause->caseExpression();
2005
2006 if (caseValue->getKind() != ParseNodeKind::NumberExpr) {
2007 tableGen.setInvalid();
2008 break;
2009 }
2010
2011 int32_t i;
2012 if (!NumberEqualsInt32(caseValue->as<NumericLiteral>().value(), &i)) {
2013 tableGen.setInvalid();
2014 break;
2015 }
2016
2017 if (!tableGen.addNumber(i)) {
2018 return false;
2019 }
2020 }
2021
2022 tableGen.finish(caseCount);
2023 }
2024
2025 if (!se.validateCaseCount(caseCount)) {
2026 return false;
2027 }
2028
2029 bool isTableSwitch = tableGen.isValid();
2030 if (isTableSwitch) {
2031 if (!se.emitTable(tableGen)) {
2032 return false;
2033 }
2034 } else {
2035 if (!se.emitCond()) {
2036 return false;
2037 }
2038
2039 // Emit code for evaluating cases and jumping to case statements.
2040 for (ParseNode* item : cases->contents()) {
2041 CaseClause* caseClause = &item->as<CaseClause>();
2042 if (caseClause->isDefault()) {
2043 continue;
2044 }
2045
2046 if (!se.prepareForCaseValue()) {
2047 return false;
2048 }
2049
2050 ParseNode* caseValue = caseClause->caseExpression();
2051 // If the expression is a literal, suppress line number emission so
2052 // that debugging works more naturally.
2053 if (!emitTree(
2054 caseValue, ValueUsage::WantValue,
2055 caseValue->isLiteral() ? SUPPRESS_LINENOTE : EMIT_LINENOTE)) {
2056 return false;
2057 }
2058
2059 if (!se.emitCaseJump()) {
2060 return false;
2061 }
2062 }
2063 }
2064
2065 // Emit code for each case's statements.
2066 for (ParseNode* item : cases->contents()) {
2067 CaseClause* caseClause = &item->as<CaseClause>();
2068 if (caseClause->isDefault()) {
2069 if (!se.emitDefaultBody()) {
2070 return false;
2071 }
2072 } else {
2073 if (isTableSwitch) {
2074 ParseNode* caseValue = caseClause->caseExpression();
2075 MOZ_ASSERT(caseValue->isKind(ParseNodeKind::NumberExpr));
2076
2077 NumericLiteral* literal = &caseValue->as<NumericLiteral>();
2078 #ifdef DEBUG
2079 // Use NumberEqualsInt32 here because switches compare using
2080 // strict equality, which will equate -0 and +0. In contrast
2081 // NumberIsInt32 would return false for -0.
2082 int32_t v;
2083 MOZ_ASSERT(mozilla::NumberEqualsInt32(literal->value(), &v));
2084 #endif
2085 int32_t i = int32_t(literal->value());
2086
2087 if (!se.emitCaseBody(i, tableGen)) {
2088 return false;
2089 }
2090 } else {
2091 if (!se.emitCaseBody()) {
2092 return false;
2093 }
2094 }
2095 }
2096
2097 if (!emitTree(caseClause->statementList())) {
2098 return false;
2099 }
2100 }
2101
2102 if (!se.emitEnd()) {
2103 return false;
2104 }
2105
2106 return true;
2107 }
2108
2109 bool BytecodeEmitter::allocateResumeIndex(BytecodeOffset offset,
2110 uint32_t* resumeIndex) {
2111 static constexpr uint32_t MaxResumeIndex = BitMask(24);
2112
2113 static_assert(
2114 MaxResumeIndex < uint32_t(AbstractGeneratorObject::RESUME_INDEX_RUNNING),
2115 "resumeIndex should not include magic AbstractGeneratorObject "
2116 "resumeIndex values");
2117 static_assert(
2118 MaxResumeIndex <= INT32_MAX / sizeof(uintptr_t),
2119 "resumeIndex * sizeof(uintptr_t) must fit in an int32. JIT code relies "
2120 "on this when loading resume entries from BaselineScript");
2121
2122 *resumeIndex = bytecodeSection().resumeOffsetList().length();
2123 if (*resumeIndex > MaxResumeIndex) {
2124 reportError(nullptr, JSMSG_TOO_MANY_RESUME_INDEXES);
2125 return false;
2126 }
2127
2128 return bytecodeSection().resumeOffsetList().append(offset.value());
2129 }
2130
2131 bool BytecodeEmitter::allocateResumeIndexRange(
2132 mozilla::Span<BytecodeOffset> offsets, uint32_t* firstResumeIndex) {
2133 *firstResumeIndex = 0;
2134
2135 for (size_t i = 0, len = offsets.size(); i < len; i++) {
2136 uint32_t resumeIndex;
2137 if (!allocateResumeIndex(offsets[i], &resumeIndex)) {
2138 return false;
2139 }
2140 if (i == 0) {
2141 *firstResumeIndex = resumeIndex;
2142 }
2143 }
2144
2145 return true;
2146 }
2147
2148 bool BytecodeEmitter::emitYieldOp(JSOp op) {
2149 // ParseContext::Scope::setOwnStackSlotCount should check the fixed slot
2150 // for the following, and it should prevent using fixed slot if there are
2151 // too many bindings:
2152 // * generator or asyn function
2153 // * module code after top-level await
2154 MOZ_ASSERT(innermostEmitterScopeNoCheck()->frameSlotEnd() <=
2155 ParseContext::Scope::FixedSlotLimit);
2156
2157 if (op == JSOp::FinalYieldRval) {
2158 return emit1(JSOp::FinalYieldRval);
2159 }
2160
2161 MOZ_ASSERT(op == JSOp::InitialYield || op == JSOp::Yield ||
2162 op == JSOp::Await);
2163
2164 BytecodeOffset off;
2165 if (!emitN(op, 3, &off)) {
2166 return false;
2167 }
2168
2169 if (op == JSOp::InitialYield || op == JSOp::Yield) {
2170 bytecodeSection().addNumYields();
2171 }
2172
2173 uint32_t resumeIndex;
2174 if (!allocateResumeIndex(bytecodeSection().offset(), &resumeIndex)) {
2175 return false;
2176 }
2177
2178 SET_RESUMEINDEX(bytecodeSection().code(off), resumeIndex);
2179
2180 BytecodeOffset unusedOffset;
2181 return emitJumpTargetOp(JSOp::AfterYield, &unusedOffset);
2182 }
2183
2184 bool BytecodeEmitter::emitPushResumeKind(GeneratorResumeKind kind) {
2185 return emit2(JSOp::ResumeKind, uint8_t(kind));
2186 }
2187
2188 bool BytecodeEmitter::emitSetThis(BinaryNode* setThisNode) {
2189 // ParseNodeKind::SetThis is used to update |this| after a super() call
2190 // in a derived class constructor.
2191
2192 MOZ_ASSERT(setThisNode->isKind(ParseNodeKind::SetThis));
2193 MOZ_ASSERT(setThisNode->left()->isKind(ParseNodeKind::Name));
2194
2195 auto name = setThisNode->left()->as<NameNode>().name();
2196
2197 // The 'this' binding is not lexical, but due to super() semantics this
2198 // initialization needs to be treated as a lexical one.
2199 NameLocation loc = lookupName(name);
2200 NameLocation lexicalLoc;
2201 if (loc.kind() == NameLocation::Kind::FrameSlot) {
2202 lexicalLoc = NameLocation::FrameSlot(BindingKind::Let, loc.frameSlot());
2203 } else if (loc.kind() == NameLocation::Kind::EnvironmentCoordinate) {
2204 EnvironmentCoordinate coord = loc.environmentCoordinate();
2205 uint8_t hops = AssertedCast<uint8_t>(coord.hops());
2206 lexicalLoc = NameLocation::EnvironmentCoordinate(BindingKind::Let, hops,
2207 coord.slot());
2208 } else {
2209 MOZ_ASSERT(loc.kind() == NameLocation::Kind::Dynamic);
2210 lexicalLoc = loc;
2211 }
2212
2213 NameOpEmitter noe(this, name, lexicalLoc, NameOpEmitter::Kind::Initialize);
2214 if (!noe.prepareForRhs()) {
2215 // [stack]
2216 return false;
2217 }
2218
2219 // Emit the new |this| value.
2220 if (!emitTree(setThisNode->right())) {
2221 // [stack] NEWTHIS
2222 return false;
2223 }
2224
2225 // Get the original |this| and throw if we already initialized
2226 // it. Do *not* use the NameLocation argument, as that's the special
2227 // lexical location below to deal with super() semantics.
2228 if (!emitGetName(name)) {
2229 // [stack] NEWTHIS THIS
2230 return false;
2231 }
2232 if (!emit1(JSOp::CheckThisReinit)) {
2233 // [stack] NEWTHIS THIS
2234 return false;
2235 }
2236 if (!emit1(JSOp::Pop)) {
2237 // [stack] NEWTHIS
2238 return false;
2239 }
2240 if (!noe.emitAssignment()) {
2241 // [stack] NEWTHIS
2242 return false;
2243 }
2244
2245 if (!emitInitializeInstanceMembers(true)) {
2246 return false;
2247 }
2248
2249 return true;
2250 }
2251
2252 bool BytecodeEmitter::defineHoistedTopLevelFunctions(ParseNode* body) {
2253 MOZ_ASSERT(inPrologue());
2254 MOZ_ASSERT(sc->isGlobalContext() || (sc->isEvalContext() && !sc->strict()));
2255 MOZ_ASSERT(body->is<LexicalScopeNode>() || body->is<ListNode>());
2256
2257 if (body->is<LexicalScopeNode>()) {
2258 body = body->as<LexicalScopeNode>().scopeBody();
2259 MOZ_ASSERT(body->is<ListNode>());
2260 }
2261
2262 if (!body->as<ListNode>().hasTopLevelFunctionDeclarations()) {
2263 return true;
2264 }
2265
2266 return emitHoistedFunctionsInList(&body->as<ListNode>());
2267 }
2268
2269 // For Global and sloppy-Eval scripts, this performs most of the steps of the
2270 // spec's [GlobalDeclarationInstantiation] and [EvalDeclarationInstantiation]
2271 // operations.
2272 //
2273 // Note that while strict-Eval is handled in the same part of the spec, it never
2274 // fails for global-redeclaration checks so those scripts initialize directly in
2275 // their bytecode.
2276 bool BytecodeEmitter::emitDeclarationInstantiation(ParseNode* body) {
2277 if (sc->isModuleContext()) {
2278 // ES Modules have dedicated variable and lexial environments and therefore
2279 // do not have to perform redeclaration checks. We initialize their bindings
2280 // elsewhere in bytecode.
2281 return true;
2282 }
2283
2284 if (sc->isEvalContext() && sc->strict()) {
2285 // Strict Eval has a dedicated variables (and lexical) environment and
2286 // therefore does not have to perform redeclaration checks. We initialize
2287 // their bindings elsewhere in the bytecode.
2288 return true;
2289 }
2290
2291 // If we have no variables bindings, then we are done!
2292 if (sc->isGlobalContext()) {
2293 if (!sc->asGlobalContext()->bindings) {
2294 return true;
2295 }
2296 } else {
2297 MOZ_ASSERT(sc->isEvalContext());
2298
2299 if (!sc->asEvalContext()->bindings) {
2300 return true;
2301 }
2302 }
2303
2304 #if DEBUG
2305 // There should be no emitted functions yet.
2306 for (const auto& thing : perScriptData().gcThingList().objects()) {
2307 MOZ_ASSERT(thing.isEmptyGlobalScope() || thing.isScope());
2308 }
2309 #endif
2310
2311 // Emit the hoisted functions to gc-things list. There is no bytecode
2312 // generated yet to bind them.
2313 if (!defineHoistedTopLevelFunctions(body)) {
2314 return false;
2315 }
2316
2317 // Save the last GCThingIndex emitted. The hoisted functions are contained in
2318 // the gc-things list up until this point. This set of gc-things also contain
2319 // initial scopes (of which there must be at least one).
2320 MOZ_ASSERT(perScriptData().gcThingList().length() > 0);
2321 GCThingIndex lastFun =
2322 GCThingIndex(perScriptData().gcThingList().length() - 1);
2323
2324 #if DEBUG
2325 for (const auto& thing : perScriptData().gcThingList().objects()) {
2326 MOZ_ASSERT(thing.isEmptyGlobalScope() || thing.isScope() ||
2327 thing.isFunction());
2328 }
2329 #endif
2330
2331 // Check for declaration conflicts and initialize the bindings.
2332 // NOTE: The self-hosting top-level script should not populate the builtins
2333 // directly on the GlobalObject (and instead uses JSOp::GetIntrinsic for
2334 // lookups).
2335 if (emitterMode == BytecodeEmitter::EmitterMode::Normal) {
2336 if (!emitGCIndexOp(JSOp::GlobalOrEvalDeclInstantiation, lastFun)) {
2337 return false;
2338 }
2339 }
2340
2341 return true;
2342 }
2343
2344 bool BytecodeEmitter::emitScript(ParseNode* body) {
2345 setScriptStartOffsetIfUnset(body->pn_pos.begin);
2346
2347 MOZ_ASSERT(inPrologue());
2348
2349 TDZCheckCache tdzCache(this);
2350 EmitterScope emitterScope(this);
2351 Maybe<AsyncEmitter> topLevelAwait;
2352 if (sc->isGlobalContext()) {
2353 if (!emitterScope.enterGlobal(this, sc->asGlobalContext())) {
2354 return false;
2355 }
2356 } else if (sc->isEvalContext()) {
2357 if (!emitterScope.enterEval(this, sc->asEvalContext())) {
2358 return false;
2359 }
2360 } else {
2361 MOZ_ASSERT(sc->isModuleContext());
2362 if (!emitterScope.enterModule(this, sc->asModuleContext())) {
2363 return false;
2364 }
2365 if (sc->asModuleContext()->isAsync()) {
2366 topLevelAwait.emplace(this);
2367 }
2368 }
2369
2370 setFunctionBodyEndPos(body->pn_pos.end);
2371
2372 bool isSloppyEval = sc->isEvalContext() && !sc->strict();
2373 if (isSloppyEval && body->is<LexicalScopeNode>() &&
2374 !body->as<LexicalScopeNode>().isEmptyScope()) {
2375 // Sloppy eval scripts may emit hoisted functions bindings with a
2376 // `JSOp::GlobalOrEvalDeclInstantiation` opcode below. If this eval needs a
2377 // top-level lexical environment, we must ensure that environment is created
2378 // before those functions are created and bound.
2379 //
2380 // This differs from the global-script case below because the global-lexical
2381 // environment exists outside the script itself. In the case of strict eval
2382 // scripts, the `emitterScope` above is already sufficient.
2383 EmitterScope lexicalEmitterScope(this);
2384 LexicalScopeNode* scope = &body->as<LexicalScopeNode>();
2385
2386 if (!lexicalEmitterScope.enterLexical(this, ScopeKind::Lexical,
2387 scope->scopeBindings())) {
2388 return false;
2389 }
2390
2391 if (!emitDeclarationInstantiation(scope->scopeBody())) {
2392 return false;
2393 }
2394
2395 switchToMain();
2396
2397 ParseNode* scopeBody = scope->scopeBody();
2398 if (!emitLexicalScopeBody(scopeBody)) {
2399 return false;
2400 }
2401
2402 if (!updateSourceCoordNotes(scopeBody->pn_pos.end)) {
2403 return false;
2404 }
2405
2406 if (!lexicalEmitterScope.leave(this)) {
2407 return false;
2408 }
2409 } else {
2410 if (!emitDeclarationInstantiation(body)) {
2411 return false;
2412 }
2413 if (topLevelAwait) {
2414 if (!topLevelAwait->prepareForModule()) {
2415 return false;
2416 }
2417 }
2418
2419 switchToMain();
2420
2421 #ifdef ENABLE_EXPLICIT_RESOURCE_MANAGEMENT
2422 if (!emitterScope.prepareForModuleDisposableScopeBody(this)) {
2423 return false;
2424 }
2425 #endif
2426
2427 if (topLevelAwait) {
2428 if (!topLevelAwait->prepareForBody()) {
2429 return false;
2430 }
2431 }
2432
2433 if (!emitTree(body)) {
2434 // [stack]
2435 return false;
2436 }
2437
2438 if (!updateSourceCoordNotes(body->pn_pos.end)) {
2439 return false;
2440 }
2441 }
2442
2443 #ifdef ENABLE_EXPLICIT_RESOURCE_MANAGEMENT
2444 if (!emitterScope.emitModuleDisposableScopeBodyEnd(this)) {
2445 return false;
2446 }
2447 #endif
2448
2449 if (topLevelAwait) {
2450 if (!topLevelAwait->emitEndModule()) {
2451 return false;
2452 }
2453 }
2454
2455 if (!markSimpleBreakpoint()) {
2456 return false;
2457 }
2458
2459 if (!emitReturnRval()) {
2460 return false;
2461 }
2462
2463 if (!emitterScope.leave(this)) {
2464 return false;
2465 }
2466
2467 if (!NameFunctions(fc, parserAtoms(), body)) {
2468 return false;
2469 }
2470
2471 // Create a Stencil and convert it into a JSScript.
2472 return intoScriptStencil(CompilationStencil::TopLevelIndex);
2473 }
2474
2475 js::UniquePtr<ImmutableScriptData>
2476 BytecodeEmitter::createImmutableScriptData() {
2477 uint32_t nslots;
2478 if (!getNslots(&nslots)) {
2479 return nullptr;
2480 }
2481
2482 bool isFunction = sc->isFunctionBox();
2483 uint16_t funLength = isFunction ? sc->asFunctionBox()->length() : 0;
2484
2485 mozilla::SaturateUint8 propertyCountEstimate = propertyAdditionEstimate;
2486
2487 // Add fields to the property count estimate.
2488 if (isFunction && sc->asFunctionBox()->useMemberInitializers()) {
2489 propertyCountEstimate +=
2490 sc->asFunctionBox()->memberInitializers().numMemberInitializers;
2491 }
2492
2493 return ImmutableScriptData::new_(
2494 fc, mainOffset(), maxFixedSlots, nslots, bodyScopeIndex,
2495 bytecodeSection().numICEntries(), isFunction, funLength,
2496 propertyCountEstimate.value(), bytecodeSection().code(),
2497 bytecodeSection().notes(), bytecodeSection().resumeOffsetList().span(),
2498 bytecodeSection().scopeNoteList().span(),
2499 bytecodeSection().tryNoteList().span());
2500 }
2501
2502 #if defined(ENABLE_DECORATORS) || defined(ENABLE_EXPLICIT_RESOURCE_MANAGEMENT)
2503 bool BytecodeEmitter::emitCheckIsCallable() {
2504 // This emits code to check if the value at the top of the stack is
2505 // callable. The value is left on the stack.
2506 // [stack] VAL
2507 if (!emitAtomOp(JSOp::GetIntrinsic,
2508 TaggedParserAtomIndex::WellKnown::IsCallable())) {
2509 // [stack] VAL ISCALLABLE
2510 return false;
2511 }
2512 if (!emit1(JSOp::Undefined)) {
2513 // [stack] VAL ISCALLABLE UNDEFINED
2514 return false;
2515 }
2516 if (!emitDupAt(2)) {
2517 // [stack] VAL ISCALLABLE UNDEFINED VAL
2518 return false;
2519 }
2520 return emitCall(JSOp::Call, 1);
2521 // [stack] VAL ISCALLABLE_RESULT
2522 }
2523 #endif
2524
2525 bool BytecodeEmitter::getNslots(uint32_t* nslots) const {
2526 uint64_t nslots64 =
2527 maxFixedSlots + static_cast<uint64_t>(bytecodeSection().maxStackDepth());
2528 if (nslots64 > UINT32_MAX) {
2529 reportError(nullptr, JSMSG_NEED_DIET, "script");
2530 return false;
2531 }
2532 *nslots = nslots64;
2533 return true;
2534 }
2535
2536 bool BytecodeEmitter::emitFunctionScript(FunctionNode* funNode) {
2537 MOZ_ASSERT(inPrologue());
2538 ParamsBodyNode* paramsBody = funNode->body();
2539 FunctionBox* funbox = sc->asFunctionBox();
2540
2541 setScriptStartOffsetIfUnset(paramsBody->pn_pos.begin);
2542
2543 // [stack]
2544
2545 FunctionScriptEmitter fse(this, funbox, Some(paramsBody->pn_pos.begin),
2546 Some(paramsBody->pn_pos.end));
2547 if (!fse.prepareForParameters()) {
2548 // [stack]
2549 return false;
2550 }
2551
2552 if (!emitFunctionFormalParameters(paramsBody)) {
2553 // [stack]
2554 return false;
2555 }
2556
2557 if (!fse.prepareForBody()) {
2558 // [stack]
2559 return false;
2560 }
2561
2562 if (!emitTree(paramsBody->body())) {
2563 // [stack]
2564 return false;
2565 }
2566
2567 if (!fse.emitEndBody()) {
2568 // [stack]
2569 return false;
2570 }
2571
2572 if (funbox->index() == CompilationStencil::TopLevelIndex) {
2573 if (!NameFunctions(fc, parserAtoms(), funNode)) {
2574 return false;
2575 }
2576 }
2577
2578 return fse.intoStencil();
2579 }
2580
2581 class js::frontend::DestructuringLHSRef {
2582 struct None {
2583 size_t numReferenceSlots() const { return 0; }
2584 };
2585
2586 mozilla::Variant<None, NameOpEmitter, PropOpEmitter, ElemOpEmitter,
2587 PrivateOpEmitter>
2588 emitter_ = AsVariant(None{});
2589
2590 public:
2591 template <typename T>
2592 void from(T&& emitter) {
2593 emitter_.emplace<T>(std::forward<T>(emitter));
2594 }
2595
2596 template <typename T>
2597 T& emitter() {
2598 return emitter_.as<T>();
2599 }
2600
2601 /**
2602 * Return the number of values pushed onto the stack.
2603 */
2604 size_t numReferenceSlots() const {
2605 return emitter_.match([](auto& e) { return e.numReferenceSlots(); });
2606 }
2607 };
2608
2609 bool BytecodeEmitter::emitDestructuringLHSRef(ParseNode* target,
2610 DestructuringFlavor flav,
2611 DestructuringLHSRef& lref) {
2612 #ifdef DEBUG
2613 int depth = bytecodeSection().stackDepth();
2614 #endif
2615
2616 switch (target->getKind()) {
2617 case ParseNodeKind::ArrayExpr:
2618 case ParseNodeKind::ObjectExpr:
2619 // No need to recurse into ParseNodeKind::Array and ParseNodeKind::Object
2620 // subpatterns here, since emitSetOrInitializeDestructuring does the
2621 // recursion when setting or initializing the value.
2622 break;
2623
2624 case ParseNodeKind::Name: {
2625 auto* name = &target->as<NameNode>();
2626 NameOpEmitter noe(this, name->atom(),
2627 flav == DestructuringFlavor::Assignment
2628 ? NameOpEmitter::Kind::SimpleAssignment
2629 : NameOpEmitter::Kind::Initialize);
2630 if (!noe.prepareForRhs()) {
2631 return false;
2632 }
2633
2634 lref.from(std::move(noe));
2635 return true;
2636 }
2637
2638 case ParseNodeKind::ArgumentsLength:
2639 case ParseNodeKind::DotExpr: {
2640 PropertyAccess* prop = &target->as<PropertyAccess>();
2641 bool isSuper = prop->isSuper();
2642 PropOpEmitter poe(this, PropOpEmitter::Kind::SimpleAssignment,
2643 isSuper ? PropOpEmitter::ObjKind::Super
2644 : PropOpEmitter::ObjKind::Other);
2645 if (!poe.prepareForObj()) {
2646 return false;
2647 }
2648 if (isSuper) {
2649 UnaryNode* base = &prop->expression().as<UnaryNode>();
2650 if (!emitGetThisForSuperBase(base)) {
2651 // [stack] THIS SUPERBASE
2652 return false;
2653 }
2654 } else {
2655 if (!emitTree(&prop->expression())) {
2656 // [stack] OBJ
2657 return false;
2658 }
2659 }
2660 if (!poe.prepareForRhs()) {
2661 // [stack] # if Super
2662 // [stack] THIS SUPERBASE
2663 // [stack] # otherwise
2664 // [stack] OBJ
2665 return false;
2666 }
2667
2668 lref.from(std::move(poe));
2669 break;
2670 }
2671
2672 case ParseNodeKind::ElemExpr: {
2673 PropertyByValue* elem = &target->as<PropertyByValue>();
2674 bool isSuper = elem->isSuper();
2675 MOZ_ASSERT(!elem->key().isKind(ParseNodeKind::PrivateName));
2676 ElemOpEmitter eoe(this, ElemOpEmitter::Kind::SimpleAssignment,
2677 isSuper ? ElemOpEmitter::ObjKind::Super
2678 : ElemOpEmitter::ObjKind::Other);
2679 if (!emitElemObjAndKey(elem, eoe)) {
2680 // [stack] # if Super
2681 // [stack] THIS KEY
2682 // [stack] # otherwise
2683 // [stack] OBJ KEY
2684 return false;
2685 }
2686 if (!eoe.prepareForRhs()) {
2687 // [stack] # if Super
2688 // [stack] THIS KEY SUPERBASE
2689 // [stack] # otherwise
2690 // [stack] OBJ KEY
2691 return false;
2692 }
2693
2694 lref.from(std::move(eoe));
2695 break;
2696 }
2697
2698 case ParseNodeKind::PrivateMemberExpr: {
2699 PrivateMemberAccess* privateExpr = &target->as<PrivateMemberAccess>();
2700 PrivateOpEmitter xoe(this, PrivateOpEmitter::Kind::SimpleAssignment,
2701 privateExpr->privateName().name());
2702 if (!emitTree(&privateExpr->expression())) {
2703 // [stack] OBJ
2704 return false;
2705 }
2706 if (!xoe.emitReference()) {
2707 // [stack] OBJ NAME
2708 return false;
2709 }
2710
2711 lref.from(std::move(xoe));
2712 break;
2713 }
2714
2715 case ParseNodeKind::CallExpr:
2716 MOZ_ASSERT_UNREACHABLE(
2717 "Parser::reportIfNotValidSimpleAssignmentTarget "
2718 "rejects function calls as assignment "
2719 "targets in destructuring assignments");
2720 break;
2721
2722 default:
2723 MOZ_CRASH("emitDestructuringLHSRef: bad lhs kind");
2724 }
2725
2726 MOZ_ASSERT(bytecodeSection().stackDepth() ==
2727 depth + int(lref.numReferenceSlots()));
2728
2729 return true;
2730 }
2731
2732 bool BytecodeEmitter::emitSetOrInitializeDestructuring(
2733 ParseNode* target, DestructuringFlavor flav, DestructuringLHSRef& lref) {
2734 // Now emit the lvalue opcode sequence. If the lvalue is a nested
2735 // destructuring initialiser-form, call ourselves to handle it, then pop
2736 // the matched value. Otherwise emit an lvalue bytecode sequence followed
2737 // by an assignment op.
2738
2739 switch (target->getKind()) {
2740 case ParseNodeKind::ArrayExpr:
2741 case ParseNodeKind::ObjectExpr:
2742 if (!emitDestructuringOps(&target->as<ListNode>(), flav)) {
2743 return false;
2744 }
2745 // emitDestructuringOps leaves the assigned (to-be-destructured) value on
2746 // top of the stack.
2747 break;
2748
2749 case ParseNodeKind::Name: {
2750 // The environment is already pushed by emitDestructuringLHSRef.
2751 // [stack] ENV? VAL
2752 auto& noe = lref.emitter<NameOpEmitter>();
2753
2754 if (!noe.emitAssignment()) {
2755 // [stack] VAL
2756 return false;
2757 }
2758 break;
2759 }
2760
2761 case ParseNodeKind::ArgumentsLength:
2762 case ParseNodeKind::DotExpr: {
2763 // The reference is already pushed by emitDestructuringLHSRef.
2764 // [stack] # if Super
2765 // [stack] THIS SUPERBASE VAL
2766 // [stack] # otherwise
2767 // [stack] OBJ VAL
2768 auto& poe = lref.emitter<PropOpEmitter>();
2769 auto* prop = &target->as<PropertyAccess>();
2770
2771 if (!poe.emitAssignment(prop->key().atom())) {
2772 // [stack] # VAL
2773 return false;
2774 }
2775 break;
2776 }
2777
2778 case ParseNodeKind::ElemExpr: {
2779 // The reference is already pushed by emitDestructuringLHSRef.
2780 // [stack] # if Super
2781 // [stack] THIS KEY SUPERBASE VAL
2782 // [stack] # otherwise
2783 // [stack] OBJ KEY VAL
2784 auto& eoe = lref.emitter<ElemOpEmitter>();
2785
2786 if (!eoe.emitAssignment()) {
2787 // [stack] VAL
2788 return false;
2789 }
2790 break;
2791 }
2792
2793 case ParseNodeKind::PrivateMemberExpr: {
2794 // The reference is already pushed by emitDestructuringLHSRef.
2795 // [stack] OBJ NAME VAL
2796 auto& xoe = lref.emitter<PrivateOpEmitter>();
2797
2798 if (!xoe.emitAssignment()) {
2799 // [stack] VAL
2800 return false;
2801 }
2802 break;
2803 }
2804
2805 case ParseNodeKind::CallExpr:
2806 MOZ_ASSERT_UNREACHABLE(
2807 "Parser::reportIfNotValidSimpleAssignmentTarget "
2808 "rejects function calls as assignment "
2809 "targets in destructuring assignments");
2810 break;
2811
2812 default:
2813 MOZ_CRASH("emitSetOrInitializeDestructuring: bad lhs kind");
2814 }
2815
2816 // Pop the assigned value.
2817 if (!emit1(JSOp::Pop)) {
2818 // [stack] # empty
2819 return false;
2820 }
2821
2822 return true;
2823 }
2824
2825 JSOp BytecodeEmitter::getIterCallOp(JSOp callOp,
2826 SelfHostedIter selfHostedIter) const {
2827 if (emitterMode == BytecodeEmitter::SelfHosting) {
2828 MOZ_ASSERT(selfHostedIter != SelfHostedIter::Deny);
2829
2830 switch (callOp) {
2831 case JSOp::Call:
2832 return JSOp::CallContent;
2833 case JSOp::CallIter:
2834 return JSOp::CallContentIter;
2835 default:
2836 MOZ_CRASH("Unknown iterator call op");
2837 }
2838 }
2839
2840 return callOp;
2841 }
2842
2843 bool BytecodeEmitter::emitIteratorNext(
2844 const Maybe<uint32_t>& callSourceCoordOffset,
2845 IteratorKind iterKind /* = IteratorKind::Sync */,
2846 SelfHostedIter selfHostedIter /* = SelfHostedIter::Deny */) {
2847 MOZ_ASSERT(selfHostedIter != SelfHostedIter::Deny ||
2848 emitterMode != BytecodeEmitter::SelfHosting,
2849 ".next() iteration is prohibited in self-hosted code because it"
2850 "can run user-modifiable iteration code");
2851
2852 // [stack] ... NEXT ITER
2853 MOZ_ASSERT(bytecodeSection().stackDepth() >= 2);
2854
2855 if (!emitCall(getIterCallOp(JSOp::Call, selfHostedIter), 0,
2856 callSourceCoordOffset)) {
2857 // [stack] ... RESULT
2858 return false;
2859 }
2860
2861 if (iterKind == IteratorKind::Async) {
2862 if (!emitAwaitInInnermostScope()) {
2863 // [stack] ... RESULT
2864 return false;
2865 }
2866 }
2867
2868 if (!emitCheckIsObj(CheckIsObjectKind::IteratorNext)) {
2869 // [stack] ... RESULT
2870 return false;
2871 }
2872 return true;
2873 }
2874
2875 bool BytecodeEmitter::emitIteratorCloseInScope(
2876 EmitterScope& currentScope,
2877 IteratorKind iterKind /* = IteratorKind::Sync */,
2878 CompletionKind completionKind /* = CompletionKind::Normal */,
2879 SelfHostedIter selfHostedIter /* = SelfHostedIter::Deny */) {
2880 MOZ_ASSERT(selfHostedIter != SelfHostedIter::Deny ||
2881 emitterMode != BytecodeEmitter::SelfHosting,
2882 ".close() on iterators is prohibited in self-hosted code because "
2883 "it can run user-modifiable iteration code");
2884
2885 if (iterKind == IteratorKind::Sync) {
2886 return emit2(JSOp::CloseIter, uint8_t(completionKind));
2887 }
2888
2889 // Generate inline logic corresponding to IteratorClose (ES2021 7.4.6) and
2890 // AsyncIteratorClose (ES2021 7.4.7). Steps numbers apply to both operations.
2891 //
2892 // Callers need to ensure that the iterator object is at the top of the
2893 // stack.
2894
2895 // For non-Throw completions, we emit the equivalent of:
2896 //
2897 // var returnMethod = GetMethod(iterator, "return");
2898 // if (returnMethod !== undefined) {
2899 // var innerResult = [Await] Call(returnMethod, iterator);
2900 // CheckIsObj(innerResult);
2901 // }
2902 //
2903 // Whereas for Throw completions, we emit:
2904 //
2905 // try {
2906 // var returnMethod = GetMethod(iterator, "return");
2907 // if (returnMethod !== undefined) {
2908 // [Await] Call(returnMethod, iterator);
2909 // }
2910 // } catch {}
2911
2912 Maybe<TryEmitter> tryCatch;
2913
2914 if (completionKind == CompletionKind::Throw) {
2915 tryCatch.emplace(this, TryEmitter::Kind::TryCatch,
2916 TryEmitter::ControlKind::NonSyntactic);
2917
2918 if (!tryCatch->emitTry()) {
2919 // [stack] ... ITER
2920 return false;
2921 }
2922 }
2923
2924 if (!emit1(JSOp::Dup)) {
2925 // [stack] ... ITER ITER
2926 return false;
2927 }
2928
2929 // Steps 1-2 are assertions, step 3 is implicit.
2930
2931 // Step 4.
2932 //
2933 // Get the "return" method.
2934 if (!emitAtomOp(JSOp::GetProp, TaggedParserAtomIndex::WellKnown::return_())) {
2935 // [stack] ... ITER RET
2936 return false;
2937 }
2938
2939 // Step 5.
2940 //
2941 // Do nothing if "return" is undefined or null.
2942 InternalIfEmitter ifReturnMethodIsDefined(this);
2943 if (!emit1(JSOp::IsNullOrUndefined)) {
2944 // [stack] ... ITER RET NULL-OR-UNDEF
2945 return false;
2946 }
2947
2948 if (!ifReturnMethodIsDefined.emitThenElse(
2949 IfEmitter::ConditionKind::Negative)) {
2950 // [stack] ... ITER RET
2951 return false;
2952 }
2953
2954 // Steps 5.c, 7.
2955 //
2956 // Call the "return" method.
2957 if (!emit1(JSOp::Swap)) {
2958 // [stack] ... RET ITER
2959 return false;
2960 }
2961
2962 if (!emitCall(getIterCallOp(JSOp::Call, selfHostedIter), 0)) {
2963 // [stack] ... RESULT
2964 return false;
2965 }
2966
2967 // 7.4.7 AsyncIteratorClose, step 5.d.
2968 if (iterKind == IteratorKind::Async) {
2969 if (completionKind != CompletionKind::Throw) {
2970 // Await clobbers rval, so save the current rval.
2971 if (!emit1(JSOp::GetRval)) {
2972 // [stack] ... RESULT RVAL
2973 return false;
2974 }
2975 if (!emit1(JSOp::Swap)) {
2976 // [stack] ... RVAL RESULT
2977 return false;
2978 }
2979 }
2980
2981 if (!emitAwaitInScope(currentScope)) {
2982 // [stack] ... RVAL? RESULT
2983 return false;
2984 }
2985
2986 if (completionKind != CompletionKind::Throw) {
2987 if (!emit1(JSOp::Swap)) {
2988 // [stack] ... RESULT RVAL
2989 return false;
2990 }
2991 if (!emit1(JSOp::SetRval)) {
2992 // [stack] ... RESULT
2993 return false;
2994 }
2995 }
2996 }
2997
2998 // Step 6 (Handled in caller).
2999
3000 // Step 8.
3001 if (completionKind != CompletionKind::Throw) {
3002 // Check that the "return" result is an object.
3003 if (!emitCheckIsObj(CheckIsObjectKind::IteratorReturn)) {
3004 // [stack] ... RESULT
3005 return false;
3006 }
3007 }
3008
3009 if (!ifReturnMethodIsDefined.emitElse()) {
3010 // [stack] ... ITER RET
3011 return false;
3012 }
3013
3014 if (!emit1(JSOp::Pop)) {
3015 // [stack] ... ITER
3016 return false;
3017 }
3018
3019 if (!ifReturnMethodIsDefined.emitEnd()) {
3020 return false;
3021 }
3022
3023 if (completionKind == CompletionKind::Throw) {
3024 if (!tryCatch->emitCatch()) {
3025 // [stack] ... ITER EXC
3026 return false;
3027 }
3028
3029 // Just ignore the exception thrown by call and await.
3030 if (!emit1(JSOp::Pop)) {
3031 // [stack] ... ITER
3032 return false;
3033 }
3034
3035 if (!tryCatch->emitEnd()) {
3036 // [stack] ... ITER
3037 return false;
3038 }
3039 }
3040
3041 // Step 9 (Handled in caller).
3042
3043 return emit1(JSOp::Pop);
3044 // [stack] ...
3045 }
3046
3047 template <typename InnerEmitter>
3048 bool BytecodeEmitter::wrapWithDestructuringTryNote(int32_t iterDepth,
3049 InnerEmitter emitter) {
3050 MOZ_ASSERT(bytecodeSection().stackDepth() >= iterDepth);
3051
3052 // Pad a nop at the beginning of the bytecode covered by the trynote so
3053 // that when unwinding environments, we may unwind to the scope
3054 // corresponding to the pc *before* the start, in case the first bytecode
3055 // emitted by |emitter| is the start of an inner scope. See comment above
3056 // UnwindEnvironmentToTryPc.
3057 if (!emit1(JSOp::TryDestructuring)) {
3058 return false;
3059 }
3060
3061 BytecodeOffset start = bytecodeSection().offset();
3062 if (!emitter(this)) {
3063 return false;
3064 }
3065 BytecodeOffset end = bytecodeSection().offset();
3066 if (start != end) {
3067 return addTryNote(TryNoteKind::Destructuring, iterDepth, start, end);
3068 }
3069 return true;
3070 }
3071
3072 bool BytecodeEmitter::emitDefault(ParseNode* defaultExpr, ParseNode* pattern) {
3073 // [stack] VALUE
3074
3075 DefaultEmitter de(this);
3076 if (!de.prepareForDefault()) {
3077 // [stack]
3078 return false;
3079 }
3080 if (!emitInitializer(defaultExpr, pattern)) {
3081 // [stack] DEFAULTVALUE
3082 return false;
3083 }
3084 if (!de.emitEnd()) {
3085 // [stack] VALUE/DEFAULTVALUE
3086 return false;
3087 }
3088 return true;
3089 }
3090
3091 bool BytecodeEmitter::emitAnonymousFunctionWithName(
3092 ParseNode* node, TaggedParserAtomIndex name) {
3093 MOZ_ASSERT(node->isDirectRHSAnonFunction());
3094
3095 if (node->is<FunctionNode>()) {
3096 // Function doesn't have 'name' property at this point.
3097 // Set function's name at compile time.
3098 setFunName(node->as<FunctionNode>().funbox(), name);
3099
3100 return emitTree(node);
3101 }
3102
3103 MOZ_ASSERT(node->is<ClassNode>());
3104
3105 return emitClass(&node->as<ClassNode>(), ClassNameKind::InferredName, name);
3106 }
3107
3108 bool BytecodeEmitter::emitAnonymousFunctionWithComputedName(
3109 ParseNode* node, FunctionPrefixKind prefixKind) {
3110 MOZ_ASSERT(node->isDirectRHSAnonFunction());
3111
3112 if (node->is<FunctionNode>()) {
3113 if (!emitTree(node)) {
3114 // [stack] NAME FUN
3115 return false;
3116 }
3117 if (!emitDupAt(1)) {
3118 // [stack] NAME FUN NAME
3119 return false;
3120 }
3121 if (!emit2(JSOp::SetFunName, uint8_t(prefixKind))) {
3122 // [stack] NAME FUN
3123 return false;
3124 }
3125 return true;
3126 }
3127
3128 MOZ_ASSERT(node->is<ClassNode>());
3129 MOZ_ASSERT(prefixKind == FunctionPrefixKind::None);
3130
3131 return emitClass(&node->as<ClassNode>(), ClassNameKind::ComputedName);
3132 }
3133
3134 void BytecodeEmitter::setFunName(FunctionBox* funbox,
3135 TaggedParserAtomIndex name) const {
3136 // The inferred name may already be set if this function is an interpreted
3137 // lazy function and we OOM'ed after we set the inferred name the first
3138 // time.
3139 if (funbox->hasInferredName()) {
3140 MOZ_ASSERT(!funbox->emitBytecode);
3141 MOZ_ASSERT(funbox->displayAtom() == name);
3142 } else {
3143 funbox->setInferredName(name);
3144 }
3145 }
3146
3147 bool BytecodeEmitter::emitInitializer(ParseNode* initializer,
3148 ParseNode* pattern) {
3149 if (initializer->isDirectRHSAnonFunction()) {
3150 MOZ_ASSERT(!pattern->isInParens());
3151 auto name = pattern->as<NameNode>().name();
3152 if (!emitAnonymousFunctionWithName(initializer, name)) {
3153 return false;
3154 }
3155 } else {
3156 if (!emitTree(initializer)) {
3157 return false;
3158 }
3159 }
3160
3161 return true;
3162 }
3163
3164 bool BytecodeEmitter::emitDestructuringOpsArray(ListNode* pattern,
3165 DestructuringFlavor flav) {
3166 MOZ_ASSERT(getSelfHostedIterFor(pattern) == SelfHostedIter::Deny,
3167 "array destructuring is prohibited in self-hosted code because it"
3168 "can run user-modifiable iteration code");
3169 MOZ_ASSERT(pattern->isKind(ParseNodeKind::ArrayExpr));
3170 MOZ_ASSERT(bytecodeSection().stackDepth() != 0);
3171
3172 // Here's pseudo code for |let [a, b, , c=y, ...d] = x;|
3173 //
3174 // Lines that are annotated "covered by trynote" mean that upon throwing
3175 // an exception, IteratorClose is called on iter only if done is false.
3176 //
3177 // let x, y;
3178 // let a, b, c, d;
3179 // let iter, next, lref, result, done, value; // stack values
3180 //
3181 // // NOTE: the fast path for this example is not applicable, because of
3182 // // the spread and the assignment |c=y|, but it is documented here for a
3183 // // simpler example, |let [a,b] = x;|
3184 // //
3185 // // if (IsOptimizableArray(x)) {
3186 // // a = x[0];
3187 // // b = x[1];
3188 // // goto end: // (skip everything below)
3189 // // }
3190 //
3191 // iter = x[Symbol.iterator]();
3192 // next = iter.next;
3193 //
3194 // // ==== emitted by loop for a ====
3195 // lref = GetReference(a); // covered by trynote
3196 //
3197 // result = Call(next, iter);
3198 // done = result.done;
3199 //
3200 // if (done)
3201 // value = undefined;
3202 // else
3203 // value = result.value;
3204 //
3205 // SetOrInitialize(lref, value); // covered by trynote
3206 //
3207 // // ==== emitted by loop for b ====
3208 // lref = GetReference(b); // covered by trynote
3209 //
3210 // if (done) {
3211 // value = undefined;
3212 // } else {
3213 // result = Call(next, iter);
3214 // done = result.done;
3215 // if (done)
3216 // value = undefined;
3217 // else
3218 // value = result.value;
3219 // }
3220 //
3221 // SetOrInitialize(lref, value); // covered by trynote
3222 //
3223 // // ==== emitted by loop for elision ====
3224 // if (done) {
3225 // value = undefined;
3226 // } else {
3227 // result = Call(next, iter);
3228 // done = result.done;
3229 // if (done)
3230 // value = undefined;
3231 // else
3232 // value = result.value;
3233 // }
3234 //
3235 // // ==== emitted by loop for c ====
3236 // lref = GetReference(c); // covered by trynote
3237 //
3238 // if (done) {
3239 // value = undefined;
3240 // } else {
3241 // result = Call(next, iter);
3242 // done = result.done;
3243 // if (done)
3244 // value = undefined;
3245 // else
3246 // value = result.value;
3247 // }
3248 //
3249 // if (value === undefined)
3250 // value = y; // covered by trynote
3251 //
3252 // SetOrInitialize(lref, value); // covered by trynote
3253 //
3254 // // ==== emitted by loop for d ====
3255 // lref = GetReference(d); // covered by trynote
3256 //
3257 // if (done)
3258 // value = [];
3259 // else
3260 // value = [...iter];
3261 //
3262 // SetOrInitialize(lref, value); // covered by trynote
3263 //
3264 // // === emitted after loop ===
3265 // if (!done)
3266 // IteratorClose(iter);
3267 //
3268 // end:
3269
3270 bool isEligibleForArrayOptimizations = true;
3271 for (ParseNode* member : pattern->contents()) {
3272 switch (member->getKind()) {
3273 case ParseNodeKind::Elision:
3274 break;
3275 case ParseNodeKind::Name: {
3276 auto name = member->as<NameNode>().name();
3277 NameLocation loc = lookupName(name);
3278 if (loc.kind() != NameLocation::Kind::ArgumentSlot &&
3279 loc.kind() != NameLocation::Kind::FrameSlot &&
3280 loc.kind() != NameLocation::Kind::EnvironmentCoordinate) {
3281 isEligibleForArrayOptimizations = false;
3282 }
3283 break;
3284 }
3285 default:
3286 // Unfortunately we can't handle any recursive destructuring,
3287 // because we can't guarantee that the recursed-into parts
3288 // won't run code which invalidates our constraints. We also
3289 // cannot handle ParseNodeKind::AssignExpr for similar reasons.
3290 isEligibleForArrayOptimizations = false;
3291 break;
3292 }
3293 if (!isEligibleForArrayOptimizations) {
3294 break;
3295 }
3296 }
3297
3298 // Use an iterator to destructure the RHS, instead of index lookup. We
3299 // must leave the *original* value on the stack.
3300 if (!emit1(JSOp::Dup)) {
3301 // [stack] ... OBJ OBJ
3302 return false;
3303 }
3304
3305 Maybe<InternalIfEmitter> ifArrayOptimizable;
3306
3307 if (isEligibleForArrayOptimizations) {
3308 ifArrayOptimizable.emplace(
3309 this, BranchEmitterBase::LexicalKind::MayContainLexicalAccessInBranch);
3310
3311 if (!emit1(JSOp::Dup)) {
3312 // [stack] OBJ OBJ
3313 return false;
3314 }
3315
3316 if (!emit1(JSOp::OptimizeGetIterator)) {
3317 // [stack] OBJ OBJ IS_OPTIMIZABLE
3318 return false;
3319 }
3320
3321 if (!ifArrayOptimizable->emitThenElse()) {
3322 // [stack] OBJ OBJ
3323 return false;
3324 }
3325
3326 if (!emitAtomOp(JSOp::GetProp,
3327 TaggedParserAtomIndex::WellKnown::length())) {
3328 // [stack] OBJ LENGTH
3329 return false;
3330 }
3331
3332 if (!emit1(JSOp::Swap)) {
3333 // [stack] LENGTH OBJ
3334 return false;
3335 }
3336
3337 uint32_t idx = 0;
3338 for (ParseNode* member : pattern->contents()) {
3339 if (member->isKind(ParseNodeKind::Elision)) {
3340 idx += 1;
3341 continue;
3342 }
3343 MOZ_ASSERT(member->isKind(ParseNodeKind::Name));
3344
3345 if (!emit1(JSOp::Dup)) {
3346 // [stack] LENGTH OBJ OBJ
3347 return false;
3348 }
3349
3350 if (!emitNumberOp(idx)) {
3351 // [stack] LENGTH OBJ OBJ IDX
3352 return false;
3353 }
3354
3355 if (!emit1(JSOp::Dup)) {
3356 // [stack] LENGTH OBJ OBJ IDX IDX
3357 return false;
3358 }
3359
3360 if (!emitDupAt(4)) {
3361 // [stack] LENGTH OBJ OBJ IDX IDX LENGTH
3362 return false;
3363 }
3364
3365 if (!emit1(JSOp::Lt)) {
3366 // [stack] LENGTH OBJ OBJ IDX IS_IN_DENSE_BOUNDS
3367 return false;
3368 }
3369
3370 InternalIfEmitter isInDenseBounds(this);
3371 if (!isInDenseBounds.emitThenElse()) {
3372 // [stack] LENGTH OBJ OBJ IDX
3373 return false;
3374 }
3375
3376 if (!emit1(JSOp::GetElem)) {
3377 // [stack] LENGTH OBJ VALUE
3378 return false;
3379 }
3380
3381 if (!isInDenseBounds.emitElse()) {
3382 // [stack] LENGTH OBJ OBJ IDX
3383 return false;
3384 }
3385
3386 if (!emitPopN(2)) {
3387 // [stack] LENGTH OBJ
3388 return false;
3389 }
3390
3391 if (!emit1(JSOp::Undefined)) {
3392 // [stack] LENGTH OBJ UNDEFINED
3393 return false;
3394 }
3395
3396 if (!isInDenseBounds.emitEnd()) {
3397 // [stack] LENGTH OBJ VALUE|UNDEFINED
3398 return false;
3399 }
3400
3401 DestructuringLHSRef lref;
3402 if (!emitDestructuringLHSRef(member, flav, lref)) {
3403 // [stack] LENGTH OBJ
3404 return false;
3405 }
3406
3407 if (!emitSetOrInitializeDestructuring(member, flav, lref)) {
3408 // [stack] LENGTH OBJ
3409 return false;
3410 }
3411
3412 idx += 1;
3413 }
3414
3415 if (!emit1(JSOp::Swap)) {
3416 // [stack] OBJ LENGTH
3417 return false;
3418 }
3419
3420 if (!emit1(JSOp::Pop)) {
3421 // [stack] OBJ
3422 return false;
3423 }
3424
3425 if (!ifArrayOptimizable->emitElse()) {
3426 // [stack] OBJ OBJ
3427 return false;
3428 }
3429 }
3430
3431 if (!emitIterator(SelfHostedIter::Deny)) {
3432 // [stack] ... OBJ NEXT ITER
3433 return false;
3434 }
3435
3436 // For an empty pattern [], call IteratorClose unconditionally. Nothing
3437 // else needs to be done.
3438 if (!pattern->head()) {
3439 if (!emit1(JSOp::Swap)) {
3440 // [stack] ... OBJ ITER NEXT
3441 return false;
3442 }
3443 if (!emit1(JSOp::Pop)) {
3444 // [stack] ... OBJ ITER
3445 return false;
3446 }
3447
3448 if (!emitIteratorCloseInInnermostScope()) {
3449 // [stack] ... OBJ
3450 return false;
3451 }
3452
3453 if (ifArrayOptimizable.isSome()) {
3454 if (!ifArrayOptimizable->emitEnd()) {
3455 // [stack] OBJ
3456 return false;
3457 }
3458 }
3459
3460 return true;
3461 }
3462
3463 // Push an initial FALSE value for DONE.
3464 if (!emit1(JSOp::False)) {
3465 // [stack] ... OBJ NEXT ITER FALSE
3466 return false;
3467 }
3468
3469 // TryNoteKind::Destructuring expects the iterator and the done value
3470 // to be the second to top and the top of the stack, respectively.
3471 // IteratorClose is called upon exception only if done is false.
3472 int32_t tryNoteDepth = bytecodeSection().stackDepth();
3473
3474 for (ParseNode* member : pattern->contents()) {
3475 bool isFirst = member == pattern->head();
3476 DebugOnly<bool> hasNext = !!member->pn_next;
3477
3478 ParseNode* subpattern;
3479 if (member->isKind(ParseNodeKind::Spread)) {
3480 subpattern = member->as<UnaryNode>().kid();
3481
3482 MOZ_ASSERT(!subpattern->isKind(ParseNodeKind::AssignExpr));
3483 } else {
3484 subpattern = member;
3485 }
3486
3487 ParseNode* lhsPattern = subpattern;
3488 ParseNode* pndefault = nullptr;
3489 if (subpattern->isKind(ParseNodeKind::AssignExpr)) {
3490 lhsPattern = subpattern->as<AssignmentNode>().left();
3491 pndefault = subpattern->as<AssignmentNode>().right();
3492 }
3493
3494 // Spec requires LHS reference to be evaluated first.
3495 DestructuringLHSRef lref;
3496 bool isElision = lhsPattern->isKind(ParseNodeKind::Elision);
3497 if (!isElision) {
3498 auto emitLHSRef = [lhsPattern, flav, &lref](BytecodeEmitter* bce) {
3499 return bce->emitDestructuringLHSRef(lhsPattern, flav, lref);
3500 // [stack] ... OBJ NEXT ITER DONE LREF*
3501 };
3502 if (!wrapWithDestructuringTryNote(tryNoteDepth, emitLHSRef)) {
3503 return false;
3504 }
3505 }
3506
3507 // Number of stack slots emitted for the LHS reference.
3508 size_t emitted = lref.numReferenceSlots();
3509
3510 // Pick the DONE value to the top of the stack.
3511 if (emitted) {
3512 if (!emitPickN(emitted)) {
3513 // [stack] ... OBJ NEXT ITER LREF* DONE
3514 return false;
3515 }
3516 }
3517
3518 if (isFirst) {
3519 // If this element is the first, DONE is always FALSE, so pop it.
3520 //
3521 // Non-first elements should emit if-else depending on the
3522 // member pattern, below.
3523 if (!emit1(JSOp::Pop)) {
3524 // [stack] ... OBJ NEXT ITER LREF*
3525 return false;
3526 }
3527 }
3528
3529 if (member->isKind(ParseNodeKind::Spread)) {
3530 InternalIfEmitter ifThenElse(this);
3531 if (!isFirst) {
3532 // If spread is not the first element of the pattern,
3533 // iterator can already be completed.
3534 // [stack] ... OBJ NEXT ITER LREF* DONE
3535
3536 if (!ifThenElse.emitThenElse()) {
3537 // [stack] ... OBJ NEXT ITER LREF*
3538 return false;
3539 }
3540
3541 if (!emitUint32Operand(JSOp::NewArray, 0)) {
3542 // [stack] ... OBJ NEXT ITER LREF* ARRAY
3543 return false;
3544 }
3545 if (!ifThenElse.emitElse()) {
3546 // [stack] ... OBJ NEXT ITER LREF*
3547 return false;
3548 }
3549 }
3550
3551 // If iterator is not completed, create a new array with the rest
3552 // of the iterator.
3553 if (!emitDupAt(emitted + 1, 2)) {
3554 // [stack] ... OBJ NEXT ITER LREF* NEXT ITER
3555 return false;
3556 }
3557 if (!emitUint32Operand(JSOp::NewArray, 0)) {
3558 // [stack] ... OBJ NEXT ITER LREF* NEXT ITER ARRAY
3559 return false;
3560 }
3561 if (!emitNumberOp(0)) {
3562 // [stack] ... OBJ NEXT ITER LREF* NEXT ITER ARRAY INDEX
3563 return false;
3564 }
3565 if (!emitSpread(SelfHostedIter::Deny)) {
3566 // [stack] ... OBJ NEXT ITER LREF* ARRAY INDEX
3567 return false;
3568 }
3569 if (!emit1(JSOp::Pop)) {
3570 // [stack] ... OBJ NEXT ITER LREF* ARRAY
3571 return false;
3572 }
3573
3574 if (!isFirst) {
3575 if (!ifThenElse.emitEnd()) {
3576 return false;
3577 }
3578 MOZ_ASSERT(ifThenElse.pushed() == 1);
3579 }
3580
3581 // At this point the iterator is done. Unpick a TRUE value for DONE above
3582 // ITER.
3583 if (!emit1(JSOp::True)) {
3584 // [stack] ... OBJ NEXT ITER LREF* ARRAY TRUE
3585 return false;
3586 }
3587 if (!emitUnpickN(emitted + 1)) {
3588 // [stack] ... OBJ NEXT ITER TRUE LREF* ARRAY
3589 return false;
3590 }
3591
3592 auto emitAssignment = [lhsPattern, flav, &lref](BytecodeEmitter* bce) {
3593 return bce->emitSetOrInitializeDestructuring(lhsPattern, flav, lref);
3594 // [stack] ... OBJ NEXT ITER TRUE
3595 };
3596 if (!wrapWithDestructuringTryNote(tryNoteDepth, emitAssignment)) {
3597 return false;
3598 }
3599
3600 MOZ_ASSERT(!hasNext);
3601 break;
3602 }
3603
3604 InternalIfEmitter ifAlreadyDone(this);
3605 if (!isFirst) {
3606 // [stack] ... OBJ NEXT ITER LREF* DONE
3607
3608 if (!ifAlreadyDone.emitThenElse()) {
3609 // [stack] ... OBJ NEXT ITER LREF*
3610 return false;
3611 }
3612
3613 if (!emit1(JSOp::Undefined)) {
3614 // [stack] ... OBJ NEXT ITER LREF* UNDEF
3615 return false;
3616 }
3617 if (!emit1(JSOp::NopDestructuring)) {
3618 // [stack] ... OBJ NEXT ITER LREF* UNDEF
3619 return false;
3620 }
3621
3622 // The iterator is done. Unpick a TRUE value for DONE above ITER.
3623 if (!emit1(JSOp::True)) {
3624 // [stack] ... OBJ NEXT ITER LREF* UNDEF TRUE
3625 return false;
3626 }
3627 if (!emitUnpickN(emitted + 1)) {
3628 // [stack] ... OBJ NEXT ITER TRUE LREF* UNDEF
3629 return false;
3630 }
3631
3632 if (!ifAlreadyDone.emitElse()) {
3633 // [stack] ... OBJ NEXT ITER LREF*
3634 return false;
3635 }
3636 }
3637
3638 if (!emitDupAt(emitted + 1, 2)) {
3639 // [stack] ... OBJ NEXT ITER LREF* NEXT
3640 return false;
3641 }
3642 if (!emitIteratorNext(Some(pattern->pn_pos.begin))) {
3643 // [stack] ... OBJ NEXT ITER LREF* RESULT
3644 return false;
3645 }
3646 if (!emit1(JSOp::Dup)) {
3647 // [stack] ... OBJ NEXT ITER LREF* RESULT RESULT
3648 return false;
3649 }
3650 if (!emitAtomOp(JSOp::GetProp, TaggedParserAtomIndex::WellKnown::done())) {
3651 // [stack] ... OBJ NEXT ITER LREF* RESULT DONE
3652 return false;
3653 }
3654
3655 if (!emit1(JSOp::Dup)) {
3656 // [stack] ... OBJ NEXT ITER LREF* RESULT DONE DONE
3657 return false;
3658 }
3659 if (!emitUnpickN(emitted + 2)) {
3660 // [stack] ... OBJ NEXT ITER DONE LREF* RESULT DONE
3661 return false;
3662 }
3663
3664 InternalIfEmitter ifDone(this);
3665 if (!ifDone.emitThenElse()) {
3666 // [stack] ... OBJ NEXT ITER DONE LREF* RESULT
3667 return false;
3668 }
3669
3670 if (!emit1(JSOp::Pop)) {
3671 // [stack] ... OBJ NEXT ITER DONE LREF*
3672 return false;
3673 }
3674 if (!emit1(JSOp::Undefined)) {
3675 // [stack] ... OBJ NEXT ITER DONE LREF* UNDEF
3676 return false;
3677 }
3678 if (!emit1(JSOp::NopDestructuring)) {
3679 // [stack] ... OBJ NEXT ITER DONE LREF* UNDEF
3680 return false;
3681 }
3682
3683 if (!ifDone.emitElse()) {
3684 // [stack] ... OBJ NEXT ITER DONE LREF* RESULT
3685 return false;
3686 }
3687
3688 if (!emitAtomOp(JSOp::GetProp, TaggedParserAtomIndex::WellKnown::value())) {
3689 // [stack] ... OBJ NEXT ITER DONE LREF* VALUE
3690 return false;
3691 }
3692
3693 if (!ifDone.emitEnd()) {
3694 return false;
3695 }
3696 MOZ_ASSERT(ifDone.pushed() == 0);
3697
3698 if (!isFirst) {
3699 if (!ifAlreadyDone.emitEnd()) {
3700 return false;
3701 }
3702 MOZ_ASSERT(ifAlreadyDone.pushed() == 2);
3703 }
3704
3705 if (pndefault) {
3706 auto emitDefault = [pndefault, lhsPattern](BytecodeEmitter* bce) {
3707 return bce->emitDefault(pndefault, lhsPattern);
3708 // [stack] ... OBJ NEXT ITER DONE LREF* VALUE
3709 };
3710
3711 if (!wrapWithDestructuringTryNote(tryNoteDepth, emitDefault)) {
3712 return false;
3713 }
3714 }
3715
3716 if (!isElision) {
3717 auto emitAssignment = [lhsPattern, flav, &lref](BytecodeEmitter* bce) {
3718 return bce->emitSetOrInitializeDestructuring(lhsPattern, flav, lref);
3719 // [stack] ... OBJ NEXT ITER DONE
3720 };
3721
3722 if (!wrapWithDestructuringTryNote(tryNoteDepth, emitAssignment)) {
3723 return false;
3724 }
3725 } else {
3726 if (!emit1(JSOp::Pop)) {
3727 // [stack] ... OBJ NEXT ITER DONE
3728 return false;
3729 }
3730 }
3731 }
3732
3733 // The last DONE value is on top of the stack. If not DONE, call
3734 // IteratorClose.
3735 // [stack] ... OBJ NEXT ITER DONE
3736
3737 InternalIfEmitter ifDone(this);
3738 if (!ifDone.emitThenElse()) {
3739 // [stack] ... OBJ NEXT ITER
3740 return false;
3741 }
3742 if (!emitPopN(2)) {
3743 // [stack] ... OBJ
3744 return false;
3745 }
3746 if (!ifDone.emitElse()) {
3747 // [stack] ... OBJ NEXT ITER
3748 return false;
3749 }
3750 if (!emit1(JSOp::Swap)) {
3751 // [stack] ... OBJ ITER NEXT
3752 return false;
3753 }
3754 if (!emit1(JSOp::Pop)) {
3755 // [stack] ... OBJ ITER
3756 return false;
3757 }
3758 if (!emitIteratorCloseInInnermostScope()) {
3759 // [stack] ... OBJ
3760 return false;
3761 }
3762 if (!ifDone.emitEnd()) {
3763 return false;
3764 }
3765
3766 if (ifArrayOptimizable.isSome()) {
3767 if (!ifArrayOptimizable->emitEnd()) {
3768 // [stack] OBJ
3769 return false;
3770 }
3771 }
3772
3773 return true;
3774 }
3775
3776 bool BytecodeEmitter::emitComputedPropertyName(UnaryNode* computedPropName) {
3777 MOZ_ASSERT(computedPropName->isKind(ParseNodeKind::ComputedName));
3778 return emitTree(computedPropName->kid()) && emit1(JSOp::ToPropertyKey);
3779 }
3780
3781 bool BytecodeEmitter::emitDestructuringOpsObject(ListNode* pattern,
3782 DestructuringFlavor flav) {
3783 MOZ_ASSERT(pattern->isKind(ParseNodeKind::ObjectExpr));
3784
3785 // [stack] ... RHS
3786 MOZ_ASSERT(bytecodeSection().stackDepth() > 0);
3787
3788 if (!emit1(JSOp::CheckObjCoercible)) {
3789 // [stack] ... RHS
3790 return false;
3791 }
3792
3793 // To understand why we chose '4', please see the discussion on Bug 1948959.
3794 const uint8_t estimatedRestSize = 4;
3795
3796 bool needsRestPropertyExcludedSet =
3797 pattern->count() > 1 && pattern->last()->isKind(ParseNodeKind::Spread);
3798 if (needsRestPropertyExcludedSet) {
3799 if (!emitDestructuringObjRestExclusionSet(pattern, estimatedRestSize)) {
3800 // [stack] ... RHS SET
3801 return false;
3802 }
3803
3804 if (!emit1(JSOp::Swap)) {
3805 // [stack] ... SET RHS
3806 return false;
3807 }
3808 }
3809
3810 for (ParseNode* member : pattern->contents()) {
3811 ParseNode* subpattern;
3812 bool hasKeyOnStack = false;
3813 if (member->isKind(ParseNodeKind::MutateProto) ||
3814 member->isKind(ParseNodeKind::Spread)) {
3815 subpattern = member->as<UnaryNode>().kid();
3816
3817 MOZ_ASSERT_IF(member->isKind(ParseNodeKind::Spread),
3818 !subpattern->isKind(ParseNodeKind::AssignExpr));
3819 } else {
3820 MOZ_ASSERT(member->isKind(ParseNodeKind::PropertyDefinition) ||
3821 member->isKind(ParseNodeKind::Shorthand));
3822 subpattern = member->as<BinaryNode>().right();
3823
3824 // Computed property names are evaluated before the subpattern.
3825 ParseNode* key = member->as<BinaryNode>().left();
3826 if (key->isKind(ParseNodeKind::ComputedName)) {
3827 if (!emitComputedPropertyName(&key->as<UnaryNode>())) {
3828 // [stack] ... SET? RHS KEY
3829 return false;
3830 }
3831 hasKeyOnStack = true;
3832 }
3833 }
3834
3835 ParseNode* lhs = subpattern;
3836 ParseNode* pndefault = nullptr;
3837 if (subpattern->isKind(ParseNodeKind::AssignExpr)) {
3838 lhs = subpattern->as<AssignmentNode>().left();
3839 pndefault = subpattern->as<AssignmentNode>().right();
3840 }
3841
3842 // Spec requires LHS reference to be evaluated first.
3843 DestructuringLHSRef lref;
3844 if (!emitDestructuringLHSRef(lhs, flav, lref)) {
3845 // [stack] ... SET? RHS KEY? LREF*
3846 return false;
3847 }
3848
3849 // Number of stack slots emitted for the LHS reference.
3850 size_t emitted = lref.numReferenceSlots();
3851
3852 // Duplicate the value being destructured to use as a reference base.
3853 if (!emitDupAt(emitted + hasKeyOnStack)) {
3854 // [stack] ... SET? RHS KEY? LREF* RHS
3855 return false;
3856 }
3857
3858 if (member->isKind(ParseNodeKind::Spread)) {
3859 if (!updateSourceCoordNotes(member->pn_pos.begin)) {
3860 return false;
3861 }
3862
3863 if (!emit2(JSOp::NewInit, estimatedRestSize)) {
3864 // [stack] ... SET? RHS LREF* RHS TARGET
3865 return false;
3866 }
3867 if (!emit1(JSOp::Dup)) {
3868 // [stack] ... SET? RHS LREF* RHS TARGET TARGET
3869 return false;
3870 }
3871 if (!emit2(JSOp::Pick, 2)) {
3872 // [stack] ... SET? RHS LREF* TARGET TARGET RHS
3873 return false;
3874 }
3875
3876 if (needsRestPropertyExcludedSet) {
3877 if (!emit2(JSOp::Pick, emitted + 4)) {
3878 // [stack] ... RHS LREF* TARGET TARGET RHS SET
3879 return false;
3880 }
3881 }
3882
3883 CopyOption option = needsRestPropertyExcludedSet ? CopyOption::Filtered
3884 : CopyOption::Unfiltered;
3885 if (!emitCopyDataProperties(option)) {
3886 // [stack] ... RHS LREF* TARGET
3887 return false;
3888 }
3889
3890 // Destructure TARGET per this member's lhs.
3891 if (!emitSetOrInitializeDestructuring(lhs, flav, lref)) {
3892 // [stack] ... RHS
3893 return false;
3894 }
3895
3896 MOZ_ASSERT(member == pattern->last(), "Rest property is always last");
3897 break;
3898 }
3899
3900 // Now push the property value currently being matched, which is the value
3901 // of the current property name "label" on the left of a colon in the object
3902 // initialiser.
3903 if (member->isKind(ParseNodeKind::MutateProto)) {
3904 if (!emitAtomOp(JSOp::GetProp,
3905 TaggedParserAtomIndex::WellKnown::proto_())) {
3906 // [stack] ... SET? RHS LREF* PROP
3907 return false;
3908 }
3909 } else {
3910 MOZ_ASSERT(member->isKind(ParseNodeKind::PropertyDefinition) ||
3911 member->isKind(ParseNodeKind::Shorthand));
3912
3913 ParseNode* key = member->as<BinaryNode>().left();
3914 if (key->isKind(ParseNodeKind::ObjectPropertyName) ||
3915 key->isKind(ParseNodeKind::StringExpr)) {
3916 if (!emitAtomOp(JSOp::GetProp, key->as<NameNode>().atom())) {
3917 // [stack] ... SET? RHS LREF* PROP
3918 return false;
3919 }
3920 } else {
3921 if (key->isKind(ParseNodeKind::NumberExpr)) {
3922 if (!emitNumberOp(key->as<NumericLiteral>().value())) {
3923 // [stack]... SET? RHS LREF* RHS KEY
3924 return false;
3925 }
3926 } else {
3927 // Otherwise this is a computed property name. BigInt keys are parsed
3928 // as (synthetic) computed property names, too.
3929 MOZ_ASSERT(key->isKind(ParseNodeKind::ComputedName));
3930 MOZ_ASSERT(hasKeyOnStack);
3931
3932 if (!emit2(JSOp::Pick, emitted + 1)) {
3933 // [stack] ... SET? RHS LREF* RHS KEY
3934 return false;
3935 }
3936
3937 // Add the computed property key to the exclusion set.
3938 if (needsRestPropertyExcludedSet) {
3939 if (!emitDupAt(emitted + 3)) {
3940 // [stack] ... SET RHS LREF* RHS KEY SET
3941 return false;
3942 }
3943 if (!emitDupAt(1)) {
3944 // [stack] ... SET RHS LREF* RHS KEY SET KEY
3945 return false;
3946 }
3947 if (!emit1(JSOp::Undefined)) {
3948 // [stack] ... SET RHS LREF* RHS KEY SET KEY UNDEFINED
3949 return false;
3950 }
3951 if (!emit1(JSOp::InitElem)) {
3952 // [stack] ... SET RHS LREF* RHS KEY SET
3953 return false;
3954 }
3955 if (!emit1(JSOp::Pop)) {
3956 // [stack] ... SET RHS LREF* RHS KEY
3957 return false;
3958 }
3959 }
3960 }
3961
3962 // Get the property value.
3963 if (!emitElemOpBase(JSOp::GetElem)) {
3964 // [stack] ... SET? RHS LREF* PROP
3965 return false;
3966 }
3967 }
3968 }
3969
3970 if (pndefault) {
3971 if (!emitDefault(pndefault, lhs)) {
3972 // [stack] ... SET? RHS LREF* VALUE
3973 return false;
3974 }
3975 }
3976
3977 // Destructure PROP per this member's lhs.
3978 if (!emitSetOrInitializeDestructuring(lhs, flav, lref)) {
3979 // [stack] ... SET? RHS
3980 return false;
3981 }
3982 }
3983
3984 return true;
3985 }
3986
3987 static bool IsDestructuringRestExclusionSetObjLiteralCompatible(
3988 ListNode* pattern) {
3989 uint32_t propCount = 0;
3990 for (ParseNode* member : pattern->contents()) {
3991 if (member->isKind(ParseNodeKind::Spread)) {
3992 MOZ_ASSERT(!member->pn_next, "unexpected trailing element after spread");
3993 break;
3994 }
3995
3996 propCount++;
3997
3998 if (member->isKind(ParseNodeKind::MutateProto)) {
3999 continue;
4000 }
4001
4002 ParseNode* key = member->as<BinaryNode>().left();
4003 if (key->isKind(ParseNodeKind::ObjectPropertyName) ||
4004 key->isKind(ParseNodeKind::StringExpr)) {
4005 continue;
4006 }
4007
4008 // Number and BigInt keys aren't yet supported. Computed property names need
4009 // to be added dynamically.
4010 MOZ_ASSERT(key->isKind(ParseNodeKind::NumberExpr) ||
4011 key->isKind(ParseNodeKind::BigIntExpr) ||
4012 key->isKind(ParseNodeKind::ComputedName));
4013 return false;
4014 }
4015
4016 if (propCount > SharedPropMap::MaxPropsForNonDictionary) {
4017 // JSOp::NewObject cannot accept dictionary-mode objects.
4018 return false;
4019 }
4020
4021 return true;
4022 }
4023
4024 bool BytecodeEmitter::emitDestructuringObjRestExclusionSet(
4025 ListNode* pattern, uint8_t estimatedRestSize) {
4026 MOZ_ASSERT(pattern->isKind(ParseNodeKind::ObjectExpr));
4027 MOZ_ASSERT(pattern->last()->isKind(ParseNodeKind::Spread));
4028
4029 // See if we can use ObjLiteral to construct the exclusion set object.
4030 if (IsDestructuringRestExclusionSetObjLiteralCompatible(pattern)) {
4031 if (!emitDestructuringRestExclusionSetObjLiteral(pattern)) {
4032 // [stack] OBJ
4033 return false;
4034 }
4035 } else {
4036 // Take the slow but sure way and start off with a blank object.
4037 if (!emit2(JSOp::NewInit, estimatedRestSize)) {
4038 // [stack] OBJ
4039 return false;
4040 }
4041 }
4042
4043 for (ParseNode* member : pattern->contents()) {
4044 if (member->isKind(ParseNodeKind::Spread)) {
4045 MOZ_ASSERT(!member->pn_next, "unexpected trailing element after spread");
4046 break;
4047 }
4048
4049 TaggedParserAtomIndex pnatom;
4050 if (member->isKind(ParseNodeKind::MutateProto)) {
4051 pnatom = TaggedParserAtomIndex::WellKnown::proto_();
4052 } else {
4053 ParseNode* key = member->as<BinaryNode>().left();
4054 if (key->isKind(ParseNodeKind::ObjectPropertyName) ||
4055 key->isKind(ParseNodeKind::StringExpr)) {
4056 pnatom = key->as<NameNode>().atom();
4057 } else if (key->isKind(ParseNodeKind::NumberExpr)) {
4058 if (!emitNumberOp(key->as<NumericLiteral>().value())) {
4059 return false;
4060 }
4061 } else {
4062 // Otherwise this is a computed property name which needs to be added
4063 // dynamically. BigInt keys are parsed as (synthetic) computed property
4064 // names, too.
4065 MOZ_ASSERT(key->isKind(ParseNodeKind::ComputedName));
4066 continue;
4067 }
4068 }
4069
4070 // Initialize elements with |undefined|.
4071 if (!emit1(JSOp::Undefined)) {
4072 return false;
4073 }
4074
4075 if (!pnatom) {
4076 if (!emit1(JSOp::InitElem)) {
4077 return false;
4078 }
4079 } else {
4080 if (!emitAtomOp(JSOp::InitProp, pnatom)) {
4081 return false;
4082 }
4083 }
4084 }
4085
4086 return true;
4087 }
4088
4089 bool BytecodeEmitter::emitDestructuringOps(ListNode* pattern,
4090 DestructuringFlavor flav) {
4091 if (pattern->isKind(ParseNodeKind::ArrayExpr)) {
4092 return emitDestructuringOpsArray(pattern, flav);
4093 }
4094 return emitDestructuringOpsObject(pattern, flav);
4095 }
4096
4097 bool BytecodeEmitter::emitTemplateString(ListNode* templateString) {
4098 bool pushedString = false;
4099
4100 for (ParseNode* item : templateString->contents()) {
4101 bool isString = (item->getKind() == ParseNodeKind::StringExpr ||
4102 item->getKind() == ParseNodeKind::TemplateStringExpr);
4103
4104 // Skip empty strings. These are very common: a template string like
4105 // `${a}${b}` has three empty strings and without this optimization
4106 // we'd emit four JSOp::Add operations instead of just one.
4107 if (isString && item->as<NameNode>().atom() ==
4108 TaggedParserAtomIndex::WellKnown::empty()) {
4109 continue;
4110 }
4111
4112 if (!isString) {
4113 // We update source notes before emitting the expression
4114 if (!updateSourceCoordNotes(item->pn_pos.begin)) {
4115 return false;
4116 }
4117 }
4118
4119 if (!emitTree(item)) {
4120 return false;
4121 }
4122
4123 if (!isString) {
4124 // We need to convert the expression to a string
4125 if (!emit1(JSOp::ToString)) {
4126 return false;
4127 }
4128 }
4129
4130 if (pushedString) {
4131 // We've pushed two strings onto the stack. Add them together, leaving
4132 // just one.
4133 if (!emit1(JSOp::Add)) {
4134 return false;
4135 }
4136 } else {
4137 pushedString = true;
4138 }
4139 }
4140
4141 if (!pushedString) {
4142 // All strings were empty, this can happen for something like `${""}`.
4143 // Just push an empty string.
4144 if (!emitStringOp(JSOp::String,
4145 TaggedParserAtomIndex::WellKnown::empty())) {
4146 return false;
4147 }
4148 }
4149
4150 return true;
4151 }
4152
4153 bool BytecodeEmitter::emitDeclarationList(ListNode* declList) {
4154 for (ParseNode* decl : declList->contents()) {
4155 ParseNode* pattern;
4156 ParseNode* initializer;
4157 if (decl->isKind(ParseNodeKind::Name)) {
4158 pattern = decl;
4159 initializer = nullptr;
4160 } else {
4161 AssignmentNode* assignNode = &decl->as<AssignmentNode>();
4162 pattern = assignNode->left();
4163 initializer = assignNode->right();
4164 }
4165
4166 if (pattern->isKind(ParseNodeKind::Name)) {
4167 // initializer can be null here.
4168 if (!emitSingleDeclaration(declList, &pattern->as<NameNode>(),
4169 initializer)) {
4170 return false;
4171 }
4172 } else {
4173 MOZ_ASSERT(pattern->isKind(ParseNodeKind::ArrayExpr) ||
4174 pattern->isKind(ParseNodeKind::ObjectExpr));
4175 MOZ_ASSERT(initializer != nullptr);
4176
4177 if (!updateSourceCoordNotes(initializer->pn_pos.begin)) {
4178 return false;
4179 }
4180 if (!markStepBreakpoint()) {
4181 return false;
4182 }
4183 if (!emitTree(initializer)) {
4184 return false;
4185 }
4186
4187 if (!emitDestructuringOps(&pattern->as<ListNode>(),
4188 DestructuringFlavor::Declaration)) {
4189 return false;
4190 }
4191
4192 if (!emit1(JSOp::Pop)) {
4193 return false;
4194 }
4195 }
4196 }
4197 return true;
4198 }
4199
4200 bool BytecodeEmitter::emitSingleDeclaration(ListNode* declList, NameNode* decl,
4201 ParseNode* initializer) {
4202 MOZ_ASSERT(decl->isKind(ParseNodeKind::Name));
4203
4204 // Nothing to do for initializer-less 'var' declarations, as there's no TDZ.
4205 if (!initializer && declList->isKind(ParseNodeKind::VarStmt)) {
4206 return true;
4207 }
4208
4209 auto nameAtom = decl->name();
4210 NameOpEmitter noe(this, nameAtom, NameOpEmitter::Kind::Initialize);
4211 if (!noe.prepareForRhs()) {
4212 // [stack] ENV?
4213 return false;
4214 }
4215 if (!initializer) {
4216 // Lexical declarations are initialized to undefined without an
4217 // initializer.
4218 MOZ_ASSERT(declList->isKind(ParseNodeKind::LetDecl),
4219 "var declarations without initializers handled above, "
4220 "and const declarations must have initializers");
4221 if (!emit1(JSOp::Undefined)) {
4222 // [stack] ENV? UNDEF
4223 return false;
4224 }
4225 } else {
4226 MOZ_ASSERT(initializer);
4227
4228 if (!updateSourceCoordNotes(initializer->pn_pos.begin)) {
4229 return false;
4230 }
4231 if (!markStepBreakpoint()) {
4232 return false;
4233 }
4234 if (!emitInitializer(initializer, decl)) {
4235 // [stack] ENV? V
4236 return false;
4237 }
4238 }
4239
4240 #ifdef ENABLE_EXPLICIT_RESOURCE_MANAGEMENT
4241 if (declList->isKind(ParseNodeKind::UsingDecl)) {
4242 if (!innermostEmitterScope()->prepareForDisposableAssignment(
4243 UsingHint::Sync)) {
4244 // [stack] ENV? V
4245 return false;
4246 }
4247 } else if (declList->isKind(ParseNodeKind::AwaitUsingDecl)) {
4248 if (!innermostEmitterScope()->prepareForDisposableAssignment(
4249 UsingHint::Async)) {
4250 // [stack] ENV? V
4251 return false;
4252 }
4253 }
4254 #endif
4255
4256 if (!noe.emitAssignment()) {
4257 // [stack] V
4258 return false;
4259 }
4260
4261 if (!emit1(JSOp::Pop)) {
4262 // [stack]
4263 return false;
4264 }
4265
4266 return true;
4267 }
4268
4269 bool BytecodeEmitter::emitAssignmentRhs(
4270 ParseNode* rhs, TaggedParserAtomIndex anonFunctionName) {
4271 if (rhs->isDirectRHSAnonFunction()) {
4272 if (anonFunctionName) {
4273 return emitAnonymousFunctionWithName(rhs, anonFunctionName);
4274 }
4275 return emitAnonymousFunctionWithComputedName(rhs, FunctionPrefixKind::None);
4276 }
4277 return emitTree(rhs);
4278 }
4279
4280 // The RHS value to assign is already on the stack, i.e., the next enumeration
4281 // value in a for-in or for-of loop. Offset is the location in the stack of the
4282 // already-emitted rhs. If we emitted a JSOp::BindUnqualifiedName or
4283 // JSOp::BindUnqualifiedGName, then the scope is on the top of the stack and we
4284 // need to dig one deeper to get the right RHS value.
4285 bool BytecodeEmitter::emitAssignmentRhs(uint8_t offset) {
4286 if (offset != 1) {
4287 return emitPickN(offset - 1);
4288 }
4289
4290 return true;
4291 }
4292
4293 static inline JSOp CompoundAssignmentParseNodeKindToJSOp(ParseNodeKind pnk) {
4294 switch (pnk) {
4295 case ParseNodeKind::InitExpr:
4296 return JSOp::Nop;
4297 case ParseNodeKind::AssignExpr:
4298 return JSOp::Nop;
4299 case ParseNodeKind::AddAssignExpr:
4300 return JSOp::Add;
4301 case ParseNodeKind::SubAssignExpr:
4302 return JSOp::Sub;
4303 case ParseNodeKind::BitOrAssignExpr:
4304 return JSOp::BitOr;
4305 case ParseNodeKind::BitXorAssignExpr:
4306 return JSOp::BitXor;
4307 case ParseNodeKind::BitAndAssignExpr:
4308 return JSOp::BitAnd;
4309 case ParseNodeKind::LshAssignExpr:
4310 return JSOp::Lsh;
4311 case ParseNodeKind::RshAssignExpr:
4312 return JSOp::Rsh;
4313 case ParseNodeKind::UrshAssignExpr:
4314 return JSOp::Ursh;
4315 case ParseNodeKind::MulAssignExpr:
4316 return JSOp::Mul;
4317 case ParseNodeKind::DivAssignExpr:
4318 return JSOp::Div;
4319 case ParseNodeKind::ModAssignExpr:
4320 return JSOp::Mod;
4321 case ParseNodeKind::PowAssignExpr:
4322 return JSOp::Pow;
4323 case ParseNodeKind::CoalesceAssignExpr:
4324 case ParseNodeKind::OrAssignExpr:
4325 case ParseNodeKind::AndAssignExpr:
4326 // Short-circuit assignment operators are handled elsewhere.
4327 [[fallthrough]];
4328 default:
4329 MOZ_CRASH("unexpected compound assignment op");
4330 }
4331 }
4332
4333 bool BytecodeEmitter::emitAssignmentOrInit(ParseNodeKind kind, ParseNode* lhs,
4334 ParseNode* rhs) {
4335 JSOp compoundOp = CompoundAssignmentParseNodeKindToJSOp(kind);
4336 bool isCompound = compoundOp != JSOp::Nop;
4337 bool isInit = kind == ParseNodeKind::InitExpr;
4338
4339 // We estimate the number of properties this could create
4340 // if used as constructor merely by counting this.foo = assignment
4341 // or init expressions;
4342 //
4343 // This currently doesn't handle this[x] = foo;
4344 if (isInit || kind == ParseNodeKind::AssignExpr) {
4345 if (lhs->isKind(ParseNodeKind::DotExpr)) {
4346 if (lhs->as<PropertyAccess>().expression().isKind(
4347 ParseNodeKind::ThisExpr)) {
4348 propertyAdditionEstimate++;
4349 }
4350 }
4351 }
4352
4353 MOZ_ASSERT_IF(isInit, lhs->isKind(ParseNodeKind::DotExpr) ||
4354 lhs->isKind(ParseNodeKind::ElemExpr) ||
4355 lhs->isKind(ParseNodeKind::PrivateMemberExpr));
4356
4357 // |name| is used within NameOpEmitter, so its lifetime must surpass |noe|.
4358 TaggedParserAtomIndex name;
4359
4360 Maybe<NameOpEmitter> noe;
4361 Maybe<PropOpEmitter> poe;
4362 Maybe<ElemOpEmitter> eoe;
4363 Maybe<PrivateOpEmitter> xoe;
4364
4365 // Deal with non-name assignments.
4366 uint8_t offset = 1;
4367
4368 // Purpose of anonFunctionName:
4369 //
4370 // In normal name assignments (`f = function(){}`), an anonymous function gets
4371 // an inferred name based on the left-hand side name node.
4372 //
4373 // In normal property assignments (`obj.x = function(){}`), the anonymous
4374 // function does not have a computed name, and rhs->isDirectRHSAnonFunction()
4375 // will be false (and anonFunctionName will not be used). However, in field
4376 // initializers (`class C { x = function(){} }`), field initialization is
4377 // implemented via a property or elem assignment (where we are now), and
4378 // rhs->isDirectRHSAnonFunction() is set - so we'll assign the name of the
4379 // function.
4380 TaggedParserAtomIndex anonFunctionName;
4381
4382 switch (lhs->getKind()) {
4383 case ParseNodeKind::Name: {
4384 name = lhs->as<NameNode>().name();
4385 anonFunctionName = name;
4386 noe.emplace(this, name,
4387 isCompound ? NameOpEmitter::Kind::CompoundAssignment
4388 : NameOpEmitter::Kind::SimpleAssignment);
4389 break;
4390 }
4391 case ParseNodeKind::ArgumentsLength:
4392 case ParseNodeKind::DotExpr: {
4393 PropertyAccess* prop = &lhs->as<PropertyAccess>();
4394 bool isSuper = prop->isSuper();
4395 poe.emplace(this,
4396 isCompound ? PropOpEmitter::Kind::CompoundAssignment
4397 : isInit ? PropOpEmitter::Kind::PropInit
4398 : PropOpEmitter::Kind::SimpleAssignment,
4399 isSuper ? PropOpEmitter::ObjKind::Super
4400 : PropOpEmitter::ObjKind::Other);
4401 if (!poe->prepareForObj()) {
4402 return false;
4403 }
4404 anonFunctionName = prop->name();
4405 if (isSuper) {
4406 UnaryNode* base = &prop->expression().as<UnaryNode>();
4407 if (!emitGetThisForSuperBase(base)) {
4408 // [stack] THIS SUPERBASE
4409 return false;
4410 }
4411 // SUPERBASE is pushed onto THIS later in poe->emitGet below.
4412 offset += 2;
4413 } else {
4414 if (!emitTree(&prop->expression())) {
4415 // [stack] OBJ
4416 return false;
4417 }
4418 offset += 1;
4419 }
4420 break;
4421 }
4422 case ParseNodeKind::ElemExpr: {
4423 PropertyByValue* elem = &lhs->as<PropertyByValue>();
4424 bool isSuper = elem->isSuper();
4425 MOZ_ASSERT(!elem->key().isKind(ParseNodeKind::PrivateName));
4426 eoe.emplace(this,
4427 isCompound ? ElemOpEmitter::Kind::CompoundAssignment
4428 : isInit ? ElemOpEmitter::Kind::PropInit
4429 : ElemOpEmitter::Kind::SimpleAssignment,
4430 isSuper ? ElemOpEmitter::ObjKind::Super
4431 : ElemOpEmitter::ObjKind::Other);
4432 if (!emitElemObjAndKey(elem, *eoe)) {
4433 // [stack] # if Super
4434 // [stack] THIS KEY
4435 // [stack] # otherwise
4436 // [stack] OBJ KEY
4437 return false;
4438 }
4439 if (isSuper) {
4440 // SUPERBASE is pushed onto KEY in eoe->emitGet below.
4441 offset += 3;
4442 } else {
4443 offset += 2;
4444 }
4445 break;
4446 }
4447 case ParseNodeKind::PrivateMemberExpr: {
4448 PrivateMemberAccess* privateExpr = &lhs->as<PrivateMemberAccess>();
4449 xoe.emplace(this,
4450 isCompound ? PrivateOpEmitter::Kind::CompoundAssignment
4451 : isInit ? PrivateOpEmitter::Kind::PropInit
4452 : PrivateOpEmitter::Kind::SimpleAssignment,
4453 privateExpr->privateName().name());
4454 if (!emitTree(&privateExpr->expression())) {
4455 // [stack] OBJ
4456 return false;
4457 }
4458 if (!xoe->emitReference()) {
4459 // [stack] OBJ KEY
4460 return false;
4461 }
4462 offset += xoe->numReferenceSlots();
4463 break;
4464 }
4465 case ParseNodeKind::ArrayExpr:
4466 case ParseNodeKind::ObjectExpr:
4467 break;
4468 case ParseNodeKind::CallExpr:
4469 if (!emitTree(lhs)) {
4470 return false;
4471 }
4472
4473 // Assignment to function calls is forbidden, but we have to make the
4474 // call first. Now we can throw.
4475 if (!emit2(JSOp::ThrowMsg, uint8_t(ThrowMsgKind::AssignToCall))) {
4476 return false;
4477 }
4478
4479 // Rebalance the stack to placate stack-depth assertions.
4480 if (!emit1(JSOp::Pop)) {
4481 return false;
4482 }
4483 break;
4484 default:
4485 MOZ_ASSERT(0);
4486 }
4487
4488 if (isCompound) {
4489 MOZ_ASSERT(rhs);
4490 switch (lhs->getKind()) {
4491 case ParseNodeKind::ArgumentsLength:
4492 case ParseNodeKind::DotExpr: {
4493 PropertyAccess* prop = &lhs->as<PropertyAccess>();
4494 if (!poe->emitGet(prop->key().atom())) {
4495 // [stack] # if Super
4496 // [stack] THIS SUPERBASE PROP
4497 // [stack] # otherwise
4498 // [stack] OBJ PROP
4499 return false;
4500 }
4501 break;
4502 }
4503 case ParseNodeKind::ElemExpr: {
4504 if (!eoe->emitGet()) {
4505 // [stack] KEY THIS OBJ ELEM
4506 return false;
4507 }
4508 break;
4509 }
4510 case ParseNodeKind::PrivateMemberExpr: {
4511 if (!xoe->emitGet()) {
4512 // [stack] OBJ KEY VALUE
4513 return false;
4514 }
4515 break;
4516 }
4517 case ParseNodeKind::CallExpr:
4518 // We just emitted a JSOp::ThrowMsg and popped the call's return
4519 // value. Push a random value to make sure the stack depth is
4520 // correct.
4521 if (!emit1(JSOp::Null)) {
4522 // [stack] NULL
4523 return false;
4524 }
4525 break;
4526 default:;
4527 }
4528 }
4529
4530 switch (lhs->getKind()) {
4531 case ParseNodeKind::Name:
4532 if (!noe->prepareForRhs()) {
4533 // [stack] ENV? VAL?
4534 return false;
4535 }
4536 offset += noe->emittedBindOp();
4537 break;
4538 case ParseNodeKind::ArgumentsLength:
4539 case ParseNodeKind::DotExpr:
4540 if (!poe->prepareForRhs()) {
4541 // [stack] # if Simple Assignment with Super
4542 // [stack] THIS SUPERBASE
4543 // [stack] # if Simple Assignment with other
4544 // [stack] OBJ
4545 // [stack] # if Compound Assignment with Super
4546 // [stack] THIS SUPERBASE PROP
4547 // [stack] # if Compound Assignment with other
4548 // [stack] OBJ PROP
4549 return false;
4550 }
4551 break;
4552 case ParseNodeKind::ElemExpr:
4553 if (!eoe->prepareForRhs()) {
4554 // [stack] # if Simple Assignment with Super
4555 // [stack] THIS KEY SUPERBASE
4556 // [stack] # if Simple Assignment with other
4557 // [stack] OBJ KEY
4558 // [stack] # if Compound Assignment with Super
4559 // [stack] THIS KEY SUPERBASE ELEM
4560 // [stack] # if Compound Assignment with other
4561 // [stack] OBJ KEY ELEM
4562 return false;
4563 }
4564 break;
4565 case ParseNodeKind::PrivateMemberExpr:
4566 // no stack adjustment needed
4567 break;
4568 default:
4569 break;
4570 }
4571
4572 if (rhs) {
4573 if (!emitAssignmentRhs(rhs, anonFunctionName)) {
4574 // [stack] ... VAL? RHS
4575 return false;
4576 }
4577 } else {
4578 // Assumption: Things with pre-emitted RHS values never need to be named.
4579 if (!emitAssignmentRhs(offset)) {
4580 // [stack] ... VAL? RHS
4581 return false;
4582 }
4583 }
4584
4585 /* If += etc., emit the binary operator with a hint for the decompiler. */
4586 if (isCompound) {
4587 if (!emit1(compoundOp)) {
4588 // [stack] ... VAL
4589 return false;
4590 }
4591 if (!emit1(JSOp::NopIsAssignOp)) {
4592 // [stack] ... VAL
4593 return false;
4594 }
4595 }
4596
4597 /* Finally, emit the specialized assignment bytecode. */
4598 switch (lhs->getKind()) {
4599 case ParseNodeKind::Name: {
4600 if (!noe->emitAssignment()) {
4601 // [stack] VAL
4602 return false;
4603 }
4604 break;
4605 }
4606 case ParseNodeKind::ArgumentsLength:
4607 case ParseNodeKind::DotExpr: {
4608 PropertyAccess* prop = &lhs->as<PropertyAccess>();
4609 if (!poe->emitAssignment(prop->key().atom())) {
4610 // [stack] VAL
4611 return false;
4612 }
4613 break;
4614 }
4615 case ParseNodeKind::CallExpr:
4616 // We threw above, so nothing to do here.
4617 break;
4618 case ParseNodeKind::ElemExpr: {
4619 if (!eoe->emitAssignment()) {
4620 // [stack] VAL
4621 return false;
4622 }
4623 break;
4624 }
4625 case ParseNodeKind::PrivateMemberExpr:
4626 if (!xoe->emitAssignment()) {
4627 // [stack] VAL
4628 return false;
4629 }
4630 break;
4631 case ParseNodeKind::ArrayExpr:
4632 case ParseNodeKind::ObjectExpr:
4633 if (!emitDestructuringOps(&lhs->as<ListNode>(),
4634 DestructuringFlavor::Assignment)) {
4635 return false;
4636 }
4637 break;
4638 default:
4639 MOZ_ASSERT(0);
4640 }
4641 return true;
4642 }
4643
4644 bool BytecodeEmitter::emitShortCircuitAssignment(AssignmentNode* node) {
4645 TDZCheckCache tdzCache(this);
4646
4647 JSOp op;
4648 switch (node->getKind()) {
4649 case ParseNodeKind::CoalesceAssignExpr:
4650 op = JSOp::Coalesce;
4651 break;
4652 case ParseNodeKind::OrAssignExpr:
4653 op = JSOp::Or;
4654 break;
4655 case ParseNodeKind::AndAssignExpr:
4656 op = JSOp::And;
4657 break;
4658 default:
4659 MOZ_CRASH("Unexpected ParseNodeKind");
4660 }
4661
4662 ParseNode* lhs = node->left();
4663 ParseNode* rhs = node->right();
4664
4665 // |name| is used within NameOpEmitter, so its lifetime must surpass |noe|.
4666 TaggedParserAtomIndex name;
4667
4668 // Select the appropriate emitter based on the left-hand side.
4669 Maybe<NameOpEmitter> noe;
4670 Maybe<PropOpEmitter> poe;
4671 Maybe<ElemOpEmitter> eoe;
4672 Maybe<PrivateOpEmitter> xoe;
4673
4674 int32_t depth = bytecodeSection().stackDepth();
4675
4676 // Number of values pushed onto the stack in addition to the lhs value.
4677 int32_t numPushed;
4678
4679 // Evaluate the left-hand side expression and compute any stack values needed
4680 // for the assignment.
4681 switch (lhs->getKind()) {
4682 case ParseNodeKind::Name: {
4683 name = lhs->as<NameNode>().name();
4684 noe.emplace(this, name, NameOpEmitter::Kind::CompoundAssignment);
4685
4686 if (!noe->prepareForRhs()) {
4687 // [stack] ENV? LHS
4688 return false;
4689 }
4690
4691 numPushed = noe->emittedBindOp();
4692 break;
4693 }
4694 case ParseNodeKind::ArgumentsLength:
4695 case ParseNodeKind::DotExpr: {
4696 PropertyAccess* prop = &lhs->as<PropertyAccess>();
4697 bool isSuper = prop->isSuper();
4698
4699 poe.emplace(this, PropOpEmitter::Kind::CompoundAssignment,
4700 isSuper ? PropOpEmitter::ObjKind::Super
4701 : PropOpEmitter::ObjKind::Other);
4702
4703 if (!poe->prepareForObj()) {
4704 return false;
4705 }
4706
4707 if (isSuper) {
4708 UnaryNode* base = &prop->expression().as<UnaryNode>();
4709 if (!emitGetThisForSuperBase(base)) {
4710 // [stack] THIS SUPERBASE
4711 return false;
4712 }
4713 } else {
4714 if (!emitTree(&prop->expression())) {
4715 // [stack] OBJ
4716 return false;
4717 }
4718 }
4719
4720 if (!poe->emitGet(prop->key().atom())) {
4721 // [stack] # if Super
4722 // [stack] THIS SUPERBASE LHS
4723 // [stack] # otherwise
4724 // [stack] OBJ LHS
4725 return false;
4726 }
4727
4728 if (!poe->prepareForRhs()) {
4729 // [stack] # if Super
4730 // [stack] THIS SUPERBASE LHS
4731 // [stack] # otherwise
4732 // [stack] OBJ LHS
4733 return false;
4734 }
4735
4736 numPushed = 1 + isSuper;
4737 break;
4738 }
4739
4740 case ParseNodeKind::ElemExpr: {
4741 PropertyByValue* elem = &lhs->as<PropertyByValue>();
4742 bool isSuper = elem->isSuper();
4743 MOZ_ASSERT(!elem->key().isKind(ParseNodeKind::PrivateName));
4744 eoe.emplace(this, ElemOpEmitter::Kind::CompoundAssignment,
4745 isSuper ? ElemOpEmitter::ObjKind::Super
4746 : ElemOpEmitter::ObjKind::Other);
4747
4748 if (!emitElemObjAndKey(elem, *eoe)) {
4749 // [stack] # if Super
4750 // [stack] THIS KEY
4751 // [stack] # otherwise
4752 // [stack] OBJ KEY
4753 return false;
4754 }
4755
4756 if (!eoe->emitGet()) {
4757 // [stack] # if Super
4758 // [stack] THIS KEY SUPERBASE LHS
4759 // [stack] # otherwise
4760 // [stack] OBJ KEY LHS
4761 return false;
4762 }
4763
4764 if (!eoe->prepareForRhs()) {
4765 // [stack] # if Super
4766 // [stack] THIS KEY SUPERBASE LHS
4767 // [stack] # otherwise
4768 // [stack] OBJ KEY LHS
4769 return false;
4770 }
4771
4772 numPushed = 2 + isSuper;
4773 break;
4774 }
4775
4776 case ParseNodeKind::PrivateMemberExpr: {
4777 PrivateMemberAccess* privateExpr = &lhs->as<PrivateMemberAccess>();
4778 xoe.emplace(this, PrivateOpEmitter::Kind::CompoundAssignment,
4779 privateExpr->privateName().name());
4780 if (!emitTree(&privateExpr->expression())) {
4781 // [stack] OBJ
4782 return false;
4783 }
4784 if (!xoe->emitReference()) {
4785 // [stack] OBJ NAME
4786 return false;
4787 }
4788 if (!xoe->emitGet()) {
4789 // [stack] OBJ NAME LHS
4790 return false;
4791 }
4792 numPushed = xoe->numReferenceSlots();
4793 break;
4794 }
4795
4796 default:
4797 MOZ_CRASH();
4798 }
4799
4800 MOZ_ASSERT(bytecodeSection().stackDepth() == depth + numPushed + 1);
4801
4802 // Test for the short-circuit condition.
4803 JumpList jump;
4804 if (!emitJump(op, &jump)) {
4805 // [stack] ... LHS
4806 return false;
4807 }
4808
4809 // The short-circuit condition wasn't fulfilled, pop the left-hand side value
4810 // which was kept on the stack.
4811 if (!emit1(JSOp::Pop)) {
4812 // [stack] ...
4813 return false;
4814 }
4815
4816 if (!emitAssignmentRhs(rhs, name)) {
4817 // [stack] ... RHS
4818 return false;
4819 }
4820
4821 // Perform the actual assignment.
4822 switch (lhs->getKind()) {
4823 case ParseNodeKind::Name: {
4824 if (!noe->emitAssignment()) {
4825 // [stack] RHS
4826 return false;
4827 }
4828 break;
4829 }
4830 case ParseNodeKind::ArgumentsLength:
4831 case ParseNodeKind::DotExpr: {
4832 PropertyAccess* prop = &lhs->as<PropertyAccess>();
4833
4834 if (!poe->emitAssignment(prop->key().atom())) {
4835 // [stack] RHS
4836 return false;
4837 }
4838 break;
4839 }
4840
4841 case ParseNodeKind::ElemExpr: {
4842 if (!eoe->emitAssignment()) {
4843 // [stack] RHS
4844 return false;
4845 }
4846 break;
4847 }
4848
4849 case ParseNodeKind::PrivateMemberExpr:
4850 if (!xoe->emitAssignment()) {
4851 // [stack] RHS
4852 return false;
4853 }
4854 break;
4855
4856 default:
4857 MOZ_CRASH();
4858 }
4859
4860 MOZ_ASSERT(bytecodeSection().stackDepth() == depth + 1);
4861
4862 // Join with the short-circuit jump and pop anything left on the stack.
4863 if (numPushed > 0) {
4864 JumpList jumpAroundPop;
4865 if (!emitJump(JSOp::Goto, &jumpAroundPop)) {
4866 // [stack] RHS
4867 return false;
4868 }
4869
4870 if (!emitJumpTargetAndPatch(jump)) {
4871 // [stack] ... LHS
4872 return false;
4873 }
4874
4875 // Reconstruct the stack depth after the jump.
4876 bytecodeSection().setStackDepth(depth + 1 + numPushed);
4877
4878 // Move the left-hand side value to the bottom and pop the rest.
4879 if (!emitUnpickN(numPushed)) {
4880 // [stack] LHS ...
4881 return false;
4882 }
4883 if (!emitPopN(numPushed)) {
4884 // [stack] LHS
4885 return false;
4886 }
4887
4888 if (!emitJumpTargetAndPatch(jumpAroundPop)) {
4889 // [stack] LHS | RHS
4890 return false;
4891 }
4892 } else {
4893 if (!emitJumpTargetAndPatch(jump)) {
4894 // [stack] LHS | RHS
4895 return false;
4896 }
4897 }
4898
4899 MOZ_ASSERT(bytecodeSection().stackDepth() == depth + 1);
4900
4901 return true;
4902 }
4903
4904 bool BytecodeEmitter::emitCallSiteObjectArray(ObjLiteralWriter& writer,
4905 ListNode* cookedOrRaw,
4906 ParseNode* head, uint32_t count) {
4907 DebugOnly<size_t> idx = 0;
4908 for (ParseNode* pn : cookedOrRaw->contentsFrom(head)) {
4909 MOZ_ASSERT(pn->isKind(ParseNodeKind::TemplateStringExpr) ||
4910 pn->isKind(ParseNodeKind::RawUndefinedExpr));
4911
4912 if (!emitObjLiteralValue(writer, pn)) {
4913 return false;
4914 }
4915 idx++;
4916 }
4917 MOZ_ASSERT(idx == count);
4918
4919 return true;
4920 }
4921
4922 bool BytecodeEmitter::emitCallSiteObject(CallSiteNode* callSiteObj) {
4923 constexpr JSOp op = JSOp::CallSiteObj;
4924
4925 // The first element of a call-site node is the raw-values list. Skip over it.
4926 ListNode* raw = callSiteObj->rawNodes();
4927 MOZ_ASSERT(raw->isKind(ParseNodeKind::ArrayExpr));
4928 ParseNode* head = callSiteObj->head()->pn_next;
4929
4930 uint32_t count = callSiteObj->count() - 1;
4931 MOZ_ASSERT(count == raw->count());
4932
4933 ObjLiteralWriter writer;
4934 writer.beginCallSiteObj(op);
4935 writer.beginDenseArrayElements();
4936
4937 // Write elements of the two arrays: the 'cooked' values followed by the
4938 // 'raw' values.
4939 MOZ_RELEASE_ASSERT(count < UINT32_MAX / 2,
4940 "Number of elements for both arrays must fit in uint32_t");
4941 if (!emitCallSiteObjectArray(writer, callSiteObj, head, count)) {
4942 return false;
4943 }
4944 if (!emitCallSiteObjectArray(writer, raw, raw->head(), count)) {
4945 return false;
4946 }
4947
4948 GCThingIndex cookedIndex;
4949 if (!addObjLiteralData(writer, &cookedIndex)) {
4950 return false;
4951 }
4952
4953 MOZ_ASSERT(sc->hasCallSiteObj());
4954
4955 return emitInternedObjectOp(cookedIndex, op);
4956 }
4957
4958 bool BytecodeEmitter::emitCatch(BinaryNode* catchClause) {
4959 // We must be nested under a try-finally statement.
4960 MOZ_ASSERT(innermostNestableControl->is<TryFinallyControl>());
4961
4962 ParseNode* param = catchClause->left();
4963 if (!param) {
4964 // Catch parameter was omitted; just discard the exception.
4965 if (!emit1(JSOp::Pop)) {
4966 return false;
4967 }
4968 } else {
4969 switch (param->getKind()) {
4970 case ParseNodeKind::ArrayExpr:
4971 case ParseNodeKind::ObjectExpr:
4972 if (!emitDestructuringOps(&param->as<ListNode>(),
4973 DestructuringFlavor::Declaration)) {
4974 return false;
4975 }
4976 if (!emit1(JSOp::Pop)) {
4977 return false;
4978 }
4979 break;
4980
4981 case ParseNodeKind::Name:
4982 if (!emitLexicalInitialization(&param->as<NameNode>())) {
4983 return false;
4984 }
4985 if (!emit1(JSOp::Pop)) {
4986 return false;
4987 }
4988 break;
4989
4990 default:
4991 MOZ_ASSERT(0);
4992 }
4993 }
4994
4995 /* Emit the catch body. */
4996 return emitTree(catchClause->right());
4997 }
4998
4999 // Using MOZ_NEVER_INLINE in here is a workaround for llvm.org/pr14047. See the
5000 // comment on EmitSwitch.
5001 MOZ_NEVER_INLINE bool BytecodeEmitter::emitTry(TryNode* tryNode) {
5002 LexicalScopeNode* catchScope = tryNode->catchScope();
5003 ParseNode* finallyNode = tryNode->finallyBlock();
5004
5005 TryEmitter::Kind kind;
5006 if (catchScope) {
5007 if (finallyNode) {
5008 kind = TryEmitter::Kind::TryCatchFinally;
5009 } else {
5010 kind = TryEmitter::Kind::TryCatch;
5011 }
5012 } else {
5013 MOZ_ASSERT(finallyNode);
5014 kind = TryEmitter::Kind::TryFinally;
5015 }
5016 TryEmitter tryCatch(this, kind, TryEmitter::ControlKind::Syntactic);
5017
5018 if (!tryCatch.emitTry()) {
5019 return false;
5020 }
5021
5022 if (!emitTree(tryNode->body())) {
5023 return false;
5024 }
5025
5026 // If this try has a catch block, emit it.
5027 if (catchScope) {
5028 // The emitted code for a catch block looks like:
5029 //
5030 // [pushlexicalenv] only if any local aliased
5031 // exception
5032 // setlocal 0; pop assign or possibly destructure exception
5033 // < catch block contents >
5034 // debugleaveblock
5035 // [poplexicalenv] only if any local aliased
5036 // if there is a finally block:
5037 // goto <finally>
5038 // [jump target for returning from finally]
5039 // goto <after finally>
5040 if (!tryCatch.emitCatch()) {
5041 return false;
5042 }
5043
5044 // Emit the lexical scope and catch body.
5045 if (!emitTree(catchScope)) {
5046 return false;
5047 }
5048 }
5049
5050 // Emit the finally handler, if there is one.
5051 if (finallyNode) {
5052 if (!tryCatch.emitFinally(Some(finallyNode->pn_pos.begin))) {
5053 return false;
5054 }
5055
5056 if (!emitTree(finallyNode)) {
5057 return false;
5058 }
5059 }
5060
5061 if (!tryCatch.emitEnd()) {
5062 return false;
5063 }
5064
5065 return true;
5066 }
5067
5068 [[nodiscard]] bool BytecodeEmitter::emitJumpToFinally(JumpList* jump,
5069 uint32_t idx) {
5070 // Push the continuation index.
5071 if (!emitNumberOp(idx)) {
5072 return false;
5073 }
5074
5075 // Push |exception_stack|.
5076 if (!emit1(JSOp::Null)) {
5077 return false;
5078 }
5079
5080 // Push |throwing|.
5081 if (!emit1(JSOp::False)) {
5082 return false;
5083 }
5084
5085 // Jump to the finally block.
5086 if (!emitJumpNoFallthrough(JSOp::Goto, jump)) {
5087 return false;
5088 }
5089
5090 return true;
5091 }
5092
5093 bool BytecodeEmitter::emitIf(TernaryNode* ifNode) {
5094 IfEmitter ifThenElse(this);
5095
5096 if (!ifThenElse.emitIf(Some(ifNode->kid1()->pn_pos.begin))) {
5097 return false;
5098 }
5099
5100 if_again:
5101 ParseNode* testNode = ifNode->kid1();
5102 auto conditionKind = IfEmitter::ConditionKind::Positive;
5103 if (testNode->isKind(ParseNodeKind::NotExpr)) {
5104 testNode = testNode->as<UnaryNode>().kid();
5105 conditionKind = IfEmitter::ConditionKind::Negative;
5106 }
5107
5108 if (!markStepBreakpoint()) {
5109 return false;
5110 }
5111
5112 // Emit code for the condition before pushing stmtInfo.
5113 // NOTE: NotExpr of testNode may be unwrapped, and in that case the negation
5114 // is handled by conditionKind.
5115 if (!emitTree(testNode)) {
5116 return false;
5117 }
5118
5119 ParseNode* elseNode = ifNode->kid3();
5120 if (elseNode) {
5121 if (!ifThenElse.emitThenElse(conditionKind)) {
5122 return false;
5123 }
5124 } else {
5125 if (!ifThenElse.emitThen(conditionKind)) {
5126 return false;
5127 }
5128 }
5129
5130 /* Emit code for the then part. */
5131 if (!emitTree(ifNode->kid2())) {
5132 return false;
5133 }
5134
5135 if (elseNode) {
5136 if (elseNode->isKind(ParseNodeKind::IfStmt)) {
5137 ifNode = &elseNode->as<TernaryNode>();
5138
5139 if (!ifThenElse.emitElseIf(Some(ifNode->kid1()->pn_pos.begin))) {
5140 return false;
5141 }
5142
5143 goto if_again;
5144 }
5145
5146 if (!ifThenElse.emitElse()) {
5147 return false;
5148 }
5149
5150 /* Emit code for the else part. */
5151 if (!emitTree(elseNode)) {
5152 return false;
5153 }
5154 }
5155
5156 if (!ifThenElse.emitEnd()) {
5157 return false;
5158 }
5159
5160 return true;
5161 }
5162
5163 bool BytecodeEmitter::emitHoistedFunctionsInList(ListNode* stmtList) {
5164 MOZ_ASSERT(stmtList->hasTopLevelFunctionDeclarations());
5165
5166 // We can call this multiple times for sloppy eval scopes.
5167 if (stmtList->emittedTopLevelFunctionDeclarations()) {
5168 return true;
5169 }
5170
5171 stmtList->setEmittedTopLevelFunctionDeclarations();
5172
5173 for (ParseNode* stmt : stmtList->contents()) {
5174 ParseNode* maybeFun = stmt;
5175
5176 if (!sc->strict()) {
5177 while (maybeFun->isKind(ParseNodeKind::LabelStmt)) {
5178 maybeFun = maybeFun->as<LabeledStatement>().statement();
5179 }
5180 }
5181
5182 if (maybeFun->is<FunctionNode>() &&
5183 maybeFun->as<FunctionNode>().functionIsHoisted()) {
5184 if (!emitTree(maybeFun)) {
5185 return false;
5186 }
5187 }
5188 }
5189
5190 return true;
5191 }
5192
5193 bool BytecodeEmitter::emitLexicalScopeBody(
5194 ParseNode* body, EmitLineNumberNote emitLineNote /* = EMIT_LINENOTE */) {
5195 if (body->isKind(ParseNodeKind::StatementList) &&
5196 body->as<ListNode>().hasTopLevelFunctionDeclarations()) {
5197 // This block contains function statements whose definitions are
5198 // hoisted to the top of the block. Emit these as a separate pass
5199 // before the rest of the block.
5200 if (!emitHoistedFunctionsInList(&body->as<ListNode>())) {
5201 return false;
5202 }
5203 }
5204
5205 // Line notes were updated by emitLexicalScope or emitScript.
5206 return emitTree(body, ValueUsage::WantValue, emitLineNote);
5207 }
5208
5209 // Using MOZ_NEVER_INLINE in here is a workaround for llvm.org/pr14047. See
5210 // the comment on emitSwitch.
5211 MOZ_NEVER_INLINE bool BytecodeEmitter::emitLexicalScope(
5212 LexicalScopeNode* lexicalScope) {
5213 LexicalScopeEmitter lse(this);
5214
5215 ParseNode* body = lexicalScope->scopeBody();
5216 if (lexicalScope->isEmptyScope()) {
5217 if (!lse.emitEmptyScope()) {
5218 return false;
5219 }
5220
5221 if (!emitLexicalScopeBody(body)) {
5222 return false;
5223 }
5224
5225 if (!lse.emitEnd()) {
5226 return false;
5227 }
5228
5229 return true;
5230 }
5231
5232 // We are about to emit some bytecode for what the spec calls "declaration
5233 // instantiation". Assign these instructions to the opening `{` of the
5234 // block. (Using the location of each declaration we're instantiating is
5235 // too weird when stepping in the debugger.)
5236 if (!ParseNodeRequiresSpecialLineNumberNotes(body)) {
5237 if (!updateSourceCoordNotes(lexicalScope->pn_pos.begin)) {
5238 return false;
5239 }
5240 }
5241
5242 ScopeKind kind;
5243 if (body->isKind(ParseNodeKind::Catch)) {
5244 BinaryNode* catchNode = &body->as<BinaryNode>();
5245 kind =
5246 (!catchNode->left() || catchNode->left()->isKind(ParseNodeKind::Name))
5247 ? ScopeKind::SimpleCatch
5248 : ScopeKind::Catch;
5249 } else {
5250 kind = lexicalScope->kind();
5251 }
5252
5253 #ifdef ENABLE_EXPLICIT_RESOURCE_MANAGEMENT
5254 BlockKind blockKind = BlockKind::Other;
5255 if (body->isKind(ParseNodeKind::ForStmt) &&
5256 body->as<ForNode>().head()->isKind(ParseNodeKind::ForOf)) {
5257 MOZ_ASSERT(kind == ScopeKind::Lexical);
5258 blockKind = BlockKind::ForOf;
5259 }
5260 #endif
5261
5262 if (!lse.emitScope(kind, lexicalScope->scopeBindings()
5263 #ifdef ENABLE_EXPLICIT_RESOURCE_MANAGEMENT
5264 ,
5265 blockKind
5266 #endif
5267 )) {
5268 return false;
5269 }
5270
5271 if (body->isKind(ParseNodeKind::ForStmt)) {
5272 // for loops need to emit JSOp::FreshenLexicalEnv/JSOp::RecreateLexicalEnv
5273 // if there are lexical declarations in the head. Signal this by passing a
5274 // non-nullptr lexical scope.
5275 if (!emitFor(&body->as<ForNode>(), &lse.emitterScope())) {
5276 return false;
5277 }
5278 } else {
5279 if (!emitLexicalScopeBody(body, SUPPRESS_LINENOTE)) {
5280 return false;
5281 }
5282 }
5283
5284 if (!lse.emitEnd()) {
5285 return false;
5286 }
5287 return true;
5288 }
5289
5290 bool BytecodeEmitter::emitWith(BinaryNode* withNode) {
5291 // Ensure that the column of the 'with' is set properly.
5292 if (!updateSourceCoordNotes(withNode->left()->pn_pos.begin)) {
5293 return false;
5294 }
5295
5296 if (!markStepBreakpoint()) {
5297 return false;
5298 }
5299
5300 if (!emitTree(withNode->left())) {
5301 return false;
5302 }
5303
5304 EmitterScope emitterScope(this);
5305 if (!emitterScope.enterWith(this)) {
5306 return false;
5307 }
5308
5309 if (!emitTree(withNode->right())) {
5310 return false;
5311 }
5312
5313 return emitterScope.leave(this);
5314 }
5315
5316 bool BytecodeEmitter::emitCopyDataProperties(CopyOption option) {
5317 DebugOnly<int32_t> depth = bytecodeSection().stackDepth();
5318
5319 uint32_t argc;
5320 if (option == CopyOption::Filtered) {
5321 MOZ_ASSERT(depth > 2);
5322 // [stack] TARGET SOURCE SET
5323 argc = 3;
5324
5325 if (!emitAtomOp(JSOp::GetIntrinsic,
5326 TaggedParserAtomIndex::WellKnown::CopyDataProperties())) {
5327 // [stack] TARGET SOURCE SET COPYDATAPROPERTIES
5328 return false;
5329 }
5330 } else {
5331 MOZ_ASSERT(depth > 1);
5332 // [stack] TARGET SOURCE
5333 argc = 2;
5334
5335 if (!emitAtomOp(
5336 JSOp::GetIntrinsic,
5337 TaggedParserAtomIndex::WellKnown::CopyDataPropertiesUnfiltered())) {
5338 // [stack] TARGET SOURCE COPYDATAPROPERTIES
5339 return false;
5340 }
5341 }
5342
5343 if (!emit1(JSOp::Undefined)) {
5344 // [stack] TARGET SOURCE SET? COPYDATAPROPERTIES
5345 // UNDEFINED
5346 return false;
5347 }
5348 if (!emit2(JSOp::Pick, argc + 1)) {
5349 // [stack] SOURCE SET? COPYDATAPROPERTIES UNDEFINED
5350 // TARGET
5351 return false;
5352 }
5353 if (!emit2(JSOp::Pick, argc + 1)) {
5354 // [stack] SET? COPYDATAPROPERTIES UNDEFINED TARGET
5355 // SOURCE
5356 return false;
5357 }
5358 if (option == CopyOption::Filtered) {
5359 if (!emit2(JSOp::Pick, argc + 1)) {
5360 // [stack] COPYDATAPROPERTIES UNDEFINED TARGET SOURCE SET
5361 return false;
5362 }
5363 }
5364 // Callee is always self-hosted instrinsic, and cannot be content function.
5365 if (!emitCall(JSOp::CallIgnoresRv, argc)) {
5366 // [stack] IGNORED
5367 return false;
5368 }
5369
5370 if (!emit1(JSOp::Pop)) {
5371 // [stack]
5372 return false;
5373 }
5374
5375 MOZ_ASSERT(depth - int(argc) == bytecodeSection().stackDepth());
5376 return true;
5377 }
5378
5379 bool BytecodeEmitter::emitBigIntOp(BigIntLiteral* bigint) {
5380 GCThingIndex index;
5381 if (!perScriptData().gcThingList().append(bigint, &index)) {
5382 return false;
5383 }
5384 return emitGCIndexOp(JSOp::BigInt, index);
5385 }
5386
5387 bool BytecodeEmitter::emitIterable(ParseNode* value,
5388 SelfHostedIter selfHostedIter,
5389 IteratorKind iterKind) {
5390 MOZ_ASSERT(getSelfHostedIterFor(value) == selfHostedIter);
5391
5392 if (!emitTree(value)) {
5393 // [stack] ITERABLE
5394 return false;
5395 }
5396
5397 switch (selfHostedIter) {
5398 case SelfHostedIter::Deny:
5399 case SelfHostedIter::AllowContent:
5400 // [stack] ITERABLE
5401 return true;
5402
5403 case SelfHostedIter::AllowContentWith: {
5404 // This is the following case:
5405 //
5406 // for (const nextValue of allowContentIterWith(items, usingIterator)) {
5407 //
5408 // `items` is emitted by `emitTree(value)` above, and the result is on the
5409 // stack as ITERABLE.
5410 // `usingIterator` is the value of `items[Symbol.iterator]`, that's
5411 // already retrieved.
5412 ListNode* argsList = value->as<CallNode>().args();
5413 MOZ_ASSERT_IF(iterKind == IteratorKind::Sync, argsList->count() == 2);
5414 MOZ_ASSERT_IF(iterKind == IteratorKind::Async, argsList->count() == 3);
5415
5416 if (!emitTree(argsList->head()->pn_next)) {
5417 // [stack] ITERABLE ITERFN
5418 return false;
5419 }
5420
5421 // Async iterator has two possible iterators: An async iterator and a sync
5422 // iterator.
5423 if (iterKind == IteratorKind::Async) {
5424 if (!emitTree(argsList->head()->pn_next->pn_next)) {
5425 // [stack] ITERABLE ASYNC_ITERFN SYNC_ITERFN
5426 return false;
5427 }
5428 }
5429
5430 // [stack] ITERABLE ASYNC_ITERFN? SYNC_ITERFN
5431 return true;
5432 }
5433
5434 case SelfHostedIter::AllowContentWithNext: {
5435 // This is the following case:
5436 //
5437 // for (const nextValue of allowContentIterWithNext(iterator, next)) {
5438 //
5439 // `iterator` is emitted by `emitTree(value)` above, and the result is on
5440 // the stack as ITER.
5441 // `next` is the value of `iterator.next`, that's already retrieved.
5442 ListNode* argsList = value->as<CallNode>().args();
5443 MOZ_ASSERT(argsList->count() == 2);
5444
5445 if (!emitTree(argsList->head()->pn_next)) {
5446 // [stack] ITER NEXT
5447 return false;
5448 }
5449
5450 if (!emit1(JSOp::Swap)) {
5451 // [stack] NEXT ITER
5452 return false;
5453 }
5454
5455 // [stack] NEXT ITER
5456 return true;
5457 }
5458 }
5459
5460 MOZ_CRASH("invalid self-hosted iteration kind");
5461 }
5462
5463 bool BytecodeEmitter::emitIterator(SelfHostedIter selfHostedIter) {
5464 MOZ_ASSERT(selfHostedIter != SelfHostedIter::Deny ||
5465 emitterMode != BytecodeEmitter::SelfHosting,
5466 "[Symbol.iterator]() call is prohibited in self-hosted code "
5467 "because it can run user-modifiable iteration code");
5468
5469 if (selfHostedIter == SelfHostedIter::AllowContentWithNext) {
5470 // [stack] NEXT ITER
5471
5472 // Nothing to do, stack already contains the iterator and its `next` method.
5473 return true;
5474 }
5475
5476 if (selfHostedIter != SelfHostedIter::AllowContentWith) {
5477 // [stack] OBJ
5478
5479 // Convert iterable to iterator.
5480 if (!emit1(JSOp::Dup)) {
5481 // [stack] OBJ OBJ
5482 return false;
5483 }
5484 if (!emit2(JSOp::Symbol, uint8_t(JS::SymbolCode::iterator))) {
5485 // [stack] OBJ OBJ @@ITERATOR
5486 return false;
5487 }
5488 if (!emitElemOpBase(JSOp::GetElem)) {
5489 // [stack] OBJ ITERFN
5490 return false;
5491 }
5492 }
5493
5494 if (!emit1(JSOp::Swap)) {
5495 // [stack] ITERFN OBJ
5496 return false;
5497 }
5498 if (!emitCall(getIterCallOp(JSOp::CallIter, selfHostedIter), 0)) {
5499 // [stack] ITER
5500 return false;
5501 }
5502 if (!emitCheckIsObj(CheckIsObjectKind::GetIterator)) {
5503 // [stack] ITER
5504 return false;
5505 }
5506 if (!emit1(JSOp::Dup)) {
5507 // [stack] ITER ITER
5508 return false;
5509 }
5510 if (!emitAtomOp(JSOp::GetProp, TaggedParserAtomIndex::WellKnown::next())) {
5511 // [stack] ITER NEXT
5512 return false;
5513 }
5514 if (!emit1(JSOp::Swap)) {
5515 // [stack] NEXT ITER
5516 return false;
5517 }
5518 return true;
5519 }
5520
5521 bool BytecodeEmitter::emitAsyncIterator(SelfHostedIter selfHostedIter) {
5522 MOZ_ASSERT(selfHostedIter != SelfHostedIter::AllowContentWithNext);
5523 MOZ_ASSERT(selfHostedIter != SelfHostedIter::Deny ||
5524 emitterMode != BytecodeEmitter::SelfHosting,
5525 "[Symbol.asyncIterator]() call is prohibited in self-hosted code "
5526 "because it can run user-modifiable iteration code");
5527
5528 if (selfHostedIter != SelfHostedIter::AllowContentWith) {
5529 // [stack] OBJ
5530
5531 // Convert iterable to iterator.
5532 if (!emit1(JSOp::Dup)) {
5533 // [stack] OBJ OBJ
5534 return false;
5535 }
5536 if (!emit2(JSOp::Symbol, uint8_t(JS::SymbolCode::asyncIterator))) {
5537 // [stack] OBJ OBJ @@ASYNCITERATOR
5538 return false;
5539 }
5540 if (!emitElemOpBase(JSOp::GetElem)) {
5541 // [stack] OBJ ASYNC_ITERFN
5542 return false;
5543 }
5544 } else {
5545 // [stack] OBJ ASYNC_ITERFN SYNC_ITERFN
5546
5547 if (!emitElemOpBase(JSOp::Swap)) {
5548 // [stack] OBJ SYNC_ITERFN ASYNC_ITERFN
5549 return false;
5550 }
5551 }
5552
5553 InternalIfEmitter ifAsyncIterIsUndefined(this);
5554 if (!emit1(JSOp::IsNullOrUndefined)) {
5555 // [stack] OBJ SYNC_ITERFN? ASYNC_ITERFN NULL-OR-UNDEF
5556 return false;
5557 }
5558 if (!ifAsyncIterIsUndefined.emitThenElse()) {
5559 // [stack] OBJ SYNC_ITERFN? ASYNC_ITERFN
5560 return false;
5561 }
5562
5563 if (!emit1(JSOp::Pop)) {
5564 // [stack] OBJ SYNC_ITERFN?
5565 return false;
5566 }
5567
5568 if (selfHostedIter != SelfHostedIter::AllowContentWith) {
5569 if (!emit1(JSOp::Dup)) {
5570 // [stack] OBJ OBJ
5571 return false;
5572 }
5573 if (!emit2(JSOp::Symbol, uint8_t(JS::SymbolCode::iterator))) {
5574 // [stack] OBJ OBJ @@ITERATOR
5575 return false;
5576 }
5577 if (!emitElemOpBase(JSOp::GetElem)) {
5578 // [stack] OBJ SYNC_ITERFN
5579 return false;
5580 }
5581 } else {
5582 // [stack] OBJ SYNC_ITERFN
5583 }
5584
5585 if (!emit1(JSOp::Swap)) {
5586 // [stack] SYNC_ITERFN OBJ
5587 return false;
5588 }
5589 if (!emitCall(getIterCallOp(JSOp::CallIter, selfHostedIter), 0)) {
5590 // [stack] ITER
5591 return false;
5592 }
5593 if (!emitCheckIsObj(CheckIsObjectKind::GetIterator)) {
5594 // [stack] ITER
5595 return false;
5596 }
5597
5598 if (!emit1(JSOp::Dup)) {
5599 // [stack] ITER ITER
5600 return false;
5601 }
5602 if (!emitAtomOp(JSOp::GetProp, TaggedParserAtomIndex::WellKnown::next())) {
5603 // [stack] ITER SYNCNEXT
5604 return false;
5605 }
5606
5607 if (!emit1(JSOp::ToAsyncIter)) {
5608 // [stack] ITER
5609 return false;
5610 }
5611
5612 if (!ifAsyncIterIsUndefined.emitElse()) {
5613 // [stack] OBJ SYNC_ITERFN? ASYNC_ITERFN
5614 return false;
5615 }
5616
5617 if (selfHostedIter == SelfHostedIter::AllowContentWith) {
5618 if (!emit1(JSOp::Swap)) {
5619 // [stack] OBJ ASYNC_ITERFN SYNC_ITERFN
5620 return false;
5621 }
5622 if (!emit1(JSOp::Pop)) {
5623 // [stack] OBJ ASYNC_ITERFN
5624 return false;
5625 }
5626 }
5627
5628 if (!emit1(JSOp::Swap)) {
5629 // [stack] ASYNC_ITERFN OBJ
5630 return false;
5631 }
5632 if (!emitCall(getIterCallOp(JSOp::CallIter, selfHostedIter), 0)) {
5633 // [stack] ITER
5634 return false;
5635 }
5636 if (!emitCheckIsObj(CheckIsObjectKind::GetAsyncIterator)) {
5637 // [stack] ITER
5638 return false;
5639 }
5640
5641 if (!ifAsyncIterIsUndefined.emitEnd()) {
5642 // [stack] ITER
5643 return false;
5644 }
5645
5646 if (!emit1(JSOp::Dup)) {
5647 // [stack] ITER ITER
5648 return false;
5649 }
5650 if (!emitAtomOp(JSOp::GetProp, TaggedParserAtomIndex::WellKnown::next())) {
5651 // [stack] ITER NEXT
5652 return false;
5653 }
5654 if (!emit1(JSOp::Swap)) {
5655 // [stack] NEXT ITER
5656 return false;
5657 }
5658
5659 return true;
5660 }
5661
5662 bool BytecodeEmitter::emitSpread(SelfHostedIter selfHostedIter) {
5663 // [stack] NEXT ITER ARR I
5664 return emitSpread(selfHostedIter, 2, JSOp::InitElemInc);
5665 // [stack] ARR FINAL_INDEX
5666 }
5667
5668 bool BytecodeEmitter::emitSpread(SelfHostedIter selfHostedIter,
5669 int spreadeeStackItems, JSOp storeElementOp) {
5670 LoopControl loopInfo(this, StatementKind::Spread);
5671 // In the [stack] annotations, (spreadee) can be "ARR I" (when spreading
5672 // into an array or into call parameters, or "TUPLE" (when spreading into a
5673 // tuple)
5674
5675 if (!loopInfo.emitLoopHead(this, Nothing())) {
5676 // [stack] NEXT ITER (spreadee)
5677 return false;
5678 }
5679
5680 {
5681 #ifdef DEBUG
5682 auto loopDepth = bytecodeSection().stackDepth();
5683 #endif
5684
5685 // Spread operations can't contain |continue|, so don't bother setting loop
5686 // and enclosing "update" offsets, as we do with for-loops.
5687
5688 if (!emitDupAt(spreadeeStackItems + 1, 2)) {
5689 // [stack] NEXT ITER (spreadee) NEXT ITER
5690 return false;
5691 }
5692 if (!emitIteratorNext(Nothing(), IteratorKind::Sync, selfHostedIter)) {
5693 // [stack] NEXT ITER (spreadee) RESULT
5694 return false;
5695 }
5696 if (!emit1(JSOp::Dup)) {
5697 // [stack] NEXT ITER (spreadee) RESULT RESULT
5698 return false;
5699 }
5700 if (!emitAtomOp(JSOp::GetProp, TaggedParserAtomIndex::WellKnown::done())) {
5701 // [stack] NEXT ITER (spreadee) RESULT DONE
5702 return false;
5703 }
5704 if (!emitJump(JSOp::JumpIfTrue, &loopInfo.breaks)) {
5705 // [stack] NEXT ITER (spreadee) RESULT
5706 return false;
5707 }
5708
5709 // Emit code to assign result.value to the iteration variable.
5710 if (!emitAtomOp(JSOp::GetProp, TaggedParserAtomIndex::WellKnown::value())) {
5711 // [stack] NEXT ITER (spreadee) VALUE
5712 return false;
5713 }
5714 if (!emit1(storeElementOp)) {
5715 // [stack] NEXT ITER (spreadee)
5716 return false;
5717 }
5718
5719 if (!loopInfo.emitLoopEnd(this, JSOp::Goto, TryNoteKind::ForOf)) {
5720 // [stack] NEXT ITER (spreadee)
5721 return false;
5722 }
5723
5724 MOZ_ASSERT(bytecodeSection().stackDepth() == loopDepth);
5725 }
5726
5727 // When we leave the loop body and jump to this point, the result value is
5728 // still on the stack. Account for that by updating the stack depth
5729 // manually.
5730 bytecodeSection().setStackDepth(bytecodeSection().stackDepth() + 1);
5731
5732 // No continues should occur in spreads.
5733 MOZ_ASSERT(!loopInfo.continues.offset.valid());
5734
5735 if (!emit2(JSOp::Pick, spreadeeStackItems + 2)) {
5736 // [stack] ITER (spreadee) RESULT NEXT
5737 return false;
5738 }
5739 if (!emit2(JSOp::Pick, spreadeeStackItems + 2)) {
5740 // [stack] (spreadee) RESULT NEXT ITER
5741 return false;
5742 }
5743
5744 return emitPopN(3);
5745 // [stack] (spreadee)
5746 }
5747
5748 bool BytecodeEmitter::emitInitializeForInOrOfTarget(TernaryNode* forHead) {
5749 MOZ_ASSERT(forHead->isKind(ParseNodeKind::ForIn) ||
5750 forHead->isKind(ParseNodeKind::ForOf));
5751
5752 MOZ_ASSERT(bytecodeSection().stackDepth() >= 1,
5753 "must have a per-iteration value for initializing");
5754
5755 ParseNode* target = forHead->kid1();
5756 MOZ_ASSERT(!forHead->kid2());
5757
5758 // If the for-in/of loop didn't have a variable declaration, per-loop
5759 // initialization is just assigning the iteration value to a target
5760 // expression.
5761 if (!target->is<DeclarationListNode>()) {
5762 return emitAssignmentOrInit(ParseNodeKind::AssignExpr, target, nullptr);
5763 // [stack] ... ITERVAL
5764 }
5765
5766 // Otherwise, per-loop initialization is (possibly) declaration
5767 // initialization. If the declaration is a lexical declaration, it must be
5768 // initialized. If the declaration is a variable declaration, an
5769 // assignment to that name (which does *not* necessarily assign to the
5770 // variable!) must be generated.
5771
5772 auto* declarationList = &target->as<DeclarationListNode>();
5773 if (!updateSourceCoordNotes(declarationList->pn_pos.begin)) {
5774 return false;
5775 }
5776
5777 target = declarationList->singleBinding();
5778
5779 NameNode* nameNode = nullptr;
5780 if (target->isKind(ParseNodeKind::Name)) {
5781 nameNode = &target->as<NameNode>();
5782 } else if (target->isKind(ParseNodeKind::AssignExpr)) {
5783 BinaryNode* assignNode = &target->as<BinaryNode>();
5784 if (assignNode->left()->is<NameNode>()) {
5785 nameNode = &assignNode->left()->as<NameNode>();
5786 }
5787 }
5788
5789 if (nameNode) {
5790 auto nameAtom = nameNode->name();
5791 NameOpEmitter noe(this, nameAtom, NameOpEmitter::Kind::Initialize);
5792 if (!noe.prepareForRhs()) {
5793 return false;
5794 }
5795 if (noe.emittedBindOp()) {
5796 // Per-iteration initialization in for-in/of loops computes the
5797 // iteration value *before* initializing. Thus the initializing
5798 // value may be buried under a bind-specific value on the stack.
5799 // Swap it to the top of the stack.
5800 MOZ_ASSERT(bytecodeSection().stackDepth() >= 2);
5801 if (!emit1(JSOp::Swap)) {
5802 return false;
5803 }
5804 } else {
5805 // In cases of emitting a frame slot or environment slot,
5806 // nothing needs be done.
5807 MOZ_ASSERT(bytecodeSection().stackDepth() >= 1);
5808 }
5809
5810 #ifdef ENABLE_EXPLICIT_RESOURCE_MANAGEMENT
5811 if (declarationList->isKind(ParseNodeKind::UsingDecl)) {
5812 if (!innermostEmitterScope()->prepareForDisposableAssignment(
5813 UsingHint::Sync)) {
5814 // [stack] ENV? V
5815 return false;
5816 }
5817 } else if (declarationList->isKind(ParseNodeKind::AwaitUsingDecl)) {
5818 if (!innermostEmitterScope()->prepareForDisposableAssignment(
5819 UsingHint::Async)) {
5820 // [stack] ENV? V
5821 return false;
5822 }
5823 }
5824 #endif
5825
5826 if (!noe.emitAssignment()) {
5827 return false;
5828 }
5829
5830 // The caller handles removing the iteration value from the stack.
5831 return true;
5832 }
5833
5834 MOZ_ASSERT(
5835 !target->isKind(ParseNodeKind::AssignExpr),
5836 "for-in/of loop destructuring declarations can't have initializers");
5837
5838 MOZ_ASSERT(target->isKind(ParseNodeKind::ArrayExpr) ||
5839 target->isKind(ParseNodeKind::ObjectExpr));
5840 return emitDestructuringOps(&target->as<ListNode>(),
5841 DestructuringFlavor::Declaration);
5842 }
5843
5844 bool BytecodeEmitter::emitForOf(ForNode* forOfLoop,
5845 const EmitterScope* headLexicalEmitterScope) {
5846 MOZ_ASSERT(forOfLoop->isKind(ParseNodeKind::ForStmt));
5847
5848 TernaryNode* forOfHead = forOfLoop->head();
5849 MOZ_ASSERT(forOfHead->isKind(ParseNodeKind::ForOf));
5850
5851 unsigned iflags = forOfLoop->iflags();
5852 IteratorKind iterKind =
5853 (iflags & JSITER_FORAWAITOF) ? IteratorKind::Async : IteratorKind::Sync;
5854 MOZ_ASSERT_IF(iterKind == IteratorKind::Async, sc->isSuspendableContext());
5855 MOZ_ASSERT_IF(iterKind == IteratorKind::Async,
5856 sc->asSuspendableContext()->isAsync());
5857
5858 ParseNode* forHeadExpr = forOfHead->kid3();
5859
5860 // Certain builtins (e.g. Array.from) are implemented in self-hosting
5861 // as for-of loops.
5862 auto selfHostedIter = getSelfHostedIterFor(forHeadExpr);
5863 #ifdef ENABLE_EXPLICIT_RESOURCE_MANAGEMENT
5864 ForOfEmitter::HeadUsingDeclarationKind headUsingDeclKind =
5865 ForOfEmitter::HeadUsingDeclarationKind::None;
5866 if (forOfHead->kid1()->isKind(ParseNodeKind::UsingDecl)) {
5867 headUsingDeclKind = ForOfEmitter::HeadUsingDeclarationKind::Sync;
5868 } else if (forOfHead->kid1()->isKind(ParseNodeKind::AwaitUsingDecl)) {
5869 headUsingDeclKind = ForOfEmitter::HeadUsingDeclarationKind::Async;
5870 }
5871 #endif
5872
5873 ForOfEmitter forOf(this, headLexicalEmitterScope, selfHostedIter, iterKind
5874 #ifdef ENABLE_EXPLICIT_RESOURCE_MANAGEMENT
5875 ,
5876 headUsingDeclKind
5877 #endif
5878 );
5879
5880 if (!forOf.emitIterated()) {
5881 // [stack]
5882 return false;
5883 }
5884
5885 if (!updateSourceCoordNotes(forHeadExpr->pn_pos.begin)) {
5886 return false;
5887 }
5888 if (!markStepBreakpoint()) {
5889 return false;
5890 }
5891 if (!emitIterable(forHeadExpr, selfHostedIter, iterKind)) {
5892 // [stack] ITERABLE
5893 return false;
5894 }
5895
5896 if (headLexicalEmitterScope) {
5897 DebugOnly<ParseNode*> forOfTarget = forOfHead->kid1();
5898 MOZ_ASSERT(forOfTarget->isKind(ParseNodeKind::LetDecl) ||
5899 forOfTarget->isKind(ParseNodeKind::ConstDecl)
5900 #ifdef ENABLE_EXPLICIT_RESOURCE_MANAGEMENT
5901 || forOfTarget->isKind(ParseNodeKind::UsingDecl) ||
5902 forOfTarget->isKind(ParseNodeKind::AwaitUsingDecl)
5903 #endif
5904 );
5905 }
5906
5907 if (!forOf.emitInitialize(forOfHead->pn_pos.begin)) {
5908 // [stack] NEXT ITER VALUE
5909 return false;
5910 }
5911
5912 if (!emitInitializeForInOrOfTarget(forOfHead)) {
5913 // [stack] NEXT ITER VALUE
5914 return false;
5915 }
5916
5917 if (!forOf.emitBody()) {
5918 // [stack] NEXT ITER UNDEF
5919 return false;
5920 }
5921
5922 // Perform the loop body.
5923 ParseNode* forBody = forOfLoop->body();
5924 if (!emitTree(forBody)) {
5925 // [stack] NEXT ITER UNDEF
5926 return false;
5927 }
5928
5929 if (!forOf.emitEnd(forHeadExpr->pn_pos.begin)) {
5930 // [stack]
5931 return false;
5932 }
5933
5934 return true;
5935 }
5936
5937 bool BytecodeEmitter::emitForIn(ForNode* forInLoop,
5938 const EmitterScope* headLexicalEmitterScope) {
5939 TernaryNode* forInHead = forInLoop->head();
5940 MOZ_ASSERT(forInHead->isKind(ParseNodeKind::ForIn));
5941
5942 ForInEmitter forIn(this, headLexicalEmitterScope);
5943
5944 // Annex B: Evaluate the var-initializer expression if present.
5945 // |for (var i = initializer in expr) { ... }|
5946 ParseNode* forInTarget = forInHead->kid1();
5947 if (forInTarget->is<DeclarationListNode>()) {
5948 auto* declarationList = &forInTarget->as<DeclarationListNode>();
5949
5950 ParseNode* decl = declarationList->singleBinding();
5951 if (decl->isKind(ParseNodeKind::AssignExpr)) {
5952 BinaryNode* assignNode = &decl->as<BinaryNode>();
5953 if (assignNode->left()->is<NameNode>()) {
5954 NameNode* nameNode = &assignNode->left()->as<NameNode>();
5955 ParseNode* initializer = assignNode->right();
5956 MOZ_ASSERT(
5957 forInTarget->isKind(ParseNodeKind::VarStmt),
5958 "for-in initializers are only permitted for |var| declarations");
5959
5960 if (!updateSourceCoordNotes(decl->pn_pos.begin)) {
5961 return false;
5962 }
5963
5964 auto nameAtom = nameNode->name();
5965 NameOpEmitter noe(this, nameAtom, NameOpEmitter::Kind::Initialize);
5966 if (!noe.prepareForRhs()) {
5967 return false;
5968 }
5969 if (!emitInitializer(initializer, nameNode)) {
5970 return false;
5971 }
5972 if (!noe.emitAssignment()) {
5973 return false;
5974 }
5975
5976 // Pop the initializer.
5977 if (!emit1(JSOp::Pop)) {
5978 return false;
5979 }
5980 }
5981 }
5982 }
5983
5984 if (!forIn.emitIterated()) {
5985 // [stack]
5986 return false;
5987 }
5988
5989 // Evaluate the expression being iterated.
5990 ParseNode* expr = forInHead->kid3();
5991
5992 if (!updateSourceCoordNotes(expr->pn_pos.begin)) {
5993 return false;
5994 }
5995 if (!markStepBreakpoint()) {
5996 return false;
5997 }
5998 if (!emitTree(expr)) {
5999 // [stack] EXPR
6000 return false;
6001 }
6002
6003 MOZ_ASSERT(forInLoop->iflags() == 0);
6004
6005 MOZ_ASSERT_IF(headLexicalEmitterScope,
6006 forInTarget->isKind(ParseNodeKind::LetDecl) ||
6007 forInTarget->isKind(ParseNodeKind::ConstDecl));
6008
6009 if (!forIn.emitInitialize()) {
6010 // [stack] ITER ITERVAL
6011 return false;
6012 }
6013
6014 if (!emitInitializeForInOrOfTarget(forInHead)) {
6015 // [stack] ITER ITERVAL
6016 return false;
6017 }
6018
6019 if (!forIn.emitBody()) {
6020 // [stack] ITER ITERVAL
6021 return false;
6022 }
6023
6024 // Perform the loop body.
6025 ParseNode* forBody = forInLoop->body();
6026 if (!emitTree(forBody)) {
6027 // [stack] ITER ITERVAL
6028 return false;
6029 }
6030
6031 if (!forIn.emitEnd(forInHead->pn_pos.begin)) {
6032 // [stack]
6033 return false;
6034 }
6035
6036 return true;
6037 }
6038
6039 /* C-style `for (init; cond; update) ...` loop. */
6040 bool BytecodeEmitter::emitCStyleFor(
6041 ForNode* forNode, const EmitterScope* headLexicalEmitterScope) {
6042 TernaryNode* forHead = forNode->head();
6043 ParseNode* forBody = forNode->body();
6044 ParseNode* init = forHead->kid1();
6045 ParseNode* cond = forHead->kid2();
6046 ParseNode* update = forHead->kid3();
6047 bool isLet = init && init->isKind(ParseNodeKind::LetDecl);
6048
6049 CForEmitter cfor(this, isLet ? headLexicalEmitterScope : nullptr);
6050
6051 if (!cfor.emitInit(init ? Some(init->pn_pos.begin) : Nothing())) {
6052 // [stack]
6053 return false;
6054 }
6055
6056 // If the head of this for-loop declared any lexical variables, the parser
6057 // wrapped this ParseNodeKind::For node in a ParseNodeKind::LexicalScope
6058 // representing the implicit scope of those variables. By the time we get
6059 // here, we have already entered that scope. So far, so good.
6060 if (init) {
6061 // Emit the `init` clause, whether it's an expression or a variable
6062 // declaration. (The loop variables were hoisted into an enclosing
6063 // scope, but we still need to emit code for the initializers.)
6064 if (init->is<DeclarationListNode>()) {
6065 MOZ_ASSERT(!init->as<DeclarationListNode>().empty());
6066
6067 if (!emitTree(init)) {
6068 // [stack]
6069 return false;
6070 }
6071 } else {
6072 if (!updateSourceCoordNotes(init->pn_pos.begin)) {
6073 return false;
6074 }
6075 if (!markStepBreakpoint()) {
6076 return false;
6077 }
6078
6079 // 'init' is an expression, not a declaration. emitTree left its
6080 // value on the stack.
6081 if (!emitTree(init, ValueUsage::IgnoreValue)) {
6082 // [stack] VAL
6083 return false;
6084 }
6085 if (!emit1(JSOp::Pop)) {
6086 // [stack]
6087 return false;
6088 }
6089 }
6090 }
6091
6092 if (!cfor.emitCond(cond ? Some(cond->pn_pos.begin) : Nothing())) {
6093 // [stack]
6094 return false;
6095 }
6096
6097 if (cond) {
6098 if (!updateSourceCoordNotes(cond->pn_pos.begin)) {
6099 return false;
6100 }
6101 if (!markStepBreakpoint()) {
6102 return false;
6103 }
6104 if (!emitTree(cond)) {
6105 // [stack] VAL
6106 return false;
6107 }
6108 }
6109
6110 if (!cfor.emitBody(cond ? CForEmitter::Cond::Present
6111 : CForEmitter::Cond::Missing)) {
6112 // [stack]
6113 return false;
6114 }
6115
6116 if (!emitTree(forBody)) {
6117 // [stack]
6118 return false;
6119 }
6120
6121 if (!cfor.emitUpdate(
6122 update ? CForEmitter::Update::Present : CForEmitter::Update::Missing,
6123 update ? Some(update->pn_pos.begin) : Nothing())) {
6124 // [stack]
6125 return false;
6126 }
6127
6128 // Check for update code to do before the condition (if any).
6129 if (update) {
6130 if (!updateSourceCoordNotes(update->pn_pos.begin)) {
6131 return false;
6132 }
6133 if (!markStepBreakpoint()) {
6134 return false;
6135 }
6136 if (!emitTree(update, ValueUsage::IgnoreValue)) {
6137 // [stack] VAL
6138 return false;
6139 }
6140 }
6141
6142 if (!cfor.emitEnd(forNode->pn_pos.begin)) {
6143 // [stack]
6144 return false;
6145 }
6146
6147 return true;
6148 }
6149
6150 bool BytecodeEmitter::emitFor(ForNode* forNode,
6151 const EmitterScope* headLexicalEmitterScope) {
6152 if (forNode->head()->isKind(ParseNodeKind::ForHead)) {
6153 return emitCStyleFor(forNode, headLexicalEmitterScope);
6154 }
6155
6156 if (!updateLineNumberNotes(forNode->pn_pos.begin)) {
6157 return false;
6158 }
6159
6160 if (forNode->head()->isKind(ParseNodeKind::ForIn)) {
6161 return emitForIn(forNode, headLexicalEmitterScope);
6162 }
6163
6164 MOZ_ASSERT(forNode->head()->isKind(ParseNodeKind::ForOf));
6165 return emitForOf(forNode, headLexicalEmitterScope);
6166 }
6167
6168 MOZ_NEVER_INLINE bool BytecodeEmitter::emitFunction(
6169 FunctionNode* funNode, bool needsProto /* = false */) {
6170 FunctionBox* funbox = funNode->funbox();
6171
6172 // [stack]
6173
6174 FunctionEmitter fe(this, funbox, funNode->syntaxKind(),
6175 funNode->functionIsHoisted()
6176 ? FunctionEmitter::IsHoisted::Yes
6177 : FunctionEmitter::IsHoisted::No);
6178
6179 // |wasEmittedByEnclosingScript| flag is set to true once the function has
6180 // been emitted. Function definitions that need hoisting to the top of the
6181 // function will be seen by emitFunction in two places.
6182 if (funbox->wasEmittedByEnclosingScript()) {
6183 if (!fe.emitAgain()) {
6184 // [stack]
6185 return false;
6186 }
6187 MOZ_ASSERT(funNode->functionIsHoisted());
6188 } else if (funbox->isInterpreted()) {
6189 if (!funbox->emitBytecode) {
6190 return fe.emitLazy();
6191 // [stack] FUN?
6192 }
6193
6194 if (!fe.prepareForNonLazy()) {
6195 // [stack]
6196 return false;
6197 }
6198
6199 BytecodeEmitter bce2(this, funbox);
6200 if (!bce2.init(funNode->pn_pos)) {
6201 return false;
6202 }
6203
6204 /* We measured the max scope depth when we parsed the function. */
6205 if (!bce2.emitFunctionScript(funNode)) {
6206 return false;
6207 }
6208
6209 if (!fe.emitNonLazyEnd()) {
6210 // [stack] FUN?
6211 return false;
6212 }
6213 } else {
6214 if (!fe.emitAsmJSModule()) {
6215 // [stack]
6216 return false;
6217 }
6218 }
6219
6220 // Track the last emitted top-level self-hosted function, so that intrinsics
6221 // can adjust attributes at parse time.
6222 //
6223 // NOTE: We also disallow lambda functions in the top-level body. This is done
6224 // to simplify handling of the self-hosted stencil. Within normal function
6225 // declarations there are no such restrictions.
6226 if (emitterMode == EmitterMode::SelfHosting) {
6227 if (sc->isTopLevelContext()) {
6228 MOZ_ASSERT(!funbox->isLambda());
6229 MOZ_ASSERT(funbox->explicitName());
6230 prevSelfHostedTopLevelFunction = funbox;
6231 }
6232 }
6233
6234 return true;
6235 }
6236
6237 bool BytecodeEmitter::emitDo(BinaryNode* doNode) {
6238 ParseNode* bodyNode = doNode->left();
6239
6240 DoWhileEmitter doWhile(this);
6241 if (!doWhile.emitBody(doNode->pn_pos.begin, getOffsetForLoop(bodyNode))) {
6242 return false;
6243 }
6244
6245 if (!emitTree(bodyNode)) {
6246 return false;
6247 }
6248
6249 if (!doWhile.emitCond()) {
6250 return false;
6251 }
6252
6253 ParseNode* condNode = doNode->right();
6254 if (!updateSourceCoordNotes(condNode->pn_pos.begin)) {
6255 return false;
6256 }
6257 if (!markStepBreakpoint()) {
6258 return false;
6259 }
6260 if (!emitTree(condNode)) {
6261 return false;
6262 }
6263
6264 if (!doWhile.emitEnd()) {
6265 return false;
6266 }
6267
6268 return true;
6269 }
6270
6271 bool BytecodeEmitter::emitWhile(BinaryNode* whileNode) {
6272 ParseNode* bodyNode = whileNode->right();
6273
6274 WhileEmitter wh(this);
6275
6276 ParseNode* condNode = whileNode->left();
6277 if (!wh.emitCond(whileNode->pn_pos.begin, getOffsetForLoop(condNode),
6278 whileNode->pn_pos.end)) {
6279 return false;
6280 }
6281
6282 if (!updateSourceCoordNotes(condNode->pn_pos.begin)) {
6283 return false;
6284 }
6285 if (!markStepBreakpoint()) {
6286 return false;
6287 }
6288 if (!emitTree(condNode)) {
6289 return false;
6290 }
6291
6292 if (!wh.emitBody()) {
6293 return false;
6294 }
6295 if (!emitTree(bodyNode)) {
6296 return false;
6297 }
6298
6299 if (!wh.emitEnd()) {
6300 return false;
6301 }
6302
6303 return true;
6304 }
6305
6306 bool BytecodeEmitter::emitBreak(TaggedParserAtomIndex label) {
6307 BreakableControl* target;
6308 if (label) {
6309 // Any statement with the matching label may be the break target.
6310 auto hasSameLabel = [label](LabelControl* labelControl) {
6311 return labelControl->label() == label;
6312 };
6313 target = findInnermostNestableControl<LabelControl>(hasSameLabel);
6314 } else {
6315 auto isNotLabel = [](BreakableControl* control) {
6316 return !control->is<LabelControl>();
6317 };
6318 target = findInnermostNestableControl<BreakableControl>(isNotLabel);
6319 }
6320
6321 return emitGoto(target, GotoKind::Break);
6322 }
6323
6324 bool BytecodeEmitter::emitContinue(TaggedParserAtomIndex label) {
6325 LoopControl* target = nullptr;
6326 if (label) {
6327 // Find the loop statement enclosed by the matching label.
6328 NestableControl* control = innermostNestableControl;
6329 while (!control->is<LabelControl>() ||
6330 control->as<LabelControl>().label() != label) {
6331 if (control->is<LoopControl>()) {
6332 target = &control->as<LoopControl>();
6333 }
6334 control = control->enclosing();
6335 }
6336 } else {
6337 target = findInnermostNestableControl<LoopControl>();
6338 }
6339 return emitGoto(target, GotoKind::Continue);
6340 }
6341
6342 bool BytecodeEmitter::emitGetFunctionThis(NameNode* thisName) {
6343 MOZ_ASSERT(sc->hasFunctionThisBinding());
6344 MOZ_ASSERT(thisName->isName(TaggedParserAtomIndex::WellKnown::dot_this_()));
6345
6346 if (!updateLineNumberNotes(thisName->pn_pos.begin)) {
6347 return false;
6348 }
6349
6350 if (!emitGetName(TaggedParserAtomIndex::WellKnown::dot_this_())) {
6351 // [stack] THIS
6352 return false;
6353 }
6354 if (sc->needsThisTDZChecks()) {
6355 if (!emit1(JSOp::CheckThis)) {
6356 // [stack] THIS
6357 return false;
6358 }
6359 }
6360
6361 return true;
6362 }
6363
6364 bool BytecodeEmitter::emitGetThisForSuperBase(UnaryNode* superBase) {
6365 MOZ_ASSERT(superBase->isKind(ParseNodeKind::SuperBase));
6366 NameNode* nameNode = &superBase->kid()->as<NameNode>();
6367 return emitGetFunctionThis(nameNode);
6368 // [stack] THIS
6369 }
6370
6371 bool BytecodeEmitter::emitThisLiteral(ThisLiteral* pn) {
6372 if (ParseNode* kid = pn->kid()) {
6373 NameNode* thisName = &kid->as<NameNode>();
6374 return emitGetFunctionThis(thisName);
6375 // [stack] THIS
6376 }
6377
6378 if (sc->thisBinding() == ThisBinding::Module) {
6379 return emit1(JSOp::Undefined);
6380 // [stack] UNDEF
6381 }
6382
6383 MOZ_ASSERT(sc->thisBinding() == ThisBinding::Global);
6384
6385 MOZ_ASSERT(outermostScope().hasNonSyntacticScopeOnChain() ==
6386 sc->hasNonSyntacticScope());
6387 if (sc->hasNonSyntacticScope()) {
6388 return emit1(JSOp::NonSyntacticGlobalThis);
6389 // [stack] THIS
6390 }
6391
6392 return emit1(JSOp::GlobalThis);
6393 // [stack] THIS
6394 }
6395
6396 bool BytecodeEmitter::emitCheckDerivedClassConstructorReturn() {
6397 MOZ_ASSERT(
6398 lookupName(TaggedParserAtomIndex::WellKnown::dot_this_()).hasKnownSlot());
6399 if (!emitGetName(TaggedParserAtomIndex::WellKnown::dot_this_())) {
6400 return false;
6401 }
6402 if (!emit1(JSOp::CheckReturn)) {
6403 return false;
6404 }
6405 if (!emit1(JSOp::SetRval)) {
6406 return false;
6407 }
6408 return true;
6409 }
6410
6411 bool BytecodeEmitter::emitNewTarget() {
6412 MOZ_ASSERT(sc->allowNewTarget());
6413
6414 if (!emitGetName(TaggedParserAtomIndex::WellKnown::dot_newTarget_())) {
6415 // [stack] NEW.TARGET
6416 return false;
6417 }
6418 return true;
6419 }
6420
6421 bool BytecodeEmitter::emitNewTarget(NewTargetNode* pn) {
6422 MOZ_ASSERT(pn->newTargetName()->isName(
6423 TaggedParserAtomIndex::WellKnown::dot_newTarget_()));
6424
6425 return emitNewTarget();
6426 }
6427
6428 bool BytecodeEmitter::emitNewTarget(CallNode* pn) {
6429 MOZ_ASSERT(pn->callOp() == JSOp::SuperCall ||
6430 pn->callOp() == JSOp::SpreadSuperCall);
6431
6432 // The parser is responsible for marking the "new.target" binding as being
6433 // implicitly used in super() calls.
6434 return emitNewTarget();
6435 }
6436
6437 bool BytecodeEmitter::emitReturn(UnaryNode* returnNode) {
6438 if (!updateSourceCoordNotes(returnNode->pn_pos.begin)) {
6439 return false;
6440 }
6441
6442 if (!markStepBreakpoint()) {
6443 return false;
6444 }
6445
6446 /* Push a return value */
6447 if (ParseNode* expr = returnNode->kid()) {
6448 if (!emitTree(expr)) {
6449 return false;
6450 }
6451
6452 if (sc->asSuspendableContext()->isAsync() &&
6453 sc->asSuspendableContext()->isGenerator()) {
6454 if (!emitAwaitInInnermostScope()) {
6455 return false;
6456 }
6457 }
6458 } else {
6459 /* No explicit return value provided */
6460 if (!emit1(JSOp::Undefined)) {
6461 return false;
6462 }
6463 }
6464
6465 // We know functionBodyEndPos is set because "return" is only
6466 // valid in a function, and so we've passed through
6467 // emitFunctionScript.
6468 if (!updateSourceCoordNotes(*functionBodyEndPos)) {
6469 return false;
6470 }
6471
6472 /*
6473 * The return value is currently on the stack. We would like to
6474 * generate JSOp::Return, but if we have work to do before returning,
6475 * we will instead generate JSOp::SetRval / JSOp::RetRval.
6476 *
6477 * We don't know whether we will need fixup code until after calling
6478 * prepareForNonLocalJumpToOutermost, so we start by generating
6479 * JSOp::SetRval, then mutate it to JSOp::Return in finishReturn if it
6480 * wasn't needed.
6481 */
6482 BytecodeOffset setRvalOffset = bytecodeSection().offset();
6483 if (!emit1(JSOp::SetRval)) {
6484 return false;
6485 }
6486
6487 NonLocalExitControl nle(this, NonLocalExitKind::Return);
6488 return nle.emitReturn(setRvalOffset);
6489 }
6490
6491 bool BytecodeEmitter::finishReturn(BytecodeOffset setRvalOffset) {
6492 // The return value is currently in rval. Depending on the current function,
6493 // we may have to do additional work before returning:
6494 // - Derived class constructors must check if the return value is an object.
6495 // - Generators and async functions must do a final yield.
6496 // - Non-async generators must return the value as an iterator result:
6497 // { value: <rval>, done: true }
6498 // - Non-generator async functions must resolve the function's result promise
6499 // with the value.
6500 //
6501 // If we have not generated any code since the SetRval that stored the return
6502 // value, we can also optimize the bytecode by rewriting that SetRval as a
6503 // JSOp::Return. See |emitReturn| above.
6504
6505 bool isDerivedClassConstructor =
6506 sc->isFunctionBox() && sc->asFunctionBox()->isDerivedClassConstructor();
6507 bool needsFinalYield =
6508 sc->isFunctionBox() && sc->asFunctionBox()->needsFinalYield();
6509 bool isSimpleReturn =
6510 setRvalOffset.valid() &&
6511 setRvalOffset + BytecodeOffsetDiff(JSOpLength_SetRval) ==
6512 bytecodeSection().offset();
6513
6514 if (isDerivedClassConstructor) {
6515 MOZ_ASSERT(!needsFinalYield);
6516 if (!emitJump(JSOp::Goto, &endOfDerivedClassConstructorBody)) {
6517 return false;
6518 }
6519 return true;
6520 }
6521
6522 if (needsFinalYield) {
6523 if (!emitJump(JSOp::Goto, &finalYields)) {
6524 return false;
6525 }
6526 return true;
6527 }
6528
6529 if (isSimpleReturn) {
6530 MOZ_ASSERT(JSOp(bytecodeSection().code()[setRvalOffset.value()]) ==
6531 JSOp::SetRval);
6532 bytecodeSection().code()[setRvalOffset.value()] = jsbytecode(JSOp::Return);
6533 return true;
6534 }
6535
6536 // Nothing special needs to be done.
6537 return emitReturnRval();
6538 }
6539
6540 bool BytecodeEmitter::emitGetDotGeneratorInScope(EmitterScope& currentScope) {
6541 if (!sc->isFunction() && sc->isModuleContext() &&
6542 sc->asModuleContext()->isAsync()) {
6543 NameLocation loc = *locationOfNameBoundInScopeType<ModuleScope>(
6544 TaggedParserAtomIndex::WellKnown::dot_generator_(), &currentScope);
6545 return emitGetNameAtLocation(
6546 TaggedParserAtomIndex::WellKnown::dot_generator_(), loc);
6547 }
6548 NameLocation loc = *locationOfNameBoundInScopeType<FunctionScope>(
6549 TaggedParserAtomIndex::WellKnown::dot_generator_(), &currentScope);
6550 return emitGetNameAtLocation(
6551 TaggedParserAtomIndex::WellKnown::dot_generator_(), loc);
6552 }
6553
6554 bool BytecodeEmitter::emitInitialYield(UnaryNode* yieldNode) {
6555 if (!emitTree(yieldNode->kid())) {
6556 return false;
6557 }
6558
6559 if (!emitYieldOp(JSOp::InitialYield)) {
6560 // [stack] RVAL GENERATOR RESUMEKIND
6561 return false;
6562 }
6563 if (!emit1(JSOp::CheckResumeKind)) {
6564 // [stack] RVAL
6565 return false;
6566 }
6567 if (!emit1(JSOp::Pop)) {
6568 // [stack]
6569 return false;
6570 }
6571
6572 return true;
6573 }
6574
6575 bool BytecodeEmitter::emitYield(UnaryNode* yieldNode) {
6576 MOZ_ASSERT(sc->isFunctionBox());
6577 MOZ_ASSERT(sc->asFunctionBox()->isGenerator());
6578 MOZ_ASSERT(yieldNode->isKind(ParseNodeKind::YieldExpr));
6579
6580 bool needsIteratorResult = sc->asFunctionBox()->needsIteratorResult();
6581 if (needsIteratorResult) {
6582 if (!emitPrepareIteratorResult()) {
6583 // [stack] ITEROBJ
6584 return false;
6585 }
6586 }
6587 if (ParseNode* expr = yieldNode->kid()) {
6588 if (!emitTree(expr)) {
6589 // [stack] ITEROBJ? VAL
6590 return false;
6591 }
6592 } else {
6593 if (!emit1(JSOp::Undefined)) {
6594 // [stack] ITEROBJ? UNDEFINED
6595 return false;
6596 }
6597 }
6598
6599 if (sc->asSuspendableContext()->isAsync()) {
6600 MOZ_ASSERT(!needsIteratorResult);
6601 if (!emitAwaitInInnermostScope()) {
6602 // [stack] RESULT
6603 return false;
6604 }
6605 }
6606
6607 if (needsIteratorResult) {
6608 if (!emitFinishIteratorResult(false)) {
6609 // [stack] ITEROBJ
6610 return false;
6611 }
6612 }
6613
6614 if (!emitGetDotGeneratorInInnermostScope()) {
6615 // [stack] # if needsIteratorResult
6616 // [stack] ITEROBJ .GENERATOR
6617 // [stack] # else
6618 // [stack] RESULT .GENERATOR
6619 return false;
6620 }
6621
6622 if (!emitYieldOp(JSOp::Yield)) {
6623 // [stack] YIELDRESULT GENERATOR RESUMEKIND
6624 return false;
6625 }
6626
6627 if (!emit1(JSOp::CheckResumeKind)) {
6628 // [stack] YIELDRESULT
6629 return false;
6630 }
6631
6632 return true;
6633 }
6634
6635 bool BytecodeEmitter::emitAwaitInInnermostScope(UnaryNode* awaitNode) {
6636 MOZ_ASSERT(sc->isSuspendableContext());
6637 MOZ_ASSERT(awaitNode->isKind(ParseNodeKind::AwaitExpr));
6638
6639 if (!emitTree(awaitNode->kid())) {
6640 return false;
6641 }
6642 return emitAwaitInInnermostScope();
6643 }
6644
6645 bool BytecodeEmitter::emitAwaitInScope(EmitterScope& currentScope) {
6646 if (!emit1(JSOp::CanSkipAwait)) {
6647 // [stack] VALUE CANSKIP
6648 return false;
6649 }
6650
6651 if (!emit1(JSOp::MaybeExtractAwaitValue)) {
6652 // [stack] VALUE_OR_RESOLVED CANSKIP
6653 return false;
6654 }
6655
6656 InternalIfEmitter ifCanSkip(this);
6657 if (!ifCanSkip.emitThen(IfEmitter::ConditionKind::Negative)) {
6658 // [stack] VALUE_OR_RESOLVED
6659 return false;
6660 }
6661
6662 if (sc->asSuspendableContext()->needsPromiseResult()) {
6663 if (!emitGetDotGeneratorInScope(currentScope)) {
6664 // [stack] VALUE GENERATOR
6665 return false;
6666 }
6667 if (!emit1(JSOp::AsyncAwait)) {
6668 // [stack] PROMISE
6669 return false;
6670 }
6671 }
6672
6673 if (!emitGetDotGeneratorInScope(currentScope)) {
6674 // [stack] VALUE|PROMISE GENERATOR
6675 return false;
6676 }
6677 if (!emitYieldOp(JSOp::Await)) {
6678 // [stack] RESOLVED GENERATOR RESUMEKIND
6679 return false;
6680 }
6681 if (!emit1(JSOp::CheckResumeKind)) {
6682 // [stack] RESOLVED
6683 return false;
6684 }
6685
6686 if (!ifCanSkip.emitEnd()) {
6687 return false;
6688 }
6689
6690 MOZ_ASSERT(ifCanSkip.popped() == 0);
6691
6692 return true;
6693 }
6694
6695 // ES2019 draft rev 49b781ec80117b60f73327ef3054703a3111e40c
6696 // 14.4.14 Runtime Semantics: Evaluation
6697 // YieldExpression : yield* AssignmentExpression
6698 bool BytecodeEmitter::emitYieldStar(ParseNode* iter) {
6699 MOZ_ASSERT(getSelfHostedIterFor(iter) == SelfHostedIter::Deny,
6700 "yield* is prohibited in self-hosted code because it can run "
6701 "user-modifiable iteration code");
6702
6703 MOZ_ASSERT(sc->isSuspendableContext());
6704 MOZ_ASSERT(sc->asSuspendableContext()->isGenerator());
6705
6706 // Step 1.
6707 IteratorKind iterKind = sc->asSuspendableContext()->isAsync()
6708 ? IteratorKind::Async
6709 : IteratorKind::Sync;
6710 bool needsIteratorResult = sc->asSuspendableContext()->needsIteratorResult();
6711
6712 // Steps 2-5.
6713 if (!emitTree(iter)) {
6714 // [stack] ITERABLE
6715 return false;
6716 }
6717 if (iterKind == IteratorKind::Async) {
6718 if (!emitAsyncIterator(SelfHostedIter::Deny)) {
6719 // [stack] NEXT ITER
6720 return false;
6721 }
6722 } else {
6723 if (!emitIterator(SelfHostedIter::Deny)) {
6724 // [stack] NEXT ITER
6725 return false;
6726 }
6727 }
6728
6729 // Step 6.
6730 // Start with NormalCompletion(undefined).
6731 if (!emit1(JSOp::Undefined)) {
6732 // [stack] NEXT ITER RECEIVED
6733 return false;
6734 }
6735 if (!emitPushResumeKind(GeneratorResumeKind::Next)) {
6736 // [stack] NEXT ITER RECEIVED RESUMEKIND
6737 return false;
6738 }
6739
6740 const int32_t startDepth = bytecodeSection().stackDepth();
6741 MOZ_ASSERT(startDepth >= 4);
6742
6743 // Step 7 is a loop.
6744 LoopControl loopInfo(this, StatementKind::YieldStar);
6745 if (!loopInfo.emitLoopHead(this, Nothing())) {
6746 // [stack] NEXT ITER RECEIVED RESUMEKIND
6747 return false;
6748 }
6749
6750 // Step 7.a. Check for Normal completion.
6751 if (!emit1(JSOp::Dup)) {
6752 // [stack] NEXT ITER RECEIVED RESUMEKIND RESUMEKIND
6753 return false;
6754 }
6755 if (!emitPushResumeKind(GeneratorResumeKind::Next)) {
6756 // [stack] NEXT ITER RECEIVED RESUMEKIND RESUMEKIND NORMAL
6757 return false;
6758 }
6759 if (!emit1(JSOp::StrictEq)) {
6760 // [stack] NEXT ITER RECEIVED RESUMEKIND IS_NORMAL
6761 return false;
6762 }
6763
6764 InternalIfEmitter ifKind(this);
6765 if (!ifKind.emitThenElse()) {
6766 // [stack] NEXT ITER RECEIVED RESUMEKIND
6767 return false;
6768 }
6769 {
6770 if (!emit1(JSOp::Pop)) {
6771 // [stack] NEXT ITER RECEIVED
6772 return false;
6773 }
6774
6775 // Step 7.a.i.
6776 // result = iter.next(received)
6777 if (!emit2(JSOp::Unpick, 2)) {
6778 // [stack] RECEIVED NEXT ITER
6779 return false;
6780 }
6781 if (!emit1(JSOp::Dup2)) {
6782 // [stack] RECEIVED NEXT ITER NEXT ITER
6783 return false;
6784 }
6785 if (!emit2(JSOp::Pick, 4)) {
6786 // [stack] NEXT ITER NEXT ITER RECEIVED
6787 return false;
6788 }
6789 if (!emitCall(JSOp::Call, 1, iter)) {
6790 // [stack] NEXT ITER RESULT
6791 return false;
6792 }
6793
6794 // Step 7.a.ii.
6795 if (iterKind == IteratorKind::Async) {
6796 if (!emitAwaitInInnermostScope()) {
6797 // [stack] NEXT ITER RESULT
6798 return false;
6799 }
6800 }
6801
6802 // Step 7.a.iii.
6803 if (!emitCheckIsObj(CheckIsObjectKind::IteratorNext)) {
6804 // [stack] NEXT ITER RESULT
6805 return false;
6806 }
6807
6808 // Bytecode for steps 7.a.iv-vii is emitted after the ifKind if-else because
6809 // it's shared with other branches.
6810 }
6811
6812 // Step 7.b. Check for Throw completion.
6813 if (!ifKind.emitElseIf(Nothing())) {
6814 // [stack] NEXT ITER RECEIVED RESUMEKIND
6815 return false;
6816 }
6817 if (!emit1(JSOp::Dup)) {
6818 // [stack] NEXT ITER RECEIVED RESUMEKIND RESUMEKIND
6819 return false;
6820 }
6821 if (!emitPushResumeKind(GeneratorResumeKind::Throw)) {
6822 // [stack] NEXT ITER RECEIVED RESUMEKIND RESUMEKIND THROW
6823 return false;
6824 }
6825 if (!emit1(JSOp::StrictEq)) {
6826 // [stack] NEXT ITER RECEIVED RESUMEKIND IS_THROW
6827 return false;
6828 }
6829 if (!ifKind.emitThenElse()) {
6830 // [stack] NEXT ITER RECEIVED RESUMEKIND
6831 return false;
6832 }
6833 {
6834 if (!emit1(JSOp::Pop)) {
6835 // [stack] NEXT ITER RECEIVED
6836 return false;
6837 }
6838 // Step 7.b.i.
6839 if (!emitDupAt(1)) {
6840 // [stack] NEXT ITER RECEIVED ITER
6841 return false;
6842 }
6843 if (!emit1(JSOp::Dup)) {
6844 // [stack] NEXT ITER RECEIVED ITER ITER
6845 return false;
6846 }
6847 if (!emitAtomOp(JSOp::GetProp,
6848 TaggedParserAtomIndex::WellKnown::throw_())) {
6849 // [stack] NEXT ITER RECEIVED ITER THROW
6850 return false;
6851 }
6852
6853 // Step 7.b.ii.
6854 InternalIfEmitter ifThrowMethodIsNotDefined(this);
6855 if (!emit1(JSOp::IsNullOrUndefined)) {
6856 // [stack] NEXT ITER RECEIVED ITER THROW NULL-OR-UNDEF
6857 return false;
6858 }
6859
6860 if (!ifThrowMethodIsNotDefined.emitThenElse(
6861 IfEmitter::ConditionKind::Negative)) {
6862 // [stack] NEXT ITER RECEIVED ITER THROW
6863 return false;
6864 }
6865
6866 // Step 7.b.ii.1.
6867 // RESULT = ITER.throw(EXCEPTION)
6868 if (!emit1(JSOp::Swap)) {
6869 // [stack] NEXT ITER RECEIVED THROW ITER
6870 return false;
6871 }
6872 if (!emit2(JSOp::Pick, 2)) {
6873 // [stack] NEXT ITER THROW ITER RECEIVED
6874 return false;
6875 }
6876 if (!emitCall(JSOp::Call, 1, iter)) {
6877 // [stack] NEXT ITER RESULT
6878 return false;
6879 }
6880
6881 // Step 7.b.ii.2.
6882 if (iterKind == IteratorKind::Async) {
6883 if (!emitAwaitInInnermostScope()) {
6884 // [stack] NEXT ITER RESULT
6885 return false;
6886 }
6887 }
6888
6889 // Step 7.b.ii.4.
6890 if (!emitCheckIsObj(CheckIsObjectKind::IteratorThrow)) {
6891 // [stack] NEXT ITER RESULT
6892 return false;
6893 }
6894
6895 // Bytecode for steps 7.b.ii.5-8 is emitted after the ifKind if-else because
6896 // it's shared with other branches.
6897
6898 // Step 7.b.iii.
6899 if (!ifThrowMethodIsNotDefined.emitElse()) {
6900 // [stack] NEXT ITER RECEIVED ITER THROW
6901 return false;
6902 }
6903 if (!emit1(JSOp::Pop)) {
6904 // [stack] NEXT ITER RECEIVED ITER
6905 return false;
6906 }
6907
6908 // Steps 7.b.iii.1-4.
6909 //
6910 // If the iterator does not have a "throw" method, it calls IteratorClose
6911 // and then throws a TypeError.
6912 if (!emitIteratorCloseInInnermostScope(iterKind, CompletionKind::Normal)) {
6913 // [stack] NEXT ITER RECEIVED ITER
6914 return false;
6915 }
6916 // Steps 7.b.iii.5-6.
6917 if (!emit2(JSOp::ThrowMsg, uint8_t(ThrowMsgKind::IteratorNoThrow))) {
6918 // [stack] NEXT ITER RECEIVED ITER
6919 // [stack] # throw
6920 return false;
6921 }
6922
6923 if (!ifThrowMethodIsNotDefined.emitEnd()) {
6924 return false;
6925 }
6926 }
6927
6928 // Step 7.c. It must be a Return completion.
6929 if (!ifKind.emitElse()) {
6930 // [stack] NEXT ITER RECEIVED RESUMEKIND
6931 return false;
6932 }
6933 {
6934 if (!emit1(JSOp::Pop)) {
6935 // [stack] NEXT ITER RECEIVED
6936 return false;
6937 }
6938
6939 // Step 7.c.i.
6940 //
6941 // Call iterator.return() for receiving a "forced return" completion from
6942 // the generator.
6943
6944 // Step 7.c.ii.
6945 //
6946 // Get the "return" method.
6947 if (!emitDupAt(1)) {
6948 // [stack] NEXT ITER RECEIVED ITER
6949 return false;
6950 }
6951 if (!emit1(JSOp::Dup)) {
6952 // [stack] NEXT ITER RECEIVED ITER ITER
6953 return false;
6954 }
6955 if (!emitAtomOp(JSOp::GetProp,
6956 TaggedParserAtomIndex::WellKnown::return_())) {
6957 // [stack] NEXT ITER RECEIVED ITER RET
6958 return false;
6959 }
6960
6961 // Step 7.c.iii.
6962 //
6963 // Do nothing if "return" is undefined or null.
6964 InternalIfEmitter ifReturnMethodIsDefined(this);
6965 if (!emit1(JSOp::IsNullOrUndefined)) {
6966 // [stack] NEXT ITER RECEIVED ITER RET NULL-OR-UNDEF
6967 return false;
6968 }
6969
6970 // Step 7.c.iv.
6971 //
6972 // Call "return" with the argument passed to Generator.prototype.return.
6973 if (!ifReturnMethodIsDefined.emitThenElse(
6974 IfEmitter::ConditionKind::Negative)) {
6975 // [stack] NEXT ITER RECEIVED ITER RET
6976 return false;
6977 }
6978 if (!emit1(JSOp::Swap)) {
6979 // [stack] NEXT ITER RECEIVED RET ITER
6980 return false;
6981 }
6982 if (!emit2(JSOp::Pick, 2)) {
6983 // [stack] NEXT ITER RET ITER RECEIVED
6984 return false;
6985 }
6986 if (needsIteratorResult) {
6987 if (!emitAtomOp(JSOp::GetProp,
6988 TaggedParserAtomIndex::WellKnown::value())) {
6989 // [stack] NEXT ITER RET ITER VAL
6990 return false;
6991 }
6992 }
6993 if (!emitCall(JSOp::Call, 1)) {
6994 // [stack] NEXT ITER RESULT
6995 return false;
6996 }
6997
6998 // Step 7.c.v.
6999 if (iterKind == IteratorKind::Async) {
7000 if (!emitAwaitInInnermostScope()) {
7001 // [stack] NEXT ITER RESULT
7002 return false;
7003 }
7004 }
7005
7006 // Step 7.c.vi.
7007 if (!emitCheckIsObj(CheckIsObjectKind::IteratorReturn)) {
7008 // [stack] NEXT ITER RESULT
7009 return false;
7010 }
7011
7012 // Check if the returned object from iterator.return() is done. If not,
7013 // continue yielding.
7014
7015 // Steps 7.c.vii-viii.
7016 InternalIfEmitter ifReturnDone(this);
7017 if (!emit1(JSOp::Dup)) {
7018 // [stack] NEXT ITER RESULT RESULT
7019 return false;
7020 }
7021 if (!emitAtomOp(JSOp::GetProp, TaggedParserAtomIndex::WellKnown::done())) {
7022 // [stack] NEXT ITER RESULT DONE
7023 return false;
7024 }
7025 if (!ifReturnDone.emitThenElse()) {
7026 // [stack] NEXT ITER RESULT
7027 return false;
7028 }
7029
7030 // Step 7.c.viii.1.
7031 if (!emitAtomOp(JSOp::GetProp, TaggedParserAtomIndex::WellKnown::value())) {
7032 // [stack] NEXT ITER VALUE
7033 return false;
7034 }
7035 if (needsIteratorResult) {
7036 if (!emitPrepareIteratorResult()) {
7037 // [stack] NEXT ITER VALUE RESULT
7038 return false;
7039 }
7040 if (!emit1(JSOp::Swap)) {
7041 // [stack] NEXT ITER RESULT VALUE
7042 return false;
7043 }
7044 if (!emitFinishIteratorResult(true)) {
7045 // [stack] NEXT ITER RESULT
7046 return false;
7047 }
7048 }
7049
7050 if (!ifReturnDone.emitElse()) {
7051 // [stack] NEXT ITER RESULT
7052 return false;
7053 }
7054
7055 // Jump to continue label for steps 7.c.ix-x.
7056 if (!emitJump(JSOp::Goto, &loopInfo.continues)) {
7057 // [stack] NEXT ITER RESULT
7058 return false;
7059 }
7060
7061 if (!ifReturnDone.emitEnd()) {
7062 // [stack] NEXT ITER RESULT
7063 return false;
7064 }
7065
7066 // Step 7.c.iii.
7067 if (!ifReturnMethodIsDefined.emitElse()) {
7068 // [stack] NEXT ITER RECEIVED ITER RET
7069 return false;
7070 }
7071 if (!emitPopN(2)) {
7072 // [stack] NEXT ITER RECEIVED
7073 return false;
7074 }
7075 if (iterKind == IteratorKind::Async) {
7076 // Step 7.c.iii.1.
7077 if (!emitAwaitInInnermostScope()) {
7078 // [stack] NEXT ITER RECEIVED
7079 return false;
7080 }
7081 }
7082 if (!ifReturnMethodIsDefined.emitEnd()) {
7083 // [stack] NEXT ITER RECEIVED
7084 return false;
7085 }
7086
7087 // Perform a "forced generator return".
7088 //
7089 // Step 7.c.iii.2.
7090 // Step 7.c.viii.2.
7091 if (!emitGetDotGeneratorInInnermostScope()) {
7092 // [stack] NEXT ITER RESULT GENOBJ
7093 return false;
7094 }
7095 if (!emitPushResumeKind(GeneratorResumeKind::Return)) {
7096 // [stack] NEXT ITER RESULT GENOBJ RESUMEKIND
7097 return false;
7098 }
7099 if (!emit1(JSOp::CheckResumeKind)) {
7100 // [stack] NEXT ITER RESULT GENOBJ RESUMEKIND
7101 return false;
7102 }
7103 }
7104
7105 if (!ifKind.emitEnd()) {
7106 // [stack] NEXT ITER RESULT
7107 return false;
7108 }
7109
7110 // Shared tail for Normal/Throw completions.
7111 //
7112 // Steps 7.a.iv-v.
7113 // Steps 7.b.ii.5-6.
7114 //
7115 // [stack] NEXT ITER RESULT
7116
7117 // if (result.done) break;
7118 if (!emit1(JSOp::Dup)) {
7119 // [stack] NEXT ITER RESULT RESULT
7120 return false;
7121 }
7122 if (!emitAtomOp(JSOp::GetProp, TaggedParserAtomIndex::WellKnown::done())) {
7123 // [stack] NEXT ITER RESULT DONE
7124 return false;
7125 }
7126 if (!emitJump(JSOp::JumpIfTrue, &loopInfo.breaks)) {
7127 // [stack] NEXT ITER RESULT
7128 return false;
7129 }
7130
7131 // Steps 7.a.vi-vii.
7132 // Steps 7.b.ii.7-8.
7133 // Steps 7.c.ix-x.
7134 if (!loopInfo.emitContinueTarget(this)) {
7135 // [stack] NEXT ITER RESULT
7136 return false;
7137 }
7138 if (iterKind == IteratorKind::Async) {
7139 if (!emitAtomOp(JSOp::GetProp, TaggedParserAtomIndex::WellKnown::value())) {
7140 // [stack] NEXT ITER RESULT
7141 return false;
7142 }
7143 }
7144 if (!emitGetDotGeneratorInInnermostScope()) {
7145 // [stack] NEXT ITER RESULT GENOBJ
7146 return false;
7147 }
7148 if (!emitYieldOp(JSOp::Yield)) {
7149 // [stack] NEXT ITER RVAL GENOBJ RESUMEKIND
7150 return false;
7151 }
7152 if (!emit1(JSOp::Swap)) {
7153 // [stack] NEXT ITER RVAL RESUMEKIND GENOBJ
7154 return false;
7155 }
7156 if (!emit1(JSOp::Pop)) {
7157 // [stack] NEXT ITER RVAL RESUMEKIND
7158 return false;
7159 }
7160 if (!loopInfo.emitLoopEnd(this, JSOp::Goto, TryNoteKind::Loop)) {
7161 // [stack] NEXT ITER RVAL RESUMEKIND
7162 return false;
7163 }
7164
7165 // Jumps to this point have 3 (instead of 4) values on the stack.
7166 MOZ_ASSERT(bytecodeSection().stackDepth() == startDepth);
7167 bytecodeSection().setStackDepth(startDepth - 1);
7168
7169 // [stack] NEXT ITER RESULT
7170
7171 // Step 7.a.v.1.
7172 // Step 7.b.ii.6.a.
7173 //
7174 // result.value
7175 if (!emit2(JSOp::Unpick, 2)) {
7176 // [stack] RESULT NEXT ITER
7177 return false;
7178 }
7179 if (!emitPopN(2)) {
7180 // [stack] RESULT
7181 return false;
7182 }
7183 if (!emitAtomOp(JSOp::GetProp, TaggedParserAtomIndex::WellKnown::value())) {
7184 // [stack] VALUE
7185 return false;
7186 }
7187
7188 MOZ_ASSERT(bytecodeSection().stackDepth() == startDepth - 3);
7189
7190 return true;
7191 }
7192
7193 bool BytecodeEmitter::emitStatementList(ListNode* stmtList) {
7194 for (ParseNode* stmt : stmtList->contents()) {
7195 if (!emitTree(stmt)) {
7196 return false;
7197 }
7198 }
7199 return true;
7200 }
7201
7202 bool BytecodeEmitter::emitExpressionStatement(UnaryNode* exprStmt) {
7203 MOZ_ASSERT(exprStmt->isKind(ParseNodeKind::ExpressionStmt));
7204
7205 /*
7206 * Top-level or called-from-a-native JS_Execute/EvaluateScript,
7207 * debugger, and eval frames may need the value of the ultimate
7208 * expression statement as the script's result, despite the fact
7209 * that it appears useless to the compiler.
7210 *
7211 * API users may also set the ReadOnlyCompileOptions::noScriptRval option when
7212 * calling JS_Compile* to suppress JSOp::SetRval.
7213 */
7214 bool wantval = false;
7215 bool useful = false;
7216 if (sc->isTopLevelContext()) {
7217 useful = wantval = !sc->noScriptRval();
7218 }
7219
7220 /* Don't eliminate expressions with side effects. */
7221 ParseNode* expr = exprStmt->kid();
7222 if (!useful) {
7223 if (!checkSideEffects(expr, &useful)) {
7224 return false;
7225 }
7226
7227 /*
7228 * Don't eliminate apparently useless expressions if they are labeled
7229 * expression statements. The startOffset() test catches the case
7230 * where we are nesting in emitTree for a labeled compound statement.
7231 */
7232 if (innermostNestableControl &&
7233 innermostNestableControl->is<LabelControl>() &&
7234 innermostNestableControl->as<LabelControl>().startOffset() >=
7235 bytecodeSection().offset()) {
7236 useful = true;
7237 }
7238 }
7239
7240 if (useful) {
7241 ValueUsage valueUsage =
7242 wantval ? ValueUsage::WantValue : ValueUsage::IgnoreValue;
7243 ExpressionStatementEmitter ese(this, valueUsage);
7244 if (!ese.prepareForExpr(exprStmt->pn_pos.begin)) {
7245 return false;
7246 }
7247 if (!markStepBreakpoint()) {
7248 return false;
7249 }
7250 if (!emitTree(expr, valueUsage)) {
7251 return false;
7252 }
7253 if (!ese.emitEnd()) {
7254 return false;
7255 }
7256 }
7257
7258 return true;
7259 }
7260
7261 bool BytecodeEmitter::emitDeleteName(UnaryNode* deleteNode) {
7262 MOZ_ASSERT(deleteNode->isKind(ParseNodeKind::DeleteNameExpr));
7263
7264 NameNode* nameExpr = &deleteNode->kid()->as<NameNode>();
7265 MOZ_ASSERT(nameExpr->isKind(ParseNodeKind::Name));
7266
7267 return emitAtomOp(JSOp::DelName, nameExpr->atom());
7268 }
7269
7270 bool BytecodeEmitter::emitDeleteProperty(UnaryNode* deleteNode) {
7271 MOZ_ASSERT(deleteNode->isKind(ParseNodeKind::DeletePropExpr));
7272
7273 PropertyAccess* propExpr = &deleteNode->kid()->as<PropertyAccess>();
7274 PropOpEmitter poe(this, PropOpEmitter::Kind::Delete,
7275 propExpr->as<PropertyAccess>().isSuper()
7276 ? PropOpEmitter::ObjKind::Super
7277 : PropOpEmitter::ObjKind::Other);
7278
7279 if (!poe.prepareForObj()) {
7280 return false;
7281 }
7282
7283 if (propExpr->isSuper()) {
7284 // The expression |delete super.foo;| has to evaluate |super.foo|, which
7285 // could throw if |this| hasn't yet been set by a |super(...)| call.
7286 auto* base = &propExpr->expression().as<UnaryNode>();
7287 if (!emitGetThisForSuperBase(base)) {
7288 // [stack] THIS
7289 return false;
7290 }
7291 } else {
7292 if (!emitPropLHS(propExpr)) {
7293 // [stack] OBJ
7294 return false;
7295 }
7296 }
7297
7298 if (!poe.emitDelete(propExpr->key().atom())) {
7299 // [stack] # if Super
7300 // [stack] THIS
7301 // [stack] # otherwise
7302 // [stack] SUCCEEDED
7303 return false;
7304 }
7305
7306 return true;
7307 }
7308
7309 bool BytecodeEmitter::emitDeleteElement(UnaryNode* deleteNode) {
7310 MOZ_ASSERT(deleteNode->isKind(ParseNodeKind::DeleteElemExpr));
7311
7312 auto* elemExpr = &deleteNode->kid()->as<PropertyByValue>();
7313 bool isSuper = elemExpr->isSuper();
7314 MOZ_ASSERT(!elemExpr->key().isKind(ParseNodeKind::PrivateName));
7315 ElemOpEmitter eoe(
7316 this, ElemOpEmitter::Kind::Delete,
7317 isSuper ? ElemOpEmitter::ObjKind::Super : ElemOpEmitter::ObjKind::Other);
7318
7319 if (!emitElemObjAndKey(elemExpr, eoe)) {
7320 // [stack] # if Super
7321 // [stack] THIS KEY
7322 // [stack] # otherwise
7323 // [stack] OBJ KEY
7324 return false;
7325 }
7326
7327 if (!eoe.emitDelete()) {
7328 // [stack] # if Super
7329 // [stack] THIS
7330 // [stack] # otherwise
7331 // [stack] SUCCEEDED
7332 return false;
7333 }
7334
7335 return true;
7336 }
7337
7338 bool BytecodeEmitter::emitDeleteExpression(UnaryNode* deleteNode) {
7339 MOZ_ASSERT(deleteNode->isKind(ParseNodeKind::DeleteExpr));
7340
7341 ParseNode* expression = deleteNode->kid();
7342
7343 // If useless, just emit JSOp::True; otherwise convert |delete <expr>| to
7344 // effectively |<expr>, true|.
7345 bool useful = false;
7346 if (!checkSideEffects(expression, &useful)) {
7347 return false;
7348 }
7349
7350 if (useful) {
7351 if (!emitTree(expression)) {
7352 return false;
7353 }
7354 if (!emit1(JSOp::Pop)) {
7355 return false;
7356 }
7357 }
7358
7359 return emit1(JSOp::True);
7360 }
7361
7362 bool BytecodeEmitter::emitDeleteOptionalChain(UnaryNode* deleteNode) {
7363 MOZ_ASSERT(deleteNode->isKind(ParseNodeKind::DeleteOptionalChainExpr));
7364
7365 OptionalEmitter oe(this, bytecodeSection().stackDepth());
7366
7367 ParseNode* kid = deleteNode->kid();
7368 switch (kid->getKind()) {
7369 case ParseNodeKind::ElemExpr:
7370 case ParseNodeKind::OptionalElemExpr: {
7371 auto* elemExpr = &kid->as<PropertyByValueBase>();
7372 if (!emitDeleteElementInOptChain(elemExpr, oe)) {
7373 // [stack] # If shortcircuit
7374 // [stack] UNDEFINED-OR-NULL
7375 // [stack] # otherwise
7376 // [stack] SUCCEEDED
7377 return false;
7378 }
7379
7380 break;
7381 }
7382 case ParseNodeKind::ArgumentsLength:
7383 case ParseNodeKind::DotExpr:
7384 case ParseNodeKind::OptionalDotExpr: {
7385 auto* propExpr = &kid->as<PropertyAccessBase>();
7386 if (!emitDeletePropertyInOptChain(propExpr, oe)) {
7387 // [stack] # If shortcircuit
7388 // [stack] UNDEFINED-OR-NULL
7389 // [stack] # otherwise
7390 // [stack] SUCCEEDED
7391 return false;
7392 }
7393 break;
7394 }
7395 default:
7396 MOZ_ASSERT_UNREACHABLE("Unrecognized optional delete ParseNodeKind");
7397 }
7398
7399 if (!oe.emitOptionalJumpTarget(JSOp::True)) {
7400 // [stack] # If shortcircuit
7401 // [stack] TRUE
7402 // [stack] # otherwise
7403 // [stack] SUCCEEDED
7404 return false;
7405 }
7406
7407 return true;
7408 }
7409
7410 bool BytecodeEmitter::emitDeletePropertyInOptChain(PropertyAccessBase* propExpr,
7411 OptionalEmitter& oe) {
7412 MOZ_ASSERT_IF(propExpr->is<PropertyAccess>(),
7413 !propExpr->as<PropertyAccess>().isSuper());
7414 PropOpEmitter poe(this, PropOpEmitter::Kind::Delete,
7415 PropOpEmitter::ObjKind::Other);
7416
7417 if (!poe.prepareForObj()) {
7418 // [stack]
7419 return false;
7420 }
7421 if (!emitOptionalTree(&propExpr->expression(), oe)) {
7422 // [stack] OBJ
7423 return false;
7424 }
7425 if (propExpr->isKind(ParseNodeKind::OptionalDotExpr)) {
7426 if (!oe.emitJumpShortCircuit()) {
7427 // [stack] # if Jump
7428 // [stack] UNDEFINED-OR-NULL
7429 // [stack] # otherwise
7430 // [stack] OBJ
7431 return false;
7432 }
7433 }
7434
7435 if (!poe.emitDelete(propExpr->key().atom())) {
7436 // [stack] SUCCEEDED
7437 return false;
7438 }
7439
7440 return true;
7441 }
7442
7443 bool BytecodeEmitter::emitDeleteElementInOptChain(PropertyByValueBase* elemExpr,
7444 OptionalEmitter& oe) {
7445 MOZ_ASSERT_IF(elemExpr->is<PropertyByValue>(),
7446 !elemExpr->as<PropertyByValue>().isSuper());
7447 ElemOpEmitter eoe(this, ElemOpEmitter::Kind::Delete,
7448 ElemOpEmitter::ObjKind::Other);
7449
7450 if (!eoe.prepareForObj()) {
7451 // [stack]
7452 return false;
7453 }
7454
7455 if (!emitOptionalTree(&elemExpr->expression(), oe)) {
7456 // [stack] OBJ
7457 return false;
7458 }
7459
7460 if (elemExpr->isKind(ParseNodeKind::OptionalElemExpr)) {
7461 if (!oe.emitJumpShortCircuit()) {
7462 // [stack] # if Jump
7463 // [stack] UNDEFINED-OR-NULL
7464 // [stack] # otherwise
7465 // [stack] OBJ
7466 return false;
7467 }
7468 }
7469
7470 if (!eoe.prepareForKey()) {
7471 // [stack] OBJ
7472 return false;
7473 }
7474
7475 if (!emitTree(&elemExpr->key())) {
7476 // [stack] OBJ KEY
7477 return false;
7478 }
7479
7480 if (!eoe.emitDelete()) {
7481 // [stack] SUCCEEDED
7482 return false;
7483 }
7484
7485 return true;
7486 }
7487
7488 bool BytecodeEmitter::emitDebugCheckSelfHosted() {
7489 // [stack] CALLEE
7490
7491 #ifdef DEBUG
7492 if (!emit1(JSOp::DebugCheckSelfHosted)) {
7493 // [stack] CALLEE
7494 return false;
7495 }
7496 #endif
7497
7498 return true;
7499 }
7500
7501 bool BytecodeEmitter::emitSelfHostedCallFunction(CallNode* callNode, JSOp op) {
7502 // Special-casing of callFunction to emit bytecode that directly
7503 // invokes the callee with the correct |this| object and arguments.
7504 // callFunction(fun, thisArg, arg0, arg1) thus becomes:
7505 // - emit lookup for fun
7506 // - emit lookup for thisArg
7507 // - emit lookups for arg0, arg1
7508 //
7509 // argc is set to the amount of actually emitted args and the
7510 // emitting of args below is disabled by setting emitArgs to false.
7511 NameNode* calleeNode = &callNode->callee()->as<NameNode>();
7512 ListNode* argsList = callNode->args();
7513
7514 MOZ_ASSERT(argsList->count() >= 2);
7515
7516 MOZ_ASSERT(callNode->callOp() == JSOp::Call);
7517
7518 bool constructing =
7519 calleeNode->name() ==
7520 TaggedParserAtomIndex::WellKnown::constructContentFunction();
7521 ParseNode* funNode = argsList->head();
7522
7523 if (!emitTree(funNode)) {
7524 // [stack] CALLEE
7525 return false;
7526 }
7527
7528 #ifdef DEBUG
7529 MOZ_ASSERT(op == JSOp::Call || op == JSOp::CallContent ||
7530 op == JSOp::NewContent);
7531 if (op == JSOp::Call) {
7532 if (!emitDebugCheckSelfHosted()) {
7533 // [stack] CALLEE
7534 return false;
7535 }
7536 }
7537 #endif
7538
7539 ParseNode* thisOrNewTarget = funNode->pn_next;
7540 if (constructing) {
7541 // Save off the new.target value, but here emit a proper |this| for a
7542 // constructing call.
7543 if (!emit1(JSOp::IsConstructing)) {
7544 // [stack] CALLEE IS_CONSTRUCTING
7545 return false;
7546 }
7547 } else {
7548 // It's |this|, emit it.
7549 if (!emitTree(thisOrNewTarget)) {
7550 // [stack] CALLEE THIS
7551 return false;
7552 }
7553 }
7554
7555 for (ParseNode* argpn : argsList->contentsFrom(thisOrNewTarget->pn_next)) {
7556 if (!emitTree(argpn)) {
7557 // [stack] CALLEE ... ARGS...
7558 return false;
7559 }
7560 }
7561
7562 if (constructing) {
7563 if (!emitTree(thisOrNewTarget)) {
7564 // [stack] CALLEE IS_CONSTRUCTING ARGS... NEW.TARGET
7565 return false;
7566 }
7567 }
7568
7569 uint32_t argc = argsList->count() - 2;
7570 if (!emitCall(op, argc)) {
7571 // [stack] RVAL
7572 return false;
7573 }
7574
7575 return true;
7576 }
7577
7578 bool BytecodeEmitter::emitSelfHostedResumeGenerator(CallNode* callNode) {
7579 ListNode* argsList = callNode->args();
7580
7581 // Syntax: resumeGenerator(gen, value, 'next'|'throw'|'return')
7582 MOZ_ASSERT(argsList->count() == 3);
7583
7584 ParseNode* genNode = argsList->head();
7585 if (!emitTree(genNode)) {
7586 // [stack] GENERATOR
7587 return false;
7588 }
7589
7590 ParseNode* valNode = genNode->pn_next;
7591 if (!emitTree(valNode)) {
7592 // [stack] GENERATOR VALUE
7593 return false;
7594 }
7595
7596 ParseNode* kindNode = valNode->pn_next;
7597 MOZ_ASSERT(kindNode->isKind(ParseNodeKind::StringExpr));
7598 GeneratorResumeKind kind =
7599 ParserAtomToResumeKind(kindNode->as<NameNode>().atom());
7600 MOZ_ASSERT(!kindNode->pn_next);
7601
7602 if (!emitPushResumeKind(kind)) {
7603 // [stack] GENERATOR VALUE RESUMEKIND
7604 return false;
7605 }
7606
7607 if (!emit1(JSOp::Resume)) {
7608 // [stack] RVAL
7609 return false;
7610 }
7611
7612 return true;
7613 }
7614
7615 bool BytecodeEmitter::emitSelfHostedForceInterpreter() {
7616 // JSScript::hasForceInterpreterOp() relies on JSOp::ForceInterpreter being
7617 // the first bytecode op in the script.
7618 MOZ_ASSERT(bytecodeSection().code().empty());
7619
7620 if (!emit1(JSOp::ForceInterpreter)) {
7621 return false;
7622 }
7623 if (!emit1(JSOp::Undefined)) {
7624 return false;
7625 }
7626
7627 return true;
7628 }
7629
7630 bool BytecodeEmitter::emitSelfHostedAllowContentIter(CallNode* callNode) {
7631 ListNode* argsList = callNode->args();
7632
7633 MOZ_ASSERT(argsList->count() == 1);
7634
7635 // We're just here as a sentinel. Pass the value through directly.
7636 return emitTree(argsList->head());
7637 }
7638
7639 bool BytecodeEmitter::emitSelfHostedAllowContentIterWith(CallNode* callNode) {
7640 ListNode* argsList = callNode->args();
7641
7642 MOZ_ASSERT(argsList->count() == 2 || argsList->count() == 3);
7643
7644 // We're just here as a sentinel. Pass the value through directly.
7645 return emitTree(argsList->head());
7646 }
7647
7648 bool BytecodeEmitter::emitSelfHostedAllowContentIterWithNext(
7649 CallNode* callNode) {
7650 ListNode* argsList = callNode->args();
7651
7652 MOZ_ASSERT(argsList->count() == 2);
7653
7654 // We're just here as a sentinel. Pass the value through directly.
7655 return emitTree(argsList->head());
7656 }
7657
7658 bool BytecodeEmitter::emitSelfHostedDefineDataProperty(CallNode* callNode) {
7659 ListNode* argsList = callNode->args();
7660
7661 // Only optimize when 3 arguments are passed.
7662 MOZ_ASSERT(argsList->count() == 3);
7663
7664 ParseNode* objNode = argsList->head();
7665 if (!emitTree(objNode)) {
7666 return false;
7667 }
7668
7669 ParseNode* idNode = objNode->pn_next;
7670 if (!emitTree(idNode)) {
7671 return false;
7672 }
7673
7674 ParseNode* valNode = idNode->pn_next;
7675 if (!emitTree(valNode)) {
7676 return false;
7677 }
7678
7679 // This will leave the object on the stack instead of pushing |undefined|,
7680 // but that's fine because the self-hosted code doesn't use the return
7681 // value.
7682 return emit1(JSOp::InitElem);
7683 }
7684
7685 bool BytecodeEmitter::emitSelfHostedHasOwn(CallNode* callNode) {
7686 ListNode* argsList = callNode->args();
7687
7688 MOZ_ASSERT(argsList->count() == 2);
7689
7690 ParseNode* idNode = argsList->head();
7691 if (!emitTree(idNode)) {
7692 return false;
7693 }
7694
7695 ParseNode* objNode = idNode->pn_next;
7696 if (!emitTree(objNode)) {
7697 return false;
7698 }
7699
7700 return emit1(JSOp::HasOwn);
7701 }
7702
7703 bool BytecodeEmitter::emitSelfHostedGetPropertySuper(CallNode* callNode) {
7704 ListNode* argsList = callNode->args();
7705
7706 MOZ_ASSERT(argsList->count() == 3);
7707
7708 ParseNode* objNode = argsList->head();
7709 ParseNode* idNode = objNode->pn_next;
7710 ParseNode* receiverNode = idNode->pn_next;
7711
7712 if (!emitTree(receiverNode)) {
7713 return false;
7714 }
7715
7716 if (!emitTree(idNode)) {
7717 return false;
7718 }
7719
7720 if (!emitTree(objNode)) {
7721 return false;
7722 }
7723
7724 return emitElemOpBase(JSOp::GetElemSuper);
7725 }
7726
7727 bool BytecodeEmitter::emitSelfHostedToNumeric(CallNode* callNode) {
7728 ListNode* argsList = callNode->args();
7729
7730 MOZ_ASSERT(argsList->count() == 1);
7731
7732 ParseNode* argNode = argsList->head();
7733
7734 if (!emitTree(argNode)) {
7735 return false;
7736 }
7737
7738 return emit1(JSOp::ToNumeric);
7739 }
7740
7741 bool BytecodeEmitter::emitSelfHostedToString(CallNode* callNode) {
7742 ListNode* argsList = callNode->args();
7743
7744 MOZ_ASSERT(argsList->count() == 1);
7745
7746 ParseNode* argNode = argsList->head();
7747
7748 if (!emitTree(argNode)) {
7749 return false;
7750 }
7751
7752 return emit1(JSOp::ToString);
7753 }
7754
7755 bool BytecodeEmitter::emitSelfHostedIsNullOrUndefined(CallNode* callNode) {
7756 ListNode* argsList = callNode->args();
7757
7758 MOZ_ASSERT(argsList->count() == 1);
7759
7760 ParseNode* argNode = argsList->head();
7761
7762 if (!emitTree(argNode)) {
7763 // [stack] ARG
7764 return false;
7765 }
7766 if (!emit1(JSOp::IsNullOrUndefined)) {
7767 // [stack] ARG IS_NULL_OR_UNDEF
7768 return false;
7769 }
7770 if (!emit1(JSOp::Swap)) {
7771 // [stack] IS_NULL_OR_UNDEF ARG
7772 return false;
7773 }
7774 if (!emit1(JSOp::Pop)) {
7775 // [stack] IS_NULL_OR_UNDEF
7776 return false;
7777 }
7778 return true;
7779 }
7780
7781 bool BytecodeEmitter::emitSelfHostedIteratorClose(CallNode* callNode) {
7782 ListNode* argsList = callNode->args();
7783 MOZ_ASSERT(argsList->count() == 1);
7784
7785 ParseNode* argNode = argsList->head();
7786 if (!emitTree(argNode)) {
7787 // [stack] ARG
7788 return false;
7789 }
7790
7791 if (!emit2(JSOp::CloseIter, uint8_t(CompletionKind::Normal))) {
7792 // [stack]
7793 return false;
7794 }
7795
7796 // This is still a call node, so we must generate a stack value.
7797 if (!emit1(JSOp::Undefined)) {
7798 // [stack] RVAL
7799 return false;
7800 }
7801
7802 return true;
7803 }
7804
7805 bool BytecodeEmitter::emitSelfHostedGetBuiltinConstructorOrPrototype(
7806 CallNode* callNode, bool isConstructor) {
7807 ListNode* argsList = callNode->args();
7808
7809 MOZ_ASSERT(argsList->count() == 1);
7810
7811 ParseNode* argNode = argsList->head();
7812
7813 if (!argNode->isKind(ParseNodeKind::StringExpr)) {
7814 reportError(callNode, JSMSG_UNEXPECTED_TYPE, "built-in name",
7815 "not a string constant");
7816 return false;
7817 }
7818
7819 auto name = argNode->as<NameNode>().atom();
7820
7821 BuiltinObjectKind kind;
7822 if (isConstructor) {
7823 kind = BuiltinConstructorForName(name);
7824 } else {
7825 kind = BuiltinPrototypeForName(name);
7826 }
7827
7828 if (kind == BuiltinObjectKind::None) {
7829 reportError(callNode, JSMSG_UNEXPECTED_TYPE, "built-in name",
7830 "not a valid built-in");
7831 return false;
7832 }
7833
7834 return emitBuiltinObject(kind);
7835 }
7836
7837 bool BytecodeEmitter::emitSelfHostedGetBuiltinConstructor(CallNode* callNode) {
7838 return emitSelfHostedGetBuiltinConstructorOrPrototype(
7839 callNode, /* isConstructor = */ true);
7840 }
7841
7842 bool BytecodeEmitter::emitSelfHostedGetBuiltinPrototype(CallNode* callNode) {
7843 return emitSelfHostedGetBuiltinConstructorOrPrototype(
7844 callNode, /* isConstructor = */ false);
7845 }
7846
7847 JS::SymbolCode ParserAtomToSymbolCode(TaggedParserAtomIndex atom) {
7848 // NOTE: This is a linear search, but the set of entries is quite small and
7849 // this is only used for initial self-hosted parse.
7850 #define MATCH_WELL_KNOWN_SYMBOL(NAME) \
7851 if (atom == TaggedParserAtomIndex::WellKnown::NAME()) { \
7852 return JS::SymbolCode::NAME; \
7853 }
7854 JS_FOR_EACH_WELL_KNOWN_SYMBOL(MATCH_WELL_KNOWN_SYMBOL)
7855 #undef MATCH_WELL_KNOWN_SYMBOL
7856
7857 return JS::SymbolCode::Limit;
7858 }
7859
7860 bool BytecodeEmitter::emitSelfHostedGetBuiltinSymbol(CallNode* callNode) {
7861 ListNode* argsList = callNode->args();
7862
7863 MOZ_ASSERT(argsList->count() == 1);
7864
7865 ParseNode* argNode = argsList->head();
7866
7867 if (!argNode->isKind(ParseNodeKind::StringExpr)) {
7868 reportError(callNode, JSMSG_UNEXPECTED_TYPE, "built-in name",
7869 "not a string constant");
7870 return false;
7871 }
7872
7873 auto name = argNode->as<NameNode>().atom();
7874
7875 JS::SymbolCode code = ParserAtomToSymbolCode(name);
7876 if (code == JS::SymbolCode::Limit) {
7877 reportError(callNode, JSMSG_UNEXPECTED_TYPE, "built-in name",
7878 "not a valid built-in");
7879 return false;
7880 }
7881
7882 return emit2(JSOp::Symbol, uint8_t(code));
7883 }
7884
7885 bool BytecodeEmitter::emitSelfHostedArgumentsLength(CallNode* callNode) {
7886 MOZ_ASSERT(!sc->asFunctionBox()->needsArgsObj());
7887 sc->asFunctionBox()->setUsesArgumentsIntrinsics();
7888
7889 MOZ_ASSERT(callNode->args()->count() == 0);
7890
7891 return emit1(JSOp::ArgumentsLength);
7892 }
7893
7894 bool BytecodeEmitter::emitSelfHostedGetArgument(CallNode* callNode) {
7895 MOZ_ASSERT(!sc->asFunctionBox()->needsArgsObj());
7896 sc->asFunctionBox()->setUsesArgumentsIntrinsics();
7897
7898 ListNode* argsList = callNode->args();
7899 MOZ_ASSERT(argsList->count() == 1);
7900
7901 ParseNode* argNode = argsList->head();
7902 if (!emitTree(argNode)) {
7903 return false;
7904 }
7905
7906 return emit1(JSOp::GetActualArg);
7907 }
7908
7909 #ifdef DEBUG
7910 void BytecodeEmitter::assertSelfHostedExpectedTopLevel(ParseNode* node) {
7911 // The function argument is expected to be a simple binding/function name.
7912 // Eg. `function foo() { }; SpecialIntrinsic(foo)`
7913 MOZ_ASSERT(node->isKind(ParseNodeKind::Name),
7914 "argument must be a function name");
7915 TaggedParserAtomIndex targetName = node->as<NameNode>().name();
7916
7917 // The special intrinsics must follow the target functions definition. A
7918 // simple assert is fine here since any hoisted function will cause a non-null
7919 // value to be set here.
7920 MOZ_ASSERT(prevSelfHostedTopLevelFunction);
7921
7922 // The target function must match the most recently defined top-level
7923 // self-hosted function.
7924 MOZ_ASSERT(prevSelfHostedTopLevelFunction->explicitName() == targetName,
7925 "selfhost decorator must immediately follow target function");
7926 }
7927 #endif
7928
7929 bool BytecodeEmitter::emitSelfHostedSetIsInlinableLargeFunction(
7930 CallNode* callNode) {
7931 #ifdef DEBUG
7932 ListNode* argsList = callNode->args();
7933
7934 MOZ_ASSERT(argsList->count() == 1);
7935
7936 assertSelfHostedExpectedTopLevel(argsList->head());
7937 #endif
7938
7939 MOZ_ASSERT(prevSelfHostedTopLevelFunction->isInitialCompilation);
7940 prevSelfHostedTopLevelFunction->setIsInlinableLargeFunction();
7941
7942 // This is still a call node, so we must generate a stack value.
7943 return emit1(JSOp::Undefined);
7944 }
7945
7946 bool BytecodeEmitter::emitSelfHostedSetCanonicalName(CallNode* callNode) {
7947 ListNode* argsList = callNode->args();
7948
7949 MOZ_ASSERT(argsList->count() == 2);
7950
7951 #ifdef DEBUG
7952 assertSelfHostedExpectedTopLevel(argsList->head());
7953 #endif
7954
7955 ParseNode* nameNode = argsList->last();
7956 MOZ_ASSERT(nameNode->isKind(ParseNodeKind::StringExpr));
7957 TaggedParserAtomIndex specName = nameNode->as<NameNode>().atom();
7958 // Canonical name must be atomized.
7959 compilationState.parserAtoms.markUsedByStencil(specName,
7960 ParserAtom::Atomize::Yes);
7961
7962 // Store the canonical name for instantiation.
7963 prevSelfHostedTopLevelFunction->functionStencil().setSelfHostedCanonicalName(
7964 specName);
7965
7966 return emit1(JSOp::Undefined);
7967 }
7968
7969 #ifdef DEBUG
7970 void BytecodeEmitter::assertSelfHostedUnsafeGetReservedSlot(
7971 ListNode* argsList) {
7972 MOZ_ASSERT(argsList->count() == 2);
7973
7974 ParseNode* objNode = argsList->head();
7975 ParseNode* slotNode = objNode->pn_next;
7976
7977 // Ensure that the slot argument is fixed, this is required by the JITs.
7978 MOZ_ASSERT(slotNode->isKind(ParseNodeKind::NumberExpr),
7979 "slot argument must be a constant");
7980 }
7981
7982 void BytecodeEmitter::assertSelfHostedUnsafeSetReservedSlot(
7983 ListNode* argsList) {
7984 MOZ_ASSERT(argsList->count() == 3);
7985
7986 ParseNode* objNode = argsList->head();
7987 ParseNode* slotNode = objNode->pn_next;
7988
7989 // Ensure that the slot argument is fixed, this is required by the JITs.
7990 MOZ_ASSERT(slotNode->isKind(ParseNodeKind::NumberExpr),
7991 "slot argument must be a constant");
7992 }
7993 #endif
7994
7995 /* A version of emitCalleeAndThis for the optional cases:
7996 * * a?.()
7997 * * a?.b()
7998 * * a?.["b"]()
7999 * * (a?.b)()
8000 * * a?.#b()
8001 *
8002 * See emitCallOrNew and emitOptionalCall for more context.
8003 */
8004 bool BytecodeEmitter::emitOptionalCalleeAndThis(ParseNode* callee,
8005 CallNode* call,
8006 CallOrNewEmitter& cone,
8007 OptionalEmitter& oe) {
8008 AutoCheckRecursionLimit recursion(fc);
8009 if (!recursion.check(fc)) {
8010 return false;
8011 }
8012
8013 switch (ParseNodeKind kind = callee->getKind()) {
8014 case ParseNodeKind::Name: {
8015 auto name = callee->as<NameNode>().name();
8016 if (!cone.emitNameCallee(name)) {
8017 // [stack] CALLEE THIS
8018 return false;
8019 }
8020 break;
8021 }
8022
8023 case ParseNodeKind::OptionalDotExpr: {
8024 MOZ_ASSERT(emitterMode != BytecodeEmitter::SelfHosting);
8025 OptionalPropertyAccess* prop = &callee->as<OptionalPropertyAccess>();
8026 bool isSuper = false;
8027
8028 PropOpEmitter& poe = cone.prepareForPropCallee(isSuper);
8029 if (!emitOptionalDotExpression(prop, poe, isSuper, oe)) {
8030 // [stack] CALLEE THIS
8031 return false;
8032 }
8033 break;
8034 }
8035 case ParseNodeKind::ArgumentsLength:
8036 case ParseNodeKind::DotExpr: {
8037 MOZ_ASSERT(emitterMode != BytecodeEmitter::SelfHosting);
8038 PropertyAccess* prop = &callee->as<PropertyAccess>();
8039 bool isSuper = prop->isSuper();
8040
8041 PropOpEmitter& poe = cone.prepareForPropCallee(isSuper);
8042 if (!emitOptionalDotExpression(prop, poe, isSuper, oe)) {
8043 // [stack] CALLEE THIS
8044 return false;
8045 }
8046 break;
8047 }
8048
8049 case ParseNodeKind::OptionalElemExpr: {
8050 OptionalPropertyByValue* elem = &callee->as<OptionalPropertyByValue>();
8051 bool isSuper = false;
8052 MOZ_ASSERT(!elem->key().isKind(ParseNodeKind::PrivateName));
8053 ElemOpEmitter& eoe = cone.prepareForElemCallee(isSuper);
8054 if (!emitOptionalElemExpression(elem, eoe, isSuper, oe)) {
8055 // [stack] CALLEE THIS
8056 return false;
8057 }
8058 break;
8059 }
8060 case ParseNodeKind::ElemExpr: {
8061 PropertyByValue* elem = &callee->as<PropertyByValue>();
8062 bool isSuper = elem->isSuper();
8063 MOZ_ASSERT(!elem->key().isKind(ParseNodeKind::PrivateName));
8064 ElemOpEmitter& eoe = cone.prepareForElemCallee(isSuper);
8065 if (!emitOptionalElemExpression(elem, eoe, isSuper, oe)) {
8066 // [stack] CALLEE THIS
8067 return false;
8068 }
8069 break;
8070 }
8071
8072 case ParseNodeKind::PrivateMemberExpr:
8073 case ParseNodeKind::OptionalPrivateMemberExpr: {
8074 PrivateMemberAccessBase* privateExpr =
8075 &callee->as<PrivateMemberAccessBase>();
8076 PrivateOpEmitter& xoe =
8077 cone.prepareForPrivateCallee(privateExpr->privateName().name());
8078 if (!emitOptionalPrivateExpression(privateExpr, xoe, oe)) {
8079 // [stack] CALLEE THIS
8080 return false;
8081 }
8082 break;
8083 }
8084
8085 case ParseNodeKind::Function:
8086 if (!cone.prepareForFunctionCallee()) {
8087 return false;
8088 }
8089 if (!emitOptionalTree(callee, oe)) {
8090 // [stack] CALLEE
8091 return false;
8092 }
8093 break;
8094
8095 case ParseNodeKind::OptionalChain: {
8096 return emitCalleeAndThisForOptionalChain(&callee->as<UnaryNode>(), call,
8097 cone);
8098 }
8099
8100 default:
8101 MOZ_RELEASE_ASSERT(kind != ParseNodeKind::SuperBase);
8102
8103 if (!cone.prepareForOtherCallee()) {
8104 return false;
8105 }
8106 if (!emitOptionalTree(callee, oe)) {
8107 // [stack] CALLEE
8108 return false;
8109 }
8110 break;
8111 }
8112
8113 if (!cone.emitThis()) {
8114 // [stack] CALLEE THIS
8115 return false;
8116 }
8117
8118 return true;
8119 }
8120
8121 bool BytecodeEmitter::emitCalleeAndThis(ParseNode* callee, CallNode* maybeCall,
8122 CallOrNewEmitter& cone) {
8123 MOZ_ASSERT_IF(maybeCall, maybeCall->callee() == callee);
8124
8125 switch (callee->getKind()) {
8126 case ParseNodeKind::Name: {
8127 auto name = callee->as<NameNode>().name();
8128 if (!cone.emitNameCallee(name)) {
8129 // [stack] CALLEE THIS?
8130 return false;
8131 }
8132 break;
8133 }
8134 case ParseNodeKind::ArgumentsLength:
8135 case ParseNodeKind::DotExpr: {
8136 MOZ_ASSERT(emitterMode != BytecodeEmitter::SelfHosting);
8137 PropertyAccess* prop = &callee->as<PropertyAccess>();
8138 bool isSuper = prop->isSuper();
8139
8140 PropOpEmitter& poe = cone.prepareForPropCallee(isSuper);
8141 if (!poe.prepareForObj()) {
8142 return false;
8143 }
8144 if (isSuper) {
8145 UnaryNode* base = &prop->expression().as<UnaryNode>();
8146 if (!emitGetThisForSuperBase(base)) {
8147 // [stack] THIS
8148 return false;
8149 }
8150 } else {
8151 if (!emitPropLHS(prop)) {
8152 // [stack] OBJ
8153 return false;
8154 }
8155 }
8156 if (!poe.emitGet(prop->key().atom())) {
8157 // [stack] CALLEE THIS?
8158 return false;
8159 }
8160
8161 break;
8162 }
8163 case ParseNodeKind::ElemExpr: {
8164 MOZ_ASSERT(emitterMode != BytecodeEmitter::SelfHosting);
8165 PropertyByValue* elem = &callee->as<PropertyByValue>();
8166 bool isSuper = elem->isSuper();
8167 MOZ_ASSERT(!elem->key().isKind(ParseNodeKind::PrivateName));
8168 ElemOpEmitter& eoe = cone.prepareForElemCallee(isSuper);
8169 if (!emitElemObjAndKey(elem, eoe)) {
8170 // [stack] # if Super
8171 // [stack] THIS? THIS KEY
8172 // [stack] # otherwise
8173 // [stack] OBJ? OBJ KEY
8174 return false;
8175 }
8176 if (!eoe.emitGet()) {
8177 // [stack] CALLEE THIS?
8178 return false;
8179 }
8180
8181 break;
8182 }
8183 case ParseNodeKind::PrivateMemberExpr: {
8184 MOZ_ASSERT(emitterMode != BytecodeEmitter::SelfHosting);
8185 PrivateMemberAccessBase* privateExpr =
8186 &callee->as<PrivateMemberAccessBase>();
8187 PrivateOpEmitter& xoe =
8188 cone.prepareForPrivateCallee(privateExpr->privateName().name());
8189 if (!emitTree(&privateExpr->expression())) {
8190 // [stack] OBJ
8191 return false;
8192 }
8193 if (!xoe.emitReference()) {
8194 // [stack] OBJ NAME
8195 return false;
8196 }
8197 if (!xoe.emitGetForCallOrNew()) {
8198 // [stack] CALLEE THIS
8199 return false;
8200 }
8201
8202 break;
8203 }
8204 case ParseNodeKind::Function:
8205 if (!cone.prepareForFunctionCallee()) {
8206 return false;
8207 }
8208 if (!emitTree(callee)) {
8209 // [stack] CALLEE
8210 return false;
8211 }
8212 break;
8213 case ParseNodeKind::SuperBase:
8214 MOZ_ASSERT(maybeCall);
8215 MOZ_ASSERT(maybeCall->isKind(ParseNodeKind::SuperCallExpr));
8216 MOZ_ASSERT(callee->isKind(ParseNodeKind::SuperBase));
8217 if (!cone.emitSuperCallee()) {
8218 // [stack] CALLEE IsConstructing
8219 return false;
8220 }
8221 break;
8222 case ParseNodeKind::OptionalChain: {
8223 MOZ_ASSERT(maybeCall);
8224 return emitCalleeAndThisForOptionalChain(&callee->as<UnaryNode>(),
8225 maybeCall, cone);
8226 }
8227 default:
8228 if (!cone.prepareForOtherCallee()) {
8229 return false;
8230 }
8231 if (!emitTree(callee)) {
8232 return false;
8233 }
8234 break;
8235 }
8236
8237 if (!cone.emitThis()) {
8238 // [stack] CALLEE THIS
8239 return false;
8240 }
8241
8242 return true;
8243 }
8244
8245 ParseNode* BytecodeEmitter::getCoordNode(ParseNode* callNode,
8246 ParseNode* calleeNode, JSOp op,
8247 ListNode* argsList) const {
8248 ParseNode* coordNode = callNode;
8249 if (op == JSOp::Call || op == JSOp::SpreadCall) {
8250 // Default to using the location of the `(` itself.
8251 // obj[expr]() // expression
8252 // ^ // column coord
8253 coordNode = argsList;
8254
8255 switch (calleeNode->getKind()) {
8256 case ParseNodeKind::ArgumentsLength:
8257 case ParseNodeKind::DotExpr:
8258 // Use the position of a property access identifier.
8259 //
8260 // obj().aprop() // expression
8261 // ^ // column coord
8262 //
8263 // Note: Because of the constant folding logic in FoldElement,
8264 // this case also applies for constant string properties.
8265 //
8266 // obj()['aprop']() // expression
8267 // ^ // column coord
8268 coordNode = &calleeNode->as<PropertyAccess>().key();
8269 break;
8270 case ParseNodeKind::Name: {
8271 // Use the start of callee name unless it is at a separator
8272 // or has no args.
8273 //
8274 // 2 + obj() // expression
8275 // ^ // column coord
8276 //
8277 if (argsList->empty() ||
8278 !bytecodeSection().atSeparator(calleeNode->pn_pos.begin)) {
8279 // Use the start of callee names.
8280 coordNode = calleeNode;
8281 }
8282 break;
8283 }
8284
8285 default:
8286 break;
8287 }
8288 }
8289 return coordNode;
8290 }
8291
8292 bool BytecodeEmitter::emitArguments(ListNode* argsList, bool isCall,
8293 bool isSpread, CallOrNewEmitter& cone) {
8294 uint32_t argc = argsList->count();
8295 if (argc >= ARGC_LIMIT) {
8296 reportError(argsList,
8297 isCall ? JSMSG_TOO_MANY_FUN_ARGS : JSMSG_TOO_MANY_CON_ARGS);
8298 return false;
8299 }
8300 if (!isSpread) {
8301 if (!cone.prepareForNonSpreadArguments()) {
8302 // [stack] CALLEE THIS
8303 return false;
8304 }
8305 for (ParseNode* arg : argsList->contents()) {
8306 if (!updateSourceCoordNotesIfNonLiteral(arg)) {
8307 return false;
8308 }
8309 if (!emitTree(arg)) {
8310 // [stack] CALLEE THIS ARG*
8311 return false;
8312 }
8313 }
8314 } else if (cone.wantSpreadOperand()) {
8315 auto* spreadNode = &argsList->head()->as<UnaryNode>();
8316 if (!updateSourceCoordNotesIfNonLiteral(spreadNode->kid())) {
8317 return false;
8318 }
8319 if (!emitTree(spreadNode->kid())) {
8320 // [stack] CALLEE THIS ARG0
8321 return false;
8322 }
8323
8324 if (!cone.emitSpreadArgumentsTest()) {
8325 // [stack] CALLEE THIS ARG0
8326 return false;
8327 }
8328
8329 if (cone.wantSpreadIteration()) {
8330 if (!emitSpreadIntoArray(spreadNode)) {
8331 // [stack] CALLEE THIS ARR
8332 return false;
8333 }
8334 }
8335
8336 if (!cone.emitSpreadArgumentsTestEnd()) {
8337 // [stack] CALLEE THIS ARR
8338 return false;
8339 }
8340 } else {
8341 if (!cone.prepareForSpreadArguments()) {
8342 // [stack] CALLEE THIS
8343 return false;
8344 }
8345 if (!emitArray(argsList)) {
8346 // [stack] CALLEE THIS ARR
8347 return false;
8348 }
8349 }
8350
8351 return true;
8352 }
8353
8354 bool BytecodeEmitter::emitOptionalCall(CallNode* callNode, OptionalEmitter& oe,
8355 ValueUsage valueUsage) {
8356 /*
8357 * A modified version of emitCallOrNew that handles optional calls.
8358 *
8359 * These include the following:
8360 * a?.()
8361 * a.b?.()
8362 * a.["b"]?.()
8363 * (a?.b)?.()
8364 *
8365 * See CallOrNewEmitter for more context.
8366 */
8367 ParseNode* calleeNode = callNode->callee();
8368 ListNode* argsList = callNode->args();
8369 bool isSpread = IsSpreadOp(callNode->callOp());
8370 JSOp op = callNode->callOp();
8371 uint32_t argc = argsList->count();
8372 bool isOptimizableSpread = isSpread && argc == 1;
8373
8374 CallOrNewEmitter cone(this, op,
8375 isOptimizableSpread
8376 ? CallOrNewEmitter::ArgumentsKind::SingleSpread
8377 : CallOrNewEmitter::ArgumentsKind::Other,
8378 valueUsage);
8379
8380 ParseNode* coordNode = getCoordNode(callNode, calleeNode, op, argsList);
8381
8382 if (!emitOptionalCalleeAndThis(calleeNode, callNode, cone, oe)) {
8383 // [stack] CALLEE THIS
8384 return false;
8385 }
8386
8387 if (callNode->isKind(ParseNodeKind::OptionalCallExpr)) {
8388 if (!oe.emitJumpShortCircuitForCall()) {
8389 // [stack] CALLEE THIS
8390 return false;
8391 }
8392 }
8393
8394 if (!emitArguments(argsList, /* isCall = */ true, isSpread, cone)) {
8395 // [stack] CALLEE THIS ARGS...
8396 return false;
8397 }
8398
8399 if (!cone.emitEnd(argc, coordNode->pn_pos.begin)) {
8400 // [stack] RVAL
8401 return false;
8402 }
8403
8404 return true;
8405 }
8406
8407 #ifdef ENABLE_EXPLICIT_RESOURCE_MANAGEMENT
8408 bool BytecodeEmitter::emitSelfHostedDisposeResources(CallNode* callNode,
8409 DisposalKind kind) {
8410 ListNode* argsList = callNode->args();
8411 MOZ_ASSERT(argsList->count() == 2);
8412
8413 ParseNode* resourcesNode = argsList->head();
8414 ParseNode* countNode = resourcesNode->pn_next;
8415
8416 DisposalEmitter de(this, bool(kind));
8417
8418 if (!emit1(JSOp::False)) {
8419 // [stack] THROWING
8420 return false;
8421 }
8422
8423 if (!emit1(JSOp::Undefined)) {
8424 // [stack] THROWING UNDEF
8425 return false;
8426 }
8427
8428 if (!de.prepareForDisposeCapability()) {
8429 // [stack] RVAL? NEEDS-AWAIT? HAS-AWAITED? THROWING UNDEF
8430 return false;
8431 }
8432
8433 if (!emitTree(resourcesNode)) {
8434 // [stack] RVAL? NEEDS-AWAIT? HAS-AWAITED? THROWING UNDEF RESOURCES
8435 return false;
8436 }
8437
8438 if (!emitTree(countNode)) {
8439 // [stack] RVAL? NEEDS-AWAIT? HAS-AWAITED? THROWING UNDEF RESOURCES COUNT
8440 return false;
8441 }
8442
8443 if (!de.emitEnd(*innermostEmitterScope())) {
8444 // [stack] EXC THROWING
8445 return false;
8446 }
8447
8448 // [stack] EXC THROWING
8449
8450 InternalIfEmitter ifThrow(this);
8451
8452 if (!ifThrow.emitThenElse()) {
8453 // [stack] EXC
8454 return false;
8455 }
8456
8457 if (!emit1(JSOp::Throw)) {
8458 // [stack]
8459 return false;
8460 }
8461
8462 if (!ifThrow.emitElse()) {
8463 // [stack] EXC
8464 return false;
8465 }
8466
8467 if (!emit1(JSOp::Pop)) {
8468 // [stack]
8469 return false;
8470 }
8471
8472 if (!ifThrow.emitEnd()) {
8473 // [stack]
8474 return false;
8475 }
8476
8477 if (!emit1(JSOp::Undefined)) {
8478 // [stack] RVAL
8479 return false;
8480 }
8481
8482 return true;
8483 }
8484 #endif
8485
8486 bool BytecodeEmitter::emitCallOrNew(CallNode* callNode, ValueUsage valueUsage) {
8487 /*
8488 * Emit callable invocation or operator new (constructor call) code.
8489 * First, emit code for the left operand to evaluate the callable or
8490 * constructable object expression.
8491 *
8492 * Then (or in a call case that has no explicit reference-base
8493 * object) we emit JSOp::Undefined to produce the undefined |this|
8494 * value required for calls (which non-strict mode functions
8495 * will box into the global object).
8496 */
8497 bool isCall = callNode->isKind(ParseNodeKind::CallExpr) ||
8498 callNode->isKind(ParseNodeKind::TaggedTemplateExpr);
8499 ParseNode* calleeNode = callNode->callee();
8500 ListNode* argsList = callNode->args();
8501 JSOp op = callNode->callOp();
8502
8503 if (calleeNode->isKind(ParseNodeKind::Name) &&
8504 emitterMode == BytecodeEmitter::SelfHosting && op == JSOp::Call) {
8505 // Calls to "forceInterpreter", "callFunction",
8506 // "callContentFunction", or "resumeGenerator" in self-hosted
8507 // code generate inline bytecode.
8508 //
8509 // NOTE: The list of special instruction names has to be kept in sync with
8510 // "js/src/builtin/.eslintrc.js".
8511 auto calleeName = calleeNode->as<NameNode>().name();
8512 if (calleeName == TaggedParserAtomIndex::WellKnown::callFunction()) {
8513 return emitSelfHostedCallFunction(callNode, JSOp::Call);
8514 }
8515 if (calleeName == TaggedParserAtomIndex::WellKnown::callContentFunction()) {
8516 return emitSelfHostedCallFunction(callNode, JSOp::CallContent);
8517 }
8518 if (calleeName ==
8519 TaggedParserAtomIndex::WellKnown::constructContentFunction()) {
8520 return emitSelfHostedCallFunction(callNode, JSOp::NewContent);
8521 }
8522 if (calleeName == TaggedParserAtomIndex::WellKnown::resumeGenerator()) {
8523 return emitSelfHostedResumeGenerator(callNode);
8524 }
8525 if (calleeName == TaggedParserAtomIndex::WellKnown::forceInterpreter()) {
8526 return emitSelfHostedForceInterpreter();
8527 }
8528 if (calleeName == TaggedParserAtomIndex::WellKnown::allowContentIter()) {
8529 return emitSelfHostedAllowContentIter(callNode);
8530 }
8531 if (calleeName ==
8532 TaggedParserAtomIndex::WellKnown::allowContentIterWith()) {
8533 return emitSelfHostedAllowContentIterWith(callNode);
8534 }
8535 if (calleeName ==
8536 TaggedParserAtomIndex::WellKnown::allowContentIterWithNext()) {
8537 return emitSelfHostedAllowContentIterWithNext(callNode);
8538 }
8539 if (calleeName == TaggedParserAtomIndex::WellKnown::DefineDataProperty() &&
8540 argsList->count() == 3) {
8541 return emitSelfHostedDefineDataProperty(callNode);
8542 }
8543 if (calleeName == TaggedParserAtomIndex::WellKnown::hasOwn()) {
8544 return emitSelfHostedHasOwn(callNode);
8545 }
8546 if (calleeName == TaggedParserAtomIndex::WellKnown::getPropertySuper()) {
8547 return emitSelfHostedGetPropertySuper(callNode);
8548 }
8549 if (calleeName == TaggedParserAtomIndex::WellKnown::ToNumeric()) {
8550 return emitSelfHostedToNumeric(callNode);
8551 }
8552 if (calleeName == TaggedParserAtomIndex::WellKnown::ToString()) {
8553 return emitSelfHostedToString(callNode);
8554 }
8555 if (calleeName ==
8556 TaggedParserAtomIndex::WellKnown::GetBuiltinConstructor()) {
8557 return emitSelfHostedGetBuiltinConstructor(callNode);
8558 }
8559 if (calleeName == TaggedParserAtomIndex::WellKnown::GetBuiltinPrototype()) {
8560 return emitSelfHostedGetBuiltinPrototype(callNode);
8561 }
8562 if (calleeName == TaggedParserAtomIndex::WellKnown::GetBuiltinSymbol()) {
8563 return emitSelfHostedGetBuiltinSymbol(callNode);
8564 }
8565 if (calleeName == TaggedParserAtomIndex::WellKnown::ArgumentsLength()) {
8566 return emitSelfHostedArgumentsLength(callNode);
8567 }
8568 if (calleeName == TaggedParserAtomIndex::WellKnown::GetArgument()) {
8569 return emitSelfHostedGetArgument(callNode);
8570 }
8571 if (calleeName ==
8572 TaggedParserAtomIndex::WellKnown::SetIsInlinableLargeFunction()) {
8573 return emitSelfHostedSetIsInlinableLargeFunction(callNode);
8574 }
8575 if (calleeName == TaggedParserAtomIndex::WellKnown::SetCanonicalName()) {
8576 return emitSelfHostedSetCanonicalName(callNode);
8577 }
8578 if (calleeName == TaggedParserAtomIndex::WellKnown::IsNullOrUndefined()) {
8579 return emitSelfHostedIsNullOrUndefined(callNode);
8580 }
8581 if (calleeName == TaggedParserAtomIndex::WellKnown::IteratorClose()) {
8582 return emitSelfHostedIteratorClose(callNode);
8583 }
8584 #ifdef ENABLE_EXPLICIT_RESOURCE_MANAGEMENT
8585 if (calleeName ==
8586 TaggedParserAtomIndex::WellKnown::DisposeResourcesAsync()) {
8587 return emitSelfHostedDisposeResources(callNode, DisposalKind::Async);
8588 }
8589 if (calleeName ==
8590 TaggedParserAtomIndex::WellKnown::DisposeResourcesSync()) {
8591 return emitSelfHostedDisposeResources(callNode, DisposalKind::Sync);
8592 }
8593 #endif
8594 #ifdef DEBUG
8595 if (calleeName ==
8596 TaggedParserAtomIndex::WellKnown::UnsafeGetReservedSlot() ||
8597 calleeName == TaggedParserAtomIndex::WellKnown::
8598 UnsafeGetObjectFromReservedSlot() ||
8599 calleeName == TaggedParserAtomIndex::WellKnown::
8600 UnsafeGetInt32FromReservedSlot() ||
8601 calleeName == TaggedParserAtomIndex::WellKnown::
8602 UnsafeGetStringFromReservedSlot()) {
8603 // Make sure that this call is correct, but don't emit any special code.
8604 assertSelfHostedUnsafeGetReservedSlot(argsList);
8605 }
8606 if (calleeName ==
8607 TaggedParserAtomIndex::WellKnown::UnsafeSetReservedSlot()) {
8608 // Make sure that this call is correct, but don't emit any special code.
8609 assertSelfHostedUnsafeSetReservedSlot(argsList);
8610 }
8611 #endif
8612 // Fall through
8613 }
8614
8615 uint32_t argc = argsList->count();
8616 bool isSpread = IsSpreadOp(op);
8617 bool isOptimizableSpread = isSpread && argc == 1;
8618 bool isDefaultDerivedClassConstructor =
8619 sc->isFunctionBox() && sc->asFunctionBox()->isDerivedClassConstructor() &&
8620 sc->asFunctionBox()->isSyntheticFunction();
8621 MOZ_ASSERT_IF(isDefaultDerivedClassConstructor, isOptimizableSpread);
8622 CallOrNewEmitter cone(
8623 this, op,
8624 isOptimizableSpread
8625 ? isDefaultDerivedClassConstructor
8626 ? CallOrNewEmitter::ArgumentsKind::PassthroughRest
8627 : CallOrNewEmitter::ArgumentsKind::SingleSpread
8628 : CallOrNewEmitter::ArgumentsKind::Other,
8629 valueUsage);
8630
8631 if (!emitCalleeAndThis(calleeNode, callNode, cone)) {
8632 // [stack] CALLEE THIS
8633 return false;
8634 }
8635 if (!emitArguments(argsList, isCall, isSpread, cone)) {
8636 // [stack] CALLEE THIS ARGS...
8637 return false;
8638 }
8639
8640 // Push new.target for construct calls.
8641 if (IsConstructOp(op)) {
8642 if (op == JSOp::SuperCall || op == JSOp::SpreadSuperCall) {
8643 if (!emitNewTarget(callNode)) {
8644 // [stack] CALLEE THIS ARGS.. NEW.TARGET
8645 return false;
8646 }
8647 } else {
8648 // Repush the callee as new.target
8649 uint32_t effectiveArgc = isSpread ? 1 : argc;
8650 if (!emitDupAt(effectiveArgc + 1)) {
8651 // [stack] CALLEE THIS ARGS.. CALLEE
8652 return false;
8653 }
8654 }
8655 }
8656
8657 ParseNode* coordNode = getCoordNode(callNode, calleeNode, op, argsList);
8658
8659 if (!cone.emitEnd(argc, coordNode->pn_pos.begin)) {
8660 // [stack] RVAL
8661 return false;
8662 }
8663
8664 return true;
8665 }
8666
8667 // This list must be kept in the same order in several places:
8668 // - The binary operators in ParseNode.h ,
8669 // - the binary operators in TokenKind.h
8670 // - the precedence list in Parser.cpp
8671 static const JSOp ParseNodeKindToJSOp[] = {
8672 // Some binary ops require special code generation (PrivateIn);
8673 // these should not use BinaryOpParseNodeKindToJSOp. This table fills those
8674 // slots with Nops to make the rest of the table lookup work.
8675 JSOp::Coalesce, JSOp::Or, JSOp::And, JSOp::BitOr, JSOp::BitXor,
8676 JSOp::BitAnd, JSOp::StrictEq, JSOp::Eq, JSOp::StrictNe, JSOp::Ne,
8677 JSOp::Lt, JSOp::Le, JSOp::Gt, JSOp::Ge, JSOp::Instanceof,
8678 JSOp::In, JSOp::Nop, JSOp::Lsh, JSOp::Rsh, JSOp::Ursh,
8679 JSOp::Add, JSOp::Sub, JSOp::Mul, JSOp::Div, JSOp::Mod,
8680 JSOp::Pow};
8681
8682 static inline JSOp BinaryOpParseNodeKindToJSOp(ParseNodeKind pnk) {
8683 MOZ_ASSERT(pnk >= ParseNodeKind::BinOpFirst);
8684 MOZ_ASSERT(pnk <= ParseNodeKind::BinOpLast);
8685 int parseNodeFirst = size_t(ParseNodeKind::BinOpFirst);
8686 #ifdef DEBUG
8687 int jsopArraySize = std::size(ParseNodeKindToJSOp);
8688 int parseNodeKindListSize =
8689 size_t(ParseNodeKind::BinOpLast) - parseNodeFirst + 1;
8690 MOZ_ASSERT(jsopArraySize == parseNodeKindListSize);
8691 // Ensure we don't use this to find an op for a parse node
8692 // requiring special emission rules.
8693 MOZ_ASSERT(ParseNodeKindToJSOp[size_t(pnk) - parseNodeFirst] != JSOp::Nop);
8694 #endif
8695 return ParseNodeKindToJSOp[size_t(pnk) - parseNodeFirst];
8696 }
8697
8698 bool BytecodeEmitter::emitRightAssociative(ListNode* node) {
8699 // ** is the only right-associative operator.
8700 MOZ_ASSERT(node->isKind(ParseNodeKind::PowExpr));
8701
8702 // Right-associative operator chain.
8703 for (ParseNode* subexpr : node->contents()) {
8704 if (!updateSourceCoordNotesIfNonLiteral(subexpr)) {
8705 return false;
8706 }
8707 if (!emitTree(subexpr)) {
8708 return false;
8709 }
8710 }
8711 for (uint32_t i = 0; i < node->count() - 1; i++) {
8712 if (!emit1(JSOp::Pow)) {
8713 return false;
8714 }
8715 }
8716 return true;
8717 }
8718
8719 Maybe<ConstantCompareOperand> ParseNodeToConstantCompareOperand(
8720 ParseNode* constant) {
8721 switch (constant->getKind()) {
8722 case ParseNodeKind::NumberExpr: {
8723 double d = constant->as<NumericLiteral>().value();
8724 int32_t ival;
8725 if (NumberEqualsInt32(d, &ival)) {
8726 if (ConstantCompareOperand::CanEncodeInt32ValueAsOperand(ival)) {
8727 return Some(ConstantCompareOperand((int8_t)ival));
8728 }
8729 }
8730 return Nothing();
8731 }
8732 case ParseNodeKind::TrueExpr:
8733 case ParseNodeKind::FalseExpr:
8734 return Some(
8735 ConstantCompareOperand(constant->isKind(ParseNodeKind::TrueExpr)));
8736 case ParseNodeKind::NullExpr:
8737 return Some(
8738 ConstantCompareOperand(ConstantCompareOperand::EncodedType::Null));
8739 case ParseNodeKind::RawUndefinedExpr:
8740 return Some(ConstantCompareOperand(
8741 ConstantCompareOperand::EncodedType::Undefined));
8742 default:
8743 return Nothing();
8744 }
8745 }
8746
8747 bool BytecodeEmitter::tryEmitConstantEq(ListNode* node, JSOp op,
8748 bool* emitted) {
8749 // We ignore long chains of === or !==, we
8750 // only optimise cases a === b or a !== b
8751 if (node->count() != 2) {
8752 *emitted = false;
8753 return true;
8754 }
8755
8756 JSOp constantOp;
8757 switch (op) {
8758 case JSOp::StrictEq:
8759 constantOp = JSOp::StrictConstantEq;
8760 break;
8761 case JSOp::StrictNe:
8762 constantOp = JSOp::StrictConstantNe;
8763 break;
8764 default:
8765 *emitted = false;
8766 return true;
8767 }
8768
8769 ParseNode* left = node->head();
8770 ParseNode* right = node->head()->pn_next;
8771
8772 ParseNode* expressionNode;
8773 ParseNode* constantNode;
8774 if (left->isConstant()) {
8775 expressionNode = right;
8776 constantNode = left;
8777 } else if (right->isConstant()) {
8778 expressionNode = left;
8779 constantNode = right;
8780 } else {
8781 *emitted = false;
8782 return true;
8783 }
8784
8785 Maybe<ConstantCompareOperand> operand =
8786 ParseNodeToConstantCompareOperand(constantNode);
8787 if (operand.isNothing()) {
8788 *emitted = false;
8789 return true;
8790 }
8791
8792 if (!emitTree(expressionNode)) {
8793 return false;
8794 }
8795
8796 if (!emitUint16Operand(constantOp, operand->rawValue())) {
8797 return false;
8798 }
8799
8800 *emitted = true;
8801 return true;
8802 }
8803
8804 bool BytecodeEmitter::emitLeftAssociative(ListNode* node) {
8805 JSOp op = BinaryOpParseNodeKindToJSOp(node->getKind());
8806 bool constantEqEmitted = false;
8807 if (!tryEmitConstantEq(node, op, &constantEqEmitted)) {
8808 return false;
8809 }
8810 if (constantEqEmitted) {
8811 return true;
8812 }
8813 // Left-associative operator chain.
8814 if (!emitTree(node->head())) {
8815 return false;
8816 }
8817 ParseNode* nextExpr = node->head()->pn_next;
8818 do {
8819 if (!updateSourceCoordNotesIfNonLiteral(nextExpr)) {
8820 return false;
8821 }
8822 if (!emitTree(nextExpr)) {
8823 return false;
8824 }
8825 if (!emit1(op)) {
8826 return false;
8827 }
8828 } while ((nextExpr = nextExpr->pn_next));
8829 return true;
8830 }
8831
8832 bool BytecodeEmitter::emitPrivateInExpr(ListNode* node) {
8833 MOZ_ASSERT(node->head()->isKind(ParseNodeKind::PrivateName));
8834
8835 NameNode& privateNameNode = node->head()->as<NameNode>();
8836 TaggedParserAtomIndex privateName = privateNameNode.name();
8837
8838 PrivateOpEmitter xoe(this, PrivateOpEmitter::Kind::ErgonomicBrandCheck,
8839 privateName);
8840
8841 ParseNode* valueNode = node->head()->pn_next;
8842 MOZ_ASSERT(valueNode->pn_next == nullptr);
8843
8844 if (!emitTree(valueNode)) {
8845 // [stack] OBJ
8846 return false;
8847 }
8848
8849 if (!xoe.emitReference()) {
8850 // [stack] OBJ BRAND if private method
8851 // [stack] OBJ NAME if private field or accessor.
8852 return false;
8853 }
8854
8855 if (!xoe.emitBrandCheck()) {
8856 // [stack] OBJ BRAND BOOL if private method
8857 // [stack] OBJ NAME BOOL if private field or accessor.
8858 return false;
8859 }
8860
8861 if (!emitUnpickN(2)) {
8862 // [stack] BOOL OBJ BRAND if private method
8863 // [stack] BOOL OBJ NAME if private field or accessor.
8864 return false;
8865 }
8866
8867 if (!emitPopN(2)) {
8868 // [stack] BOOL
8869 return false;
8870 }
8871
8872 return true;
8873 }
8874
8875 /*
8876 * Special `emitTree` for Optional Chaining case.
8877 * Examples of this are `emitOptionalChain`, `emitDeleteOptionalChain` and
8878 * `emitCalleeAndThisForOptionalChain`.
8879 */
8880 bool BytecodeEmitter::emitOptionalTree(
8881 ParseNode* pn, OptionalEmitter& oe,
8882 ValueUsage valueUsage /* = ValueUsage::WantValue */) {
8883 AutoCheckRecursionLimit recursion(fc);
8884 if (!recursion.check(fc)) {
8885 return false;
8886 }
8887 ParseNodeKind kind = pn->getKind();
8888 switch (kind) {
8889 case ParseNodeKind::OptionalDotExpr: {
8890 OptionalPropertyAccess* prop = &pn->as<OptionalPropertyAccess>();
8891 bool isSuper = false;
8892 PropOpEmitter poe(this, PropOpEmitter::Kind::Get,
8893 PropOpEmitter::ObjKind::Other);
8894 if (!emitOptionalDotExpression(prop, poe, isSuper, oe)) {
8895 return false;
8896 }
8897 break;
8898 }
8899 case ParseNodeKind::ArgumentsLength:
8900 case ParseNodeKind::DotExpr: {
8901 PropertyAccess* prop = &pn->as<PropertyAccess>();
8902 bool isSuper = prop->isSuper();
8903 PropOpEmitter poe(this, PropOpEmitter::Kind::Get,
8904 isSuper ? PropOpEmitter::ObjKind::Super
8905 : PropOpEmitter::ObjKind::Other);
8906 if (!emitOptionalDotExpression(prop, poe, isSuper, oe)) {
8907 return false;
8908 }
8909 break;
8910 }
8911
8912 case ParseNodeKind::OptionalElemExpr: {
8913 OptionalPropertyByValue* elem = &pn->as<OptionalPropertyByValue>();
8914 bool isSuper = false;
8915 MOZ_ASSERT(!elem->key().isKind(ParseNodeKind::PrivateName));
8916 ElemOpEmitter eoe(this, ElemOpEmitter::Kind::Get,
8917 ElemOpEmitter::ObjKind::Other);
8918
8919 if (!emitOptionalElemExpression(elem, eoe, isSuper, oe)) {
8920 return false;
8921 }
8922 break;
8923 }
8924 case ParseNodeKind::ElemExpr: {
8925 PropertyByValue* elem = &pn->as<PropertyByValue>();
8926 bool isSuper = elem->isSuper();
8927 MOZ_ASSERT(!elem->key().isKind(ParseNodeKind::PrivateName));
8928 ElemOpEmitter eoe(this, ElemOpEmitter::Kind::Get,
8929 isSuper ? ElemOpEmitter::ObjKind::Super
8930 : ElemOpEmitter::ObjKind::Other);
8931
8932 if (!emitOptionalElemExpression(elem, eoe, isSuper, oe)) {
8933 return false;
8934 }
8935 break;
8936 }
8937 case ParseNodeKind::PrivateMemberExpr:
8938 case ParseNodeKind::OptionalPrivateMemberExpr: {
8939 PrivateMemberAccessBase* privateExpr = &pn->as<PrivateMemberAccessBase>();
8940 PrivateOpEmitter xoe(this, PrivateOpEmitter::Kind::Get,
8941 privateExpr->privateName().name());
8942 if (!emitOptionalPrivateExpression(privateExpr, xoe, oe)) {
8943 return false;
8944 }
8945 break;
8946 }
8947 case ParseNodeKind::CallExpr:
8948 case ParseNodeKind::OptionalCallExpr:
8949 if (!emitOptionalCall(&pn->as<CallNode>(), oe, valueUsage)) {
8950 return false;
8951 }
8952 break;
8953 // List of accepted ParseNodeKinds that might appear only at the beginning
8954 // of an Optional Chain.
8955 // For example, a taggedTemplateExpr node might occur if we have
8956 // `test`?.b, with `test` as the taggedTemplateExpr ParseNode.
8957 default:
8958 #ifdef DEBUG
8959 // https://tc39.es/ecma262/#sec-primary-expression
8960 bool isPrimaryExpression =
8961 kind == ParseNodeKind::ThisExpr || kind == ParseNodeKind::Name ||
8962 kind == ParseNodeKind::PrivateName ||
8963 kind == ParseNodeKind::NullExpr || kind == ParseNodeKind::TrueExpr ||
8964 kind == ParseNodeKind::FalseExpr ||
8965 kind == ParseNodeKind::NumberExpr ||
8966 kind == ParseNodeKind::BigIntExpr ||
8967 kind == ParseNodeKind::StringExpr ||
8968 kind == ParseNodeKind::ArrayExpr ||
8969 kind == ParseNodeKind::ObjectExpr ||
8970 kind == ParseNodeKind::Function || kind == ParseNodeKind::ClassDecl ||
8971 kind == ParseNodeKind::RegExpExpr ||
8972 kind == ParseNodeKind::TemplateStringExpr ||
8973 kind == ParseNodeKind::TemplateStringListExpr ||
8974 kind == ParseNodeKind::RawUndefinedExpr || pn->isInParens();
8975
8976 // https://tc39.es/ecma262/#sec-left-hand-side-expressions
8977 bool isMemberExpression = isPrimaryExpression ||
8978 kind == ParseNodeKind::TaggedTemplateExpr ||
8979 kind == ParseNodeKind::NewExpr ||
8980 kind == ParseNodeKind::NewTargetExpr ||
8981 kind == ParseNodeKind::ImportMetaExpr;
8982
8983 bool isCallExpression = kind == ParseNodeKind::SetThis ||
8984 kind == ParseNodeKind::CallImportExpr;
8985
8986 MOZ_ASSERT(isMemberExpression || isCallExpression,
8987 "Unknown ParseNodeKind for OptionalChain");
8988 #endif
8989 return emitTree(pn);
8990 }
8991 return true;
8992 }
8993
8994 // Handle the case of a call made on a OptionalChainParseNode.
8995 // For example `(a?.b)()` and `(a?.b)?.()`.
8996 bool BytecodeEmitter::emitCalleeAndThisForOptionalChain(
8997 UnaryNode* optionalChain, CallNode* callNode, CallOrNewEmitter& cone) {
8998 ParseNode* calleeNode = optionalChain->kid();
8999
9000 // Create a new OptionalEmitter, in order to emit the right bytecode
9001 // in isolation.
9002 OptionalEmitter oe(this, bytecodeSection().stackDepth());
9003
9004 if (!emitOptionalCalleeAndThis(calleeNode, callNode, cone, oe)) {
9005 // [stack] CALLEE THIS
9006 return false;
9007 }
9008
9009 // complete the jump if necessary. This will set both the "this" value
9010 // and the "callee" value to undefined, if the callee is undefined. It
9011 // does not matter much what the this value is, the function call will
9012 // fail if it is not optional, and be set to undefined otherwise.
9013 if (!oe.emitOptionalJumpTarget(JSOp::Undefined,
9014 OptionalEmitter::Kind::Reference)) {
9015 // [stack] # If shortcircuit
9016 // [stack] UNDEFINED UNDEFINED
9017 // [stack] # otherwise
9018 // [stack] CALLEE THIS
9019 return false;
9020 }
9021 return true;
9022 }
9023
9024 bool BytecodeEmitter::emitOptionalChain(UnaryNode* optionalChain,
9025 ValueUsage valueUsage) {
9026 ParseNode* expr = optionalChain->kid();
9027
9028 OptionalEmitter oe(this, bytecodeSection().stackDepth());
9029
9030 if (!emitOptionalTree(expr, oe, valueUsage)) {
9031 // [stack] VAL
9032 return false;
9033 }
9034
9035 if (!oe.emitOptionalJumpTarget(JSOp::Undefined)) {
9036 // [stack] # If shortcircuit
9037 // [stack] UNDEFINED
9038 // [stack] # otherwise
9039 // [stack] VAL
9040 return false;
9041 }
9042
9043 return true;
9044 }
9045
9046 bool BytecodeEmitter::emitOptionalDotExpression(PropertyAccessBase* prop,
9047 PropOpEmitter& poe,
9048 bool isSuper,
9049 OptionalEmitter& oe) {
9050 if (!poe.prepareForObj()) {
9051 // [stack]
9052 return false;
9053 }
9054
9055 if (isSuper) {
9056 UnaryNode* base = &prop->expression().as<UnaryNode>();
9057 if (!emitGetThisForSuperBase(base)) {
9058 // [stack] OBJ
9059 return false;
9060 }
9061 } else {
9062 if (!emitOptionalTree(&prop->expression(), oe)) {
9063 // [stack] OBJ
9064 return false;
9065 }
9066 }
9067
9068 if (prop->isKind(ParseNodeKind::OptionalDotExpr)) {
9069 MOZ_ASSERT(!isSuper);
9070 if (!oe.emitJumpShortCircuit()) {
9071 // [stack] # if Jump
9072 // [stack] UNDEFINED-OR-NULL
9073 // [stack] # otherwise
9074 // [stack] OBJ
9075 return false;
9076 }
9077 }
9078
9079 if (!poe.emitGet(prop->key().atom())) {
9080 // [stack] PROP
9081 return false;
9082 }
9083
9084 return true;
9085 }
9086
9087 bool BytecodeEmitter::emitOptionalElemExpression(PropertyByValueBase* elem,
9088 ElemOpEmitter& eoe,
9089 bool isSuper,
9090 OptionalEmitter& oe) {
9091 if (!eoe.prepareForObj()) {
9092 // [stack]
9093 return false;
9094 }
9095
9096 if (isSuper) {
9097 UnaryNode* base = &elem->expression().as<UnaryNode>();
9098 if (!emitGetThisForSuperBase(base)) {
9099 // [stack] OBJ
9100 return false;
9101 }
9102 } else {
9103 if (!emitOptionalTree(&elem->expression(), oe)) {
9104 // [stack] OBJ
9105 return false;
9106 }
9107 }
9108
9109 if (elem->isKind(ParseNodeKind::OptionalElemExpr)) {
9110 MOZ_ASSERT(!isSuper);
9111 if (!oe.emitJumpShortCircuit()) {
9112 // [stack] # if Jump
9113 // [stack] UNDEFINED-OR-NULL
9114 // [stack] # otherwise
9115 // [stack] OBJ
9116 return false;
9117 }
9118 }
9119
9120 if (!eoe.prepareForKey()) {
9121 // [stack] OBJ? OBJ
9122 return false;
9123 }
9124
9125 if (!emitTree(&elem->key())) {
9126 // [stack] OBJ? OBJ KEY
9127 return false;
9128 }
9129
9130 if (!eoe.emitGet()) {
9131 // [stack] ELEM
9132 return false;
9133 }
9134
9135 return true;
9136 }
9137
9138 bool BytecodeEmitter::emitOptionalPrivateExpression(
9139 PrivateMemberAccessBase* privateExpr, PrivateOpEmitter& xoe,
9140 OptionalEmitter& oe) {
9141 if (!emitOptionalTree(&privateExpr->expression(), oe)) {
9142 // [stack] OBJ
9143 return false;
9144 }
9145
9146 if (privateExpr->isKind(ParseNodeKind::OptionalPrivateMemberExpr)) {
9147 if (!oe.emitJumpShortCircuit()) {
9148 // [stack] # if Jump
9149 // [stack] UNDEFINED-OR-NULL
9150 // [stack] # otherwise
9151 // [stack] OBJ
9152 return false;
9153 }
9154 }
9155
9156 if (!xoe.emitReference()) {
9157 // [stack] OBJ NAME
9158 return false;
9159 }
9160 if (!xoe.emitGet()) {
9161 // [stack] CALLEE THIS # if call
9162 // [stack] VALUE # otherwise
9163 return false;
9164 }
9165
9166 return true;
9167 }
9168
9169 bool BytecodeEmitter::emitShortCircuit(ListNode* node, ValueUsage valueUsage) {
9170 MOZ_ASSERT(node->isKind(ParseNodeKind::OrExpr) ||
9171 node->isKind(ParseNodeKind::CoalesceExpr) ||
9172 node->isKind(ParseNodeKind::AndExpr));
9173
9174 /*
9175 * JSOp::Or converts the operand on the stack to boolean, leaves the original
9176 * value on the stack and jumps if true; otherwise it falls into the next
9177 * bytecode, which pops the left operand and then evaluates the right operand.
9178 * The jump goes around the right operand evaluation.
9179 *
9180 * JSOp::And converts the operand on the stack to boolean and jumps if false;
9181 * otherwise it falls into the right operand's bytecode.
9182 */
9183
9184 TDZCheckCache tdzCache(this);
9185
9186 JSOp op;
9187 switch (node->getKind()) {
9188 case ParseNodeKind::OrExpr:
9189 op = JSOp::Or;
9190 break;
9191 case ParseNodeKind::CoalesceExpr:
9192 op = JSOp::Coalesce;
9193 break;
9194 case ParseNodeKind::AndExpr:
9195 op = JSOp::And;
9196 break;
9197 default:
9198 MOZ_CRASH("Unexpected ParseNodeKind");
9199 }
9200
9201 JumpList jump;
9202
9203 // Left-associative operator chain: avoid too much recursion.
9204 //
9205 // Emit all nodes but the last.
9206 for (ParseNode* expr : node->contentsTo(node->last())) {
9207 if (!emitTree(expr)) {
9208 return false;
9209 }
9210 if (!emitJump(op, &jump)) {
9211 return false;
9212 }
9213 if (!emit1(JSOp::Pop)) {
9214 return false;
9215 }
9216 }
9217
9218 // Emit the last node
9219 if (!emitTree(node->last(), valueUsage)) {
9220 return false;
9221 }
9222
9223 if (!emitJumpTargetAndPatch(jump)) {
9224 return false;
9225 }
9226 return true;
9227 }
9228
9229 bool BytecodeEmitter::emitSequenceExpr(ListNode* node, ValueUsage valueUsage) {
9230 for (ParseNode* child : node->contentsTo(node->last())) {
9231 if (!updateSourceCoordNotes(child->pn_pos.begin)) {
9232 return false;
9233 }
9234 if (!emitTree(child, ValueUsage::IgnoreValue)) {
9235 return false;
9236 }
9237 if (!emit1(JSOp::Pop)) {
9238 return false;
9239 }
9240 }
9241
9242 ParseNode* child = node->last();
9243 if (!updateSourceCoordNotes(child->pn_pos.begin)) {
9244 return false;
9245 }
9246 if (!emitTree(child, valueUsage)) {
9247 return false;
9248 }
9249 return true;
9250 }
9251
9252 // Using MOZ_NEVER_INLINE in here is a workaround for llvm.org/pr14047. See
9253 // the comment on emitSwitch.
9254 MOZ_NEVER_INLINE bool BytecodeEmitter::emitIncOrDec(UnaryNode* incDec,
9255 ValueUsage valueUsage) {
9256 switch (incDec->kid()->getKind()) {
9257 case ParseNodeKind::ArgumentsLength:
9258 case ParseNodeKind::DotExpr:
9259 return emitPropIncDec(incDec, valueUsage);
9260 case ParseNodeKind::ElemExpr:
9261 return emitElemIncDec(incDec, valueUsage);
9262 case ParseNodeKind::PrivateMemberExpr:
9263 return emitPrivateIncDec(incDec, valueUsage);
9264 case ParseNodeKind::CallExpr:
9265 return emitCallIncDec(incDec);
9266 default:
9267 return emitNameIncDec(incDec, valueUsage);
9268 }
9269 }
9270
9271 // Using MOZ_NEVER_INLINE in here is a workaround for llvm.org/pr14047. See
9272 // the comment on emitSwitch.
9273 MOZ_NEVER_INLINE bool BytecodeEmitter::emitLabeledStatement(
9274 const LabeledStatement* labeledStmt) {
9275 auto name = labeledStmt->label();
9276 LabelEmitter label(this);
9277
9278 label.emitLabel(name);
9279
9280 if (!emitTree(labeledStmt->statement())) {
9281 return false;
9282 }
9283 if (!label.emitEnd()) {
9284 return false;
9285 }
9286
9287 return true;
9288 }
9289
9290 bool BytecodeEmitter::emitConditionalExpression(
9291 ConditionalExpression& conditional, ValueUsage valueUsage) {
9292 CondEmitter cond(this);
9293 if (!cond.emitCond()) {
9294 return false;
9295 }
9296
9297 ParseNode* conditionNode = &conditional.condition();
9298 auto conditionKind = IfEmitter::ConditionKind::Positive;
9299 if (conditionNode->isKind(ParseNodeKind::NotExpr)) {
9300 conditionNode = conditionNode->as<UnaryNode>().kid();
9301 conditionKind = IfEmitter::ConditionKind::Negative;
9302 }
9303
9304 // NOTE: NotExpr of conditionNode may be unwrapped, and in that case the
9305 // negation is handled by conditionKind.
9306 if (!emitTree(conditionNode)) {
9307 return false;
9308 }
9309
9310 if (!cond.emitThenElse(conditionKind)) {
9311 return false;
9312 }
9313
9314 if (!emitTree(&conditional.thenExpression(), valueUsage)) {
9315 return false;
9316 }
9317
9318 if (!cond.emitElse()) {
9319 return false;
9320 }
9321
9322 if (!emitTree(&conditional.elseExpression(), valueUsage)) {
9323 return false;
9324 }
9325
9326 if (!cond.emitEnd()) {
9327 return false;
9328 }
9329 MOZ_ASSERT(cond.pushed() == 1);
9330
9331 return true;
9332 }
9333
9334 // Check for an object-literal property list that can be handled by the
9335 // ObjLiteral writer. We ensure that for each `prop: value` pair, the key is a
9336 // constant name or numeric index, there is no accessor specified, and the value
9337 // can be encoded by an ObjLiteral instruction (constant number, string,
9338 // boolean, null/undefined).
9339 void BytecodeEmitter::isPropertyListObjLiteralCompatible(
9340 ListNode* obj, bool* withValues, bool* withoutValues) const {
9341 bool keysOK = true;
9342 bool valuesOK = true;
9343 uint32_t propCount = 0;
9344
9345 for (ParseNode* propdef : obj->contents()) {
9346 if (!propdef->is<BinaryNode>()) {
9347 keysOK = false;
9348 break;
9349 }
9350 propCount++;
9351
9352 BinaryNode* prop = &propdef->as<BinaryNode>();
9353 ParseNode* key = prop->left();
9354 ParseNode* value = prop->right();
9355
9356 // Computed keys not OK (ObjLiteral data stores constant keys).
9357 if (key->isKind(ParseNodeKind::ComputedName)) {
9358 keysOK = false;
9359 break;
9360 }
9361
9362 // BigIntExprs should have been lowered to computed names at parse
9363 // time, and so should be excluded above.
9364 MOZ_ASSERT(!key->isKind(ParseNodeKind::BigIntExpr));
9365
9366 // Numeric keys OK as long as they are integers and in range.
9367 if (key->isKind(ParseNodeKind::NumberExpr)) {
9368 double numValue = key->as<NumericLiteral>().value();
9369 int32_t i = 0;
9370 if (!NumberIsInt32(numValue, &i)) {
9371 keysOK = false;
9372 break;
9373 }
9374 if (!ObjLiteralWriter::arrayIndexInRange(i)) {
9375 keysOK = false;
9376 break;
9377 }
9378 }
9379
9380 MOZ_ASSERT(key->isKind(ParseNodeKind::ObjectPropertyName) ||
9381 key->isKind(ParseNodeKind::StringExpr) ||
9382 key->isKind(ParseNodeKind::NumberExpr));
9383
9384 AccessorType accessorType =
9385 prop->is<PropertyDefinition>()
9386 ? prop->as<PropertyDefinition>().accessorType()
9387 : AccessorType::None;
9388 if (accessorType != AccessorType::None) {
9389 keysOK = false;
9390 break;
9391 }
9392
9393 if (!isRHSObjLiteralCompatible(value)) {
9394 valuesOK = false;
9395 }
9396 }
9397
9398 if (propCount > SharedPropMap::MaxPropsForNonDictionary) {
9399 // JSOp::NewObject cannot accept dictionary-mode objects.
9400 keysOK = false;
9401 }
9402
9403 *withValues = keysOK && valuesOK;
9404 *withoutValues = keysOK;
9405 }
9406
9407 bool BytecodeEmitter::isArrayObjLiteralCompatible(ListNode* array) const {
9408 for (ParseNode* elem : array->contents()) {
9409 if (elem->isKind(ParseNodeKind::Spread)) {
9410 return false;
9411 }
9412 if (!isRHSObjLiteralCompatible(elem)) {
9413 return false;
9414 }
9415 }
9416 return true;
9417 }
9418
9419 bool BytecodeEmitter::emitPropertyList(ListNode* obj, PropertyEmitter& pe,
9420 PropListType type) {
9421 // [stack] CTOR? OBJ
9422
9423 size_t curFieldKeyIndex = 0;
9424 size_t curStaticFieldKeyIndex = 0;
9425 for (ParseNode* propdef : obj->contents()) {
9426 if (propdef->is<ClassField>()) {
9427 MOZ_ASSERT(type == ClassBody);
9428 // Only handle computing field keys here: the .initializers lambda array
9429 // is created elsewhere.
9430 ClassField* field = &propdef->as<ClassField>();
9431 if (field->name().getKind() == ParseNodeKind::ComputedName) {
9432 auto fieldKeys =
9433 field->isStatic()
9434 ? TaggedParserAtomIndex::WellKnown::dot_staticFieldKeys_()
9435 : TaggedParserAtomIndex::WellKnown::dot_fieldKeys_();
9436 if (!emitGetName(fieldKeys)) {
9437 // [stack] CTOR OBJ ARRAY
9438 return false;
9439 }
9440
9441 ParseNode* nameExpr = field->name().as<UnaryNode>().kid();
9442
9443 if (!emitTree(nameExpr, ValueUsage::WantValue)) {
9444 // [stack] CTOR OBJ ARRAY KEY
9445 return false;
9446 }
9447
9448 if (!emit1(JSOp::ToPropertyKey)) {
9449 // [stack] CTOR OBJ ARRAY KEY
9450 return false;
9451 }
9452
9453 size_t fieldKeysIndex;
9454 if (field->isStatic()) {
9455 fieldKeysIndex = curStaticFieldKeyIndex++;
9456 } else {
9457 fieldKeysIndex = curFieldKeyIndex++;
9458 }
9459
9460 if (!emitUint32Operand(JSOp::InitElemArray, fieldKeysIndex)) {
9461 // [stack] CTOR OBJ ARRAY
9462 return false;
9463 }
9464
9465 if (!emit1(JSOp::Pop)) {
9466 // [stack] CTOR OBJ
9467 return false;
9468 }
9469 }
9470 continue;
9471 }
9472
9473 if (propdef->isKind(ParseNodeKind::StaticClassBlock)) {
9474 // Static class blocks are emitted as part of
9475 // emitCreateMemberInitializers.
9476 continue;
9477 }
9478
9479 if (propdef->is<LexicalScopeNode>()) {
9480 // Constructors are sometimes wrapped in LexicalScopeNodes. As we
9481 // already handled emitting the constructor, skip it.
9482 MOZ_ASSERT(
9483 propdef->as<LexicalScopeNode>().scopeBody()->is<ClassMethod>());
9484 continue;
9485 }
9486
9487 // Handle __proto__: v specially because *only* this form, and no other
9488 // involving "__proto__", performs [[Prototype]] mutation.
9489 if (propdef->isKind(ParseNodeKind::MutateProto)) {
9490 // [stack] OBJ
9491 MOZ_ASSERT(type == ObjectLiteral);
9492 if (!pe.prepareForProtoValue(propdef->pn_pos.begin)) {
9493 // [stack] OBJ
9494 return false;
9495 }
9496 if (!emitTree(propdef->as<UnaryNode>().kid())) {
9497 // [stack] OBJ PROTO
9498 return false;
9499 }
9500 if (!pe.emitMutateProto()) {
9501 // [stack] OBJ
9502 return false;
9503 }
9504 continue;
9505 }
9506
9507 if (propdef->isKind(ParseNodeKind::Spread)) {
9508 MOZ_ASSERT(type == ObjectLiteral);
9509 // [stack] OBJ
9510 if (!pe.prepareForSpreadOperand(propdef->pn_pos.begin)) {
9511 // [stack] OBJ OBJ
9512 return false;
9513 }
9514 if (!emitTree(propdef->as<UnaryNode>().kid())) {
9515 // [stack] OBJ OBJ VAL
9516 return false;
9517 }
9518 if (!pe.emitSpread()) {
9519 // [stack] OBJ
9520 return false;
9521 }
9522 continue;
9523 }
9524
9525 BinaryNode* prop = &propdef->as<BinaryNode>();
9526
9527 ParseNode* key = prop->left();
9528 AccessorType accessorType;
9529 if (prop->is<ClassMethod>()) {
9530 ClassMethod& method = prop->as<ClassMethod>();
9531 accessorType = method.accessorType();
9532
9533 if (!method.isStatic() && key->isKind(ParseNodeKind::PrivateName) &&
9534 accessorType != AccessorType::None) {
9535 // Private non-static accessors are stamped onto instances from
9536 // initializers; see emitCreateMemberInitializers.
9537 continue;
9538 }
9539 } else if (prop->is<PropertyDefinition>()) {
9540 accessorType = prop->as<PropertyDefinition>().accessorType();
9541 } else {
9542 accessorType = AccessorType::None;
9543 }
9544
9545 auto emitValue = [this, &key, &prop, accessorType, &pe]() {
9546 // [stack] CTOR? OBJ CTOR? KEY?
9547
9548 ParseNode* propVal = prop->right();
9549 if (propVal->isDirectRHSAnonFunction()) {
9550 // The following branches except for the last `else` clause emit the
9551 // cases handled in NameResolver::resolveFun (see NameFunctions.cpp)
9552 if (key->isKind(ParseNodeKind::ObjectPropertyName) ||
9553 key->isKind(ParseNodeKind::PrivateName) ||
9554 key->isKind(ParseNodeKind::StringExpr)) {
9555 auto keyAtom = key->as<NameNode>().atom();
9556 if (!emitAnonymousFunctionWithName(propVal, keyAtom)) {
9557 // [stack] CTOR? OBJ CTOR? VAL
9558 return false;
9559 }
9560 } else if (key->isKind(ParseNodeKind::NumberExpr)) {
9561 MOZ_ASSERT(accessorType == AccessorType::None);
9562
9563 auto keyAtom = key->as<NumericLiteral>().toAtom(fc, parserAtoms());
9564 if (!keyAtom) {
9565 return false;
9566 }
9567 if (!emitAnonymousFunctionWithName(propVal, keyAtom)) {
9568 // [stack] CTOR? OBJ CTOR? KEY VAL
9569 return false;
9570 }
9571 } else if (key->isKind(ParseNodeKind::ComputedName) &&
9572 (key->as<UnaryNode>().kid()->isKind(
9573 ParseNodeKind::NumberExpr) ||
9574 key->as<UnaryNode>().kid()->isKind(
9575 ParseNodeKind::StringExpr)) &&
9576 accessorType == AccessorType::None) {
9577 ParseNode* keyKid = key->as<UnaryNode>().kid();
9578 if (keyKid->isKind(ParseNodeKind::NumberExpr)) {
9579 auto keyAtom =
9580 keyKid->as<NumericLiteral>().toAtom(fc, parserAtoms());
9581 if (!keyAtom) {
9582 return false;
9583 }
9584 if (!emitAnonymousFunctionWithName(propVal, keyAtom)) {
9585 // [stack] CTOR? OBJ CTOR? KEY VAL
9586 return false;
9587 }
9588 } else {
9589 MOZ_ASSERT(keyKid->isKind(ParseNodeKind::StringExpr));
9590 auto keyAtom = keyKid->as<NameNode>().atom();
9591 if (!emitAnonymousFunctionWithName(propVal, keyAtom)) {
9592 // [stack] CTOR? OBJ CTOR? KEY VAL
9593 return false;
9594 }
9595 }
9596 } else {
9597 // Either a proper computed property name or a synthetic computed
9598 // property name for BigInt keys.
9599 MOZ_ASSERT(key->isKind(ParseNodeKind::ComputedName));
9600
9601 FunctionPrefixKind prefix =
9602 accessorType == AccessorType::None ? FunctionPrefixKind::None
9603 : accessorType == AccessorType::Getter ? FunctionPrefixKind::Get
9604 : FunctionPrefixKind::Set;
9605
9606 if (!emitAnonymousFunctionWithComputedName(propVal, prefix)) {
9607 // [stack] CTOR? OBJ CTOR? KEY VAL
9608 return false;
9609 }
9610 }
9611 } else {
9612 if (!emitTree(propVal)) {
9613 // [stack] CTOR? OBJ CTOR? KEY? VAL
9614 return false;
9615 }
9616 }
9617
9618 if (propVal->is<FunctionNode>() &&
9619 propVal->as<FunctionNode>().funbox()->needsHomeObject()) {
9620 if (!pe.emitInitHomeObject()) {
9621 // [stack] CTOR? OBJ CTOR? KEY? FUN
9622 return false;
9623 }
9624 }
9625
9626 #ifdef ENABLE_DECORATORS
9627 if (prop->is<ClassMethod>()) {
9628 ClassMethod& method = prop->as<ClassMethod>();
9629 if (method.decorators() && !method.decorators()->empty()) {
9630 DecoratorEmitter::Kind kind;
9631 switch (method.accessorType()) {
9632 case AccessorType::Getter:
9633 kind = DecoratorEmitter::Getter;
9634 break;
9635 case AccessorType::Setter:
9636 kind = DecoratorEmitter::Setter;
9637 break;
9638 case AccessorType::None:
9639 kind = DecoratorEmitter::Method;
9640 break;
9641 }
9642
9643 if (!method.isStatic()) {
9644 bool hasKeyOnStack = key->isKind(ParseNodeKind::NumberExpr) ||
9645 key->isKind(ParseNodeKind::ComputedName);
9646 if (!emitDupAt(hasKeyOnStack ? 4 : 3)) {
9647 // [stack] ADDINIT OBJ KEY? VAL ADDINIT
9648 return false;
9649 }
9650 } else {
9651 // TODO: See bug 1868220 for support for static methods.
9652 // Note: Key will be present if this has a private name.
9653 if (!emit1(JSOp::Undefined)) {
9654 // [stack] CTOR OBJ CTOR KEY? VAL ADDINIT
9655 return false;
9656 }
9657 }
9658
9659 if (!emit1(JSOp::Swap)) {
9660 // [stack] ADDINIT CTOR? OBJ CTOR? KEY? ADDINIT VAL
9661 return false;
9662 }
9663
9664 // The decorators are applied to the current value on the stack,
9665 // possibly replacing it.
9666 DecoratorEmitter de(this);
9667 if (!de.emitApplyDecoratorsToElementDefinition(
9668 kind, key, method.decorators(), method.isStatic())) {
9669 // [stack] ADDINIT CTOR? OBJ CTOR? KEY? ADDINIT VAL
9670 return false;
9671 }
9672
9673 if (!emit1(JSOp::Swap)) {
9674 // [stack] ADDINIT CTOR? OBJ CTOR? KEY? VAL ADDINIT
9675 return false;
9676 }
9677
9678 if (!emitPopN(1)) {
9679 // [stack] ADDINIT CTOR? OBJ CTOR? KEY? VAL
9680 return false;
9681 }
9682 }
9683 }
9684 #endif
9685
9686 return true;
9687 };
9688
9689 PropertyEmitter::Kind kind =
9690 (type == ClassBody && propdef->as<ClassMethod>().isStatic())
9691 ? PropertyEmitter::Kind::Static
9692 : PropertyEmitter::Kind::Prototype;
9693 if (key->isKind(ParseNodeKind::ObjectPropertyName) ||
9694 key->isKind(ParseNodeKind::StringExpr)) {
9695 // [stack] CTOR? OBJ
9696
9697 auto keyAtom = key->as<NameNode>().atom();
9698
9699 // emitClass took care of constructor already.
9700 if (type == ClassBody &&
9701 keyAtom == TaggedParserAtomIndex::WellKnown::constructor() &&
9702 !propdef->as<ClassMethod>().isStatic()) {
9703 continue;
9704 }
9705
9706 if (!pe.prepareForPropValue(propdef->pn_pos.begin, kind)) {
9707 // [stack] CTOR? OBJ CTOR?
9708 return false;
9709 }
9710
9711 if (!emitValue()) {
9712 // [stack] CTOR? OBJ CTOR? VAL
9713 return false;
9714 }
9715
9716 if (!pe.emitInit(accessorType, keyAtom)) {
9717 // [stack] CTOR? OBJ
9718 return false;
9719 }
9720
9721 continue;
9722 }
9723
9724 if (key->isKind(ParseNodeKind::NumberExpr)) {
9725 // [stack] CTOR? OBJ
9726 if (!pe.prepareForIndexPropKey(propdef->pn_pos.begin, kind)) {
9727 // [stack] CTOR? OBJ CTOR?
9728 return false;
9729 }
9730 if (!emitNumberOp(key->as<NumericLiteral>().value())) {
9731 // [stack] CTOR? OBJ CTOR? KEY
9732 return false;
9733 }
9734 if (!pe.prepareForIndexPropValue()) {
9735 // [stack] CTOR? OBJ CTOR? KEY
9736 return false;
9737 }
9738 if (!emitValue()) {
9739 // [stack] CTOR? OBJ CTOR? KEY VAL
9740 return false;
9741 }
9742
9743 if (!pe.emitInitIndexOrComputed(accessorType)) {
9744 // [stack] CTOR? OBJ
9745 return false;
9746 }
9747
9748 continue;
9749 }
9750
9751 if (key->isKind(ParseNodeKind::ComputedName)) {
9752 // Either a proper computed property name or a synthetic computed property
9753 // name for BigInt keys.
9754
9755 // [stack] CTOR? OBJ
9756
9757 if (!pe.prepareForComputedPropKey(propdef->pn_pos.begin, kind)) {
9758 // [stack] CTOR? OBJ CTOR?
9759 return false;
9760 }
9761 if (!emitTree(key->as<UnaryNode>().kid())) {
9762 // [stack] CTOR? OBJ CTOR? KEY
9763 return false;
9764 }
9765 if (!pe.prepareForComputedPropValue()) {
9766 // [stack] CTOR? OBJ CTOR? KEY
9767 return false;
9768 }
9769 if (!emitValue()) {
9770 // [stack] CTOR? OBJ CTOR? KEY VAL
9771 return false;
9772 }
9773
9774 if (!pe.emitInitIndexOrComputed(accessorType)) {
9775 // [stack] CTOR? OBJ
9776 return false;
9777 }
9778
9779 continue;
9780 }
9781
9782 MOZ_ASSERT(key->isKind(ParseNodeKind::PrivateName));
9783 MOZ_ASSERT(type == ClassBody);
9784
9785 auto* privateName = &key->as<NameNode>();
9786
9787 if (kind == PropertyEmitter::Kind::Prototype) {
9788 MOZ_ASSERT(accessorType == AccessorType::None);
9789 if (!pe.prepareForPrivateMethod()) {
9790 // [stack] CTOR OBJ
9791 return false;
9792 }
9793 NameOpEmitter noe(this, privateName->atom(),
9794 NameOpEmitter::Kind::SimpleAssignment);
9795
9796 // Ensure the NameOp emitter doesn't push an environment onto the stack,
9797 // because that would change the stack location of the home object.
9798 MOZ_ASSERT(noe.loc().kind() == NameLocation::Kind::FrameSlot ||
9799 noe.loc().kind() == NameLocation::Kind::EnvironmentCoordinate);
9800
9801 if (!noe.prepareForRhs()) {
9802 // [stack] CTOR OBJ
9803 return false;
9804 }
9805 if (!emitValue()) {
9806 // [stack] CTOR OBJ METHOD
9807 return false;
9808 }
9809 if (!noe.emitAssignment()) {
9810 // [stack] CTOR OBJ METHOD
9811 return false;
9812 }
9813 if (!emit1(JSOp::Pop)) {
9814 // [stack] CTOR OBJ
9815 return false;
9816 }
9817 if (!pe.skipInit()) {
9818 // [stack] CTOR OBJ
9819 return false;
9820 }
9821 continue;
9822 }
9823
9824 MOZ_ASSERT(kind == PropertyEmitter::Kind::Static);
9825
9826 // [stack] CTOR OBJ
9827
9828 if (!pe.prepareForPrivateStaticMethod(propdef->pn_pos.begin)) {
9829 // [stack] CTOR OBJ CTOR
9830 return false;
9831 }
9832 if (!emitGetPrivateName(privateName)) {
9833 // [stack] CTOR OBJ CTOR KEY
9834 return false;
9835 }
9836 if (!emitValue()) {
9837 // [stack] CTOR OBJ CTOR KEY VAL
9838 return false;
9839 }
9840
9841 if (!pe.emitPrivateStaticMethod(accessorType)) {
9842 // [stack] CTOR OBJ
9843 return false;
9844 }
9845
9846 if (privateName->privateNameKind() == PrivateNameKind::Setter) {
9847 if (!emitDupAt(1)) {
9848 // [stack] CTOR OBJ CTOR
9849 return false;
9850 }
9851 if (!emitGetPrivateName(privateName)) {
9852 // [stack] CTOR OBJ CTOR NAME
9853 return false;
9854 }
9855 if (!emitAtomOp(JSOp::GetIntrinsic,
9856 TaggedParserAtomIndex::WellKnown::NoPrivateGetter())) {
9857 // [stack] CTOR OBJ CTOR NAME FUN
9858 return false;
9859 }
9860 if (!emit1(JSOp::InitHiddenElemGetter)) {
9861 // [stack] CTOR OBJ CTOR
9862 return false;
9863 }
9864 if (!emit1(JSOp::Pop)) {
9865 // [stack] CTOR OBJ
9866 return false;
9867 }
9868 }
9869 }
9870
9871 return true;
9872 }
9873
9874 bool BytecodeEmitter::emitPropertyListObjLiteral(ListNode* obj, JSOp op,
9875 bool useObjLiteralValues) {
9876 ObjLiteralWriter writer;
9877
9878 #ifdef DEBUG
9879 // In self-hosted JS, we check duplication only on debug build.
9880 mozilla::Maybe<mozilla::HashSet<frontend::TaggedParserAtomIndex,
9881 frontend::TaggedParserAtomIndexHasher>>
9882 selfHostedPropNames;
9883 if (emitterMode == BytecodeEmitter::SelfHosting) {
9884 selfHostedPropNames.emplace();
9885 }
9886 #endif
9887
9888 if (op == JSOp::Object) {
9889 writer.beginObject(op);
9890 } else {
9891 MOZ_ASSERT(op == JSOp::NewObject);
9892 writer.beginShape(op);
9893 }
9894
9895 for (ParseNode* propdef : obj->contents()) {
9896 BinaryNode* prop = &propdef->as<BinaryNode>();
9897 ParseNode* key = prop->left();
9898
9899 if (key->is<NameNode>()) {
9900 if (emitterMode == BytecodeEmitter::SelfHosting) {
9901 auto propName = key->as<NameNode>().atom();
9902 #ifdef DEBUG
9903 // Self-hosted JS shouldn't contain duplicate properties.
9904 auto p = selfHostedPropNames->lookupForAdd(propName);
9905 MOZ_ASSERT(!p);
9906 if (!selfHostedPropNames->add(p, propName)) {
9907 js::ReportOutOfMemory(fc);
9908 return false;
9909 }
9910 #endif
9911 writer.setPropNameNoDuplicateCheck(parserAtoms(), propName);
9912 } else {
9913 if (!writer.setPropName(parserAtoms(), key->as<NameNode>().atom())) {
9914 return false;
9915 }
9916 }
9917 } else {
9918 double numValue = key->as<NumericLiteral>().value();
9919 int32_t i = 0;
9920 DebugOnly<bool> numIsInt =
9921 NumberIsInt32(numValue, &i); // checked previously.
9922 MOZ_ASSERT(numIsInt);
9923 MOZ_ASSERT(
9924 ObjLiteralWriter::arrayIndexInRange(i)); // checked previously.
9925
9926 // Ignore indexed properties if we're not storing property values, and
9927 // rely on InitElem ops to define those. These properties will be either
9928 // dense elements (not possible to represent in the literal's shape) or
9929 // sparse elements (enumerated separately, so this doesn't affect property
9930 // iteration order).
9931 if (!useObjLiteralValues) {
9932 continue;
9933 }
9934
9935 writer.setPropIndex(i);
9936 }
9937
9938 if (useObjLiteralValues) {
9939 MOZ_ASSERT(op == JSOp::Object);
9940 ParseNode* value = prop->right();
9941 if (!emitObjLiteralValue(writer, value)) {
9942 return false;
9943 }
9944 } else {
9945 if (!writer.propWithUndefinedValue(fc)) {
9946 return false;
9947 }
9948 }
9949 }
9950
9951 GCThingIndex index;
9952 if (!addObjLiteralData(writer, &index)) {
9953 return false;
9954 }
9955
9956 // JSOp::Object may only be used by (top-level) run-once scripts.
9957 MOZ_ASSERT_IF(op == JSOp::Object,
9958 sc->isTopLevelContext() && sc->treatAsRunOnce());
9959
9960 if (!emitGCIndexOp(op, index)) {
9961 // [stack] OBJ
9962 return false;
9963 }
9964
9965 return true;
9966 }
9967
9968 bool BytecodeEmitter::emitDestructuringRestExclusionSetObjLiteral(
9969 ListNode* pattern) {
9970 // Note: if we want to squeeze out a little more performance, we could switch
9971 // to the `JSOp::Object` opcode, because the exclusion set object is never
9972 // exposed to the user, so it's safe to bake the object into the bytecode.
9973 constexpr JSOp op = JSOp::NewObject;
9974
9975 ObjLiteralWriter writer;
9976 writer.beginShape(op);
9977
9978 for (ParseNode* member : pattern->contents()) {
9979 if (member->isKind(ParseNodeKind::Spread)) {
9980 MOZ_ASSERT(!member->pn_next, "unexpected trailing element after spread");
9981 break;
9982 }
9983
9984 TaggedParserAtomIndex atom;
9985 if (member->isKind(ParseNodeKind::MutateProto)) {
9986 atom = TaggedParserAtomIndex::WellKnown::proto_();
9987 } else {
9988 ParseNode* key = member->as<BinaryNode>().left();
9989 atom = key->as<NameNode>().atom();
9990 }
9991
9992 if (!writer.setPropName(parserAtoms(), atom)) {
9993 return false;
9994 }
9995
9996 if (!writer.propWithUndefinedValue(fc)) {
9997 return false;
9998 }
9999 }
10000
10001 GCThingIndex index;
10002 if (!addObjLiteralData(writer, &index)) {
10003 return false;
10004 }
10005
10006 if (!emitGCIndexOp(op, index)) {
10007 // [stack] OBJ
10008 return false;
10009 }
10010
10011 return true;
10012 }
10013
10014 bool BytecodeEmitter::emitObjLiteralArray(ListNode* array) {
10015 MOZ_ASSERT(checkSingletonContext());
10016
10017 constexpr JSOp op = JSOp::Object;
10018
10019 ObjLiteralWriter writer;
10020 writer.beginArray(op);
10021
10022 writer.beginDenseArrayElements();
10023 for (ParseNode* elem : array->contents()) {
10024 if (!emitObjLiteralValue(writer, elem)) {
10025 return false;
10026 }
10027 }
10028
10029 GCThingIndex index;
10030 if (!addObjLiteralData(writer, &index)) {
10031 return false;
10032 }
10033
10034 if (!emitGCIndexOp(op, index)) {
10035 // [stack] OBJ
10036 return false;
10037 }
10038
10039 return true;
10040 }
10041
10042 bool BytecodeEmitter::isRHSObjLiteralCompatible(ParseNode* value) const {
10043 return value->isKind(ParseNodeKind::NumberExpr) ||
10044 value->isKind(ParseNodeKind::TrueExpr) ||
10045 value->isKind(ParseNodeKind::FalseExpr) ||
10046 value->isKind(ParseNodeKind::NullExpr) ||
10047 value->isKind(ParseNodeKind::RawUndefinedExpr) ||
10048 value->isKind(ParseNodeKind::StringExpr) ||
10049 value->isKind(ParseNodeKind::TemplateStringExpr);
10050 }
10051
10052 bool BytecodeEmitter::emitObjLiteralValue(ObjLiteralWriter& writer,
10053 ParseNode* value) {
10054 MOZ_ASSERT(isRHSObjLiteralCompatible(value));
10055 if (value->isKind(ParseNodeKind::NumberExpr)) {
10056 double numValue = value->as<NumericLiteral>().value();
10057 int32_t i = 0;
10058 js::Value v;
10059 if (NumberIsInt32(numValue, &i)) {
10060 v.setInt32(i);
10061 } else {
10062 v.setDouble(numValue);
10063 }
10064 if (!writer.propWithConstNumericValue(fc, v)) {
10065 return false;
10066 }
10067 } else if (value->isKind(ParseNodeKind::TrueExpr)) {
10068 if (!writer.propWithTrueValue(fc)) {
10069 return false;
10070 }
10071 } else if (value->isKind(ParseNodeKind::FalseExpr)) {
10072 if (!writer.propWithFalseValue(fc)) {
10073 return false;
10074 }
10075 } else if (value->isKind(ParseNodeKind::NullExpr)) {
10076 if (!writer.propWithNullValue(fc)) {
10077 return false;
10078 }
10079 } else if (value->isKind(ParseNodeKind::RawUndefinedExpr)) {
10080 if (!writer.propWithUndefinedValue(fc)) {
10081 return false;
10082 }
10083 } else if (value->isKind(ParseNodeKind::StringExpr) ||
10084 value->isKind(ParseNodeKind::TemplateStringExpr)) {
10085 if (!writer.propWithAtomValue(fc, parserAtoms(),
10086 value->as<NameNode>().atom())) {
10087 return false;
10088 }
10089 } else {
10090 MOZ_CRASH("Unexpected parse node");
10091 }
10092 return true;
10093 }
10094
10095 static bool NeedsPrivateBrand(ParseNode* member) {
10096 return member->is<ClassMethod>() &&
10097 member->as<ClassMethod>().name().isKind(ParseNodeKind::PrivateName) &&
10098 !member->as<ClassMethod>().isStatic();
10099 }
10100
10101 #ifdef ENABLE_DECORATORS
10102 static bool HasDecorators(ParseNode* member) {
10103 return member->is<ClassMethod>() && member->as<ClassMethod>().decorators();
10104 }
10105 #endif
10106
10107 mozilla::Maybe<MemberInitializers> BytecodeEmitter::setupMemberInitializers(
10108 ListNode* classMembers, FieldPlacement placement) const {
10109 bool isStatic = placement == FieldPlacement::Static;
10110
10111 size_t numFields = 0;
10112 size_t numPrivateInitializers = 0;
10113 bool hasPrivateBrand = false;
10114 #ifdef ENABLE_DECORATORS
10115 bool hasDecorators = false;
10116 #endif
10117 for (ParseNode* member : classMembers->contents()) {
10118 if (NeedsFieldInitializer(member, isStatic)) {
10119 numFields++;
10120 } else if (NeedsAccessorInitializer(member, isStatic)) {
10121 numPrivateInitializers++;
10122 hasPrivateBrand = true;
10123 } else if (NeedsPrivateBrand(member)) {
10124 hasPrivateBrand = true;
10125 }
10126 #ifdef ENABLE_DECORATORS
10127 if (!hasDecorators && HasDecorators(member)) {
10128 hasDecorators = true;
10129 }
10130 #endif
10131 }
10132
10133 // If there are more initializers than can be represented, return invalid.
10134 if (numFields + numPrivateInitializers >
10135 MemberInitializers::MaxInitializers) {
10136 return Nothing();
10137 }
10138 return Some(MemberInitializers(hasPrivateBrand,
10139 #ifdef ENABLE_DECORATORS
10140 hasDecorators,
10141 #endif
10142 numFields + numPrivateInitializers));
10143 }
10144
10145 // Purpose of .fieldKeys:
10146 // Computed field names (`["x"] = 2;`) must be ran at class-evaluation time,
10147 // not object construction time. The transformation to do so is roughly as
10148 // follows:
10149 //
10150 // class C {
10151 // [keyExpr] = valueExpr;
10152 // }
10153 // -->
10154 // let .fieldKeys = [keyExpr];
10155 // let .initializers = [
10156 // () => {
10157 // this[.fieldKeys[0]] = valueExpr;
10158 // }
10159 // ];
10160 // class C {
10161 // constructor() {
10162 // .initializers[0]();
10163 // }
10164 // }
10165 //
10166 // BytecodeEmitter::emitCreateFieldKeys does `let .fieldKeys = [...];`
10167 // BytecodeEmitter::emitPropertyList fills in the elements of the array.
10168 // See GeneralParser::fieldInitializer for the `this[.fieldKeys[0]]` part.
10169 bool BytecodeEmitter::emitCreateFieldKeys(ListNode* obj,
10170 FieldPlacement placement) {
10171 bool isStatic = placement == FieldPlacement::Static;
10172 auto isFieldWithComputedName = [isStatic](ParseNode* propdef) {
10173 return propdef->is<ClassField>() &&
10174 propdef->as<ClassField>().isStatic() == isStatic &&
10175 propdef->as<ClassField>().name().getKind() ==
10176 ParseNodeKind::ComputedName;
10177 };
10178
10179 size_t numFieldKeys = std::count_if(
10180 obj->contents().begin(), obj->contents().end(), isFieldWithComputedName);
10181 if (numFieldKeys == 0) {
10182 return true;
10183 }
10184
10185 auto fieldKeys =
10186 isStatic ? TaggedParserAtomIndex::WellKnown::dot_staticFieldKeys_()
10187 : TaggedParserAtomIndex::WellKnown::dot_fieldKeys_();
10188 NameOpEmitter noe(this, fieldKeys, NameOpEmitter::Kind::Initialize);
10189 if (!noe.prepareForRhs()) {
10190 return false;
10191 }
10192
10193 if (!emitUint32Operand(JSOp::NewArray, numFieldKeys)) {
10194 // [stack] ARRAY
10195 return false;
10196 }
10197
10198 if (!noe.emitAssignment()) {
10199 // [stack] ARRAY
10200 return false;
10201 }
10202
10203 if (!emit1(JSOp::Pop)) {
10204 // [stack]
10205 return false;
10206 }
10207
10208 return true;
10209 }
10210
10211 static bool HasInitializer(ParseNode* node, bool isStaticContext) {
10212 return (node->is<ClassField>() &&
10213 node->as<ClassField>().isStatic() == isStaticContext) ||
10214 (isStaticContext && node->is<StaticClassBlock>());
10215 }
10216
10217 static FunctionNode* GetInitializer(ParseNode* node, bool isStaticContext) {
10218 MOZ_ASSERT(HasInitializer(node, isStaticContext));
10219 MOZ_ASSERT_IF(!node->is<ClassField>(), isStaticContext);
10220 return node->is<ClassField>() ? node->as<ClassField>().initializer()
10221 : node->as<StaticClassBlock>().function();
10222 }
10223
10224 static bool IsPrivateInstanceAccessor(const ClassMethod* classMethod) {
10225 return !classMethod->isStatic() &&
10226 classMethod->name().isKind(ParseNodeKind::PrivateName) &&
10227 classMethod->accessorType() != AccessorType::None;
10228 }
10229
10230 bool BytecodeEmitter::emitCreateMemberInitializers(ClassEmitter& ce,
10231 ListNode* obj,
10232 FieldPlacement placement
10233 #ifdef ENABLE_DECORATORS
10234 ,
10235 bool hasHeritage
10236 #endif
10237 ) {
10238 // FieldPlacement::Instance, hasHeritage == false
10239 // [stack] HOME
10240 //
10241 // FieldPlacement::Instance, hasHeritage == true
10242 // [stack] HOME HERIT
10243 //
10244 // FieldPlacement::Static
10245 // [stack] CTOR HOME
10246 #ifdef ENABLE_DECORATORS
10247 MOZ_ASSERT_IF(placement == FieldPlacement::Static, !hasHeritage);
10248 #endif
10249 mozilla::Maybe<MemberInitializers> memberInitializers =
10250 setupMemberInitializers(obj, placement);
10251 if (!memberInitializers) {
10252 ReportAllocationOverflow(fc);
10253 return false;
10254 }
10255
10256 size_t numInitializers = memberInitializers->numMemberInitializers;
10257 if (numInitializers == 0) {
10258 return true;
10259 }
10260
10261 bool isStatic = placement == FieldPlacement::Static;
10262 if (!ce.prepareForMemberInitializers(numInitializers, isStatic)) {
10263 // [stack] HOME HERIT? ARR
10264 // or:
10265 // [stack] CTOR HOME ARR
10266 return false;
10267 }
10268
10269 // Private accessors could be used in the field initializers, so make sure
10270 // accessor initializers appear earlier in the .initializers array so they
10271 // run first. Static private methods are not initialized using initializers
10272 // (emitPropertyList emits bytecode to stamp them onto the constructor), so
10273 // skip this step if isStatic.
10274 if (!isStatic) {
10275 if (!emitPrivateMethodInitializers(ce, obj)) {
10276 return false;
10277 }
10278 }
10279
10280 for (ParseNode* propdef : obj->contents()) {
10281 if (!HasInitializer(propdef, isStatic)) {
10282 continue;
10283 }
10284
10285 FunctionNode* initializer = GetInitializer(propdef, isStatic);
10286
10287 if (!ce.prepareForMemberInitializer()) {
10288 return false;
10289 }
10290 if (!emitTree(initializer)) {
10291 // [stack] HOME HERIT? ARR LAMBDA
10292 // or:
10293 // [stack] CTOR HOME ARR LAMBDA
10294 return false;
10295 }
10296 if (initializer->funbox()->needsHomeObject()) {
10297 MOZ_ASSERT(initializer->funbox()->allowSuperProperty());
10298 if (!ce.emitMemberInitializerHomeObject(isStatic)) {
10299 // [stack] HOME HERIT? ARR LAMBDA
10300 // or:
10301 // [stack] CTOR HOME ARR LAMBDA
10302 return false;
10303 }
10304 }
10305 if (!ce.emitStoreMemberInitializer()) {
10306 // [stack] HOME HERIT? ARR
10307 // or:
10308 // [stack] CTOR HOME ARR
10309 return false;
10310 }
10311 }
10312
10313 #ifdef ENABLE_DECORATORS
10314 // Index to use to append new initializers returned by decorators to the array
10315 if (!emitNumberOp(numInitializers)) {
10316 // [stack] HOME HERIT? ARR I
10317 // or:
10318 // [stack] CTOR HOME ARR I
10319 return false;
10320 }
10321
10322 for (ParseNode* propdef : obj->contents()) {
10323 if (!propdef->is<ClassField>()) {
10324 continue;
10325 }
10326 ClassField* field = &propdef->as<ClassField>();
10327 if (field->isStatic() != isStatic) {
10328 continue;
10329 }
10330 if (field->decorators() && !field->decorators()->empty()) {
10331 DecoratorEmitter de(this);
10332 if (!field->hasAccessor()) {
10333 if (!emitDupAt((hasHeritage || isStatic) ? 4 : 3)) {
10334 // [stack] ADDINIT HOME HERIT? ARR I ADDINIT
10335 // or:
10336 // [stack] ADDINIT CTOR HOME ARR I ADDINIT
10337 return false;
10338 }
10339 if (!de.emitApplyDecoratorsToFieldDefinition(
10340 &field->name(), field->decorators(), field->isStatic())) {
10341 // [stack] HOME HERIT? ARR I ADDINIT INITS
10342 // or:
10343 // [stack] CTOR HOME ARR I ADDINIT INITS
10344 return false;
10345 }
10346 if (!emit1(JSOp::Swap)) {
10347 // [stack] HOME HERIT? ARR I INITS ADDINIT
10348 // or:
10349 // [stack] CTOR HOME ARR I INITS ADDINIT
10350 return false;
10351 }
10352 if (!emitPopN(1)) {
10353 // [stack] ADDINIT HOME HERIT? ARR I INITS
10354 // or:
10355 // [stack] ADDINIT CTOR HOME ARR I INITS
10356 return false;
10357 }
10358 } else {
10359 ClassMethod* accessorGetterNode = field->accessorGetterNode();
10360 auto accessorGetterKeyAtom =
10361 accessorGetterNode->left()->as<NameNode>().atom();
10362 ClassMethod* accessorSetterNode = field->accessorSetterNode();
10363 auto accessorSetterKeyAtom =
10364 accessorSetterNode->left()->as<NameNode>().atom();
10365 if (!IsPrivateInstanceAccessor(accessorGetterNode)) {
10366 if (!emitTree(&accessorGetterNode->method())) {
10367 // [stack] ADDINIT HOME HERIT? ARR I GET
10368 // or:
10369 // [stack] ADDINIT CTOR HOME ARR I GET
10370 return false;
10371 }
10372 if (!emitTree(&accessorSetterNode->method())) {
10373 // [stack] ADDINIT HOME HERIT? ARR I GET
10374 // SET
10375 // or:
10376 // [stack] ADDINIT CTOR HOME ARR I GET SET
10377 return false;
10378 }
10379 } else {
10380 MOZ_ASSERT(IsPrivateInstanceAccessor(accessorSetterNode));
10381 auto getAccessor = [this](
10382 ClassMethod* classMethod,
10383 TaggedParserAtomIndex& updatedAtom) -> bool {
10384 // [stack]
10385
10386 // Synthesize a name for the lexical variable that will store the
10387 // private method body.
10388 TaggedParserAtomIndex name =
10389 classMethod->name().as<NameNode>().atom();
10390 AccessorType accessorType = classMethod->accessorType();
10391 StringBuilder storedMethodName(fc);
10392 if (!storedMethodName.append(parserAtoms(), name)) {
10393 return false;
10394 }
10395 if (!storedMethodName.append(accessorType == AccessorType::Getter
10396 ? ".getter"
10397 : ".setter")) {
10398 return false;
10399 }
10400 updatedAtom = storedMethodName.finishParserAtom(parserAtoms(), fc);
10401 if (!updatedAtom) {
10402 return false;
10403 }
10404
10405 return emitGetName(updatedAtom);
10406 // [stack] ACCESSOR
10407 };
10408
10409 if (!getAccessor(accessorGetterNode, accessorGetterKeyAtom)) {
10410 // [stack] ADDINIT HOME HERIT? ARR I GET
10411 // or:
10412 // [stack] ADDINIT CTOR HOME ARR I GET
10413 return false;
10414 };
10415
10416 if (!getAccessor(accessorSetterNode, accessorSetterKeyAtom)) {
10417 // [stack] ADDINIT HOME HERIT? ARR I GET SET
10418 // or:
10419 // [stack] ADDINIT CTOR HOME ARR I GET SET
10420 return false;
10421 };
10422 }
10423
10424 if (!emitDupAt((hasHeritage || isStatic) ? 6 : 5)) {
10425 // [stack] ADDINIT HOME HERIT? ARR I GET SET ADDINIT
10426 // or:
10427 // [stack] ADDINIT CTOR HOME ARR I GET SET ADDINIT
10428 return false;
10429 }
10430
10431 if (!emitUnpickN(2)) {
10432 // [stack] ADDINIT HOME HERIT? ARR I ADDINIT GET SET
10433 // or:
10434 // [stack] ADDINIT CTOR HOME ARR I ADDINIT GET SET
10435 return false;
10436 }
10437
10438 if (!de.emitApplyDecoratorsToAccessorDefinition(
10439 &field->name(), field->decorators(), field->isStatic())) {
10440 // [stack] ADDINIT HOME HERIT? ARR I ADDINIT GET SET INITS
10441 // or:
10442 // [stack] ADDINIT CTOR HOME ARR I ADDINIT GET SET INITS
10443 return false;
10444 }
10445
10446 if (!emitPickN(3)) {
10447 // [stack] HOME HERIT? ARR I GET SET INITS ADDINIT
10448 // or:
10449 // [stack] CTOR HOME ARR I GET SET INITS ADDINIT
10450 return false;
10451 }
10452
10453 if (!emitPopN(1)) {
10454 // [stack] ADDINIT HOME HERIT? ARR I GET SET INITS
10455 // or:
10456 // [stack] ADDINIT CTOR HOME ARR I GET SET INITS
10457 return false;
10458 }
10459
10460 if (!emitUnpickN(2)) {
10461 // [stack] ADDINIT HOME HERIT? ARR I INITS GET SET
10462 // or:
10463 // [stack] ADDINIT CTOR HOME ARR I INITS GET SET
10464 return false;
10465 }
10466
10467 if (!IsPrivateInstanceAccessor(accessorGetterNode)) {
10468 if (!isStatic) {
10469 if (!emitDupAt(hasHeritage ? 6 : 5)) {
10470 // [stack] ADDINIT HOME HERIT? ARR I INITS GET SET HOME
10471 return false;
10472 }
10473 } else {
10474 if (!emitDupAt(6)) {
10475 // [stack] ADDINIT CTOR HOME ARR I INITS GET SET CTOR
10476 return false;
10477 }
10478 if (!emitDupAt(6)) {
10479 // [stack] ADDINIT CTOR HOME ARR I INITS GET SET CTOR HOME
10480 return false;
10481 }
10482 }
10483
10484 PropertyEmitter::Kind kind = field->isStatic()
10485 ? PropertyEmitter::Kind::Static
10486 : PropertyEmitter::Kind::Prototype;
10487 if (!accessorGetterNode->name().isKind(ParseNodeKind::PrivateName)) {
10488 MOZ_ASSERT(
10489 !accessorSetterNode->name().isKind(ParseNodeKind::PrivateName));
10490
10491 if (!ce.prepareForPropValue(propdef->pn_pos.begin, kind)) {
10492 // [stack] ADDINIT HOME HERIT? ARR I INITS GET SET HOME
10493 // or:
10494 // [stack] ADDINIT CTOR HOME ARR I INITS GET SET CTOR HOME CTOR
10495 return false;
10496 }
10497 if (!emitPickN(isStatic ? 3 : 1)) {
10498 // [stack] ADDINIT HOME HERIT? ARR I INITS GET HOME SET
10499 // or:
10500 // [stack] ADDINIT CTOR HOME ARR I INITS GET CTOR HOME CTOR SET
10501 return false;
10502 }
10503 if (!ce.emitInit(AccessorType::Setter, accessorSetterKeyAtom)) {
10504 // [stack] ADDINIT HOME HERIT? ARR I INITS GET HOME
10505 // or:
10506 // [stack] ADDINIT CTOR HOME ARR I INITS GET CTOR HOME
10507 return false;
10508 }
10509
10510 if (!ce.prepareForPropValue(propdef->pn_pos.begin, kind)) {
10511 // [stack] ADDINIT HOME HERIT? ARR I INITS GET HOME
10512 // or:
10513 // [stack] ADDINIT CTOR HOME ARR I INITS GET CTOR HOME CTOR
10514 return false;
10515 }
10516 if (!emitPickN(isStatic ? 3 : 1)) {
10517 // [stack] ADDINIT HOME HERIT? ARR I INITS HOME GET
10518 // or:
10519 // [stack] ADDINIT CTOR HOME ARR I INITS CTOR HOME CTOR GET
10520 return false;
10521 }
10522 if (!ce.emitInit(AccessorType::Getter, accessorGetterKeyAtom)) {
10523 // [stack] ADDINIT HOME HERIT? ARR I INITS HOME
10524 // or:
10525 // [stack] ADDINIT CTOR HOME ARR I INITS CTOR HOME
10526 return false;
10527 }
10528 } else {
10529 MOZ_ASSERT(isStatic);
10530 // The getter and setter share the same name.
10531 if (!emitNewPrivateName(accessorSetterKeyAtom,
10532 accessorSetterKeyAtom)) {
10533 return false;
10534 }
10535 if (!ce.prepareForPrivateStaticMethod(propdef->pn_pos.begin)) {
10536 // [stack] ADDINIT CTOR HOME ARR I INITS GET SET CTOR HOME CTOR
10537 return false;
10538 }
10539 if (!emitGetPrivateName(
10540 &accessorSetterNode->name().as<NameNode>())) {
10541 // [stack] ADDINIT CTOR HOME ARR I INITS GET SET CTOR HOME CTOR
10542 // KEY
10543 return false;
10544 }
10545 if (!emitPickN(4)) {
10546 // [stack] ADDINIT CTOR HOME ARR I INITS GET CTOR HOME CTOR KEY
10547 // SET
10548 return false;
10549 }
10550 if (!ce.emitPrivateStaticMethod(AccessorType::Setter)) {
10551 // [stack] ADDINIT CTOR HOME ARR I INITS GET CTOR HOME
10552 return false;
10553 }
10554
10555 if (!ce.prepareForPrivateStaticMethod(propdef->pn_pos.begin)) {
10556 // [stack] ADDINIT CTOR HOME ARR I INITS GET CTOR HOME CTOR
10557 return false;
10558 }
10559 if (!emitGetPrivateName(
10560 &accessorGetterNode->name().as<NameNode>())) {
10561 // [stack] ADDINIT CTOR HOME ARR I INITS GET CTOR HOME CTOR KEY
10562 return false;
10563 }
10564 if (!emitPickN(4)) {
10565 // [stack] ADDINIT CTOR HOME ARR I INITS CTOR HOME CTOR KEY GET
10566 return false;
10567 }
10568 if (!ce.emitPrivateStaticMethod(AccessorType::Getter)) {
10569 // [stack] ADDINIT CTOR HOME ARR I INITS CTOR HOME
10570 return false;
10571 }
10572 }
10573
10574 if (!isStatic) {
10575 if (!emitPopN(1)) {
10576 // [stack] ADDINIT HOME HERIT? ARR I INITS
10577 return false;
10578 }
10579 } else {
10580 if (!emitPopN(2)) {
10581 // [stack] ADDINIT CTOR HOME ARR I INITS
10582 return false;
10583 }
10584 }
10585 } else {
10586 MOZ_ASSERT(IsPrivateInstanceAccessor(accessorSetterNode));
10587
10588 if (!emitLexicalInitialization(accessorSetterKeyAtom)) {
10589 // [stack] ADDINIT HOME HERIT? ARR I INITS GET SET
10590 // or:
10591 // [stack] ADDINIT CTOR HOME ARR I INITS GET SET
10592 return false;
10593 }
10594
10595 if (!emitPopN(1)) {
10596 // [stack] ADDINIT HOME HERIT? ARR I INITS GET
10597 // or:
10598 // [stack] ADDINIT CTOR HOME ARR I INITS GET
10599 return false;
10600 }
10601
10602 if (!emitLexicalInitialization(accessorGetterKeyAtom)) {
10603 // [stack] ADDINIT HOME HERIT? ARR I INITS GET
10604 // or:
10605 // [stack] ADDINIT CTOR HOME ARR I INITS GET
10606 return false;
10607 }
10608
10609 if (!emitPopN(1)) {
10610 // [stack] ADDINIT HOME HERIT? ARR I INITS
10611 // or:
10612 // [stack] ADDINIT CTOR HOME ARR I INITS
10613 return false;
10614 }
10615 }
10616 }
10617 if (!emit1(JSOp::InitElemInc)) {
10618 // [stack] ADDINIT HOME HERIT? ARR I
10619 // or:
10620 // [stack] ADDINIT CTOR HOME ARR I
10621 return false;
10622 }
10623 }
10624 }
10625
10626 // Pop I
10627 if (!emitPopN(1)) {
10628 // [stack] ADDINIT HOME HERIT? ARR
10629 // or:
10630 // [stack] ADDINIT CTOR HOME ARR
10631 return false;
10632 }
10633 #endif
10634
10635 if (!ce.emitMemberInitializersEnd()) {
10636 // [stack] ADDINIT HOME HERIT?
10637 // or:
10638 // [stack] ADDINIT CTOR HOME
10639 return false;
10640 }
10641
10642 return true;
10643 }
10644
10645 bool BytecodeEmitter::emitPrivateMethodInitializers(ClassEmitter& ce,
10646 ListNode* obj) {
10647 for (ParseNode* propdef : obj->contents()) {
10648 if (!propdef->is<ClassMethod>()) {
10649 continue;
10650 }
10651 auto* classMethod = &propdef->as<ClassMethod>();
10652
10653 // Skip over anything which isn't a private instance accessor.
10654 if (!IsPrivateInstanceAccessor(classMethod)) {
10655 continue;
10656 }
10657
10658 if (!ce.prepareForMemberInitializer()) {
10659 // [stack] HOMEOBJ HERITAGE? ARRAY
10660 // or:
10661 // [stack] CTOR HOMEOBJ ARRAY
10662 return false;
10663 }
10664
10665 // Synthesize a name for the lexical variable that will store the
10666 // private method body.
10667 TaggedParserAtomIndex name = classMethod->name().as<NameNode>().atom();
10668 AccessorType accessorType = classMethod->accessorType();
10669 StringBuilder storedMethodName(fc);
10670 if (!storedMethodName.append(parserAtoms(), name)) {
10671 return false;
10672 }
10673 if (!storedMethodName.append(
10674 accessorType == AccessorType::Getter ? ".getter" : ".setter")) {
10675 return false;
10676 }
10677 auto storedMethodAtom =
10678 storedMethodName.finishParserAtom(parserAtoms(), fc);
10679
10680 // Emit the private method body and store it as a lexical var.
10681 if (!emitFunction(&classMethod->method())) {
10682 // [stack] HOMEOBJ HERITAGE? ARRAY METHOD
10683 // or:
10684 // [stack] CTOR HOMEOBJ ARRAY METHOD
10685 return false;
10686 }
10687 // The private method body needs to access the home object,
10688 // and the CE knows where that is on the stack.
10689 if (classMethod->method().funbox()->needsHomeObject()) {
10690 if (!ce.emitMemberInitializerHomeObject(false)) {
10691 // [stack] HOMEOBJ HERITAGE? ARRAY METHOD
10692 // or:
10693 // [stack] CTOR HOMEOBJ ARRAY METHOD
10694 return false;
10695 }
10696 }
10697 if (!emitLexicalInitialization(storedMethodAtom)) {
10698 // [stack] HOMEOBJ HERITAGE? ARRAY METHOD
10699 // or:
10700 // [stack] CTOR HOMEOBJ ARRAY METHOD
10701 return false;
10702 }
10703 if (!emit1(JSOp::Pop)) {
10704 // [stack] HOMEOBJ HERITAGE? ARRAY
10705 // or:
10706 // [stack] CTOR HOMEOBJ ARRAY
10707 return false;
10708 }
10709
10710 if (!emitPrivateMethodInitializer(classMethod, storedMethodAtom)) {
10711 // [stack] HOMEOBJ HERITAGE? ARRAY
10712 // or:
10713 // [stack] CTOR HOMEOBJ ARRAY
10714 return false;
10715 }
10716
10717 // Store the emitted initializer function into the .initializers array.
10718 if (!ce.emitStoreMemberInitializer()) {
10719 // [stack] HOMEOBJ HERITAGE? ARRAY
10720 // or:
10721 // [stack] CTOR HOMEOBJ ARRAY
10722 return false;
10723 }
10724 }
10725
10726 return true;
10727 }
10728
10729 bool BytecodeEmitter::emitPrivateMethodInitializer(
10730 ClassMethod* classMethod, TaggedParserAtomIndex storedMethodAtom) {
10731 MOZ_ASSERT(IsPrivateInstanceAccessor(classMethod));
10732
10733 auto* name = &classMethod->name().as<NameNode>();
10734
10735 // Emit the synthesized initializer function.
10736 FunctionNode* funNode = classMethod->initializerIfPrivate();
10737 MOZ_ASSERT(funNode);
10738 FunctionBox* funbox = funNode->funbox();
10739 FunctionEmitter fe(this, funbox, funNode->syntaxKind(),
10740 FunctionEmitter::IsHoisted::No);
10741 if (!fe.prepareForNonLazy()) {
10742 // [stack]
10743 return false;
10744 }
10745
10746 BytecodeEmitter bce2(this, funbox);
10747 if (!bce2.init(funNode->pn_pos)) {
10748 return false;
10749 }
10750 ParamsBodyNode* paramsBody = funNode->body();
10751 FunctionScriptEmitter fse(&bce2, funbox, Nothing(), Nothing());
10752 if (!fse.prepareForParameters()) {
10753 // [stack]
10754 return false;
10755 }
10756 if (!bce2.emitFunctionFormalParameters(paramsBody)) {
10757 // [stack]
10758 return false;
10759 }
10760 if (!fse.prepareForBody()) {
10761 // [stack]
10762 return false;
10763 }
10764
10765 if (!bce2.emit1(JSOp::FunctionThis)) {
10766 // [stack] THIS
10767 return false;
10768 }
10769 if (!bce2.emitGetPrivateName(name)) {
10770 // [stack] THIS NAME
10771 return false;
10772 }
10773 if (!bce2.emitGetName(storedMethodAtom)) {
10774 // [stack] THIS NAME METHOD
10775 return false;
10776 }
10777
10778 switch (name->privateNameKind()) {
10779 case PrivateNameKind::Setter:
10780 if (!bce2.emit1(JSOp::InitHiddenElemSetter)) {
10781 // [stack] THIS
10782 return false;
10783 }
10784 if (!bce2.emitGetPrivateName(name)) {
10785 // [stack] THIS NAME
10786 return false;
10787 }
10788 if (!bce2.emitAtomOp(
10789 JSOp::GetIntrinsic,
10790 TaggedParserAtomIndex::WellKnown::NoPrivateGetter())) {
10791 // [stack] THIS NAME FUN
10792 return false;
10793 }
10794 if (!bce2.emit1(JSOp::InitHiddenElemGetter)) {
10795 // [stack] THIS
10796 return false;
10797 }
10798 break;
10799 case PrivateNameKind::Getter:
10800 case PrivateNameKind::GetterSetter:
10801 if (classMethod->accessorType() == AccessorType::Getter) {
10802 if (!bce2.emit1(JSOp::InitHiddenElemGetter)) {
10803 // [stack] THIS
10804 return false;
10805 }
10806 } else {
10807 if (!bce2.emit1(JSOp::InitHiddenElemSetter)) {
10808 // [stack] THIS
10809 return false;
10810 }
10811 }
10812 break;
10813 default:
10814 MOZ_CRASH("Invalid op");
10815 }
10816
10817 // Pop remaining THIS.
10818 if (!bce2.emit1(JSOp::Pop)) {
10819 // [stack]
10820 return false;
10821 }
10822
10823 if (!fse.emitEndBody()) {
10824 // [stack]
10825 return false;
10826 }
10827 if (!fse.intoStencil()) {
10828 return false;
10829 }
10830
10831 if (!fe.emitNonLazyEnd()) {
10832 // [stack] HOMEOBJ HERITAGE? ARRAY FUN
10833 // or:
10834 // [stack] CTOR HOMEOBJ ARRAY FUN
10835 return false;
10836 }
10837
10838 return true;
10839 }
10840
10841 const MemberInitializers& BytecodeEmitter::findMemberInitializersForCall()
10842 const {
10843 for (const auto* current = this; current; current = current->parent) {
10844 if (current->sc->isFunctionBox()) {
10845 FunctionBox* funbox = current->sc->asFunctionBox();
10846
10847 if (funbox->isArrow()) {
10848 continue;
10849 }
10850
10851 // If we found a non-arrow / non-constructor we were never allowed to
10852 // expect fields in the first place.
10853 MOZ_RELEASE_ASSERT(funbox->isClassConstructor());
10854
10855 return funbox->useMemberInitializers() ? funbox->memberInitializers()
10856 : MemberInitializers::Empty();
10857 }
10858 }
10859
10860 MOZ_RELEASE_ASSERT(compilationState.scopeContext.memberInitializers);
10861 return *compilationState.scopeContext.memberInitializers;
10862 }
10863
10864 bool BytecodeEmitter::emitInitializeInstanceMembers(
10865 bool isDerivedClassConstructor) {
10866 const MemberInitializers& memberInitializers =
10867 findMemberInitializersForCall();
10868 MOZ_ASSERT(memberInitializers.valid);
10869
10870 if (memberInitializers.hasPrivateBrand) {
10871 // This is guaranteed to run after super(), so we don't need TDZ checks.
10872 if (!emitGetName(TaggedParserAtomIndex::WellKnown::dot_this_())) {
10873 // [stack] THIS
10874 return false;
10875 }
10876 if (!emitGetName(TaggedParserAtomIndex::WellKnown::dot_privateBrand_())) {
10877 // [stack] THIS BRAND
10878 return false;
10879 }
10880 if (isDerivedClassConstructor) {
10881 if (!emitCheckPrivateField(ThrowCondition::ThrowHas,
10882 ThrowMsgKind::PrivateBrandDoubleInit)) {
10883 // [stack] THIS BRAND BOOL
10884 return false;
10885 }
10886 if (!emit1(JSOp::Pop)) {
10887 // [stack] THIS BRAND
10888 return false;
10889 }
10890 }
10891 if (!emit1(JSOp::Null)) {
10892 // [stack] THIS BRAND NULL
10893 return false;
10894 }
10895 if (!emit1(JSOp::InitHiddenElem)) {
10896 // [stack] THIS
10897 return false;
10898 }
10899 if (!emit1(JSOp::Pop)) {
10900 // [stack]
10901 return false;
10902 }
10903 }
10904
10905 size_t numInitializers = memberInitializers.numMemberInitializers;
10906 if (numInitializers > 0) {
10907 if (!emitGetName(TaggedParserAtomIndex::WellKnown::dot_initializers_())) {
10908 // [stack] ARRAY
10909 return false;
10910 }
10911
10912 for (size_t index = 0; index < numInitializers; index++) {
10913 if (index < numInitializers - 1) {
10914 // We Dup to keep the array around (it is consumed in the bytecode
10915 // below) for next iterations of this loop, except for the last
10916 // iteration, which avoids an extra Pop at the end of the loop.
10917 if (!emit1(JSOp::Dup)) {
10918 // [stack] ARRAY ARRAY
10919 return false;
10920 }
10921 }
10922
10923 if (!emitNumberOp(index)) {
10924 // [stack] ARRAY? ARRAY INDEX
10925 return false;
10926 }
10927
10928 if (!emit1(JSOp::GetElem)) {
10929 // [stack] ARRAY? FUNC
10930 return false;
10931 }
10932
10933 // This is guaranteed to run after super(), so we don't need TDZ checks.
10934 if (!emitGetName(TaggedParserAtomIndex::WellKnown::dot_this_())) {
10935 // [stack] ARRAY? FUNC THIS
10936 return false;
10937 }
10938
10939 // Callee is always internal function.
10940 if (!emitCall(JSOp::CallIgnoresRv, 0)) {
10941 // [stack] ARRAY? RVAL
10942 return false;
10943 }
10944
10945 if (!emit1(JSOp::Pop)) {
10946 // [stack] ARRAY?
10947 return false;
10948 }
10949 }
10950 #ifdef ENABLE_DECORATORS
10951 if (memberInitializers.hasDecorators) {
10952 // Decorators Proposal
10953 // https://arai-a.github.io/ecma262-compare/?pr=2417&id=sec-initializeinstanceelements
10954 // 4. For each element e of elements, do
10955 // 4.a. If elementRecord.[[Kind]] is field or accessor, then
10956 // 4.a.i. Perform ? InitializeFieldOrAccessor(O, elementRecord).
10957 //
10958
10959 // TODO: (See Bug 1817993) At the moment, we're applying the
10960 // initialization logic in two steps. The pre-decorator initialization
10961 // code runs, stores the initial value, and then we retrieve it here and
10962 // apply the initializers added by decorators. We should unify these two
10963 // steps.
10964 if (!emitGetName(TaggedParserAtomIndex::WellKnown::dot_initializers_())) {
10965 // [stack] ARRAY
10966 return false;
10967 }
10968
10969 if (!emit1(JSOp::Dup)) {
10970 // [stack] ARRAY ARRAY
10971 return false;
10972 }
10973
10974 if (!emitAtomOp(JSOp::GetProp,
10975 TaggedParserAtomIndex::WellKnown::length())) {
10976 // [stack] ARRAY LENGTH
10977 return false;
10978 }
10979
10980 if (!emitNumberOp(static_cast<double>(numInitializers))) {
10981 // [stack] ARRAY LENGTH INDEX
10982 return false;
10983 }
10984
10985 InternalWhileEmitter wh(this);
10986 // At this point, we have no context to determine offsets in the
10987 // code for this while statement. Ideally, it would correspond to
10988 // the field we're initializing.
10989 if (!wh.emitCond()) {
10990 // [stack] ARRAY LENGTH INDEX
10991 return false;
10992 }
10993
10994 if (!emit1(JSOp::Dup)) {
10995 // [stack] ARRAY LENGTH INDEX INDEX
10996 return false;
10997 }
10998
10999 if (!emitDupAt(2)) {
11000 // [stack] ARRAY LENGTH INDEX INDEX LENGTH
11001 return false;
11002 }
11003
11004 if (!emit1(JSOp::Lt)) {
11005 // [stack] ARRAY LENGTH INDEX BOOL
11006 return false;
11007 }
11008
11009 if (!wh.emitBody()) {
11010 // [stack] ARRAY LENGTH INDEX
11011 return false;
11012 }
11013
11014 if (!emitDupAt(2)) {
11015 // [stack] ARRAY LENGTH INDEX ARRAY
11016 return false;
11017 }
11018
11019 if (!emitDupAt(1)) {
11020 // [stack] ARRAY LENGTH INDEX ARRAY INDEX
11021 return false;
11022 }
11023
11024 // Retrieve initializers for this field
11025 if (!emit1(JSOp::GetElem)) {
11026 // [stack] ARRAY LENGTH INDEX INITIALIZERS
11027 return false;
11028 }
11029
11030 // This is guaranteed to run after super(), so we don't need TDZ checks.
11031 if (!emitGetName(TaggedParserAtomIndex::WellKnown::dot_this_())) {
11032 // [stack] ARRAY LENGTH INDEX INITIALIZERS THIS
11033 return false;
11034 }
11035
11036 if (!emit1(JSOp::Swap)) {
11037 // [stack] ARRAY LENGTH INDEX THIS INITIALIZERS
11038 return false;
11039 }
11040
11041 DecoratorEmitter de(this);
11042 if (!de.emitInitializeFieldOrAccessor()) {
11043 // [stack] ARRAY LENGTH INDEX
11044 return false;
11045 }
11046
11047 if (!emit1(JSOp::Inc)) {
11048 // [stack] ARRAY LENGTH INDEX
11049 return false;
11050 }
11051
11052 if (!wh.emitEnd()) {
11053 // [stack] ARRAY LENGTH INDEX
11054 return false;
11055 }
11056
11057 if (!emitPopN(3)) {
11058 // [stack]
11059 return false;
11060 }
11061 // 5. Return unused.
11062
11063 if (!de.emitCallExtraInitializers(TaggedParserAtomIndex::WellKnown::
11064 dot_instanceExtraInitializers_())) {
11065 return false;
11066 }
11067 }
11068 #endif
11069 }
11070 return true;
11071 }
11072
11073 bool BytecodeEmitter::emitInitializeStaticFields(ListNode* classMembers) {
11074 auto isStaticField = [](ParseNode* propdef) {
11075 return HasInitializer(propdef, true);
11076 };
11077 size_t numFields =
11078 std::count_if(classMembers->contents().begin(),
11079 classMembers->contents().end(), isStaticField);
11080
11081 if (numFields == 0) {
11082 return true;
11083 }
11084
11085 if (!emitGetName(
11086 TaggedParserAtomIndex::WellKnown::dot_staticInitializers_())) {
11087 // [stack] CTOR ARRAY
11088 return false;
11089 }
11090
11091 for (size_t fieldIndex = 0; fieldIndex < numFields; fieldIndex++) {
11092 bool hasNext = fieldIndex < numFields - 1;
11093 if (hasNext) {
11094 // We Dup to keep the array around (it is consumed in the bytecode below)
11095 // for next iterations of this loop, except for the last iteration, which
11096 // avoids an extra Pop at the end of the loop.
11097 if (!emit1(JSOp::Dup)) {
11098 // [stack] CTOR ARRAY ARRAY
11099 return false;
11100 }
11101 }
11102
11103 if (!emitNumberOp(fieldIndex)) {
11104 // [stack] CTOR ARRAY? ARRAY INDEX
11105 return false;
11106 }
11107
11108 if (!emit1(JSOp::GetElem)) {
11109 // [stack] CTOR ARRAY? FUNC
11110 return false;
11111 }
11112
11113 if (!emitDupAt(1 + hasNext)) {
11114 // [stack] CTOR ARRAY? FUNC CTOR
11115 return false;
11116 }
11117
11118 // Callee is always internal function.
11119 if (!emitCall(JSOp::CallIgnoresRv, 0)) {
11120 // [stack] CTOR ARRAY? RVAL
11121 return false;
11122 }
11123
11124 if (!emit1(JSOp::Pop)) {
11125 // [stack] CTOR ARRAY?
11126 return false;
11127 }
11128 }
11129
11130 #ifdef ENABLE_DECORATORS
11131 // Decorators Proposal
11132 // https://arai-a.github.io/ecma262-compare/?pr=2417&id=sec-initializeinstanceelements
11133 // 4. For each element e of elements, do
11134 // 4.a. If elementRecord.[[Kind]] is field or accessor, then
11135 // 4.a.i. Perform ? InitializeFieldOrAccessor(O, elementRecord).
11136 //
11137
11138 // TODO: (See Bug 1817993) At the moment, we're applying the initialization
11139 // logic in two steps. The pre-decorator initialization code runs, stores
11140 // the initial value, and then we retrieve it here and apply the
11141 // initializers added by decorators. We should unify these two steps.
11142 if (!emitGetName(
11143 TaggedParserAtomIndex::WellKnown::dot_staticInitializers_())) {
11144 // [stack] CTOR ARRAY
11145 return false;
11146 }
11147
11148 if (!emit1(JSOp::Dup)) {
11149 // [stack] CTOR ARRAY ARRAY
11150 return false;
11151 }
11152
11153 if (!emitAtomOp(JSOp::GetProp, TaggedParserAtomIndex::WellKnown::length())) {
11154 // [stack] CTOR ARRAY LENGTH
11155 return false;
11156 }
11157
11158 if (!emitNumberOp(static_cast<double>(numFields))) {
11159 // [stack] CTOR ARRAY LENGTH INDEX
11160 return false;
11161 }
11162
11163 InternalWhileEmitter wh(this);
11164 // At this point, we have no context to determine offsets in the
11165 // code for this while statement. Ideally, it would correspond to
11166 // the field we're initializing.
11167 if (!wh.emitCond()) {
11168 // [stack] CTOR ARRAY LENGTH INDEX
11169 return false;
11170 }
11171
11172 if (!emit1(JSOp::Dup)) {
11173 // [stack] CTOR ARRAY LENGTH INDEX INDEX
11174 return false;
11175 }
11176
11177 if (!emitDupAt(2)) {
11178 // [stack] CTOR ARRAY LENGTH INDEX INDEX LENGTH
11179 return false;
11180 }
11181
11182 if (!emit1(JSOp::Lt)) {
11183 // [stack] CTOR ARRAY LENGTH INDEX BOOL
11184 return false;
11185 }
11186
11187 if (!wh.emitBody()) {
11188 // [stack] CTOR ARRAY LENGTH INDEX
11189 return false;
11190 }
11191
11192 if (!emitDupAt(2)) {
11193 // [stack] CTOR ARRAY LENGTH INDEX ARRAY
11194 return false;
11195 }
11196
11197 if (!emitDupAt(1)) {
11198 // [stack] CTOR ARRAY LENGTH INDEX ARRAY INDEX
11199 return false;
11200 }
11201
11202 // Retrieve initializers for this field
11203 if (!emit1(JSOp::GetElem)) {
11204 // [stack] CTOR ARRAY LENGTH INDEX INITIALIZERS
11205 return false;
11206 }
11207
11208 if (!emitDupAt(4)) {
11209 // [stack] CTOR ARRAY LENGTH INDEX INITIALIZERS CTOR
11210 return false;
11211 }
11212
11213 if (!emit1(JSOp::Swap)) {
11214 // [stack] CTOR ARRAY LENGTH INDEX CTOR INITIALIZERS
11215 return false;
11216 }
11217
11218 DecoratorEmitter de(this);
11219 if (!de.emitInitializeFieldOrAccessor()) {
11220 // [stack] CTOR ARRAY LENGTH INDEX
11221 return false;
11222 }
11223
11224 if (!emit1(JSOp::Inc)) {
11225 // [stack] CTOR ARRAY LENGTH INDEX
11226 return false;
11227 }
11228
11229 if (!wh.emitEnd()) {
11230 // [stack] CTOR ARRAY LENGTH INDEX
11231 return false;
11232 }
11233
11234 if (!emitPopN(3)) {
11235 // [stack] CTOR
11236 return false;
11237 }
11238 // 5. Return unused.
11239 #endif
11240
11241 // Overwrite |.staticInitializers| and |.staticFieldKeys| with undefined to
11242 // avoid keeping the arrays alive indefinitely.
11243 auto clearStaticFieldSlot = [&](TaggedParserAtomIndex name) {
11244 NameOpEmitter noe(this, name, NameOpEmitter::Kind::SimpleAssignment);
11245 if (!noe.prepareForRhs()) {
11246 // [stack] ENV? VAL?
11247 return false;
11248 }
11249
11250 if (!emit1(JSOp::Undefined)) {
11251 // [stack] ENV? VAL? UNDEFINED
11252 return false;
11253 }
11254
11255 if (!noe.emitAssignment()) {
11256 // [stack] VAL
11257 return false;
11258 }
11259
11260 if (!emit1(JSOp::Pop)) {
11261 // [stack]
11262 return false;
11263 }
11264
11265 return true;
11266 };
11267
11268 if (!clearStaticFieldSlot(
11269 TaggedParserAtomIndex::WellKnown::dot_staticInitializers_())) {
11270 return false;
11271 }
11272
11273 auto isStaticFieldWithComputedName = [](ParseNode* propdef) {
11274 return propdef->is<ClassField>() && propdef->as<ClassField>().isStatic() &&
11275 propdef->as<ClassField>().name().getKind() ==
11276 ParseNodeKind::ComputedName;
11277 };
11278
11279 if (std::any_of(classMembers->contents().begin(),
11280 classMembers->contents().end(),
11281 isStaticFieldWithComputedName)) {
11282 if (!clearStaticFieldSlot(
11283 TaggedParserAtomIndex::WellKnown::dot_staticFieldKeys_())) {
11284 return false;
11285 }
11286 }
11287
11288 return true;
11289 }
11290
11291 // Using MOZ_NEVER_INLINE in here is a workaround for llvm.org/pr14047. See
11292 // the comment on emitSwitch.
11293 MOZ_NEVER_INLINE bool BytecodeEmitter::emitObject(ListNode* objNode) {
11294 // Note: this method uses the ObjLiteralWriter and emits ObjLiteralStencil
11295 // objects into the GCThingList, which will evaluate them into real GC objects
11296 // or shapes during JSScript::fullyInitFromEmitter. Eventually we want
11297 // JSOp::Object to be a real opcode, but for now, performance constraints
11298 // limit us to evaluating object literals at the end of parse, when we're
11299 // allowed to allocate GC things.
11300 //
11301 // There are four cases here, in descending order of preference:
11302 //
11303 // 1. The list of property names is "normal" and constant (no computed
11304 // values, no integer indices), the values are all simple constants
11305 // (numbers, booleans, strings), *and* this occurs in a run-once
11306 // (singleton) context. In this case, we can emit ObjLiteral
11307 // instructions to build an object with values, and the object will be
11308 // attached to a JSOp::Object opcode, whose semantics are for the backend
11309 // to simply steal the object from the script.
11310 //
11311 // 2. The list of property names is "normal" and constant as above, *and* this
11312 // occurs in a run-once (singleton) context, but some values are complex
11313 // (computed expressions, sub-objects, functions, etc.). In this case, we
11314 // can still use JSOp::Object (because singleton context), but the object
11315 // has |undefined| property values and InitProp ops are emitted to set the
11316 // values.
11317 //
11318 // 3. The list of property names is "normal" and constant as above, but this
11319 // occurs in a non-run-once (non-singleton) context. In this case, we can
11320 // use the ObjLiteral functionality to describe an *empty* object (all
11321 // values left undefined) with the right fields, which will become a
11322 // JSOp::NewObject opcode using the object's shape to speed up the creation
11323 // of the object each time it executes. The emitted bytecode still needs
11324 // InitProp ops to set the values in this case.
11325 //
11326 // 4. Any other case. As a fallback, we use NewInit to create a new, empty
11327 // object (i.e., `{}`) and then emit bytecode to initialize its properties
11328 // one-by-one.
11329
11330 bool useObjLiteral = false;
11331 bool useObjLiteralValues = false;
11332 isPropertyListObjLiteralCompatible(objNode, &useObjLiteralValues,
11333 &useObjLiteral);
11334
11335 // [stack]
11336 //
11337 ObjectEmitter oe(this);
11338 if (useObjLiteral) {
11339 bool singleton = checkSingletonContext() &&
11340 !objNode->hasNonConstInitializer() && objNode->head();
11341 JSOp op;
11342 if (singleton) {
11343 // Case 1 or 2.
11344 op = JSOp::Object;
11345 } else {
11346 // Case 3.
11347 useObjLiteralValues = false;
11348 op = JSOp::NewObject;
11349 }
11350
11351 // Use an ObjLiteral op. This will record ObjLiteral insns in the
11352 // objLiteralWriter's buffer and add a fixup to the list of ObjLiteral
11353 // fixups so that at GC-publish time at the end of parse, the full object
11354 // (case 1 or 2) or shape (case 3) can be allocated and the bytecode can be
11355 // patched to refer to it.
11356 if (!emitPropertyListObjLiteral(objNode, op, useObjLiteralValues)) {
11357 // [stack] OBJ
11358 return false;
11359 }
11360 // Put the ObjectEmitter in the right state. This tells it that there will
11361 // already be an object on the stack as a result of the (eventual)
11362 // NewObject or Object op, and prepares it to emit values if needed.
11363 if (!oe.emitObjectWithTemplateOnStack()) {
11364 // [stack] OBJ
11365 return false;
11366 }
11367 if (!useObjLiteralValues) {
11368 // Case 2 or 3 above: we still need to emit bytecode to fill in the
11369 // object's property values.
11370 if (!emitPropertyList(objNode, oe, ObjectLiteral)) {
11371 // [stack] OBJ
11372 return false;
11373 }
11374 }
11375 } else {
11376 // Case 4 above: no ObjLiteral use, just bytecode to build the object from
11377 // scratch.
11378 if (!oe.emitObject(objNode->count())) {
11379 // [stack] OBJ
11380 return false;
11381 }
11382 if (!emitPropertyList(objNode, oe, ObjectLiteral)) {
11383 // [stack] OBJ
11384 return false;
11385 }
11386 }
11387
11388 if (!oe.emitEnd()) {
11389 // [stack] OBJ
11390 return false;
11391 }
11392
11393 return true;
11394 }
11395
11396 bool BytecodeEmitter::emitArrayLiteral(ListNode* array) {
11397 // Emit JSOp::Object if the array consists entirely of primitive values and we
11398 // are in a singleton context.
11399 if (checkSingletonContext() && !array->hasNonConstInitializer() &&
11400 !array->empty() && isArrayObjLiteralCompatible(array)) {
11401 return emitObjLiteralArray(array);
11402 }
11403
11404 return emitArray(array);
11405 }
11406
11407 bool BytecodeEmitter::emitArray(ListNode* array) {
11408 /*
11409 * Emit code for [a, b, c] that is equivalent to constructing a new
11410 * array and in source order evaluating each element value and adding
11411 * it to the array, without invoking latent setters. We use the
11412 * JSOp::NewInit and JSOp::InitElemArray bytecodes to ignore setters and
11413 * to avoid dup'ing and popping the array as each element is added, as
11414 * JSOp::SetElem/JSOp::SetProp would do.
11415 */
11416
11417 uint32_t nspread = 0;
11418 for (ParseNode* elem : array->contents()) {
11419 if (elem->isKind(ParseNodeKind::Spread)) {
11420 nspread++;
11421 }
11422 }
11423
11424 // Array literal's length is limited to NELEMENTS_LIMIT in parser.
11425 static_assert(NativeObject::MAX_DENSE_ELEMENTS_COUNT <= INT32_MAX,
11426 "array literals' maximum length must not exceed limits "
11427 "required by BaselineCompiler::emit_NewArray, "
11428 "BaselineCompiler::emit_InitElemArray, "
11429 "and DoSetElemFallback's handling of JSOp::InitElemArray");
11430
11431 uint32_t count = array->count();
11432 MOZ_ASSERT(count >= nspread);
11433 MOZ_ASSERT(count <= NativeObject::MAX_DENSE_ELEMENTS_COUNT,
11434 "the parser must throw an error if the array exceeds maximum "
11435 "length");
11436
11437 // For arrays with spread, this is a very pessimistic allocation, the
11438 // minimum possible final size.
11439 if (!emitUint32Operand(JSOp::NewArray, count - nspread)) {
11440 // [stack] ARRAY
11441 return false;
11442 }
11443
11444 uint32_t index = 0;
11445 bool afterSpread = false;
11446 for (ParseNode* elem : array->contents()) {
11447 if (elem->isKind(ParseNodeKind::Spread)) {
11448 if (!afterSpread) {
11449 afterSpread = true;
11450 if (!emitNumberOp(index)) {
11451 // [stack] ARRAY INDEX
11452 return false;
11453 }
11454 }
11455
11456 ParseNode* expr = elem->as<UnaryNode>().kid();
11457 SelfHostedIter selfHostedIter = getSelfHostedIterFor(expr);
11458
11459 if (!updateSourceCoordNotes(elem->pn_pos.begin)) {
11460 return false;
11461 }
11462 if (!emitIterable(expr, selfHostedIter)) {
11463 // [stack] ARRAY INDEX ITERABLE
11464 return false;
11465 }
11466 if (!emitIterator(selfHostedIter)) {
11467 // [stack] ARRAY INDEX NEXT ITER
11468 return false;
11469 }
11470 if (!emit2(JSOp::Pick, 3)) {
11471 // [stack] INDEX NEXT ITER ARRAY
11472 return false;
11473 }
11474 if (!emit2(JSOp::Pick, 3)) {
11475 // [stack] NEXT ITER ARRAY INDEX
11476 return false;
11477 }
11478 if (!emitSpread(selfHostedIter)) {
11479 // [stack] ARRAY INDEX
11480 return false;
11481 }
11482 } else {
11483 if (!updateSourceCoordNotesIfNonLiteral(elem)) {
11484 return false;
11485 }
11486 if (elem->isKind(ParseNodeKind::Elision)) {
11487 if (!emit1(JSOp::Hole)) {
11488 return false;
11489 }
11490 } else {
11491 if (!emitTree(elem, ValueUsage::WantValue)) {
11492 // [stack] ARRAY INDEX? VALUE
11493 return false;
11494 }
11495 }
11496
11497 if (afterSpread) {
11498 if (!emit1(JSOp::InitElemInc)) {
11499 // [stack] ARRAY (INDEX+1)
11500 return false;
11501 }
11502 } else {
11503 if (!emitUint32Operand(JSOp::InitElemArray, index)) {
11504 // [stack] ARRAY
11505 return false;
11506 }
11507 }
11508 }
11509
11510 index++;
11511 }
11512 MOZ_ASSERT(index == count);
11513 if (afterSpread) {
11514 if (!emit1(JSOp::Pop)) {
11515 // [stack] ARRAY
11516 return false;
11517 }
11518 }
11519 return true;
11520 }
11521
11522 bool BytecodeEmitter::emitSpreadIntoArray(UnaryNode* elem) {
11523 MOZ_ASSERT(elem->isKind(ParseNodeKind::Spread));
11524
11525 if (!updateSourceCoordNotes(elem->pn_pos.begin)) {
11526 // [stack] VALUE
11527 return false;
11528 }
11529
11530 SelfHostedIter selfHostedIter = getSelfHostedIterFor(elem->kid());
11531 MOZ_ASSERT(selfHostedIter == SelfHostedIter::Deny ||
11532 selfHostedIter == SelfHostedIter::AllowContent);
11533
11534 if (!emitIterator(selfHostedIter)) {
11535 // [stack] NEXT ITER
11536 return false;
11537 }
11538
11539 if (!emitUint32Operand(JSOp::NewArray, 0)) {
11540 // [stack] NEXT ITER ARRAY
11541 return false;
11542 }
11543
11544 if (!emitNumberOp(0)) {
11545 // [stack] NEXT ITER ARRAY INDEX
11546 return false;
11547 }
11548
11549 if (!emitSpread(selfHostedIter)) {
11550 // [stack] ARRAY INDEX
11551 return false;
11552 }
11553
11554 if (!emit1(JSOp::Pop)) {
11555 // [stack] ARRAY
11556 return false;
11557 }
11558 return true;
11559 }
11560
11561 static inline JSOp UnaryOpParseNodeKindToJSOp(ParseNodeKind pnk) {
11562 switch (pnk) {
11563 case ParseNodeKind::ThrowStmt:
11564 return JSOp::Throw;
11565 case ParseNodeKind::VoidExpr:
11566 return JSOp::Void;
11567 case ParseNodeKind::NotExpr:
11568 return JSOp::Not;
11569 case ParseNodeKind::BitNotExpr:
11570 return JSOp::BitNot;
11571 case ParseNodeKind::PosExpr:
11572 return JSOp::Pos;
11573 case ParseNodeKind::NegExpr:
11574 return JSOp::Neg;
11575 default:
11576 MOZ_CRASH("unexpected unary op");
11577 }
11578 }
11579
11580 bool BytecodeEmitter::emitUnary(UnaryNode* unaryNode) {
11581 if (!updateSourceCoordNotes(unaryNode->pn_pos.begin)) {
11582 return false;
11583 }
11584
11585 JSOp op = UnaryOpParseNodeKindToJSOp(unaryNode->getKind());
11586 ValueUsage valueUsage =
11587 op == JSOp::Void ? ValueUsage::IgnoreValue : ValueUsage::WantValue;
11588 if (!emitTree(unaryNode->kid(), valueUsage)) {
11589 return false;
11590 }
11591 return emit1(op);
11592 }
11593
11594 bool BytecodeEmitter::emitTypeof(UnaryNode* typeofNode, JSOp op) {
11595 MOZ_ASSERT(op == JSOp::Typeof || op == JSOp::TypeofExpr);
11596
11597 if (!updateSourceCoordNotes(typeofNode->pn_pos.begin)) {
11598 return false;
11599 }
11600
11601 if (!emitTree(typeofNode->kid())) {
11602 return false;
11603 }
11604
11605 return emit1(op);
11606 }
11607
11608 bool BytecodeEmitter::tryEmitTypeofEq(ListNode* node, bool* emitted) {
11609 // Emit specialized opcode for `typeof val == "type` or `typeof val != "type`
11610 // if possible.
11611 //
11612 // NOTE: Given the comparison is done for string, `==` and `===` have
11613 // no difference. Same for `!=` and `!==`.
11614 MOZ_ASSERT(node->isKind(ParseNodeKind::StrictEqExpr) ||
11615 node->isKind(ParseNodeKind::EqExpr) ||
11616 node->isKind(ParseNodeKind::StrictNeExpr) ||
11617 node->isKind(ParseNodeKind::NeExpr));
11618
11619 if (node->count() != 2) {
11620 *emitted = false;
11621 return true;
11622 }
11623
11624 ParseNode* left = node->head();
11625 ParseNode* right = left->pn_next;
11626 MOZ_ASSERT(right);
11627
11628 UnaryNode* typeofNode;
11629 NameNode* typenameNode;
11630 JSOp op;
11631
11632 if (node->isKind(ParseNodeKind::StrictEqExpr) ||
11633 node->isKind(ParseNodeKind::EqExpr)) {
11634 op = JSOp::Eq;
11635 } else {
11636 op = JSOp::Ne;
11637 }
11638
11639 // NOTE: ParseNodeKind::TypeOfExpr cannot use JSOp::TypeofEq.
11640 // See JSOp::GetName document.
11641 if (left->isKind(ParseNodeKind::TypeOfNameExpr) &&
11642 right->isKind(ParseNodeKind::StringExpr)) {
11643 typeofNode = &left->as<UnaryNode>();
11644 typenameNode = &right->as<NameNode>();
11645 } else if (right->isKind(ParseNodeKind::TypeOfNameExpr) &&
11646 left->isKind(ParseNodeKind::StringExpr)) {
11647 typeofNode = &right->as<UnaryNode>();
11648 typenameNode = &left->as<NameNode>();
11649 } else {
11650 *emitted = false;
11651 return true;
11652 }
11653
11654 JSType type;
11655 TaggedParserAtomIndex typeName = typenameNode->atom();
11656 if (typeName == TaggedParserAtomIndex::WellKnown::undefined()) {
11657 type = JSTYPE_UNDEFINED;
11658 } else if (typeName == TaggedParserAtomIndex::WellKnown::object()) {
11659 type = JSTYPE_OBJECT;
11660 } else if (typeName == TaggedParserAtomIndex::WellKnown::function()) {
11661 type = JSTYPE_FUNCTION;
11662 } else if (typeName == TaggedParserAtomIndex::WellKnown::string()) {
11663 type = JSTYPE_STRING;
11664 } else if (typeName == TaggedParserAtomIndex::WellKnown::number()) {
11665 type = JSTYPE_NUMBER;
11666 } else if (typeName == TaggedParserAtomIndex::WellKnown::boolean()) {
11667 type = JSTYPE_BOOLEAN;
11668 } else if (typeName == TaggedParserAtomIndex::WellKnown::symbol()) {
11669 type = JSTYPE_SYMBOL;
11670 } else if (typeName == TaggedParserAtomIndex::WellKnown::bigint()) {
11671 type = JSTYPE_BIGINT;
11672 } else {
11673 *emitted = false;
11674 return true;
11675 }
11676
11677 if (!updateSourceCoordNotes(typeofNode->pn_pos.begin)) {
11678 return false;
11679 }
11680
11681 if (!emitTree(typeofNode->kid())) {
11682 // [stack] VAL
11683 return false;
11684 }
11685
11686 if (!emit2(JSOp::TypeofEq, TypeofEqOperand(type, op).rawValue())) {
11687 // [stack] CMP
11688 return false;
11689 }
11690
11691 *emitted = true;
11692 return true;
11693 }
11694
11695 bool BytecodeEmitter::emitFunctionFormalParameters(ParamsBodyNode* paramsBody) {
11696 FunctionBox* funbox = sc->asFunctionBox();
11697
11698 bool hasRest = funbox->hasRest();
11699
11700 FunctionParamsEmitter fpe(this, funbox);
11701 for (ParseNode* arg : paramsBody->parameters()) {
11702 ParseNode* bindingElement = arg;
11703 ParseNode* initializer = nullptr;
11704 if (arg->isKind(ParseNodeKind::AssignExpr)) {
11705 bindingElement = arg->as<BinaryNode>().left();
11706 initializer = arg->as<BinaryNode>().right();
11707 }
11708 bool hasInitializer = !!initializer;
11709 bool isRest =
11710 hasRest && arg->pn_next == *std::end(paramsBody->parameters());
11711 bool isDestructuring = !bindingElement->isKind(ParseNodeKind::Name);
11712
11713 // Left-hand sides are either simple names or destructuring patterns.
11714 MOZ_ASSERT(bindingElement->isKind(ParseNodeKind::Name) ||
11715 bindingElement->isKind(ParseNodeKind::ArrayExpr) ||
11716 bindingElement->isKind(ParseNodeKind::ObjectExpr));
11717
11718 auto emitDefaultInitializer = [this, &initializer, &bindingElement]() {
11719 // [stack]
11720
11721 if (!this->emitInitializer(initializer, bindingElement)) {
11722 // [stack] DEFAULT
11723 return false;
11724 }
11725 return true;
11726 };
11727
11728 auto emitDestructuring = [this, &bindingElement]() {
11729 // [stack] ARG
11730
11731 if (!this->emitDestructuringOps(&bindingElement->as<ListNode>(),
11732 DestructuringFlavor::Declaration)) {
11733 // [stack] ARG
11734 return false;
11735 }
11736
11737 return true;
11738 };
11739
11740 if (isRest) {
11741 if (isDestructuring) {
11742 if (!fpe.prepareForDestructuringRest()) {
11743 // [stack]
11744 return false;
11745 }
11746 if (!emitDestructuring()) {
11747 // [stack]
11748 return false;
11749 }
11750 if (!fpe.emitDestructuringRestEnd()) {
11751 // [stack]
11752 return false;
11753 }
11754 } else {
11755 auto paramName = bindingElement->as<NameNode>().name();
11756 if (!fpe.emitRest(paramName)) {
11757 // [stack]
11758 return false;
11759 }
11760 }
11761
11762 continue;
11763 }
11764
11765 if (isDestructuring) {
11766 if (hasInitializer) {
11767 if (!fpe.prepareForDestructuringDefaultInitializer()) {
11768 // [stack]
11769 return false;
11770 }
11771 if (!emitDefaultInitializer()) {
11772 // [stack]
11773 return false;
11774 }
11775 if (!fpe.prepareForDestructuringDefault()) {
11776 // [stack]
11777 return false;
11778 }
11779 if (!emitDestructuring()) {
11780 // [stack]
11781 return false;
11782 }
11783 if (!fpe.emitDestructuringDefaultEnd()) {
11784 // [stack]
11785 return false;
11786 }
11787 } else {
11788 if (!fpe.prepareForDestructuring()) {
11789 // [stack]
11790 return false;
11791 }
11792 if (!emitDestructuring()) {
11793 // [stack]
11794 return false;
11795 }
11796 if (!fpe.emitDestructuringEnd()) {
11797 // [stack]
11798 return false;
11799 }
11800 }
11801
11802 continue;
11803 }
11804
11805 if (hasInitializer) {
11806 if (!fpe.prepareForDefault()) {
11807 // [stack]
11808 return false;
11809 }
11810 if (!emitDefaultInitializer()) {
11811 // [stack]
11812 return false;
11813 }
11814 auto paramName = bindingElement->as<NameNode>().name();
11815 if (!fpe.emitDefaultEnd(paramName)) {
11816 // [stack]
11817 return false;
11818 }
11819
11820 continue;
11821 }
11822
11823 auto paramName = bindingElement->as<NameNode>().name();
11824 if (!fpe.emitSimple(paramName)) {
11825 // [stack]
11826 return false;
11827 }
11828 }
11829
11830 return true;
11831 }
11832
11833 bool BytecodeEmitter::emitInitializeFunctionSpecialNames() {
11834 FunctionBox* funbox = sc->asFunctionBox();
11835
11836 // [stack]
11837
11838 auto emitInitializeFunctionSpecialName =
11839 [](BytecodeEmitter* bce, TaggedParserAtomIndex name, JSOp op) {
11840 // A special name must be slotful, either on the frame or on the
11841 // call environment.
11842 MOZ_ASSERT(bce->lookupName(name).hasKnownSlot());
11843
11844 NameOpEmitter noe(bce, name, NameOpEmitter::Kind::Initialize);
11845 if (!noe.prepareForRhs()) {
11846 // [stack]
11847 return false;
11848 }
11849 if (!bce->emit1(op)) {
11850 // [stack] THIS/ARGUMENTS/NEW.TARGET
11851 return false;
11852 }
11853 if (!noe.emitAssignment()) {
11854 // [stack] THIS/ARGUMENTS/NEW.TARGET
11855 return false;
11856 }
11857 if (!bce->emit1(JSOp::Pop)) {
11858 // [stack]
11859 return false;
11860 }
11861
11862 return true;
11863 };
11864
11865 // Do nothing if the function doesn't have an arguments binding.
11866 if (funbox->needsArgsObj()) {
11867 // Self-hosted code should use the more efficient ArgumentsLength and
11868 // GetArgument intrinsics instead of `arguments`.
11869 MOZ_ASSERT(emitterMode != BytecodeEmitter::SelfHosting);
11870 if (!emitInitializeFunctionSpecialName(
11871 this, TaggedParserAtomIndex::WellKnown::arguments(),
11872 JSOp::Arguments)) {
11873 // [stack]
11874 return false;
11875 }
11876 }
11877
11878 // Do nothing if the function doesn't have a this-binding (this
11879 // happens for instance if it doesn't use this/eval or if it's an
11880 // arrow function).
11881 if (funbox->functionHasThisBinding()) {
11882 if (!emitInitializeFunctionSpecialName(
11883 this, TaggedParserAtomIndex::WellKnown::dot_this_(),
11884 JSOp::FunctionThis)) {
11885 return false;
11886 }
11887 }
11888
11889 // Do nothing if the function doesn't have a new.target-binding (this happens
11890 // for instance if it doesn't use new.target/eval or if it's an arrow
11891 // function).
11892 if (funbox->functionHasNewTargetBinding()) {
11893 if (!emitInitializeFunctionSpecialName(
11894 this, TaggedParserAtomIndex::WellKnown::dot_newTarget_(),
11895 JSOp::NewTarget)) {
11896 return false;
11897 }
11898 }
11899
11900 // Do nothing if the function doesn't implicitly return a promise result.
11901 if (funbox->needsPromiseResult()) {
11902 if (!emitInitializeFunctionSpecialName(
11903 this, TaggedParserAtomIndex::WellKnown::dot_generator_(),
11904 JSOp::Generator)) {
11905 // [stack]
11906 return false;
11907 }
11908 }
11909 return true;
11910 }
11911
11912 bool BytecodeEmitter::emitLexicalInitialization(NameNode* name) {
11913 return emitLexicalInitialization(name->name());
11914 }
11915
11916 bool BytecodeEmitter::emitLexicalInitialization(TaggedParserAtomIndex name) {
11917 NameOpEmitter noe(this, name, NameOpEmitter::Kind::Initialize);
11918 if (!noe.prepareForRhs()) {
11919 return false;
11920 }
11921
11922 // The caller has pushed the RHS to the top of the stack. Assert that the
11923 // binding can be initialized without a binding object on the stack, and that
11924 // no JSOp::BindUnqualifiedName or JSOp::BindUnqualifiedGName ops were
11925 // emitted.
11926 MOZ_ASSERT(noe.loc().isLexical() || noe.loc().isSynthetic() ||
11927 noe.loc().isPrivateMethod());
11928 MOZ_ASSERT(!noe.emittedBindOp());
11929
11930 if (!noe.emitAssignment()) {
11931 return false;
11932 }
11933
11934 return true;
11935 }
11936
11937 static MOZ_ALWAYS_INLINE ParseNode* FindConstructor(ListNode* classMethods) {
11938 for (ParseNode* classElement : classMethods->contents()) {
11939 ParseNode* unwrappedElement = classElement;
11940 if (unwrappedElement->is<LexicalScopeNode>()) {
11941 unwrappedElement = unwrappedElement->as<LexicalScopeNode>().scopeBody();
11942 }
11943 if (unwrappedElement->is<ClassMethod>()) {
11944 ClassMethod& method = unwrappedElement->as<ClassMethod>();
11945 ParseNode& methodName = method.name();
11946 if (!method.isStatic() &&
11947 (methodName.isKind(ParseNodeKind::ObjectPropertyName) ||
11948 methodName.isKind(ParseNodeKind::StringExpr)) &&
11949 methodName.as<NameNode>().atom() ==
11950 TaggedParserAtomIndex::WellKnown::constructor()) {
11951 return classElement;
11952 }
11953 }
11954 }
11955 return nullptr;
11956 }
11957
11958 bool BytecodeEmitter::emitNewPrivateName(TaggedParserAtomIndex bindingName,
11959 TaggedParserAtomIndex symbolName) {
11960 if (!emitAtomOp(JSOp::NewPrivateName, symbolName)) {
11961 // [stack] HERITAGE PRIVATENAME
11962 return false;
11963 }
11964
11965 // Add a binding for #name => privatename
11966 if (!emitLexicalInitialization(bindingName)) {
11967 // [stack] HERITAGE PRIVATENAME
11968 return false;
11969 }
11970
11971 // Pop Private name off the stack.
11972 if (!emit1(JSOp::Pop)) {
11973 // [stack] HERITAGE
11974 return false;
11975 }
11976
11977 return true;
11978 }
11979
11980 bool BytecodeEmitter::emitNewPrivateNames(
11981 TaggedParserAtomIndex privateBrandName, ListNode* classMembers) {
11982 bool hasPrivateBrand = false;
11983
11984 for (ParseNode* classElement : classMembers->contents()) {
11985 ParseNode* elementName;
11986 if (classElement->is<ClassMethod>()) {
11987 elementName = &classElement->as<ClassMethod>().name();
11988 } else if (classElement->is<ClassField>()) {
11989 elementName = &classElement->as<ClassField>().name();
11990 } else {
11991 continue;
11992 }
11993
11994 if (!elementName->isKind(ParseNodeKind::PrivateName)) {
11995 continue;
11996 }
11997
11998 // Non-static private methods' private names are optimized away.
11999 bool isOptimized = false;
12000 if (classElement->is<ClassMethod>() &&
12001 !classElement->as<ClassMethod>().isStatic()) {
12002 hasPrivateBrand = true;
12003 if (classElement->as<ClassMethod>().accessorType() ==
12004 AccessorType::None) {
12005 isOptimized = true;
12006 }
12007 }
12008
12009 if (!isOptimized) {
12010 auto privateName = elementName->as<NameNode>().name();
12011 if (!emitNewPrivateName(privateName, privateName)) {
12012 return false;
12013 }
12014 }
12015 }
12016
12017 if (hasPrivateBrand) {
12018 // We don't make a private name for every optimized method, but we need one
12019 // private name per class, the `.privateBrand`.
12020 if (!emitNewPrivateName(
12021 TaggedParserAtomIndex::WellKnown::dot_privateBrand_(),
12022 privateBrandName)) {
12023 return false;
12024 }
12025 }
12026 return true;
12027 }
12028
12029 // This follows ES6 14.5.14 (ClassDefinitionEvaluation) and ES6 14.5.15
12030 // (BindingClassDeclarationEvaluation).
12031 bool BytecodeEmitter::emitClass(
12032 ClassNode* classNode,
12033 ClassNameKind nameKind /* = ClassNameKind::BindingName */,
12034 TaggedParserAtomIndex
12035 nameForAnonymousClass /* = TaggedParserAtomIndex::null() */) {
12036 MOZ_ASSERT((nameKind == ClassNameKind::InferredName) ==
12037 bool(nameForAnonymousClass));
12038
12039 ParseNode* heritageExpression = classNode->heritage();
12040 ListNode* classMembers = classNode->memberList();
12041 ParseNode* constructor = FindConstructor(classMembers);
12042
12043 // If |nameKind != ClassNameKind::ComputedName|
12044 // [stack]
12045 // Else
12046 // [stack] NAME
12047
12048 ClassEmitter ce(this);
12049 TaggedParserAtomIndex innerName;
12050 ClassEmitter::Kind kind = ClassEmitter::Kind::Expression;
12051 if (ClassNames* names = classNode->names()) {
12052 MOZ_ASSERT(nameKind == ClassNameKind::BindingName);
12053 innerName = names->innerBinding()->name();
12054 MOZ_ASSERT(innerName);
12055
12056 if (names->outerBinding()) {
12057 MOZ_ASSERT(names->outerBinding()->name());
12058 MOZ_ASSERT(names->outerBinding()->name() == innerName);
12059 kind = ClassEmitter::Kind::Declaration;
12060 }
12061 }
12062
12063 if (LexicalScopeNode* scopeBindings = classNode->scopeBindings()) {
12064 if (!ce.emitScope(scopeBindings->scopeBindings())) {
12065 // [stack]
12066 return false;
12067 }
12068 }
12069
12070 bool isDerived = !!heritageExpression;
12071 if (isDerived) {
12072 if (!updateSourceCoordNotes(classNode->pn_pos.begin)) {
12073 return false;
12074 }
12075 if (!markStepBreakpoint()) {
12076 return false;
12077 }
12078 if (!emitTree(heritageExpression)) {
12079 // [stack] HERITAGE
12080 return false;
12081 }
12082 }
12083
12084 // The class body scope holds any private names. Those mustn't be visible in
12085 // the heritage expression and hence the scope must be emitted after the
12086 // heritage expression.
12087 if (ClassBodyScopeNode* bodyScopeBindings = classNode->bodyScopeBindings()) {
12088 if (!ce.emitBodyScope(bodyScopeBindings->scopeBindings())) {
12089 // [stack] HERITAGE
12090 return false;
12091 }
12092
12093 // The spec does not say anything about private brands being symbols. It's
12094 // an implementation detail. So we can give the special private brand
12095 // symbol any description we want and users won't normally see it. For
12096 // debugging, use the class name.
12097 auto privateBrandName = innerName;
12098 if (!innerName) {
12099 privateBrandName = nameForAnonymousClass
12100 ? nameForAnonymousClass
12101 : TaggedParserAtomIndex::WellKnown::anonymous();
12102 }
12103 if (!emitNewPrivateNames(privateBrandName, classMembers)) {
12104 return false;
12105 }
12106 }
12107
12108 bool hasNameOnStack = nameKind == ClassNameKind::ComputedName;
12109 if (isDerived) {
12110 if (!ce.emitDerivedClass(innerName, nameForAnonymousClass,
12111 hasNameOnStack)) {
12112 // [stack] HOMEOBJ HERITAGE
12113 return false;
12114 }
12115 } else {
12116 int membersCount = 0;
12117 for (ParseNode* node : classMembers->contents()) {
12118 if (node->getKind() == ParseNodeKind::ClassField) {
12119 membersCount++;
12120 }
12121 }
12122 membersCount = (membersCount > 255) ? 255 : membersCount;
12123 if (!ce.emitClass(innerName, nameForAnonymousClass, hasNameOnStack,
12124 uint8_t(membersCount))) {
12125 // [stack] HOMEOBJ
12126 return false;
12127 }
12128 }
12129
12130 // Stack currently has HOMEOBJ followed by optional HERITAGE. When HERITAGE
12131 // is not used, an implicit value of %FunctionPrototype% is implied.
12132
12133 // See |Parser::classMember(...)| for the reason why |.initializers| is
12134 // created within its own scope.
12135 Maybe<LexicalScopeEmitter> lse;
12136 FunctionNode* ctor;
12137 #ifdef ENABLE_DECORATORS
12138 bool extraInitializersPresent = false;
12139 #endif
12140 if (constructor->is<LexicalScopeNode>()) {
12141 LexicalScopeNode* constructorScope = &constructor->as<LexicalScopeNode>();
12142
12143 MOZ_ASSERT(!constructorScope->isEmptyScope());
12144 #ifdef ENABLE_DECORATORS
12145 // With decorators enabled we expect to see |.initializers|,
12146 // and |.instanceExtraInitializers| in this scope.
12147 MOZ_ASSERT(constructorScope->scopeBindings()->length == 2);
12148 MOZ_ASSERT(GetScopeDataTrailingNames(constructorScope->scopeBindings())[0]
12149 .name() ==
12150 TaggedParserAtomIndex::WellKnown::dot_initializers_());
12151 MOZ_ASSERT(
12152 GetScopeDataTrailingNames(constructorScope->scopeBindings())[1]
12153 .name() ==
12154 TaggedParserAtomIndex::WellKnown::dot_instanceExtraInitializers_());
12155
12156 // We should only call this code if we know decorators are present, see bug
12157 // 1871147.
12158 lse.emplace(this);
12159 if (!lse->emitScope(ScopeKind::Lexical,
12160 constructorScope->scopeBindings())) {
12161 return false;
12162 }
12163
12164 // TODO: See bug 1868220 for support for static extra initializers.
12165 if (!ce.prepareForExtraInitializers(TaggedParserAtomIndex::WellKnown::
12166 dot_instanceExtraInitializers_())) {
12167 return false;
12168 }
12169
12170 if (classNode->addInitializerFunction()) {
12171 DecoratorEmitter de(this);
12172 if (!de.emitCreateAddInitializerFunction(
12173 classNode->addInitializerFunction(),
12174 TaggedParserAtomIndex::WellKnown::
12175 dot_instanceExtraInitializers_())) {
12176 // [stack] HOMEOBJ HERITAGE? ADDINIT
12177 return false;
12178 }
12179
12180 if (!emitUnpickN(isDerived ? 2 : 1)) {
12181 // [stack] ADDINIT HOMEOBJ HERITAGE?
12182 return false;
12183 }
12184
12185 extraInitializersPresent = true;
12186 }
12187 #else
12188 // The constructor scope should only contain the |.initializers| binding.
12189 MOZ_ASSERT(constructorScope->scopeBindings()->length == 1);
12190 MOZ_ASSERT(GetScopeDataTrailingNames(constructorScope->scopeBindings())[0]
12191 .name() ==
12192 TaggedParserAtomIndex::WellKnown::dot_initializers_());
12193 #endif
12194
12195 auto needsInitializer = [](ParseNode* propdef) {
12196 return NeedsFieldInitializer(propdef, false) ||
12197 NeedsAccessorInitializer(propdef, false);
12198 };
12199
12200 // As an optimization omit the |.initializers| binding when no instance
12201 // fields or private methods are present.
12202 bool needsInitializers =
12203 std::any_of(classMembers->contents().begin(),
12204 classMembers->contents().end(), needsInitializer);
12205 if (needsInitializers) {
12206 #ifndef ENABLE_DECORATORS
12207 lse.emplace(this);
12208 if (!lse->emitScope(ScopeKind::Lexical,
12209 constructorScope->scopeBindings())) {
12210 return false;
12211 }
12212 #endif
12213 // Any class with field initializers will have a constructor
12214 if (!emitCreateMemberInitializers(ce, classMembers,
12215 FieldPlacement::Instance
12216 #ifdef ENABLE_DECORATORS
12217 ,
12218 isDerived
12219 #endif
12220 )) {
12221 return false;
12222 }
12223 }
12224
12225 ctor = &constructorScope->scopeBody()->as<ClassMethod>().method();
12226 } else {
12227 // The |.initializers| binding is never emitted when in self-hosting mode.
12228 MOZ_ASSERT(emitterMode == BytecodeEmitter::SelfHosting);
12229 ctor = &constructor->as<ClassMethod>().method();
12230 }
12231
12232 bool needsHomeObject = ctor->funbox()->needsHomeObject();
12233 // HERITAGE is consumed inside emitFunction.
12234 if (nameKind == ClassNameKind::InferredName) {
12235 setFunName(ctor->funbox(), nameForAnonymousClass);
12236 }
12237 if (!emitFunction(ctor, isDerived)) {
12238 // [stack] HOMEOBJ CTOR
12239 return false;
12240 }
12241 if (lse.isSome()) {
12242 if (!lse->emitEnd()) {
12243 return false;
12244 }
12245 lse.reset();
12246 }
12247 if (!ce.emitInitConstructor(needsHomeObject)) {
12248 // [stack] CTOR HOMEOBJ
12249 return false;
12250 }
12251
12252 if (!emitCreateFieldKeys(classMembers, FieldPlacement::Instance)) {
12253 return false;
12254 }
12255
12256 #ifdef ENABLE_DECORATORS
12257 // TODO: See Bug 1868220 for support for static extra initializers.
12258 if (!emit1(JSOp::Undefined)) {
12259 // [stack] ADDINIT? CTOR HOMEOBJ UNDEFINED
12260 return false;
12261 }
12262 if (!emitUnpickN(2)) {
12263 // [stack] ADDINIT? UNDEFINED CTOR HOMEOBJ
12264 return false;
12265 }
12266 #endif
12267
12268 if (!emitCreateMemberInitializers(ce, classMembers, FieldPlacement::Static
12269 #ifdef ENABLE_DECORATORS
12270 ,
12271 false
12272 #endif
12273 )) {
12274 return false;
12275 }
12276
12277 #ifdef ENABLE_DECORATORS
12278 if (!emitPickN(2)) {
12279 // [stack] ADDINIT? CTOR HOMEOBJ UNDEFINED
12280 return false;
12281 }
12282 if (!emitPopN(1)) {
12283 // [stack] ADDINIT? CTOR HOMEOBJ
12284 return false;
12285 }
12286 #endif
12287
12288 if (!emitCreateFieldKeys(classMembers, FieldPlacement::Static)) {
12289 return false;
12290 }
12291
12292 if (!emitPropertyList(classMembers, ce, ClassBody)) {
12293 // [stack] CTOR HOMEOBJ
12294 return false;
12295 }
12296
12297 #ifdef ENABLE_DECORATORS
12298 if (extraInitializersPresent) {
12299 if (!emitPickN(2)) {
12300 // [stack] CTOR HOMEOBJ ADDINIT
12301 return false;
12302 }
12303 if (!emitPopN(1)) {
12304 // [stack] CTOR HOMEOBJ
12305 return false;
12306 }
12307 }
12308 #endif
12309
12310 if (!ce.emitBinding()) {
12311 // [stack] CTOR
12312 return false;
12313 }
12314
12315 if (!emitInitializeStaticFields(classMembers)) {
12316 // [stack] CTOR
12317 return false;
12318 }
12319
12320 #if ENABLE_DECORATORS
12321 if (!ce.prepareForDecorators()) {
12322 // [stack] CTOR
12323 return false;
12324 }
12325 if (classNode->decorators() != nullptr) {
12326 DecoratorEmitter de(this);
12327 NameNode* className =
12328 classNode->names() ? classNode->names()->innerBinding() : nullptr;
12329 if (!de.emitApplyDecoratorsToClassDefinition(className,
12330 classNode->decorators())) {
12331 // [stack] CTOR
12332 return false;
12333 }
12334 }
12335 #endif
12336
12337 if (!ce.emitEnd(kind)) {
12338 // [stack] # class declaration
12339 // [stack]
12340 // [stack] # class expression
12341 // [stack] CTOR
12342 return false;
12343 }
12344
12345 return true;
12346 }
12347
12348 bool BytecodeEmitter::emitExportDefault(BinaryNode* exportNode) {
12349 MOZ_ASSERT(exportNode->isKind(ParseNodeKind::ExportDefaultStmt));
12350
12351 ParseNode* valueNode = exportNode->left();
12352 if (valueNode->isDirectRHSAnonFunction()) {
12353 MOZ_ASSERT(exportNode->right());
12354
12355 if (!emitAnonymousFunctionWithName(
12356 valueNode, TaggedParserAtomIndex::WellKnown::default_())) {
12357 return false;
12358 }
12359 } else {
12360 if (!emitTree(valueNode)) {
12361 return false;
12362 }
12363 }
12364
12365 if (ParseNode* binding = exportNode->right()) {
12366 if (!emitLexicalInitialization(&binding->as<NameNode>())) {
12367 return false;
12368 }
12369
12370 if (!emit1(JSOp::Pop)) {
12371 return false;
12372 }
12373 }
12374
12375 return true;
12376 }
12377
12378 bool BytecodeEmitter::emitTree(
12379 ParseNode* pn, ValueUsage valueUsage /* = ValueUsage::WantValue */,
12380 EmitLineNumberNote emitLineNote /* = EMIT_LINENOTE */) {
12381 AutoCheckRecursionLimit recursion(fc);
12382 if (!recursion.check(fc)) {
12383 return false;
12384 }
12385
12386 /* Emit notes to tell the current bytecode's source line number.
12387 However, a couple trees require special treatment; see the
12388 relevant emitter functions for details. */
12389 if (emitLineNote == EMIT_LINENOTE &&
12390 !ParseNodeRequiresSpecialLineNumberNotes(pn)) {
12391 if (!updateLineNumberNotes(pn->pn_pos.begin)) {
12392 return false;
12393 }
12394 }
12395
12396 switch (pn->getKind()) {
12397 case ParseNodeKind::Function:
12398 if (!emitFunction(&pn->as<FunctionNode>())) {
12399 return false;
12400 }
12401 break;
12402
12403 case ParseNodeKind::ParamsBody:
12404 MOZ_ASSERT_UNREACHABLE(
12405 "ParamsBody should be handled in emitFunctionScript.");
12406 break;
12407
12408 case ParseNodeKind::IfStmt:
12409 if (!emitIf(&pn->as<TernaryNode>())) {
12410 return false;
12411 }
12412 break;
12413
12414 case ParseNodeKind::SwitchStmt:
12415 if (!emitSwitch(&pn->as<SwitchStatement>())) {
12416 return false;
12417 }
12418 break;
12419
12420 case ParseNodeKind::WhileStmt:
12421 if (!emitWhile(&pn->as<BinaryNode>())) {
12422 return false;
12423 }
12424 break;
12425
12426 case ParseNodeKind::DoWhileStmt:
12427 if (!emitDo(&pn->as<BinaryNode>())) {
12428 return false;
12429 }
12430 break;
12431
12432 case ParseNodeKind::ForStmt:
12433 if (!emitFor(&pn->as<ForNode>())) {
12434 return false;
12435 }
12436 break;
12437
12438 case ParseNodeKind::BreakStmt:
12439 // Ensure that the column of the 'break' is set properly.
12440 if (!updateSourceCoordNotes(pn->pn_pos.begin)) {
12441 return false;
12442 }
12443 if (!markStepBreakpoint()) {
12444 return false;
12445 }
12446
12447 if (!emitBreak(pn->as<BreakStatement>().label())) {
12448 return false;
12449 }
12450 break;
12451
12452 case ParseNodeKind::ContinueStmt:
12453 // Ensure that the column of the 'continue' is set properly.
12454 if (!updateSourceCoordNotes(pn->pn_pos.begin)) {
12455 return false;
12456 }
12457 if (!markStepBreakpoint()) {
12458 return false;
12459 }
12460
12461 if (!emitContinue(pn->as<ContinueStatement>().label())) {
12462 return false;
12463 }
12464 break;
12465
12466 case ParseNodeKind::WithStmt:
12467 if (!emitWith(&pn->as<BinaryNode>())) {
12468 return false;
12469 }
12470 break;
12471
12472 case ParseNodeKind::TryStmt:
12473 if (!emitTry(&pn->as<TryNode>())) {
12474 return false;
12475 }
12476 break;
12477
12478 case ParseNodeKind::Catch:
12479 if (!emitCatch(&pn->as<BinaryNode>())) {
12480 return false;
12481 }
12482 break;
12483
12484 case ParseNodeKind::VarStmt:
12485 if (!emitDeclarationList(&pn->as<ListNode>())) {
12486 return false;
12487 }
12488 break;
12489
12490 case ParseNodeKind::ReturnStmt:
12491 if (!emitReturn(&pn->as<UnaryNode>())) {
12492 return false;
12493 }
12494 break;
12495
12496 case ParseNodeKind::YieldStarExpr:
12497 if (!emitYieldStar(pn->as<UnaryNode>().kid())) {
12498 return false;
12499 }
12500 break;
12501
12502 case ParseNodeKind::Generator:
12503 if (!emit1(JSOp::Generator)) {
12504 return false;
12505 }
12506 break;
12507
12508 case ParseNodeKind::InitialYield:
12509 if (!emitInitialYield(&pn->as<UnaryNode>())) {
12510 return false;
12511 }
12512 break;
12513
12514 case ParseNodeKind::YieldExpr:
12515 if (!emitYield(&pn->as<UnaryNode>())) {
12516 return false;
12517 }
12518 break;
12519
12520 case ParseNodeKind::AwaitExpr:
12521 if (!emitAwaitInInnermostScope(&pn->as<UnaryNode>())) {
12522 return false;
12523 }
12524 break;
12525
12526 case ParseNodeKind::StatementList:
12527 if (!emitStatementList(&pn->as<ListNode>())) {
12528 return false;
12529 }
12530 break;
12531
12532 case ParseNodeKind::EmptyStmt:
12533 break;
12534
12535 case ParseNodeKind::ExpressionStmt:
12536 if (!emitExpressionStatement(&pn->as<UnaryNode>())) {
12537 return false;
12538 }
12539 break;
12540
12541 case ParseNodeKind::LabelStmt:
12542 if (!emitLabeledStatement(&pn->as<LabeledStatement>())) {
12543 return false;
12544 }
12545 break;
12546
12547 case ParseNodeKind::CommaExpr:
12548 if (!emitSequenceExpr(&pn->as<ListNode>(), valueUsage)) {
12549 return false;
12550 }
12551 break;
12552
12553 case ParseNodeKind::InitExpr:
12554 case ParseNodeKind::AssignExpr:
12555 case ParseNodeKind::AddAssignExpr:
12556 case ParseNodeKind::SubAssignExpr:
12557 case ParseNodeKind::BitOrAssignExpr:
12558 case ParseNodeKind::BitXorAssignExpr:
12559 case ParseNodeKind::BitAndAssignExpr:
12560 case ParseNodeKind::LshAssignExpr:
12561 case ParseNodeKind::RshAssignExpr:
12562 case ParseNodeKind::UrshAssignExpr:
12563 case ParseNodeKind::MulAssignExpr:
12564 case ParseNodeKind::DivAssignExpr:
12565 case ParseNodeKind::ModAssignExpr:
12566 case ParseNodeKind::PowAssignExpr: {
12567 BinaryNode* assignNode = &pn->as<BinaryNode>();
12568 if (!emitAssignmentOrInit(assignNode->getKind(), assignNode->left(),
12569 assignNode->right())) {
12570 return false;
12571 }
12572 break;
12573 }
12574
12575 case ParseNodeKind::CoalesceAssignExpr:
12576 case ParseNodeKind::OrAssignExpr:
12577 case ParseNodeKind::AndAssignExpr:
12578 if (!emitShortCircuitAssignment(&pn->as<AssignmentNode>())) {
12579 return false;
12580 }
12581 break;
12582
12583 case ParseNodeKind::ConditionalExpr:
12584 if (!emitConditionalExpression(pn->as<ConditionalExpression>(),
12585 valueUsage)) {
12586 return false;
12587 }
12588 break;
12589
12590 case ParseNodeKind::OrExpr:
12591 case ParseNodeKind::CoalesceExpr:
12592 case ParseNodeKind::AndExpr:
12593 if (!emitShortCircuit(&pn->as<ListNode>(), valueUsage)) {
12594 return false;
12595 }
12596 break;
12597
12598 case ParseNodeKind::StrictEqExpr:
12599 case ParseNodeKind::EqExpr:
12600 case ParseNodeKind::StrictNeExpr:
12601 case ParseNodeKind::NeExpr: {
12602 bool emitted;
12603 if (!tryEmitTypeofEq(&pn->as<ListNode>(), &emitted)) {
12604 return false;
12605 }
12606 if (emitted) {
12607 return true;
12608 }
12609 }
12610 [[fallthrough]];
12611
12612 case ParseNodeKind::AddExpr:
12613 case ParseNodeKind::SubExpr:
12614 case ParseNodeKind::BitOrExpr:
12615 case ParseNodeKind::BitXorExpr:
12616 case ParseNodeKind::BitAndExpr:
12617 case ParseNodeKind::LtExpr:
12618 case ParseNodeKind::LeExpr:
12619 case ParseNodeKind::GtExpr:
12620 case ParseNodeKind::GeExpr:
12621 case ParseNodeKind::InExpr:
12622 case ParseNodeKind::InstanceOfExpr:
12623 case ParseNodeKind::LshExpr:
12624 case ParseNodeKind::RshExpr:
12625 case ParseNodeKind::UrshExpr:
12626 case ParseNodeKind::MulExpr:
12627 case ParseNodeKind::DivExpr:
12628 case ParseNodeKind::ModExpr:
12629 if (!emitLeftAssociative(&pn->as<ListNode>())) {
12630 return false;
12631 }
12632 break;
12633
12634 case ParseNodeKind::PrivateInExpr:
12635 if (!emitPrivateInExpr(&pn->as<ListNode>())) {
12636 return false;
12637 }
12638 break;
12639
12640 case ParseNodeKind::PowExpr:
12641 if (!emitRightAssociative(&pn->as<ListNode>())) {
12642 return false;
12643 }
12644 break;
12645
12646 case ParseNodeKind::TypeOfNameExpr:
12647 if (!emitTypeof(&pn->as<UnaryNode>(), JSOp::Typeof)) {
12648 return false;
12649 }
12650 break;
12651
12652 case ParseNodeKind::TypeOfExpr:
12653 if (!emitTypeof(&pn->as<UnaryNode>(), JSOp::TypeofExpr)) {
12654 return false;
12655 }
12656 break;
12657
12658 case ParseNodeKind::ThrowStmt:
12659 if (!updateSourceCoordNotes(pn->pn_pos.begin)) {
12660 return false;
12661 }
12662 if (!markStepBreakpoint()) {
12663 return false;
12664 }
12665 [[fallthrough]];
12666 case ParseNodeKind::VoidExpr:
12667 case ParseNodeKind::NotExpr:
12668 case ParseNodeKind::BitNotExpr:
12669 case ParseNodeKind::PosExpr:
12670 case ParseNodeKind::NegExpr:
12671 if (!emitUnary(&pn->as<UnaryNode>())) {
12672 return false;
12673 }
12674 break;
12675
12676 case ParseNodeKind::PreIncrementExpr:
12677 case ParseNodeKind::PreDecrementExpr:
12678 case ParseNodeKind::PostIncrementExpr:
12679 case ParseNodeKind::PostDecrementExpr:
12680 if (!emitIncOrDec(&pn->as<UnaryNode>(), valueUsage)) {
12681 return false;
12682 }
12683 break;
12684
12685 case ParseNodeKind::DeleteNameExpr:
12686 if (!emitDeleteName(&pn->as<UnaryNode>())) {
12687 return false;
12688 }
12689 break;
12690
12691 case ParseNodeKind::DeletePropExpr:
12692 if (!emitDeleteProperty(&pn->as<UnaryNode>())) {
12693 return false;
12694 }
12695 break;
12696
12697 case ParseNodeKind::DeleteElemExpr:
12698 if (!emitDeleteElement(&pn->as<UnaryNode>())) {
12699 return false;
12700 }
12701 break;
12702
12703 case ParseNodeKind::DeleteExpr:
12704 if (!emitDeleteExpression(&pn->as<UnaryNode>())) {
12705 return false;
12706 }
12707 break;
12708
12709 case ParseNodeKind::DeleteOptionalChainExpr:
12710 if (!emitDeleteOptionalChain(&pn->as<UnaryNode>())) {
12711 return false;
12712 }
12713 break;
12714
12715 case ParseNodeKind::OptionalChain:
12716 if (!emitOptionalChain(&pn->as<UnaryNode>(), valueUsage)) {
12717 return false;
12718 }
12719 break;
12720
12721 case ParseNodeKind::DotExpr: {
12722 PropertyAccess* prop = &pn->as<PropertyAccess>();
12723 bool isSuper = prop->isSuper();
12724 PropOpEmitter poe(this, PropOpEmitter::Kind::Get,
12725 isSuper ? PropOpEmitter::ObjKind::Super
12726 : PropOpEmitter::ObjKind::Other);
12727 if (!poe.prepareForObj()) {
12728 return false;
12729 }
12730 if (isSuper) {
12731 UnaryNode* base = &prop->expression().as<UnaryNode>();
12732 if (!emitGetThisForSuperBase(base)) {
12733 // [stack] THIS
12734 return false;
12735 }
12736 } else {
12737 if (!emitPropLHS(prop)) {
12738 // [stack] OBJ
12739 return false;
12740 }
12741 }
12742 if (!poe.emitGet(prop->key().atom())) {
12743 // [stack] PROP
12744 return false;
12745 }
12746 break;
12747 }
12748
12749 case ParseNodeKind::ArgumentsLength: {
12750 if (sc->isFunctionBox() &&
12751 sc->asFunctionBox()->isEligibleForArgumentsLength() &&
12752 !sc->asFunctionBox()->needsArgsObj()) {
12753 if (!emit1(JSOp::ArgumentsLength)) {
12754 return false;
12755 }
12756 } else {
12757 PropOpEmitter poe(this, PropOpEmitter::Kind::Get,
12758 PropOpEmitter::ObjKind::Other);
12759 if (!poe.prepareForObj()) {
12760 return false;
12761 }
12762
12763 NameOpEmitter noe(this, TaggedParserAtomIndex::WellKnown::arguments(),
12764 NameOpEmitter::Kind::Get);
12765 if (!noe.emitGet()) {
12766 return false;
12767 }
12768 if (!poe.emitGet(TaggedParserAtomIndex::WellKnown::length())) {
12769 return false;
12770 }
12771 }
12772 break;
12773 }
12774
12775 case ParseNodeKind::ElemExpr: {
12776 PropertyByValue* elem = &pn->as<PropertyByValue>();
12777 bool isSuper = elem->isSuper();
12778 MOZ_ASSERT(!elem->key().isKind(ParseNodeKind::PrivateName));
12779 ElemOpEmitter eoe(this, ElemOpEmitter::Kind::Get,
12780 isSuper ? ElemOpEmitter::ObjKind::Super
12781 : ElemOpEmitter::ObjKind::Other);
12782 if (!emitElemObjAndKey(elem, eoe)) {
12783 // [stack] # if Super
12784 // [stack] THIS KEY
12785 // [stack] # otherwise
12786 // [stack] OBJ KEY
12787 return false;
12788 }
12789 if (!eoe.emitGet()) {
12790 // [stack] ELEM
12791 return false;
12792 }
12793
12794 break;
12795 }
12796
12797 case ParseNodeKind::PrivateMemberExpr: {
12798 PrivateMemberAccess* privateExpr = &pn->as<PrivateMemberAccess>();
12799 PrivateOpEmitter xoe(this, PrivateOpEmitter::Kind::Get,
12800 privateExpr->privateName().name());
12801 if (!emitTree(&privateExpr->expression())) {
12802 // [stack] OBJ
12803 return false;
12804 }
12805 if (!xoe.emitReference()) {
12806 // [stack] OBJ NAME
12807 return false;
12808 }
12809 if (!xoe.emitGet()) {
12810 // [stack] VALUE
12811 return false;
12812 }
12813
12814 break;
12815 }
12816
12817 case ParseNodeKind::NewExpr:
12818 case ParseNodeKind::TaggedTemplateExpr:
12819 case ParseNodeKind::CallExpr:
12820 case ParseNodeKind::SuperCallExpr:
12821 if (!emitCallOrNew(&pn->as<CallNode>(), valueUsage)) {
12822 return false;
12823 }
12824 break;
12825
12826 case ParseNodeKind::LexicalScope:
12827 if (!emitLexicalScope(&pn->as<LexicalScopeNode>())) {
12828 return false;
12829 }
12830 break;
12831
12832 case ParseNodeKind::ConstDecl:
12833 case ParseNodeKind::LetDecl:
12834 if (!emitDeclarationList(&pn->as<ListNode>())) {
12835 return false;
12836 }
12837 break;
12838 #ifdef ENABLE_EXPLICIT_RESOURCE_MANAGEMENT
12839 case ParseNodeKind::AwaitUsingDecl:
12840 case ParseNodeKind::UsingDecl:
12841 if (!emitDeclarationList(&pn->as<ListNode>())) {
12842 return false;
12843 }
12844 break;
12845 #endif
12846
12847 case ParseNodeKind::ImportDecl:
12848 MOZ_ASSERT(sc->isModuleContext());
12849 break;
12850
12851 case ParseNodeKind::ExportStmt: {
12852 MOZ_ASSERT(sc->isModuleContext());
12853 UnaryNode* node = &pn->as<UnaryNode>();
12854 ParseNode* decl = node->kid();
12855 if (decl->getKind() != ParseNodeKind::ExportSpecList) {
12856 if (!emitTree(decl)) {
12857 return false;
12858 }
12859 }
12860 break;
12861 }
12862
12863 case ParseNodeKind::ExportDefaultStmt:
12864 MOZ_ASSERT(sc->isModuleContext());
12865 if (!emitExportDefault(&pn->as<BinaryNode>())) {
12866 return false;
12867 }
12868 break;
12869
12870 case ParseNodeKind::ExportFromStmt:
12871 MOZ_ASSERT(sc->isModuleContext());
12872 break;
12873
12874 case ParseNodeKind::CallSiteObj:
12875 if (!emitCallSiteObject(&pn->as<CallSiteNode>())) {
12876 return false;
12877 }
12878 break;
12879
12880 case ParseNodeKind::ArrayExpr:
12881 if (!emitArrayLiteral(&pn->as<ListNode>())) {
12882 return false;
12883 }
12884 break;
12885
12886 case ParseNodeKind::ObjectExpr:
12887 if (!emitObject(&pn->as<ListNode>())) {
12888 return false;
12889 }
12890 break;
12891
12892 case ParseNodeKind::Name:
12893 if (!emitGetName(&pn->as<NameNode>())) {
12894 return false;
12895 }
12896 break;
12897
12898 case ParseNodeKind::PrivateName:
12899 if (!emitGetPrivateName(&pn->as<NameNode>())) {
12900 return false;
12901 }
12902 break;
12903
12904 case ParseNodeKind::TemplateStringListExpr:
12905 if (!emitTemplateString(&pn->as<ListNode>())) {
12906 return false;
12907 }
12908 break;
12909
12910 case ParseNodeKind::TemplateStringExpr:
12911 case ParseNodeKind::StringExpr:
12912 if (!emitStringOp(JSOp::String, pn->as<NameNode>().atom())) {
12913 return false;
12914 }
12915 break;
12916
12917 case ParseNodeKind::NumberExpr:
12918 if (!emitNumberOp(pn->as<NumericLiteral>().value())) {
12919 return false;
12920 }
12921 break;
12922
12923 case ParseNodeKind::BigIntExpr:
12924 if (!emitBigIntOp(&pn->as<BigIntLiteral>())) {
12925 return false;
12926 }
12927 break;
12928
12929 case ParseNodeKind::RegExpExpr: {
12930 GCThingIndex index;
12931 if (!perScriptData().gcThingList().append(&pn->as<RegExpLiteral>(),
12932 &index)) {
12933 return false;
12934 }
12935 if (!emitRegExp(index)) {
12936 return false;
12937 }
12938 break;
12939 }
12940
12941 case ParseNodeKind::TrueExpr:
12942 if (!emit1(JSOp::True)) {
12943 return false;
12944 }
12945 break;
12946 case ParseNodeKind::FalseExpr:
12947 if (!emit1(JSOp::False)) {
12948 return false;
12949 }
12950 break;
12951 case ParseNodeKind::NullExpr:
12952 if (!emit1(JSOp::Null)) {
12953 return false;
12954 }
12955 break;
12956 case ParseNodeKind::RawUndefinedExpr:
12957 if (!emit1(JSOp::Undefined)) {
12958 return false;
12959 }
12960 break;
12961
12962 case ParseNodeKind::ThisExpr:
12963 if (!emitThisLiteral(&pn->as<ThisLiteral>())) {
12964 return false;
12965 }
12966 break;
12967
12968 case ParseNodeKind::DebuggerStmt:
12969 if (!updateSourceCoordNotes(pn->pn_pos.begin)) {
12970 return false;
12971 }
12972 if (!markStepBreakpoint()) {
12973 return false;
12974 }
12975 if (!emit1(JSOp::Debugger)) {
12976 return false;
12977 }
12978 break;
12979
12980 case ParseNodeKind::ClassDecl:
12981 if (!emitClass(&pn->as<ClassNode>())) {
12982 return false;
12983 }
12984 break;
12985
12986 case ParseNodeKind::NewTargetExpr:
12987 if (!emitNewTarget(&pn->as<NewTargetNode>())) {
12988 return false;
12989 }
12990 break;
12991
12992 case ParseNodeKind::ImportMetaExpr:
12993 if (!emit1(JSOp::ImportMeta)) {
12994 return false;
12995 }
12996 break;
12997
12998 case ParseNodeKind::CallImportExpr: {
12999 BinaryNode* spec = &pn->as<BinaryNode>().right()->as<BinaryNode>();
13000
13001 if (!emitTree(spec->left())) {
13002 // [stack] specifier
13003 return false;
13004 }
13005
13006 if (!spec->right()->isKind(ParseNodeKind::PosHolder)) {
13007 // [stack] specifier options
13008 if (!emitTree(spec->right())) {
13009 return false;
13010 }
13011 } else {
13012 // [stack] specifier undefined
13013 if (!emit1(JSOp::Undefined)) {
13014 return false;
13015 }
13016 }
13017
13018 if (!emit1(JSOp::DynamicImport)) {
13019 return false;
13020 }
13021
13022 break;
13023 }
13024
13025 case ParseNodeKind::SetThis:
13026 if (!emitSetThis(&pn->as<BinaryNode>())) {
13027 return false;
13028 }
13029 break;
13030
13031 case ParseNodeKind::PropertyNameExpr:
13032 case ParseNodeKind::PosHolder:
13033 MOZ_FALLTHROUGH_ASSERT(
13034 "Should never try to emit ParseNodeKind::PosHolder or ::Property");
13035
13036 default:
13037 MOZ_ASSERT(0);
13038 }
13039
13040 return true;
13041 }
13042
13043 static bool AllocSrcNote(FrontendContext* fc, SrcNotesVector& notes,
13044 unsigned size, unsigned* index) {
13045 size_t oldLength = notes.length();
13046
13047 if (MOZ_UNLIKELY(oldLength + size > MaxSrcNotesLength)) {
13048 ReportAllocationOverflow(fc);
13049 return false;
13050 }
13051
13052 if (!notes.growByUninitialized(size)) {
13053 return false;
13054 }
13055
13056 *index = oldLength;
13057 return true;
13058 }
13059
13060 bool BytecodeEmitter::addTryNote(TryNoteKind kind, uint32_t stackDepth,
13061 BytecodeOffset start, BytecodeOffset end) {
13062 MOZ_ASSERT(!inPrologue());
13063 return bytecodeSection().tryNoteList().append(kind, stackDepth, start, end);
13064 }
13065
13066 bool BytecodeEmitter::newSrcNote(SrcNoteType type, unsigned* indexp) {
13067 SrcNotesVector& notes = bytecodeSection().notes();
13068 unsigned index;
13069
13070 /*
13071 * Compute delta from the last annotated bytecode's offset. If it's too
13072 * big to fit in sn, allocate one or more xdelta notes and reset sn.
13073 */
13074 BytecodeOffset offset = bytecodeSection().offset();
13075 ptrdiff_t delta = (offset - bytecodeSection().lastNoteOffset()).value();
13076 bytecodeSection().setLastNoteOffset(offset);
13077
13078 auto allocator = [&](unsigned size) -> SrcNote* {
13079 if (!AllocSrcNote(fc, notes, size, &index)) {
13080 return nullptr;
13081 }
13082 return &notes[index];
13083 };
13084
13085 if (!SrcNoteWriter::writeNote(type, delta, allocator)) {
13086 return false;
13087 }
13088
13089 if (indexp) {
13090 *indexp = index;
13091 }
13092
13093 if (type == SrcNoteType::NewLine || type == SrcNoteType::SetLine) {
13094 lastLineOnlySrcNoteIndex = index;
13095 } else {
13096 lastLineOnlySrcNoteIndex = LastSrcNoteIsNotLineOnly;
13097 }
13098
13099 return true;
13100 }
13101
13102 bool BytecodeEmitter::newSrcNote2(SrcNoteType type, ptrdiff_t offset,
13103 unsigned* indexp) {
13104 unsigned index;
13105 if (!newSrcNote(type, &index)) {
13106 return false;
13107 }
13108 if (!newSrcNoteOperand(offset)) {
13109 return false;
13110 }
13111 if (indexp) {
13112 *indexp = index;
13113 }
13114 return true;
13115 }
13116
13117 bool BytecodeEmitter::convertLastNewLineToNewLineColumn(
13118 JS::LimitedColumnNumberOneOrigin column) {
13119 SrcNotesVector& notes = bytecodeSection().notes();
13120 MOZ_ASSERT(lastLineOnlySrcNoteIndex == notes.length() - 1);
13121 SrcNote* sn = &notes[lastLineOnlySrcNoteIndex];
13122 MOZ_ASSERT(sn->type() == SrcNoteType::NewLine);
13123
13124 SrcNoteWriter::convertNote(sn, SrcNoteType::NewLineColumn);
13125 if (!newSrcNoteOperand(SrcNote::NewLineColumn::toOperand(column))) {
13126 return false;
13127 }
13128
13129 lastLineOnlySrcNoteIndex = LastSrcNoteIsNotLineOnly;
13130 return true;
13131 }
13132
13133 bool BytecodeEmitter::convertLastSetLineToSetLineColumn(
13134 JS::LimitedColumnNumberOneOrigin column) {
13135 SrcNotesVector& notes = bytecodeSection().notes();
13136 // The Line operand is either 1 byte or 4 bytes.
13137 MOZ_ASSERT(lastLineOnlySrcNoteIndex == notes.length() - 1 - 1 ||
13138 lastLineOnlySrcNoteIndex == notes.length() - 1 - 4);
13139 SrcNote* sn = &notes[lastLineOnlySrcNoteIndex];
13140 MOZ_ASSERT(sn->type() == SrcNoteType::SetLine);
13141
13142 SrcNoteWriter::convertNote(sn, SrcNoteType::SetLineColumn);
13143 if (!newSrcNoteOperand(SrcNote::SetLineColumn::columnToOperand(column))) {
13144 return false;
13145 }
13146
13147 lastLineOnlySrcNoteIndex = LastSrcNoteIsNotLineOnly;
13148 return true;
13149 }
13150
13151 bool BytecodeEmitter::newSrcNoteOperand(ptrdiff_t operand) {
13152 if (!SrcNote::isRepresentableOperand(operand)) {
13153 reportError(nullptr, JSMSG_NEED_DIET, "script");
13154 return false;
13155 }
13156
13157 SrcNotesVector& notes = bytecodeSection().notes();
13158
13159 auto allocator = [&](unsigned size) -> SrcNote* {
13160 unsigned index;
13161 if (!AllocSrcNote(fc, notes, size, &index)) {
13162 return nullptr;
13163 }
13164 return &notes[index];
13165 };
13166
13167 return SrcNoteWriter::writeOperand(operand, allocator);
13168 }
13169
13170 bool BytecodeEmitter::intoScriptStencil(ScriptIndex scriptIndex) {
13171 js::UniquePtr<ImmutableScriptData> immutableScriptData =
13172 createImmutableScriptData();
13173 if (!immutableScriptData) {
13174 return false;
13175 }
13176
13177 MOZ_ASSERT(outermostScope().hasNonSyntacticScopeOnChain() ==
13178 sc->hasNonSyntacticScope());
13179
13180 auto& things = perScriptData().gcThingList().objects();
13181 if (!compilationState.appendGCThings(fc, scriptIndex, things)) {
13182 return false;
13183 }
13184
13185 // Hand over the ImmutableScriptData instance generated by BCE.
13186 auto* sharedData =
13187 SharedImmutableScriptData::createWith(fc, std::move(immutableScriptData));
13188 if (!sharedData) {
13189 return false;
13190 }
13191
13192 // De-duplicate the bytecode within the runtime.
13193 if (!compilationState.sharedData.addAndShare(fc, scriptIndex, sharedData)) {
13194 return false;
13195 }
13196
13197 ScriptStencil& script = compilationState.scriptData[scriptIndex];
13198 script.setHasSharedData();
13199
13200 // Update flags specific to functions.
13201 if (sc->isFunctionBox()) {
13202 FunctionBox* funbox = sc->asFunctionBox();
13203 MOZ_ASSERT(&script == &funbox->functionStencil());
13204 funbox->copyUpdatedImmutableFlags();
13205 MOZ_ASSERT(script.isFunction());
13206 } else {
13207 ScriptStencilExtra& scriptExtra = compilationState.scriptExtra[scriptIndex];
13208 sc->copyScriptExtraFields(scriptExtra);
13209 }
13210
13211 return true;
13212 }
13213
13214 SelfHostedIter BytecodeEmitter::getSelfHostedIterFor(
13215 ParseNode* parseNode) const {
13216 if (emitterMode == BytecodeEmitter::SelfHosting &&
13217 parseNode->isKind(ParseNodeKind::CallExpr)) {
13218 auto* callee = parseNode->as<CallNode>().callee();
13219 if (callee->isName(TaggedParserAtomIndex::WellKnown::allowContentIter())) {
13220 return SelfHostedIter::AllowContent;
13221 }
13222 if (callee->isName(
13223 TaggedParserAtomIndex::WellKnown::allowContentIterWith())) {
13224 return SelfHostedIter::AllowContentWith;
13225 }
13226 if (callee->isName(
13227 TaggedParserAtomIndex::WellKnown::allowContentIterWithNext())) {
13228 return SelfHostedIter::AllowContentWithNext;
13229 }
13230 }
13231
13232 return SelfHostedIter::Deny;
13233 }
13234
13235 #if defined(DEBUG) || defined(JS_JITSPEW)
13236 void BytecodeEmitter::dumpAtom(TaggedParserAtomIndex index) const {
13237 parserAtoms().dump(index);
13238 }
13239 #endif