Debian Codegraph @

js/src/jit/BaselineCodeGen.h

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 #ifndef jit_BaselineCodeGen_h
8 #define jit_BaselineCodeGen_h
9
10 #include "jit/BaselineFrameInfo.h"
11 #include "jit/BytecodeAnalysis.h"
12 #include "jit/CompileWrappers.h"
13 #include "jit/FixedList.h"
14 #include "jit/MacroAssembler.h"
15 #include "jit/PerfSpewer.h"
16
17 namespace js {
18
19 namespace jit {
20
21 class BaselineSnapshot;
22
23 enum class ScriptGCThingType {
24 Atom,
25 String,
26 RegExp,
27 Object,
28 Function,
29 Scope,
30 BigInt
31 };
32
33 // Base class for BaselineCompiler and BaselineInterpreterGenerator. The Handler
34 // template is a class storing fields/methods that are interpreter or compiler
35 // specific. This can be combined with template specialization of methods in
36 // this class to specialize behavior.
37 template <typename Handler>
38 class BaselineCodeGen {
39 protected:
40 Handler handler;
41
42 CompileRuntime* runtime;
43 MacroAssembler& masm;
44
45 typename Handler::FrameInfoT& frame;
46
47 // Shared epilogue code to return to the caller.
48 NonAssertingLabel return_;
49
50 NonAssertingLabel postBarrierSlot_;
51
52 // Prologue code where we resume for Ion prologue bailouts.
53 NonAssertingLabel bailoutPrologue_;
54
55 CodeOffset profilerEnterFrameToggleOffset_;
56 CodeOffset profilerExitFrameToggleOffset_;
57
58 // Early Ion bailouts will enter at this address. This is after frame
59 // construction and before environment chain is initialized.
60 CodeOffset bailoutPrologueOffset_;
61
62 // Baseline Interpreter can enter Baseline Compiler code at this address. This
63 // is right after the warm-up counter check in the prologue.
64 CodeOffset warmUpCheckPrologueOffset_;
65
66 uint32_t pushedBeforeCall_ = 0;
67 #ifdef DEBUG
68 bool inCall_ = false;
69 #endif
70
71 template <typename... HandlerArgs>
72 explicit BaselineCodeGen(TempAllocator& alloc, MacroAssembler& masmArg,
73 CompileRuntime* runtimeArg, HandlerArgs&&... args);
74
75 template <typename T>
76 void pushArg(const T& t) {
77 masm.Push(t);
78 }
79
80 // Pushes the current script as argument for a VM function.
81 void pushScriptArg();
82
83 // Pushes the bytecode pc as argument for a VM function.
84 void pushBytecodePCArg();
85
86 // Pushes a name/object/scope associated with the current bytecode op (and
87 // stored in the script) as argument for a VM function.
88 void loadScriptGCThing(ScriptGCThingType type, Register dest,
89 Register scratch);
90 void loadScriptGCThingInternal(ScriptGCThingType type, Register dest,
91 Register scratch);
92 void pushScriptGCThingArg(ScriptGCThingType type, Register scratch1,
93 Register scratch2);
94 void pushScriptNameArg(Register scratch1, Register scratch2);
95
96 // Pushes a bytecode operand as argument for a VM function.
97 void pushUint8BytecodeOperandArg(Register scratch);
98 void pushUint16BytecodeOperandArg(Register scratch);
99
100 void loadInt32LengthBytecodeOperand(Register dest);
101 void loadNumFormalArguments(Register dest);
102
103 // Loads the current JSScript* in dest.
104 void loadScript(Register dest);
105 // Loads the current JitScript* in dest
106 void loadJitScript(Register dest);
107
108 void saveInterpreterPCReg();
109 void restoreInterpreterPCReg();
110
111 // Subtracts |script->nslots() * sizeof(Value)| from reg.
112 void subtractScriptSlotsSize(Register reg, Register scratch);
113
114 // Loads the resume entries of the current BaselineScript* in dest
115 void loadBaselineScriptResumeEntries(Register dest, Register scratch);
116
117 // Jump to the script's resume entry indicated by resumeIndex.
118 void jumpToResumeEntry(Register resumeIndex, Register scratch1,
119 Register scratch2);
120
121 // Load the global's lexical environment.
122 void loadGlobalLexicalEnvironment(Register dest);
123 void pushGlobalLexicalEnvironmentValue(ValueOperand scratch);
124
125 // Load the |this|-value from the global's lexical environment.
126 void loadGlobalThisValue(ValueOperand dest);
127
128 // Computes the frame size. See BaselineFrame::debugFrameSize_.
129 void computeFrameSize(Register dest);
130
131 void prepareVMCall();
132
133 void storeFrameSizeAndPushDescriptor(uint32_t argSize, Register scratch);
134
135 enum class CallVMPhase { BeforePushingLocals, AfterPushingLocals };
136 bool callVMInternal(VMFunctionId id, RetAddrEntry::Kind kind,
137 CallVMPhase phase);
138
139 template <typename Fn, Fn fn>
140 bool callVM(RetAddrEntry::Kind kind = RetAddrEntry::Kind::CallVM,
141 CallVMPhase phase = CallVMPhase::AfterPushingLocals);
142
143 template <typename Fn, Fn fn>
144 bool callVMNonOp(CallVMPhase phase = CallVMPhase::AfterPushingLocals) {
145 return callVM<Fn, fn>(RetAddrEntry::Kind::NonOpCallVM, phase);
146 }
147
148 // ifDebuggee should be a function emitting code for when the script is a
149 // debuggee script. ifNotDebuggee (if present) is called to emit code for
150 // non-debuggee scripts.
151 template <typename F1, typename F2>
152 [[nodiscard]] bool emitDebugInstrumentation(
153 const F1& ifDebuggee, const mozilla::Maybe<F2>& ifNotDebuggee);
154 template <typename F>
155 [[nodiscard]] bool emitDebugInstrumentation(const F& ifDebuggee) {
156 return emitDebugInstrumentation(ifDebuggee, mozilla::Maybe<F>());
157 }
158
159 bool emitSuspend(JSOp op);
160
161 template <typename F>
162 [[nodiscard]] bool emitAfterYieldDebugInstrumentation(const F& ifDebuggee,
163 Register scratch);
164
165 // ifSet should be a function emitting code for when the script has |flag|
166 // set. ifNotSet emits code for when the flag isn't set.
167 template <typename F1, typename F2>
168 [[nodiscard]] bool emitTestScriptFlag(JSScript::ImmutableFlags flag,
169 const F1& ifSet, const F2& ifNotSet,
170 Register scratch);
171
172 // If |script->hasFlag(flag) == value|, execute the code emitted by |emit|.
173 template <typename F>
174 [[nodiscard]] bool emitTestScriptFlag(JSScript::ImmutableFlags flag,
175 bool value, const F& emit,
176 Register scratch);
177 template <typename F>
178 [[nodiscard]] bool emitTestScriptFlag(JSScript::MutableFlags flag, bool value,
179 const F& emit, Register scratch);
180
181 [[nodiscard]] bool emitEnterGeneratorCode(Register script,
182 Register resumeIndex,
183 Register scratch);
184
185 void emitInterpJumpToResumeEntry(Register script, Register resumeIndex,
186 Register scratch);
187 void emitJumpToInterpretOpLabel();
188
189 [[nodiscard]] bool emitCheckThis(ValueOperand val, bool reinit = false);
190 void emitLoadReturnValue(ValueOperand val);
191 void emitGetAliasedVar(ValueOperand dest);
192 [[nodiscard]] bool emitGetAliasedDebugVar(ValueOperand dest);
193
194 [[nodiscard]] bool emitNextIC();
195 [[nodiscard]] bool emitInterruptCheck();
196 [[nodiscard]] bool emitWarmUpCounterIncrement();
197
198 #define EMIT_OP(op, ...) bool emit_##op();
199 FOR_EACH_OPCODE(EMIT_OP)
200 #undef EMIT_OP
201
202 // JSOp::Pos, JSOp::Neg, JSOp::BitNot, JSOp::Inc, JSOp::Dec, JSOp::ToNumeric.
203 [[nodiscard]] bool emitUnaryArith();
204
205 // JSOp::BitXor, JSOp::Lsh, JSOp::Add etc.
206 [[nodiscard]] bool emitBinaryArith();
207
208 // Handles JSOp::Lt, JSOp::Gt, and friends
209 [[nodiscard]] bool emitCompare();
210
211 [[nodiscard]] bool emitConstantStrictEq(JSOp op);
212
213 // Handles JSOp::NewObject and JSOp::NewInit.
214 [[nodiscard]] bool emitNewObject();
215
216 // For a JOF_JUMP op, jumps to the op's jump target.
217 void emitJump();
218
219 // For a JOF_JUMP op, jumps to the op's jump target depending on the Value
220 // in |val|.
221 void emitTestBooleanTruthy(bool branchIfTrue, ValueOperand val);
222
223 // Converts |val| to an index in the jump table and stores this in |dest|
224 // or branches to the default pc if not int32 or out-of-range.
225 void emitGetTableSwitchIndex(ValueOperand val, Register dest,
226 Register scratch1, Register scratch2);
227
228 // Jumps to the target of a table switch based on |key| and the
229 // firstResumeIndex stored in JSOp::TableSwitch.
230 void emitTableSwitchJump(Register key, Register scratch1, Register scratch2);
231
232 [[nodiscard]] bool emitReturn();
233
234 [[nodiscard]] bool emitTest(bool branchIfTrue);
235 [[nodiscard]] bool emitAndOr(bool branchIfTrue);
236 [[nodiscard]] bool emitCoalesce();
237
238 [[nodiscard]] bool emitCall(JSOp op);
239 [[nodiscard]] bool emitSpreadCall(JSOp op);
240
241 [[nodiscard]] bool emitDelElem(bool strict);
242 [[nodiscard]] bool emitDelProp(bool strict);
243 [[nodiscard]] bool emitSetElemSuper(bool strict);
244 [[nodiscard]] bool emitSetPropSuper(bool strict);
245
246 // Try to bake in the result of BindUnqualifiedGName instead of using an IC.
247 // Return true if we managed to optimize the op.
248 bool tryOptimizeBindUnqualifiedGlobalName();
249
250 [[nodiscard]] bool emitInitPropGetterSetter();
251 [[nodiscard]] bool emitInitElemGetterSetter();
252
253 [[nodiscard]] bool emitFormalArgAccess(JSOp op);
254
255 [[nodiscard]] bool emitUninitializedLexicalCheck(const ValueOperand& val);
256
257 [[nodiscard]] bool emitIsMagicValue();
258
259 void getEnvironmentCoordinateObject(Register reg);
260 Address getEnvironmentCoordinateAddressFromObject(Register objReg,
261 Register reg);
262 Address getEnvironmentCoordinateAddress(Register reg);
263
264 [[nodiscard]] bool emitPrologue();
265 [[nodiscard]] bool emitEpilogue();
266 [[nodiscard]] bool emitStackCheck();
267 [[nodiscard]] bool emitDebugPrologue();
268 [[nodiscard]] bool emitDebugEpilogue();
269
270 [[nodiscard]] bool initEnvironmentChain();
271
272 [[nodiscard]] bool emitHandleCodeCoverageAtPrologue();
273
274 void emitInitFrameFields(Register nonFunctionEnv);
275 [[nodiscard]] bool emitIsDebuggeeCheck();
276 void emitInitializeLocals();
277
278 void emitProfilerEnterFrame();
279 void emitProfilerExitFrame();
280
281 void emitOutOfLinePostBarrierSlot();
282 };
283
284 using RetAddrEntryVector = js::Vector<RetAddrEntry, 16, SystemAllocPolicy>;
285 using AllocSiteIndexVector = js::Vector<uint32_t, 16, SystemAllocPolicy>;
286
287 // Interface used by BaselineCodeGen for BaselineCompiler.
288 class BaselineCompilerHandler {
289 CompilerFrameInfo frame_;
290 TempAllocator& alloc_;
291 BytecodeAnalysis analysis_;
292 #ifdef DEBUG
293 const MacroAssembler& masm_;
294 #endif
295 FixedList<Label> labels_;
296 RetAddrEntryVector retAddrEntries_;
297 AllocSiteIndexVector allocSiteIndices_;
298
299 // Native code offsets for OSR at JSOp::LoopHead ops.
300 using OSREntryVector =
301 Vector<BaselineScript::OSREntry, 16, SystemAllocPolicy>;
302 OSREntryVector osrEntries_;
303
304 JSScript* script_;
305 jsbytecode* pc_;
306
307 JSObject* globalLexicalEnvironment_;
308 JSObject* globalThis_;
309
310 // Index of the current ICEntry in the script's JitScript.
311 uint32_t icEntryIndex_;
312
313 uint32_t baseWarmUpThreshold_;
314
315 bool compileDebugInstrumentation_;
316 bool ionCompileable_;
317
318 bool compilingOffThread_ = false;
319
320 bool needsEnvAllocSite_ = false;
321
322 public:
323 using FrameInfoT = CompilerFrameInfo;
324
325 BaselineCompilerHandler(MacroAssembler& masm, TempAllocator& alloc,
326 BaselineSnapshot* snapshot);
327
328 [[nodiscard]] bool init();
329
330 CompilerFrameInfo& frame() { return frame_; }
331
332 jsbytecode* pc() const { return pc_; }
333 jsbytecode* maybePC() const { return pc_; }
334
335 void moveToNextPC() { pc_ += GetBytecodeLength(pc_); }
336 Label* labelOf(jsbytecode* pc) { return &labels_[script_->pcToOffset(pc)]; }
337
338 bool isDefinitelyLastOp() const { return pc_ == script_->lastPC(); }
339
340 bool shouldEmitDebugEpilogueAtReturnOp() const {
341 // The JIT uses the return address -> pc mapping and bakes in the pc
342 // argument so the DebugEpilogue call needs to be part of the returning
343 // bytecode op for this to work.
344 return true;
345 }
346
347 JSScript* script() const { return script_; }
348 JSScript* maybeScript() const { return script_; }
349
350 JSFunction* function() const { return script_->function(); }
351 JSFunction* maybeFunction() const { return function(); }
352
353 ModuleObject* module() const { return script_->module(); }
354
355 bool compileDebugInstrumentation() const {
356 return compileDebugInstrumentation_;
357 }
358
359 bool maybeIonCompileable() const { return ionCompileable_; }
360 void setIonCompileable(bool value) { ionCompileable_ = value; }
361
362 uint32_t icEntryIndex() const { return icEntryIndex_; }
363 void moveToNextICEntry() { icEntryIndex_++; }
364
365 BytecodeAnalysis& analysis() { return analysis_; }
366
367 RetAddrEntryVector& retAddrEntries() { return retAddrEntries_; }
368 OSREntryVector& osrEntries() { return osrEntries_; }
369
370 [[nodiscard]] bool recordCallRetAddr(RetAddrEntry::Kind kind,
371 uint32_t retOffset);
372
373 // If a script has more |nslots| than this the stack check must account
374 // for these slots explicitly.
375 bool mustIncludeSlotsInStackCheck() const {
376 static constexpr size_t NumSlotsLimit = 128;
377 return script()->nslots() > NumSlotsLimit;
378 }
379
380 bool canHaveFixedSlots() const { return script()->nfixed() != 0; }
381
382 JSObject* maybeGlobalLexicalEnvironment() const {
383 return globalLexicalEnvironment_;
384 }
385 JSObject* globalThis() const { return globalThis_; }
386
387 uint32_t baseWarmUpThreshold() const { return baseWarmUpThreshold_; }
388
389 void maybeDisableIon();
390
391 [[nodiscard]] bool addAllocSiteIndex(uint32_t entryIndex) {
392 return allocSiteIndices_.append(entryIndex);
393 }
394 void createAllocSites();
395
396 bool compilingOffThread() const { return compilingOffThread_; }
397 void setCompilingOffThread() { compilingOffThread_ = true; }
398
399 bool addEnvAllocSite() {
400 needsEnvAllocSite_ = true;
401 return true;
402 }
403
404 bool realmIndependentJitcode() const {
405 return JS::Prefs::experimental_self_hosted_cache() &&
406 script()->selfHosted();
407 }
408 };
409
410 using BaselineCompilerCodeGen = BaselineCodeGen<BaselineCompilerHandler>;
411
412 class BaselineCompiler final : private BaselineCompilerCodeGen {
413 // Native code offsets for bytecode ops in the script's resume offsets list.
414 ResumeOffsetEntryVector resumeOffsetEntries_;
415
416 // Native code offsets for debug traps if the script is compiled with debug
417 // instrumentation.
418 using DebugTrapEntryVector =
419 Vector<BaselineScript::DebugTrapEntry, 0, SystemAllocPolicy>;
420 DebugTrapEntryVector debugTrapEntries_;
421
422 CodeOffset profilerPushToggleOffset_;
423
424 BaselinePerfSpewer perfSpewer_;
425
426 public:
427 BaselineCompiler(TempAllocator& alloc, CompileRuntime* runtime,
428 MacroAssembler& masm, BaselineSnapshot* snapshot);
429 [[nodiscard]] bool init();
430
431 static bool PrepareToCompile(JSContext* cx, Handle<JSScript*> script,
432 bool compileDebugInstrumentation);
433
434 MethodStatus compile(JSContext* cx);
435 MethodStatus compileOffThread();
436
437 bool finishCompile(JSContext* cx);
438
439 bool compileDebugInstrumentation() const {
440 return handler.compileDebugInstrumentation();
441 }
442
443 private:
444 bool compileImpl();
445
446 bool emitBody();
447
448 [[nodiscard]] bool emitDebugTrap();
449 };
450
451 // Interface used by BaselineCodeGen for BaselineInterpreterGenerator.
452 class BaselineInterpreterHandler {
453 InterpreterFrameInfo frame_;
454
455 // Entry point to start interpreting a bytecode op. No registers are live. PC
456 // is loaded from the frame.
457 NonAssertingLabel interpretOp_;
458
459 // Like interpretOp_ but at this point the PC is expected to be in
460 // InterpreterPCReg.
461 NonAssertingLabel interpretOpWithPCReg_;
462
463 // Offsets of toggled jumps for debugger instrumentation.
464 using CodeOffsetVector = Vector<uint32_t, 0, SystemAllocPolicy>;
465 CodeOffsetVector debugInstrumentationOffsets_;
466
467 // Offsets of toggled jumps for code coverage instrumentation.
468 CodeOffsetVector codeCoverageOffsets_;
469 NonAssertingLabel codeCoverageAtPrologueLabel_;
470 NonAssertingLabel codeCoverageAtPCLabel_;
471
472 // Offsets of IC calls for IsIonInlinableOp ops, for Ion bailouts.
473 BaselineInterpreter::ICReturnOffsetVector icReturnOffsets_;
474
475 // Offsets of some callVMs for BaselineDebugModeOSR.
476 BaselineInterpreter::CallVMOffsets callVMOffsets_;
477
478 // The current JSOp we are emitting interpreter code for.
479 mozilla::Maybe<JSOp> currentOp_;
480
481 public:
482 using FrameInfoT = InterpreterFrameInfo;
483
484 explicit BaselineInterpreterHandler(MacroAssembler& masm);
485
486 InterpreterFrameInfo& frame() { return frame_; }
487
488 Label* interpretOpLabel() { return &interpretOp_; }
489 Label* interpretOpWithPCRegLabel() { return &interpretOpWithPCReg_; }
490
491 Label* codeCoverageAtPrologueLabel() { return &codeCoverageAtPrologueLabel_; }
492 Label* codeCoverageAtPCLabel() { return &codeCoverageAtPCLabel_; }
493
494 CodeOffsetVector& debugInstrumentationOffsets() {
495 return debugInstrumentationOffsets_;
496 }
497 CodeOffsetVector& codeCoverageOffsets() { return codeCoverageOffsets_; }
498
499 BaselineInterpreter::ICReturnOffsetVector& icReturnOffsets() {
500 return icReturnOffsets_;
501 }
502
503 void setCurrentOp(JSOp op) { currentOp_.emplace(op); }
504 void resetCurrentOp() { currentOp_.reset(); }
505 mozilla::Maybe<JSOp> currentOp() const { return currentOp_; }
506
507 // Interpreter doesn't know the script and pc statically.
508 jsbytecode* maybePC() const { return nullptr; }
509 bool isDefinitelyLastOp() const { return false; }
510 JSScript* maybeScript() const { return nullptr; }
511 JSFunction* maybeFunction() const { return nullptr; }
512
513 bool shouldEmitDebugEpilogueAtReturnOp() const {
514 // The interpreter doesn't use the return address -> pc mapping and doesn't
515 // bake in bytecode PCs so it can emit a shared DebugEpilogue call instead
516 // of duplicating it for every return op.
517 return false;
518 }
519
520 [[nodiscard]] bool addDebugInstrumentationOffset(CodeOffset offset);
521
522 const BaselineInterpreter::CallVMOffsets& callVMOffsets() const {
523 return callVMOffsets_;
524 }
525
526 [[nodiscard]] bool recordCallRetAddr(RetAddrEntry::Kind kind,
527 uint32_t retOffset);
528
529 bool maybeIonCompileable() const { return true; }
530
531 // The interpreter doesn't know the number of slots statically so we always
532 // include them.
533 bool mustIncludeSlotsInStackCheck() const { return true; }
534
535 bool canHaveFixedSlots() const { return true; }
536 JSObject* maybeGlobalLexicalEnvironment() const { return nullptr; }
537
538 bool addEnvAllocSite() { return false; } // Not supported.
539
540 bool realmIndependentJitcode() const { return true; }
541 };
542
543 using BaselineInterpreterCodeGen = BaselineCodeGen<BaselineInterpreterHandler>;
544
545 class BaselineInterpreterGenerator final : private BaselineInterpreterCodeGen {
546 // Offsets of patchable call instructions for debugger breakpoints/stepping.
547 Vector<uint32_t, 0, SystemAllocPolicy> debugTrapOffsets_;
548
549 // Offsets of move instructions for tableswitch base address.
550 Vector<CodeOffset, 0, SystemAllocPolicy> tableLabels_;
551
552 // Offset of the first tableswitch entry.
553 uint32_t tableOffset_ = 0;
554
555 // Offset of the code to start interpreting a bytecode op.
556 uint32_t interpretOpOffset_ = 0;
557
558 // Like interpretOpOffset_ but skips the debug trap for the current op.
559 uint32_t interpretOpNoDebugTrapOffset_ = 0;
560
561 // Offset of the jump (tail call) to the debug trap handler trampoline code.
562 // When the debugger is enabled, NOPs are patched to calls to this location.
563 uint32_t debugTrapHandlerOffset_ = 0;
564
565 BaselineInterpreterPerfSpewer perfSpewer_;
566
567 public:
568 explicit BaselineInterpreterGenerator(JSContext* cx, TempAllocator& alloc,
569 MacroAssembler& masm);
570
571 [[nodiscard]] bool generate(JSContext* cx, BaselineInterpreter& interpreter);
572
573 private:
574 [[nodiscard]] bool emitInterpreterLoop();
575 [[nodiscard]] bool emitDebugTrap();
576
577 void emitOutOfLineCodeCoverageInstrumentation();
578 };
579
580 } // namespace jit
581 } // namespace js
582
583 #endif /* jit_BaselineCodeGen_h */