Debian Codegraph @

js/src/wasm/WasmBCFrame.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 *
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 #include "wasm/WasmBCFrame.h"
20
21 #include "wasm/WasmBaselineCompile.h" // For BaseLocalIter
22 #include "wasm/WasmBCClass.h"
23
24 #include "jit/MacroAssembler-inl.h"
25 #include "wasm/WasmBCClass-inl.h"
26 #include "wasm/WasmBCCodegen-inl.h"
27 #include "wasm/WasmBCRegDefs-inl.h"
28 #include "wasm/WasmBCRegMgmt-inl.h"
29 #include "wasm/WasmBCStkMgmt-inl.h"
30
31 namespace js {
32 namespace wasm {
33
34 using mozilla::Maybe;
35 using mozilla::Some;
36
37 //////////////////////////////////////////////////////////////////////////////
38 //
39 // BaseLocalIter methods.
40
41 BaseLocalIter::BaseLocalIter(const ValTypeVector& locals,
42 const ArgTypeVector& args, bool debugEnabled)
43 : locals_(locals),
44 args_(args),
45 argsIter_(args_),
46 index_(0),
47 frameSize_(0),
48 nextFrameSize_(debugEnabled ? DebugFrame::offsetOfFrame() : 0),
49 frameOffset_(INT32_MAX),
50 stackResultPointerOffset_(INT32_MAX),
51 mirType_(MIRType::Undefined),
52 done_(false) {
53 MOZ_ASSERT(args.lengthWithoutStackResults() <= locals.length());
54 settle();
55 }
56
57 int32_t BaseLocalIter::pushLocal(size_t nbytes) {
58 MOZ_ASSERT(nbytes % 4 == 0 && nbytes <= 16);
59 nextFrameSize_ = AlignBytes(frameSize_, nbytes) + nbytes;
60 return nextFrameSize_; // Locals grow down so capture base address.
61 }
62
63 void BaseLocalIter::settle() {
64 MOZ_ASSERT(!done_);
65 frameSize_ = nextFrameSize_;
66
67 if (!argsIter_.done()) {
68 mirType_ = argsIter_.mirType();
69 MIRType concreteType = mirType_;
70 switch (mirType_) {
71 case MIRType::StackResults:
72 // The pointer to stack results is handled like any other argument:
73 // either addressed in place if it is passed on the stack, or we spill
74 // it in the frame if it's in a register.
75 MOZ_ASSERT(args_.isSyntheticStackResultPointerArg(index_));
76 concreteType = MIRType::Pointer;
77 [[fallthrough]];
78 case MIRType::Int32:
79 case MIRType::Int64:
80 case MIRType::Double:
81 case MIRType::Float32:
82 case MIRType::WasmAnyRef:
83 #ifdef ENABLE_WASM_SIMD
84 case MIRType::Simd128:
85 #endif
86 if (argsIter_->argInRegister()) {
87 frameOffset_ = pushLocal(MIRTypeToSize(concreteType));
88 } else {
89 frameOffset_ = -(argsIter_->offsetFromArgBase() + sizeof(Frame));
90 }
91 break;
92 default:
93 MOZ_CRASH("Argument type");
94 }
95 if (mirType_ == MIRType::StackResults) {
96 stackResultPointerOffset_ = frameOffset();
97 // Advance past the synthetic stack result pointer argument and fall
98 // through to the next case.
99 argsIter_++;
100 frameSize_ = nextFrameSize_;
101 MOZ_ASSERT(argsIter_.done());
102 } else {
103 return;
104 }
105 }
106
107 if (index_ < locals_.length()) {
108 switch (locals_[index_].kind()) {
109 case ValType::I32:
110 case ValType::I64:
111 case ValType::F32:
112 case ValType::F64:
113 #ifdef ENABLE_WASM_SIMD
114 case ValType::V128:
115 #endif
116 case ValType::Ref:
117 mirType_ = locals_[index_].toMIRType();
118 frameOffset_ = pushLocal(MIRTypeToSize(mirType_));
119 break;
120 default:
121 MOZ_CRASH("Compiler bug: Unexpected local type");
122 }
123 return;
124 }
125
126 done_ = true;
127 }
128
129 void BaseLocalIter::operator++(int) {
130 MOZ_ASSERT(!done_);
131 index_++;
132 if (!argsIter_.done()) {
133 argsIter_++;
134 }
135 settle();
136 }
137
138 //////////////////////////////////////////////////////////////////////////////
139 //
140 // Stack map methods.
141
142 bool BaseCompiler::createStackMap(const char* who) {
143 const ExitStubMapVector noExtras;
144 return stackMapGenerator_.createStackMap(who, noExtras, masm.currentOffset(),
145 HasDebugFrameWithLiveRefs::No, stk_);
146 }
147
148 bool BaseCompiler::createStackMap(const char* who, CodeOffset assemblerOffset) {
149 const ExitStubMapVector noExtras;
150 return stackMapGenerator_.createStackMap(who, noExtras,
151 assemblerOffset.offset(),
152 HasDebugFrameWithLiveRefs::No, stk_);
153 }
154
155 bool BaseCompiler::createStackMap(
156 const char* who, HasDebugFrameWithLiveRefs debugFrameWithLiveRefs) {
157 const ExitStubMapVector noExtras;
158 return stackMapGenerator_.createStackMap(who, noExtras, masm.currentOffset(),
159 debugFrameWithLiveRefs, stk_);
160 }
161
162 bool BaseCompiler::createStackMap(
163 const char* who, const ExitStubMapVector& extras, uint32_t assemblerOffset,
164 HasDebugFrameWithLiveRefs debugFrameWithLiveRefs) {
165 return stackMapGenerator_.createStackMap(who, extras, assemblerOffset,
166 debugFrameWithLiveRefs, stk_);
167 }
168
169 bool MachineStackTracker::cloneTo(MachineStackTracker* dst) {
170 MOZ_ASSERT(dst->vec_.empty());
171 if (!dst->vec_.appendAll(vec_)) {
172 return false;
173 }
174 dst->numPtrs_ = numPtrs_;
175 return true;
176 }
177
178 bool StackMapGenerator::generateStackmapEntriesForTrapExit(
179 const ArgTypeVector& args, ExitStubMapVector* extras) {
180 return GenerateStackmapEntriesForTrapExit(args, trapExitLayout_,
181 trapExitLayoutNumWords_, extras);
182 }
183
184 bool StackMapGenerator::createStackMap(
185 const char* who, const ExitStubMapVector& extras, uint32_t assemblerOffset,
186 HasDebugFrameWithLiveRefs debugFrameWithLiveRefs, const StkVector& stk) {
187 size_t countedPointers = machineStackTracker.numPtrs() + memRefsOnStk;
188 #ifndef DEBUG
189 // An important optimization. If there are obviously no pointers, as
190 // we expect in the majority of cases, exit quickly.
191 if (countedPointers == 0 &&
192 debugFrameWithLiveRefs == HasDebugFrameWithLiveRefs::No) {
193 // We can skip creating the map if there are no |true| elements in
194 // |extras|.
195 bool extrasHasRef = false;
196 for (bool b : extras) {
197 if (b) {
198 extrasHasRef = true;
199 break;
200 }
201 }
202 if (!extrasHasRef) {
203 return true;
204 }
205 }
206 #else
207 // In the debug case, create the stackmap regardless, and cross-check
208 // the pointer-counting below. We expect the final map to have
209 // |countedPointers| in total. This doesn't include those in the
210 // DebugFrame, but they do not appear in the map's bitmap. Note that
211 // |countedPointers| is debug-only from this point onwards.
212 for (bool b : extras) {
213 countedPointers += (b ? 1 : 0);
214 }
215 #endif
216
217 // Start with the frame-setup map, and add operand-stack information to
218 // that. augmentedMst holds live data only within individual calls to
219 // createStackMap.
220 augmentedMst.clear();
221 if (!machineStackTracker.cloneTo(&augmentedMst)) {
222 return false;
223 }
224
225 // At this point, augmentedMst only contains entries covering the
226 // incoming argument area (if any) and for the area allocated by this
227 // function's prologue. We now need to calculate how far the machine's
228 // stack pointer is below where it was at the start of the body. But we
229 // must take care not to include any words pushed as arguments to an
230 // upcoming function call, since those words belong to the stackmap of
231 // the callee, not to the stackmap of this function. Any alignment padding
232 // for the args also belongs to the callee.
233 //
234 // The only padding belonging to the stackmap of this function is that
235 // required to align the upcoming frame. This is accounted for where
236 // framePushedExcludingOutboundCallArgs is set, in startCallArgs(), and is
237 // comprised of just one component:
238 //
239 // * call->frameAlignAdjustment
240 Maybe<uint32_t> framePushedExcludingArgs;
241 if (framePushedAtEntryToBody.isNothing()) {
242 // Still in the prologue. framePushedExcludingArgs remains Nothing.
243 MOZ_ASSERT(framePushedExcludingOutboundCallArgs.isNothing());
244 } else {
245 // In the body.
246 MOZ_ASSERT(masm_.framePushed() >= framePushedAtEntryToBody.value());
247 if (framePushedExcludingOutboundCallArgs.isSome()) {
248 // In the body, and we've potentially pushed some args onto the stack.
249 // We must ignore them when sizing the stackmap.
250 MOZ_ASSERT(masm_.framePushed() >=
251 framePushedExcludingOutboundCallArgs.value());
252 MOZ_ASSERT(framePushedExcludingOutboundCallArgs.value() >=
253 framePushedAtEntryToBody.value());
254 framePushedExcludingArgs =
255 Some(framePushedExcludingOutboundCallArgs.value());
256 } else {
257 // In the body, but not with call args on the stack. The stackmap
258 // must be sized so as to extend all the way "down" to
259 // masm_.framePushed().
260 framePushedExcludingArgs = Some(masm_.framePushed());
261 }
262 }
263
264 if (framePushedExcludingArgs.isSome()) {
265 uint32_t bodyPushedBytes =
266 framePushedExcludingArgs.value() - framePushedAtEntryToBody.value();
267 MOZ_ASSERT(0 == bodyPushedBytes % sizeof(void*));
268 if (!augmentedMst.pushNonGCPointers(bodyPushedBytes / sizeof(void*))) {
269 return false;
270 }
271 }
272
273 // Scan the operand stack, marking pointers in the just-added new
274 // section.
275 MOZ_ASSERT_IF(framePushedAtEntryToBody.isNothing(), stk.empty());
276 MOZ_ASSERT_IF(framePushedExcludingArgs.isNothing(), stk.empty());
277
278 for (const Stk& v : stk) {
279 #ifndef DEBUG
280 // We don't track roots in registers, per rationale below, so if this
281 // doesn't hold, something is seriously wrong, and we're likely to get a
282 // GC-related crash.
283 MOZ_RELEASE_ASSERT(v.kind() != Stk::RegisterRef);
284 if (v.kind() != Stk::MemRef) {
285 continue;
286 }
287 #else
288 // Take the opportunity to check everything we reasonably can about
289 // operand stack elements.
290 switch (v.kind()) {
291 case Stk::MemI32:
292 case Stk::MemI64:
293 case Stk::MemF32:
294 case Stk::MemF64:
295 case Stk::ConstI32:
296 case Stk::ConstI64:
297 case Stk::ConstF32:
298 case Stk::ConstF64:
299 # ifdef ENABLE_WASM_SIMD
300 case Stk::MemV128:
301 case Stk::ConstV128:
302 # endif
303 // All of these have uninteresting type.
304 continue;
305 case Stk::LocalI32:
306 case Stk::LocalI64:
307 case Stk::LocalF32:
308 case Stk::LocalF64:
309 # ifdef ENABLE_WASM_SIMD
310 case Stk::LocalV128:
311 # endif
312 // These also have uninteresting type. Check that they live in the
313 // section of stack set up by beginFunction(). The unguarded use of
314 // |value()| here is safe due to the assertion above this loop.
315 MOZ_ASSERT(v.offs() <= framePushedAtEntryToBody.value());
316 continue;
317 case Stk::RegisterI32:
318 case Stk::RegisterI64:
319 case Stk::RegisterF32:
320 case Stk::RegisterF64:
321 # ifdef ENABLE_WASM_SIMD
322 case Stk::RegisterV128:
323 # endif
324 // These also have uninteresting type, but more to the point: all
325 // registers holding live values should have been flushed to the
326 // machine stack immediately prior to the instruction to which this
327 // stackmap pertains. So these can't happen.
328 MOZ_CRASH("createStackMap: operand stack has Register-non-Ref");
329 case Stk::MemRef:
330 // This is the only case we care about. We'll handle it after the
331 // switch.
332 break;
333 case Stk::LocalRef:
334 // We need the stackmap to mention this pointer, but it should
335 // already be in the machineStackTracker section created by
336 // beginFunction().
337 MOZ_ASSERT(v.offs() <= framePushedAtEntryToBody.value());
338 continue;
339 case Stk::ConstRef:
340 // This can currently only be a null pointer.
341 MOZ_ASSERT(v.refval() == 0);
342 continue;
343 case Stk::RegisterRef:
344 // This can't happen, per rationale above.
345 MOZ_CRASH("createStackMap: operand stack contains RegisterRef");
346 default:
347 MOZ_CRASH("createStackMap: unknown operand stack element");
348 }
349 #endif
350 // v.offs() holds masm.framePushed() at the point immediately after it
351 // was pushed on the stack. Since it's still on the stack,
352 // masm.framePushed() can't be less.
353 MOZ_ASSERT(v.offs() <= framePushedExcludingArgs.value());
354 uint32_t offsFromMapLowest = framePushedExcludingArgs.value() - v.offs();
355 MOZ_ASSERT(0 == offsFromMapLowest % sizeof(void*));
356 augmentedMst.setGCPointer(offsFromMapLowest / sizeof(void*));
357 }
358
359 MOZ_ASSERT(numStackArgBytes % sizeof(void*) == 0);
360 const size_t numStackArgWords = numStackArgBytes / sizeof(void*);
361 const size_t numStackArgPaddingBytes =
362 AlignStackArgAreaSize(numStackArgBytes) - numStackArgBytes;
363 const size_t numStackArgPaddingWords =
364 numStackArgPaddingBytes / sizeof(void*);
365
366 // Create the final StackMap. The initial map is zeroed out, so there's
367 // no need to write zero bits in it.
368 const uint32_t extraWords = extras.length();
369 const uint32_t augmentedMstWords = augmentedMst.length();
370 const uint32_t numMappedWords =
371 numStackArgPaddingWords + extraWords + augmentedMstWords;
372 StackMap* stackMap = StackMap::create(numMappedWords);
373 if (!stackMap) {
374 return false;
375 }
376
377 {
378 // First the exit stub extra words, if any.
379 uint32_t i = 0;
380 for (bool b : extras) {
381 if (b) {
382 stackMap->set(i, StackMap::Kind::AnyRef);
383 }
384 i++;
385 }
386 }
387 {
388 // Followed by the "main" part of the map.
389 //
390 // This is really just a bit-array copy, so it is reasonable to ask
391 // whether the representation of MachineStackTracker could be made more
392 // similar to that of StackMap, so that the copy could be done with
393 // `memcpy`. Unfortunately it's not so simple; see comment on `class
394 // MachineStackTracker` for details.
395 MachineStackTracker::Iter iter(augmentedMst);
396 while (true) {
397 size_t i = iter.get();
398 if (i == MachineStackTracker::Iter::FINISHED) {
399 break;
400 }
401 stackMap->set(extraWords + i, StackMap::Kind::AnyRef);
402 }
403 }
404
405 stackMap->setExitStubWords(extraWords);
406
407 // Record in the map, how far down from the highest address the Frame* is.
408 // Take the opportunity to check that we haven't marked any part of the
409 // Frame itself as a pointer.
410 stackMap->setFrameOffsetFromTop(numStackArgPaddingWords + numStackArgWords +
411 sizeof(Frame) / sizeof(void*));
412 #ifdef DEBUG
413 for (uint32_t i = 0; i < sizeof(Frame) / sizeof(void*); i++) {
414 MOZ_ASSERT(stackMap->get(stackMap->header.numMappedWords -
415 stackMap->header.frameOffsetFromTop + i) ==
416 StackMap::Kind::POD);
417 }
418 #endif
419
420 // Note the presence of a DebugFrame with live pointers, if any.
421 if (debugFrameWithLiveRefs != HasDebugFrameWithLiveRefs::No) {
422 stackMap->setHasDebugFrameWithLiveRefs();
423 }
424
425 // Add the completed map to the running collection thereof.
426 if (!stackMaps_->add(assemblerOffset, stackMap)) {
427 stackMap->destroy();
428 return false;
429 }
430
431 #ifdef DEBUG
432 {
433 // Crosscheck the map pointer counting.
434 uint32_t nw = stackMap->header.numMappedWords;
435 uint32_t np = 0;
436 for (uint32_t i = 0; i < nw; i++) {
437 if (stackMap->get(i) == StackMap::Kind::AnyRef) {
438 np += 1;
439 }
440 }
441 MOZ_ASSERT(size_t(np) == countedPointers);
442 }
443 #endif
444
445 return true;
446 }
447
448 //////////////////////////////////////////////////////////////////////////////
449 //
450 // Stack frame methods.
451
452 void BaseStackFrame::zeroLocals(BaseRegAlloc* ra) {
453 MOZ_ASSERT(varLow_ != UINT32_MAX);
454
455 if (varLow_ == varHigh_) {
456 return;
457 }
458
459 static const uint32_t wordSize = sizeof(void*);
460
461 // The adjustments to 'low' by the size of the item being stored compensates
462 // for the fact that locals offsets are the offsets from Frame to the bytes
463 // directly "above" the locals in the locals area. See comment at Local.
464
465 // On 64-bit systems we may have 32-bit alignment for the local area as it
466 // may be preceded by parameters and prologue/debug data.
467
468 uint32_t low = varLow_;
469 if (low % wordSize) {
470 masm.store32(Imm32(0), Address(sp_, localOffset(low + 4)));
471 low += 4;
472 }
473 MOZ_ASSERT(low % wordSize == 0);
474
475 const uint32_t high = AlignBytes(varHigh_, wordSize);
476
477 // An UNROLL_LIMIT of 16 is chosen so that we only need an 8-bit signed
478 // immediate to represent the offset in the store instructions in the loop
479 // on x64.
480
481 const uint32_t UNROLL_LIMIT = 16;
482 const uint32_t initWords = (high - low) / wordSize;
483 const uint32_t tailWords = initWords % UNROLL_LIMIT;
484 const uint32_t loopHigh = high - (tailWords * wordSize);
485
486 // With only one word to initialize, just store an immediate zero.
487
488 if (initWords == 1) {
489 masm.storePtr(ImmWord(0), Address(sp_, localOffset(low + wordSize)));
490 return;
491 }
492
493 // For other cases, it's best to have a zero in a register.
494 //
495 // One can do more here with SIMD registers (store 16 bytes at a time) or
496 // with instructions like STRD on ARM (store 8 bytes at a time), but that's
497 // for another day.
498
499 RegI32 zero = ra->needI32();
500 masm.mov(ImmWord(0), zero);
501
502 // For the general case we want to have a loop body of UNROLL_LIMIT stores
503 // and then a tail of less than UNROLL_LIMIT stores. When initWords is less
504 // than 2*UNROLL_LIMIT the loop trip count is at most 1 and there is no
505 // benefit to having the pointer calculations and the compare-and-branch.
506 // So we completely unroll when we have initWords < 2 * UNROLL_LIMIT. (In
507 // this case we'll end up using 32-bit offsets on x64 for up to half of the
508 // stores, though.)
509
510 // Fully-unrolled case.
511
512 if (initWords < 2 * UNROLL_LIMIT) {
513 for (uint32_t i = low; i < high; i += wordSize) {
514 masm.storePtr(zero, Address(sp_, localOffset(i + wordSize)));
515 }
516 ra->freeI32(zero);
517 return;
518 }
519
520 // Unrolled loop with a tail. Stores will use negative offsets. That's OK
521 // for x86 and ARM, at least.
522
523 // Compute pointer to the highest-addressed slot on the frame.
524 RegI32 p = ra->needI32();
525 masm.computeEffectiveAddress(Address(sp_, localOffset(low + wordSize)), p);
526
527 // Compute pointer to the lowest-addressed slot on the frame that will be
528 // initialized by the loop body.
529 RegI32 lim = ra->needI32();
530 masm.computeEffectiveAddress(Address(sp_, localOffset(loopHigh + wordSize)),
531 lim);
532
533 // The loop body. Eventually we'll have p == lim and exit the loop.
534 Label again;
535 masm.bind(&again);
536 for (uint32_t i = 0; i < UNROLL_LIMIT; ++i) {
537 masm.storePtr(zero, Address(p, -(wordSize * i)));
538 }
539 masm.subPtr(Imm32(UNROLL_LIMIT * wordSize), p);
540 masm.branchPtr(Assembler::Below, lim, p, &again);
541
542 // The tail.
543 for (uint32_t i = 0; i < tailWords; ++i) {
544 masm.storePtr(zero, Address(p, -(wordSize * i)));
545 }
546
547 ra->freeI32(p);
548 ra->freeI32(lim);
549 ra->freeI32(zero);
550 }
551
552 } // namespace wasm
553 } // namespace js