Debian Codegraph @

js/src/wasm/WasmBCFrame.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 *
4 * Copyright 2016 Mozilla Foundation
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18
19 // This is an INTERNAL header for Wasm baseline compiler: CPU stack frame,
20 // stack maps, and associated logic.
21
22 #ifndef wasm_wasm_baseline_frame_h
23 #define wasm_wasm_baseline_frame_h
24
25 #include "wasm/WasmBaselineCompile.h" // For BaseLocalIter
26 #include "wasm/WasmBCDefs.h"
27 #include "wasm/WasmBCRegDefs.h"
28 #include "wasm/WasmBCStk.h"
29 #include "wasm/WasmConstants.h" // For MaxFrameSize
30
31 // [SMDOC] Wasm baseline compiler's stack frame.
32 //
33 // For background, see "Wasm's ABIs" in WasmFrame.h, the following should never
34 // be in conflict with that.
35 //
36 // The stack frame has four parts ("below" means at lower addresses):
37 //
38 // - the Frame element;
39 // - the Local area, including the DebugFrame element and possibly a spilled
40 // pointer to stack results, if any; allocated below the header with various
41 // forms of alignment;
42 // - the Dynamic area, comprising the temporary storage the compiler uses for
43 // register spilling, allocated below the Local area;
44 // - the Arguments area, comprising memory allocated for outgoing calls,
45 // allocated below the Dynamic area.
46 //
47 // +==============================+
48 // | Incoming stack arg |
49 // | ... |
50 // ------------- +==============================+
51 // | Frame (fixed size) |
52 // ------------- +==============================+ <-------------------- FP
53 // ^ | DebugFrame (optional) | ^ ^ ^^
54 // localSize | Register arg local | | | ||
55 // | | ... | | | framePushed
56 // | | Register stack result ptr?| | | ||
57 // | | Non-arg local | | | ||
58 // | | ... | | | ||
59 // | | (padding) | | | ||
60 // | | Instance pointer | | | ||
61 // | +------------------------------+ | | ||
62 // v | (padding) | | v ||
63 // ------------- +==============================+ currentStackHeight ||
64 // ^ | Dynamic (variable size) | | ||
65 // dynamicSize | ... | | ||
66 // v | ... | v ||
67 // ------------- | (free space, sometimes) | --------- v|
68 // +==============================+ <----- SP not-during calls
69 // | Arguments (sometimes) | |
70 // | ... | v
71 // +==============================+ <----- SP during calls
72 //
73 // The Frame is addressed off the stack pointer. masm.framePushed() is always
74 // correct, and masm.getStackPointer() + masm.framePushed() always addresses the
75 // Frame, with the DebugFrame optionally below it.
76 //
77 // The Local area (including the DebugFrame and, if needed, the spilled value of
78 // the stack results area pointer) is laid out by BaseLocalIter and is allocated
79 // and deallocated by standard prologue and epilogue functions that manipulate
80 // the stack pointer, but it is accessed via BaseStackFrame.
81 //
82 // The Dynamic area is maintained by and accessed via BaseStackFrame. On some
83 // systems (such as ARM64), the Dynamic memory may be allocated in chunks
84 // because the SP needs a specific alignment, and in this case there will
85 // normally be some free space directly above the SP. The stack height does not
86 // include the free space, it reflects the logically used space only.
87 //
88 // The Dynamic area is where space for stack results is allocated when calling
89 // functions that return results on the stack. If a function has stack results,
90 // a pointer to the low address of the stack result area is passed as an
91 // additional argument, according to the usual ABI. See
92 // ABIResultIter::HasStackResults.
93 //
94 // The Arguments area is allocated and deallocated via BaseStackFrame (see
95 // comments later) but is accessed directly off the stack pointer.
96
97 namespace js {
98 namespace wasm {
99
100 using namespace js::jit;
101
102 // Abstraction of the height of the stack frame, to avoid type confusion.
103
104 class StackHeight {
105 friend class BaseStackFrameAllocator;
106
107 uint32_t height;
108
109 public:
110 explicit StackHeight(uint32_t h) : height(h) {}
111 static StackHeight Invalid() { return StackHeight(UINT32_MAX); }
112 bool isValid() const { return height != UINT32_MAX; }
113 bool operator==(StackHeight rhs) const {
114 MOZ_ASSERT(isValid() && rhs.isValid());
115 return height == rhs.height;
116 }
117 bool operator!=(StackHeight rhs) const { return !(*this == rhs); }
118 };
119
120 // Abstraction for where multi-value results go on the machine stack.
121
122 class StackResultsLoc {
123 uint32_t bytes_;
124 size_t count_;
125 mozilla::Maybe<uint32_t> height_;
126
127 public:
128 StackResultsLoc() : bytes_(0), count_(0) {};
129 StackResultsLoc(uint32_t bytes, size_t count, uint32_t height)
130 : bytes_(bytes), count_(count), height_(mozilla::Some(height)) {
131 MOZ_ASSERT(bytes != 0);
132 MOZ_ASSERT(count != 0);
133 MOZ_ASSERT(height != 0);
134 }
135
136 uint32_t bytes() const { return bytes_; }
137 uint32_t count() const { return count_; }
138 uint32_t height() const { return height_.value(); }
139
140 bool hasStackResults() const { return bytes() != 0; }
141 StackResults stackResults() const {
142 return hasStackResults() ? StackResults::HasStackResults
143 : StackResults::NoStackResults;
144 }
145 };
146
147 // Abstraction of the baseline compiler's stack frame (except for the Frame /
148 // DebugFrame parts). See comments above for more. Remember, "below" on the
149 // stack means at lower addresses.
150 //
151 // The abstraction is split into two parts: BaseStackFrameAllocator is
152 // responsible for allocating and deallocating space on the stack and for
153 // performing computations that are affected by how the allocation is performed;
154 // BaseStackFrame then provides a pleasant interface for stack frame management.
155
156 class BaseStackFrameAllocator {
157 MacroAssembler& masm;
158
159 #ifdef RABALDR_CHUNKY_STACK
160 // On platforms that require the stack pointer to be aligned on a boundary
161 // greater than the typical stack item (eg, ARM64 requires 16-byte alignment
162 // but items are 8 bytes), allocate stack memory in chunks, and use a
163 // separate stack height variable to track the effective stack pointer
164 // within the allocated area. Effectively, there's a variable amount of
165 // free space directly above the stack pointer. See diagram above.
166
167 // The following must be true in order for the stack height to be
168 // predictable at control flow joins:
169 //
170 // - The Local area is always aligned according to WasmStackAlignment, ie,
171 // masm.framePushed() % WasmStackAlignment is zero after allocating
172 // locals.
173 //
174 // - ChunkSize is always a multiple of WasmStackAlignment.
175 //
176 // - Pushing and popping are always in units of ChunkSize (hence preserving
177 // alignment).
178 //
179 // - The free space on the stack (masm.framePushed() - currentStackHeight_)
180 // is a predictable (nonnegative) amount.
181
182 // As an optimization, we pre-allocate some space on the stack, the size of
183 // this allocation is InitialChunk and it must be a multiple of ChunkSize.
184 // It is allocated as part of the function prologue and deallocated as part
185 // of the epilogue, along with the locals.
186 //
187 // If ChunkSize is too large then we risk overflowing the stack on simple
188 // recursions with few live values where stack overflow should not be a
189 // risk; if it is too small we spend too much time adjusting the stack
190 // pointer.
191 //
192 // Good values for ChunkSize are the subject of future empirical analysis;
193 // eight words is just an educated guess.
194
195 static constexpr uint32_t ChunkSize = 8 * sizeof(void*);
196 static constexpr uint32_t InitialChunk = ChunkSize;
197
198 // The current logical height of the frame is
199 // currentStackHeight_ = localSize_ + dynamicSize
200 // where dynamicSize is not accounted for explicitly and localSize_ also
201 // includes size for the DebugFrame.
202 //
203 // The allocated size of the frame, provided by masm.framePushed(), is usually
204 // larger than currentStackHeight_, notably at the beginning of execution when
205 // we've allocated InitialChunk extra space.
206
207 uint32_t currentStackHeight_;
208 #endif
209
210 // Size of the Local area in bytes (stable after BaseCompiler::init() has
211 // called BaseStackFrame::setupLocals(), which in turn calls
212 // BaseStackFrameAllocator::setLocalSize()), always rounded to the proper
213 // stack alignment. The Local area is then allocated in beginFunction(),
214 // following the allocation of the Header. See onFixedStackAllocated()
215 // below.
216
217 uint32_t localSize_;
218
219 protected:
220 ///////////////////////////////////////////////////////////////////////////
221 //
222 // Initialization
223
224 explicit BaseStackFrameAllocator(MacroAssembler& masm)
225 : masm(masm),
226 #ifdef RABALDR_CHUNKY_STACK
227 currentStackHeight_(0),
228 #endif
229 localSize_(UINT32_MAX) {
230 }
231
232 protected:
233 //////////////////////////////////////////////////////////////////////
234 //
235 // The Local area - the static part of the frame.
236
237 // Record the size of the Local area, once it is known.
238
239 void setLocalSize(uint32_t localSize) {
240 MOZ_ASSERT(localSize == AlignBytes(localSize, sizeof(void*)),
241 "localSize_ should be aligned to at least a pointer");
242 MOZ_ASSERT(localSize_ == UINT32_MAX);
243 localSize_ = localSize;
244 }
245
246 // Record the current stack height, after it has become stable in
247 // beginFunction(). See also BaseStackFrame::onFixedStackAllocated().
248
249 void onFixedStackAllocated() {
250 MOZ_ASSERT(localSize_ != UINT32_MAX);
251 #ifdef RABALDR_CHUNKY_STACK
252 currentStackHeight_ = localSize_;
253 #endif
254 }
255
256 public:
257 // The fixed amount of memory, in bytes, allocated on the stack below the
258 // Header for purposes such as locals and other fixed values. Includes all
259 // necessary alignment, and on ARM64 also the initial chunk for the working
260 // stack memory.
261
262 uint32_t fixedAllocSize() const {
263 MOZ_ASSERT(localSize_ != UINT32_MAX);
264 #ifdef RABALDR_CHUNKY_STACK
265 return localSize_ + InitialChunk;
266 #else
267 return localSize_;
268 #endif
269 }
270
271 #ifdef RABALDR_CHUNKY_STACK
272 // The allocated frame size is frequently larger than the logical stack
273 // height; we round up to a chunk boundary, and special case the initial
274 // chunk.
275 uint32_t framePushedForHeight(uint32_t logicalHeight) {
276 if (logicalHeight <= fixedAllocSize()) {
277 return fixedAllocSize();
278 }
279 return fixedAllocSize() +
280 AlignBytes(logicalHeight - fixedAllocSize(), ChunkSize);
281 }
282 #endif
283
284 protected:
285 //////////////////////////////////////////////////////////////////////
286 //
287 // The Dynamic area - the dynamic part of the frame, for spilling and saving
288 // intermediate values.
289
290 // Offset off of sp_ for the slot at stack area location `offset`.
291
292 int32_t stackOffset(int32_t offset) {
293 MOZ_ASSERT(offset > 0);
294 return masm.framePushed() - offset;
295 }
296
297 uint32_t computeHeightWithStackResults(StackHeight stackBase,
298 uint32_t stackResultBytes) {
299 MOZ_ASSERT(stackResultBytes);
300 MOZ_ASSERT(currentStackHeight() >= stackBase.height);
301 return stackBase.height + stackResultBytes;
302 }
303
304 #ifdef RABALDR_CHUNKY_STACK
305 void pushChunkyBytes(uint32_t bytes) {
306 checkChunkyInvariants();
307 uint32_t freeSpace = masm.framePushed() - currentStackHeight_;
308 if (freeSpace < bytes) {
309 uint32_t bytesToReserve = AlignBytes(bytes - freeSpace, ChunkSize);
310 MOZ_ASSERT(bytesToReserve + freeSpace >= bytes);
311 masm.reserveStack(bytesToReserve);
312 }
313 currentStackHeight_ += bytes;
314 checkChunkyInvariants();
315 }
316
317 void popChunkyBytes(uint32_t bytes) {
318 checkChunkyInvariants();
319 currentStackHeight_ -= bytes;
320 // Sometimes, popChunkyBytes() is used to pop a larger area, as when we drop
321 // values consumed by a call, and we may need to drop several chunks. But
322 // never drop the initial chunk. Crucially, the amount we drop is always an
323 // integral number of chunks.
324 uint32_t freeSpace = masm.framePushed() - currentStackHeight_;
325 if (freeSpace >= ChunkSize) {
326 uint32_t targetAllocSize = framePushedForHeight(currentStackHeight_);
327 uint32_t amountToFree = masm.framePushed() - targetAllocSize;
328 MOZ_ASSERT(amountToFree % ChunkSize == 0);
329 if (amountToFree) {
330 masm.freeStack(amountToFree);
331 }
332 }
333 checkChunkyInvariants();
334 }
335 #endif
336
337 uint32_t currentStackHeight() const {
338 #ifdef RABALDR_CHUNKY_STACK
339 return currentStackHeight_;
340 #else
341 return masm.framePushed();
342 #endif
343 }
344
345 private:
346 #ifdef RABALDR_CHUNKY_STACK
347 void checkChunkyInvariants() {
348 MOZ_ASSERT(masm.framePushed() >= fixedAllocSize());
349 MOZ_ASSERT(masm.framePushed() >= currentStackHeight_);
350 MOZ_ASSERT(masm.framePushed() == fixedAllocSize() ||
351 masm.framePushed() - currentStackHeight_ < ChunkSize);
352 MOZ_ASSERT((masm.framePushed() - localSize_) % ChunkSize == 0);
353 }
354 #endif
355
356 // For a given stack height, return the appropriate size of the allocated
357 // frame.
358
359 uint32_t framePushedForHeight(StackHeight stackHeight) {
360 #ifdef RABALDR_CHUNKY_STACK
361 // A more complicated adjustment is needed.
362 return framePushedForHeight(stackHeight.height);
363 #else
364 // The allocated frame size equals the stack height.
365 return stackHeight.height;
366 #endif
367 }
368
369 public:
370 // The current height of the stack area, not necessarily zero-based, in a
371 // type-safe way.
372
373 StackHeight stackHeight() const { return StackHeight(currentStackHeight()); }
374
375 // Set the frame height to a previously recorded value.
376
377 void setStackHeight(StackHeight amount) {
378 #ifdef RABALDR_CHUNKY_STACK
379 currentStackHeight_ = amount.height;
380 masm.setFramePushed(framePushedForHeight(amount));
381 checkChunkyInvariants();
382 #else
383 masm.setFramePushed(amount.height);
384 #endif
385 }
386
387 // The current height of the dynamic part of the stack area (ie, the backing
388 // store for the evaluation stack), zero-based.
389
390 uint32_t dynamicHeight() const { return currentStackHeight() - localSize_; }
391
392 // Before branching to an outer control label, pop the execution stack to
393 // the level expected by that region, but do not update masm.framePushed()
394 // as that will happen as compilation leaves the block.
395 //
396 // Note these operate directly on the stack pointer register.
397
398 void popStackBeforeBranch(StackHeight destStackHeight,
399 uint32_t stackResultBytes) {
400 uint32_t framePushedHere = masm.framePushed();
401 StackHeight heightThere =
402 StackHeight(destStackHeight.height + stackResultBytes);
403 uint32_t framePushedThere = framePushedForHeight(heightThere);
404 if (framePushedHere > framePushedThere) {
405 masm.addToStackPtr(Imm32(framePushedHere - framePushedThere));
406 }
407 }
408
409 void popStackBeforeBranch(StackHeight destStackHeight, ResultType type) {
410 popStackBeforeBranch(destStackHeight,
411 ABIResultIter::MeasureStackBytes(type));
412 }
413
414 // Given that there are |stackParamSize| bytes on the dynamic stack
415 // corresponding to the stack results, return the stack height once these
416 // parameters are popped.
417
418 StackHeight stackResultsBase(uint32_t stackParamSize) {
419 return StackHeight(currentStackHeight() - stackParamSize);
420 }
421
422 // For most of WebAssembly, adjacent instructions have fallthrough control
423 // flow between them, which allows us to simply thread the current stack
424 // height through the compiler. There are two exceptions to this rule: when
425 // leaving a block via dead code, and when entering the "else" arm of an "if".
426 // In these cases, the stack height is the block entry height, plus any stack
427 // values (results in the block exit case, parameters in the else entry case).
428
429 void resetStackHeight(StackHeight destStackHeight, ResultType type) {
430 uint32_t height = destStackHeight.height;
431 height += ABIResultIter::MeasureStackBytes(type);
432 setStackHeight(StackHeight(height));
433 }
434
435 // Return offset of stack result.
436
437 uint32_t locateStackResult(const ABIResult& result, StackHeight stackBase,
438 uint32_t stackResultBytes) {
439 MOZ_ASSERT(result.onStack());
440 MOZ_ASSERT(result.stackOffset() + result.size() <= stackResultBytes);
441 uint32_t end = computeHeightWithStackResults(stackBase, stackResultBytes);
442 return end - result.stackOffset();
443 }
444
445 public:
446 //////////////////////////////////////////////////////////////////////
447 //
448 // The Argument area - for outgoing calls.
449 //
450 // We abstract these operations as an optimization: we can merge the freeing
451 // of the argument area and dropping values off the stack after a call. But
452 // they always amount to manipulating the real stack pointer by some amount.
453 //
454 // Note that we do not update currentStackHeight_ for this; the frame does
455 // not know about outgoing arguments. But we do update framePushed(), so we
456 // can still index into the frame below the outgoing arguments area.
457
458 // This is always equivalent to a masm.reserveStack() call.
459
460 void allocArgArea(size_t argSize) {
461 if (argSize) {
462 masm.reserveStack(argSize);
463 }
464 }
465
466 // This frees the argument area allocated by allocArgArea(), and `argSize`
467 // must be equal to the `argSize` argument to allocArgArea(). In addition
468 // we drop some values from the frame, corresponding to the values that were
469 // consumed by the call.
470
471 void freeArgAreaAndPopBytes(size_t argSize, size_t dropSize) {
472 // The method is called to re-initialize SP after the call. Note that
473 // this operation shall not be optimized for argSize + dropSize == 0.
474 #ifdef RABALDR_CHUNKY_STACK
475 // Freeing the outgoing arguments and freeing the consumed values have
476 // different semantics here, which is why the operation is split.
477 masm.freeStackTo(masm.framePushed() - argSize);
478 popChunkyBytes(dropSize);
479 #else
480 masm.freeStackTo(masm.framePushed() - (argSize + dropSize));
481 #endif
482 }
483 };
484
485 class BaseStackFrame final : public BaseStackFrameAllocator {
486 MacroAssembler& masm;
487
488 // The largest observed value of masm.framePushed(), ie, the size of the
489 // stack frame. Read this for its true value only when code generation is
490 // finished.
491 uint32_t maxFramePushed_;
492
493 // Patch point where we check for stack overflow.
494 CodeOffset stackAddOffset_;
495
496 // Low byte offset of pointer to stack results, if any.
497 mozilla::Maybe<int32_t> stackResultsPtrOffset_;
498
499 // The offset of instance pointer.
500 uint32_t instancePointerOffset_;
501
502 // Low byte offset of local area for true locals (not parameters).
503 uint32_t varLow_;
504
505 // High byte offset + 1 of local area for true locals.
506 uint32_t varHigh_;
507
508 // The stack pointer, cached for brevity.
509 RegisterOrSP sp_;
510
511 public:
512 explicit BaseStackFrame(MacroAssembler& masm)
513 : BaseStackFrameAllocator(masm),
514 masm(masm),
515 maxFramePushed_(0),
516 stackAddOffset_(0),
517 instancePointerOffset_(UINT32_MAX),
518 varLow_(UINT32_MAX),
519 varHigh_(UINT32_MAX),
520 sp_(masm.getStackPointer()) {}
521
522 ///////////////////////////////////////////////////////////////////////////
523 //
524 // Stack management and overflow checking
525
526 // This must be called once beginFunction has allocated space for the Header
527 // (the Frame and DebugFrame) and the Local area, and will record the current
528 // frame size for internal use by the stack abstractions.
529
530 void onFixedStackAllocated() {
531 maxFramePushed_ = masm.framePushed();
532 BaseStackFrameAllocator::onFixedStackAllocated();
533 }
534
535 // We won't know until after we've generated code how big the frame will be
536 // (we may need arbitrary spill slots and outgoing param slots) so emit a
537 // patchable add that is patched in endFunction().
538 //
539 // Note the platform scratch register may be used by branchPtr(), so
540 // generally tmp must be something else.
541
542 void checkStack(Register tmp, TrapSiteDesc trapSiteDesc) {
543 stackAddOffset_ = masm.sub32FromStackPtrWithPatch(tmp);
544 Label ok;
545 masm.branchPtr(Assembler::Below,
546 Address(InstanceReg, wasm::Instance::offsetOfStackLimit()),
547 tmp, &ok);
548 masm.wasmTrap(Trap::StackOverflow, trapSiteDesc);
549 masm.bind(&ok);
550 }
551
552 void patchCheckStack() {
553 masm.patchSub32FromStackPtr(stackAddOffset_,
554 Imm32(int32_t(maxFramePushed_)));
555 }
556
557 // Very large frames are implausible, probably an attack.
558
559 bool checkStackHeight() { return maxFramePushed_ <= MaxFrameSize; }
560
561 ///////////////////////////////////////////////////////////////////////////
562 //
563 // Local area
564
565 struct Local {
566 // Type of the value.
567 const MIRType type;
568
569 // Byte offset from Frame "into" the locals, ie positive for true locals
570 // and negative for incoming args that read directly from the arg area.
571 // It assumes the stack is growing down and that locals are on the stack
572 // at lower addresses than Frame, and is the offset from Frame of the
573 // lowest-addressed byte of the local.
574 const int32_t offs;
575
576 Local(MIRType type, int32_t offs) : type(type), offs(offs) {}
577
578 bool isStackArgument() const { return offs < 0; }
579 };
580
581 // Profiling shows that the number of parameters and locals frequently
582 // touches or exceeds 8. So 16 seems like a reasonable starting point.
583 using LocalVector = Vector<Local, 16, SystemAllocPolicy>;
584
585 // Initialize `localInfo` based on the types of `locals` and `args`.
586 [[nodiscard]] bool setupLocals(const ValTypeVector& locals,
587 const ArgTypeVector& args, bool debugEnabled,
588 LocalVector* localInfo) {
589 if (!localInfo->reserve(locals.length())) {
590 return false;
591 }
592
593 mozilla::DebugOnly<uint32_t> index = 0;
594 BaseLocalIter i(locals, args, debugEnabled);
595 for (; !i.done() && i.index() < args.lengthWithoutStackResults(); i++) {
596 MOZ_ASSERT(i.isArg());
597 MOZ_ASSERT(i.index() == index);
598 localInfo->infallibleEmplaceBack(i.mirType(), i.frameOffset());
599 index++;
600 }
601
602 varLow_ = i.frameSize();
603 for (; !i.done(); i++) {
604 MOZ_ASSERT(!i.isArg());
605 MOZ_ASSERT(i.index() == index);
606 localInfo->infallibleEmplaceBack(i.mirType(), i.frameOffset());
607 index++;
608 }
609 varHigh_ = i.frameSize();
610
611 // Reserve an additional stack slot for the instance pointer.
612 const uint32_t pointerAlignedVarHigh = AlignBytes(varHigh_, sizeof(void*));
613 const uint32_t localSize = pointerAlignedVarHigh + sizeof(void*);
614 instancePointerOffset_ = localSize;
615
616 setLocalSize(AlignBytes(localSize, WasmStackAlignment));
617
618 if (args.hasSyntheticStackResultPointerArg()) {
619 stackResultsPtrOffset_ = mozilla::Some(i.stackResultPointerOffset());
620 }
621
622 return true;
623 }
624
625 void zeroLocals(BaseRegAlloc* ra);
626
627 Address addressOfLocal(const Local& local, uint32_t additionalOffset = 0) {
628 if (local.isStackArgument()) {
629 return Address(FramePointer,
630 stackArgumentOffsetFromFp(local) + additionalOffset);
631 }
632 return Address(sp_, localOffsetFromSp(local) + additionalOffset);
633 }
634
635 void loadLocalI32(const Local& src, RegI32 dest) {
636 masm.load32(addressOfLocal(src), dest);
637 }
638
639 #ifndef JS_PUNBOX64
640 void loadLocalI64Low(const Local& src, RegI32 dest) {
641 masm.load32(addressOfLocal(src, INT64LOW_OFFSET), dest);
642 }
643
644 void loadLocalI64High(const Local& src, RegI32 dest) {
645 masm.load32(addressOfLocal(src, INT64HIGH_OFFSET), dest);
646 }
647 #endif
648
649 void loadLocalI64(const Local& src, RegI64 dest) {
650 masm.load64(addressOfLocal(src), dest);
651 }
652
653 void loadLocalRef(const Local& src, RegRef dest) {
654 masm.loadPtr(addressOfLocal(src), dest);
655 }
656
657 void loadLocalF64(const Local& src, RegF64 dest) {
658 masm.loadDouble(addressOfLocal(src), dest);
659 }
660
661 void loadLocalF32(const Local& src, RegF32 dest) {
662 masm.loadFloat32(addressOfLocal(src), dest);
663 }
664
665 #ifdef ENABLE_WASM_SIMD
666 void loadLocalV128(const Local& src, RegV128 dest) {
667 masm.loadUnalignedSimd128(addressOfLocal(src), dest);
668 }
669 #endif
670
671 void storeLocalI32(RegI32 src, const Local& dest) {
672 masm.store32(src, addressOfLocal(dest));
673 }
674
675 void storeLocalI64(RegI64 src, const Local& dest) {
676 masm.store64(src, addressOfLocal(dest));
677 }
678
679 void storeLocalRef(RegRef src, const Local& dest) {
680 masm.storePtr(src, addressOfLocal(dest));
681 }
682
683 void storeLocalF64(RegF64 src, const Local& dest) {
684 masm.storeDouble(src, addressOfLocal(dest));
685 }
686
687 void storeLocalF32(RegF32 src, const Local& dest) {
688 masm.storeFloat32(src, addressOfLocal(dest));
689 }
690
691 #ifdef ENABLE_WASM_SIMD
692 void storeLocalV128(RegV128 src, const Local& dest) {
693 masm.storeUnalignedSimd128(src, addressOfLocal(dest));
694 }
695 #endif
696
697 // Offset off of sp_ for `local`.
698 int32_t localOffsetFromSp(const Local& local) {
699 MOZ_ASSERT(!local.isStackArgument());
700 return localOffset(local.offs);
701 }
702
703 // Offset off of frame pointer for `stack argument`.
704 int32_t stackArgumentOffsetFromFp(const Local& local) {
705 MOZ_ASSERT(local.isStackArgument());
706 return -local.offs;
707 }
708
709 // The incoming stack result area pointer is for stack results of the function
710 // being compiled.
711 void loadIncomingStackResultAreaPtr(RegPtr reg) {
712 const int32_t offset = stackResultsPtrOffset_.value();
713 Address src = offset < 0 ? Address(FramePointer, -offset)
714 : Address(sp_, stackOffset(offset));
715 masm.loadPtr(src, reg);
716 }
717
718 void storeIncomingStackResultAreaPtr(RegPtr reg) {
719 // If we get here, that means the pointer to the stack results area was
720 // passed in as a register, and therefore it will be spilled below the
721 // frame, so the offset is a positive height.
722 MOZ_ASSERT(stackResultsPtrOffset_.value() > 0);
723 masm.storePtr(reg,
724 Address(sp_, stackOffset(stackResultsPtrOffset_.value())));
725 }
726
727 void loadInstancePtr(Register dst) {
728 // Sometimes loadInstancePtr is used in context when SP is not sync is FP,
729 // e.g. just after tail calls returns.
730 masm.loadPtr(Address(FramePointer, -instancePointerOffset_), dst);
731 }
732
733 void storeInstancePtr(Register instance) {
734 masm.storePtr(instance, Address(sp_, stackOffset(instancePointerOffset_)));
735 }
736
737 int32_t getInstancePtrOffset() { return stackOffset(instancePointerOffset_); }
738
739 // An outgoing stack result area pointer is for stack results of callees of
740 // the function being compiled.
741 void computeOutgoingStackResultAreaPtr(const StackResultsLoc& results,
742 RegPtr dest) {
743 MOZ_ASSERT(results.height() <= masm.framePushed());
744 uint32_t offsetFromSP = masm.framePushed() - results.height();
745 masm.moveStackPtrTo(dest);
746 if (offsetFromSP) {
747 masm.addPtr(Imm32(offsetFromSP), dest);
748 }
749 }
750
751 private:
752 // Offset off of sp_ for a local with offset `offset` from Frame.
753 int32_t localOffset(int32_t offset) { return masm.framePushed() - offset; }
754
755 public:
756 ///////////////////////////////////////////////////////////////////////////
757 //
758 // Dynamic area
759
760 static constexpr size_t StackSizeOfPtr = ABIResult::StackSizeOfPtr;
761 static constexpr size_t StackSizeOfInt64 = ABIResult::StackSizeOfInt64;
762 static constexpr size_t StackSizeOfFloat = ABIResult::StackSizeOfFloat;
763 static constexpr size_t StackSizeOfDouble = ABIResult::StackSizeOfDouble;
764 #ifdef ENABLE_WASM_SIMD
765 static constexpr size_t StackSizeOfV128 = ABIResult::StackSizeOfV128;
766 #endif
767
768 // Pushes the register `r` to the stack. This pushes the full 64-bit width on
769 // 64-bit systems, and 32-bits otherwise.
770 uint32_t pushGPR(Register r) {
771 mozilla::DebugOnly<uint32_t> stackBefore = currentStackHeight();
772 #ifdef RABALDR_CHUNKY_STACK
773 pushChunkyBytes(StackSizeOfPtr);
774 masm.storePtr(r, Address(sp_, stackOffset(currentStackHeight())));
775 #else
776 masm.Push(r);
777 #endif
778 maxFramePushed_ = std::max(maxFramePushed_, masm.framePushed());
779 MOZ_ASSERT(stackBefore + StackSizeOfPtr == currentStackHeight());
780 return currentStackHeight();
781 }
782
783 uint32_t pushFloat32(FloatRegister r) {
784 mozilla::DebugOnly<uint32_t> stackBefore = currentStackHeight();
785 #ifdef RABALDR_CHUNKY_STACK
786 pushChunkyBytes(StackSizeOfFloat);
787 masm.storeFloat32(r, Address(sp_, stackOffset(currentStackHeight())));
788 #else
789 if (StackSizeOfFloat == 4) {
790 masm.Push(r);
791 } else {
792 masm.Push(r.asDouble());
793 }
794 #endif
795 maxFramePushed_ = std::max(maxFramePushed_, masm.framePushed());
796 MOZ_ASSERT(stackBefore + StackSizeOfFloat == currentStackHeight());
797 return currentStackHeight();
798 }
799
800 #ifdef ENABLE_WASM_SIMD
801 uint32_t pushV128(RegV128 r) {
802 mozilla::DebugOnly<uint32_t> stackBefore = currentStackHeight();
803 # ifdef RABALDR_CHUNKY_STACK
804 pushChunkyBytes(StackSizeOfV128);
805 # else
806 masm.adjustStack(-(int)StackSizeOfV128);
807 # endif
808 masm.storeUnalignedSimd128(r,
809 Address(sp_, stackOffset(currentStackHeight())));
810 maxFramePushed_ = std::max(maxFramePushed_, masm.framePushed());
811 MOZ_ASSERT(stackBefore + StackSizeOfV128 == currentStackHeight());
812 return currentStackHeight();
813 }
814 #endif
815
816 uint32_t pushDouble(FloatRegister r) {
817 mozilla::DebugOnly<uint32_t> stackBefore = currentStackHeight();
818 #ifdef RABALDR_CHUNKY_STACK
819 pushChunkyBytes(StackSizeOfDouble);
820 masm.storeDouble(r, Address(sp_, stackOffset(currentStackHeight())));
821 #else
822 masm.Push(r);
823 #endif
824 maxFramePushed_ = std::max(maxFramePushed_, masm.framePushed());
825 MOZ_ASSERT(stackBefore + StackSizeOfDouble == currentStackHeight());
826 return currentStackHeight();
827 }
828
829 // Pops the stack into the register `r`. This pops the full 64-bit width on
830 // 64-bit systems, and 32-bits otherwise.
831 void popGPR(Register r) {
832 mozilla::DebugOnly<uint32_t> stackBefore = currentStackHeight();
833 #ifdef RABALDR_CHUNKY_STACK
834 masm.loadPtr(Address(sp_, stackOffset(currentStackHeight())), r);
835 popChunkyBytes(StackSizeOfPtr);
836 #else
837 masm.Pop(r);
838 #endif
839 MOZ_ASSERT(stackBefore - StackSizeOfPtr == currentStackHeight());
840 }
841
842 void popFloat32(FloatRegister r) {
843 mozilla::DebugOnly<uint32_t> stackBefore = currentStackHeight();
844 #ifdef RABALDR_CHUNKY_STACK
845 masm.loadFloat32(Address(sp_, stackOffset(currentStackHeight())), r);
846 popChunkyBytes(StackSizeOfFloat);
847 #else
848 if (StackSizeOfFloat == 4) {
849 masm.Pop(r);
850 } else {
851 masm.Pop(r.asDouble());
852 }
853 #endif
854 MOZ_ASSERT(stackBefore - StackSizeOfFloat == currentStackHeight());
855 }
856
857 void popDouble(FloatRegister r) {
858 mozilla::DebugOnly<uint32_t> stackBefore = currentStackHeight();
859 #ifdef RABALDR_CHUNKY_STACK
860 masm.loadDouble(Address(sp_, stackOffset(currentStackHeight())), r);
861 popChunkyBytes(StackSizeOfDouble);
862 #else
863 masm.Pop(r);
864 #endif
865 MOZ_ASSERT(stackBefore - StackSizeOfDouble == currentStackHeight());
866 }
867
868 #ifdef ENABLE_WASM_SIMD
869 void popV128(RegV128 r) {
870 mozilla::DebugOnly<uint32_t> stackBefore = currentStackHeight();
871 masm.loadUnalignedSimd128(Address(sp_, stackOffset(currentStackHeight())),
872 r);
873 # ifdef RABALDR_CHUNKY_STACK
874 popChunkyBytes(StackSizeOfV128);
875 # else
876 masm.adjustStack((int)StackSizeOfV128);
877 # endif
878 MOZ_ASSERT(stackBefore - StackSizeOfV128 == currentStackHeight());
879 }
880 #endif
881
882 void popBytes(size_t bytes) {
883 if (bytes > 0) {
884 #ifdef RABALDR_CHUNKY_STACK
885 popChunkyBytes(bytes);
886 #else
887 masm.freeStack(bytes);
888 #endif
889 }
890 }
891
892 void loadStackI32(int32_t offset, RegI32 dest) {
893 masm.load32(Address(sp_, stackOffset(offset)), dest);
894 }
895
896 void loadStackI64(int32_t offset, RegI64 dest) {
897 masm.load64(Address(sp_, stackOffset(offset)), dest);
898 }
899
900 #ifndef JS_PUNBOX64
901 void loadStackI64Low(int32_t offset, RegI32 dest) {
902 masm.load32(Address(sp_, stackOffset(offset - INT64LOW_OFFSET)), dest);
903 }
904
905 void loadStackI64High(int32_t offset, RegI32 dest) {
906 masm.load32(Address(sp_, stackOffset(offset - INT64HIGH_OFFSET)), dest);
907 }
908 #endif
909
910 void loadStackRef(int32_t offset, RegRef dest) {
911 masm.loadPtr(Address(sp_, stackOffset(offset)), dest);
912 }
913
914 void loadStackF64(int32_t offset, RegF64 dest) {
915 masm.loadDouble(Address(sp_, stackOffset(offset)), dest);
916 }
917
918 void loadStackF32(int32_t offset, RegF32 dest) {
919 masm.loadFloat32(Address(sp_, stackOffset(offset)), dest);
920 }
921
922 #ifdef ENABLE_WASM_SIMD
923 void loadStackV128(int32_t offset, RegV128 dest) {
924 masm.loadUnalignedSimd128(Address(sp_, stackOffset(offset)), dest);
925 }
926 #endif
927
928 uint32_t prepareStackResultArea(StackHeight stackBase,
929 uint32_t stackResultBytes) {
930 uint32_t end = computeHeightWithStackResults(stackBase, stackResultBytes);
931 if (currentStackHeight() < end) {
932 uint32_t bytes = end - currentStackHeight();
933 #ifdef RABALDR_CHUNKY_STACK
934 pushChunkyBytes(bytes);
935 #else
936 masm.reserveStack(bytes);
937 #endif
938 maxFramePushed_ = std::max(maxFramePushed_, masm.framePushed());
939 }
940 return end;
941 }
942
943 void finishStackResultArea(StackHeight stackBase, uint32_t stackResultBytes) {
944 uint32_t end = computeHeightWithStackResults(stackBase, stackResultBytes);
945 MOZ_ASSERT(currentStackHeight() >= end);
946 popBytes(currentStackHeight() - end);
947 }
948
949 // |srcHeight| and |destHeight| are stack heights *including* |bytes|.
950 void shuffleStackResultsTowardFP(uint32_t srcHeight, uint32_t destHeight,
951 uint32_t bytes, Register temp) {
952 MOZ_ASSERT(destHeight < srcHeight);
953 MOZ_ASSERT(bytes % sizeof(uint32_t) == 0);
954 // The shuffleStackResultsTowardFP is used when SP/framePushed is not
955 // tracked by the compiler, e.g. after possible return call -- use
956 // FramePointer instead of sp_.
957 int32_t destOffset = int32_t(-destHeight + bytes);
958 int32_t srcOffset = int32_t(-srcHeight + bytes);
959 while (bytes >= sizeof(intptr_t)) {
960 destOffset -= sizeof(intptr_t);
961 srcOffset -= sizeof(intptr_t);
962 bytes -= sizeof(intptr_t);
963 masm.loadPtr(Address(FramePointer, srcOffset), temp);
964 masm.storePtr(temp, Address(FramePointer, destOffset));
965 }
966 if (bytes) {
967 MOZ_ASSERT(bytes == sizeof(uint32_t));
968 destOffset -= sizeof(uint32_t);
969 srcOffset -= sizeof(uint32_t);
970 masm.load32(Address(FramePointer, srcOffset), temp);
971 masm.store32(temp, Address(FramePointer, destOffset));
972 }
973 }
974
975 // Unlike the overload that operates on raw heights, |srcHeight| and
976 // |destHeight| are stack heights *not including* |bytes|.
977 void shuffleStackResultsTowardFP(StackHeight srcHeight,
978 StackHeight destHeight, uint32_t bytes,
979 Register temp) {
980 MOZ_ASSERT(srcHeight.isValid());
981 MOZ_ASSERT(destHeight.isValid());
982 uint32_t src = computeHeightWithStackResults(srcHeight, bytes);
983 uint32_t dest = computeHeightWithStackResults(destHeight, bytes);
984 MOZ_ASSERT(src <= currentStackHeight());
985 MOZ_ASSERT(dest <= currentStackHeight());
986 shuffleStackResultsTowardFP(src, dest, bytes, temp);
987 }
988
989 // |srcHeight| and |destHeight| are stack heights *including* |bytes|.
990 void shuffleStackResultsTowardSP(uint32_t srcHeight, uint32_t destHeight,
991 uint32_t bytes, Register temp) {
992 MOZ_ASSERT(destHeight > srcHeight);
993 MOZ_ASSERT(bytes % sizeof(uint32_t) == 0);
994 uint32_t destOffset = stackOffset(destHeight);
995 uint32_t srcOffset = stackOffset(srcHeight);
996 while (bytes >= sizeof(intptr_t)) {
997 masm.loadPtr(Address(sp_, srcOffset), temp);
998 masm.storePtr(temp, Address(sp_, destOffset));
999 destOffset += sizeof(intptr_t);
1000 srcOffset += sizeof(intptr_t);
1001 bytes -= sizeof(intptr_t);
1002 }
1003 if (bytes) {
1004 MOZ_ASSERT(bytes == sizeof(uint32_t));
1005 masm.load32(Address(sp_, srcOffset), temp);
1006 masm.store32(temp, Address(sp_, destOffset));
1007 }
1008 }
1009
1010 // Copy results from the top of the current stack frame to an area of memory,
1011 // and pop the stack accordingly. `dest` is the address of the low byte of
1012 // that memory.
1013 void popStackResultsToMemory(Register dest, uint32_t bytes, Register temp) {
1014 MOZ_ASSERT(bytes <= currentStackHeight());
1015 MOZ_ASSERT(bytes % sizeof(uint32_t) == 0);
1016 uint32_t bytesToPop = bytes;
1017 uint32_t srcOffset = stackOffset(currentStackHeight());
1018 uint32_t destOffset = 0;
1019 while (bytes >= sizeof(intptr_t)) {
1020 masm.loadPtr(Address(sp_, srcOffset), temp);
1021 masm.storePtr(temp, Address(dest, destOffset));
1022 destOffset += sizeof(intptr_t);
1023 srcOffset += sizeof(intptr_t);
1024 bytes -= sizeof(intptr_t);
1025 }
1026 if (bytes) {
1027 MOZ_ASSERT(bytes == sizeof(uint32_t));
1028 masm.load32(Address(sp_, srcOffset), temp);
1029 masm.store32(temp, Address(dest, destOffset));
1030 }
1031 popBytes(bytesToPop);
1032 }
1033
1034 void allocArgArea(size_t argSize) {
1035 if (argSize) {
1036 BaseStackFrameAllocator::allocArgArea(argSize);
1037 maxFramePushed_ = std::max(maxFramePushed_, masm.framePushed());
1038 }
1039 }
1040
1041 private:
1042 void store32BitsToStack(int32_t imm, uint32_t destHeight, Register temp) {
1043 masm.move32(Imm32(imm), temp);
1044 masm.store32(temp, Address(sp_, stackOffset(destHeight)));
1045 }
1046
1047 void store64BitsToStack(int64_t imm, uint32_t destHeight, Register temp) {
1048 #ifdef JS_PUNBOX64
1049 masm.move64(Imm64(imm), Register64(temp));
1050 masm.store64(Register64(temp), Address(sp_, stackOffset(destHeight)));
1051 #else
1052 union {
1053 int64_t i64;
1054 int32_t i32[2];
1055 } bits = {.i64 = imm};
1056 static_assert(sizeof(bits) == 8);
1057 store32BitsToStack(bits.i32[0], destHeight, temp);
1058 store32BitsToStack(bits.i32[1], destHeight - sizeof(int32_t), temp);
1059 #endif
1060 }
1061
1062 public:
1063 void storeImmediatePtrToStack(intptr_t imm, uint32_t destHeight,
1064 Register temp) {
1065 #ifdef JS_PUNBOX64
1066 static_assert(StackSizeOfPtr == 8);
1067 store64BitsToStack(imm, destHeight, temp);
1068 #else
1069 static_assert(StackSizeOfPtr == 4);
1070 store32BitsToStack(int32_t(imm), destHeight, temp);
1071 #endif
1072 }
1073
1074 void storeImmediateI64ToStack(int64_t imm, uint32_t destHeight,
1075 Register temp) {
1076 store64BitsToStack(imm, destHeight, temp);
1077 }
1078
1079 void storeImmediateF32ToStack(float imm, uint32_t destHeight, Register temp) {
1080 union {
1081 int32_t i32;
1082 float f32;
1083 } bits = {.f32 = imm};
1084 static_assert(sizeof(bits) == 4);
1085 // Do not store 4 bytes if StackSizeOfFloat == 8. It's probably OK to do
1086 // so, but it costs little to store something predictable.
1087 if (StackSizeOfFloat == 4) {
1088 store32BitsToStack(bits.i32, destHeight, temp);
1089 } else {
1090 store64BitsToStack(uint32_t(bits.i32), destHeight, temp);
1091 }
1092 }
1093
1094 void storeImmediateF64ToStack(double imm, uint32_t destHeight,
1095 Register temp) {
1096 union {
1097 int64_t i64;
1098 double f64;
1099 } bits = {.f64 = imm};
1100 static_assert(sizeof(bits) == 8);
1101 store64BitsToStack(bits.i64, destHeight, temp);
1102 }
1103
1104 #ifdef ENABLE_WASM_SIMD
1105 void storeImmediateV128ToStack(V128 imm, uint32_t destHeight, Register temp) {
1106 union {
1107 int32_t i32[4];
1108 uint8_t bytes[16];
1109 } bits{};
1110 static_assert(sizeof(bits) == 16);
1111 memcpy(bits.bytes, imm.bytes, 16);
1112 for (unsigned i = 0; i < 4; i++) {
1113 store32BitsToStack(bits.i32[i], destHeight - i * sizeof(int32_t), temp);
1114 }
1115 }
1116 #endif
1117 };
1118
1119 //////////////////////////////////////////////////////////////////////////////
1120 //
1121 // MachineStackTracker, used for stack-slot pointerness tracking.
1122
1123 // An expensive operation in stack-map creation is copying of the
1124 // MachineStackTracker (MST) into the final StackMap. This is done in
1125 // StackMapGenerator::createStackMap. Given that this is basically a
1126 // bit-array copy, it is reasonable to ask whether the two classes could have
1127 // a more similar representation, so that the copy could then be done with
1128 // `memcpy`.
1129 //
1130 // Although in principle feasible, the follow complications exist, and so for
1131 // the moment, this has not been done.
1132 //
1133 // * StackMap is optimised for compact size (storage) since there will be
1134 // many, so it uses a true bitmap. MST is intended to be fast and simple,
1135 // and only one exists at once (per compilation thread). Doing this would
1136 // require MST to use a true bitmap, and hence ..
1137 //
1138 // * .. the copying can't be a straight memcpy, since StackMap has entries for
1139 // words not covered by MST. Hence the copy would need to shift bits in
1140 // each byte left or right (statistically speaking, in 7 cases out of 8) in
1141 // order to ensure no "holes" in the resulting bitmap.
1142 //
1143 // * Furthermore the copying would need to logically invert the direction of
1144 // the stacks. For MST, index zero in the vector corresponds to the highest
1145 // address in the stack. For StackMap, bit index zero corresponds to the
1146 // lowest address in the stack.
1147 //
1148 // * Finally, StackMap is a variable-length structure whose size must be known
1149 // at creation time. The size of an MST by contrast isn't known at creation
1150 // time -- it grows as the baseline compiler pushes stuff on its value
1151 // stack. That's why it has to have vector entry 0 being the highest address.
1152 //
1153 // * Although not directly relevant, StackMaps are also created by the via-Ion
1154 // compilation routes, by translation from the pre-existing "JS-era"
1155 // LSafePoints (CreateStackMapFromLSafepoint). So if we want to mash
1156 // StackMap around to suit baseline better, we also need to ensure it
1157 // doesn't break Ion somehow.
1158
1159 class MachineStackTracker {
1160 // Simulates the machine's stack, with one bool per word. The booleans are
1161 // represented as `uint8_t`s so as to guarantee the element size is one
1162 // byte. Index zero in this vector corresponds to the highest address in
1163 // the machine's stack. The last entry corresponds to what SP currently
1164 // points at. This all assumes a grow-down stack.
1165 //
1166 // numPtrs_ contains the number of "true" values in vec_, and is therefore
1167 // redundant. But it serves as a constant-time way to detect the common
1168 // case where vec_ holds no "true" values.
1169 size_t numPtrs_;
1170 Vector<uint8_t, 64, SystemAllocPolicy> vec_;
1171
1172 public:
1173 MachineStackTracker() : numPtrs_(0) {}
1174
1175 ~MachineStackTracker() {
1176 #ifdef DEBUG
1177 size_t n = 0;
1178 for (uint8_t b : vec_) {
1179 n += (b ? 1 : 0);
1180 }
1181 MOZ_ASSERT(n == numPtrs_);
1182 #endif
1183 }
1184
1185 // Clone this MachineStackTracker, writing the result at |dst|.
1186 [[nodiscard]] bool cloneTo(MachineStackTracker* dst);
1187
1188 // Notionally push |n| non-pointers on the stack.
1189 [[nodiscard]] bool pushNonGCPointers(size_t n) {
1190 return vec_.appendN(uint8_t(false), n);
1191 }
1192
1193 // Mark the stack slot |offsetFromSP| up from the bottom as holding a
1194 // pointer.
1195 void setGCPointer(size_t offsetFromSP) {
1196 // offsetFromSP == 0 denotes the most recently pushed item, == 1 the
1197 // second most recently pushed item, etc.
1198 MOZ_ASSERT(offsetFromSP < vec_.length());
1199
1200 size_t offsetFromTop = vec_.length() - 1 - offsetFromSP;
1201 numPtrs_ = numPtrs_ + 1 - (vec_[offsetFromTop] ? 1 : 0);
1202 vec_[offsetFromTop] = uint8_t(true);
1203 }
1204
1205 // Query the pointerness of the slot |offsetFromSP| up from the bottom.
1206 bool isGCPointer(size_t offsetFromSP) const {
1207 MOZ_ASSERT(offsetFromSP < vec_.length());
1208
1209 size_t offsetFromTop = vec_.length() - 1 - offsetFromSP;
1210 return bool(vec_[offsetFromTop]);
1211 }
1212
1213 // Return the number of words tracked by this MachineStackTracker.
1214 size_t length() const { return vec_.length(); }
1215
1216 // Return the number of pointer-typed words tracked by this
1217 // MachineStackTracker.
1218 size_t numPtrs() const {
1219 MOZ_ASSERT(numPtrs_ <= length());
1220 return numPtrs_;
1221 }
1222
1223 // Discard all contents, but (per mozilla::Vector::clear semantics) don't
1224 // free or reallocate any dynamic storage associated with |vec_|.
1225 void clear() {
1226 vec_.clear();
1227 numPtrs_ = 0;
1228 }
1229
1230 // An iterator that produces indices of reftyped slots, starting at the
1231 // logical bottom of the (grow-down) stack. Indices have the same meaning
1232 // as the arguments to `isGCPointer`. That is, if this iterator produces a
1233 // value `i`, then it means that `isGCPointer(i) == true`; if the value `i`
1234 // is never produced then `isGCPointer(i) == false`. The values are
1235 // produced in ascending order.
1236 //
1237 // Because most slots are non-reftyped, some effort has been put into
1238 // skipping over large groups of non-reftyped slots quickly.
1239 class Iter {
1240 // Both `bufU8_` and `bufU32_` are made to point to `vec_`s array of
1241 // `uint8_t`s, so we can scan (backwards) through it either in bytes or
1242 // 32-bit words. Recall that the last element in `vec_` pertains to the
1243 // lowest-addressed word in the machine's grow-down stack, and we want to
1244 // iterate logically "up" this stack, so we need to iterate backwards
1245 // through `vec_`.
1246 //
1247 // This dual-pointer scheme assumes that the `vec_`s content array is at
1248 // least 32-bit aligned.
1249 const uint8_t* bufU8_;
1250 const uint32_t* bufU32_;
1251 // The number of elements in `bufU8_`.
1252 const size_t nElems_;
1253 // The index in `bufU8_` where the next search should start.
1254 size_t next_;
1255
1256 public:
1257 explicit Iter(const MachineStackTracker& mst)
1258 : bufU8_((uint8_t*)mst.vec_.begin()),
1259 bufU32_((uint32_t*)mst.vec_.begin()),
1260 nElems_(mst.vec_.length()),
1261 next_(mst.vec_.length() - 1) {
1262 MOZ_ASSERT(uintptr_t(bufU8_) == uintptr_t(bufU32_));
1263 // Check minimum alignment constraint on the array.
1264 MOZ_ASSERT(0 == (uintptr_t(bufU8_) & 3));
1265 }
1266
1267 ~Iter() { MOZ_ASSERT(uintptr_t(bufU8_) == uintptr_t(bufU32_)); }
1268
1269 // It is important, for termination of the search loop in `next()`, that
1270 // this has the value obtained by subtracting 1 from size_t(0).
1271 static constexpr size_t FINISHED = ~size_t(0);
1272 static_assert(FINISHED == size_t(0) - 1);
1273
1274 // Returns the next index `i` for which `isGCPointer(i) == true`.
1275 size_t get() {
1276 while (next_ != FINISHED) {
1277 if (bufU8_[next_]) {
1278 next_--;
1279 return nElems_ - 1 - (next_ + 1);
1280 }
1281 // Invariant: next_ != FINISHED (so it's still a valid index)
1282 // and: bufU8_[next_] == 0
1283 // (so we need to move backwards by at least 1)
1284 //
1285 // BEGIN optimization -- this could be removed without affecting
1286 // correctness.
1287 if ((next_ & 7) == 0) {
1288 // We're at the "bottom" of the current dual-4-element word. Check
1289 // if we can jump backwards by 8. This saves a conditional branch
1290 // and a few cycles by ORing two adjacent 32-bit words together,
1291 // whilst not requiring 64-bit alignment of `bufU32_`.
1292 while (next_ >= 8 &&
1293 (bufU32_[(next_ - 4) >> 2] | bufU32_[(next_ - 8) >> 2]) == 0) {
1294 next_ -= 8;
1295 }
1296 }
1297 // END optimization
1298 next_--;
1299 }
1300 return FINISHED;
1301 }
1302 };
1303 };
1304
1305 //////////////////////////////////////////////////////////////////////////////
1306 //
1307 // StackMapGenerator, which carries all state needed to create stackmaps.
1308
1309 enum class HasDebugFrameWithLiveRefs { No, Maybe };
1310
1311 struct StackMapGenerator {
1312 private:
1313 // --- These are constant for the life of the function's compilation ---
1314
1315 // For generating stackmaps, we'll need to know the offsets of registers
1316 // as saved by the trap exit stub.
1317 const RegisterOffsets& trapExitLayout_;
1318 const size_t trapExitLayoutNumWords_;
1319
1320 // Completed stackmaps are added here
1321 StackMaps* stackMaps_;
1322
1323 // So as to be able to get current offset when creating stackmaps
1324 const MacroAssembler& masm_;
1325
1326 public:
1327 // --- These are constant once we've completed beginFunction() ---
1328
1329 // The number of bytes of arguments passed to this function in memory.
1330 size_t numStackArgBytes;
1331
1332 MachineStackTracker machineStackTracker; // tracks machine stack pointerness
1333
1334 // This holds masm.framePushed at entry to the function's body. It is a
1335 // Maybe because createStackMap needs to know whether or not we're still
1336 // in the prologue. It makes a Nothing-to-Some transition just once per
1337 // function.
1338 mozilla::Maybe<uint32_t> framePushedAtEntryToBody;
1339
1340 // --- These can change at any point ---
1341
1342 // This holds masm.framePushed at it would be be for a function call
1343 // instruction, but excluding the stack area used to pass arguments in
1344 // memory. That is, for an upcoming function call, this will hold
1345 //
1346 // masm.framePushed() at the call instruction -
1347 // StackArgAreaSizeAligned(argumentTypes)
1348 //
1349 // This value denotes the lowest-addressed stack word covered by the current
1350 // function's stackmap. Words below this point form the highest-addressed
1351 // area of the callee's stackmap. Note that all alignment padding above the
1352 // arguments-in-memory themselves belongs to the callee's stackmap, as return
1353 // calls will replace the function arguments with a new set of arguments which
1354 // may have different alignment.
1355 //
1356 // When not inside a function call setup/teardown sequence, it is Nothing.
1357 // It can make Nothing-to/from-Some transitions arbitrarily as we progress
1358 // through the function body.
1359 mozilla::Maybe<uint32_t> framePushedExcludingOutboundCallArgs;
1360
1361 // The number of memory-resident, ref-typed entries on the containing
1362 // BaseCompiler::stk_.
1363 size_t memRefsOnStk;
1364
1365 // This is a copy of machineStackTracker that is used only within individual
1366 // calls to createStackMap. It is here only to avoid possible heap allocation
1367 // costs resulting from making it local to createStackMap().
1368 MachineStackTracker augmentedMst;
1369
1370 StackMapGenerator(StackMaps* stackMaps, const RegisterOffsets& trapExitLayout,
1371 const size_t trapExitLayoutNumWords,
1372 const MacroAssembler& masm)
1373 : trapExitLayout_(trapExitLayout),
1374 trapExitLayoutNumWords_(trapExitLayoutNumWords),
1375 stackMaps_(stackMaps),
1376 masm_(masm),
1377 numStackArgBytes(0),
1378 memRefsOnStk(0) {}
1379
1380 // At the beginning of a function, we may have live roots in registers (as
1381 // arguments) at the point where we perform a stack overflow check. This
1382 // method generates the "extra" stackmap entries to describe that, in the
1383 // case that the check fails and we wind up calling into the wasm exit
1384 // stub, as generated by GenerateTrapExit().
1385 //
1386 // The resulting map must correspond precisely with the stack layout
1387 // created for the integer registers as saved by (code generated by)
1388 // GenerateTrapExit(). To do that we use trapExitLayout_ and
1389 // trapExitLayoutNumWords_, which together comprise a description of the
1390 // layout and are created by GenerateTrapExitRegisterOffsets().
1391 [[nodiscard]] bool generateStackmapEntriesForTrapExit(
1392 const ArgTypeVector& args, ExitStubMapVector* extras);
1393
1394 // Creates a stackmap associated with the instruction denoted by
1395 // |assemblerOffset|, incorporating pointers from the current operand
1396 // stack |stk|, incorporating possible extra pointers in |extra| at the
1397 // lower addressed end, and possibly with the associated frame having a
1398 // DebugFrame that must be traced, as indicated by |debugFrameWithLiveRefs|.
1399 [[nodiscard]] bool createStackMap(
1400 const char* who, const ExitStubMapVector& extras,
1401 uint32_t assemblerOffset,
1402 HasDebugFrameWithLiveRefs debugFrameWithLiveRefs, const StkVector& stk);
1403 };
1404
1405 } // namespace wasm
1406 } // namespace js
1407
1408 #endif // wasm_wasm_baseline_frame_h