Debian Codegraph @

js/src/jit/JitRuntime.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_JitRuntime_h
8 #define jit_JitRuntime_h
9
10 #include "mozilla/Assertions.h"
11 #include "mozilla/Atomics.h"
12 #include "mozilla/EnumeratedArray.h"
13 #include "mozilla/LinkedList.h"
14
15 #include <stddef.h>
16 #include <stdint.h>
17
18 #include "jstypes.h"
19
20 #include "jit/ABIFunctions.h"
21 #include "jit/BaselineICList.h"
22 #include "jit/BaselineJIT.h"
23 #include "jit/CalleeToken.h"
24 #include "jit/InterpreterEntryTrampoline.h"
25 #include "jit/IonCompileTask.h"
26 #include "jit/IonTypes.h"
27 #include "jit/JitCode.h"
28 #include "jit/JitHints.h"
29 #include "jit/shared/Assembler-shared.h"
30 #include "jit/TrampolineNatives.h"
31 #include "js/AllocPolicy.h"
32 #include "js/ProfilingFrameIterator.h"
33 #include "js/TypeDecls.h"
34 #include "js/UniquePtr.h"
35 #include "js/Vector.h"
36 #include "threading/ProtectedData.h"
37 #include "vm/GeckoProfiler.h"
38 #include "vm/Runtime.h"
39
40 class JS_PUBLIC_API JSTracer;
41
42 namespace js {
43
44 class AutoLockHelperThreadState;
45 class GCMarker;
46 enum class ArraySortKind;
47
48 namespace jit {
49
50 class FrameSizeClass;
51 class Label;
52 class MacroAssembler;
53 struct VMFunctionData;
54
55 enum class VMFunctionId;
56
57 enum class BaselineICFallbackKind : uint8_t {
58 #define DEF_ENUM_KIND(kind) kind,
59 IC_BASELINE_FALLBACK_CODE_KIND_LIST(DEF_ENUM_KIND)
60 #undef DEF_ENUM_KIND
61 Count
62 };
63
64 enum class BailoutReturnKind {
65 GetProp,
66 GetPropSuper,
67 SetProp,
68 GetElem,
69 GetElemSuper,
70 Call,
71 New,
72 Count
73 };
74
75 // Class storing code and offsets for all Baseline IC fallback trampolines. This
76 // is stored in JitRuntime and generated when creating the JitRuntime.
77 class BaselineICFallbackCode {
78 JitCode* code_ = nullptr;
79 using OffsetArray =
80 mozilla::EnumeratedArray<BaselineICFallbackKind, uint32_t,
81 size_t(BaselineICFallbackKind::Count)>;
82 OffsetArray offsets_ = {};
83
84 // Keep track of offset into various baseline stubs' code at return
85 // point from called script.
86 using BailoutReturnArray =
87 mozilla::EnumeratedArray<BailoutReturnKind, uint32_t,
88 size_t(BailoutReturnKind::Count)>;
89 BailoutReturnArray bailoutReturnOffsets_ = {};
90
91 public:
92 BaselineICFallbackCode() = default;
93 BaselineICFallbackCode(const BaselineICFallbackCode&) = delete;
94 void operator=(const BaselineICFallbackCode&) = delete;
95
96 void initOffset(BaselineICFallbackKind kind, uint32_t offset) {
97 offsets_[kind] = offset;
98 }
99 void initCode(JitCode* code) { code_ = code; }
100 void initBailoutReturnOffset(BailoutReturnKind kind, uint32_t offset) {
101 bailoutReturnOffsets_[kind] = offset;
102 }
103 TrampolinePtr addr(BaselineICFallbackKind kind) const {
104 return TrampolinePtr(code_->raw() + offsets_[kind]);
105 }
106 uint8_t* bailoutReturnAddr(BailoutReturnKind kind) const {
107 return code_->raw() + bailoutReturnOffsets_[kind];
108 }
109 };
110
111 enum class ArgumentsRectifierKind { Normal, TrialInlining };
112
113 enum class DebugTrapHandlerKind { Interpreter, Compiler, Count };
114
115 enum class IonGenericCallKind { Call, Construct, Count };
116
117 using EnterJitCode = void (*)(void*, unsigned int, Value*, InterpreterFrame*,
118 CalleeToken, JSObject*, size_t, Value*);
119
120 class JitcodeGlobalTable;
121 class PerfSpewerRangeRecorder;
122
123 class JitRuntime {
124 private:
125 MainThreadData<uint64_t> nextCompilationId_{0};
126
127 // Buffer for OSR from baseline to Ion. To avoid holding on to this for too
128 // long it's also freed in EnterBaseline and EnterJit (after returning from
129 // JIT code).
130 MainThreadData<js::UniquePtr<uint8_t>> ionOsrTempData_{nullptr};
131 MainThreadData<uint32_t> ionOsrTempDataSize_{0};
132
133 // List of Ion compile tasks that should be freed. Used to batch multiple
134 // tasks into a single IonFreeTask.
135 MainThreadData<IonFreeCompileTasks> ionFreeTaskBatch_;
136
137 // Shared exception-handler tail.
138 WriteOnceData<uint32_t> exceptionTailOffset_{0};
139 WriteOnceData<uint32_t> exceptionTailReturnValueCheckOffset_{0};
140
141 // Shared profiler exit frame tail.
142 WriteOnceData<uint32_t> profilerExitFrameTailOffset_{0};
143
144 // Trampoline for entering JIT code.
145 WriteOnceData<uint32_t> enterJITOffset_{0};
146
147 // Generic bailout table; used if the bailout table overflows.
148 WriteOnceData<uint32_t> bailoutHandlerOffset_{0};
149
150 // Argument-rectifying thunks, in the case of insufficient arguments passed
151 // to a function call site. The return offset is used to rebuild stack frames
152 // when bailing out.
153 WriteOnceData<uint32_t> argumentsRectifierOffset_{0};
154 WriteOnceData<uint32_t> trialInliningArgumentsRectifierOffset_{0};
155 WriteOnceData<uint32_t> argumentsRectifierReturnOffset_{0};
156
157 // Thunk that invalides an (Ion compiled) caller on the Ion stack.
158 WriteOnceData<uint32_t> invalidatorOffset_{0};
159
160 // Thunk that calls the GC pre barrier.
161 WriteOnceData<uint32_t> valuePreBarrierOffset_{0};
162 WriteOnceData<uint32_t> stringPreBarrierOffset_{0};
163 WriteOnceData<uint32_t> objectPreBarrierOffset_{0};
164 WriteOnceData<uint32_t> shapePreBarrierOffset_{0};
165 WriteOnceData<uint32_t> wasmAnyRefPreBarrierOffset_{0};
166
167 // Thunk called to finish compilation of an IonScript.
168 WriteOnceData<uint32_t> lazyLinkStubOffset_{0};
169
170 // Thunk to enter the interpreter from JIT code.
171 WriteOnceData<uint32_t> interpreterStubOffset_{0};
172
173 // Thunk to convert the value in R0 to int32 if it's a double.
174 // Note: this stub treats -0 as +0 and may clobber R1.scratchReg().
175 WriteOnceData<uint32_t> doubleToInt32ValueStubOffset_{0};
176
177 // Thunk to do a generic call from Ion.
178 mozilla::EnumeratedArray<IonGenericCallKind, WriteOnceData<uint32_t>,
179 size_t(IonGenericCallKind::Count)>
180 ionGenericCallStubOffset_;
181
182 // Thunk used by the debugger for breakpoint and step mode.
183 mozilla::EnumeratedArray<DebugTrapHandlerKind, WriteOnceData<JitCode*>,
184 size_t(DebugTrapHandlerKind::Count)>
185 debugTrapHandlers_;
186
187 // BaselineInterpreter state.
188 BaselineInterpreter baselineInterpreter_;
189
190 // Code for trampolines and VMFunction wrappers.
191 WriteOnceData<JitCode*> trampolineCode_{nullptr};
192
193 // Thunk that calls into the C++ interpreter from the interpreter
194 // entry trampoline that is generated with --emit-interpreter-entry
195 WriteOnceData<uint32_t> vmInterpreterEntryOffset_{0};
196
197 // Maps VMFunctionId to the offset of the wrapper code in trampolineCode_.
198 using VMWrapperOffsets = Vector<uint32_t, 0, SystemAllocPolicy>;
199 VMWrapperOffsets functionWrapperOffsets_;
200
201 MainThreadData<BaselineICFallbackCode> baselineICFallbackCode_;
202
203 // Global table of jitcode native address => bytecode address mappings.
204 UnprotectedData<JitcodeGlobalTable*> jitcodeGlobalTable_{nullptr};
205
206 // Map that stores Jit Hints for each script.
207 MainThreadData<JitHintsMap*> jitHintsMap_{nullptr};
208
209 // Map used to collect entry trampolines for the Interpreters which is used
210 // for external profiling to identify which functions are being interpreted.
211 MainThreadData<EntryTrampolineMap*> interpreterEntryMap_{nullptr};
212
213 #ifdef DEBUG
214 // The number of possible bailing places encountered before forcefully bailing
215 // in that place if the counter reaches zero. Note that zero also means
216 // inactive.
217 MainThreadData<uint32_t> ionBailAfterCounter_{0};
218
219 // Whether the bailAfter mechanism is enabled. Used to avoid generating the
220 // Ion code instrumentation for ionBailAfterCounter_ if the testing function
221 // isn't used.
222 MainThreadData<bool> ionBailAfterEnabled_{false};
223 #endif
224
225 // Number of Ion compilations which were finished off thread and are
226 // waiting to be lazily linked. This is only set while holding the helper
227 // thread state lock, but may be read from at other times.
228 using NumFinishedOffThreadTasksType =
229 mozilla::Atomic<size_t, mozilla::SequentiallyConsistent>;
230 NumFinishedOffThreadTasksType numFinishedOffThreadTasks_{0};
231
232 // List of Ion compilation waiting to get linked.
233 using IonCompileTaskList = mozilla::LinkedList<js::jit::IonCompileTask>;
234 MainThreadData<IonCompileTaskList> ionLazyLinkList_;
235 MainThreadData<size_t> ionLazyLinkListSize_{0};
236
237 // Pointer to trampoline code for each TrampolineNative. The JSFunction has
238 // a JitEntry pointer that points to an item in this array.
239 using TrampolineNativeJitEntryArray =
240 mozilla::EnumeratedArray<TrampolineNative, void*,
241 size_t(TrampolineNative::Count)>;
242 TrampolineNativeJitEntryArray trampolineNativeJitEntries_{};
243
244 #ifdef DEBUG
245 // Flag that can be set from JIT code to indicate it's invalid to call
246 // arbitrary JS code in a particular region. This is checked in RunScript.
247 MainThreadData<uint32_t> disallowArbitraryCode_{false};
248 #endif
249
250 bool generateTrampolines(JSContext* cx);
251 bool generateBaselineICFallbackCode(JSContext* cx);
252
253 void generateLazyLinkStub(MacroAssembler& masm);
254 void generateInterpreterStub(MacroAssembler& masm);
255 void generateDoubleToInt32ValueStub(MacroAssembler& masm);
256 void generateProfilerExitFrameTailStub(MacroAssembler& masm,
257 Label* profilerExitTail);
258 void generateExceptionTailStub(MacroAssembler& masm, Label* profilerExitTail,
259 Label* bailoutTail);
260 void generateBailoutTailStub(MacroAssembler& masm, Label* bailoutTail);
261 void generateEnterJIT(JSContext* cx, MacroAssembler& masm);
262 void generateArgumentsRectifier(MacroAssembler& masm,
263 ArgumentsRectifierKind kind);
264 void generateBailoutHandler(MacroAssembler& masm, Label* bailoutTail);
265 void generateInvalidator(MacroAssembler& masm, Label* bailoutTail);
266 uint32_t generatePreBarrier(JSContext* cx, MacroAssembler& masm,
267 MIRType type);
268 void generateIonGenericCallStub(MacroAssembler& masm,
269 IonGenericCallKind kind);
270
271 // Helper functions for generateIonGenericCallStub
272 void generateIonGenericCallBoundFunction(MacroAssembler& masm, Label* entry,
273 Label* vmCall);
274 void generateIonGenericCallNativeFunction(MacroAssembler& masm,
275 bool isConstructing);
276 void generateIonGenericCallFunCall(MacroAssembler& masm, Label* entry,
277 Label* vmCall);
278 void generateIonGenericCallArgumentsShift(MacroAssembler& masm, Register argc,
279 Register curr, Register end,
280 Register scratch, Label* done);
281
282 JitCode* generateDebugTrapHandler(JSContext* cx, DebugTrapHandlerKind kind);
283
284 bool generateVMWrapper(JSContext* cx, MacroAssembler& masm, VMFunctionId id,
285 const VMFunctionData& f, DynFn nativeFun,
286 uint32_t* wrapperOffset);
287
288 bool generateVMWrappers(JSContext* cx, MacroAssembler& masm,
289 PerfSpewerRangeRecorder& rangeRecorder);
290
291 uint32_t startTrampolineCode(MacroAssembler& masm);
292
293 TrampolinePtr trampolineCode(uint32_t offset) const {
294 MOZ_ASSERT(offset > 0);
295 MOZ_ASSERT(offset < trampolineCode_->instructionsSize());
296 return TrampolinePtr(trampolineCode_->raw() + offset);
297 }
298
299 void generateBaselineInterpreterEntryTrampoline(MacroAssembler& masm);
300 void generateInterpreterEntryTrampoline(MacroAssembler& masm);
301
302 using TrampolineNativeJitEntryOffsets =
303 mozilla::EnumeratedArray<TrampolineNative, uint32_t,
304 size_t(TrampolineNative::Count)>;
305 void generateTrampolineNatives(MacroAssembler& masm,
306 TrampolineNativeJitEntryOffsets& offsets,
307 PerfSpewerRangeRecorder& rangeRecorder);
308 uint32_t generateArraySortTrampoline(MacroAssembler& masm,
309 ArraySortKind kind);
310
311 void bindLabelToOffset(Label* label, uint32_t offset) {
312 MOZ_ASSERT(!trampolineCode_);
313 label->bind(offset);
314 }
315
316 public:
317 JitCode* generateEntryTrampolineForScript(JSContext* cx, JSScript* script);
318
319 JitRuntime() = default;
320 ~JitRuntime();
321 [[nodiscard]] bool initialize(JSContext* cx);
322
323 static void TraceAtomZoneRoots(JSTracer* trc);
324 [[nodiscard]] static bool MarkJitcodeGlobalTableIteratively(GCMarker* marker);
325 static void TraceWeakJitcodeGlobalTable(JSRuntime* rt, JSTracer* trc);
326
327 const BaselineICFallbackCode& baselineICFallbackCode() const {
328 return baselineICFallbackCode_.ref();
329 }
330
331 IonCompilationId nextCompilationId() {
332 return IonCompilationId(nextCompilationId_++);
333 }
334
335 [[nodiscard]] bool addIonCompileToFreeTaskBatch(IonCompileTask* task) {
336 return ionFreeTaskBatch_.ref().append(task);
337 }
338 void maybeStartIonFreeTask(bool force);
339
340 UniquePtr<LifoAlloc> tryReuseIonLifoAlloc();
341
342 #ifdef DEBUG
343 bool disallowArbitraryCode() const { return disallowArbitraryCode_; }
344 void clearDisallowArbitraryCode() { disallowArbitraryCode_ = false; }
345 const void* addressOfDisallowArbitraryCode() const {
346 return &disallowArbitraryCode_.refNoCheck();
347 }
348 #endif
349
350 uint8_t* allocateIonOsrTempData(size_t size);
351 void freeIonOsrTempData();
352
353 TrampolinePtr getVMWrapper(VMFunctionId funId) const {
354 MOZ_ASSERT(trampolineCode_);
355 return trampolineCode(functionWrapperOffsets_[size_t(funId)]);
356 }
357
358 bool ensureDebugTrapHandler(JSContext* cx, DebugTrapHandlerKind kind);
359 JitCode* debugTrapHandler(DebugTrapHandlerKind kind) const {
360 MOZ_ASSERT(debugTrapHandlers_[kind]);
361 return debugTrapHandlers_[kind];
362 }
363
364 BaselineInterpreter& baselineInterpreter() { return baselineInterpreter_; }
365 const BaselineInterpreter& baselineInterpreter() const {
366 return baselineInterpreter_;
367 }
368
369 TrampolinePtr getGenericBailoutHandler() const {
370 return trampolineCode(bailoutHandlerOffset_);
371 }
372
373 TrampolinePtr getExceptionTail() const {
374 return trampolineCode(exceptionTailOffset_);
375 }
376 TrampolinePtr getExceptionTailReturnValueCheck() const {
377 return trampolineCode(exceptionTailReturnValueCheckOffset_);
378 }
379
380 TrampolinePtr getProfilerExitFrameTail() const {
381 return trampolineCode(profilerExitFrameTailOffset_);
382 }
383
384 TrampolinePtr getArgumentsRectifier(
385 ArgumentsRectifierKind kind = ArgumentsRectifierKind::Normal) const {
386 if (kind == ArgumentsRectifierKind::TrialInlining) {
387 return trampolineCode(trialInliningArgumentsRectifierOffset_);
388 }
389 return trampolineCode(argumentsRectifierOffset_);
390 }
391
392 uint32_t vmInterpreterEntryOffset() { return vmInterpreterEntryOffset_; }
393
394 TrampolinePtr getArgumentsRectifierReturnAddr() const {
395 return trampolineCode(argumentsRectifierReturnOffset_);
396 }
397
398 TrampolinePtr getInvalidationThunk() const {
399 return trampolineCode(invalidatorOffset_);
400 }
401
402 EnterJitCode enterJit() const {
403 return JS_DATA_TO_FUNC_PTR(EnterJitCode,
404 trampolineCode(enterJITOffset_).value);
405 }
406
407 // Return the registers from the native caller frame of the given JIT frame.
408 // Nothing{} if frameStackAddress is NOT pointing at a native-to-JIT entry
409 // frame, or if the information is not accessible/implemented on this
410 // platform.
411 static mozilla::Maybe<::JS::ProfilingFrameIterator::RegisterState>
412 getCppEntryRegisters(JitFrameLayout* frameStackAddress);
413
414 TrampolinePtr preBarrier(MIRType type) const {
415 switch (type) {
416 case MIRType::Value:
417 return trampolineCode(valuePreBarrierOffset_);
418 case MIRType::String:
419 return trampolineCode(stringPreBarrierOffset_);
420 case MIRType::Object:
421 return trampolineCode(objectPreBarrierOffset_);
422 case MIRType::Shape:
423 return trampolineCode(shapePreBarrierOffset_);
424 case MIRType::WasmAnyRef:
425 return trampolineCode(wasmAnyRefPreBarrierOffset_);
426 default:
427 MOZ_CRASH();
428 }
429 }
430
431 TrampolinePtr lazyLinkStub() const {
432 return trampolineCode(lazyLinkStubOffset_);
433 }
434 TrampolinePtr interpreterStub() const {
435 return trampolineCode(interpreterStubOffset_);
436 }
437
438 TrampolinePtr getDoubleToInt32ValueStub() const {
439 return trampolineCode(doubleToInt32ValueStubOffset_);
440 }
441
442 TrampolinePtr getIonGenericCallStub(IonGenericCallKind kind) const {
443 return trampolineCode(ionGenericCallStubOffset_[kind]);
444 }
445
446 void** trampolineNativeJitEntry(TrampolineNative native) {
447 void** jitEntry = &trampolineNativeJitEntries_[native];
448 MOZ_ASSERT(*jitEntry >= trampolineCode_->raw());
449 MOZ_ASSERT(*jitEntry <
450 trampolineCode_->raw() + trampolineCode_->instructionsSize());
451 return jitEntry;
452 }
453 TrampolineNative trampolineNativeForJitEntry(void** entry) {
454 MOZ_RELEASE_ASSERT(entry >= trampolineNativeJitEntries_.begin());
455 size_t index = entry - trampolineNativeJitEntries_.begin();
456 MOZ_RELEASE_ASSERT(index < size_t(TrampolineNative::Count));
457 return TrampolineNative(index);
458 }
459
460 bool hasJitcodeGlobalTable() const { return jitcodeGlobalTable_ != nullptr; }
461
462 JitcodeGlobalTable* getJitcodeGlobalTable() {
463 MOZ_ASSERT(hasJitcodeGlobalTable());
464 return jitcodeGlobalTable_;
465 }
466
467 bool hasJitHintsMap() const { return jitHintsMap_ != nullptr; }
468
469 JitHintsMap* getJitHintsMap() {
470 MOZ_ASSERT(hasJitHintsMap());
471 return jitHintsMap_;
472 }
473
474 bool hasInterpreterEntryMap() const {
475 return interpreterEntryMap_ != nullptr;
476 }
477
478 EntryTrampolineMap* getInterpreterEntryMap() {
479 MOZ_ASSERT(hasInterpreterEntryMap());
480 return interpreterEntryMap_;
481 }
482
483 bool isProfilerInstrumentationEnabled(JSRuntime* rt) {
484 return rt->geckoProfiler().enabled();
485 }
486
487 bool isOptimizationTrackingEnabled(JSRuntime* rt) {
488 return isProfilerInstrumentationEnabled(rt);
489 }
490
491 #ifdef DEBUG
492 void* addressOfIonBailAfterCounter() { return &ionBailAfterCounter_; }
493
494 // Set after how many bailing places we should forcefully bail.
495 // Zero disables this feature.
496 void setIonBailAfterCounter(uint32_t after) { ionBailAfterCounter_ = after; }
497 bool ionBailAfterEnabled() const { return ionBailAfterEnabled_; }
498 void setIonBailAfterEnabled(bool enabled) { ionBailAfterEnabled_ = enabled; }
499 #endif
500
501 size_t numFinishedOffThreadTasks() const {
502 return numFinishedOffThreadTasks_;
503 }
504 NumFinishedOffThreadTasksType& numFinishedOffThreadTasksRef(
505 const AutoLockHelperThreadState& locked) {
506 return numFinishedOffThreadTasks_;
507 }
508
509 IonCompileTaskList& ionLazyLinkList(JSRuntime* rt);
510
511 size_t ionLazyLinkListSize() const { return ionLazyLinkListSize_; }
512
513 void ionLazyLinkListRemove(JSRuntime* rt, js::jit::IonCompileTask* task);
514 void ionLazyLinkListAdd(JSRuntime* rt, js::jit::IonCompileTask* task);
515 };
516
517 } // namespace jit
518 } // namespace js
519
520 #endif /* jit_JitRuntime_h */