Debian Codegraph @

js/src/jit/arm64/Trampoline-arm64.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/arm64/SharedICHelpers-arm64.h"
8 #include "jit/Bailouts.h"
9 #include "jit/BaselineFrame.h"
10 #include "jit/CalleeToken.h"
11 #include "jit/JitFrames.h"
12 #include "jit/JitRuntime.h"
13 #include "jit/PerfSpewer.h"
14 #include "jit/VMFunctions.h"
15 #include "vm/JitActivation.h" // js::jit::JitActivation
16 #include "vm/JSContext.h"
17
18 #include "jit/MacroAssembler-inl.h"
19
20 using namespace js;
21 using namespace js::jit;
22
23 /* This method generates a trampoline on ARM64 for a c++ function with
24 * the following signature:
25 * bool blah(void* code, int argc, Value* argv,
26 * JSObject* scopeChain, Value* vp)
27 * ...using standard AArch64 calling convention
28 */
29 void JitRuntime::generateEnterJIT(JSContext* cx, MacroAssembler& masm) {
30 AutoCreatedBy acb(masm, "JitRuntime::generateEnterJIT");
31
32 enterJITOffset_ = startTrampolineCode(masm);
33
34 const Register reg_code = IntArgReg0; // EnterJitData::jitcode.
35 const Register reg_argc = IntArgReg1; // EnterJitData::maxArgc.
36 const Register reg_argv = IntArgReg2; // EnterJitData::maxArgv.
37 const Register reg_osrFrame = IntArgReg3; // EnterJitData::osrFrame.
38 const Register reg_callee = IntArgReg4; // EnterJitData::calleeToken.
39 const Register reg_scope = IntArgReg5; // EnterJitData::scopeChain.
40 const Register reg_osrNStack =
41 IntArgReg6; // EnterJitData::osrNumStackValues.
42 const Register reg_vp = IntArgReg7; // Address of EnterJitData::result.
43
44 static_assert(OsrFrameReg == IntArgReg3);
45
46 // During the pushes below, use the normal stack pointer.
47 masm.SetStackPointer64(sp);
48
49 // Save return address and old frame pointer; set new frame pointer.
50 masm.push(r30, r29);
51 masm.moveStackPtrTo(r29);
52
53 // Save callee-save integer registers.
54 // Also save x7 (reg_vp) and x30 (lr), for use later.
55 masm.push(r19, r20, r21, r22);
56 masm.push(r23, r24, r25, r26);
57 masm.push(r27, r28, r7, r30);
58
59 // Save callee-save floating-point registers.
60 // AArch64 ABI specifies that only the lower 64 bits must be saved.
61 masm.push(d8, d9, d10, d11);
62 masm.push(d12, d13, d14, d15);
63
64 #ifdef DEBUG
65 // Emit stack canaries.
66 masm.movePtr(ImmWord(0xdeadd00d), r23);
67 masm.movePtr(ImmWord(0xdeadd11d), r24);
68 masm.push(r23, r24);
69 #endif
70
71 // Common code below attempts to push single registers at a time,
72 // which breaks the stack pointer's 16-byte alignment requirement.
73 // Note that movePtr() is invalid because StackPointer is treated as xzr.
74 //
75 // FIXME: After testing, this entire function should be rewritten to not
76 // use the PseudoStackPointer: since the amount of data pushed is
77 // precalculated, we can just allocate the whole frame header at once and
78 // index off sp. This will save a significant number of instructions where
79 // Push() updates sp.
80 masm.Mov(PseudoStackPointer64, sp);
81 masm.SetStackPointer64(PseudoStackPointer64);
82
83 // Remember stack depth without padding and arguments.
84 masm.moveStackPtrTo(r19);
85
86 // If constructing, include newTarget in argument vector.
87 {
88 Label noNewTarget;
89 Imm32 constructingToken(CalleeToken_FunctionConstructing);
90 masm.branchTest32(Assembler::Zero, reg_callee, constructingToken,
91 &noNewTarget);
92 masm.add32(Imm32(1), reg_argc);
93 masm.bind(&noNewTarget);
94 }
95
96 // JitFrameLayout is as follows (higher is higher in memory):
97 // N*8 - [ JS argument vector ] (base 16-byte aligned)
98 // 8 - calleeToken
99 // 8 - frameDescriptor (16-byte aligned)
100 // 8 - returnAddress
101 // 8 - frame pointer (16-byte aligned, pushed by callee)
102
103 // Touch frame incrementally (a requirement for Windows).
104 //
105 // Use already saved callee-save registers r20 and r21 as temps.
106 //
107 // This has to be done outside the ScratchRegisterScope, as the temps are
108 // under demand inside the touchFrameValues call.
109
110 // Give sp 16-byte alignment and sync stack pointers.
111 masm.andToStackPtr(Imm32(~0xf));
112 // We needn't worry about the Gecko Profiler mark because touchFrameValues
113 // touches in large increments.
114 masm.touchFrameValues(reg_argc, r20, r21);
115 // Restore stack pointer, preserved above.
116 masm.moveToStackPtr(r19);
117
118 // Push the argument vector onto the stack.
119 // WARNING: destructively modifies reg_argv
120 {
121 vixl::UseScratchRegisterScope temps(&masm.asVIXL());
122
123 const ARMRegister tmp_argc = temps.AcquireX();
124 const ARMRegister tmp_sp = temps.AcquireX();
125
126 Label noArguments;
127 Label loopHead;
128
129 masm.movePtr(reg_argc, tmp_argc.asUnsized());
130
131 // sp -= 8
132 // Since we're using PostIndex Str below, this is necessary to avoid
133 // overwriting the Gecko Profiler mark pushed above.
134 masm.subFromStackPtr(Imm32(8));
135
136 // sp -= 8 * argc
137 masm.Sub(PseudoStackPointer64, PseudoStackPointer64,
138 Operand(tmp_argc, vixl::SXTX, 3));
139
140 // Give sp 16-byte alignment and sync stack pointers.
141 masm.andToStackPtr(Imm32(~0xf));
142 masm.moveStackPtrTo(tmp_sp.asUnsized());
143
144 masm.branchTestPtr(Assembler::Zero, reg_argc, reg_argc, &noArguments);
145
146 // Begin argument-pushing loop.
147 // This could be optimized using Ldp and Stp.
148 {
149 masm.bind(&loopHead);
150
151 // Load an argument from argv, then increment argv by 8.
152 masm.Ldr(x24, MemOperand(ARMRegister(reg_argv, 64), Operand(8),
153 vixl::PostIndex));
154
155 // Store the argument to tmp_sp, then increment tmp_sp by 8.
156 masm.Str(x24, MemOperand(tmp_sp, Operand(8), vixl::PostIndex));
157
158 // Decrement tmp_argc and set the condition codes for the new value.
159 masm.Subs(tmp_argc, tmp_argc, Operand(1));
160
161 // Branch if arguments remain.
162 masm.B(&loopHead, vixl::Condition::NonZero);
163 }
164
165 masm.bind(&noArguments);
166 }
167 masm.checkStackAlignment();
168
169 // Push the calleeToken and the frame descriptor.
170 // The result address is used to store the actual number of arguments
171 // without adding an argument to EnterJIT.
172 {
173 vixl::UseScratchRegisterScope temps(&masm.asVIXL());
174 MOZ_ASSERT(temps.IsAvailable(ScratchReg64)); // ip0
175 temps.Exclude(ScratchReg64);
176 Register scratch = ScratchReg64.asUnsized();
177 masm.push(reg_callee);
178
179 // Push the descriptor.
180 masm.unboxInt32(Address(reg_vp, 0x0), scratch);
181 masm.PushFrameDescriptorForJitCall(FrameType::CppToJSJit, scratch, scratch);
182 }
183 masm.checkStackAlignment();
184
185 Label osrReturnPoint;
186 {
187 // Check for Interpreter -> Baseline OSR.
188
189 AllocatableGeneralRegisterSet regs(GeneralRegisterSet::All());
190 MOZ_ASSERT(!regs.has(FramePointer));
191 regs.take(OsrFrameReg);
192 regs.take(reg_code);
193 regs.take(reg_osrNStack);
194 MOZ_ASSERT(!regs.has(ReturnReg), "ReturnReg matches reg_code");
195
196 Label notOsr;
197 masm.branchTestPtr(Assembler::Zero, OsrFrameReg, OsrFrameReg, &notOsr);
198
199 Register scratch = regs.takeAny();
200
201 // Frame prologue.
202 masm.Adr(ARMRegister(scratch, 64), &osrReturnPoint);
203 masm.push(scratch, FramePointer);
204 masm.moveStackPtrTo(FramePointer);
205
206 // Reserve frame.
207 masm.subFromStackPtr(Imm32(BaselineFrame::Size()));
208
209 Register framePtrScratch = regs.takeAny();
210 masm.touchFrameValues(reg_osrNStack, scratch, framePtrScratch);
211 masm.moveStackPtrTo(framePtrScratch);
212
213 // Reserve space for locals and stack values.
214 // scratch = num_stack_values * sizeof(Value).
215 masm.Lsl(ARMRegister(scratch, 32), ARMRegister(reg_osrNStack, 32), 3);
216 masm.subFromStackPtr(scratch);
217
218 // Enter exit frame.
219 masm.pushFrameDescriptor(FrameType::BaselineJS);
220 masm.push(xzr); // Push xzr for a fake return address.
221 masm.push(FramePointer);
222 // No GC things to mark: push a bare token.
223 masm.loadJSContext(scratch);
224 masm.enterFakeExitFrame(scratch, scratch, ExitFrameType::Bare);
225
226 masm.push(reg_code);
227
228 // Initialize the frame, including filling in the slots.
229 using Fn = bool (*)(BaselineFrame* frame, InterpreterFrame* interpFrame,
230 uint32_t numStackValues);
231 masm.setupUnalignedABICall(r19);
232 masm.passABIArg(framePtrScratch); // BaselineFrame.
233 masm.passABIArg(reg_osrFrame); // InterpreterFrame.
234 masm.passABIArg(reg_osrNStack);
235 masm.callWithABI<Fn, jit::InitBaselineFrameForOsr>(
236 ABIType::General, CheckUnsafeCallWithABI::DontCheckHasExitFrame);
237
238 masm.pop(scratch);
239 MOZ_ASSERT(scratch != ReturnReg);
240
241 masm.addToStackPtr(Imm32(ExitFrameLayout::SizeWithFooter()));
242
243 Label error;
244 masm.branchIfFalseBool(ReturnReg, &error);
245
246 // If OSR-ing, then emit instrumentation for setting lastProfilerFrame
247 // if profiler instrumentation is enabled.
248 {
249 Label skipProfilingInstrumentation;
250 AbsoluteAddress addressOfEnabled(
251 cx->runtime()->geckoProfiler().addressOfEnabled());
252 masm.branch32(Assembler::Equal, addressOfEnabled, Imm32(0),
253 &skipProfilingInstrumentation);
254 masm.profilerEnterFrame(FramePointer, regs.getAny());
255 masm.bind(&skipProfilingInstrumentation);
256 }
257
258 masm.jump(scratch);
259
260 // OOM: frame epilogue, load error value, discard return address and return.
261 masm.bind(&error);
262 masm.moveToStackPtr(FramePointer);
263 masm.pop(FramePointer);
264 masm.addToStackPtr(Imm32(sizeof(uintptr_t))); // Return address.
265 masm.syncStackPtr();
266 masm.moveValue(MagicValue(JS_ION_ERROR), JSReturnOperand);
267 masm.B(&osrReturnPoint);
268
269 masm.bind(&notOsr);
270 masm.movePtr(reg_scope, R1_);
271 }
272
273 // The callee will push the return address and frame pointer on the stack,
274 // thus we check that the stack would be aligned once the call is complete.
275 masm.assertStackAlignment(JitStackAlignment, 2 * sizeof(uintptr_t));
276
277 // Call function.
278 // Since AArch64 doesn't have the pc register available, the callee must push
279 // lr.
280 masm.callJitNoProfiler(reg_code);
281
282 // Interpreter -> Baseline OSR will return here.
283 masm.bind(&osrReturnPoint);
284
285 // Discard arguments and padding. Set sp to the address of the saved
286 // registers. In debug builds we have to include the two stack canaries
287 // checked below.
288 #ifdef DEBUG
289 static constexpr size_t SavedRegSize = 22 * sizeof(void*);
290 #else
291 static constexpr size_t SavedRegSize = 20 * sizeof(void*);
292 #endif
293 masm.computeEffectiveAddress(Address(FramePointer, -int32_t(SavedRegSize)),
294 masm.getStackPointer());
295
296 masm.syncStackPtr();
297 masm.SetStackPointer64(sp);
298
299 #ifdef DEBUG
300 // Check that canaries placed on function entry are still present.
301 masm.pop(r24, r23);
302 Label x23OK, x24OK;
303
304 masm.branchPtr(Assembler::Equal, r23, ImmWord(0xdeadd00d), &x23OK);
305 masm.breakpoint();
306 masm.bind(&x23OK);
307
308 masm.branchPtr(Assembler::Equal, r24, ImmWord(0xdeadd11d), &x24OK);
309 masm.breakpoint();
310 masm.bind(&x24OK);
311 #endif
312
313 // Restore callee-save floating-point registers.
314 masm.pop(d15, d14, d13, d12);
315 masm.pop(d11, d10, d9, d8);
316
317 // Restore callee-save integer registers.
318 // Also restore x7 (reg_vp) and x30 (lr).
319 masm.pop(r30, r7, r28, r27);
320 masm.pop(r26, r25, r24, r23);
321 masm.pop(r22, r21, r20, r19);
322
323 // Store return value (in JSReturnReg = x2 to just-popped reg_vp).
324 masm.storeValue(JSReturnOperand, Address(reg_vp, 0));
325
326 // Restore old frame pointer.
327 masm.pop(r29, r30);
328
329 // Return using the value popped into x30.
330 masm.abiret();
331
332 // Reset stack pointer.
333 masm.SetStackPointer64(PseudoStackPointer64);
334 }
335
336 // static
337 mozilla::Maybe<::JS::ProfilingFrameIterator::RegisterState>
338 JitRuntime::getCppEntryRegisters(JitFrameLayout* frameStackAddress) {
339 // Not supported, or not implemented yet.
340 // TODO: Implement along with the corresponding stack-walker changes, in
341 // coordination with the Gecko Profiler, see bug 1635987 and follow-ups.
342 return mozilla::Nothing{};
343 }
344
345 static void PushRegisterDump(MacroAssembler& masm) {
346 const LiveRegisterSet First28GeneralRegisters = LiveRegisterSet(
347 GeneralRegisterSet(Registers::AllMask &
348 ~(1 << 31 | 1 << 30 | 1 << 29 | 1 << 28)),
349 FloatRegisterSet(FloatRegisters::NoneMask));
350
351 const LiveRegisterSet AllFloatRegisters =
352 LiveRegisterSet(GeneralRegisterSet(Registers::NoneMask),
353 FloatRegisterSet(FloatRegisters::AllMask));
354
355 // Push all general-purpose registers.
356 //
357 // The ARM64 ABI does not treat SP as a normal register that can
358 // be pushed. So pushing happens in two phases.
359 //
360 // Registers are pushed in reverse order of code.
361 //
362 // See block comment in MacroAssembler.h for further required invariants.
363
364 // First, push the last four registers, passing zero for sp.
365 // Zero is pushed for x28 and x31: the pseudo-SP and SP, respectively.
366 masm.asVIXL().Push(xzr, x30, x29, xzr);
367
368 // Second, push the first 28 registers that serve no special purpose.
369 masm.PushRegsInMask(First28GeneralRegisters);
370
371 // Finally, push all floating-point registers, completing the RegisterDump.
372 masm.PushRegsInMask(AllFloatRegisters);
373 }
374
375 void JitRuntime::generateInvalidator(MacroAssembler& masm, Label* bailoutTail) {
376 AutoCreatedBy acb(masm, "JitRuntime::generateInvalidator");
377
378 invalidatorOffset_ = startTrampolineCode(masm);
379
380 // The InvalidationBailoutStack saved in r0 must be:
381 // - osiPointReturnAddress_
382 // - ionScript_ (pushed by CodeGeneratorARM64::generateInvalidateEpilogue())
383 // - regs_ (pushed here)
384 // - fpregs_ (pushed here) [=r0]
385 PushRegisterDump(masm);
386 masm.moveStackPtrTo(r0);
387
388 // Reserve space for InvalidationBailout's bailoutInfo outparam.
389 masm.Sub(x1, masm.GetStackPointer64(), Operand(sizeof(void*)));
390 masm.moveToStackPtr(r1);
391
392 using Fn = bool (*)(InvalidationBailoutStack* sp, BaselineBailoutInfo** info);
393 masm.setupUnalignedABICall(r10);
394 masm.passABIArg(r0);
395 masm.passABIArg(r1);
396
397 masm.callWithABI<Fn, InvalidationBailout>(
398 ABIType::General, CheckUnsafeCallWithABI::DontCheckOther);
399
400 masm.pop(r2); // Get the bailoutInfo outparam.
401
402 // Pop the machine state and the dead frame.
403 masm.moveToStackPtr(FramePointer);
404
405 // Jump to shared bailout tail. The BailoutInfo pointer has to be in r2.
406 masm.jump(bailoutTail);
407 }
408
409 void JitRuntime::generateArgumentsRectifier(MacroAssembler& masm,
410 ArgumentsRectifierKind kind) {
411 AutoCreatedBy acb(masm, "JitRuntime::generateArgumentsRectifier");
412
413 switch (kind) {
414 case ArgumentsRectifierKind::Normal:
415 argumentsRectifierOffset_ = startTrampolineCode(masm);
416 break;
417 case ArgumentsRectifierKind::TrialInlining:
418 trialInliningArgumentsRectifierOffset_ = startTrampolineCode(masm);
419 break;
420 }
421
422 // Save the return address for later.
423 masm.push(lr);
424
425 // Frame prologue.
426 //
427 // NOTE: if this changes, fix the Baseline bailout code too!
428 // See BaselineStackBuilder::calculatePrevFramePtr and
429 // BaselineStackBuilder::buildRectifierFrame (in BaselineBailouts.cpp).
430 masm.push(FramePointer);
431 masm.moveStackPtrTo(FramePointer);
432
433 // Load the information that the rectifier needs from the stack.
434 masm.loadNumActualArgs(FramePointer, r0);
435 masm.loadPtr(
436 Address(FramePointer, RectifierFrameLayout::offsetOfCalleeToken()), r1);
437
438 // Extract a JSFunction pointer from the callee token and keep the
439 // intermediary to avoid later recalculation.
440 masm.And(x5, x1, Operand(CalleeTokenMask));
441
442 // Get the arguments from the function object.
443 masm.loadFunctionArgCount(x5.asUnsized(), x6.asUnsized());
444
445 static_assert(CalleeToken_FunctionConstructing == 0x1,
446 "Constructing must be low-order bit");
447 masm.And(x4, x1, Operand(CalleeToken_FunctionConstructing));
448 masm.Add(x7, x6, x4);
449
450 // Copy the number of actual arguments into r8.
451 masm.mov(r0, r8);
452
453 // Calculate the position that our arguments are at before sp gets modified.
454 masm.Add(x3, masm.GetStackPointer64(), Operand(x8, vixl::LSL, 3));
455 masm.Add(x3, x3, Operand(sizeof(RectifierFrameLayout)));
456
457 // If the number of Values without |this| is even, push 8 padding bytes to
458 // ensure the stack is 16-byte aligned.
459 Label noPadding;
460 masm.Tbnz(x7, 0, &noPadding);
461 masm.asVIXL().Push(xzr);
462 masm.bind(&noPadding);
463
464 {
465 Label notConstructing;
466 masm.Cbz(x4, &notConstructing);
467
468 // new.target lives at the end of the pushed args
469 // NB: The arg vector holder starts at the beginning of the last arg,
470 // add a value to get to argv[argc]
471 masm.loadPtr(Address(r3, sizeof(Value)), r4);
472 masm.Push(r4);
473
474 masm.bind(&notConstructing);
475 }
476
477 // Calculate the number of undefineds that need to be pushed.
478 masm.Sub(w2, w6, w8);
479
480 // Put an undefined in a register so it can be pushed.
481 masm.moveValue(UndefinedValue(), ValueOperand(r4));
482
483 // Push undefined N times.
484 {
485 Label undefLoopTop;
486 masm.bind(&undefLoopTop);
487 masm.Push(r4);
488 masm.Subs(w2, w2, Operand(1));
489 masm.B(&undefLoopTop, Assembler::NonZero);
490 }
491
492 // Arguments copy loop. Copy for x8 >= 0 to include |this|.
493 {
494 Label copyLoopTop;
495 masm.bind(&copyLoopTop);
496 masm.Ldr(x4, MemOperand(x3, -sizeof(Value), vixl::PostIndex));
497 masm.Push(r4);
498 masm.Subs(x8, x8, Operand(1));
499 masm.B(&copyLoopTop, Assembler::NotSigned);
500 }
501
502 masm.push(r1); // Callee token.
503 masm.pushFrameDescriptorForJitCall(FrameType::Rectifier, r0, r0);
504
505 // Call the target function.
506 switch (kind) {
507 case ArgumentsRectifierKind::Normal:
508 masm.loadJitCodeRaw(r5, r3);
509 argumentsRectifierReturnOffset_ = masm.callJitNoProfiler(r3);
510 break;
511 case ArgumentsRectifierKind::TrialInlining:
512 Label noBaselineScript, done;
513 masm.loadBaselineJitCodeRaw(r5, r3, &noBaselineScript);
514 masm.callJitNoProfiler(r3);
515 masm.jump(&done);
516
517 // See BaselineCacheIRCompiler::emitCallInlinedFunction.
518 masm.bind(&noBaselineScript);
519 masm.loadJitCodeRaw(r5, r3);
520 masm.callJitNoProfiler(r3);
521 masm.bind(&done);
522 break;
523 }
524
525 masm.moveToStackPtr(FramePointer);
526 masm.pop(FramePointer);
527 masm.ret();
528 }
529
530 static void PushBailoutFrame(MacroAssembler& masm, Register spArg) {
531 // This assumes no SIMD registers, as JS does not support SIMD.
532
533 // The stack saved in spArg must be (higher entries have higher memory
534 // addresses):
535 // - snapshotOffset_
536 // - frameSize_
537 // - regs_
538 // - fpregs_ (spArg + 0)
539 PushRegisterDump(masm);
540 masm.moveStackPtrTo(spArg);
541 }
542
543 static void GenerateBailoutThunk(MacroAssembler& masm, Label* bailoutTail) {
544 PushBailoutFrame(masm, r0);
545
546 // SP % 8 == 4
547 // STEP 1c: Call the bailout function, giving a pointer to the
548 // structure we just blitted onto the stack.
549 // Make space for the BaselineBailoutInfo* outparam.
550 masm.reserveStack(sizeof(void*));
551 masm.moveStackPtrTo(r1);
552
553 using Fn = bool (*)(BailoutStack* sp, BaselineBailoutInfo** info);
554 masm.setupUnalignedABICall(r2);
555 masm.passABIArg(r0);
556 masm.passABIArg(r1);
557 masm.callWithABI<Fn, Bailout>(ABIType::General,
558 CheckUnsafeCallWithABI::DontCheckOther);
559
560 // Get the bailoutInfo outparam.
561 masm.pop(r2);
562
563 // Remove both the bailout frame and the topmost Ion frame's stack.
564 masm.moveToStackPtr(FramePointer);
565
566 // Jump to shared bailout tail. The BailoutInfo pointer has to be in r2.
567 masm.jump(bailoutTail);
568 }
569
570 void JitRuntime::generateBailoutHandler(MacroAssembler& masm,
571 Label* bailoutTail) {
572 AutoCreatedBy acb(masm, "JitRuntime::generateBailoutHandler");
573
574 bailoutHandlerOffset_ = startTrampolineCode(masm);
575
576 GenerateBailoutThunk(masm, bailoutTail);
577 }
578
579 bool JitRuntime::generateVMWrapper(JSContext* cx, MacroAssembler& masm,
580 VMFunctionId id, const VMFunctionData& f,
581 DynFn nativeFun, uint32_t* wrapperOffset) {
582 AutoCreatedBy acb(masm, "JitRuntime::generateVMWrapper");
583
584 *wrapperOffset = startTrampolineCode(masm);
585
586 // Avoid conflicts with argument registers while discarding the result after
587 // the function call.
588 AllocatableGeneralRegisterSet regs(Register::Codes::WrapperMask);
589
590 static_assert(
591 (Register::Codes::VolatileMask & ~Register::Codes::WrapperMask) == 0,
592 "Wrapper register set must be a superset of the Volatile register set.");
593
594 // The first argument is the JSContext.
595 Register reg_cx = IntArgReg0;
596 regs.take(reg_cx);
597 Register temp = regs.getAny();
598
599 // On entry, the stack is:
600 // ... frame ...
601 // [args]
602 // descriptor
603 //
604 // Before we pass arguments (potentially pushing some of them on the stack),
605 // we want:
606 // ... frame ...
607 // [args]
608 // descriptor \
609 // return address | <- exit frame
610 // saved frame pointer /
611 // VM id <- exit frame footer
612 // [space for out-param, if necessary]]
613 // [alignment padding, if necessary]
614 //
615 // To minimize PSP overhead, we compute the final stack size and update the
616 // stack pointer all in one go. Then we use the PSP to "push" the required
617 // values into the pre-allocated stack space.
618 size_t stackAdjustment = 0;
619
620 // The descriptor was already pushed.
621 stackAdjustment += ExitFrameLayout::SizeWithFooter() - sizeof(uintptr_t);
622 stackAdjustment += f.sizeOfOutParamStackSlot();
623
624 masm.SetStackPointer64(sp);
625
626 // First, update the actual stack pointer to its final aligned value.
627 masm.Sub(ARMRegister(temp, 64), masm.GetStackPointer64(),
628 Operand(stackAdjustment));
629 masm.And(sp, ARMRegister(temp, 64), ~(uint64_t(JitStackAlignment) - 1));
630
631 // On link-register platforms, it is the responsibility of the VM *callee* to
632 // push the return address, while the caller must ensure that the address
633 // is stored in lr on entry. This allows the VM wrapper to work with both
634 // direct calls and tail calls.
635 masm.str(ARMRegister(lr, 64),
636 MemOperand(PseudoStackPointer64, -8, vixl::PreIndex));
637
638 // Push the frame pointer using the PSP.
639 masm.str(ARMRegister(FramePointer, 64),
640 MemOperand(PseudoStackPointer64, -8, vixl::PreIndex));
641
642 // Because we've been moving the PSP as we fill in the frame, we can set the
643 // frame pointer for this frame directly from the PSP.
644 masm.movePtr(PseudoStackPointer, FramePointer);
645
646 masm.loadJSContext(reg_cx);
647
648 // Finish the exit frame. See MacroAssembler::enterExitFrame.
649
650 // linkExitFrame
651 masm.loadPtr(Address(reg_cx, JSContext::offsetOfActivation()), temp);
652 masm.storePtr(FramePointer,
653 Address(temp, JitActivation::offsetOfPackedExitFP()));
654
655 // Push `ExitFrameType::VMFunction + VMFunctionId`
656 uint32_t type = uint32_t(ExitFrameType::VMFunction) + uint32_t(id);
657 masm.move32(Imm32(type), temp);
658 masm.str(ARMRegister(temp, 64),
659 MemOperand(PseudoStackPointer64, -8, vixl::PreIndex));
660
661 // If the out parameter is a handle, initialize it to empty.
662 // See MacroAssembler::reserveVMFunctionOutParamSpace and PushEmptyRooted.
663 if (f.outParam == Type_Handle) {
664 switch (f.outParamRootType) {
665 case VMFunctionData::RootNone:
666 MOZ_CRASH("Handle must have root type");
667 case VMFunctionData::RootObject:
668 case VMFunctionData::RootString:
669 case VMFunctionData::RootCell:
670 case VMFunctionData::RootBigInt:
671 masm.str(xzr, MemOperand(PseudoStackPointer64, -8, vixl::PreIndex));
672 break;
673 case VMFunctionData::RootValue:
674 masm.movePtr(ImmWord(UndefinedValue().asRawBits()), temp);
675 masm.str(ARMRegister(temp, 64),
676 MemOperand(PseudoStackPointer64, -8, vixl::PreIndex));
677 break;
678 case VMFunctionData::RootId:
679 masm.movePtr(ImmWord(JS::PropertyKey::Void().asRawBits()), temp);
680 masm.str(ARMRegister(temp, 64),
681 MemOperand(PseudoStackPointer64, -8, vixl::PreIndex));
682 }
683 }
684
685 // Now that we've filled in the stack frame, synchronize the PSP with the
686 // real stack pointer and return to PSP-mode while we pass arguments.
687 masm.moveStackPtrTo(PseudoStackPointer);
688 masm.SetStackPointer64(PseudoStackPointer64);
689
690 MOZ_ASSERT(masm.framePushed() == 0);
691 masm.setupAlignedABICall();
692 masm.passABIArg(reg_cx);
693
694 size_t argDisp = ExitFrameLayout::Size();
695
696 // Copy arguments.
697 for (uint32_t explicitArg = 0; explicitArg < f.explicitArgs; explicitArg++) {
698 switch (f.argProperties(explicitArg)) {
699 case VMFunctionData::WordByValue:
700 masm.passABIArg(
701 MoveOperand(FramePointer, argDisp),
702 (f.argPassedInFloatReg(explicitArg) ? ABIType::Float64
703 : ABIType::General));
704 argDisp += sizeof(void*);
705 break;
706
707 case VMFunctionData::WordByRef:
708 masm.passABIArg(MoveOperand(FramePointer, argDisp,
709 MoveOperand::Kind::EffectiveAddress),
710 ABIType::General);
711 argDisp += sizeof(void*);
712 break;
713
714 case VMFunctionData::DoubleByValue:
715 case VMFunctionData::DoubleByRef:
716 MOZ_CRASH("NYI: AArch64 callVM should not be used with 128bit values.");
717 }
718 }
719
720 // Copy the semi-implicit outparam, if any.
721 // It is not a C++-abi outparam, which would get passed in the
722 // outparam register, but a real parameter to the function, which
723 // was stack-allocated above.
724 const int32_t outParamOffset =
725 -int32_t(ExitFooterFrame::Size()) - f.sizeOfOutParamStackSlot();
726 if (f.outParam != Type_Void) {
727 masm.passABIArg(MoveOperand(FramePointer, outParamOffset,
728 MoveOperand::Kind::EffectiveAddress),
729 ABIType::General);
730 }
731
732 masm.callWithABI(nativeFun, ABIType::General,
733 CheckUnsafeCallWithABI::DontCheckHasExitFrame);
734
735 // Test for failure.
736 switch (f.failType()) {
737 case Type_Cell:
738 masm.branchTestPtr(Assembler::Zero, r0, r0, masm.failureLabel());
739 break;
740 case Type_Bool:
741 masm.branchIfFalseBool(r0, masm.failureLabel());
742 break;
743 case Type_Void:
744 break;
745 default:
746 MOZ_CRASH("unknown failure kind");
747 }
748
749 // Load the outparam.
750 masm.loadVMFunctionOutParam(f, Address(FramePointer, outParamOffset));
751
752 // Until C++ code is instrumented against Spectre, prevent speculative
753 // execution from returning any private data.
754 if (f.returnsData() && JitOptions.spectreJitToCxxCalls) {
755 masm.speculationBarrier();
756 }
757
758 // Pop frame and restore frame pointer. We call Mov here directly instead
759 // of `moveToStackPtr` to avoid a syncStackPtr. The stack pointer will be
760 // synchronized as part of retn, after adjusting the PSP.
761 masm.Mov(masm.GetStackPointer64(), ARMRegister(FramePointer, 64));
762 masm.pop(FramePointer);
763
764 // Return. Subtract sizeof(void*) for the frame pointer.
765 masm.retn(Imm32(sizeof(ExitFrameLayout) - sizeof(void*) +
766 f.explicitStackSlots() * sizeof(void*) +
767 f.extraValuesToPop * sizeof(Value)));
768
769 return true;
770 }
771
772 uint32_t JitRuntime::generatePreBarrier(JSContext* cx, MacroAssembler& masm,
773 MIRType type) {
774 AutoCreatedBy acb(masm, "JitRuntime::generatePreBarrier");
775
776 uint32_t offset = startTrampolineCode(masm);
777
778 static_assert(PreBarrierReg == r1);
779 Register temp1 = r2;
780 Register temp2 = r3;
781 Register temp3 = r4;
782 masm.push(temp1);
783 masm.push(temp2);
784 masm.push(temp3);
785
786 Label noBarrier;
787 masm.emitPreBarrierFastPath(cx->runtime(), type, temp1, temp2, temp3,
788 &noBarrier);
789
790 // Call into C++ to mark this GC thing.
791 masm.pop(temp3);
792 masm.pop(temp2);
793 masm.pop(temp1);
794
795 LiveRegisterSet regs =
796 LiveRegisterSet(GeneralRegisterSet(Registers::VolatileMask),
797 FloatRegisterSet(FloatRegisters::VolatileMask));
798
799 // Also preserve the return address.
800 regs.add(lr);
801
802 masm.PushRegsInMask(regs);
803
804 masm.movePtr(ImmPtr(cx->runtime()), r3);
805
806 masm.setupUnalignedABICall(r0);
807 masm.passABIArg(r3);
808 masm.passABIArg(PreBarrierReg);
809 masm.callWithABI(JitPreWriteBarrier(type));
810
811 // Pop the volatile regs and restore LR.
812 masm.PopRegsInMask(regs);
813 masm.abiret();
814
815 masm.bind(&noBarrier);
816 masm.pop(temp3);
817 masm.pop(temp2);
818 masm.pop(temp1);
819 masm.abiret();
820
821 return offset;
822 }
823
824 void JitRuntime::generateBailoutTailStub(MacroAssembler& masm,
825 Label* bailoutTail) {
826 AutoCreatedBy acb(masm, "JitRuntime::generateBailoutTailStub");
827
828 masm.bind(bailoutTail);
829 masm.generateBailoutTail(r1, r2);
830 }