Debian Codegraph @

js/src/jit/MacroAssembler.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/MacroAssembler-inl.h"
8
9 #include "mozilla/FloatingPoint.h"
10 #include "mozilla/Latin1.h"
11 #include "mozilla/MathAlgorithms.h"
12 #include "mozilla/XorShift128PlusRNG.h"
13
14 #include <algorithm>
15 #include <limits>
16 #include <utility>
17
18 #include "jit/AtomicOp.h"
19 #include "jit/AtomicOperations.h"
20 #include "jit/Bailouts.h"
21 #include "jit/BaselineFrame.h"
22 #include "jit/BaselineJIT.h"
23 #include "jit/JitFrames.h"
24 #include "jit/JitOptions.h"
25 #include "jit/JitRuntime.h"
26 #include "jit/JitScript.h"
27 #include "jit/MoveEmitter.h"
28 #include "jit/ReciprocalMulConstants.h"
29 #include "jit/SharedICHelpers.h"
30 #include "jit/SharedICRegisters.h"
31 #include "jit/Simulator.h"
32 #include "jit/VMFunctions.h"
33 #include "js/Conversions.h"
34 #include "js/friend/DOMProxy.h" // JS::ExpandoAndGeneration
35 #include "js/GCAPI.h" // JS::AutoCheckCannotGC
36 #include "js/ScalarType.h" // js::Scalar::Type
37 #include "util/Unicode.h"
38 #include "vm/ArgumentsObject.h"
39 #include "vm/ArrayBufferViewObject.h"
40 #include "vm/BoundFunctionObject.h"
41 #include "vm/DateObject.h"
42 #include "vm/DateTime.h"
43 #include "vm/Float16.h"
44 #include "vm/FunctionFlags.h" // js::FunctionFlags
45 #include "vm/Iteration.h"
46 #include "vm/JSContext.h"
47 #include "vm/JSFunction.h"
48 #include "vm/StringType.h"
49 #include "vm/TypedArrayObject.h"
50 #include "wasm/WasmBuiltins.h"
51 #include "wasm/WasmCodegenConstants.h"
52 #include "wasm/WasmCodegenTypes.h"
53 #include "wasm/WasmInstanceData.h"
54 #include "wasm/WasmMemory.h"
55 #include "wasm/WasmTypeDef.h"
56 #include "wasm/WasmValidate.h"
57
58 #include "jit/TemplateObject-inl.h"
59 #include "vm/BytecodeUtil-inl.h"
60 #include "vm/Interpreter-inl.h"
61 #include "vm/JSObject-inl.h"
62 #include "wasm/WasmGcObject-inl.h"
63
64 using namespace js;
65 using namespace js::jit;
66
67 using JS::GenericNaN;
68
69 using mozilla::CheckedInt;
70
71 TrampolinePtr MacroAssembler::preBarrierTrampoline(MIRType type) {
72 const JitRuntime* rt = runtime()->jitRuntime();
73 return rt->preBarrier(type);
74 }
75
76 template <typename T>
77 void MacroAssembler::storeToTypedFloatArray(Scalar::Type arrayType,
78 FloatRegister value, const T& dest,
79 Register temp,
80 LiveRegisterSet volatileLiveRegs) {
81 switch (arrayType) {
82 case Scalar::Float16:
83 storeFloat16(value, dest, temp, volatileLiveRegs);
84 break;
85 case Scalar::Float32: {
86 if (value.isDouble()) {
87 ScratchFloat32Scope fpscratch(*this);
88 convertDoubleToFloat32(value, fpscratch);
89 storeFloat32(fpscratch, dest);
90 } else {
91 MOZ_ASSERT(value.isSingle());
92 storeFloat32(value, dest);
93 }
94 break;
95 }
96 case Scalar::Float64:
97 MOZ_ASSERT(value.isDouble());
98 storeDouble(value, dest);
99 break;
100 default:
101 MOZ_CRASH("Invalid typed array type");
102 }
103 }
104
105 template void MacroAssembler::storeToTypedFloatArray(
106 Scalar::Type arrayType, FloatRegister value, const BaseIndex& dest,
107 Register temp, LiveRegisterSet volatileLiveRegs);
108 template void MacroAssembler::storeToTypedFloatArray(
109 Scalar::Type arrayType, FloatRegister value, const Address& dest,
110 Register temp, LiveRegisterSet volatileLiveRegs);
111
112 void MacroAssembler::boxUint32(Register source, ValueOperand dest,
113 Uint32Mode mode, Label* fail) {
114 switch (mode) {
115 // Fail if the value does not fit in an int32.
116 case Uint32Mode::FailOnDouble: {
117 branchTest32(Assembler::Signed, source, source, fail);
118 tagValue(JSVAL_TYPE_INT32, source, dest);
119 break;
120 }
121 case Uint32Mode::ForceDouble: {
122 // Always convert the value to double.
123 ScratchDoubleScope fpscratch(*this);
124 convertUInt32ToDouble(source, fpscratch);
125 boxDouble(fpscratch, dest, fpscratch);
126 break;
127 }
128 }
129 }
130
131 template <typename T>
132 void MacroAssembler::loadFromTypedArray(Scalar::Type arrayType, const T& src,
133 AnyRegister dest, Register temp1,
134 Register temp2, Label* fail,
135 LiveRegisterSet volatileLiveRegs) {
136 switch (arrayType) {
137 case Scalar::Int8:
138 load8SignExtend(src, dest.gpr());
139 break;
140 case Scalar::Uint8:
141 case Scalar::Uint8Clamped:
142 load8ZeroExtend(src, dest.gpr());
143 break;
144 case Scalar::Int16:
145 load16SignExtend(src, dest.gpr());
146 break;
147 case Scalar::Uint16:
148 load16ZeroExtend(src, dest.gpr());
149 break;
150 case Scalar::Int32:
151 load32(src, dest.gpr());
152 break;
153 case Scalar::Uint32:
154 if (dest.isFloat()) {
155 load32(src, temp1);
156 convertUInt32ToDouble(temp1, dest.fpu());
157 } else {
158 load32(src, dest.gpr());
159
160 // Bail out if the value doesn't fit into a signed int32 value. This
161 // is what allows MLoadUnboxedScalar to have a type() of
162 // MIRType::Int32 for UInt32 array loads.
163 branchTest32(Assembler::Signed, dest.gpr(), dest.gpr(), fail);
164 }
165 break;
166 case Scalar::Float16:
167 loadFloat16(src, dest.fpu(), temp1, temp2, volatileLiveRegs);
168 canonicalizeFloat(dest.fpu());
169 break;
170 case Scalar::Float32:
171 loadFloat32(src, dest.fpu());
172 canonicalizeFloat(dest.fpu());
173 break;
174 case Scalar::Float64:
175 loadDouble(src, dest.fpu());
176 canonicalizeDouble(dest.fpu());
177 break;
178 case Scalar::BigInt64:
179 case Scalar::BigUint64:
180 default:
181 MOZ_CRASH("Invalid typed array type");
182 }
183 }
184
185 template void MacroAssembler::loadFromTypedArray(
186 Scalar::Type arrayType, const Address& src, AnyRegister dest,
187 Register temp1, Register temp2, Label* fail,
188 LiveRegisterSet volatileLiveRegs);
189 template void MacroAssembler::loadFromTypedArray(
190 Scalar::Type arrayType, const BaseIndex& src, AnyRegister dest,
191 Register temp1, Register temp2, Label* fail,
192 LiveRegisterSet volatileLiveRegs);
193
194 void MacroAssembler::loadFromTypedArray(Scalar::Type arrayType,
195 const BaseIndex& src,
196 const ValueOperand& dest,
197 Uint32Mode uint32Mode, Register temp,
198 Label* fail,
199 LiveRegisterSet volatileLiveRegs) {
200 switch (arrayType) {
201 case Scalar::Int8:
202 case Scalar::Uint8:
203 case Scalar::Uint8Clamped:
204 case Scalar::Int16:
205 case Scalar::Uint16:
206 case Scalar::Int32:
207 loadFromTypedArray(arrayType, src, AnyRegister(dest.scratchReg()),
208 InvalidReg, InvalidReg, nullptr, LiveRegisterSet{});
209 tagValue(JSVAL_TYPE_INT32, dest.scratchReg(), dest);
210 break;
211 case Scalar::Uint32:
212 load32(src, dest.scratchReg());
213 boxUint32(dest.scratchReg(), dest, uint32Mode, fail);
214 break;
215 case Scalar::Float16: {
216 ScratchDoubleScope dscratch(*this);
217 FloatRegister fscratch = dscratch.asSingle();
218 loadFromTypedArray(arrayType, src, AnyRegister(fscratch),
219 dest.scratchReg(), temp, nullptr, volatileLiveRegs);
220 convertFloat32ToDouble(fscratch, dscratch);
221 boxDouble(dscratch, dest, dscratch);
222 break;
223 }
224 case Scalar::Float32: {
225 ScratchDoubleScope dscratch(*this);
226 FloatRegister fscratch = dscratch.asSingle();
227 loadFromTypedArray(arrayType, src, AnyRegister(fscratch), InvalidReg,
228 InvalidReg, nullptr, LiveRegisterSet{});
229 convertFloat32ToDouble(fscratch, dscratch);
230 boxDouble(dscratch, dest, dscratch);
231 break;
232 }
233 case Scalar::Float64: {
234 ScratchDoubleScope fpscratch(*this);
235 loadFromTypedArray(arrayType, src, AnyRegister(fpscratch), InvalidReg,
236 InvalidReg, nullptr, LiveRegisterSet{});
237 boxDouble(fpscratch, dest, fpscratch);
238 break;
239 }
240 case Scalar::BigInt64:
241 case Scalar::BigUint64:
242 default:
243 MOZ_CRASH("Invalid typed array type");
244 }
245 }
246
247 void MacroAssembler::loadFromTypedBigIntArray(Scalar::Type arrayType,
248 const BaseIndex& src,
249 const ValueOperand& dest,
250 Register bigInt,
251 Register64 temp) {
252 MOZ_ASSERT(Scalar::isBigIntType(arrayType));
253
254 load64(src, temp);
255 initializeBigInt64(arrayType, bigInt, temp);
256 tagValue(JSVAL_TYPE_BIGINT, bigInt, dest);
257 }
258
259 // Inlined version of gc::CheckAllocatorState that checks the bare essentials
260 // and bails for anything that cannot be handled with our jit allocators.
261 void MacroAssembler::checkAllocatorState(Register temp, gc::AllocKind allocKind,
262 Label* fail) {
263 // Don't execute the inline path if GC probes are built in.
264 #ifdef JS_GC_PROBES
265 jump(fail);
266 #endif
267
268 #ifdef JS_GC_ZEAL
269 // Don't execute the inline path if gc zeal or tracing are active.
270 const uint32_t* ptrZealModeBits = runtime()->addressOfGCZealModeBits();
271 branch32(Assembler::NotEqual, AbsoluteAddress(ptrZealModeBits), Imm32(0),
272 fail);
273 #endif
274
275 // If the zone has a realm with an object allocation metadata hook, emit a
276 // guard for this. Note that IC stubs and some other trampolines can be shared
277 // across realms, so we don't bake in a realm pointer.
278 if (gc::IsObjectAllocKind(allocKind) &&
279 realm()->zone()->hasRealmWithAllocMetadataBuilder()) {
280 loadJSContext(temp);
281 loadPtr(Address(temp, JSContext::offsetOfRealm()), temp);
282 branchPtr(Assembler::NotEqual,
283 Address(temp, Realm::offsetOfAllocationMetadataBuilder()),
284 ImmWord(0), fail);
285 }
286 }
287
288 bool MacroAssembler::shouldNurseryAllocate(gc::AllocKind allocKind,
289 gc::Heap initialHeap) {
290 // Note that Ion elides barriers on writes to objects known to be in the
291 // nursery, so any allocation that can be made into the nursery must be made
292 // into the nursery, even if the nursery is disabled. At runtime these will
293 // take the out-of-line path, which is required to insert a barrier for the
294 // initializing writes.
295 return IsNurseryAllocable(allocKind) && initialHeap != gc::Heap::Tenured;
296 }
297
298 // Inline version of Nursery::allocateObject. If the object has dynamic slots,
299 // this fills in the slots_ pointer.
300 void MacroAssembler::nurseryAllocateObject(Register result, Register temp,
301 gc::AllocKind allocKind,
302 size_t nDynamicSlots, Label* fail,
303 const AllocSiteInput& allocSite) {
304 MOZ_ASSERT(IsNurseryAllocable(allocKind));
305
306 // Currently the JIT does not nursery allocate foreground finalized
307 // objects. This is allowed for objects that support this and have the
308 // JSCLASS_SKIP_NURSERY_FINALIZE class flag set. It's hard to assert that here
309 // though so disallow all foreground finalized objects for now.
310 MOZ_ASSERT(!IsForegroundFinalized(allocKind));
311
312 // We still need to allocate in the nursery, per the comment in
313 // shouldNurseryAllocate; however, we need to insert into the
314 // mallocedBuffers set, so bail to do the nursery allocation in the
315 // interpreter.
316 if (nDynamicSlots >= Nursery::MaxNurseryBufferSize / sizeof(Value)) {
317 jump(fail);
318 return;
319 }
320
321 // Check whether this allocation site needs pretenuring. This dynamic check
322 // only happens for baseline code.
323 if (allocSite.is<Register>()) {
324 Register site = allocSite.as<Register>();
325 branchTestPtr(Assembler::NonZero,
326 Address(site, gc::AllocSite::offsetOfScriptAndState()),
327 Imm32(gc::AllocSite::LONG_LIVED_BIT), fail);
328 }
329
330 // No explicit check for nursery.isEnabled() is needed, as the comparison
331 // with the nursery's end will always fail in such cases.
332 CompileZone* zone = realm()->zone();
333 size_t thingSize = gc::Arena::thingSize(allocKind);
334 size_t totalSize = thingSize;
335 if (nDynamicSlots) {
336 totalSize += ObjectSlots::allocSize(nDynamicSlots);
337 }
338 MOZ_ASSERT(totalSize < INT32_MAX);
339 MOZ_ASSERT(totalSize % gc::CellAlignBytes == 0);
340
341 bumpPointerAllocate(result, temp, fail, zone, JS::TraceKind::Object,
342 totalSize, allocSite);
343
344 if (nDynamicSlots) {
345 store32(Imm32(nDynamicSlots),
346 Address(result, thingSize + ObjectSlots::offsetOfCapacity()));
347 store32(
348 Imm32(0),
349 Address(result, thingSize + ObjectSlots::offsetOfDictionarySlotSpan()));
350 store64(Imm64(ObjectSlots::NoUniqueIdInDynamicSlots),
351 Address(result, thingSize + ObjectSlots::offsetOfMaybeUniqueId()));
352 computeEffectiveAddress(
353 Address(result, thingSize + ObjectSlots::offsetOfSlots()), temp);
354 storePtr(temp, Address(result, NativeObject::offsetOfSlots()));
355 }
356 }
357
358 // Inlined version of FreeSpan::allocate. This does not fill in slots_.
359 void MacroAssembler::freeListAllocate(Register result, Register temp,
360 gc::AllocKind allocKind, Label* fail) {
361 CompileZone* zone = realm()->zone();
362 int thingSize = int(gc::Arena::thingSize(allocKind));
363
364 Label fallback;
365 Label success;
366
367 // Load the first and last offsets of |zone|'s free list for |allocKind|.
368 // If there is no room remaining in the span, fall back to get the next one.
369 gc::FreeSpan** ptrFreeList = zone->addressOfFreeList(allocKind);
370 loadPtr(AbsoluteAddress(ptrFreeList), temp);
371 load16ZeroExtend(Address(temp, js::gc::FreeSpan::offsetOfFirst()), result);
372 load16ZeroExtend(Address(temp, js::gc::FreeSpan::offsetOfLast()), temp);
373 branch32(Assembler::AboveOrEqual, result, temp, &fallback);
374
375 // Bump the offset for the next allocation.
376 add32(Imm32(thingSize), result);
377 loadPtr(AbsoluteAddress(ptrFreeList), temp);
378 store16(result, Address(temp, js::gc::FreeSpan::offsetOfFirst()));
379 sub32(Imm32(thingSize), result);
380 addPtr(temp, result); // Turn the offset into a pointer.
381 jump(&success);
382
383 bind(&fallback);
384 // If there are no free spans left, we bail to finish the allocation. The
385 // interpreter will call the GC allocator to set up a new arena to allocate
386 // from, after which we can resume allocating in the jit.
387 branchTest32(Assembler::Zero, result, result, fail);
388 loadPtr(AbsoluteAddress(ptrFreeList), temp);
389 addPtr(temp, result); // Turn the offset into a pointer.
390 Push(result);
391 // Update the free list to point to the next span (which may be empty).
392 load32(Address(result, 0), result);
393 store32(result, Address(temp, js::gc::FreeSpan::offsetOfFirst()));
394 Pop(result);
395
396 bind(&success);
397
398 if (runtime()->geckoProfiler().enabled()) {
399 uint32_t* countAddress = zone->addressOfTenuredAllocCount();
400 movePtr(ImmPtr(countAddress), temp);
401 add32(Imm32(1), Address(temp, 0));
402 }
403 }
404
405 // Inlined equivalent of gc::AllocateObject, without failure case handling.
406 void MacroAssembler::allocateObject(Register result, Register temp,
407 gc::AllocKind allocKind,
408 uint32_t nDynamicSlots,
409 gc::Heap initialHeap, Label* fail,
410 const AllocSiteInput& allocSite) {
411 MOZ_ASSERT(gc::IsObjectAllocKind(allocKind));
412
413 checkAllocatorState(temp, allocKind, fail);
414
415 if (shouldNurseryAllocate(allocKind, initialHeap)) {
416 MOZ_ASSERT(initialHeap == gc::Heap::Default);
417 return nurseryAllocateObject(result, temp, allocKind, nDynamicSlots, fail,
418 allocSite);
419 }
420
421 // Fall back to calling into the VM to allocate objects in the tenured heap
422 // that have dynamic slots.
423 if (nDynamicSlots) {
424 jump(fail);
425 return;
426 }
427
428 return freeListAllocate(result, temp, allocKind, fail);
429 }
430
431 void MacroAssembler::createGCObject(Register obj, Register temp,
432 const TemplateObject& templateObj,
433 gc::Heap initialHeap, Label* fail,
434 bool initContents /* = true */,
435 const AllocSiteInput& allocSite) {
436 gc::AllocKind allocKind = templateObj.getAllocKind();
437 MOZ_ASSERT(gc::IsObjectAllocKind(allocKind));
438
439 uint32_t nDynamicSlots = 0;
440 if (templateObj.isNativeObject()) {
441 const TemplateNativeObject& ntemplate =
442 templateObj.asTemplateNativeObject();
443 nDynamicSlots = ntemplate.numDynamicSlots();
444 }
445
446 allocateObject(obj, temp, allocKind, nDynamicSlots, initialHeap, fail,
447 allocSite);
448 initGCThing(obj, temp, templateObj, initContents);
449 }
450
451 void MacroAssembler::createPlainGCObject(
452 Register result, Register shape, Register temp, Register temp2,
453 uint32_t numFixedSlots, uint32_t numDynamicSlots, gc::AllocKind allocKind,
454 gc::Heap initialHeap, Label* fail, const AllocSiteInput& allocSite,
455 bool initContents /* = true */) {
456 MOZ_ASSERT(gc::IsObjectAllocKind(allocKind));
457 MOZ_ASSERT(shape != temp, "shape can overlap with temp2, but not temp");
458
459 // Allocate object.
460 allocateObject(result, temp, allocKind, numDynamicSlots, initialHeap, fail,
461 allocSite);
462
463 // Initialize shape field.
464 storePtr(shape, Address(result, JSObject::offsetOfShape()));
465
466 // If the object has dynamic slots, allocateObject will initialize
467 // the slots field. If not, we must initialize it now.
468 if (numDynamicSlots == 0) {
469 storePtr(ImmPtr(emptyObjectSlots),
470 Address(result, NativeObject::offsetOfSlots()));
471 }
472
473 // Initialize elements field.
474 storePtr(ImmPtr(emptyObjectElements),
475 Address(result, NativeObject::offsetOfElements()));
476
477 // Initialize fixed slots.
478 if (initContents) {
479 fillSlotsWithUndefined(Address(result, NativeObject::getFixedSlotOffset(0)),
480 temp, 0, numFixedSlots);
481 }
482
483 // Initialize dynamic slots.
484 if (numDynamicSlots > 0) {
485 loadPtr(Address(result, NativeObject::offsetOfSlots()), temp2);
486 fillSlotsWithUndefined(Address(temp2, 0), temp, 0, numDynamicSlots);
487 }
488 }
489
490 void MacroAssembler::createArrayWithFixedElements(
491 Register result, Register shape, Register temp, Register dynamicSlotsTemp,
492 uint32_t arrayLength, uint32_t arrayCapacity, uint32_t numUsedDynamicSlots,
493 uint32_t numDynamicSlots, gc::AllocKind allocKind, gc::Heap initialHeap,
494 Label* fail, const AllocSiteInput& allocSite) {
495 MOZ_ASSERT(gc::IsObjectAllocKind(allocKind));
496 MOZ_ASSERT(shape != temp, "shape can overlap with temp2, but not temp");
497 MOZ_ASSERT(result != temp);
498
499 // This only supports allocating arrays with fixed elements and does not
500 // support any dynamic elements.
501 MOZ_ASSERT(arrayCapacity >= arrayLength);
502 MOZ_ASSERT(gc::GetGCKindSlots(allocKind) >=
503 arrayCapacity + ObjectElements::VALUES_PER_HEADER);
504
505 MOZ_ASSERT(numUsedDynamicSlots <= numDynamicSlots);
506
507 // Allocate object.
508 allocateObject(result, temp, allocKind, numDynamicSlots, initialHeap, fail,
509 allocSite);
510
511 // Initialize shape field.
512 storePtr(shape, Address(result, JSObject::offsetOfShape()));
513
514 // If the object has dynamic slots, allocateObject will initialize
515 // the slots field. If not, we must initialize it now.
516 if (numDynamicSlots == 0) {
517 storePtr(ImmPtr(emptyObjectSlots),
518 Address(result, NativeObject::offsetOfSlots()));
519 }
520
521 // Initialize elements pointer for fixed (inline) elements.
522 computeEffectiveAddress(
523 Address(result, NativeObject::offsetOfFixedElements()), temp);
524 storePtr(temp, Address(result, NativeObject::offsetOfElements()));
525
526 // Initialize elements header.
527 store32(Imm32(ObjectElements::FIXED),
528 Address(temp, ObjectElements::offsetOfFlags()));
529 store32(Imm32(0), Address(temp, ObjectElements::offsetOfInitializedLength()));
530 store32(Imm32(arrayCapacity),
531 Address(temp, ObjectElements::offsetOfCapacity()));
532 store32(Imm32(arrayLength), Address(temp, ObjectElements::offsetOfLength()));
533
534 // Initialize dynamic slots.
535 if (numUsedDynamicSlots > 0) {
536 MOZ_ASSERT(dynamicSlotsTemp != temp);
537 MOZ_ASSERT(dynamicSlotsTemp != InvalidReg);
538 loadPtr(Address(result, NativeObject::offsetOfSlots()), dynamicSlotsTemp);
539 fillSlotsWithUndefined(Address(dynamicSlotsTemp, 0), temp, 0,
540 numUsedDynamicSlots);
541 }
542 }
543
544 void MacroAssembler::createFunctionClone(Register result, Register canonical,
545 Register envChain, Register temp,
546 gc::AllocKind allocKind, Label* fail,
547 const AllocSiteInput& allocSite) {
548 MOZ_ASSERT(allocKind == gc::AllocKind::FUNCTION ||
549 allocKind == gc::AllocKind::FUNCTION_EXTENDED);
550 MOZ_ASSERT(result != temp);
551
552 // Allocate object.
553 size_t numDynamicSlots = 0;
554 gc::Heap initialHeap = gc::Heap::Default;
555 allocateObject(result, temp, allocKind, numDynamicSlots, initialHeap, fail,
556 allocSite);
557
558 // Initialize shape field.
559 loadPtr(Address(canonical, JSObject::offsetOfShape()), temp);
560 storePtr(temp, Address(result, JSObject::offsetOfShape()));
561
562 // Initialize dynamic slots and elements pointers.
563 storePtr(ImmPtr(emptyObjectSlots),
564 Address(result, NativeObject::offsetOfSlots()));
565 storePtr(ImmPtr(emptyObjectElements),
566 Address(result, NativeObject::offsetOfElements()));
567
568 // Initialize FlagsAndArgCountSlot.
569 storeValue(Address(canonical, JSFunction::offsetOfFlagsAndArgCount()),
570 Address(result, JSFunction::offsetOfFlagsAndArgCount()), temp);
571
572 // Initialize NativeFuncOrInterpretedEnvSlot.
573 storeValue(JSVAL_TYPE_OBJECT, envChain,
574 Address(result, JSFunction::offsetOfEnvironment()));
575
576 #ifdef DEBUG
577 // The new function must be allocated in the nursery if the nursery is
578 // enabled. Assert no post-barrier is needed.
579 Label ok;
580 branchPtrInNurseryChunk(Assembler::Equal, result, temp, &ok);
581 branchPtrInNurseryChunk(Assembler::NotEqual, envChain, temp, &ok);
582 assumeUnreachable("Missing post write barrier in createFunctionClone");
583 bind(&ok);
584 #endif
585
586 // Initialize NativeJitInfoOrInterpretedScriptSlot. This is a BaseScript*
587 // pointer stored as PrivateValue.
588 loadPrivate(Address(canonical, JSFunction::offsetOfJitInfoOrScript()), temp);
589 storePrivateValue(temp,
590 Address(result, JSFunction::offsetOfJitInfoOrScript()));
591
592 // Initialize AtomSlot.
593 storeValue(Address(canonical, JSFunction::offsetOfAtom()),
594 Address(result, JSFunction::offsetOfAtom()), temp);
595
596 // Initialize extended slots.
597 if (allocKind == gc::AllocKind::FUNCTION_EXTENDED) {
598 for (size_t i = 0; i < FunctionExtended::NUM_EXTENDED_SLOTS; i++) {
599 Address addr(result, FunctionExtended::offsetOfExtendedSlot(i));
600 storeValue(UndefinedValue(), addr);
601 }
602 }
603 }
604
605 // Inline version of Nursery::allocateString.
606 void MacroAssembler::nurseryAllocateString(Register result, Register temp,
607 gc::AllocKind allocKind,
608 Label* fail) {
609 MOZ_ASSERT(IsNurseryAllocable(allocKind));
610
611 // No explicit check for nursery.isEnabled() is needed, as the comparison
612 // with the nursery's end will always fail in such cases.
613
614 CompileZone* zone = realm()->zone();
615 size_t thingSize = gc::Arena::thingSize(allocKind);
616 bumpPointerAllocate(result, temp, fail, zone, JS::TraceKind::String,
617 thingSize);
618 }
619
620 // Inline version of Nursery::allocateBigInt.
621 void MacroAssembler::nurseryAllocateBigInt(Register result, Register temp,
622 Label* fail) {
623 MOZ_ASSERT(IsNurseryAllocable(gc::AllocKind::BIGINT));
624
625 // No explicit check for nursery.isEnabled() is needed, as the comparison
626 // with the nursery's end will always fail in such cases.
627
628 CompileZone* zone = realm()->zone();
629 size_t thingSize = gc::Arena::thingSize(gc::AllocKind::BIGINT);
630
631 bumpPointerAllocate(result, temp, fail, zone, JS::TraceKind::BigInt,
632 thingSize);
633 }
634
635 static bool IsNurseryAllocEnabled(CompileZone* zone, JS::TraceKind kind) {
636 switch (kind) {
637 case JS::TraceKind::Object:
638 return zone->allocNurseryObjects();
639 case JS::TraceKind::String:
640 return zone->allocNurseryStrings();
641 case JS::TraceKind::BigInt:
642 return zone->allocNurseryBigInts();
643 default:
644 MOZ_CRASH("Bad nursery allocation kind");
645 }
646 }
647
648 // This function handles nursery allocations for JS. For wasm, see
649 // MacroAssembler::wasmBumpPointerAllocate.
650 void MacroAssembler::bumpPointerAllocate(Register result, Register temp,
651 Label* fail, CompileZone* zone,
652 JS::TraceKind traceKind, uint32_t size,
653 const AllocSiteInput& allocSite) {
654 MOZ_ASSERT(size >= gc::MinCellSize);
655
656 uint32_t totalSize = size + Nursery::nurseryCellHeaderSize();
657 MOZ_ASSERT(totalSize < INT32_MAX, "Nursery allocation too large");
658 MOZ_ASSERT(totalSize % gc::CellAlignBytes == 0);
659
660 // We know statically whether nursery allocation is enable for a particular
661 // kind because we discard JIT code when this changes.
662 if (!IsNurseryAllocEnabled(zone, traceKind)) {
663 jump(fail);
664 return;
665 }
666
667 // Use a relative 32 bit offset to the Nursery position_ to currentEnd_ to
668 // avoid 64-bit immediate loads.
669 void* posAddr = zone->addressOfNurseryPosition();
670 int32_t endOffset = Nursery::offsetOfCurrentEndFromPosition();
671
672 movePtr(ImmPtr(posAddr), temp);
673 loadPtr(Address(temp, 0), result);
674 addPtr(Imm32(totalSize), result);
675 branchPtr(Assembler::Below, Address(temp, endOffset), result, fail);
676 storePtr(result, Address(temp, 0));
677 subPtr(Imm32(size), result);
678
679 if (allocSite.is<gc::CatchAllAllocSite>()) {
680 // No allocation site supplied. This is the case when called from Warp, or
681 // from places that don't support pretenuring.
682 gc::CatchAllAllocSite siteKind = allocSite.as<gc::CatchAllAllocSite>();
683 gc::AllocSite* site = zone->catchAllAllocSite(traceKind, siteKind);
684 uintptr_t headerWord = gc::NurseryCellHeader::MakeValue(site, traceKind);
685 storePtr(ImmWord(headerWord),
686 Address(result, -js::Nursery::nurseryCellHeaderSize()));
687
688 if (traceKind != JS::TraceKind::Object ||
689 runtime()->geckoProfiler().enabled()) {
690 // Update the catch all allocation site, which his is used to calculate
691 // nursery allocation counts so we can determine whether to disable
692 // nursery allocation of strings and bigints.
693 uint32_t* countAddress = site->nurseryAllocCountAddress();
694 CheckedInt<int32_t> counterOffset =
695 (CheckedInt<uintptr_t>(uintptr_t(countAddress)) -
696 CheckedInt<uintptr_t>(uintptr_t(posAddr)))
697 .toChecked<int32_t>();
698 if (counterOffset.isValid()) {
699 add32(Imm32(1), Address(temp, counterOffset.value()));
700 } else {
701 movePtr(ImmPtr(countAddress), temp);
702 add32(Imm32(1), Address(temp, 0));
703 }
704 }
705 } else {
706 // Update allocation site and store pointer in the nursery cell header. This
707 // is only used from baseline.
708 Register site = allocSite.as<Register>();
709 updateAllocSite(temp, result, zone, site);
710 // See NurseryCellHeader::MakeValue.
711 orPtr(Imm32(int32_t(traceKind)), site);
712 storePtr(site, Address(result, -js::Nursery::nurseryCellHeaderSize()));
713 }
714 }
715
716 // Update the allocation site in the same way as Nursery::allocateCell.
717 void MacroAssembler::updateAllocSite(Register temp, Register result,
718 CompileZone* zone, Register site) {
719 Label done;
720
721 add32(Imm32(1), Address(site, gc::AllocSite::offsetOfNurseryAllocCount()));
722
723 branch32(Assembler::NotEqual,
724 Address(site, gc::AllocSite::offsetOfNurseryAllocCount()),
725 Imm32(js::gc::NormalSiteAttentionThreshold), &done);
726
727 loadPtr(AbsoluteAddress(zone->addressOfNurseryAllocatedSites()), temp);
728 storePtr(temp, Address(site, gc::AllocSite::offsetOfNextNurseryAllocated()));
729 storePtr(site, AbsoluteAddress(zone->addressOfNurseryAllocatedSites()));
730
731 bind(&done);
732 }
733
734 // Inlined equivalent of gc::AllocateString, jumping to fail if nursery
735 // allocation requested but unsuccessful.
736 void MacroAssembler::allocateString(Register result, Register temp,
737 gc::AllocKind allocKind,
738 gc::Heap initialHeap, Label* fail) {
739 MOZ_ASSERT(allocKind == gc::AllocKind::STRING ||
740 allocKind == gc::AllocKind::FAT_INLINE_STRING);
741
742 checkAllocatorState(temp, allocKind, fail);
743
744 if (shouldNurseryAllocate(allocKind, initialHeap)) {
745 MOZ_ASSERT(initialHeap == gc::Heap::Default);
746 return nurseryAllocateString(result, temp, allocKind, fail);
747 }
748
749 freeListAllocate(result, temp, allocKind, fail);
750 }
751
752 void MacroAssembler::newGCString(Register result, Register temp,
753 gc::Heap initialHeap, Label* fail) {
754 allocateString(result, temp, js::gc::AllocKind::STRING, initialHeap, fail);
755 }
756
757 void MacroAssembler::newGCFatInlineString(Register result, Register temp,
758 gc::Heap initialHeap, Label* fail) {
759 allocateString(result, temp, js::gc::AllocKind::FAT_INLINE_STRING,
760 initialHeap, fail);
761 }
762
763 void MacroAssembler::newGCBigInt(Register result, Register temp,
764 gc::Heap initialHeap, Label* fail) {
765 constexpr gc::AllocKind allocKind = gc::AllocKind::BIGINT;
766
767 checkAllocatorState(temp, allocKind, fail);
768
769 if (shouldNurseryAllocate(allocKind, initialHeap)) {
770 MOZ_ASSERT(initialHeap == gc::Heap::Default);
771 return nurseryAllocateBigInt(result, temp, fail);
772 }
773
774 freeListAllocate(result, temp, allocKind, fail);
775 }
776
777 void MacroAssembler::copySlotsFromTemplate(
778 Register obj, const TemplateNativeObject& templateObj, uint32_t start,
779 uint32_t end) {
780 uint32_t nfixed = std::min(templateObj.numFixedSlots(), end);
781 for (unsigned i = start; i < nfixed; i++) {
782 // Template objects are not exposed to script and therefore immutable.
783 // However, regexp template objects are sometimes used directly (when
784 // the cloning is not observable), and therefore we can end up with a
785 // non-zero lastIndex. Detect this case here and just substitute 0, to
786 // avoid racing with the main thread updating this slot.
787 Value v;
788 if (templateObj.isRegExpObject() && i == RegExpObject::lastIndexSlot()) {
789 v = Int32Value(0);
790 } else {
791 v = templateObj.getSlot(i);
792 }
793 storeValue(v, Address(obj, NativeObject::getFixedSlotOffset(i)));
794 }
795 }
796
797 void MacroAssembler::fillSlotsWithConstantValue(Address base, Register temp,
798 uint32_t start, uint32_t end,
799 const Value& v) {
800 MOZ_ASSERT(v.isUndefined() || IsUninitializedLexical(v));
801
802 if (start >= end) {
803 return;
804 }
805
806 #ifdef JS_NUNBOX32
807 // We only have a single spare register, so do the initialization as two
808 // strided writes of the tag and body.
809 Address addr = base;
810 move32(Imm32(v.toNunboxPayload()), temp);
811 for (unsigned i = start; i < end; ++i, addr.offset += sizeof(GCPtr<Value>)) {
812 store32(temp, ToPayload(addr));
813 }
814
815 addr = base;
816 move32(Imm32(v.toNunboxTag()), temp);
817 for (unsigned i = start; i < end; ++i, addr.offset += sizeof(GCPtr<Value>)) {
818 store32(temp, ToType(addr));
819 }
820 #else
821 moveValue(v, ValueOperand(temp));
822 for (uint32_t i = start; i < end; ++i, base.offset += sizeof(GCPtr<Value>)) {
823 storePtr(temp, base);
824 }
825 #endif
826 }
827
828 void MacroAssembler::fillSlotsWithUndefined(Address base, Register temp,
829 uint32_t start, uint32_t end) {
830 fillSlotsWithConstantValue(base, temp, start, end, UndefinedValue());
831 }
832
833 void MacroAssembler::fillSlotsWithUninitialized(Address base, Register temp,
834 uint32_t start, uint32_t end) {
835 fillSlotsWithConstantValue(base, temp, start, end,
836 MagicValue(JS_UNINITIALIZED_LEXICAL));
837 }
838
839 static std::pair<uint32_t, uint32_t> FindStartOfUninitializedAndUndefinedSlots(
840 const TemplateNativeObject& templateObj, uint32_t nslots) {
841 MOZ_ASSERT(nslots == templateObj.slotSpan());
842 MOZ_ASSERT(nslots > 0);
843
844 uint32_t first = nslots;
845 for (; first != 0; --first) {
846 if (templateObj.getSlot(first - 1) != UndefinedValue()) {
847 break;
848 }
849 }
850 uint32_t startOfUndefined = first;
851
852 if (first != 0 && IsUninitializedLexical(templateObj.getSlot(first - 1))) {
853 for (; first != 0; --first) {
854 if (!IsUninitializedLexical(templateObj.getSlot(first - 1))) {
855 break;
856 }
857 }
858 }
859 uint32_t startOfUninitialized = first;
860
861 return {startOfUninitialized, startOfUndefined};
862 }
863
864 void MacroAssembler::initTypedArraySlots(
865 Register obj, Register temp, Register lengthReg, LiveRegisterSet liveRegs,
866 Label* fail, FixedLengthTypedArrayObject* templateObj,
867 TypedArrayLength lengthKind) {
868 MOZ_ASSERT(!templateObj->hasBuffer());
869
870 constexpr size_t dataSlotOffset = ArrayBufferViewObject::dataOffset();
871 constexpr size_t dataOffset = dataSlotOffset + sizeof(HeapSlot);
872
873 static_assert(
874 FixedLengthTypedArrayObject::FIXED_DATA_START ==
875 FixedLengthTypedArrayObject::DATA_SLOT + 1,
876 "fixed inline element data assumed to begin after the data slot");
877
878 static_assert(
879 FixedLengthTypedArrayObject::INLINE_BUFFER_LIMIT ==
880 JSObject::MAX_BYTE_SIZE - dataOffset,
881 "typed array inline buffer is limited by the maximum object byte size");
882
883 // Initialise data elements to zero.
884 size_t length = templateObj->length();
885 MOZ_ASSERT(length <= INT32_MAX,
886 "Template objects are only created for int32 lengths");
887 size_t nbytes = length * templateObj->bytesPerElement();
888
889 if (lengthKind == TypedArrayLength::Fixed &&
890 nbytes <= FixedLengthTypedArrayObject::INLINE_BUFFER_LIMIT) {
891 MOZ_ASSERT(dataOffset + nbytes <= templateObj->tenuredSizeOfThis());
892
893 // Store data elements inside the remaining JSObject slots.
894 computeEffectiveAddress(Address(obj, dataOffset), temp);
895 storePrivateValue(temp, Address(obj, dataSlotOffset));
896
897 // Write enough zero pointers into fixed data to zero every
898 // element. (This zeroes past the end of a byte count that's
899 // not a multiple of pointer size. That's okay, because fixed
900 // data is a count of 8-byte HeapSlots (i.e. <= pointer size),
901 // and we won't inline unless the desired memory fits in that
902 // space.)
903 static_assert(sizeof(HeapSlot) == 8, "Assumed 8 bytes alignment");
904
905 size_t numZeroPointers = ((nbytes + 7) & ~0x7) / sizeof(char*);
906 for (size_t i = 0; i < numZeroPointers; i++) {
907 storePtr(ImmWord(0), Address(obj, dataOffset + i * sizeof(char*)));
908 }
909 MOZ_ASSERT(nbytes > 0, "Zero-length TypedArrays need ZeroLengthArrayData");
910 } else {
911 if (lengthKind == TypedArrayLength::Fixed) {
912 move32(Imm32(length), lengthReg);
913 }
914
915 // Ensure volatile |obj| is saved across the call.
916 if (obj.volatile_()) {
917 liveRegs.addUnchecked(obj);
918 }
919
920 // Allocate a buffer on the heap to store the data elements.
921 PushRegsInMask(liveRegs);
922 using Fn = void (*)(JSContext* cx, TypedArrayObject* obj, int32_t count);
923 setupUnalignedABICall(temp);
924 loadJSContext(temp);
925 passABIArg(temp);
926 passABIArg(obj);
927 passABIArg(lengthReg);
928 callWithABI<Fn, AllocateAndInitTypedArrayBuffer>();
929 PopRegsInMask(liveRegs);
930
931 // Fail when data slot is UndefinedValue.
932 branchTestUndefined(Assembler::Equal, Address(obj, dataSlotOffset), fail);
933 }
934 }
935
936 void MacroAssembler::initGCSlots(Register obj, Register temp,
937 const TemplateNativeObject& templateObj) {
938 MOZ_ASSERT(!templateObj.isArrayObject());
939
940 // Slots of non-array objects are required to be initialized.
941 // Use the values currently in the template object.
942 uint32_t nslots = templateObj.slotSpan();
943 if (nslots == 0) {
944 return;
945 }
946
947 uint32_t nfixed = templateObj.numUsedFixedSlots();
948 uint32_t ndynamic = templateObj.numDynamicSlots();
949
950 // Attempt to group slot writes such that we minimize the amount of
951 // duplicated data we need to embed in code and load into registers. In
952 // general, most template object slots will be undefined except for any
953 // reserved slots. Since reserved slots come first, we split the object
954 // logically into independent non-UndefinedValue writes to the head and
955 // duplicated writes of UndefinedValue to the tail. For the majority of
956 // objects, the "tail" will be the entire slot range.
957 //
958 // The template object may be a CallObject, in which case we need to
959 // account for uninitialized lexical slots as well as undefined
960 // slots. Uninitialized lexical slots appears in CallObjects if the function
961 // has parameter expressions, in which case closed over parameters have
962 // TDZ. Uninitialized slots come before undefined slots in CallObjects.
963 auto [startOfUninitialized, startOfUndefined] =
964 FindStartOfUninitializedAndUndefinedSlots(templateObj, nslots);
965 MOZ_ASSERT(startOfUninitialized <= nfixed); // Reserved slots must be fixed.
966 MOZ_ASSERT(startOfUndefined >= startOfUninitialized);
967 MOZ_ASSERT_IF(!templateObj.isCallObject() &&
968 !templateObj.isBlockLexicalEnvironmentObject(),
969 startOfUninitialized == startOfUndefined);
970
971 // Copy over any preserved reserved slots.
972 copySlotsFromTemplate(obj, templateObj, 0, startOfUninitialized);
973
974 // Fill the rest of the fixed slots with undefined and uninitialized.
975 size_t offset = NativeObject::getFixedSlotOffset(startOfUninitialized);
976 fillSlotsWithUninitialized(Address(obj, offset), temp, startOfUninitialized,
977 std::min(startOfUndefined, nfixed));
978
979 if (startOfUndefined < nfixed) {
980 offset = NativeObject::getFixedSlotOffset(startOfUndefined);
981 fillSlotsWithUndefined(Address(obj, offset), temp, startOfUndefined,
982 nfixed);
983 }
984
985 if (ndynamic) {
986 // We are short one register to do this elegantly. Borrow the obj
987 // register briefly for our slots base address.
988 push(obj);
989 loadPtr(Address(obj, NativeObject::offsetOfSlots()), obj);
990
991 // Fill uninitialized slots if necessary. Otherwise initialize all
992 // slots to undefined.
993 if (startOfUndefined > nfixed) {
994 MOZ_ASSERT(startOfUninitialized != startOfUndefined);
995 fillSlotsWithUninitialized(Address(obj, 0), temp, 0,
996 startOfUndefined - nfixed);
997 size_t offset = (startOfUndefined - nfixed) * sizeof(Value);
998 fillSlotsWithUndefined(Address(obj, offset), temp,
999 startOfUndefined - nfixed, ndynamic);
1000 } else {
1001 fillSlotsWithUndefined(Address(obj, 0), temp, 0, ndynamic);
1002 }
1003
1004 pop(obj);
1005 }
1006 }
1007
1008 void MacroAssembler::initGCThing(Register obj, Register temp,
1009 const TemplateObject& templateObj,
1010 bool initContents) {
1011 // Fast initialization of an empty object returned by allocateObject().
1012
1013 storePtr(ImmGCPtr(templateObj.shape()),
1014 Address(obj, JSObject::offsetOfShape()));
1015
1016 if (templateObj.isNativeObject()) {
1017 const TemplateNativeObject& ntemplate =
1018 templateObj.asTemplateNativeObject();
1019 MOZ_ASSERT(!ntemplate.hasDynamicElements());
1020
1021 // If the object has dynamic slots, the slots member has already been
1022 // filled in.
1023 if (ntemplate.numDynamicSlots() == 0) {
1024 storePtr(ImmPtr(emptyObjectSlots),
1025 Address(obj, NativeObject::offsetOfSlots()));
1026 }
1027
1028 if (ntemplate.isArrayObject()) {
1029 // Can't skip initializing reserved slots.
1030 MOZ_ASSERT(initContents);
1031
1032 int elementsOffset = NativeObject::offsetOfFixedElements();
1033
1034 computeEffectiveAddress(Address(obj, elementsOffset), temp);
1035 storePtr(temp, Address(obj, NativeObject::offsetOfElements()));
1036
1037 // Fill in the elements header.
1038 store32(
1039 Imm32(ntemplate.getDenseCapacity()),
1040 Address(obj, elementsOffset + ObjectElements::offsetOfCapacity()));
1041 store32(Imm32(ntemplate.getDenseInitializedLength()),
1042 Address(obj, elementsOffset +
1043 ObjectElements::offsetOfInitializedLength()));
1044 store32(Imm32(ntemplate.getArrayLength()),
1045 Address(obj, elementsOffset + ObjectElements::offsetOfLength()));
1046 store32(Imm32(ObjectElements::FIXED),
1047 Address(obj, elementsOffset + ObjectElements::offsetOfFlags()));
1048 } else if (ntemplate.isArgumentsObject()) {
1049 // The caller will initialize the reserved slots.
1050 MOZ_ASSERT(!initContents);
1051 storePtr(ImmPtr(emptyObjectElements),
1052 Address(obj, NativeObject::offsetOfElements()));
1053 } else {
1054 // If the target type could be a TypedArray that maps shared memory
1055 // then this would need to store emptyObjectElementsShared in that case.
1056 MOZ_ASSERT(!ntemplate.isSharedMemory());
1057
1058 // Can't skip initializing reserved slots.
1059 MOZ_ASSERT(initContents);
1060
1061 storePtr(ImmPtr(emptyObjectElements),
1062 Address(obj, NativeObject::offsetOfElements()));
1063
1064 initGCSlots(obj, temp, ntemplate);
1065 }
1066 } else {
1067 MOZ_CRASH("Unknown object");
1068 }
1069
1070 #ifdef JS_GC_PROBES
1071 AllocatableRegisterSet regs(RegisterSet::Volatile());
1072 LiveRegisterSet save(regs.asLiveSet());
1073 PushRegsInMask(save);
1074
1075 regs.takeUnchecked(obj);
1076 Register temp2 = regs.takeAnyGeneral();
1077
1078 using Fn = void (*)(JSObject* obj);
1079 setupUnalignedABICall(temp2);
1080 passABIArg(obj);
1081 callWithABI<Fn, TraceCreateObject>();
1082
1083 PopRegsInMask(save);
1084 #endif
1085 }
1086
1087 static size_t StringCharsByteLength(const JSLinearString* linear) {
1088 CharEncoding encoding =
1089 linear->hasLatin1Chars() ? CharEncoding::Latin1 : CharEncoding::TwoByte;
1090 size_t encodingSize = encoding == CharEncoding::Latin1
1091 ? sizeof(JS::Latin1Char)
1092 : sizeof(char16_t);
1093 return linear->length() * encodingSize;
1094 }
1095
1096 bool MacroAssembler::canCompareStringCharsInline(const JSLinearString* linear) {
1097 // Limit the number of inline instructions used for character comparisons. Use
1098 // the same instruction limit for both encodings, i.e. two-byte uses half the
1099 // limit of Latin-1 strings.
1100 constexpr size_t ByteLengthCompareCutoff = 32;
1101
1102 size_t byteLength = StringCharsByteLength(linear);
1103 return 0 < byteLength && byteLength <= ByteLengthCompareCutoff;
1104 }
1105
1106 template <typename T, typename CharT>
1107 static inline T CopyCharacters(const CharT* chars) {
1108 T value = 0;
1109 std::memcpy(&value, chars, sizeof(T));
1110 return value;
1111 }
1112
1113 template <typename T>
1114 static inline T CopyCharacters(const JSLinearString* linear, size_t index) {
1115 JS::AutoCheckCannotGC nogc;
1116
1117 if (linear->hasLatin1Chars()) {
1118 MOZ_ASSERT(index + sizeof(T) / sizeof(JS::Latin1Char) <= linear->length());
1119 return CopyCharacters<T>(linear->latin1Chars(nogc) + index);
1120 }
1121
1122 MOZ_ASSERT(sizeof(T) >= sizeof(char16_t));
1123 MOZ_ASSERT(index + sizeof(T) / sizeof(char16_t) <= linear->length());
1124 return CopyCharacters<T>(linear->twoByteChars(nogc) + index);
1125 }
1126
1127 void MacroAssembler::branchIfNotStringCharsEquals(Register stringChars,
1128 const JSLinearString* linear,
1129 Label* label) {
1130 CharEncoding encoding =
1131 linear->hasLatin1Chars() ? CharEncoding::Latin1 : CharEncoding::TwoByte;
1132 size_t encodingSize = encoding == CharEncoding::Latin1
1133 ? sizeof(JS::Latin1Char)
1134 : sizeof(char16_t);
1135 size_t byteLength = StringCharsByteLength(linear);
1136
1137 size_t pos = 0;
1138 for (size_t stride : {8, 4, 2, 1}) {
1139 while (byteLength >= stride) {
1140 Address addr(stringChars, pos * encodingSize);
1141 switch (stride) {
1142 case 8: {
1143 auto x = CopyCharacters<uint64_t>(linear, pos);
1144 branch64(Assembler::NotEqual, addr, Imm64(x), label);
1145 break;
1146 }
1147 case 4: {
1148 auto x = CopyCharacters<uint32_t>(linear, pos);
1149 branch32(Assembler::NotEqual, addr, Imm32(x), label);
1150 break;
1151 }
1152 case 2: {
1153 auto x = CopyCharacters<uint16_t>(linear, pos);
1154 branch16(Assembler::NotEqual, addr, Imm32(x), label);
1155 break;
1156 }
1157 case 1: {
1158 auto x = CopyCharacters<uint8_t>(linear, pos);
1159 branch8(Assembler::NotEqual, addr, Imm32(x), label);
1160 break;
1161 }
1162 }
1163
1164 byteLength -= stride;
1165 pos += stride / encodingSize;
1166 }
1167
1168 // Prefer a single comparison for trailing bytes instead of doing
1169 // multiple consecutive comparisons.
1170 //
1171 // For example when comparing against the string "example", emit two
1172 // four-byte comparisons against "exam" and "mple" instead of doing
1173 // three comparisons against "exam", "pl", and finally "e".
1174 if (pos > 0 && byteLength > stride / 2) {
1175 MOZ_ASSERT(stride == 8 || stride == 4);
1176
1177 size_t prev = pos - (stride - byteLength) / encodingSize;
1178 Address addr(stringChars, prev * encodingSize);
1179 switch (stride) {
1180 case 8: {
1181 auto x = CopyCharacters<uint64_t>(linear, prev);
1182 branch64(Assembler::NotEqual, addr, Imm64(x), label);
1183 break;
1184 }
1185 case 4: {
1186 auto x = CopyCharacters<uint32_t>(linear, prev);
1187 branch32(Assembler::NotEqual, addr, Imm32(x), label);
1188 break;
1189 }
1190 }
1191
1192 // Break from the loop, because we've finished the complete string.
1193 break;
1194 }
1195 }
1196 }
1197
1198 void MacroAssembler::loadStringCharsForCompare(Register input,
1199 const JSLinearString* linear,
1200 Register stringChars,
1201 Label* fail) {
1202 CharEncoding encoding =
1203 linear->hasLatin1Chars() ? CharEncoding::Latin1 : CharEncoding::TwoByte;
1204
1205 // Take the slow path when the string is a rope or has a different character
1206 // representation.
1207 branchIfRope(input, fail);
1208 if (encoding == CharEncoding::Latin1) {
1209 branchTwoByteString(input, fail);
1210 } else {
1211 JS::AutoCheckCannotGC nogc;
1212 if (mozilla::IsUtf16Latin1(linear->twoByteRange(nogc))) {
1213 branchLatin1String(input, fail);
1214 } else {
1215 // This case was already handled in the caller.
1216 #ifdef DEBUG
1217 Label ok;
1218 branchTwoByteString(input, &ok);
1219 assumeUnreachable("Unexpected Latin-1 string");
1220 bind(&ok);
1221 #endif
1222 }
1223 }
1224
1225 #ifdef DEBUG
1226 {
1227 size_t length = linear->length();
1228 MOZ_ASSERT(length > 0);
1229
1230 Label ok;
1231 branch32(Assembler::AboveOrEqual,
1232 Address(input, JSString::offsetOfLength()), Imm32(length), &ok);
1233 assumeUnreachable("Input mustn't be smaller than search string");
1234 bind(&ok);
1235 }
1236 #endif
1237
1238 // Load the input string's characters.
1239 loadStringChars(input, stringChars, encoding);
1240 }
1241
1242 void MacroAssembler::compareStringChars(JSOp op, Register stringChars,
1243 const JSLinearString* linear,
1244 Register output) {
1245 MOZ_ASSERT(IsEqualityOp(op));
1246
1247 size_t byteLength = StringCharsByteLength(linear);
1248
1249 // Prefer a single compare-and-set instruction if possible.
1250 if (byteLength == 1 || byteLength == 2 || byteLength == 4 ||
1251 byteLength == 8) {
1252 auto cond = JSOpToCondition(op, /* isSigned = */ false);
1253
1254 Address addr(stringChars, 0);
1255 switch (byteLength) {
1256 case 8: {
1257 auto x = CopyCharacters<uint64_t>(linear, 0);
1258 cmp64Set(cond, addr, Imm64(x), output);
1259 break;
1260 }
1261 case 4: {
1262 auto x = CopyCharacters<uint32_t>(linear, 0);
1263 cmp32Set(cond, addr, Imm32(x), output);
1264 break;
1265 }
1266 case 2: {
1267 auto x = CopyCharacters<uint16_t>(linear, 0);
1268 cmp16Set(cond, addr, Imm32(x), output);
1269 break;
1270 }
1271 case 1: {
1272 auto x = CopyCharacters<uint8_t>(linear, 0);
1273 cmp8Set(cond, addr, Imm32(x), output);
1274 break;
1275 }
1276 }
1277 } else {
1278 Label setNotEqualResult;
1279 branchIfNotStringCharsEquals(stringChars, linear, &setNotEqualResult);
1280
1281 // Falls through if both strings are equal.
1282
1283 Label done;
1284 move32(Imm32(op == JSOp::Eq || op == JSOp::StrictEq), output);
1285 jump(&done);
1286
1287 bind(&setNotEqualResult);
1288 move32(Imm32(op == JSOp::Ne || op == JSOp::StrictNe), output);
1289
1290 bind(&done);
1291 }
1292 }
1293
1294 void MacroAssembler::compareStrings(JSOp op, Register left, Register right,
1295 Register result, Label* fail) {
1296 MOZ_ASSERT(left != result);
1297 MOZ_ASSERT(right != result);
1298 MOZ_ASSERT(IsEqualityOp(op) || IsRelationalOp(op));
1299
1300 Label notPointerEqual;
1301 // If operands point to the same instance, the strings are trivially equal.
1302 branchPtr(Assembler::NotEqual, left, right,
1303 IsEqualityOp(op) ? &notPointerEqual : fail);
1304 move32(Imm32(op == JSOp::Eq || op == JSOp::StrictEq || op == JSOp::Le ||
1305 op == JSOp::Ge),
1306 result);
1307
1308 if (IsEqualityOp(op)) {
1309 Label done;
1310 jump(&done);
1311
1312 bind(&notPointerEqual);
1313
1314 Label leftIsNotAtom;
1315 Label setNotEqualResult;
1316 // Atoms cannot be equal to each other if they point to different strings.
1317 Imm32 atomBit(JSString::ATOM_BIT);
1318 branchTest32(Assembler::Zero, Address(left, JSString::offsetOfFlags()),
1319 atomBit, &leftIsNotAtom);
1320 branchTest32(Assembler::NonZero, Address(right, JSString::offsetOfFlags()),
1321 atomBit, &setNotEqualResult);
1322
1323 bind(&leftIsNotAtom);
1324 // Strings of different length can never be equal.
1325 loadStringLength(left, result);
1326 branch32(Assembler::Equal, Address(right, JSString::offsetOfLength()),
1327 result, fail);
1328
1329 bind(&setNotEqualResult);
1330 move32(Imm32(op == JSOp::Ne || op == JSOp::StrictNe), result);
1331
1332 bind(&done);
1333 }
1334 }
1335
1336 void MacroAssembler::loadStringChars(Register str, Register dest,
1337 CharEncoding encoding) {
1338 MOZ_ASSERT(str != dest);
1339
1340 if (JitOptions.spectreStringMitigations) {
1341 if (encoding == CharEncoding::Latin1) {
1342 // If the string is a rope, zero the |str| register. The code below
1343 // depends on str->flags so this should block speculative execution.
1344 movePtr(ImmWord(0), dest);
1345 test32MovePtr(Assembler::Zero, Address(str, JSString::offsetOfFlags()),
1346 Imm32(JSString::LINEAR_BIT), dest, str);
1347 } else {
1348 // If we're loading TwoByte chars, there's an additional risk:
1349 // if the string has Latin1 chars, we could read out-of-bounds. To
1350 // prevent this, we check both the Linear and Latin1 bits. We don't
1351 // have a scratch register, so we use these flags also to block
1352 // speculative execution, similar to the use of 0 above.
1353 MOZ_ASSERT(encoding == CharEncoding::TwoByte);
1354 static constexpr uint32_t Mask =
1355 JSString::LINEAR_BIT | JSString::LATIN1_CHARS_BIT;
1356 static_assert(Mask < 2048,
1357 "Mask should be a small, near-null value to ensure we "
1358 "block speculative execution when it's used as string "
1359 "pointer");
1360 move32(Imm32(Mask), dest);
1361 and32(Address(str, JSString::offsetOfFlags()), dest);
1362 cmp32MovePtr(Assembler::NotEqual, dest, Imm32(JSString::LINEAR_BIT), dest,
1363 str);
1364 }
1365 }
1366
1367 // Load the inline chars.
1368 computeEffectiveAddress(Address(str, JSInlineString::offsetOfInlineStorage()),
1369 dest);
1370
1371 // If it's not an inline string, load the non-inline chars. Use a
1372 // conditional move to prevent speculative execution.
1373 test32LoadPtr(Assembler::Zero, Address(str, JSString::offsetOfFlags()),
1374 Imm32(JSString::INLINE_CHARS_BIT),
1375 Address(str, JSString::offsetOfNonInlineChars()), dest);
1376 }
1377
1378 void MacroAssembler::loadNonInlineStringChars(Register str, Register dest,
1379 CharEncoding encoding) {
1380 MOZ_ASSERT(str != dest);
1381
1382 if (JitOptions.spectreStringMitigations) {
1383 // If the string is a rope, has inline chars, or has a different
1384 // character encoding, set str to a near-null value to prevent
1385 // speculative execution below (when reading str->nonInlineChars).
1386
1387 static constexpr uint32_t Mask = JSString::LINEAR_BIT |
1388 JSString::INLINE_CHARS_BIT |
1389 JSString::LATIN1_CHARS_BIT;
1390 static_assert(Mask < 2048,
1391 "Mask should be a small, near-null value to ensure we "
1392 "block speculative execution when it's used as string "
1393 "pointer");
1394
1395 uint32_t expectedBits = JSString::LINEAR_BIT;
1396 if (encoding == CharEncoding::Latin1) {
1397 expectedBits |= JSString::LATIN1_CHARS_BIT;
1398 }
1399
1400 move32(Imm32(Mask), dest);
1401 and32(Address(str, JSString::offsetOfFlags()), dest);
1402
1403 cmp32MovePtr(Assembler::NotEqual, dest, Imm32(expectedBits), dest, str);
1404 }
1405
1406 loadPtr(Address(str, JSString::offsetOfNonInlineChars()), dest);
1407 }
1408
1409 void MacroAssembler::storeNonInlineStringChars(Register chars, Register str) {
1410 MOZ_ASSERT(chars != str);
1411 storePtr(chars, Address(str, JSString::offsetOfNonInlineChars()));
1412 }
1413
1414 void MacroAssembler::loadInlineStringCharsForStore(Register str,
1415 Register dest) {
1416 computeEffectiveAddress(Address(str, JSInlineString::offsetOfInlineStorage()),
1417 dest);
1418 }
1419
1420 void MacroAssembler::loadInlineStringChars(Register str, Register dest,
1421 CharEncoding encoding) {
1422 MOZ_ASSERT(str != dest);
1423
1424 if (JitOptions.spectreStringMitigations) {
1425 // Making this Spectre-safe is a bit complicated: using
1426 // computeEffectiveAddress and then zeroing the output register if
1427 // non-inline is not sufficient: when the index is very large, it would
1428 // allow reading |nullptr + index|. Just fall back to loadStringChars
1429 // for now.
1430 loadStringChars(str, dest, encoding);
1431 } else {
1432 computeEffectiveAddress(
1433 Address(str, JSInlineString::offsetOfInlineStorage()), dest);
1434 }
1435 }
1436
1437 void MacroAssembler::loadRopeLeftChild(Register str, Register dest) {
1438 MOZ_ASSERT(str != dest);
1439
1440 if (JitOptions.spectreStringMitigations) {
1441 // Zero the output register if the input was not a rope.
1442 movePtr(ImmWord(0), dest);
1443 test32LoadPtr(Assembler::Zero, Address(str, JSString::offsetOfFlags()),
1444 Imm32(JSString::LINEAR_BIT),
1445 Address(str, JSRope::offsetOfLeft()), dest);
1446 } else {
1447 loadPtr(Address(str, JSRope::offsetOfLeft()), dest);
1448 }
1449 }
1450
1451 void MacroAssembler::loadRopeRightChild(Register str, Register dest) {
1452 MOZ_ASSERT(str != dest);
1453
1454 if (JitOptions.spectreStringMitigations) {
1455 // Zero the output register if the input was not a rope.
1456 movePtr(ImmWord(0), dest);
1457 test32LoadPtr(Assembler::Zero, Address(str, JSString::offsetOfFlags()),
1458 Imm32(JSString::LINEAR_BIT),
1459 Address(str, JSRope::offsetOfRight()), dest);
1460 } else {
1461 loadPtr(Address(str, JSRope::offsetOfRight()), dest);
1462 }
1463 }
1464
1465 void MacroAssembler::storeRopeChildren(Register left, Register right,
1466 Register str) {
1467 storePtr(left, Address(str, JSRope::offsetOfLeft()));
1468 storePtr(right, Address(str, JSRope::offsetOfRight()));
1469 }
1470
1471 void MacroAssembler::loadDependentStringBase(Register str, Register dest) {
1472 MOZ_ASSERT(str != dest);
1473
1474 if (JitOptions.spectreStringMitigations) {
1475 // If the string is not a dependent string, zero the |str| register.
1476 // The code below loads str->base so this should block speculative
1477 // execution.
1478 movePtr(ImmWord(0), dest);
1479 test32MovePtr(Assembler::Zero, Address(str, JSString::offsetOfFlags()),
1480 Imm32(JSString::DEPENDENT_BIT), dest, str);
1481 }
1482
1483 loadPtr(Address(str, JSDependentString::offsetOfBase()), dest);
1484 }
1485
1486 void MacroAssembler::storeDependentStringBase(Register base, Register str) {
1487 storePtr(base, Address(str, JSDependentString::offsetOfBase()));
1488 }
1489
1490 void MacroAssembler::branchIfMaybeSplitSurrogatePair(Register leftChild,
1491 Register index,
1492 Register scratch,
1493 Label* maybeSplit,
1494 Label* notSplit) {
1495 // If |index| is the last character of the left child and the left child
1496 // is a two-byte string, it's possible that a surrogate pair is split
1497 // between the left and right child of a rope.
1498
1499 // Can't be a split surrogate when the left child is a Latin-1 string.
1500 branchLatin1String(leftChild, notSplit);
1501
1502 // Can't be a split surrogate when |index + 1| is in the left child.
1503 add32(Imm32(1), index, scratch);
1504 branch32(Assembler::Above, Address(leftChild, JSString::offsetOfLength()),
1505 scratch, notSplit);
1506
1507 // Jump to |maybeSplit| if the left child is another rope.
1508 branchIfRope(leftChild, maybeSplit);
1509
1510 // Load the character at |index|.
1511 loadStringChars(leftChild, scratch, CharEncoding::TwoByte);
1512 loadChar(scratch, index, scratch, CharEncoding::TwoByte);
1513
1514 // Jump to |maybeSplit| if the last character is a lead surrogate.
1515 branchIfLeadSurrogate(scratch, scratch, maybeSplit);
1516 }
1517
1518 void MacroAssembler::loadRopeChild(CharKind kind, Register str, Register index,
1519 Register output, Register maybeScratch,
1520 Label* isLinear, Label* splitSurrogate) {
1521 // This follows JSString::getChar.
1522 branchIfNotRope(str, isLinear);
1523
1524 loadRopeLeftChild(str, output);
1525
1526 Label loadedChild;
1527 if (kind == CharKind::CharCode) {
1528 // Check if |index| is contained in the left child.
1529 branch32(Assembler::Above, Address(output, JSString::offsetOfLength()),
1530 index, &loadedChild);
1531 } else {
1532 MOZ_ASSERT(maybeScratch != InvalidReg);
1533
1534 // Check if |index| is contained in the left child.
1535 Label loadRight;
1536 branch32(Assembler::BelowOrEqual,
1537 Address(output, JSString::offsetOfLength()), index, &loadRight);
1538 {
1539 // Handle possible split surrogate pairs.
1540 branchIfMaybeSplitSurrogatePair(output, index, maybeScratch,
1541 splitSurrogate, &loadedChild);
1542 jump(&loadedChild);
1543 }
1544 bind(&loadRight);
1545 }
1546
1547 // The index must be in the rightChild.
1548 loadRopeRightChild(str, output);
1549
1550 bind(&loadedChild);
1551 }
1552
1553 void MacroAssembler::branchIfCanLoadStringChar(CharKind kind, Register str,
1554 Register index, Register scratch,
1555 Register maybeScratch,
1556 Label* label) {
1557 Label splitSurrogate;
1558 loadRopeChild(kind, str, index, scratch, maybeScratch, label,
1559 &splitSurrogate);
1560
1561 // Branch if the left resp. right side is linear.
1562 branchIfNotRope(scratch, label);
1563
1564 if (kind == CharKind::CodePoint) {
1565 bind(&splitSurrogate);
1566 }
1567 }
1568
1569 void MacroAssembler::branchIfNotCanLoadStringChar(CharKind kind, Register str,
1570 Register index,
1571 Register scratch,
1572 Register maybeScratch,
1573 Label* label) {
1574 Label done;
1575 loadRopeChild(kind, str, index, scratch, maybeScratch, &done, label);
1576
1577 // Branch if the left or right side is another rope.
1578 branchIfRope(scratch, label);
1579
1580 bind(&done);
1581 }
1582
1583 void MacroAssembler::loadStringChar(CharKind kind, Register str, Register index,
1584 Register output, Register scratch1,
1585 Register scratch2, Label* fail) {
1586 MOZ_ASSERT(str != output);
1587 MOZ_ASSERT(str != index);
1588 MOZ_ASSERT(index != output);
1589 MOZ_ASSERT_IF(kind == CharKind::CodePoint, index != scratch1);
1590 MOZ_ASSERT(output != scratch1);
1591 MOZ_ASSERT(output != scratch2);
1592
1593 // Use scratch1 for the index (adjusted below).
1594 if (index != scratch1) {
1595 move32(index, scratch1);
1596 }
1597 movePtr(str, output);
1598
1599 // This follows JSString::getChar.
1600 Label notRope;
1601 branchIfNotRope(str, &notRope);
1602
1603 loadRopeLeftChild(str, output);
1604
1605 // Check if the index is contained in the leftChild.
1606 Label loadedChild, notInLeft;
1607 spectreBoundsCheck32(scratch1, Address(output, JSString::offsetOfLength()),
1608 scratch2, &notInLeft);
1609 if (kind == CharKind::CodePoint) {
1610 branchIfMaybeSplitSurrogatePair(output, scratch1, scratch2, fail,
1611 &loadedChild);
1612 }
1613 jump(&loadedChild);
1614
1615 // The index must be in the rightChild.
1616 // index -= rope->leftChild()->length()
1617 bind(&notInLeft);
1618 sub32(Address(output, JSString::offsetOfLength()), scratch1);
1619 loadRopeRightChild(str, output);
1620
1621 // If the left or right side is another rope, give up.
1622 bind(&loadedChild);
1623 branchIfRope(output, fail);
1624
1625 bind(&notRope);
1626
1627 Label isLatin1, done;
1628 branchLatin1String(output, &isLatin1);
1629 {
1630 loadStringChars(output, scratch2, CharEncoding::TwoByte);
1631
1632 if (kind == CharKind::CharCode) {
1633 loadChar(scratch2, scratch1, output, CharEncoding::TwoByte);
1634 } else {
1635 // Load the first character.
1636 addToCharPtr(scratch2, scratch1, CharEncoding::TwoByte);
1637 loadChar(Address(scratch2, 0), output, CharEncoding::TwoByte);
1638
1639 // If the first character isn't a lead surrogate, go to |done|.
1640 branchIfNotLeadSurrogate(output, &done);
1641
1642 // branchIfMaybeSplitSurrogatePair ensures that the surrogate pair can't
1643 // split between two rope children. So if |index + 1 < str.length|, then
1644 // |index| and |index + 1| are in the same rope child.
1645 //
1646 // NB: We use the non-adjusted |index| and |str| inputs, because |output|
1647 // was overwritten and no longer contains the rope child.
1648
1649 // If |index + 1| is a valid index into |str|.
1650 add32(Imm32(1), index, scratch1);
1651 spectreBoundsCheck32(scratch1, Address(str, JSString::offsetOfLength()),
1652 InvalidReg, &done);
1653
1654 // Then load the next character at |scratch2 + sizeof(char16_t)|.
1655 loadChar(Address(scratch2, sizeof(char16_t)), scratch1,
1656 CharEncoding::TwoByte);
1657
1658 // If the next character isn't a trail surrogate, go to |done|.
1659 branchIfNotTrailSurrogate(scratch1, scratch2, &done);
1660
1661 // Inlined unicode::UTF16Decode(char16_t, char16_t).
1662 lshift32(Imm32(10), output);
1663 add32(Imm32(unicode::NonBMPMin - (unicode::LeadSurrogateMin << 10) -
1664 unicode::TrailSurrogateMin),
1665 scratch1);
1666 add32(scratch1, output);
1667 }
1668
1669 jump(&done);
1670 }
1671 bind(&isLatin1);
1672 {
1673 loadStringChars(output, scratch2, CharEncoding::Latin1);
1674 loadChar(scratch2, scratch1, output, CharEncoding::Latin1);
1675 }
1676
1677 bind(&done);
1678 }
1679
1680 void MacroAssembler::loadStringChar(Register str, int32_t index,
1681 Register output, Register scratch1,
1682 Register scratch2, Label* fail) {
1683 MOZ_ASSERT(str != output);
1684 MOZ_ASSERT(output != scratch1);
1685 MOZ_ASSERT(output != scratch2);
1686
1687 if (index == 0) {
1688 movePtr(str, scratch1);
1689
1690 // This follows JSString::getChar.
1691 Label notRope;
1692 branchIfNotRope(str, &notRope);
1693
1694 loadRopeLeftChild(str, scratch1);
1695
1696 // Rope children can't be empty, so the index can't be in the right side.
1697
1698 // If the left side is another rope, give up.
1699 branchIfRope(scratch1, fail);
1700
1701 bind(&notRope);
1702
1703 Label isLatin1, done;
1704 branchLatin1String(scratch1, &isLatin1);
1705 loadStringChars(scratch1, scratch2, CharEncoding::TwoByte);
1706 loadChar(Address(scratch2, 0), output, CharEncoding::TwoByte);
1707 jump(&done);
1708
1709 bind(&isLatin1);
1710 loadStringChars(scratch1, scratch2, CharEncoding::Latin1);
1711 loadChar(Address(scratch2, 0), output, CharEncoding::Latin1);
1712
1713 bind(&done);
1714 } else {
1715 move32(Imm32(index), scratch1);
1716 loadStringChar(str, scratch1, output, scratch1, scratch2, fail);
1717 }
1718 }
1719
1720 void MacroAssembler::loadStringIndexValue(Register str, Register dest,
1721 Label* fail) {
1722 MOZ_ASSERT(str != dest);
1723
1724 load32(Address(str, JSString::offsetOfFlags()), dest);
1725
1726 // Does not have a cached index value.
1727 branchTest32(Assembler::Zero, dest, Imm32(JSString::INDEX_VALUE_BIT), fail);
1728
1729 // Extract the index.
1730 rshift32(Imm32(JSString::INDEX_VALUE_SHIFT), dest);
1731 }
1732
1733 void MacroAssembler::loadChar(Register chars, Register index, Register dest,
1734 CharEncoding encoding, int32_t offset /* = 0 */) {
1735 if (encoding == CharEncoding::Latin1) {
1736 loadChar(BaseIndex(chars, index, TimesOne, offset), dest, encoding);
1737 } else {
1738 loadChar(BaseIndex(chars, index, TimesTwo, offset), dest, encoding);
1739 }
1740 }
1741
1742 void MacroAssembler::addToCharPtr(Register chars, Register index,
1743 CharEncoding encoding) {
1744 if (encoding == CharEncoding::Latin1) {
1745 static_assert(sizeof(char) == 1,
1746 "Latin-1 string index shouldn't need scaling");
1747 addPtr(index, chars);
1748 } else {
1749 computeEffectiveAddress(BaseIndex(chars, index, TimesTwo), chars);
1750 }
1751 }
1752
1753 void MacroAssembler::branchIfNotLeadSurrogate(Register src, Label* label) {
1754 branch32(Assembler::Below, src, Imm32(unicode::LeadSurrogateMin), label);
1755 branch32(Assembler::Above, src, Imm32(unicode::LeadSurrogateMax), label);
1756 }
1757
1758 void MacroAssembler::branchSurrogate(Assembler::Condition cond, Register src,
1759 Register scratch, Label* label,
1760 SurrogateChar surrogateChar) {
1761 // For TrailSurrogateMin ≤ x ≤ TrailSurrogateMax and
1762 // LeadSurrogateMin ≤ x ≤ LeadSurrogateMax, the following equations hold.
1763 //
1764 // SurrogateMin ≤ x ≤ SurrogateMax
1765 // <> SurrogateMin ≤ x ≤ SurrogateMin + 2^10 - 1
1766 // <> ((x - SurrogateMin) >>> 10) = 0 where >>> is an unsigned-shift
1767 // See Hacker's Delight, section 4-1 for details.
1768 //
1769 // ((x - SurrogateMin) >>> 10) = 0
1770 // <> floor((x - SurrogateMin) / 1024) = 0
1771 // <> floor((x / 1024) - (SurrogateMin / 1024)) = 0
1772 // <> floor(x / 1024) = SurrogateMin / 1024
1773 // <> floor(x / 1024) * 1024 = SurrogateMin
1774 // <> (x >>> 10) << 10 = SurrogateMin
1775 // <> x & ~(2^10 - 1) = SurrogateMin
1776
1777 constexpr char16_t SurrogateMask = 0xFC00;
1778 char16_t SurrogateMin = surrogateChar == SurrogateChar::Lead
1779 ? unicode::LeadSurrogateMin
1780 : unicode::TrailSurrogateMin;
1781
1782 and32(Imm32(SurrogateMask), src, scratch);
1783 branch32(cond, scratch, Imm32(SurrogateMin), label);
1784 }
1785
1786 void MacroAssembler::loadStringFromUnit(Register unit, Register dest,
1787 const StaticStrings& staticStrings) {
1788 movePtr(ImmPtr(&staticStrings.unitStaticTable), dest);
1789 loadPtr(BaseIndex(dest, unit, ScalePointer), dest);
1790 }
1791
1792 void MacroAssembler::loadLengthTwoString(Register c1, Register c2,
1793 Register dest,
1794 const StaticStrings& staticStrings) {
1795 // Compute (toSmallCharTable[c1] << SMALL_CHAR_BITS) + toSmallCharTable[c2]
1796 // to obtain the index into `StaticStrings::length2StaticTable`.
1797 static_assert(sizeof(StaticStrings::SmallChar) == 1);
1798
1799 movePtr(ImmPtr(&StaticStrings::toSmallCharTable.storage), dest);
1800 load8ZeroExtend(BaseIndex(dest, c1, Scale::TimesOne), c1);
1801 load8ZeroExtend(BaseIndex(dest, c2, Scale::TimesOne), c2);
1802
1803 lshift32(Imm32(StaticStrings::SMALL_CHAR_BITS), c1);
1804 add32(c2, c1);
1805
1806 // Look up the string from the computed index.
1807 movePtr(ImmPtr(&staticStrings.length2StaticTable), dest);
1808 loadPtr(BaseIndex(dest, c1, ScalePointer), dest);
1809 }
1810
1811 void MacroAssembler::lookupStaticString(Register ch, Register dest,
1812 const StaticStrings& staticStrings) {
1813 MOZ_ASSERT(ch != dest);
1814
1815 movePtr(ImmPtr(&staticStrings.unitStaticTable), dest);
1816 loadPtr(BaseIndex(dest, ch, ScalePointer), dest);
1817 }
1818
1819 void MacroAssembler::lookupStaticString(Register ch, Register dest,
1820 const StaticStrings& staticStrings,
1821 Label* fail) {
1822 MOZ_ASSERT(ch != dest);
1823
1824 boundsCheck32PowerOfTwo(ch, StaticStrings::UNIT_STATIC_LIMIT, fail);
1825 movePtr(ImmPtr(&staticStrings.unitStaticTable), dest);
1826 loadPtr(BaseIndex(dest, ch, ScalePointer), dest);
1827 }
1828
1829 void MacroAssembler::lookupStaticString(Register ch1, Register ch2,
1830 Register dest,
1831 const StaticStrings& staticStrings,
1832 Label* fail) {
1833 MOZ_ASSERT(ch1 != dest);
1834 MOZ_ASSERT(ch2 != dest);
1835
1836 branch32(Assembler::AboveOrEqual, ch1,
1837 Imm32(StaticStrings::SMALL_CHAR_TABLE_SIZE), fail);
1838 branch32(Assembler::AboveOrEqual, ch2,
1839 Imm32(StaticStrings::SMALL_CHAR_TABLE_SIZE), fail);
1840
1841 movePtr(ImmPtr(&StaticStrings::toSmallCharTable.storage), dest);
1842 load8ZeroExtend(BaseIndex(dest, ch1, Scale::TimesOne), ch1);
1843 load8ZeroExtend(BaseIndex(dest, ch2, Scale::TimesOne), ch2);
1844
1845 branch32(Assembler::Equal, ch1, Imm32(StaticStrings::INVALID_SMALL_CHAR),
1846 fail);
1847 branch32(Assembler::Equal, ch2, Imm32(StaticStrings::INVALID_SMALL_CHAR),
1848 fail);
1849
1850 lshift32(Imm32(StaticStrings::SMALL_CHAR_BITS), ch1);
1851 add32(ch2, ch1);
1852
1853 // Look up the string from the computed index.
1854 movePtr(ImmPtr(&staticStrings.length2StaticTable), dest);
1855 loadPtr(BaseIndex(dest, ch1, ScalePointer), dest);
1856 }
1857
1858 void MacroAssembler::lookupStaticIntString(Register integer, Register dest,
1859 Register scratch,
1860 const StaticStrings& staticStrings,
1861 Label* fail) {
1862 MOZ_ASSERT(integer != scratch);
1863
1864 boundsCheck32PowerOfTwo(integer, StaticStrings::INT_STATIC_LIMIT, fail);
1865 movePtr(ImmPtr(&staticStrings.intStaticTable), scratch);
1866 loadPtr(BaseIndex(scratch, integer, ScalePointer), dest);
1867 }
1868
1869 void MacroAssembler::loadInt32ToStringWithBase(
1870 Register input, Register base, Register dest, Register scratch1,
1871 Register scratch2, const StaticStrings& staticStrings,
1872 const LiveRegisterSet& volatileRegs, bool lowerCase, Label* fail) {
1873 #ifdef DEBUG
1874 Label baseBad, baseOk;
1875 branch32(Assembler::LessThan, base, Imm32(2), &baseBad);
1876 branch32(Assembler::LessThanOrEqual, base, Imm32(36), &baseOk);
1877 bind(&baseBad);
1878 assumeUnreachable("base must be in range [2, 36]");
1879 bind(&baseOk);
1880 #endif
1881
1882 // Compute |"0123456789abcdefghijklmnopqrstuvwxyz"[r]|.
1883 auto toChar = [this, base, lowerCase](Register r) {
1884 #ifdef DEBUG
1885 Label ok;
1886 branch32(Assembler::Below, r, base, &ok);
1887 assumeUnreachable("bad digit");
1888 bind(&ok);
1889 #else
1890 // Silence unused lambda capture warning.
1891 (void)base;
1892 #endif
1893
1894 Label done;
1895 add32(Imm32('0'), r);
1896 branch32(Assembler::BelowOrEqual, r, Imm32('9'), &done);
1897 add32(Imm32((lowerCase ? 'a' : 'A') - '0' - 10), r);
1898 bind(&done);
1899 };
1900
1901 // Perform a "unit" lookup when |unsigned(input) < unsigned(base)|.
1902 Label lengthTwo, done;
1903 branch32(Assembler::AboveOrEqual, input, base, &lengthTwo);
1904 {
1905 move32(input, scratch1);
1906 toChar(scratch1);
1907
1908 loadStringFromUnit(scratch1, dest, staticStrings);
1909
1910 jump(&done);
1911 }
1912 bind(&lengthTwo);
1913
1914 // Compute |base * base|.
1915 move32(base, scratch1);
1916 mul32(scratch1, scratch1);
1917
1918 // Perform a "length2" lookup when |unsigned(input) < unsigned(base * base)|.
1919 branch32(Assembler::AboveOrEqual, input, scratch1, fail);
1920 {
1921 // Compute |scratch1 = input / base| and |scratch2 = input % base|.
1922 move32(input, scratch1);
1923 flexibleDivMod32(base, scratch1, scratch2, true, volatileRegs);
1924
1925 // Compute the digits of the divisor and remainder.
1926 toChar(scratch1);
1927 toChar(scratch2);
1928
1929 // Look up the 2-character digit string in the small-char table.
1930 loadLengthTwoString(scratch1, scratch2, dest, staticStrings);
1931 }
1932 bind(&done);
1933 }
1934
1935 void MacroAssembler::loadInt32ToStringWithBase(
1936 Register input, int32_t base, Register dest, Register scratch1,
1937 Register scratch2, const StaticStrings& staticStrings, bool lowerCase,
1938 Label* fail) {
1939 MOZ_ASSERT(2 <= base && base <= 36, "base must be in range [2, 36]");
1940
1941 // Compute |"0123456789abcdefghijklmnopqrstuvwxyz"[r]|.
1942 auto toChar = [this, base, lowerCase](Register r) {
1943 #ifdef DEBUG
1944 Label ok;
1945 branch32(Assembler::Below, r, Imm32(base), &ok);
1946 assumeUnreachable("bad digit");
1947 bind(&ok);
1948 #endif
1949
1950 if (base <= 10) {
1951 add32(Imm32('0'), r);
1952 } else {
1953 Label done;
1954 add32(Imm32('0'), r);
1955 branch32(Assembler::BelowOrEqual, r, Imm32('9'), &done);
1956 add32(Imm32((lowerCase ? 'a' : 'A') - '0' - 10), r);
1957 bind(&done);
1958 }
1959 };
1960
1961 // Perform a "unit" lookup when |unsigned(input) < unsigned(base)|.
1962 Label lengthTwo, done;
1963 branch32(Assembler::AboveOrEqual, input, Imm32(base), &lengthTwo);
1964 {
1965 move32(input, scratch1);
1966 toChar(scratch1);
1967
1968 loadStringFromUnit(scratch1, dest, staticStrings);
1969
1970 jump(&done);
1971 }
1972 bind(&lengthTwo);
1973
1974 // Perform a "length2" lookup when |unsigned(input) < unsigned(base * base)|.
1975 branch32(Assembler::AboveOrEqual, input, Imm32(base * base), fail);
1976 {
1977 // Compute |scratch1 = input / base| and |scratch2 = input % base|.
1978 if (mozilla::IsPowerOfTwo(uint32_t(base))) {
1979 uint32_t shift = mozilla::FloorLog2(base);
1980
1981 rshift32(Imm32(shift), input, scratch1);
1982 and32(Imm32((uint32_t(1) << shift) - 1), input, scratch2);
1983 } else {
1984 // The following code matches CodeGenerator::visitUDivOrModConstant()
1985 // for x86-shared. Also see Hacker's Delight 2nd edition, chapter 10-8
1986 // "Unsigned Division by 7" for the case when |rmc.multiplier| exceeds
1987 // UINT32_MAX and we need to adjust the shift amount.
1988
1989 auto rmc = ReciprocalMulConstants::computeUnsignedDivisionConstants(base);
1990
1991 // We first compute |q = (M * n) >> 32), where M = rmc.multiplier.
1992 mulHighUnsigned32(Imm32(rmc.multiplier), input, scratch1);
1993
1994 if (rmc.multiplier > UINT32_MAX) {
1995 // M >= 2^32 and shift == 0 is impossible, as d >= 2 implies that
1996 // ((M * n) >> (32 + shift)) >= n > floor(n/d) whenever n >= d,
1997 // contradicting the proof of correctness in computeDivisionConstants.
1998 MOZ_ASSERT(rmc.shiftAmount > 0);
1999 MOZ_ASSERT(rmc.multiplier < (int64_t(1) << 33));
2000
2001 // Compute |t = (n - q) / 2|.
2002 move32(input, scratch2);
2003 sub32(scratch1, scratch2);
2004 rshift32(Imm32(1), scratch2);
2005
2006 // Compute |t = (n - q) / 2 + q = (n + q) / 2|.
2007 add32(scratch2, scratch1);
2008
2009 // Finish the computation |q = floor(n / d)|.
2010 rshift32(Imm32(rmc.shiftAmount - 1), scratch1);
2011 } else {
2012 rshift32(Imm32(rmc.shiftAmount), scratch1);
2013 }
2014
2015 // Compute the remainder from |r = n - q * d|.
2016 move32(scratch1, dest);
2017 mul32(Imm32(base), dest);
2018 move32(input, scratch2);
2019 sub32(dest, scratch2);
2020 }
2021
2022 // Compute the digits of the divisor and remainder.
2023 toChar(scratch1);
2024 toChar(scratch2);
2025
2026 // Look up the 2-character digit string in the small-char table.
2027 loadLengthTwoString(scratch1, scratch2, dest, staticStrings);
2028 }
2029 bind(&done);
2030 }
2031
2032 void MacroAssembler::loadBigIntDigits(Register bigInt, Register digits) {
2033 MOZ_ASSERT(digits != bigInt);
2034
2035 // Load the inline digits.
2036 computeEffectiveAddress(Address(bigInt, BigInt::offsetOfInlineDigits()),
2037 digits);
2038
2039 // If inline digits aren't used, load the heap digits. Use a conditional move
2040 // to prevent speculative execution.
2041 cmp32LoadPtr(Assembler::Above, Address(bigInt, BigInt::offsetOfLength()),
2042 Imm32(int32_t(BigInt::inlineDigitsLength())),
2043 Address(bigInt, BigInt::offsetOfHeapDigits()), digits);
2044 }
2045
2046 void MacroAssembler::loadBigInt64(Register bigInt, Register64 dest) {
2047 // This code follows the implementation of |BigInt::toUint64()|. We're also
2048 // using it for inline callers of |BigInt::toInt64()|, which works, because
2049 // all supported Jit architectures use a two's complement representation for
2050 // int64 values, which means the WrapToSigned call in toInt64() is a no-op.
2051
2052 Label done, nonZero;
2053
2054 branchIfBigIntIsNonZero(bigInt, &nonZero);
2055 {
2056 move64(Imm64(0), dest);
2057 jump(&done);
2058 }
2059 bind(&nonZero);
2060
2061 #ifdef JS_PUNBOX64
2062 Register digits = dest.reg;
2063 #else
2064 Register digits = dest.high;
2065 #endif
2066
2067 loadBigIntDigits(bigInt, digits);
2068
2069 #if JS_PUNBOX64
2070 // Load the first digit into the destination register.
2071 load64(Address(digits, 0), dest);
2072 #else
2073 // Load the first digit into the destination register's low value.
2074 load32(Address(digits, 0), dest.low);
2075
2076 // And conditionally load the second digit into the high value register.
2077 Label twoDigits, digitsDone;
2078 branch32(Assembler::Above, Address(bigInt, BigInt::offsetOfLength()),
2079 Imm32(1), &twoDigits);
2080 {
2081 move32(Imm32(0), dest.high);
2082 jump(&digitsDone);
2083 }
2084 {
2085 bind(&twoDigits);
2086 load32(Address(digits, sizeof(BigInt::Digit)), dest.high);
2087 }
2088 bind(&digitsDone);
2089 #endif
2090
2091 branchTest32(Assembler::Zero, Address(bigInt, BigInt::offsetOfFlags()),
2092 Imm32(BigInt::signBitMask()), &done);
2093 neg64(dest);
2094
2095 bind(&done);
2096 }
2097
2098 void MacroAssembler::loadBigIntDigit(Register bigInt, Register dest) {
2099 Label done, nonZero;
2100 branchIfBigIntIsNonZero(bigInt, &nonZero);
2101 {
2102 movePtr(ImmWord(0), dest);
2103 jump(&done);
2104 }
2105 bind(&nonZero);
2106
2107 loadBigIntDigits(bigInt, dest);
2108
2109 // Load the first digit into the destination register.
2110 loadPtr(Address(dest, 0), dest);
2111
2112 bind(&done);
2113 }
2114
2115 void MacroAssembler::loadBigIntDigit(Register bigInt, Register dest,
2116 Label* fail) {
2117 MOZ_ASSERT(bigInt != dest);
2118
2119 branch32(Assembler::Above, Address(bigInt, BigInt::offsetOfLength()),
2120 Imm32(1), fail);
2121
2122 static_assert(BigInt::inlineDigitsLength() > 0,
2123 "Single digit BigInts use inline storage");
2124
2125 // Load the first inline digit into the destination register.
2126 movePtr(ImmWord(0), dest);
2127 cmp32LoadPtr(Assembler::NotEqual, Address(bigInt, BigInt::offsetOfLength()),
2128 Imm32(0), Address(bigInt, BigInt::offsetOfInlineDigits()), dest);
2129 }
2130
2131 void MacroAssembler::loadBigIntPtr(Register bigInt, Register dest,
2132 Label* fail) {
2133 loadBigIntDigit(bigInt, dest, fail);
2134
2135 // BigInt digits are stored as unsigned numbers. Take the failure path when
2136 // the digit can't be stored in intptr_t.
2137
2138 Label nonNegative, done;
2139 branchIfBigIntIsNonNegative(bigInt, &nonNegative);
2140 {
2141 // Negate |dest| when the BigInt is negative.
2142 negPtr(dest);
2143
2144 // Test after negating to handle INTPTR_MIN correctly.
2145 branchTestPtr(Assembler::NotSigned, dest, dest, fail);
2146 jump(&done);
2147 }
2148 bind(&nonNegative);
2149 branchTestPtr(Assembler::Signed, dest, dest, fail);
2150 bind(&done);
2151 }
2152
2153 void MacroAssembler::initializeBigInt64(Scalar::Type type, Register bigInt,
2154 Register64 val, Register64 temp) {
2155 MOZ_ASSERT(Scalar::isBigIntType(type));
2156
2157 store32(Imm32(0), Address(bigInt, BigInt::offsetOfFlags()));
2158
2159 Label done, nonZero;
2160 branch64(Assembler::NotEqual, val, Imm64(0), &nonZero);
2161 {
2162 store32(Imm32(0), Address(bigInt, BigInt::offsetOfLength()));
2163 jump(&done);
2164 }
2165 bind(&nonZero);
2166
2167 if (type == Scalar::BigInt64) {
2168 // Copy the input when we're not allowed to clobber it.
2169 if (temp != Register64::Invalid()) {
2170 move64(val, temp);
2171 val = temp;
2172 }
2173
2174 // Set the sign-bit for negative values and then continue with the two's
2175 // complement.
2176 Label isPositive;
2177 branch64(Assembler::GreaterThan, val, Imm64(0), &isPositive);
2178 {
2179 store32(Imm32(BigInt::signBitMask()),
2180 Address(bigInt, BigInt::offsetOfFlags()));
2181 neg64(val);
2182 }
2183 bind(&isPositive);
2184 }
2185
2186 store32(Imm32(1), Address(bigInt, BigInt::offsetOfLength()));
2187
2188 static_assert(sizeof(BigInt::Digit) == sizeof(uintptr_t),
2189 "BigInt Digit size matches uintptr_t, so there's a single "
2190 "store on 64-bit and up to two stores on 32-bit");
2191
2192 #ifndef JS_PUNBOX64
2193 Label singleDigit;
2194 branchTest32(Assembler::Zero, val.high, val.high, &singleDigit);
2195 store32(Imm32(2), Address(bigInt, BigInt::offsetOfLength()));
2196 bind(&singleDigit);
2197
2198 // We can perform a single store64 on 32-bit platforms, because inline
2199 // storage can store at least two 32-bit integers.
2200 static_assert(BigInt::inlineDigitsLength() >= 2,
2201 "BigInt inline storage can store at least two digits");
2202 #endif
2203
2204 store64(val, Address(bigInt, js::BigInt::offsetOfInlineDigits()));
2205
2206 bind(&done);
2207 }
2208
2209 void MacroAssembler::initializeBigIntPtr(Register bigInt, Register val) {
2210 store32(Imm32(0), Address(bigInt, BigInt::offsetOfFlags()));
2211
2212 Label done, nonZero;
2213 branchTestPtr(Assembler::NonZero, val, val, &nonZero);
2214 {
2215 store32(Imm32(0), Address(bigInt, BigInt::offsetOfLength()));
2216 jump(&done);
2217 }
2218 bind(&nonZero);
2219
2220 // Set the sign-bit for negative values and then continue with the two's
2221 // complement.
2222 Label isPositive;
2223 branchTestPtr(Assembler::NotSigned, val, val, &isPositive);
2224 {
2225 store32(Imm32(BigInt::signBitMask()),
2226 Address(bigInt, BigInt::offsetOfFlags()));
2227 negPtr(val);
2228 }
2229 bind(&isPositive);
2230
2231 store32(Imm32(1), Address(bigInt, BigInt::offsetOfLength()));
2232
2233 static_assert(sizeof(BigInt::Digit) == sizeof(uintptr_t),
2234 "BigInt Digit size matches uintptr_t");
2235
2236 storePtr(val, Address(bigInt, js::BigInt::offsetOfInlineDigits()));
2237
2238 bind(&done);
2239 }
2240
2241 void MacroAssembler::copyBigIntWithInlineDigits(Register src, Register dest,
2242 Register temp,
2243 gc::Heap initialHeap,
2244 Label* fail) {
2245 branch32(Assembler::Above, Address(src, BigInt::offsetOfLength()),
2246 Imm32(int32_t(BigInt::inlineDigitsLength())), fail);
2247
2248 newGCBigInt(dest, temp, initialHeap, fail);
2249
2250 // Copy the sign-bit, but not any of the other bits used by the GC.
2251 load32(Address(src, BigInt::offsetOfFlags()), temp);
2252 and32(Imm32(BigInt::signBitMask()), temp);
2253 store32(temp, Address(dest, BigInt::offsetOfFlags()));
2254
2255 // Copy the length.
2256 load32(Address(src, BigInt::offsetOfLength()), temp);
2257 store32(temp, Address(dest, BigInt::offsetOfLength()));
2258
2259 // Copy the digits.
2260 Address srcDigits(src, js::BigInt::offsetOfInlineDigits());
2261 Address destDigits(dest, js::BigInt::offsetOfInlineDigits());
2262
2263 for (size_t i = 0; i < BigInt::inlineDigitsLength(); i++) {
2264 static_assert(sizeof(BigInt::Digit) == sizeof(uintptr_t),
2265 "BigInt Digit size matches uintptr_t");
2266
2267 loadPtr(srcDigits, temp);
2268 storePtr(temp, destDigits);
2269
2270 srcDigits = Address(src, srcDigits.offset + sizeof(BigInt::Digit));
2271 destDigits = Address(dest, destDigits.offset + sizeof(BigInt::Digit));
2272 }
2273 }
2274
2275 void MacroAssembler::compareBigIntAndInt32(JSOp op, Register bigInt,
2276 Register int32, Register scratch1,
2277 Register scratch2, Label* ifTrue,
2278 Label* ifFalse) {
2279 MOZ_ASSERT(IsLooseEqualityOp(op) || IsRelationalOp(op));
2280
2281 static_assert(std::is_same_v<BigInt::Digit, uintptr_t>,
2282 "BigInt digit can be loaded in a pointer-sized register");
2283 static_assert(sizeof(BigInt::Digit) >= sizeof(uint32_t),
2284 "BigInt digit stores at least an uint32");
2285
2286 // Test for too large numbers.
2287 //
2288 // If the unsigned value of the BigInt can't be expressed in an uint32/uint64,
2289 // the result of the comparison is a constant.
2290 if (op == JSOp::Eq || op == JSOp::Ne) {
2291 Label* tooLarge = op == JSOp::Eq ? ifFalse : ifTrue;
2292 branch32(Assembler::GreaterThan,
2293 Address(bigInt, BigInt::offsetOfDigitLength()), Imm32(1),
2294 tooLarge);
2295 } else {
2296 Label doCompare;
2297 branch32(Assembler::LessThanOrEqual,
2298 Address(bigInt, BigInt::offsetOfDigitLength()), Imm32(1),
2299 &doCompare);
2300
2301 // Still need to take the sign-bit into account for relational operations.
2302 if (op == JSOp::Lt || op == JSOp::Le) {
2303 branchIfBigIntIsNegative(bigInt, ifTrue);
2304 jump(ifFalse);
2305 } else {
2306 branchIfBigIntIsNegative(bigInt, ifFalse);
2307 jump(ifTrue);
2308 }
2309
2310 bind(&doCompare);
2311 }
2312
2313 // Test for mismatched signs and, if the signs are equal, load |abs(x)| in
2314 // |scratch1| and |abs(y)| in |scratch2| and then compare the unsigned numbers
2315 // against each other.
2316 {
2317 // Jump to |ifTrue| resp. |ifFalse| if the BigInt is strictly less than
2318 // resp. strictly greater than the int32 value, depending on the comparison
2319 // operator.
2320 Label* greaterThan;
2321 Label* lessThan;
2322 if (op == JSOp::Eq) {
2323 greaterThan = ifFalse;
2324 lessThan = ifFalse;
2325 } else if (op == JSOp::Ne) {
2326 greaterThan = ifTrue;
2327 lessThan = ifTrue;
2328 } else if (op == JSOp::Lt || op == JSOp::Le) {
2329 greaterThan = ifFalse;
2330 lessThan = ifTrue;
2331 } else {
2332 MOZ_ASSERT(op == JSOp::Gt || op == JSOp::Ge);
2333 greaterThan = ifTrue;
2334 lessThan = ifFalse;
2335 }
2336
2337 // BigInt digits are always stored as an unsigned number.
2338 loadBigIntDigit(bigInt, scratch1);
2339
2340 // Load the int32 into |scratch2| and negate it for negative numbers.
2341 move32(int32, scratch2);
2342
2343 Label isNegative, doCompare;
2344 branchIfBigIntIsNegative(bigInt, &isNegative);
2345 branch32(Assembler::LessThan, int32, Imm32(0), greaterThan);
2346 jump(&doCompare);
2347
2348 // We rely on |neg32(INT32_MIN)| staying INT32_MIN, because we're using an
2349 // unsigned comparison below.
2350 bind(&isNegative);
2351 branch32(Assembler::GreaterThanOrEqual, int32, Imm32(0), lessThan);
2352 neg32(scratch2);
2353
2354 // Not all supported platforms (e.g. MIPS64) zero-extend 32-bit operations,
2355 // so we need to explicitly clear any high 32-bits.
2356 move32ZeroExtendToPtr(scratch2, scratch2);
2357
2358 // Reverse the relational comparator for negative numbers.
2359 // |-x < -y| <=> |+x > +y|.
2360 // |-x ≤ -y| <=> |+x ≥ +y|.
2361 // |-x > -y| <=> |+x < +y|.
2362 // |-x ≥ -y| <=> |+x ≤ +y|.
2363 JSOp reversed = ReverseCompareOp(op);
2364 if (reversed != op) {
2365 branchPtr(JSOpToCondition(reversed, /* isSigned = */ false), scratch1,
2366 scratch2, ifTrue);
2367 jump(ifFalse);
2368 }
2369
2370 bind(&doCompare);
2371 branchPtr(JSOpToCondition(op, /* isSigned = */ false), scratch1, scratch2,
2372 ifTrue);
2373 }
2374 }
2375
2376 void MacroAssembler::compareBigIntAndInt32(JSOp op, Register bigInt,
2377 Imm32 int32, Register scratch,
2378 Label* ifTrue, Label* ifFalse) {
2379 MOZ_ASSERT(IsLooseEqualityOp(op) || IsRelationalOp(op));
2380
2381 static_assert(std::is_same_v<BigInt::Digit, uintptr_t>,
2382 "BigInt digit can be loaded in a pointer-sized register");
2383 static_assert(sizeof(BigInt::Digit) >= sizeof(uint32_t),
2384 "BigInt digit stores at least an uint32");
2385
2386 // Comparison against zero doesn't require loading any BigInt digits.
2387 if (int32.value == 0) {
2388 switch (op) {
2389 case JSOp::Eq:
2390 branchIfBigIntIsZero(bigInt, ifTrue);
2391 break;
2392 case JSOp::Ne:
2393 branchIfBigIntIsNonZero(bigInt, ifTrue);
2394 break;
2395 case JSOp::Lt:
2396 branchIfBigIntIsNegative(bigInt, ifTrue);
2397 break;
2398 case JSOp::Le:
2399 branchIfBigIntIsZero(bigInt, ifTrue);
2400 branchIfBigIntIsNegative(bigInt, ifTrue);
2401 break;
2402 case JSOp::Gt:
2403 branchIfBigIntIsZero(bigInt, ifFalse);
2404 branchIfBigIntIsNonNegative(bigInt, ifTrue);
2405 break;
2406 case JSOp::Ge:
2407 branchIfBigIntIsNonNegative(bigInt, ifTrue);
2408 break;
2409 default:
2410 MOZ_CRASH("bad comparison operator");
2411 }
2412
2413 // Fall through to the false case.
2414 return;
2415 }
2416
2417 // Jump to |ifTrue| resp. |ifFalse| if the BigInt is strictly less than
2418 // resp. strictly greater than the int32 value, depending on the comparison
2419 // operator.
2420 Label* greaterThan;
2421 Label* lessThan;
2422 if (op == JSOp::Eq) {
2423 greaterThan = ifFalse;
2424 lessThan = ifFalse;
2425 } else if (op == JSOp::Ne) {
2426 greaterThan = ifTrue;
2427 lessThan = ifTrue;
2428 } else if (op == JSOp::Lt || op == JSOp::Le) {
2429 greaterThan = ifFalse;
2430 lessThan = ifTrue;
2431 } else {
2432 MOZ_ASSERT(op == JSOp::Gt || op == JSOp::Ge);
2433 greaterThan = ifTrue;
2434 lessThan = ifFalse;
2435 }
2436
2437 // Test for mismatched signs.
2438 if (int32.value > 0) {
2439 branchIfBigIntIsNegative(bigInt, lessThan);
2440 } else {
2441 branchIfBigIntIsNonNegative(bigInt, greaterThan);
2442 }
2443
2444 // Both signs are equal, load |abs(x)| in |scratch| and then compare the
2445 // unsigned numbers against each other.
2446 //
2447 // If the unsigned value of the BigInt can't be expressed in an uint32/uint64,
2448 // the result of the comparison is a constant.
2449 Label* tooLarge = int32.value > 0 ? greaterThan : lessThan;
2450 loadBigIntDigit(bigInt, scratch, tooLarge);
2451
2452 // Use the unsigned value of the immediate.
2453 ImmWord uint32 = ImmWord(mozilla::Abs(int32.value));
2454
2455 // Reverse the relational comparator for negative numbers.
2456 // |-x < -y| <=> |+x > +y|.
2457 // |-x ≤ -y| <=> |+x ≥ +y|.
2458 // |-x > -y| <=> |+x < +y|.
2459 // |-x ≥ -y| <=> |+x ≤ +y|.
2460 if (int32.value < 0) {
2461 op = ReverseCompareOp(op);
2462 }
2463
2464 branchPtr(JSOpToCondition(op, /* isSigned = */ false), scratch, uint32,
2465 ifTrue);
2466 }
2467
2468 void MacroAssembler::equalBigInts(Register left, Register right, Register temp1,
2469 Register temp2, Register temp3,
2470 Register temp4, Label* notSameSign,
2471 Label* notSameLength, Label* notSameDigit) {
2472 MOZ_ASSERT(left != temp1);
2473 MOZ_ASSERT(right != temp1);
2474 MOZ_ASSERT(right != temp2);
2475
2476 // Jump to |notSameSign| when the sign aren't the same.
2477 load32(Address(left, BigInt::offsetOfFlags()), temp1);
2478 xor32(Address(right, BigInt::offsetOfFlags()), temp1);
2479 branchTest32(Assembler::NonZero, temp1, Imm32(BigInt::signBitMask()),
2480 notSameSign);
2481
2482 // Jump to |notSameLength| when the digits length is different.
2483 load32(Address(right, BigInt::offsetOfLength()), temp1);
2484 branch32(Assembler::NotEqual, Address(left, BigInt::offsetOfLength()), temp1,
2485 notSameLength);
2486
2487 // Both BigInts have the same sign and the same number of digits. Loop
2488 // over each digit, starting with the left-most one, and break from the
2489 // loop when the first non-matching digit was found.
2490
2491 loadBigIntDigits(left, temp2);
2492 loadBigIntDigits(right, temp3);
2493
2494 static_assert(sizeof(BigInt::Digit) == sizeof(void*),
2495 "BigInt::Digit is pointer sized");
2496
2497 computeEffectiveAddress(BaseIndex(temp2, temp1, ScalePointer), temp2);
2498 computeEffectiveAddress(BaseIndex(temp3, temp1, ScalePointer), temp3);
2499
2500 Label start, loop;
2501 jump(&start);
2502 bind(&loop);
2503
2504 subPtr(Imm32(sizeof(BigInt::Digit)), temp2);
2505 subPtr(Imm32(sizeof(BigInt::Digit)), temp3);
2506
2507 loadPtr(Address(temp3, 0), temp4);
2508 branchPtr(Assembler::NotEqual, Address(temp2, 0), temp4, notSameDigit);
2509
2510 bind(&start);
2511 branchSub32(Assembler::NotSigned, Imm32(1), temp1, &loop);
2512
2513 // No different digits were found, both BigInts are equal to each other.
2514 }
2515
2516 void MacroAssembler::typeOfObject(Register obj, Register scratch, Label* slow,
2517 Label* isObject, Label* isCallable,
2518 Label* isUndefined) {
2519 loadObjClassUnsafe(obj, scratch);
2520
2521 // Proxies can emulate undefined and have complex isCallable behavior.
2522 branchTestClassIsProxy(true, scratch, slow);
2523
2524 // JSFunctions are always callable.
2525 branchTestClassIsFunction(Assembler::Equal, scratch, isCallable);
2526
2527 // Objects that emulate undefined.
2528 Address flags(scratch, JSClass::offsetOfFlags());
2529 branchTest32(Assembler::NonZero, flags, Imm32(JSCLASS_EMULATES_UNDEFINED),
2530 isUndefined);
2531
2532 // Handle classes with a call hook.
2533 branchPtr(Assembler::Equal, Address(scratch, offsetof(JSClass, cOps)),
2534 ImmPtr(nullptr), isObject);
2535
2536 loadPtr(Address(scratch, offsetof(JSClass, cOps)), scratch);
2537 branchPtr(Assembler::Equal, Address(scratch, offsetof(JSClassOps, call)),
2538 ImmPtr(nullptr), isObject);
2539
2540 jump(isCallable);
2541 }
2542
2543 void MacroAssembler::isCallableOrConstructor(bool isCallable, Register obj,
2544 Register output, Label* isProxy) {
2545 MOZ_ASSERT(obj != output);
2546
2547 Label notFunction, hasCOps, done;
2548 loadObjClassUnsafe(obj, output);
2549
2550 // An object is callable iff:
2551 // is<JSFunction>() || (getClass()->cOps && getClass()->cOps->call).
2552 // An object is constructor iff:
2553 // ((is<JSFunction>() && as<JSFunction>().isConstructor) ||
2554 // (getClass()->cOps && getClass()->cOps->construct)).
2555 branchTestClassIsFunction(Assembler::NotEqual, output, &notFunction);
2556 if (isCallable) {
2557 move32(Imm32(1), output);
2558 } else {
2559 static_assert(mozilla::IsPowerOfTwo(uint32_t(FunctionFlags::CONSTRUCTOR)),
2560 "FunctionFlags::CONSTRUCTOR has only one bit set");
2561
2562 load32(Address(obj, JSFunction::offsetOfFlagsAndArgCount()), output);
2563 rshift32(Imm32(mozilla::FloorLog2(uint32_t(FunctionFlags::CONSTRUCTOR))),
2564 output);
2565 and32(Imm32(1), output);
2566 }
2567 jump(&done);
2568
2569 bind(&notFunction);
2570
2571 if (!isCallable) {
2572 // For bound functions, we need to check the isConstructor flag.
2573 Label notBoundFunction;
2574 branchPtr(Assembler::NotEqual, output, ImmPtr(&BoundFunctionObject::class_),
2575 &notBoundFunction);
2576
2577 static_assert(BoundFunctionObject::IsConstructorFlag == 0b1,
2578 "AND operation results in boolean value");
2579 unboxInt32(Address(obj, BoundFunctionObject::offsetOfFlagsSlot()), output);
2580 and32(Imm32(BoundFunctionObject::IsConstructorFlag), output);
2581 jump(&done);
2582
2583 bind(&notBoundFunction);
2584 }
2585
2586 // Just skim proxies off. Their notion of isCallable()/isConstructor() is
2587 // more complicated.
2588 branchTestClassIsProxy(true, output, isProxy);
2589
2590 branchPtr(Assembler::NonZero, Address(output, offsetof(JSClass, cOps)),
2591 ImmPtr(nullptr), &hasCOps);
2592 move32(Imm32(0), output);
2593 jump(&done);
2594
2595 bind(&hasCOps);
2596 loadPtr(Address(output, offsetof(JSClass, cOps)), output);
2597 size_t opsOffset =
2598 isCallable ? offsetof(JSClassOps, call) : offsetof(JSClassOps, construct);
2599 cmpPtrSet(Assembler::NonZero, Address(output, opsOffset), ImmPtr(nullptr),
2600 output);
2601
2602 bind(&done);
2603 }
2604
2605 void MacroAssembler::loadJSContext(Register dest) {
2606 movePtr(ImmPtr(runtime()->mainContextPtr()), dest);
2607 }
2608
2609 static const uint8_t* ContextRealmPtr(CompileRuntime* rt) {
2610 return (static_cast<const uint8_t*>(rt->mainContextPtr()) +
2611 JSContext::offsetOfRealm());
2612 }
2613
2614 void MacroAssembler::loadGlobalObjectData(Register dest) {
2615 loadPtr(AbsoluteAddress(ContextRealmPtr(runtime())), dest);
2616 loadPtr(Address(dest, Realm::offsetOfActiveGlobal()), dest);
2617 loadPrivate(Address(dest, GlobalObject::offsetOfGlobalDataSlot()), dest);
2618 }
2619
2620 void MacroAssembler::switchToRealm(Register realm) {
2621 storePtr(realm, AbsoluteAddress(ContextRealmPtr(runtime())));
2622 }
2623
2624 void MacroAssembler::loadRealmFuse(RealmFuses::FuseIndex index, Register dest) {
2625 // Load Realm pointer
2626 loadPtr(AbsoluteAddress(ContextRealmPtr(runtime())), dest);
2627 loadPtr(Address(dest, RealmFuses::offsetOfFuseWordRelativeToRealm(index)),
2628 dest);
2629 }
2630
2631 void MacroAssembler::switchToRealm(const void* realm, Register scratch) {
2632 MOZ_ASSERT(realm);
2633
2634 movePtr(ImmPtr(realm), scratch);
2635 switchToRealm(scratch);
2636 }
2637
2638 void MacroAssembler::switchToObjectRealm(Register obj, Register scratch) {
2639 loadPtr(Address(obj, JSObject::offsetOfShape()), scratch);
2640 loadPtr(Address(scratch, Shape::offsetOfBaseShape()), scratch);
2641 loadPtr(Address(scratch, BaseShape::offsetOfRealm()), scratch);
2642 switchToRealm(scratch);
2643 }
2644
2645 void MacroAssembler::switchToBaselineFrameRealm(Register scratch) {
2646 Address envChain(FramePointer,
2647 BaselineFrame::reverseOffsetOfEnvironmentChain());
2648 loadPtr(envChain, scratch);
2649 switchToObjectRealm(scratch, scratch);
2650 }
2651
2652 void MacroAssembler::switchToWasmInstanceRealm(Register scratch1,
2653 Register scratch2) {
2654 loadPtr(Address(InstanceReg, wasm::Instance::offsetOfCx()), scratch1);
2655 loadPtr(Address(InstanceReg, wasm::Instance::offsetOfRealm()), scratch2);
2656 storePtr(scratch2, Address(scratch1, JSContext::offsetOfRealm()));
2657 }
2658
2659 template <typename ValueType>
2660 void MacroAssembler::storeLocalAllocSite(ValueType value, Register scratch) {
2661 loadPtr(AbsoluteAddress(ContextRealmPtr(runtime())), scratch);
2662 storePtr(value, Address(scratch, JS::Realm::offsetOfLocalAllocSite()));
2663 }
2664
2665 template void MacroAssembler::storeLocalAllocSite(Register, Register);
2666 template void MacroAssembler::storeLocalAllocSite(ImmWord, Register);
2667 template void MacroAssembler::storeLocalAllocSite(ImmPtr, Register);
2668
2669 void MacroAssembler::debugAssertContextRealm(const void* realm,
2670 Register scratch) {
2671 #ifdef DEBUG
2672 Label ok;
2673 movePtr(ImmPtr(realm), scratch);
2674 branchPtr(Assembler::Equal, AbsoluteAddress(ContextRealmPtr(runtime())),
2675 scratch, &ok);
2676 assumeUnreachable("Unexpected context realm");
2677 bind(&ok);
2678 #endif
2679 }
2680
2681 void MacroAssembler::setIsCrossRealmArrayConstructor(Register obj,
2682 Register output) {
2683 #ifdef DEBUG
2684 Label notProxy;
2685 branchTestObjectIsProxy(false, obj, output, &notProxy);
2686 assumeUnreachable("Unexpected proxy in setIsCrossRealmArrayConstructor");
2687 bind(&notProxy);
2688 #endif
2689
2690 // The object's realm must not be cx->realm.
2691 Label isFalse, done;
2692 loadPtr(Address(obj, JSObject::offsetOfShape()), output);
2693 loadPtr(Address(output, Shape::offsetOfBaseShape()), output);
2694 loadPtr(Address(output, BaseShape::offsetOfRealm()), output);
2695 branchPtr(Assembler::Equal, AbsoluteAddress(ContextRealmPtr(runtime())),
2696 output, &isFalse);
2697
2698 // The object must be a function.
2699 branchTestObjIsFunction(Assembler::NotEqual, obj, output, obj, &isFalse);
2700
2701 // The function must be the ArrayConstructor native.
2702 branchPtr(Assembler::NotEqual,
2703 Address(obj, JSFunction::offsetOfNativeOrEnv()),
2704 ImmPtr(js::ArrayConstructor), &isFalse);
2705
2706 move32(Imm32(1), output);
2707 jump(&done);
2708
2709 bind(&isFalse);
2710 move32(Imm32(0), output);
2711
2712 bind(&done);
2713 }
2714
2715 void MacroAssembler::guardObjectHasSameRealm(Register obj, Register scratch,
2716 Label* fail) {
2717 loadPtr(Address(obj, JSObject::offsetOfShape()), scratch);
2718 loadPtr(Address(scratch, Shape::offsetOfBaseShape()), scratch);
2719 loadPtr(Address(scratch, BaseShape::offsetOfRealm()), scratch);
2720 branchPtr(Assembler::NotEqual, AbsoluteAddress(ContextRealmPtr(runtime())),
2721 scratch, fail);
2722 }
2723
2724 void MacroAssembler::setIsDefinitelyTypedArrayConstructor(Register obj,
2725 Register output) {
2726 Label isFalse, isTrue, done;
2727
2728 // The object must be a function. (Wrappers are not supported.)
2729 branchTestObjIsFunction(Assembler::NotEqual, obj, output, obj, &isFalse);
2730
2731 // Load the native into |output|.
2732 loadPtr(Address(obj, JSFunction::offsetOfNativeOrEnv()), output);
2733
2734 auto branchIsTypedArrayCtor = [&](Scalar::Type type) {
2735 // The function must be a TypedArrayConstructor native (from any realm).
2736 JSNative constructor = TypedArrayConstructorNative(type);
2737 branchPtr(Assembler::Equal, output, ImmPtr(constructor), &isTrue);
2738 };
2739
2740 #define TYPED_ARRAY_CONSTRUCTOR_NATIVE(_, T, N) \
2741 branchIsTypedArrayCtor(Scalar::N);
2742 JS_FOR_EACH_TYPED_ARRAY(TYPED_ARRAY_CONSTRUCTOR_NATIVE)
2743 #undef TYPED_ARRAY_CONSTRUCTOR_NATIVE
2744
2745 // Falls through to the false case.
2746
2747 bind(&isFalse);
2748 move32(Imm32(0), output);
2749 jump(&done);
2750
2751 bind(&isTrue);
2752 move32(Imm32(1), output);
2753
2754 bind(&done);
2755 }
2756
2757 void MacroAssembler::loadMegamorphicCache(Register dest) {
2758 movePtr(ImmPtr(runtime()->addressOfMegamorphicCache()), dest);
2759 }
2760 void MacroAssembler::loadMegamorphicSetPropCache(Register dest) {
2761 movePtr(ImmPtr(runtime()->addressOfMegamorphicSetPropCache()), dest);
2762 }
2763
2764 void MacroAssembler::tryFastAtomize(Register str, Register scratch,
2765 Register output, Label* fail) {
2766 Label found, done, notAtomRef;
2767
2768 branchTest32(Assembler::Zero, Address(str, JSString::offsetOfFlags()),
2769 Imm32(JSString::ATOM_REF_BIT), &notAtomRef);
2770 loadPtr(Address(str, JSAtomRefString::offsetOfAtom()), output);
2771 jump(&done);
2772 bind(&notAtomRef);
2773
2774 uintptr_t cachePtr = uintptr_t(runtime()->addressOfStringToAtomCache());
2775 void* offset = (void*)(cachePtr + StringToAtomCache::offsetOfLastLookups());
2776 movePtr(ImmPtr(offset), scratch);
2777
2778 static_assert(StringToAtomCache::NumLastLookups == 2);
2779 size_t stringOffset = StringToAtomCache::LastLookup::offsetOfString();
2780 size_t lookupSize = sizeof(StringToAtomCache::LastLookup);
2781 branchPtr(Assembler::Equal, Address(scratch, stringOffset), str, &found);
2782 branchPtr(Assembler::NotEqual, Address(scratch, lookupSize + stringOffset),
2783 str, fail);
2784 addPtr(Imm32(lookupSize), scratch);
2785
2786 // We found a hit in the lastLookups_ array! Load the associated atom
2787 // and jump back up to our usual atom handling code
2788 bind(&found);
2789 size_t atomOffset = StringToAtomCache::LastLookup::offsetOfAtom();
2790 loadPtr(Address(scratch, atomOffset), output);
2791 bind(&done);
2792 }
2793
2794 void MacroAssembler::loadAtomHash(Register id, Register outHash, Label* done) {
2795 Label doneInner, fatInline;
2796 if (!done) {
2797 done = &doneInner;
2798 }
2799 move32(Imm32(JSString::FAT_INLINE_MASK), outHash);
2800 and32(Address(id, JSString::offsetOfFlags()), outHash);
2801
2802 branch32(Assembler::Equal, outHash, Imm32(JSString::FAT_INLINE_MASK),
2803 &fatInline);
2804 load32(Address(id, NormalAtom::offsetOfHash()), outHash);
2805 jump(done);
2806 bind(&fatInline);
2807 load32(Address(id, FatInlineAtom::offsetOfHash()), outHash);
2808 jump(done);
2809 bind(&doneInner);
2810 }
2811
2812 void MacroAssembler::loadAtomOrSymbolAndHash(ValueOperand value, Register outId,
2813 Register outHash,
2814 Label* cacheMiss) {
2815 Label isString, isSymbol, isNull, isUndefined, done, nonAtom, atom;
2816
2817 {
2818 ScratchTagScope tag(*this, value);
2819 splitTagForTest(value, tag);
2820 branchTestString(Assembler::Equal, tag, &isString);
2821 branchTestSymbol(Assembler::Equal, tag, &isSymbol);
2822 branchTestNull(Assembler::Equal, tag, &isNull);
2823 branchTestUndefined(Assembler::NotEqual, tag, cacheMiss);
2824 }
2825
2826 const JSAtomState& names = runtime()->names();
2827 movePropertyKey(NameToId(names.undefined), outId);
2828 move32(Imm32(names.undefined->hash()), outHash);
2829 jump(&done);
2830
2831 bind(&isNull);
2832 movePropertyKey(NameToId(names.null), outId);
2833 move32(Imm32(names.null->hash()), outHash);
2834 jump(&done);
2835
2836 bind(&isSymbol);
2837 unboxSymbol(value, outId);
2838 load32(Address(outId, JS::Symbol::offsetOfHash()), outHash);
2839 orPtr(Imm32(PropertyKey::SymbolTypeTag), outId);
2840 jump(&done);
2841
2842 bind(&isString);
2843 unboxString(value, outId);
2844 branchTest32(Assembler::Zero, Address(outId, JSString::offsetOfFlags()),
2845 Imm32(JSString::ATOM_BIT), &nonAtom);
2846
2847 bind(&atom);
2848 loadAtomHash(outId, outHash, &done);
2849
2850 bind(&nonAtom);
2851 tryFastAtomize(outId, outHash, outId, cacheMiss);
2852 jump(&atom);
2853
2854 bind(&done);
2855 }
2856
2857 void MacroAssembler::emitExtractValueFromMegamorphicCacheEntry(
2858 Register obj, Register entry, Register scratch1, Register scratch2,
2859 ValueOperand output, Label* cacheHit, Label* cacheMiss,
2860 Label* cacheHitGetter) {
2861 Label isMissing, dynamicSlot, protoLoopHead, protoLoopTail;
2862
2863 // scratch2 = entry->hopsAndKind_
2864 load8ZeroExtend(
2865 Address(entry, MegamorphicCache::Entry::offsetOfHopsAndKind()), scratch2);
2866 // if (scratch2 == NumHopsForMissingProperty) goto isMissing
2867 branch32(Assembler::Equal, scratch2,
2868 Imm32(MegamorphicCache::Entry::NumHopsForMissingProperty),
2869 &isMissing);
2870
2871 if (cacheHitGetter) {
2872 // Here we're going to set scratch1 to 0 for a data property and 1 for a
2873 // getter and scratch2 to the number of hops
2874 Label dataProperty;
2875
2876 // if (scratch2 & NonDataPropertyFlag == 0) goto dataProperty
2877 move32(Imm32(0), scratch1);
2878 branchTest32(Assembler::Zero, scratch2,
2879 Imm32(MegamorphicCache::Entry::NonDataPropertyFlag),
2880 &dataProperty);
2881
2882 // if (scratch2 > NonDataPropertyFlag | MaxHopsForAccessorProperty) goto
2883 // cacheMiss
2884 branch32(Assembler::GreaterThan, scratch2,
2885 Imm32(MegamorphicCache::Entry::NonDataPropertyFlag |
2886 MegamorphicCache::Entry::MaxHopsForAccessorProperty),
2887 cacheMiss);
2888
2889 and32(Imm32(~MegamorphicCache::Entry::NonDataPropertyFlag), scratch2);
2890 move32(Imm32(1), scratch1);
2891
2892 bind(&dataProperty);
2893 } else {
2894 // if (scratch2 & NonDataPropertyFlag) goto cacheMiss
2895 branchTest32(Assembler::NonZero, scratch2,
2896 Imm32(MegamorphicCache::Entry::NonDataPropertyFlag),
2897 cacheMiss);
2898 }
2899
2900 // NOTE: Where this is called, `output` can actually alias `obj`, and before
2901 // the last cacheMiss branch above we can't write to `obj`, so we can't
2902 // use `output`'s scratch register there. However a cache miss is impossible
2903 // now, so we're free to use `output` as we like.
2904 Register outputScratch = output.scratchReg();
2905 if (!outputScratch.aliases(obj)) {
2906 // We're okay with paying this very slight extra cost to avoid a potential
2907 // footgun of writing to what callers understand as only an input register.
2908 movePtr(obj, outputScratch);
2909 }
2910 branchTest32(Assembler::Zero, scratch2, scratch2, &protoLoopTail);
2911 bind(&protoLoopHead);
2912 loadObjProto(outputScratch, outputScratch);
2913 branchSub32(Assembler::NonZero, Imm32(1), scratch2, &protoLoopHead);
2914 bind(&protoLoopTail);
2915
2916 // entry = entry->slotOffset()
2917 load32(Address(entry, MegamorphicCacheEntry::offsetOfSlotOffset()), entry);
2918
2919 // scratch2 = slotOffset.offset()
2920 rshift32(Imm32(TaggedSlotOffset::OffsetShift), entry, scratch2);
2921
2922 // if (!slotOffset.isFixedSlot()) goto dynamicSlot
2923 branchTest32(Assembler::Zero, entry, Imm32(TaggedSlotOffset::IsFixedSlotFlag),
2924 &dynamicSlot);
2925 // output = outputScratch[scratch2]
2926 loadValue(BaseIndex(outputScratch, scratch2, TimesOne), output);
2927 if (cacheHitGetter) {
2928 branchTest32(Assembler::NonZero, scratch1, scratch1, cacheHitGetter);
2929 }
2930 jump(cacheHit);
2931
2932 bind(&dynamicSlot);
2933 // output = outputScratch->slots_[scratch2]
2934 loadPtr(Address(outputScratch, NativeObject::offsetOfSlots()), outputScratch);
2935 loadValue(BaseIndex(outputScratch, scratch2, TimesOne), output);
2936 if (cacheHitGetter) {
2937 branchTest32(Assembler::NonZero, scratch1, scratch1, cacheHitGetter);
2938 }
2939 jump(cacheHit);
2940
2941 bind(&isMissing);
2942 // output = undefined
2943 moveValue(UndefinedValue(), output);
2944 jump(cacheHit);
2945 }
2946
2947 template <typename IdOperandType>
2948 void MacroAssembler::emitMegamorphicCacheLookupByValueCommon(
2949 IdOperandType id, Register obj, Register scratch1, Register scratch2,
2950 Register outEntryPtr, Label* cacheMiss, Label* cacheMissWithEntry) {
2951 // A lot of this code is shared with emitMegamorphicCacheLookup. It would
2952 // be nice to be able to avoid the duplication here, but due to a few
2953 // differences like taking the id in a ValueOperand instead of being able
2954 // to bake it in as an immediate, and only needing a Register for the output
2955 // value, it seemed more awkward to read once it was deduplicated.
2956
2957 // outEntryPtr = obj->shape()
2958 loadPtr(Address(obj, JSObject::offsetOfShape()), outEntryPtr);
2959
2960 movePtr(outEntryPtr, scratch2);
2961
2962 // outEntryPtr = (outEntryPtr >> 3) ^ (outEntryPtr >> 13) + idHash
2963 rshiftPtr(Imm32(MegamorphicCache::ShapeHashShift1), outEntryPtr);
2964 rshiftPtr(Imm32(MegamorphicCache::ShapeHashShift2), scratch2);
2965 xorPtr(scratch2, outEntryPtr);
2966
2967 if constexpr (std::is_same<IdOperandType, ValueOperand>::value) {
2968 loadAtomOrSymbolAndHash(id, scratch1, scratch2, cacheMiss);
2969 } else {
2970 static_assert(std::is_same<IdOperandType, Register>::value);
2971 movePtr(id, scratch1);
2972 loadAtomHash(scratch1, scratch2, nullptr);
2973 }
2974 addPtr(scratch2, outEntryPtr);
2975
2976 // outEntryPtr %= MegamorphicCache::NumEntries
2977 constexpr size_t cacheSize = MegamorphicCache::NumEntries;
2978 static_assert(mozilla::IsPowerOfTwo(cacheSize));
2979 size_t cacheMask = cacheSize - 1;
2980 and32(Imm32(cacheMask), outEntryPtr);
2981
2982 loadMegamorphicCache(scratch2);
2983 // outEntryPtr = &scratch2->entries_[outEntryPtr]
2984 constexpr size_t entrySize = sizeof(MegamorphicCache::Entry);
2985 static_assert(sizeof(void*) == 4 || entrySize == 24);
2986 if constexpr (sizeof(void*) == 4) {
2987 mul32(Imm32(entrySize), outEntryPtr);
2988 computeEffectiveAddress(BaseIndex(scratch2, outEntryPtr, TimesOne,
2989 MegamorphicCache::offsetOfEntries()),
2990 outEntryPtr);
2991 } else {
2992 computeEffectiveAddress(BaseIndex(outEntryPtr, outEntryPtr, TimesTwo),
2993 outEntryPtr);
2994 computeEffectiveAddress(BaseIndex(scratch2, outEntryPtr, TimesEight,
2995 MegamorphicCache::offsetOfEntries()),
2996 outEntryPtr);
2997 }
2998
2999 // if (outEntryPtr->key_ != scratch1) goto cacheMissWithEntry
3000 branchPtr(Assembler::NotEqual,
3001 Address(outEntryPtr, MegamorphicCache::Entry::offsetOfKey()),
3002 scratch1, cacheMissWithEntry);
3003 loadPtr(Address(obj, JSObject::offsetOfShape()), scratch1);
3004
3005 // if (outEntryPtr->shape_ != scratch1) goto cacheMissWithEntry
3006 branchPtr(Assembler::NotEqual,
3007 Address(outEntryPtr, MegamorphicCache::Entry::offsetOfShape()),
3008 scratch1, cacheMissWithEntry);
3009
3010 // scratch2 = scratch2->generation_
3011 load16ZeroExtend(Address(scratch2, MegamorphicCache::offsetOfGeneration()),
3012 scratch2);
3013 load16ZeroExtend(
3014 Address(outEntryPtr, MegamorphicCache::Entry::offsetOfGeneration()),
3015 scratch1);
3016 // if (outEntryPtr->generation_ != scratch2) goto cacheMissWithEntry
3017 branch32(Assembler::NotEqual, scratch1, scratch2, cacheMissWithEntry);
3018 }
3019
3020 void MacroAssembler::emitMegamorphicCacheLookup(
3021 PropertyKey id, Register obj, Register scratch1, Register scratch2,
3022 Register outEntryPtr, ValueOperand output, Label* cacheHit,
3023 Label* cacheHitGetter) {
3024 Label cacheMiss, isMissing, dynamicSlot, protoLoopHead, protoLoopTail;
3025
3026 // scratch1 = obj->shape()
3027 loadPtr(Address(obj, JSObject::offsetOfShape()), scratch1);
3028
3029 movePtr(scratch1, outEntryPtr);
3030 movePtr(scratch1, scratch2);
3031
3032 // outEntryPtr = (scratch1 >> 3) ^ (scratch1 >> 13) + hash(id)
3033 rshiftPtr(Imm32(MegamorphicCache::ShapeHashShift1), outEntryPtr);
3034 rshiftPtr(Imm32(MegamorphicCache::ShapeHashShift2), scratch2);
3035 xorPtr(scratch2, outEntryPtr);
3036 addPtr(Imm32(HashAtomOrSymbolPropertyKey(id)), outEntryPtr);
3037
3038 // outEntryPtr %= MegamorphicCache::NumEntries
3039 constexpr size_t cacheSize = MegamorphicCache::NumEntries;
3040 static_assert(mozilla::IsPowerOfTwo(cacheSize));
3041 size_t cacheMask = cacheSize - 1;
3042 and32(Imm32(cacheMask), outEntryPtr);
3043
3044 loadMegamorphicCache(scratch2);
3045 // outEntryPtr = &scratch2->entries_[outEntryPtr]
3046 constexpr size_t entrySize = sizeof(MegamorphicCache::Entry);
3047 static_assert(sizeof(void*) == 4 || entrySize == 24);
3048 if constexpr (sizeof(void*) == 4) {
3049 mul32(Imm32(entrySize), outEntryPtr);
3050 computeEffectiveAddress(BaseIndex(scratch2, outEntryPtr, TimesOne,
3051 MegamorphicCache::offsetOfEntries()),
3052 outEntryPtr);
3053 } else {
3054 computeEffectiveAddress(BaseIndex(outEntryPtr, outEntryPtr, TimesTwo),
3055 outEntryPtr);
3056 computeEffectiveAddress(BaseIndex(scratch2, outEntryPtr, TimesEight,
3057 MegamorphicCache::offsetOfEntries()),
3058 outEntryPtr);
3059 }
3060
3061 // if (outEntryPtr->shape_ != scratch1) goto cacheMiss
3062 branchPtr(Assembler::NotEqual,
3063 Address(outEntryPtr, MegamorphicCache::Entry::offsetOfShape()),
3064 scratch1, &cacheMiss);
3065
3066 // if (outEntryPtr->key_ != id) goto cacheMiss
3067 movePropertyKey(id, scratch1);
3068 branchPtr(Assembler::NotEqual,
3069 Address(outEntryPtr, MegamorphicCache::Entry::offsetOfKey()),
3070 scratch1, &cacheMiss);
3071
3072 // scratch2 = scratch2->generation_
3073 load16ZeroExtend(Address(scratch2, MegamorphicCache::offsetOfGeneration()),
3074 scratch2);
3075 load16ZeroExtend(
3076 Address(outEntryPtr, MegamorphicCache::Entry::offsetOfGeneration()),
3077 scratch1);
3078 // if (outEntryPtr->generation_ != scratch2) goto cacheMiss
3079 branch32(Assembler::NotEqual, scratch1, scratch2, &cacheMiss);
3080
3081 emitExtractValueFromMegamorphicCacheEntry(obj, outEntryPtr, scratch1,
3082 scratch2, output, cacheHit,
3083 &cacheMiss, cacheHitGetter);
3084
3085 bind(&cacheMiss);
3086 }
3087
3088 template <typename IdOperandType>
3089 void MacroAssembler::emitMegamorphicCacheLookupByValue(
3090 IdOperandType id, Register obj, Register scratch1, Register scratch2,
3091 Register outEntryPtr, ValueOperand output, Label* cacheHit,
3092 Label* cacheHitGetter) {
3093 Label cacheMiss, cacheMissWithEntry;
3094 emitMegamorphicCacheLookupByValueCommon(id, obj, scratch1, scratch2,
3095 outEntryPtr, &cacheMiss,
3096 &cacheMissWithEntry);
3097 emitExtractValueFromMegamorphicCacheEntry(
3098 obj, outEntryPtr, scratch1, scratch2, output, cacheHit,
3099 &cacheMissWithEntry, cacheHitGetter);
3100 bind(&cacheMiss);
3101 xorPtr(outEntryPtr, outEntryPtr);
3102 bind(&cacheMissWithEntry);
3103 }
3104
3105 template void MacroAssembler::emitMegamorphicCacheLookupByValue<ValueOperand>(
3106 ValueOperand id, Register obj, Register scratch1, Register scratch2,
3107 Register outEntryPtr, ValueOperand output, Label* cacheHit,
3108 Label* cacheHitGetter);
3109
3110 template void MacroAssembler::emitMegamorphicCacheLookupByValue<Register>(
3111 Register id, Register obj, Register scratch1, Register scratch2,
3112 Register outEntryPtr, ValueOperand output, Label* cacheHit,
3113 Label* cacheHitGetter);
3114
3115 void MacroAssembler::emitMegamorphicCacheLookupExists(
3116 ValueOperand id, Register obj, Register scratch1, Register scratch2,
3117 Register outEntryPtr, Register output, Label* cacheHit, bool hasOwn) {
3118 Label cacheMiss, cacheMissWithEntry, cacheHitFalse;
3119 emitMegamorphicCacheLookupByValueCommon(id, obj, scratch1, scratch2,
3120 outEntryPtr, &cacheMiss,
3121 &cacheMissWithEntry);
3122
3123 // scratch1 = outEntryPtr->hopsAndKind_
3124 load8ZeroExtend(
3125 Address(outEntryPtr, MegamorphicCache::Entry::offsetOfHopsAndKind()),
3126 scratch1);
3127
3128 branch32(Assembler::Equal, scratch1,
3129 Imm32(MegamorphicCache::Entry::NumHopsForMissingProperty),
3130 &cacheHitFalse);
3131 branchTest32(Assembler::NonZero, scratch1,
3132 Imm32(MegamorphicCache::Entry::NonDataPropertyFlag),
3133 &cacheMissWithEntry);
3134
3135 if (hasOwn) {
3136 branch32(Assembler::NotEqual, scratch1, Imm32(0), &cacheHitFalse);
3137 }
3138
3139 move32(Imm32(1), output);
3140 jump(cacheHit);
3141
3142 bind(&cacheHitFalse);
3143 xor32(output, output);
3144 jump(cacheHit);
3145
3146 bind(&cacheMiss);
3147 xorPtr(outEntryPtr, outEntryPtr);
3148 bind(&cacheMissWithEntry);
3149 }
3150
3151 void MacroAssembler::extractCurrentIndexAndKindFromIterator(Register iterator,
3152 Register outIndex,
3153 Register outKind) {
3154 // Load iterator object
3155 Address nativeIterAddr(iterator,
3156 PropertyIteratorObject::offsetOfIteratorSlot());
3157 loadPrivate(nativeIterAddr, outIndex);
3158
3159 // Compute offset of propertyCursor_ from propertiesBegin()
3160 loadPtr(Address(outIndex, NativeIterator::offsetOfPropertyCursor()), outKind);
3161 subPtr(Address(outIndex, NativeIterator::offsetOfShapesEnd()), outKind);
3162
3163 // Compute offset of current index from indicesBegin(). Note that because
3164 // propertyCursor has already been incremented, this is actually the offset
3165 // of the next index. We adjust accordingly below.
3166 size_t indexAdjustment =
3167 sizeof(GCPtr<JSLinearString*>) / sizeof(PropertyIndex);
3168 if (indexAdjustment != 1) {
3169 MOZ_ASSERT(indexAdjustment == 2);
3170 rshift32(Imm32(1), outKind);
3171 }
3172
3173 // Load current index.
3174 loadPtr(Address(outIndex, NativeIterator::offsetOfPropertiesEnd()), outIndex);
3175 load32(BaseIndex(outIndex, outKind, Scale::TimesOne,
3176 -int32_t(sizeof(PropertyIndex))),
3177 outIndex);
3178
3179 // Extract kind.
3180 rshift32(Imm32(PropertyIndex::KindShift), outIndex, outKind);
3181
3182 // Extract index.
3183 and32(Imm32(PropertyIndex::IndexMask), outIndex);
3184 }
3185
3186 template <typename IdType>
3187 void MacroAssembler::emitMegamorphicCachedSetSlot(
3188 IdType id, Register obj, Register scratch1,
3189 #ifndef JS_CODEGEN_X86 // See MegamorphicSetElement in LIROps.yaml
3190 Register scratch2, Register scratch3,
3191 #endif
3192 ValueOperand value, const LiveRegisterSet& liveRegs, Label* cacheHit,
3193 void (*emitPreBarrier)(MacroAssembler&, const Address&, MIRType)) {
3194 Label cacheMiss, dynamicSlot, doAdd, doSet, doAddDynamic, doSetDynamic;
3195
3196 #ifdef JS_CODEGEN_X86
3197 pushValue(value);
3198 Register scratch2 = value.typeReg();
3199 Register scratch3 = value.payloadReg();
3200 #endif
3201
3202 // outEntryPtr = obj->shape()
3203 loadPtr(Address(obj, JSObject::offsetOfShape()), scratch3);
3204
3205 movePtr(scratch3, scratch2);
3206
3207 // scratch3 = (scratch3 >> 3) ^ (scratch3 >> 13) + idHash
3208 rshiftPtr(Imm32(MegamorphicSetPropCache::ShapeHashShift1), scratch3);
3209 rshiftPtr(Imm32(MegamorphicSetPropCache::ShapeHashShift2), scratch2);
3210 xorPtr(scratch2, scratch3);
3211
3212 if constexpr (std::is_same<IdType, ValueOperand>::value) {
3213 loadAtomOrSymbolAndHash(id, scratch1, scratch2, &cacheMiss);
3214 addPtr(scratch2, scratch3);
3215 } else {
3216 static_assert(std::is_same<IdType, PropertyKey>::value);
3217 addPtr(Imm32(HashAtomOrSymbolPropertyKey(id)), scratch3);
3218 movePropertyKey(id, scratch1);
3219 }
3220
3221 // scratch3 %= MegamorphicSetPropCache::NumEntries
3222 constexpr size_t cacheSize = MegamorphicSetPropCache::NumEntries;
3223 static_assert(mozilla::IsPowerOfTwo(cacheSize));
3224 size_t cacheMask = cacheSize - 1;
3225 and32(Imm32(cacheMask), scratch3);
3226
3227 loadMegamorphicSetPropCache(scratch2);
3228 // scratch3 = &scratch2->entries_[scratch3]
3229 constexpr size_t entrySize = sizeof(MegamorphicSetPropCache::Entry);
3230 mul32(Imm32(entrySize), scratch3);
3231 computeEffectiveAddress(BaseIndex(scratch2, scratch3, TimesOne,
3232 MegamorphicSetPropCache::offsetOfEntries()),
3233 scratch3);
3234
3235 // if (scratch3->key_ != scratch1) goto cacheMiss
3236 branchPtr(Assembler::NotEqual,
3237 Address(scratch3, MegamorphicSetPropCache::Entry::offsetOfKey()),
3238 scratch1, &cacheMiss);
3239
3240 loadPtr(Address(obj, JSObject::offsetOfShape()), scratch1);
3241 // if (scratch3->shape_ != scratch1) goto cacheMiss
3242 branchPtr(Assembler::NotEqual,
3243 Address(scratch3, MegamorphicSetPropCache::Entry::offsetOfShape()),
3244 scratch1, &cacheMiss);
3245
3246 // scratch2 = scratch2->generation_
3247 load16ZeroExtend(
3248 Address(scratch2, MegamorphicSetPropCache::offsetOfGeneration()),
3249 scratch2);
3250 load16ZeroExtend(
3251 Address(scratch3, MegamorphicSetPropCache::Entry::offsetOfGeneration()),
3252 scratch1);
3253 // if (scratch3->generation_ != scratch2) goto cacheMiss
3254 branch32(Assembler::NotEqual, scratch1, scratch2, &cacheMiss);
3255
3256 // scratch2 = entry->slotOffset()
3257 load32(
3258 Address(scratch3, MegamorphicSetPropCache::Entry::offsetOfSlotOffset()),
3259 scratch2);
3260
3261 // scratch1 = slotOffset.offset()
3262 rshift32(Imm32(TaggedSlotOffset::OffsetShift), scratch2, scratch1);
3263
3264 Address afterShapePtr(scratch3,
3265 MegamorphicSetPropCache::Entry::offsetOfAfterShape());
3266
3267 // if (!slotOffset.isFixedSlot()) goto dynamicSlot
3268 branchTest32(Assembler::Zero, scratch2,
3269 Imm32(TaggedSlotOffset::IsFixedSlotFlag), &dynamicSlot);
3270
3271 // Calculate slot address in scratch1. Jump to doSet if scratch3 == nullptr,
3272 // else jump (or fall-through) to doAdd.
3273 addPtr(obj, scratch1);
3274 branchPtr(Assembler::Equal, afterShapePtr, ImmPtr(nullptr), &doSet);
3275 jump(&doAdd);
3276
3277 bind(&dynamicSlot);
3278 branchPtr(Assembler::Equal, afterShapePtr, ImmPtr(nullptr), &doSetDynamic);
3279
3280 Address slotAddr(scratch1, 0);
3281
3282 // If entry->newCapacity_ is nonzero, we need to grow the slots on the
3283 // object. Otherwise just jump straight to a dynamic add.
3284 load16ZeroExtend(
3285 Address(scratch3, MegamorphicSetPropCache::Entry::offsetOfNewCapacity()),
3286 scratch2);
3287 branchTest32(Assembler::Zero, scratch2, scratch2, &doAddDynamic);
3288
3289 LiveRegisterSet save;
3290 save.set() = RegisterSet::Intersect(liveRegs.set(), RegisterSet::Volatile());
3291 save.addUnchecked(scratch1); // Used as call temp below.
3292 save.takeUnchecked(scratch2); // Used for the return value.
3293 PushRegsInMask(save);
3294
3295 using Fn = bool (*)(JSContext* cx, NativeObject* obj, uint32_t newCount);
3296 setupUnalignedABICall(scratch1);
3297 loadJSContext(scratch1);
3298 passABIArg(scratch1);
3299 passABIArg(obj);
3300 passABIArg(scratch2);
3301 callWithABI<Fn, NativeObject::growSlotsPure>();
3302 storeCallPointerResult(scratch2);
3303
3304 MOZ_ASSERT(!save.has(scratch2));
3305 PopRegsInMask(save);
3306
3307 branchIfFalseBool(scratch2, &cacheMiss);
3308
3309 bind(&doAddDynamic);
3310 addPtr(Address(obj, NativeObject::offsetOfSlots()), scratch1);
3311
3312 bind(&doAdd);
3313 // scratch3 = entry->afterShape()
3314 loadPtr(
3315 Address(scratch3, MegamorphicSetPropCache::Entry::offsetOfAfterShape()),
3316 scratch3);
3317
3318 storeObjShape(scratch3, obj,
3319 [emitPreBarrier](MacroAssembler& masm, const Address& addr) {
3320 emitPreBarrier(masm, addr, MIRType::Shape);
3321 });
3322 #ifdef JS_CODEGEN_X86
3323 popValue(value);
3324 #endif
3325 storeValue(value, slotAddr);
3326 jump(cacheHit);
3327
3328 bind(&doSetDynamic);
3329 addPtr(Address(obj, NativeObject::offsetOfSlots()), scratch1);
3330 bind(&doSet);
3331 guardedCallPreBarrier(slotAddr, MIRType::Value);
3332
3333 #ifdef JS_CODEGEN_X86
3334 popValue(value);
3335 #endif
3336 storeValue(value, slotAddr);
3337 jump(cacheHit);
3338
3339 bind(&cacheMiss);
3340 #ifdef JS_CODEGEN_X86
3341 popValue(value);
3342 #endif
3343 }
3344
3345 template void MacroAssembler::emitMegamorphicCachedSetSlot<PropertyKey>(
3346 PropertyKey id, Register obj, Register scratch1,
3347 #ifndef JS_CODEGEN_X86 // See MegamorphicSetElement in LIROps.yaml
3348 Register scratch2, Register scratch3,
3349 #endif
3350 ValueOperand value, const LiveRegisterSet& liveRegs, Label* cacheHit,
3351 void (*emitPreBarrier)(MacroAssembler&, const Address&, MIRType));
3352
3353 template void MacroAssembler::emitMegamorphicCachedSetSlot<ValueOperand>(
3354 ValueOperand id, Register obj, Register scratch1,
3355 #ifndef JS_CODEGEN_X86 // See MegamorphicSetElement in LIROps.yaml
3356 Register scratch2, Register scratch3,
3357 #endif
3358 ValueOperand value, const LiveRegisterSet& liveRegs, Label* cacheHit,
3359 void (*emitPreBarrier)(MacroAssembler&, const Address&, MIRType));
3360
3361 void MacroAssembler::guardNonNegativeIntPtrToInt32(Register reg, Label* fail) {
3362 #ifdef DEBUG
3363 Label ok;
3364 branchPtr(Assembler::NotSigned, reg, reg, &ok);
3365 assumeUnreachable("Unexpected negative value");
3366 bind(&ok);
3367 #endif
3368
3369 #ifdef JS_64BIT
3370 branchPtr(Assembler::Above, reg, Imm32(INT32_MAX), fail);
3371 #endif
3372 }
3373
3374 void MacroAssembler::loadArrayBufferByteLengthIntPtr(Register obj,
3375 Register output) {
3376 Address slotAddr(obj, ArrayBufferObject::offsetOfByteLengthSlot());
3377 loadPrivate(slotAddr, output);
3378 }
3379
3380 void MacroAssembler::loadArrayBufferViewByteOffsetIntPtr(Register obj,
3381 Register output) {
3382 Address slotAddr(obj, ArrayBufferViewObject::byteOffsetOffset());
3383 loadPrivate(slotAddr, output);
3384 }
3385
3386 void MacroAssembler::loadArrayBufferViewLengthIntPtr(Register obj,
3387 Register output) {
3388 Address slotAddr(obj, ArrayBufferViewObject::lengthOffset());
3389 loadPrivate(slotAddr, output);
3390 }
3391
3392 void MacroAssembler::loadGrowableSharedArrayBufferByteLengthIntPtr(
3393 Synchronization sync, Register obj, Register output) {
3394 // Load the SharedArrayRawBuffer.
3395 loadPrivate(Address(obj, SharedArrayBufferObject::rawBufferOffset()), output);
3396
3397 memoryBarrierBefore(sync);
3398
3399 // Load the byteLength of the SharedArrayRawBuffer into |output|.
3400 static_assert(sizeof(mozilla::Atomic<size_t>) == sizeof(size_t));
3401 loadPtr(Address(output, SharedArrayRawBuffer::offsetOfByteLength()), output);
3402
3403 memoryBarrierAfter(sync);
3404 }
3405
3406 void MacroAssembler::loadResizableArrayBufferViewLengthIntPtr(
3407 ResizableArrayBufferView view, Synchronization sync, Register obj,
3408 Register output, Register scratch) {
3409 // Inline implementation of ArrayBufferViewObject::length(), when the input is
3410 // guaranteed to be a resizable arraybuffer view object.
3411
3412 loadArrayBufferViewLengthIntPtr(obj, output);
3413
3414 Label done;
3415 branchPtr(Assembler::NotEqual, output, ImmWord(0), &done);
3416
3417 // Load obj->elements in |scratch|.
3418 loadPtr(Address(obj, NativeObject::offsetOfElements()), scratch);
3419
3420 // If backed by non-shared memory, detached and out-of-bounds both return
3421 // zero, so we're done here.
3422 branchTest32(Assembler::Zero,
3423 Address(scratch, ObjectElements::offsetOfFlags()),
3424 Imm32(ObjectElements::SHARED_MEMORY), &done);
3425
3426 // Load the auto-length slot.
3427 unboxBoolean(Address(obj, ArrayBufferViewObject::autoLengthOffset()),
3428 scratch);
3429
3430 // If non-auto length, there's nothing to do.
3431 branchTest32(Assembler::Zero, scratch, scratch, &done);
3432
3433 // Load bufferByteLength into |output|.
3434 {
3435 // Resizable TypedArrays are guaranteed to have an ArrayBuffer.
3436 unboxObject(Address(obj, ArrayBufferViewObject::bufferOffset()), output);
3437
3438 // Load the byte length from the raw-buffer of growable SharedArrayBuffers.
3439 loadGrowableSharedArrayBufferByteLengthIntPtr(sync, output, output);
3440 }
3441
3442 // Load the byteOffset into |scratch|.
3443 loadArrayBufferViewByteOffsetIntPtr(obj, scratch);
3444
3445 // Compute the accessible byte length |bufferByteLength - byteOffset|.
3446 subPtr(scratch, output);
3447
3448 if (view == ResizableArrayBufferView::TypedArray) {
3449 // Compute the array length from the byte length.
3450 resizableTypedArrayElementShiftBy(obj, output, scratch);
3451 }
3452
3453 bind(&done);
3454 }
3455
3456 void MacroAssembler::loadResizableTypedArrayByteOffsetMaybeOutOfBoundsIntPtr(
3457 Register obj, Register output, Register scratch) {
3458 // Inline implementation of TypedArrayObject::byteOffsetMaybeOutOfBounds(),
3459 // when the input is guaranteed to be a resizable typed array object.
3460
3461 loadArrayBufferViewByteOffsetIntPtr(obj, output);
3462
3463 // TypedArray is neither detached nor out-of-bounds when byteOffset non-zero.
3464 Label done;
3465 branchPtr(Assembler::NotEqual, output, ImmWord(0), &done);
3466
3467 // We're done when the initial byteOffset is zero.
3468 loadPrivate(Address(obj, ArrayBufferViewObject::initialByteOffsetOffset()),
3469 output);
3470 branchPtr(Assembler::Equal, output, ImmWord(0), &done);
3471
3472 // If the buffer is attached, return initialByteOffset.
3473 branchIfHasAttachedArrayBuffer(obj, scratch, &done);
3474
3475 // Otherwise return zero to match the result for fixed-length TypedArrays.
3476 movePtr(ImmWord(0), output);
3477
3478 bind(&done);
3479 }
3480
3481 void MacroAssembler::dateFillLocalTimeSlots(
3482 Register obj, Register scratch, const LiveRegisterSet& volatileRegs) {
3483 // Inline implementation of the cache check from
3484 // DateObject::fillLocalTimeSlots().
3485
3486 Label callVM, done;
3487
3488 // Check if the cache is already populated.
3489 branchTestUndefined(Assembler::Equal,
3490 Address(obj, DateObject::offsetOfLocalTimeSlot()),
3491 &callVM);
3492
3493 unboxInt32(Address(obj, DateObject::offsetOfUTCTimeZoneOffsetSlot()),
3494 scratch);
3495
3496 branch32(Assembler::Equal,
3497 AbsoluteAddress(DateTimeInfo::addressOfUTCToLocalOffsetSeconds()),
3498 scratch, &done);
3499
3500 bind(&callVM);
3501 {
3502 PushRegsInMask(volatileRegs);
3503
3504 using Fn = void (*)(DateObject*);
3505 setupUnalignedABICall(scratch);
3506 passABIArg(obj);
3507 callWithABI<Fn, jit::DateFillLocalTimeSlots>();
3508
3509 PopRegsInMask(volatileRegs);
3510 }
3511
3512 bind(&done);
3513 }
3514
3515 void MacroAssembler::udiv32ByConstant(Register src, uint32_t divisor,
3516 Register dest) {
3517 auto rmc = ReciprocalMulConstants::computeUnsignedDivisionConstants(divisor);
3518 MOZ_ASSERT(rmc.multiplier <= UINT32_MAX, "division needs scratch register");
3519
3520 // We first compute |q = (M * n) >> 32), where M = rmc.multiplier.
3521 mulHighUnsigned32(Imm32(rmc.multiplier), src, dest);
3522
3523 // Finish the computation |q = floor(n / d)|.
3524 rshift32(Imm32(rmc.shiftAmount), dest);
3525 }
3526
3527 void MacroAssembler::umod32ByConstant(Register src, uint32_t divisor,
3528 Register dest, Register scratch) {
3529 MOZ_ASSERT(dest != scratch);
3530
3531 auto rmc = ReciprocalMulConstants::computeUnsignedDivisionConstants(divisor);
3532 MOZ_ASSERT(rmc.multiplier <= UINT32_MAX, "division needs scratch register");
3533
3534 if (src != dest) {
3535 move32(src, dest);
3536 }
3537
3538 // We first compute |q = (M * n) >> 32), where M = rmc.multiplier.
3539 mulHighUnsigned32(Imm32(rmc.multiplier), dest, scratch);
3540
3541 // Finish the computation |q = floor(n / d)|.
3542 rshift32(Imm32(rmc.shiftAmount), scratch);
3543
3544 // Compute the remainder from |r = n - q * d|.
3545 mul32(Imm32(divisor), scratch);
3546 sub32(scratch, dest);
3547 }
3548
3549 template <typename GetTimeFn>
3550 void MacroAssembler::dateTimeFromSecondsIntoYear(ValueOperand secondsIntoYear,
3551 ValueOperand output,
3552 Register scratch1,
3553 Register scratch2,
3554 GetTimeFn getTimeFn) {
3555 #ifdef DEBUG
3556 Label okValue;
3557 branchTestInt32(Assembler::Equal, secondsIntoYear, &okValue);
3558 branchTestNaNValue(Assembler::Equal, secondsIntoYear, scratch1, &okValue);
3559 assumeUnreachable("secondsIntoYear is an int32 or NaN");
3560 bind(&okValue);
3561 #endif
3562
3563 moveValue(secondsIntoYear, output);
3564
3565 Label done;
3566 fallibleUnboxInt32(secondsIntoYear, scratch1, &done);
3567
3568 #ifdef DEBUG
3569 Label okInt;
3570 branchTest32(Assembler::NotSigned, scratch1, scratch1, &okInt);
3571 assumeUnreachable("secondsIntoYear is an unsigned int32");
3572 bind(&okInt);
3573 #endif
3574
3575 getTimeFn(scratch1, scratch1, scratch2);
3576
3577 tagValue(JSVAL_TYPE_INT32, scratch1, output);
3578
3579 bind(&done);
3580 }
3581
3582 void MacroAssembler::dateHoursFromSecondsIntoYear(ValueOperand secondsIntoYear,
3583 ValueOperand output,
3584 Register scratch1,
3585 Register scratch2) {
3586 // Inline implementation of seconds-into-year to local hours computation from
3587 // date_getHours.
3588
3589 // Compute `(yearSeconds / SecondsPerHour) % HoursPerDay`.
3590 auto hoursFromSecondsIntoYear = [this](Register src, Register dest,
3591 Register scratch) {
3592 udiv32ByConstant(src, SecondsPerHour, dest);
3593 umod32ByConstant(dest, HoursPerDay, dest, scratch);
3594 };
3595
3596 dateTimeFromSecondsIntoYear(secondsIntoYear, output, scratch1, scratch2,
3597 hoursFromSecondsIntoYear);
3598 }
3599
3600 void MacroAssembler::dateMinutesFromSecondsIntoYear(
3601 ValueOperand secondsIntoYear, ValueOperand output, Register scratch1,
3602 Register scratch2) {
3603 // Inline implementation of seconds-into-year to local minutes computation
3604 // from date_getMinutes.
3605
3606 // Compute `(yearSeconds / SecondsPerMinute) % MinutesPerHour`.
3607 auto minutesFromSecondsIntoYear = [this](Register src, Register dest,
3608 Register scratch) {
3609 udiv32ByConstant(src, SecondsPerMinute, dest);
3610 umod32ByConstant(dest, MinutesPerHour, dest, scratch);
3611 };
3612
3613 dateTimeFromSecondsIntoYear(secondsIntoYear, output, scratch1, scratch2,
3614 minutesFromSecondsIntoYear);
3615 }
3616
3617 void MacroAssembler::dateSecondsFromSecondsIntoYear(
3618 ValueOperand secondsIntoYear, ValueOperand output, Register scratch1,
3619 Register scratch2) {
3620 // Inline implementation of seconds-into-year to local seconds computation
3621 // from date_getSeconds.
3622
3623 // Compute `yearSeconds % SecondsPerMinute`.
3624 auto secondsFromSecondsIntoYear = [this](Register src, Register dest,
3625 Register scratch) {
3626 umod32ByConstant(src, SecondsPerMinute, dest, scratch);
3627 };
3628
3629 dateTimeFromSecondsIntoYear(secondsIntoYear, output, scratch1, scratch2,
3630 secondsFromSecondsIntoYear);
3631 }
3632
3633 void MacroAssembler::computeImplicitThis(Register env, ValueOperand output,
3634 Label* slowPath) {
3635 // Inline implementation of ComputeImplicitThis.
3636
3637 Register scratch = output.scratchReg();
3638 MOZ_ASSERT(scratch != env);
3639
3640 loadObjClassUnsafe(env, scratch);
3641
3642 // Go to the slow path for possible debug environment proxies.
3643 branchTestClassIsProxy(true, scratch, slowPath);
3644
3645 // WithEnvironmentObjects have an actual implicit |this|.
3646 Label nonWithEnv, done;
3647 branchPtr(Assembler::NotEqual, scratch,
3648 ImmPtr(&WithEnvironmentObject::class_), &nonWithEnv);
3649 {
3650 if (JitOptions.spectreObjectMitigations) {
3651 spectreZeroRegister(Assembler::NotEqual, scratch, env);
3652 }
3653
3654 loadValue(Address(env, WithEnvironmentObject::offsetOfThisSlot()), output);
3655
3656 jump(&done);
3657 }
3658 bind(&nonWithEnv);
3659
3660 // The implicit |this| is |undefined| for all environment types except
3661 // WithEnvironmentObject.
3662 moveValue(JS::UndefinedValue(), output);
3663
3664 bind(&done);
3665 }
3666
3667 void MacroAssembler::loadDOMExpandoValueGuardGeneration(
3668 Register obj, ValueOperand output,
3669 JS::ExpandoAndGeneration* expandoAndGeneration, uint64_t generation,
3670 Label* fail) {
3671 loadPtr(Address(obj, ProxyObject::offsetOfReservedSlots()),
3672 output.scratchReg());
3673 loadValue(Address(output.scratchReg(),
3674 js::detail::ProxyReservedSlots::offsetOfPrivateSlot()),
3675 output);
3676
3677 // Guard the ExpandoAndGeneration* matches the proxy's ExpandoAndGeneration
3678 // privateSlot.
3679 branchTestValue(Assembler::NotEqual, output,
3680 PrivateValue(expandoAndGeneration), fail);
3681
3682 // Guard expandoAndGeneration->generation matches the expected generation.
3683 Address generationAddr(output.payloadOrValueReg(),
3684 JS::ExpandoAndGeneration::offsetOfGeneration());
3685 branch64(Assembler::NotEqual, generationAddr, Imm64(generation), fail);
3686
3687 // Load expandoAndGeneration->expando into the output Value register.
3688 loadValue(Address(output.payloadOrValueReg(),
3689 JS::ExpandoAndGeneration::offsetOfExpando()),
3690 output);
3691 }
3692
3693 void MacroAssembler::loadJitActivation(Register dest) {
3694 loadJSContext(dest);
3695 loadPtr(Address(dest, offsetof(JSContext, activation_)), dest);
3696 }
3697
3698 void MacroAssembler::loadBaselineCompileQueue(Register dest) {
3699 loadPtr(AbsoluteAddress(ContextRealmPtr(runtime())), dest);
3700 computeEffectiveAddress(Address(dest, Realm::offsetOfBaselineCompileQueue()),
3701 dest);
3702 }
3703
3704 void MacroAssembler::guardSpecificAtom(Register str, JSAtom* atom,
3705 Register scratch,
3706 const LiveRegisterSet& volatileRegs,
3707 Label* fail) {
3708 Label done, notCachedAtom;
3709 branchPtr(Assembler::Equal, str, ImmGCPtr(atom), &done);
3710
3711 // The pointers are not equal, so if the input string is also an atom it
3712 // must be a different string.
3713 branchTest32(Assembler::NonZero, Address(str, JSString::offsetOfFlags()),
3714 Imm32(JSString::ATOM_BIT), fail);
3715
3716 // Try to do a cheap atomize on the string and repeat the above test
3717 tryFastAtomize(str, scratch, scratch, &notCachedAtom);
3718 branchPtr(Assembler::Equal, scratch, ImmGCPtr(atom), &done);
3719 jump(fail);
3720 bind(&notCachedAtom);
3721
3722 // Check the length.
3723 branch32(Assembler::NotEqual, Address(str, JSString::offsetOfLength()),
3724 Imm32(atom->length()), fail);
3725
3726 // Compare short atoms using inline assembly.
3727 if (canCompareStringCharsInline(atom)) {
3728 // Pure two-byte strings can't be equal to Latin-1 strings.
3729 if (atom->hasTwoByteChars()) {
3730 JS::AutoCheckCannotGC nogc;
3731 if (!mozilla::IsUtf16Latin1(atom->twoByteRange(nogc))) {
3732 branchLatin1String(str, fail);
3733 }
3734 }
3735
3736 // Call into the VM when the input is a rope or has a different encoding.
3737 Label vmCall;
3738
3739 // Load the input string's characters.
3740 Register stringChars = scratch;
3741 loadStringCharsForCompare(str, atom, stringChars, &vmCall);
3742
3743 // Start comparing character by character.
3744 branchIfNotStringCharsEquals(stringChars, atom, fail);
3745
3746 // Falls through if both strings are equal.
3747 jump(&done);
3748
3749 bind(&vmCall);
3750 }
3751
3752 // We have a non-atomized string with the same length. Call a helper
3753 // function to do the comparison.
3754 PushRegsInMask(volatileRegs);
3755
3756 using Fn = bool (*)(JSString* str1, JSString* str2);
3757 setupUnalignedABICall(scratch);
3758 movePtr(ImmGCPtr(atom), scratch);
3759 passABIArg(scratch);
3760 passABIArg(str);
3761 callWithABI<Fn, EqualStringsHelperPure>();
3762 storeCallPointerResult(scratch);
3763
3764 MOZ_ASSERT(!volatileRegs.has(scratch));
3765 PopRegsInMask(volatileRegs);
3766 branchIfFalseBool(scratch, fail);
3767
3768 bind(&done);
3769 }
3770
3771 void MacroAssembler::guardStringToInt32(Register str, Register output,
3772 Register scratch,
3773 LiveRegisterSet volatileRegs,
3774 Label* fail) {
3775 Label vmCall, done;
3776 // Use indexed value as fast path if possible.
3777 loadStringIndexValue(str, output, &vmCall);
3778 jump(&done);
3779 {
3780 bind(&vmCall);
3781
3782 // Reserve space for holding the result int32_t of the call. Use
3783 // pointer-size to avoid misaligning the stack on 64-bit platforms.
3784 reserveStack(sizeof(uintptr_t));
3785 moveStackPtrTo(output);
3786
3787 volatileRegs.takeUnchecked(scratch);
3788 if (output.volatile_()) {
3789 volatileRegs.addUnchecked(output);
3790 }
3791 PushRegsInMask(volatileRegs);
3792
3793 using Fn = bool (*)(JSContext* cx, JSString* str, int32_t* result);
3794 setupUnalignedABICall(scratch);
3795 loadJSContext(scratch);
3796 passABIArg(scratch);
3797 passABIArg(str);
3798 passABIArg(output);
3799 callWithABI<Fn, GetInt32FromStringPure>();
3800 storeCallPointerResult(scratch);
3801
3802 PopRegsInMask(volatileRegs);
3803
3804 Label ok;
3805 branchIfTrueBool(scratch, &ok);
3806 {
3807 // OOM path, recovered by GetInt32FromStringPure.
3808 //
3809 // Use addToStackPtr instead of freeStack as freeStack tracks stack height
3810 // flow-insensitively, and using it twice would confuse the stack height
3811 // tracking.
3812 addToStackPtr(Imm32(sizeof(uintptr_t)));
3813 jump(fail);
3814 }
3815 bind(&ok);
3816 load32(Address(output, 0), output);
3817 freeStack(sizeof(uintptr_t));
3818 }
3819 bind(&done);
3820 }
3821
3822 void MacroAssembler::generateBailoutTail(Register scratch,
3823 Register bailoutInfo) {
3824 Label bailoutFailed;
3825 branchIfFalseBool(ReturnReg, &bailoutFailed);
3826
3827 // Finish bailing out to Baseline.
3828 {
3829 // Prepare a register set for use in this case.
3830 AllocatableGeneralRegisterSet regs(GeneralRegisterSet::All());
3831 MOZ_ASSERT_IF(!IsHiddenSP(getStackPointer()),
3832 !regs.has(AsRegister(getStackPointer())));
3833 regs.take(bailoutInfo);
3834
3835 Register temp = regs.takeAny();
3836
3837 #ifdef DEBUG
3838 // Assert the stack pointer points to the JitFrameLayout header. Copying
3839 // starts here.
3840 Label ok;
3841 loadPtr(Address(bailoutInfo, offsetof(BaselineBailoutInfo, incomingStack)),
3842 temp);
3843 branchStackPtr(Assembler::Equal, temp, &ok);
3844 assumeUnreachable("Unexpected stack pointer value");
3845 bind(&ok);
3846 #endif
3847
3848 Register copyCur = regs.takeAny();
3849 Register copyEnd = regs.takeAny();
3850
3851 // Copy data onto stack.
3852 loadPtr(Address(bailoutInfo, offsetof(BaselineBailoutInfo, copyStackTop)),
3853 copyCur);
3854 loadPtr(
3855 Address(bailoutInfo, offsetof(BaselineBailoutInfo, copyStackBottom)),
3856 copyEnd);
3857 {
3858 Label copyLoop;
3859 Label endOfCopy;
3860 bind(&copyLoop);
3861 branchPtr(Assembler::BelowOrEqual, copyCur, copyEnd, &endOfCopy);
3862 subPtr(Imm32(sizeof(uintptr_t)), copyCur);
3863 subFromStackPtr(Imm32(sizeof(uintptr_t)));
3864 loadPtr(Address(copyCur, 0), temp);
3865 storePtr(temp, Address(getStackPointer(), 0));
3866 jump(&copyLoop);
3867 bind(&endOfCopy);
3868 }
3869
3870 loadPtr(Address(bailoutInfo, offsetof(BaselineBailoutInfo, resumeFramePtr)),
3871 FramePointer);
3872
3873 // Enter exit frame for the FinishBailoutToBaseline call.
3874 pushFrameDescriptor(FrameType::BaselineJS);
3875 push(Address(bailoutInfo, offsetof(BaselineBailoutInfo, resumeAddr)));
3876 push(FramePointer);
3877 // No GC things to mark on the stack, push a bare token.
3878 loadJSContext(scratch);
3879 enterFakeExitFrame(scratch, scratch, ExitFrameType::Bare);
3880
3881 // Save needed values onto stack temporarily.
3882 push(Address(bailoutInfo, offsetof(BaselineBailoutInfo, resumeAddr)));
3883
3884 // Call a stub to free allocated memory and create arguments objects.
3885 using Fn = bool (*)(BaselineBailoutInfo* bailoutInfoArg);
3886 setupUnalignedABICall(temp);
3887 passABIArg(bailoutInfo);
3888 callWithABI<Fn, FinishBailoutToBaseline>(
3889 ABIType::General, CheckUnsafeCallWithABI::DontCheckHasExitFrame);
3890 branchIfFalseBool(ReturnReg, exceptionLabel());
3891
3892 // Restore values where they need to be and resume execution.
3893 AllocatableGeneralRegisterSet enterRegs(GeneralRegisterSet::All());
3894 MOZ_ASSERT(!enterRegs.has(FramePointer));
3895 Register jitcodeReg = enterRegs.takeAny();
3896
3897 pop(jitcodeReg);
3898
3899 // Discard exit frame.
3900 addToStackPtr(Imm32(ExitFrameLayout::SizeWithFooter()));
3901
3902 jump(jitcodeReg);
3903 }
3904
3905 bind(&bailoutFailed);
3906 {
3907 // jit::Bailout or jit::InvalidationBailout failed and returned false. The
3908 // Ion frame has already been discarded and the stack pointer points to the
3909 // JitFrameLayout header. Turn it into an ExitFrameLayout, similar to
3910 // EnsureUnwoundJitExitFrame, and call the exception handler.
3911 loadJSContext(scratch);
3912 enterFakeExitFrame(scratch, scratch, ExitFrameType::UnwoundJit);
3913 jump(exceptionLabel());
3914 }
3915 }
3916
3917 void MacroAssembler::loadJitCodeRaw(Register func, Register dest) {
3918 static_assert(BaseScript::offsetOfJitCodeRaw() ==
3919 SelfHostedLazyScript::offsetOfJitCodeRaw(),
3920 "SelfHostedLazyScript and BaseScript must use same layout for "
3921 "jitCodeRaw_");
3922 static_assert(
3923 BaseScript::offsetOfJitCodeRaw() == wasm::JumpTableJitEntryOffset,
3924 "Wasm exported functions jit entries must use same layout for "
3925 "jitCodeRaw_");
3926 loadPrivate(Address(func, JSFunction::offsetOfJitInfoOrScript()), dest);
3927 loadPtr(Address(dest, BaseScript::offsetOfJitCodeRaw()), dest);
3928 }
3929
3930 void MacroAssembler::loadBaselineJitCodeRaw(Register func, Register dest,
3931 Label* failure) {
3932 // Load JitScript
3933 loadPrivate(Address(func, JSFunction::offsetOfJitInfoOrScript()), dest);
3934 if (failure) {
3935 branchIfScriptHasNoJitScript(dest, failure);
3936 }
3937 loadJitScript(dest, dest);
3938
3939 // Load BaselineScript
3940 loadPtr(Address(dest, JitScript::offsetOfBaselineScript()), dest);
3941 if (failure) {
3942 static_assert(DisabledScript < CompilingScript);
3943 branchPtr(Assembler::BelowOrEqual, dest, ImmWord(CompilingScript), failure);
3944 }
3945
3946 // Load Baseline jitcode
3947 loadPtr(Address(dest, BaselineScript::offsetOfMethod()), dest);
3948 loadPtr(Address(dest, JitCode::offsetOfCode()), dest);
3949 }
3950
3951 void MacroAssembler::loadBaselineFramePtr(Register framePtr, Register dest) {
3952 if (framePtr != dest) {
3953 movePtr(framePtr, dest);
3954 }
3955 subPtr(Imm32(BaselineFrame::Size()), dest);
3956 }
3957
3958 void MacroAssembler::storeICScriptInJSContext(Register icScript) {
3959 storePtr(icScript, AbsoluteAddress(runtime()->addressOfInlinedICScript()));
3960 }
3961
3962 void MacroAssembler::handleFailure() {
3963 // Re-entry code is irrelevant because the exception will leave the
3964 // running function and never come back
3965 TrampolinePtr excTail = runtime()->jitRuntime()->getExceptionTail();
3966 jump(excTail);
3967 }
3968
3969 void MacroAssembler::assumeUnreachable(const char* output) {
3970 #ifdef JS_MASM_VERBOSE
3971 if (!IsCompilingWasm()) {
3972 AllocatableRegisterSet regs(RegisterSet::Volatile());
3973 LiveRegisterSet save(regs.asLiveSet());
3974 PushRegsInMask(save);
3975 Register temp = regs.takeAnyGeneral();
3976
3977 using Fn = void (*)(const char* output);
3978 setupUnalignedABICall(temp);
3979 movePtr(ImmPtr(output), temp);
3980 passABIArg(temp);
3981 callWithABI<Fn, AssumeUnreachable>(ABIType::General,
3982 CheckUnsafeCallWithABI::DontCheckOther);
3983
3984 PopRegsInMask(save);
3985 }
3986 #endif
3987
3988 breakpoint();
3989 }
3990
3991 void MacroAssembler::printf(const char* output) {
3992 #ifdef JS_MASM_VERBOSE
3993 AllocatableRegisterSet regs(RegisterSet::Volatile());
3994 LiveRegisterSet save(regs.asLiveSet());
3995 PushRegsInMask(save);
3996
3997 Register temp = regs.takeAnyGeneral();
3998
3999 using Fn = void (*)(const char* output);
4000 setupUnalignedABICall(temp);
4001 movePtr(ImmPtr(output), temp);
4002 passABIArg(temp);
4003 callWithABI<Fn, Printf0>();
4004
4005 PopRegsInMask(save);
4006 #endif
4007 }
4008
4009 void MacroAssembler::printf(const char* output, Register value) {
4010 #ifdef JS_MASM_VERBOSE
4011 AllocatableRegisterSet regs(RegisterSet::Volatile());
4012 LiveRegisterSet save(regs.asLiveSet());
4013 PushRegsInMask(save);
4014
4015 regs.takeUnchecked(value);
4016
4017 Register temp = regs.takeAnyGeneral();
4018
4019 using Fn = void (*)(const char* output, uintptr_t value);
4020 setupUnalignedABICall(temp);
4021 movePtr(ImmPtr(output), temp);
4022 passABIArg(temp);
4023 passABIArg(value);
4024 callWithABI<Fn, Printf1>();
4025
4026 PopRegsInMask(save);
4027 #endif
4028 }
4029
4030 void MacroAssembler::convertInt32ValueToDouble(ValueOperand val) {
4031 Label done;
4032 branchTestInt32(Assembler::NotEqual, val, &done);
4033 ScratchDoubleScope fpscratch(*this);
4034 convertInt32ToDouble(val.payloadOrValueReg(), fpscratch);
4035 boxDouble(fpscratch, val, fpscratch);
4036 bind(&done);
4037 }
4038
4039 void MacroAssembler::convertValueToFloatingPoint(
4040 ValueOperand value, FloatRegister output, Register maybeTemp,
4041 LiveRegisterSet volatileLiveRegs, Label* fail,
4042 FloatingPointType outputType) {
4043 Label isDouble, isInt32OrBool, isNull, done;
4044
4045 {
4046 ScratchTagScope tag(*this, value);
4047 splitTagForTest(value, tag);
4048
4049 branchTestDouble(Assembler::Equal, tag, &isDouble);
4050 branchTestInt32(Assembler::Equal, tag, &isInt32OrBool);
4051 branchTestBoolean(Assembler::Equal, tag, &isInt32OrBool);
4052 branchTestNull(Assembler::Equal, tag, &isNull);
4053 branchTestUndefined(Assembler::NotEqual, tag, fail);
4054 }
4055
4056 // fall-through: undefined
4057 if (outputType == FloatingPointType::Float16 ||
4058 outputType == FloatingPointType::Float32) {
4059 loadConstantFloat32(float(GenericNaN()), output);
4060 } else {
4061 loadConstantDouble(GenericNaN(), output);
4062 }
4063 jump(&done);
4064
4065 bind(&isNull);
4066 if (outputType == FloatingPointType::Float16 ||
4067 outputType == FloatingPointType::Float32) {
4068 loadConstantFloat32(0.0f, output);
4069 } else {
4070 loadConstantDouble(0.0, output);
4071 }
4072 jump(&done);
4073
4074 bind(&isInt32OrBool);
4075 if (outputType == FloatingPointType::Float16) {
4076 convertInt32ToFloat16(value.payloadOrValueReg(), output, maybeTemp,
4077 volatileLiveRegs);
4078 } else if (outputType == FloatingPointType::Float32) {
4079 convertInt32ToFloat32(value.payloadOrValueReg(), output);
4080 } else {
4081 convertInt32ToDouble(value.payloadOrValueReg(), output);
4082 }
4083 jump(&done);
4084
4085 // On some non-multiAlias platforms, unboxDouble may use the scratch register,
4086 // so do not merge code paths here.
4087 bind(&isDouble);
4088 if ((outputType == FloatingPointType::Float16 ||
4089 outputType == FloatingPointType::Float32) &&
4090 hasMultiAlias()) {
4091 ScratchDoubleScope tmp(*this);
4092 unboxDouble(value, tmp);
4093
4094 if (outputType == FloatingPointType::Float16) {
4095 convertDoubleToFloat16(tmp, output, maybeTemp, volatileLiveRegs);
4096 } else {
4097 convertDoubleToFloat32(tmp, output);
4098 }
4099 } else {
4100 FloatRegister tmp = output.asDouble();
4101 unboxDouble(value, tmp);
4102
4103 if (outputType == FloatingPointType::Float16) {
4104 convertDoubleToFloat16(tmp, output, maybeTemp, volatileLiveRegs);
4105 } else if (outputType == FloatingPointType::Float32) {
4106 convertDoubleToFloat32(tmp, output);
4107 }
4108 }
4109
4110 bind(&done);
4111 }
4112
4113 void MacroAssembler::outOfLineTruncateSlow(FloatRegister src, Register dest,
4114 bool widenFloatToDouble,
4115 bool compilingWasm,
4116 wasm::BytecodeOffset callOffset) {
4117 ScratchDoubleScope fpscratch(*this);
4118 if (widenFloatToDouble) {
4119 convertFloat32ToDouble(src, fpscratch);
4120 src = fpscratch;
4121 }
4122 MOZ_ASSERT(src.isDouble());
4123
4124 if (compilingWasm) {
4125 Push(InstanceReg);
4126 int32_t framePushedAfterInstance = framePushed();
4127
4128 setupWasmABICall();
4129 passABIArg(src, ABIType::Float64);
4130
4131 int32_t instanceOffset = framePushed() - framePushedAfterInstance;
4132 callWithABI(callOffset, wasm::SymbolicAddress::ToInt32,
4133 mozilla::Some(instanceOffset));
4134 storeCallInt32Result(dest);
4135
4136 Pop(InstanceReg);
4137 } else {
4138 using Fn = int32_t (*)(double);
4139 setupUnalignedABICall(dest);
4140 passABIArg(src, ABIType::Float64);
4141 callWithABI<Fn, JS::ToInt32>(ABIType::General,
4142 CheckUnsafeCallWithABI::DontCheckOther);
4143 storeCallInt32Result(dest);
4144 }
4145 }
4146
4147 void MacroAssembler::convertValueToInt32(ValueOperand value, FloatRegister temp,
4148 Register output, Label* fail,
4149 bool negativeZeroCheck,
4150 IntConversionInputKind conversion) {
4151 Label done, isInt32, isBool, isDouble, isString;
4152
4153 {
4154 ScratchTagScope tag(*this, value);
4155 splitTagForTest(value, tag);
4156
4157 branchTestInt32(Equal, tag, &isInt32);
4158 branchTestDouble(Equal, tag, &isDouble);
4159 if (conversion == IntConversionInputKind::Any) {
4160 branchTestBoolean(Equal, tag, &isBool);
4161 branchTestNull(Assembler::NotEqual, tag, fail);
4162 } else {
4163 jump(fail);
4164 }
4165 }
4166
4167 // The value is null - just emit 0.
4168 if (conversion == IntConversionInputKind::Any) {
4169 move32(Imm32(0), output);
4170 jump(&done);
4171 }
4172
4173 // Try converting double into integer.
4174 {
4175 bind(&isDouble);
4176 unboxDouble(value, temp);
4177 convertDoubleToInt32(temp, output, fail, negativeZeroCheck);
4178 jump(&done);
4179 }
4180
4181 // Just unbox a bool, the result is 0 or 1.
4182 if (conversion == IntConversionInputKind::Any) {
4183 bind(&isBool);
4184 unboxBoolean(value, output);
4185 jump(&done);
4186 }
4187
4188 // Integers can be unboxed.
4189 {
4190 bind(&isInt32);
4191 unboxInt32(value, output);
4192 }
4193
4194 bind(&done);
4195 }
4196
4197 void MacroAssembler::truncateValueToInt32(
4198 ValueOperand value, Label* handleStringEntry, Label* handleStringRejoin,
4199 Label* truncateDoubleSlow, Register stringReg, FloatRegister temp,
4200 Register output, Label* fail) {
4201 Label done, isInt32, isBool, isDouble, isNull, isString;
4202
4203 bool handleStrings = handleStringEntry && handleStringRejoin;
4204
4205 // |output| needs to be different from |stringReg| to load string indices.
4206 MOZ_ASSERT_IF(handleStrings, stringReg != output);
4207
4208 {
4209 ScratchTagScope tag(*this, value);
4210 splitTagForTest(value, tag);
4211
4212 branchTestInt32(Equal, tag, &isInt32);
4213 branchTestDouble(Equal, tag, &isDouble);
4214 branchTestBoolean(Equal, tag, &isBool);
4215 branchTestNull(Equal, tag, &isNull);
4216 if (handleStrings) {
4217 branchTestString(Equal, tag, &isString);
4218 }
4219 branchTestUndefined(Assembler::NotEqual, tag, fail);
4220 }
4221
4222 // The value is null or undefined in truncation contexts - just emit 0.
4223 {
4224 bind(&isNull);
4225 move32(Imm32(0), output);
4226 jump(&done);
4227 }
4228
4229 // First try loading a string index. If that fails, try converting a string
4230 // into a double, then jump to the double case.
4231 Label handleStringIndex;
4232 if (handleStrings) {
4233 bind(&isString);
4234 unboxString(value, stringReg);
4235 loadStringIndexValue(stringReg, output, handleStringEntry);
4236 jump(&done);
4237 }
4238
4239 // Try converting double into integer.
4240 {
4241 bind(&isDouble);
4242 unboxDouble(value, temp);
4243
4244 if (handleStrings) {
4245 bind(handleStringRejoin);
4246 }
4247 branchTruncateDoubleMaybeModUint32(
4248 temp, output, truncateDoubleSlow ? truncateDoubleSlow : fail);
4249 jump(&done);
4250 }
4251
4252 // Just unbox a bool, the result is 0 or 1.
4253 {
4254 bind(&isBool);
4255 unboxBoolean(value, output);
4256 jump(&done);
4257 }
4258
4259 // Integers can be unboxed.
4260 {
4261 bind(&isInt32);
4262 unboxInt32(value, output);
4263 }
4264
4265 bind(&done);
4266 }
4267
4268 void MacroAssembler::clampValueToUint8(ValueOperand value,
4269 Label* handleStringEntry,
4270 Label* handleStringRejoin,
4271 Register stringReg, FloatRegister temp,
4272 Register output, Label* fail) {
4273 Label done, isInt32, isBool, isDouble, isNull, isString;
4274 {
4275 ScratchTagScope tag(*this, value);
4276 splitTagForTest(value, tag);
4277
4278 branchTestInt32(Equal, tag, &isInt32);
4279 branchTestDouble(Equal, tag, &isDouble);
4280 branchTestBoolean(Equal, tag, &isBool);
4281 branchTestNull(Equal, tag, &isNull);
4282 branchTestString(Equal, tag, &isString);
4283 branchTestUndefined(Assembler::NotEqual, tag, fail);
4284 }
4285
4286 // The value is null or undefined in truncation contexts - just emit 0.
4287 {
4288 bind(&isNull);
4289 move32(Imm32(0), output);
4290 jump(&done);
4291 }
4292
4293 // Try converting a string into a double, then jump to the double case.
4294 {
4295 bind(&isString);
4296 unboxString(value, stringReg);
4297 jump(handleStringEntry);
4298 }
4299
4300 // Try converting double into integer.
4301 {
4302 bind(&isDouble);
4303 unboxDouble(value, temp);
4304 bind(handleStringRejoin);
4305 clampDoubleToUint8(temp, output);
4306 jump(&done);
4307 }
4308
4309 // Just unbox a bool, the result is 0 or 1.
4310 {
4311 bind(&isBool);
4312 unboxBoolean(value, output);
4313 jump(&done);
4314 }
4315
4316 // Integers can be unboxed.
4317 {
4318 bind(&isInt32);
4319 unboxInt32(value, output);
4320 clampIntToUint8(output);
4321 }
4322
4323 bind(&done);
4324 }
4325
4326 void MacroAssembler::finish() {
4327 if (failureLabel_.used()) {
4328 bind(&failureLabel_);
4329 handleFailure();
4330 }
4331
4332 MacroAssemblerSpecific::finish();
4333
4334 MOZ_RELEASE_ASSERT(
4335 size() <= MaxCodeBytesPerProcess,
4336 "AssemblerBuffer should ensure we don't exceed MaxCodeBytesPerProcess");
4337
4338 if (bytesNeeded() > MaxCodeBytesPerProcess) {
4339 setOOM();
4340 }
4341 }
4342
4343 void MacroAssembler::link(JitCode* code) {
4344 MOZ_ASSERT(!oom());
4345 linkProfilerCallSites(code);
4346 }
4347
4348 MacroAssembler::AutoProfilerCallInstrumentation::
4349 AutoProfilerCallInstrumentation(MacroAssembler& masm) {
4350 if (!masm.emitProfilingInstrumentation_) {
4351 return;
4352 }
4353
4354 Register reg = CallTempReg0;
4355 Register reg2 = CallTempReg1;
4356 masm.push(reg);
4357 masm.push(reg2);
4358
4359 CodeOffset label = masm.movWithPatch(ImmWord(uintptr_t(-1)), reg);
4360 masm.loadJSContext(reg2);
4361 masm.loadPtr(Address(reg2, offsetof(JSContext, profilingActivation_)), reg2);
4362 masm.storePtr(reg,
4363 Address(reg2, JitActivation::offsetOfLastProfilingCallSite()));
4364
4365 masm.appendProfilerCallSite(label);
4366
4367 masm.pop(reg2);
4368 masm.pop(reg);
4369 }
4370
4371 void MacroAssembler::linkProfilerCallSites(JitCode* code) {
4372 for (size_t i = 0; i < profilerCallSites_.length(); i++) {
4373 CodeOffset offset = profilerCallSites_[i];
4374 CodeLocationLabel location(code, offset);
4375 PatchDataWithValueCheck(location, ImmPtr(location.raw()),
4376 ImmPtr((void*)-1));
4377 }
4378 }
4379
4380 void MacroAssembler::alignJitStackBasedOnNArgs(Register nargs,
4381 bool countIncludesThis) {
4382 // The stack should already be aligned to the size of a value.
4383 assertStackAlignment(sizeof(Value), 0);
4384
4385 static_assert(JitStackValueAlignment == 1 || JitStackValueAlignment == 2,
4386 "JitStackValueAlignment is either 1 or 2.");
4387 if (JitStackValueAlignment == 1) {
4388 return;
4389 }
4390 // A jit frame is composed of the following:
4391 //
4392 // [padding?] [argN] .. [arg1] [this] [[argc] [callee] [descr] [raddr]]
4393 // \________JitFrameLayout_________/
4394 // (The stack grows this way --->)
4395 //
4396 // We want to ensure that |raddr|, the return address, is 16-byte aligned.
4397 // (Note: if 8-byte alignment was sufficient, we would have already
4398 // returned above.)
4399
4400 // JitFrameLayout does not affect the alignment, so we can ignore it.
4401 static_assert(sizeof(JitFrameLayout) % JitStackAlignment == 0,
4402 "JitFrameLayout doesn't affect stack alignment");
4403
4404 // Therefore, we need to ensure that |this| is aligned.
4405 // This implies that |argN| must be aligned if N is even,
4406 // and offset by |sizeof(Value)| if N is odd.
4407
4408 // Depending on the context of the caller, it may be easier to pass in a
4409 // register that has already been modified to include |this|. If that is the
4410 // case, we want to flip the direction of the test.
4411 Assembler::Condition condition =
4412 countIncludesThis ? Assembler::NonZero : Assembler::Zero;
4413
4414 Label alignmentIsOffset, end;
4415 branchTestPtr(condition, nargs, Imm32(1), &alignmentIsOffset);
4416
4417 // |argN| should be aligned to 16 bytes.
4418 andToStackPtr(Imm32(~(JitStackAlignment - 1)));
4419 jump(&end);
4420
4421 // |argN| should be offset by 8 bytes from 16-byte alignment.
4422 // We already know that it is 8-byte aligned, so the only possibilities are:
4423 // a) It is 16-byte aligned, and we must offset it by 8 bytes.
4424 // b) It is not 16-byte aligned, and therefore already has the right offset.
4425 // Therefore, we test to see if it is 16-byte aligned, and adjust it if it is.
4426 bind(&alignmentIsOffset);
4427 branchTestStackPtr(Assembler::NonZero, Imm32(JitStackAlignment - 1), &end);
4428 subFromStackPtr(Imm32(sizeof(Value)));
4429
4430 bind(&end);
4431 }
4432
4433 void MacroAssembler::alignJitStackBasedOnNArgs(uint32_t argc,
4434 bool countIncludesThis) {
4435 // The stack should already be aligned to the size of a value.
4436 assertStackAlignment(sizeof(Value), 0);
4437
4438 static_assert(JitStackValueAlignment == 1 || JitStackValueAlignment == 2,
4439 "JitStackValueAlignment is either 1 or 2.");
4440 if (JitStackValueAlignment == 1) {
4441 return;
4442 }
4443
4444 // See above for full explanation.
4445 uint32_t nArgs = argc + !countIncludesThis;
4446 if (nArgs % 2 == 0) {
4447 // |argN| should be 16-byte aligned
4448 andToStackPtr(Imm32(~(JitStackAlignment - 1)));
4449 } else {
4450 // |argN| must be 16-byte aligned if argc is even,
4451 // and offset by 8 if argc is odd.
4452 Label end;
4453 branchTestStackPtr(Assembler::NonZero, Imm32(JitStackAlignment - 1), &end);
4454 subFromStackPtr(Imm32(sizeof(Value)));
4455 bind(&end);
4456 assertStackAlignment(JitStackAlignment, sizeof(Value));
4457 }
4458 }
4459
4460 // ===============================================================
4461
4462 MacroAssembler::MacroAssembler(TempAllocator& alloc,
4463 CompileRuntime* maybeRuntime,
4464 CompileRealm* maybeRealm)
4465 : maybeRuntime_(maybeRuntime),
4466 maybeRealm_(maybeRealm),
4467 framePushed_(0),
4468 #ifdef DEBUG
4469 inCall_(false),
4470 #endif
4471 dynamicAlignment_(false),
4472 emitProfilingInstrumentation_(false) {
4473 moveResolver_.setAllocator(alloc);
4474 }
4475
4476 StackMacroAssembler::StackMacroAssembler(JSContext* cx, TempAllocator& alloc)
4477 : MacroAssembler(alloc, CompileRuntime::get(cx->runtime()),
4478 CompileRealm::get(cx->realm())) {}
4479
4480 OffThreadMacroAssembler::OffThreadMacroAssembler(TempAllocator& alloc,
4481 CompileRealm* realm)
4482 : MacroAssembler(alloc, realm->runtime(), realm) {
4483 MOZ_ASSERT(CurrentThreadIsOffThreadCompiling());
4484 }
4485
4486 WasmMacroAssembler::WasmMacroAssembler(TempAllocator& alloc, bool limitedSize)
4487 : MacroAssembler(alloc) {
4488 #if defined(JS_CODEGEN_ARM64)
4489 // Stubs + builtins + the baseline compiler all require the native SP,
4490 // not the PSP.
4491 SetStackPointer64(sp);
4492 #endif
4493 if (!limitedSize) {
4494 setUnlimitedBuffer();
4495 }
4496 }
4497
4498 bool MacroAssembler::icBuildOOLFakeExitFrame(void* fakeReturnAddr,
4499 AutoSaveLiveRegisters& save) {
4500 return buildOOLFakeExitFrame(fakeReturnAddr);
4501 }
4502
4503 #ifndef JS_CODEGEN_ARM64
4504 void MacroAssembler::subFromStackPtr(Register reg) {
4505 subPtr(reg, getStackPointer());
4506 }
4507 #endif // JS_CODEGEN_ARM64
4508
4509 //{{{ check_macroassembler_style
4510 // ===============================================================
4511 // Stack manipulation functions.
4512
4513 void MacroAssembler::PushRegsInMask(LiveGeneralRegisterSet set) {
4514 PushRegsInMask(LiveRegisterSet(set.set(), FloatRegisterSet()));
4515 }
4516
4517 void MacroAssembler::PopRegsInMask(LiveRegisterSet set) {
4518 PopRegsInMaskIgnore(set, LiveRegisterSet());
4519 }
4520
4521 void MacroAssembler::PopRegsInMask(LiveGeneralRegisterSet set) {
4522 PopRegsInMask(LiveRegisterSet(set.set(), FloatRegisterSet()));
4523 }
4524
4525 void MacroAssembler::Push(PropertyKey key, Register scratchReg) {
4526 if (key.isGCThing()) {
4527 // If we're pushing a gcthing, then we can't just push the tagged key
4528 // value since the GC won't have any idea that the push instruction
4529 // carries a reference to a gcthing. Need to unpack the pointer,
4530 // push it using ImmGCPtr, and then rematerialize the PropertyKey at
4531 // runtime.
4532
4533 if (key.isString()) {
4534 JSString* str = key.toString();
4535 MOZ_ASSERT((uintptr_t(str) & PropertyKey::TypeMask) == 0);
4536 static_assert(PropertyKey::StringTypeTag == 0,
4537 "need to orPtr StringTypeTag if it's not 0");
4538 Push(ImmGCPtr(str));
4539 } else {
4540 MOZ_ASSERT(key.isSymbol());
4541 movePropertyKey(key, scratchReg);
4542 Push(scratchReg);
4543 }
4544 } else {
4545 MOZ_ASSERT(key.isInt());
4546 Push(ImmWord(key.asRawBits()));
4547 }
4548 }
4549
4550 void MacroAssembler::moveValue(const TypedOrValueRegister& src,
4551 const ValueOperand& dest) {
4552 if (src.hasValue()) {
4553 moveValue(src.valueReg(), dest);
4554 return;
4555 }
4556
4557 MIRType type = src.type();
4558 AnyRegister reg = src.typedReg();
4559
4560 if (!IsFloatingPointType(type)) {
4561 boxNonDouble(ValueTypeFromMIRType(type), reg.gpr(), dest);
4562 return;
4563 }
4564
4565 ScratchDoubleScope scratch(*this);
4566 FloatRegister freg = reg.fpu();
4567 if (type == MIRType::Float32) {
4568 convertFloat32ToDouble(freg, scratch);
4569 freg = scratch;
4570 }
4571 boxDouble(freg, dest, scratch);
4572 }
4573
4574 void MacroAssembler::movePropertyKey(PropertyKey key, Register dest) {
4575 if (key.isGCThing()) {
4576 // See comment in |Push(PropertyKey, ...)| above for an explanation.
4577 if (key.isString()) {
4578 JSString* str = key.toString();
4579 MOZ_ASSERT((uintptr_t(str) & PropertyKey::TypeMask) == 0);
4580 static_assert(PropertyKey::StringTypeTag == 0,
4581 "need to orPtr StringTypeTag tag if it's not 0");
4582 movePtr(ImmGCPtr(str), dest);
4583 } else {
4584 MOZ_ASSERT(key.isSymbol());
4585 JS::Symbol* sym = key.toSymbol();
4586 movePtr(ImmGCPtr(sym), dest);
4587 orPtr(Imm32(PropertyKey::SymbolTypeTag), dest);
4588 }
4589 } else {
4590 MOZ_ASSERT(key.isInt());
4591 movePtr(ImmWord(key.asRawBits()), dest);
4592 }
4593 }
4594
4595 void MacroAssembler::Push(TypedOrValueRegister v) {
4596 if (v.hasValue()) {
4597 Push(v.valueReg());
4598 } else if (IsFloatingPointType(v.type())) {
4599 FloatRegister reg = v.typedReg().fpu();
4600 if (v.type() == MIRType::Float32) {
4601 ScratchDoubleScope fpscratch(*this);
4602 convertFloat32ToDouble(reg, fpscratch);
4603 PushBoxed(fpscratch);
4604 } else {
4605 PushBoxed(reg);
4606 }
4607 } else {
4608 Push(ValueTypeFromMIRType(v.type()), v.typedReg().gpr());
4609 }
4610 }
4611
4612 void MacroAssembler::Push(const ConstantOrRegister& v) {
4613 if (v.constant()) {
4614 Push(v.value());
4615 } else {
4616 Push(v.reg());
4617 }
4618 }
4619
4620 void MacroAssembler::Push(const Address& addr) {
4621 push(addr);
4622 framePushed_ += sizeof(uintptr_t);
4623 }
4624
4625 void MacroAssembler::Push(const ValueOperand& val) {
4626 pushValue(val);
4627 framePushed_ += sizeof(Value);
4628 }
4629
4630 void MacroAssembler::Push(const Value& val) {
4631 pushValue(val);
4632 framePushed_ += sizeof(Value);
4633 }
4634
4635 void MacroAssembler::Push(JSValueType type, Register reg) {
4636 pushValue(type, reg);
4637 framePushed_ += sizeof(Value);
4638 }
4639
4640 void MacroAssembler::Push(const Register64 reg) {
4641 #if JS_BITS_PER_WORD == 64
4642 Push(reg.reg);
4643 #else
4644 MOZ_ASSERT(MOZ_LITTLE_ENDIAN(), "Big-endian not supported.");
4645 Push(reg.high);
4646 Push(reg.low);
4647 #endif
4648 }
4649
4650 void MacroAssembler::Pop(const Register64 reg) {
4651 #if JS_BITS_PER_WORD == 64
4652 Pop(reg.reg);
4653 #else
4654 MOZ_ASSERT(MOZ_LITTLE_ENDIAN(), "Big-endian not supported.");
4655 Pop(reg.low);
4656 Pop(reg.high);
4657 #endif
4658 }
4659
4660 void MacroAssembler::PushEmptyRooted(VMFunctionData::RootType rootType) {
4661 switch (rootType) {
4662 case VMFunctionData::RootNone:
4663 MOZ_CRASH("Handle must have root type");
4664 case VMFunctionData::RootObject:
4665 case VMFunctionData::RootString:
4666 case VMFunctionData::RootCell:
4667 case VMFunctionData::RootBigInt:
4668 Push(ImmPtr(nullptr));
4669 break;
4670 case VMFunctionData::RootValue:
4671 Push(UndefinedValue());
4672 break;
4673 case VMFunctionData::RootId:
4674 Push(ImmWord(JS::PropertyKey::Void().asRawBits()));
4675 break;
4676 }
4677 }
4678
4679 void MacroAssembler::adjustStack(int amount) {
4680 if (amount > 0) {
4681 freeStack(amount);
4682 } else if (amount < 0) {
4683 reserveStack(-amount);
4684 }
4685 }
4686
4687 void MacroAssembler::freeStack(uint32_t amount) {
4688 MOZ_ASSERT(amount <= framePushed_);
4689 if (amount) {
4690 addToStackPtr(Imm32(amount));
4691 }
4692 framePushed_ -= amount;
4693 }
4694
4695 void MacroAssembler::reserveVMFunctionOutParamSpace(const VMFunctionData& f) {
4696 switch (f.outParam) {
4697 case Type_Handle:
4698 PushEmptyRooted(f.outParamRootType);
4699 break;
4700
4701 case Type_Value:
4702 case Type_Double:
4703 case Type_Pointer:
4704 case Type_Int32:
4705 case Type_Bool:
4706 reserveStack(f.sizeOfOutParamStackSlot());
4707 break;
4708
4709 case Type_Void:
4710 break;
4711
4712 case Type_Cell:
4713 MOZ_CRASH("Unexpected outparam type");
4714 }
4715 }
4716
4717 void MacroAssembler::loadVMFunctionOutParam(const VMFunctionData& f,
4718 const Address& addr) {
4719 switch (f.outParam) {
4720 case Type_Handle:
4721 switch (f.outParamRootType) {
4722 case VMFunctionData::RootNone:
4723 MOZ_CRASH("Handle must have root type");
4724 case VMFunctionData::RootObject:
4725 case VMFunctionData::RootString:
4726 case VMFunctionData::RootCell:
4727 case VMFunctionData::RootBigInt:
4728 case VMFunctionData::RootId:
4729 loadPtr(addr, ReturnReg);
4730 break;
4731 case VMFunctionData::RootValue:
4732 loadValue(addr, JSReturnOperand);
4733 break;
4734 }
4735 break;
4736
4737 case Type_Value:
4738 loadValue(addr, JSReturnOperand);
4739 break;
4740
4741 case Type_Int32:
4742 load32(addr, ReturnReg);
4743 break;
4744
4745 case Type_Bool:
4746 load8ZeroExtend(addr, ReturnReg);
4747 break;
4748
4749 case Type_Double:
4750 loadDouble(addr, ReturnDoubleReg);
4751 break;
4752
4753 case Type_Pointer:
4754 loadPtr(addr, ReturnReg);
4755 break;
4756
4757 case Type_Void:
4758 break;
4759
4760 case Type_Cell:
4761 MOZ_CRASH("Unexpected outparam type");
4762 }
4763 }
4764
4765 // ===============================================================
4766 // ABI function calls.
4767 template <class ABIArgGeneratorT>
4768 void MacroAssembler::setupABICallHelper() {
4769 #ifdef DEBUG
4770 MOZ_ASSERT(!inCall_);
4771 inCall_ = true;
4772 #endif
4773
4774 #ifdef JS_SIMULATOR
4775 signature_ = 0;
4776 #endif
4777
4778 // Reinitialize the ABIArg generator.
4779 abiArgs_ = ABIArgGeneratorT();
4780
4781 #if defined(JS_CODEGEN_ARM)
4782 // On ARM, we need to know what ABI we are using.
4783 abiArgs_.setUseHardFp(ARMFlags::UseHardFpABI());
4784 #endif
4785 }
4786
4787 void MacroAssembler::setupNativeABICall() {
4788 setupABICallHelper<ABIArgGenerator>();
4789 }
4790
4791 void MacroAssembler::setupWasmABICall() {
4792 MOZ_ASSERT(IsCompilingWasm(), "non-wasm should use setupAlignedABICall");
4793 setupABICallHelper<WasmABIArgGenerator>();
4794
4795 #if defined(JS_CODEGEN_ARM)
4796 // The builtin thunk does the FP -> GPR moving on soft-FP, so
4797 // use hard fp unconditionally.
4798 abiArgs_.setUseHardFp(true);
4799 #endif
4800 dynamicAlignment_ = false;
4801 }
4802
4803 void MacroAssembler::setupUnalignedABICallDontSaveRestoreSP() {
4804 andToStackPtr(Imm32(~(ABIStackAlignment - 1)));
4805 setFramePushed(0); // Required for aligned callWithABI.
4806 setupAlignedABICall();
4807 }
4808
4809 void MacroAssembler::setupAlignedABICall() {
4810 MOZ_ASSERT(!IsCompilingWasm(), "wasm should use setupWasmABICall");
4811 setupNativeABICall();
4812 dynamicAlignment_ = false;
4813 }
4814
4815 void MacroAssembler::passABIArg(const MoveOperand& from, ABIType type) {
4816 MOZ_ASSERT(inCall_);
4817 appendSignatureType(type);
4818
4819 ABIArg arg;
4820 MoveOp::Type moveType;
4821 switch (type) {
4822 case ABIType::Float32:
4823 arg = abiArgs_.next(MIRType::Float32);
4824 moveType = MoveOp::FLOAT32;
4825 break;
4826 case ABIType::Float64:
4827 arg = abiArgs_.next(MIRType::Double);
4828 moveType = MoveOp::DOUBLE;
4829 break;
4830 case ABIType::General:
4831 arg = abiArgs_.next(MIRType::Pointer);
4832 moveType = MoveOp::GENERAL;
4833 break;
4834 default:
4835 MOZ_CRASH("Unexpected argument type");
4836 }
4837
4838 MoveOperand to(*this, arg);
4839 if (from == to) {
4840 return;
4841 }
4842
4843 if (oom()) {
4844 return;
4845 }
4846 propagateOOM(moveResolver_.addMove(from, to, moveType));
4847 }
4848
4849 void MacroAssembler::callWithABINoProfiler(void* fun, ABIType result,
4850 CheckUnsafeCallWithABI check) {
4851 appendSignatureType(result);
4852 #ifdef JS_SIMULATOR
4853 fun = Simulator::RedirectNativeFunction(fun, signature());
4854 #endif
4855
4856 uint32_t stackAdjust;
4857 callWithABIPre(&stackAdjust);
4858
4859 #ifdef JS_CHECK_UNSAFE_CALL_WITH_ABI
4860 if (check == CheckUnsafeCallWithABI::Check) {
4861 // Set the JSContext::inUnsafeCallWithABI flag.
4862 push(ReturnReg);
4863 loadJSContext(ReturnReg);
4864 Address flagAddr(ReturnReg, JSContext::offsetOfInUnsafeCallWithABI());
4865 store32(Imm32(1), flagAddr);
4866 pop(ReturnReg);
4867 // On arm64, SP may be < PSP now (that's OK).
4868 // eg testcase: tests/bug1375074.js
4869 }
4870 #endif
4871
4872 call(ImmPtr(fun));
4873
4874 callWithABIPost(stackAdjust, result);
4875
4876 #ifdef JS_CHECK_UNSAFE_CALL_WITH_ABI
4877 if (check == CheckUnsafeCallWithABI::Check) {
4878 // Check JSContext::inUnsafeCallWithABI was cleared as expected.
4879 Label ok;
4880 push(ReturnReg);
4881 loadJSContext(ReturnReg);
4882 Address flagAddr(ReturnReg, JSContext::offsetOfInUnsafeCallWithABI());
4883 branch32(Assembler::Equal, flagAddr, Imm32(0), &ok);
4884 assumeUnreachable("callWithABI: callee did not use AutoUnsafeCallWithABI");
4885 bind(&ok);
4886 pop(ReturnReg);
4887 // On arm64, SP may be < PSP now (that's OK).
4888 // eg testcase: tests/bug1375074.js
4889 }
4890 #endif
4891 }
4892
4893 CodeOffset MacroAssembler::callWithABI(wasm::BytecodeOffset bytecode,
4894 wasm::SymbolicAddress imm,
4895 mozilla::Maybe<int32_t> instanceOffset,
4896 ABIType result) {
4897 MOZ_ASSERT(wasm::NeedsBuiltinThunk(imm));
4898
4899 uint32_t stackAdjust;
4900 callWithABIPre(&stackAdjust, /* callFromWasm = */ true);
4901
4902 // The instance register is used in builtin thunks and must be set.
4903 if (instanceOffset) {
4904 loadPtr(Address(getStackPointer(), *instanceOffset + stackAdjust),
4905 InstanceReg);
4906 } else {
4907 MOZ_CRASH("instanceOffset is Nothing only for unsupported abi calls.");
4908 }
4909 CodeOffset raOffset = call(
4910 wasm::CallSiteDesc(bytecode.offset(), wasm::CallSiteKind::Symbolic), imm);
4911
4912 callWithABIPost(stackAdjust, result, /* callFromWasm = */ true);
4913
4914 return raOffset;
4915 }
4916
4917 void MacroAssembler::callDebugWithABI(wasm::SymbolicAddress imm,
4918 ABIType result) {
4919 MOZ_ASSERT(!wasm::NeedsBuiltinThunk(imm));
4920 uint32_t stackAdjust;
4921 callWithABIPre(&stackAdjust, /* callFromWasm = */ false);
4922 call(imm);
4923 callWithABIPost(stackAdjust, result, /* callFromWasm = */ false);
4924 }
4925
4926 // ===============================================================
4927 // Exit frame footer.
4928
4929 void MacroAssembler::linkExitFrame(Register cxreg, Register scratch) {
4930 loadPtr(Address(cxreg, JSContext::offsetOfActivation()), scratch);
4931 storeStackPtr(Address(scratch, JitActivation::offsetOfPackedExitFP()));
4932 }
4933
4934 // ===============================================================
4935 // Simple value-shuffling helpers, to hide MoveResolver verbosity
4936 // in common cases.
4937
4938 void MacroAssembler::moveRegPair(Register src0, Register src1, Register dst0,
4939 Register dst1, MoveOp::Type type) {
4940 MoveResolver& moves = moveResolver();
4941 if (src0 != dst0) {
4942 propagateOOM(moves.addMove(MoveOperand(src0), MoveOperand(dst0), type));
4943 }
4944 if (src1 != dst1) {
4945 propagateOOM(moves.addMove(MoveOperand(src1), MoveOperand(dst1), type));
4946 }
4947 propagateOOM(moves.resolve());
4948 if (oom()) {
4949 return;
4950 }
4951
4952 MoveEmitter emitter(*this);
4953 emitter.emit(moves);
4954 emitter.finish();
4955 }
4956
4957 // ===============================================================
4958 // Arithmetic functions
4959
4960 void MacroAssembler::pow32(Register base, Register power, Register dest,
4961 Register temp1, Register temp2, Label* onOver) {
4962 // Inline int32-specialized implementation of js::powi with overflow
4963 // detection.
4964
4965 move32(Imm32(1), dest); // result = 1
4966
4967 // x^y where x == 1 returns 1 for any y.
4968 Label done;
4969 branch32(Assembler::Equal, base, Imm32(1), &done);
4970
4971 // x^y where y < 0 returns a non-int32 value for any x != 1. Except when y is
4972 // large enough so that the result is no longer representable as a double with
4973 // fractional parts. We can't easily determine when y is too large, so we bail
4974 // here.
4975 // Note: it's important for this condition to match the code in CacheIR.cpp
4976 // (CanAttachInt32Pow) to prevent failure loops.
4977 branchTest32(Assembler::Signed, power, power, onOver);
4978
4979 move32(base, temp1); // runningSquare = x
4980 move32(power, temp2); // n = y
4981
4982 Label start;
4983 jump(&start);
4984
4985 Label loop;
4986 bind(&loop);
4987
4988 // runningSquare *= runningSquare
4989 branchMul32(Assembler::Overflow, temp1, temp1, onOver);
4990
4991 bind(&start);
4992
4993 // if ((n & 1) != 0) result *= runningSquare
4994 Label even;
4995 branchTest32(Assembler::Zero, temp2, Imm32(1), &even);
4996 branchMul32(Assembler::Overflow, temp1, dest, onOver);
4997 bind(&even);
4998
4999 // n >>= 1
5000 // if (n == 0) return result
5001 branchRshift32(Assembler::NonZero, Imm32(1), temp2, &loop);
5002
5003 bind(&done);
5004 }
5005
5006 void MacroAssembler::powPtr(Register base, Register power, Register dest,
5007 Register temp1, Register temp2, Label* onOver) {
5008 // Inline intptr-specialized implementation of BigInt::pow with overflow
5009 // detection.
5010
5011 // Negative exponents are disallowed for any BigInts.
5012 branchTestPtr(Assembler::Signed, power, power, onOver);
5013
5014 movePtr(ImmWord(1), dest); // result = 1
5015
5016 // x^y where x == 1 returns 1 for any y.
5017 Label done;
5018 branchPtr(Assembler::Equal, base, ImmWord(1), &done);
5019
5020 // x^y where x == -1 returns 1 for even y, and -1 for odd y.
5021 Label notNegativeOne;
5022 branchPtr(Assembler::NotEqual, base, ImmWord(-1), &notNegativeOne);
5023 test32MovePtr(Assembler::NonZero, power, Imm32(1), base, dest);
5024 jump(&done);
5025 bind(&notNegativeOne);
5026
5027 // x ** y with |x| > 1 and y >= DigitBits can't be pointer-sized.
5028 branchPtr(Assembler::GreaterThanOrEqual, power, Imm32(BigInt::DigitBits),
5029 onOver);
5030
5031 movePtr(base, temp1); // runningSquare = x
5032 movePtr(power, temp2); // n = y
5033
5034 Label start;
5035 jump(&start);
5036
5037 Label loop;
5038 bind(&loop);
5039
5040 // runningSquare *= runningSquare
5041 branchMulPtr(Assembler::Overflow, temp1, temp1, onOver);
5042
5043 bind(&start);
5044
5045 // if ((n & 1) != 0) result *= runningSquare
5046 Label even;
5047 branchTest32(Assembler::Zero, temp2, Imm32(1), &even);
5048 branchMulPtr(Assembler::Overflow, temp1, dest, onOver);
5049 bind(&even);
5050
5051 // n >>= 1
5052 // if (n == 0) return result
5053 branchRshift32(Assembler::NonZero, Imm32(1), temp2, &loop);
5054
5055 bind(&done);
5056 }
5057
5058 void MacroAssembler::signInt32(Register input, Register output) {
5059 MOZ_ASSERT(input != output);
5060
5061 rshift32Arithmetic(Imm32(31), input, output);
5062 or32(Imm32(1), output);
5063 cmp32Move32(Assembler::Equal, input, Imm32(0), input, output);
5064 }
5065
5066 void MacroAssembler::signDouble(FloatRegister input, FloatRegister output) {
5067 MOZ_ASSERT(input != output);
5068
5069 Label done, zeroOrNaN, negative;
5070 loadConstantDouble(0.0, output);
5071 branchDouble(Assembler::DoubleEqualOrUnordered, input, output, &zeroOrNaN);
5072 branchDouble(Assembler::DoubleLessThan, input, output, &negative);
5073
5074 loadConstantDouble(1.0, output);
5075 jump(&done);
5076
5077 bind(&negative);
5078 loadConstantDouble(-1.0, output);
5079 jump(&done);
5080
5081 bind(&zeroOrNaN);
5082 moveDouble(input, output);
5083
5084 bind(&done);
5085 }
5086
5087 void MacroAssembler::signDoubleToInt32(FloatRegister input, Register output,
5088 FloatRegister temp, Label* fail) {
5089 MOZ_ASSERT(input != temp);
5090
5091 Label done, zeroOrNaN, negative;
5092 loadConstantDouble(0.0, temp);
5093 branchDouble(Assembler::DoubleEqualOrUnordered, input, temp, &zeroOrNaN);
5094 branchDouble(Assembler::DoubleLessThan, input, temp, &negative);
5095
5096 move32(Imm32(1), output);
5097 jump(&done);
5098
5099 bind(&negative);
5100 move32(Imm32(-1), output);
5101 jump(&done);
5102
5103 // Fail for NaN and negative zero.
5104 bind(&zeroOrNaN);
5105 branchDouble(Assembler::DoubleUnordered, input, input, fail);
5106
5107 // The easiest way to distinguish -0.0 from 0.0 is that 1.0/-0.0
5108 // is -Infinity instead of Infinity.
5109 loadConstantDouble(1.0, temp);
5110 divDouble(input, temp);
5111 branchDouble(Assembler::DoubleLessThan, temp, input, fail);
5112 move32(Imm32(0), output);
5113
5114 bind(&done);
5115 }
5116
5117 void MacroAssembler::randomDouble(Register rng, FloatRegister dest,
5118 Register64 temp0, Register64 temp1) {
5119 using mozilla::non_crypto::XorShift128PlusRNG;
5120
5121 static_assert(
5122 sizeof(XorShift128PlusRNG) == 2 * sizeof(uint64_t),
5123 "Code below assumes XorShift128PlusRNG contains two uint64_t values");
5124
5125 Address state0Addr(rng, XorShift128PlusRNG::offsetOfState0());
5126 Address state1Addr(rng, XorShift128PlusRNG::offsetOfState1());
5127
5128 Register64 s0Reg = temp0;
5129 Register64 s1Reg = temp1;
5130
5131 // uint64_t s1 = mState[0];
5132 load64(state0Addr, s1Reg);
5133
5134 // s1 ^= s1 << 23;
5135 move64(s1Reg, s0Reg);
5136 lshift64(Imm32(23), s1Reg);
5137 xor64(s0Reg, s1Reg);
5138
5139 // s1 ^= s1 >> 17
5140 move64(s1Reg, s0Reg);
5141 rshift64(Imm32(17), s1Reg);
5142 xor64(s0Reg, s1Reg);
5143
5144 // const uint64_t s0 = mState[1];
5145 load64(state1Addr, s0Reg);
5146
5147 // mState[0] = s0;
5148 store64(s0Reg, state0Addr);
5149
5150 // s1 ^= s0
5151 xor64(s0Reg, s1Reg);
5152
5153 // s1 ^= s0 >> 26
5154 rshift64(Imm32(26), s0Reg);
5155 xor64(s0Reg, s1Reg);
5156
5157 // mState[1] = s1
5158 store64(s1Reg, state1Addr);
5159
5160 // s1 += mState[0]
5161 load64(state0Addr, s0Reg);
5162 add64(s0Reg, s1Reg);
5163
5164 // See comment in XorShift128PlusRNG::nextDouble().
5165 static constexpr int MantissaBits =
5166 mozilla::FloatingPoint<double>::kExponentShift + 1;
5167 static constexpr double ScaleInv = double(1) / (1ULL << MantissaBits);
5168
5169 and64(Imm64((1ULL << MantissaBits) - 1), s1Reg);
5170
5171 // Note: we know s1Reg isn't signed after the and64 so we can use the faster
5172 // convertInt64ToDouble instead of convertUInt64ToDouble.
5173 convertInt64ToDouble(s1Reg, dest);
5174
5175 // dest *= ScaleInv
5176 mulDoublePtr(ImmPtr(&ScaleInv), s0Reg.scratchReg(), dest);
5177 }
5178
5179 void MacroAssembler::sameValueDouble(FloatRegister left, FloatRegister right,
5180 FloatRegister temp, Register dest) {
5181 Label nonEqual, isSameValue, isNotSameValue;
5182 branchDouble(Assembler::DoubleNotEqualOrUnordered, left, right, &nonEqual);
5183 {
5184 // First, test for being equal to 0.0, which also includes -0.0.
5185 loadConstantDouble(0.0, temp);
5186 branchDouble(Assembler::DoubleNotEqual, left, temp, &isSameValue);
5187
5188 // The easiest way to distinguish -0.0 from 0.0 is that 1.0/-0.0
5189 // is -Infinity instead of Infinity.
5190 Label isNegInf;
5191 loadConstantDouble(1.0, temp);
5192 divDouble(left, temp);
5193 branchDouble(Assembler::DoubleLessThan, temp, left, &isNegInf);
5194 {
5195 loadConstantDouble(1.0, temp);
5196 divDouble(right, temp);
5197 branchDouble(Assembler::DoubleGreaterThan, temp, right, &isSameValue);
5198 jump(&isNotSameValue);
5199 }
5200 bind(&isNegInf);
5201 {
5202 loadConstantDouble(1.0, temp);
5203 divDouble(right, temp);
5204 branchDouble(Assembler::DoubleLessThan, temp, right, &isSameValue);
5205 jump(&isNotSameValue);
5206 }
5207 }
5208 bind(&nonEqual);
5209 {
5210 // Test if both values are NaN.
5211 branchDouble(Assembler::DoubleOrdered, left, left, &isNotSameValue);
5212 branchDouble(Assembler::DoubleOrdered, right, right, &isNotSameValue);
5213 }
5214
5215 Label done;
5216 bind(&isSameValue);
5217 move32(Imm32(1), dest);
5218 jump(&done);
5219
5220 bind(&isNotSameValue);
5221 move32(Imm32(0), dest);
5222
5223 bind(&done);
5224 }
5225
5226 void MacroAssembler::minMaxArrayInt32(Register array, Register result,
5227 Register temp1, Register temp2,
5228 Register temp3, bool isMax, Label* fail) {
5229 // array must be a packed array. Load its elements.
5230 Register elements = temp1;
5231 loadPtr(Address(array, NativeObject::offsetOfElements()), elements);
5232
5233 // Load the length and guard that it is non-zero.
5234 Address lengthAddr(elements, ObjectElements::offsetOfInitializedLength());
5235 load32(lengthAddr, temp3);
5236 branchTest32(Assembler::Zero, temp3, temp3, fail);
5237
5238 // Compute the address of the last element.
5239 Register elementsEnd = temp2;
5240 BaseObjectElementIndex elementsEndAddr(elements, temp3,
5241 -int32_t(sizeof(Value)));
5242 computeEffectiveAddress(elementsEndAddr, elementsEnd);
5243
5244 // Load the first element into result.
5245 fallibleUnboxInt32(Address(elements, 0), result, fail);
5246
5247 Label loop, done;
5248 bind(&loop);
5249
5250 // Check whether we're done.
5251 branchPtr(Assembler::Equal, elements, elementsEnd, &done);
5252
5253 // If not, advance to the next element and load it.
5254 addPtr(Imm32(sizeof(Value)), elements);
5255 fallibleUnboxInt32(Address(elements, 0), temp3, fail);
5256
5257 // Update result if necessary.
5258 Assembler::Condition cond =
5259 isMax ? Assembler::GreaterThan : Assembler::LessThan;
5260 cmp32Move32(cond, temp3, result, temp3, result);
5261
5262 jump(&loop);
5263 bind(&done);
5264 }
5265
5266 void MacroAssembler::minMaxArrayNumber(Register array, FloatRegister result,
5267 FloatRegister floatTemp, Register temp1,
5268 Register temp2, bool isMax,
5269 Label* fail) {
5270 // array must be a packed array. Load its elements.
5271 Register elements = temp1;
5272 loadPtr(Address(array, NativeObject::offsetOfElements()), elements);
5273
5274 // Load the length and check if the array is empty.
5275 Label isEmpty;
5276 Address lengthAddr(elements, ObjectElements::offsetOfInitializedLength());
5277 load32(lengthAddr, temp2);
5278 branchTest32(Assembler::Zero, temp2, temp2, &isEmpty);
5279
5280 // Compute the address of the last element.
5281 Register elementsEnd = temp2;
5282 BaseObjectElementIndex elementsEndAddr(elements, temp2,
5283 -int32_t(sizeof(Value)));
5284 computeEffectiveAddress(elementsEndAddr, elementsEnd);
5285
5286 // Load the first element into result.
5287 ensureDouble(Address(elements, 0), result, fail);
5288
5289 Label loop, done;
5290 bind(&loop);
5291
5292 // Check whether we're done.
5293 branchPtr(Assembler::Equal, elements, elementsEnd, &done);
5294
5295 // If not, advance to the next element and load it into floatTemp.
5296 addPtr(Imm32(sizeof(Value)), elements);
5297 ensureDouble(Address(elements, 0), floatTemp, fail);
5298
5299 // Update result if necessary.
5300 if (isMax) {
5301 maxDouble(floatTemp, result, /* handleNaN = */ true);
5302 } else {
5303 minDouble(floatTemp, result, /* handleNaN = */ true);
5304 }
5305 jump(&loop);
5306
5307 // With no arguments, min/max return +Infinity/-Infinity respectively.
5308 bind(&isEmpty);
5309 if (isMax) {
5310 loadConstantDouble(mozilla::NegativeInfinity<double>(), result);
5311 } else {
5312 loadConstantDouble(mozilla::PositiveInfinity<double>(), result);
5313 }
5314
5315 bind(&done);
5316 }
5317
5318 void MacroAssembler::loadRegExpLastIndex(Register regexp, Register string,
5319 Register lastIndex,
5320 Label* notFoundZeroLastIndex) {
5321 Address flagsSlot(regexp, RegExpObject::offsetOfFlags());
5322 Address lastIndexSlot(regexp, RegExpObject::offsetOfLastIndex());
5323 Address stringLength(string, JSString::offsetOfLength());
5324
5325 Label notGlobalOrSticky, loadedLastIndex;
5326
5327 branchTest32(Assembler::Zero, flagsSlot,
5328 Imm32(JS::RegExpFlag::Global | JS::RegExpFlag::Sticky),
5329 &notGlobalOrSticky);
5330 {
5331 // It's a global or sticky regular expression. Emit the following code:
5332 //
5333 // lastIndex = regexp.lastIndex
5334 // if lastIndex > string.length:
5335 // jump to notFoundZeroLastIndex (skip the regexp match/test operation)
5336 //
5337 // The `notFoundZeroLastIndex` code should set regexp.lastIndex to 0 and
5338 // treat this as a not-found result.
5339 //
5340 // See steps 5-8 in js::RegExpBuiltinExec.
5341 //
5342 // Earlier guards must have ensured regexp.lastIndex is a non-negative
5343 // integer.
5344 #ifdef DEBUG
5345 {
5346 Label ok;
5347 branchTestInt32(Assembler::Equal, lastIndexSlot, &ok);
5348 assumeUnreachable("Expected int32 value for lastIndex");
5349 bind(&ok);
5350 }
5351 #endif
5352 unboxInt32(lastIndexSlot, lastIndex);
5353 #ifdef DEBUG
5354 {
5355 Label ok;
5356 branchTest32(Assembler::NotSigned, lastIndex, lastIndex, &ok);
5357 assumeUnreachable("Expected non-negative lastIndex");
5358 bind(&ok);
5359 }
5360 #endif
5361 branch32(Assembler::Below, stringLength, lastIndex, notFoundZeroLastIndex);
5362 jump(&loadedLastIndex);
5363 }
5364
5365 bind(&notGlobalOrSticky);
5366 move32(Imm32(0), lastIndex);
5367
5368 bind(&loadedLastIndex);
5369 }
5370
5371 void MacroAssembler::loadAndClearRegExpSearcherLastLimit(Register result,
5372 Register scratch) {
5373 MOZ_ASSERT(result != scratch);
5374
5375 loadJSContext(scratch);
5376
5377 Address limitField(scratch, JSContext::offsetOfRegExpSearcherLastLimit());
5378 load32(limitField, result);
5379
5380 #ifdef DEBUG
5381 Label ok;
5382 branch32(Assembler::NotEqual, result, Imm32(RegExpSearcherLastLimitSentinel),
5383 &ok);
5384 assumeUnreachable("Unexpected sentinel for regExpSearcherLastLimit");
5385 bind(&ok);
5386 store32(Imm32(RegExpSearcherLastLimitSentinel), limitField);
5387 #endif
5388 }
5389
5390 void MacroAssembler::loadParsedRegExpShared(Register regexp, Register result,
5391 Label* unparsed) {
5392 Address sharedSlot(regexp, RegExpObject::offsetOfShared());
5393 branchTestUndefined(Assembler::Equal, sharedSlot, unparsed);
5394 unboxNonDouble(sharedSlot, result, JSVAL_TYPE_PRIVATE_GCTHING);
5395
5396 static_assert(sizeof(RegExpShared::Kind) == sizeof(uint32_t));
5397 branch32(Assembler::Equal, Address(result, RegExpShared::offsetOfKind()),
5398 Imm32(int32_t(RegExpShared::Kind::Unparsed)), unparsed);
5399 }
5400
5401 // ===============================================================
5402 // Branch functions
5403
5404 void MacroAssembler::loadFunctionLength(Register func,
5405 Register funFlagsAndArgCount,
5406 Register output, Label* slowPath) {
5407 #ifdef DEBUG
5408 {
5409 // These flags should already have been checked by caller.
5410 Label ok;
5411 uint32_t FlagsToCheck =
5412 FunctionFlags::SELFHOSTLAZY | FunctionFlags::RESOLVED_LENGTH;
5413 branchTest32(Assembler::Zero, funFlagsAndArgCount, Imm32(FlagsToCheck),
5414 &ok);
5415 assumeUnreachable("The function flags should already have been checked.");
5416 bind(&ok);
5417 }
5418 #endif // DEBUG
5419
5420 // NOTE: `funFlagsAndArgCount` and `output` must be allowed to alias.
5421
5422 // Load the target function's length.
5423 Label isInterpreted, lengthLoaded;
5424 branchTest32(Assembler::NonZero, funFlagsAndArgCount,
5425 Imm32(FunctionFlags::BASESCRIPT), &isInterpreted);
5426 {
5427 // The length property of a native function stored with the flags.
5428 rshift32(Imm32(JSFunction::ArgCountShift), funFlagsAndArgCount, output);
5429 jump(&lengthLoaded);
5430 }
5431 bind(&isInterpreted);
5432 {
5433 // Load the length property of an interpreted function.
5434 loadPrivate(Address(func, JSFunction::offsetOfJitInfoOrScript()), output);
5435 loadPtr(Address(output, JSScript::offsetOfSharedData()), output);
5436 branchTestPtr(Assembler::Zero, output, output, slowPath);
5437 loadPtr(Address(output, SharedImmutableScriptData::offsetOfISD()), output);
5438 load16ZeroExtend(Address(output, ImmutableScriptData::offsetOfFunLength()),
5439 output);
5440 }
5441 bind(&lengthLoaded);
5442 }
5443
5444 void MacroAssembler::loadFunctionName(Register func, Register output,
5445 ImmGCPtr emptyString, Label* slowPath) {
5446 MOZ_ASSERT(func != output);
5447
5448 // Get the JSFunction flags.
5449 load32(Address(func, JSFunction::offsetOfFlagsAndArgCount()), output);
5450
5451 // If the name was previously resolved, the name property may be shadowed.
5452 // If the function is an accessor with lazy name, AtomSlot contains the
5453 // unprefixed name.
5454 branchTest32(
5455 Assembler::NonZero, output,
5456 Imm32(FunctionFlags::RESOLVED_NAME | FunctionFlags::LAZY_ACCESSOR_NAME),
5457 slowPath);
5458
5459 Label noName, done;
5460 branchTest32(Assembler::NonZero, output,
5461 Imm32(FunctionFlags::HAS_GUESSED_ATOM), &noName);
5462
5463 Address atomAddr(func, JSFunction::offsetOfAtom());
5464 branchTestUndefined(Assembler::Equal, atomAddr, &noName);
5465 unboxString(atomAddr, output);
5466 jump(&done);
5467
5468 {
5469 bind(&noName);
5470
5471 // An absent name property defaults to the empty string.
5472 movePtr(emptyString, output);
5473 }
5474
5475 bind(&done);
5476 }
5477
5478 void MacroAssembler::assertFunctionIsExtended(Register func) {
5479 #ifdef DEBUG
5480 Label extended;
5481 branchTestFunctionFlags(func, FunctionFlags::EXTENDED, Assembler::NonZero,
5482 &extended);
5483 assumeUnreachable("Function is not extended");
5484 bind(&extended);
5485 #endif
5486 }
5487
5488 void MacroAssembler::branchTestType(Condition cond, Register tag,
5489 JSValueType type, Label* label) {
5490 switch (type) {
5491 case JSVAL_TYPE_DOUBLE:
5492 branchTestDouble(cond, tag, label);
5493 break;
5494 case JSVAL_TYPE_INT32:
5495 branchTestInt32(cond, tag, label);
5496 break;
5497 case JSVAL_TYPE_BOOLEAN:
5498 branchTestBoolean(cond, tag, label);
5499 break;
5500 case JSVAL_TYPE_UNDEFINED:
5501 branchTestUndefined(cond, tag, label);
5502 break;
5503 case JSVAL_TYPE_NULL:
5504 branchTestNull(cond, tag, label);
5505 break;
5506 case JSVAL_TYPE_MAGIC:
5507 branchTestMagic(cond, tag, label);
5508 break;
5509 case JSVAL_TYPE_STRING:
5510 branchTestString(cond, tag, label);
5511 break;
5512 case JSVAL_TYPE_SYMBOL:
5513 branchTestSymbol(cond, tag, label);
5514 break;
5515 case JSVAL_TYPE_BIGINT:
5516 branchTestBigInt(cond, tag, label);
5517 break;
5518 case JSVAL_TYPE_OBJECT:
5519 branchTestObject(cond, tag, label);
5520 break;
5521 default:
5522 MOZ_CRASH("Unexpected value type");
5523 }
5524 }
5525
5526 void MacroAssembler::branchTestObjShapeList(
5527 Condition cond, Register obj, Register shapeElements, Register shapeScratch,
5528 Register endScratch, Register spectreScratch, Label* label) {
5529 MOZ_ASSERT(cond == Assembler::Equal || cond == Assembler::NotEqual);
5530
5531 bool needSpectreMitigations = spectreScratch != InvalidReg;
5532
5533 Label done;
5534 Label* onMatch = cond == Assembler::Equal ? label : &done;
5535 Label* onNoMatch = cond == Assembler::Equal ? &done : label;
5536
5537 // Load the object's shape pointer into shapeScratch, and prepare to compare
5538 // it with the shapes in the list. The shapes are stored as private values so
5539 // we can compare directly.
5540 loadPtr(Address(obj, JSObject::offsetOfShape()), shapeScratch);
5541
5542 // Compute end pointer.
5543 Address lengthAddr(shapeElements,
5544 ObjectElements::offsetOfInitializedLength());
5545 load32(lengthAddr, endScratch);
5546 branch32(Assembler::Equal, endScratch, Imm32(0), onNoMatch);
5547 BaseObjectElementIndex endPtrAddr(shapeElements, endScratch);
5548 computeEffectiveAddress(endPtrAddr, endScratch);
5549
5550 Label loop;
5551 bind(&loop);
5552
5553 // Compare the object's shape with a shape from the list. Note that on 64-bit
5554 // this includes the tag bits, but on 32-bit we only compare the low word of
5555 // the value. This is fine because the list of shapes is never exposed and the
5556 // tag is guaranteed to be PrivateGCThing.
5557 if (needSpectreMitigations) {
5558 move32(Imm32(0), spectreScratch);
5559 }
5560 branchPtr(Assembler::Equal, Address(shapeElements, 0), shapeScratch, onMatch);
5561 if (needSpectreMitigations) {
5562 spectreMovePtr(Assembler::Equal, spectreScratch, obj);
5563 }
5564
5565 // Advance to next shape and loop if not finished.
5566 addPtr(Imm32(sizeof(Value)), shapeElements);
5567 branchPtr(Assembler::Below, shapeElements, endScratch, &loop);
5568
5569 if (cond == Assembler::NotEqual) {
5570 jump(label);
5571 }
5572 bind(&done);
5573 }
5574
5575 void MacroAssembler::branchTestObjCompartment(Condition cond, Register obj,
5576 const Address& compartment,
5577 Register scratch, Label* label) {
5578 MOZ_ASSERT(obj != scratch);
5579 loadPtr(Address(obj, JSObject::offsetOfShape()), scratch);
5580 loadPtr(Address(scratch, Shape::offsetOfBaseShape()), scratch);
5581 loadPtr(Address(scratch, BaseShape::offsetOfRealm()), scratch);
5582 loadPtr(Address(scratch, Realm::offsetOfCompartment()), scratch);
5583 branchPtr(cond, compartment, scratch, label);
5584 }
5585
5586 void MacroAssembler::branchTestObjCompartment(
5587 Condition cond, Register obj, const JS::Compartment* compartment,
5588 Register scratch, Label* label) {
5589 MOZ_ASSERT(obj != scratch);
5590 loadPtr(Address(obj, JSObject::offsetOfShape()), scratch);
5591 loadPtr(Address(scratch, Shape::offsetOfBaseShape()), scratch);
5592 loadPtr(Address(scratch, BaseShape::offsetOfRealm()), scratch);
5593 loadPtr(Address(scratch, Realm::offsetOfCompartment()), scratch);
5594 branchPtr(cond, scratch, ImmPtr(compartment), label);
5595 }
5596
5597 void MacroAssembler::branchIfNonNativeObj(Register obj, Register scratch,
5598 Label* label) {
5599 loadPtr(Address(obj, JSObject::offsetOfShape()), scratch);
5600 branchTest32(Assembler::Zero,
5601 Address(scratch, Shape::offsetOfImmutableFlags()),
5602 Imm32(Shape::isNativeBit()), label);
5603 }
5604
5605 void MacroAssembler::branchIfObjectNotExtensible(Register obj, Register scratch,
5606 Label* label) {
5607 loadPtr(Address(obj, JSObject::offsetOfShape()), scratch);
5608
5609 // Spectre-style checks are not needed here because we do not interpret data
5610 // based on this check.
5611 static_assert(sizeof(ObjectFlags) == sizeof(uint16_t));
5612 load16ZeroExtend(Address(scratch, Shape::offsetOfObjectFlags()), scratch);
5613 branchTest32(Assembler::NonZero, scratch,
5614 Imm32(uint32_t(ObjectFlag::NotExtensible)), label);
5615 }
5616
5617 void MacroAssembler::branchTestObjectNeedsProxyResultValidation(
5618 Condition cond, Register obj, Register scratch, Label* label) {
5619 MOZ_ASSERT(cond == Assembler::Zero || cond == Assembler::NonZero);
5620
5621 Label done;
5622 Label* doValidation = cond == NonZero ? label : &done;
5623 Label* skipValidation = cond == NonZero ? &done : label;
5624
5625 loadPtr(Address(obj, JSObject::offsetOfShape()), scratch);
5626 branchTest32(Assembler::Zero,
5627 Address(scratch, Shape::offsetOfImmutableFlags()),
5628 Imm32(Shape::isNativeBit()), doValidation);
5629 static_assert(sizeof(ObjectFlags) == sizeof(uint16_t));
5630 load16ZeroExtend(Address(scratch, Shape::offsetOfObjectFlags()), scratch);
5631 branchTest32(Assembler::NonZero, scratch,
5632 Imm32(uint32_t(ObjectFlag::NeedsProxyGetSetResultValidation)),
5633 doValidation);
5634
5635 loadPtr(Address(obj, JSObject::offsetOfShape()), scratch);
5636 loadPtr(Address(scratch, Shape::offsetOfBaseShape()), scratch);
5637 loadPtr(Address(scratch, BaseShape::offsetOfClasp()), scratch);
5638 loadPtr(Address(scratch, offsetof(JSClass, cOps)), scratch);
5639 branchTestPtr(Assembler::Zero, scratch, scratch, skipValidation);
5640 loadPtr(Address(scratch, offsetof(JSClassOps, resolve)), scratch);
5641 branchTestPtr(Assembler::NonZero, scratch, scratch, doValidation);
5642 bind(&done);
5643 }
5644
5645 void MacroAssembler::wasmTrap(wasm::Trap trap,
5646 const wasm::TrapSiteDesc& trapSiteDesc) {
5647 FaultingCodeOffset fco = wasmTrapInstruction();
5648 MOZ_ASSERT_IF(!oom(),
5649 currentOffset() - fco.get() == WasmTrapInstructionLength);
5650
5651 append(trap, wasm::TrapMachineInsn::OfficialUD, fco.get(), trapSiteDesc);
5652 }
5653
5654 std::pair<CodeOffset, uint32_t> MacroAssembler::wasmReserveStackChecked(
5655 uint32_t amount, const wasm::TrapSiteDesc& trapSiteDesc) {
5656 if (amount > MAX_UNCHECKED_LEAF_FRAME_SIZE) {
5657 // The frame is large. Don't bump sp until after the stack limit check so
5658 // that the trap handler isn't called with a wild sp.
5659 Label ok;
5660 Register scratch = ABINonArgReg0;
5661 moveStackPtrTo(scratch);
5662
5663 Label trap;
5664 branchPtr(Assembler::Below, scratch, Imm32(amount), &trap);
5665 subPtr(Imm32(amount), scratch);
5666 branchPtr(Assembler::Below,
5667 Address(InstanceReg, wasm::Instance::offsetOfStackLimit()),
5668 scratch, &ok);
5669
5670 bind(&trap);
5671 wasmTrap(wasm::Trap::StackOverflow, trapSiteDesc);
5672 CodeOffset trapInsnOffset = CodeOffset(currentOffset());
5673
5674 bind(&ok);
5675 reserveStack(amount);
5676 return std::pair<CodeOffset, uint32_t>(trapInsnOffset, 0);
5677 }
5678
5679 reserveStack(amount);
5680 Label ok;
5681 branchStackPtrRhs(Assembler::Below,
5682 Address(InstanceReg, wasm::Instance::offsetOfStackLimit()),
5683 &ok);
5684 wasmTrap(wasm::Trap::StackOverflow, trapSiteDesc);
5685 CodeOffset trapInsnOffset = CodeOffset(currentOffset());
5686 bind(&ok);
5687 return std::pair<CodeOffset, uint32_t>(trapInsnOffset, amount);
5688 }
5689
5690 static void MoveDataBlock(MacroAssembler& masm, Register base, int32_t from,
5691 int32_t to, uint32_t size) {
5692 MOZ_ASSERT(base != masm.getStackPointer());
5693 if (from == to || size == 0) {
5694 return; // noop
5695 }
5696
5697 #ifdef JS_CODEGEN_ARM64
5698 vixl::UseScratchRegisterScope temps(&masm);
5699 const Register scratch = temps.AcquireX().asUnsized();
5700 #elif defined(JS_CODEGEN_ARM) || defined(JS_CODEGEN_X86)
5701 static constexpr Register scratch = ABINonArgReg0;
5702 masm.push(scratch);
5703 #elif defined(JS_CODEGEN_LOONG64) || defined(JS_CODEGEN_MIPS64) || \
5704 defined(JS_CODEGEN_RISCV64)
5705 ScratchRegisterScope scratch(masm);
5706 #elif !defined(JS_CODEGEN_NONE)
5707 const Register scratch = ScratchReg;
5708 #else
5709 const Register scratch = InvalidReg;
5710 #endif
5711
5712 if (to < from) {
5713 for (uint32_t i = 0; i < size; i += sizeof(void*)) {
5714 masm.loadPtr(Address(base, from + i), scratch);
5715 masm.storePtr(scratch, Address(base, to + i));
5716 }
5717 } else {
5718 for (uint32_t i = size; i > 0;) {
5719 i -= sizeof(void*);
5720 masm.loadPtr(Address(base, from + i), scratch);
5721 masm.storePtr(scratch, Address(base, to + i));
5722 }
5723 }
5724
5725 #if defined(JS_CODEGEN_ARM) || defined(JS_CODEGEN_X86)
5726 masm.pop(scratch);
5727 #endif
5728 }
5729
5730 struct ReturnCallTrampolineData {
5731 #ifdef JS_CODEGEN_ARM
5732 uint32_t trampolineOffset;
5733 #else
5734 CodeLabel trampoline;
5735 #endif
5736 };
5737
5738 static ReturnCallTrampolineData MakeReturnCallTrampoline(MacroAssembler& masm) {
5739 uint32_t savedPushed = masm.framePushed();
5740
5741 ReturnCallTrampolineData data;
5742
5743 {
5744 #if defined(JS_CODEGEN_ARM) || defined(JS_CODEGEN_ARM64)
5745 AutoForbidPoolsAndNops afp(&masm, 1);
5746 #elif defined(JS_CODEGEN_RISCV64)
5747 BlockTrampolinePoolScope block_trampoline_pool(&masm, 1);
5748 #endif
5749
5750 // Build simple trampoline code: load the instance slot from the frame,
5751 // restore FP, and return to prevous caller.
5752 #ifdef JS_CODEGEN_ARM
5753 data.trampolineOffset = masm.currentOffset();
5754 #else
5755 masm.bind(&data.trampoline);
5756 #endif
5757
5758 masm.setFramePushed(AlignBytes(
5759 wasm::FrameWithInstances::sizeOfInstanceFieldsAndShadowStack(),
5760 WasmStackAlignment));
5761
5762 masm.wasmMarkCallAsSlow();
5763 }
5764
5765 masm.loadPtr(
5766 Address(masm.getStackPointer(), WasmCallerInstanceOffsetBeforeCall),
5767 InstanceReg);
5768 masm.loadWasmPinnedRegsFromInstance(mozilla::Nothing());
5769 masm.switchToWasmInstanceRealm(ABINonArgReturnReg0, ABINonArgReturnReg1);
5770 masm.moveToStackPtr(FramePointer);
5771 #ifdef JS_CODEGEN_ARM64
5772 masm.pop(FramePointer, lr);
5773 masm.append(wasm::CodeRangeUnwindInfo::UseFpLr, masm.currentOffset());
5774 masm.Mov(PseudoStackPointer64, vixl::sp);
5775 masm.abiret();
5776 #else
5777 masm.pop(FramePointer);
5778 masm.append(wasm::CodeRangeUnwindInfo::UseFp, masm.currentOffset());
5779 masm.ret();
5780 #endif
5781
5782 masm.append(wasm::CodeRangeUnwindInfo::Normal, masm.currentOffset());
5783 masm.setFramePushed(savedPushed);
5784 return data;
5785 }
5786
5787 // CollapseWasmFrame methods merge frames fields: callee parameters, instance
5788 // slots, and caller RA. See the diagram below. The C0 is the previous caller,
5789 // the C1 is the caller of the return call, and the C2 is the callee.
5790 //
5791 // +-------------------+ +--------------------+
5792 // |C0 instance slots | |C0 instance slots |
5793 // +-------------------+ -+ +--------------------+ -+
5794 // | RA | | | RA | |
5795 // +-------------------+ | C0 +--------------------+ |C0
5796 // | FP | v | FP | v
5797 // +-------------------+ +--------------------+
5798 // |C0 private frame | |C0 private frame |
5799 // +-------------------+ +--------------------+
5800 // |C1 results area | |C1/C2 results area |
5801 // +-------------------+ +--------------------+
5802 // |C1 parameters | |? trampoline frame |
5803 // +-------------------+ +--------------------+
5804 // |C1 instance slots | |C2 parameters |
5805 // +-------------------+ -+ +--------------------+
5806 // |C0 RA | | |C2 instance slots’ |
5807 // +-------------------+ | C1 +--------------------+ -+
5808 // |C0 FP | v |C0 RA’ | |
5809 // +-------------------+ +--------------------+ | C2
5810 // |C1 private frame | |C0 FP’ | v
5811 // +-------------------+ +--------------------+ <= start of C2
5812 // |C2 parameters |
5813 // +-------------------+
5814 // |C2 instance slots |
5815 // +-------------------+ <= call C2
5816 //
5817 // The C2 parameters are moved in place of the C1 parameters, and the
5818 // C1 frame data is removed. The instance slots, return address, and
5819 // frame pointer to the C0 callsite are saved or adjusted.
5820 //
5821 // For cross-instance calls, the trampoline frame will be introduced
5822 // if the C0 callsite has no ability to restore instance registers and realm.
5823
5824 static void CollapseWasmFrameFast(MacroAssembler& masm,
5825 const ReturnCallAdjustmentInfo& retCallInfo) {
5826 uint32_t framePushedAtStart = masm.framePushed();
5827 static_assert(sizeof(wasm::Frame) == 2 * sizeof(void*));
5828
5829 // The instance slots + stack arguments are expected to be padded and
5830 // aligned to the WasmStackAlignment boundary. There is no data expected
5831 // in the padded region, such as results stack area or locals, to avoid
5832 // unwanted stack growth.
5833 uint32_t newSlotsAndStackArgBytes =
5834 AlignBytes(retCallInfo.newSlotsAndStackArgBytes, WasmStackAlignment);
5835 uint32_t oldSlotsAndStackArgBytes =
5836 AlignBytes(retCallInfo.oldSlotsAndStackArgBytes, WasmStackAlignment);
5837
5838 static constexpr Register tempForCaller = WasmTailCallInstanceScratchReg;
5839 static constexpr Register tempForFP = WasmTailCallFPScratchReg;
5840 static constexpr Register tempForRA = WasmTailCallRAScratchReg;
5841 #ifndef JS_USE_LINK_REGISTER
5842 masm.push(tempForRA);
5843 #endif
5844
5845 // Load the FP, RA, and instance slots into registers to preserve them while
5846 // the new frame is collapsed over the current one.
5847 masm.loadPtr(Address(FramePointer, wasm::Frame::callerFPOffset()), tempForFP);
5848 masm.loadPtr(Address(FramePointer, wasm::Frame::returnAddressOffset()),
5849 tempForRA);
5850 masm.append(wasm::CodeRangeUnwindInfo::RestoreFpRa, masm.currentOffset());
5851 bool copyCallerSlot = oldSlotsAndStackArgBytes != newSlotsAndStackArgBytes;
5852 if (copyCallerSlot) {
5853 masm.loadPtr(
5854 Address(FramePointer, wasm::FrameWithInstances::callerInstanceOffset()),
5855 tempForCaller);
5856 }
5857
5858 // Copy parameters data, ignoring shadow data and instance slots.
5859 // Make all offsets relative to the FramePointer.
5860 int32_t newArgSrc = -framePushedAtStart;
5861 int32_t newArgDest =
5862 sizeof(wasm::Frame) + oldSlotsAndStackArgBytes - newSlotsAndStackArgBytes;
5863 const uint32_t SlotsSize =
5864 wasm::FrameWithInstances::sizeOfInstanceFieldsAndShadowStack();
5865 MoveDataBlock(masm, FramePointer, newArgSrc + SlotsSize,
5866 newArgDest + SlotsSize,
5867 retCallInfo.newSlotsAndStackArgBytes - SlotsSize);
5868
5869 // Copy caller instance slots from the current frame.
5870 if (copyCallerSlot) {
5871 masm.storePtr(
5872 tempForCaller,
5873 Address(FramePointer, newArgDest + WasmCallerInstanceOffsetBeforeCall));
5874 }
5875
5876 // Store current instance as the new callee instance slot.
5877 masm.storePtr(
5878 InstanceReg,
5879 Address(FramePointer, newArgDest + WasmCalleeInstanceOffsetBeforeCall));
5880
5881 #ifdef JS_USE_LINK_REGISTER
5882 // RA is already in its place, just move stack.
5883 masm.addToStackPtr(Imm32(framePushedAtStart + newArgDest));
5884 #else
5885 // Push RA to new frame: store RA, restore temp, and move stack.
5886 int32_t newFrameOffset = newArgDest - sizeof(wasm::Frame);
5887 masm.storePtr(tempForRA,
5888 Address(FramePointer,
5889 newFrameOffset + wasm::Frame::returnAddressOffset()));
5890 // Restore tempForRA, but keep RA on top of the stack.
5891 // There is no non-locking exchange instruction between register and memory.
5892 // Using tempForCaller as scratch register.
5893 masm.loadPtr(Address(masm.getStackPointer(), 0), tempForCaller);
5894 masm.storePtr(tempForRA, Address(masm.getStackPointer(), 0));
5895 masm.mov(tempForCaller, tempForRA);
5896 masm.append(wasm::CodeRangeUnwindInfo::RestoreFp, masm.currentOffset());
5897 masm.addToStackPtr(Imm32(framePushedAtStart + newFrameOffset +
5898 wasm::Frame::returnAddressOffset() + sizeof(void*)));
5899 #endif
5900
5901 masm.movePtr(tempForFP, FramePointer);
5902 // Setting framePushed to pre-collapse state, to properly set that in the
5903 // following code.
5904 masm.setFramePushed(framePushedAtStart);
5905 }
5906
5907 static void CollapseWasmFrameSlow(MacroAssembler& masm,
5908 const ReturnCallAdjustmentInfo& retCallInfo,
5909 wasm::CallSiteDesc desc,
5910 ReturnCallTrampolineData data) {
5911 uint32_t framePushedAtStart = masm.framePushed();
5912 static constexpr Register tempForCaller = WasmTailCallInstanceScratchReg;
5913 static constexpr Register tempForFP = WasmTailCallFPScratchReg;
5914 static constexpr Register tempForRA = WasmTailCallRAScratchReg;
5915
5916 static_assert(sizeof(wasm::Frame) == 2 * sizeof(void*));
5917
5918 // The hidden frame will "break" after wasm::Frame data fields.
5919 // Calculate sum of wasm stack alignment before and after the break as
5920 // the size to reserve.
5921 const uint32_t HiddenFrameAfterSize =
5922 AlignBytes(wasm::FrameWithInstances::sizeOfInstanceFieldsAndShadowStack(),
5923 WasmStackAlignment);
5924 const uint32_t HiddenFrameSize =
5925 AlignBytes(sizeof(wasm::Frame), WasmStackAlignment) +
5926 HiddenFrameAfterSize;
5927
5928 // If it is not slow, prepare two frame: one is regular wasm frame, and
5929 // another one is hidden. The hidden frame contains one instance slots
5930 // for unwind and recovering pinned registers.
5931 // The instance slots + stack arguments are expected to be padded and
5932 // aligned to the WasmStackAlignment boundary. There is no data expected
5933 // in the padded region, such as results stack area or locals, to avoid
5934 // unwanted stack growth.
5935 // The Hidden frame will be inserted with this constraint too.
5936 uint32_t newSlotsAndStackArgBytes =
5937 AlignBytes(retCallInfo.newSlotsAndStackArgBytes, WasmStackAlignment);
5938 uint32_t oldSlotsAndStackArgBytes =
5939 AlignBytes(retCallInfo.oldSlotsAndStackArgBytes, WasmStackAlignment);
5940
5941 // Make all offsets relative to the FramePointer.
5942 int32_t newArgSrc = -framePushedAtStart;
5943 int32_t newArgDest = sizeof(wasm::Frame) + oldSlotsAndStackArgBytes -
5944 HiddenFrameSize - newSlotsAndStackArgBytes;
5945 int32_t hiddenFrameArgsDest =
5946 sizeof(wasm::Frame) + oldSlotsAndStackArgBytes - HiddenFrameAfterSize;
5947
5948 // It will be possible to overwrite data (on the top of the stack) due to
5949 // the added hidden frame, reserve needed space.
5950 uint32_t reserved = newArgDest - int32_t(sizeof(void*)) < newArgSrc
5951 ? newArgSrc - newArgDest + sizeof(void*)
5952 : 0;
5953 masm.reserveStack(reserved);
5954
5955 #ifndef JS_USE_LINK_REGISTER
5956 masm.push(tempForRA);
5957 #endif
5958
5959 // Load FP, RA and instance slots to preserve them from being overwritten.
5960 masm.loadPtr(Address(FramePointer, wasm::Frame::callerFPOffset()), tempForFP);
5961 masm.loadPtr(Address(FramePointer, wasm::Frame::returnAddressOffset()),
5962 tempForRA);
5963 masm.append(wasm::CodeRangeUnwindInfo::RestoreFpRa, masm.currentOffset());
5964 masm.loadPtr(
5965 Address(FramePointer, newArgSrc + WasmCallerInstanceOffsetBeforeCall),
5966 tempForCaller);
5967
5968 // Copy parameters data, ignoring shadow data and instance slots.
5969 const uint32_t SlotsSize =
5970 wasm::FrameWithInstances::sizeOfInstanceFieldsAndShadowStack();
5971 MoveDataBlock(masm, FramePointer, newArgSrc + SlotsSize,
5972 newArgDest + SlotsSize,
5973 retCallInfo.newSlotsAndStackArgBytes - SlotsSize);
5974
5975 // Form hidden frame for trampoline.
5976 int32_t newFPOffset = hiddenFrameArgsDest - sizeof(wasm::Frame);
5977 masm.storePtr(
5978 tempForRA,
5979 Address(FramePointer, newFPOffset + wasm::Frame::returnAddressOffset()));
5980
5981 // Copy original FP.
5982 masm.storePtr(
5983 tempForFP,
5984 Address(FramePointer, newFPOffset + wasm::Frame::callerFPOffset()));
5985
5986 // Set up instance slots.
5987 masm.storePtr(
5988 tempForCaller,
5989 Address(FramePointer,
5990 newFPOffset + wasm::FrameWithInstances::calleeInstanceOffset()));
5991 masm.storePtr(
5992 tempForCaller,
5993 Address(FramePointer, newArgDest + WasmCallerInstanceOffsetBeforeCall));
5994 masm.storePtr(
5995 InstanceReg,
5996 Address(FramePointer, newArgDest + WasmCalleeInstanceOffsetBeforeCall));
5997
5998 #ifdef JS_CODEGEN_ARM
5999 // ARM has no CodeLabel -- calculate PC directly.
6000 masm.mov(pc, tempForRA);
6001 masm.computeEffectiveAddress(
6002 Address(tempForRA,
6003 int32_t(data.trampolineOffset - masm.currentOffset() - 4)),
6004 tempForRA);
6005 masm.append(desc, CodeOffset(data.trampolineOffset));
6006 #else
6007 masm.mov(&data.trampoline, tempForRA);
6008
6009 masm.addCodeLabel(data.trampoline);
6010 // Add slow trampoline callsite description, to be annotated in
6011 // stack/frame iterators.
6012 masm.append(desc, *data.trampoline.target());
6013 #endif
6014
6015 #ifdef JS_USE_LINK_REGISTER
6016 masm.freeStack(reserved);
6017 // RA is already in its place, just move stack.
6018 masm.addToStackPtr(Imm32(framePushedAtStart + newArgDest));
6019 #else
6020 // Push RA to new frame: store RA, restore temp, and move stack.
6021 int32_t newFrameOffset = newArgDest - sizeof(wasm::Frame);
6022 masm.storePtr(tempForRA,
6023 Address(FramePointer,
6024 newFrameOffset + wasm::Frame::returnAddressOffset()));
6025 // Restore tempForRA, but keep RA on top of the stack.
6026 // There is no non-locking exchange instruction between register and memory.
6027 // Using tempForCaller as scratch register.
6028 masm.loadPtr(Address(masm.getStackPointer(), 0), tempForCaller);
6029 masm.storePtr(tempForRA, Address(masm.getStackPointer(), 0));
6030 masm.mov(tempForCaller, tempForRA);
6031 masm.append(wasm::CodeRangeUnwindInfo::RestoreFp, masm.currentOffset());
6032 masm.addToStackPtr(Imm32(framePushedAtStart + newFrameOffset +
6033 wasm::Frame::returnAddressOffset() + reserved +
6034 sizeof(void*)));
6035 #endif
6036
6037 // Point FramePointer to hidden frame.
6038 masm.computeEffectiveAddress(Address(FramePointer, newFPOffset),
6039 FramePointer);
6040 // Setting framePushed to pre-collapse state, to properly set that in the
6041 // following code.
6042 masm.setFramePushed(framePushedAtStart);
6043 }
6044
6045 void MacroAssembler::wasmCollapseFrameFast(
6046 const ReturnCallAdjustmentInfo& retCallInfo) {
6047 CollapseWasmFrameFast(*this, retCallInfo);
6048 }
6049
6050 void MacroAssembler::wasmCollapseFrameSlow(
6051 const ReturnCallAdjustmentInfo& retCallInfo, wasm::CallSiteDesc desc) {
6052 static constexpr Register temp1 = ABINonArgReg1;
6053 static constexpr Register temp2 = ABINonArgReg3;
6054
6055 // Check if RA has slow marker. If there is no marker, generate a trampoline
6056 // frame to restore register state when this tail call returns.
6057
6058 Label slow, done;
6059 loadPtr(Address(FramePointer, wasm::Frame::returnAddressOffset()), temp1);
6060 wasmCheckSlowCallsite(temp1, &slow, temp1, temp2);
6061 CollapseWasmFrameFast(*this, retCallInfo);
6062 jump(&done);
6063 append(wasm::CodeRangeUnwindInfo::Normal, currentOffset());
6064
6065 ReturnCallTrampolineData data = MakeReturnCallTrampoline(*this);
6066
6067 bind(&slow);
6068 CollapseWasmFrameSlow(*this, retCallInfo, desc, data);
6069
6070 bind(&done);
6071 }
6072
6073 CodeOffset MacroAssembler::wasmCallImport(const wasm::CallSiteDesc& desc,
6074 const wasm::CalleeDesc& callee) {
6075 storePtr(InstanceReg,
6076 Address(getStackPointer(), WasmCallerInstanceOffsetBeforeCall));
6077
6078 // Load the callee, before the caller's registers are clobbered.
6079 uint32_t instanceDataOffset = callee.importInstanceDataOffset();
6080 loadPtr(
6081 Address(InstanceReg, wasm::Instance::offsetInData(
6082 instanceDataOffset +
6083 offsetof(wasm::FuncImportInstanceData, code))),
6084 ABINonArgReg0);
6085
6086 #if !defined(JS_CODEGEN_NONE) && !defined(JS_CODEGEN_WASM32)
6087 static_assert(ABINonArgReg0 != InstanceReg, "by constraint");
6088 #endif
6089
6090 // Switch to the callee's realm.
6091 loadPtr(
6092 Address(InstanceReg, wasm::Instance::offsetInData(
6093 instanceDataOffset +
6094 offsetof(wasm::FuncImportInstanceData, realm))),
6095 ABINonArgReg1);
6096 loadPtr(Address(InstanceReg, wasm::Instance::offsetOfCx()), ABINonArgReg2);
6097 storePtr(ABINonArgReg1, Address(ABINonArgReg2, JSContext::offsetOfRealm()));
6098
6099 // Switch to the callee's instance and pinned registers and make the call.
6100 loadPtr(Address(InstanceReg,
6101 wasm::Instance::offsetInData(
6102 instanceDataOffset +
6103 offsetof(wasm::FuncImportInstanceData, instance))),
6104 InstanceReg);
6105
6106 storePtr(InstanceReg,
6107 Address(getStackPointer(), WasmCalleeInstanceOffsetBeforeCall));
6108 loadWasmPinnedRegsFromInstance(mozilla::Nothing());
6109
6110 return wasmMarkedSlowCall(desc, ABINonArgReg0);
6111 }
6112
6113 CodeOffset MacroAssembler::wasmReturnCallImport(
6114 const wasm::CallSiteDesc& desc, const wasm::CalleeDesc& callee,
6115 const ReturnCallAdjustmentInfo& retCallInfo) {
6116 storePtr(InstanceReg,
6117 Address(getStackPointer(), WasmCallerInstanceOffsetBeforeCall));
6118
6119 // Load the callee, before the caller's registers are clobbered.
6120 uint32_t instanceDataOffset = callee.importInstanceDataOffset();
6121 loadPtr(
6122 Address(InstanceReg, wasm::Instance::offsetInData(
6123 instanceDataOffset +
6124 offsetof(wasm::FuncImportInstanceData, code))),
6125 ABINonArgReg0);
6126
6127 #if !defined(JS_CODEGEN_NONE) && !defined(JS_CODEGEN_WASM32)
6128 static_assert(ABINonArgReg0 != InstanceReg, "by constraint");
6129 #endif
6130
6131 // Switch to the callee's realm.
6132 loadPtr(
6133 Address(InstanceReg, wasm::Instance::offsetInData(
6134 instanceDataOffset +
6135 offsetof(wasm::FuncImportInstanceData, realm))),
6136 ABINonArgReg1);
6137 loadPtr(Address(InstanceReg, wasm::Instance::offsetOfCx()), ABINonArgReg2);
6138 storePtr(ABINonArgReg1, Address(ABINonArgReg2, JSContext::offsetOfRealm()));
6139
6140 // Switch to the callee's instance and pinned registers and make the call.
6141 loadPtr(Address(InstanceReg,
6142 wasm::Instance::offsetInData(
6143 instanceDataOffset +
6144 offsetof(wasm::FuncImportInstanceData, instance))),
6145 InstanceReg);
6146
6147 storePtr(InstanceReg,
6148 Address(getStackPointer(), WasmCalleeInstanceOffsetBeforeCall));
6149 loadWasmPinnedRegsFromInstance(mozilla::Nothing());
6150
6151 wasm::CallSiteDesc stubDesc(desc.lineOrBytecode(),
6152 wasm::CallSiteKind::ReturnStub);
6153 wasmCollapseFrameSlow(retCallInfo, stubDesc);
6154 jump(ABINonArgReg0);
6155 append(wasm::CodeRangeUnwindInfo::Normal, currentOffset());
6156 return CodeOffset(currentOffset());
6157 }
6158
6159 CodeOffset MacroAssembler::wasmReturnCall(
6160 const wasm::CallSiteDesc& desc, uint32_t funcDefIndex,
6161 const ReturnCallAdjustmentInfo& retCallInfo) {
6162 wasmCollapseFrameFast(retCallInfo);
6163 CodeOffset offset = farJumpWithPatch();
6164 append(desc, offset, funcDefIndex);
6165 append(wasm::CodeRangeUnwindInfo::Normal, currentOffset());
6166 return offset;
6167 }
6168
6169 CodeOffset MacroAssembler::wasmCallBuiltinInstanceMethod(
6170 const wasm::CallSiteDesc& desc, const ABIArg& instanceArg,
6171 wasm::SymbolicAddress builtin, wasm::FailureMode failureMode) {
6172 MOZ_ASSERT(instanceArg != ABIArg());
6173
6174 storePtr(InstanceReg,
6175 Address(getStackPointer(), WasmCallerInstanceOffsetBeforeCall));
6176 storePtr(InstanceReg,
6177 Address(getStackPointer(), WasmCalleeInstanceOffsetBeforeCall));
6178
6179 if (instanceArg.kind() == ABIArg::GPR) {
6180 movePtr(InstanceReg, instanceArg.gpr());
6181 } else if (instanceArg.kind() == ABIArg::Stack) {
6182 storePtr(InstanceReg,
6183 Address(getStackPointer(), instanceArg.offsetFromArgBase()));
6184 } else {
6185 MOZ_CRASH("Unknown abi passing style for pointer");
6186 }
6187
6188 CodeOffset ret = call(desc, builtin);
6189 wasmTrapOnFailedInstanceCall(ReturnReg, failureMode, desc.toTrapSiteDesc());
6190
6191 return ret;
6192 }
6193
6194 void MacroAssembler::wasmTrapOnFailedInstanceCall(
6195 Register resultRegister, wasm::FailureMode failureMode,
6196 const wasm::TrapSiteDesc& trapSiteDesc) {
6197 Label noTrap;
6198 switch (failureMode) {
6199 case wasm::FailureMode::Infallible:
6200 return;
6201 case wasm::FailureMode::FailOnNegI32:
6202 branchTest32(Assembler::NotSigned, resultRegister, resultRegister,
6203 &noTrap);
6204 break;
6205 case wasm::FailureMode::FailOnMaxI32:
6206 branchPtr(Assembler::NotEqual, resultRegister,
6207 ImmWord(uintptr_t(INT32_MAX)), &noTrap);
6208 break;
6209 case wasm::FailureMode::FailOnNullPtr:
6210 branchTestPtr(Assembler::NonZero, resultRegister, resultRegister,
6211 &noTrap);
6212 break;
6213 case wasm::FailureMode::FailOnInvalidRef:
6214 branchPtr(Assembler::NotEqual, resultRegister,
6215 ImmWord(uintptr_t(wasm::AnyRef::invalid().forCompiledCode())),
6216 &noTrap);
6217 break;
6218 }
6219 wasmTrap(wasm::Trap::ThrowReported, trapSiteDesc);
6220 bind(&noTrap);
6221 }
6222
6223 CodeOffset MacroAssembler::asmCallIndirect(const wasm::CallSiteDesc& desc,
6224 const wasm::CalleeDesc& callee) {
6225 MOZ_ASSERT(callee.which() == wasm::CalleeDesc::AsmJSTable);
6226
6227 const Register scratch = WasmTableCallScratchReg0;
6228 const Register index = WasmTableCallIndexReg;
6229
6230 // Optimization opportunity: when offsetof(FunctionTableElem, code) == 0, as
6231 // it is at present, we can probably generate better code here by folding
6232 // the address computation into the load.
6233
6234 static_assert(sizeof(wasm::FunctionTableElem) == 8 ||
6235 sizeof(wasm::FunctionTableElem) == 16,
6236 "elements of function tables are two words");
6237
6238 // asm.js tables require no signature check, and have had their index
6239 // masked into range and thus need no bounds check.
6240 loadPtr(
6241 Address(InstanceReg, wasm::Instance::offsetInData(
6242 callee.tableFunctionBaseInstanceDataOffset())),
6243 scratch);
6244 if (sizeof(wasm::FunctionTableElem) == 8) {
6245 computeEffectiveAddress(BaseIndex(scratch, index, TimesEight), scratch);
6246 } else {
6247 lshift32(Imm32(4), index);
6248 addPtr(index, scratch);
6249 }
6250 loadPtr(Address(scratch, offsetof(wasm::FunctionTableElem, code)), scratch);
6251 storePtr(InstanceReg,
6252 Address(getStackPointer(), WasmCallerInstanceOffsetBeforeCall));
6253 storePtr(InstanceReg,
6254 Address(getStackPointer(), WasmCalleeInstanceOffsetBeforeCall));
6255 return call(desc, scratch);
6256 }
6257
6258 // In principle, call_indirect requires an expensive context switch to the
6259 // callee's instance and realm before the call and an almost equally expensive
6260 // switch back to the caller's ditto after. However, if the caller's instance
6261 // is the same as the callee's instance then no context switch is required, and
6262 // it only takes a compare-and-branch at run-time to test this - all values are
6263 // in registers already. We therefore generate two call paths, one for the fast
6264 // call without the context switch (which additionally avoids a null check) and
6265 // one for the slow call with the context switch.
6266
6267 void MacroAssembler::wasmCallIndirect(const wasm::CallSiteDesc& desc,
6268 const wasm::CalleeDesc& callee,
6269 Label* boundsCheckFailedLabel,
6270 Label* nullCheckFailedLabel,
6271 mozilla::Maybe<uint32_t> tableSize,
6272 CodeOffset* fastCallOffset,
6273 CodeOffset* slowCallOffset) {
6274 static_assert(sizeof(wasm::FunctionTableElem) == 2 * sizeof(void*),
6275 "Exactly two pointers or index scaling won't work correctly");
6276 MOZ_ASSERT(callee.which() == wasm::CalleeDesc::WasmTable);
6277
6278 const int shift = sizeof(wasm::FunctionTableElem) == 8 ? 3 : 4;
6279 const Register calleeScratch = WasmTableCallScratchReg0;
6280 const Register index = WasmTableCallIndexReg;
6281
6282 // Check the table index and throw if out-of-bounds.
6283 //
6284 // Frequently the table size is known, so optimize for that. Otherwise
6285 // compare with a memory operand when that's possible. (There's little sense
6286 // in hoisting the load of the bound into a register at a higher level and
6287 // reusing that register, because a hoisted value would either have to be
6288 // spilled and re-loaded before the next call_indirect, or would be abandoned
6289 // because we could not trust that a hoisted value would not have changed.)
6290
6291 if (boundsCheckFailedLabel) {
6292 if (tableSize.isSome()) {
6293 branch32(Assembler::Condition::AboveOrEqual, index, Imm32(*tableSize),
6294 boundsCheckFailedLabel);
6295 } else {
6296 branch32(
6297 Assembler::Condition::BelowOrEqual,
6298 Address(InstanceReg, wasm::Instance::offsetInData(
6299 callee.tableLengthInstanceDataOffset())),
6300 index, boundsCheckFailedLabel);
6301 }
6302 }
6303
6304 // Write the functype-id into the ABI functype-id register.
6305
6306 const wasm::CallIndirectId callIndirectId = callee.wasmTableSigId();
6307 switch (callIndirectId.kind()) {
6308 case wasm::CallIndirectIdKind::Global:
6309 loadPtr(Address(InstanceReg, wasm::Instance::offsetInData(
6310 callIndirectId.instanceDataOffset() +
6311 offsetof(wasm::TypeDefInstanceData,
6312 superTypeVector))),
6313 WasmTableCallSigReg);
6314 break;
6315 case wasm::CallIndirectIdKind::Immediate:
6316 move32(Imm32(callIndirectId.immediate()), WasmTableCallSigReg);
6317 break;
6318 case wasm::CallIndirectIdKind::AsmJS:
6319 case wasm::CallIndirectIdKind::None:
6320 break;
6321 }
6322
6323 // Load the base pointer of the table and compute the address of the callee in
6324 // the table.
6325
6326 loadPtr(
6327 Address(InstanceReg, wasm::Instance::offsetInData(
6328 callee.tableFunctionBaseInstanceDataOffset())),
6329 calleeScratch);
6330 shiftIndex32AndAdd(index, shift, calleeScratch);
6331
6332 // Load the callee instance and decide whether to take the fast path or the
6333 // slow path.
6334
6335 Label fastCall;
6336 Label done;
6337 const Register newInstanceTemp = WasmTableCallScratchReg1;
6338 loadPtr(Address(calleeScratch, offsetof(wasm::FunctionTableElem, instance)),
6339 newInstanceTemp);
6340 branchPtr(Assembler::Equal, InstanceReg, newInstanceTemp, &fastCall);
6341
6342 // Slow path: Save context, check for null, setup new context, call, restore
6343 // context.
6344 //
6345 // TODO: The slow path could usefully be out-of-line and the test above would
6346 // just fall through to the fast path. This keeps the fast-path code dense,
6347 // and has correct static prediction for the branch (forward conditional
6348 // branches predicted not taken, normally).
6349
6350 storePtr(InstanceReg,
6351 Address(getStackPointer(), WasmCallerInstanceOffsetBeforeCall));
6352 movePtr(newInstanceTemp, InstanceReg);
6353 storePtr(InstanceReg,
6354 Address(getStackPointer(), WasmCalleeInstanceOffsetBeforeCall));
6355
6356 #ifdef WASM_HAS_HEAPREG
6357 // Use the null pointer exception resulting from loading HeapReg from a null
6358 // instance to handle a call to a null slot.
6359 MOZ_ASSERT(nullCheckFailedLabel == nullptr);
6360 loadWasmPinnedRegsFromInstance(mozilla::Some(desc.toTrapSiteDesc()));
6361 #else
6362 MOZ_ASSERT(nullCheckFailedLabel != nullptr);
6363 branchTestPtr(Assembler::Zero, InstanceReg, InstanceReg,
6364 nullCheckFailedLabel);
6365
6366 loadWasmPinnedRegsFromInstance(mozilla::Nothing());
6367 #endif
6368 switchToWasmInstanceRealm(index, WasmTableCallScratchReg1);
6369
6370 loadPtr(Address(calleeScratch, offsetof(wasm::FunctionTableElem, code)),
6371 calleeScratch);
6372
6373 *slowCallOffset = wasmMarkedSlowCall(desc, calleeScratch);
6374
6375 // Restore registers and realm and join up with the fast path.
6376
6377 loadPtr(Address(getStackPointer(), WasmCallerInstanceOffsetBeforeCall),
6378 InstanceReg);
6379 loadWasmPinnedRegsFromInstance(mozilla::Nothing());
6380 switchToWasmInstanceRealm(ABINonArgReturnReg0, ABINonArgReturnReg1);
6381 jump(&done);
6382
6383 // Fast path: just load the code pointer and go. The instance and heap
6384 // register are the same as in the caller, and nothing will be null.
6385 //
6386 // (In particular, the code pointer will not be null: if it were, the instance
6387 // would have been null, and then it would not have been equivalent to our
6388 // current instance. So no null check is needed on the fast path.)
6389
6390 bind(&fastCall);
6391
6392 loadPtr(Address(calleeScratch, offsetof(wasm::FunctionTableElem, code)),
6393 calleeScratch);
6394
6395 // We use a different type of call site for the fast call since the instance
6396 // slots in the frame do not have valid values.
6397
6398 wasm::CallSiteDesc newDesc(desc.lineOrBytecode(),
6399 wasm::CallSiteKind::IndirectFast);
6400 *fastCallOffset = call(newDesc, calleeScratch);
6401
6402 bind(&done);
6403 }
6404
6405 void MacroAssembler::wasmReturnCallIndirect(
6406 const wasm::CallSiteDesc& desc, const wasm::CalleeDesc& callee,
6407 Label* boundsCheckFailedLabel, Label* nullCheckFailedLabel,
6408 mozilla::Maybe<uint32_t> tableSize,
6409 const ReturnCallAdjustmentInfo& retCallInfo) {
6410 static_assert(sizeof(wasm::FunctionTableElem) == 2 * sizeof(void*),
6411 "Exactly two pointers or index scaling won't work correctly");
6412 MOZ_ASSERT(callee.which() == wasm::CalleeDesc::WasmTable);
6413
6414 const int shift = sizeof(wasm::FunctionTableElem) == 8 ? 3 : 4;
6415 const Register calleeScratch = WasmTableCallScratchReg0;
6416 const Register index = WasmTableCallIndexReg;
6417
6418 // Check the table index and throw if out-of-bounds.
6419 //
6420 // Frequently the table size is known, so optimize for that. Otherwise
6421 // compare with a memory operand when that's possible. (There's little sense
6422 // in hoisting the load of the bound into a register at a higher level and
6423 // reusing that register, because a hoisted value would either have to be
6424 // spilled and re-loaded before the next call_indirect, or would be abandoned
6425 // because we could not trust that a hoisted value would not have changed.)
6426
6427 if (boundsCheckFailedLabel) {
6428 if (tableSize.isSome()) {
6429 branch32(Assembler::Condition::AboveOrEqual, index, Imm32(*tableSize),
6430 boundsCheckFailedLabel);
6431 } else {
6432 branch32(
6433 Assembler::Condition::BelowOrEqual,
6434 Address(InstanceReg, wasm::Instance::offsetInData(
6435 callee.tableLengthInstanceDataOffset())),
6436 index, boundsCheckFailedLabel);
6437 }
6438 }
6439
6440 // Write the functype-id into the ABI functype-id register.
6441
6442 const wasm::CallIndirectId callIndirectId = callee.wasmTableSigId();
6443 switch (callIndirectId.kind()) {
6444 case wasm::CallIndirectIdKind::Global:
6445 loadPtr(Address(InstanceReg, wasm::Instance::offsetInData(
6446 callIndirectId.instanceDataOffset() +
6447 offsetof(wasm::TypeDefInstanceData,
6448 superTypeVector))),
6449 WasmTableCallSigReg);
6450 break;
6451 case wasm::CallIndirectIdKind::Immediate:
6452 move32(Imm32(callIndirectId.immediate()), WasmTableCallSigReg);
6453 break;
6454 case wasm::CallIndirectIdKind::AsmJS:
6455 case wasm::CallIndirectIdKind::None:
6456 break;
6457 }
6458
6459 // Load the base pointer of the table and compute the address of the callee in
6460 // the table.
6461
6462 loadPtr(
6463 Address(InstanceReg, wasm::Instance::offsetInData(
6464 callee.tableFunctionBaseInstanceDataOffset())),
6465 calleeScratch);
6466 shiftIndex32AndAdd(index, shift, calleeScratch);
6467
6468 // Load the callee instance and decide whether to take the fast path or the
6469 // slow path.
6470
6471 Label fastCall;
6472 Label done;
6473 const Register newInstanceTemp = WasmTableCallScratchReg1;
6474 loadPtr(Address(calleeScratch, offsetof(wasm::FunctionTableElem, instance)),
6475 newInstanceTemp);
6476 branchPtr(Assembler::Equal, InstanceReg, newInstanceTemp, &fastCall);
6477
6478 // Slow path: Save context, check for null, setup new context.
6479
6480 storePtr(InstanceReg,
6481 Address(getStackPointer(), WasmCallerInstanceOffsetBeforeCall));
6482 movePtr(newInstanceTemp, InstanceReg);
6483
6484 #ifdef WASM_HAS_HEAPREG
6485 // Use the null pointer exception resulting from loading HeapReg from a null
6486 // instance to handle a call to a null slot.
6487 MOZ_ASSERT(nullCheckFailedLabel == nullptr);
6488 loadWasmPinnedRegsFromInstance(mozilla::Some(desc.toTrapSiteDesc()));
6489 #else
6490 MOZ_ASSERT(nullCheckFailedLabel != nullptr);
6491 branchTestPtr(Assembler::Zero, InstanceReg, InstanceReg,
6492 nullCheckFailedLabel);
6493
6494 loadWasmPinnedRegsFromInstance(mozilla::Nothing());
6495 #endif
6496 switchToWasmInstanceRealm(index, WasmTableCallScratchReg1);
6497
6498 loadPtr(Address(calleeScratch, offsetof(wasm::FunctionTableElem, code)),
6499 calleeScratch);
6500
6501 wasm::CallSiteDesc stubDesc(desc.lineOrBytecode(),
6502 wasm::CallSiteKind::ReturnStub);
6503 wasmCollapseFrameSlow(retCallInfo, stubDesc);
6504 jump(calleeScratch);
6505 append(wasm::CodeRangeUnwindInfo::Normal, currentOffset());
6506
6507 // Fast path: just load the code pointer and go.
6508
6509 bind(&fastCall);
6510
6511 loadPtr(Address(calleeScratch, offsetof(wasm::FunctionTableElem, code)),
6512 calleeScratch);
6513
6514 wasmCollapseFrameFast(retCallInfo);
6515 jump(calleeScratch);
6516 append(wasm::CodeRangeUnwindInfo::Normal, currentOffset());
6517 }
6518
6519 void MacroAssembler::wasmCallRef(const wasm::CallSiteDesc& desc,
6520 const wasm::CalleeDesc& callee,
6521 CodeOffset* fastCallOffset,
6522 CodeOffset* slowCallOffset) {
6523 MOZ_ASSERT(callee.which() == wasm::CalleeDesc::FuncRef);
6524 const Register calleeScratch = WasmCallRefCallScratchReg0;
6525 const Register calleeFnObj = WasmCallRefReg;
6526
6527 // Load from the function's WASM_INSTANCE_SLOT extended slot, and decide
6528 // whether to take the fast path or the slow path. Register this load
6529 // instruction to be source of a trap -- null pointer check.
6530
6531 Label fastCall;
6532 Label done;
6533 const Register newInstanceTemp = WasmCallRefCallScratchReg1;
6534 size_t instanceSlotOffset = FunctionExtended::offsetOfExtendedSlot(
6535 FunctionExtended::WASM_INSTANCE_SLOT);
6536 static_assert(FunctionExtended::WASM_INSTANCE_SLOT < wasm::NullPtrGuardSize);
6537 FaultingCodeOffset fco =
6538 loadPtr(Address(calleeFnObj, instanceSlotOffset), newInstanceTemp);
6539 append(wasm::Trap::NullPointerDereference, wasm::TrapMachineInsnForLoadWord(),
6540 fco.get(), desc.toTrapSiteDesc());
6541 branchPtr(Assembler::Equal, InstanceReg, newInstanceTemp, &fastCall);
6542
6543 storePtr(InstanceReg,
6544 Address(getStackPointer(), WasmCallerInstanceOffsetBeforeCall));
6545 movePtr(newInstanceTemp, InstanceReg);
6546 storePtr(InstanceReg,
6547 Address(getStackPointer(), WasmCalleeInstanceOffsetBeforeCall));
6548
6549 loadWasmPinnedRegsFromInstance(mozilla::Nothing());
6550 switchToWasmInstanceRealm(WasmCallRefCallScratchReg0,
6551 WasmCallRefCallScratchReg1);
6552
6553 // Get funcUncheckedCallEntry() from the function's
6554 // WASM_FUNC_UNCHECKED_ENTRY_SLOT extended slot.
6555 size_t uncheckedEntrySlotOffset = FunctionExtended::offsetOfExtendedSlot(
6556 FunctionExtended::WASM_FUNC_UNCHECKED_ENTRY_SLOT);
6557 loadPtr(Address(calleeFnObj, uncheckedEntrySlotOffset), calleeScratch);
6558
6559 *slowCallOffset = wasmMarkedSlowCall(desc, calleeScratch);
6560
6561 // Restore registers and realm and back to this caller's.
6562 loadPtr(Address(getStackPointer(), WasmCallerInstanceOffsetBeforeCall),
6563 InstanceReg);
6564 loadWasmPinnedRegsFromInstance(mozilla::Nothing());
6565 switchToWasmInstanceRealm(ABINonArgReturnReg0, ABINonArgReturnReg1);
6566 jump(&done);
6567
6568 // Fast path: just load WASM_FUNC_UNCHECKED_ENTRY_SLOT value and go.
6569 // The instance and pinned registers are the same as in the caller.
6570
6571 bind(&fastCall);
6572
6573 loadPtr(Address(calleeFnObj, uncheckedEntrySlotOffset), calleeScratch);
6574
6575 // We use a different type of call site for the fast call since the instance
6576 // slots in the frame do not have valid values.
6577
6578 wasm::CallSiteDesc newDesc(desc.lineOrBytecode(),
6579 wasm::CallSiteKind::FuncRefFast);
6580 *fastCallOffset = call(newDesc, calleeScratch);
6581
6582 bind(&done);
6583 }
6584
6585 void MacroAssembler::wasmReturnCallRef(
6586 const wasm::CallSiteDesc& desc, const wasm::CalleeDesc& callee,
6587 const ReturnCallAdjustmentInfo& retCallInfo) {
6588 MOZ_ASSERT(callee.which() == wasm::CalleeDesc::FuncRef);
6589 const Register calleeScratch = WasmCallRefCallScratchReg0;
6590 const Register calleeFnObj = WasmCallRefReg;
6591
6592 // Load from the function's WASM_INSTANCE_SLOT extended slot, and decide
6593 // whether to take the fast path or the slow path. Register this load
6594 // instruction to be source of a trap -- null pointer check.
6595
6596 Label fastCall;
6597 Label done;
6598 const Register newInstanceTemp = WasmCallRefCallScratchReg1;
6599 size_t instanceSlotOffset = FunctionExtended::offsetOfExtendedSlot(
6600 FunctionExtended::WASM_INSTANCE_SLOT);
6601 static_assert(FunctionExtended::WASM_INSTANCE_SLOT < wasm::NullPtrGuardSize);
6602 FaultingCodeOffset fco =
6603 loadPtr(Address(calleeFnObj, instanceSlotOffset), newInstanceTemp);
6604 append(wasm::Trap::NullPointerDereference, wasm::TrapMachineInsnForLoadWord(),
6605 fco.get(), desc.toTrapSiteDesc());
6606 branchPtr(Assembler::Equal, InstanceReg, newInstanceTemp, &fastCall);
6607
6608 storePtr(InstanceReg,
6609 Address(getStackPointer(), WasmCallerInstanceOffsetBeforeCall));
6610 movePtr(newInstanceTemp, InstanceReg);
6611 storePtr(InstanceReg,
6612 Address(getStackPointer(), WasmCalleeInstanceOffsetBeforeCall));
6613
6614 loadWasmPinnedRegsFromInstance(mozilla::Nothing());
6615 switchToWasmInstanceRealm(WasmCallRefCallScratchReg0,
6616 WasmCallRefCallScratchReg1);
6617
6618 // Get funcUncheckedCallEntry() from the function's
6619 // WASM_FUNC_UNCHECKED_ENTRY_SLOT extended slot.
6620 size_t uncheckedEntrySlotOffset = FunctionExtended::offsetOfExtendedSlot(
6621 FunctionExtended::WASM_FUNC_UNCHECKED_ENTRY_SLOT);
6622 loadPtr(Address(calleeFnObj, uncheckedEntrySlotOffset), calleeScratch);
6623
6624 wasm::CallSiteDesc stubDesc(desc.lineOrBytecode(),
6625 wasm::CallSiteKind::ReturnStub);
6626 wasmCollapseFrameSlow(retCallInfo, stubDesc);
6627 jump(calleeScratch);
6628 append(wasm::CodeRangeUnwindInfo::Normal, currentOffset());
6629
6630 // Fast path: just load WASM_FUNC_UNCHECKED_ENTRY_SLOT value and go.
6631 // The instance and pinned registers are the same as in the caller.
6632
6633 bind(&fastCall);
6634
6635 loadPtr(Address(calleeFnObj, uncheckedEntrySlotOffset), calleeScratch);
6636
6637 wasmCollapseFrameFast(retCallInfo);
6638 jump(calleeScratch);
6639 append(wasm::CodeRangeUnwindInfo::Normal, currentOffset());
6640 }
6641
6642 void MacroAssembler::wasmBoundsCheckRange32(
6643 Register index, Register length, Register limit, Register tmp,
6644 const wasm::TrapSiteDesc& trapSiteDesc) {
6645 Label ok;
6646 Label fail;
6647
6648 mov(index, tmp);
6649 branchAdd32(Assembler::CarrySet, length, tmp, &fail);
6650 branch32(Assembler::Above, tmp, limit, &fail);
6651 jump(&ok);
6652
6653 bind(&fail);
6654 wasmTrap(wasm::Trap::OutOfBounds, trapSiteDesc);
6655
6656 bind(&ok);
6657 }
6658
6659 #ifdef ENABLE_WASM_MEMORY64
6660 void MacroAssembler::wasmClampTable64Address(Register64 address, Register out) {
6661 Label oob;
6662 Label ret;
6663 branch64(Assembler::Above, address, Imm64(UINT32_MAX), &oob);
6664 move64To32(address, out);
6665 jump(&ret);
6666 bind(&oob);
6667 static_assert(wasm::MaxTableElemsRuntime < UINT32_MAX);
6668 move32(Imm32(UINT32_MAX), out);
6669 bind(&ret);
6670 };
6671 #endif
6672
6673 BranchWasmRefIsSubtypeRegisters MacroAssembler::regsForBranchWasmRefIsSubtype(
6674 wasm::RefType type) {
6675 MOZ_ASSERT(type.isValid());
6676 switch (type.hierarchy()) {
6677 case wasm::RefTypeHierarchy::Any:
6678 return BranchWasmRefIsSubtypeRegisters{
6679 .needSuperSTV = type.isTypeRef(),
6680 .needScratch1 = !type.isNone() && !type.isAny(),
6681 .needScratch2 = type.isTypeRef() && !type.typeDef()->isFinal() &&
6682 type.typeDef()->subTypingDepth() >=
6683 wasm::MinSuperTypeVectorLength,
6684 };
6685 case wasm::RefTypeHierarchy::Func:
6686 return BranchWasmRefIsSubtypeRegisters{
6687 .needSuperSTV = type.isTypeRef(),
6688 .needScratch1 = type.isTypeRef(),
6689 .needScratch2 = type.isTypeRef() && !type.typeDef()->isFinal() &&
6690 type.typeDef()->subTypingDepth() >=
6691 wasm::MinSuperTypeVectorLength,
6692 };
6693 case wasm::RefTypeHierarchy::Extern:
6694 case wasm::RefTypeHierarchy::Exn:
6695 return BranchWasmRefIsSubtypeRegisters{
6696 .needSuperSTV = false,
6697 .needScratch1 = false,
6698 .needScratch2 = false,
6699 };
6700 default:
6701 MOZ_CRASH("unknown type hierarchy for cast");
6702 }
6703 }
6704
6705 void MacroAssembler::branchWasmRefIsSubtype(
6706 Register ref, wasm::MaybeRefType sourceType, wasm::RefType destType,
6707 Label* label, bool onSuccess, Register superSTV, Register scratch1,
6708 Register scratch2) {
6709 switch (destType.hierarchy()) {
6710 case wasm::RefTypeHierarchy::Any: {
6711 branchWasmRefIsSubtypeAny(ref, sourceType.valueOr(wasm::RefType::any()),
6712 destType, label, onSuccess, superSTV, scratch1,
6713 scratch2);
6714 } break;
6715 case wasm::RefTypeHierarchy::Func: {
6716 branchWasmRefIsSubtypeFunc(ref, sourceType.valueOr(wasm::RefType::func()),
6717 destType, label, onSuccess, superSTV, scratch1,
6718 scratch2);
6719 } break;
6720 case wasm::RefTypeHierarchy::Extern: {
6721 branchWasmRefIsSubtypeExtern(ref,
6722 sourceType.valueOr(wasm::RefType::extern_()),
6723 destType, label, onSuccess);
6724 } break;
6725 case wasm::RefTypeHierarchy::Exn: {
6726 branchWasmRefIsSubtypeExn(ref, sourceType.valueOr(wasm::RefType::exn()),
6727 destType, label, onSuccess);
6728 } break;
6729 default:
6730 MOZ_CRASH("unknown type hierarchy for wasm cast");
6731 }
6732 }
6733
6734 void MacroAssembler::branchWasmRefIsSubtypeAny(
6735 Register ref, wasm::RefType sourceType, wasm::RefType destType,
6736 Label* label, bool onSuccess, Register superSTV, Register scratch1,
6737 Register scratch2) {
6738 MOZ_ASSERT(sourceType.isValid());
6739 MOZ_ASSERT(destType.isValid());
6740 MOZ_ASSERT(sourceType.isAnyHierarchy());
6741 MOZ_ASSERT(destType.isAnyHierarchy());
6742
6743 mozilla::DebugOnly<BranchWasmRefIsSubtypeRegisters> needs =
6744 regsForBranchWasmRefIsSubtype(destType);
6745 MOZ_ASSERT_IF(needs.value.needSuperSTV, superSTV != Register::Invalid());
6746 MOZ_ASSERT_IF(needs.value.needScratch1, scratch1 != Register::Invalid());
6747 MOZ_ASSERT_IF(needs.value.needScratch2, scratch2 != Register::Invalid());
6748
6749 Label fallthrough;
6750 Label* successLabel = onSuccess ? label : &fallthrough;
6751 Label* failLabel = onSuccess ? &fallthrough : label;
6752 Label* nullLabel = destType.isNullable() ? successLabel : failLabel;
6753
6754 auto finishSuccess = [&]() {
6755 if (successLabel != &fallthrough) {
6756 jump(successLabel);
6757 }
6758 bind(&fallthrough);
6759 };
6760 auto finishFail = [&]() {
6761 if (failLabel != &fallthrough) {
6762 jump(failLabel);
6763 }
6764 bind(&fallthrough);
6765 };
6766
6767 // Check for null.
6768 if (sourceType.isNullable()) {
6769 branchWasmAnyRefIsNull(true, ref, nullLabel);
6770 }
6771
6772 // The only value that can inhabit 'none' is null. So, early out if we got
6773 // not-null.
6774 if (destType.isNone()) {
6775 finishFail();
6776 return;
6777 }
6778
6779 if (destType.isAny()) {
6780 // No further checks for 'any'
6781 finishSuccess();
6782 return;
6783 }
6784
6785 // 'type' is now 'eq' or lower, which currently will either be a gc object or
6786 // an i31.
6787
6788 // Check first for i31 values, and get them out of the way. i31 values are
6789 // valid when casting to i31 or eq, and invalid otherwise.
6790 if (destType.isI31() || destType.isEq()) {
6791 branchWasmAnyRefIsI31(true, ref, successLabel);
6792
6793 if (destType.isI31()) {
6794 // No further checks for 'i31'
6795 finishFail();
6796 return;
6797 }
6798 }
6799
6800 // Then check for any kind of gc object.
6801 MOZ_ASSERT(scratch1 != Register::Invalid());
6802 if (!wasm::RefType::isSubTypeOf(sourceType, wasm::RefType::struct_()) &&
6803 !wasm::RefType::isSubTypeOf(sourceType, wasm::RefType::array())) {
6804 branchWasmAnyRefIsObjectOrNull(false, ref, failLabel);
6805 branchObjectIsWasmGcObject(false, ref, scratch1, failLabel);
6806 }
6807
6808 if (destType.isEq()) {
6809 // No further checks for 'eq'
6810 finishSuccess();
6811 return;
6812 }
6813
6814 // 'type' is now 'struct', 'array', or a concrete type. (Bottom types and i31
6815 // were handled above.)
6816 //
6817 // Casting to a concrete type only requires a simple check on the
6818 // object's super type vector. Casting to an abstract type (struct, array)
6819 // requires loading the object's superTypeVector->typeDef->kind, and checking
6820 // that it is correct.
6821
6822 loadPtr(Address(ref, int32_t(WasmGcObject::offsetOfSuperTypeVector())),
6823 scratch1);
6824 if (destType.isTypeRef()) {
6825 // Concrete type, do superTypeVector check.
6826 branchWasmSTVIsSubtype(scratch1, superSTV, scratch2, destType.typeDef(),
6827 label, onSuccess);
6828 bind(&fallthrough);
6829 return;
6830 }
6831
6832 // Abstract type, do kind check
6833 loadPtr(
6834 Address(scratch1, int32_t(wasm::SuperTypeVector::offsetOfSelfTypeDef())),
6835 scratch1);
6836 load8ZeroExtend(Address(scratch1, int32_t(wasm::TypeDef::offsetOfKind())),
6837 scratch1);
6838 branch32(onSuccess ? Assembler::Equal : Assembler::NotEqual, scratch1,
6839 Imm32(int32_t(destType.typeDefKind())), label);
6840 bind(&fallthrough);
6841 }
6842
6843 void MacroAssembler::branchWasmRefIsSubtypeFunc(
6844 Register ref, wasm::RefType sourceType, wasm::RefType destType,
6845 Label* label, bool onSuccess, Register superSTV, Register scratch1,
6846 Register scratch2) {
6847 MOZ_ASSERT(sourceType.isValid());
6848 MOZ_ASSERT(destType.isValid());
6849 MOZ_ASSERT(sourceType.isFuncHierarchy());
6850 MOZ_ASSERT(destType.isFuncHierarchy());
6851
6852 mozilla::DebugOnly<BranchWasmRefIsSubtypeRegisters> needs =
6853 regsForBranchWasmRefIsSubtype(destType);
6854 MOZ_ASSERT_IF(needs.value.needSuperSTV, superSTV != Register::Invalid());
6855 MOZ_ASSERT_IF(needs.value.needScratch1, scratch1 != Register::Invalid());
6856 MOZ_ASSERT_IF(needs.value.needScratch2, scratch2 != Register::Invalid());
6857
6858 Label fallthrough;
6859 Label* successLabel = onSuccess ? label : &fallthrough;
6860 Label* failLabel = onSuccess ? &fallthrough : label;
6861 Label* nullLabel = destType.isNullable() ? successLabel : failLabel;
6862
6863 auto finishSuccess = [&]() {
6864 if (successLabel != &fallthrough) {
6865 jump(successLabel);
6866 }
6867 bind(&fallthrough);
6868 };
6869 auto finishFail = [&]() {
6870 if (failLabel != &fallthrough) {
6871 jump(failLabel);
6872 }
6873 bind(&fallthrough);
6874 };
6875
6876 // Check for null.
6877 if (sourceType.isNullable()) {
6878 branchTestPtr(Assembler::Zero, ref, ref, nullLabel);
6879 }
6880
6881 // The only value that can inhabit 'nofunc' is null. So, early out if we got
6882 // not-null.
6883 if (destType.isNoFunc()) {
6884 finishFail();
6885 return;
6886 }
6887
6888 if (destType.isFunc()) {
6889 // No further checks for 'func' (any func)
6890 finishSuccess();
6891 return;
6892 }
6893
6894 // In the func hierarchy, a supertype vector check is now sufficient for all
6895 // remaining cases.
6896 loadPrivate(Address(ref, int32_t(FunctionExtended::offsetOfWasmSTV())),
6897 scratch1);
6898 branchWasmSTVIsSubtype(scratch1, superSTV, scratch2, destType.typeDef(),
6899 label, onSuccess);
6900 bind(&fallthrough);
6901 }
6902
6903 void MacroAssembler::branchWasmRefIsSubtypeExtern(Register ref,
6904 wasm::RefType sourceType,
6905 wasm::RefType destType,
6906 Label* label,
6907 bool onSuccess) {
6908 MOZ_ASSERT(sourceType.isValid());
6909 MOZ_ASSERT(destType.isValid());
6910 MOZ_ASSERT(sourceType.isExternHierarchy());
6911 MOZ_ASSERT(destType.isExternHierarchy());
6912
6913 Label fallthrough;
6914 Label* successLabel = onSuccess ? label : &fallthrough;
6915 Label* failLabel = onSuccess ? &fallthrough : label;
6916 Label* nullLabel = destType.isNullable() ? successLabel : failLabel;
6917
6918 auto finishSuccess = [&]() {
6919 if (successLabel != &fallthrough) {
6920 jump(successLabel);
6921 }
6922 bind(&fallthrough);
6923 };
6924 auto finishFail = [&]() {
6925 if (failLabel != &fallthrough) {
6926 jump(failLabel);
6927 }
6928 bind(&fallthrough);
6929 };
6930
6931 // Check for null.
6932 if (sourceType.isNullable()) {
6933 branchTestPtr(Assembler::Zero, ref, ref, nullLabel);
6934 }
6935
6936 // The only value that can inhabit 'noextern' is null. So, early out if we got
6937 // not-null.
6938 if (destType.isNoExtern()) {
6939 finishFail();
6940 return;
6941 }
6942
6943 // There are no other possible types except externref, so succeed!
6944 finishSuccess();
6945 }
6946
6947 void MacroAssembler::branchWasmRefIsSubtypeExn(Register ref,
6948 wasm::RefType sourceType,
6949 wasm::RefType destType,
6950 Label* label, bool onSuccess) {
6951 MOZ_ASSERT(sourceType.isValid());
6952 MOZ_ASSERT(destType.isValid());
6953 MOZ_ASSERT(sourceType.isExnHierarchy());
6954 MOZ_ASSERT(destType.isExnHierarchy());
6955
6956 Label fallthrough;
6957 Label* successLabel = onSuccess ? label : &fallthrough;
6958 Label* failLabel = onSuccess ? &fallthrough : label;
6959 Label* nullLabel = destType.isNullable() ? successLabel : failLabel;
6960
6961 auto finishSuccess = [&]() {
6962 if (successLabel != &fallthrough) {
6963 jump(successLabel);
6964 }
6965 bind(&fallthrough);
6966 };
6967 auto finishFail = [&]() {
6968 if (failLabel != &fallthrough) {
6969 jump(failLabel);
6970 }
6971 bind(&fallthrough);
6972 };
6973
6974 // Check for null.
6975 if (sourceType.isNullable()) {
6976 branchTestPtr(Assembler::Zero, ref, ref, nullLabel);
6977 }
6978
6979 // The only value that can inhabit 'noexn' is null. So, early out if we got
6980 // not-null.
6981 if (destType.isNoExn()) {
6982 finishFail();
6983 return;
6984 }
6985
6986 // There are no other possible types except exnref, so succeed!
6987 finishSuccess();
6988 }
6989
6990 void MacroAssembler::branchWasmSTVIsSubtype(Register subSTV, Register superSTV,
6991 Register scratch,
6992 const wasm::TypeDef* destType,
6993 Label* label, bool onSuccess) {
6994 if (destType->isFinal()) {
6995 // A final type cannot have subtypes, and therefore a simple equality check
6996 // is sufficient.
6997 MOZ_ASSERT(scratch == Register::Invalid());
6998 branchPtr(onSuccess ? Assembler::Equal : Assembler::NotEqual, subSTV,
6999 superSTV, label);
7000 return;
7001 }
7002
7003 MOZ_ASSERT((destType->subTypingDepth() >= wasm::MinSuperTypeVectorLength) ==
7004 (scratch != Register::Invalid()));
7005
7006 Label fallthrough;
7007 Label* successLabel = onSuccess ? label : &fallthrough;
7008 Label* failLabel = onSuccess ? &fallthrough : label;
7009
7010 // Emit a fast success path for if subSTV == superSTV.
7011 // If they are unequal, they still may be subtypes.
7012 branchPtr(Assembler::Equal, subSTV, superSTV, successLabel);
7013
7014 // Emit a bounds check if the super type depth may be out-of-bounds.
7015 if (destType->subTypingDepth() >= wasm::MinSuperTypeVectorLength) {
7016 load32(Address(subSTV, wasm::SuperTypeVector::offsetOfLength()), scratch);
7017 branch32(Assembler::BelowOrEqual, scratch,
7018 Imm32(destType->subTypingDepth()), failLabel);
7019 }
7020
7021 // Load the `superTypeDepth` entry from subSTV. This will be `superSTV` if
7022 // `subSTV` is indeed a subtype.
7023 loadPtr(Address(subSTV, wasm::SuperTypeVector::offsetOfSTVInVector(
7024 destType->subTypingDepth())),
7025 subSTV);
7026
7027 // We succeed iff the entries are equal.
7028 branchPtr(onSuccess ? Assembler::Equal : Assembler::NotEqual, subSTV,
7029 superSTV, label);
7030
7031 bind(&fallthrough);
7032 }
7033
7034 void MacroAssembler::branchWasmSTVIsSubtypeDynamicDepth(
7035 Register subSTV, Register superSTV, Register superDepth, Register scratch,
7036 Label* label, bool onSuccess) {
7037 Label fallthrough;
7038 Label* failed = onSuccess ? &fallthrough : label;
7039
7040 // Bounds check of the super type vector
7041 load32(Address(subSTV, wasm::SuperTypeVector::offsetOfLength()), scratch);
7042 branch32(Assembler::BelowOrEqual, scratch, superDepth, failed);
7043
7044 // Load `subSTV[superTypeDepth]`. This will be `superSTV` if `subSTV` is
7045 // indeed a subtype.
7046 loadPtr(BaseIndex(subSTV, superDepth, ScalePointer,
7047 offsetof(wasm::SuperTypeVector, types_)),
7048 subSTV);
7049
7050 // We succeed iff the entries are equal
7051 branchPtr(onSuccess ? Assembler::Equal : Assembler::NotEqual, subSTV,
7052 superSTV, label);
7053
7054 bind(&fallthrough);
7055 }
7056
7057 void MacroAssembler::extractWasmAnyRefTag(Register src, Register dest) {
7058 andPtr(Imm32(int32_t(wasm::AnyRef::TagMask)), src, dest);
7059 }
7060
7061 void MacroAssembler::untagWasmAnyRef(Register src, Register dest,
7062 wasm::AnyRefTag tag) {
7063 MOZ_ASSERT(tag != wasm::AnyRefTag::ObjectOrNull, "No untagging needed");
7064 computeEffectiveAddress(Address(src, -int32_t(tag)), dest);
7065 }
7066
7067 void MacroAssembler::branchWasmAnyRefIsNull(bool isNull, Register src,
7068 Label* label) {
7069 branchTestPtr(isNull ? Assembler::Zero : Assembler::NonZero, src, src, label);
7070 }
7071
7072 void MacroAssembler::branchWasmAnyRefIsI31(bool isI31, Register src,
7073 Label* label) {
7074 branchTestPtr(isI31 ? Assembler::NonZero : Assembler::Zero, src,
7075 Imm32(int32_t(wasm::AnyRefTag::I31)), label);
7076 }
7077
7078 void MacroAssembler::branchWasmAnyRefIsObjectOrNull(bool isObject, Register src,
7079 Label* label) {
7080 branchTestPtr(isObject ? Assembler::Zero : Assembler::NonZero, src,
7081 Imm32(int32_t(wasm::AnyRef::TagMask)), label);
7082 }
7083
7084 void MacroAssembler::branchWasmAnyRefIsJSString(bool isJSString, Register src,
7085 Register temp, Label* label) {
7086 extractWasmAnyRefTag(src, temp);
7087 branch32(isJSString ? Assembler::Equal : Assembler::NotEqual, temp,
7088 Imm32(int32_t(wasm::AnyRefTag::String)), label);
7089 }
7090
7091 void MacroAssembler::branchWasmAnyRefIsGCThing(bool isGCThing, Register src,
7092 Label* label) {
7093 Label fallthrough;
7094 Label* isGCThingLabel = isGCThing ? label : &fallthrough;
7095 Label* isNotGCThingLabel = isGCThing ? &fallthrough : label;
7096
7097 // A null value or i31 value are not GC things.
7098 branchWasmAnyRefIsNull(true, src, isNotGCThingLabel);
7099 branchWasmAnyRefIsI31(true, src, isNotGCThingLabel);
7100 jump(isGCThingLabel);
7101 bind(&fallthrough);
7102 }
7103
7104 void MacroAssembler::branchWasmAnyRefIsNurseryCell(bool isNurseryCell,
7105 Register src, Register temp,
7106 Label* label) {
7107 Label done;
7108 branchWasmAnyRefIsGCThing(false, src, isNurseryCell ? &done : label);
7109
7110 getWasmAnyRefGCThingChunk(src, temp);
7111 branchPtr(isNurseryCell ? Assembler::NotEqual : Assembler::Equal,
7112 Address(temp, gc::ChunkStoreBufferOffset), ImmWord(0), label);
7113 bind(&done);
7114 }
7115
7116 void MacroAssembler::truncate32ToWasmI31Ref(Register src, Register dest) {
7117 // This will either zero-extend or sign-extend the high 32-bits on 64-bit
7118 // platforms (see comments on invariants in MacroAssembler.h). Either case
7119 // is fine, as we won't use this bits.
7120 //
7121 // Move the payload of the integer over by 1 to make room for the tag. This
7122 // will perform the truncation required by the spec.
7123 lshift32(Imm32(1), src, dest);
7124 // Add the i31 tag to the integer.
7125 orPtr(Imm32(int32_t(wasm::AnyRefTag::I31)), dest);
7126 #ifdef JS_64BIT
7127 debugAssertCanonicalInt32(dest);
7128 #endif
7129 }
7130
7131 void MacroAssembler::convertWasmI31RefTo32Signed(Register src, Register dest) {
7132 #ifdef JS_64BIT
7133 debugAssertCanonicalInt32(src);
7134 #endif
7135 // This will either zero-extend or sign-extend the high 32-bits on 64-bit
7136 // platforms (see comments on invariants in MacroAssembler.h). Either case
7137 // is fine, as we won't use this bits.
7138 //
7139 // Shift the payload back (clobbering the tag). This will sign-extend, giving
7140 // us the unsigned behavior we want.
7141 rshift32Arithmetic(Imm32(1), src, dest);
7142 }
7143
7144 void MacroAssembler::convertWasmI31RefTo32Unsigned(Register src,
7145 Register dest) {
7146 #ifdef JS_64BIT
7147 debugAssertCanonicalInt32(src);
7148 #endif
7149 // This will either zero-extend or sign-extend the high 32-bits on 64-bit
7150 // platforms (see comments on invariants in MacroAssembler.h). Either case
7151 // is fine, as we won't use this bits.
7152 //
7153 // Shift the payload back (clobbering the tag). This will zero-extend, giving
7154 // us the unsigned behavior we want.
7155 rshift32(Imm32(1), src, dest);
7156 }
7157
7158 void MacroAssembler::branchValueConvertsToWasmAnyRefInline(
7159 ValueOperand src, Register scratchInt, FloatRegister scratchFloat,
7160 Label* label) {
7161 // We can convert objects, strings, 31-bit integers and null without boxing.
7162 Label checkInt32;
7163 Label checkDouble;
7164 Label fallthrough;
7165 {
7166 ScratchTagScope tag(*this, src);
7167 splitTagForTest(src, tag);
7168 branchTestObject(Assembler::Equal, tag, label);
7169 branchTestString(Assembler::Equal, tag, label);
7170 branchTestNull(Assembler::Equal, tag, label);
7171 branchTestInt32(Assembler::Equal, tag, &checkInt32);
7172 branchTestDouble(Assembler::Equal, tag, &checkDouble);
7173 }
7174 jump(&fallthrough);
7175
7176 bind(&checkInt32);
7177 {
7178 unboxInt32(src, scratchInt);
7179 branch32(Assembler::GreaterThan, scratchInt,
7180 Imm32(wasm::AnyRef::MaxI31Value), &fallthrough);
7181 branch32(Assembler::LessThan, scratchInt, Imm32(wasm::AnyRef::MinI31Value),
7182 &fallthrough);
7183 jump(label);
7184 }
7185
7186 bind(&checkDouble);
7187 {
7188 unboxDouble(src, scratchFloat);
7189 convertDoubleToInt32(scratchFloat, scratchInt, &fallthrough);
7190 branch32(Assembler::GreaterThan, scratchInt,
7191 Imm32(wasm::AnyRef::MaxI31Value), &fallthrough);
7192 branch32(Assembler::LessThan, scratchInt, Imm32(wasm::AnyRef::MinI31Value),
7193 &fallthrough);
7194 jump(label);
7195 }
7196
7197 bind(&fallthrough);
7198 }
7199
7200 void MacroAssembler::convertValueToWasmAnyRef(ValueOperand src, Register dest,
7201 FloatRegister scratchFloat,
7202 Label* oolConvert) {
7203 Label doubleValue, int32Value, nullValue, stringValue, objectValue, done;
7204 {
7205 ScratchTagScope tag(*this, src);
7206 splitTagForTest(src, tag);
7207 branchTestObject(Assembler::Equal, tag, &objectValue);
7208 branchTestString(Assembler::Equal, tag, &stringValue);
7209 branchTestNull(Assembler::Equal, tag, &nullValue);
7210 branchTestInt32(Assembler::Equal, tag, &int32Value);
7211 branchTestDouble(Assembler::Equal, tag, &doubleValue);
7212 jump(oolConvert);
7213 }
7214
7215 bind(&doubleValue);
7216 {
7217 unboxDouble(src, scratchFloat);
7218 convertDoubleToInt32(scratchFloat, dest, oolConvert);
7219 branch32(Assembler::GreaterThan, dest, Imm32(wasm::AnyRef::MaxI31Value),
7220 oolConvert);
7221 branch32(Assembler::LessThan, dest, Imm32(wasm::AnyRef::MinI31Value),
7222 oolConvert);
7223 truncate32ToWasmI31Ref(dest, dest);
7224 jump(&done);
7225 }
7226
7227 bind(&int32Value);
7228 {
7229 unboxInt32(src, dest);
7230 branch32(Assembler::GreaterThan, dest, Imm32(wasm::AnyRef::MaxI31Value),
7231 oolConvert);
7232 branch32(Assembler::LessThan, dest, Imm32(wasm::AnyRef::MinI31Value),
7233 oolConvert);
7234 truncate32ToWasmI31Ref(dest, dest);
7235 jump(&done);
7236 }
7237
7238 bind(&nullValue);
7239 {
7240 static_assert(wasm::AnyRef::NullRefValue == 0);
7241 xorPtr(dest, dest);
7242 jump(&done);
7243 }
7244
7245 bind(&stringValue);
7246 {
7247 unboxString(src, dest);
7248 orPtr(Imm32((int32_t)wasm::AnyRefTag::String), dest);
7249 jump(&done);
7250 }
7251
7252 bind(&objectValue);
7253 {
7254 unboxObject(src, dest);
7255 }
7256
7257 bind(&done);
7258 }
7259
7260 void MacroAssembler::convertObjectToWasmAnyRef(Register src, Register dest) {
7261 // JS objects are represented without any tagging.
7262 movePtr(src, dest);
7263 }
7264
7265 void MacroAssembler::convertStringToWasmAnyRef(Register src, Register dest) {
7266 // JS strings require a tag.
7267 orPtr(Imm32(int32_t(wasm::AnyRefTag::String)), src, dest);
7268 }
7269
7270 void MacroAssembler::branchObjectIsWasmGcObject(bool isGcObject, Register src,
7271 Register scratch,
7272 Label* label) {
7273 constexpr uint32_t ShiftedMask = (Shape::kindMask() << Shape::kindShift());
7274 constexpr uint32_t ShiftedKind =
7275 (uint32_t(Shape::Kind::WasmGC) << Shape::kindShift());
7276 MOZ_ASSERT(src != scratch);
7277
7278 loadPtr(Address(src, JSObject::offsetOfShape()), scratch);
7279 load32(Address(scratch, Shape::offsetOfImmutableFlags()), scratch);
7280 and32(Imm32(ShiftedMask), scratch);
7281 branch32(isGcObject ? Assembler::Equal : Assembler::NotEqual, scratch,
7282 Imm32(ShiftedKind), label);
7283 }
7284
7285 void MacroAssembler::wasmNewStructObject(Register instance, Register result,
7286 Register allocSite, Register temp,
7287 size_t offsetOfTypeDefData,
7288 Label* fail, gc::AllocKind allocKind,
7289 bool zeroFields) {
7290 MOZ_ASSERT(instance != result);
7291
7292 // Don't execute the inline path if GC probes are built in.
7293 #ifdef JS_GC_PROBES
7294 jump(fail);
7295 #endif
7296
7297 #ifdef JS_GC_ZEAL
7298 // Don't execute the inline path if gc zeal or tracing are active.
7299 loadPtr(Address(instance, wasm::Instance::offsetOfAddressOfGCZealModeBits()),
7300 temp);
7301 loadPtr(Address(temp, 0), temp);
7302 branch32(Assembler::NotEqual, temp, Imm32(0), fail);
7303 #endif
7304
7305 // If the alloc site is long lived, immediately fall back to the OOL path,
7306 // which will handle that.
7307 branchTestPtr(Assembler::NonZero,
7308 Address(allocSite, gc::AllocSite::offsetOfScriptAndState()),
7309 Imm32(gc::AllocSite::LONG_LIVED_BIT), fail);
7310
7311 size_t sizeBytes = gc::Arena::thingSize(allocKind);
7312 wasmBumpPointerAllocate(instance, result, allocSite, temp, fail, sizeBytes);
7313
7314 loadPtr(Address(instance, offsetOfTypeDefData +
7315 wasm::TypeDefInstanceData::offsetOfShape()),
7316 temp);
7317 storePtr(temp, Address(result, WasmArrayObject::offsetOfShape()));
7318 loadPtr(Address(instance,
7319 offsetOfTypeDefData +
7320 wasm::TypeDefInstanceData::offsetOfSuperTypeVector()),
7321 temp);
7322 storePtr(temp, Address(result, WasmArrayObject::offsetOfSuperTypeVector()));
7323 storePtr(ImmWord(0),
7324 Address(result, WasmStructObject::offsetOfOutlineData()));
7325
7326 if (zeroFields) {
7327 MOZ_ASSERT(sizeBytes % sizeof(void*) == 0);
7328 for (size_t i = WasmStructObject::offsetOfInlineData(); i < sizeBytes;
7329 i += sizeof(void*)) {
7330 storePtr(ImmWord(0), Address(result, i));
7331 }
7332 }
7333 }
7334
7335 void MacroAssembler::wasmNewArrayObject(Register instance, Register result,
7336 Register numElements,
7337 Register allocSite, Register temp,
7338 size_t offsetOfTypeDefData, Label* fail,
7339 uint32_t elemSize, bool zeroFields) {
7340 MOZ_ASSERT(instance != result);
7341
7342 // Don't execute the inline path if GC probes are built in.
7343 #ifdef JS_GC_PROBES
7344 jump(fail);
7345 #endif
7346
7347 #ifdef JS_GC_ZEAL
7348 // Don't execute the inline path if gc zeal or tracing are active.
7349 loadPtr(Address(instance, wasm::Instance::offsetOfAddressOfGCZealModeBits()),
7350 temp);
7351 loadPtr(Address(temp, 0), temp);
7352 branch32(Assembler::NotEqual, temp, Imm32(0), fail);
7353 #endif
7354
7355 // If the alloc site is long lived, immediately fall back to the OOL path,
7356 // which will handle that.
7357 branchTestPtr(Assembler::NonZero,
7358 Address(allocSite, gc::AllocSite::offsetOfScriptAndState()),
7359 Imm32(gc::AllocSite::LONG_LIVED_BIT), fail);
7360
7361 // Ensure that the numElements is small enough to fit in inline storage.
7362 branch32(Assembler::Above, numElements,
7363 Imm32(WasmArrayObject::maxInlineElementsForElemSize(elemSize)),
7364 fail);
7365
7366 // Push numElements for later; numElements will be used as a temp in the
7367 // meantime. Make sure that all exit paths pop the value again!
7368 Label popAndFail;
7369 #ifdef JS_CODEGEN_ARM64
7370 // On arm64, we must maintain 16-alignment of both the actual and pseudo stack
7371 // pointers.
7372 push(numElements, xzr);
7373 syncStackPtr();
7374 #else
7375 push(numElements);
7376 #endif
7377
7378 // Compute the size of the allocation in bytes. The final size must correspond
7379 // to an AllocKind. See WasmArrayObject::calcStorageBytes and
7380 // WasmArrayObject::allocKindForIL.
7381
7382 // Compute the size of all array element data.
7383 mul32(Imm32(elemSize), numElements);
7384 // Add the data header.
7385 add32(Imm32(sizeof(WasmArrayObject::DataHeader)), numElements);
7386 // Round up to gc::CellAlignBytes to play nice with the GC and to simplify the
7387 // zeroing logic below.
7388 add32(Imm32(gc::CellAlignBytes - 1), numElements);
7389 and32(Imm32(~int32_t(gc::CellAlignBytes - 1)), numElements);
7390 // Add the size of the WasmArrayObject to get the full allocation size.
7391 static_assert(WasmArrayObject_MaxInlineBytes + sizeof(WasmArrayObject) <
7392 INT32_MAX);
7393 add32(Imm32(sizeof(WasmArrayObject)), numElements);
7394 // Per gc::slotsToAllocKindBytes, subtract sizeof(NativeObject),
7395 // divide by sizeof(js::Value), then look up the final AllocKind-based
7396 // allocation size from a table.
7397 movePtr(wasm::SymbolicAddress::SlotsToAllocKindBytesTable, temp);
7398 move32ZeroExtendToPtr(numElements, numElements);
7399 subPtr(Imm32(sizeof(NativeObject)), numElements);
7400 static_assert(sizeof(js::Value) == 8);
7401 rshiftPtr(Imm32(3), numElements);
7402 static_assert(sizeof(gc::slotsToAllocKindBytes[0]) == 4);
7403 load32(BaseIndex(temp, numElements, Scale::TimesFour), numElements);
7404
7405 wasmBumpPointerAllocateDynamic(instance, result, allocSite,
7406 /*size=*/numElements, temp, &popAndFail);
7407
7408 // Initialize the shape and STV
7409 loadPtr(Address(instance, offsetOfTypeDefData +
7410 wasm::TypeDefInstanceData::offsetOfShape()),
7411 temp);
7412 storePtr(temp, Address(result, WasmArrayObject::offsetOfShape()));
7413 loadPtr(Address(instance,
7414 offsetOfTypeDefData +
7415 wasm::TypeDefInstanceData::offsetOfSuperTypeVector()),
7416 temp);
7417 storePtr(temp, Address(result, WasmArrayObject::offsetOfSuperTypeVector()));
7418
7419 // Store inline data header and data pointer
7420 storePtr(ImmWord(WasmArrayObject::DataIsIL),
7421 Address(result, WasmArrayObject::offsetOfInlineStorage()));
7422 computeEffectiveAddress(
7423 Address(result, WasmArrayObject::offsetOfInlineArrayData()), temp);
7424 // temp now points at the base of the array data; this will be used later
7425 storePtr(temp, Address(result, WasmArrayObject::offsetOfData()));
7426 // numElements will be saved to the array object later; for now we want to
7427 // continue using numElements as a temp.
7428
7429 // Zero the array elements. This loop depends on the size of the array data
7430 // being a multiple of the machine word size. This is currently always the
7431 // case since WasmArrayObject::calcStorageBytes rounds up to
7432 // gc::CellAlignBytes.
7433 static_assert(gc::CellAlignBytes % sizeof(void*) == 0);
7434 Label zeroed;
7435 if (zeroFields) {
7436 // numElements currently stores the total size of the allocation. temp
7437 // points at the base of the inline array data. We will zero the memory by
7438 // advancing numElements to the end of the allocation, then counting down
7439 // toward temp, zeroing one word at a time. The following aliases make this
7440 // clearer.
7441 Register current = numElements;
7442 Register inlineArrayData = temp;
7443
7444 // We first need to update current to actually point at the end of the
7445 // allocation. We can compute this from the data pointer, since the data
7446 // pointer points at a known offset within the array.
7447 //
7448 // It is easier to understand the code below as first subtracting the offset
7449 // (to get back to the start of the allocation), then adding the total size
7450 // of the allocation (using Scale::TimesOne).
7451 computeEffectiveAddress(
7452 BaseIndex(inlineArrayData, current, Scale::TimesOne,
7453 -int32_t(WasmArrayObject::offsetOfInlineArrayData())),
7454 current);
7455
7456 // Exit immediately if the array has zero elements.
7457 branchPtr(Assembler::Equal, current, inlineArrayData, &zeroed);
7458
7459 // Loop, counting down until current == inlineArrayData.
7460 Label loop;
7461 bind(&loop);
7462 subPtr(Imm32(sizeof(void*)), current);
7463 storePtr(ImmWord(0), Address(current, 0));
7464 branchPtr(Assembler::NotEqual, current, inlineArrayData, &loop);
7465 }
7466 bind(&zeroed);
7467
7468 // Finally, store the actual numElements in the array object.
7469 #ifdef JS_CODEGEN_ARM64
7470 pop(xzr, numElements);
7471 syncStackPtr();
7472 #else
7473 pop(numElements);
7474 #endif
7475 store32(numElements, Address(result, WasmArrayObject::offsetOfNumElements()));
7476
7477 Label done;
7478 jump(&done);
7479
7480 bind(&popAndFail);
7481 #ifdef JS_CODEGEN_ARM64
7482 pop(xzr, numElements);
7483 syncStackPtr();
7484 #else
7485 pop(numElements);
7486 #endif
7487 jump(fail);
7488
7489 bind(&done);
7490 }
7491
7492 void MacroAssembler::wasmNewArrayObjectFixed(
7493 Register instance, Register result, Register allocSite, Register temp1,
7494 Register temp2, size_t offsetOfTypeDefData, Label* fail,
7495 uint32_t numElements, uint32_t storageBytes, bool zeroFields) {
7496 MOZ_ASSERT(storageBytes <= WasmArrayObject_MaxInlineBytes);
7497 MOZ_ASSERT(instance != result);
7498
7499 // Don't execute the inline path if GC probes are built in.
7500 #ifdef JS_GC_PROBES
7501 jump(fail);
7502 #endif
7503
7504 #ifdef JS_GC_ZEAL
7505 // Don't execute the inline path if gc zeal or tracing are active.
7506 loadPtr(Address(instance, wasm::Instance::offsetOfAddressOfGCZealModeBits()),
7507 temp1);
7508 loadPtr(Address(temp1, 0), temp1);
7509 branch32(Assembler::NotEqual, temp1, Imm32(0), fail);
7510 #endif
7511
7512 // If the alloc site is long lived, immediately fall back to the OOL path,
7513 // which will handle that.
7514 branchTestPtr(Assembler::NonZero,
7515 Address(allocSite, gc::AllocSite::offsetOfScriptAndState()),
7516 Imm32(gc::AllocSite::LONG_LIVED_BIT), fail);
7517
7518 gc::AllocKind allocKind = WasmArrayObject::allocKindForIL(storageBytes);
7519 uint32_t totalSize = gc::Arena::thingSize(allocKind);
7520 wasmBumpPointerAllocate(instance, result, allocSite, temp1, fail, totalSize);
7521
7522 loadPtr(Address(instance, offsetOfTypeDefData +
7523 wasm::TypeDefInstanceData::offsetOfShape()),
7524 temp1);
7525 loadPtr(Address(instance,
7526 offsetOfTypeDefData +
7527 wasm::TypeDefInstanceData::offsetOfSuperTypeVector()),
7528 temp2);
7529 storePtr(temp1, Address(result, WasmArrayObject::offsetOfShape()));
7530 storePtr(temp2, Address(result, WasmArrayObject::offsetOfSuperTypeVector()));
7531 store32(Imm32(numElements),
7532 Address(result, WasmArrayObject::offsetOfNumElements()));
7533
7534 // Store inline data header and data pointer
7535 storePtr(ImmWord(WasmArrayObject::DataIsIL),
7536 Address(result, WasmArrayObject::offsetOfInlineStorage()));
7537 computeEffectiveAddress(
7538 Address(result, WasmArrayObject::offsetOfInlineArrayData()), temp2);
7539 // temp2 now points at the base of the array data; this will be used later
7540 storePtr(temp2, Address(result, WasmArrayObject::offsetOfData()));
7541
7542 if (zeroFields) {
7543 MOZ_ASSERT(storageBytes % sizeof(void*) == 0);
7544
7545 // Advance temp1 to the end of the allocation
7546 // (note that temp2 is already past the data header)
7547 Label done;
7548 computeEffectiveAddress(
7549 Address(temp2, -sizeof(WasmArrayObject::DataHeader) + storageBytes),
7550 temp1);
7551 branchPtr(Assembler::Equal, temp1, temp2, &done);
7552
7553 // Count temp2 down toward temp1, zeroing one word at a time
7554 Label loop;
7555 bind(&loop);
7556 subPtr(Imm32(sizeof(void*)), temp1);
7557 storePtr(ImmWord(0), Address(temp1, 0));
7558 branchPtr(Assembler::NotEqual, temp1, temp2, &loop);
7559
7560 bind(&done);
7561 }
7562 }
7563
7564 void MacroAssembler::wasmBumpPointerAllocate(Register instance, Register result,
7565 Register allocSite, Register temp1,
7566 Label* fail, uint32_t size) {
7567 MOZ_ASSERT(size >= gc::MinCellSize);
7568
7569 uint32_t totalSize = size + Nursery::nurseryCellHeaderSize();
7570 MOZ_ASSERT(totalSize < INT32_MAX, "Nursery allocation too large");
7571 MOZ_ASSERT(totalSize % gc::CellAlignBytes == 0);
7572
7573 int32_t endOffset = Nursery::offsetOfCurrentEndFromPosition();
7574
7575 // Bail to OOL code if the alloc site needs to be pushed onto the active
7576 // list.
7577 load32(Address(allocSite, gc::AllocSite::offsetOfNurseryAllocCount()), temp1);
7578 branch32(Assembler::Equal, temp1,
7579 Imm32(js::gc::NormalSiteAttentionThreshold - 1), fail);
7580
7581 // Bump allocate in the nursery, bailing if there is not enough room.
7582 loadPtr(Address(instance, wasm::Instance::offsetOfAddressOfNurseryPosition()),
7583 temp1);
7584 loadPtr(Address(temp1, 0), result);
7585 addPtr(Imm32(totalSize), result);
7586 branchPtr(Assembler::Below, Address(temp1, endOffset), result, fail);
7587 storePtr(result, Address(temp1, 0));
7588 subPtr(Imm32(size), result);
7589
7590 // Increment the alloc count in the allocation site and store pointer in the
7591 // nursery cell header. See NurseryCellHeader::MakeValue.
7592 add32(Imm32(1),
7593 Address(allocSite, gc::AllocSite::offsetOfNurseryAllocCount()));
7594 // Because JS::TraceKind::Object is zero, there is no need to explicitly set
7595 // it in the nursery cell header.
7596 static_assert(int(JS::TraceKind::Object) == 0);
7597 storePtr(allocSite, Address(result, -js::Nursery::nurseryCellHeaderSize()));
7598 }
7599
7600 void MacroAssembler::wasmBumpPointerAllocateDynamic(
7601 Register instance, Register result, Register allocSite, Register size,
7602 Register temp1, Label* fail) {
7603 #ifdef DEBUG
7604 // Replaces MOZ_ASSERT(size >= gc::MinCellSize);
7605 Label ok1;
7606 branch32(Assembler::AboveOrEqual, size, Imm32(gc::MinCellSize), &ok1);
7607 breakpoint();
7608 bind(&ok1);
7609
7610 Label ok2;
7611 branch32(Assembler::BelowOrEqual, size, Imm32(JSObject::MAX_BYTE_SIZE), &ok2);
7612 breakpoint();
7613 bind(&ok2);
7614 #endif
7615
7616 int32_t endOffset = Nursery::offsetOfCurrentEndFromPosition();
7617
7618 // Bail to OOL code if the alloc site needs to be initialized.
7619 load32(Address(allocSite, gc::AllocSite::offsetOfNurseryAllocCount()), temp1);
7620 branch32(Assembler::Equal, temp1,
7621 Imm32(js::gc::NormalSiteAttentionThreshold - 1), fail);
7622
7623 // Bump allocate in the nursery, bailing if there is not enough room.
7624 loadPtr(Address(instance, wasm::Instance::offsetOfAddressOfNurseryPosition()),
7625 temp1);
7626 loadPtr(Address(temp1, 0), result);
7627 computeEffectiveAddress(BaseIndex(result, size, Scale::TimesOne,
7628 Nursery::nurseryCellHeaderSize()),
7629 result);
7630 branchPtr(Assembler::Below, Address(temp1, endOffset), result, fail);
7631 storePtr(result, Address(temp1, 0));
7632 subPtr(size, result);
7633
7634 // Increment the alloc count in the allocation site and store pointer in the
7635 // nursery cell header. See NurseryCellHeader::MakeValue.
7636
7637 add32(Imm32(1),
7638 Address(allocSite, gc::AllocSite::offsetOfNurseryAllocCount()));
7639 // Because JS::TraceKind::Object is zero, there is no need to explicitly set
7640 // it in the nursery cell header.
7641 static_assert(int(JS::TraceKind::Object) == 0);
7642 storePtr(allocSite, Address(result, -js::Nursery::nurseryCellHeaderSize()));
7643 }
7644
7645 // Unboxing is branchy and contorted because of Spectre mitigations - we don't
7646 // have enough scratch registers. Were it not for the spectre mitigations in
7647 // branchTestObjClass, the branch nest below would be restructured significantly
7648 // by inverting branches and using fewer registers.
7649
7650 // Unbox an anyref in src (clobbering src in the process) and then re-box it as
7651 // a Value in *dst. See the definition of AnyRef for a discussion of pointer
7652 // representation.
7653 void MacroAssembler::convertWasmAnyRefToValue(Register instance, Register src,
7654 ValueOperand dst,
7655 Register scratch) {
7656 MOZ_ASSERT(src != scratch);
7657 #if JS_BITS_PER_WORD == 32
7658 MOZ_ASSERT(dst.typeReg() != scratch);
7659 MOZ_ASSERT(dst.payloadReg() != scratch);
7660 #else
7661 MOZ_ASSERT(dst.valueReg() != scratch);
7662 #endif
7663
7664 Label isI31, isObjectOrNull, isObject, isWasmValueBox, done;
7665
7666 // Check for if this is an i31 value first
7667 branchTestPtr(Assembler::NonZero, src, Imm32(int32_t(wasm::AnyRefTag::I31)),
7668 &isI31);
7669 // Then check for the object or null tag
7670 branchTestPtr(Assembler::Zero, src, Imm32(wasm::AnyRef::TagMask),
7671 &isObjectOrNull);
7672
7673 // If we're not i31, object, or null, we must be a string
7674 untagWasmAnyRef(src, src, wasm::AnyRefTag::String);
7675 moveValue(TypedOrValueRegister(MIRType::String, AnyRegister(src)), dst);
7676 jump(&done);
7677
7678 // This is an i31 value, convert to an int32 JS value
7679 bind(&isI31);
7680 convertWasmI31RefTo32Signed(src, src);
7681 moveValue(TypedOrValueRegister(MIRType::Int32, AnyRegister(src)), dst);
7682 jump(&done);
7683
7684 // Check for the null value
7685 bind(&isObjectOrNull);
7686 branchTestPtr(Assembler::NonZero, src, src, &isObject);
7687 moveValue(NullValue(), dst);
7688 jump(&done);
7689
7690 // Otherwise we must be a non-null object. We next to check if it's storing a
7691 // boxed value
7692 bind(&isObject);
7693 // The type test will clear src if the test fails, so store early.
7694 moveValue(TypedOrValueRegister(MIRType::Object, AnyRegister(src)), dst);
7695 // Spectre mitigations: see comment above about efficiency.
7696 branchTestObjClass(Assembler::Equal, src,
7697 Address(instance, wasm::Instance::offsetOfValueBoxClass()),
7698 scratch, src, &isWasmValueBox);
7699 jump(&done);
7700
7701 // This is a boxed JS value, unbox it.
7702 bind(&isWasmValueBox);
7703 loadValue(Address(src, wasm::AnyRef::valueBoxOffsetOfValue()), dst);
7704
7705 bind(&done);
7706 }
7707
7708 void MacroAssembler::convertWasmAnyRefToValue(Register instance, Register src,
7709 const Address& dst,
7710 Register scratch) {
7711 MOZ_ASSERT(src != scratch);
7712
7713 Label isI31, isObjectOrNull, isObject, isWasmValueBox, done;
7714
7715 // Check for if this is an i31 value first
7716 branchTestPtr(Assembler::NonZero, src, Imm32(int32_t(wasm::AnyRefTag::I31)),
7717 &isI31);
7718 // Then check for the object or null tag
7719 branchTestPtr(Assembler::Zero, src, Imm32(wasm::AnyRef::TagMask),
7720 &isObjectOrNull);
7721
7722 // If we're not i31, object, or null, we must be a string
7723 rshiftPtr(Imm32(wasm::AnyRef::TagShift), src);
7724 lshiftPtr(Imm32(wasm::AnyRef::TagShift), src);
7725 storeValue(JSVAL_TYPE_STRING, src, dst);
7726 jump(&done);
7727
7728 // This is an i31 value, convert to an int32 JS value
7729 bind(&isI31);
7730 convertWasmI31RefTo32Signed(src, src);
7731 storeValue(JSVAL_TYPE_INT32, src, dst);
7732 jump(&done);
7733
7734 // Check for the null value
7735 bind(&isObjectOrNull);
7736 branchTestPtr(Assembler::NonZero, src, src, &isObject);
7737 storeValue(NullValue(), dst);
7738 jump(&done);
7739
7740 // Otherwise we must be a non-null object. We next to check if it's storing a
7741 // boxed value
7742 bind(&isObject);
7743 // The type test will clear src if the test fails, so store early.
7744 storeValue(JSVAL_TYPE_OBJECT, src, dst);
7745 // Spectre mitigations: see comment above about efficiency.
7746 branchTestObjClass(Assembler::Equal, src,
7747 Address(instance, wasm::Instance::offsetOfValueBoxClass()),
7748 scratch, src, &isWasmValueBox);
7749 jump(&done);
7750
7751 // This is a boxed JS value, unbox it.
7752 bind(&isWasmValueBox);
7753 copy64(Address(src, wasm::AnyRef::valueBoxOffsetOfValue()), dst, scratch);
7754
7755 bind(&done);
7756 }
7757
7758 void MacroAssembler::nopPatchableToCall(const wasm::CallSiteDesc& desc) {
7759 CodeOffset offset = nopPatchableToCall();
7760 append(desc, offset);
7761 }
7762
7763 void MacroAssembler::emitPreBarrierFastPath(JSRuntime* rt, MIRType type,
7764 Register temp1, Register temp2,
7765 Register temp3, Label* noBarrier) {
7766 MOZ_ASSERT(temp1 != PreBarrierReg);
7767 MOZ_ASSERT(temp2 != PreBarrierReg);
7768 MOZ_ASSERT(temp3 != PreBarrierReg);
7769
7770 // Load the GC thing in temp1.
7771 if (type == MIRType::Value) {
7772 unboxGCThingForGCBarrier(Address(PreBarrierReg, 0), temp1);
7773 } else if (type == MIRType::WasmAnyRef) {
7774 unboxWasmAnyRefGCThingForGCBarrier(Address(PreBarrierReg, 0), temp1);
7775 } else {
7776 MOZ_ASSERT(type == MIRType::Object || type == MIRType::String ||
7777 type == MIRType::Shape);
7778 loadPtr(Address(PreBarrierReg, 0), temp1);
7779 }
7780
7781 #ifdef DEBUG
7782 // The caller should have checked for null pointers.
7783 Label nonZero;
7784 branchTestPtr(Assembler::NonZero, temp1, temp1, &nonZero);
7785 assumeUnreachable("JIT pre-barrier: unexpected nullptr");
7786 bind(&nonZero);
7787 #endif
7788
7789 // Load the chunk address in temp2.
7790 andPtr(Imm32(int32_t(~gc::ChunkMask)), temp1, temp2);
7791
7792 // If the GC thing is in the nursery, we don't need to barrier it.
7793 if (type == MIRType::Value || type == MIRType::Object ||
7794 type == MIRType::String || type == MIRType::WasmAnyRef) {
7795 branchPtr(Assembler::NotEqual, Address(temp2, gc::ChunkStoreBufferOffset),
7796 ImmWord(0), noBarrier);
7797 } else {
7798 #ifdef DEBUG
7799 Label isTenured;
7800 branchPtr(Assembler::Equal, Address(temp2, gc::ChunkStoreBufferOffset),
7801 ImmWord(0), &isTenured);
7802 assumeUnreachable("JIT pre-barrier: unexpected nursery pointer");
7803 bind(&isTenured);
7804 #endif
7805 }
7806
7807 // Determine the bit index and store in temp1.
7808 //
7809 // bit = (addr & js::gc::ChunkMask) / js::gc::CellBytesPerMarkBit +
7810 // static_cast<uint32_t>(colorBit);
7811 static_assert(gc::CellBytesPerMarkBit == 8,
7812 "Calculation below relies on this");
7813 static_assert(size_t(gc::ColorBit::BlackBit) == 0,
7814 "Calculation below relies on this");
7815 andPtr(Imm32(gc::ChunkMask), temp1);
7816 rshiftPtr(Imm32(3), temp1);
7817
7818 static_assert(gc::MarkBitmapWordBits == JS_BITS_PER_WORD,
7819 "Calculation below relies on this");
7820
7821 // Load the bitmap word in temp2.
7822 //
7823 // word = chunk.bitmap[bit / MarkBitmapWordBits];
7824
7825 // Fold the adjustment for the fact that arenas don't start at the beginning
7826 // of the chunk into the offset to the chunk bitmap.
7827 const size_t firstArenaAdjustment =
7828 gc::ChunkMarkBitmap::FirstThingAdjustmentBits / CHAR_BIT;
7829 const intptr_t offset =
7830 intptr_t(gc::ChunkMarkBitmapOffset) - intptr_t(firstArenaAdjustment);
7831
7832 movePtr(temp1, temp3);
7833 #if JS_BITS_PER_WORD == 64
7834 rshiftPtr(Imm32(6), temp1);
7835 loadPtr(BaseIndex(temp2, temp1, TimesEight, offset), temp2);
7836 #else
7837 rshiftPtr(Imm32(5), temp1);
7838 loadPtr(BaseIndex(temp2, temp1, TimesFour, offset), temp2);
7839 #endif
7840
7841 // Load the mask in temp1.
7842 //
7843 // mask = uintptr_t(1) << (bit % MarkBitmapWordBits);
7844 andPtr(Imm32(gc::MarkBitmapWordBits - 1), temp3);
7845 move32(Imm32(1), temp1);
7846 #ifdef JS_CODEGEN_X64
7847 MOZ_ASSERT(temp3 == rcx);
7848 shlq_cl(temp1);
7849 #elif JS_CODEGEN_X86
7850 MOZ_ASSERT(temp3 == ecx);
7851 shll_cl(temp1);
7852 #elif JS_CODEGEN_ARM
7853 ma_lsl(temp3, temp1, temp1);
7854 #elif JS_CODEGEN_ARM64
7855 Lsl(ARMRegister(temp1, 64), ARMRegister(temp1, 64), ARMRegister(temp3, 64));
7856 #elif JS_CODEGEN_MIPS64
7857 ma_dsll(temp1, temp1, temp3);
7858 #elif JS_CODEGEN_LOONG64
7859 as_sll_d(temp1, temp1, temp3);
7860 #elif JS_CODEGEN_RISCV64
7861 sll(temp1, temp1, temp3);
7862 #elif JS_CODEGEN_WASM32
7863 MOZ_CRASH();
7864 #elif JS_CODEGEN_NONE
7865 MOZ_CRASH();
7866 #else
7867 # error "Unknown architecture"
7868 #endif
7869
7870 // No barrier is needed if the bit is set, |word & mask != 0|.
7871 branchTestPtr(Assembler::NonZero, temp2, temp1, noBarrier);
7872 }
7873
7874 // ========================================================================
7875 // JS atomic operations.
7876
7877 void MacroAssembler::atomicIsLockFreeJS(Register value, Register output) {
7878 // Keep this in sync with isLockfreeJS() in jit/AtomicOperations.h.
7879 static_assert(AtomicOperations::isLockfreeJS(1)); // Implementation artifact
7880 static_assert(AtomicOperations::isLockfreeJS(2)); // Implementation artifact
7881 static_assert(AtomicOperations::isLockfreeJS(4)); // Spec requirement
7882 static_assert(AtomicOperations::isLockfreeJS(8)); // Implementation artifact
7883
7884 Label done;
7885 move32(Imm32(1), output);
7886 branch32(Assembler::Equal, value, Imm32(8), &done);
7887 branch32(Assembler::Equal, value, Imm32(4), &done);
7888 branch32(Assembler::Equal, value, Imm32(2), &done);
7889 branch32(Assembler::Equal, value, Imm32(1), &done);
7890 move32(Imm32(0), output);
7891 bind(&done);
7892 }
7893
7894 // ========================================================================
7895 // Spectre Mitigations.
7896
7897 void MacroAssembler::spectreMaskIndex32(Register index, Register length,
7898 Register output) {
7899 MOZ_ASSERT(JitOptions.spectreIndexMasking);
7900 MOZ_ASSERT(length != output);
7901 MOZ_ASSERT(index != output);
7902
7903 move32(Imm32(0), output);
7904 cmp32Move32(Assembler::Below, index, length, index, output);
7905 }
7906
7907 void MacroAssembler::spectreMaskIndex32(Register index, const Address& length,
7908 Register output) {
7909 MOZ_ASSERT(JitOptions.spectreIndexMasking);
7910 MOZ_ASSERT(index != length.base);
7911 MOZ_ASSERT(length.base != output);
7912 MOZ_ASSERT(index != output);
7913
7914 move32(Imm32(0), output);
7915 cmp32Move32(Assembler::Below, index, length, index, output);
7916 }
7917
7918 void MacroAssembler::spectreMaskIndexPtr(Register index, Register length,
7919 Register output) {
7920 MOZ_ASSERT(JitOptions.spectreIndexMasking);
7921 MOZ_ASSERT(length != output);
7922 MOZ_ASSERT(index != output);
7923
7924 movePtr(ImmWord(0), output);
7925 cmpPtrMovePtr(Assembler::Below, index, length, index, output);
7926 }
7927
7928 void MacroAssembler::spectreMaskIndexPtr(Register index, const Address& length,
7929 Register output) {
7930 MOZ_ASSERT(JitOptions.spectreIndexMasking);
7931 MOZ_ASSERT(index != length.base);
7932 MOZ_ASSERT(length.base != output);
7933 MOZ_ASSERT(index != output);
7934
7935 movePtr(ImmWord(0), output);
7936 cmpPtrMovePtr(Assembler::Below, index, length, index, output);
7937 }
7938
7939 void MacroAssembler::boundsCheck32PowerOfTwo(Register index, uint32_t length,
7940 Label* failure) {
7941 MOZ_ASSERT(mozilla::IsPowerOfTwo(length));
7942 branch32(Assembler::AboveOrEqual, index, Imm32(length), failure);
7943
7944 // Note: it's fine to clobber the input register, as this is a no-op: it
7945 // only affects speculative execution.
7946 if (JitOptions.spectreIndexMasking) {
7947 and32(Imm32(length - 1), index);
7948 }
7949 }
7950
7951 void MacroAssembler::loadWasmPinnedRegsFromInstance(
7952 const wasm::MaybeTrapSiteDesc& trapSiteDesc) {
7953 #ifdef WASM_HAS_HEAPREG
7954 static_assert(wasm::Instance::offsetOfMemory0Base() < 4096,
7955 "We count only on the low page being inaccessible");
7956 FaultingCodeOffset fco = loadPtr(
7957 Address(InstanceReg, wasm::Instance::offsetOfMemory0Base()), HeapReg);
7958 if (trapSiteDesc) {
7959 append(wasm::Trap::IndirectCallToNull, wasm::TrapMachineInsnForLoadWord(),
7960 fco.get(), *trapSiteDesc);
7961 }
7962 #else
7963 MOZ_ASSERT(!trapSiteDesc);
7964 #endif
7965 }
7966
7967 //}}} check_macroassembler_style
7968
7969 #ifdef JS_64BIT
7970 void MacroAssembler::debugAssertCanonicalInt32(Register r) {
7971 # ifdef DEBUG
7972 if (!js::jit::JitOptions.lessDebugCode) {
7973 # if defined(JS_CODEGEN_X64) || defined(JS_CODEGEN_ARM64)
7974 Label ok;
7975 branchPtr(Assembler::BelowOrEqual, r, ImmWord(UINT32_MAX), &ok);
7976 breakpoint();
7977 bind(&ok);
7978 # elif defined(JS_CODEGEN_MIPS64) || defined(JS_CODEGEN_LOONG64)
7979 Label ok;
7980 ScratchRegisterScope scratch(asMasm());
7981 move32SignExtendToPtr(r, scratch);
7982 branchPtr(Assembler::Equal, r, scratch, &ok);
7983 breakpoint();
7984 bind(&ok);
7985 # else
7986 MOZ_CRASH("IMPLEMENT ME");
7987 # endif
7988 }
7989 # endif
7990 }
7991 #endif
7992
7993 void MacroAssembler::memoryBarrierBefore(Synchronization sync) {
7994 memoryBarrier(sync.barrierBefore);
7995 }
7996
7997 void MacroAssembler::memoryBarrierAfter(Synchronization sync) {
7998 memoryBarrier(sync.barrierAfter);
7999 }
8000
8001 void MacroAssembler::convertDoubleToFloat16(FloatRegister src,
8002 FloatRegister dest, Register temp,
8003 LiveRegisterSet volatileLiveRegs) {
8004 if (MacroAssembler::SupportsFloat64To16()) {
8005 convertDoubleToFloat16(src, dest);
8006
8007 // Float16 is currently passed as Float32, so expand again to Float32.
8008 convertFloat16ToFloat32(dest, dest);
8009 return;
8010 }
8011
8012 LiveRegisterSet save = volatileLiveRegs;
8013 save.takeUnchecked(dest);
8014 save.takeUnchecked(dest.asDouble());
8015 save.takeUnchecked(temp);
8016
8017 PushRegsInMask(save);
8018
8019 using Fn = float (*)(double);
8020 setupUnalignedABICall(temp);
8021 passABIArg(src, ABIType::Float64);
8022 callWithABI<Fn, jit::RoundFloat16ToFloat32>(ABIType::Float32);
8023 storeCallFloatResult(dest);
8024
8025 PopRegsInMask(save);
8026 }
8027
8028 void MacroAssembler::convertDoubleToFloat16(FloatRegister src,
8029 FloatRegister dest, Register temp1,
8030 Register temp2) {
8031 MOZ_ASSERT(MacroAssembler::SupportsFloat64To16() ||
8032 MacroAssembler::SupportsFloat32To16());
8033 MOZ_ASSERT(src != dest);
8034
8035 if (MacroAssembler::SupportsFloat64To16()) {
8036 convertDoubleToFloat16(src, dest);
8037
8038 // Float16 is currently passed as Float32, so expand again to Float32.
8039 convertFloat16ToFloat32(dest, dest);
8040 return;
8041 }
8042
8043 using Float32 = mozilla::FloatingPoint<float>;
8044
8045 #ifdef DEBUG
8046 static auto float32Bits = [](float16 f16) {
8047 // Cast to float and reinterpret to bit representation.
8048 return mozilla::BitwiseCast<Float32::Bits>(static_cast<float>(f16));
8049 };
8050
8051 static auto nextExponent = [](float16 f16, int32_t direction) {
8052 constexpr auto kSignificandWidth = Float32::kSignificandWidth;
8053
8054 // Shift out mantissa and then adjust exponent.
8055 auto bits = float32Bits(f16);
8056 return ((bits >> kSignificandWidth) + direction) << kSignificandWidth;
8057 };
8058 #endif
8059
8060 // Float32 larger or equals to |overflow| are infinity (or NaN) in Float16.
8061 constexpr uint32_t overflow = 0x4780'0000;
8062 MOZ_ASSERT(overflow == nextExponent(std::numeric_limits<float16>::max(), 1));
8063
8064 // Float32 smaller than |underflow| are zero in Float16.
8065 constexpr uint32_t underflow = 0x3300'0000;
8066 MOZ_ASSERT(underflow ==
8067 nextExponent(std::numeric_limits<float16>::denorm_min(), -1));
8068
8069 // Float32 larger or equals to |normal| are normal numbers in Float16.
8070 constexpr uint32_t normal = 0x3880'0000;
8071 MOZ_ASSERT(normal == float32Bits(std::numeric_limits<float16>::min()));
8072
8073 // There are five possible cases to consider:
8074 // 1. Non-finite (infinity and NaN)
8075 // 2. Overflow to infinity
8076 // 3. Normal numbers
8077 // 4. Denormal numbers
8078 // 5. Underflow to zero
8079 //
8080 // Cases 1-2 and 4-5 don't need separate code paths, so we only need to be
8081 // concerned about incorrect double rounding for cases 3-4.
8082 //
8083 // Double rounding:
8084 //
8085 // Conversion from float64 -> float32 -> float16 can introduce double rounding
8086 // errors when compared to a direct conversion float64 -> float16.
8087 //
8088 // Number of bits in the exponent and mantissa. These are relevant below.
8089 //
8090 // exponent mantissa
8091 // -----------------------
8092 // f16 | 5 10
8093 // f32 | 8 23
8094 // f64 | 11 52
8095 //
8096 // Examples:
8097 //
8098 // Input (f64): 0.0000610649585723877
8099 // Bits (f64): 3f10'0200'0000'0000
8100 // Bits (f32): 3880'1000
8101 // Bits (f16): 0400
8102 //
8103 // Ignore the three left-most nibbles of the f64 bits (those are the sign and
8104 // exponent). Shift the f64 mantissa right by (52 - 23) = 29 bits. The bits
8105 // of the f32 mantissa are therefore 00'1000. Converting from f32 to f16 will
8106 // right shift the mantissa by (23 - 10) = 13 bits. `001000 >> 13` is all
8107 // zero. Directly converting from f64 to f16 right shifts the f64 mantissa by
8108 // (52 - 10) = 42 bits. `0'0200'0000'0000 >> 42` is also all zero. So in this
8109 // case no double rounding did take place.
8110 //
8111 // Input (f64): 0.00006106495857238771
8112 // Bits (f64): 3f10'0200'0000'0001
8113 // Bits (f32): 3880'1000
8114 // Bits (f16): 0401
8115 //
8116 // The f64 to f32 conversion returns the same result 3880'1000 as in the first
8117 // example, but the direct f64 to f16 conversion must return 0401. Let's look
8118 // at the binary representation of the mantissa.
8119 //
8120 // Mantissa of 3f10'0200'0000'0001 in binary representation:
8121 //
8122 // Low 32-bits
8123 // __________________|__________________
8124 // / |
8125 // 0000 0000 0010 0000 0000 0000 0000 0000 0000 0000 0000 0000 0001
8126 // | |
8127 // | GRS
8128 // | 001
8129 // |
8130 // GRS (G)uard bit
8131 // 011 (R)ound bit
8132 // (S)ticky bit
8133 //
8134 // The guard, round, and sticky bits control when to round: If the round bit
8135 // is one and at least one of guard or sticky is one, then round up. The
8136 // sticky bit is the or-ed value of all bits right of the round bit.
8137 //
8138 // When rounding to float16, GRS is 011, so we have to round up, whereas when
8139 // rounding to float32, GRS is 001, so no rounding takes place.
8140 //
8141 // Mantissa of 3880'1000 in binary representation:
8142 //
8143 // e000 0000 0001 0000 0000 0000
8144 // |
8145 // GRS
8146 // 010
8147 //
8148 // The round bit is set, but neither the guard nor sticky bit is set, so no
8149 // rounding takes place for the f32 -> f16 conversion. We can attempt to
8150 // recover the missing sticky bit from the f64 -> f16 conversion by looking at
8151 // the low 32-bits of the f64 mantissa. If at least one bit is set in the
8152 // low 32-bits (and the MSB is zero), then add one to the f32 mantissa.
8153 // Modified mantissa now looks like:
8154 //
8155 // e000 0000 0001 0000 0000 0001
8156 // |
8157 // GRS
8158 // 011
8159 //
8160 // GRS is now 011, so we round up and get the correctly rounded result 0401.
8161 //
8162 // Input (f64): 0.00006112456321716307
8163 // Bits (f64): 3f10'05ff'ffff'ffff
8164 // Bits (f32): 3880'3000
8165 // Bits (f16): 0401
8166 //
8167 // Low 32-bits
8168 // __________________|__________________
8169 // / |
8170 // 0000 0000 0101 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111
8171 // | |
8172 // | GRS
8173 // | 111
8174 // |
8175 // GRS
8176 // 101
8177 //
8178 // When rounding to float16, GRS is 101, so we don't round, whereas when
8179 // rounding to float32, GRS is 111, so we have to round up.
8180 //
8181 // Mantissa of 3880'3000 in binary representation:
8182 //
8183 // e000 0000 0011 0000 0000 0000
8184 // |
8185 // GRS
8186 // 110
8187 //
8188 // The guard and sticky bits are set, so the float32 -> float16 conversion
8189 // incorrectly rounds up when compared to the direct float64 -> float16
8190 // conversion. To avoid rounding twice we subtract one if the MSB of the low
8191 // 32-bits of the f64 mantissa is set. Modified mantissa now looks like:
8192 //
8193 // e000 0000 0010 1111 1111 1111
8194 // |
8195 // GRS
8196 // 101
8197 //
8198 // GRS is now 101, so we don't round and get the correct result 0401.
8199 //
8200 // Approach used to avoid double rounding:
8201 //
8202 // 1. For normal numbers, inspect the f32 mantissa and if its round bit is set
8203 // and the sticky bits are all zero, then possibly adjust the f32 mantissa
8204 // depending on the low 32-bits of the f64 mantissa.
8205 //
8206 // 2. For denormal numbers, possibly adjust the f32 mantissa if the round and
8207 // sticky bits are all zero.
8208
8209 // First round to float32 and reinterpret to bit representation.
8210 convertDoubleToFloat32(src, dest);
8211 moveFloat32ToGPR(dest, temp1);
8212
8213 // Mask off sign bit to simplify range checks.
8214 and32(Imm32(~Float32::kSignBit), temp1);
8215
8216 Label done;
8217
8218 // No changes necessary for underflow or overflow, including zero and
8219 // non-finite numbers.
8220 branch32(Assembler::Below, temp1, Imm32(underflow), &done);
8221 branch32(Assembler::AboveOrEqual, temp1, Imm32(overflow), &done);
8222
8223 // Compute 0x1000 for normal and 0x0000 for denormal numbers.
8224 cmp32Set(Assembler::AboveOrEqual, temp1, Imm32(normal), temp2);
8225 lshift32(Imm32(12), temp2);
8226
8227 // Look at the last thirteen bits of the mantissa which will be shifted out
8228 // when converting from float32 to float16. (The round and sticky bits.)
8229 //
8230 // Normal numbers: If the round bit is set and sticky bits are zero, then
8231 // adjust the float32 mantissa.
8232 // Denormal numbers: If all bits are zero, then adjust the mantissa.
8233 and32(Imm32(0x1fff), temp1);
8234 branch32(Assembler::NotEqual, temp1, temp2, &done);
8235 {
8236 #if defined(JS_CODEGEN_X86) || defined(JS_CODEGEN_X64)
8237 // x86 can use SIMD instructions to avoid GPR<>XMM register moves.
8238 ScratchSimd128Scope scratch(*this);
8239
8240 int32_t one[] = {1, 0, 0, 0};
8241 loadConstantSimd128(SimdConstant::CreateX4(one), scratch);
8242
8243 // 1. If the low 32-bits of |src| are all zero, then set |scratch| to 0.
8244 // 2. If the MSB of the low 32-bits is set, then set |scratch| to -1.
8245 // 3. Otherwise set |scratch| to 1.
8246 vpsignd(Operand(src), scratch, scratch);
8247
8248 // Add |scratch| to the mantissa.
8249 vpaddd(Operand(scratch), dest, dest);
8250 #else
8251 // Determine in which direction to round. When the low 32-bits are all zero,
8252 // then we don't have to round.
8253 moveLowDoubleToGPR(src, temp2);
8254 branch32(Assembler::Equal, temp2, Imm32(0), &done);
8255
8256 // Load either -1 or +1 into |temp2|.
8257 rshift32Arithmetic(Imm32(31), temp2);
8258 or32(Imm32(1), temp2);
8259
8260 // Add or subtract one to the mantissa.
8261 moveFloat32ToGPR(dest, temp1);
8262 add32(temp2, temp1);
8263 moveGPRToFloat32(temp1, dest);
8264 #endif
8265 }
8266
8267 bind(&done);
8268
8269 // Perform the actual float16 conversion.
8270 convertFloat32ToFloat16(dest, dest);
8271
8272 // Float16 is currently passed as Float32, so expand again to Float32.
8273 convertFloat16ToFloat32(dest, dest);
8274 }
8275
8276 void MacroAssembler::convertFloat32ToFloat16(FloatRegister src,
8277 FloatRegister dest, Register temp,
8278 LiveRegisterSet volatileLiveRegs) {
8279 if (MacroAssembler::SupportsFloat32To16()) {
8280 convertFloat32ToFloat16(src, dest);
8281
8282 // Float16 is currently passed as Float32, so expand again to Float32.
8283 convertFloat16ToFloat32(dest, dest);
8284 return;
8285 }
8286
8287 LiveRegisterSet save = volatileLiveRegs;
8288 save.takeUnchecked(dest);
8289 save.takeUnchecked(dest.asDouble());
8290 save.takeUnchecked(temp);
8291
8292 PushRegsInMask(save);
8293
8294 using Fn = float (*)(float);
8295 setupUnalignedABICall(temp);
8296 passABIArg(src, ABIType::Float32);
8297 callWithABI<Fn, jit::RoundFloat16ToFloat32>(ABIType::Float32);
8298 storeCallFloatResult(dest);
8299
8300 PopRegsInMask(save);
8301 }
8302
8303 void MacroAssembler::convertInt32ToFloat16(Register src, FloatRegister dest,
8304 Register temp,
8305 LiveRegisterSet volatileLiveRegs) {
8306 if (MacroAssembler::SupportsFloat32To16()) {
8307 convertInt32ToFloat16(src, dest);
8308
8309 // Float16 is currently passed as Float32, so expand again to Float32.
8310 convertFloat16ToFloat32(dest, dest);
8311 return;
8312 }
8313
8314 LiveRegisterSet save = volatileLiveRegs;
8315 save.takeUnchecked(dest);
8316 save.takeUnchecked(dest.asDouble());
8317 save.takeUnchecked(temp);
8318
8319 PushRegsInMask(save);
8320
8321 using Fn = float (*)(int32_t);
8322 setupUnalignedABICall(temp);
8323 passABIArg(src);
8324 callWithABI<Fn, jit::RoundFloat16ToFloat32>(ABIType::Float32);
8325 storeCallFloatResult(dest);
8326
8327 PopRegsInMask(save);
8328 }
8329
8330 template <typename T>
8331 void MacroAssembler::loadFloat16(const T& src, FloatRegister dest,
8332 Register temp1, Register temp2,
8333 LiveRegisterSet volatileLiveRegs) {
8334 if (MacroAssembler::SupportsFloat32To16()) {
8335 loadFloat16(src, dest, temp1);
8336
8337 // Float16 is currently passed as Float32, so expand again to Float32.
8338 convertFloat16ToFloat32(dest, dest);
8339 return;
8340 }
8341
8342 load16ZeroExtend(src, temp1);
8343
8344 LiveRegisterSet save = volatileLiveRegs;
8345 save.takeUnchecked(dest);
8346 save.takeUnchecked(dest.asDouble());
8347 save.takeUnchecked(temp1);
8348 save.takeUnchecked(temp2);
8349
8350 PushRegsInMask(save);
8351
8352 using Fn = float (*)(int32_t);
8353 setupUnalignedABICall(temp2);
8354 passABIArg(temp1);
8355 callWithABI<Fn, jit::Float16ToFloat32>(ABIType::Float32);
8356 storeCallFloatResult(dest);
8357
8358 PopRegsInMask(save);
8359 }
8360
8361 template void MacroAssembler::loadFloat16(const Address& src,
8362 FloatRegister dest, Register temp1,
8363 Register temp2,
8364 LiveRegisterSet volatileLiveRegs);
8365
8366 template void MacroAssembler::loadFloat16(const BaseIndex& src,
8367 FloatRegister dest, Register temp1,
8368 Register temp2,
8369 LiveRegisterSet volatileLiveRegs);
8370
8371 template <typename T>
8372 void MacroAssembler::storeFloat16(FloatRegister src, const T& dest,
8373 Register temp,
8374 LiveRegisterSet volatileLiveRegs) {
8375 ScratchFloat32Scope fpscratch(*this);
8376
8377 if (src.isDouble()) {
8378 if (MacroAssembler::SupportsFloat64To16()) {
8379 convertDoubleToFloat16(src, fpscratch);
8380 storeFloat16(fpscratch, dest, temp);
8381 return;
8382 }
8383
8384 convertDoubleToFloat16(src, fpscratch, temp, volatileLiveRegs);
8385 src = fpscratch;
8386 }
8387 MOZ_ASSERT(src.isSingle());
8388
8389 if (MacroAssembler::SupportsFloat32To16()) {
8390 convertFloat32ToFloat16(src, fpscratch);
8391 storeFloat16(fpscratch, dest, temp);
8392 return;
8393 }
8394
8395 moveFloat16ToGPR(src, temp, volatileLiveRegs);
8396 store16(temp, dest);
8397 }
8398
8399 template void MacroAssembler::storeFloat16(FloatRegister src,
8400 const Address& dest, Register temp,
8401 LiveRegisterSet volatileLiveRegs);
8402
8403 template void MacroAssembler::storeFloat16(FloatRegister src,
8404 const BaseIndex& dest, Register temp,
8405 LiveRegisterSet volatileLiveRegs);
8406
8407 void MacroAssembler::moveFloat16ToGPR(FloatRegister src, Register dest,
8408 LiveRegisterSet volatileLiveRegs) {
8409 if (MacroAssembler::SupportsFloat32To16()) {
8410 ScratchFloat32Scope fpscratch(*this);
8411
8412 // Float16 is currently passed as Float32, so first narrow to Float16.
8413 convertFloat32ToFloat16(src, fpscratch);
8414
8415 moveFloat16ToGPR(fpscratch, dest);
8416 return;
8417 }
8418
8419 LiveRegisterSet save = volatileLiveRegs;
8420 save.takeUnchecked(dest);
8421
8422 PushRegsInMask(save);
8423
8424 using Fn = int32_t (*)(float);
8425 setupUnalignedABICall(dest);
8426 passABIArg(src, ABIType::Float32);
8427 callWithABI<Fn, jit::Float32ToFloat16>();
8428 storeCallInt32Result(dest);
8429
8430 PopRegsInMask(save);
8431 }
8432
8433 void MacroAssembler::moveGPRToFloat16(Register src, FloatRegister dest,
8434 Register temp,
8435 LiveRegisterSet volatileLiveRegs) {
8436 if (MacroAssembler::SupportsFloat32To16()) {
8437 moveGPRToFloat16(src, dest);
8438
8439 // Float16 is currently passed as Float32, so expand again to Float32.
8440 convertFloat16ToFloat32(dest, dest);
8441 return;
8442 }
8443
8444 LiveRegisterSet save = volatileLiveRegs;
8445 save.takeUnchecked(dest);
8446 save.takeUnchecked(dest.asDouble());
8447 save.takeUnchecked(temp);
8448
8449 PushRegsInMask(save);
8450
8451 using Fn = float (*)(int32_t);
8452 setupUnalignedABICall(temp);
8453 passABIArg(src);
8454 callWithABI<Fn, jit::Float16ToFloat32>(ABIType::Float32);
8455 storeCallFloatResult(dest);
8456
8457 PopRegsInMask(save);
8458 }
8459
8460 void MacroAssembler::debugAssertIsObject(const ValueOperand& val) {
8461 #ifdef DEBUG
8462 Label ok;
8463 branchTestObject(Assembler::Equal, val, &ok);
8464 assumeUnreachable("Expected an object!");
8465 bind(&ok);
8466 #endif
8467 }
8468
8469 void MacroAssembler::debugAssertObjHasFixedSlots(Register obj,
8470 Register scratch) {
8471 #ifdef DEBUG
8472 Label hasFixedSlots;
8473 loadPtr(Address(obj, JSObject::offsetOfShape()), scratch);
8474 branchTest32(Assembler::NonZero,
8475 Address(scratch, Shape::offsetOfImmutableFlags()),
8476 Imm32(NativeShape::fixedSlotsMask()), &hasFixedSlots);
8477 assumeUnreachable("Expected a fixed slot");
8478 bind(&hasFixedSlots);
8479 #endif
8480 }
8481
8482 void MacroAssembler::debugAssertObjectHasClass(Register obj, Register scratch,
8483 const JSClass* clasp) {
8484 #ifdef DEBUG
8485 Label done;
8486 branchTestObjClassNoSpectreMitigations(Assembler::Equal, obj, clasp, scratch,
8487 &done);
8488 assumeUnreachable("Class check failed");
8489 bind(&done);
8490 #endif
8491 }
8492
8493 void MacroAssembler::debugAssertGCThingIsTenured(Register ptr, Register temp) {
8494 #ifdef DEBUG
8495 Label done;
8496 branchPtrInNurseryChunk(Assembler::NotEqual, ptr, temp, &done);
8497 assumeUnreachable("Expected a tenured pointer");
8498 bind(&done);
8499 #endif
8500 }
8501
8502 void MacroAssembler::branchArrayIsNotPacked(Register array, Register temp1,
8503 Register temp2, Label* label) {
8504 loadPtr(Address(array, NativeObject::offsetOfElements()), temp1);
8505
8506 // Test length == initializedLength.
8507 Address initLength(temp1, ObjectElements::offsetOfInitializedLength());
8508 load32(Address(temp1, ObjectElements::offsetOfLength()), temp2);
8509 branch32(Assembler::NotEqual, initLength, temp2, label);
8510
8511 // Test the NON_PACKED flag.
8512 Address flags(temp1, ObjectElements::offsetOfFlags());
8513 branchTest32(Assembler::NonZero, flags, Imm32(ObjectElements::NON_PACKED),
8514 label);
8515 }
8516
8517 void MacroAssembler::setIsPackedArray(Register obj, Register output,
8518 Register temp) {
8519 // Ensure it's an ArrayObject.
8520 Label notPackedArray;
8521 branchTestObjClass(Assembler::NotEqual, obj, &ArrayObject::class_, temp, obj,
8522 &notPackedArray);
8523
8524 branchArrayIsNotPacked(obj, temp, output, &notPackedArray);
8525
8526 Label done;
8527 move32(Imm32(1), output);
8528 jump(&done);
8529
8530 bind(&notPackedArray);
8531 move32(Imm32(0), output);
8532
8533 bind(&done);
8534 }
8535
8536 void MacroAssembler::packedArrayPop(Register array, ValueOperand output,
8537 Register temp1, Register temp2,
8538 Label* fail) {
8539 // Load obj->elements in temp1.
8540 loadPtr(Address(array, NativeObject::offsetOfElements()), temp1);
8541
8542 // Check flags.
8543 static constexpr uint32_t UnhandledFlags =
8544 ObjectElements::Flags::NON_PACKED |
8545 ObjectElements::Flags::NONWRITABLE_ARRAY_LENGTH |
8546 ObjectElements::Flags::NOT_EXTENSIBLE |
8547 ObjectElements::Flags::MAYBE_IN_ITERATION;
8548 Address flags(temp1, ObjectElements::offsetOfFlags());
8549 branchTest32(Assembler::NonZero, flags, Imm32(UnhandledFlags), fail);
8550
8551 // Load length in temp2. Ensure length == initializedLength.
8552 Address lengthAddr(temp1, ObjectElements::offsetOfLength());
8553 Address initLengthAddr(temp1, ObjectElements::offsetOfInitializedLength());
8554 load32(lengthAddr, temp2);
8555 branch32(Assembler::NotEqual, initLengthAddr, temp2, fail);
8556
8557 // Result is |undefined| if length == 0.
8558 Label notEmpty, done;
8559 branchTest32(Assembler::NonZero, temp2, temp2, &notEmpty);
8560 {
8561 moveValue(UndefinedValue(), output);
8562 jump(&done);
8563 }
8564
8565 bind(&notEmpty);
8566
8567 // Load the last element.
8568 sub32(Imm32(1), temp2);
8569 BaseObjectElementIndex elementAddr(temp1, temp2);
8570 loadValue(elementAddr, output);
8571
8572 // Pre-barrier the element because we're removing it from the array.
8573 EmitPreBarrier(*this, elementAddr, MIRType::Value);
8574
8575 // Update length and initializedLength.
8576 store32(temp2, lengthAddr);
8577 store32(temp2, initLengthAddr);
8578
8579 bind(&done);
8580 }
8581
8582 void MacroAssembler::packedArrayShift(Register array, ValueOperand output,
8583 Register temp1, Register temp2,
8584 LiveRegisterSet volatileRegs,
8585 Label* fail) {
8586 // Load obj->elements in temp1.
8587 loadPtr(Address(array, NativeObject::offsetOfElements()), temp1);
8588
8589 // Check flags.
8590 static constexpr uint32_t UnhandledFlags =
8591 ObjectElements::Flags::NON_PACKED |
8592 ObjectElements::Flags::NONWRITABLE_ARRAY_LENGTH |
8593 ObjectElements::Flags::NOT_EXTENSIBLE |
8594 ObjectElements::Flags::MAYBE_IN_ITERATION;
8595 Address flags(temp1, ObjectElements::offsetOfFlags());
8596 branchTest32(Assembler::NonZero, flags, Imm32(UnhandledFlags), fail);
8597
8598 // Load length in temp2. Ensure length == initializedLength.
8599 Address lengthAddr(temp1, ObjectElements::offsetOfLength());
8600 Address initLengthAddr(temp1, ObjectElements::offsetOfInitializedLength());
8601 load32(lengthAddr, temp2);
8602 branch32(Assembler::NotEqual, initLengthAddr, temp2, fail);
8603
8604 // Result is |undefined| if length == 0.
8605 Label notEmpty, done;
8606 branchTest32(Assembler::NonZero, temp2, temp2, &notEmpty);
8607 {
8608 moveValue(UndefinedValue(), output);
8609 jump(&done);
8610 }
8611
8612 bind(&notEmpty);
8613
8614 // Load the first element.
8615 Address elementAddr(temp1, 0);
8616 loadValue(elementAddr, output);
8617
8618 // Move the other elements and update the initializedLength/length. This will
8619 // also trigger pre-barriers.
8620 {
8621 // Ensure output is in volatileRegs. Don't preserve temp1 and temp2.
8622 volatileRegs.takeUnchecked(temp1);
8623 volatileRegs.takeUnchecked(temp2);
8624 if (output.hasVolatileReg()) {
8625 volatileRegs.addUnchecked(output);
8626 }
8627
8628 PushRegsInMask(volatileRegs);
8629
8630 using Fn = void (*)(ArrayObject* arr);
8631 setupUnalignedABICall(temp1);
8632 passABIArg(array);
8633 callWithABI<Fn, ArrayShiftMoveElements>();
8634
8635 PopRegsInMask(volatileRegs);
8636 }
8637
8638 bind(&done);
8639 }
8640
8641 void MacroAssembler::loadArgumentsObjectElement(Register obj, Register index,
8642 ValueOperand output,
8643 Register temp, Label* fail) {
8644 Register temp2 = output.scratchReg();
8645
8646 // Get initial length value.
8647 unboxInt32(Address(obj, ArgumentsObject::getInitialLengthSlotOffset()), temp);
8648
8649 // Ensure no overridden elements.
8650 branchTest32(Assembler::NonZero, temp,
8651 Imm32(ArgumentsObject::ELEMENT_OVERRIDDEN_BIT), fail);
8652
8653 // Bounds check.
8654 rshift32(Imm32(ArgumentsObject::PACKED_BITS_COUNT), temp);
8655 spectreBoundsCheck32(index, temp, temp2, fail);
8656
8657 // Load ArgumentsData.
8658 loadPrivate(Address(obj, ArgumentsObject::getDataSlotOffset()), temp);
8659
8660 // Guard the argument is not a FORWARD_TO_CALL_SLOT MagicValue.
8661 BaseValueIndex argValue(temp, index, ArgumentsData::offsetOfArgs());
8662 branchTestMagic(Assembler::Equal, argValue, fail);
8663 loadValue(argValue, output);
8664 }
8665
8666 void MacroAssembler::loadArgumentsObjectElementHole(Register obj,
8667 Register index,
8668 ValueOperand output,
8669 Register temp,
8670 Label* fail) {
8671 Register temp2 = output.scratchReg();
8672
8673 // Get initial length value.
8674 unboxInt32(Address(obj, ArgumentsObject::getInitialLengthSlotOffset()), temp);
8675
8676 // Ensure no overridden elements.
8677 branchTest32(Assembler::NonZero, temp,
8678 Imm32(ArgumentsObject::ELEMENT_OVERRIDDEN_BIT), fail);
8679
8680 // Bounds check.
8681 Label outOfBounds, done;
8682 rshift32(Imm32(ArgumentsObject::PACKED_BITS_COUNT), temp);
8683 spectreBoundsCheck32(index, temp, temp2, &outOfBounds);
8684
8685 // Load ArgumentsData.
8686 loadPrivate(Address(obj, ArgumentsObject::getDataSlotOffset()), temp);
8687
8688 // Guard the argument is not a FORWARD_TO_CALL_SLOT MagicValue.
8689 BaseValueIndex argValue(temp, index, ArgumentsData::offsetOfArgs());
8690 branchTestMagic(Assembler::Equal, argValue, fail);
8691 loadValue(argValue, output);
8692 jump(&done);
8693
8694 bind(&outOfBounds);
8695 branch32(Assembler::LessThan, index, Imm32(0), fail);
8696 moveValue(UndefinedValue(), output);
8697
8698 bind(&done);
8699 }
8700
8701 void MacroAssembler::loadArgumentsObjectElementExists(
8702 Register obj, Register index, Register output, Register temp, Label* fail) {
8703 // Ensure the index is non-negative.
8704 branch32(Assembler::LessThan, index, Imm32(0), fail);
8705
8706 // Get initial length value.
8707 unboxInt32(Address(obj, ArgumentsObject::getInitialLengthSlotOffset()), temp);
8708
8709 // Ensure no overridden or deleted elements.
8710 branchTest32(Assembler::NonZero, temp,
8711 Imm32(ArgumentsObject::ELEMENT_OVERRIDDEN_BIT), fail);
8712
8713 // Compare index against the length.
8714 rshift32(Imm32(ArgumentsObject::PACKED_BITS_COUNT), temp);
8715 cmp32Set(Assembler::LessThan, index, temp, output);
8716 }
8717
8718 void MacroAssembler::loadArgumentsObjectLength(Register obj, Register output,
8719 Label* fail) {
8720 // Get initial length value.
8721 unboxInt32(Address(obj, ArgumentsObject::getInitialLengthSlotOffset()),
8722 output);
8723
8724 // Test if length has been overridden.
8725 branchTest32(Assembler::NonZero, output,
8726 Imm32(ArgumentsObject::LENGTH_OVERRIDDEN_BIT), fail);
8727
8728 // Shift out arguments length and return it.
8729 rshift32(Imm32(ArgumentsObject::PACKED_BITS_COUNT), output);
8730 }
8731
8732 void MacroAssembler::loadArgumentsObjectLength(Register obj, Register output) {
8733 // Get initial length value.
8734 unboxInt32(Address(obj, ArgumentsObject::getInitialLengthSlotOffset()),
8735 output);
8736
8737 #ifdef DEBUG
8738 // Assert length hasn't been overridden.
8739 Label ok;
8740 branchTest32(Assembler::Zero, output,
8741 Imm32(ArgumentsObject::LENGTH_OVERRIDDEN_BIT), &ok);
8742 assumeUnreachable("arguments object length has been overridden");
8743 bind(&ok);
8744 #endif
8745
8746 // Shift out arguments length and return it.
8747 rshift32(Imm32(ArgumentsObject::PACKED_BITS_COUNT), output);
8748 }
8749
8750 void MacroAssembler::branchTestArgumentsObjectFlags(Register obj, Register temp,
8751 uint32_t flags,
8752 Condition cond,
8753 Label* label) {
8754 MOZ_ASSERT((flags & ~ArgumentsObject::PACKED_BITS_MASK) == 0);
8755
8756 // Get initial length value.
8757 unboxInt32(Address(obj, ArgumentsObject::getInitialLengthSlotOffset()), temp);
8758
8759 // Test flags.
8760 branchTest32(cond, temp, Imm32(flags), label);
8761 }
8762
8763 static constexpr bool ValidateSizeRange(Scalar::Type from, Scalar::Type to) {
8764 for (Scalar::Type type = from; type < to; type = Scalar::Type(type + 1)) {
8765 if (TypedArrayElemSize(type) != TypedArrayElemSize(from)) {
8766 return false;
8767 }
8768 }
8769 return true;
8770 }
8771
8772 void MacroAssembler::typedArrayElementSize(Register obj, Register output) {
8773 loadObjClassUnsafe(obj, output);
8774
8775 // Map resizable to fixed-length TypedArray classes.
8776 Label fixedLength;
8777 branchPtr(Assembler::Below, output,
8778 ImmPtr(std::end(TypedArrayObject::fixedLengthClasses)),
8779 &fixedLength);
8780 {
8781 MOZ_ASSERT(std::end(TypedArrayObject::fixedLengthClasses) ==
8782 std::begin(TypedArrayObject::resizableClasses),
8783 "TypedArray classes are in contiguous memory");
8784
8785 const auto* firstFixedLengthTypedArrayClass =
8786 std::begin(TypedArrayObject::fixedLengthClasses);
8787 const auto* firstResizableTypedArrayClass =
8788 std::begin(TypedArrayObject::resizableClasses);
8789
8790 MOZ_ASSERT(firstFixedLengthTypedArrayClass < firstResizableTypedArrayClass);
8791
8792 ptrdiff_t diff =
8793 firstResizableTypedArrayClass - firstFixedLengthTypedArrayClass;
8794
8795 mozilla::CheckedInt<int32_t> checked = diff;
8796 checked *= sizeof(JSClass);
8797 MOZ_ASSERT(checked.isValid(), "pointer difference fits in int32");
8798
8799 subPtr(Imm32(int32_t(checked.value())), output);
8800 }
8801 bind(&fixedLength);
8802
8803 #ifdef DEBUG
8804 Label invalidClass, validClass;
8805 branchPtr(Assembler::Below, output,
8806 ImmPtr(std::begin(TypedArrayObject::fixedLengthClasses)),
8807 &invalidClass);
8808 branchPtr(Assembler::Below, output,
8809 ImmPtr(std::end(TypedArrayObject::fixedLengthClasses)),
8810 &validClass);
8811 bind(&invalidClass);
8812 assumeUnreachable("value isn't a valid FixedLengthTypedArray class");
8813 bind(&validClass);
8814 #endif
8815
8816 auto classForType = [](Scalar::Type type) {
8817 MOZ_ASSERT(type < Scalar::MaxTypedArrayViewType);
8818 return &TypedArrayObject::fixedLengthClasses[type];
8819 };
8820
8821 Label one, two, four, eight, done;
8822
8823 static_assert(ValidateSizeRange(Scalar::Int8, Scalar::Int16),
8824 "element size is one in [Int8, Int16)");
8825 branchPtr(Assembler::Below, output, ImmPtr(classForType(Scalar::Int16)),
8826 &one);
8827
8828 static_assert(ValidateSizeRange(Scalar::Int16, Scalar::Int32),
8829 "element size is two in [Int16, Int32)");
8830 branchPtr(Assembler::Below, output, ImmPtr(classForType(Scalar::Int32)),
8831 &two);
8832
8833 static_assert(ValidateSizeRange(Scalar::Int32, Scalar::Float64),
8834 "element size is four in [Int32, Float64)");
8835 branchPtr(Assembler::Below, output, ImmPtr(classForType(Scalar::Float64)),
8836 &four);
8837
8838 static_assert(ValidateSizeRange(Scalar::Float64, Scalar::Uint8Clamped),
8839 "element size is eight in [Float64, Uint8Clamped)");
8840 branchPtr(Assembler::Below, output,
8841 ImmPtr(classForType(Scalar::Uint8Clamped)), &eight);
8842
8843 static_assert(ValidateSizeRange(Scalar::Uint8Clamped, Scalar::BigInt64),
8844 "element size is one in [Uint8Clamped, BigInt64)");
8845 branchPtr(Assembler::Below, output, ImmPtr(classForType(Scalar::BigInt64)),
8846 &one);
8847
8848 static_assert(ValidateSizeRange(Scalar::BigInt64, Scalar::Float16),
8849 "element size is eight in [BigInt64, Float16)");
8850 branchPtr(Assembler::Below, output, ImmPtr(classForType(Scalar::Float16)),
8851 &eight);
8852
8853 static_assert(
8854 ValidateSizeRange(Scalar::Float16, Scalar::MaxTypedArrayViewType),
8855 "element size is two in [Float16, MaxTypedArrayViewType)");
8856 jump(&two);
8857
8858 bind(&eight);
8859 move32(Imm32(8), output);
8860 jump(&done);
8861
8862 bind(&four);
8863 move32(Imm32(4), output);
8864 jump(&done);
8865
8866 bind(&two);
8867 move32(Imm32(2), output);
8868 jump(&done);
8869
8870 bind(&one);
8871 move32(Imm32(1), output);
8872
8873 bind(&done);
8874 }
8875
8876 void MacroAssembler::resizableTypedArrayElementShiftBy(Register obj,
8877 Register output,
8878 Register scratch) {
8879 loadObjClassUnsafe(obj, scratch);
8880
8881 #ifdef DEBUG
8882 Label invalidClass, validClass;
8883 branchPtr(Assembler::Below, scratch,
8884 ImmPtr(std::begin(TypedArrayObject::resizableClasses)),
8885 &invalidClass);
8886 branchPtr(Assembler::Below, scratch,
8887 ImmPtr(std::end(TypedArrayObject::resizableClasses)), &validClass);
8888 bind(&invalidClass);
8889 assumeUnreachable("value isn't a valid ResizableLengthTypedArray class");
8890 bind(&validClass);
8891 #endif
8892
8893 auto classForType = [](Scalar::Type type) {
8894 MOZ_ASSERT(type < Scalar::MaxTypedArrayViewType);
8895 return &TypedArrayObject::resizableClasses[type];
8896 };
8897
8898 Label zero, one, two, three;
8899
8900 static_assert(ValidateSizeRange(Scalar::Int8, Scalar::Int16),
8901 "element shift is zero in [Int8, Int16)");
8902 branchPtr(Assembler::Below, scratch, ImmPtr(classForType(Scalar::Int16)),
8903 &zero);
8904
8905 static_assert(ValidateSizeRange(Scalar::Int16, Scalar::Int32),
8906 "element shift is one in [Int16, Int32)");
8907 branchPtr(Assembler::Below, scratch, ImmPtr(classForType(Scalar::Int32)),
8908 &one);
8909
8910 static_assert(ValidateSizeRange(Scalar::Int32, Scalar::Float64),
8911 "element shift is two in [Int32, Float64)");
8912 branchPtr(Assembler::Below, scratch, ImmPtr(classForType(Scalar::Float64)),
8913 &two);
8914
8915 static_assert(ValidateSizeRange(Scalar::Float64, Scalar::Uint8Clamped),
8916 "element shift is three in [Float64, Uint8Clamped)");
8917 branchPtr(Assembler::Below, scratch,
8918 ImmPtr(classForType(Scalar::Uint8Clamped)), &three);
8919
8920 static_assert(ValidateSizeRange(Scalar::Uint8Clamped, Scalar::BigInt64),
8921 "element shift is zero in [Uint8Clamped, BigInt64)");
8922 branchPtr(Assembler::Below, scratch, ImmPtr(classForType(Scalar::BigInt64)),
8923 &zero);
8924
8925 static_assert(ValidateSizeRange(Scalar::BigInt64, Scalar::Float16),
8926 "element shift is three in [BigInt64, Float16)");
8927 branchPtr(Assembler::Below, scratch, ImmPtr(classForType(Scalar::Float16)),
8928 &three);
8929
8930 static_assert(
8931 ValidateSizeRange(Scalar::Float16, Scalar::MaxTypedArrayViewType),
8932 "element shift is one in [Float16, MaxTypedArrayViewType)");
8933 jump(&one);
8934
8935 bind(&three);
8936 rshiftPtr(Imm32(3), output);
8937 jump(&zero);
8938
8939 bind(&two);
8940 rshiftPtr(Imm32(2), output);
8941 jump(&zero);
8942
8943 bind(&one);
8944 rshiftPtr(Imm32(1), output);
8945
8946 bind(&zero);
8947 }
8948
8949 void MacroAssembler::branchIfClassIsNotTypedArray(Register clasp,
8950 Label* notTypedArray) {
8951 // Inline implementation of IsTypedArrayClass().
8952
8953 const auto* firstTypedArrayClass =
8954 std::begin(TypedArrayObject::fixedLengthClasses);
8955 const auto* lastTypedArrayClass =
8956 std::prev(std::end(TypedArrayObject::resizableClasses));
8957 MOZ_ASSERT(std::end(TypedArrayObject::fixedLengthClasses) ==
8958 std::begin(TypedArrayObject::resizableClasses),
8959 "TypedArray classes are in contiguous memory");
8960
8961 branchPtr(Assembler::Below, clasp, ImmPtr(firstTypedArrayClass),
8962 notTypedArray);
8963 branchPtr(Assembler::Above, clasp, ImmPtr(lastTypedArrayClass),
8964 notTypedArray);
8965 }
8966
8967 void MacroAssembler::branchIfClassIsNotFixedLengthTypedArray(
8968 Register clasp, Label* notTypedArray) {
8969 // Inline implementation of IsFixedLengthTypedArrayClass().
8970
8971 const auto* firstTypedArrayClass =
8972 std::begin(TypedArrayObject::fixedLengthClasses);
8973 const auto* lastTypedArrayClass =
8974 std::prev(std::end(TypedArrayObject::fixedLengthClasses));
8975
8976 branchPtr(Assembler::Below, clasp, ImmPtr(firstTypedArrayClass),
8977 notTypedArray);
8978 branchPtr(Assembler::Above, clasp, ImmPtr(lastTypedArrayClass),
8979 notTypedArray);
8980 }
8981
8982 void MacroAssembler::branchIfClassIsNotResizableTypedArray(
8983 Register clasp, Label* notTypedArray) {
8984 // Inline implementation of IsResizableTypedArrayClass().
8985
8986 const auto* firstTypedArrayClass =
8987 std::begin(TypedArrayObject::resizableClasses);
8988 const auto* lastTypedArrayClass =
8989 std::prev(std::end(TypedArrayObject::resizableClasses));
8990
8991 branchPtr(Assembler::Below, clasp, ImmPtr(firstTypedArrayClass),
8992 notTypedArray);
8993 branchPtr(Assembler::Above, clasp, ImmPtr(lastTypedArrayClass),
8994 notTypedArray);
8995 }
8996
8997 void MacroAssembler::branchIfHasDetachedArrayBuffer(BranchIfDetached branchIf,
8998 Register obj, Register temp,
8999 Label* label) {
9000 // Inline implementation of ArrayBufferViewObject::hasDetachedBuffer().
9001
9002 // TODO: The data-slot of detached views is set to undefined, which would be
9003 // a faster way to detect detached buffers.
9004
9005 // auto cond = branchIf == BranchIfDetached::Yes ? Assembler::Equal
9006 // : Assembler::NotEqual;
9007 // branchTestUndefined(cond, Address(obj,
9008 // ArrayBufferViewObject::dataOffset()), label);
9009
9010 Label done;
9011 Label* ifNotDetached = branchIf == BranchIfDetached::Yes ? &done : label;
9012 Condition detachedCond =
9013 branchIf == BranchIfDetached::Yes ? Assembler::NonZero : Assembler::Zero;
9014
9015 // Load obj->elements in temp.
9016 loadPtr(Address(obj, NativeObject::offsetOfElements()), temp);
9017
9018 // Shared buffers can't be detached.
9019 branchTest32(Assembler::NonZero,
9020 Address(temp, ObjectElements::offsetOfFlags()),
9021 Imm32(ObjectElements::SHARED_MEMORY), ifNotDetached);
9022
9023 // An ArrayBufferView with a null/true buffer has never had its buffer
9024 // exposed, so nothing can possibly detach it.
9025 fallibleUnboxObject(Address(obj, ArrayBufferViewObject::bufferOffset()), temp,
9026 ifNotDetached);
9027
9028 // Load the ArrayBuffer flags and branch if the detached flag is (not) set.
9029 unboxInt32(Address(temp, ArrayBufferObject::offsetOfFlagsSlot()), temp);
9030 branchTest32(detachedCond, temp, Imm32(ArrayBufferObject::DETACHED), label);
9031
9032 if (branchIf == BranchIfDetached::Yes) {
9033 bind(&done);
9034 }
9035 }
9036
9037 void MacroAssembler::branchIfResizableArrayBufferViewOutOfBounds(Register obj,
9038 Register temp,
9039 Label* label) {
9040 // Implementation of ArrayBufferViewObject::isOutOfBounds().
9041
9042 Label done;
9043
9044 loadArrayBufferViewLengthIntPtr(obj, temp);
9045 branchPtr(Assembler::NotEqual, temp, ImmWord(0), &done);
9046
9047 loadArrayBufferViewByteOffsetIntPtr(obj, temp);
9048 branchPtr(Assembler::NotEqual, temp, ImmWord(0), &done);
9049
9050 loadPrivate(Address(obj, ArrayBufferViewObject::initialLengthOffset()), temp);
9051 branchPtr(Assembler::NotEqual, temp, ImmWord(0), label);
9052
9053 loadPrivate(Address(obj, ArrayBufferViewObject::initialByteOffsetOffset()),
9054 temp);
9055 branchPtr(Assembler::NotEqual, temp, ImmWord(0), label);
9056
9057 bind(&done);
9058 }
9059
9060 void MacroAssembler::branchIfResizableArrayBufferViewInBounds(Register obj,
9061 Register temp,
9062 Label* label) {
9063 // Implementation of ArrayBufferViewObject::isOutOfBounds().
9064
9065 Label done;
9066
9067 loadArrayBufferViewLengthIntPtr(obj, temp);
9068 branchPtr(Assembler::NotEqual, temp, ImmWord(0), label);
9069
9070 loadArrayBufferViewByteOffsetIntPtr(obj, temp);
9071 branchPtr(Assembler::NotEqual, temp, ImmWord(0), label);
9072
9073 loadPrivate(Address(obj, ArrayBufferViewObject::initialLengthOffset()), temp);
9074 branchPtr(Assembler::NotEqual, temp, ImmWord(0), &done);
9075
9076 loadPrivate(Address(obj, ArrayBufferViewObject::initialByteOffsetOffset()),
9077 temp);
9078 branchPtr(Assembler::Equal, temp, ImmWord(0), label);
9079
9080 bind(&done);
9081 }
9082
9083 void MacroAssembler::branchIfNativeIteratorNotReusable(Register ni,
9084 Label* notReusable) {
9085 // See NativeIterator::isReusable.
9086 Address flagsAddr(ni, NativeIterator::offsetOfFlagsAndCount());
9087
9088 #ifdef DEBUG
9089 Label niIsInitialized;
9090 branchTest32(Assembler::NonZero, flagsAddr,
9091 Imm32(NativeIterator::Flags::Initialized), &niIsInitialized);
9092 assumeUnreachable(
9093 "Expected a NativeIterator that's been completely "
9094 "initialized");
9095 bind(&niIsInitialized);
9096 #endif
9097
9098 branchTest32(Assembler::NonZero, flagsAddr,
9099 Imm32(NativeIterator::Flags::NotReusable), notReusable);
9100 }
9101
9102 void MacroAssembler::branchNativeIteratorIndices(Condition cond, Register ni,
9103 Register temp,
9104 NativeIteratorIndices kind,
9105 Label* label) {
9106 Address iterFlagsAddr(ni, NativeIterator::offsetOfFlagsAndCount());
9107 load32(iterFlagsAddr, temp);
9108 and32(Imm32(NativeIterator::IndicesMask), temp);
9109 uint32_t shiftedKind = uint32_t(kind) << NativeIterator::IndicesShift;
9110 branch32(cond, temp, Imm32(shiftedKind), label);
9111 }
9112
9113 static void LoadNativeIterator(MacroAssembler& masm, Register obj,
9114 Register dest) {
9115 MOZ_ASSERT(obj != dest);
9116
9117 #ifdef DEBUG
9118 // Assert we have a PropertyIteratorObject.
9119 Label ok;
9120 masm.branchTestObjClass(Assembler::Equal, obj,
9121 &PropertyIteratorObject::class_, dest, obj, &ok);
9122 masm.assumeUnreachable("Expected PropertyIteratorObject!");
9123 masm.bind(&ok);
9124 #endif
9125
9126 // Load NativeIterator object.
9127 Address slotAddr(obj, PropertyIteratorObject::offsetOfIteratorSlot());
9128 masm.loadPrivate(slotAddr, dest);
9129 }
9130
9131 // The ShapeCachePtr may be used to cache an iterator for for-in. Return that
9132 // iterator in |dest| if:
9133 // - the shape cache pointer exists and stores a native iterator
9134 // - the iterator is reusable
9135 // - the iterated object has no dense elements
9136 // - the shapes of each object on the proto chain of |obj| match the cached
9137 // shapes
9138 // - the proto chain has no dense elements
9139 // Otherwise, jump to |failure|.
9140 void MacroAssembler::maybeLoadIteratorFromShape(Register obj, Register dest,
9141 Register temp, Register temp2,
9142 Register temp3,
9143 Label* failure) {
9144 // Register usage:
9145 // obj: always contains the input object
9146 // temp: walks the obj->shape->baseshape->proto->shape->... chain
9147 // temp2: points to the native iterator. Incremented to walk the shapes array.
9148 // temp3: scratch space
9149 // dest: stores the resulting PropertyIteratorObject on success
9150
9151 Label success;
9152 Register shapeAndProto = temp;
9153 Register nativeIterator = temp2;
9154
9155 // Load ShapeCache from shape.
9156 loadPtr(Address(obj, JSObject::offsetOfShape()), shapeAndProto);
9157 loadPtr(Address(shapeAndProto, Shape::offsetOfCachePtr()), dest);
9158
9159 // Check if it's an iterator.
9160 andPtr(Imm32(ShapeCachePtr::MASK), dest, temp3);
9161 branch32(Assembler::NotEqual, temp3, Imm32(ShapeCachePtr::ITERATOR), failure);
9162
9163 // If we've cached an iterator, |obj| must be a native object.
9164 #ifdef DEBUG
9165 Label nonNative;
9166 branchIfNonNativeObj(obj, temp3, &nonNative);
9167 #endif
9168
9169 // Verify that |obj| has no dense elements.
9170 loadPtr(Address(obj, NativeObject::offsetOfElements()), temp3);
9171 branch32(Assembler::NotEqual,
9172 Address(temp3, ObjectElements::offsetOfInitializedLength()),
9173 Imm32(0), failure);
9174
9175 // Clear tag bits from iterator object. |dest| is now valid.
9176 // Load the native iterator and verify that it's reusable.
9177 andPtr(Imm32(~ShapeCachePtr::MASK), dest);
9178 LoadNativeIterator(*this, dest, nativeIterator);
9179 branchIfNativeIteratorNotReusable(nativeIterator, failure);
9180
9181 // We have to compare the shapes in the native iterator with the shapes on the
9182 // proto chain to ensure the cached iterator is still valid. The shape array
9183 // always starts at a fixed offset from the base of the NativeIterator, so
9184 // instead of using an instruction outside the loop to initialize a pointer to
9185 // the shapes array, we can bake it into the offset and reuse the pointer to
9186 // the NativeIterator. We add |sizeof(Shape*)| to start at the second shape.
9187 // (The first shape corresponds to the object itself. We don't have to check
9188 // it, because we got the iterator via the shape.)
9189 size_t nativeIteratorProtoShapeOffset =
9190 NativeIterator::offsetOfFirstShape() + sizeof(Shape*);
9191
9192 // Loop over the proto chain. At the head of the loop, |shape| is the shape of
9193 // the current object, and |iteratorShapes| points to the expected shape of
9194 // its proto.
9195 Label protoLoop;
9196 bind(&protoLoop);
9197
9198 // Load the proto. If the proto is null, then we're done.
9199 loadPtr(Address(shapeAndProto, Shape::offsetOfBaseShape()), shapeAndProto);
9200 loadPtr(Address(shapeAndProto, BaseShape::offsetOfProto()), shapeAndProto);
9201 branchPtr(Assembler::Equal, shapeAndProto, ImmPtr(nullptr), &success);
9202
9203 #ifdef DEBUG
9204 // We have guarded every shape up until this point, so we know that the proto
9205 // is a native object.
9206 branchIfNonNativeObj(shapeAndProto, temp3, &nonNative);
9207 #endif
9208
9209 // Verify that the proto has no dense elements.
9210 loadPtr(Address(shapeAndProto, NativeObject::offsetOfElements()), temp3);
9211 branch32(Assembler::NotEqual,
9212 Address(temp3, ObjectElements::offsetOfInitializedLength()),
9213 Imm32(0), failure);
9214
9215 // Compare the shape of the proto to the expected shape.
9216 loadPtr(Address(shapeAndProto, JSObject::offsetOfShape()), shapeAndProto);
9217 loadPtr(Address(nativeIterator, nativeIteratorProtoShapeOffset), temp3);
9218 branchPtr(Assembler::NotEqual, shapeAndProto, temp3, failure);
9219
9220 // Increment |iteratorShapes| and jump back to the top of the loop.
9221 addPtr(Imm32(sizeof(Shape*)), nativeIterator);
9222 jump(&protoLoop);
9223
9224 #ifdef DEBUG
9225 bind(&nonNative);
9226 assumeUnreachable("Expected NativeObject in maybeLoadIteratorFromShape");
9227 #endif
9228
9229 bind(&success);
9230 }
9231
9232 void MacroAssembler::iteratorMore(Register obj, ValueOperand output,
9233 Register temp) {
9234 Label done;
9235 Register outputScratch = output.scratchReg();
9236 LoadNativeIterator(*this, obj, outputScratch);
9237
9238 // If propertyCursor_ < propertiesEnd_, load the next string and advance
9239 // the cursor. Otherwise return MagicValue(JS_NO_ITER_VALUE).
9240 Label iterDone;
9241 Address cursorAddr(outputScratch, NativeIterator::offsetOfPropertyCursor());
9242 Address cursorEndAddr(outputScratch, NativeIterator::offsetOfPropertiesEnd());
9243 loadPtr(cursorAddr, temp);
9244 branchPtr(Assembler::BelowOrEqual, cursorEndAddr, temp, &iterDone);
9245
9246 // Get next string.
9247 loadPtr(Address(temp, 0), temp);
9248
9249 // Increase the cursor.
9250 addPtr(Imm32(sizeof(GCPtr<JSLinearString*>)), cursorAddr);
9251
9252 tagValue(JSVAL_TYPE_STRING, temp, output);
9253 jump(&done);
9254
9255 bind(&iterDone);
9256 moveValue(MagicValue(JS_NO_ITER_VALUE), output);
9257
9258 bind(&done);
9259 }
9260
9261 void MacroAssembler::iteratorClose(Register obj, Register temp1, Register temp2,
9262 Register temp3) {
9263 LoadNativeIterator(*this, obj, temp1);
9264
9265 // The shared iterator used for for-in with null/undefined is immutable and
9266 // unlinked. See NativeIterator::isEmptyIteratorSingleton.
9267 Label done;
9268 branchTest32(Assembler::NonZero,
9269 Address(temp1, NativeIterator::offsetOfFlagsAndCount()),
9270 Imm32(NativeIterator::Flags::IsEmptyIteratorSingleton), &done);
9271
9272 // Clear active bit.
9273 and32(Imm32(~NativeIterator::Flags::Active),
9274 Address(temp1, NativeIterator::offsetOfFlagsAndCount()));
9275
9276 // Clear objectBeingIterated.
9277 Address iterObjAddr(temp1, NativeIterator::offsetOfObjectBeingIterated());
9278 guardedCallPreBarrierAnyZone(iterObjAddr, MIRType::Object, temp2);
9279 storePtr(ImmPtr(nullptr), iterObjAddr);
9280
9281 // Reset property cursor.
9282 loadPtr(Address(temp1, NativeIterator::offsetOfShapesEnd()), temp2);
9283 storePtr(temp2, Address(temp1, NativeIterator::offsetOfPropertyCursor()));
9284
9285 // Unlink from the iterator list.
9286 const Register next = temp2;
9287 const Register prev = temp3;
9288 loadPtr(Address(temp1, NativeIterator::offsetOfNext()), next);
9289 loadPtr(Address(temp1, NativeIterator::offsetOfPrev()), prev);
9290 storePtr(prev, Address(next, NativeIterator::offsetOfPrev()));
9291 storePtr(next, Address(prev, NativeIterator::offsetOfNext()));
9292 #ifdef DEBUG
9293 storePtr(ImmPtr(nullptr), Address(temp1, NativeIterator::offsetOfNext()));
9294 storePtr(ImmPtr(nullptr), Address(temp1, NativeIterator::offsetOfPrev()));
9295 #endif
9296
9297 bind(&done);
9298 }
9299
9300 void MacroAssembler::registerIterator(Register enumeratorsList, Register iter,
9301 Register temp) {
9302 // iter->next = list
9303 storePtr(enumeratorsList, Address(iter, NativeIterator::offsetOfNext()));
9304
9305 // iter->prev = list->prev
9306 loadPtr(Address(enumeratorsList, NativeIterator::offsetOfPrev()), temp);
9307 storePtr(temp, Address(iter, NativeIterator::offsetOfPrev()));
9308
9309 // list->prev->next = iter
9310 storePtr(iter, Address(temp, NativeIterator::offsetOfNext()));
9311
9312 // list->prev = iter
9313 storePtr(iter, Address(enumeratorsList, NativeIterator::offsetOfPrev()));
9314 }
9315
9316 void MacroAssembler::prepareOOBStoreElement(Register object, Register index,
9317 Register elements,
9318 Register maybeTemp, Label* failure,
9319 LiveRegisterSet volatileLiveRegs) {
9320 Address length(elements, ObjectElements::offsetOfLength());
9321 Address initLength(elements, ObjectElements::offsetOfInitializedLength());
9322 Address capacity(elements, ObjectElements::offsetOfCapacity());
9323 Address flags(elements, ObjectElements::offsetOfFlags());
9324
9325 // If index < capacity, we can add a dense element inline. If not, we
9326 // need to allocate more elements.
9327 Label allocElement, enoughCapacity;
9328 spectreBoundsCheck32(index, capacity, maybeTemp, &allocElement);
9329 jump(&enoughCapacity);
9330
9331 bind(&allocElement);
9332
9333 // We currently only support storing one past the current capacity.
9334 // We could add support for stores beyond that point by calling a different
9335 // function, but then we'd have to think carefully about when to go sparse.
9336 branch32(Assembler::NotEqual, capacity, index, failure);
9337
9338 volatileLiveRegs.takeUnchecked(elements);
9339 if (maybeTemp != InvalidReg) {
9340 volatileLiveRegs.takeUnchecked(maybeTemp);
9341 }
9342 PushRegsInMask(volatileLiveRegs);
9343
9344 // Use `elements` as a scratch register because we're about to reallocate it.
9345 using Fn = bool (*)(JSContext* cx, NativeObject* obj);
9346 setupUnalignedABICall(elements);
9347 loadJSContext(elements);
9348 passABIArg(elements);
9349 passABIArg(object);
9350 callWithABI<Fn, NativeObject::addDenseElementPure>();
9351 storeCallPointerResult(elements);
9352
9353 PopRegsInMask(volatileLiveRegs);
9354 branchIfFalseBool(elements, failure);
9355
9356 // Load the reallocated elements pointer.
9357 loadPtr(Address(object, NativeObject::offsetOfElements()), elements);
9358
9359 bind(&enoughCapacity);
9360
9361 // If our caller couldn't give us a temp register, use `object`.
9362 Register temp;
9363 if (maybeTemp == InvalidReg) {
9364 push(object);
9365 temp = object;
9366 } else {
9367 temp = maybeTemp;
9368 }
9369
9370 // Load the index of the first uninitialized element into `temp`.
9371 load32(initLength, temp);
9372
9373 // If it is not `index`, mark this elements array as non-packed.
9374 Label noHoles, loop, done;
9375 branch32(Assembler::Equal, temp, index, &noHoles);
9376 or32(Imm32(ObjectElements::NON_PACKED), flags);
9377
9378 // Loop over intermediate elements and fill them with the magic hole value.
9379 bind(&loop);
9380 storeValue(MagicValue(JS_ELEMENTS_HOLE), BaseValueIndex(elements, temp));
9381 add32(Imm32(1), temp);
9382 branch32(Assembler::NotEqual, temp, index, &loop);
9383
9384 bind(&noHoles);
9385
9386 // The new initLength is index + 1. Update it.
9387 add32(Imm32(1), temp);
9388 store32(temp, initLength);
9389
9390 // If necessary, update length as well.
9391 branch32(Assembler::Above, length, temp, &done);
9392 store32(temp, length);
9393 bind(&done);
9394
9395 if (maybeTemp == InvalidReg) {
9396 pop(object);
9397 }
9398 }
9399
9400 void MacroAssembler::toHashableNonGCThing(ValueOperand value,
9401 ValueOperand result,
9402 FloatRegister tempFloat) {
9403 // Inline implementation of |HashableValue::setValue()|.
9404
9405 #ifdef DEBUG
9406 Label ok;
9407 branchTestGCThing(Assembler::NotEqual, value, &ok);
9408 assumeUnreachable("Unexpected GC thing");
9409 bind(&ok);
9410 #endif
9411
9412 Label useInput, done;
9413 branchTestDouble(Assembler::NotEqual, value, &useInput);
9414 {
9415 Register int32 = result.scratchReg();
9416 unboxDouble(value, tempFloat);
9417
9418 // Normalize int32-valued doubles to int32 and negative zero to +0.
9419 Label canonicalize;
9420 convertDoubleToInt32(tempFloat, int32, &canonicalize, false);
9421 {
9422 tagValue(JSVAL_TYPE_INT32, int32, result);
9423 jump(&done);
9424 }
9425 bind(&canonicalize);
9426 {
9427 // Normalize the sign bit of a NaN.
9428 branchDouble(Assembler::DoubleOrdered, tempFloat, tempFloat, &useInput);
9429 moveValue(JS::NaNValue(), result);
9430 jump(&done);
9431 }
9432 }
9433
9434 bind(&useInput);
9435 moveValue(value, result);
9436
9437 bind(&done);
9438 }
9439
9440 void MacroAssembler::toHashableValue(ValueOperand value, ValueOperand result,
9441 FloatRegister tempFloat,
9442 Label* atomizeString, Label* tagString) {
9443 // Inline implementation of |HashableValue::setValue()|.
9444
9445 ScratchTagScope tag(*this, value);
9446 splitTagForTest(value, tag);
9447
9448 Label notString, useInput, done;
9449 branchTestString(Assembler::NotEqual, tag, &notString);
9450 {
9451 ScratchTagScopeRelease _(&tag);
9452
9453 Register str = result.scratchReg();
9454 unboxString(value, str);
9455
9456 branchTest32(Assembler::NonZero, Address(str, JSString::offsetOfFlags()),
9457 Imm32(JSString::ATOM_BIT), &useInput);
9458
9459 jump(atomizeString);
9460 bind(tagString);
9461
9462 tagValue(JSVAL_TYPE_STRING, str, result);
9463 jump(&done);
9464 }
9465 bind(&notString);
9466 branchTestDouble(Assembler::NotEqual, tag, &useInput);
9467 {
9468 ScratchTagScopeRelease _(&tag);
9469
9470 Register int32 = result.scratchReg();
9471 unboxDouble(value, tempFloat);
9472
9473 Label canonicalize;
9474 convertDoubleToInt32(tempFloat, int32, &canonicalize, false);
9475 {
9476 tagValue(JSVAL_TYPE_INT32, int32, result);
9477 jump(&done);
9478 }
9479 bind(&canonicalize);
9480 {
9481 branchDouble(Assembler::DoubleOrdered, tempFloat, tempFloat, &useInput);
9482 moveValue(JS::NaNValue(), result);
9483 jump(&done);
9484 }
9485 }
9486
9487 bind(&useInput);
9488 moveValue(value, result);
9489
9490 bind(&done);
9491 }
9492
9493 void MacroAssembler::scrambleHashCode(Register result) {
9494 // Inline implementation of |mozilla::ScrambleHashCode()|.
9495
9496 mul32(Imm32(mozilla::kGoldenRatioU32), result);
9497 }
9498
9499 void MacroAssembler::prepareHashNonGCThing(ValueOperand value, Register result,
9500 Register temp) {
9501 // Inline implementation of |OrderedHashTableImpl::prepareHash()| and
9502 // |mozilla::HashGeneric(v.asRawBits())|.
9503
9504 #ifdef DEBUG
9505 Label ok;
9506 branchTestGCThing(Assembler::NotEqual, value, &ok);
9507 assumeUnreachable("Unexpected GC thing");
9508 bind(&ok);
9509 #endif
9510
9511 // uint32_t v1 = static_cast<uint32_t>(aValue);
9512 #ifdef JS_PUNBOX64
9513 move64To32(value.toRegister64(), result);
9514 #else
9515 move32(value.payloadReg(), result);
9516 #endif
9517
9518 // uint32_t v2 = static_cast<uint32_t>(static_cast<uint64_t>(aValue) >> 32);
9519 #ifdef JS_PUNBOX64
9520 auto r64 = Register64(temp);
9521 move64(value.toRegister64(), r64);
9522 rshift64Arithmetic(Imm32(32), r64);
9523 #else
9524 move32(value.typeReg(), temp);
9525 #endif
9526
9527 // mozilla::WrappingMultiply(kGoldenRatioU32, RotateLeft5(aHash) ^ aValue);
9528 // with |aHash = 0| and |aValue = v1|.
9529 mul32(Imm32(mozilla::kGoldenRatioU32), result);
9530
9531 // mozilla::WrappingMultiply(kGoldenRatioU32, RotateLeft5(aHash) ^ aValue);
9532 // with |aHash = <above hash>| and |aValue = v2|.
9533 rotateLeft(Imm32(5), result, result);
9534 xor32(temp, result);
9535
9536 // Combine |mul32| and |scrambleHashCode| by directly multiplying with
9537 // |kGoldenRatioU32 * kGoldenRatioU32|.
9538 //
9539 // mul32(Imm32(mozilla::kGoldenRatioU32), result);
9540 //
9541 // scrambleHashCode(result);
9542 mul32(Imm32(mozilla::kGoldenRatioU32 * mozilla::kGoldenRatioU32), result);
9543 }
9544
9545 void MacroAssembler::prepareHashString(Register str, Register result,
9546 Register temp) {
9547 // Inline implementation of |OrderedHashTableImpl::prepareHash()| and
9548 // |JSAtom::hash()|.
9549
9550 #ifdef DEBUG
9551 Label ok;
9552 branchTest32(Assembler::NonZero, Address(str, JSString::offsetOfFlags()),
9553 Imm32(JSString::ATOM_BIT), &ok);
9554 assumeUnreachable("Unexpected non-atom string");
9555 bind(&ok);
9556 #endif
9557
9558 #ifdef JS_64BIT
9559 static_assert(FatInlineAtom::offsetOfHash() == NormalAtom::offsetOfHash());
9560 load32(Address(str, NormalAtom::offsetOfHash()), result);
9561 #else
9562 move32(Imm32(JSString::FAT_INLINE_MASK), temp);
9563 and32(Address(str, JSString::offsetOfFlags()), temp);
9564
9565 // Set |result| to 1 for FatInlineAtoms.
9566 move32(Imm32(0), result);
9567 cmp32Set(Assembler::Equal, temp, Imm32(JSString::FAT_INLINE_MASK), result);
9568
9569 // Use a computed load for branch-free code.
9570
9571 static_assert(FatInlineAtom::offsetOfHash() > NormalAtom::offsetOfHash());
9572
9573 constexpr size_t offsetDiff =
9574 FatInlineAtom::offsetOfHash() - NormalAtom::offsetOfHash();
9575 static_assert(mozilla::IsPowerOfTwo(offsetDiff));
9576
9577 uint8_t shift = mozilla::FloorLog2Size(offsetDiff);
9578 if (IsShiftInScaleRange(shift)) {
9579 load32(
9580 BaseIndex(str, result, ShiftToScale(shift), NormalAtom::offsetOfHash()),
9581 result);
9582 } else {
9583 lshift32(Imm32(shift), result);
9584 load32(BaseIndex(str, result, TimesOne, NormalAtom::offsetOfHash()),
9585 result);
9586 }
9587 #endif
9588
9589 scrambleHashCode(result);
9590 }
9591
9592 void MacroAssembler::prepareHashSymbol(Register sym, Register result) {
9593 // Inline implementation of |OrderedHashTableImpl::prepareHash()| and
9594 // |Symbol::hash()|.
9595
9596 load32(Address(sym, JS::Symbol::offsetOfHash()), result);
9597
9598 scrambleHashCode(result);
9599 }
9600
9601 void MacroAssembler::prepareHashBigInt(Register bigInt, Register result,
9602 Register temp1, Register temp2,
9603 Register temp3) {
9604 // Inline implementation of |OrderedHashTableImpl::prepareHash()| and
9605 // |BigInt::hash()|.
9606
9607 // Inline implementation of |mozilla::AddU32ToHash()|.
9608 auto addU32ToHash = [&](auto toAdd) {
9609 rotateLeft(Imm32(5), result, result);
9610 xor32(toAdd, result);
9611 mul32(Imm32(mozilla::kGoldenRatioU32), result);
9612 };
9613
9614 move32(Imm32(0), result);
9615
9616 // Inline |mozilla::HashBytes()|.
9617
9618 load32(Address(bigInt, BigInt::offsetOfLength()), temp1);
9619 loadBigIntDigits(bigInt, temp2);
9620
9621 Label start, loop;
9622 jump(&start);
9623 bind(&loop);
9624
9625 {
9626 // Compute |AddToHash(AddToHash(hash, data), sizeof(Digit))|.
9627 #if defined(JS_CODEGEN_MIPS64)
9628 // Hash the lower 32-bits.
9629 addU32ToHash(Address(temp2, 0));
9630
9631 // Hash the upper 32-bits.
9632 addU32ToHash(Address(temp2, sizeof(int32_t)));
9633 #elif JS_PUNBOX64
9634 // Use a single 64-bit load on non-MIPS64 platforms.
9635 loadPtr(Address(temp2, 0), temp3);
9636
9637 // Hash the lower 32-bits.
9638 addU32ToHash(temp3);
9639
9640 // Hash the upper 32-bits.
9641 rshiftPtr(Imm32(32), temp3);
9642 addU32ToHash(temp3);
9643 #else
9644 addU32ToHash(Address(temp2, 0));
9645 #endif
9646 }
9647 addPtr(Imm32(sizeof(BigInt::Digit)), temp2);
9648
9649 bind(&start);
9650 branchSub32(Assembler::NotSigned, Imm32(1), temp1, &loop);
9651
9652 // Compute |mozilla::AddToHash(h, isNegative())|.
9653 {
9654 static_assert(mozilla::IsPowerOfTwo(BigInt::signBitMask()));
9655
9656 load32(Address(bigInt, BigInt::offsetOfFlags()), temp1);
9657 and32(Imm32(BigInt::signBitMask()), temp1);
9658 rshift32(Imm32(mozilla::FloorLog2(BigInt::signBitMask())), temp1);
9659
9660 addU32ToHash(temp1);
9661 }
9662
9663 scrambleHashCode(result);
9664 }
9665
9666 void MacroAssembler::prepareHashObject(Register setObj, ValueOperand value,
9667 Register result, Register temp1,
9668 Register temp2, Register temp3,
9669 Register temp4) {
9670 #ifdef JS_PUNBOX64
9671 // Inline implementation of |OrderedHashTableImpl::prepareHash()| and
9672 // |HashCodeScrambler::scramble(v.asRawBits())|.
9673
9674 // Load |HashCodeScrambler*|. If the object has no buffer yet this will be
9675 // nullptr. In this case we use 0 as hash number because the hash won't be
9676 // used in MacroAssembler::orderedHashTableLookup when there are no entries.
9677 Label done;
9678 static_assert(MapObject::offsetOfHashCodeScrambler() ==
9679 SetObject::offsetOfHashCodeScrambler());
9680 loadPrivate(Address(setObj, SetObject::offsetOfHashCodeScrambler()), temp1);
9681 move32(Imm32(0), result);
9682 branchTestPtr(Assembler::Zero, temp1, temp1, &done);
9683
9684 // Load |HashCodeScrambler::mK0| and |HashCodeScrambler::mK1|.
9685 auto k0 = Register64(temp1);
9686 auto k1 = Register64(temp2);
9687 load64(Address(temp1, mozilla::HashCodeScrambler::offsetOfMK1()), k1);
9688 load64(Address(temp1, mozilla::HashCodeScrambler::offsetOfMK0()), k0);
9689
9690 // Hash numbers are 32-bit values, so only hash the lower double-word.
9691 static_assert(sizeof(mozilla::HashNumber) == 4);
9692 move32To64ZeroExtend(value.valueReg(), Register64(result));
9693
9694 // Inline implementation of |SipHasher::sipHash()|.
9695 auto m = Register64(result);
9696 auto v0 = Register64(temp3);
9697 auto v1 = Register64(temp4);
9698 auto v2 = k0;
9699 auto v3 = k1;
9700
9701 auto sipRound = [&]() {
9702 // mV0 = WrappingAdd(mV0, mV1);
9703 add64(v1, v0);
9704
9705 // mV1 = RotateLeft(mV1, 13);
9706 rotateLeft64(Imm32(13), v1, v1, InvalidReg);
9707
9708 // mV1 ^= mV0;
9709 xor64(v0, v1);
9710
9711 // mV0 = RotateLeft(mV0, 32);
9712 rotateLeft64(Imm32(32), v0, v0, InvalidReg);
9713
9714 // mV2 = WrappingAdd(mV2, mV3);
9715 add64(v3, v2);
9716
9717 // mV3 = RotateLeft(mV3, 16);
9718 rotateLeft64(Imm32(16), v3, v3, InvalidReg);
9719
9720 // mV3 ^= mV2;
9721 xor64(v2, v3);
9722
9723 // mV0 = WrappingAdd(mV0, mV3);
9724 add64(v3, v0);
9725
9726 // mV3 = RotateLeft(mV3, 21);
9727 rotateLeft64(Imm32(21), v3, v3, InvalidReg);
9728
9729 // mV3 ^= mV0;
9730 xor64(v0, v3);
9731
9732 // mV2 = WrappingAdd(mV2, mV1);
9733 add64(v1, v2);
9734
9735 // mV1 = RotateLeft(mV1, 17);
9736 rotateLeft64(Imm32(17), v1, v1, InvalidReg);
9737
9738 // mV1 ^= mV2;
9739 xor64(v2, v1);
9740
9741 // mV2 = RotateLeft(mV2, 32);
9742 rotateLeft64(Imm32(32), v2, v2, InvalidReg);
9743 };
9744
9745 // 1. Initialization.
9746 // mV0 = aK0 ^ UINT64_C(0x736f6d6570736575);
9747 move64(Imm64(0x736f6d6570736575), v0);
9748 xor64(k0, v0);
9749
9750 // mV1 = aK1 ^ UINT64_C(0x646f72616e646f6d);
9751 move64(Imm64(0x646f72616e646f6d), v1);
9752 xor64(k1, v1);
9753
9754 // mV2 = aK0 ^ UINT64_C(0x6c7967656e657261);
9755 MOZ_ASSERT(v2 == k0);
9756 xor64(Imm64(0x6c7967656e657261), v2);
9757
9758 // mV3 = aK1 ^ UINT64_C(0x7465646279746573);
9759 MOZ_ASSERT(v3 == k1);
9760 xor64(Imm64(0x7465646279746573), v3);
9761
9762 // 2. Compression.
9763 // mV3 ^= aM;
9764 xor64(m, v3);
9765
9766 // sipRound();
9767 sipRound();
9768
9769 // mV0 ^= aM;
9770 xor64(m, v0);
9771
9772 // 3. Finalization.
9773 // mV2 ^= 0xff;
9774 xor64(Imm64(0xff), v2);
9775
9776 // for (int i = 0; i < 3; i++) sipRound();
9777 for (int i = 0; i < 3; i++) {
9778 sipRound();
9779 }
9780
9781 // return mV0 ^ mV1 ^ mV2 ^ mV3;
9782 xor64(v1, v0);
9783 xor64(v2, v3);
9784 xor64(v3, v0);
9785
9786 move64To32(v0, result);
9787
9788 scrambleHashCode(result);
9789
9790 bind(&done);
9791 #else
9792 MOZ_CRASH("Not implemented");
9793 #endif
9794 }
9795
9796 void MacroAssembler::prepareHashValue(Register setObj, ValueOperand value,
9797 Register result, Register temp1,
9798 Register temp2, Register temp3,
9799 Register temp4) {
9800 Label isString, isObject, isSymbol, isBigInt;
9801 {
9802 ScratchTagScope tag(*this, value);
9803 splitTagForTest(value, tag);
9804
9805 branchTestString(Assembler::Equal, tag, &isString);
9806 branchTestObject(Assembler::Equal, tag, &isObject);
9807 branchTestSymbol(Assembler::Equal, tag, &isSymbol);
9808 branchTestBigInt(Assembler::Equal, tag, &isBigInt);
9809 }
9810
9811 Label done;
9812 {
9813 prepareHashNonGCThing(value, result, temp1);
9814 jump(&done);
9815 }
9816 bind(&isString);
9817 {
9818 unboxString(value, temp1);
9819 prepareHashString(temp1, result, temp2);
9820 jump(&done);
9821 }
9822 bind(&isObject);
9823 {
9824 prepareHashObject(setObj, value, result, temp1, temp2, temp3, temp4);
9825 jump(&done);
9826 }
9827 bind(&isSymbol);
9828 {
9829 unboxSymbol(value, temp1);
9830 prepareHashSymbol(temp1, result);
9831 jump(&done);
9832 }
9833 bind(&isBigInt);
9834 {
9835 unboxBigInt(value, temp1);
9836 prepareHashBigInt(temp1, result, temp2, temp3, temp4);
9837
9838 // Fallthrough to |done|.
9839 }
9840
9841 bind(&done);
9842 }
9843
9844 template <typename TableObject>
9845 void MacroAssembler::orderedHashTableLookup(Register setOrMapObj,
9846 ValueOperand value, Register hash,
9847 Register entryTemp, Register temp1,
9848 Register temp2, Register temp3,
9849 Register temp4, Label* found,
9850 IsBigInt isBigInt) {
9851 // Inline implementation of |OrderedHashTableImpl::lookup()|.
9852
9853 MOZ_ASSERT_IF(isBigInt == IsBigInt::No, temp3 == InvalidReg);
9854 MOZ_ASSERT_IF(isBigInt == IsBigInt::No, temp4 == InvalidReg);
9855
9856 #ifdef DEBUG
9857 Label ok;
9858 if (isBigInt == IsBigInt::No) {
9859 branchTestBigInt(Assembler::NotEqual, value, &ok);
9860 assumeUnreachable("Unexpected BigInt");
9861 } else if (isBigInt == IsBigInt::Yes) {
9862 branchTestBigInt(Assembler::Equal, value, &ok);
9863 assumeUnreachable("Unexpected non-BigInt");
9864 }
9865 bind(&ok);
9866 #endif
9867
9868 // Jump to notFound if the hash table has no entries and may not have a
9869 // buffer. Check this before calling Assert{Map,Set}ObjectHash because |hash|
9870 // may be 0 when there's no hash code scrambler.
9871 Label notFound;
9872 unboxInt32(Address(setOrMapObj, TableObject::offsetOfLiveCount()), temp1);
9873 branchTest32(Assembler::Zero, temp1, temp1, &notFound);
9874
9875 #ifdef DEBUG
9876 PushRegsInMask(LiveRegisterSet(RegisterSet::Volatile()));
9877
9878 pushValue(value);
9879 moveStackPtrTo(temp2);
9880
9881 setupUnalignedABICall(temp1);
9882 loadJSContext(temp1);
9883 passABIArg(temp1);
9884 passABIArg(setOrMapObj);
9885 passABIArg(temp2);
9886 passABIArg(hash);
9887
9888 if constexpr (std::is_same_v<TableObject, SetObject>) {
9889 using Fn =
9890 void (*)(JSContext*, SetObject*, const Value*, mozilla::HashNumber);
9891 callWithABI<Fn, jit::AssertSetObjectHash>();
9892 } else {
9893 static_assert(std::is_same_v<TableObject, MapObject>);
9894 using Fn =
9895 void (*)(JSContext*, MapObject*, const Value*, mozilla::HashNumber);
9896 callWithABI<Fn, jit::AssertMapObjectHash>();
9897 }
9898
9899 popValue(value);
9900 PopRegsInMask(LiveRegisterSet(RegisterSet::Volatile()));
9901 #endif
9902
9903 // Determine the bucket by computing |hash >> object->hashShift|. The hash
9904 // shift is stored as PrivateUint32Value.
9905 move32(hash, entryTemp);
9906 unboxInt32(Address(setOrMapObj, TableObject::offsetOfHashShift()), temp2);
9907 flexibleRshift32(temp2, entryTemp);
9908
9909 loadPrivate(Address(setOrMapObj, TableObject::offsetOfHashTable()), temp2);
9910 loadPtr(BaseIndex(temp2, entryTemp, ScalePointer), entryTemp);
9911
9912 // Search for a match in this bucket.
9913 Label start, loop;
9914 jump(&start);
9915 bind(&loop);
9916 {
9917 // Inline implementation of |HashableValue::operator==|.
9918
9919 static_assert(TableObject::Table::offsetOfImplDataElement() == 0,
9920 "offsetof(Data, element) is 0");
9921 auto keyAddr = Address(entryTemp, TableObject::Table::offsetOfEntryKey());
9922
9923 if (isBigInt == IsBigInt::No) {
9924 // Two HashableValues are equal if they have equal bits.
9925 branch64(Assembler::Equal, keyAddr, value.toRegister64(), found);
9926 } else {
9927 #ifdef JS_PUNBOX64
9928 auto key = ValueOperand(temp1);
9929 #else
9930 auto key = ValueOperand(temp1, temp2);
9931 #endif
9932
9933 loadValue(keyAddr, key);
9934
9935 // Two HashableValues are equal if they have equal bits.
9936 branch64(Assembler::Equal, key.toRegister64(), value.toRegister64(),
9937 found);
9938
9939 // BigInt values are considered equal if they represent the same
9940 // mathematical value.
9941 Label next;
9942 fallibleUnboxBigInt(key, temp2, &next);
9943 if (isBigInt == IsBigInt::Yes) {
9944 unboxBigInt(value, temp1);
9945 } else {
9946 fallibleUnboxBigInt(value, temp1, &next);
9947 }
9948 equalBigInts(temp1, temp2, temp3, temp4, temp1, temp2, &next, &next,
9949 &next);
9950 jump(found);
9951 bind(&next);
9952 }
9953 }
9954 loadPtr(Address(entryTemp, TableObject::Table::offsetOfImplDataChain()),
9955 entryTemp);
9956 bind(&start);
9957 branchTestPtr(Assembler::NonZero, entryTemp, entryTemp, &loop);
9958
9959 bind(&notFound);
9960 }
9961
9962 void MacroAssembler::setObjectHas(Register setObj, ValueOperand value,
9963 Register hash, Register result,
9964 Register temp1, Register temp2,
9965 Register temp3, Register temp4,
9966 IsBigInt isBigInt) {
9967 Label found;
9968 orderedHashTableLookup<SetObject>(setObj, value, hash, result, temp1, temp2,
9969 temp3, temp4, &found, isBigInt);
9970
9971 Label done;
9972 move32(Imm32(0), result);
9973 jump(&done);
9974
9975 bind(&found);
9976 move32(Imm32(1), result);
9977 bind(&done);
9978 }
9979
9980 void MacroAssembler::mapObjectHas(Register mapObj, ValueOperand value,
9981 Register hash, Register result,
9982 Register temp1, Register temp2,
9983 Register temp3, Register temp4,
9984 IsBigInt isBigInt) {
9985 Label found;
9986 orderedHashTableLookup<MapObject>(mapObj, value, hash, result, temp1, temp2,
9987 temp3, temp4, &found, isBigInt);
9988
9989 Label done;
9990 move32(Imm32(0), result);
9991 jump(&done);
9992
9993 bind(&found);
9994 move32(Imm32(1), result);
9995 bind(&done);
9996 }
9997
9998 void MacroAssembler::mapObjectGet(Register mapObj, ValueOperand value,
9999 Register hash, ValueOperand result,
10000 Register temp1, Register temp2,
10001 Register temp3, Register temp4,
10002 Register temp5, IsBigInt isBigInt) {
10003 Label found;
10004 orderedHashTableLookup<MapObject>(mapObj, value, hash, temp1, temp2, temp3,
10005 temp4, temp5, &found, isBigInt);
10006
10007 Label done;
10008 moveValue(UndefinedValue(), result);
10009 jump(&done);
10010
10011 // |temp1| holds the found entry.
10012 bind(&found);
10013 loadValue(Address(temp1, MapObject::Table::Entry::offsetOfValue()), result);
10014
10015 bind(&done);
10016 }
10017
10018 template <typename TableObject>
10019 void MacroAssembler::loadOrderedHashTableCount(Register setOrMapObj,
10020 Register result) {
10021 // Inline implementation of |OrderedHashTableImpl::count()|.
10022
10023 // Load the live count, stored as PrivateUint32Value.
10024 unboxInt32(Address(setOrMapObj, TableObject::offsetOfLiveCount()), result);
10025 }
10026
10027 void MacroAssembler::loadSetObjectSize(Register setObj, Register result) {
10028 loadOrderedHashTableCount<SetObject>(setObj, result);
10029 }
10030
10031 void MacroAssembler::loadMapObjectSize(Register mapObj, Register result) {
10032 loadOrderedHashTableCount<MapObject>(mapObj, result);
10033 }
10034
10035 // Can't push large frames blindly on windows, so we must touch frame memory
10036 // incrementally, with no more than 4096 - 1 bytes between touches.
10037 //
10038 // This is used across all platforms for simplicity.
10039 void MacroAssembler::touchFrameValues(Register numStackValues,
10040 Register scratch1, Register scratch2) {
10041 const size_t FRAME_TOUCH_INCREMENT = 2048;
10042 static_assert(FRAME_TOUCH_INCREMENT < 4096 - 1,
10043 "Frame increment is too large");
10044
10045 moveStackPtrTo(scratch2);
10046
10047 lshiftPtr(Imm32(3), numStackValues, scratch1);
10048 {
10049 // Note: this loop needs to update the stack pointer register because older
10050 // Linux kernels check the distance between the touched address and RSP.
10051 // See bug 1839669 comment 47.
10052 Label touchFrameLoop;
10053 Label touchFrameLoopEnd;
10054 bind(&touchFrameLoop);
10055 branchSub32(Assembler::Signed, Imm32(FRAME_TOUCH_INCREMENT), scratch1,
10056 &touchFrameLoopEnd);
10057 subFromStackPtr(Imm32(FRAME_TOUCH_INCREMENT));
10058 store32(Imm32(0), Address(getStackPointer(), 0));
10059 jump(&touchFrameLoop);
10060 bind(&touchFrameLoopEnd);
10061 }
10062
10063 moveToStackPtr(scratch2);
10064 }
10065
10066 #ifdef FUZZING_JS_FUZZILLI
10067 void MacroAssembler::fuzzilliHashDouble(FloatRegister src, Register result,
10068 Register temp) {
10069 canonicalizeDouble(src);
10070
10071 # ifdef JS_PUNBOX64
10072 Register64 r64(temp);
10073 # else
10074 Register64 r64(temp, result);
10075 # endif
10076
10077 moveDoubleToGPR64(src, r64);
10078
10079 # ifdef JS_PUNBOX64
10080 // Move the high word into |result|.
10081 move64(r64, Register64(result));
10082 rshift64(Imm32(32), Register64(result));
10083 # endif
10084
10085 // Add the high and low words of |r64|.
10086 add32(temp, result);
10087 }
10088
10089 void MacroAssembler::fuzzilliStoreHash(Register value, Register temp1,
10090 Register temp2) {
10091 loadJSContext(temp1);
10092
10093 // stats
10094 Address addrExecHashInputs(temp1, offsetof(JSContext, executionHashInputs));
10095 add32(Imm32(1), addrExecHashInputs);
10096
10097 // hash
10098 Address addrExecHash(temp1, offsetof(JSContext, executionHash));
10099 load32(addrExecHash, temp2);
10100 add32(value, temp2);
10101 rotateLeft(Imm32(1), temp2, temp2);
10102 store32(temp2, addrExecHash);
10103 }
10104 #endif
10105
10106 namespace js {
10107 namespace jit {
10108
10109 #ifdef DEBUG
10110 template <class RegisterType>
10111 AutoGenericRegisterScope<RegisterType>::AutoGenericRegisterScope(
10112 MacroAssembler& masm, RegisterType reg)
10113 : RegisterType(reg), masm_(masm), released_(false) {
10114 masm.debugTrackedRegisters_.add(reg);
10115 }
10116
10117 template AutoGenericRegisterScope<Register>::AutoGenericRegisterScope(
10118 MacroAssembler& masm, Register reg);
10119 template AutoGenericRegisterScope<FloatRegister>::AutoGenericRegisterScope(
10120 MacroAssembler& masm, FloatRegister reg);
10121 #endif // DEBUG
10122
10123 #ifdef DEBUG
10124 template <class RegisterType>
10125 AutoGenericRegisterScope<RegisterType>::~AutoGenericRegisterScope() {
10126 if (!released_) {
10127 release();
10128 }
10129 }
10130
10131 template AutoGenericRegisterScope<Register>::~AutoGenericRegisterScope();
10132 template AutoGenericRegisterScope<FloatRegister>::~AutoGenericRegisterScope();
10133
10134 template <class RegisterType>
10135 void AutoGenericRegisterScope<RegisterType>::release() {
10136 MOZ_ASSERT(!released_);
10137 released_ = true;
10138 const RegisterType& reg = *dynamic_cast<RegisterType*>(this);
10139 masm_.debugTrackedRegisters_.take(reg);
10140 }
10141
10142 template void AutoGenericRegisterScope<Register>::release();
10143 template void AutoGenericRegisterScope<FloatRegister>::release();
10144
10145 template <class RegisterType>
10146 void AutoGenericRegisterScope<RegisterType>::reacquire() {
10147 MOZ_ASSERT(released_);
10148 released_ = false;
10149 const RegisterType& reg = *dynamic_cast<RegisterType*>(this);
10150 masm_.debugTrackedRegisters_.add(reg);
10151 }
10152
10153 template void AutoGenericRegisterScope<Register>::reacquire();
10154 template void AutoGenericRegisterScope<FloatRegister>::reacquire();
10155
10156 #endif // DEBUG
10157
10158 } // namespace jit
10159
10160 } // namespace js