Debian Codegraph @

js/src/jit/BaselineCodeGen.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 #include "jit/BaselineCodeGen.h"
8
9 #include "mozilla/Casting.h"
10
11 #include "gc/GC.h"
12 #include "jit/BaselineCompileQueue.h"
13 #include "jit/BaselineCompileTask.h"
14 #include "jit/BaselineIC.h"
15 #include "jit/BaselineJIT.h"
16 #include "jit/CacheIRCompiler.h"
17 #include "jit/CacheIRGenerator.h"
18 #include "jit/CalleeToken.h"
19 #include "jit/FixedList.h"
20 #include "jit/IonOptimizationLevels.h"
21 #include "jit/JitcodeMap.h"
22 #include "jit/JitFrames.h"
23 #include "jit/JitRuntime.h"
24 #include "jit/JitSpewer.h"
25 #include "jit/Linker.h"
26 #include "jit/PerfSpewer.h"
27 #include "jit/SharedICHelpers.h"
28 #include "jit/TemplateObject.h"
29 #include "jit/TrialInlining.h"
30 #include "jit/VMFunctions.h"
31 #include "js/friend/ErrorMessages.h" // JSMSG_*
32 #include "js/UniquePtr.h"
33 #include "vm/AsyncFunction.h"
34 #include "vm/AsyncIteration.h"
35 #include "vm/BuiltinObjectKind.h"
36 #include "vm/ConstantCompareOperand.h"
37 #include "vm/EnvironmentObject.h"
38 #include "vm/FunctionFlags.h" // js::FunctionFlags
39 #include "vm/Interpreter.h"
40 #include "vm/JSFunction.h"
41 #include "vm/Logging.h"
42 #include "vm/Time.h"
43 #ifdef MOZ_VTUNE
44 # include "vtune/VTuneWrapper.h"
45 #endif
46
47 #include "debugger/DebugAPI-inl.h"
48 #include "jit/BaselineFrameInfo-inl.h"
49 #include "jit/JitHints-inl.h"
50 #include "jit/JitScript-inl.h"
51 #include "jit/MacroAssembler-inl.h"
52 #include "jit/SharedICHelpers-inl.h"
53 #include "jit/TemplateObject-inl.h"
54 #include "jit/VMFunctionList-inl.h"
55 #include "vm/Interpreter-inl.h"
56 #include "vm/JSScript-inl.h"
57
58 using namespace js;
59 using namespace js::jit;
60
61 using JS::TraceKind;
62
63 using mozilla::AssertedCast;
64 using mozilla::Maybe;
65
66 namespace js {
67
68 class PlainObject;
69
70 namespace jit {
71
72 BaselineCompilerHandler::BaselineCompilerHandler(MacroAssembler& masm,
73 TempAllocator& alloc,
74 BaselineSnapshot* snapshot)
75 : frame_(snapshot->script(), masm),
76 alloc_(alloc),
77 analysis_(alloc, snapshot->script()),
78 #ifdef DEBUG
79 masm_(masm),
80 #endif
81 script_(snapshot->script()),
82 pc_(snapshot->script()->code()),
83 globalLexicalEnvironment_(snapshot->globalLexical()),
84 globalThis_(snapshot->globalThis()),
85 icEntryIndex_(0),
86 baseWarmUpThreshold_(snapshot->baseWarmUpThreshold()),
87 compileDebugInstrumentation_(snapshot->compileDebugInstrumentation()),
88 ionCompileable_(snapshot->isIonCompileable()) {
89 }
90
91 BaselineInterpreterHandler::BaselineInterpreterHandler(MacroAssembler& masm)
92 : frame_(masm) {}
93
94 template <typename Handler>
95 template <typename... HandlerArgs>
96 BaselineCodeGen<Handler>::BaselineCodeGen(TempAllocator& alloc,
97 MacroAssembler& masmArg,
98 CompileRuntime* runtimeArg,
99 HandlerArgs&&... args)
100 : handler(masmArg, std::forward<HandlerArgs>(args)...),
101 runtime(runtimeArg),
102 masm(masmArg),
103 frame(handler.frame()) {}
104
105 BaselineCompiler::BaselineCompiler(TempAllocator& alloc,
106 CompileRuntime* runtime,
107 MacroAssembler& masm,
108 BaselineSnapshot* snapshot)
109 : BaselineCodeGen(alloc, masm, runtime,
110 /* HandlerArgs = */ alloc, snapshot) {
111 #ifdef JS_CODEGEN_NONE
112 MOZ_CRASH();
113 #endif
114 }
115
116 BaselineInterpreterGenerator::BaselineInterpreterGenerator(JSContext* cx,
117 TempAllocator& alloc,
118 MacroAssembler& masm)
119 : BaselineCodeGen(alloc, masm, CompileRuntime::get(cx->runtime())
120 /* no handlerArgs */) {}
121
122 bool BaselineCompilerHandler::init() {
123 if (!analysis_.init(alloc_)) {
124 return false;
125 }
126
127 uint32_t len = script_->length();
128
129 if (!labels_.init(alloc_, len)) {
130 return false;
131 }
132
133 for (size_t i = 0; i < len; i++) {
134 new (&labels_[i]) Label();
135 }
136
137 if (!frame_.init(alloc_)) {
138 return false;
139 }
140
141 return true;
142 }
143
144 bool BaselineCompiler::init() {
145 if (!handler.init()) {
146 return false;
147 }
148
149 return true;
150 }
151
152 bool BaselineCompilerHandler::recordCallRetAddr(RetAddrEntry::Kind kind,
153 uint32_t retOffset) {
154 uint32_t pcOffset = script_->pcToOffset(pc_);
155
156 // Entries must be sorted by pcOffset for binary search to work.
157 // See BaselineScript::retAddrEntryFromPCOffset.
158 MOZ_ASSERT_IF(!retAddrEntries_.empty(),
159 retAddrEntries_.back().pcOffset() <= pcOffset);
160
161 // Similarly, entries must be sorted by return offset and this offset must be
162 // unique. See BaselineScript::retAddrEntryFromReturnOffset.
163 MOZ_ASSERT_IF(!retAddrEntries_.empty() && !masm_.oom(),
164 retAddrEntries_.back().returnOffset().offset() < retOffset);
165
166 if (!retAddrEntries_.emplaceBack(pcOffset, kind, CodeOffset(retOffset))) {
167 return false;
168 }
169
170 return true;
171 }
172
173 bool BaselineInterpreterHandler::recordCallRetAddr(RetAddrEntry::Kind kind,
174 uint32_t retOffset) {
175 switch (kind) {
176 case RetAddrEntry::Kind::DebugPrologue:
177 MOZ_ASSERT(callVMOffsets_.debugPrologueOffset == 0,
178 "expected single DebugPrologue call");
179 callVMOffsets_.debugPrologueOffset = retOffset;
180 break;
181 case RetAddrEntry::Kind::DebugEpilogue:
182 MOZ_ASSERT(callVMOffsets_.debugEpilogueOffset == 0,
183 "expected single DebugEpilogue call");
184 callVMOffsets_.debugEpilogueOffset = retOffset;
185 break;
186 case RetAddrEntry::Kind::DebugAfterYield:
187 MOZ_ASSERT(callVMOffsets_.debugAfterYieldOffset == 0,
188 "expected single DebugAfterYield call");
189 callVMOffsets_.debugAfterYieldOffset = retOffset;
190 break;
191 default:
192 break;
193 }
194
195 return true;
196 }
197
198 bool BaselineInterpreterHandler::addDebugInstrumentationOffset(
199 CodeOffset offset) {
200 return debugInstrumentationOffsets_.append(offset.offset());
201 }
202
203 /*static*/
204 bool BaselineCompiler::PrepareToCompile(JSContext* cx, Handle<JSScript*> script,
205 bool compileDebugInstrumentation) {
206 JitSpew(JitSpew_BaselineScripts, "Baseline compiling script %s:%u:%u (%p)",
207 script->filename(), script->lineno(),
208 script->column().oneOriginValue(), script.get());
209
210 AutoKeepJitScripts keepJitScript(cx);
211 if (!script->ensureHasJitScript(cx, keepJitScript)) {
212 return false;
213 }
214
215 // When code coverage is enabled, we have to create the ScriptCounts if they
216 // do not exist.
217 if (!script->hasScriptCounts() && cx->realm()->collectCoverageForDebug()) {
218 if (!script->initScriptCounts(cx)) {
219 return false;
220 }
221 }
222
223 if (!JitOptions.disableJitHints &&
224 cx->runtime()->jitRuntime()->hasJitHintsMap()) {
225 JitHintsMap* jitHints = cx->runtime()->jitRuntime()->getJitHintsMap();
226 jitHints->setEagerBaselineHint(script);
227 }
228
229 if (!script->jitScript()->ensureHasCachedBaselineJitData(cx, script)) {
230 return false;
231 }
232
233 if (MOZ_UNLIKELY(compileDebugInstrumentation) &&
234 !cx->runtime()->jitRuntime()->ensureDebugTrapHandler(
235 cx, DebugTrapHandlerKind::Compiler)) {
236 return false;
237 }
238
239 return true;
240 }
241
242 MethodStatus BaselineCompiler::compile(JSContext* cx) {
243 Rooted<JSScript*> script(cx, handler.script());
244
245 JitSpew(JitSpew_Codegen, "# Emitting baseline code for script %s:%u:%u",
246 script->filename(), script->lineno(),
247 script->column().oneOriginValue());
248
249 AutoIncrementalTimer timer(cx->realm()->timers.baselineCompileTime);
250
251 MOZ_ASSERT(!script->hasBaselineScript());
252
253 if (!compileImpl()) {
254 ReportOutOfMemory(cx);
255 return Method_Error;
256 }
257
258 if (!finishCompile(cx)) {
259 return Method_Error;
260 }
261
262 return Method_Compiled;
263 }
264
265 MethodStatus BaselineCompiler::compileOffThread() {
266 handler.setCompilingOffThread();
267 if (!compileImpl()) {
268 return Method_Error;
269 }
270 return Method_Compiled;
271 }
272
273 bool BaselineCompiler::compileImpl() {
274 AutoCreatedBy acb(masm, "BaselineCompiler::compile");
275
276 perfSpewer_.recordOffset(masm, "Prologue");
277 if (!emitPrologue()) {
278 return false;
279 }
280
281 if (!emitBody()) {
282 return false;
283 }
284
285 perfSpewer_.recordOffset(masm, "Epilogue");
286 if (!emitEpilogue()) {
287 return false;
288 }
289
290 perfSpewer_.recordOffset(masm, "OOLPostBarrierSlot");
291 emitOutOfLinePostBarrierSlot();
292
293 return true;
294 }
295
296 bool BaselineCompiler::finishCompile(JSContext* cx) {
297 Rooted<JSScript*> script(cx, handler.script());
298 bool isSelfHostedJitCodeShared =
299 JS::Prefs::experimental_self_hosted_cache() && script->selfHosted();
300
301 UniquePtr<BaselineScript> baselineScript(
302 nullptr, JS::DeletePolicy<BaselineScript>(cx->runtime()));
303 JitCode* code = nullptr;
304 {
305 mozilla::Maybe<AutoAllocInAtomsZone> ar;
306 if (isSelfHostedJitCodeShared) {
307 ar.emplace(cx);
308 }
309
310 AutoCreatedBy acb2(masm, "exception_tail");
311 Linker linker(masm);
312 if (masm.oom()) {
313 ReportOutOfMemory(cx);
314 return false;
315 }
316
317 code = linker.newCode(cx, CodeKind::Baseline);
318 if (!code) {
319 return false;
320 }
321
322 baselineScript.reset(BaselineScript::New(
323 cx, warmUpCheckPrologueOffset_.offset(),
324 profilerEnterFrameToggleOffset_.offset(),
325 profilerExitFrameToggleOffset_.offset(),
326 handler.retAddrEntries().length(), handler.osrEntries().length(),
327 debugTrapEntries_.length(), script->resumeOffsets().size()));
328 if (!baselineScript) {
329 return false;
330 }
331
332 baselineScript->setMethod(code);
333
334 JitSpew(JitSpew_BaselineScripts,
335 "Created BaselineScript %p (raw %p) for %s:%u:%u",
336 (void*)baselineScript.get(), (void*)code->raw(), script->filename(),
337 script->lineno(), script->column().oneOriginValue());
338
339 // If profiler instrumentation is enabled, toggle instrumentation on.
340 if (cx->runtime()->jitRuntime()->isProfilerInstrumentationEnabled(
341 cx->runtime())) {
342 baselineScript->toggleProfilerInstrumentation(true);
343 }
344 }
345 baselineScript->copyRetAddrEntries(handler.retAddrEntries().begin());
346 baselineScript->copyOSREntries(handler.osrEntries().begin());
347 baselineScript->copyDebugTrapEntries(debugTrapEntries_.begin());
348
349 // Compute native resume addresses for the script's resume offsets.
350 baselineScript->computeResumeNativeOffsets(script, resumeOffsetEntries_);
351
352 if (compileDebugInstrumentation()) {
353 baselineScript->setHasDebugInstrumentation();
354 }
355
356 // If BytecodeAnalysis indicated that we should disable Ion or inlining,
357 // update the script now.
358 handler.maybeDisableIon();
359
360 // AllocSites must be allocated on the main thread.
361 handler.createAllocSites();
362
363 // Always register a native => bytecode mapping entry, since profiler can be
364 // turned on with baseline jitcode on stack, and baseline jitcode cannot be
365 // invalidated.
366 {
367 UniqueJitcodeGlobalEntry entry;
368 JitSpew(JitSpew_Profiling,
369 "Added JitcodeGlobalEntry for baseline %sscript %s:%u:%u (%p)",
370 isSelfHostedJitCodeShared ? "shared self-hosted " : "",
371 script->filename(), script->lineno(),
372 script->column().oneOriginValue(), baselineScript.get());
373
374 // Generate profiling string.
375 UniqueChars str = GeckoProfilerRuntime::allocProfileString(cx, script);
376 if (!str) {
377 return false;
378 }
379
380 if (isSelfHostedJitCodeShared) {
381 entry = MakeJitcodeGlobalEntry<SelfHostedSharedEntry>(
382 cx, code, code->raw(), code->rawEnd(), std::move(str));
383 } else {
384 entry = MakeJitcodeGlobalEntry<BaselineEntry>(
385 cx, code, code->raw(), code->rawEnd(), script, std::move(str));
386 }
387 if (!entry) {
388 return false;
389 }
390
391 JitcodeGlobalTable* globalTable =
392 cx->runtime()->jitRuntime()->getJitcodeGlobalTable();
393 if (!globalTable->addEntry(std::move(entry))) {
394 ReportOutOfMemory(cx);
395 return false;
396 }
397
398 // Mark the jitcode as having a bytecode map.
399 code->setHasBytecodeMap();
400 }
401
402 script->jitScript()->setBaselineScript(script, baselineScript.release());
403
404 perfSpewer_.saveProfile(cx, script, code);
405
406 #ifdef MOZ_VTUNE
407 vtune::MarkScript(code, script, "baseline");
408 #endif
409
410 return true;
411 }
412
413 void BaselineCompilerHandler::maybeDisableIon() {
414 if (analysis_.isIonDisabled()) {
415 script()->disableIon();
416 }
417 if (analysis_.isInliningDisabled()) {
418 script()->setUninlineable();
419 }
420 }
421
422 // On most platforms we use a dedicated bytecode PC register to avoid many
423 // dependent loads and stores for sequences of simple bytecode ops. This
424 // register must be saved/restored around VM and IC calls.
425 //
426 // On 32-bit x86 we don't have enough registers for this (because R0-R2 require
427 // 6 registers) so there we always store the pc on the frame.
428 static constexpr bool HasInterpreterPCReg() {
429 return InterpreterPCReg != InvalidReg;
430 }
431
432 static Register LoadBytecodePC(MacroAssembler& masm, Register scratch) {
433 if (HasInterpreterPCReg()) {
434 return InterpreterPCReg;
435 }
436
437 Address pcAddr(FramePointer, BaselineFrame::reverseOffsetOfInterpreterPC());
438 masm.loadPtr(pcAddr, scratch);
439 return scratch;
440 }
441
442 static void LoadInt8Operand(MacroAssembler& masm, Register dest) {
443 Register pc = LoadBytecodePC(masm, dest);
444 masm.load8SignExtend(Address(pc, sizeof(jsbytecode)), dest);
445 }
446
447 static void LoadUint8Operand(MacroAssembler& masm, Register dest) {
448 Register pc = LoadBytecodePC(masm, dest);
449 masm.load8ZeroExtend(Address(pc, sizeof(jsbytecode)), dest);
450 }
451
452 static void LoadUint16Operand(MacroAssembler& masm, Register dest) {
453 Register pc = LoadBytecodePC(masm, dest);
454 masm.load16ZeroExtend(Address(pc, sizeof(jsbytecode)), dest);
455 }
456
457 static void LoadConstantCompareOperand(MacroAssembler& masm,
458 Register constantType,
459 Register payload) {
460 // Note: In baseline interpreter on 32-bit we dont
461 // have a separate pc register see HasInterpreterPCReg()
462 // so we use the payload reg as scratch first and then rewrite the
463 // actual payload on to it after loading the type
464 Register pc = LoadBytecodePC(masm, payload);
465 masm.load8ZeroExtend(Address(pc, ConstantCompareOperand::OFFSET_OF_TYPE),
466 constantType);
467 masm.load8SignExtend(Address(pc, ConstantCompareOperand::OFFSET_OF_VALUE),
468 payload);
469 }
470
471 static void LoadInt32Operand(MacroAssembler& masm, Register dest) {
472 Register pc = LoadBytecodePC(masm, dest);
473 masm.load32(Address(pc, sizeof(jsbytecode)), dest);
474 }
475
476 static void LoadInt32OperandSignExtendToPtr(MacroAssembler& masm, Register pc,
477 Register dest) {
478 masm.load32SignExtendToPtr(Address(pc, sizeof(jsbytecode)), dest);
479 }
480
481 static void LoadUint24Operand(MacroAssembler& masm, size_t offset,
482 Register dest) {
483 // Load the opcode and operand, then left shift to discard the opcode.
484 Register pc = LoadBytecodePC(masm, dest);
485 masm.load32(Address(pc, offset), dest);
486 masm.rshift32(Imm32(8), dest);
487 }
488
489 static void LoadInlineValueOperand(MacroAssembler& masm, ValueOperand dest) {
490 // Note: the Value might be unaligned but as above we rely on all our
491 // platforms having appropriate support for unaligned accesses (except for
492 // floating point instructions on ARM).
493 Register pc = LoadBytecodePC(masm, dest.scratchReg());
494 masm.loadUnalignedValue(Address(pc, sizeof(jsbytecode)), dest);
495 }
496
497 template <typename Handler>
498 void BaselineCodeGen<Handler>::loadScript(Register dest) {
499 if (handler.realmIndependentJitcode()) {
500 masm.loadPtr(frame.addressOfInterpreterScript(), dest);
501 } else {
502 masm.movePtr(ImmGCPtr(handler.maybeScript()), dest);
503 }
504 }
505
506 template <typename Handler>
507 void BaselineCodeGen<Handler>::loadJitScript(Register dest) {
508 if (handler.realmIndependentJitcode()) {
509 loadScript(dest);
510 masm.loadPtr(Address(dest, JSScript::offsetOfWarmUpData()), dest);
511 } else {
512 masm.movePtr(ImmPtr(handler.maybeScript()->jitScript()), dest);
513 }
514 }
515
516 template <>
517 void BaselineCompilerCodeGen::saveInterpreterPCReg() {}
518
519 template <>
520 void BaselineInterpreterCodeGen::saveInterpreterPCReg() {
521 if (HasInterpreterPCReg()) {
522 masm.storePtr(InterpreterPCReg, frame.addressOfInterpreterPC());
523 }
524 }
525
526 template <>
527 void BaselineCompilerCodeGen::restoreInterpreterPCReg() {}
528
529 template <>
530 void BaselineInterpreterCodeGen::restoreInterpreterPCReg() {
531 if (HasInterpreterPCReg()) {
532 masm.loadPtr(frame.addressOfInterpreterPC(), InterpreterPCReg);
533 }
534 }
535
536 template <>
537 void BaselineCompilerCodeGen::emitInitializeLocals() {
538 // Initialize all locals to |undefined|. Lexical bindings are temporal
539 // dead zoned in bytecode.
540
541 size_t n = frame.nlocals();
542 if (n == 0) {
543 return;
544 }
545
546 // Use R0 to minimize code size. If the number of locals to push is <
547 // LOOP_UNROLL_FACTOR, then the initialization pushes are emitted directly
548 // and inline. Otherwise, they're emitted in a partially unrolled loop.
549 static const size_t LOOP_UNROLL_FACTOR = 4;
550 size_t toPushExtra = n % LOOP_UNROLL_FACTOR;
551
552 masm.moveValue(UndefinedValue(), R0);
553
554 // Handle any extra pushes left over by the optional unrolled loop below.
555 for (size_t i = 0; i < toPushExtra; i++) {
556 masm.pushValue(R0);
557 }
558
559 // Partially unrolled loop of pushes.
560 if (n >= LOOP_UNROLL_FACTOR) {
561 size_t toPush = n - toPushExtra;
562 MOZ_ASSERT(toPush % LOOP_UNROLL_FACTOR == 0);
563 MOZ_ASSERT(toPush >= LOOP_UNROLL_FACTOR);
564 masm.move32(Imm32(toPush), R1.scratchReg());
565 // Emit unrolled loop with 4 pushes per iteration.
566 Label pushLoop;
567 masm.bind(&pushLoop);
568 for (size_t i = 0; i < LOOP_UNROLL_FACTOR; i++) {
569 masm.pushValue(R0);
570 }
571 masm.branchSub32(Assembler::NonZero, Imm32(LOOP_UNROLL_FACTOR),
572 R1.scratchReg(), &pushLoop);
573 }
574 }
575
576 template <>
577 void BaselineInterpreterCodeGen::emitInitializeLocals() {
578 // Push |undefined| for all locals.
579
580 Register scratch = R0.scratchReg();
581 loadScript(scratch);
582 masm.loadPtr(Address(scratch, JSScript::offsetOfSharedData()), scratch);
583 masm.loadPtr(Address(scratch, SharedImmutableScriptData::offsetOfISD()),
584 scratch);
585 masm.load32(Address(scratch, ImmutableScriptData::offsetOfNfixed()), scratch);
586
587 Label top, done;
588 masm.branchTest32(Assembler::Zero, scratch, scratch, &done);
589 masm.bind(&top);
590 {
591 masm.pushValue(UndefinedValue());
592 masm.branchSub32(Assembler::NonZero, Imm32(1), scratch, &top);
593 }
594 masm.bind(&done);
595 }
596
597 // On input:
598 // R2.scratchReg() contains object being written to.
599 // Called with the baseline stack synced, except for R0 which is preserved.
600 // All other registers are usable as scratch.
601 // This calls:
602 // void PostWriteBarrier(JSRuntime* rt, JSObject* obj);
603 template <typename Handler>
604 void BaselineCodeGen<Handler>::emitOutOfLinePostBarrierSlot() {
605 AutoCreatedBy acb(masm,
606 "BaselineCodeGen<Handler>::emitOutOfLinePostBarrierSlot");
607
608 if (!postBarrierSlot_.used()) {
609 return;
610 }
611
612 masm.bind(&postBarrierSlot_);
613
614 #ifdef JS_USE_LINK_REGISTER
615 masm.pushReturnAddress();
616 #endif
617
618 Register objReg = R2.scratchReg();
619
620 // Check one element cache to avoid VM call.
621 Label skipBarrier;
622 auto* lastCellAddr = runtime->addressOfLastBufferedWholeCell();
623 masm.branchPtr(Assembler::Equal, AbsoluteAddress(lastCellAddr), objReg,
624 &skipBarrier);
625
626 saveInterpreterPCReg();
627
628 AllocatableGeneralRegisterSet regs(GeneralRegisterSet::All());
629 MOZ_ASSERT(!regs.has(FramePointer));
630 regs.take(R0);
631 regs.take(objReg);
632 Register scratch = regs.takeAny();
633
634 masm.pushValue(R0);
635
636 using Fn = void (*)(JSRuntime* rt, js::gc::Cell* cell);
637 masm.setupUnalignedABICall(scratch);
638 masm.movePtr(ImmPtr(runtime), scratch);
639 masm.passABIArg(scratch);
640 masm.passABIArg(objReg);
641 masm.callWithABI<Fn, PostWriteBarrier>();
642
643 restoreInterpreterPCReg();
644
645 masm.popValue(R0);
646
647 masm.bind(&skipBarrier);
648 masm.ret();
649 }
650
651 // Scan the a cache IR stub's fields and create an allocation site for any that
652 // refer to the catch-all unknown allocation site. This will be the case for
653 // stubs created when running in the interpreter. This happens on transition to
654 // baseline.
655 static bool CreateAllocSitesForCacheIRStub(JSScript* script, uint32_t pcOffset,
656 ICCacheIRStub* stub) {
657 const CacheIRStubInfo* stubInfo = stub->stubInfo();
658 uint8_t* stubData = stub->stubDataStart();
659
660 ICScript* icScript = script->jitScript()->icScript();
661
662 uint32_t field = 0;
663 size_t offset = 0;
664 while (true) {
665 StubField::Type fieldType = stubInfo->fieldType(field);
666 if (fieldType == StubField::Type::Limit) {
667 break;
668 }
669
670 if (fieldType == StubField::Type::AllocSite) {
671 gc::AllocSite* site =
672 stubInfo->getPtrStubField<ICCacheIRStub, gc::AllocSite>(stub, offset);
673 if (site->kind() == gc::AllocSite::Kind::Unknown) {
674 gc::AllocSite* newSite =
675 icScript->getOrCreateAllocSite(script, pcOffset);
676 if (!newSite) {
677 return false;
678 }
679
680 stubInfo->replaceStubRawWord(stubData, offset, uintptr_t(site),
681 uintptr_t(newSite));
682 }
683 }
684
685 field++;
686 offset += StubField::sizeInBytes(fieldType);
687 }
688
689 return true;
690 }
691
692 static void CreateAllocSitesForICChain(JSScript* script, uint32_t entryIndex) {
693 JitScript* jitScript = script->jitScript();
694 ICStub* stub = jitScript->icEntry(entryIndex).firstStub();
695 uint32_t pcOffset = jitScript->fallbackStub(entryIndex)->pcOffset();
696
697 while (!stub->isFallback()) {
698 if (!CreateAllocSitesForCacheIRStub(script, pcOffset,
699 stub->toCacheIRStub())) {
700 // This is an optimization and safe to skip if we hit OOM or per-zone
701 // limit.
702 return;
703 }
704 stub = stub->toCacheIRStub()->next();
705 }
706 }
707
708 void BaselineCompilerHandler::createAllocSites() {
709 for (uint32_t allocSiteIndex : allocSiteIndices_) {
710 CreateAllocSitesForICChain(script(), allocSiteIndex);
711 }
712
713 if (needsEnvAllocSite_) {
714 script()->jitScript()->icScript()->ensureEnvAllocSite(script());
715 }
716 }
717
718 template <>
719 bool BaselineCompilerCodeGen::emitNextIC() {
720 AutoCreatedBy acb(masm, "emitNextIC");
721
722 // Emit a call to an IC stored in JitScript. Calls to this must match the
723 // ICEntry order in JitScript: first the non-op IC entries for |this| and
724 // formal arguments, then the for-op IC entries for JOF_IC ops.
725
726 JSScript* script = handler.script();
727 uint32_t pcOffset = script->pcToOffset(handler.pc());
728
729 // We don't use every ICEntry and we can skip unreachable ops, so we have
730 // to loop until we find an ICEntry for the current pc.
731 const ICFallbackStub* stub;
732 uint32_t entryIndex;
733 do {
734 stub = script->jitScript()->fallbackStub(handler.icEntryIndex());
735 entryIndex = handler.icEntryIndex();
736 handler.moveToNextICEntry();
737 } while (stub->pcOffset() < pcOffset);
738
739 MOZ_ASSERT(stub->pcOffset() == pcOffset);
740 MOZ_ASSERT(BytecodeOpHasIC(JSOp(*handler.pc())));
741
742 if (BytecodeOpCanHaveAllocSite(JSOp(*handler.pc())) &&
743 !handler.addAllocSiteIndex(entryIndex)) {
744 return false;
745 }
746
747 // Load stub pointer into ICStubReg.
748 masm.loadPtr(frame.addressOfICScript(), ICStubReg);
749 size_t firstStubOffset = ICScript::offsetOfFirstStub(entryIndex);
750 masm.loadPtr(Address(ICStubReg, firstStubOffset), ICStubReg);
751
752 CodeOffset returnOffset;
753 EmitCallIC(masm, &returnOffset);
754
755 RetAddrEntry::Kind kind = RetAddrEntry::Kind::IC;
756 if (!handler.retAddrEntries().emplaceBack(pcOffset, kind, returnOffset)) {
757 return false;
758 }
759
760 return true;
761 }
762
763 template <>
764 bool BaselineInterpreterCodeGen::emitNextIC() {
765 saveInterpreterPCReg();
766 masm.loadPtr(frame.addressOfInterpreterICEntry(), ICStubReg);
767 masm.loadPtr(Address(ICStubReg, ICEntry::offsetOfFirstStub()), ICStubReg);
768 masm.call(Address(ICStubReg, ICStub::offsetOfStubCode()));
769 uint32_t returnOffset = masm.currentOffset();
770 restoreInterpreterPCReg();
771
772 // If this is an IC for a bytecode op where Ion may inline scripts, we need to
773 // record the return offset for Ion bailouts.
774 if (handler.currentOp()) {
775 JSOp op = *handler.currentOp();
776 MOZ_ASSERT(BytecodeOpHasIC(op));
777 if (IsIonInlinableOp(op)) {
778 if (!handler.icReturnOffsets().emplaceBack(returnOffset, op)) {
779 return false;
780 }
781 }
782 }
783
784 return true;
785 }
786
787 template <>
788 void BaselineCompilerCodeGen::computeFrameSize(Register dest) {
789 MOZ_ASSERT(!inCall_, "must not be called in the middle of a VM call");
790 masm.move32(Imm32(frame.frameSize()), dest);
791 }
792
793 template <>
794 void BaselineInterpreterCodeGen::computeFrameSize(Register dest) {
795 // dest := FramePointer - StackPointer.
796 MOZ_ASSERT(!inCall_, "must not be called in the middle of a VM call");
797 masm.mov(FramePointer, dest);
798 masm.subStackPtrFrom(dest);
799 }
800
801 template <typename Handler>
802 void BaselineCodeGen<Handler>::prepareVMCall() {
803 pushedBeforeCall_ = masm.framePushed();
804 #ifdef DEBUG
805 inCall_ = true;
806 #endif
807
808 // Ensure everything is synced.
809 frame.syncStack(0);
810 }
811
812 template <>
813 void BaselineCompilerCodeGen::storeFrameSizeAndPushDescriptor(
814 uint32_t argSize, Register scratch) {
815 #ifdef DEBUG
816 masm.store32(Imm32(frame.frameSize()), frame.addressOfDebugFrameSize());
817 #endif
818
819 masm.pushFrameDescriptor(FrameType::BaselineJS);
820 }
821
822 template <>
823 void BaselineInterpreterCodeGen::storeFrameSizeAndPushDescriptor(
824 uint32_t argSize, Register scratch) {
825 #ifdef DEBUG
826 // Store the frame size without VMFunction arguments in debug builds.
827 // scratch := FramePointer - StackPointer - argSize.
828 masm.mov(FramePointer, scratch);
829 masm.subStackPtrFrom(scratch);
830 masm.sub32(Imm32(argSize), scratch);
831 masm.store32(scratch, frame.addressOfDebugFrameSize());
832 #endif
833
834 masm.pushFrameDescriptor(FrameType::BaselineJS);
835 }
836
837 static uint32_t GetVMFunctionArgSize(const VMFunctionData& fun) {
838 return fun.explicitStackSlots() * sizeof(void*);
839 }
840
841 template <typename Handler>
842 bool BaselineCodeGen<Handler>::callVMInternal(VMFunctionId id,
843 RetAddrEntry::Kind kind,
844 CallVMPhase phase) {
845 #ifdef DEBUG
846 // Assert prepareVMCall() has been called.
847 MOZ_ASSERT(inCall_);
848 inCall_ = false;
849 #endif
850
851 TrampolinePtr code = runtime->jitRuntime()->getVMWrapper(id);
852 const VMFunctionData& fun = GetVMFunction(id);
853
854 uint32_t argSize = GetVMFunctionArgSize(fun);
855
856 // Assert all arguments were pushed.
857 MOZ_ASSERT(masm.framePushed() - pushedBeforeCall_ == argSize);
858
859 saveInterpreterPCReg();
860
861 if (phase == CallVMPhase::AfterPushingLocals) {
862 storeFrameSizeAndPushDescriptor(argSize, R0.scratchReg());
863 } else {
864 MOZ_ASSERT(phase == CallVMPhase::BeforePushingLocals);
865 #ifdef DEBUG
866 uint32_t frameBaseSize = BaselineFrame::frameSizeForNumValueSlots(0);
867 masm.store32(Imm32(frameBaseSize), frame.addressOfDebugFrameSize());
868 #endif
869 masm.pushFrameDescriptor(FrameType::BaselineJS);
870 }
871 // Perform the call.
872 masm.call(code);
873 uint32_t callOffset = masm.currentOffset();
874
875 // Pop arguments from framePushed.
876 masm.implicitPop(argSize);
877
878 restoreInterpreterPCReg();
879
880 return handler.recordCallRetAddr(kind, callOffset);
881 }
882
883 template <typename Handler>
884 template <typename Fn, Fn fn>
885 bool BaselineCodeGen<Handler>::callVM(RetAddrEntry::Kind kind,
886 CallVMPhase phase) {
887 VMFunctionId fnId = VMFunctionToId<Fn, fn>::id;
888 return callVMInternal(fnId, kind, phase);
889 }
890
891 template <typename Handler>
892 bool BaselineCodeGen<Handler>::emitStackCheck() {
893 Label skipCall;
894 if (handler.mustIncludeSlotsInStackCheck()) {
895 // Subtract the size of script->nslots() first.
896 Register scratch = R1.scratchReg();
897 masm.moveStackPtrTo(scratch);
898 subtractScriptSlotsSize(scratch, R2.scratchReg());
899 masm.branchPtr(Assembler::BelowOrEqual,
900 AbsoluteAddress(runtime->addressOfJitStackLimit()), scratch,
901 &skipCall);
902 } else {
903 masm.branchStackPtrRhs(Assembler::BelowOrEqual,
904 AbsoluteAddress(runtime->addressOfJitStackLimit()),
905 &skipCall);
906 }
907
908 prepareVMCall();
909 masm.loadBaselineFramePtr(FramePointer, R1.scratchReg());
910 pushArg(R1.scratchReg());
911
912 const CallVMPhase phase = CallVMPhase::BeforePushingLocals;
913 const RetAddrEntry::Kind kind = RetAddrEntry::Kind::StackCheck;
914
915 using Fn = bool (*)(JSContext*, BaselineFrame*);
916 if (!callVM<Fn, CheckOverRecursedBaseline>(kind, phase)) {
917 return false;
918 }
919
920 masm.bind(&skipCall);
921 return true;
922 }
923
924 static void EmitCallFrameIsDebuggeeCheck(MacroAssembler& masm) {
925 using Fn = void (*)(BaselineFrame* frame);
926 masm.setupUnalignedABICall(R0.scratchReg());
927 masm.loadBaselineFramePtr(FramePointer, R0.scratchReg());
928 masm.passABIArg(R0.scratchReg());
929 masm.callWithABI<Fn, FrameIsDebuggeeCheck>();
930 }
931
932 template <>
933 bool BaselineCompilerCodeGen::emitIsDebuggeeCheck() {
934 if (handler.compileDebugInstrumentation()) {
935 EmitCallFrameIsDebuggeeCheck(masm);
936 }
937 return true;
938 }
939
940 template <>
941 bool BaselineInterpreterCodeGen::emitIsDebuggeeCheck() {
942 // Use a toggled jump to call FrameIsDebuggeeCheck only if the debugger is
943 // enabled.
944 //
945 // TODO(bug 1522394): consider having a cx->realm->isDebuggee guard before the
946 // call. Consider moving the callWithABI out-of-line.
947
948 Label skipCheck;
949 CodeOffset toggleOffset = masm.toggledJump(&skipCheck);
950 {
951 saveInterpreterPCReg();
952 EmitCallFrameIsDebuggeeCheck(masm);
953 restoreInterpreterPCReg();
954 }
955 masm.bind(&skipCheck);
956 return handler.addDebugInstrumentationOffset(toggleOffset);
957 }
958
959 static void MaybeIncrementCodeCoverageCounter(MacroAssembler& masm,
960 JSScript* script,
961 jsbytecode* pc) {
962 if (!script->hasScriptCounts()) {
963 return;
964 }
965 PCCounts* counts = script->maybeGetPCCounts(pc);
966 uint64_t* counterAddr = &counts->numExec();
967 masm.inc64(AbsoluteAddress(counterAddr));
968 }
969
970 template <>
971 bool BaselineCompilerCodeGen::emitHandleCodeCoverageAtPrologue() {
972 // TSAN disapproves of accessing scriptCounts off-thread.
973 // We don't compile off-thread if the script has scriptCounts.
974 if (handler.compilingOffThread()) {
975 return true;
976 }
977
978 // If the main instruction is not a jump target, then we emit the
979 // corresponding code coverage counter.
980 JSScript* script = handler.script();
981 jsbytecode* main = script->main();
982 if (!BytecodeIsJumpTarget(JSOp(*main))) {
983 MaybeIncrementCodeCoverageCounter(masm, script, main);
984 }
985 return true;
986 }
987
988 template <>
989 bool BaselineInterpreterCodeGen::emitHandleCodeCoverageAtPrologue() {
990 Label skipCoverage;
991 CodeOffset toggleOffset = masm.toggledJump(&skipCoverage);
992 masm.call(handler.codeCoverageAtPrologueLabel());
993 masm.bind(&skipCoverage);
994 return handler.codeCoverageOffsets().append(toggleOffset.offset());
995 }
996
997 template <>
998 void BaselineCompilerCodeGen::subtractScriptSlotsSize(Register reg,
999 Register scratch) {
1000 uint32_t slotsSize = handler.script()->nslots() * sizeof(Value);
1001 masm.subPtr(Imm32(slotsSize), reg);
1002 }
1003
1004 template <>
1005 void BaselineInterpreterCodeGen::subtractScriptSlotsSize(Register reg,
1006 Register scratch) {
1007 // reg = reg - script->nslots() * sizeof(Value)
1008 MOZ_ASSERT(reg != scratch);
1009 loadScript(scratch);
1010 masm.loadPtr(Address(scratch, JSScript::offsetOfSharedData()), scratch);
1011 masm.loadPtr(Address(scratch, SharedImmutableScriptData::offsetOfISD()),
1012 scratch);
1013 masm.load32(Address(scratch, ImmutableScriptData::offsetOfNslots()), scratch);
1014 static_assert(sizeof(Value) == 8,
1015 "shift by 3 below assumes Value is 8 bytes");
1016 masm.lshiftPtr(Imm32(3), scratch);
1017 masm.subPtr(scratch, reg);
1018 }
1019
1020 template <typename Handler>
1021 void BaselineCodeGen<Handler>::loadGlobalLexicalEnvironment(Register dest) {
1022 if (handler.realmIndependentJitcode()) {
1023 masm.loadGlobalObjectData(dest);
1024 masm.loadPtr(Address(dest, GlobalObjectData::offsetOfLexicalEnvironment()),
1025 dest);
1026 } else {
1027 MOZ_ASSERT(!handler.maybeScript()->hasNonSyntacticScope());
1028 masm.movePtr(ImmGCPtr(handler.maybeGlobalLexicalEnvironment()), dest);
1029 }
1030 }
1031
1032 template <typename Handler>
1033 void BaselineCodeGen<Handler>::pushGlobalLexicalEnvironmentValue(
1034 ValueOperand scratch) {
1035 if (handler.realmIndependentJitcode()) {
1036 loadGlobalLexicalEnvironment(scratch.scratchReg());
1037 masm.tagValue(JSVAL_TYPE_OBJECT, scratch.scratchReg(), scratch);
1038 frame.push(scratch);
1039 } else {
1040 frame.push(ObjectValue(*handler.maybeGlobalLexicalEnvironment()));
1041 }
1042 }
1043
1044 template <>
1045 void BaselineCompilerCodeGen::loadGlobalThisValue(ValueOperand dest) {
1046 JSObject* thisObj = handler.globalThis();
1047 masm.moveValue(ObjectValue(*thisObj), dest);
1048 }
1049
1050 template <>
1051 void BaselineInterpreterCodeGen::loadGlobalThisValue(ValueOperand dest) {
1052 Register scratch = dest.scratchReg();
1053 loadGlobalLexicalEnvironment(scratch);
1054 static constexpr size_t SlotOffset =
1055 GlobalLexicalEnvironmentObject::offsetOfThisValueSlot();
1056 masm.loadValue(Address(scratch, SlotOffset), dest);
1057 }
1058
1059 template <typename Handler>
1060 void BaselineCodeGen<Handler>::pushScriptArg() {
1061 if (handler.realmIndependentJitcode()) {
1062 pushArg(frame.addressOfInterpreterScript());
1063 } else {
1064 pushArg(ImmGCPtr(handler.maybeScript()));
1065 }
1066 }
1067
1068 template <>
1069 void BaselineCompilerCodeGen::pushBytecodePCArg() {
1070 pushArg(ImmPtr(handler.pc()));
1071 }
1072
1073 template <>
1074 void BaselineInterpreterCodeGen::pushBytecodePCArg() {
1075 if (HasInterpreterPCReg()) {
1076 pushArg(InterpreterPCReg);
1077 } else {
1078 pushArg(frame.addressOfInterpreterPC());
1079 }
1080 }
1081
1082 static gc::Cell* GetScriptGCThing(JSScript* script, jsbytecode* pc,
1083 ScriptGCThingType type) {
1084 switch (type) {
1085 case ScriptGCThingType::Atom:
1086 return script->getAtom(pc);
1087 case ScriptGCThingType::String:
1088 return script->getString(pc);
1089 case ScriptGCThingType::RegExp:
1090 return script->getRegExp(pc);
1091 case ScriptGCThingType::Object:
1092 return script->getObject(pc);
1093 case ScriptGCThingType::Function:
1094 return script->getFunction(pc);
1095 case ScriptGCThingType::Scope:
1096 return script->getScope(pc);
1097 case ScriptGCThingType::BigInt:
1098 return script->getBigInt(pc);
1099 }
1100 MOZ_CRASH("Unexpected GCThing type");
1101 }
1102
1103 template <typename Handler>
1104 void BaselineCodeGen<Handler>::loadScriptGCThingInternal(ScriptGCThingType type,
1105 Register dest,
1106 Register scratch) {
1107 // Load the GCCellPtr.
1108 loadScript(dest);
1109 masm.loadPtr(Address(dest, JSScript::offsetOfPrivateData()), dest);
1110 masm.loadPtr(BaseIndex(dest, scratch, ScalePointer,
1111 PrivateScriptData::offsetOfGCThings()),
1112 dest);
1113
1114 // Clear the tag bits.
1115 switch (type) {
1116 case ScriptGCThingType::Atom:
1117 case ScriptGCThingType::String:
1118 // Use xorPtr with a 32-bit immediate because it's more efficient than
1119 // andPtr on 64-bit.
1120 static_assert(uintptr_t(TraceKind::String) == 2,
1121 "Unexpected tag bits for string GCCellPtr");
1122 masm.xorPtr(Imm32(2), dest);
1123 break;
1124 case ScriptGCThingType::RegExp:
1125 case ScriptGCThingType::Object:
1126 case ScriptGCThingType::Function:
1127 // No-op because GCCellPtr tag bits are zero for objects.
1128 static_assert(uintptr_t(TraceKind::Object) == 0,
1129 "Unexpected tag bits for object GCCellPtr");
1130 break;
1131 case ScriptGCThingType::BigInt:
1132 // Use xorPtr with a 32-bit immediate because it's more efficient than
1133 // andPtr on 64-bit.
1134 static_assert(uintptr_t(TraceKind::BigInt) == 1,
1135 "Unexpected tag bits for BigInt GCCellPtr");
1136 masm.xorPtr(Imm32(1), dest);
1137 break;
1138 case ScriptGCThingType::Scope:
1139 // Use xorPtr with a 32-bit immediate because it's more efficient than
1140 // andPtr on 64-bit.
1141 static_assert(uintptr_t(TraceKind::Scope) >= JS::OutOfLineTraceKindMask,
1142 "Expected Scopes to have OutOfLineTraceKindMask tag");
1143 masm.xorPtr(Imm32(JS::OutOfLineTraceKindMask), dest);
1144 break;
1145 }
1146 }
1147
1148 template <>
1149 void BaselineCompilerCodeGen::loadScriptGCThing(ScriptGCThingType type,
1150 Register dest,
1151 Register scratch) {
1152 if (handler.realmIndependentJitcode()) {
1153 masm.move32(Imm32(GET_GCTHING_INDEX(handler.pc())), scratch);
1154 loadScriptGCThingInternal(type, dest, scratch);
1155 } else {
1156 gc::Cell* thing = GetScriptGCThing(handler.script(), handler.pc(), type);
1157 masm.movePtr(ImmGCPtr(thing), dest);
1158 }
1159 }
1160
1161 template <>
1162 void BaselineInterpreterCodeGen::loadScriptGCThing(ScriptGCThingType type,
1163 Register dest,
1164 Register scratch) {
1165 MOZ_ASSERT(dest != scratch);
1166
1167 // Load the index in |scratch|.
1168 LoadInt32Operand(masm, scratch);
1169
1170 loadScriptGCThingInternal(type, dest, scratch);
1171
1172 #ifdef DEBUG
1173 // Assert low bits are not set.
1174 Label ok;
1175 masm.branchTestPtr(Assembler::Zero, dest, Imm32(0b111), &ok);
1176 masm.assumeUnreachable("GC pointer with tag bits set");
1177 masm.bind(&ok);
1178 #endif
1179 }
1180
1181 template <typename Handler>
1182 void BaselineCodeGen<Handler>::pushScriptGCThingArg(ScriptGCThingType type,
1183 Register scratch1,
1184 Register scratch2) {
1185 if (handler.realmIndependentJitcode()) {
1186 loadScriptGCThing(type, scratch1, scratch2);
1187 pushArg(scratch1);
1188 } else {
1189 gc::Cell* thing =
1190 GetScriptGCThing(handler.maybeScript(), handler.maybePC(), type);
1191 pushArg(ImmGCPtr(thing));
1192 }
1193 }
1194
1195 template <typename Handler>
1196 void BaselineCodeGen<Handler>::pushScriptNameArg(Register scratch1,
1197 Register scratch2) {
1198 pushScriptGCThingArg(ScriptGCThingType::Atom, scratch1, scratch2);
1199 }
1200
1201 template <>
1202 void BaselineCompilerCodeGen::pushUint8BytecodeOperandArg(Register) {
1203 MOZ_ASSERT(JOF_OPTYPE(JSOp(*handler.pc())) == JOF_UINT8);
1204 pushArg(Imm32(GET_UINT8(handler.pc())));
1205 }
1206
1207 template <>
1208 void BaselineInterpreterCodeGen::pushUint8BytecodeOperandArg(Register scratch) {
1209 LoadUint8Operand(masm, scratch);
1210 pushArg(scratch);
1211 }
1212
1213 template <>
1214 void BaselineCompilerCodeGen::pushUint16BytecodeOperandArg(Register) {
1215 MOZ_ASSERT(JOF_OPTYPE(JSOp(*handler.pc())) == JOF_UINT16);
1216 pushArg(Imm32(GET_UINT16(handler.pc())));
1217 }
1218
1219 template <>
1220 void BaselineInterpreterCodeGen::pushUint16BytecodeOperandArg(
1221 Register scratch) {
1222 LoadUint16Operand(masm, scratch);
1223 pushArg(scratch);
1224 }
1225
1226 template <>
1227 void BaselineCompilerCodeGen::loadInt32LengthBytecodeOperand(Register dest) {
1228 uint32_t length = GET_UINT32(handler.pc());
1229 MOZ_ASSERT(length <= INT32_MAX,
1230 "the bytecode emitter must fail to compile code that would "
1231 "produce a length exceeding int32_t range");
1232 masm.move32(Imm32(AssertedCast<int32_t>(length)), dest);
1233 }
1234
1235 template <>
1236 void BaselineInterpreterCodeGen::loadInt32LengthBytecodeOperand(Register dest) {
1237 LoadInt32Operand(masm, dest);
1238 }
1239
1240 template <typename Handler>
1241 bool BaselineCodeGen<Handler>::emitDebugPrologue() {
1242 auto ifDebuggee = [this]() {
1243 // Load pointer to BaselineFrame in R0.
1244 masm.loadBaselineFramePtr(FramePointer, R0.scratchReg());
1245
1246 prepareVMCall();
1247 pushArg(R0.scratchReg());
1248
1249 const RetAddrEntry::Kind kind = RetAddrEntry::Kind::DebugPrologue;
1250
1251 using Fn = bool (*)(JSContext*, BaselineFrame*);
1252 if (!callVM<Fn, jit::DebugPrologue>(kind)) {
1253 return false;
1254 }
1255
1256 return true;
1257 };
1258 return emitDebugInstrumentation(ifDebuggee);
1259 }
1260
1261 template <>
1262 void BaselineCompilerCodeGen::emitInitFrameFields(Register nonFunctionEnv) {
1263 Register scratch = R0.scratchReg();
1264 Register scratch2 = R2.scratchReg();
1265 MOZ_ASSERT(nonFunctionEnv != scratch && nonFunctionEnv != scratch2);
1266
1267 uint32_t flags =
1268 handler.realmIndependentJitcode() ? BaselineFrame::REALM_INDEPENDENT : 0;
1269 masm.store32(Imm32(flags), frame.addressOfFlags());
1270
1271 if (handler.function()) {
1272 masm.loadFunctionFromCalleeToken(frame.addressOfCalleeToken(), scratch);
1273 masm.unboxObject(Address(scratch, JSFunction::offsetOfEnvironment()),
1274 scratch2);
1275 masm.storePtr(scratch2, frame.addressOfEnvironmentChain());
1276 if (handler.realmIndependentJitcode()) {
1277 masm.loadPrivate(Address(scratch, JSFunction::offsetOfJitInfoOrScript()),
1278 scratch);
1279 masm.storePtr(scratch, frame.addressOfInterpreterScript());
1280 }
1281 } else {
1282 if (handler.realmIndependentJitcode()) {
1283 masm.loadPtr(frame.addressOfCalleeToken(), scratch);
1284 masm.andPtr(Imm32(uint32_t(CalleeTokenMask)), scratch);
1285 masm.storePtr(scratch, frame.addressOfInterpreterScript());
1286 }
1287 masm.storePtr(nonFunctionEnv, frame.addressOfEnvironmentChain());
1288 }
1289
1290 // If cx->inlinedICScript contains an inlined ICScript (passed from
1291 // the caller), take that ICScript and store it in the frame, then
1292 // overwrite cx->inlinedICScript with nullptr.
1293 Label notInlined, done;
1294 masm.movePtr(ImmPtr(runtime->addressOfInlinedICScript()), scratch);
1295 Address inlinedAddr(scratch, 0);
1296 masm.branchPtr(Assembler::Equal, inlinedAddr, ImmWord(0), &notInlined);
1297 masm.loadPtr(inlinedAddr, scratch2);
1298 masm.storePtr(scratch2, frame.addressOfICScript());
1299 masm.storePtr(ImmPtr(nullptr), inlinedAddr);
1300 masm.jump(&done);
1301
1302 // Otherwise, store this script's default ICSCript in the frame.
1303 masm.bind(&notInlined);
1304 if (handler.realmIndependentJitcode()) {
1305 // When JitCode is reused in a new realm, the frames baked into
1306 // the native bytecode need to refer to the IC list for the new JitScript or
1307 // they will execute the IC scripts using the IC stub fields from the wrong
1308 // script.
1309 loadJitScript(scratch);
1310 masm.addPtr(Imm32(JitScript::offsetOfICScript()), scratch);
1311 masm.storePtr(scratch, frame.addressOfICScript());
1312 } else {
1313 masm.storePtr(ImmPtr(handler.script()->jitScript()->icScript()),
1314 frame.addressOfICScript());
1315 }
1316 masm.bind(&done);
1317 }
1318
1319 template <>
1320 void BaselineInterpreterCodeGen::emitInitFrameFields(Register nonFunctionEnv) {
1321 MOZ_ASSERT(nonFunctionEnv == R1.scratchReg(),
1322 "Don't clobber nonFunctionEnv below");
1323
1324 // If we have a dedicated PC register we use it as scratch1 to avoid a
1325 // register move below.
1326 Register scratch1 =
1327 HasInterpreterPCReg() ? InterpreterPCReg : R0.scratchReg();
1328 Register scratch2 = R2.scratchReg();
1329
1330 masm.store32(Imm32(BaselineFrame::RUNNING_IN_INTERPRETER),
1331 frame.addressOfFlags());
1332
1333 // Initialize interpreterScript.
1334 Label notFunction, done;
1335 masm.loadPtr(frame.addressOfCalleeToken(), scratch1);
1336 masm.branchTestPtr(Assembler::NonZero, scratch1, Imm32(CalleeTokenScriptBit),
1337 &notFunction);
1338 {
1339 // CalleeToken_Function or CalleeToken_FunctionConstructing.
1340 masm.andPtr(Imm32(uint32_t(CalleeTokenMask)), scratch1);
1341 masm.unboxObject(Address(scratch1, JSFunction::offsetOfEnvironment()),
1342 scratch2);
1343 masm.storePtr(scratch2, frame.addressOfEnvironmentChain());
1344 masm.loadPrivate(Address(scratch1, JSFunction::offsetOfJitInfoOrScript()),
1345 scratch1);
1346 masm.jump(&done);
1347 }
1348 masm.bind(&notFunction);
1349 {
1350 // CalleeToken_Script.
1351 masm.andPtr(Imm32(uint32_t(CalleeTokenMask)), scratch1);
1352 masm.storePtr(nonFunctionEnv, frame.addressOfEnvironmentChain());
1353 }
1354 masm.bind(&done);
1355 masm.storePtr(scratch1, frame.addressOfInterpreterScript());
1356
1357 // Initialize icScript and interpreterICEntry
1358 masm.loadJitScript(scratch1, scratch2);
1359 masm.computeEffectiveAddress(Address(scratch2, JitScript::offsetOfICScript()),
1360 scratch2);
1361 masm.storePtr(scratch2, frame.addressOfICScript());
1362 masm.computeEffectiveAddress(Address(scratch2, ICScript::offsetOfICEntries()),
1363 scratch2);
1364 masm.storePtr(scratch2, frame.addressOfInterpreterICEntry());
1365
1366 // Initialize interpreter pc.
1367 masm.loadPtr(Address(scratch1, JSScript::offsetOfSharedData()), scratch1);
1368 masm.loadPtr(Address(scratch1, SharedImmutableScriptData::offsetOfISD()),
1369 scratch1);
1370 masm.addPtr(Imm32(ImmutableScriptData::offsetOfCode()), scratch1);
1371
1372 if (HasInterpreterPCReg()) {
1373 MOZ_ASSERT(scratch1 == InterpreterPCReg,
1374 "pc must be stored in the pc register");
1375 } else {
1376 masm.storePtr(scratch1, frame.addressOfInterpreterPC());
1377 }
1378 }
1379
1380 // Assert we don't need a post write barrier to write sourceObj to a slot of
1381 // destObj. See comments in WarpBuilder::buildNamedLambdaEnv.
1382 static void AssertCanElidePostWriteBarrier(MacroAssembler& masm,
1383 Register destObj, Register sourceObj,
1384 Register temp) {
1385 #ifdef DEBUG
1386 Label ok;
1387 masm.branchPtrInNurseryChunk(Assembler::Equal, destObj, temp, &ok);
1388 masm.branchPtrInNurseryChunk(Assembler::NotEqual, sourceObj, temp, &ok);
1389 masm.assumeUnreachable("Unexpected missing post write barrier in Baseline");
1390 masm.bind(&ok);
1391 #endif
1392 }
1393
1394 template <>
1395 bool BaselineCompilerCodeGen::initEnvironmentChain() {
1396 if (!handler.function()) {
1397 return true;
1398 }
1399 if (!handler.script()->needsFunctionEnvironmentObjects()) {
1400 return true;
1401 }
1402
1403 AllocatableGeneralRegisterSet regs(GeneralRegisterSet::All());
1404 Register temp = regs.takeAny();
1405 Label done;
1406 if (!handler.realmIndependentJitcode()) {
1407 // Allocate a NamedLambdaObject and/or a CallObject. If the function needs
1408 // both, the NamedLambdaObject must enclose the CallObject. If one of the
1409 // allocations fails, we perform the whole operation in C++.
1410
1411 auto [callObjectTemplate, namedLambdaTemplate] =
1412 handler.script()->jitScript()->functionEnvironmentTemplates(
1413 handler.function());
1414 MOZ_ASSERT(namedLambdaTemplate || callObjectTemplate);
1415
1416 Register newEnv = regs.takeAny();
1417 Register enclosingEnv = regs.takeAny();
1418 Register callee = regs.takeAny();
1419 Register siteRegister;
1420
1421 Label fail;
1422 masm.loadPtr(frame.addressOfEnvironmentChain(), enclosingEnv);
1423 masm.loadFunctionFromCalleeToken(frame.addressOfCalleeToken(), callee);
1424
1425 AllocSiteInput site;
1426 if (handler.addEnvAllocSite()) {
1427 siteRegister = regs.takeAny();
1428 masm.loadPtr(frame.addressOfICScript(), temp);
1429 masm.loadPtr(Address(temp, ICScript::offsetOfEnvAllocSite()),
1430 siteRegister);
1431 site = AllocSiteInput(siteRegister);
1432 }
1433
1434 // Allocate a NamedLambdaObject if needed.
1435 if (namedLambdaTemplate) {
1436 TemplateObject templateObject(namedLambdaTemplate);
1437 masm.createGCObject(newEnv, temp, templateObject, gc::Heap::Default,
1438 &fail, true, site);
1439
1440 // Store enclosing environment.
1441 Address enclosingSlot(newEnv,
1442 NamedLambdaObject::offsetOfEnclosingEnvironment());
1443 masm.storeValue(JSVAL_TYPE_OBJECT, enclosingEnv, enclosingSlot);
1444 AssertCanElidePostWriteBarrier(masm, newEnv, enclosingEnv, temp);
1445
1446 // Store callee.
1447 Address lambdaSlot(newEnv, NamedLambdaObject::offsetOfLambdaSlot());
1448 masm.storeValue(JSVAL_TYPE_OBJECT, callee, lambdaSlot);
1449 AssertCanElidePostWriteBarrier(masm, newEnv, callee, temp);
1450
1451 if (callObjectTemplate) {
1452 masm.movePtr(newEnv, enclosingEnv);
1453 }
1454 }
1455
1456 // Allocate a CallObject if needed.
1457 if (callObjectTemplate) {
1458 TemplateObject templateObject(callObjectTemplate);
1459 masm.createGCObject(newEnv, temp, templateObject, gc::Heap::Default,
1460 &fail, true, site);
1461
1462 // Store enclosing environment.
1463 Address enclosingSlot(newEnv, CallObject::offsetOfEnclosingEnvironment());
1464 masm.storeValue(JSVAL_TYPE_OBJECT, enclosingEnv, enclosingSlot);
1465 AssertCanElidePostWriteBarrier(masm, newEnv, enclosingEnv, temp);
1466
1467 // Store callee.
1468 Address calleeSlot(newEnv, CallObject::offsetOfCallee());
1469 masm.storeValue(JSVAL_TYPE_OBJECT, callee, calleeSlot);
1470 AssertCanElidePostWriteBarrier(masm, newEnv, callee, temp);
1471 }
1472
1473 // Update the frame's environment chain and mark it initialized.
1474 masm.storePtr(newEnv, frame.addressOfEnvironmentChain());
1475 masm.or32(Imm32(BaselineFrame::HAS_INITIAL_ENV), frame.addressOfFlags());
1476 masm.jump(&done);
1477
1478 masm.bind(&fail);
1479 }
1480
1481 prepareVMCall();
1482
1483 masm.loadBaselineFramePtr(FramePointer, temp);
1484 pushArg(temp);
1485
1486 const CallVMPhase phase = CallVMPhase::BeforePushingLocals;
1487
1488 using Fn = bool (*)(JSContext*, BaselineFrame*);
1489 if (!callVMNonOp<Fn, jit::InitFunctionEnvironmentObjects>(phase)) {
1490 return false;
1491 }
1492
1493 masm.bind(&done);
1494 return true;
1495 }
1496
1497 template <>
1498 bool BaselineInterpreterCodeGen::initEnvironmentChain() {
1499 // For function scripts, call InitFunctionEnvironmentObjects if needed. For
1500 // non-function scripts this is a no-op.
1501
1502 Label done;
1503 masm.branchTestPtr(Assembler::NonZero, frame.addressOfCalleeToken(),
1504 Imm32(CalleeTokenScriptBit), &done);
1505 {
1506 auto initEnv = [this]() {
1507 // Call into the VM to create the proper environment objects.
1508 prepareVMCall();
1509
1510 masm.loadBaselineFramePtr(FramePointer, R0.scratchReg());
1511 pushArg(R0.scratchReg());
1512
1513 const CallVMPhase phase = CallVMPhase::BeforePushingLocals;
1514
1515 using Fn = bool (*)(JSContext*, BaselineFrame*);
1516 return callVMNonOp<Fn, jit::InitFunctionEnvironmentObjects>(phase);
1517 };
1518 if (!emitTestScriptFlag(
1519 JSScript::ImmutableFlags::NeedsFunctionEnvironmentObjects, true,
1520 initEnv, R2.scratchReg())) {
1521 return false;
1522 }
1523 }
1524
1525 masm.bind(&done);
1526 return true;
1527 }
1528
1529 template <typename Handler>
1530 bool BaselineCodeGen<Handler>::emitInterruptCheck() {
1531 frame.syncStack(0);
1532
1533 Label done;
1534 masm.branch32(Assembler::Equal,
1535 AbsoluteAddress(runtime->addressOfInterruptBits()), Imm32(0),
1536 &done);
1537
1538 prepareVMCall();
1539
1540 // Use a custom RetAddrEntry::Kind so DebugModeOSR can distinguish this call
1541 // from other callVMs that might happen at this pc.
1542 const RetAddrEntry::Kind kind = RetAddrEntry::Kind::InterruptCheck;
1543
1544 using Fn = bool (*)(JSContext*);
1545 if (!callVM<Fn, InterruptCheck>(kind)) {
1546 return false;
1547 }
1548
1549 masm.bind(&done);
1550 return true;
1551 }
1552
1553 template <>
1554 bool BaselineCompilerCodeGen::emitWarmUpCounterIncrement() {
1555 frame.assertSyncedStack();
1556
1557 // Record native code offset for OSR from Baseline Interpreter into Baseline
1558 // JIT code. This is right before the warm-up check in the Baseline JIT code,
1559 // to make sure we can immediately enter Ion if the script is warm enough or
1560 // if --ion-eager is used.
1561 JSScript* script = handler.script();
1562 jsbytecode* pc = handler.pc();
1563 if (JSOp(*pc) == JSOp::LoopHead) {
1564 uint32_t pcOffset = script->pcToOffset(pc);
1565 uint32_t nativeOffset = masm.currentOffset();
1566 if (!handler.osrEntries().emplaceBack(pcOffset, nativeOffset)) {
1567 return false;
1568 }
1569 }
1570
1571 // Emit no warm-up counter increments if Ion is not enabled or if the script
1572 // will never be Ion-compileable.
1573 if (!handler.maybeIonCompileable()) {
1574 return true;
1575 }
1576
1577 Register scriptReg = R2.scratchReg();
1578 Register countReg = R0.scratchReg();
1579
1580 // Load the ICScript* in scriptReg.
1581 masm.loadPtr(frame.addressOfICScript(), scriptReg);
1582
1583 // Bump warm-up counter.
1584 Address warmUpCounterAddr(scriptReg, ICScript::offsetOfWarmUpCount());
1585 masm.load32(warmUpCounterAddr, countReg);
1586 masm.add32(Imm32(1), countReg);
1587 masm.store32(countReg, warmUpCounterAddr);
1588
1589 if (!JitOptions.disableInlining) {
1590 // Consider trial inlining.
1591 // Note: unlike other warmup thresholds, where we try to enter a
1592 // higher tier whenever we are higher than a given warmup count,
1593 // trial inlining triggers once when reaching the threshold.
1594 Label noTrialInlining;
1595 masm.branch32(Assembler::NotEqual, countReg,
1596 Imm32(JitOptions.trialInliningWarmUpThreshold),
1597 &noTrialInlining);
1598 prepareVMCall();
1599
1600 masm.PushBaselineFramePtr(FramePointer, R0.scratchReg());
1601
1602 using Fn = bool (*)(JSContext*, BaselineFrame*);
1603 if (!callVMNonOp<Fn, DoTrialInlining>()) {
1604 return false;
1605 }
1606 // Reload registers potentially clobbered by the call.
1607 masm.loadPtr(frame.addressOfICScript(), scriptReg);
1608 masm.load32(warmUpCounterAddr, countReg);
1609 masm.bind(&noTrialInlining);
1610 }
1611
1612 if (JSOp(*pc) == JSOp::LoopHead) {
1613 // If this is a loop where we can't OSR (for example because it's inside a
1614 // catch or finally block), increment the warmup counter but don't attempt
1615 // OSR (Ion/Warp only compiles the try block).
1616 if (!handler.analysis().info(pc).loopHeadCanOsr) {
1617 return true;
1618 }
1619 }
1620
1621 Label done;
1622
1623 uint32_t warmUpThreshold = OptimizationInfo::warmUpThresholdForPC(
1624 script, pc, handler.baseWarmUpThreshold());
1625 masm.branch32(Assembler::LessThan, countReg, Imm32(warmUpThreshold), &done);
1626
1627 // Don't trigger Warp compilations from trial-inlined scripts.
1628 Address depthAddr(scriptReg, ICScript::offsetOfDepth());
1629 masm.branch32(Assembler::NotEqual, depthAddr, Imm32(0), &done);
1630
1631 // Load the IonScript* in scriptReg. We can load this from the ICScript*
1632 // because it must be an outer ICScript embedded in the JitScript.
1633 constexpr int32_t offset = -int32_t(JitScript::offsetOfICScript()) +
1634 int32_t(JitScript::offsetOfIonScript());
1635 masm.loadPtr(Address(scriptReg, offset), scriptReg);
1636
1637 // Do nothing if Ion is already compiling this script off-thread or if Ion has
1638 // been disabled for this script.
1639 masm.branchTestPtr(Assembler::NonZero, scriptReg, Imm32(SpecialScriptBit),
1640 &done);
1641
1642 // Try to compile and/or finish a compilation.
1643 if (JSOp(*pc) == JSOp::LoopHead) {
1644 // Try to OSR into Ion.
1645 computeFrameSize(R0.scratchReg());
1646
1647 prepareVMCall();
1648
1649 pushBytecodePCArg();
1650 pushArg(R0.scratchReg());
1651 masm.PushBaselineFramePtr(FramePointer, R0.scratchReg());
1652
1653 using Fn = bool (*)(JSContext*, BaselineFrame*, uint32_t, jsbytecode*,
1654 IonOsrTempData**);
1655 if (!callVM<Fn, IonCompileScriptForBaselineOSR>()) {
1656 return false;
1657 }
1658
1659 // The return register holds the IonOsrTempData*. Perform OSR if it's not
1660 // nullptr.
1661 static_assert(ReturnReg != OsrFrameReg,
1662 "Code below depends on osrDataReg != OsrFrameReg");
1663 Register osrDataReg = ReturnReg;
1664 masm.branchTestPtr(Assembler::Zero, osrDataReg, osrDataReg, &done);
1665
1666 // Success! Switch from Baseline JIT code to Ion JIT code.
1667
1668 // At this point, stack looks like:
1669 //
1670 // +-> [...Calling-Frame...]
1671 // | [...Actual-Args/ThisV/ArgCount/Callee...]
1672 // | [Descriptor]
1673 // | [Return-Addr]
1674 // +---[Saved-FramePtr]
1675 // [...Baseline-Frame...]
1676
1677 #ifdef DEBUG
1678 // Get a scratch register that's not osrDataReg or OsrFrameReg.
1679 AllocatableGeneralRegisterSet regs(GeneralRegisterSet::All());
1680 MOZ_ASSERT(!regs.has(FramePointer));
1681 regs.take(osrDataReg);
1682 regs.take(OsrFrameReg);
1683
1684 Register scratchReg = regs.takeAny();
1685
1686 // If profiler instrumentation is on, ensure that lastProfilingFrame is
1687 // the frame currently being OSR-ed
1688 {
1689 Label checkOk;
1690 AbsoluteAddress addressOfEnabled(
1691 runtime->geckoProfiler().addressOfEnabled());
1692 masm.branch32(Assembler::Equal, addressOfEnabled, Imm32(0), &checkOk);
1693 masm.loadPtr(AbsoluteAddress(runtime->addressOfJitActivation()),
1694 scratchReg);
1695 masm.loadPtr(
1696 Address(scratchReg, JitActivation::offsetOfLastProfilingFrame()),
1697 scratchReg);
1698
1699 // It may be the case that we entered the baseline frame with
1700 // profiling turned off on, then in a call within a loop (i.e. a
1701 // callee frame), turn on profiling, then return to this frame,
1702 // and then OSR with profiling turned on. In this case, allow for
1703 // lastProfilingFrame to be null.
1704 masm.branchPtr(Assembler::Equal, scratchReg, ImmWord(0), &checkOk);
1705
1706 masm.branchPtr(Assembler::Equal, FramePointer, scratchReg, &checkOk);
1707 masm.assumeUnreachable("Baseline OSR lastProfilingFrame mismatch.");
1708 masm.bind(&checkOk);
1709 }
1710 #endif
1711
1712 // Restore the stack pointer so that the saved frame pointer is on top of
1713 // the stack.
1714 masm.moveToStackPtr(FramePointer);
1715
1716 // Jump into Ion.
1717 masm.loadPtr(Address(osrDataReg, IonOsrTempData::offsetOfBaselineFrame()),
1718 OsrFrameReg);
1719 masm.jump(Address(osrDataReg, IonOsrTempData::offsetOfJitCode()));
1720 } else {
1721 prepareVMCall();
1722
1723 masm.PushBaselineFramePtr(FramePointer, R0.scratchReg());
1724
1725 using Fn = bool (*)(JSContext*, BaselineFrame*);
1726 if (!callVMNonOp<Fn, IonCompileScriptForBaselineAtEntry>()) {
1727 return false;
1728 }
1729 }
1730
1731 masm.bind(&done);
1732 return true;
1733 }
1734
1735 template <>
1736 bool BaselineInterpreterCodeGen::emitWarmUpCounterIncrement() {
1737 Register scriptReg = R2.scratchReg();
1738 Register countReg = R0.scratchReg();
1739
1740 // Load the JitScript* in scriptReg.
1741 loadScript(scriptReg);
1742 masm.loadJitScript(scriptReg, scriptReg);
1743
1744 // Bump warm-up counter.
1745 Address warmUpCounterAddr(scriptReg, JitScript::offsetOfWarmUpCount());
1746 masm.load32(warmUpCounterAddr, countReg);
1747 masm.add32(Imm32(1), countReg);
1748 masm.store32(countReg, warmUpCounterAddr);
1749
1750 if (JitOptions.baselineBatching) {
1751 Register scratch = R1.scratchReg();
1752 Label done, compileBatch;
1753 Address baselineScriptAddr(scriptReg, JitScript::offsetOfBaselineScript());
1754
1755 // If the script is not warm enough to compile, we're done.
1756 masm.branch32(Assembler::BelowOrEqual, countReg,
1757 Imm32(JitOptions.baselineJitWarmUpThreshold), &done);
1758
1759 // Decide what to do based on the state of the baseline script field.
1760 Label notSpecial;
1761 masm.loadPtr(baselineScriptAddr, scratch);
1762 masm.branchTestPtr(Assembler::Zero, scratch, Imm32(SpecialScriptBit),
1763 &notSpecial);
1764
1765 // The baseline script is a special tagged value: disabled, queued, or
1766 // compiling. If it's queued and the warmup count is high enough,
1767 // trigger a batch compilation with whatever is currently queued.
1768 // Otherwise, we're done.
1769 uint32_t eagerWarmUpThreshold = JitOptions.baselineJitWarmUpThreshold * 2;
1770 masm.branchPtr(Assembler::NotEqual, scratch,
1771 ImmPtr(BaselineQueuedScriptPtr), &done);
1772
1773 masm.branch32(Assembler::Below, countReg, Imm32(eagerWarmUpThreshold),
1774 &done);
1775
1776 masm.jump(&compileBatch);
1777
1778 masm.bind(&notSpecial);
1779
1780 // If we already have a valid BaselineScript, tier up now.
1781 Label notCompiled;
1782 masm.branchPtr(Assembler::BelowOrEqual, scratch,
1783 ImmPtr(BaselineCompilingScriptPtr), &notCompiled);
1784
1785 // We just need to update our frame, find the OSR address, and jump to it.
1786 saveInterpreterPCReg();
1787
1788 using Fn = uint8_t* (*)(BaselineFrame*);
1789 masm.setupUnalignedABICall(R0.scratchReg());
1790 masm.loadBaselineFramePtr(FramePointer, R0.scratchReg());
1791 masm.passABIArg(R0.scratchReg());
1792 masm.callWithABI<Fn, BaselineScript::OSREntryForFrame>();
1793
1794 // If we are a debuggee frame, and our baseline script was compiled
1795 // without debug instrumentation, and recompilation failed, we may
1796 // not have an OSR entry available.
1797 masm.branchTestPtr(Assembler::Zero, ReturnReg, ReturnReg, &done);
1798
1799 // Otherwise: OSR!
1800 masm.jump(ReturnReg);
1801
1802 masm.bind(&notCompiled);
1803
1804 // Otherwise, add this script to the queue.
1805 // First, mark the jitscript as queued.
1806 masm.storePtr(ImmPtr(BaselineQueuedScriptPtr), baselineScriptAddr);
1807
1808 Register queueReg = scratch;
1809 masm.loadBaselineCompileQueue(queueReg);
1810
1811 Address numQueuedAddr(queueReg, BaselineCompileQueue::offsetOfNumQueued());
1812 masm.load32(numQueuedAddr, countReg);
1813
1814 BaseIndex queueSlot(queueReg, countReg, ScalePointer,
1815 BaselineCompileQueue::offsetOfQueue());
1816
1817 // Store the JSScript in the compilation queue. Note that we don't need
1818 // a prebarrier here because we will always be overwriting a nullptr,
1819 // and we don't need a postbarrier because the script is always tenured.
1820 #ifdef DEBUG
1821 Label queueSlotIsEmpty;
1822 masm.branchPtr(Assembler::Equal, queueSlot, ImmWord(0), &queueSlotIsEmpty);
1823 masm.assumeUnreachable(
1824 "Overwriting non-null slot in baseline compile queue");
1825 masm.bind(&queueSlotIsEmpty);
1826 #endif
1827 loadScript(scriptReg);
1828 masm.storePtr(scriptReg, queueSlot);
1829
1830 // Update `numQueued`.
1831 masm.add32(Imm32(1), countReg);
1832 masm.store32(countReg, numQueuedAddr);
1833
1834 // If the queue is now full, trigger a batch compilation.
1835 masm.branch32(Assembler::Below, countReg,
1836 Imm32(JitOptions.baselineQueueCapacity), &done);
1837
1838 masm.bind(&compileBatch);
1839 prepareVMCall();
1840
1841 using Fn2 = bool (*)(JSContext*);
1842 if (!callVM<Fn2, DispatchOffThreadBaselineBatch>()) {
1843 return false;
1844 }
1845 masm.bind(&done);
1846 return true;
1847 }
1848
1849 // If the script is warm enough for Baseline compilation, call into the VM to
1850 // compile it.
1851 Label done;
1852 masm.branch32(Assembler::BelowOrEqual, countReg,
1853 Imm32(JitOptions.baselineJitWarmUpThreshold), &done);
1854
1855 masm.branchTestPtr(Assembler::NonZero,
1856 Address(scriptReg, JitScript::offsetOfBaselineScript()),
1857 Imm32(SpecialScriptBit), &done);
1858 {
1859 prepareVMCall();
1860
1861 masm.PushBaselineFramePtr(FramePointer, R0.scratchReg());
1862
1863 using Fn = bool (*)(JSContext*, BaselineFrame*, uint8_t**);
1864 if (!callVM<Fn, BaselineCompileFromBaselineInterpreter>()) {
1865 return false;
1866 }
1867
1868 // If the function returned nullptr we either skipped compilation or were
1869 // unable to compile the script. Continue running in the interpreter.
1870 masm.branchTestPtr(Assembler::Zero, ReturnReg, ReturnReg, &done);
1871
1872 // Success! Switch from interpreter to JIT code by jumping to the
1873 // corresponding code in the BaselineScript.
1874 //
1875 // This works because BaselineCompiler uses the same frame layout (stack is
1876 // synced at OSR points) and BaselineCompileFromBaselineInterpreter has
1877 // already cleared the RUNNING_IN_INTERPRETER flag for us.
1878 // See BaselineFrame::prepareForBaselineInterpreterToJitOSR.
1879 masm.jump(ReturnReg);
1880 }
1881
1882 masm.bind(&done);
1883 return true;
1884 }
1885
1886 bool BaselineCompiler::emitDebugTrap() {
1887 MOZ_ASSERT(compileDebugInstrumentation());
1888 MOZ_ASSERT(frame.numUnsyncedSlots() == 0);
1889
1890 JSScript* script = handler.script();
1891 bool enabled = DebugAPI::stepModeEnabled(script) ||
1892 DebugAPI::hasBreakpointsAt(script, handler.pc());
1893
1894 // Emit patchable call to debug trap handler.
1895 JitCode* handlerCode =
1896 runtime->jitRuntime()->debugTrapHandler(DebugTrapHandlerKind::Compiler);
1897 CodeOffset nativeOffset = masm.toggledCall(handlerCode, enabled);
1898
1899 uint32_t pcOffset = script->pcToOffset(handler.pc());
1900 if (!debugTrapEntries_.emplaceBack(pcOffset, nativeOffset.offset())) {
1901 return false;
1902 }
1903
1904 // Add a RetAddrEntry for the return offset -> pc mapping.
1905 return handler.recordCallRetAddr(RetAddrEntry::Kind::DebugTrap,
1906 masm.currentOffset());
1907 }
1908
1909 template <typename Handler>
1910 void BaselineCodeGen<Handler>::emitProfilerEnterFrame() {
1911 // Store stack position to lastProfilingFrame variable, guarded by a toggled
1912 // jump. Starts off initially disabled.
1913 Label noInstrument;
1914 CodeOffset toggleOffset = masm.toggledJump(&noInstrument);
1915 masm.profilerEnterFrame(FramePointer, R0.scratchReg());
1916 masm.bind(&noInstrument);
1917
1918 // Store the start offset in the appropriate location.
1919 MOZ_ASSERT(!profilerEnterFrameToggleOffset_.bound());
1920 profilerEnterFrameToggleOffset_ = toggleOffset;
1921 }
1922
1923 template <typename Handler>
1924 void BaselineCodeGen<Handler>::emitProfilerExitFrame() {
1925 // Store previous frame to lastProfilingFrame variable, guarded by a toggled
1926 // jump. Starts off initially disabled.
1927 Label noInstrument;
1928 CodeOffset toggleOffset = masm.toggledJump(&noInstrument);
1929 masm.profilerExitFrame();
1930 masm.bind(&noInstrument);
1931
1932 // Store the start offset in the appropriate location.
1933 MOZ_ASSERT(!profilerExitFrameToggleOffset_.bound());
1934 profilerExitFrameToggleOffset_ = toggleOffset;
1935 }
1936
1937 template <typename Handler>
1938 bool BaselineCodeGen<Handler>::emit_Nop() {
1939 return true;
1940 }
1941
1942 template <typename Handler>
1943 bool BaselineCodeGen<Handler>::emit_NopDestructuring() {
1944 return true;
1945 }
1946
1947 template <typename Handler>
1948 bool BaselineCodeGen<Handler>::emit_NopIsAssignOp() {
1949 return true;
1950 }
1951
1952 template <typename Handler>
1953 bool BaselineCodeGen<Handler>::emit_TryDestructuring() {
1954 return true;
1955 }
1956
1957 template <typename Handler>
1958 bool BaselineCodeGen<Handler>::emit_Pop() {
1959 frame.pop();
1960 return true;
1961 }
1962
1963 template <>
1964 bool BaselineCompilerCodeGen::emit_PopN() {
1965 frame.popn(GET_UINT16(handler.pc()));
1966 return true;
1967 }
1968
1969 template <>
1970 bool BaselineInterpreterCodeGen::emit_PopN() {
1971 LoadUint16Operand(masm, R0.scratchReg());
1972 frame.popn(R0.scratchReg());
1973 return true;
1974 }
1975
1976 template <>
1977 bool BaselineCompilerCodeGen::emit_DupAt() {
1978 frame.syncStack(0);
1979
1980 // DupAt takes a value on the stack and re-pushes it on top. It's like
1981 // GetLocal but it addresses from the top of the stack instead of from the
1982 // stack frame.
1983
1984 int depth = -(GET_UINT24(handler.pc()) + 1);
1985 masm.loadValue(frame.addressOfStackValue(depth), R0);
1986 frame.push(R0);
1987 return true;
1988 }
1989
1990 template <>
1991 bool BaselineInterpreterCodeGen::emit_DupAt() {
1992 LoadUint24Operand(masm, 0, R0.scratchReg());
1993 masm.loadValue(frame.addressOfStackValue(R0.scratchReg()), R0);
1994 frame.push(R0);
1995 return true;
1996 }
1997
1998 template <typename Handler>
1999 bool BaselineCodeGen<Handler>::emit_Dup() {
2000 // Keep top stack value in R0, sync the rest so that we can use R1. We use
2001 // separate registers because every register can be used by at most one
2002 // StackValue.
2003 frame.popRegsAndSync(1);
2004 masm.moveValue(R0, R1);
2005
2006 // inc/dec ops use Dup followed by Inc/Dec. Push R0 last to avoid a move.
2007 frame.push(R1);
2008 frame.push(R0);
2009 return true;
2010 }
2011
2012 template <typename Handler>
2013 bool BaselineCodeGen<Handler>::emit_Dup2() {
2014 frame.syncStack(0);
2015
2016 masm.loadValue(frame.addressOfStackValue(-2), R0);
2017 masm.loadValue(frame.addressOfStackValue(-1), R1);
2018
2019 frame.push(R0);
2020 frame.push(R1);
2021 return true;
2022 }
2023
2024 template <typename Handler>
2025 bool BaselineCodeGen<Handler>::emit_Swap() {
2026 // Keep top stack values in R0 and R1.
2027 frame.popRegsAndSync(2);
2028
2029 frame.push(R1);
2030 frame.push(R0);
2031 return true;
2032 }
2033
2034 template <>
2035 bool BaselineCompilerCodeGen::emit_Pick() {
2036 frame.syncStack(0);
2037
2038 // Pick takes a value on the stack and moves it to the top.
2039 // For instance, pick 2:
2040 // before: A B C D E
2041 // after : A B D E C
2042
2043 // First, move value at -(amount + 1) into R0.
2044 int32_t depth = -(GET_INT8(handler.pc()) + 1);
2045 masm.loadValue(frame.addressOfStackValue(depth), R0);
2046
2047 // Move the other values down.
2048 depth++;
2049 for (; depth < 0; depth++) {
2050 Address source = frame.addressOfStackValue(depth);
2051 Address dest = frame.addressOfStackValue(depth - 1);
2052 masm.loadValue(source, R1);
2053 masm.storeValue(R1, dest);
2054 }
2055
2056 // Push R0.
2057 frame.pop();
2058 frame.push(R0);
2059 return true;
2060 }
2061
2062 template <>
2063 bool BaselineInterpreterCodeGen::emit_Pick() {
2064 // First, move the value to move up into R0.
2065 Register scratch = R2.scratchReg();
2066 LoadUint8Operand(masm, scratch);
2067 masm.loadValue(frame.addressOfStackValue(scratch), R0);
2068
2069 // Move the other values down.
2070 Label top, done;
2071 masm.bind(&top);
2072 masm.branchSub32(Assembler::Signed, Imm32(1), scratch, &done);
2073 {
2074 masm.loadValue(frame.addressOfStackValue(scratch), R1);
2075 masm.storeValue(R1, frame.addressOfStackValue(scratch, sizeof(Value)));
2076 masm.jump(&top);
2077 }
2078
2079 masm.bind(&done);
2080
2081 // Replace value on top of the stack with R0.
2082 masm.storeValue(R0, frame.addressOfStackValue(-1));
2083 return true;
2084 }
2085
2086 template <>
2087 bool BaselineCompilerCodeGen::emit_Unpick() {
2088 frame.syncStack(0);
2089
2090 // Pick takes the top of the stack value and moves it under the nth value.
2091 // For instance, unpick 2:
2092 // before: A B C D E
2093 // after : A B E C D
2094
2095 // First, move value at -1 into R0.
2096 masm.loadValue(frame.addressOfStackValue(-1), R0);
2097
2098 MOZ_ASSERT(GET_INT8(handler.pc()) > 0,
2099 "Interpreter code assumes JSOp::Unpick operand > 0");
2100
2101 // Move the other values up.
2102 int32_t depth = -(GET_INT8(handler.pc()) + 1);
2103 for (int32_t i = -1; i > depth; i--) {
2104 Address source = frame.addressOfStackValue(i - 1);
2105 Address dest = frame.addressOfStackValue(i);
2106 masm.loadValue(source, R1);
2107 masm.storeValue(R1, dest);
2108 }
2109
2110 // Store R0 under the nth value.
2111 Address dest = frame.addressOfStackValue(depth);
2112 masm.storeValue(R0, dest);
2113 return true;
2114 }
2115
2116 template <>
2117 bool BaselineInterpreterCodeGen::emit_Unpick() {
2118 Register scratch = R2.scratchReg();
2119 LoadUint8Operand(masm, scratch);
2120
2121 // Move the top value into R0.
2122 masm.loadValue(frame.addressOfStackValue(-1), R0);
2123
2124 // Overwrite the nth stack value with R0 but first save the old value in R1.
2125 masm.loadValue(frame.addressOfStackValue(scratch), R1);
2126 masm.storeValue(R0, frame.addressOfStackValue(scratch));
2127
2128 // Now for each slot x in [n-1, 1] do the following:
2129 //
2130 // * Store the value in slot x in R0.
2131 // * Store the value in the previous slot (now in R1) in slot x.
2132 // * Move R0 to R1.
2133
2134 #ifdef DEBUG
2135 // Assert the operand > 0 so the branchSub32 below doesn't "underflow" to
2136 // negative values.
2137 {
2138 Label ok;
2139 masm.branch32(Assembler::GreaterThan, scratch, Imm32(0), &ok);
2140 masm.assumeUnreachable("JSOp::Unpick with operand <= 0?");
2141 masm.bind(&ok);
2142 }
2143 #endif
2144
2145 Label top, done;
2146 masm.bind(&top);
2147 masm.branchSub32(Assembler::Zero, Imm32(1), scratch, &done);
2148 {
2149 // Overwrite stack slot x with slot x + 1, saving the old value in R1.
2150 masm.loadValue(frame.addressOfStackValue(scratch), R0);
2151 masm.storeValue(R1, frame.addressOfStackValue(scratch));
2152 masm.moveValue(R0, R1);
2153 masm.jump(&top);
2154 }
2155
2156 // Finally, replace the value on top of the stack (slot 0) with R1. This is
2157 // the value that used to be in slot 1.
2158 masm.bind(&done);
2159 masm.storeValue(R1, frame.addressOfStackValue(-1));
2160 return true;
2161 }
2162
2163 template <>
2164 void BaselineCompilerCodeGen::emitJump() {
2165 jsbytecode* pc = handler.pc();
2166 MOZ_ASSERT(IsJumpOpcode(JSOp(*pc)));
2167 frame.assertSyncedStack();
2168
2169 jsbytecode* target = pc + GET_JUMP_OFFSET(pc);
2170 masm.jump(handler.labelOf(target));
2171 }
2172
2173 template <>
2174 void BaselineInterpreterCodeGen::emitJump() {
2175 // We have to add the current pc's jump offset to the current pc. We can use
2176 // R0 and R1 as scratch because we jump to the "next op" label so these
2177 // registers aren't in use at this point.
2178 Register scratch1 = R0.scratchReg();
2179 Register scratch2 = R1.scratchReg();
2180 Register pc = LoadBytecodePC(masm, scratch1);
2181 LoadInt32OperandSignExtendToPtr(masm, pc, scratch2);
2182 if (HasInterpreterPCReg()) {
2183 masm.addPtr(scratch2, InterpreterPCReg);
2184 } else {
2185 masm.addPtr(pc, scratch2);
2186 masm.storePtr(scratch2, frame.addressOfInterpreterPC());
2187 }
2188 masm.jump(handler.interpretOpWithPCRegLabel());
2189 }
2190
2191 template <>
2192 void BaselineCompilerCodeGen::emitTestBooleanTruthy(bool branchIfTrue,
2193 ValueOperand val) {
2194 jsbytecode* pc = handler.pc();
2195 MOZ_ASSERT(IsJumpOpcode(JSOp(*pc)));
2196 frame.assertSyncedStack();
2197
2198 jsbytecode* target = pc + GET_JUMP_OFFSET(pc);
2199 masm.branchTestBooleanTruthy(branchIfTrue, val, handler.labelOf(target));
2200 }
2201
2202 template <>
2203 void BaselineInterpreterCodeGen::emitTestBooleanTruthy(bool branchIfTrue,
2204 ValueOperand val) {
2205 Label done;
2206 masm.branchTestBooleanTruthy(!branchIfTrue, val, &done);
2207 emitJump();
2208 masm.bind(&done);
2209 }
2210
2211 template <>
2212 template <typename F1, typename F2>
2213 [[nodiscard]] bool BaselineCompilerCodeGen::emitTestScriptFlag(
2214 JSScript::ImmutableFlags flag, const F1& ifSet, const F2& ifNotSet,
2215 Register scratch) {
2216 if (handler.script()->hasFlag(flag)) {
2217 return ifSet();
2218 }
2219 return ifNotSet();
2220 }
2221
2222 template <>
2223 template <typename F1, typename F2>
2224 [[nodiscard]] bool BaselineInterpreterCodeGen::emitTestScriptFlag(
2225 JSScript::ImmutableFlags flag, const F1& ifSet, const F2& ifNotSet,
2226 Register scratch) {
2227 Label flagNotSet, done;
2228 loadScript(scratch);
2229 masm.branchTest32(Assembler::Zero,
2230 Address(scratch, JSScript::offsetOfImmutableFlags()),
2231 Imm32(uint32_t(flag)), &flagNotSet);
2232 {
2233 if (!ifSet()) {
2234 return false;
2235 }
2236 masm.jump(&done);
2237 }
2238 masm.bind(&flagNotSet);
2239 {
2240 if (!ifNotSet()) {
2241 return false;
2242 }
2243 }
2244
2245 masm.bind(&done);
2246 return true;
2247 }
2248
2249 template <>
2250 template <typename F>
2251 [[nodiscard]] bool BaselineCompilerCodeGen::emitTestScriptFlag(
2252 JSScript::ImmutableFlags flag, bool value, const F& emit,
2253 Register scratch) {
2254 if (handler.script()->hasFlag(flag) == value) {
2255 return emit();
2256 }
2257 return true;
2258 }
2259
2260 template <>
2261 template <typename F>
2262 [[nodiscard]] bool BaselineCompilerCodeGen::emitTestScriptFlag(
2263 JSScript::MutableFlags flag, bool value, const F& emit, Register scratch) {
2264 if (handler.script()->hasFlag(flag) == value) {
2265 return emit();
2266 }
2267 return true;
2268 }
2269
2270 template <>
2271 template <typename F>
2272 [[nodiscard]] bool BaselineInterpreterCodeGen::emitTestScriptFlag(
2273 JSScript::ImmutableFlags flag, bool value, const F& emit,
2274 Register scratch) {
2275 Label done;
2276 loadScript(scratch);
2277 masm.branchTest32(value ? Assembler::Zero : Assembler::NonZero,
2278 Address(scratch, JSScript::offsetOfImmutableFlags()),
2279 Imm32(uint32_t(flag)), &done);
2280 {
2281 if (!emit()) {
2282 return false;
2283 }
2284 }
2285
2286 masm.bind(&done);
2287 return true;
2288 }
2289
2290 template <>
2291 template <typename F>
2292 [[nodiscard]] bool BaselineInterpreterCodeGen::emitTestScriptFlag(
2293 JSScript::MutableFlags flag, bool value, const F& emit, Register scratch) {
2294 Label done;
2295 loadScript(scratch);
2296 masm.branchTest32(value ? Assembler::Zero : Assembler::NonZero,
2297 Address(scratch, JSScript::offsetOfMutableFlags()),
2298 Imm32(uint32_t(flag)), &done);
2299 {
2300 if (!emit()) {
2301 return false;
2302 }
2303 }
2304
2305 masm.bind(&done);
2306 return true;
2307 }
2308
2309 template <typename Handler>
2310 bool BaselineCodeGen<Handler>::emit_Goto() {
2311 frame.syncStack(0);
2312 emitJump();
2313 return true;
2314 }
2315
2316 template <typename Handler>
2317 bool BaselineCodeGen<Handler>::emitTest(bool branchIfTrue) {
2318 bool knownBoolean = frame.stackValueHasKnownType(-1, JSVAL_TYPE_BOOLEAN);
2319
2320 // Keep top stack value in R0.
2321 frame.popRegsAndSync(1);
2322
2323 if (!knownBoolean && !emitNextIC()) {
2324 return false;
2325 }
2326
2327 // IC will leave a BooleanValue in R0, just need to branch on it.
2328 emitTestBooleanTruthy(branchIfTrue, R0);
2329 return true;
2330 }
2331
2332 template <typename Handler>
2333 bool BaselineCodeGen<Handler>::emit_JumpIfFalse() {
2334 return emitTest(false);
2335 }
2336
2337 template <typename Handler>
2338 bool BaselineCodeGen<Handler>::emit_JumpIfTrue() {
2339 return emitTest(true);
2340 }
2341
2342 template <typename Handler>
2343 bool BaselineCodeGen<Handler>::emitAndOr(bool branchIfTrue) {
2344 bool knownBoolean = frame.stackValueHasKnownType(-1, JSVAL_TYPE_BOOLEAN);
2345
2346 // And and Or leave the original value on the stack.
2347 frame.syncStack(0);
2348
2349 masm.loadValue(frame.addressOfStackValue(-1), R0);
2350 if (!knownBoolean && !emitNextIC()) {
2351 return false;
2352 }
2353
2354 emitTestBooleanTruthy(branchIfTrue, R0);
2355 return true;
2356 }
2357
2358 template <typename Handler>
2359 bool BaselineCodeGen<Handler>::emit_And() {
2360 return emitAndOr(false);
2361 }
2362
2363 template <typename Handler>
2364 bool BaselineCodeGen<Handler>::emit_Or() {
2365 return emitAndOr(true);
2366 }
2367
2368 template <typename Handler>
2369 bool BaselineCodeGen<Handler>::emit_Coalesce() {
2370 // Coalesce leaves the original value on the stack.
2371 frame.syncStack(0);
2372
2373 masm.loadValue(frame.addressOfStackValue(-1), R0);
2374
2375 Label undefinedOrNull;
2376
2377 masm.branchTestUndefined(Assembler::Equal, R0, &undefinedOrNull);
2378 masm.branchTestNull(Assembler::Equal, R0, &undefinedOrNull);
2379 emitJump();
2380
2381 masm.bind(&undefinedOrNull);
2382 // fall through
2383 return true;
2384 }
2385
2386 template <typename Handler>
2387 bool BaselineCodeGen<Handler>::emit_Not() {
2388 bool knownBoolean = frame.stackValueHasKnownType(-1, JSVAL_TYPE_BOOLEAN);
2389
2390 // Keep top stack value in R0.
2391 frame.popRegsAndSync(1);
2392
2393 if (!knownBoolean && !emitNextIC()) {
2394 return false;
2395 }
2396
2397 masm.notBoolean(R0);
2398
2399 frame.push(R0, JSVAL_TYPE_BOOLEAN);
2400 return true;
2401 }
2402
2403 template <typename Handler>
2404 bool BaselineCodeGen<Handler>::emit_Pos() {
2405 return emitUnaryArith();
2406 }
2407
2408 template <typename Handler>
2409 bool BaselineCodeGen<Handler>::emit_ToNumeric() {
2410 return emitUnaryArith();
2411 }
2412
2413 template <typename Handler>
2414 bool BaselineCodeGen<Handler>::emit_LoopHead() {
2415 if (!emit_JumpTarget()) {
2416 return false;
2417 }
2418 if (!emitInterruptCheck()) {
2419 return false;
2420 }
2421 if (!emitWarmUpCounterIncrement()) {
2422 return false;
2423 }
2424 return true;
2425 }
2426
2427 template <typename Handler>
2428 bool BaselineCodeGen<Handler>::emit_Void() {
2429 frame.pop();
2430 frame.push(UndefinedValue());
2431 return true;
2432 }
2433
2434 template <typename Handler>
2435 bool BaselineCodeGen<Handler>::emit_Undefined() {
2436 frame.push(UndefinedValue());
2437 return true;
2438 }
2439
2440 template <typename Handler>
2441 bool BaselineCodeGen<Handler>::emit_Hole() {
2442 frame.push(MagicValue(JS_ELEMENTS_HOLE));
2443 return true;
2444 }
2445
2446 template <typename Handler>
2447 bool BaselineCodeGen<Handler>::emit_Null() {
2448 frame.push(NullValue());
2449 return true;
2450 }
2451
2452 template <typename Handler>
2453 bool BaselineCodeGen<Handler>::emit_CheckIsObj() {
2454 frame.syncStack(0);
2455 masm.loadValue(frame.addressOfStackValue(-1), R0);
2456
2457 Label ok;
2458 masm.branchTestObject(Assembler::Equal, R0, &ok);
2459
2460 prepareVMCall();
2461
2462 pushUint8BytecodeOperandArg(R0.scratchReg());
2463
2464 using Fn = bool (*)(JSContext*, CheckIsObjectKind);
2465 if (!callVM<Fn, ThrowCheckIsObject>()) {
2466 return false;
2467 }
2468
2469 masm.bind(&ok);
2470 return true;
2471 }
2472
2473 template <typename Handler>
2474 bool BaselineCodeGen<Handler>::emit_CheckThis() {
2475 frame.syncStack(0);
2476 masm.loadValue(frame.addressOfStackValue(-1), R0);
2477
2478 return emitCheckThis(R0);
2479 }
2480
2481 template <typename Handler>
2482 bool BaselineCodeGen<Handler>::emit_CheckThisReinit() {
2483 frame.syncStack(0);
2484 masm.loadValue(frame.addressOfStackValue(-1), R0);
2485
2486 return emitCheckThis(R0, /* reinit = */ true);
2487 }
2488
2489 template <typename Handler>
2490 bool BaselineCodeGen<Handler>::emitCheckThis(ValueOperand val, bool reinit) {
2491 Label thisOK;
2492 if (reinit) {
2493 masm.branchTestMagic(Assembler::Equal, val, &thisOK);
2494 } else {
2495 masm.branchTestMagic(Assembler::NotEqual, val, &thisOK);
2496 }
2497
2498 prepareVMCall();
2499
2500 if (reinit) {
2501 using Fn = bool (*)(JSContext*);
2502 if (!callVM<Fn, ThrowInitializedThis>()) {
2503 return false;
2504 }
2505 } else {
2506 using Fn = bool (*)(JSContext*);
2507 if (!callVM<Fn, ThrowUninitializedThis>()) {
2508 return false;
2509 }
2510 }
2511
2512 masm.bind(&thisOK);
2513 return true;
2514 }
2515
2516 template <typename Handler>
2517 bool BaselineCodeGen<Handler>::emit_CheckReturn() {
2518 MOZ_ASSERT_IF(handler.maybeScript(),
2519 handler.maybeScript()->isDerivedClassConstructor());
2520
2521 // Load |this| in R0, return value in R1.
2522 frame.popRegsAndSync(1);
2523 emitLoadReturnValue(R1);
2524
2525 Label done, returnBad, checkThis;
2526 masm.branchTestObject(Assembler::NotEqual, R1, &checkThis);
2527 {
2528 masm.moveValue(R1, R0);
2529 masm.jump(&done);
2530 }
2531 masm.bind(&checkThis);
2532 masm.branchTestUndefined(Assembler::NotEqual, R1, &returnBad);
2533 masm.branchTestMagic(Assembler::NotEqual, R0, &done);
2534 masm.bind(&returnBad);
2535
2536 prepareVMCall();
2537 pushArg(R1);
2538
2539 using Fn = bool (*)(JSContext*, HandleValue);
2540 if (!callVM<Fn, ThrowBadDerivedReturnOrUninitializedThis>()) {
2541 return false;
2542 }
2543 masm.assumeUnreachable("Should throw on bad derived constructor return");
2544
2545 masm.bind(&done);
2546
2547 // Push |rval| or |this| onto the stack.
2548 frame.push(R0);
2549 return true;
2550 }
2551
2552 template <typename Handler>
2553 bool BaselineCodeGen<Handler>::emit_FunctionThis() {
2554 MOZ_ASSERT_IF(handler.maybeFunction(), !handler.maybeFunction()->isArrow());
2555
2556 frame.pushThis();
2557
2558 auto boxThis = [this]() {
2559 // Load |thisv| in R0. Skip the call if it's already an object.
2560 Label skipCall;
2561 frame.popRegsAndSync(1);
2562 masm.branchTestObject(Assembler::Equal, R0, &skipCall);
2563
2564 prepareVMCall();
2565 masm.loadBaselineFramePtr(FramePointer, R1.scratchReg());
2566
2567 pushArg(R1.scratchReg());
2568
2569 using Fn = bool (*)(JSContext*, BaselineFrame*, MutableHandleValue);
2570 if (!callVM<Fn, BaselineGetFunctionThis>()) {
2571 return false;
2572 }
2573
2574 masm.bind(&skipCall);
2575 frame.push(R0);
2576 return true;
2577 };
2578
2579 // In strict mode code, |this| is left alone.
2580 return emitTestScriptFlag(JSScript::ImmutableFlags::Strict, false, boxThis,
2581 R2.scratchReg());
2582 }
2583
2584 template <typename Handler>
2585 bool BaselineCodeGen<Handler>::emit_GlobalThis() {
2586 frame.syncStack(0);
2587
2588 loadGlobalThisValue(R0);
2589 frame.push(R0);
2590 return true;
2591 }
2592
2593 template <typename Handler>
2594 bool BaselineCodeGen<Handler>::emit_NonSyntacticGlobalThis() {
2595 frame.syncStack(0);
2596
2597 prepareVMCall();
2598
2599 masm.loadPtr(frame.addressOfEnvironmentChain(), R0.scratchReg());
2600 pushArg(R0.scratchReg());
2601
2602 using Fn = void (*)(JSContext*, HandleObject, MutableHandleValue);
2603 if (!callVM<Fn, GetNonSyntacticGlobalThis>()) {
2604 return false;
2605 }
2606
2607 frame.push(R0);
2608 return true;
2609 }
2610
2611 template <typename Handler>
2612 bool BaselineCodeGen<Handler>::emit_True() {
2613 frame.push(BooleanValue(true));
2614 return true;
2615 }
2616
2617 template <typename Handler>
2618 bool BaselineCodeGen<Handler>::emit_False() {
2619 frame.push(BooleanValue(false));
2620 return true;
2621 }
2622
2623 template <typename Handler>
2624 bool BaselineCodeGen<Handler>::emit_Zero() {
2625 frame.push(Int32Value(0));
2626 return true;
2627 }
2628
2629 template <typename Handler>
2630 bool BaselineCodeGen<Handler>::emit_One() {
2631 frame.push(Int32Value(1));
2632 return true;
2633 }
2634
2635 template <>
2636 bool BaselineCompilerCodeGen::emit_Int8() {
2637 frame.push(Int32Value(GET_INT8(handler.pc())));
2638 return true;
2639 }
2640
2641 template <>
2642 bool BaselineInterpreterCodeGen::emit_Int8() {
2643 LoadInt8Operand(masm, R0.scratchReg());
2644 masm.tagValue(JSVAL_TYPE_INT32, R0.scratchReg(), R0);
2645 frame.push(R0);
2646 return true;
2647 }
2648
2649 template <>
2650 bool BaselineCompilerCodeGen::emit_Int32() {
2651 frame.push(Int32Value(GET_INT32(handler.pc())));
2652 return true;
2653 }
2654
2655 template <>
2656 bool BaselineInterpreterCodeGen::emit_Int32() {
2657 LoadInt32Operand(masm, R0.scratchReg());
2658 masm.tagValue(JSVAL_TYPE_INT32, R0.scratchReg(), R0);
2659 frame.push(R0);
2660 return true;
2661 }
2662
2663 template <>
2664 bool BaselineCompilerCodeGen::emit_Uint16() {
2665 frame.push(Int32Value(GET_UINT16(handler.pc())));
2666 return true;
2667 }
2668
2669 template <>
2670 bool BaselineInterpreterCodeGen::emit_Uint16() {
2671 LoadUint16Operand(masm, R0.scratchReg());
2672 masm.tagValue(JSVAL_TYPE_INT32, R0.scratchReg(), R0);
2673 frame.push(R0);
2674 return true;
2675 }
2676
2677 template <>
2678 bool BaselineCompilerCodeGen::emit_Uint24() {
2679 frame.push(Int32Value(GET_UINT24(handler.pc())));
2680 return true;
2681 }
2682
2683 template <>
2684 bool BaselineInterpreterCodeGen::emit_Uint24() {
2685 LoadUint24Operand(masm, 0, R0.scratchReg());
2686 masm.tagValue(JSVAL_TYPE_INT32, R0.scratchReg(), R0);
2687 frame.push(R0);
2688 return true;
2689 }
2690
2691 template <>
2692 bool BaselineCompilerCodeGen::emit_Double() {
2693 frame.push(GET_INLINE_VALUE(handler.pc()));
2694 return true;
2695 }
2696
2697 template <>
2698 bool BaselineInterpreterCodeGen::emit_Double() {
2699 LoadInlineValueOperand(masm, R0);
2700 frame.push(R0);
2701 return true;
2702 }
2703
2704 template <typename Handler>
2705 bool BaselineCodeGen<Handler>::emit_BigInt() {
2706 if (handler.realmIndependentJitcode()) {
2707 frame.syncStack(0);
2708 Register scratch1 = R0.scratchReg();
2709 Register scratch2 = R1.scratchReg();
2710 loadScriptGCThing(ScriptGCThingType::BigInt, scratch1, scratch2);
2711 masm.tagValue(JSVAL_TYPE_BIGINT, scratch1, R0);
2712 frame.push(R0);
2713 } else {
2714 BigInt* bi = handler.maybeScript()->getBigInt(handler.maybePC());
2715 frame.push(BigIntValue(bi));
2716 }
2717 return true;
2718 }
2719
2720 template <typename Handler>
2721 bool BaselineCodeGen<Handler>::emit_String() {
2722 if (handler.realmIndependentJitcode()) {
2723 frame.syncStack(0);
2724 Register scratch1 = R0.scratchReg();
2725 Register scratch2 = R1.scratchReg();
2726 loadScriptGCThing(ScriptGCThingType::String, scratch1, scratch2);
2727 masm.tagValue(JSVAL_TYPE_STRING, scratch1, R0);
2728 frame.push(R0);
2729 } else {
2730 frame.push(
2731 StringValue(handler.maybeScript()->getString(handler.maybePC())));
2732 }
2733 return true;
2734 }
2735
2736 template <>
2737 bool BaselineCompilerCodeGen::emit_Symbol() {
2738 unsigned which = GET_UINT8(handler.pc());
2739 JS::Symbol* sym = runtime->wellKnownSymbols().get(which);
2740 frame.push(SymbolValue(sym));
2741 return true;
2742 }
2743
2744 template <>
2745 bool BaselineInterpreterCodeGen::emit_Symbol() {
2746 Register scratch1 = R0.scratchReg();
2747 Register scratch2 = R1.scratchReg();
2748 LoadUint8Operand(masm, scratch1);
2749
2750 masm.movePtr(ImmPtr(&runtime->wellKnownSymbols()), scratch2);
2751 masm.loadPtr(BaseIndex(scratch2, scratch1, ScalePointer), scratch1);
2752
2753 masm.tagValue(JSVAL_TYPE_SYMBOL, scratch1, R0);
2754 frame.push(R0);
2755 return true;
2756 }
2757
2758 template <typename Handler>
2759 bool BaselineCodeGen<Handler>::emit_Object() {
2760 if (handler.realmIndependentJitcode()) {
2761 Register scratch1 = R0.scratchReg();
2762 Register scratch2 = R1.scratchReg();
2763 loadScriptGCThing(ScriptGCThingType::Object, scratch1, scratch2);
2764 masm.tagValue(JSVAL_TYPE_OBJECT, scratch1, R0);
2765 frame.push(R0);
2766 } else {
2767 frame.push(
2768 ObjectValue(*handler.maybeScript()->getObject(handler.maybePC())));
2769 }
2770 return true;
2771 }
2772
2773 template <typename Handler>
2774 bool BaselineCodeGen<Handler>::emit_CallSiteObj() {
2775 return emit_Object();
2776 }
2777
2778 template <typename Handler>
2779 bool BaselineCodeGen<Handler>::emit_RegExp() {
2780 prepareVMCall();
2781 pushScriptGCThingArg(ScriptGCThingType::RegExp, R0.scratchReg(),
2782 R1.scratchReg());
2783
2784 using Fn = JSObject* (*)(JSContext*, Handle<RegExpObject*>);
2785 if (!callVM<Fn, CloneRegExpObject>()) {
2786 return false;
2787 }
2788
2789 // Box and push return value.
2790 masm.tagValue(JSVAL_TYPE_OBJECT, ReturnReg, R0);
2791 frame.push(R0);
2792 return true;
2793 }
2794
2795 template <typename Handler>
2796 bool BaselineCodeGen<Handler>::emit_Lambda() {
2797 frame.syncStack(0);
2798
2799 if (!emitNextIC()) {
2800 return false;
2801 }
2802
2803 frame.push(R0);
2804 return true;
2805 }
2806
2807 template <typename Handler>
2808 bool BaselineCodeGen<Handler>::emit_SetFunName() {
2809 frame.popRegsAndSync(2);
2810
2811 frame.push(R0);
2812 frame.syncStack(0);
2813
2814 masm.unboxObject(R0, R0.scratchReg());
2815
2816 prepareVMCall();
2817
2818 pushUint8BytecodeOperandArg(R2.scratchReg());
2819 pushArg(R1);
2820 pushArg(R0.scratchReg());
2821
2822 using Fn =
2823 bool (*)(JSContext*, HandleFunction, HandleValue, FunctionPrefixKind);
2824 return callVM<Fn, SetFunctionName>();
2825 }
2826
2827 template <typename Handler>
2828 bool BaselineCodeGen<Handler>::emit_BitOr() {
2829 return emitBinaryArith();
2830 }
2831
2832 template <typename Handler>
2833 bool BaselineCodeGen<Handler>::emit_BitXor() {
2834 return emitBinaryArith();
2835 }
2836
2837 template <typename Handler>
2838 bool BaselineCodeGen<Handler>::emit_BitAnd() {
2839 return emitBinaryArith();
2840 }
2841
2842 template <typename Handler>
2843 bool BaselineCodeGen<Handler>::emit_Lsh() {
2844 return emitBinaryArith();
2845 }
2846
2847 template <typename Handler>
2848 bool BaselineCodeGen<Handler>::emit_Rsh() {
2849 return emitBinaryArith();
2850 }
2851
2852 template <typename Handler>
2853 bool BaselineCodeGen<Handler>::emit_Ursh() {
2854 return emitBinaryArith();
2855 }
2856
2857 template <typename Handler>
2858 bool BaselineCodeGen<Handler>::emit_Add() {
2859 return emitBinaryArith();
2860 }
2861
2862 template <typename Handler>
2863 bool BaselineCodeGen<Handler>::emit_Sub() {
2864 return emitBinaryArith();
2865 }
2866
2867 template <typename Handler>
2868 bool BaselineCodeGen<Handler>::emit_Mul() {
2869 return emitBinaryArith();
2870 }
2871
2872 template <typename Handler>
2873 bool BaselineCodeGen<Handler>::emit_Div() {
2874 return emitBinaryArith();
2875 }
2876
2877 template <typename Handler>
2878 bool BaselineCodeGen<Handler>::emit_Mod() {
2879 return emitBinaryArith();
2880 }
2881
2882 template <typename Handler>
2883 bool BaselineCodeGen<Handler>::emit_Pow() {
2884 return emitBinaryArith();
2885 }
2886
2887 template <typename Handler>
2888 bool BaselineCodeGen<Handler>::emitBinaryArith() {
2889 // Keep top JSStack value in R0 and R2
2890 frame.popRegsAndSync(2);
2891
2892 // Call IC
2893 if (!emitNextIC()) {
2894 return false;
2895 }
2896
2897 // Mark R0 as pushed stack value.
2898 frame.push(R0);
2899 return true;
2900 }
2901
2902 template <typename Handler>
2903 bool BaselineCodeGen<Handler>::emitUnaryArith() {
2904 // Keep top stack value in R0.
2905 frame.popRegsAndSync(1);
2906
2907 // Call IC
2908 if (!emitNextIC()) {
2909 return false;
2910 }
2911
2912 // Mark R0 as pushed stack value.
2913 frame.push(R0);
2914 return true;
2915 }
2916
2917 template <typename Handler>
2918 bool BaselineCodeGen<Handler>::emit_BitNot() {
2919 return emitUnaryArith();
2920 }
2921
2922 template <typename Handler>
2923 bool BaselineCodeGen<Handler>::emit_Neg() {
2924 return emitUnaryArith();
2925 }
2926
2927 template <typename Handler>
2928 bool BaselineCodeGen<Handler>::emit_Inc() {
2929 return emitUnaryArith();
2930 }
2931
2932 template <typename Handler>
2933 bool BaselineCodeGen<Handler>::emit_Dec() {
2934 return emitUnaryArith();
2935 }
2936
2937 template <typename Handler>
2938 bool BaselineCodeGen<Handler>::emit_Lt() {
2939 return emitCompare();
2940 }
2941
2942 template <typename Handler>
2943 bool BaselineCodeGen<Handler>::emit_Le() {
2944 return emitCompare();
2945 }
2946
2947 template <typename Handler>
2948 bool BaselineCodeGen<Handler>::emit_Gt() {
2949 return emitCompare();
2950 }
2951
2952 template <typename Handler>
2953 bool BaselineCodeGen<Handler>::emit_Ge() {
2954 return emitCompare();
2955 }
2956
2957 template <typename Handler>
2958 bool BaselineCodeGen<Handler>::emit_Eq() {
2959 return emitCompare();
2960 }
2961
2962 template <typename Handler>
2963 bool BaselineCodeGen<Handler>::emit_Ne() {
2964 return emitCompare();
2965 }
2966
2967 template <typename Handler>
2968 bool BaselineCodeGen<Handler>::emitCompare() {
2969 // Keep top JSStack value in R0 and R1.
2970 frame.popRegsAndSync(2);
2971
2972 // Call IC.
2973 if (!emitNextIC()) {
2974 return false;
2975 }
2976
2977 // Mark R0 as pushed stack value.
2978 frame.push(R0, JSVAL_TYPE_BOOLEAN);
2979 return true;
2980 }
2981
2982 template <typename Handler>
2983 bool BaselineCodeGen<Handler>::emit_StrictEq() {
2984 return emitCompare();
2985 }
2986
2987 template <typename Handler>
2988 bool BaselineCodeGen<Handler>::emit_StrictNe() {
2989 return emitCompare();
2990 }
2991
2992 template <>
2993 bool BaselineCompilerCodeGen::emitConstantStrictEq(JSOp op) {
2994 ConstantCompareOperand data =
2995 ConstantCompareOperand::fromRawValue(GET_UINT16(handler.pc()));
2996
2997 frame.popRegsAndSync(1);
2998
2999 ValueOperand value = R0;
3000 Label fail, pass, done;
3001
3002 switch (data.type()) {
3003 case ConstantCompareOperand::EncodedType::Int32: {
3004 int32_t constantVal = data.toInt32();
3005
3006 Label maybeDouble;
3007 masm.branchTestInt32(Assembler::NotEqual, value, &maybeDouble);
3008 masm.branch32(JSOpToCondition(op, true), value.payloadOrValueReg(),
3009 Imm32(constantVal), &pass,
3010 MacroAssembler::LhsHighBitsAreClean::No);
3011 masm.jump(&fail);
3012
3013 masm.bind(&maybeDouble);
3014 {
3015 FloatRegister unboxedValue = FloatReg0;
3016 FloatRegister floatPayload = FloatReg1;
3017
3018 masm.branchTestDouble(Assembler::NotEqual, value,
3019 op == JSOp::StrictEq ? &fail : &pass);
3020
3021 masm.unboxDouble(value, unboxedValue);
3022 masm.loadConstantDouble(double(constantVal), floatPayload);
3023 masm.branchDouble(JSOpToDoubleCondition(op), unboxedValue, floatPayload,
3024 &pass);
3025 }
3026 break;
3027 }
3028
3029 case ConstantCompareOperand::EncodedType::Boolean: {
3030 bool constantVal = data.toBoolean();
3031 Register boolUnboxed = R1.scratchReg();
3032 masm.fallibleUnboxBoolean(value, boolUnboxed,
3033 op == JSOp::StrictEq ? &fail : &pass);
3034 masm.branch32(JSOpToCondition(op, true), boolUnboxed, Imm32(constantVal),
3035 &pass);
3036 break;
3037 }
3038
3039 case ConstantCompareOperand::EncodedType::Null: {
3040 masm.branchTestNull(Assembler::NotEqual, value,
3041 op == JSOp::StrictEq ? &fail : &pass);
3042 if (op == JSOp::StrictEq) {
3043 masm.jump(&pass);
3044 }
3045 break;
3046 }
3047
3048 case ConstantCompareOperand::EncodedType::Undefined: {
3049 masm.branchTestUndefined(Assembler::NotEqual, value,
3050 op == JSOp::StrictEq ? &fail : &pass);
3051 if (op == JSOp::StrictEq) {
3052 masm.jump(&pass);
3053 }
3054 break;
3055 }
3056 }
3057
3058 masm.bind(&fail);
3059 {
3060 masm.moveValue(BooleanValue(false), R0);
3061 masm.jump(&done);
3062 }
3063
3064 masm.bind(&pass);
3065 {
3066 masm.moveValue(BooleanValue(true), R0);
3067 }
3068
3069 masm.bind(&done);
3070 frame.push(R0, JSVAL_TYPE_BOOLEAN);
3071 return true;
3072 }
3073
3074 template <>
3075 bool BaselineCompilerCodeGen::emit_StrictConstantEq() {
3076 return emitConstantStrictEq(JSOp::StrictEq);
3077 }
3078
3079 template <>
3080 bool BaselineCompilerCodeGen::emit_StrictConstantNe() {
3081 return emitConstantStrictEq(JSOp::StrictNe);
3082 }
3083
3084 template <>
3085 bool BaselineInterpreterCodeGen::emitConstantStrictEq(JSOp op) {
3086 frame.popRegsAndSync(1);
3087
3088 ValueOperand value = R0;
3089 Register constantType = R1.scratchReg();
3090 Register payload = R2.scratchReg();
3091
3092 LoadConstantCompareOperand(masm, constantType, payload);
3093 Label isInt32, isBool, isNull, isUndefined;
3094 Label pass, fail, done;
3095
3096 masm.branch32(Assembler::Equal, constantType,
3097 Imm32(int32_t(ConstantCompareOperand::EncodedType::Int32)),
3098 &isInt32);
3099 masm.branch32(Assembler::Equal, constantType,
3100 Imm32(int32_t(ConstantCompareOperand::EncodedType::Boolean)),
3101 &isBool);
3102 masm.branch32(Assembler::Equal, constantType,
3103 Imm32(int32_t(ConstantCompareOperand::EncodedType::Null)),
3104 &isNull);
3105 masm.branch32(Assembler::Equal, constantType,
3106 Imm32(int32_t(ConstantCompareOperand::EncodedType::Undefined)),
3107 &isUndefined);
3108 masm.assumeUnreachable("Unexpected constant compare type");
3109
3110 masm.bind(&isInt32);
3111 {
3112 Label maybeDouble;
3113 masm.branchTestInt32(Assembler::NotEqual, value, &maybeDouble);
3114 masm.branch32(JSOpToCondition(op, true), value.payloadOrValueReg(), payload,
3115 &pass, MacroAssembler::LhsHighBitsAreClean::No);
3116 masm.jump(&fail);
3117
3118 masm.bind(&maybeDouble);
3119 {
3120 FloatRegister unboxedValue = FloatReg0;
3121 FloatRegister floatPayload = FloatReg1;
3122 masm.branchTestDouble(Assembler::NotEqual, value,
3123 op == JSOp::StrictEq ? &fail : &pass);
3124 masm.unboxDouble(value, unboxedValue);
3125 masm.convertInt32ToDouble(payload, floatPayload);
3126 masm.branchDouble(JSOpToDoubleCondition(op), unboxedValue, floatPayload,
3127 &pass);
3128 masm.jump(&fail);
3129 }
3130 }
3131
3132 masm.bind(&isBool);
3133 {
3134 Register boolUnboxed = R1.scratchReg();
3135 masm.fallibleUnboxBoolean(value, boolUnboxed,
3136 op == JSOp::StrictEq ? &fail : &pass);
3137 masm.branch32(JSOpToCondition(op, true), boolUnboxed, payload, &pass);
3138 masm.jump(&fail);
3139 }
3140
3141 masm.bind(&isNull);
3142 {
3143 masm.branchTestNull(Assembler::NotEqual, value,
3144 op == JSOp::StrictEq ? &fail : &pass);
3145 masm.jump(op == JSOp::StrictEq ? &pass : &fail);
3146 }
3147
3148 masm.bind(&isUndefined);
3149 {
3150 masm.branchTestUndefined(Assembler::NotEqual, value,
3151 op == JSOp::StrictEq ? &fail : &pass);
3152 masm.jump(op == JSOp::StrictEq ? &pass : &fail);
3153 }
3154
3155 masm.bind(&pass);
3156 {
3157 masm.moveValue(BooleanValue(true), value);
3158 masm.jump(&done);
3159 }
3160
3161 masm.bind(&fail);
3162 {
3163 masm.moveValue(BooleanValue(false), value);
3164 }
3165
3166 masm.bind(&done);
3167 frame.push(R0, JSVAL_TYPE_BOOLEAN);
3168 return true;
3169 }
3170
3171 template <>
3172 bool BaselineInterpreterCodeGen::emit_StrictConstantEq() {
3173 return emitConstantStrictEq(JSOp::StrictEq);
3174 }
3175
3176 template <>
3177 bool BaselineInterpreterCodeGen::emit_StrictConstantNe() {
3178 return emitConstantStrictEq(JSOp::StrictNe);
3179 }
3180
3181 template <typename Handler>
3182 bool BaselineCodeGen<Handler>::emit_Case() {
3183 frame.popRegsAndSync(1);
3184
3185 Label done;
3186 masm.branchTestBooleanTruthy(/* branchIfTrue */ false, R0, &done);
3187 {
3188 // Pop the switch value if the case matches.
3189 masm.addToStackPtr(Imm32(sizeof(Value)));
3190 emitJump();
3191 }
3192 masm.bind(&done);
3193 return true;
3194 }
3195
3196 template <typename Handler>
3197 bool BaselineCodeGen<Handler>::emit_Default() {
3198 frame.pop();
3199 return emit_Goto();
3200 }
3201
3202 template <typename Handler>
3203 bool BaselineCodeGen<Handler>::emit_Lineno() {
3204 return true;
3205 }
3206
3207 template <typename Handler>
3208 bool BaselineCodeGen<Handler>::emit_NewArray() {
3209 frame.syncStack(0);
3210
3211 if (!emitNextIC()) {
3212 return false;
3213 }
3214
3215 frame.push(R0);
3216 return true;
3217 }
3218
3219 static void MarkElementsNonPackedIfHoleValue(MacroAssembler& masm,
3220 Register elements,
3221 ValueOperand val) {
3222 Label notHole;
3223 masm.branchTestMagic(Assembler::NotEqual, val, &notHole);
3224 {
3225 Address elementsFlags(elements, ObjectElements::offsetOfFlags());
3226 masm.or32(Imm32(ObjectElements::NON_PACKED), elementsFlags);
3227 }
3228 masm.bind(&notHole);
3229 }
3230
3231 template <>
3232 bool BaselineInterpreterCodeGen::emit_InitElemArray() {
3233 // Pop value into R0, keep the object on the stack.
3234 frame.popRegsAndSync(1);
3235
3236 // Load object in R2.
3237 Register obj = R2.scratchReg();
3238 masm.unboxObject(frame.addressOfStackValue(-1), obj);
3239
3240 // Load index in R1.
3241 Register index = R1.scratchReg();
3242 LoadInt32Operand(masm, index);
3243
3244 // Store the Value. No pre-barrier because this is an initialization.
3245 masm.loadPtr(Address(obj, NativeObject::offsetOfElements()), obj);
3246 masm.storeValue(R0, BaseObjectElementIndex(obj, index));
3247
3248 // Bump initialized length.
3249 Address initLength(obj, ObjectElements::offsetOfInitializedLength());
3250 masm.add32(Imm32(1), index);
3251 masm.store32(index, initLength);
3252
3253 // Mark elements as NON_PACKED if we stored the hole value.
3254 MarkElementsNonPackedIfHoleValue(masm, obj, R0);
3255
3256 // Post-barrier.
3257 Label skipBarrier;
3258 Register scratch = index;
3259 masm.branchValueIsNurseryCell(Assembler::NotEqual, R0, scratch, &skipBarrier);
3260 {
3261 masm.unboxObject(frame.addressOfStackValue(-1), obj);
3262 masm.branchPtrInNurseryChunk(Assembler::Equal, obj, scratch, &skipBarrier);
3263 MOZ_ASSERT(obj == R2.scratchReg(), "post barrier expects object in R2");
3264 masm.call(&postBarrierSlot_);
3265 }
3266 masm.bind(&skipBarrier);
3267 return true;
3268 }
3269
3270 template <>
3271 bool BaselineCompilerCodeGen::emit_InitElemArray() {
3272 // Pop value into R0, keep the object on the stack.
3273 Maybe<Value> knownValue = frame.knownStackValue(-1);
3274 frame.popRegsAndSync(1);
3275
3276 // Load object in R2.
3277 Register obj = R2.scratchReg();
3278 masm.unboxObject(frame.addressOfStackValue(-1), obj);
3279
3280 uint32_t index = GET_UINT32(handler.pc());
3281 MOZ_ASSERT(index <= INT32_MAX,
3282 "the bytecode emitter must fail to compile code that would "
3283 "produce an index exceeding int32_t range");
3284
3285 // Store the Value. No pre-barrier because this is an initialization.
3286 masm.loadPtr(Address(obj, NativeObject::offsetOfElements()), obj);
3287 masm.storeValue(R0, Address(obj, index * sizeof(Value)));
3288
3289 // Bump initialized length.
3290 Address initLength(obj, ObjectElements::offsetOfInitializedLength());
3291 masm.store32(Imm32(index + 1), initLength);
3292
3293 // Mark elements as NON_PACKED if we stored the hole value. We know this
3294 // statically except when debugger instrumentation is enabled because that
3295 // forces a stack-sync (which discards constants and known types) for each op.
3296 if (knownValue && knownValue->isMagic(JS_ELEMENTS_HOLE)) {
3297 Address elementsFlags(obj, ObjectElements::offsetOfFlags());
3298 masm.or32(Imm32(ObjectElements::NON_PACKED), elementsFlags);
3299 } else if (handler.compileDebugInstrumentation()) {
3300 MarkElementsNonPackedIfHoleValue(masm, obj, R0);
3301 } else {
3302 #ifdef DEBUG
3303 Label notHole;
3304 masm.branchTestMagic(Assembler::NotEqual, R0, &notHole);
3305 masm.assumeUnreachable("Unexpected hole value");
3306 masm.bind(&notHole);
3307 #endif
3308 }
3309
3310 // Post-barrier.
3311 if (knownValue) {
3312 MOZ_ASSERT(JS::GCPolicy<Value>::isTenured(*knownValue));
3313 } else {
3314 Label skipBarrier;
3315 Register scratch = R1.scratchReg();
3316 masm.branchValueIsNurseryCell(Assembler::NotEqual, R0, scratch,
3317 &skipBarrier);
3318 {
3319 masm.unboxObject(frame.addressOfStackValue(-1), obj);
3320 masm.branchPtrInNurseryChunk(Assembler::Equal, obj, scratch,
3321 &skipBarrier);
3322 MOZ_ASSERT(obj == R2.scratchReg(), "post barrier expects object in R2");
3323 masm.call(&postBarrierSlot_);
3324 }
3325 masm.bind(&skipBarrier);
3326 }
3327 return true;
3328 }
3329
3330 template <typename Handler>
3331 bool BaselineCodeGen<Handler>::emit_NewObject() {
3332 return emitNewObject();
3333 }
3334
3335 template <typename Handler>
3336 bool BaselineCodeGen<Handler>::emit_NewInit() {
3337 return emitNewObject();
3338 }
3339
3340 template <typename Handler>
3341 bool BaselineCodeGen<Handler>::emitNewObject() {
3342 frame.syncStack(0);
3343
3344 if (!emitNextIC()) {
3345 return false;
3346 }
3347
3348 frame.push(R0);
3349 return true;
3350 }
3351
3352 template <typename Handler>
3353 bool BaselineCodeGen<Handler>::emit_InitElem() {
3354 // Store RHS in the scratch slot.
3355 frame.storeStackValue(-1, frame.addressOfScratchValue(), R2);
3356 frame.pop();
3357
3358 // Keep object and index in R0 and R1.
3359 frame.popRegsAndSync(2);
3360
3361 // Push the object to store the result of the IC.
3362 frame.push(R0);
3363 frame.syncStack(0);
3364
3365 // Keep RHS on the stack.
3366 frame.pushScratchValue();
3367
3368 // Call IC.
3369 if (!emitNextIC()) {
3370 return false;
3371 }
3372
3373 // Pop the rhs, so that the object is on the top of the stack.
3374 frame.pop();
3375 return true;
3376 }
3377
3378 template <typename Handler>
3379 bool BaselineCodeGen<Handler>::emit_InitHiddenElem() {
3380 return emit_InitElem();
3381 }
3382
3383 template <typename Handler>
3384 bool BaselineCodeGen<Handler>::emit_InitLockedElem() {
3385 return emit_InitElem();
3386 }
3387
3388 template <typename Handler>
3389 bool BaselineCodeGen<Handler>::emit_MutateProto() {
3390 // Keep values on the stack for the decompiler.
3391 frame.syncStack(0);
3392
3393 masm.unboxObject(frame.addressOfStackValue(-2), R0.scratchReg());
3394 masm.loadValue(frame.addressOfStackValue(-1), R1);
3395
3396 prepareVMCall();
3397
3398 pushArg(R1);
3399 pushArg(R0.scratchReg());
3400
3401 using Fn = bool (*)(JSContext*, Handle<PlainObject*>, HandleValue);
3402 if (!callVM<Fn, MutatePrototype>()) {
3403 return false;
3404 }
3405
3406 frame.pop();
3407 return true;
3408 }
3409
3410 template <typename Handler>
3411 bool BaselineCodeGen<Handler>::emit_InitProp() {
3412 // Load lhs in R0, rhs in R1.
3413 frame.syncStack(0);
3414 masm.loadValue(frame.addressOfStackValue(-2), R0);
3415 masm.loadValue(frame.addressOfStackValue(-1), R1);
3416
3417 // Call IC.
3418 if (!emitNextIC()) {
3419 return false;
3420 }
3421
3422 // Leave the object on the stack.
3423 frame.pop();
3424 return true;
3425 }
3426
3427 template <typename Handler>
3428 bool BaselineCodeGen<Handler>::emit_InitLockedProp() {
3429 return emit_InitProp();
3430 }
3431
3432 template <typename Handler>
3433 bool BaselineCodeGen<Handler>::emit_InitHiddenProp() {
3434 return emit_InitProp();
3435 }
3436
3437 template <typename Handler>
3438 bool BaselineCodeGen<Handler>::emit_GetElem() {
3439 // Keep top two stack values in R0 and R1.
3440 frame.popRegsAndSync(2);
3441
3442 // Call IC.
3443 if (!emitNextIC()) {
3444 return false;
3445 }
3446
3447 // Mark R0 as pushed stack value.
3448 frame.push(R0);
3449 return true;
3450 }
3451
3452 template <typename Handler>
3453 bool BaselineCodeGen<Handler>::emit_GetElemSuper() {
3454 // Store obj in the scratch slot.
3455 frame.storeStackValue(-1, frame.addressOfScratchValue(), R2);
3456 frame.pop();
3457
3458 // Keep receiver and index in R0 and R1.
3459 frame.popRegsAndSync(2);
3460
3461 // Keep obj on the stack.
3462 frame.pushScratchValue();
3463
3464 if (!emitNextIC()) {
3465 return false;
3466 }
3467
3468 frame.pop();
3469 frame.push(R0);
3470 return true;
3471 }
3472
3473 template <typename Handler>
3474 bool BaselineCodeGen<Handler>::emit_SetElem() {
3475 // Store RHS in the scratch slot.
3476 frame.storeStackValue(-1, frame.addressOfScratchValue(), R2);
3477 frame.pop();
3478
3479 // Keep object and index in R0 and R1.
3480 frame.popRegsAndSync(2);
3481
3482 // Keep RHS on the stack.
3483 frame.pushScratchValue();
3484
3485 // Call IC.
3486 if (!emitNextIC()) {
3487 return false;
3488 }
3489
3490 return true;
3491 }
3492
3493 template <typename Handler>
3494 bool BaselineCodeGen<Handler>::emit_StrictSetElem() {
3495 return emit_SetElem();
3496 }
3497
3498 template <typename Handler>
3499 bool BaselineCodeGen<Handler>::emitSetElemSuper(bool strict) {
3500 // Incoming stack is |receiver, propval, obj, rval|. We need to shuffle
3501 // stack to leave rval when operation is complete.
3502
3503 // Pop rval into R0, then load receiver into R1 and replace with rval.
3504 frame.popRegsAndSync(1);
3505 masm.loadValue(frame.addressOfStackValue(-3), R1);
3506 masm.storeValue(R0, frame.addressOfStackValue(-3));
3507
3508 prepareVMCall();
3509
3510 pushArg(Imm32(strict));
3511 pushArg(R0); // rval
3512 masm.loadValue(frame.addressOfStackValue(-2), R0);
3513 pushArg(R0); // propval
3514 pushArg(R1); // receiver
3515 masm.loadValue(frame.addressOfStackValue(-1), R0);
3516 pushArg(R0); // obj
3517
3518 using Fn = bool (*)(JSContext*, HandleValue, HandleValue, HandleValue,
3519 HandleValue, bool);
3520 if (!callVM<Fn, js::SetElementSuper>()) {
3521 return false;
3522 }
3523
3524 frame.popn(2);
3525 return true;
3526 }
3527
3528 template <typename Handler>
3529 bool BaselineCodeGen<Handler>::emit_SetElemSuper() {
3530 return emitSetElemSuper(/* strict = */ false);
3531 }
3532
3533 template <typename Handler>
3534 bool BaselineCodeGen<Handler>::emit_StrictSetElemSuper() {
3535 return emitSetElemSuper(/* strict = */ true);
3536 }
3537
3538 template <typename Handler>
3539 bool BaselineCodeGen<Handler>::emitDelElem(bool strict) {
3540 // Keep values on the stack for the decompiler.
3541 frame.syncStack(0);
3542 masm.loadValue(frame.addressOfStackValue(-2), R0);
3543 masm.loadValue(frame.addressOfStackValue(-1), R1);
3544
3545 prepareVMCall();
3546
3547 pushArg(R1);
3548 pushArg(R0);
3549
3550 using Fn = bool (*)(JSContext*, HandleValue, HandleValue, bool*);
3551 if (strict) {
3552 if (!callVM<Fn, DelElemOperation<true>>()) {
3553 return false;
3554 }
3555 } else {
3556 if (!callVM<Fn, DelElemOperation<false>>()) {
3557 return false;
3558 }
3559 }
3560
3561 masm.boxNonDouble(JSVAL_TYPE_BOOLEAN, ReturnReg, R1);
3562 frame.popn(2);
3563 frame.push(R1, JSVAL_TYPE_BOOLEAN);
3564 return true;
3565 }
3566
3567 template <typename Handler>
3568 bool BaselineCodeGen<Handler>::emit_DelElem() {
3569 return emitDelElem(/* strict = */ false);
3570 }
3571
3572 template <typename Handler>
3573 bool BaselineCodeGen<Handler>::emit_StrictDelElem() {
3574 return emitDelElem(/* strict = */ true);
3575 }
3576
3577 template <typename Handler>
3578 bool BaselineCodeGen<Handler>::emit_In() {
3579 frame.popRegsAndSync(2);
3580
3581 if (!emitNextIC()) {
3582 return false;
3583 }
3584
3585 frame.push(R0, JSVAL_TYPE_BOOLEAN);
3586 return true;
3587 }
3588
3589 template <typename Handler>
3590 bool BaselineCodeGen<Handler>::emit_HasOwn() {
3591 frame.popRegsAndSync(2);
3592
3593 if (!emitNextIC()) {
3594 return false;
3595 }
3596
3597 frame.push(R0, JSVAL_TYPE_BOOLEAN);
3598 return true;
3599 }
3600
3601 template <typename Handler>
3602 bool BaselineCodeGen<Handler>::emit_CheckPrivateField() {
3603 // Keep key and val on the stack.
3604 frame.syncStack(0);
3605 masm.loadValue(frame.addressOfStackValue(-2), R0);
3606 masm.loadValue(frame.addressOfStackValue(-1), R1);
3607
3608 if (!emitNextIC()) {
3609 return false;
3610 }
3611
3612 frame.push(R0, JSVAL_TYPE_BOOLEAN);
3613 return true;
3614 }
3615
3616 template <typename Handler>
3617 bool BaselineCodeGen<Handler>::emit_NewPrivateName() {
3618 prepareVMCall();
3619
3620 pushScriptNameArg(R0.scratchReg(), R1.scratchReg());
3621
3622 using Fn = JS::Symbol* (*)(JSContext*, Handle<JSAtom*>);
3623 if (!callVM<Fn, NewPrivateName>()) {
3624 return false;
3625 }
3626
3627 masm.tagValue(JSVAL_TYPE_SYMBOL, ReturnReg, R0);
3628 frame.push(R0);
3629 return true;
3630 }
3631
3632 template <typename Handler>
3633 bool BaselineCodeGen<Handler>::emit_GetGName() {
3634 frame.syncStack(0);
3635
3636 loadGlobalLexicalEnvironment(R0.scratchReg());
3637
3638 // Call IC.
3639 if (!emitNextIC()) {
3640 return false;
3641 }
3642
3643 // Mark R0 as pushed stack value.
3644 frame.push(R0);
3645 return true;
3646 }
3647
3648 template <>
3649 bool BaselineCompilerCodeGen::tryOptimizeBindUnqualifiedGlobalName() {
3650 if (handler.realmIndependentJitcode()) {
3651 return false;
3652 }
3653 JSScript* script = handler.script();
3654 MOZ_ASSERT(!script->hasNonSyntacticScope());
3655
3656 if (handler.compilingOffThread()) {
3657 return false;
3658 }
3659
3660 GlobalObject* global = &script->global();
3661 PropertyName* name = script->getName(handler.pc());
3662 if (JSObject* binding =
3663 MaybeOptimizeBindUnqualifiedGlobalName(global, name)) {
3664 frame.push(ObjectValue(*binding));
3665 return true;
3666 }
3667 return false;
3668 }
3669
3670 template <>
3671 bool BaselineInterpreterCodeGen::tryOptimizeBindUnqualifiedGlobalName() {
3672 // Interpreter doesn't optimize simple BindUnqualifiedGNames.
3673 return false;
3674 }
3675
3676 template <typename Handler>
3677 bool BaselineCodeGen<Handler>::emit_BindUnqualifiedGName() {
3678 if (tryOptimizeBindUnqualifiedGlobalName()) {
3679 return true;
3680 }
3681
3682 frame.syncStack(0);
3683 loadGlobalLexicalEnvironment(R0.scratchReg());
3684
3685 // Call IC.
3686 if (!emitNextIC()) {
3687 return false;
3688 }
3689
3690 // Mark R0 as pushed stack value.
3691 frame.push(R0);
3692 return true;
3693 }
3694
3695 template <typename Handler>
3696 bool BaselineCodeGen<Handler>::emit_BindVar() {
3697 frame.syncStack(0);
3698 masm.loadPtr(frame.addressOfEnvironmentChain(), R0.scratchReg());
3699
3700 prepareVMCall();
3701 pushArg(R0.scratchReg());
3702
3703 using Fn = JSObject* (*)(JSContext*, JSObject*);
3704 if (!callVM<Fn, BindVarOperation>()) {
3705 return false;
3706 }
3707
3708 masm.tagValue(JSVAL_TYPE_OBJECT, ReturnReg, R0);
3709 frame.push(R0);
3710 return true;
3711 }
3712
3713 template <typename Handler>
3714 bool BaselineCodeGen<Handler>::emit_SetProp() {
3715 // Keep lhs in R0, rhs in R1.
3716 frame.popRegsAndSync(2);
3717
3718 // Keep RHS on the stack.
3719 frame.push(R1);
3720 frame.syncStack(0);
3721
3722 // Call IC.
3723 if (!emitNextIC()) {
3724 return false;
3725 }
3726
3727 return true;
3728 }
3729
3730 template <typename Handler>
3731 bool BaselineCodeGen<Handler>::emit_StrictSetProp() {
3732 return emit_SetProp();
3733 }
3734
3735 template <typename Handler>
3736 bool BaselineCodeGen<Handler>::emit_SetName() {
3737 return emit_SetProp();
3738 }
3739
3740 template <typename Handler>
3741 bool BaselineCodeGen<Handler>::emit_StrictSetName() {
3742 return emit_SetProp();
3743 }
3744
3745 template <typename Handler>
3746 bool BaselineCodeGen<Handler>::emit_SetGName() {
3747 return emit_SetProp();
3748 }
3749
3750 template <typename Handler>
3751 bool BaselineCodeGen<Handler>::emit_StrictSetGName() {
3752 return emit_SetProp();
3753 }
3754
3755 template <typename Handler>
3756 bool BaselineCodeGen<Handler>::emitSetPropSuper(bool strict) {
3757 // Incoming stack is |receiver, obj, rval|. We need to shuffle stack to
3758 // leave rval when operation is complete.
3759
3760 // Pop rval into R0, then load receiver into R1 and replace with rval.
3761 frame.popRegsAndSync(1);
3762 masm.loadValue(frame.addressOfStackValue(-2), R1);
3763 masm.storeValue(R0, frame.addressOfStackValue(-2));
3764
3765 prepareVMCall();
3766
3767 pushArg(Imm32(strict));
3768 pushArg(R0); // rval
3769 pushScriptNameArg(R0.scratchReg(), R2.scratchReg());
3770 pushArg(R1); // receiver
3771 masm.loadValue(frame.addressOfStackValue(-1), R0);
3772 pushArg(R0); // obj
3773
3774 using Fn = bool (*)(JSContext*, HandleValue, HandleValue,
3775 Handle<PropertyName*>, HandleValue, bool);
3776 if (!callVM<Fn, js::SetPropertySuper>()) {
3777 return false;
3778 }
3779
3780 frame.pop();
3781 return true;
3782 }
3783
3784 template <typename Handler>
3785 bool BaselineCodeGen<Handler>::emit_SetPropSuper() {
3786 return emitSetPropSuper(/* strict = */ false);
3787 }
3788
3789 template <typename Handler>
3790 bool BaselineCodeGen<Handler>::emit_StrictSetPropSuper() {
3791 return emitSetPropSuper(/* strict = */ true);
3792 }
3793
3794 template <typename Handler>
3795 bool BaselineCodeGen<Handler>::emit_GetProp() {
3796 // Keep object in R0.
3797 frame.popRegsAndSync(1);
3798
3799 // Call IC.
3800 if (!emitNextIC()) {
3801 return false;
3802 }
3803
3804 // Mark R0 as pushed stack value.
3805 frame.push(R0);
3806 return true;
3807 }
3808
3809 template <typename Handler>
3810 bool BaselineCodeGen<Handler>::emit_GetBoundName() {
3811 return emit_GetProp();
3812 }
3813
3814 template <typename Handler>
3815 bool BaselineCodeGen<Handler>::emit_GetPropSuper() {
3816 // Receiver -> R1, ObjectOrNull -> R0
3817 frame.popRegsAndSync(1);
3818 masm.loadValue(frame.addressOfStackValue(-1), R1);
3819 frame.pop();
3820
3821 if (!emitNextIC()) {
3822 return false;
3823 }
3824
3825 frame.push(R0);
3826 return true;
3827 }
3828
3829 template <typename Handler>
3830 bool BaselineCodeGen<Handler>::emitDelProp(bool strict) {
3831 // Keep value on the stack for the decompiler.
3832 frame.syncStack(0);
3833 masm.loadValue(frame.addressOfStackValue(-1), R0);
3834
3835 prepareVMCall();
3836
3837 pushScriptNameArg(R1.scratchReg(), R2.scratchReg());
3838 pushArg(R0);
3839
3840 using Fn = bool (*)(JSContext*, HandleValue, Handle<PropertyName*>, bool*);
3841 if (strict) {
3842 if (!callVM<Fn, DelPropOperation<true>>()) {
3843 return false;
3844 }
3845 } else {
3846 if (!callVM<Fn, DelPropOperation<false>>()) {
3847 return false;
3848 }
3849 }
3850
3851 masm.boxNonDouble(JSVAL_TYPE_BOOLEAN, ReturnReg, R1);
3852 frame.pop();
3853 frame.push(R1, JSVAL_TYPE_BOOLEAN);
3854 return true;
3855 }
3856
3857 template <typename Handler>
3858 bool BaselineCodeGen<Handler>::emit_DelProp() {
3859 return emitDelProp(/* strict = */ false);
3860 }
3861
3862 template <typename Handler>
3863 bool BaselineCodeGen<Handler>::emit_StrictDelProp() {
3864 return emitDelProp(/* strict = */ true);
3865 }
3866
3867 template <>
3868 void BaselineCompilerCodeGen::getEnvironmentCoordinateObject(Register reg) {
3869 EnvironmentCoordinate ec(handler.pc());
3870
3871 masm.loadPtr(frame.addressOfEnvironmentChain(), reg);
3872 for (unsigned i = ec.hops(); i; i--) {
3873 masm.unboxObject(
3874 Address(reg, EnvironmentObject::offsetOfEnclosingEnvironment()), reg);
3875 }
3876 }
3877
3878 template <>
3879 void BaselineInterpreterCodeGen::getEnvironmentCoordinateObject(Register reg) {
3880 MOZ_CRASH("Shouldn't call this for interpreter");
3881 }
3882
3883 template <>
3884 Address BaselineCompilerCodeGen::getEnvironmentCoordinateAddressFromObject(
3885 Register objReg, Register reg) {
3886 EnvironmentCoordinate ec(handler.pc());
3887
3888 if (EnvironmentObject::nonExtensibleIsFixedSlot(ec)) {
3889 return Address(objReg, NativeObject::getFixedSlotOffset(ec.slot()));
3890 }
3891
3892 uint32_t slot = EnvironmentObject::nonExtensibleDynamicSlotIndex(ec);
3893 masm.loadPtr(Address(objReg, NativeObject::offsetOfSlots()), reg);
3894 return Address(reg, slot * sizeof(Value));
3895 }
3896
3897 template <>
3898 Address BaselineInterpreterCodeGen::getEnvironmentCoordinateAddressFromObject(
3899 Register objReg, Register reg) {
3900 MOZ_CRASH("Shouldn't call this for interpreter");
3901 }
3902
3903 template <typename Handler>
3904 Address BaselineCodeGen<Handler>::getEnvironmentCoordinateAddress(
3905 Register reg) {
3906 getEnvironmentCoordinateObject(reg);
3907 return getEnvironmentCoordinateAddressFromObject(reg, reg);
3908 }
3909
3910 // For a JOF_ENVCOORD op load the number of hops from the bytecode and skip this
3911 // number of environment objects.
3912 static void LoadAliasedVarEnv(MacroAssembler& masm, Register env,
3913 Register scratch) {
3914 static_assert(ENVCOORD_HOPS_LEN == 1,
3915 "Code assumes number of hops is stored in uint8 operand");
3916 LoadUint8Operand(masm, scratch);
3917
3918 Label top, done;
3919 masm.branchTest32(Assembler::Zero, scratch, scratch, &done);
3920 masm.bind(&top);
3921 {
3922 Address nextEnv(env, EnvironmentObject::offsetOfEnclosingEnvironment());
3923 masm.unboxObject(nextEnv, env);
3924 masm.branchSub32(Assembler::NonZero, Imm32(1), scratch, &top);
3925 }
3926 masm.bind(&done);
3927 }
3928
3929 template <>
3930 void BaselineCompilerCodeGen::emitGetAliasedVar(ValueOperand dest) {
3931 frame.syncStack(0);
3932
3933 Address address = getEnvironmentCoordinateAddress(R0.scratchReg());
3934 masm.loadValue(address, dest);
3935 }
3936
3937 template <>
3938 void BaselineInterpreterCodeGen::emitGetAliasedVar(ValueOperand dest) {
3939 Register env = R0.scratchReg();
3940 Register scratch = R1.scratchReg();
3941
3942 // Load the right environment object.
3943 masm.loadPtr(frame.addressOfEnvironmentChain(), env);
3944 LoadAliasedVarEnv(masm, env, scratch);
3945
3946 // Load the slot index.
3947 static_assert(ENVCOORD_SLOT_LEN == 3,
3948 "Code assumes slot is stored in uint24 operand");
3949 LoadUint24Operand(masm, ENVCOORD_HOPS_LEN, scratch);
3950
3951 // Load the Value from a fixed or dynamic slot.
3952 // See EnvironmentObject::nonExtensibleIsFixedSlot.
3953 Label isDynamic, done;
3954 masm.branch32(Assembler::AboveOrEqual, scratch,
3955 Imm32(NativeObject::MAX_FIXED_SLOTS), &isDynamic);
3956 {
3957 uint32_t offset = NativeObject::getFixedSlotOffset(0);
3958 masm.loadValue(BaseValueIndex(env, scratch, offset), dest);
3959 masm.jump(&done);
3960 }
3961 masm.bind(&isDynamic);
3962 {
3963 masm.loadPtr(Address(env, NativeObject::offsetOfSlots()), env);
3964
3965 // Use an offset to subtract the number of fixed slots.
3966 int32_t offset = -int32_t(NativeObject::MAX_FIXED_SLOTS * sizeof(Value));
3967 masm.loadValue(BaseValueIndex(env, scratch, offset), dest);
3968 }
3969 masm.bind(&done);
3970 }
3971
3972 template <typename Handler>
3973 bool BaselineCodeGen<Handler>::emitGetAliasedDebugVar(ValueOperand dest) {
3974 frame.syncStack(0);
3975 Register env = R0.scratchReg();
3976 // Load the right environment object.
3977 masm.loadPtr(frame.addressOfEnvironmentChain(), env);
3978
3979 prepareVMCall();
3980 pushBytecodePCArg();
3981 pushArg(env);
3982
3983 using Fn =
3984 bool (*)(JSContext*, JSObject* env, jsbytecode*, MutableHandleValue);
3985 return callVM<Fn, LoadAliasedDebugVar>();
3986 }
3987
3988 template <typename Handler>
3989 bool BaselineCodeGen<Handler>::emit_GetAliasedDebugVar() {
3990 if (!emitGetAliasedDebugVar(R0)) {
3991 return false;
3992 }
3993
3994 frame.push(R0);
3995 return true;
3996 }
3997
3998 template <typename Handler>
3999 bool BaselineCodeGen<Handler>::emit_GetAliasedVar() {
4000 emitGetAliasedVar(R0);
4001
4002 frame.push(R0);
4003 return true;
4004 }
4005
4006 template <>
4007 bool BaselineCompilerCodeGen::emit_SetAliasedVar() {
4008 // Keep rvalue in R0.
4009 frame.popRegsAndSync(1);
4010 Register objReg = R2.scratchReg();
4011
4012 getEnvironmentCoordinateObject(objReg);
4013 Address address =
4014 getEnvironmentCoordinateAddressFromObject(objReg, R1.scratchReg());
4015 masm.guardedCallPreBarrier(address, MIRType::Value);
4016 masm.storeValue(R0, address);
4017 frame.push(R0);
4018
4019 // Only R0 is live at this point.
4020 // Scope coordinate object is already in R2.scratchReg().
4021 Register temp = R1.scratchReg();
4022
4023 Label skipBarrier;
4024 masm.branchPtrInNurseryChunk(Assembler::Equal, objReg, temp, &skipBarrier);
4025 masm.branchValueIsNurseryCell(Assembler::NotEqual, R0, temp, &skipBarrier);
4026
4027 masm.call(&postBarrierSlot_); // Won't clobber R0
4028
4029 masm.bind(&skipBarrier);
4030 return true;
4031 }
4032
4033 template <>
4034 bool BaselineInterpreterCodeGen::emit_SetAliasedVar() {
4035 AllocatableGeneralRegisterSet regs(GeneralRegisterSet::All());
4036 MOZ_ASSERT(!regs.has(FramePointer));
4037 regs.take(R2);
4038 if (HasInterpreterPCReg()) {
4039 regs.take(InterpreterPCReg);
4040 }
4041
4042 Register env = regs.takeAny();
4043 Register scratch1 = regs.takeAny();
4044 Register scratch2 = regs.takeAny();
4045 Register scratch3 = regs.takeAny();
4046
4047 // Load the right environment object.
4048 masm.loadPtr(frame.addressOfEnvironmentChain(), env);
4049 LoadAliasedVarEnv(masm, env, scratch1);
4050
4051 // Load the slot index.
4052 static_assert(ENVCOORD_SLOT_LEN == 3,
4053 "Code assumes slot is stored in uint24 operand");
4054 LoadUint24Operand(masm, ENVCOORD_HOPS_LEN, scratch1);
4055
4056 // Store the RHS Value in R2.
4057 masm.loadValue(frame.addressOfStackValue(-1), R2);
4058
4059 // Load a pointer to the fixed or dynamic slot into scratch2. We want to call
4060 // guardedCallPreBarrierAnyZone once to avoid code bloat.
4061
4062 // See EnvironmentObject::nonExtensibleIsFixedSlot.
4063 Label isDynamic, done;
4064 masm.branch32(Assembler::AboveOrEqual, scratch1,
4065 Imm32(NativeObject::MAX_FIXED_SLOTS), &isDynamic);
4066 {
4067 uint32_t offset = NativeObject::getFixedSlotOffset(0);
4068 BaseValueIndex slotAddr(env, scratch1, offset);
4069 masm.computeEffectiveAddress(slotAddr, scratch2);
4070 masm.jump(&done);
4071 }
4072 masm.bind(&isDynamic);
4073 {
4074 masm.loadPtr(Address(env, NativeObject::offsetOfSlots()), scratch2);
4075
4076 // Use an offset to subtract the number of fixed slots.
4077 int32_t offset = -int32_t(NativeObject::MAX_FIXED_SLOTS * sizeof(Value));
4078 BaseValueIndex slotAddr(scratch2, scratch1, offset);
4079 masm.computeEffectiveAddress(slotAddr, scratch2);
4080 }
4081 masm.bind(&done);
4082
4083 // Pre-barrier and store.
4084 Address slotAddr(scratch2, 0);
4085 masm.guardedCallPreBarrierAnyZone(slotAddr, MIRType::Value, scratch3);
4086 masm.storeValue(R2, slotAddr);
4087
4088 // Post barrier.
4089 Label skipBarrier;
4090 masm.branchPtrInNurseryChunk(Assembler::Equal, env, scratch1, &skipBarrier);
4091 masm.branchValueIsNurseryCell(Assembler::NotEqual, R2, scratch1,
4092 &skipBarrier);
4093 {
4094 // Post barrier code expects the object in R2.
4095 masm.movePtr(env, R2.scratchReg());
4096 masm.call(&postBarrierSlot_);
4097 }
4098 masm.bind(&skipBarrier);
4099 return true;
4100 }
4101
4102 template <typename Handler>
4103 bool BaselineCodeGen<Handler>::emit_GetName() {
4104 frame.syncStack(0);
4105
4106 masm.loadPtr(frame.addressOfEnvironmentChain(), R0.scratchReg());
4107
4108 // Call IC.
4109 if (!emitNextIC()) {
4110 return false;
4111 }
4112
4113 // Mark R0 as pushed stack value.
4114 frame.push(R0);
4115 return true;
4116 }
4117
4118 template <typename Handler>
4119 bool BaselineCodeGen<Handler>::emit_BindUnqualifiedName() {
4120 frame.syncStack(0);
4121 masm.loadPtr(frame.addressOfEnvironmentChain(), R0.scratchReg());
4122
4123 // Call IC.
4124 if (!emitNextIC()) {
4125 return false;
4126 }
4127
4128 // Mark R0 as pushed stack value.
4129 frame.push(R0);
4130 return true;
4131 }
4132
4133 template <typename Handler>
4134 bool BaselineCodeGen<Handler>::emit_BindName() {
4135 frame.syncStack(0);
4136 masm.loadPtr(frame.addressOfEnvironmentChain(), R0.scratchReg());
4137
4138 // Call IC.
4139 if (!emitNextIC()) {
4140 return false;
4141 }
4142
4143 // Mark R0 as pushed stack value.
4144 frame.push(R0);
4145 return true;
4146 }
4147
4148 template <typename Handler>
4149 bool BaselineCodeGen<Handler>::emit_DelName() {
4150 frame.syncStack(0);
4151 masm.loadPtr(frame.addressOfEnvironmentChain(), R0.scratchReg());
4152
4153 prepareVMCall();
4154
4155 pushArg(R0.scratchReg());
4156 pushScriptNameArg(R1.scratchReg(), R2.scratchReg());
4157
4158 using Fn = bool (*)(JSContext*, Handle<PropertyName*>, HandleObject,
4159 MutableHandleValue);
4160 if (!callVM<Fn, js::DeleteNameOperation>()) {
4161 return false;
4162 }
4163
4164 frame.push(R0);
4165 return true;
4166 }
4167
4168 template <typename Handler>
4169 bool BaselineCodeGen<Handler>::emit_GetImport() {
4170 frame.syncStack(0);
4171
4172 if (!emitNextIC()) {
4173 return false;
4174 }
4175
4176 frame.push(R0);
4177 return true;
4178 }
4179
4180 template <typename Handler>
4181 bool BaselineCodeGen<Handler>::emit_GetIntrinsic() {
4182 frame.syncStack(0);
4183
4184 if (!emitNextIC()) {
4185 return false;
4186 }
4187
4188 frame.push(R0);
4189 return true;
4190 }
4191
4192 template <typename Handler>
4193 bool BaselineCodeGen<Handler>::emit_SetIntrinsic() {
4194 frame.syncStack(0);
4195 masm.loadValue(frame.addressOfStackValue(-1), R0);
4196
4197 prepareVMCall();
4198
4199 pushArg(R0);
4200 pushBytecodePCArg();
4201 pushScriptArg();
4202
4203 using Fn = bool (*)(JSContext*, JSScript*, jsbytecode*, HandleValue);
4204 return callVM<Fn, SetIntrinsicOperation>();
4205 }
4206
4207 template <typename Handler>
4208 bool BaselineCodeGen<Handler>::emit_GlobalOrEvalDeclInstantiation() {
4209 frame.syncStack(0);
4210
4211 prepareVMCall();
4212
4213 loadInt32LengthBytecodeOperand(R0.scratchReg());
4214 pushArg(R0.scratchReg());
4215 pushScriptArg();
4216 masm.loadPtr(frame.addressOfEnvironmentChain(), R0.scratchReg());
4217 pushArg(R0.scratchReg());
4218
4219 using Fn = bool (*)(JSContext*, HandleObject, HandleScript, GCThingIndex);
4220 return callVM<Fn, js::GlobalOrEvalDeclInstantiation>();
4221 }
4222
4223 template <typename Handler>
4224 bool BaselineCodeGen<Handler>::emitInitPropGetterSetter() {
4225 // Keep values on the stack for the decompiler.
4226 frame.syncStack(0);
4227
4228 prepareVMCall();
4229
4230 masm.unboxObject(frame.addressOfStackValue(-1), R0.scratchReg());
4231 masm.unboxObject(frame.addressOfStackValue(-2), R1.scratchReg());
4232
4233 pushArg(R0.scratchReg());
4234 pushScriptNameArg(R0.scratchReg(), R2.scratchReg());
4235 pushArg(R1.scratchReg());
4236 pushBytecodePCArg();
4237
4238 using Fn = bool (*)(JSContext*, jsbytecode*, HandleObject,
4239 Handle<PropertyName*>, HandleObject);
4240 if (!callVM<Fn, InitPropGetterSetterOperation>()) {
4241 return false;
4242 }
4243
4244 frame.pop();
4245 return true;
4246 }
4247
4248 template <typename Handler>
4249 bool BaselineCodeGen<Handler>::emit_InitPropGetter() {
4250 return emitInitPropGetterSetter();
4251 }
4252
4253 template <typename Handler>
4254 bool BaselineCodeGen<Handler>::emit_InitHiddenPropGetter() {
4255 return emitInitPropGetterSetter();
4256 }
4257
4258 template <typename Handler>
4259 bool BaselineCodeGen<Handler>::emit_InitPropSetter() {
4260 return emitInitPropGetterSetter();
4261 }
4262
4263 template <typename Handler>
4264 bool BaselineCodeGen<Handler>::emit_InitHiddenPropSetter() {
4265 return emitInitPropGetterSetter();
4266 }
4267
4268 template <typename Handler>
4269 bool BaselineCodeGen<Handler>::emitInitElemGetterSetter() {
4270 // Load index and value in R0 and R1, but keep values on the stack for the
4271 // decompiler.
4272 frame.syncStack(0);
4273 masm.loadValue(frame.addressOfStackValue(-2), R0);
4274 masm.unboxObject(frame.addressOfStackValue(-1), R1.scratchReg());
4275
4276 prepareVMCall();
4277
4278 pushArg(R1.scratchReg());
4279 pushArg(R0);
4280 masm.unboxObject(frame.addressOfStackValue(-3), R0.scratchReg());
4281 pushArg(R0.scratchReg());
4282 pushBytecodePCArg();
4283
4284 using Fn = bool (*)(JSContext*, jsbytecode*, HandleObject, HandleValue,
4285 HandleObject);
4286 if (!callVM<Fn, InitElemGetterSetterOperation>()) {
4287 return false;
4288 }
4289
4290 frame.popn(2);
4291 return true;
4292 }
4293
4294 template <typename Handler>
4295 bool BaselineCodeGen<Handler>::emit_InitElemGetter() {
4296 return emitInitElemGetterSetter();
4297 }
4298
4299 template <typename Handler>
4300 bool BaselineCodeGen<Handler>::emit_InitHiddenElemGetter() {
4301 return emitInitElemGetterSetter();
4302 }
4303
4304 template <typename Handler>
4305 bool BaselineCodeGen<Handler>::emit_InitElemSetter() {
4306 return emitInitElemGetterSetter();
4307 }
4308
4309 template <typename Handler>
4310 bool BaselineCodeGen<Handler>::emit_InitHiddenElemSetter() {
4311 return emitInitElemGetterSetter();
4312 }
4313
4314 template <typename Handler>
4315 bool BaselineCodeGen<Handler>::emit_InitElemInc() {
4316 // Keep the object and rhs on the stack.
4317 frame.syncStack(0);
4318
4319 // Load object in R0, index in R1.
4320 masm.loadValue(frame.addressOfStackValue(-3), R0);
4321 masm.loadValue(frame.addressOfStackValue(-2), R1);
4322
4323 // Call IC.
4324 if (!emitNextIC()) {
4325 return false;
4326 }
4327
4328 // Pop the rhs
4329 frame.pop();
4330
4331 // Increment index
4332 Address indexAddr = frame.addressOfStackValue(-1);
4333 #ifdef DEBUG
4334 Label isInt32;
4335 masm.branchTestInt32(Assembler::Equal, indexAddr, &isInt32);
4336 masm.assumeUnreachable("INITELEM_INC index must be Int32");
4337 masm.bind(&isInt32);
4338 #endif
4339 masm.incrementInt32Value(indexAddr);
4340 return true;
4341 }
4342
4343 template <>
4344 bool BaselineCompilerCodeGen::emit_GetLocal() {
4345 frame.pushLocal(GET_LOCALNO(handler.pc()));
4346 return true;
4347 }
4348
4349 static BaseValueIndex ComputeAddressOfLocal(MacroAssembler& masm,
4350 Register indexScratch) {
4351 // Locals are stored in memory at a negative offset from the frame pointer. We
4352 // negate the index first to effectively subtract it.
4353 masm.negPtr(indexScratch);
4354 return BaseValueIndex(FramePointer, indexScratch,
4355 BaselineFrame::reverseOffsetOfLocal(0));
4356 }
4357
4358 template <>
4359 bool BaselineInterpreterCodeGen::emit_GetLocal() {
4360 Register scratch = R0.scratchReg();
4361 LoadUint24Operand(masm, 0, scratch);
4362 BaseValueIndex addr = ComputeAddressOfLocal(masm, scratch);
4363 masm.loadValue(addr, R0);
4364 frame.push(R0);
4365 return true;
4366 }
4367
4368 template <>
4369 bool BaselineCompilerCodeGen::emit_SetLocal() {
4370 // Ensure no other StackValue refers to the old value, for instance i + (i =
4371 // 3). This also allows us to use R0 as scratch below.
4372 frame.syncStack(1);
4373
4374 uint32_t local = GET_LOCALNO(handler.pc());
4375 frame.storeStackValue(-1, frame.addressOfLocal(local), R0);
4376 return true;
4377 }
4378
4379 template <>
4380 bool BaselineInterpreterCodeGen::emit_SetLocal() {
4381 Register scratch = R0.scratchReg();
4382 LoadUint24Operand(masm, 0, scratch);
4383 BaseValueIndex addr = ComputeAddressOfLocal(masm, scratch);
4384 masm.loadValue(frame.addressOfStackValue(-1), R1);
4385 masm.storeValue(R1, addr);
4386 return true;
4387 }
4388
4389 template <>
4390 bool BaselineCompilerCodeGen::emitFormalArgAccess(JSOp op) {
4391 MOZ_ASSERT(op == JSOp::GetArg || op == JSOp::SetArg);
4392
4393 uint32_t arg = GET_ARGNO(handler.pc());
4394
4395 // Fast path: the script does not use |arguments| or formals don't
4396 // alias the arguments object.
4397 if (!handler.script()->argsObjAliasesFormals()) {
4398 if (op == JSOp::GetArg) {
4399 frame.pushArg(arg);
4400 } else {
4401 // See the comment in emit_SetLocal.
4402 frame.syncStack(1);
4403 frame.storeStackValue(-1, frame.addressOfArg(arg), R0);
4404 }
4405
4406 return true;
4407 }
4408
4409 // Sync so that we can use R0.
4410 frame.syncStack(0);
4411
4412 // Load the arguments object data vector.
4413 Register reg = R2.scratchReg();
4414 masm.loadPtr(frame.addressOfArgsObj(), reg);
4415 masm.loadPrivate(Address(reg, ArgumentsObject::getDataSlotOffset()), reg);
4416
4417 // Load/store the argument.
4418 Address argAddr(reg, ArgumentsData::offsetOfArgs() + arg * sizeof(Value));
4419 if (op == JSOp::GetArg) {
4420 masm.loadValue(argAddr, R0);
4421 frame.push(R0);
4422 } else {
4423 Register temp = R1.scratchReg();
4424 masm.guardedCallPreBarrierAnyZone(argAddr, MIRType::Value, temp);
4425 masm.loadValue(frame.addressOfStackValue(-1), R0);
4426 masm.storeValue(R0, argAddr);
4427
4428 MOZ_ASSERT(frame.numUnsyncedSlots() == 0);
4429
4430 // Reload the arguments object.
4431 Register reg = R2.scratchReg();
4432 masm.loadPtr(frame.addressOfArgsObj(), reg);
4433
4434 Label skipBarrier;
4435
4436 masm.branchPtrInNurseryChunk(Assembler::Equal, reg, temp, &skipBarrier);
4437 masm.branchValueIsNurseryCell(Assembler::NotEqual, R0, temp, &skipBarrier);
4438
4439 masm.call(&postBarrierSlot_);
4440
4441 masm.bind(&skipBarrier);
4442 }
4443
4444 return true;
4445 }
4446
4447 template <>
4448 bool BaselineInterpreterCodeGen::emitFormalArgAccess(JSOp op) {
4449 MOZ_ASSERT(op == JSOp::GetArg || op == JSOp::SetArg);
4450
4451 // Load the index.
4452 Register argReg = R1.scratchReg();
4453 LoadUint16Operand(masm, argReg);
4454
4455 // If the frame has no arguments object, this must be an unaliased access.
4456 Label isUnaliased, done;
4457 masm.branchTest32(Assembler::Zero, frame.addressOfFlags(),
4458 Imm32(BaselineFrame::HAS_ARGS_OBJ), &isUnaliased);
4459 {
4460 Register reg = R2.scratchReg();
4461
4462 // If it's an unmapped arguments object, this is an unaliased access.
4463 loadScript(reg);
4464 masm.branchTest32(
4465 Assembler::Zero, Address(reg, JSScript::offsetOfImmutableFlags()),
4466 Imm32(uint32_t(JSScript::ImmutableFlags::HasMappedArgsObj)),
4467 &isUnaliased);
4468
4469 // Load the arguments object data vector.
4470 masm.loadPtr(frame.addressOfArgsObj(), reg);
4471 masm.loadPrivate(Address(reg, ArgumentsObject::getDataSlotOffset()), reg);
4472
4473 // Load/store the argument.
4474 BaseValueIndex argAddr(reg, argReg, ArgumentsData::offsetOfArgs());
4475 if (op == JSOp::GetArg) {
4476 masm.loadValue(argAddr, R0);
4477 frame.push(R0);
4478 } else {
4479 masm.guardedCallPreBarrierAnyZone(argAddr, MIRType::Value,
4480 R0.scratchReg());
4481 masm.loadValue(frame.addressOfStackValue(-1), R0);
4482 masm.storeValue(R0, argAddr);
4483
4484 // Reload the arguments object.
4485 masm.loadPtr(frame.addressOfArgsObj(), reg);
4486
4487 Register temp = R1.scratchReg();
4488 masm.branchPtrInNurseryChunk(Assembler::Equal, reg, temp, &done);
4489 masm.branchValueIsNurseryCell(Assembler::NotEqual, R0, temp, &done);
4490
4491 masm.call(&postBarrierSlot_);
4492 }
4493 masm.jump(&done);
4494 }
4495 masm.bind(&isUnaliased);
4496 {
4497 BaseValueIndex addr(FramePointer, argReg,
4498 JitFrameLayout::offsetOfActualArgs());
4499 if (op == JSOp::GetArg) {
4500 masm.loadValue(addr, R0);
4501 frame.push(R0);
4502 } else {
4503 masm.loadValue(frame.addressOfStackValue(-1), R0);
4504 masm.storeValue(R0, addr);
4505 }
4506 }
4507
4508 masm.bind(&done);
4509 return true;
4510 }
4511
4512 template <typename Handler>
4513 bool BaselineCodeGen<Handler>::emit_GetArg() {
4514 return emitFormalArgAccess(JSOp::GetArg);
4515 }
4516
4517 template <typename Handler>
4518 bool BaselineCodeGen<Handler>::emit_SetArg() {
4519 return emitFormalArgAccess(JSOp::SetArg);
4520 }
4521
4522 template <>
4523 bool BaselineInterpreterCodeGen::emit_GetFrameArg() {
4524 frame.syncStack(0);
4525
4526 Register argReg = R1.scratchReg();
4527 LoadUint16Operand(masm, argReg);
4528
4529 BaseValueIndex addr(FramePointer, argReg,
4530 JitFrameLayout::offsetOfActualArgs());
4531 masm.loadValue(addr, R0);
4532 frame.push(R0);
4533 return true;
4534 }
4535
4536 template <>
4537 bool BaselineCompilerCodeGen::emit_GetFrameArg() {
4538 uint32_t arg = GET_ARGNO(handler.pc());
4539 frame.pushArg(arg);
4540 return true;
4541 }
4542
4543 template <typename Handler>
4544 bool BaselineCodeGen<Handler>::emit_ArgumentsLength() {
4545 frame.syncStack(0);
4546
4547 masm.loadNumActualArgs(FramePointer, R0.scratchReg());
4548 masm.tagValue(JSVAL_TYPE_INT32, R0.scratchReg(), R0);
4549
4550 frame.push(R0);
4551 return true;
4552 }
4553
4554 template <typename Handler>
4555 bool BaselineCodeGen<Handler>::emit_GetActualArg() {
4556 frame.popRegsAndSync(1);
4557
4558 #ifdef DEBUG
4559 {
4560 Label ok;
4561 masm.branchTestInt32(Assembler::Equal, R0, &ok);
4562 masm.assumeUnreachable("GetActualArg unexpected type");
4563 masm.bind(&ok);
4564 }
4565 #endif
4566
4567 Register index = R0.scratchReg();
4568 masm.unboxInt32(R0, index);
4569
4570 #ifdef DEBUG
4571 {
4572 Label ok;
4573 masm.loadNumActualArgs(FramePointer, R1.scratchReg());
4574 masm.branch32(Assembler::Above, R1.scratchReg(), index, &ok);
4575 masm.assumeUnreachable("GetActualArg invalid index");
4576 masm.bind(&ok);
4577 }
4578 #endif
4579
4580 BaseValueIndex addr(FramePointer, index,
4581 JitFrameLayout::offsetOfActualArgs());
4582 masm.loadValue(addr, R0);
4583 frame.push(R0);
4584 return true;
4585 }
4586
4587 template <>
4588 void BaselineCompilerCodeGen::loadNumFormalArguments(Register dest) {
4589 masm.move32(Imm32(handler.function()->nargs()), dest);
4590 }
4591
4592 template <>
4593 void BaselineInterpreterCodeGen::loadNumFormalArguments(Register dest) {
4594 masm.loadFunctionFromCalleeToken(frame.addressOfCalleeToken(), dest);
4595 masm.loadFunctionArgCount(dest, dest);
4596 }
4597
4598 template <typename Handler>
4599 bool BaselineCodeGen<Handler>::emit_NewTarget() {
4600 MOZ_ASSERT_IF(handler.maybeFunction(), !handler.maybeFunction()->isArrow());
4601
4602 frame.syncStack(0);
4603
4604 #ifdef DEBUG
4605 Register scratch1 = R0.scratchReg();
4606 Register scratch2 = R1.scratchReg();
4607
4608 Label isFunction;
4609 masm.loadPtr(frame.addressOfCalleeToken(), scratch1);
4610 masm.branchTestPtr(Assembler::Zero, scratch1, Imm32(CalleeTokenScriptBit),
4611 &isFunction);
4612 masm.assumeUnreachable("Unexpected non-function script");
4613 masm.bind(&isFunction);
4614
4615 Label notArrow;
4616 masm.andPtr(Imm32(uint32_t(CalleeTokenMask)), scratch1);
4617 masm.branchFunctionKind(Assembler::NotEqual,
4618 FunctionFlags::FunctionKind::Arrow, scratch1,
4619 scratch2, &notArrow);
4620 masm.assumeUnreachable("Unexpected arrow function");
4621 masm.bind(&notArrow);
4622 #endif
4623
4624 // if (isConstructing()) push(argv[Max(numActualArgs, numFormalArgs)])
4625 Label notConstructing, done;
4626 masm.branchTestPtr(Assembler::Zero, frame.addressOfCalleeToken(),
4627 Imm32(CalleeToken_FunctionConstructing), &notConstructing);
4628 {
4629 Register argvLen = R0.scratchReg();
4630 Register nformals = R1.scratchReg();
4631 masm.loadNumActualArgs(FramePointer, argvLen);
4632
4633 // If argvLen < nformals, set argvlen := nformals.
4634 loadNumFormalArguments(nformals);
4635 masm.cmp32Move32(Assembler::Below, argvLen, nformals, nformals, argvLen);
4636
4637 BaseValueIndex newTarget(FramePointer, argvLen,
4638 JitFrameLayout::offsetOfActualArgs());
4639 masm.loadValue(newTarget, R0);
4640 masm.jump(&done);
4641 }
4642 // else push(undefined)
4643 masm.bind(&notConstructing);
4644 masm.moveValue(UndefinedValue(), R0);
4645
4646 masm.bind(&done);
4647 frame.push(R0);
4648 return true;
4649 }
4650
4651 template <typename Handler>
4652 bool BaselineCodeGen<Handler>::emit_ThrowSetConst() {
4653 prepareVMCall();
4654 pushArg(Imm32(JSMSG_BAD_CONST_ASSIGN));
4655
4656 using Fn = bool (*)(JSContext*, unsigned);
4657 return callVM<Fn, jit::ThrowRuntimeLexicalError>();
4658 }
4659
4660 template <typename Handler>
4661 bool BaselineCodeGen<Handler>::emitUninitializedLexicalCheck(
4662 const ValueOperand& val) {
4663 Label done;
4664 masm.branchTestMagicValue(Assembler::NotEqual, val, JS_UNINITIALIZED_LEXICAL,
4665 &done);
4666
4667 prepareVMCall();
4668 pushArg(Imm32(JSMSG_UNINITIALIZED_LEXICAL));
4669
4670 using Fn = bool (*)(JSContext*, unsigned);
4671 if (!callVM<Fn, jit::ThrowRuntimeLexicalError>()) {
4672 return false;
4673 }
4674
4675 masm.bind(&done);
4676 return true;
4677 }
4678
4679 template <typename Handler>
4680 bool BaselineCodeGen<Handler>::emit_CheckLexical() {
4681 frame.syncStack(0);
4682 masm.loadValue(frame.addressOfStackValue(-1), R0);
4683 return emitUninitializedLexicalCheck(R0);
4684 }
4685
4686 template <typename Handler>
4687 bool BaselineCodeGen<Handler>::emit_CheckAliasedLexical() {
4688 return emit_CheckLexical();
4689 }
4690
4691 template <typename Handler>
4692 bool BaselineCodeGen<Handler>::emit_InitLexical() {
4693 return emit_SetLocal();
4694 }
4695
4696 template <typename Handler>
4697 bool BaselineCodeGen<Handler>::emit_InitGLexical() {
4698 frame.popRegsAndSync(1);
4699 pushGlobalLexicalEnvironmentValue(R1);
4700 frame.push(R0);
4701 return emit_SetProp();
4702 }
4703
4704 template <typename Handler>
4705 bool BaselineCodeGen<Handler>::emit_InitAliasedLexical() {
4706 return emit_SetAliasedVar();
4707 }
4708
4709 template <typename Handler>
4710 bool BaselineCodeGen<Handler>::emit_Uninitialized() {
4711 frame.push(MagicValue(JS_UNINITIALIZED_LEXICAL));
4712 return true;
4713 }
4714
4715 template <>
4716 bool BaselineCompilerCodeGen::emitCall(JSOp op) {
4717 MOZ_ASSERT(IsInvokeOp(op));
4718
4719 frame.syncStack(0);
4720
4721 uint32_t argc = GET_ARGC(handler.pc());
4722 masm.move32(Imm32(argc), R0.scratchReg());
4723
4724 // Call IC
4725 if (!emitNextIC()) {
4726 return false;
4727 }
4728
4729 // Update FrameInfo.
4730 bool construct = IsConstructOp(op);
4731 frame.popn(2 + argc + construct);
4732 frame.push(R0);
4733 return true;
4734 }
4735
4736 template <>
4737 bool BaselineInterpreterCodeGen::emitCall(JSOp op) {
4738 MOZ_ASSERT(IsInvokeOp(op));
4739
4740 // The IC expects argc in R0.
4741 LoadUint16Operand(masm, R0.scratchReg());
4742 if (!emitNextIC()) {
4743 return false;
4744 }
4745
4746 // Pop the arguments. We have to reload pc/argc because the IC clobbers them.
4747 // The return value is in R0 so we can't use that.
4748 Register scratch = R1.scratchReg();
4749 uint32_t extraValuesToPop = IsConstructOp(op) ? 3 : 2;
4750 Register spReg = AsRegister(masm.getStackPointer());
4751 LoadUint16Operand(masm, scratch);
4752 masm.computeEffectiveAddress(
4753 BaseValueIndex(spReg, scratch, extraValuesToPop * sizeof(Value)), spReg);
4754 frame.push(R0);
4755 return true;
4756 }
4757
4758 template <typename Handler>
4759 bool BaselineCodeGen<Handler>::emitSpreadCall(JSOp op) {
4760 MOZ_ASSERT(IsInvokeOp(op));
4761
4762 frame.syncStack(0);
4763 masm.move32(Imm32(1), R0.scratchReg());
4764
4765 // Call IC
4766 if (!emitNextIC()) {
4767 return false;
4768 }
4769
4770 // Update FrameInfo.
4771 bool construct = op == JSOp::SpreadNew || op == JSOp::SpreadSuperCall;
4772 frame.popn(3 + construct);
4773 frame.push(R0);
4774 return true;
4775 }
4776
4777 template <typename Handler>
4778 bool BaselineCodeGen<Handler>::emit_Call() {
4779 return emitCall(JSOp::Call);
4780 }
4781
4782 template <typename Handler>
4783 bool BaselineCodeGen<Handler>::emit_CallContent() {
4784 return emitCall(JSOp::CallContent);
4785 }
4786
4787 template <typename Handler>
4788 bool BaselineCodeGen<Handler>::emit_CallIgnoresRv() {
4789 return emitCall(JSOp::CallIgnoresRv);
4790 }
4791
4792 template <typename Handler>
4793 bool BaselineCodeGen<Handler>::emit_CallIter() {
4794 return emitCall(JSOp::CallIter);
4795 }
4796
4797 template <typename Handler>
4798 bool BaselineCodeGen<Handler>::emit_CallContentIter() {
4799 return emitCall(JSOp::CallContentIter);
4800 }
4801
4802 template <typename Handler>
4803 bool BaselineCodeGen<Handler>::emit_New() {
4804 return emitCall(JSOp::New);
4805 }
4806
4807 template <typename Handler>
4808 bool BaselineCodeGen<Handler>::emit_NewContent() {
4809 return emitCall(JSOp::NewContent);
4810 }
4811
4812 template <typename Handler>
4813 bool BaselineCodeGen<Handler>::emit_SuperCall() {
4814 return emitCall(JSOp::SuperCall);
4815 }
4816
4817 template <typename Handler>
4818 bool BaselineCodeGen<Handler>::emit_Eval() {
4819 return emitCall(JSOp::Eval);
4820 }
4821
4822 template <typename Handler>
4823 bool BaselineCodeGen<Handler>::emit_StrictEval() {
4824 return emitCall(JSOp::StrictEval);
4825 }
4826
4827 template <typename Handler>
4828 bool BaselineCodeGen<Handler>::emit_SpreadCall() {
4829 return emitSpreadCall(JSOp::SpreadCall);
4830 }
4831
4832 template <typename Handler>
4833 bool BaselineCodeGen<Handler>::emit_SpreadNew() {
4834 return emitSpreadCall(JSOp::SpreadNew);
4835 }
4836
4837 template <typename Handler>
4838 bool BaselineCodeGen<Handler>::emit_SpreadSuperCall() {
4839 return emitSpreadCall(JSOp::SpreadSuperCall);
4840 }
4841
4842 template <typename Handler>
4843 bool BaselineCodeGen<Handler>::emit_SpreadEval() {
4844 return emitSpreadCall(JSOp::SpreadEval);
4845 }
4846
4847 template <typename Handler>
4848 bool BaselineCodeGen<Handler>::emit_StrictSpreadEval() {
4849 return emitSpreadCall(JSOp::StrictSpreadEval);
4850 }
4851
4852 template <typename Handler>
4853 bool BaselineCodeGen<Handler>::emit_OptimizeSpreadCall() {
4854 frame.popRegsAndSync(1);
4855
4856 if (!emitNextIC()) {
4857 return false;
4858 }
4859
4860 frame.push(R0);
4861 return true;
4862 }
4863
4864 template <typename Handler>
4865 bool BaselineCodeGen<Handler>::emit_ImplicitThis() {
4866 frame.popRegsAndSync(1);
4867
4868 Register env = R1.scratchReg();
4869 masm.unboxObject(R0, env);
4870
4871 Label slowPath, skipCall;
4872 masm.computeImplicitThis(env, R0, &slowPath);
4873 masm.jump(&skipCall);
4874
4875 masm.bind(&slowPath);
4876 {
4877 prepareVMCall();
4878
4879 pushArg(env);
4880
4881 using Fn = void (*)(JSContext*, HandleObject, MutableHandleValue);
4882 if (!callVM<Fn, ImplicitThisOperation>()) {
4883 return false;
4884 }
4885 }
4886
4887 masm.bind(&skipCall);
4888 frame.push(R0);
4889 return true;
4890 }
4891
4892 template <typename Handler>
4893 bool BaselineCodeGen<Handler>::emit_Instanceof() {
4894 frame.popRegsAndSync(2);
4895
4896 if (!emitNextIC()) {
4897 return false;
4898 }
4899
4900 frame.push(R0, JSVAL_TYPE_BOOLEAN);
4901 return true;
4902 }
4903
4904 template <typename Handler>
4905 bool BaselineCodeGen<Handler>::emit_Typeof() {
4906 frame.popRegsAndSync(1);
4907
4908 if (!emitNextIC()) {
4909 return false;
4910 }
4911
4912 frame.push(R0);
4913 return true;
4914 }
4915
4916 template <typename Handler>
4917 bool BaselineCodeGen<Handler>::emit_TypeofExpr() {
4918 return emit_Typeof();
4919 }
4920
4921 template <typename Handler>
4922 bool BaselineCodeGen<Handler>::emit_TypeofEq() {
4923 frame.popRegsAndSync(1);
4924
4925 if (!emitNextIC()) {
4926 return false;
4927 }
4928
4929 frame.push(R0);
4930 return true;
4931 }
4932
4933 template <typename Handler>
4934 bool BaselineCodeGen<Handler>::emit_ThrowMsg() {
4935 prepareVMCall();
4936 pushUint8BytecodeOperandArg(R2.scratchReg());
4937
4938 using Fn = bool (*)(JSContext*, const unsigned);
4939 return callVM<Fn, js::ThrowMsgOperation>();
4940 }
4941
4942 template <typename Handler>
4943 bool BaselineCodeGen<Handler>::emit_Throw() {
4944 // Keep value to throw in R0.
4945 frame.popRegsAndSync(1);
4946
4947 prepareVMCall();
4948 pushArg(R0);
4949
4950 using Fn = bool (*)(JSContext*, HandleValue);
4951 return callVM<Fn, js::ThrowOperation>();
4952 }
4953
4954 template <typename Handler>
4955 bool BaselineCodeGen<Handler>::emit_ThrowWithStack() {
4956 // Keep value to throw in R0 and the stack in R1.
4957 frame.popRegsAndSync(2);
4958
4959 prepareVMCall();
4960 pushArg(R1);
4961 pushArg(R0);
4962
4963 using Fn = bool (*)(JSContext*, HandleValue, HandleValue);
4964 return callVM<Fn, js::ThrowWithStackOperation>();
4965 }
4966
4967 template <typename Handler>
4968 bool BaselineCodeGen<Handler>::emit_Try() {
4969 return true;
4970 }
4971
4972 template <typename Handler>
4973 bool BaselineCodeGen<Handler>::emit_Finally() {
4974 // To match the interpreter, emit an interrupt check at the start of the
4975 // finally block.
4976 return emitInterruptCheck();
4977 }
4978
4979 template <typename Handler>
4980 void BaselineCodeGen<Handler>::loadBaselineScriptResumeEntries(
4981 Register dest, Register scratch) {
4982 MOZ_ASSERT(dest != scratch);
4983
4984 loadJitScript(dest);
4985 masm.loadPtr(Address(dest, JitScript::offsetOfBaselineScript()), dest);
4986 masm.load32(Address(dest, BaselineScript::offsetOfResumeEntriesOffset()),
4987 scratch);
4988 masm.addPtr(scratch, dest);
4989 }
4990
4991 template <typename Handler>
4992 void BaselineCodeGen<Handler>::emitInterpJumpToResumeEntry(Register script,
4993 Register resumeIndex,
4994 Register scratch) {
4995 // Load JSScript::immutableScriptData() into |script|.
4996 masm.loadPtr(Address(script, JSScript::offsetOfSharedData()), script);
4997 masm.loadPtr(Address(script, SharedImmutableScriptData::offsetOfISD()),
4998 script);
4999
5000 // Load the resume pcOffset in |resumeIndex|.
5001 masm.load32(
5002 Address(script, ImmutableScriptData::offsetOfResumeOffsetsOffset()),
5003 scratch);
5004 masm.computeEffectiveAddress(BaseIndex(scratch, resumeIndex, TimesFour),
5005 scratch);
5006 masm.load32(BaseIndex(script, scratch, TimesOne), resumeIndex);
5007
5008 // Add resume offset to PC, jump to it.
5009 masm.computeEffectiveAddress(BaseIndex(script, resumeIndex, TimesOne,
5010 ImmutableScriptData::offsetOfCode()),
5011 script);
5012 Address pcAddr(FramePointer, BaselineFrame::reverseOffsetOfInterpreterPC());
5013 masm.storePtr(script, pcAddr);
5014 emitJumpToInterpretOpLabel();
5015 }
5016
5017 template <>
5018 void BaselineCompilerCodeGen::jumpToResumeEntry(Register resumeIndex,
5019 Register scratch1,
5020 Register scratch2) {
5021 loadBaselineScriptResumeEntries(scratch1, scratch2);
5022 masm.loadPtr(
5023 BaseIndex(scratch1, resumeIndex, ScaleFromElemWidth(sizeof(uintptr_t))),
5024 scratch1);
5025 masm.jump(scratch1);
5026 }
5027
5028 template <>
5029 void BaselineInterpreterCodeGen::jumpToResumeEntry(Register resumeIndex,
5030 Register scratch1,
5031 Register scratch2) {
5032 loadScript(scratch1);
5033 emitInterpJumpToResumeEntry(scratch1, resumeIndex, scratch2);
5034 }
5035
5036 template <>
5037 template <typename F1, typename F2>
5038 [[nodiscard]] bool BaselineCompilerCodeGen::emitDebugInstrumentation(
5039 const F1& ifDebuggee, const Maybe<F2>& ifNotDebuggee) {
5040 // The JIT calls either ifDebuggee or (if present) ifNotDebuggee, because it
5041 // knows statically whether we're compiling with debug instrumentation.
5042
5043 if (handler.compileDebugInstrumentation()) {
5044 return ifDebuggee();
5045 }
5046
5047 if (ifNotDebuggee) {
5048 return (*ifNotDebuggee)();
5049 }
5050
5051 return true;
5052 }
5053
5054 template <>
5055 template <typename F1, typename F2>
5056 [[nodiscard]] bool BaselineInterpreterCodeGen::emitDebugInstrumentation(
5057 const F1& ifDebuggee, const Maybe<F2>& ifNotDebuggee) {
5058 // The interpreter emits both ifDebuggee and (if present) ifNotDebuggee
5059 // paths, with a toggled jump followed by a branch on the frame's DEBUGGEE
5060 // flag.
5061
5062 Label isNotDebuggee, done;
5063
5064 CodeOffset toggleOffset = masm.toggledJump(&isNotDebuggee);
5065 if (!handler.addDebugInstrumentationOffset(toggleOffset)) {
5066 return false;
5067 }
5068
5069 masm.branchTest32(Assembler::Zero, frame.addressOfFlags(),
5070 Imm32(BaselineFrame::DEBUGGEE), &isNotDebuggee);
5071
5072 if (!ifDebuggee()) {
5073 return false;
5074 }
5075
5076 if (ifNotDebuggee) {
5077 masm.jump(&done);
5078 }
5079
5080 masm.bind(&isNotDebuggee);
5081
5082 if (ifNotDebuggee && !(*ifNotDebuggee)()) {
5083 return false;
5084 }
5085
5086 masm.bind(&done);
5087 return true;
5088 }
5089
5090 template <typename Handler>
5091 bool BaselineCodeGen<Handler>::emit_PushLexicalEnv() {
5092 // Call a stub to push the block on the block chain.
5093 prepareVMCall();
5094 masm.loadBaselineFramePtr(FramePointer, R0.scratchReg());
5095
5096 pushScriptGCThingArg(ScriptGCThingType::Scope, R1.scratchReg(),
5097 R2.scratchReg());
5098 pushArg(R0.scratchReg());
5099
5100 using Fn = bool (*)(JSContext*, BaselineFrame*, Handle<LexicalScope*>);
5101 return callVM<Fn, jit::PushLexicalEnv>();
5102 }
5103
5104 template <typename Handler>
5105 bool BaselineCodeGen<Handler>::emit_PushClassBodyEnv() {
5106 prepareVMCall();
5107 masm.loadBaselineFramePtr(FramePointer, R0.scratchReg());
5108
5109 pushScriptGCThingArg(ScriptGCThingType::Scope, R1.scratchReg(),
5110 R2.scratchReg());
5111 pushArg(R0.scratchReg());
5112
5113 using Fn = bool (*)(JSContext*, BaselineFrame*, Handle<ClassBodyScope*>);
5114 return callVM<Fn, jit::PushClassBodyEnv>();
5115 }
5116
5117 template <typename Handler>
5118 bool BaselineCodeGen<Handler>::emit_PopLexicalEnv() {
5119 frame.syncStack(0);
5120
5121 Register scratch1 = R0.scratchReg();
5122
5123 auto ifDebuggee = [this, scratch1]() {
5124 masm.loadBaselineFramePtr(FramePointer, scratch1);
5125
5126 prepareVMCall();
5127 pushBytecodePCArg();
5128 pushArg(scratch1);
5129
5130 using Fn = bool (*)(JSContext*, BaselineFrame*, const jsbytecode*);
5131 return callVM<Fn, jit::DebugLeaveThenPopLexicalEnv>();
5132 };
5133 auto ifNotDebuggee = [this, scratch1]() {
5134 Register scratch2 = R1.scratchReg();
5135 masm.loadPtr(frame.addressOfEnvironmentChain(), scratch1);
5136 masm.debugAssertObjectHasClass(scratch1, scratch2,
5137 &LexicalEnvironmentObject::class_);
5138 Address enclosingAddr(scratch1,
5139 EnvironmentObject::offsetOfEnclosingEnvironment());
5140 masm.unboxObject(enclosingAddr, scratch1);
5141 masm.storePtr(scratch1, frame.addressOfEnvironmentChain());
5142 return true;
5143 };
5144 return emitDebugInstrumentation(ifDebuggee, mozilla::Some(ifNotDebuggee));
5145 }
5146
5147 template <typename Handler>
5148 bool BaselineCodeGen<Handler>::emit_FreshenLexicalEnv() {
5149 frame.syncStack(0);
5150
5151 masm.loadBaselineFramePtr(FramePointer, R0.scratchReg());
5152
5153 auto ifDebuggee = [this]() {
5154 prepareVMCall();
5155 pushBytecodePCArg();
5156 pushArg(R0.scratchReg());
5157
5158 using Fn = bool (*)(JSContext*, BaselineFrame*, const jsbytecode*);
5159 return callVM<Fn, jit::DebuggeeFreshenLexicalEnv>();
5160 };
5161 auto ifNotDebuggee = [this]() {
5162 prepareVMCall();
5163 pushArg(R0.scratchReg());
5164
5165 using Fn = bool (*)(JSContext*, BaselineFrame*);
5166 return callVM<Fn, jit::FreshenLexicalEnv>();
5167 };
5168 return emitDebugInstrumentation(ifDebuggee, mozilla::Some(ifNotDebuggee));
5169 }
5170
5171 template <typename Handler>
5172 bool BaselineCodeGen<Handler>::emit_RecreateLexicalEnv() {
5173 frame.syncStack(0);
5174
5175 masm.loadBaselineFramePtr(FramePointer, R0.scratchReg());
5176
5177 auto ifDebuggee = [this]() {
5178 prepareVMCall();
5179 pushBytecodePCArg();
5180 pushArg(R0.scratchReg());
5181
5182 using Fn = bool (*)(JSContext*, BaselineFrame*, const jsbytecode*);
5183 return callVM<Fn, jit::DebuggeeRecreateLexicalEnv>();
5184 };
5185 auto ifNotDebuggee = [this]() {
5186 prepareVMCall();
5187 pushArg(R0.scratchReg());
5188
5189 using Fn = bool (*)(JSContext*, BaselineFrame*);
5190 return callVM<Fn, jit::RecreateLexicalEnv>();
5191 };
5192 return emitDebugInstrumentation(ifDebuggee, mozilla::Some(ifNotDebuggee));
5193 }
5194
5195 template <typename Handler>
5196 bool BaselineCodeGen<Handler>::emit_DebugLeaveLexicalEnv() {
5197 auto ifDebuggee = [this]() {
5198 prepareVMCall();
5199 masm.loadBaselineFramePtr(FramePointer, R0.scratchReg());
5200 pushBytecodePCArg();
5201 pushArg(R0.scratchReg());
5202
5203 using Fn = bool (*)(JSContext*, BaselineFrame*, const jsbytecode*);
5204 return callVM<Fn, jit::DebugLeaveLexicalEnv>();
5205 };
5206 return emitDebugInstrumentation(ifDebuggee);
5207 }
5208
5209 template <typename Handler>
5210 bool BaselineCodeGen<Handler>::emit_PushVarEnv() {
5211 prepareVMCall();
5212 masm.loadBaselineFramePtr(FramePointer, R0.scratchReg());
5213 pushScriptGCThingArg(ScriptGCThingType::Scope, R1.scratchReg(),
5214 R2.scratchReg());
5215 pushArg(R0.scratchReg());
5216
5217 using Fn = bool (*)(JSContext*, BaselineFrame*, Handle<Scope*>);
5218 return callVM<Fn, jit::PushVarEnv>();
5219 }
5220
5221 template <typename Handler>
5222 bool BaselineCodeGen<Handler>::emit_EnterWith() {
5223 // Pop "with" object to R0.
5224 frame.popRegsAndSync(1);
5225
5226 // Call a stub to push the object onto the environment chain.
5227 prepareVMCall();
5228
5229 pushScriptGCThingArg(ScriptGCThingType::Scope, R1.scratchReg(),
5230 R2.scratchReg());
5231 pushArg(R0);
5232 masm.loadBaselineFramePtr(FramePointer, R1.scratchReg());
5233 pushArg(R1.scratchReg());
5234
5235 using Fn =
5236 bool (*)(JSContext*, BaselineFrame*, HandleValue, Handle<WithScope*>);
5237 return callVM<Fn, jit::EnterWith>();
5238 }
5239
5240 template <typename Handler>
5241 bool BaselineCodeGen<Handler>::emit_LeaveWith() {
5242 // Call a stub to pop the with object from the environment chain.
5243 prepareVMCall();
5244
5245 masm.loadBaselineFramePtr(FramePointer, R0.scratchReg());
5246 pushArg(R0.scratchReg());
5247
5248 using Fn = bool (*)(JSContext*, BaselineFrame*);
5249 return callVM<Fn, jit::LeaveWith>();
5250 }
5251
5252 #ifdef ENABLE_EXPLICIT_RESOURCE_MANAGEMENT
5253 template <typename Handler>
5254 bool BaselineCodeGen<Handler>::emit_AddDisposable() {
5255 frame.syncStack(0);
5256 prepareVMCall();
5257
5258 pushUint8BytecodeOperandArg(R0.scratchReg()); // hint
5259
5260 masm.unboxBoolean(frame.addressOfStackValue(-1), R0.scratchReg());
5261 pushArg(R0.scratchReg()); // needsClosure
5262
5263 masm.loadValue(frame.addressOfStackValue(-2), R1);
5264 pushArg(R1); // method
5265
5266 masm.loadValue(frame.addressOfStackValue(-3), R2);
5267 pushArg(R2); // object
5268
5269 masm.loadPtr(frame.addressOfEnvironmentChain(), R0.scratchReg());
5270 pushArg(R0.scratchReg());
5271
5272 using Fn = bool (*)(JSContext*, JS::Handle<JSObject*>, JS::Handle<JS::Value>,
5273 JS::Handle<JS::Value>, bool, UsingHint);
5274 if (!callVM<Fn, js::AddDisposableResourceToCapability>()) {
5275 return false;
5276 }
5277 frame.popn(3);
5278 return true;
5279 }
5280
5281 template <typename Handler>
5282 bool BaselineCodeGen<Handler>::emit_TakeDisposeCapability() {
5283 frame.syncStack(0);
5284
5285 masm.loadPtr(frame.addressOfEnvironmentChain(), R0.scratchReg());
5286 Address capAddr(R0.scratchReg(),
5287 DisposableEnvironmentObject::offsetOfDisposeCapability());
5288 masm.guardedCallPreBarrierAnyZone(capAddr, MIRType::Value, R2.scratchReg());
5289 masm.loadValue(capAddr, R1);
5290 masm.storeValue(UndefinedValue(), capAddr);
5291
5292 frame.push(R1);
5293 return true;
5294 }
5295
5296 template <typename Handler>
5297 bool BaselineCodeGen<Handler>::emit_CreateSuppressedError() {
5298 frame.popRegsAndSync(2);
5299 prepareVMCall();
5300
5301 pushArg(R1); // suppressed
5302 pushArg(R0); // error
5303
5304 using Fn = ErrorObject* (*)(JSContext*, JS::Handle<JS::Value>,
5305 JS::Handle<JS::Value>);
5306
5307 if (!callVM<Fn, js::CreateSuppressedError>()) {
5308 return false;
5309 }
5310
5311 masm.tagValue(JSVAL_TYPE_OBJECT, ReturnReg, R0);
5312 frame.push(R0);
5313 return true;
5314 }
5315 #endif
5316
5317 template <typename Handler>
5318 bool BaselineCodeGen<Handler>::emit_Exception() {
5319 prepareVMCall();
5320
5321 using Fn = bool (*)(JSContext*, MutableHandleValue);
5322 if (!callVM<Fn, GetAndClearException>()) {
5323 return false;
5324 }
5325
5326 frame.push(R0);
5327 return true;
5328 }
5329
5330 template <typename Handler>
5331 bool BaselineCodeGen<Handler>::emit_ExceptionAndStack() {
5332 // First call into the VM to store the exception stack.
5333 {
5334 prepareVMCall();
5335
5336 using Fn = bool (*)(JSContext*, MutableHandleValue);
5337 if (!callVM<Fn, GetPendingExceptionStack>()) {
5338 return false;
5339 }
5340
5341 frame.push(R0);
5342 }
5343
5344 // Now get the actual exception value and clear the exception state.
5345 {
5346 prepareVMCall();
5347
5348 using Fn = bool (*)(JSContext*, MutableHandleValue);
5349 if (!callVM<Fn, GetAndClearException>()) {
5350 return false;
5351 }
5352
5353 frame.push(R0);
5354 }
5355
5356 // Finally swap the stack and the exception.
5357 frame.popRegsAndSync(2);
5358 frame.push(R1);
5359 frame.push(R0);
5360
5361 return true;
5362 }
5363
5364 template <typename Handler>
5365 bool BaselineCodeGen<Handler>::emit_Debugger() {
5366 prepareVMCall();
5367
5368 frame.assertSyncedStack();
5369 masm.loadBaselineFramePtr(FramePointer, R0.scratchReg());
5370 pushArg(R0.scratchReg());
5371
5372 using Fn = bool (*)(JSContext*, BaselineFrame*);
5373 if (!callVM<Fn, jit::OnDebuggerStatement>()) {
5374 return false;
5375 }
5376
5377 return true;
5378 }
5379
5380 template <typename Handler>
5381 bool BaselineCodeGen<Handler>::emitDebugEpilogue() {
5382 auto ifDebuggee = [this]() {
5383 // Move return value into the frame's rval slot.
5384 masm.storeValue(JSReturnOperand, frame.addressOfReturnValue());
5385 masm.or32(Imm32(BaselineFrame::HAS_RVAL), frame.addressOfFlags());
5386
5387 // Load BaselineFrame pointer in R0.
5388 frame.syncStack(0);
5389 masm.loadBaselineFramePtr(FramePointer, R0.scratchReg());
5390
5391 prepareVMCall();
5392 pushBytecodePCArg();
5393 pushArg(R0.scratchReg());
5394
5395 const RetAddrEntry::Kind kind = RetAddrEntry::Kind::DebugEpilogue;
5396
5397 using Fn = bool (*)(JSContext*, BaselineFrame*, const jsbytecode*);
5398 if (!callVM<Fn, jit::DebugEpilogueOnBaselineReturn>(kind)) {
5399 return false;
5400 }
5401
5402 masm.loadValue(frame.addressOfReturnValue(), JSReturnOperand);
5403 return true;
5404 };
5405 return emitDebugInstrumentation(ifDebuggee);
5406 }
5407
5408 template <typename Handler>
5409 bool BaselineCodeGen<Handler>::emitReturn() {
5410 if (handler.shouldEmitDebugEpilogueAtReturnOp()) {
5411 if (!emitDebugEpilogue()) {
5412 return false;
5413 }
5414 }
5415
5416 // Only emit the jump if this JSOp::RetRval is not the last instruction.
5417 // Not needed for last instruction, because last instruction flows
5418 // into return label.
5419 if (!handler.isDefinitelyLastOp()) {
5420 masm.jump(&return_);
5421 }
5422
5423 return true;
5424 }
5425
5426 template <typename Handler>
5427 bool BaselineCodeGen<Handler>::emit_Return() {
5428 frame.assertStackDepth(1);
5429
5430 frame.popValue(JSReturnOperand);
5431 return emitReturn();
5432 }
5433
5434 template <typename Handler>
5435 void BaselineCodeGen<Handler>::emitLoadReturnValue(ValueOperand val) {
5436 Label done, noRval;
5437 masm.branchTest32(Assembler::Zero, frame.addressOfFlags(),
5438 Imm32(BaselineFrame::HAS_RVAL), &noRval);
5439 masm.loadValue(frame.addressOfReturnValue(), val);
5440 masm.jump(&done);
5441
5442 masm.bind(&noRval);
5443 masm.moveValue(UndefinedValue(), val);
5444
5445 masm.bind(&done);
5446 }
5447
5448 template <typename Handler>
5449 bool BaselineCodeGen<Handler>::emit_RetRval() {
5450 frame.assertStackDepth(0);
5451
5452 masm.moveValue(UndefinedValue(), JSReturnOperand);
5453
5454 if (!handler.maybeScript() || !handler.maybeScript()->noScriptRval()) {
5455 // Return the value in the return value slot, if any.
5456 Label done;
5457 Address flags = frame.addressOfFlags();
5458 masm.branchTest32(Assembler::Zero, flags, Imm32(BaselineFrame::HAS_RVAL),
5459 &done);
5460 masm.loadValue(frame.addressOfReturnValue(), JSReturnOperand);
5461 masm.bind(&done);
5462 }
5463
5464 return emitReturn();
5465 }
5466
5467 template <typename Handler>
5468 bool BaselineCodeGen<Handler>::emit_ToPropertyKey() {
5469 frame.popRegsAndSync(1);
5470
5471 if (!emitNextIC()) {
5472 return false;
5473 }
5474
5475 frame.push(R0);
5476 return true;
5477 }
5478
5479 template <typename Handler>
5480 bool BaselineCodeGen<Handler>::emit_ToAsyncIter() {
5481 frame.syncStack(0);
5482 masm.unboxObject(frame.addressOfStackValue(-2), R0.scratchReg());
5483 masm.loadValue(frame.addressOfStackValue(-1), R1);
5484
5485 prepareVMCall();
5486 pushArg(R1);
5487 pushArg(R0.scratchReg());
5488
5489 using Fn = JSObject* (*)(JSContext*, HandleObject, HandleValue);
5490 if (!callVM<Fn, js::CreateAsyncFromSyncIterator>()) {
5491 return false;
5492 }
5493
5494 masm.tagValue(JSVAL_TYPE_OBJECT, ReturnReg, R0);
5495 frame.popn(2);
5496 frame.push(R0);
5497 return true;
5498 }
5499
5500 template <typename Handler>
5501 bool BaselineCodeGen<Handler>::emit_CanSkipAwait() {
5502 frame.syncStack(0);
5503 masm.loadValue(frame.addressOfStackValue(-1), R0);
5504
5505 prepareVMCall();
5506 pushArg(R0);
5507
5508 using Fn = bool (*)(JSContext*, HandleValue, bool* canSkip);
5509 if (!callVM<Fn, js::CanSkipAwait>()) {
5510 return false;
5511 }
5512
5513 masm.tagValue(JSVAL_TYPE_BOOLEAN, ReturnReg, R0);
5514 frame.push(R0, JSVAL_TYPE_BOOLEAN);
5515 return true;
5516 }
5517
5518 template <typename Handler>
5519 bool BaselineCodeGen<Handler>::emit_MaybeExtractAwaitValue() {
5520 frame.syncStack(0);
5521 masm.loadValue(frame.addressOfStackValue(-2), R0);
5522
5523 masm.unboxBoolean(frame.addressOfStackValue(-1), R1.scratchReg());
5524
5525 Label cantExtract;
5526 masm.branchIfFalseBool(R1.scratchReg(), &cantExtract);
5527
5528 prepareVMCall();
5529 pushArg(R0);
5530
5531 using Fn = bool (*)(JSContext*, HandleValue, MutableHandleValue);
5532 if (!callVM<Fn, js::ExtractAwaitValue>()) {
5533 return false;
5534 }
5535
5536 masm.storeValue(R0, frame.addressOfStackValue(-2));
5537 masm.bind(&cantExtract);
5538
5539 return true;
5540 }
5541
5542 template <typename Handler>
5543 bool BaselineCodeGen<Handler>::emit_AsyncAwait() {
5544 frame.syncStack(0);
5545 masm.loadValue(frame.addressOfStackValue(-2), R1);
5546 masm.unboxObject(frame.addressOfStackValue(-1), R0.scratchReg());
5547
5548 prepareVMCall();
5549 pushArg(R1);
5550 pushArg(R0.scratchReg());
5551
5552 using Fn = JSObject* (*)(JSContext*, Handle<AsyncFunctionGeneratorObject*>,
5553 HandleValue);
5554 if (!callVM<Fn, js::AsyncFunctionAwait>()) {
5555 return false;
5556 }
5557
5558 masm.tagValue(JSVAL_TYPE_OBJECT, ReturnReg, R0);
5559 frame.popn(2);
5560 frame.push(R0);
5561 return true;
5562 }
5563
5564 template <typename Handler>
5565 bool BaselineCodeGen<Handler>::emit_AsyncResolve() {
5566 frame.syncStack(0);
5567 masm.loadValue(frame.addressOfStackValue(-2), R1);
5568 masm.unboxObject(frame.addressOfStackValue(-1), R0.scratchReg());
5569
5570 prepareVMCall();
5571 pushArg(R1);
5572 pushArg(R0.scratchReg());
5573
5574 using Fn = JSObject* (*)(JSContext*, Handle<AsyncFunctionGeneratorObject*>,
5575 HandleValue);
5576 if (!callVM<Fn, js::AsyncFunctionResolve>()) {
5577 return false;
5578 }
5579
5580 masm.tagValue(JSVAL_TYPE_OBJECT, ReturnReg, R0);
5581 frame.popn(2);
5582 frame.push(R0);
5583 return true;
5584 }
5585
5586 template <typename Handler>
5587 bool BaselineCodeGen<Handler>::emit_AsyncReject() {
5588 frame.syncStack(0);
5589 masm.loadValue(frame.addressOfStackValue(-3), R2);
5590 masm.loadValue(frame.addressOfStackValue(-2), R1);
5591 masm.unboxObject(frame.addressOfStackValue(-1), R0.scratchReg());
5592
5593 prepareVMCall();
5594 pushArg(R1);
5595 pushArg(R2);
5596 pushArg(R0.scratchReg());
5597
5598 using Fn = JSObject* (*)(JSContext*, Handle<AsyncFunctionGeneratorObject*>,
5599 HandleValue, HandleValue);
5600 if (!callVM<Fn, js::AsyncFunctionReject>()) {
5601 return false;
5602 }
5603
5604 masm.tagValue(JSVAL_TYPE_OBJECT, ReturnReg, R0);
5605 frame.popn(3);
5606 frame.push(R0);
5607 return true;
5608 }
5609
5610 template <typename Handler>
5611 bool BaselineCodeGen<Handler>::emit_CheckObjCoercible() {
5612 frame.syncStack(0);
5613 masm.loadValue(frame.addressOfStackValue(-1), R0);
5614
5615 Label fail, done;
5616
5617 masm.branchTestUndefined(Assembler::Equal, R0, &fail);
5618 masm.branchTestNull(Assembler::NotEqual, R0, &done);
5619
5620 masm.bind(&fail);
5621 prepareVMCall();
5622
5623 pushArg(R0);
5624
5625 using Fn = bool (*)(JSContext*, HandleValue);
5626 if (!callVM<Fn, ThrowObjectCoercible>()) {
5627 return false;
5628 }
5629
5630 masm.bind(&done);
5631 return true;
5632 }
5633
5634 template <typename Handler>
5635 bool BaselineCodeGen<Handler>::emit_ToString() {
5636 // Keep top stack value in R0.
5637 frame.popRegsAndSync(1);
5638
5639 // Inline path for string.
5640 Label done;
5641 masm.branchTestString(Assembler::Equal, R0, &done);
5642
5643 prepareVMCall();
5644
5645 pushArg(R0);
5646
5647 // Call ToStringSlow which doesn't handle string inputs.
5648 using Fn = JSString* (*)(JSContext*, HandleValue);
5649 if (!callVM<Fn, ToStringSlow<CanGC>>()) {
5650 return false;
5651 }
5652
5653 masm.tagValue(JSVAL_TYPE_STRING, ReturnReg, R0);
5654
5655 masm.bind(&done);
5656 frame.push(R0);
5657 return true;
5658 }
5659
5660 static constexpr uint32_t TableSwitchOpLowOffset = 1 * JUMP_OFFSET_LEN;
5661 static constexpr uint32_t TableSwitchOpHighOffset = 2 * JUMP_OFFSET_LEN;
5662 static constexpr uint32_t TableSwitchOpFirstResumeIndexOffset =
5663 3 * JUMP_OFFSET_LEN;
5664
5665 template <>
5666 void BaselineCompilerCodeGen::emitGetTableSwitchIndex(ValueOperand val,
5667 Register dest,
5668 Register scratch1,
5669 Register scratch2) {
5670 jsbytecode* pc = handler.pc();
5671 jsbytecode* defaultpc = pc + GET_JUMP_OFFSET(pc);
5672 Label* defaultLabel = handler.labelOf(defaultpc);
5673
5674 int32_t low = GET_JUMP_OFFSET(pc + TableSwitchOpLowOffset);
5675 int32_t high = GET_JUMP_OFFSET(pc + TableSwitchOpHighOffset);
5676 int32_t length = high - low + 1;
5677
5678 // Jump to the 'default' pc if not int32 (tableswitch is only used when
5679 // all cases are int32).
5680 masm.branchTestInt32(Assembler::NotEqual, val, defaultLabel);
5681 masm.unboxInt32(val, dest);
5682
5683 // Subtract 'low'. Bounds check.
5684 if (low != 0) {
5685 masm.sub32(Imm32(low), dest);
5686 }
5687 masm.branch32(Assembler::AboveOrEqual, dest, Imm32(length), defaultLabel);
5688 }
5689
5690 template <>
5691 void BaselineInterpreterCodeGen::emitGetTableSwitchIndex(ValueOperand val,
5692 Register dest,
5693 Register scratch1,
5694 Register scratch2) {
5695 // Jump to the 'default' pc if not int32 (tableswitch is only used when
5696 // all cases are int32).
5697 Label done, jumpToDefault;
5698 masm.branchTestInt32(Assembler::NotEqual, val, &jumpToDefault);
5699 masm.unboxInt32(val, dest);
5700
5701 Register pcReg = LoadBytecodePC(masm, scratch1);
5702 Address lowAddr(pcReg, sizeof(jsbytecode) + TableSwitchOpLowOffset);
5703 Address highAddr(pcReg, sizeof(jsbytecode) + TableSwitchOpHighOffset);
5704
5705 // Jump to default if val > high.
5706 masm.branch32(Assembler::LessThan, highAddr, dest, &jumpToDefault);
5707
5708 // Jump to default if val < low.
5709 masm.load32(lowAddr, scratch2);
5710 masm.branch32(Assembler::GreaterThan, scratch2, dest, &jumpToDefault);
5711
5712 // index := val - low.
5713 masm.sub32(scratch2, dest);
5714 masm.jump(&done);
5715
5716 masm.bind(&jumpToDefault);
5717 emitJump();
5718
5719 masm.bind(&done);
5720 }
5721
5722 template <>
5723 void BaselineCompilerCodeGen::emitTableSwitchJump(Register key,
5724 Register scratch1,
5725 Register scratch2) {
5726 // Jump to resumeEntries[firstResumeIndex + key].
5727
5728 // Note: BytecodeEmitter::allocateResumeIndex static_asserts
5729 // |firstResumeIndex * sizeof(uintptr_t)| fits in int32_t.
5730 uint32_t firstResumeIndex =
5731 GET_RESUMEINDEX(handler.pc() + TableSwitchOpFirstResumeIndexOffset);
5732 loadBaselineScriptResumeEntries(scratch1, scratch2);
5733 masm.loadPtr(BaseIndex(scratch1, key, ScaleFromElemWidth(sizeof(uintptr_t)),
5734 firstResumeIndex * sizeof(uintptr_t)),
5735 scratch1);
5736 masm.jump(scratch1);
5737 }
5738
5739 template <>
5740 void BaselineInterpreterCodeGen::emitTableSwitchJump(Register key,
5741 Register scratch1,
5742 Register scratch2) {
5743 // Load the op's firstResumeIndex in scratch1.
5744 LoadUint24Operand(masm, TableSwitchOpFirstResumeIndexOffset, scratch1);
5745
5746 masm.add32(key, scratch1);
5747 jumpToResumeEntry(scratch1, key, scratch2);
5748 }
5749
5750 template <typename Handler>
5751 bool BaselineCodeGen<Handler>::emit_TableSwitch() {
5752 frame.popRegsAndSync(1);
5753
5754 Register key = R0.scratchReg();
5755 Register scratch1 = R1.scratchReg();
5756 Register scratch2 = R2.scratchReg();
5757
5758 // Call a stub to convert R0 from double to int32 if needed.
5759 // Note: this stub may clobber scratch1.
5760 masm.call(runtime->jitRuntime()->getDoubleToInt32ValueStub());
5761
5762 // Load the index in the jump table in |key|, or branch to default pc if not
5763 // int32 or out-of-range.
5764 emitGetTableSwitchIndex(R0, key, scratch1, scratch2);
5765
5766 // Jump to the target pc.
5767 emitTableSwitchJump(key, scratch1, scratch2);
5768 return true;
5769 }
5770
5771 template <typename Handler>
5772 bool BaselineCodeGen<Handler>::emit_Iter() {
5773 frame.popRegsAndSync(1);
5774
5775 if (!emitNextIC()) {
5776 return false;
5777 }
5778
5779 frame.push(R0);
5780 return true;
5781 }
5782
5783 template <typename Handler>
5784 bool BaselineCodeGen<Handler>::emit_MoreIter() {
5785 frame.syncStack(0);
5786
5787 masm.unboxObject(frame.addressOfStackValue(-1), R1.scratchReg());
5788
5789 masm.iteratorMore(R1.scratchReg(), R0, R2.scratchReg());
5790 frame.push(R0);
5791 return true;
5792 }
5793
5794 template <typename Handler>
5795 bool BaselineCodeGen<Handler>::emitIsMagicValue() {
5796 frame.syncStack(0);
5797
5798 Label isMagic, done;
5799 masm.branchTestMagic(Assembler::Equal, frame.addressOfStackValue(-1),
5800 &isMagic);
5801 masm.moveValue(BooleanValue(false), R0);
5802 masm.jump(&done);
5803
5804 masm.bind(&isMagic);
5805 masm.moveValue(BooleanValue(true), R0);
5806
5807 masm.bind(&done);
5808 frame.push(R0, JSVAL_TYPE_BOOLEAN);
5809 return true;
5810 }
5811
5812 template <typename Handler>
5813 bool BaselineCodeGen<Handler>::emit_IsNoIter() {
5814 return emitIsMagicValue();
5815 }
5816
5817 template <typename Handler>
5818 bool BaselineCodeGen<Handler>::emit_EndIter() {
5819 // Pop iterator value.
5820 frame.pop();
5821
5822 // Pop the iterator object to close in R0.
5823 frame.popRegsAndSync(1);
5824
5825 AllocatableGeneralRegisterSet regs(GeneralRegisterSet::All());
5826 MOZ_ASSERT(!regs.has(FramePointer));
5827 if (HasInterpreterPCReg()) {
5828 regs.take(InterpreterPCReg);
5829 }
5830
5831 Register obj = R0.scratchReg();
5832 regs.take(obj);
5833 masm.unboxObject(R0, obj);
5834
5835 Register temp1 = regs.takeAny();
5836 Register temp2 = regs.takeAny();
5837 Register temp3 = regs.takeAny();
5838 masm.iteratorClose(obj, temp1, temp2, temp3);
5839 return true;
5840 }
5841
5842 template <typename Handler>
5843 bool BaselineCodeGen<Handler>::emit_CloseIter() {
5844 frame.popRegsAndSync(1);
5845
5846 Register iter = R0.scratchReg();
5847 masm.unboxObject(R0, iter);
5848
5849 return emitNextIC();
5850 }
5851
5852 template <typename Handler>
5853 bool BaselineCodeGen<Handler>::emit_OptimizeGetIterator() {
5854 frame.popRegsAndSync(1);
5855
5856 if (!emitNextIC()) {
5857 return false;
5858 }
5859
5860 frame.push(R0);
5861 return true;
5862 }
5863
5864 template <typename Handler>
5865 bool BaselineCodeGen<Handler>::emit_IsGenClosing() {
5866 return emitIsMagicValue();
5867 }
5868
5869 template <typename Handler>
5870 bool BaselineCodeGen<Handler>::emit_IsNullOrUndefined() {
5871 frame.syncStack(0);
5872
5873 Label isNullOrUndefined, done;
5874 masm.branchTestNull(Assembler::Equal, frame.addressOfStackValue(-1),
5875 &isNullOrUndefined);
5876 masm.branchTestUndefined(Assembler::Equal, frame.addressOfStackValue(-1),
5877 &isNullOrUndefined);
5878 masm.moveValue(BooleanValue(false), R0);
5879 masm.jump(&done);
5880
5881 masm.bind(&isNullOrUndefined);
5882 masm.moveValue(BooleanValue(true), R0);
5883
5884 masm.bind(&done);
5885 frame.push(R0, JSVAL_TYPE_BOOLEAN);
5886 return true;
5887 }
5888
5889 template <typename Handler>
5890 bool BaselineCodeGen<Handler>::emit_GetRval() {
5891 frame.syncStack(0);
5892
5893 emitLoadReturnValue(R0);
5894
5895 frame.push(R0);
5896 return true;
5897 }
5898
5899 template <typename Handler>
5900 bool BaselineCodeGen<Handler>::emit_SetRval() {
5901 // Store to the frame's return value slot.
5902 frame.storeStackValue(-1, frame.addressOfReturnValue(), R2);
5903 masm.or32(Imm32(BaselineFrame::HAS_RVAL), frame.addressOfFlags());
5904 frame.pop();
5905 return true;
5906 }
5907
5908 template <typename Handler>
5909 bool BaselineCodeGen<Handler>::emit_Callee() {
5910 MOZ_ASSERT_IF(handler.maybeScript(), handler.maybeScript()->function());
5911 frame.syncStack(0);
5912 masm.loadFunctionFromCalleeToken(frame.addressOfCalleeToken(),
5913 R0.scratchReg());
5914 masm.tagValue(JSVAL_TYPE_OBJECT, R0.scratchReg(), R0);
5915 frame.push(R0);
5916 return true;
5917 }
5918
5919 template <>
5920 bool BaselineCompilerCodeGen::emit_EnvCallee() {
5921 frame.syncStack(0);
5922 uint8_t numHops = GET_UINT8(handler.pc());
5923 Register scratch = R0.scratchReg();
5924
5925 masm.loadPtr(frame.addressOfEnvironmentChain(), scratch);
5926 for (unsigned i = 0; i < numHops; i++) {
5927 Address nextAddr(scratch,
5928 EnvironmentObject::offsetOfEnclosingEnvironment());
5929 masm.unboxObject(nextAddr, scratch);
5930 }
5931
5932 masm.loadValue(Address(scratch, CallObject::offsetOfCallee()), R0);
5933 frame.push(R0);
5934 return true;
5935 }
5936
5937 template <>
5938 bool BaselineInterpreterCodeGen::emit_EnvCallee() {
5939 Register scratch = R0.scratchReg();
5940 Register env = R1.scratchReg();
5941
5942 static_assert(JSOpLength_EnvCallee - sizeof(jsbytecode) == ENVCOORD_HOPS_LEN,
5943 "op must have uint8 operand for LoadAliasedVarEnv");
5944
5945 // Load the right environment object.
5946 masm.loadPtr(frame.addressOfEnvironmentChain(), env);
5947 LoadAliasedVarEnv(masm, env, scratch);
5948
5949 masm.pushValue(Address(env, CallObject::offsetOfCallee()));
5950 return true;
5951 }
5952
5953 template <typename Handler>
5954 bool BaselineCodeGen<Handler>::emit_SuperBase() {
5955 frame.popRegsAndSync(1);
5956
5957 Register scratch = R0.scratchReg();
5958 Register proto = R1.scratchReg();
5959
5960 // Unbox callee.
5961 masm.unboxObject(R0, scratch);
5962
5963 // Load [[HomeObject]]
5964 Address homeObjAddr(scratch,
5965 FunctionExtended::offsetOfMethodHomeObjectSlot());
5966
5967 masm.assertFunctionIsExtended(scratch);
5968 #ifdef DEBUG
5969 Label isObject;
5970 masm.branchTestObject(Assembler::Equal, homeObjAddr, &isObject);
5971 masm.assumeUnreachable("[[HomeObject]] must be Object");
5972 masm.bind(&isObject);
5973 #endif
5974 masm.unboxObject(homeObjAddr, scratch);
5975
5976 // Load prototype from [[HomeObject]]
5977 masm.loadObjProto(scratch, proto);
5978
5979 #ifdef DEBUG
5980 // We won't encounter a lazy proto, because the prototype is guaranteed to
5981 // either be a JSFunction or a PlainObject, and only proxy objects can have a
5982 // lazy proto.
5983 MOZ_ASSERT(uintptr_t(TaggedProto::LazyProto) == 1);
5984
5985 Label proxyCheckDone;
5986 masm.branchPtr(Assembler::NotEqual, proto, ImmWord(1), &proxyCheckDone);
5987 masm.assumeUnreachable("Unexpected lazy proto in JSOp::SuperBase");
5988 masm.bind(&proxyCheckDone);
5989 #endif
5990
5991 Label nullProto, done;
5992 masm.branchPtr(Assembler::Equal, proto, ImmWord(0), &nullProto);
5993
5994 // Box prototype and return
5995 masm.tagValue(JSVAL_TYPE_OBJECT, proto, R1);
5996 masm.jump(&done);
5997
5998 masm.bind(&nullProto);
5999 masm.moveValue(NullValue(), R1);
6000
6001 masm.bind(&done);
6002 frame.push(R1);
6003 return true;
6004 }
6005
6006 template <typename Handler>
6007 bool BaselineCodeGen<Handler>::emit_SuperFun() {
6008 frame.popRegsAndSync(1);
6009
6010 Register callee = R0.scratchReg();
6011 Register proto = R1.scratchReg();
6012 #ifdef DEBUG
6013 Register scratch = R2.scratchReg();
6014 #endif
6015
6016 // Unbox callee.
6017 masm.unboxObject(R0, callee);
6018
6019 #ifdef DEBUG
6020 Label classCheckDone;
6021 masm.branchTestObjIsFunction(Assembler::Equal, callee, scratch, callee,
6022 &classCheckDone);
6023 masm.assumeUnreachable("Unexpected non-JSFunction callee in JSOp::SuperFun");
6024 masm.bind(&classCheckDone);
6025 #endif
6026
6027 // Load prototype of callee
6028 masm.loadObjProto(callee, proto);
6029
6030 #ifdef DEBUG
6031 // We won't encounter a lazy proto, because |callee| is guaranteed to be a
6032 // JSFunction and only proxy objects can have a lazy proto.
6033 MOZ_ASSERT(uintptr_t(TaggedProto::LazyProto) == 1);
6034
6035 Label proxyCheckDone;
6036 masm.branchPtr(Assembler::NotEqual, proto, ImmWord(1), &proxyCheckDone);
6037 masm.assumeUnreachable("Unexpected lazy proto in JSOp::SuperFun");
6038 masm.bind(&proxyCheckDone);
6039 #endif
6040
6041 Label nullProto, done;
6042 masm.branchPtr(Assembler::Equal, proto, ImmWord(0), &nullProto);
6043
6044 // Box prototype and return
6045 masm.tagValue(JSVAL_TYPE_OBJECT, proto, R1);
6046 masm.jump(&done);
6047
6048 masm.bind(&nullProto);
6049 masm.moveValue(NullValue(), R1);
6050
6051 masm.bind(&done);
6052 frame.push(R1);
6053 return true;
6054 }
6055
6056 template <typename Handler>
6057 bool BaselineCodeGen<Handler>::emit_Arguments() {
6058 frame.syncStack(0);
6059
6060 MOZ_ASSERT_IF(handler.maybeScript(), handler.maybeScript()->needsArgsObj());
6061
6062 prepareVMCall();
6063
6064 masm.loadBaselineFramePtr(FramePointer, R0.scratchReg());
6065 pushArg(R0.scratchReg());
6066
6067 using Fn = bool (*)(JSContext*, BaselineFrame*, MutableHandleValue);
6068 if (!callVM<Fn, jit::NewArgumentsObject>()) {
6069 return false;
6070 }
6071
6072 frame.push(R0);
6073 return true;
6074 }
6075
6076 template <typename Handler>
6077 bool BaselineCodeGen<Handler>::emit_Rest() {
6078 frame.syncStack(0);
6079
6080 if (!emitNextIC()) {
6081 return false;
6082 }
6083
6084 // Mark R0 as pushed stack value.
6085 frame.push(R0);
6086 return true;
6087 }
6088
6089 template <typename Handler>
6090 bool BaselineCodeGen<Handler>::emit_Generator() {
6091 frame.assertStackDepth(0);
6092
6093 masm.loadBaselineFramePtr(FramePointer, R0.scratchReg());
6094
6095 prepareVMCall();
6096 pushArg(R0.scratchReg());
6097
6098 using Fn = JSObject* (*)(JSContext*, BaselineFrame*);
6099 if (!callVM<Fn, jit::CreateGeneratorFromFrame>()) {
6100 return false;
6101 }
6102
6103 masm.tagValue(JSVAL_TYPE_OBJECT, ReturnReg, R0);
6104 frame.push(R0);
6105 return true;
6106 }
6107
6108 template <typename Handler>
6109 bool BaselineCodeGen<Handler>::emitSuspend(JSOp op) {
6110 MOZ_ASSERT(op == JSOp::InitialYield || op == JSOp::Yield ||
6111 op == JSOp::Await);
6112
6113 // Load the generator object in R2, but leave the return value on the
6114 // expression stack.
6115 Register genObj = R2.scratchReg();
6116 if (op == JSOp::InitialYield) {
6117 // Generator and return value are one and the same.
6118 frame.syncStack(0);
6119 frame.assertStackDepth(1);
6120 masm.unboxObject(frame.addressOfStackValue(-1), genObj);
6121 } else {
6122 frame.popRegsAndSync(1);
6123 masm.unboxObject(R0, genObj);
6124 }
6125
6126 if (frame.hasKnownStackDepth(1) && !handler.canHaveFixedSlots()) {
6127 // If the expression stack is empty, we can inline the Yield. Note that this
6128 // branch is never taken for the interpreter because it doesn't know static
6129 // stack depths.
6130 MOZ_ASSERT_IF(op == JSOp::InitialYield && handler.maybePC(),
6131 GET_RESUMEINDEX(handler.maybePC()) == 0);
6132 Address resumeIndexSlot(genObj,
6133 AbstractGeneratorObject::offsetOfResumeIndexSlot());
6134 Register temp = R1.scratchReg();
6135 if (op == JSOp::InitialYield) {
6136 masm.storeValue(Int32Value(0), resumeIndexSlot);
6137 } else {
6138 jsbytecode* pc = handler.maybePC();
6139 MOZ_ASSERT(pc, "compiler-only code never has a null pc");
6140 masm.move32(Imm32(GET_RESUMEINDEX(pc)), temp);
6141 masm.storeValue(JSVAL_TYPE_INT32, temp, resumeIndexSlot);
6142 }
6143
6144 Register envObj = R0.scratchReg();
6145 Address envChainSlot(
6146 genObj, AbstractGeneratorObject::offsetOfEnvironmentChainSlot());
6147 masm.loadPtr(frame.addressOfEnvironmentChain(), envObj);
6148 masm.guardedCallPreBarrierAnyZone(envChainSlot, MIRType::Value, temp);
6149 masm.storeValue(JSVAL_TYPE_OBJECT, envObj, envChainSlot);
6150
6151 Label skipBarrier;
6152 masm.branchPtrInNurseryChunk(Assembler::Equal, genObj, temp, &skipBarrier);
6153 masm.branchPtrInNurseryChunk(Assembler::NotEqual, envObj, temp,
6154 &skipBarrier);
6155 MOZ_ASSERT(genObj == R2.scratchReg());
6156 masm.call(&postBarrierSlot_);
6157 masm.bind(&skipBarrier);
6158 } else {
6159 masm.loadBaselineFramePtr(FramePointer, R1.scratchReg());
6160 computeFrameSize(R0.scratchReg());
6161
6162 prepareVMCall();
6163 pushBytecodePCArg();
6164 pushArg(R0.scratchReg());
6165 pushArg(R1.scratchReg());
6166 pushArg(genObj);
6167
6168 using Fn = bool (*)(JSContext*, HandleObject, BaselineFrame*, uint32_t,
6169 const jsbytecode*);
6170 if (!callVM<Fn, jit::NormalSuspend>()) {
6171 return false;
6172 }
6173 }
6174
6175 masm.loadValue(frame.addressOfStackValue(-1), JSReturnOperand);
6176 if (!emitReturn()) {
6177 return false;
6178 }
6179
6180 // Three values are pushed onto the stack when resuming the generator,
6181 // replacing the one slot that holds the return value.
6182 frame.incStackDepth(2);
6183 return true;
6184 }
6185
6186 template <typename Handler>
6187 bool BaselineCodeGen<Handler>::emit_InitialYield() {
6188 return emitSuspend(JSOp::InitialYield);
6189 }
6190
6191 template <typename Handler>
6192 bool BaselineCodeGen<Handler>::emit_Yield() {
6193 return emitSuspend(JSOp::Yield);
6194 }
6195
6196 template <typename Handler>
6197 bool BaselineCodeGen<Handler>::emit_Await() {
6198 return emitSuspend(JSOp::Await);
6199 }
6200
6201 template <>
6202 template <typename F>
6203 bool BaselineCompilerCodeGen::emitAfterYieldDebugInstrumentation(
6204 const F& ifDebuggee, Register) {
6205 if (handler.compileDebugInstrumentation()) {
6206 return ifDebuggee();
6207 }
6208 return true;
6209 }
6210
6211 template <>
6212 template <typename F>
6213 bool BaselineInterpreterCodeGen::emitAfterYieldDebugInstrumentation(
6214 const F& ifDebuggee, Register scratch) {
6215 // Note that we can't use emitDebugInstrumentation here because the frame's
6216 // DEBUGGEE flag hasn't been initialized yet.
6217
6218 // If the current Realm is not a debuggee we're done.
6219 Label done;
6220 CodeOffset toggleOffset = masm.toggledJump(&done);
6221 if (!handler.addDebugInstrumentationOffset(toggleOffset)) {
6222 return false;
6223 }
6224 masm.loadPtr(AbsoluteAddress(runtime->addressOfRealm()), scratch);
6225 masm.branchTest32(Assembler::Zero,
6226 Address(scratch, Realm::offsetOfDebugModeBits()),
6227 Imm32(Realm::debugModeIsDebuggeeBit()), &done);
6228
6229 if (!ifDebuggee()) {
6230 return false;
6231 }
6232
6233 masm.bind(&done);
6234 return true;
6235 }
6236
6237 template <typename Handler>
6238 bool BaselineCodeGen<Handler>::emit_AfterYield() {
6239 if (!emit_JumpTarget()) {
6240 return false;
6241 }
6242
6243 auto ifDebuggee = [this]() {
6244 frame.assertSyncedStack();
6245 masm.loadBaselineFramePtr(FramePointer, R0.scratchReg());
6246 prepareVMCall();
6247 pushArg(R0.scratchReg());
6248
6249 const RetAddrEntry::Kind kind = RetAddrEntry::Kind::DebugAfterYield;
6250
6251 using Fn = bool (*)(JSContext*, BaselineFrame*);
6252 if (!callVM<Fn, jit::DebugAfterYield>(kind)) {
6253 return false;
6254 }
6255
6256 return true;
6257 };
6258 return emitAfterYieldDebugInstrumentation(ifDebuggee, R0.scratchReg());
6259 }
6260
6261 template <typename Handler>
6262 bool BaselineCodeGen<Handler>::emit_FinalYieldRval() {
6263 // Store generator in R0.
6264 frame.popRegsAndSync(1);
6265 masm.unboxObject(R0, R0.scratchReg());
6266
6267 prepareVMCall();
6268 pushBytecodePCArg();
6269 pushArg(R0.scratchReg());
6270
6271 using Fn = bool (*)(JSContext*, HandleObject, const jsbytecode*);
6272 if (!callVM<Fn, jit::FinalSuspend>()) {
6273 return false;
6274 }
6275
6276 masm.loadValue(frame.addressOfReturnValue(), JSReturnOperand);
6277 return emitReturn();
6278 }
6279
6280 template <>
6281 void BaselineCompilerCodeGen::emitJumpToInterpretOpLabel() {
6282 TrampolinePtr code =
6283 runtime->jitRuntime()->baselineInterpreter().interpretOpAddr();
6284 masm.jump(code);
6285 }
6286
6287 template <>
6288 void BaselineInterpreterCodeGen::emitJumpToInterpretOpLabel() {
6289 masm.jump(handler.interpretOpLabel());
6290 }
6291
6292 template <typename Handler>
6293 bool BaselineCodeGen<Handler>::emitEnterGeneratorCode(Register script,
6294 Register resumeIndex,
6295 Register scratch) {
6296 // Resume in either the BaselineScript (if present) or Baseline Interpreter.
6297
6298 static_assert(CompilingScript == 0x5,
6299 "Comparison below requires specific sentinel encoding");
6300
6301 // Initialize the icScript slot in the baseline frame.
6302 masm.loadJitScript(script, scratch);
6303 masm.computeEffectiveAddress(Address(scratch, JitScript::offsetOfICScript()),
6304 scratch);
6305 Address icScriptAddr(FramePointer, BaselineFrame::reverseOffsetOfICScript());
6306 masm.storePtr(scratch, icScriptAddr);
6307
6308 Label noBaselineScript;
6309 // Frames with shared bytecode need the interpreterScript pointer
6310 if (handler.realmIndependentJitcode()) {
6311 masm.storePtr(script, frame.addressOfInterpreterScript());
6312 }
6313 masm.loadJitScript(script, scratch);
6314 masm.loadPtr(Address(scratch, JitScript::offsetOfBaselineScript()), scratch);
6315 masm.branchPtr(Assembler::BelowOrEqual, scratch,
6316 ImmPtr(BaselineCompilingScriptPtr), &noBaselineScript);
6317
6318 masm.load32(Address(scratch, BaselineScript::offsetOfResumeEntriesOffset()),
6319 script);
6320 masm.addPtr(scratch, script);
6321 masm.loadPtr(
6322 BaseIndex(script, resumeIndex, ScaleFromElemWidth(sizeof(uintptr_t))),
6323 scratch);
6324 masm.jump(scratch);
6325
6326 masm.bind(&noBaselineScript);
6327
6328 // Initialize interpreter frame fields.
6329 Address flagsAddr(FramePointer, BaselineFrame::reverseOffsetOfFlags());
6330 Address scriptAddr(FramePointer,
6331 BaselineFrame::reverseOffsetOfInterpreterScript());
6332 masm.or32(Imm32(BaselineFrame::RUNNING_IN_INTERPRETER), flagsAddr);
6333 masm.storePtr(script, scriptAddr);
6334
6335 // Initialize pc and jump to it.
6336 emitInterpJumpToResumeEntry(script, resumeIndex, scratch);
6337 return true;
6338 }
6339
6340 template <typename Handler>
6341 bool BaselineCodeGen<Handler>::emit_Resume() {
6342 frame.syncStack(0);
6343 masm.assertStackAlignment(sizeof(Value), 0);
6344
6345 AllocatableGeneralRegisterSet regs(GeneralRegisterSet::All());
6346 MOZ_ASSERT(!regs.has(FramePointer));
6347 if (HasInterpreterPCReg()) {
6348 regs.take(InterpreterPCReg);
6349 }
6350
6351 saveInterpreterPCReg();
6352
6353 // Load generator object.
6354 Register genObj = regs.takeAny();
6355 masm.unboxObject(frame.addressOfStackValue(-3), genObj);
6356
6357 // Load callee.
6358 Register callee = regs.takeAny();
6359 masm.unboxObject(
6360 Address(genObj, AbstractGeneratorObject::offsetOfCalleeSlot()), callee);
6361
6362 // Save a pointer to the JSOp::Resume operand stack Values.
6363 Register callerStackPtr = regs.takeAny();
6364 masm.computeEffectiveAddress(frame.addressOfStackValue(-1), callerStackPtr);
6365
6366 // Branch to |interpret| to resume the generator in the C++ interpreter if the
6367 // script does not have a JitScript.
6368 Label interpret;
6369 Register scratch1 = regs.takeAny();
6370 masm.loadPrivate(Address(callee, JSFunction::offsetOfJitInfoOrScript()),
6371 scratch1);
6372 masm.branchIfScriptHasNoJitScript(scratch1, &interpret);
6373
6374 // Push |undefined| for all formals.
6375 Register scratch2 = regs.takeAny();
6376 Label loop, loopDone;
6377 masm.loadFunctionArgCount(callee, scratch2);
6378
6379 static_assert(sizeof(Value) == 8);
6380 #ifndef JS_CODEGEN_NONE
6381 static_assert(JitStackAlignment == 16 || JitStackAlignment == 8);
6382 #endif
6383 // If JitStackValueAlignment == 1, then we were already correctly aligned on
6384 // entry, as guaranteed by the assertStackAlignment at the entry to this
6385 // function.
6386 if (JitStackValueAlignment > 1) {
6387 Register alignment = regs.takeAny();
6388 masm.moveStackPtrTo(alignment);
6389 masm.alignJitStackBasedOnNArgs(scratch2, false);
6390
6391 // Compute alignment adjustment.
6392 masm.subStackPtrFrom(alignment);
6393
6394 // Some code, like BaselineFrame::trace, will inspect the whole range of
6395 // the stack frame. In order to ensure that garbage data left behind from
6396 // previous activations doesn't confuse other machinery, we zero out the
6397 // alignment bytes.
6398 Label alignmentZero;
6399 masm.branchPtr(Assembler::Equal, alignment, ImmWord(0), &alignmentZero);
6400
6401 // Since we know prior to the stack alignment that the stack was 8 byte
6402 // aligned, and JitStackAlignment is 8 or 16 bytes, if we are doing an
6403 // alignment then we -must- have aligned by subtracting 8 bytes from
6404 // the stack pointer.
6405 //
6406 // So we can freely store a valid double here.
6407 masm.storeValue(DoubleValue(0), Address(masm.getStackPointer(), 0));
6408 masm.bind(&alignmentZero);
6409 }
6410
6411 masm.branchTest32(Assembler::Zero, scratch2, scratch2, &loopDone);
6412 masm.bind(&loop);
6413 {
6414 masm.pushValue(UndefinedValue());
6415 masm.branchSub32(Assembler::NonZero, Imm32(1), scratch2, &loop);
6416 }
6417 masm.bind(&loopDone);
6418
6419 // Push |undefined| for |this|.
6420 masm.pushValue(UndefinedValue());
6421
6422 #ifdef DEBUG
6423 // Update BaselineFrame debugFrameSize field.
6424 masm.mov(FramePointer, scratch2);
6425 masm.subStackPtrFrom(scratch2);
6426 masm.store32(scratch2, frame.addressOfDebugFrameSize());
6427 #endif
6428
6429 masm.PushCalleeToken(callee, /* constructing = */ false);
6430 masm.pushFrameDescriptorForJitCall(FrameType::BaselineJS, /* argc = */ 0);
6431
6432 // PushCalleeToken bumped framePushed. Reset it.
6433 MOZ_ASSERT(masm.framePushed() == sizeof(uintptr_t));
6434 masm.setFramePushed(0);
6435
6436 regs.add(callee);
6437
6438 // Push a fake return address on the stack. We will resume here when the
6439 // generator returns.
6440 Label genStart, returnTarget;
6441 #ifdef JS_USE_LINK_REGISTER
6442 masm.call(&genStart);
6443 #else
6444 masm.callAndPushReturnAddress(&genStart);
6445 #endif
6446
6447 // Record the return address so the return offset -> pc mapping works.
6448 if (!handler.recordCallRetAddr(RetAddrEntry::Kind::IC,
6449 masm.currentOffset())) {
6450 return false;
6451 }
6452
6453 masm.jump(&returnTarget);
6454 masm.bind(&genStart);
6455 #ifdef JS_USE_LINK_REGISTER
6456 masm.pushReturnAddress();
6457 #endif
6458
6459 // Construct BaselineFrame.
6460 masm.push(FramePointer);
6461 masm.moveStackPtrTo(FramePointer);
6462
6463 // If profiler instrumentation is on, update lastProfilingFrame on
6464 // current JitActivation
6465 {
6466 Register scratchReg = scratch2;
6467 Label skip;
6468 AbsoluteAddress addressOfEnabled(
6469 runtime->geckoProfiler().addressOfEnabled());
6470 masm.branch32(Assembler::Equal, addressOfEnabled, Imm32(0), &skip);
6471 masm.loadJSContext(scratchReg);
6472 masm.loadPtr(Address(scratchReg, JSContext::offsetOfProfilingActivation()),
6473 scratchReg);
6474 masm.storePtr(
6475 FramePointer,
6476 Address(scratchReg, JitActivation::offsetOfLastProfilingFrame()));
6477 masm.bind(&skip);
6478 }
6479
6480 masm.subFromStackPtr(Imm32(BaselineFrame::Size()));
6481 masm.assertStackAlignment(sizeof(Value), 0);
6482
6483 // Store flags and env chain.
6484 masm.store32(Imm32(BaselineFrame::HAS_INITIAL_ENV), frame.addressOfFlags());
6485 masm.unboxObject(
6486 Address(genObj, AbstractGeneratorObject::offsetOfEnvironmentChainSlot()),
6487 scratch2);
6488 masm.storePtr(scratch2, frame.addressOfEnvironmentChain());
6489
6490 // Store the arguments object if there is one.
6491 Label noArgsObj;
6492 Address argsObjSlot(genObj, AbstractGeneratorObject::offsetOfArgsObjSlot());
6493 masm.fallibleUnboxObject(argsObjSlot, scratch2, &noArgsObj);
6494 {
6495 masm.storePtr(scratch2, frame.addressOfArgsObj());
6496 masm.or32(Imm32(BaselineFrame::HAS_ARGS_OBJ), frame.addressOfFlags());
6497 }
6498 masm.bind(&noArgsObj);
6499
6500 // Push locals and expression slots if needed.
6501 Label noStackStorage;
6502 Address stackStorageSlot(genObj,
6503 AbstractGeneratorObject::offsetOfStackStorageSlot());
6504 masm.fallibleUnboxObject(stackStorageSlot, scratch2, &noStackStorage);
6505 {
6506 Register initLength = regs.takeAny();
6507 masm.loadPtr(Address(scratch2, NativeObject::offsetOfElements()), scratch2);
6508 masm.load32(Address(scratch2, ObjectElements::offsetOfInitializedLength()),
6509 initLength);
6510 masm.store32(
6511 Imm32(0),
6512 Address(scratch2, ObjectElements::offsetOfInitializedLength()));
6513
6514 Label loop, loopDone;
6515 masm.branchTest32(Assembler::Zero, initLength, initLength, &loopDone);
6516 masm.bind(&loop);
6517 {
6518 masm.pushValue(Address(scratch2, 0));
6519 masm.guardedCallPreBarrierAnyZone(Address(scratch2, 0), MIRType::Value,
6520 scratch1);
6521 masm.addPtr(Imm32(sizeof(Value)), scratch2);
6522 masm.branchSub32(Assembler::NonZero, Imm32(1), initLength, &loop);
6523 }
6524 masm.bind(&loopDone);
6525 regs.add(initLength);
6526 }
6527
6528 masm.bind(&noStackStorage);
6529
6530 // Push arg, generator, resumeKind stack Values, in that order.
6531 masm.pushValue(Address(callerStackPtr, sizeof(Value)));
6532 masm.pushValue(JSVAL_TYPE_OBJECT, genObj);
6533 masm.pushValue(Address(callerStackPtr, 0));
6534
6535 masm.switchToObjectRealm(genObj, scratch2);
6536
6537 // Load script in scratch1.
6538 masm.unboxObject(
6539 Address(genObj, AbstractGeneratorObject::offsetOfCalleeSlot()), scratch1);
6540 masm.loadPrivate(Address(scratch1, JSFunction::offsetOfJitInfoOrScript()),
6541 scratch1);
6542
6543 // Load resume index in scratch2 and mark generator as running.
6544 Address resumeIndexSlot(genObj,
6545 AbstractGeneratorObject::offsetOfResumeIndexSlot());
6546 masm.unboxInt32(resumeIndexSlot, scratch2);
6547 masm.storeValue(Int32Value(AbstractGeneratorObject::RESUME_INDEX_RUNNING),
6548 resumeIndexSlot);
6549
6550 if (!emitEnterGeneratorCode(scratch1, scratch2, regs.getAny())) {
6551 return false;
6552 }
6553
6554 // Call into the VM to resume the generator in the C++ interpreter if there's
6555 // no JitScript.
6556 masm.bind(&interpret);
6557
6558 prepareVMCall();
6559
6560 pushArg(callerStackPtr);
6561 pushArg(genObj);
6562
6563 using Fn = bool (*)(JSContext*, HandleObject, Value*, MutableHandleValue);
6564 if (!callVM<Fn, jit::InterpretResume>()) {
6565 return false;
6566 }
6567
6568 masm.bind(&returnTarget);
6569
6570 // Restore Stack pointer
6571 masm.computeEffectiveAddress(frame.addressOfStackValue(-1),
6572 masm.getStackPointer());
6573
6574 // After the generator returns, we restore the stack pointer, switch back to
6575 // the current realm, push the return value, and we're done.
6576 if (!handler.realmIndependentJitcode()) {
6577 masm.switchToRealm(handler.maybeScript()->realm(), R2.scratchReg());
6578 } else {
6579 masm.switchToBaselineFrameRealm(R2.scratchReg());
6580 }
6581 restoreInterpreterPCReg();
6582 frame.popn(3);
6583 frame.push(R0);
6584 return true;
6585 }
6586
6587 template <typename Handler>
6588 bool BaselineCodeGen<Handler>::emit_CheckResumeKind() {
6589 // Load resumeKind in R1, generator in R0.
6590 frame.popRegsAndSync(2);
6591
6592 #ifdef DEBUG
6593 Label ok;
6594 masm.branchTestInt32(Assembler::Equal, R1, &ok);
6595 masm.assumeUnreachable("Expected int32 resumeKind");
6596 masm.bind(&ok);
6597 #endif
6598
6599 // If resumeKind is 'next' we don't have to do anything.
6600 Label done;
6601 masm.unboxInt32(R1, R1.scratchReg());
6602 masm.branch32(Assembler::Equal, R1.scratchReg(),
6603 Imm32(int32_t(GeneratorResumeKind::Next)), &done);
6604
6605 prepareVMCall();
6606
6607 pushArg(R1.scratchReg()); // resumeKind
6608
6609 masm.loadValue(frame.addressOfStackValue(-1), R2);
6610 pushArg(R2); // arg
6611
6612 masm.unboxObject(R0, R0.scratchReg());
6613 pushArg(R0.scratchReg()); // genObj
6614
6615 masm.loadBaselineFramePtr(FramePointer, R2.scratchReg());
6616 pushArg(R2.scratchReg()); // frame
6617
6618 using Fn = bool (*)(JSContext*, BaselineFrame*,
6619 Handle<AbstractGeneratorObject*>, HandleValue, int32_t);
6620 if (!callVM<Fn, jit::GeneratorThrowOrReturn>()) {
6621 return false;
6622 }
6623
6624 masm.bind(&done);
6625 return true;
6626 }
6627
6628 template <>
6629 bool BaselineCompilerCodeGen::emit_ResumeKind() {
6630 GeneratorResumeKind resumeKind = ResumeKindFromPC(handler.pc());
6631 frame.push(Int32Value(int32_t(resumeKind)));
6632 return true;
6633 }
6634
6635 template <>
6636 bool BaselineInterpreterCodeGen::emit_ResumeKind() {
6637 LoadUint8Operand(masm, R0.scratchReg());
6638 masm.tagValue(JSVAL_TYPE_INT32, R0.scratchReg(), R0);
6639 frame.push(R0);
6640 return true;
6641 }
6642
6643 template <typename Handler>
6644 bool BaselineCodeGen<Handler>::emit_DebugCheckSelfHosted() {
6645 #ifdef DEBUG
6646 frame.syncStack(0);
6647
6648 masm.loadValue(frame.addressOfStackValue(-1), R0);
6649
6650 prepareVMCall();
6651 pushArg(R0);
6652
6653 using Fn = bool (*)(JSContext*, HandleValue);
6654 if (!callVM<Fn, js::Debug_CheckSelfHosted>()) {
6655 return false;
6656 }
6657 #endif
6658 return true;
6659 }
6660
6661 template <typename Handler>
6662 bool BaselineCodeGen<Handler>::emit_IsConstructing() {
6663 frame.push(MagicValue(JS_IS_CONSTRUCTING));
6664 return true;
6665 }
6666
6667 template <>
6668 bool BaselineCompilerCodeGen::emit_JumpTarget() {
6669 if (!handler.compilingOffThread()) {
6670 MaybeIncrementCodeCoverageCounter(masm, handler.script(), handler.pc());
6671 }
6672 return true;
6673 }
6674
6675 template <>
6676 bool BaselineInterpreterCodeGen::emit_JumpTarget() {
6677 Register scratch1 = R0.scratchReg();
6678 Register scratch2 = R1.scratchReg();
6679
6680 Label skipCoverage;
6681 CodeOffset toggleOffset = masm.toggledJump(&skipCoverage);
6682 masm.call(handler.codeCoverageAtPCLabel());
6683 masm.bind(&skipCoverage);
6684 if (!handler.codeCoverageOffsets().append(toggleOffset.offset())) {
6685 return false;
6686 }
6687
6688 // Load icIndex in scratch1.
6689 LoadInt32Operand(masm, scratch1);
6690
6691 // Compute ICEntry* and store to frame->interpreterICEntry.
6692 masm.loadPtr(frame.addressOfICScript(), scratch2);
6693 static_assert(sizeof(ICEntry) == sizeof(uintptr_t));
6694 masm.computeEffectiveAddress(BaseIndex(scratch2, scratch1, ScalePointer,
6695 ICScript::offsetOfICEntries()),
6696 scratch2);
6697 masm.storePtr(scratch2, frame.addressOfInterpreterICEntry());
6698 return true;
6699 }
6700
6701 template <typename Handler>
6702 bool BaselineCodeGen<Handler>::emit_CheckClassHeritage() {
6703 frame.syncStack(0);
6704
6705 // Leave the heritage value on the stack.
6706 masm.loadValue(frame.addressOfStackValue(-1), R0);
6707
6708 prepareVMCall();
6709 pushArg(R0);
6710
6711 using Fn = bool (*)(JSContext*, HandleValue);
6712 return callVM<Fn, js::CheckClassHeritageOperation>();
6713 }
6714
6715 template <typename Handler>
6716 bool BaselineCodeGen<Handler>::emit_InitHomeObject() {
6717 // Load HomeObject in R0.
6718 frame.popRegsAndSync(1);
6719
6720 // Load function off stack
6721 Register func = R2.scratchReg();
6722 masm.unboxObject(frame.addressOfStackValue(-1), func);
6723
6724 masm.assertFunctionIsExtended(func);
6725
6726 // Set HOMEOBJECT_SLOT
6727 Register temp = R1.scratchReg();
6728 Address addr(func, FunctionExtended::offsetOfMethodHomeObjectSlot());
6729 masm.guardedCallPreBarrierAnyZone(addr, MIRType::Value, temp);
6730 masm.storeValue(R0, addr);
6731
6732 Label skipBarrier;
6733 masm.branchPtrInNurseryChunk(Assembler::Equal, func, temp, &skipBarrier);
6734 masm.branchValueIsNurseryCell(Assembler::NotEqual, R0, temp, &skipBarrier);
6735 masm.call(&postBarrierSlot_);
6736 masm.bind(&skipBarrier);
6737
6738 return true;
6739 }
6740
6741 template <typename Handler>
6742 bool BaselineCodeGen<Handler>::emit_BuiltinObject() {
6743 frame.syncStack(0);
6744
6745 if (!emitNextIC()) {
6746 return false;
6747 }
6748
6749 // Mark R0 as pushed stack value.
6750 frame.push(R0);
6751 return true;
6752 }
6753
6754 template <typename Handler>
6755 bool BaselineCodeGen<Handler>::emit_ObjWithProto() {
6756 frame.syncStack(0);
6757
6758 // Leave the proto value on the stack for the decompiler
6759 masm.loadValue(frame.addressOfStackValue(-1), R0);
6760
6761 prepareVMCall();
6762 pushArg(R0);
6763
6764 using Fn = PlainObject* (*)(JSContext*, HandleValue);
6765 if (!callVM<Fn, js::ObjectWithProtoOperation>()) {
6766 return false;
6767 }
6768
6769 masm.tagValue(JSVAL_TYPE_OBJECT, ReturnReg, R0);
6770 frame.pop();
6771 frame.push(R0);
6772 return true;
6773 }
6774
6775 template <typename Handler>
6776 bool BaselineCodeGen<Handler>::emit_FunWithProto() {
6777 frame.popRegsAndSync(1);
6778
6779 masm.unboxObject(R0, R0.scratchReg());
6780 masm.loadPtr(frame.addressOfEnvironmentChain(), R1.scratchReg());
6781
6782 prepareVMCall();
6783 pushArg(R0.scratchReg());
6784 pushArg(R1.scratchReg());
6785 pushScriptGCThingArg(ScriptGCThingType::Function, R0.scratchReg(),
6786 R1.scratchReg());
6787
6788 using Fn =
6789 JSObject* (*)(JSContext*, HandleFunction, HandleObject, HandleObject);
6790 if (!callVM<Fn, js::FunWithProtoOperation>()) {
6791 return false;
6792 }
6793
6794 masm.tagValue(JSVAL_TYPE_OBJECT, ReturnReg, R0);
6795 frame.push(R0);
6796 return true;
6797 }
6798
6799 template <typename Handler>
6800 bool BaselineCodeGen<Handler>::emit_ImportMeta() {
6801 frame.syncStack(0);
6802
6803 if (!emitNextIC()) {
6804 return false;
6805 }
6806
6807 // Mark R0 as pushed stack value.
6808 frame.push(R0);
6809 return true;
6810 }
6811
6812 template <typename Handler>
6813 bool BaselineCodeGen<Handler>::emit_DynamicImport() {
6814 // Put specifier into R0 and object value into R1
6815 frame.popRegsAndSync(2);
6816
6817 prepareVMCall();
6818 pushArg(R1);
6819 pushArg(R0);
6820 pushScriptArg();
6821
6822 using Fn = JSObject* (*)(JSContext*, HandleScript, HandleValue, HandleValue);
6823 if (!callVM<Fn, js::StartDynamicModuleImport>()) {
6824 return false;
6825 }
6826
6827 masm.tagValue(JSVAL_TYPE_OBJECT, ReturnReg, R0);
6828 frame.push(R0);
6829 return true;
6830 }
6831
6832 template <>
6833 bool BaselineCompilerCodeGen::emit_ForceInterpreter() {
6834 // Caller is responsible for checking script->hasForceInterpreterOp().
6835 MOZ_CRASH("JSOp::ForceInterpreter in baseline");
6836 }
6837
6838 template <>
6839 bool BaselineInterpreterCodeGen::emit_ForceInterpreter() {
6840 masm.assumeUnreachable("JSOp::ForceInterpreter");
6841 return true;
6842 }
6843
6844 template <typename Handler>
6845 bool BaselineCodeGen<Handler>::emitPrologue() {
6846 AutoCreatedBy acb(masm, "BaselineCodeGen<Handler>::emitPrologue");
6847
6848 #ifdef JS_USE_LINK_REGISTER
6849 // Push link register from generateEnterJIT()'s BLR.
6850 masm.pushReturnAddress();
6851 #endif
6852
6853 masm.push(FramePointer);
6854 masm.moveStackPtrTo(FramePointer);
6855
6856 masm.checkStackAlignment();
6857
6858 emitProfilerEnterFrame();
6859
6860 masm.subFromStackPtr(Imm32(BaselineFrame::Size()));
6861
6862 // Initialize BaselineFrame. Also handles env chain pre-initialization (in
6863 // case GC gets run during stack check). For global and eval scripts, the env
6864 // chain is in R1. For function scripts, the env chain is in the callee.
6865 emitInitFrameFields(R1.scratchReg());
6866
6867 // When compiling with Debugger instrumentation, set the debuggeeness of
6868 // the frame before any operation that can call into the VM.
6869 if (!emitIsDebuggeeCheck()) {
6870 return false;
6871 }
6872
6873 // Initialize the env chain before any operation that may call into the VM and
6874 // trigger a GC.
6875 if (!initEnvironmentChain()) {
6876 return false;
6877 }
6878
6879 // Check for overrecursion before initializing locals.
6880 if (!emitStackCheck()) {
6881 return false;
6882 }
6883
6884 emitInitializeLocals();
6885
6886 // Ion prologue bailouts will enter here in the Baseline Interpreter.
6887 masm.bind(&bailoutPrologue_);
6888
6889 frame.assertSyncedStack();
6890
6891 if (!handler.realmIndependentJitcode()) {
6892 masm.debugAssertContextRealm(handler.maybeScript()->realm(),
6893 R1.scratchReg());
6894 }
6895
6896 if (!emitDebugPrologue()) {
6897 return false;
6898 }
6899
6900 if (!emitHandleCodeCoverageAtPrologue()) {
6901 return false;
6902 }
6903
6904 if (!emitWarmUpCounterIncrement()) {
6905 return false;
6906 }
6907
6908 warmUpCheckPrologueOffset_ = CodeOffset(masm.currentOffset());
6909
6910 return true;
6911 }
6912
6913 template <typename Handler>
6914 bool BaselineCodeGen<Handler>::emitEpilogue() {
6915 AutoCreatedBy acb(masm, "BaselineCodeGen<Handler>::emitEpilogue");
6916
6917 masm.bind(&return_);
6918
6919 if (!handler.shouldEmitDebugEpilogueAtReturnOp()) {
6920 if (!emitDebugEpilogue()) {
6921 return false;
6922 }
6923 }
6924
6925 emitProfilerExitFrame();
6926
6927 masm.moveToStackPtr(FramePointer);
6928 masm.pop(FramePointer);
6929
6930 masm.ret();
6931 return true;
6932 }
6933
6934 bool BaselineCompiler::emitBody() {
6935 AutoCreatedBy acb(masm, "BaselineCompiler::emitBody");
6936
6937 JSScript* script = handler.script();
6938 MOZ_ASSERT(handler.pc() == script->code());
6939
6940 mozilla::DebugOnly<jsbytecode*> prevpc = handler.pc();
6941
6942 while (true) {
6943 JSOp op = JSOp(*handler.pc());
6944 JitSpew(JitSpew_BaselineOp, "Compiling op @ %d: %s",
6945 int(script->pcToOffset(handler.pc())), CodeName(op));
6946
6947 BytecodeInfo* info = handler.analysis().maybeInfo(handler.pc());
6948
6949 // Skip unreachable ops.
6950 if (!info) {
6951 // Test if last instructions and stop emitting in that case.
6952 handler.moveToNextPC();
6953 if (handler.pc() >= script->codeEnd()) {
6954 break;
6955 }
6956
6957 prevpc = handler.pc();
6958 continue;
6959 }
6960
6961 if (info->jumpTarget) {
6962 // Fully sync the stack if there are incoming jumps.
6963 frame.syncStack(0);
6964 frame.setStackDepth(info->stackDepth);
6965 masm.bind(handler.labelOf(handler.pc()));
6966 } else if (MOZ_UNLIKELY(compileDebugInstrumentation())) {
6967 // Also fully sync the stack if the debugger is enabled.
6968 frame.syncStack(0);
6969 } else {
6970 // At the beginning of any op, at most the top 2 stack-values are
6971 // unsynced.
6972 if (frame.stackDepth() > 2) {
6973 frame.syncStack(2);
6974 }
6975 }
6976
6977 frame.assertValidState(*info);
6978
6979 // If the script has a resume offset for this pc we need to keep track of
6980 // the native code offset.
6981 if (info->hasResumeOffset) {
6982 frame.assertSyncedStack();
6983 uint32_t pcOffset = script->pcToOffset(handler.pc());
6984 uint32_t nativeOffset = masm.currentOffset();
6985 if (!resumeOffsetEntries_.emplaceBack(pcOffset, nativeOffset)) {
6986 return false;
6987 }
6988 }
6989
6990 // Emit traps for breakpoints and step mode.
6991 if (MOZ_UNLIKELY(compileDebugInstrumentation()) && !emitDebugTrap()) {
6992 return false;
6993 }
6994
6995 perfSpewer_.recordInstruction(masm, handler.pc(), frame);
6996
6997 #define EMIT_OP(OP, ...) \
6998 case JSOp::OP: { \
6999 AutoCreatedBy acb(masm, "op=" #OP); \
7000 if (MOZ_UNLIKELY(!this->emit_##OP())) return false; \
7001 } break;
7002
7003 switch (op) {
7004 FOR_EACH_OPCODE(EMIT_OP)
7005 default:
7006 MOZ_CRASH("Unexpected op");
7007 }
7008
7009 #undef EMIT_OP
7010
7011 MOZ_ASSERT(masm.framePushed() == 0);
7012
7013 // Test if last instructions and stop emitting in that case.
7014 handler.moveToNextPC();
7015 if (handler.pc() >= script->codeEnd()) {
7016 break;
7017 }
7018
7019 #ifdef DEBUG
7020 prevpc = handler.pc();
7021 #endif
7022 }
7023
7024 MOZ_ASSERT(JSOp(*prevpc) == JSOp::RetRval || JSOp(*prevpc) == JSOp::Return);
7025 return true;
7026 }
7027
7028 bool BaselineInterpreterGenerator::emitDebugTrap() {
7029 CodeOffset offset = masm.nopPatchableToCall();
7030 if (!debugTrapOffsets_.append(offset.offset())) {
7031 return false;
7032 }
7033
7034 return true;
7035 }
7036
7037 // Register holding the bytecode pc during dispatch. This exists so the debug
7038 // trap handler can reload the pc into this register when it's done.
7039 static constexpr Register InterpreterPCRegAtDispatch =
7040 HasInterpreterPCReg() ? InterpreterPCReg : R0.scratchReg();
7041
7042 bool BaselineInterpreterGenerator::emitInterpreterLoop() {
7043 AutoCreatedBy acb(masm, "BaselineInterpreterGenerator::emitInterpreterLoop");
7044
7045 Register scratch1 = R0.scratchReg();
7046 Register scratch2 = R1.scratchReg();
7047
7048 // Entry point for interpreting a bytecode op. No registers are live except
7049 // for InterpreterPCReg.
7050 masm.bind(handler.interpretOpWithPCRegLabel());
7051
7052 // Emit a patchable call for debugger breakpoints/stepping.
7053 if (!emitDebugTrap()) {
7054 return false;
7055 }
7056 Label interpretOpAfterDebugTrap;
7057 masm.bind(&interpretOpAfterDebugTrap);
7058
7059 // Load pc, bytecode op.
7060 Register pcReg = LoadBytecodePC(masm, scratch1);
7061 masm.load8ZeroExtend(Address(pcReg, 0), scratch1);
7062
7063 // Jump to table[op].
7064 {
7065 CodeOffset label = masm.moveNearAddressWithPatch(scratch2);
7066 if (!tableLabels_.append(label)) {
7067 return false;
7068 }
7069 BaseIndex pointer(scratch2, scratch1, ScalePointer);
7070 masm.branchToComputedAddress(pointer);
7071 }
7072
7073 // At the end of each op, emit code to bump the pc and jump to the
7074 // next op (this is also known as a threaded interpreter).
7075 auto opEpilogue = [&](JSOp op, size_t opLength) -> bool {
7076 MOZ_ASSERT(masm.framePushed() == 0);
7077
7078 if (!BytecodeFallsThrough(op)) {
7079 // Nothing to do.
7080 masm.assumeUnreachable("unexpected fall through");
7081 return true;
7082 }
7083
7084 // Bump frame->interpreterICEntry if needed.
7085 if (BytecodeOpHasIC(op)) {
7086 frame.bumpInterpreterICEntry();
7087 }
7088
7089 // Bump bytecode PC.
7090 if (HasInterpreterPCReg()) {
7091 MOZ_ASSERT(InterpreterPCRegAtDispatch == InterpreterPCReg);
7092 masm.addPtr(Imm32(opLength), InterpreterPCReg);
7093 } else {
7094 MOZ_ASSERT(InterpreterPCRegAtDispatch == scratch1);
7095 masm.loadPtr(frame.addressOfInterpreterPC(), InterpreterPCRegAtDispatch);
7096 masm.addPtr(Imm32(opLength), InterpreterPCRegAtDispatch);
7097 masm.storePtr(InterpreterPCRegAtDispatch, frame.addressOfInterpreterPC());
7098 }
7099
7100 if (!emitDebugTrap()) {
7101 return false;
7102 }
7103
7104 // Load the opcode, jump to table[op].
7105 masm.load8ZeroExtend(Address(InterpreterPCRegAtDispatch, 0), scratch1);
7106 CodeOffset label = masm.moveNearAddressWithPatch(scratch2);
7107 if (!tableLabels_.append(label)) {
7108 return false;
7109 }
7110 BaseIndex pointer(scratch2, scratch1, ScalePointer);
7111 masm.branchToComputedAddress(pointer);
7112 return true;
7113 };
7114
7115 // Emit code for each bytecode op.
7116 Label opLabels[JSOP_LIMIT];
7117 #define EMIT_OP(OP, ...) \
7118 { \
7119 AutoCreatedBy acb(masm, "op=" #OP); \
7120 perfSpewer_.recordOffset(masm, JSOp::OP); \
7121 masm.bind(&opLabels[uint8_t(JSOp::OP)]); \
7122 handler.setCurrentOp(JSOp::OP); \
7123 if (!this->emit_##OP()) { \
7124 return false; \
7125 } \
7126 if (!opEpilogue(JSOp::OP, JSOpLength_##OP)) { \
7127 return false; \
7128 } \
7129 handler.resetCurrentOp(); \
7130 }
7131 FOR_EACH_OPCODE(EMIT_OP)
7132 #undef EMIT_OP
7133
7134 // External entry point to start interpreting bytecode ops. This is used for
7135 // things like exception handling and OSR. DebugModeOSR patches JIT frames to
7136 // return here from the DebugTrapHandler.
7137 masm.bind(handler.interpretOpLabel());
7138 interpretOpOffset_ = masm.currentOffset();
7139 restoreInterpreterPCReg();
7140 masm.jump(handler.interpretOpWithPCRegLabel());
7141
7142 // Second external entry point: this skips the debug trap for the first op
7143 // and is used by OSR.
7144 interpretOpNoDebugTrapOffset_ = masm.currentOffset();
7145 restoreInterpreterPCReg();
7146 masm.jump(&interpretOpAfterDebugTrap);
7147
7148 // External entry point for Ion prologue bailouts.
7149 bailoutPrologueOffset_ = CodeOffset(masm.currentOffset());
7150 restoreInterpreterPCReg();
7151 masm.jump(&bailoutPrologue_);
7152
7153 // Emit debug trap handler code (target of patchable call instructions). This
7154 // is just a tail call to the debug trap handler trampoline code.
7155 {
7156 JitCode* handlerCode = runtime->jitRuntime()->debugTrapHandler(
7157 DebugTrapHandlerKind::Interpreter);
7158 debugTrapHandlerOffset_ = masm.currentOffset();
7159 masm.jump(handlerCode);
7160 }
7161
7162 // Emit the table.
7163 masm.haltingAlign(sizeof(void*));
7164
7165 #if defined(JS_CODEGEN_ARM) || defined(JS_CODEGEN_ARM64)
7166 size_t numInstructions = JSOP_LIMIT * (sizeof(uintptr_t) / sizeof(uint32_t));
7167 AutoForbidPoolsAndNops afp(&masm, numInstructions);
7168 #endif
7169
7170 tableOffset_ = masm.currentOffset();
7171
7172 for (size_t i = 0; i < JSOP_LIMIT; i++) {
7173 const Label& opLabel = opLabels[i];
7174 MOZ_ASSERT(opLabel.bound());
7175 CodeLabel cl;
7176 masm.writeCodePointer(&cl);
7177 cl.target()->bind(opLabel.offset());
7178 masm.addCodeLabel(cl);
7179 }
7180
7181 return true;
7182 }
7183
7184 void BaselineInterpreterGenerator::emitOutOfLineCodeCoverageInstrumentation() {
7185 AutoCreatedBy acb(masm,
7186 "BaselineInterpreterGenerator::"
7187 "emitOutOfLineCodeCoverageInstrumentation");
7188
7189 masm.bind(handler.codeCoverageAtPrologueLabel());
7190 #ifdef JS_USE_LINK_REGISTER
7191 masm.pushReturnAddress();
7192 #endif
7193
7194 saveInterpreterPCReg();
7195
7196 using Fn1 = void (*)(BaselineFrame* frame);
7197 masm.setupUnalignedABICall(R0.scratchReg());
7198 masm.loadBaselineFramePtr(FramePointer, R0.scratchReg());
7199 masm.passABIArg(R0.scratchReg());
7200 masm.callWithABI<Fn1, HandleCodeCoverageAtPrologue>();
7201
7202 restoreInterpreterPCReg();
7203 masm.ret();
7204
7205 masm.bind(handler.codeCoverageAtPCLabel());
7206 #ifdef JS_USE_LINK_REGISTER
7207 masm.pushReturnAddress();
7208 #endif
7209
7210 saveInterpreterPCReg();
7211
7212 using Fn2 = void (*)(BaselineFrame* frame, jsbytecode* pc);
7213 masm.setupUnalignedABICall(R0.scratchReg());
7214 masm.loadBaselineFramePtr(FramePointer, R0.scratchReg());
7215 masm.passABIArg(R0.scratchReg());
7216 Register pcReg = LoadBytecodePC(masm, R2.scratchReg());
7217 masm.passABIArg(pcReg);
7218 masm.callWithABI<Fn2, HandleCodeCoverageAtPC>();
7219
7220 restoreInterpreterPCReg();
7221 masm.ret();
7222 }
7223
7224 bool BaselineInterpreterGenerator::generate(JSContext* cx,
7225 BaselineInterpreter& interpreter) {
7226 AutoCreatedBy acb(masm, "BaselineInterpreterGenerator::generate");
7227
7228 if (!cx->runtime()->jitRuntime()->ensureDebugTrapHandler(
7229 cx, DebugTrapHandlerKind::Interpreter)) {
7230 return false;
7231 }
7232
7233 perfSpewer_.recordOffset(masm, "Prologue");
7234 if (!emitPrologue()) {
7235 ReportOutOfMemory(cx);
7236 return false;
7237 }
7238
7239 perfSpewer_.recordOffset(masm, "InterpreterLoop");
7240 if (!emitInterpreterLoop()) {
7241 ReportOutOfMemory(cx);
7242 return false;
7243 }
7244
7245 perfSpewer_.recordOffset(masm, "Epilogue");
7246 if (!emitEpilogue()) {
7247 ReportOutOfMemory(cx);
7248 return false;
7249 }
7250
7251 perfSpewer_.recordOffset(masm, "OOLPostBarrierSlot");
7252 emitOutOfLinePostBarrierSlot();
7253
7254 perfSpewer_.recordOffset(masm, "OOLCodeCoverageInstrumentation");
7255 emitOutOfLineCodeCoverageInstrumentation();
7256
7257 {
7258 AutoCreatedBy acb(masm, "everything_else");
7259 Linker linker(masm);
7260 if (masm.oom()) {
7261 ReportOutOfMemory(cx);
7262 return false;
7263 }
7264
7265 JitCode* code = linker.newCode(cx, CodeKind::Other);
7266 if (!code) {
7267 return false;
7268 }
7269
7270 // Register BaselineInterpreter code with the profiler's JitCode table.
7271 {
7272 auto entry = MakeJitcodeGlobalEntry<BaselineInterpreterEntry>(
7273 cx, code, code->raw(), code->rawEnd());
7274 if (!entry) {
7275 return false;
7276 }
7277
7278 JitcodeGlobalTable* globalTable =
7279 cx->runtime()->jitRuntime()->getJitcodeGlobalTable();
7280 if (!globalTable->addEntry(std::move(entry))) {
7281 ReportOutOfMemory(cx);
7282 return false;
7283 }
7284
7285 code->setHasBytecodeMap();
7286 }
7287
7288 // Patch loads now that we know the tableswitch base address.
7289 CodeLocationLabel tableLoc(code, CodeOffset(tableOffset_));
7290 for (CodeOffset off : tableLabels_) {
7291 MacroAssembler::patchNearAddressMove(CodeLocationLabel(code, off),
7292 tableLoc);
7293 }
7294
7295 perfSpewer_.saveProfile(code);
7296
7297 #ifdef MOZ_VTUNE
7298 vtune::MarkStub(code, "BaselineInterpreter");
7299 #endif
7300
7301 interpreter.init(
7302 code, interpretOpOffset_, interpretOpNoDebugTrapOffset_,
7303 bailoutPrologueOffset_.offset(),
7304 profilerEnterFrameToggleOffset_.offset(),
7305 profilerExitFrameToggleOffset_.offset(), debugTrapHandlerOffset_,
7306 std::move(handler.debugInstrumentationOffsets()),
7307 std::move(debugTrapOffsets_), std::move(handler.codeCoverageOffsets()),
7308 std::move(handler.icReturnOffsets()), handler.callVMOffsets());
7309 }
7310
7311 if (cx->runtime()->geckoProfiler().enabled()) {
7312 interpreter.toggleProfilerInstrumentation(true);
7313 }
7314
7315 if (coverage::IsLCovEnabled()) {
7316 interpreter.toggleCodeCoverageInstrumentationUnchecked(true);
7317 }
7318
7319 return true;
7320 }
7321
7322 JitCode* JitRuntime::generateDebugTrapHandler(JSContext* cx,
7323 DebugTrapHandlerKind kind) {
7324 TempAllocator temp(&cx->tempLifoAlloc());
7325 StackMacroAssembler masm(cx, temp);
7326 AutoCreatedBy acb(masm, "JitRuntime::generateDebugTrapHandler");
7327
7328 AllocatableGeneralRegisterSet regs(GeneralRegisterSet::All());
7329 MOZ_ASSERT(!regs.has(FramePointer));
7330 regs.takeUnchecked(ICStubReg);
7331 if (HasInterpreterPCReg()) {
7332 regs.takeUnchecked(InterpreterPCReg);
7333 }
7334 #ifdef JS_CODEGEN_ARM
7335 regs.takeUnchecked(BaselineSecondScratchReg);
7336 AutoNonDefaultSecondScratchRegister andssr(masm, BaselineSecondScratchReg);
7337 #endif
7338 Register scratch1 = regs.takeAny();
7339 Register scratch2 = regs.takeAny();
7340 Register scratch3 = regs.takeAny();
7341
7342 if (kind == DebugTrapHandlerKind::Interpreter) {
7343 // The interpreter calls this for every script when debugging, so check if
7344 // the script has any breakpoints or is in step mode before calling into
7345 // C++.
7346 Label hasDebugScript;
7347 Address scriptAddr(FramePointer,
7348 BaselineFrame::reverseOffsetOfInterpreterScript());
7349 masm.loadPtr(scriptAddr, scratch1);
7350 masm.branchTest32(Assembler::NonZero,
7351 Address(scratch1, JSScript::offsetOfMutableFlags()),
7352 Imm32(int32_t(JSScript::MutableFlags::HasDebugScript)),
7353 &hasDebugScript);
7354 masm.abiret();
7355 masm.bind(&hasDebugScript);
7356
7357 if (HasInterpreterPCReg()) {
7358 // Update frame's bytecode pc because the debugger depends on it.
7359 Address pcAddr(FramePointer,
7360 BaselineFrame::reverseOffsetOfInterpreterPC());
7361 masm.storePtr(InterpreterPCReg, pcAddr);
7362 }
7363 }
7364
7365 // Load the return address in scratch1.
7366 masm.loadAbiReturnAddress(scratch1);
7367
7368 // Load BaselineFrame pointer in scratch2.
7369 masm.loadBaselineFramePtr(FramePointer, scratch2);
7370
7371 // Enter a stub frame and call the HandleDebugTrap VM function. Ensure
7372 // the stub frame has a nullptr ICStub pointer, since this pointer is marked
7373 // during GC.
7374 masm.movePtr(ImmPtr(nullptr), ICStubReg);
7375 EmitBaselineEnterStubFrame(masm, scratch3);
7376
7377 using Fn = bool (*)(JSContext*, BaselineFrame*, const uint8_t*);
7378 VMFunctionId id = VMFunctionToId<Fn, jit::HandleDebugTrap>::id;
7379 TrampolinePtr code = cx->runtime()->jitRuntime()->getVMWrapper(id);
7380
7381 masm.push(scratch1);
7382 masm.push(scratch2);
7383 EmitBaselineCallVM(code, masm);
7384
7385 EmitBaselineLeaveStubFrame(masm);
7386
7387 if (kind == DebugTrapHandlerKind::Interpreter) {
7388 // We have to reload the bytecode pc register.
7389 Address pcAddr(FramePointer, BaselineFrame::reverseOffsetOfInterpreterPC());
7390 masm.loadPtr(pcAddr, InterpreterPCRegAtDispatch);
7391 }
7392 masm.abiret();
7393
7394 Linker linker(masm);
7395 JitCode* handlerCode = linker.newCode(cx, CodeKind::Other);
7396 if (!handlerCode) {
7397 return nullptr;
7398 }
7399
7400 CollectPerfSpewerJitCodeProfile(handlerCode, "DebugTrapHandler");
7401
7402 #ifdef MOZ_VTUNE
7403 vtune::MarkStub(handlerCode, "DebugTrapHandler");
7404 #endif
7405
7406 return handlerCode;
7407 }
7408
7409 } // namespace jit
7410 } // namespace js