Commit f2d935671c6 for nodejs
commit f2d935671c6b65337d66bb920384c15adabd5b4b
Author: Node.js GitHub Bot <github-bot@iojs.org>
Date: Tue Dec 1 04:38:43 2026 -0500
deps: patch V8 to 15.8.62.81
Refs: https://github.com/v8/v8/compare/15.8.62.61...15.8.62.81
PR-URL: https://github.com/nodejs/node/pull/67863
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
diff --git a/deps/v8/include/v8-version.h b/deps/v8/include/v8-version.h
index e2fefa97222..07fe8178b75 100644
--- a/deps/v8/include/v8-version.h
+++ b/deps/v8/include/v8-version.h
@@ -11,7 +11,7 @@
#define V8_MAJOR_VERSION 15
#define V8_MINOR_VERSION 8
#define V8_BUILD_NUMBER 62
-#define V8_PATCH_LEVEL 61
+#define V8_PATCH_LEVEL 81
// Use 1 for candidates and 0 otherwise.
// (Boolean macro values are not supported by all preprocessors.)
diff --git a/deps/v8/src/builtins/base.tq b/deps/v8/src/builtins/base.tq
index 4d587295ef6..3567132623e 100644
--- a/deps/v8/src/builtins/base.tq
+++ b/deps/v8/src/builtins/base.tq
@@ -747,9 +747,6 @@ extern macro Comment(constexpr string): void;
extern macro DebugBreak(): void;
extern macro PrintStringSimple(String): void;
-extern macro SetSupportsDynamicParameterCount(
- JSFunction, DispatchHandle): void;
-
// ES6 7.1.4 ToInteger ( argument )
transitioning macro ToIntegerImpl(
implicit context: Context)(input: JSAny): Number {
diff --git a/deps/v8/src/builtins/builtins-internal-gen.cc b/deps/v8/src/builtins/builtins-internal-gen.cc
index 330b40b14fc..85259f49141 100644
--- a/deps/v8/src/builtins/builtins-internal-gen.cc
+++ b/deps/v8/src/builtins/builtins-internal-gen.cc
@@ -89,8 +89,7 @@ TF_BUILTIN(DebugBreakTrampoline, CodeStubAssembler) {
#ifdef V8_JS_LINKAGE_INCLUDES_DISPATCH_HANDLE
auto dispatch_handle =
UncheckedParameter<JSDispatchHandleT>(Descriptor::kJSDispatchHandle);
- TNode<Uint16T> expected_parameter_count =
- LoadParameterCountFromJSDispatchTable(dispatch_handle);
+ TNode<Uint16T> expected_parameter_count = DynamicJSParameterCount();
#else
auto dispatch_handle = InvalidDispatchHandleConstant();
TNode<Uint16T> expected_parameter_count = Uint16Constant(0);
diff --git a/deps/v8/src/builtins/builtins-object.cc b/deps/v8/src/builtins/builtins-object.cc
index 7677d9c3f99..38b4f3522ed 100644
--- a/deps/v8/src/builtins/builtins-object.cc
+++ b/deps/v8/src/builtins/builtins-object.cc
@@ -122,6 +122,7 @@ Tagged<Object> ObjectLookupAccessor(Isolate* isolate,
switch (it.state()) {
case LookupIterator::INTERCEPTOR:
case LookupIterator::TRANSITION:
+ case LookupIterator::STRING_LOOKUP_START_OBJECT:
UNREACHABLE();
case LookupIterator::ACCESS_CHECK:
@@ -152,7 +153,6 @@ Tagged<Object> ObjectLookupAccessor(Isolate* isolate,
}
return ObjectLookupAccessor(isolate, prototype, key, component);
}
- case LookupIterator::STRING_LOOKUP_START_OBJECT:
case LookupIterator::WASM_OBJECT:
continue; // Continue to the prototype, if present.
case LookupIterator::TYPED_ARRAY_INDEX_NOT_FOUND:
@@ -181,7 +181,8 @@ Tagged<Object> ObjectLookupAccessor(Isolate* isolate,
return *AccessorPair::GetComponent(
isolate, holder_realm, Cast<AccessorPair>(maybe_pair), component);
}
- continue;
+ DCHECK(IsAccessorInfo(*maybe_pair));
+ return ReadOnlyRoots(isolate).undefined_value();
}
}
UNREACHABLE();
diff --git a/deps/v8/src/builtins/builtins-utils-gen.h b/deps/v8/src/builtins/builtins-utils-gen.h
index 5e675fe2f50..48ad9b8990e 100644
--- a/deps/v8/src/builtins/builtins-utils-gen.h
+++ b/deps/v8/src/builtins/builtins-utils-gen.h
@@ -52,9 +52,7 @@ class CodeAssemblerState;
void Builtins::Generate_##Name(compiler::CodeAssemblerState* state) { \
Name##Assembler assembler(state); \
state->SetInitialDebugInformation(#Name, __FILE__, __LINE__); \
- if (Builtins::KindOf(Builtin::k##Name) == Builtins::TFJ) { \
- assembler.PerformStackCheck(assembler.GetJSContextParameter()); \
- } \
+ assembler.EmitBuiltinProlog(Builtin::k##Name); \
assembler.Generate##Name##Impl(); \
} \
void Name##Assembler::Generate##Name##Impl()
diff --git a/deps/v8/src/builtins/js-to-wasm.tq b/deps/v8/src/builtins/js-to-wasm.tq
index 8eaecc0c6f7..b88ef84b692 100644
--- a/deps/v8/src/builtins/js-to-wasm.tq
+++ b/deps/v8/src/builtins/js-to-wasm.tq
@@ -837,34 +837,22 @@ macro JSToWasmWrapperHelper(
}
transitioning javascript builtin JSToWasmWrapper(
- js-implicit context: NativeContext, receiver: JSAny, target: JSFunction,
- dispatchHandle: DispatchHandle)(...arguments): JSAny {
- // This is a generic builtin that can be installed on functions with different
- // parameter counts, so we need to support that.
- SetSupportsDynamicParameterCount(target, dispatchHandle);
-
+ js-implicit context: NativeContext, receiver: JSAny, target: JSFunction)(
+ ...arguments): JSAny {
return JSToWasmWrapperHelper(
context, receiver, target, arguments, Promise::kNoPromise);
}
transitioning javascript builtin WasmPromising(
- js-implicit context: NativeContext, receiver: JSAny, target: JSFunction,
- dispatchHandle: DispatchHandle)(...arguments): JSAny {
- // This is a generic builtin that can be installed on functions with different
- // parameter counts, so we need to support that.
- SetSupportsDynamicParameterCount(target, dispatchHandle);
-
+ js-implicit context: NativeContext, receiver: JSAny, target: JSFunction)(
+ ...arguments): JSAny {
return JSToWasmWrapperHelper(
context, receiver, target, arguments, Promise::kPromise);
}
transitioning javascript builtin WasmStressSwitch(
- js-implicit context: NativeContext, receiver: JSAny, target: JSFunction,
- dispatchHandle: DispatchHandle)(...arguments): JSAny {
- // This is a generic builtin that can be installed on functions with different
- // parameter counts, so we need to support that.
- SetSupportsDynamicParameterCount(target, dispatchHandle);
-
+ js-implicit context: NativeContext, receiver: JSAny, target: JSFunction)(
+ ...arguments): JSAny {
return JSToWasmWrapperHelper(
context, receiver, target, arguments, Promise::kStressSwitch);
}
diff --git a/deps/v8/src/builtins/js-trampoline-assembler.cc b/deps/v8/src/builtins/js-trampoline-assembler.cc
index 1b1fbc5e9ac..eec0c1ae8e2 100644
--- a/deps/v8/src/builtins/js-trampoline-assembler.cc
+++ b/deps/v8/src/builtins/js-trampoline-assembler.cc
@@ -38,17 +38,27 @@ void JSTrampolineAssembler::TailCallJSFunction(
expected_parameter_count);
}
-void JSTrampolineAssembler::CompileLazy(TNode<JSFunction> function,
- TNode<Context> context) {
+TNode<Uint16T> JSTrampolineAssembler::LoadIncomingParameterCount() {
#ifdef V8_JS_LINKAGE_INCLUDES_DISPATCH_HANDLE
+ // TODO(crbug.com/465487205): Until incoming JSDispatchHandles are kept alive
+ // via the stack, the parameter count must be loaded at the very start of the
+ // builtin before any runtime call or stack check can trigger a GC and sweep
+ // an unrooted dispatch table entry.
+ DCHECK(IsAtStart());
auto dispatch_handle =
UncheckedParameter<JSDispatchHandleT>(Descriptor::kDispatchHandle);
- TNode<Uint16T> expected_parameter_count =
- LoadParameterCountFromJSDispatchTable(dispatch_handle);
+ return LoadParameterCountFromJSDispatchTable(dispatch_handle);
#else
CHECK(!V8_ENABLE_SANDBOX_BOOL);
- TNode<Uint16T> expected_parameter_count = Uint16Constant(0);
+ return Uint16Constant(0);
#endif
+}
+
+TF_BUILTIN(CompileLazy, JSTrampolineAssembler) {
+ TNode<Uint16T> expected_parameter_count = LoadIncomingParameterCount();
+
+ auto function = Parameter<JSFunction>(Descriptor::kTarget);
+ auto context = Parameter<Context>(Descriptor::kContext);
// First lookup code, maybe we don't need to compile!
Label compile_function(this, Label::kDeferred);
@@ -98,16 +108,10 @@ void JSTrampolineAssembler::CompileLazy(TNode<JSFunction> function,
TailCallJSFunction(function, expected_parameter_count);
}
-TF_BUILTIN(CompileLazy, JSTrampolineAssembler) {
- auto function = Parameter<JSFunction>(Descriptor::kTarget);
- auto context = Parameter<Context>(Descriptor::kContext);
-
- CompileLazy(function, context);
-}
-
-
template <typename Function>
void JSTrampolineAssembler::TieringBuiltinImpl(const Function& Impl) {
+ TNode<Uint16T> expected_parameter_count = LoadIncomingParameterCount();
+
auto function = Parameter<JSFunction>(Descriptor::kTarget);
auto context = Parameter<Context>(Descriptor::kContext);
auto argc = UncheckedParameter<Int32T>(Descriptor::kActualArgumentsCount);
@@ -116,13 +120,9 @@ void JSTrampolineAssembler::TieringBuiltinImpl(const Function& Impl) {
#ifdef V8_JS_LINKAGE_INCLUDES_DISPATCH_HANDLE
auto dispatch_handle =
UncheckedParameter<JSDispatchHandleT>(Descriptor::kDispatchHandle);
- TNode<Uint16T> expected_parameter_count =
- LoadParameterCountFromJSDispatchTable(dispatch_handle);
#else
- CHECK(!V8_ENABLE_SANDBOX_BOOL);
auto dispatch_handle = LoadObjectField<JSDispatchHandleT>(
function, offsetof(JSFunction, dispatch_handle_));
- TNode<Uint16T> expected_parameter_count = Uint16Constant(0);
#endif
// Apply the actual tiering. This function must uninstall the tiering builtin.
diff --git a/deps/v8/src/builtins/js-trampoline-assembler.h b/deps/v8/src/builtins/js-trampoline-assembler.h
index f0b342bb986..48b09f277d7 100644
--- a/deps/v8/src/builtins/js-trampoline-assembler.h
+++ b/deps/v8/src/builtins/js-trampoline-assembler.h
@@ -24,8 +24,7 @@ class JSTrampolineAssembler : public CodeStubAssembler {
template <typename Function>
void TieringBuiltinImpl(const Function& Impl);
-
- void CompileLazy(TNode<JSFunction> function, TNode<Context> context);
+ TNode<Uint16T> LoadIncomingParameterCount();
};
} // namespace v8::internal
diff --git a/deps/v8/src/builtins/wasm-interpreter-wrappers.tq b/deps/v8/src/builtins/wasm-interpreter-wrappers.tq
index 03362f07512..522cae914b9 100644
--- a/deps/v8/src/builtins/wasm-interpreter-wrappers.tq
+++ b/deps/v8/src/builtins/wasm-interpreter-wrappers.tq
@@ -69,11 +69,8 @@ macro LocationAllocatorForWasmInterpreterReturns(stack: RawPtr):
transitioning javascript builtin JSToWasmInterpreterWrapper(
- js-implicit context: NativeContext, receiver: JSAny, target: JSFunction,
- dispatchHandle: DispatchHandle)(...arguments): JSAny {
- // This is a generic builtin that can be installed on functions with different
- // parameter counts, so we need to support that.
- SetSupportsDynamicParameterCount(target, dispatchHandle);
+ js-implicit context: NativeContext, receiver: JSAny, target: JSFunction)(
+ ...arguments): JSAny {
const functionData = target.shared_function_info.wasm_exported_function_data;
const internalFunction = functionData.internal;
diff --git a/deps/v8/src/codegen/code-stub-assembler.cc b/deps/v8/src/codegen/code-stub-assembler.cc
index 01583c64141..ea7639ebb61 100644
--- a/deps/v8/src/codegen/code-stub-assembler.cc
+++ b/deps/v8/src/codegen/code-stub-assembler.cc
@@ -2252,6 +2252,25 @@ TNode<Uint16T> CodeStubAssembler::LoadParameterCountFromJSDispatchTable(
return Load<Uint16T>(table, offset);
}
+TNode<Uint16T> CodeStubAssembler::GetParameterCountFromDispatchHandle() {
+ // TODO(crbug.com/465487205): Until incoming JSDispatchHandles are kept alive
+ // via the stack, the parameter count must be loaded at the very start of the
+ // builtin before any runtime call or stack check can trigger a GC and sweep
+ // an unrooted dispatch table entry.
+ DCHECK(IsAtStart());
+ DCHECK(IsJSFunctionCall());
+ TNode<JSDispatchHandleT> dispatch_handle;
+#ifdef V8_JS_LINKAGE_INCLUDES_DISPATCH_HANDLE
+ dispatch_handle = GetJSDispatchHandleParameter();
+#else
+ TNode<JSFunction> function =
+ UncheckedParameter<JSFunction>(kTargetParameterIndex);
+ dispatch_handle = LoadObjectField<JSDispatchHandleT>(
+ function, offsetof(JSFunction, dispatch_handle_));
+#endif
+ return LoadParameterCountFromJSDispatchTable(dispatch_handle);
+}
+
void CodeStubAssembler::TailCallJSCode(
TNode<Code> code, TNode<Context> context, TNode<JSFunction> function,
TNode<Object> new_target, TNode<Int32T> arg_count,
@@ -2353,13 +2372,6 @@ TNode<TrustedObject> CodeStubAssembler::ResolveTrustedPointerHandle(
#endif // V8_ENABLE_SANDBOX
-void CodeStubAssembler::SetSupportsDynamicParameterCount(
- TNode<JSFunction> callee, TNode<JSDispatchHandleT> dispatch_handle) {
- TNode<Uint16T> dynamic_parameter_count =
- LoadParameterCountFromJSDispatchTable(dispatch_handle);
- SetDynamicJSParameterCount(dynamic_parameter_count);
-}
-
TNode<JSDispatchHandleT> CodeStubAssembler::InvalidDispatchHandleConstant() {
return UncheckedCast<JSDispatchHandleT>(
Uint32Constant(kInvalidDispatchHandle.value()));
@@ -20943,6 +20955,25 @@ IntegerLiteral CodeStubAssembler::ConstexprIntegerLiteralBitwiseOr(
return lhs | rhs;
}
+void CodeStubAssembler::EmitBuiltinProlog(Builtin builtin_id) {
+ if (Builtins::KindOf(builtin_id) == Builtins::TFJ) {
+ if (Builtins::IsJSTrampoline(builtin_id)) {
+ // JS trampolines (such as generic Wasm wrappers and DebugBreakTrampoline)
+ // can be installed on functions with different parameter counts and load
+ // the expected parameter count from the JSDispatchTable entry (used to
+ // clean up the caller's argument slots in PopAndReturn for Wasm wrappers,
+ // or re-verified in TailCallJSCode for DebugBreakTrampoline).
+ // TODO(crbug.com/465487205): Until incoming JSDispatchHandles are kept
+ // alive via the stack, this load must happen before the stack check
+ // below, as Runtime::kStackGuard can trigger a GC that sweeps an unrooted
+ // dispatch table entry if the JSFunction's dispatch_handle field in the
+ // heap was concurrently overwritten.
+ SetDynamicJSParameterCount(GetParameterCountFromDispatchHandle());
+ }
+ PerformStackCheck(GetJSContextParameter());
+ }
+}
+
void CodeStubAssembler::PerformStackCheck(TNode<Context> context) {
Label ok(this), stack_check_interrupt(this, Label::kDeferred);
diff --git a/deps/v8/src/codegen/code-stub-assembler.h b/deps/v8/src/codegen/code-stub-assembler.h
index 649da046747..d32b4825eee 100644
--- a/deps/v8/src/codegen/code-stub-assembler.h
+++ b/deps/v8/src/codegen/code-stub-assembler.h
@@ -4509,6 +4509,8 @@ class V8_EXPORT_PRIVATE CodeStubAssembler
// Load the parameter count of a JSDispatchTable entry.
TNode<Uint16T> LoadParameterCountFromJSDispatchTable(
TNode<JSDispatchHandleT> dispatch_handle);
+ // Load the parameter count of the incoming JS call's dispatch handle.
+ TNode<Uint16T> GetParameterCountFromDispatchHandle();
TNode<UintPtrT> ComputeJSDispatchTableEntryOffset(
TNode<JSDispatchHandleT> handle);
@@ -4539,25 +4541,6 @@ class V8_EXPORT_PRIVATE CodeStubAssembler
TNode<JSDispatchHandleT> dispatch_handle,
TNode<Uint16T> expected_parameter_count);
- // Indicate that this code must support a dynamic parameter count.
- //
- // This is used for builtins that must work on functions with different
- // parameter counts. In that case, the true JS parameter count is only known
- // at runtime and must be obtained in order to compute the total number of
- // arguments (which may include padding arguments). The parameter count is
- // subsequently available through the corresponding CodeAssembler accessors.
- // The target function object and the dispatch handle need to be passed in
- // and are used to obtain the actual parameter count of the called function.
- //
- // This should generally be invoked directly at the start of the function.
- //
- // TODO(saelo): it would be a bit nicer if this would happen automatically in
- // the function prologue for functions marked as requiring this (e.g. via the
- // call descriptor). It's not clear if that's worth the effort though for the
- // handful of builtins that need this.
- void SetSupportsDynamicParameterCount(
- TNode<JSFunction> callee, TNode<JSDispatchHandleT> dispatch_handle);
-
// Figure out the SFI's code object using its data field.
// If |data_type_out| is provided, the instance type of the function data will
// be stored in it. In case the code object is a builtin (data is a Smi),
@@ -4792,6 +4775,7 @@ class V8_EXPORT_PRIVATE CodeStubAssembler
#endif
}
+ void EmitBuiltinProlog(Builtin builtin_id);
void PerformStackCheck(TNode<Context> context);
void SetPropertyLength(TNode<Context> context, TNode<JSAny> array,
diff --git a/deps/v8/src/codegen/s390/macro-assembler-s390.cc b/deps/v8/src/codegen/s390/macro-assembler-s390.cc
index ba2b9a6df1a..a564c613987 100644
--- a/deps/v8/src/codegen/s390/macro-assembler-s390.cc
+++ b/deps/v8/src/codegen/s390/macro-assembler-s390.cc
@@ -4564,16 +4564,12 @@ void MacroAssembler::SwapFloat32(DoubleRegister src, MemOperand dst,
void MacroAssembler::SwapFloat32(MemOperand src, MemOperand dst,
DoubleRegister scratch) {
- // push d0, to be used as scratch
- lay(sp, MemOperand(sp, -kDoubleSize));
- StoreF64(d0, MemOperand(sp));
+ DCHECK(!AreAliased(scratch, kDoubleRegZero));
LoadF32(scratch, src);
- LoadF32(d0, dst);
+ LoadF32(kDoubleRegZero, dst);
StoreF32(scratch, dst);
- StoreF32(d0, src);
- // restore d0
- LoadF64(d0, MemOperand(sp));
- lay(sp, MemOperand(sp, kDoubleSize));
+ StoreF32(kDoubleRegZero, src);
+ lzdr(kDoubleRegZero);
}
void MacroAssembler::SwapDouble(DoubleRegister src, DoubleRegister dst,
@@ -4595,16 +4591,12 @@ void MacroAssembler::SwapDouble(DoubleRegister src, MemOperand dst,
void MacroAssembler::SwapDouble(MemOperand src, MemOperand dst,
DoubleRegister scratch) {
- // push d0, to be used as scratch
- lay(sp, MemOperand(sp, -kDoubleSize));
- StoreF64(d0, MemOperand(sp));
+ DCHECK(!AreAliased(scratch, kDoubleRegZero));
LoadF64(scratch, src);
- LoadF64(d0, dst);
+ LoadF64(kDoubleRegZero, dst);
StoreF64(scratch, dst);
- StoreF64(d0, src);
- // restore d0
- LoadF64(d0, MemOperand(sp));
- lay(sp, MemOperand(sp, kDoubleSize));
+ StoreF64(kDoubleRegZero, src);
+ lzdr(kDoubleRegZero);
}
void MacroAssembler::SwapSimd128(Simd128Register src, Simd128Register dst,
@@ -4625,16 +4617,13 @@ void MacroAssembler::SwapSimd128(Simd128Register src, MemOperand dst,
void MacroAssembler::SwapSimd128(MemOperand src, MemOperand dst,
Simd128Register scratch) {
- // push d0, to be used as scratch
- lay(sp, MemOperand(sp, -kSimd128Size));
- StoreV128(d0, MemOperand(sp), ip);
+ DCHECK(!AreAliased(scratch, kDoubleRegZero));
LoadV128(scratch, src, ip);
- LoadV128(d0, dst, ip);
+ LoadV128(kDoubleRegZero, dst, ip);
StoreV128(scratch, dst, ip);
- StoreV128(d0, src, ip);
- // restore d0
- LoadV128(d0, MemOperand(sp), ip);
- lay(sp, MemOperand(sp, kSimd128Size));
+ StoreV128(kDoubleRegZero, src, ip);
+ vx(kDoubleRegZero, kDoubleRegZero, kDoubleRegZero, Condition(0), Condition(0),
+ Condition(0));
}
void MacroAssembler::ComputeCodeStartAddress(Register dst) {
diff --git a/deps/v8/src/codegen/turboshaft-builtins-assembler-inl.h b/deps/v8/src/codegen/turboshaft-builtins-assembler-inl.h
index 38c1626d22b..b28f96d650d 100644
--- a/deps/v8/src/codegen/turboshaft-builtins-assembler-inl.h
+++ b/deps/v8/src/codegen/turboshaft-builtins-assembler-inl.h
@@ -540,6 +540,10 @@ class BuiltinsReducer : public Next {
// TODO(nicohartmann): CSA tracks some debug information here.
// Emit stack check.
if (Builtins::KindOf(builtin_id) == Builtins::TFJ_TSA) {
+ // JS trampolines require loading the dynamic JS parameter count before
+ // the stack check (see CodeStubAssembler::EmitBuiltinProlog) and are not
+ // currently supported in TSA.
+ DCHECK(!Builtins::IsJSTrampoline(builtin_id));
__ PerformStackCheck(__ JSContextParameter());
}
}
diff --git a/deps/v8/src/compiler/backend/gap-resolver.cc b/deps/v8/src/compiler/backend/gap-resolver.cc
index dd7ab756027..af940a705ba 100644
--- a/deps/v8/src/compiler/backend/gap-resolver.cc
+++ b/deps/v8/src/compiler/backend/gap-resolver.cc
@@ -25,6 +25,19 @@ MoveOperandKind GetKind(const InstructionOperand& move) {
return IsFloatingPoint(loc_op.representation()) ? kFpReg : kGpReg;
}
+// Returns the wider in-register GP representation (matching Is32BitOperand in
+// 64-bit backends' Use32BitMove helpers).
+MachineRepresentation WiderGpRepresentation(const InstructionOperand& src,
+ const InstructionOperand& dst) {
+ MachineRepresentation src_rep = LocationOperand::cast(src).representation();
+ if constexpr (kSystemPointerSize == 8) {
+ if (Is32BitOperand(src)) {
+ return LocationOperand::cast(dst).representation();
+ }
+ }
+ return src_rep;
+}
+
} // namespace
void GapResolver::Resolve(ParallelMove* moves) {
@@ -116,15 +129,26 @@ void GapResolver::PerformCycle(const std::vector<MoveOperands*>& cycle) {
// {MoveToTempLocation} will then choose the location accordingly.
MachineRepresentation src_rep =
LocationOperand::cast(move1->source()).representation();
- MachineRepresentation dst_rep =
- LocationOperand::cast(move1->destination()).representation();
- // Floating-point moves may have mixed representations (e.g. from same-as-
- // input SIMD splat/extract instructions or identity moves). Size the
- // temporary by the source representation so that Push and Pop agree on the
- // number of stack slots and wider sources preserve upper lanes in registers.
- // General-purpose moves keep the destination representation because 32-bit
- // sources may hold 64-bit values due to virtual register renaming.
- MachineRepresentation rep = IsFloatingPoint(src_rep) ? src_rep : dst_rep;
+ // Splitting {source -> destination} into {source -> temp[rep]} followed by
+ // {temp[rep] -> destination} must preserve all live bits of {source} in
+ // {temp} and match the width behavior of a direct {source -> destination}
+ // move:
+ // - For FP/SIMD, {source} never holds valid bits wider than {src_rep} (and
+ // {Push} sizes stack temporaries from {src_rep}), so {rep = src_rep}
+ // preserves all bits in {temp}, makes {temp[src_rep] -> destination} match
+ // a direct move, and keeps {Push} and {Pop} balanced.
+ // - For GP on 64-bit targets, virtual register renaming allows a 32-bit
+ // source to hold a zero-extended 64-bit value when {dst_rep} is 64-bit (so
+ // {source -> temp[rep]} needs a 64-bit {rep}), while same-as-input
+ // instructions such as x64 64-bit shifts with a 32-bit output require a
+ // 64-bit source to keep its upper bits into a 32-bit destination (so
+ // {temp[rep] -> destination} also needs a 64-bit {rep}). Choosing the wider
+ // GP representation satisfies both legs and matches {Use32BitMove(source,
+ // destination)}.
+ MachineRepresentation rep =
+ IsFloatingPoint(src_rep)
+ ? src_rep
+ : WiderGpRepresentation(move1->source(), move1->destination());
DCHECK_EQ(ElementSizeInPointers(src_rep), ElementSizeInPointers(rep));
for (size_t i = 0; i < cycle.size() - 1; ++i) {
assembler_->SetPendingMove(cycle[i]);
diff --git a/deps/v8/src/compiler/backend/instruction.cc b/deps/v8/src/compiler/backend/instruction.cc
index 5390a91d058..eb28b785452 100644
--- a/deps/v8/src/compiler/backend/instruction.cc
+++ b/deps/v8/src/compiler/backend/instruction.cc
@@ -9,7 +9,6 @@
#include "src/base/iterator.h"
#include "src/base/logging.h"
-#include "src/codegen/aligned-slot-allocator.h"
#include "src/codegen/interface-descriptors.h"
#include "src/codegen/machine-type.h"
#include "src/codegen/register-configuration.h"
@@ -90,55 +89,34 @@ FlagsCondition CommuteFlagsCondition(FlagsCondition condition) {
UNREACHABLE();
}
-bool InstructionOperand::InterferesWith(const InstructionOperand& other) const {
- const bool combine_fp_aliasing = kFPAliasing == AliasingKind::kCombine &&
- this->IsFPLocationOperand() &&
- other.IsFPLocationOperand();
- const bool stack_slots = this->IsAnyStackSlot() && other.IsAnyStackSlot();
- if (!combine_fp_aliasing && !stack_slots) {
- return EqualsCanonicalized(other);
- }
- const LocationOperand& loc = *LocationOperand::cast(this);
- const LocationOperand& other_loc = LocationOperand::cast(other);
- MachineRepresentation rep = loc.representation();
- MachineRepresentation other_rep = other_loc.representation();
- LocationOperand::LocationKind kind = loc.location_kind();
- LocationOperand::LocationKind other_kind = other_loc.location_kind();
- if (kind != other_kind) return false;
-
- if (combine_fp_aliasing && !stack_slots) {
+bool InstructionOperand::InterferesWithSlow(
+ const InstructionOperand& other) const {
+ DCHECK(HasComplexAliasing() || other.HasComplexAliasing());
+ if (kFPAliasing == AliasingKind::kCombine && IsFPRegister() &&
+ other.IsFPRegister()) {
+ const LocationOperand& loc = *LocationOperand::cast(this);
+ const LocationOperand& other_loc = LocationOperand::cast(other);
+ MachineRepresentation rep = loc.representation();
+ MachineRepresentation other_rep = other_loc.representation();
if (rep == other_rep) return EqualsCanonicalized(other);
- DCHECK_EQ(kind, LocationOperand::REGISTER);
// FP register-register interference.
return GetRegConfig()->AreAliases(rep, loc.register_code(), other_rep,
other_loc.register_code());
}
-
- DCHECK(stack_slots);
- int num_slots =
- AlignedSlotAllocator::NumSlotsForWidth(ElementSizeInBytes(rep));
- int num_slots_other =
- AlignedSlotAllocator::NumSlotsForWidth(ElementSizeInBytes(other_rep));
- const bool complex_stack_slot_interference =
- (num_slots > 1 || num_slots_other > 1);
- if (!complex_stack_slot_interference) {
- return EqualsCanonicalized(other);
+ if (IsAnyStackSlot() && other.IsAnyStackSlot()) {
+ // Complex multi-slot operand interference:
+ // - slots of different FP reps can alias because the gap resolver may break
+ // a move into 2 or 4 equivalent smaller moves,
+ // - stack layout can be rearranged for tail calls.
+ const LocationOperand& loc = *LocationOperand::cast(this);
+ const LocationOperand& other_loc = LocationOperand::cast(other);
+ int index_hi = loc.index();
+ int index_lo = index_hi - loc.NumStackSlots() + 1;
+ int other_index_hi = other_loc.index();
+ int other_index_lo = other_index_hi - other_loc.NumStackSlots() + 1;
+ return other_index_hi >= index_lo && index_hi >= other_index_lo;
}
-
- // Complex multi-slot operand interference:
- // - slots of different FP reps can alias because the gap resolver may break a
- // move into 2 or 4 equivalent smaller moves,
- // - stack layout can be rearranged for tail calls
- DCHECK_EQ(LocationOperand::STACK_SLOT, kind);
- int index_hi = loc.index();
- int index_lo =
- index_hi -
- AlignedSlotAllocator::NumSlotsForWidth(ElementSizeInBytes(rep)) + 1;
- int other_index_hi = other_loc.index();
- int other_index_lo =
- other_index_hi -
- AlignedSlotAllocator::NumSlotsForWidth(ElementSizeInBytes(other_rep)) + 1;
- return other_index_hi >= index_lo && index_hi >= other_index_lo;
+ return false;
}
bool LocationOperand::IsCompatible(LocationOperand* op) {
@@ -337,8 +315,8 @@ bool ParallelMove::IsRedundant() const {
void ParallelMove::PrepareInsertAfter(
MoveOperands* move, ZoneVector<MoveOperands*>* to_eliminate) const {
- bool no_aliasing = kFPAliasing != AliasingKind::kCombine ||
- !move->destination().IsFPLocationOperand();
+ if (move->IsRedundant()) return;
+ bool no_aliasing = !move->destination().HasComplexAliasing();
MoveOperands* replacement = nullptr;
MoveOperands* eliminated = nullptr;
for (MoveOperands* curr : *this) {
@@ -349,7 +327,11 @@ void ParallelMove::PrepareInsertAfter(
DCHECK(!replacement);
replacement = curr;
if (no_aliasing && eliminated != nullptr) break;
- } else if (curr->destination().InterferesWith(move->destination())) {
+ }
+ // Not `else if`: a multi-slot stack operand can both match `move`'s source
+ // and interfere with `move`'s destination if `move` shifts it by a partial
+ // width (e.g., `[fp_stack:2|s128] = [fp_stack:1|s128]` overlaps on slot 1).
+ if (curr->destination().InterferesWith(move->destination())) {
// We can eliminate curr, since move overwrites at least a part of its
// destination, implying its value is no longer live.
eliminated = curr;
diff --git a/deps/v8/src/compiler/backend/instruction.h b/deps/v8/src/compiler/backend/instruction.h
index 57fa5cbea54..37354d0586f 100644
--- a/deps/v8/src/compiler/backend/instruction.h
+++ b/deps/v8/src/compiler/backend/instruction.h
@@ -148,7 +148,8 @@ class V8_EXPORT_PRIVATE INSTRUCTION_OPERAND_ALIGN InstructionOperand {
return this->GetCanonicalizedValue() < that.GetCanonicalizedValue();
}
- bool InterferesWith(const InstructionOperand& other) const;
+ inline bool HasComplexAliasing() const;
+ inline bool InterferesWith(const InstructionOperand& other) const;
// APIs to aid debugging. For general-stream APIs, use operator<<.
void Print() const;
@@ -168,6 +169,9 @@ class V8_EXPORT_PRIVATE INSTRUCTION_OPERAND_ALIGN InstructionOperand {
using KindField = base::BitField64<Kind, 0, 3>;
uint64_t value_;
+
+ private:
+ bool InterferesWithSlow(const InstructionOperand& other) const;
};
using InstructionOperandVector = ZoneVector<InstructionOperand>;
@@ -574,6 +578,11 @@ class LocationOperand : public InstructionOperand {
return RepresentationField::decode(value_);
}
+ int NumStackSlots() const {
+ DCHECK(IsAnyStackSlot());
+ return ElementSizeInPointers(representation());
+ }
+
static bool IsSupportedRepresentation(MachineRepresentation rep) {
switch (rep) {
case MachineRepresentation::kWord32:
@@ -796,6 +805,36 @@ uint64_t InstructionOperand::GetCanonicalizedValue() const {
return this->value_;
}
+bool InstructionOperand::HasComplexAliasing() const {
+ return (kFPAliasing == AliasingKind::kCombine && IsFPRegister()) ||
+ (IsAnyStackSlot() && LocationOperand::cast(*this).NumStackSlots() > 1);
+}
+
+bool InstructionOperand::InterferesWith(const InstructionOperand& other) const {
+ if (V8_LIKELY(!HasComplexAliasing() && !other.HasComplexAliasing())) {
+ return EqualsCanonicalized(other);
+ }
+ return InterferesWithSlow(other);
+}
+
+// Returns whether a general-purpose {LocationOperand} (register or stack slot)
+// has a 32-bit representation. Note that {ElementSizeInBytes} cannot be used
+// here because under pointer compression {kTagged*} and {kProtectedPointer}
+// have 4-byte on-heap size but occupy full 64-bit registers and stack slots on
+// 64-bit targets.
+inline bool Is32BitOperand(const InstructionOperand& operand) {
+ DCHECK(operand.IsLocationOperand());
+ MachineRepresentation rep = LocationOperand::cast(operand).representation();
+ if constexpr (kSystemPointerSize == 4) {
+ return rep != MachineRepresentation::kWord64;
+ }
+ return rep == MachineRepresentation::kWord32 || IsAnyCompressed(rep);
+}
+
+inline bool Is32BitOperand(const InstructionOperand* operand) {
+ return Is32BitOperand(*operand);
+}
+
// Required for maps that don't care about machine type.
struct CompareOperandModuloType {
bool operator()(const InstructionOperand& a,
@@ -1845,10 +1884,10 @@ class V8_EXPORT_PRIVATE InstructionBlock final
uint64_t pgo_execution_count_ = 0;
#endif
RpoNumber dominator_;
- int32_t code_start_; // start index of arch-specific code.
- int32_t code_end_ = -1; // end index of arch-specific code.
- const bool deferred_ : 1; // Block contains deferred code.
- bool handler_ : 1; // Block is a handler entry point.
+ int32_t code_start_; // start index of arch-specific code.
+ int32_t code_end_ = -1; // end index of arch-specific code.
+ const bool deferred_ : 1; // Block contains deferred code.
+ bool handler_ : 1; // Block is a handler entry point.
bool table_switch_target_ : 1; // Block is a table switch target, implying an
// indirect jump.
bool align_switch_targets_ : 1; // insert switch target alignment before
diff --git a/deps/v8/src/compiler/backend/loong64/code-generator-loong64.cc b/deps/v8/src/compiler/backend/loong64/code-generator-loong64.cc
index 29f2689c829..3616f2a977f 100644
--- a/deps/v8/src/compiler/backend/loong64/code-generator-loong64.cc
+++ b/deps/v8/src/compiler/backend/loong64/code-generator-loong64.cc
@@ -5522,14 +5522,6 @@ void CodeGenerator::SetPendingMove(MoveOperands* move) {
namespace {
-bool Is32BitOperand(InstructionOperand* operand) {
- DCHECK(operand->IsStackSlot() || operand->IsRegister());
- MachineRepresentation mr = LocationOperand::cast(operand)->representation();
- return mr == MachineRepresentation::kWord32 ||
- mr == MachineRepresentation::kCompressed ||
- mr == MachineRepresentation::kCompressedPointer;
-}
-
// When we need only 32 bits, move only 32 bits, otherwise the destination
// register' upper 32 bits may contain dirty data.
bool Use32BitMove(InstructionOperand* source, InstructionOperand* destination) {
diff --git a/deps/v8/src/compiler/backend/mips64/code-generator-mips64.cc b/deps/v8/src/compiler/backend/mips64/code-generator-mips64.cc
index 98ede0190bd..80d9530fb6d 100644
--- a/deps/v8/src/compiler/backend/mips64/code-generator-mips64.cc
+++ b/deps/v8/src/compiler/backend/mips64/code-generator-mips64.cc
@@ -4648,14 +4648,6 @@ void CodeGenerator::SetPendingMove(MoveOperands* move) {
namespace {
-bool Is32BitOperand(InstructionOperand* operand) {
- DCHECK(operand->IsStackSlot() || operand->IsRegister());
- MachineRepresentation mr = LocationOperand::cast(operand)->representation();
- return mr == MachineRepresentation::kWord32 ||
- mr == MachineRepresentation::kCompressed ||
- mr == MachineRepresentation::kCompressedPointer;
-}
-
// When we need only 32 bits, move only 32 bits, otherwise the destination
// register' upper 32 bits may contain dirty data.
bool Use32BitMove(InstructionOperand* source, InstructionOperand* destination) {
diff --git a/deps/v8/src/compiler/backend/move-optimizer.cc b/deps/v8/src/compiler/backend/move-optimizer.cc
index f80c453efca..f3d64007b93 100644
--- a/deps/v8/src/compiler/backend/move-optimizer.cc
+++ b/deps/v8/src/compiler/backend/move-optimizer.cc
@@ -4,8 +4,6 @@
#include "src/compiler/backend/move-optimizer.h"
-#include "src/codegen/register-configuration.h"
-
#if V8_TARGET_ARCH_ARM64
#include "src/codegen/macro-assembler.h"
#endif
@@ -33,84 +31,21 @@ struct MoveKey {
class OperandSet {
public:
- explicit OperandSet(ZoneVector<InstructionOperand>* buffer)
- : set_(buffer), fp_reps_(0) {
+ explicit OperandSet(ZoneVector<InstructionOperand>* buffer) : set_(buffer) {
buffer->clear();
}
- void InsertOp(const InstructionOperand& op) {
- set_->push_back(op);
-
- if (kFPAliasing == AliasingKind::kCombine && op.IsFPRegister()) {
- fp_reps_ |= RepresentationBit(LocationOperand::cast(op).representation());
- }
- }
-
- bool Contains(const InstructionOperand& op) const {
- for (const InstructionOperand& elem : *set_) {
- if (elem.EqualsCanonicalized(op)) return true;
- }
- return false;
- }
+ void InsertOp(const InstructionOperand& op) { set_->push_back(op); }
bool ContainsOpOrAlias(const InstructionOperand& op) const {
- if (Contains(op)) return true;
-
- if (kFPAliasing == AliasingKind::kCombine && op.IsFPRegister()) {
- // Platforms where FP registers have complex aliasing need extra checks.
- const LocationOperand& loc = LocationOperand::cast(op);
- MachineRepresentation rep = loc.representation();
- // If haven't encountered mixed rep FP registers, skip the extra checks.
- if (!HasMixedFPReps(fp_reps_ | RepresentationBit(rep))) return false;
-
- // Check register against aliasing registers of other FP representations.
- MachineRepresentation other_rep1, other_rep2;
- switch (rep) {
- case MachineRepresentation::kFloat32:
- other_rep1 = MachineRepresentation::kFloat64;
- other_rep2 = MachineRepresentation::kSimd128;
- break;
- case MachineRepresentation::kFloat64:
- other_rep1 = MachineRepresentation::kFloat32;
- other_rep2 = MachineRepresentation::kSimd128;
- break;
- case MachineRepresentation::kSimd128:
- other_rep1 = MachineRepresentation::kFloat32;
- other_rep2 = MachineRepresentation::kFloat64;
- break;
- default:
- UNREACHABLE();
- }
- const RegisterConfiguration* config = RegisterConfiguration::Default();
- int base = -1;
- int aliases =
- config->GetAliases(rep, loc.register_code(), other_rep1, &base);
- DCHECK(aliases > 0 || (aliases == 0 && base == -1));
- while (aliases--) {
- if (Contains(AllocatedOperand(LocationOperand::REGISTER, other_rep1,
- base + aliases))) {
- return true;
- }
- }
- aliases = config->GetAliases(rep, loc.register_code(), other_rep2, &base);
- DCHECK(aliases > 0 || (aliases == 0 && base == -1));
- while (aliases--) {
- if (Contains(AllocatedOperand(LocationOperand::REGISTER, other_rep2,
- base + aliases))) {
- return true;
- }
- }
+ for (const InstructionOperand& elem : *set_) {
+ if (elem.InterferesWith(op)) return true;
}
return false;
}
private:
- static bool HasMixedFPReps(int reps) {
- return reps && !base::bits::IsPowerOfTwo(reps);
- }
-
ZoneVector<InstructionOperand>* set_;
- int fp_reps_;
};
int FindFirstNonEmptySlot(const Instruction* instr) {
diff --git a/deps/v8/src/compiler/backend/register-allocator-verifier.cc b/deps/v8/src/compiler/backend/register-allocator-verifier.cc
index e607dc7afb2..76551852e33 100644
--- a/deps/v8/src/compiler/backend/register-allocator-verifier.cc
+++ b/deps/v8/src/compiler/backend/register-allocator-verifier.cc
@@ -4,6 +4,7 @@
#include "src/compiler/backend/register-allocator-verifier.h"
+#include <algorithm>
#include <optional>
#include "src/compiler/backend/instruction.h"
@@ -276,6 +277,33 @@ void RegisterAllocatorVerifier::CheckConstraint(
UNREACHABLE();
}
+void BlockAssessments::DropInterferingStackSlots(InstructionOperand op) {
+ DCHECK(op.IsAnyStackSlot());
+ const LocationOperand& loc = LocationOperand::cast(op);
+ int num_slots = loc.NumStackSlots();
+ max_stack_slot_width_ = std::max(max_stack_slot_width_, num_slots);
+ int index = loc.index();
+ map_.erase(op);
+ stale_ref_stack_slots_.erase(op);
+ // Erase any stack slots at lower indices covered by `op`.
+ for (int i = index - num_slots + 1; i < index; ++i) {
+ AllocatedOperand probe(LocationOperand::STACK_SLOT,
+ MachineRepresentation::kWord32, i);
+ map_.erase(probe);
+ stale_ref_stack_slots_.erase(probe);
+ }
+ // Erase any wider stack slots anchored at higher indices that overlap `op`.
+ for (int i = index + 1; i < index + max_stack_slot_width_; ++i) {
+ AllocatedOperand probe(LocationOperand::STACK_SLOT,
+ MachineRepresentation::kWord32, i);
+ auto it = map_.find(probe);
+ if (it != map_.end() && it->first.InterferesWith(op)) {
+ stale_ref_stack_slots_.erase(it->first);
+ map_.erase(it);
+ }
+ }
+}
+
void BlockAssessments::PerformMoves(const Instruction* instruction) {
const ParallelMove* first =
instruction->GetParallelMove(Instruction::GapPosition::START);
@@ -289,28 +317,36 @@ void BlockAssessments::PerformParallelMoves(const ParallelMove* moves) {
if (moves == nullptr) return;
CHECK(map_for_moves_.empty());
+ bool has_complex_dest = false;
for (MoveOperands* move : *moves) {
if (move->IsEliminated() || move->IsRedundant()) continue;
auto it = map_.find(move->source());
// The RHS of a parallel move should have been already assessed.
CHECK(it != map_.end());
// The LHS of a parallel move should not have been assigned in this
- // parallel move.
- CHECK(map_for_moves_.find(move->destination()) == map_for_moves_.end());
+ // parallel move, nor interfere with any other destination in this parallel
+ // move.
+ const InstructionOperand& dest = move->destination();
+ CHECK(map_for_moves_.find(dest) == map_for_moves_.end());
+ has_complex_dest = has_complex_dest || dest.HasComplexAliasing();
+ if (has_complex_dest) {
+ for (const auto& prev : map_for_moves_) {
+ CHECK(!prev.first.InterferesWith(dest));
+ }
+ }
// The RHS of a parallel move should not be a stale reference.
CHECK(!IsStaleReferenceStackSlot(move->source()));
// Copy the assessment to the destination.
- map_for_moves_[move->destination()] = it->second;
+ map_for_moves_[dest] = it->second;
}
- for (auto pair : map_for_moves_) {
+ for (const auto& pair : map_for_moves_) {
+ Drop(pair.first);
+ }
+ for (const auto& pair : map_for_moves_) {
// Re-insert the existing key for the new assignment so that it has the
// correct representation (which is ignored by the canonicalizing map
// comparator).
- InstructionOperand op = pair.first;
- map_.erase(op);
map_.insert(pair);
- // Destination is no longer a stale reference.
- stale_ref_stack_slots().erase(op);
}
map_for_moves_.clear();
}
@@ -414,11 +450,19 @@ BlockAssessments* RegisterAllocatorVerifier::CreateForBlock(
}
const BlockAssessments* pred_assessments = iterator->second;
CHECK_NOT_NULL(pred_assessments);
+ ret->UpdateMaxStackSlotWidth(pred_assessments->max_stack_slot_width());
for (auto pair : pred_assessments->map()) {
InstructionOperand operand = pair.first;
- if (ret->map().find(operand) == ret->map().end()) {
+ auto existing = ret->map().find(operand);
+ if (existing == ret->map().end()) {
ret->map().insert(std::make_pair(
operand, zone()->New<PendingAssessment>(zone(), block, operand)));
+ } else if (operand.IsAnyStackSlot() &&
+ LocationOperand::cast(operand).NumStackSlots() >
+ LocationOperand::cast(existing->first).NumStackSlots()) {
+ Assessment* assessment = existing->second;
+ ret->map().erase(existing);
+ ret->map().insert(std::make_pair(operand, assessment));
}
}
diff --git a/deps/v8/src/compiler/backend/register-allocator-verifier.h b/deps/v8/src/compiler/backend/register-allocator-verifier.h
index a7684d81708..072d531061f 100644
--- a/deps/v8/src/compiler/backend/register-allocator-verifier.h
+++ b/deps/v8/src/compiler/backend/register-allocator-verifier.h
@@ -133,7 +133,8 @@ struct OperandAsKeyLess {
};
// Assessments associated with a basic block.
-class BlockAssessments : public ZoneObject {
+class V8_EXPORT_PRIVATE BlockAssessments
+ : public NON_EXPORTED_BASE(ZoneObject) {
public:
using OperandMap = ZoneMap<InstructionOperand, Assessment*, OperandAsKeyLess>;
using OperandSet = ZoneSet<InstructionOperand, OperandAsKeyLess>;
@@ -149,17 +150,26 @@ class BlockAssessments : public ZoneObject {
BlockAssessments& operator=(const BlockAssessments&) = delete;
void Drop(InstructionOperand operand) {
+ if (operand.IsAnyStackSlot()) {
+ DropInterferingStackSlots(operand);
+ return;
+ }
map_.erase(operand);
stale_ref_stack_slots_.erase(operand);
}
+ void DropInterferingStackSlots(InstructionOperand operand);
void DropRegisters();
void AddDefinition(InstructionOperand operand, int virtual_register) {
- auto existent = map_.find(operand);
- if (existent != map_.end()) {
- // Drop the assignment
- map_.erase(existent);
- // Destination operand is no longer a stale reference.
- stale_ref_stack_slots_.erase(operand);
+ if (operand.IsAnyStackSlot()) {
+ DropInterferingStackSlots(operand);
+ } else {
+ auto existent = map_.find(operand);
+ if (existent != map_.end()) {
+ // Drop the assignment
+ map_.erase(existent);
+ // Destination operand is no longer a stale reference.
+ stale_ref_stack_slots_.erase(operand);
+ }
}
map_.insert(
std::make_pair(operand, zone_->New<FinalAssessment>(virtual_register)));
@@ -174,6 +184,11 @@ class BlockAssessments : public ZoneObject {
map_.insert(other->map_.begin(), other->map_.end());
stale_ref_stack_slots_.insert(other->stale_ref_stack_slots_.begin(),
other->stale_ref_stack_slots_.end());
+ max_stack_slot_width_ = other->max_stack_slot_width_;
+ }
+ int max_stack_slot_width() const { return max_stack_slot_width_; }
+ void UpdateMaxStackSlotWidth(int width) {
+ max_stack_slot_width_ = std::max(max_stack_slot_width_, width);
}
void CheckReferenceMap(const ReferenceMap* reference_map);
bool IsStaleReferenceStackSlot(InstructionOperand op,
@@ -198,6 +213,7 @@ class BlockAssessments : public ZoneObject {
// implications of a stack slot being stale?
OperandSet stale_ref_stack_slots_;
int spill_slot_delta_;
+ int max_stack_slot_width_ = 1;
Zone* zone_;
const InstructionSequence* sequence_;
};
diff --git a/deps/v8/src/compiler/backend/register-allocator.cc b/deps/v8/src/compiler/backend/register-allocator.cc
index 3e71083556d..476214011a9 100644
--- a/deps/v8/src/compiler/backend/register-allocator.cc
+++ b/deps/v8/src/compiler/backend/register-allocator.cc
@@ -1701,6 +1701,9 @@ void ConstraintBuilder::MeetConstraintsBefore(int instr_index) {
input_vreg);
// Spill at every use position for simplicity, this case is very rare.
data()->AddGapMove(instr_index, Instruction::END, input_copy, *slot);
+ if (second->HasReferenceMap() && code()->IsReference(input_vreg)) {
+ second->reference_map()->RecordReference(*slot);
+ }
spilled_consts->push_back(range);
}
}
diff --git a/deps/v8/src/compiler/backend/riscv/code-generator-riscv.cc b/deps/v8/src/compiler/backend/riscv/code-generator-riscv.cc
index fb1cb846894..767230699b9 100644
--- a/deps/v8/src/compiler/backend/riscv/code-generator-riscv.cc
+++ b/deps/v8/src/compiler/backend/riscv/code-generator-riscv.cc
@@ -5796,13 +5796,6 @@ void CodeGenerator::SetPendingMove(MoveOperands* move) {
}
namespace {
-bool Is32BitOperand(InstructionOperand* operand) {
- DCHECK(operand->IsStackSlot() || operand->IsRegister());
- MachineRepresentation mr = LocationOperand::cast(operand)->representation();
- return mr == MachineRepresentation::kWord32 ||
- mr == MachineRepresentation::kCompressed ||
- mr == MachineRepresentation::kCompressedPointer;
-}
// When we need only 32 bits, move only 32 bits, otherwise the destination
// register' upper 32 bits may contain dirty data.
diff --git a/deps/v8/src/compiler/backend/x64/code-generator-x64.cc b/deps/v8/src/compiler/backend/x64/code-generator-x64.cc
index d69787f557b..fcdfc21f347 100644
--- a/deps/v8/src/compiler/backend/x64/code-generator-x64.cc
+++ b/deps/v8/src/compiler/backend/x64/code-generator-x64.cc
@@ -8856,14 +8856,6 @@ void CodeGenerator::SetPendingMove(MoveOperands* move) {
namespace {
-bool Is32BitOperand(InstructionOperand* operand) {
- DCHECK(operand->IsStackSlot() || operand->IsRegister());
- MachineRepresentation mr = LocationOperand::cast(operand)->representation();
- return mr == MachineRepresentation::kWord32 ||
- mr == MachineRepresentation::kCompressed ||
- mr == MachineRepresentation::kCompressedPointer;
-}
-
// When we need only 32 bits, move only 32 bits. Benefits:
// - Save a byte here and there (depending on the destination
// register; "movl eax, ..." is smaller than "movq rax, ...").
diff --git a/deps/v8/src/compiler/code-assembler.cc b/deps/v8/src/compiler/code-assembler.cc
index 86afaddf3ad..05b5f211f82 100644
--- a/deps/v8/src/compiler/code-assembler.cc
+++ b/deps/v8/src/compiler/code-assembler.cc
@@ -520,6 +520,21 @@ TNode<Context> CodeAssembler::GetJSContextParameter() {
static_cast<int>(call_descriptor->JSParameterCount())));
}
+#ifdef V8_JS_LINKAGE_INCLUDES_DISPATCH_HANDLE
+TNode<JSDispatchHandleT> CodeAssembler::GetJSDispatchHandleParameter() {
+ auto call_descriptor = raw_assembler()->call_descriptor();
+ DCHECK(call_descriptor->IsJSFunctionCall());
+ // In JS call descriptors, implicit register parameters (new.target, argc,
+ // dispatch_handle, context) are indexed immediately after the formal JS stack
+ // parameters (0 .. JSParameterCount() - 1).
+ return UncheckedParameter<JSDispatchHandleT>(
+ Linkage::GetJSCallDispatchHandleParamIndex(
+ static_cast<int>(call_descriptor->JSParameterCount())));
+}
+#endif
+
+bool CodeAssembler::IsAtStart() const { return raw_assembler()->IsAtStart(); }
+
bool CodeAssembler::HasDynamicJSParameterCount() {
return raw_assembler()->dynamic_js_parameter_count() != nullptr;
}
@@ -531,14 +546,12 @@ TNode<Uint16T> CodeAssembler::DynamicJSParameterCount() {
void CodeAssembler::SetDynamicJSParameterCount(TNode<Uint16T> parameter_count) {
DCHECK(!HasDynamicJSParameterCount());
- // For code to support a dynamic parameter count, it's static parameter count
- // must currently be zero, i.e. varargs. Otherwise we'd also need to ensure
- // that the dynamic parameter count is not smaller than the static one.
- //
- // TODO(saelo): it would probably be a bit nicer if we could assert here that
- // IsJSFunctionCall() is true and then use the JSParameterCount() of the
- // descriptor instead, but that doesn't work because not all users of this
- // feature are TFJ builtins (some are TFC builtins).
+ DCHECK(IsJSFunctionCall());
+ // For code to support a dynamic parameter count, its static parameter count
+ // must currently be zero (kDontAdaptArgumentsSentinel), i.e. varargs.
+ // Otherwise we'd also need to ensure that the dynamic parameter count is not
+ // smaller than the static one.
+ DCHECK_EQ(raw_assembler()->call_descriptor()->JSParameterCount(), 0);
DCHECK_EQ(raw_assembler()->call_descriptor()->ParameterSlotCount(), 0);
raw_assembler()->set_dynamic_js_parameter_count(parameter_count);
}
diff --git a/deps/v8/src/compiler/code-assembler.h b/deps/v8/src/compiler/code-assembler.h
index 28631548188..2287e334c8b 100644
--- a/deps/v8/src/compiler/code-assembler.h
+++ b/deps/v8/src/compiler/code-assembler.h
@@ -729,6 +729,8 @@ class V8_EXPORT_PRIVATE CodeAssembler {
return UncheckedCast<UintPtrT>(x);
}
+ bool IsAtStart() const;
+
// Support for code with a "dynamic" parameter count.
//
// Code assembled by our code assembler always has a "static" parameter count
@@ -738,9 +740,9 @@ class V8_EXPORT_PRIVATE CodeAssembler {
// objects with different parameter counts. In that case, the actual
// parameter count is only known at runtime. Examples of such builtins
// include the CompileLazy builtin and the InterpreterEntryTrampoline, or the
- // generic JSToWasm and JSToJS wrappers. These builtins then may have to
- // obtain the "dynamic" parameter count, for example to correctly remove all
- // function arguments (including padding arguments) from the stack.
+ // generic JSToWasm wrappers. These builtins then may have to obtain the
+ // "dynamic" parameter count, for example to correctly remove all function
+ // arguments (including padding arguments) from the stack.
bool HasDynamicJSParameterCount();
TNode<Uint16T> DynamicJSParameterCount();
void SetDynamicJSParameterCount(TNode<Uint16T> parameter_count);
@@ -777,6 +779,9 @@ class V8_EXPORT_PRIVATE CodeAssembler {
Node* UntypedParameter(int value);
TNode<Context> GetJSContextParameter();
+#ifdef V8_JS_LINKAGE_INCLUDES_DISPATCH_HANDLE
+ TNode<JSDispatchHandleT> GetJSDispatchHandleParameter();
+#endif
void Return(TNode<Object> value);
void Return(TNode<Object> value1, TNode<Object> value2);
void Return(TNode<Object> value1, TNode<Object> value2, TNode<Object> value3);
diff --git a/deps/v8/src/compiler/common-operator-reducer.cc b/deps/v8/src/compiler/common-operator-reducer.cc
index b0f327ecf70..acaf3334c2f 100644
--- a/deps/v8/src/compiler/common-operator-reducer.cc
+++ b/deps/v8/src/compiler/common-operator-reducer.cc
@@ -312,8 +312,19 @@ Reduction CommonOperatorReducer::ReducePhi(Node* node) {
if (machine()->Word32Select().IsSupported()) {
// Select positive value with conditional move if is supported.
+ // If {vfalse}'s left input (0) is wrapped in a value identity
+ // (e.g. TypeGuard pinned inside {if_false}), we cannot reuse
+ // {vfalse} directly at {merge} as doing so would hoist it out of
+ // {if_false}. Create a fresh Int32Sub using the unwrapped
+ // constant instead.
+ Node* false_value = vfalse;
+ if (NodeProperties::IsValueIdentity(mvfalse.left().node())) {
+ Node* zero = graph()->NewNode(common()->Int32Constant(0));
+ false_value =
+ graph()->NewNode(machine()->Int32Sub(), zero, vtrue);
+ }
Node* abs = graph()->NewNode(machine()->Word32Select().op(), cond,
- vtrue, vfalse);
+ vtrue, false_value);
return Replace(abs);
} else {
// Generate absolute integer value.
diff --git a/deps/v8/src/compiler/common-operator.h b/deps/v8/src/compiler/common-operator.h
index 1a0abe59b9d..d03d4108bae 100644
--- a/deps/v8/src/compiler/common-operator.h
+++ b/deps/v8/src/compiler/common-operator.h
@@ -755,7 +755,8 @@ class FrameState : public CommonNodeWrapperBase {
Node* locals() const {
Node* n = node()->InputAt(kFrameStateLocalsInput);
DCHECK(n->opcode() == IrOpcode::kStateValues ||
- n->opcode() == IrOpcode::kTypedStateValues);
+ n->opcode() == IrOpcode::kTypedStateValues ||
+ n->opcode() == IrOpcode::kDeadValue);
return n;
}
// TODO(jgruber): Consider renaming this to the more meaningful
diff --git a/deps/v8/src/compiler/graph-reducer.cc b/deps/v8/src/compiler/graph-reducer.cc
index 0abbd11e5cb..7d834aa78a5 100644
--- a/deps/v8/src/compiler/graph-reducer.cc
+++ b/deps/v8/src/compiler/graph-reducer.cc
@@ -96,12 +96,12 @@ void GraphReducer::ReduceNode(Node* node) {
void GraphReducer::ReduceGraph() { ReduceNode(graph()->end()); }
-
-Reduction GraphReducer::Reduce(Node* const node) {
+Reduction GraphReducer::Reduce(Node* const node, NodeId* max_id) {
auto skip = reducers_.end();
for (auto i = reducers_.begin(); i != reducers_.end();) {
if (i != skip) {
tick_counter_->TickAndMaybeEnterSafepoint();
+ *max_id = static_cast<NodeId>(graph()->NodeCount() - 1);
Reduction reduction = (*i)->Reduce(node, observe_node_manager_);
if (!reduction.Changed()) {
// No change from this reducer.
@@ -144,7 +144,6 @@ Reduction GraphReducer::Reduce(Node* const node) {
return Reducer::Changed(node);
}
-
void GraphReducer::ReduceTop() {
NodeState& entry = stack_.top();
Node* node = entry.node;
@@ -172,10 +171,11 @@ void GraphReducer::ReduceTop() {
}
// Remember the max node id before reduction.
- NodeId const max_id = static_cast<NodeId>(graph()->NodeCount() - 1);
+ NodeId const initial_max_id = static_cast<NodeId>(graph()->NodeCount() - 1);
+ NodeId max_id = initial_max_id;
// All inputs should be visited or on stack. Apply reductions to node.
- Reduction reduction = Reduce(node);
+ Reduction reduction = Reduce(node, &max_id);
// If there was no reduction, pop {node} and continue.
if (!reduction.Changed()) return Pop();
@@ -205,6 +205,11 @@ void GraphReducer::ReduceTop() {
// Check if we have a new replacement.
if (replacement != node) {
Replace(node, replacement, max_id);
+ if (replacement->id() > initial_max_id && replacement->id() <= max_id) {
+ // {replacement} was created by an earlier reducer in this Reduce() step,
+ // so it has not been reduced yet.
+ Recurse(replacement);
+ }
}
}
diff --git a/deps/v8/src/compiler/graph-reducer.h b/deps/v8/src/compiler/graph-reducer.h
index 8afbafe5467..17eb995632f 100644
--- a/deps/v8/src/compiler/graph-reducer.h
+++ b/deps/v8/src/compiler/graph-reducer.h
@@ -174,8 +174,9 @@ class V8_EXPORT_PRIVATE GraphReducer
int input_index;
};
- // Reduce a single node.
- Reduction Reduce(Node* const);
+ // Reduce a single node. Sets {*max_id} to the max node id before the last
+ // reducer step so that only nodes created by a replacing reducer exceed it.
+ Reduction Reduce(Node* const, NodeId* max_id);
// Reduce the node on top of the stack.
void ReduceTop();
diff --git a/deps/v8/src/compiler/js-call-reducer.cc b/deps/v8/src/compiler/js-call-reducer.cc
index 080e06f79f3..86332c3891c 100644
--- a/deps/v8/src/compiler/js-call-reducer.cc
+++ b/deps/v8/src/compiler/js-call-reducer.cc
@@ -1909,6 +1909,12 @@ TNode<Object> IteratingArrayBuiltinReducerAssembler::ReduceArrayPrototypeSort(
// Load elem = temp_array[j].
TNode<Object> elem = LoadElement<Object>(element_access, temp_array, j);
+ // Lowering the call can add eager deopts on its inputs, e.g. argument
+ // conversions for an inlined Wasm comparefn. Earlier comparefn calls
+ // may have had side effects, so these deopts must not resume before
+ // the sort.
+ Checkpoint(SortContinueFromSnapshotEagerFrameState(frame_state_params));
+
TNode<Object> comparefn_this = UndefinedConstant();
TNode<Object> cmp_result =
JSCall2(comparefn, comparefn_this, pivot, elem,
diff --git a/deps/v8/src/compiler/js-inlining-heuristic.cc b/deps/v8/src/compiler/js-inlining-heuristic.cc
index 33680c28858..db11796b77e 100644
--- a/deps/v8/src/compiler/js-inlining-heuristic.cc
+++ b/deps/v8/src/compiler/js-inlining-heuristic.cc
@@ -398,6 +398,7 @@ struct NodeAndIndex {
bool CollectStateValuesOwnedUses(Node* node, Node* state_values,
NodeAndIndex* uses_buffer, size_t* use_count,
size_t max_uses) {
+ if (state_values->opcode() == IrOpcode::kDeadValue) return false;
// Only accumulate states that are not shared with other users.
if (state_values->UseCount() > 1) return true;
for (int i = 0; i < state_values->InputCount(); i++) {
@@ -423,6 +424,7 @@ Node* JSInliningHeuristic::DuplicateStateValuesAndRename(Node* state_values,
StateCloneMode mode) {
// Only rename in states that are not shared with other users. This needs to
// be in sync with the condition in {CollectStateValuesOwnedUses}.
+ DCHECK_NE(state_values->opcode(), IrOpcode::kDeadValue);
Node* copy = (mode == kChangeInPlace && state_values->UseCount() <= 1)
? state_values
: nullptr;
@@ -649,7 +651,10 @@ bool JSInliningHeuristic::TryReuseDispatch(Node* node, Node* callee,
// Collect the uses to check case 2.
Node* checkpoint_state = nullptr;
if (checkpoint) {
- checkpoint_state = checkpoint->InputAt(0);
+ checkpoint_state = NodeProperties::GetFrameStateInput(checkpoint);
+ // {checkpoint} may still be on the GraphReducer stack while its FrameState
+ // input has already been replaced with DeadValue by DeadCodeElimination.
+ if (checkpoint_state->opcode() != IrOpcode::kFrameState) return false;
if (!CollectFrameStateUniqueUses(callee, FrameState{checkpoint_state},
replaceable_uses, &replaceable_uses_count,
kMaxUses)) {
diff --git a/deps/v8/src/compiler/node-properties.h b/deps/v8/src/compiler/node-properties.h
index a9673b43c36..8c953e309f1 100644
--- a/deps/v8/src/compiler/node-properties.h
+++ b/deps/v8/src/compiler/node-properties.h
@@ -134,10 +134,10 @@ class V8_EXPORT_PRIVATE NodeProperties {
// Returns whether the node acts as the identity function on a value
// input. The input that is passed through is returned via {out_value}.
- static bool IsValueIdentity(Node* node, Node** out_value) {
+ static bool IsValueIdentity(Node* node, Node** out_value = nullptr) {
switch (node->opcode()) {
case IrOpcode::kTypeGuard:
- *out_value = GetValueInput(node, 0);
+ if (out_value) *out_value = GetValueInput(node, 0);
return true;
default:
return false;
diff --git a/deps/v8/src/compiler/opcodes.h b/deps/v8/src/compiler/opcodes.h
index 30fd3e1693e..bace823d9e9 100644
--- a/deps/v8/src/compiler/opcodes.h
+++ b/deps/v8/src/compiler/opcodes.h
@@ -278,6 +278,7 @@
V(ChangeTaggedToUint32) \
V(ChangeTaggedToFloat64) \
V(ChangeTaggedToTaggedSigned) \
+ V(ChangeTaggedToTaggedPointer) \
V(ChangeSmiOrHoleToFloat64) \
V(ChangeNumberOrHoleToFloat64) \
V(ChangeInt31ToTaggedSigned) \
diff --git a/deps/v8/src/compiler/raw-machine-assembler.cc b/deps/v8/src/compiler/raw-machine-assembler.cc
index b93a2fdea0a..42c370ad571 100644
--- a/deps/v8/src/compiler/raw-machine-assembler.cc
+++ b/deps/v8/src/compiler/raw-machine-assembler.cc
@@ -841,6 +841,18 @@ void RawMachineAssembler::SetInitialDebugInformation(
bool RawMachineAssembler::InsideBlock() { return current_block_ != nullptr; }
+bool RawMachineAssembler::IsAtStart() const {
+ if (current_block_ != schedule_->start()) return false;
+ for (Node* node : *current_block_) {
+ if (node->opcode() == IrOpcode::kCall ||
+ node->opcode() == IrOpcode::kAllocate ||
+ node->opcode() == IrOpcode::kAllocateRaw) {
+ return false;
+ }
+ }
+ return true;
+}
+
BasicBlock* RawMachineAssembler::CurrentBlock() {
DCHECK(current_block_);
return current_block_;
diff --git a/deps/v8/src/compiler/raw-machine-assembler.h b/deps/v8/src/compiler/raw-machine-assembler.h
index 3783df4d760..f9d0fa6db63 100644
--- a/deps/v8/src/compiler/raw-machine-assembler.h
+++ b/deps/v8/src/compiler/raw-machine-assembler.h
@@ -1131,6 +1131,7 @@ class V8_EXPORT_PRIVATE RawMachineAssembler {
void PrintCurrentBlock(std::ostream& os);
#endif // DEBUG
bool InsideBlock();
+ bool IsAtStart() const;
// Add success / exception successor blocks and ends the current block ending
// in a potentially throwing call node.
@@ -1186,15 +1187,11 @@ class V8_EXPORT_PRIVATE RawMachineAssembler {
// If we're generating the code for one of these special builtins, this
// function will return a node containing the actual JS parameter count.
// Otherwise it will be nullptr.
- //
- // TODO(saelo): it would be a bit nicer if we could automatically determine
- // that the dynamic parameter count is required (for example from the call
- // descriptor) and then directly fetch it in the prologue and use it in the
- // epilogue without the higher-level assemblers having to get involved. It's
- // not clear if it's worth the effort though for the handful of builtins that
- // work this way though.
Node* dynamic_js_parameter_count() { return dynamic_js_parameter_count_; }
void set_dynamic_js_parameter_count(Node* parameter_count) {
+ // Must be set at the start of the builtin before any call/GC can sweep an
+ // unrooted dispatch table entry.
+ DCHECK(IsAtStart());
dynamic_js_parameter_count_ = parameter_count;
}
diff --git a/deps/v8/src/compiler/representation-change.cc b/deps/v8/src/compiler/representation-change.cc
index 921f3565852..f40aed31ff9 100644
--- a/deps/v8/src/compiler/representation-change.cc
+++ b/deps/v8/src/compiler/representation-change.cc
@@ -510,6 +510,8 @@ Node* RepresentationChanger::GetTaggedPointerRepresentationFor(
op = simplified()->ChangeFloat64ToTaggedPointer();
} else if (output_type.Is(Type::SignedBigInt64()) &&
use_info.type_check() == TypeCheckKind::kBigInt) {
+ // Non-kBigInt uses of kWord64 BigInts are already rematerialized in
+ // GetRepresentationFor.
op = simplified()->ChangeInt64ToBigInt();
} else if (output_type.Is(Type::UnsignedBigInt64()) &&
use_info.type_check() == TypeCheckKind::kBigInt) {
@@ -531,6 +533,13 @@ Node* RepresentationChanger::GetTaggedPointerRepresentationFor(
if (output_type.Is(Type::Number())) {
// float64 -> tagged
op = simplified()->ChangeFloat64ToTaggedPointer();
+ } else if (output_type.Is(Type::NumberOrUndefined())) {
+ // ChangeFloat64OrUndefinedToTagged always produces a HeapNumber or
+ // Undefined, never a Smi.
+ op = simplified()->ChangeFloat64OrUndefinedToTagged(
+ output_type.Maybe(Type::MinusZero())
+ ? CheckForMinusZeroMode::kCheckForMinusZero
+ : CheckForMinusZeroMode::kDontCheckForMinusZero);
} else {
return TypeError(node, output_rep, output_type,
MachineRepresentation::kTaggedPointer);
@@ -556,8 +565,13 @@ Node* RepresentationChanger::GetTaggedPointerRepresentationFor(
!output_type.Maybe(Type::SignedSmall())) {
DCHECK_NE(output_rep, MachineRepresentation::kTaggedSigned);
return node;
- } else {
+ } else if (use_info.type_check() != TypeCheckKind::kNone) {
+ DCHECK_EQ(use_info.type_check(), TypeCheckKind::kHeapObject);
op = simplified()->CheckedTaggedToTaggedPointer(use_info.feedback());
+ } else {
+ // Known-Smi inputs are folded to HeapNumber allocation by
+ // SimplifiedOptimizationReducer::ReduceConvert.
+ op = simplified()->ChangeTaggedToTaggedPointer();
}
} else {
return TypeError(node, output_rep, output_type,
@@ -1404,10 +1418,12 @@ Node* RepresentationChanger::GetWord64RepresentationFor(
}
} else if (use_info.type_check() == TypeCheckKind::kSigned64 ||
use_info.type_check() == TypeCheckKind::kArrayIndex) {
- if (output_type.Is(cache_->kDoubleRepresentableInt64) ||
- (output_type.Is(cache_->kDoubleRepresentableInt64OrMinusZero) &&
- use_info.truncation().IdentifiesZeroAndMinusZero())) {
+ if (output_type.Is(cache_->kDoubleRepresentableInt64)) {
op = machine()->ChangeFloat64ToInt64();
+ } else if (output_type.Is(cache_->kDoubleRepresentableInt64OrMinusZero) &&
+ use_info.truncation().IdentifiesZeroAndMinusZero()) {
+ op = machine()->TruncateFloat64ToInt64(
+ TruncateKind::kArchitectureDefault);
} else {
op = simplified()->CheckedFloat64ToInt64(
output_type.Maybe(Type::MinusZero())
@@ -1425,10 +1441,12 @@ Node* RepresentationChanger::GetWord64RepresentationFor(
: CheckForMinusZeroMode::kDontCheckForMinusZero,
use_info.feedback());
}
- } else if (output_type.Is(cache_->kDoubleRepresentableInt64) ||
- (output_type.Is(cache_->kDoubleRepresentableInt64OrMinusZero) &&
- use_info.truncation().IdentifiesZeroAndMinusZero())) {
+ } else if (output_type.Is(cache_->kDoubleRepresentableInt64)) {
op = machine()->ChangeFloat64ToInt64();
+ } else if (output_type.Is(cache_->kDoubleRepresentableInt64OrMinusZero) &&
+ use_info.truncation().IdentifiesZeroAndMinusZero()) {
+ op =
+ machine()->TruncateFloat64ToInt64(TruncateKind::kArchitectureDefault);
} else if (output_type.Is(cache_->kDoubleRepresentableUint64)) {
op = machine()->ChangeFloat64ToUint64();
} else {
@@ -1448,10 +1466,12 @@ Node* RepresentationChanger::GetWord64RepresentationFor(
}
} else if (use_info.type_check() == TypeCheckKind::kSigned64 ||
use_info.type_check() == TypeCheckKind::kArrayIndex) {
- if (output_type.Is(cache_->kDoubleRepresentableInt64) ||
- (output_type.Is(cache_->kDoubleRepresentableInt64OrMinusZero) &&
- use_info.truncation().IdentifiesZeroAndMinusZero())) {
+ if (output_type.Is(cache_->kDoubleRepresentableInt64)) {
op = machine()->ChangeFloat64ToInt64();
+ } else if (output_type.Is(cache_->kDoubleRepresentableInt64OrMinusZero) &&
+ use_info.truncation().IdentifiesZeroAndMinusZero()) {
+ op = machine()->TruncateFloat64ToInt64(
+ TruncateKind::kArchitectureDefault);
} else {
op = simplified()->CheckedFloat64ToInt64(
output_type.Maybe(Type::MinusZero())
@@ -1469,10 +1489,12 @@ Node* RepresentationChanger::GetWord64RepresentationFor(
: CheckForMinusZeroMode::kDontCheckForMinusZero,
use_info.feedback());
}
- } else if (output_type.Is(cache_->kDoubleRepresentableInt64) ||
- (output_type.Is(cache_->kDoubleRepresentableInt64OrMinusZero) &&
- use_info.truncation().IdentifiesZeroAndMinusZero())) {
+ } else if (output_type.Is(cache_->kDoubleRepresentableInt64)) {
op = machine()->ChangeFloat64ToInt64();
+ } else if (output_type.Is(cache_->kDoubleRepresentableInt64OrMinusZero) &&
+ use_info.truncation().IdentifiesZeroAndMinusZero()) {
+ op =
+ machine()->TruncateFloat64ToInt64(TruncateKind::kArchitectureDefault);
} else if (output_type.Is(cache_->kDoubleRepresentableUint64)) {
op = machine()->ChangeFloat64ToUint64();
} else {
@@ -1514,10 +1536,13 @@ Node* RepresentationChanger::GetWord64RepresentationFor(
use_info.feedback());
}
} else if (use_info.type_check() == TypeCheckKind::kSigned64) {
- if (output_type.Is(cache_->kDoubleRepresentableInt64) ||
- (output_type.Is(cache_->kDoubleRepresentableInt64OrMinusZero) &&
- use_info.truncation().IdentifiesZeroAndMinusZero())) {
+ if (output_type.Is(cache_->kDoubleRepresentableInt64)) {
op = simplified()->ChangeTaggedToInt64();
+ } else if (output_type.Is(cache_->kDoubleRepresentableInt64OrMinusZero) &&
+ use_info.truncation().IdentifiesZeroAndMinusZero()) {
+ node = InsertChangeTaggedToFloat64(node);
+ op = machine()->TruncateFloat64ToInt64(
+ TruncateKind::kArchitectureDefault);
} else {
op = simplified()->CheckedTaggedToInt64(
output_type.Maybe(Type::MinusZero())
@@ -1533,10 +1558,13 @@ Node* RepresentationChanger::GetWord64RepresentationFor(
use_info.feedback());
} else if (use_info.type_check() == TypeCheckKind::kArrayIndex) {
op = simplified()->CheckedTaggedToArrayIndex(use_info.feedback());
- } else if (output_type.Is(cache_->kDoubleRepresentableInt64) ||
- (output_type.Is(cache_->kDoubleRepresentableInt64OrMinusZero) &&
- use_info.truncation().IdentifiesZeroAndMinusZero())) {
+ } else if (output_type.Is(cache_->kDoubleRepresentableInt64)) {
op = simplified()->ChangeTaggedToInt64();
+ } else if (output_type.Is(cache_->kDoubleRepresentableInt64OrMinusZero) &&
+ use_info.truncation().IdentifiesZeroAndMinusZero()) {
+ node = InsertChangeTaggedToFloat64(node);
+ op =
+ machine()->TruncateFloat64ToInt64(TruncateKind::kArchitectureDefault);
} else {
return TypeError(node, output_rep, output_type,
MachineRepresentation::kWord64);
diff --git a/deps/v8/src/compiler/simplified-lowering-verifier.cc b/deps/v8/src/compiler/simplified-lowering-verifier.cc
index 416a68e08fc..a47cfe861d3 100644
--- a/deps/v8/src/compiler/simplified-lowering-verifier.cc
+++ b/deps/v8/src/compiler/simplified-lowering-verifier.cc
@@ -280,7 +280,8 @@ void SimplifiedLoweringVerifier::VisitNode(Node* node,
CheckAndSet(node, InputType(node, 0), InputTruncation(node, 0));
break;
}
- case IrOpcode::kChangeFloat64ToInt64: {
+ case IrOpcode::kChangeFloat64ToInt64:
+ case IrOpcode::kTruncateFloat64ToInt64: {
Truncation output_trunc =
JoinTruncation(InputTruncation(node, 0), Truncation::Word64());
CheckAndSet(node, InputType(node, 0), output_trunc);
@@ -513,6 +514,7 @@ void SimplifiedLoweringVerifier::VisitNode(Node* node,
CASE(ChangeTaggedToUint32)
CASE(ChangeTaggedToFloat64)
CASE(ChangeTaggedToTaggedSigned)
+ CASE(ChangeTaggedToTaggedPointer)
CASE(ChangeSmiOrHoleToFloat64)
CASE(ChangeNumberOrHoleToFloat64)
CASE(ChangeInt64ToTagged)
@@ -656,7 +658,6 @@ void SimplifiedLoweringVerifier::VisitNode(Node* node,
CASE(ChangeFloat64ToUint32)
CASE(ChangeFloat64ToUint64)
CASE(Float64SilenceNaN)
- CASE(TruncateFloat64ToInt64)
CASE(TruncateFloat64ToUint32)
CASE(TruncateFloat32ToInt32)
CASE(TruncateFloat32ToUint32)
diff --git a/deps/v8/src/compiler/simplified-lowering.cc b/deps/v8/src/compiler/simplified-lowering.cc
index 9ea2e639c1c..1f743829ccb 100644
--- a/deps/v8/src/compiler/simplified-lowering.cc
+++ b/deps/v8/src/compiler/simplified-lowering.cc
@@ -157,6 +157,7 @@ UseInfo TruncatingUseInfoFromRepresentation(
case MachineRepresentation::kTaggedSigned:
return UseInfo::TaggedSigned();
case MachineRepresentation::kTaggedPointer:
+ return UseInfo::TaggedPointer();
case MachineRepresentation::kTagged:
case MachineRepresentation::kTrustedPointer:
case MachineRepresentation::kMapWord:
@@ -1650,8 +1651,11 @@ class RepresentationSelector {
} else if (base_taggedness == kTaggedBase &&
CanBeTaggedPointer(field_representation)) {
Type value_type = NodeProperties::GetType(value);
- if (value_representation == MachineRepresentation::kTaggedSigned) {
- // Write barriers are only for stores of heap objects.
+ if (field_representation != MachineRepresentation::kTaggedPointer &&
+ value_representation == MachineRepresentation::kTaggedSigned) {
+ // Write barriers are only for stores of heap objects. Stores to
+ // kTaggedPointer fields convert kTaggedSigned inputs into HeapNumbers
+ // during ProcessInput, so they still require a write barrier.
return kNoWriteBarrier;
}
if (field_type.Is(Type::BooleanOrNullOrUndefined()) ||
diff --git a/deps/v8/src/compiler/simplified-operator-reducer.cc b/deps/v8/src/compiler/simplified-operator-reducer.cc
index 1714eb3de8c..de1e01fba69 100644
--- a/deps/v8/src/compiler/simplified-operator-reducer.cc
+++ b/deps/v8/src/compiler/simplified-operator-reducer.cc
@@ -31,7 +31,11 @@ Decision DecideObjectIsSmi(Node* const input) {
}
if (m.IsAllocate()) return Decision::kFalse;
if (m.IsChangeBitToTagged()) return Decision::kFalse;
+ if (m.IsChangeFloat64OrUndefinedToTagged()) return Decision::kFalse;
+ if (m.IsChangeFloat64ToTaggedPointer()) return Decision::kFalse;
+ if (m.IsChangeTaggedToTaggedPointer()) return Decision::kFalse;
if (m.IsChangeInt31ToTaggedSigned()) return Decision::kTrue;
+ if (m.IsChangeTaggedToTaggedSigned()) return Decision::kTrue;
if (m.IsHeapConstant()) return Decision::kFalse;
return Decision::kUnknown;
}
@@ -237,6 +241,13 @@ Reduction SimplifiedOperatorReducer::Reduce(Node* node) {
}
break;
}
+ case IrOpcode::kChangeTaggedToTaggedPointer: {
+ Node* const input = node->InputAt(0);
+ if (DecideObjectIsSmi(input) == Decision::kFalse) {
+ return Replace(input);
+ }
+ break;
+ }
case IrOpcode::kCheckedTaggedToTaggedPointer: {
Node* const input = node->InputAt(0);
switch (DecideObjectIsSmi(input)) {
diff --git a/deps/v8/src/compiler/simplified-operator.cc b/deps/v8/src/compiler/simplified-operator.cc
index 3a344044303..aee3bb906ae 100644
--- a/deps/v8/src/compiler/simplified-operator.cc
+++ b/deps/v8/src/compiler/simplified-operator.cc
@@ -937,6 +937,7 @@ bool operator==(AssertNotNullParameters const& lhs,
V(ChangeTaggedToUint32, Operator::kNoProperties, 1, 0) \
V(ChangeTaggedToFloat64, Operator::kNoProperties, 1, 0) \
V(ChangeTaggedToTaggedSigned, Operator::kNoProperties, 1, 0) \
+ V(ChangeTaggedToTaggedPointer, Operator::kNoProperties, 1, 0) \
V(ChangeSmiOrHoleToFloat64, Operator::kNoProperties, 1, 0) \
V(ChangeNumberOrHoleToFloat64, Operator::kNoProperties, 1, 0) \
V(ChangeFloat64ToTaggedPointer, Operator::kNoProperties, 1, 0) \
diff --git a/deps/v8/src/compiler/simplified-operator.h b/deps/v8/src/compiler/simplified-operator.h
index 1f2fcafbfd7..82b5ff835c8 100644
--- a/deps/v8/src/compiler/simplified-operator.h
+++ b/deps/v8/src/compiler/simplified-operator.h
@@ -1075,6 +1075,7 @@ class V8_EXPORT_PRIVATE SimplifiedOperatorBuilder final
const Operator* ChangeTaggedToUint32();
const Operator* ChangeTaggedToFloat64();
const Operator* ChangeTaggedToTaggedSigned();
+ const Operator* ChangeTaggedToTaggedPointer();
const Operator* ChangeSmiOrHoleToFloat64();
const Operator* ChangeNumberOrHoleToFloat64();
const Operator* ChangeInt31ToTaggedSigned();
diff --git a/deps/v8/src/compiler/turboshaft/assembler.h b/deps/v8/src/compiler/turboshaft/assembler.h
index 59f83f65f02..6a5acaf9ca5 100644
--- a/deps/v8/src/compiler/turboshaft/assembler.h
+++ b/deps/v8/src/compiler/turboshaft/assembler.h
@@ -2222,6 +2222,10 @@ class AssemblerOpInterface : public Next {
return V<Boolean>::Cast(
Convert(input, ConvertOp::Kind::kObject, ConvertOp::Kind::kBoolean));
}
+ V<HeapObject> ConvertToHeapObject(V<Object> input) {
+ return V<HeapObject>::Cast(
+ Convert(input, ConvertOp::Kind::kObject, ConvertOp::Kind::kHeapObject));
+ }
V<String> ConvertNumberToString(V<Number> input) {
return V<String>::Cast(
Convert(input, ConvertOp::Kind::kNumber, ConvertOp::Kind::kString));
diff --git a/deps/v8/src/compiler/turboshaft/graph-builder.cc b/deps/v8/src/compiler/turboshaft/graph-builder.cc
index 6c28884a15a..b1ecfde0622 100644
--- a/deps/v8/src/compiler/turboshaft/graph-builder.cc
+++ b/deps/v8/src/compiler/turboshaft/graph-builder.cc
@@ -1036,6 +1036,8 @@ OpIndex GraphBuilder::Process(
return __ Convert(Map(node->InputAt(0)),
ConvertOp::Kind::kNumberOrOddball,
ConvertOp::Kind::kSmi);
+ case IrOpcode::kChangeTaggedToTaggedPointer:
+ return __ ConvertToHeapObject(Map(node->InputAt(0)));
case IrOpcode::kCheckedTaggedToTaggedSigned: {
DCHECK(dominating_frame_state.valid());
diff --git a/deps/v8/src/compiler/turboshaft/machine-lowering-reducer-inl.h b/deps/v8/src/compiler/turboshaft/machine-lowering-reducer-inl.h
index 46c384b0160..45b9acc288d 100644
--- a/deps/v8/src/compiler/turboshaft/machine-lowering-reducer-inl.h
+++ b/deps/v8/src/compiler/turboshaft/machine-lowering-reducer-inl.h
@@ -900,6 +900,15 @@ class MachineLoweringReducer : public Next {
BIND(done, result);
return result;
}
+ case ConvertOp::Kind::kHeapObject: {
+ DCHECK_EQ(from, ConvertOp::Kind::kObject);
+ ScopedVar<HeapObject> result(this, V<HeapObject>::Cast(input));
+ IF (UNLIKELY(__ ObjectIsSmi(input))) {
+ result =
+ __ ConvertInt32ToHeapNumber(__ UntagSmi(V<Smi>::Cast(input)));
+ }
+ return result;
+ }
default:
UNREACHABLE();
}
diff --git a/deps/v8/src/compiler/turboshaft/machine-optimization-reducer.h b/deps/v8/src/compiler/turboshaft/machine-optimization-reducer.h
index 2c1b5cece12..66879a717cd 100644
--- a/deps/v8/src/compiler/turboshaft/machine-optimization-reducer.h
+++ b/deps/v8/src/compiler/turboshaft/machine-optimization-reducer.h
@@ -2334,11 +2334,15 @@ class MachineOptimizationReducer : public Next {
break;
}
- if (!index.valid() && matcher_.Is<ConstantOp>(base_idx)) {
- const ConstantOp& base = matcher_.Cast<ConstantOp>(base_idx);
- if (base.kind == any_of(ConstantOp::Kind::kHeapObject,
- ConstantOp::Kind::kCompressedHeapObject)) {
- if (offset == offsetof(HeapObject, map_)) {
+ if (kind.tagged_base && !kind.is_atomic && !index.valid()) {
+ if (const ConstantOp* base = matcher_.TryCast<ConstantOp>(base_idx);
+ base != nullptr &&
+ base->kind == any_of(ConstantOp::Kind::kHeapObject,
+ ConstantOp::Kind::kCompressedHeapObject)) {
+ if (offset == offsetof(HeapObject, map_) &&
+ loaded_rep == any_of(MemoryRepresentation::TaggedPointer(),
+ MemoryRepresentation::AnyTagged())) {
+ DCHECK_EQ(result_rep, RegisterRepresentation::Tagged());
// Only few loads should be loading the map from a ConstantOp
// HeapObject, so unparking the JSHeapBroker here rather than before
// the optimization pass itself it probably more efficient.
@@ -2351,7 +2355,7 @@ class MachineOptimizationReducer : public Next {
if (broker != nullptr) {
UnparkedScopeIfNeeded scope(broker);
AllowHandleDereference allow_handle_dereference;
- OptionalMapRef map = TryMakeRef(broker, base.handle()->map());
+ OptionalMapRef map = TryMakeRef(broker, base->handle()->map());
if (MapLoadCanBeConstantFolded(map)) {
return __ HeapConstant(map->object());
}
@@ -2359,7 +2363,7 @@ class MachineOptimizationReducer : public Next {
}
// TODO(dmercadier): consider constant-folding other accesses, in
// particular for constant objects (ie, if
- // base.handle()->InReadOnlySpace() is true). We have to be a bit
+ // base->handle()->InReadOnlySpace() is true). We have to be a bit
// careful though, because loading could be invalid (since we could
// be in unreachable code). (all objects have a map, so loading the map
// should always be safe, regardless of whether we are generating
diff --git a/deps/v8/src/compiler/turboshaft/operations.cc b/deps/v8/src/compiler/turboshaft/operations.cc
index 8ca48ae16d1..8e014c70dcb 100644
--- a/deps/v8/src/compiler/turboshaft/operations.cc
+++ b/deps/v8/src/compiler/turboshaft/operations.cc
@@ -1381,6 +1381,8 @@ std::ostream& operator<<(std::ostream& os, ConvertOp::Kind kind) {
switch (kind) {
case ConvertOp::Kind::kObject:
return os << "Object";
+ case ConvertOp::Kind::kHeapObject:
+ return os << "HeapObject";
case ConvertOp::Kind::kBoolean:
return os << "Boolean";
case ConvertOp::Kind::kNumber:
@@ -2497,6 +2499,22 @@ IsSmiDecision DecideObjectIsSmi(const Graph& graph, V<Object> idx, int depth) {
}
case Opcode::kAllocate:
return IsSmiDecision::kFalse;
+ case Opcode::kConvert: {
+ switch (op.Cast<ConvertOp>().to) {
+ case ConvertOp::Kind::kHeapObject:
+ case ConvertOp::Kind::kBoolean:
+ case ConvertOp::Kind::kString:
+ return IsSmiDecision::kFalse;
+ case ConvertOp::Kind::kSmi:
+ return IsSmiDecision::kTrue;
+ case ConvertOp::Kind::kObject:
+ case ConvertOp::Kind::kNumber:
+ case ConvertOp::Kind::kNumberOrOddball:
+ case ConvertOp::Kind::kPlainPrimitive:
+ return IsSmiDecision::kUnknown;
+ }
+ UNREACHABLE();
+ }
case Opcode::kConvertUntaggedToJSPrimitive: {
using Kind = ConvertUntaggedToJSPrimitiveOp::JSPrimitiveKind;
switch (op.Cast<ConvertUntaggedToJSPrimitiveOp>().kind) {
diff --git a/deps/v8/src/compiler/turboshaft/operations.h b/deps/v8/src/compiler/turboshaft/operations.h
index 07cff09545d..8c9f6b66557 100644
--- a/deps/v8/src/compiler/turboshaft/operations.h
+++ b/deps/v8/src/compiler/turboshaft/operations.h
@@ -5309,6 +5309,7 @@ struct ObjectIsNumericValueOp
struct ConvertOp : FixedArityOperationT<1, ConvertOp> {
enum class Kind : uint8_t {
kObject,
+ kHeapObject,
kBoolean,
kNumber,
kNumberOrOddball,
@@ -11368,8 +11369,8 @@ TURBOSHAFT_THROWING_OPERATIONS_LIST(THROWING_OP_LOOKS_VALID)
// instance, a SmiConstant is always a Smi, and a HeapObject constant is never a
// Smi.
enum class IsSmiDecision : uint8_t { kUnknown, kTrue, kFalse };
-IsSmiDecision DecideObjectIsSmi(const Graph& graph, V<Object> idx,
- int depth = 0);
+V8_EXPORT_PRIVATE IsSmiDecision DecideObjectIsSmi(const Graph& graph,
+ V<Object> idx, int depth = 0);
} // namespace v8::internal::compiler::turboshaft
diff --git a/deps/v8/src/compiler/turboshaft/simplified-optimization-reducer.h b/deps/v8/src/compiler/turboshaft/simplified-optimization-reducer.h
index 75f1274d902..3236c166d9c 100644
--- a/deps/v8/src/compiler/turboshaft/simplified-optimization-reducer.h
+++ b/deps/v8/src/compiler/turboshaft/simplified-optimization-reducer.h
@@ -164,6 +164,29 @@ class SimplifiedOptimizationReducer : public Next {
goto no_change;
}
+ V<Object> REDUCE(Convert)(V<Object> input, ConvertOp::Kind from,
+ ConvertOp::Kind to) {
+ LABEL_BLOCK(no_change) { return Next::ReduceConvert(input, from, to); }
+ if (ShouldSkipOptimizationStep()) goto no_change;
+
+ if (to == ConvertOp::Kind::kHeapObject) {
+ switch (__ DecideObjectIsSmi(input)) {
+ case IsSmiDecision::kFalse:
+ return input;
+ case IsSmiDecision::kTrue:
+ return __ ConvertInt32ToHeapNumber(__ UntagSmi(V<Smi>::Cast(input)));
+ case IsSmiDecision::kUnknown:
+ break;
+ }
+ }
+ if (to == ConvertOp::Kind::kSmi &&
+ __ DecideObjectIsSmi(input) == IsSmiDecision::kTrue) {
+ return input;
+ }
+
+ goto no_change;
+ }
+
OpIndex REDUCE(ObjectIs)(V<Object> input, ObjectIsOp::Kind kind,
ObjectIsOp::InputAssumptions input_assumptions) {
LABEL_BLOCK(no_change) {
diff --git a/deps/v8/src/compiler/turboshaft/turbolev-graph-builder.cc b/deps/v8/src/compiler/turboshaft/turbolev-graph-builder.cc
index a17cbf2430e..cc8385eac44 100644
--- a/deps/v8/src/compiler/turboshaft/turbolev-graph-builder.cc
+++ b/deps/v8/src/compiler/turboshaft/turbolev-graph-builder.cc
@@ -5774,6 +5774,12 @@ class GraphBuildingNodeProcessor {
return maglev::ProcessResult::kContinue;
}
+ maglev::ProcessResult Process(maglev::Retain* node,
+ const maglev::ProcessingState&) {
+ __ Retain(Map(node->ValueInput()));
+ return maglev::ProcessResult::kContinue;
+ }
+
maglev::ProcessResult Process(maglev::TurbofanStaticAssert* node,
const maglev::ProcessingState&) {
V<Word32> condition = __ TaggedEqual(
diff --git a/deps/v8/src/compiler/verifier.cc b/deps/v8/src/compiler/verifier.cc
index a52ffbbd1ab..1f948e677a3 100644
--- a/deps/v8/src/compiler/verifier.cc
+++ b/deps/v8/src/compiler/verifier.cc
@@ -1487,7 +1487,8 @@ void Verifier::Visitor::Check(Node* node, const AllNodes& all) {
// CheckTypeIs(node, to));
break;
}
- case IrOpcode::kChangeTaggedToTaggedSigned: // Fall through.
+ case IrOpcode::kChangeTaggedToTaggedSigned:
+ case IrOpcode::kChangeTaggedToTaggedPointer:
break;
case IrOpcode::kTruncateTaggedToFloat64PreserveUndefined:
case IrOpcode::kTruncateTaggedToFloat64: {
diff --git a/deps/v8/src/execution/isolate.cc b/deps/v8/src/execution/isolate.cc
index 5a497723603..24685d3983c 100644
--- a/deps/v8/src/execution/isolate.cc
+++ b/deps/v8/src/execution/isolate.cc
@@ -4406,13 +4406,16 @@ DirectHandle<NativeContext> Isolate::GetIncumbentContextSlow() {
// 1st candidate: most-recently-entered author function's context
// if it's newer than the last Context::BackupIncumbentScope entry.
//
- // NOTE: This code assumes that the stack grows downward.
+ // NOTE: This code assumes that the stack grows downward. Compare against
+ // fp() rather than sp(), because sp() is kNullAddress on reconstructed
+ // Fast C API caller frames whereas fp() is valid and BackupIncumbentScope
+ // always resides outside JS frames.
Address top_backup_incumbent =
top_backup_incumbent_scope()
? top_backup_incumbent_scope()->JSStackComparableAddressPrivate()
: 0;
if (!it.done() &&
- (!top_backup_incumbent || it.frame()->sp() < top_backup_incumbent)) {
+ (!top_backup_incumbent || it.frame()->fp() < top_backup_incumbent)) {
Tagged<Context> context = Cast<Context>(it.frame()->context());
// If the topmost_script_having_context is set then it must be correct.
if (DEBUG_BOOL && !topmost_script_having_context().is_null()) {
diff --git a/deps/v8/src/heap/factory.cc b/deps/v8/src/heap/factory.cc
index 400a43dc58a..cebec2761df 100644
--- a/deps/v8/src/heap/factory.cc
+++ b/deps/v8/src/heap/factory.cc
@@ -4715,25 +4715,23 @@ void Factory::SetRegExpAtomData(DirectHandle<JSRegExp> regexp,
regexp->set_data(*regexp_data);
}
-void Factory::SetRegExpIrregexpData(DirectHandle<JSRegExp> regexp,
- DirectHandle<String> original_source,
- DirectHandle<String> escaped_source,
- JSRegExp::Flags flags, int capture_count,
- uint32_t backtrack_limit,
- uint32_t bit_field) {
+void Factory::SetRegExpIrregexpData(
+ DirectHandle<JSRegExp> regexp, DirectHandle<String> original_source,
+ DirectHandle<String> escaped_source, JSRegExp::Flags flags,
+ int capture_count, uint32_t backtrack_limit, uint32_t bit_field,
+ DirectHandle<TrustedFixedArray> capture_name_map) {
DirectHandle<RegExpData> regexp_data =
NewIrRegExpData(original_source, escaped_source, flags, capture_count,
- backtrack_limit, bit_field);
+ backtrack_limit, bit_field, capture_name_map);
regexp->set_data(*regexp_data);
}
-void Factory::SetRegExpExperimentalData(DirectHandle<JSRegExp> regexp,
- DirectHandle<String> original_source,
- DirectHandle<String> escaped_source,
- JSRegExp::Flags flags,
- int capture_count) {
+void Factory::SetRegExpExperimentalData(
+ DirectHandle<JSRegExp> regexp, DirectHandle<String> original_source,
+ DirectHandle<String> escaped_source, JSRegExp::Flags flags,
+ int capture_count, DirectHandle<TrustedFixedArray> capture_name_map) {
DirectHandle<RegExpData> regexp_data = NewExperimentalRegExpData(
- original_source, escaped_source, flags, capture_count);
+ original_source, escaped_source, flags, capture_count, capture_name_map);
regexp->set_data(*regexp_data);
}
@@ -4762,7 +4760,7 @@ DirectHandle<RegExpData> Factory::NewAtomRegExpData(
DirectHandle<RegExpData> Factory::NewIrRegExpData(
DirectHandle<String> original_source, DirectHandle<String> escaped_source,
JSRegExp::Flags flags, int capture_count, uint32_t backtrack_limit,
- uint32_t bit_field) {
+ uint32_t bit_field, DirectHandle<TrustedFixedArray> capture_name_map) {
DirectHandle<RegExpDataWrapper> wrapper = NewRegExpDataWrapper();
int size = sizeof(IrRegExpData);
Tagged<HeapObject> result = AllocateRawWithImmortalMap(
@@ -4777,7 +4775,7 @@ DirectHandle<RegExpData> Factory::NewIrRegExpData(
instance->clear_uc16_code();
instance->clear_latin1_bytecode();
instance->clear_uc16_bytecode();
- instance->clear_capture_name_map();
+ instance->set_capture_name_map(capture_name_map);
instance->set_max_register_count(JSRegExp::kUninitializedValue);
instance->set_capture_count(capture_count);
int ticks_until_tier_up = v8_flags.regexp_tier_up
@@ -4796,7 +4794,8 @@ DirectHandle<RegExpData> Factory::NewIrRegExpData(
DirectHandle<RegExpData> Factory::NewExperimentalRegExpData(
DirectHandle<String> original_source, DirectHandle<String> escaped_source,
- JSRegExp::Flags flags, int capture_count) {
+ JSRegExp::Flags flags, int capture_count,
+ DirectHandle<TrustedFixedArray> capture_name_map) {
DirectHandle<RegExpDataWrapper> wrapper = NewRegExpDataWrapper();
int size = sizeof(IrRegExpData);
Tagged<HeapObject> result = AllocateRawWithImmortalMap(
@@ -4818,7 +4817,7 @@ DirectHandle<RegExpData> Factory::NewExperimentalRegExpData(
instance->clear_uc16_code();
instance->clear_latin1_bytecode();
instance->clear_uc16_bytecode();
- instance->clear_capture_name_map();
+ instance->set_capture_name_map(capture_name_map);
instance->set_max_register_count(JSRegExp::kUninitializedValue);
instance->set_capture_count(capture_count);
instance->set_ticks_until_tier_up(JSRegExp::kUninitializedValue);
diff --git a/deps/v8/src/heap/factory.h b/deps/v8/src/heap/factory.h
index 11f91d9e926..57d048549c1 100644
--- a/deps/v8/src/heap/factory.h
+++ b/deps/v8/src/heap/factory.h
@@ -1159,33 +1159,33 @@ class V8_EXPORT_PRIVATE Factory : public FactoryBase<Factory> {
JSRegExp::Flags flags,
DirectHandle<String> match_pattern);
- // Creates a new FixedArray that holds the data associated with the
- // irregexp regexp and stores it in the regexp.
- void SetRegExpIrregexpData(DirectHandle<JSRegExp> regexp,
- DirectHandle<String> original_source,
- DirectHandle<String> escaped_source,
- JSRegExp::Flags flags, int capture_count,
- uint32_t backtrack_limit, uint32_t bit_field);
-
- // Creates a new FixedArray that holds the data associated with the
- // experimental regexp and stores it in the regexp.
- void SetRegExpExperimentalData(DirectHandle<JSRegExp> regexp,
- DirectHandle<String> original_source,
- DirectHandle<String> escaped_source,
- JSRegExp::Flags flags, int capture_count);
+ // Creates a new IrRegExpData associated with the irregexp regexp and stores
+ // it in the regexp.
+ void SetRegExpIrregexpData(
+ DirectHandle<JSRegExp> regexp, DirectHandle<String> original_source,
+ DirectHandle<String> escaped_source, JSRegExp::Flags flags,
+ int capture_count, uint32_t backtrack_limit, uint32_t bit_field,
+ DirectHandle<TrustedFixedArray> capture_name_map = {});
+
+ // Creates a new IrRegExpData associated with the experimental regexp and
+ // stores it in the regexp.
+ void SetRegExpExperimentalData(
+ DirectHandle<JSRegExp> regexp, DirectHandle<String> original_source,
+ DirectHandle<String> escaped_source, JSRegExp::Flags flags,
+ int capture_count, DirectHandle<TrustedFixedArray> capture_name_map = {});
DirectHandle<RegExpData> NewAtomRegExpData(
DirectHandle<String> original_source, DirectHandle<String> escaped_source,
JSRegExp::Flags flags, DirectHandle<String> pattern);
- DirectHandle<RegExpData> NewIrRegExpData(DirectHandle<String> original_source,
- DirectHandle<String> escaped_source,
- JSRegExp::Flags flags,
- int capture_count,
- uint32_t backtrack_limit,
- uint32_t bit_field);
+ DirectHandle<RegExpData> NewIrRegExpData(
+ DirectHandle<String> original_source, DirectHandle<String> escaped_source,
+ JSRegExp::Flags flags, int capture_count, uint32_t backtrack_limit,
+ uint32_t bit_field,
+ DirectHandle<TrustedFixedArray> capture_name_map = {});
DirectHandle<RegExpData> NewExperimentalRegExpData(
DirectHandle<String> original_source, DirectHandle<String> escaped_source,
- JSRegExp::Flags flags, int capture_count);
+ JSRegExp::Flags flags, int capture_count,
+ DirectHandle<TrustedFixedArray> capture_name_map = {});
// Returns the value for a known global constant (a property of the global
// object which is neither configurable nor writable) like 'undefined'.
diff --git a/deps/v8/src/maglev/maglev-graph-builder.cc b/deps/v8/src/maglev/maglev-graph-builder.cc
index 427ba013e31..144f12bf7cb 100644
--- a/deps/v8/src/maglev/maglev-graph-builder.cc
+++ b/deps/v8/src/maglev/maglev-graph-builder.cc
@@ -15642,6 +15642,9 @@ ReduceResult MaglevGraphBuilder::VisitForInNext() {
GET_VALUE_OR_ABORT(
key, BuildLoadFixedArrayElement(cache_array, index,
LoadType::kInternalizedString));
+ // Keep the enumerator map alive so that a GC before the load cannot
+ // right-trim the shared enum cache if the map check above is eliminated.
+ RETURN_IF_ABORT(AddNewNode<Retain>({cache_type}));
SetAccumulator(key);
current_for_in_state.receiver = receiver;
diff --git a/deps/v8/src/maglev/maglev-graph-optimizer.cc b/deps/v8/src/maglev/maglev-graph-optimizer.cc
index cd9330f544e..c2909a8d0d5 100644
--- a/deps/v8/src/maglev/maglev-graph-optimizer.cc
+++ b/deps/v8/src/maglev/maglev-graph-optimizer.cc
@@ -1288,6 +1288,11 @@ ProcessResult MaglevGraphOptimizer::VisitAssumeType(AssumeType*,
return ProcessResult::kContinue;
}
+ProcessResult MaglevGraphOptimizer::VisitRetain(Retain*,
+ const ProcessingState&) {
+ return ProcessResult::kContinue;
+}
+
ProcessResult MaglevGraphOptimizer::VisitTurbofanStaticAssert(
TurbofanStaticAssert*, const ProcessingState&) {
return ProcessResult::kContinue;
diff --git a/deps/v8/src/maglev/maglev-ir.cc b/deps/v8/src/maglev/maglev-ir.cc
index b5a67f435ec..9f6b1df1d64 100644
--- a/deps/v8/src/maglev/maglev-ir.cc
+++ b/deps/v8/src/maglev/maglev-ir.cc
@@ -5219,6 +5219,19 @@ void DebugBreak::GenerateCode(MaglevAssembler* masm,
__ DebugBreak();
}
+void Retain::SetValueLocationConstraints() {
+ // For non-constant values, UseAny extends the input's live range up to this
+ // node so safepoints keep it alive across GC without emitting code here.
+ UseAny(ValueInput());
+}
+void Retain::GenerateCode(MaglevAssembler* masm, const ProcessingState& state) {
+ // UseAny does not keep constants alive (they have no register/stack-slot
+ // safepoint entries), so retain HeapConstants on the code object directly.
+ if (HeapConstant* constant = ValueInput().node()->TryCast<HeapConstant>()) {
+ masm->code_gen_state()->Retain(constant->object().object());
+ }
+}
+
int Abort::MaxCallStackArgs() const {
DCHECK_EQ(Runtime::FunctionForId(Runtime::kAbort)->nargs, 1);
return 1;
diff --git a/deps/v8/src/maglev/maglev-ir.h b/deps/v8/src/maglev/maglev-ir.h
index 49f301db43b..5b76bacf77d 100644
--- a/deps/v8/src/maglev/maglev-ir.h
+++ b/deps/v8/src/maglev/maglev-ir.h
@@ -465,6 +465,7 @@ class ExceptionHandlerInfo;
V(CheckInstanceType) \
V(Dead) \
V(DebugBreak) \
+ V(Retain) \
V(MajorGCForCompilerTesting) \
V(FunctionEntryStackCheck) \
V(GeneratorStore) \
@@ -7740,6 +7741,25 @@ class AssumeType : public NodeT<AssumeType> {
const NodeType asserted_type_;
};
+class Retain : public FixedInputNodeT<1, Retain> {
+ public:
+ explicit Retain(uint64_t bitfield) : Base(bitfield) {}
+
+ static constexpr OpProperties kProperties = OpProperties::NotIdempotent();
+
+ DECLARE_INPUTS(Value)
+ DECLARE_INPUT_TYPES(Tagged)
+
+#ifdef V8_COMPRESS_POINTERS
+ void MarkTaggedInputsAsDecompressing() {
+ // Don't need to decompress just to keep the object alive.
+ }
+#endif
+
+ void SetValueLocationConstraints();
+ void GenerateCode(MaglevAssembler*, const ProcessingState&);
+};
+
class TurbofanStaticAssert : public FixedInputNodeT<1, TurbofanStaticAssert> {
public:
explicit TurbofanStaticAssert(uint64_t bitfield) : Base(bitfield) {}
diff --git a/deps/v8/src/maglev/maglev-phi-representation-selector.cc b/deps/v8/src/maglev/maglev-phi-representation-selector.cc
index 5b44744d9e9..1e672736354 100644
--- a/deps/v8/src/maglev/maglev-phi-representation-selector.cc
+++ b/deps/v8/src/maglev/maglev-phi-representation-selector.cc
@@ -143,6 +143,14 @@ MaglevPhiRepresentationSelector::ProcessPhi(Phi* node) {
return ProcessPhiResult::kNone;
}
+ if (node->input_count() == 1) {
+ // Later passes unwrap single-input Phis to their input, so uses/deopt
+ // frames may already bypass this Phi while earlier uses still point to it.
+ // Keep it tagged so its representation cannot diverge from its input's.
+ EnsurePhiInputsTagged(node);
+ return ProcessPhiResult::kNone;
+ }
+
TRACE_UNTAGGING("Considering for untagging: " << PrintNodeLabel(node));
// {input_mask} represents the ValueRepresentation that {node} could have,
diff --git a/deps/v8/src/objects/js-locale.cc b/deps/v8/src/objects/js-locale.cc
index cb39d27470f..0fbf4cbf3be 100644
--- a/deps/v8/src/objects/js-locale.cc
+++ b/deps/v8/src/objects/js-locale.cc
@@ -15,7 +15,6 @@
#include <string>
#include <vector>
-#include "src/api/api.h"
#include "src/execution/isolate.h"
#include "src/heap/factory.h"
#include "src/objects/intl-objects.h"
@@ -321,19 +320,16 @@ bool IsValidVariants(std::string_view variants) {
Maybe<bool> ApplyOptionsToTag(Isolate* isolate, DirectHandle<String> tag,
DirectHandle<JSReceiver> options,
icu::LocaleBuilder* builder) {
- v8::Isolate* v8_isolate = reinterpret_cast<v8::Isolate*>(isolate);
if (tag->length() == 0) {
THROW_NEW_ERROR(isolate, NewRangeError(MessageTemplate::kLocaleNotEmpty));
}
- v8::String::Utf8Value bcp47_tag(v8_isolate, v8::Utils::ToLocal(tag));
- builder->setLanguageTag(
- {*bcp47_tag, static_cast<int32_t>(bcp47_tag.length())});
- DCHECK_LT(0, bcp47_tag.length());
- DCHECK_NOT_NULL(*bcp47_tag);
+ std::string bcp47_tag = tag->ToStdString();
+ builder->setLanguageTag(bcp47_tag);
+ DCHECK(!bcp47_tag.empty());
// 2. If IsStructurallyValidLanguageTag(tag) is false, throw a RangeError
// exception.
- if (!JSLocale::StartsWithUnicodeLanguageId(*bcp47_tag)) {
+ if (!JSLocale::StartsWithUnicodeLanguageId(bcp47_tag.c_str())) {
return Just(false);
}
UErrorCode status = U_ZERO_ERROR;
diff --git a/deps/v8/src/objects/lookup.cc b/deps/v8/src/objects/lookup.cc
index 402b02a3687..41f5e6e0000 100644
--- a/deps/v8/src/objects/lookup.cc
+++ b/deps/v8/src/objects/lookup.cc
@@ -80,6 +80,7 @@ void LookupIterator::Next() {
DCHECK_NE(JSPROXY, state_);
DCHECK_NE(TRANSITION, state_);
DCHECK_NE(NOT_FOUND, state_);
+ DCHECK_NE(STRING_LOOKUP_START_OBJECT, state_);
DisallowGarbageCollection no_gc;
has_property_ = false;
@@ -90,6 +91,8 @@ void LookupIterator::Next() {
state_ = IsElement() ? LookupInSpecialHolder<true>(map, holder)
: LookupInSpecialHolder<false>(map, holder);
if (IsFound()) return;
+ } else {
+ state_ = NOT_FOUND;
}
IsElement() ? NextInternal<true>(map, holder)
@@ -99,6 +102,7 @@ void LookupIterator::Next() {
template <bool is_element>
void LookupIterator::NextInternal(Tagged<Map> orig_map,
Tagged<JSReceiver> holder) {
+ CHECK_EQ(NOT_FOUND, state_);
Tagged<Map> map = orig_map;
do {
Tagged<JSReceiver> maybe_holder = NextHolder(map);
diff --git a/deps/v8/src/regexp/experimental/experimental.cc b/deps/v8/src/regexp/experimental/experimental.cc
index 4101d13cfa1..0ba170f9af6 100644
--- a/deps/v8/src/regexp/experimental/experimental.cc
+++ b/deps/v8/src/regexp/experimental/experimental.cc
@@ -33,16 +33,19 @@ bool ExperimentalRegExp::CanBeHandled(Tree* tree,
void ExperimentalRegExp::Initialize(Isolate* isolate, DirectHandle<JSRegExp> re,
DirectHandle<String> original_source,
DirectHandle<String> escaped_source,
- Flags flags, int capture_count) {
+ Flags flags, int capture_count,
+ ZoneVector<Capture*>* named_captures) {
DCHECK(v8_flags.enable_experimental_regexp_engine);
if (v8_flags.trace_experimental_regexp_engine) {
StdoutStream{} << "Initializing experimental regexp " << *original_source
<< std::endl;
}
+ DirectHandle<TrustedFixedArray> capture_name_map =
+ RegExp::CreateCaptureNameMap(isolate, named_captures);
isolate->factory()->SetRegExpExperimentalData(
re, original_source, escaped_source, JSRegExp::AsJSRegExpFlags(flags),
- capture_count);
+ capture_count, capture_name_map);
}
bool ExperimentalRegExp::IsCompiled(DirectHandle<IrRegExpData> re_data,
@@ -73,13 +76,8 @@ DirectHandle<TrustedByteArray> VectorToByteArray(Isolate* isolate,
namespace {
-struct CompilationResult {
- DirectHandle<TrustedByteArray> bytecode;
- DirectHandle<TrustedFixedArray> capture_name_map;
-};
-
// Compiles source pattern, but doesn't change the regexp object.
-std::optional<CompilationResult> CompileImpl(
+MaybeDirectHandle<TrustedByteArray> CompileImpl(
Isolate* isolate, DirectHandle<IrRegExpData> re_data) {
Zone zone(isolate->allocator(), ZONE_NAME);
@@ -97,18 +95,14 @@ std::optional<CompilationResult> CompileImpl(
// the only way parsing can fail now is because of stack overflow.
DCHECK_EQ(parse_result.error, Error::kStackOverflow);
RegExp::ThrowRegExpException(isolate, re_data, parse_result.error);
- return std::nullopt;
+ return {};
}
SBXCHECK_EQ(parse_result.capture_count, re_data->capture_count());
ZoneList<Instruction> bytecode = ExperimentalCompiler::Compile(
parse_result.tree, JSRegExp::AsRegExpFlags(re_data->flags()), &zone);
- CompilationResult result;
- result.bytecode = VectorToByteArray(isolate, bytecode.ToVector());
- result.capture_name_map =
- RegExp::CreateCaptureNameMap(isolate, parse_result.named_captures);
- return result;
+ return VectorToByteArray(isolate, bytecode.ToVector());
}
} // namespace
@@ -127,15 +121,13 @@ bool ExperimentalRegExp::Compile(Isolate* isolate,
<< std::endl;
}
- std::optional<CompilationResult> compilation_result =
- CompileImpl(isolate, re_data);
- if (!compilation_result.has_value()) {
+ DirectHandle<TrustedByteArray> bytecode;
+ if (!CompileImpl(isolate, re_data).ToHandle(&bytecode)) {
DCHECK(isolate->has_exception());
return false;
}
- re_data->SetBytecodeForExperimental(isolate, *compilation_result->bytecode);
- re_data->set_capture_name_map(compilation_result->capture_name_map);
+ re_data->SetBytecodeForExperimental(isolate, *bytecode);
return true;
}
@@ -286,13 +278,13 @@ int32_t ExperimentalRegExp::OneshotExecRaw(
<< regexp_data->original_source() << std::endl;
}
- std::optional<CompilationResult> compilation_result =
- CompileImpl(isolate, regexp_data);
- if (!compilation_result.has_value()) return RegExp::kInternalRegExpException;
+ DirectHandle<TrustedByteArray> bytecode;
+ if (!CompileImpl(isolate, regexp_data).ToHandle(&bytecode)) {
+ return RegExp::kInternalRegExpException;
+ }
DisallowGarbageCollection no_gc;
- return ExecRawImpl(isolate, RegExp::kFromRuntime,
- *compilation_result->bytecode, *subject,
+ return ExecRawImpl(isolate, RegExp::kFromRuntime, *bytecode, *subject,
regexp_data->capture_count(), output_registers,
output_register_count, subject_index);
}
diff --git a/deps/v8/src/regexp/experimental/experimental.h b/deps/v8/src/regexp/experimental/experimental.h
index 03848157f24..51abe2289ff 100644
--- a/deps/v8/src/regexp/experimental/experimental.h
+++ b/deps/v8/src/regexp/experimental/experimental.h
@@ -26,7 +26,8 @@ class ExperimentalRegExp final : public AllStatic {
static void Initialize(Isolate* isolate, DirectHandle<JSRegExp> re,
DirectHandle<String> original_source,
DirectHandle<String> escaped_source, Flags flags,
- int capture_count);
+ int capture_count,
+ ZoneVector<Capture*>* named_captures);
static bool IsCompiled(DirectHandle<IrRegExpData> re_data, Isolate* isolate);
V8_WARN_UNUSED_RESULT
static bool Compile(Isolate* isolate, DirectHandle<IrRegExpData> re_data);
diff --git a/deps/v8/src/regexp/regexp.cc b/deps/v8/src/regexp/regexp.cc
index 2e62116a33a..2038bdc91cd 100644
--- a/deps/v8/src/regexp/regexp.cc
+++ b/deps/v8/src/regexp/regexp.cc
@@ -53,7 +53,8 @@ class RegExpImpl final : public AllStatic {
DirectHandle<String> original_source,
DirectHandle<String> escaped_source,
Flags flags, int capture_count,
- uint32_t backtrack_limit, uint32_t bit_field);
+ uint32_t backtrack_limit, uint32_t bit_field,
+ ZoneVector<Capture*>* named_captures);
// Prepare a RegExp for being executed one or more times (using
// IrregexpExecOnce) on the subject.
@@ -431,9 +432,9 @@ MaybeDirectHandle<Object> RegExp::Compile(Isolate* isolate,
EscapeRegExpSource(isolate, original_source));
if (v8_flags.default_to_experimental_regexp_engine && is_linear_executable) {
DCHECK(v8_flags.enable_experimental_regexp_engine);
- regexp::ExperimentalRegExp::Initialize(isolate, re, original_source,
- escaped_source, flags,
- parse_result.capture_count);
+ regexp::ExperimentalRegExp::Initialize(
+ isolate, re, original_source, escaped_source, flags,
+ parse_result.capture_count, parse_result.named_captures);
has_been_compiled = true;
} else if (flags & JSRegExp::kLinear) {
DCHECK(v8_flags.enable_experimental_regexp_engine);
@@ -443,9 +444,9 @@ MaybeDirectHandle<Object> RegExp::Compile(Isolate* isolate,
return RegExp::ThrowRegExpException(isolate, flags, original_source,
regexp::Error::kNotLinear);
}
- regexp::ExperimentalRegExp::Initialize(isolate, re, original_source,
- escaped_source, flags,
- parse_result.capture_count);
+ regexp::ExperimentalRegExp::Initialize(
+ isolate, re, original_source, escaped_source, flags,
+ parse_result.capture_count, parse_result.named_captures);
has_been_compiled = true;
} else if (parse_result.simple && !IsIgnoreCase(flags) && !IsSticky(flags) &&
!HasFewDifferentCharacters(original_source)) {
@@ -477,7 +478,8 @@ MaybeDirectHandle<Object> RegExp::Compile(Isolate* isolate,
Bits::IsLinearExecutableBit::encode(is_linear_executable);
regexp::RegExpImpl::IrregexpInitialize(
isolate, re, original_source, escaped_source, flags,
- parse_result.capture_count, backtrack_limit, bit_field);
+ parse_result.capture_count, backtrack_limit, bit_field,
+ parse_result.named_captures);
}
// Compilation succeeded so the data is set on the regexp
// and we can store it in the cache.
@@ -981,9 +983,6 @@ bool RegExpImpl::CompileIrregexpFromSource(
BUILTIN_CODE(isolate, RegExpInterpreterTrampoline);
re_data->set_code(is_one_byte, *trampoline);
}
- DirectHandle<TrustedFixedArray> capture_name_map =
- RegExp::CreateCaptureNameMap(isolate, compile_data.named_captures);
- re_data->set_capture_name_map(capture_name_map);
int register_max = re_data->max_register_count();
if (compile_data.register_count > register_max) {
re_data->set_max_register_count(compile_data.register_count);
@@ -1166,11 +1165,14 @@ void RegExpImpl::IrregexpInitialize(Isolate* isolate, DirectHandle<JSRegExp> re,
DirectHandle<String> escaped_source,
Flags flags, int capture_count,
uint32_t backtrack_limit,
- uint32_t bit_field) {
+ uint32_t bit_field,
+ ZoneVector<Capture*>* named_captures) {
+ DirectHandle<TrustedFixedArray> capture_name_map =
+ RegExp::CreateCaptureNameMap(isolate, named_captures);
// Initialize compiled code entries to null.
isolate->factory()->SetRegExpIrregexpData(
re, original_source, escaped_source, JSRegExp::AsJSRegExpFlags(flags),
- capture_count, backtrack_limit, bit_field);
+ capture_count, backtrack_limit, bit_field, capture_name_map);
}
// static
diff --git a/deps/v8/src/runtime/runtime-regexp.cc b/deps/v8/src/runtime/runtime-regexp.cc
index 41060a34fa9..56165ca0537 100644
--- a/deps/v8/src/runtime/runtime-regexp.cc
+++ b/deps/v8/src/runtime/runtime-regexp.cc
@@ -1355,7 +1355,11 @@ static Tagged<UnionOf<ExceptionHole, Null, FixedArray>> SearchRegExpMultiple(
// has_capture can only be true for IrRegExp.
DirectHandle<IrRegExpData> re_data;
- if (has_capture) re_data = TrustedCast<IrRegExpData>(regexp_data);
+ bool has_named_captures = false;
+ if (has_capture) {
+ re_data = TrustedCast<IrRegExpData>(regexp_data);
+ has_named_captures = re_data->has_capture_name_map();
+ }
static const int kMinLengthToCache = 0x1000;
@@ -1379,12 +1383,9 @@ static Tagged<UnionOf<ExceptionHole, Null, FixedArray>> SearchRegExpMultiple(
}
DirectHandle<FixedArray> cached_fixed_array(cached_answer_array,
isolate);
- // The cache FixedArray is a COW-array and we need to return a copy. A
- // cache hit implies an earlier run compiled the pattern, so the capture
- // name map is populated.
+ // The cache FixedArray is a COW-array and we need to return a copy.
DirectHandle<FixedArray> copied_fixed_array = CopyMatches(
- isolate, cached_fixed_array,
- has_capture && re_data->has_capture_name_map(), capture_count);
+ isolate, cached_fixed_array, has_named_captures, capture_count);
RegExp::SetLastMatchInfo(isolate, last_match_array, subject,
capture_count, raw_last_match);
return *copied_fixed_array;
@@ -1406,10 +1407,10 @@ static Tagged<UnionOf<ExceptionHole, Null, FixedArray>> SearchRegExpMultiple(
// Two smis before and after the match, for very long strings.
static const uint32_t kMaxBuilderEntriesPerRegExpMatch = 5;
- // The capture name map is populated lazily, so this must stay below the
- // GlobalExecRunner constructor, which is what compiles the pattern.
- const bool has_named_captures =
- has_capture && re_data->has_capture_name_map();
+ DirectHandle<TrustedFixedArray> capture_map;
+ if (has_named_captures) {
+ capture_map = direct_handle(re_data->capture_name_map(), isolate);
+ }
while (true) {
int32_t* current_match = runner.FetchNext();
@@ -1467,8 +1468,6 @@ static Tagged<UnionOf<ExceptionHole, Null, FixedArray>> SearchRegExpMultiple(
elements->set(cursor++, *subject);
if (has_named_captures) {
- DirectHandle<TrustedFixedArray> capture_map(
- re_data->capture_name_map(), isolate);
DirectHandle<JSObject> groups = ConstructNamedCaptureGroupsObject(
isolate, capture_map, [=](int ix) { return elements->get(ix); });
elements->set(cursor++, *groups);
@@ -1512,8 +1511,7 @@ static Tagged<UnionOf<ExceptionHole, Null, FixedArray>> SearchRegExpMultiple(
DirectHandle<FixedArray> copied_fixed_array = CopyMatches(
isolate, result_fixed_array, has_named_captures, capture_count);
regexp::ResultsCache::Enter(
- isolate, subject,
- direct_handle(regexp->data(isolate)->wrapper(), isolate),
+ isolate, subject, direct_handle(regexp_data->wrapper(), isolate),
copied_fixed_array, last_match_cache,
regexp::ResultsCache::REGEXP_MULTIPLE_INDICES);
}
diff --git a/deps/v8/src/runtime/runtime-scopes.cc b/deps/v8/src/runtime/runtime-scopes.cc
index 1a3b14276b2..269d33fe331 100644
--- a/deps/v8/src/runtime/runtime-scopes.cc
+++ b/deps/v8/src/runtime/runtime-scopes.cc
@@ -364,6 +364,17 @@ RUNTIME_FUNCTION(Runtime_HandleExceptionsInDisposeDisposableStack) {
namespace {
+#ifdef DEBUG
+bool HasDebugEvaluateContextInChain(Tagged<Context> current,
+ Tagged<Context> limit) {
+ while (current != limit) {
+ if (current->IsDebugEvaluateContext()) return true;
+ current = current->previous();
+ }
+ return false;
+}
+#endif // DEBUG
+
Tagged<Object> DeclareEvalHelper(Isolate* isolate, Handle<String> name,
Handle<Object> value) {
// Declarations are always made in a function, native, eval, or script
@@ -372,18 +383,21 @@ Tagged<Object> DeclareEvalHelper(Isolate* isolate, Handle<String> name,
// context and not the declaration context.
Handle<Context> context(isolate->context()->declaration_context(), isolate);
- // For debug-evaluate we always use sloppy eval, in which case context could
- // also be a module context. As module contexts reuse the extension slot
- // we need to check for this.
- const bool is_debug_evaluate_in_module =
- isolate->context()->IsDebugEvaluateContext() &&
- context->IsModuleContext();
+ // Regular JS inside a module is always strict, so direct sloppy eval can
+ // only reach a ModuleContext via debug-evaluate. Module contexts cannot be
+ // extended (their extension slot holds the SourceTextModule), so disallow
+ // hoisting var/function declarations into them altogether.
+ if (context->IsModuleContext()) {
+ DCHECK(HasDebugEvaluateContextInChain(isolate->context(), *context));
+ THROW_NEW_ERROR_RETURN_FAILURE(
+ isolate,
+ NewEvalError(MessageTemplate::kVarNotAllowedInEvalScope, name));
+ }
DCHECK(context->IsFunctionContext() || IsNativeContext(*context) ||
context->IsScriptContext() || context->IsEvalContext() ||
(context->IsBlockContext() &&
- context->scope_info()->is_declaration_scope()) ||
- is_debug_evaluate_in_module);
+ context->scope_info()->is_declaration_scope()));
bool is_var = IsUndefined(*value);
DCHECK_IMPLIES(!is_var, IsJSFunction(*value));
@@ -421,13 +435,29 @@ Tagged<Object> DeclareEvalHelper(Isolate* isolate, Handle<String> name,
}
if (attributes != ABSENT) {
+ // For regular sloppy eval, conflicts with lexical bindings (and with the
+ // implicit `arguments` binding in a non-simple parameter scope) are caught
+ // at parse time by DeclarationScope::CheckConflictingVarDeclarations.
+ // During debug-evaluate, deserializing a DebugEvaluateContext creates a
+ // DeclarationScope that stops that check before reaching enclosing
+ // contexts, so we can encounter lexical/read-only bindings here.
+ if (IsLexicalVariableMode(mode) || (attributes & READ_ONLY) != 0 ||
+ (index != Context::kNotFound && context->IsFunctionContext() &&
+ !context->scope_info()->HasSimpleParameters())) {
+ DCHECK(HasDebugEvaluateContextInChain(isolate->context(), *context));
+ return ThrowRedeclarationError(isolate, name,
+ RedeclarationType::kSyntaxError);
+ }
DCHECK_EQ(NONE, attributes);
+ DCHECK_EQ(VariableMode::kVar, mode);
+ DCHECK_EQ(kCreatedInitialized, init_flag);
// Skip var re-declarations.
if (is_var) return ReadOnlyRoots(isolate).undefined_value();
if (index != Context::kNotFound) {
DCHECK(holder.is_identical_to(context));
+ DCHECK(!context->IsElementTdzHole(index));
Context::Set(context, index, value, isolate);
Tagged<ScopeInfo> scope_info = context->scope_info();
int var_index = index - scope_info->ContextHeaderLength();
@@ -441,12 +471,12 @@ Tagged<Object> DeclareEvalHelper(Isolate* isolate, Handle<String> name,
}
object = Cast<JSObject>(holder);
+ DCHECK(IsJSContextExtensionObject(*object));
- } else if (context->has_extension() && !is_debug_evaluate_in_module) {
+ } else if (context->has_extension()) {
object = direct_handle(context->extension_object(), isolate);
DCHECK(IsJSContextExtensionObject(*object));
- } else if (context->scope_info()->HasContextExtensionSlot() &&
- !is_debug_evaluate_in_module) {
+ } else if (context->scope_info()->HasContextExtensionSlot()) {
// Sloppy varblock and function contexts might not have an extension object
// yet. Sloppy eval will never have an extension object, as vars are hoisted
// out, and lets are known statically.
@@ -820,9 +850,17 @@ MaybeDirectHandle<Object> LoadLookupSlot(
if (!holder.is_null() && IsSourceTextModule(*holder)) {
Handle<Object> receiver = isolate->factory()->undefined_value();
- if (receiver_return) *receiver_return = receiver;
- return SourceTextModule::LoadVariable(
+ Handle<Object> value = SourceTextModule::LoadVariable(
isolate, Cast<SourceTextModule>(holder), index);
+ // Check for uninitialized bindings. This looks at the value rather than
+ // at {flag}, so that it also covers imports, whose cell belongs to the
+ // exporting module. The hole must never escape as a value.
+ if (IsTdzHole(*value)) {
+ THROW_NEW_ERROR(isolate,
+ NewReferenceError(MessageTemplate::kNotDefined, name));
+ }
+ if (receiver_return) *receiver_return = receiver;
+ return value;
}
if (index != Context::kNotFound) {
DCHECK(IsContext(*holder));
@@ -940,9 +978,14 @@ MaybeDirectHandle<Object> StoreLookupSlot(
// In case of JSProxy, an exception might have been thrown.
if (isolate->has_exception()) return MaybeDirectHandle<Object>();
} else if (IsSourceTextModule(*holder)) {
+ DirectHandle<SourceTextModule> module = Cast<SourceTextModule>(holder);
+ // Check for uninitialized bindings, see LoadLookupSlot.
+ if (IsTdzHole(*SourceTextModule::LoadVariable(isolate, module, index))) {
+ THROW_NEW_ERROR(isolate,
+ NewReferenceError(MessageTemplate::kNotDefined, name));
+ }
if ((attributes & READ_ONLY) == 0) {
- SourceTextModule::StoreVariable(Cast<SourceTextModule>(holder), index,
- value);
+ SourceTextModule::StoreVariable(module, index, value);
} else {
THROW_NEW_ERROR(isolate, NewTypeError(MessageTemplate::kConstAssign));
}
diff --git a/deps/v8/src/sandbox/js-dispatch-table-inl.h b/deps/v8/src/sandbox/js-dispatch-table-inl.h
index 8755de05faf..ec7161adeb3 100644
--- a/deps/v8/src/sandbox/js-dispatch-table-inl.h
+++ b/deps/v8/src/sandbox/js-dispatch-table-inl.h
@@ -512,10 +512,10 @@ bool JSDispatchTable::IsCompatibleCode(Tagged<Code> code,
// Signature mismatch. This is mostly not safe, except for certain varargs
// builtins which are able to correctly handle such a mismatch. Examples
- // include builtins like the InterpreterEntryTrampoline or the JSToWasm and
- // JSToJS wrappers which determine their actual parameter count at runtime
- // (see CodeStubAssembler::SetSupportsDynamicParameterCount()), or internal
- // builtins that end up tailcalling into other code such as CompileLazy.
+ // include builtins like the InterpreterEntryTrampoline or the JSToWasm
+ // wrappers which determine their actual parameter count at runtime (see
+ // CodeStubAssembler::EmitBuiltinProlog()), or internal builtins that end up
+ // tailcalling into other code such as CompileLazy.
//
// Currently, we also allow this for testing code (from our test suites).
// TODO(saelo): maybe we should also forbid this just to be sure.
diff --git a/deps/v8/src/torque/constants.h b/deps/v8/src/torque/constants.h
index b057b9f2111..42784765e95 100644
--- a/deps/v8/src/torque/constants.h
+++ b/deps/v8/src/torque/constants.h
@@ -44,7 +44,6 @@ static const char* const EXTERNALPTR_TYPE_STRING = "ExternalPointer";
static const char* const CPPHEAPPTR_TYPE_STRING = "CppHeapPointer";
static const char* const TRUSTEDPTR_TYPE_STRING = "TrustedPointer";
static const char* const PROTECTEDPTR_TYPE_STRING = "ProtectedPointer";
-static const char* const DISPATCH_HANDLE_TYPE_STRING = "DispatchHandle";
static const char* const CONST_STRING_TYPE_STRING = "constexpr string";
static const char* const STRING_TYPE_STRING = "String";
static const char* const NUMBER_TYPE_STRING = "Number";
diff --git a/deps/v8/src/torque/implementation-visitor.cc b/deps/v8/src/torque/implementation-visitor.cc
index f796a3f0487..c521045b1bb 100644
--- a/deps/v8/src/torque/implementation-visitor.cc
+++ b/deps/v8/src/torque/implementation-visitor.cc
@@ -761,22 +761,6 @@ void ImplementationVisitor::Visit(Builtin* builtin) {
<< "Descriptor::kJSTarget);\n";
csa_ccfile() << " USE(" << generated_name << ");\n";
expected_types = {TypeOracle::GetJSFunctionType()};
- } else if (param_name == "dispatchHandle") {
- if (V8_JS_LINKAGE_INCLUDES_DISPATCH_HANDLE_BOOL) {
- csa_ccfile() << " TNode<JSDispatchHandleT> " << generated_name
- << " = "
- "UncheckedParameter<JSDispatchHandleT>(Descriptor::"
- "kJSDispatchHandle);\n";
- } else {
- csa_ccfile() << " TNode<JSDispatchHandleT> " << generated_name
- << " = "
- "ReinterpretCast<JSDispatchHandleT>("
- "LoadJSFunctionDispatchHandle("
- "UncheckedParameter<JSFunction>("
- << "Descriptor::kJSTarget)));\n";
- }
- csa_ccfile() << " USE(" << generated_name << ");\n";
- expected_types = {TypeOracle::GetDispatchHandleType()};
} else {
Error(
"Unexpected implicit parameter \"", param_name,
diff --git a/deps/v8/src/torque/type-oracle.h b/deps/v8/src/torque/type-oracle.h
index b96f347e1bb..18eddedb16b 100644
--- a/deps/v8/src/torque/type-oracle.h
+++ b/deps/v8/src/torque/type-oracle.h
@@ -213,10 +213,6 @@ class TypeOracle : public base::ContextualClass<TypeOracle> {
return Get().GetBuiltinType(PROTECTEDPTR_TYPE_STRING);
}
- static const Type* GetDispatchHandleType() {
- return Get().GetBuiltinType(DISPATCH_HANDLE_TYPE_STRING);
- }
-
static const Type* GetMapType() {
return Get().GetBuiltinType(MAP_TYPE_STRING);
}
diff --git a/deps/v8/test/cctest/compiler/test-code-generator.cc b/deps/v8/test/cctest/compiler/test-code-generator.cc
index b8a589edab7..2b7e42d303f 100644
--- a/deps/v8/test/cctest/compiler/test-code-generator.cc
+++ b/deps/v8/test/cctest/compiler/test-code-generator.cc
@@ -2014,6 +2014,198 @@ TEST(GapMoveCycleMixedRep) {
}
#endif
+#if V8_TARGET_ARCH_64_BIT
+TEST(GapMoveCycleMixedGpRep) {
+ enum class CycleKind {
+ kRegToRegWithScratchReg,
+ kRegToRegWithStackTemp,
+ kStackToRegWithScratchReg,
+ };
+
+ HandleAndZoneScope scope;
+ Isolate* isolate = scope.main_isolate();
+
+ auto RunCycleCheck = [isolate](MachineRepresentation src_rep,
+ MachineRepresentation dst_rep, CycleKind kind,
+ uint64_t payload) {
+ HandleScope handles(isolate);
+ Zone local_zone(isolate->allocator(), ZONE_NAME);
+ Zone* zone = &local_zone;
+
+ MachineSignature::Builder sig_builder(zone, 1, 0);
+ sig_builder.AddReturn(MachineType::Uint64());
+ CallDescriptor* desc = Linkage::GetSimplifiedCDescriptor(
+ zone, sig_builder.Get(), CallDescriptor::kInitializeRootRegister);
+ Linkage linkage(desc);
+
+ ZoneVector<InstructionBlock*> blocks(zone);
+ InstructionBlock* block = zone->New<InstructionBlock>(
+ zone, RpoNumber::FromInt(0), RpoNumber::Invalid(), RpoNumber::Invalid(),
+ RpoNumber::Invalid(), false, false);
+ block->mark_needs_frame();
+ block->mark_must_construct_frame();
+ blocks.push_back(block);
+
+ InstructionSequence sequence(isolate, zone, &blocks);
+ Frame frame(desc->CalculateFixedFrameSize(CodeKind::FOR_TESTING), zone);
+
+ int s0_index = frame.AllocateSpillSlot(kSystemPointerSize);
+ int s1_index = frame.AllocateSpillSlot(kSystemPointerSize);
+
+ const RegisterConfiguration* config = RegisterConfiguration::Default();
+ int r0_code = -1;
+ int r1_code = -1;
+ for (int i = 0; i < config->num_allocatable_general_registers(); ++i) {
+ int code = config->GetAllocatableGeneralCode(i);
+ if (code == kReturnRegister0.code()) continue;
+ if (r0_code == -1) {
+ r0_code = code;
+ } else {
+ r1_code = code;
+ break;
+ }
+ }
+ CHECK_NE(r0_code, -1);
+ CHECK_NE(r1_code, -1);
+
+ BitVector* allocated_regs =
+ zone->New<BitVector>(config->num_general_registers(), zone);
+ allocated_regs->Add(r0_code);
+ allocated_regs->Add(r1_code);
+ for (Register reg : desc->CalleeSavedRegisters()) {
+ if (config->IsAllocatableGeneralCode(reg.code())) {
+ allocated_regs->Add(reg.code());
+ break;
+ }
+ }
+ frame.SetAllocatedRegisters(allocated_regs);
+ frame.SetAllocatedDoubleRegisters(
+ zone->New<BitVector>(config->num_double_registers(), zone));
+
+ sequence.StartBlock(RpoNumber::FromInt(0));
+
+ auto AddU64Constant = [&](uint64_t val) {
+ int vreg = sequence.NextVirtualRegister();
+ sequence.AddConstant(vreg, Constant(static_cast<int64_t>(val)));
+ return ConstantOperand(vreg);
+ };
+
+ ConstantOperand payload_op = AddU64Constant(payload);
+ ConstantOperand other0_op = AddU64Constant(0x1122334455667788ULL);
+ ConstantOperand other1_op = AddU64Constant(0x99AABBCCDDEEFF00ULL);
+ ConstantOperand other2_op = AddU64Constant(0x2468ACE013579BDFULL);
+
+ AllocatedOperand r0_w64(LocationOperand::REGISTER,
+ MachineRepresentation::kWord64, r0_code);
+ AllocatedOperand r0_src(LocationOperand::REGISTER, src_rep, r0_code);
+ AllocatedOperand r1_w64(LocationOperand::REGISTER,
+ MachineRepresentation::kWord64, r1_code);
+ AllocatedOperand r1_dst(LocationOperand::REGISTER, dst_rep, r1_code);
+ AllocatedOperand s0_w64(LocationOperand::STACK_SLOT,
+ MachineRepresentation::kWord64, s0_index);
+ AllocatedOperand s0_src(LocationOperand::STACK_SLOT, src_rep, s0_index);
+ AllocatedOperand s1_w64(LocationOperand::STACK_SLOT,
+ MachineRepresentation::kWord64, s1_index);
+
+ Instruction* init_nop = Instruction::New(zone, kArchNop);
+ ParallelMove* init_moves =
+ init_nop->GetOrCreateParallelMove(Instruction::START, zone);
+ if (kind == CycleKind::kStackToRegWithScratchReg) {
+ init_moves->AddMove(payload_op, s0_w64);
+ init_moves->AddMove(other0_op, r0_w64);
+ } else {
+ init_moves->AddMove(payload_op, r0_w64);
+ init_moves->AddMove(other0_op, s0_w64);
+ }
+ init_moves->AddMove(other1_op, r1_w64);
+ init_moves->AddMove(other2_op, s1_w64);
+ sequence.AddInstruction(init_nop);
+
+ Instruction* cycle_nop = Instruction::New(zone, kArchNop);
+ ParallelMove* cycle_moves =
+ cycle_nop->GetOrCreateParallelMove(Instruction::START, zone);
+ // Order each cycle so that the mixed-width move into r1_dst is the direct
+ // blocker of cycle_moves[0] and therefore becomes cycle.back() in
+ // GapResolver::PerformCycle.
+ switch (kind) {
+ case CycleKind::kRegToRegWithScratchReg:
+ cycle_moves->AddMove(r1_w64, r0_w64);
+ cycle_moves->AddMove(r0_src, r1_dst);
+ break;
+ case CycleKind::kRegToRegWithStackTemp:
+ cycle_moves->AddMove(s1_w64, r0_w64);
+ cycle_moves->AddMove(s0_w64, s1_w64);
+ cycle_moves->AddMove(r1_w64, s0_w64);
+ cycle_moves->AddMove(r0_src, r1_dst);
+ break;
+ case CycleKind::kStackToRegWithScratchReg:
+ cycle_moves->AddMove(r1_w64, s0_w64);
+ cycle_moves->AddMove(s0_src, r1_dst);
+ break;
+ }
+ sequence.AddInstruction(cycle_nop);
+
+ InstructionOperand ret_inputs[] = {
+ ImmediateOperand(ImmediateOperand::INLINE_INT32, 0),
+ AllocatedOperand(LocationOperand::REGISTER,
+ MachineRepresentation::kWord64,
+ kReturnRegister0.code())};
+ Instruction* ret_instr =
+ Instruction::New(zone, kArchRet, 0, nullptr, arraysize(ret_inputs),
+ ret_inputs, 0, nullptr);
+ ParallelMove* pre_ret =
+ ret_instr->GetOrCreateParallelMove(Instruction::START, zone);
+ pre_ret->AddMove(r1_w64, AllocatedOperand(LocationOperand::REGISTER,
+ MachineRepresentation::kWord64,
+ kReturnRegister0.code()));
+
+ sequence.AddInstruction(ret_instr);
+ sequence.EndBlock(RpoNumber::FromInt(0));
+
+ OptimizedCompilationInfo info("gap_cycle_mixed_gp_rep", zone,
+ CodeKind::FOR_TESTING);
+ CodeGenerator codegen(zone, &frame, &linkage, &sequence, &info, isolate,
+ std::optional<OsrHelper>(), kNoSourcePosition,
+ nullptr, AssemblerOptions::Default(isolate),
+ Builtin::kNoBuiltinId, 0, 0);
+ codegen.AssembleCode();
+ DirectHandle<Code> code = codegen.FinalizeCode().ToHandleChecked();
+ auto fn = GeneratedCode<uint64_t>::FromCode(isolate, *code);
+ CHECK_EQ(payload, fn.Call());
+ };
+
+ static constexpr uint64_t kFull64Payload = 0x7123456789ABCDEFULL;
+ // Bit 31 set with zero upper 32 bits, to catch accidental sign-extension of
+ // zero-extended 32-bit values moved into 64-bit destinations.
+ static constexpr uint64_t kZeroExtended32Payload = 0x0000000089ABCDEFULL;
+
+ for (CycleKind kind :
+ {CycleKind::kRegToRegWithScratchReg, CycleKind::kRegToRegWithStackTemp,
+ CycleKind::kStackToRegWithScratchReg}) {
+ // 64-bit source to 32-bit destination must preserve upper 32 bits.
+ RunCycleCheck(MachineRepresentation::kWord64,
+ MachineRepresentation::kWord32, kind, kFull64Payload);
+ RunCycleCheck(MachineRepresentation::kSandboxedPointer,
+ MachineRepresentation::kWord32, kind, kFull64Payload);
+ RunCycleCheck(MachineRepresentation::kTagged,
+ MachineRepresentation::kWord32, kind, kFull64Payload);
+ RunCycleCheck(MachineRepresentation::kTaggedSigned,
+ MachineRepresentation::kWord32, kind, kFull64Payload);
+#ifdef V8_COMPRESS_POINTERS
+ RunCycleCheck(MachineRepresentation::kWord64,
+ MachineRepresentation::kCompressed, kind, kFull64Payload);
+ RunCycleCheck(MachineRepresentation::kTagged,
+ MachineRepresentation::kCompressed, kind, kFull64Payload);
+#endif
+ // 32-bit source holding a zero-extended 64-bit value to 64-bit destination.
+ RunCycleCheck(MachineRepresentation::kWord32,
+ MachineRepresentation::kWord64, kind, kZeroExtended32Payload);
+ RunCycleCheck(MachineRepresentation::kWord32,
+ MachineRepresentation::kTagged, kind, kZeroExtended32Payload);
+ }
+}
+#endif // V8_TARGET_ARCH_64_BIT
+
#if V8_ENABLE_WEBASSEMBLY
namespace {
diff --git a/deps/v8/test/inspector/debugger/evaluate-on-call-frame-module-tdz-expected.txt b/deps/v8/test/inspector/debugger/evaluate-on-call-frame-module-tdz-expected.txt
new file mode 100644
index 00000000000..66c278cf2d7
--- /dev/null
+++ b/deps/v8/test/inspector/debugger/evaluate-on-call-frame-module-tdz-expected.txt
@@ -0,0 +1,28 @@
+Tests that Debugger.evaluateOnCallFrame respects the TDZ of module bindings.
+Paused in a function, bindings in TDZ:
+ exportedLet => throws ReferenceError: exportedLet is not defined
+ typeof exportedLet => throws ReferenceError: exportedLet is not defined
+ exportedConst => throws ReferenceError: exportedConst is not defined
+ ExportedClass => throws ReferenceError: ExportedClass is not defined
+ importedLet => throws ReferenceError: importedLet is not defined
+ exportedLet = 4 => throws ReferenceError: exportedLet is not defined
+ exportedConst = 4 => throws ReferenceError: exportedConst is not defined
+ importedLet = 4 => throws ReferenceError: importedLet is not defined
+ param = exportedLet => throws ReferenceError: exportedLet is not defined
+ param = importedLet, param = 5 => throws ReferenceError: importedLet is not defined
+ param => 1
+Paused at module top-level, bindings in TDZ:
+ exportedLet => throws ReferenceError: exportedLet is not defined
+ importedLet => throws ReferenceError: importedLet is not defined
+ exportedLet = 4 => throws ReferenceError: exportedLet is not defined
+ readParam() => 1
+Paused at module top-level, initialized:
+ exportedLet => 2
+ importedLet => 2
+ exportedConst => 3
+ typeof ExportedClass => function
+ exportedLet = 4 => 4
+ importedLet => 4
+ exportedConst = 4 => throws TypeError: Assignment to constant variable.
+ importedLet = 5 => throws TypeError: Assignment to constant variable.
+ readParam() => 1
diff --git a/deps/v8/test/inspector/debugger/evaluate-on-call-frame-module-tdz.js b/deps/v8/test/inspector/debugger/evaluate-on-call-frame-module-tdz.js
new file mode 100644
index 00000000000..1ba79b92e8a
--- /dev/null
+++ b/deps/v8/test/inspector/debugger/evaluate-on-call-frame-module-tdz.js
@@ -0,0 +1,97 @@
+// Copyright 2026 the V8 project authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+const {session, contextGroup, Protocol} = InspectorTest.start(
+ 'Tests that Debugger.evaluateOnCallFrame respects the TDZ of module ' +
+ 'bindings.');
+
+const moduleName = 'evaluate-on-call-frame-module-tdz.mjs';
+
+// The module imports from itself so that it also has an import binding that
+// is still in its TDZ while the module body runs.
+const moduleSource = `
+import {exportedLet as importedLet} from '${moduleName}';
+
+function host(param) {
+ globalThis.readParam = () => param;
+ debugger;
+}
+host(1);
+debugger;
+
+export let exportedLet = 2;
+export const exportedConst = 3;
+export class ExportedClass {}
+debugger;
+`;
+
+async function evaluate(callFrameId, expression) {
+ const response =
+ await Protocol.Debugger.evaluateOnCallFrame({callFrameId, expression});
+ if (response.error) {
+ InspectorTest.log(` ${expression} => error ${response.error.message}`);
+ return;
+ }
+ const {result, exceptionDetails} = response.result;
+ if (exceptionDetails) {
+ const [message] = exceptionDetails.exception.description.split('\n');
+ InspectorTest.log(` ${expression} => throws ${message}`);
+ } else {
+ InspectorTest.log(` ${expression} => ${result.value}`);
+ }
+}
+
+async function evaluateAllOnPause(title, expressions) {
+ const {params: {callFrames: [{callFrameId}]}} =
+ await Protocol.Debugger.oncePaused();
+ InspectorTest.log(title);
+ for (const expression of expressions) {
+ await evaluate(callFrameId, expression);
+ }
+ await Protocol.Debugger.resume();
+}
+
+(async function test() {
+ await Protocol.Debugger.enable();
+ contextGroup.addModule(moduleSource, moduleName);
+
+ await evaluateAllOnPause('Paused in a function, bindings in TDZ:', [
+ // Reads.
+ 'exportedLet',
+ 'typeof exportedLet',
+ 'exportedConst',
+ 'ExportedClass',
+ 'importedLet',
+ // Writes.
+ 'exportedLet = 4',
+ 'exportedConst = 4',
+ 'importedLet = 4',
+ // The value of an uninitialized binding must not reach other variables.
+ 'param = exportedLet',
+ 'param = importedLet, param = 5',
+ 'param',
+ ]);
+
+ await evaluateAllOnPause('Paused at module top-level, bindings in TDZ:', [
+ 'exportedLet',
+ 'importedLet',
+ 'exportedLet = 4',
+ 'readParam()',
+ ]);
+
+ await evaluateAllOnPause('Paused at module top-level, initialized:', [
+ 'exportedLet',
+ 'importedLet',
+ 'exportedConst',
+ 'typeof ExportedClass',
+ 'exportedLet = 4',
+ 'importedLet',
+ 'exportedConst = 4',
+ 'importedLet = 5',
+ 'readParam()',
+ ]);
+
+ await Protocol.Debugger.disable();
+ InspectorTest.completeTest();
+})();
diff --git a/deps/v8/test/inspector/debugger/evaluate-on-call-frame-redeclaration-expected.txt b/deps/v8/test/inspector/debugger/evaluate-on-call-frame-redeclaration-expected.txt
new file mode 100644
index 00000000000..963b214bcfc
--- /dev/null
+++ b/deps/v8/test/inspector/debugger/evaluate-on-call-frame-redeclaration-expected.txt
@@ -0,0 +1,67 @@
+Tests var and function declarations in Debugger.evaluateOnCallFrame.
+
+Running test: testModuleExportsRepro
+function e1(){}: EvalError: Identifier 'e1' cannot be declared with 'var' in current evaluation scope, consider trying 'let' instead
+function e2(){}: EvalError: Identifier 'e2' cannot be declared with 'var' in current evaluation scope, consider trying 'let' instead
+function e3(){}: EvalError: Identifier 'e3' cannot be declared with 'var' in current evaluation scope, consider trying 'let' instead
+var e1 = 99;: EvalError: Identifier 'e1' cannot be declared with 'var' in current evaluation scope, consider trying 'let' instead
+{ function e1(){} }: EvalError: Identifier 'e1' cannot be declared with 'var' in current evaluation scope, consider trying 'let' instead
+function c(){}: EvalError: Identifier 'c' cannot be declared with 'var' in current evaluation scope, consider trying 'let' instead
+var c = 99;: EvalError: Identifier 'c' cannot be declared with 'var' in current evaluation scope, consider trying 'let' instead
+function fn(){}: EvalError: Identifier 'fn' cannot be declared with 'var' in current evaluation scope, consider trying 'let' instead
+function localLet(){}: EvalError: Identifier 'localLet' cannot be declared with 'var' in current evaluation scope, consider trying 'let' instead
+var localLet = 99;: EvalError: Identifier 'localLet' cannot be declared with 'var' in current evaluation scope, consider trying 'let' instead
+function localConst(){}: EvalError: Identifier 'localConst' cannot be declared with 'var' in current evaluation scope, consider trying 'let' instead
+var missing = 1;: EvalError: Identifier 'missing' cannot be declared with 'var' in current evaluation scope, consider trying 'let' instead
+function missing(){}: EvalError: Identifier 'missing' cannot be declared with 'var' in current evaluation scope, consider trying 'let' instead
+var v = 11;: EvalError: Identifier 'v' cannot be declared with 'var' in current evaluation scope, consider trying 'let' instead
+function v(){ return 42; }: EvalError: Identifier 'v' cannot be declared with 'var' in current evaluation scope, consider trying 'let' instead
+var localVar = 41;: EvalError: Identifier 'localVar' cannot be declared with 'var' in current evaluation scope, consider trying 'let' instead
+function localVar(){ return 84; }: EvalError: Identifier 'localVar' cannot be declared with 'var' in current evaluation scope, consider trying 'let' instead
+after: {"e1":1,"e2":2,"e3":3,"c":4,"fn":"orig","v":10,"localLet":20,"localConst":30,"localVar":40}
+
+Running test: testModuleTopLevel
+function e(){}: EvalError: Identifier 'e' cannot be declared with 'var' in current evaluation scope, consider trying 'let' instead
+var e;: EvalError: Identifier 'e' cannot be declared with 'var' in current evaluation scope, consider trying 'let' instead
+
+Running test: testModuleImports
+function dep1(){}: EvalError: Identifier 'dep1' cannot be declared with 'var' in current evaluation scope, consider trying 'let' instead
+function dep2(){}: EvalError: Identifier 'dep2' cannot be declared with 'var' in current evaluation scope, consider trying 'let' instead
+function depVar(){}: EvalError: Identifier 'depVar' cannot be declared with 'var' in current evaluation scope, consider trying 'let' instead
+var dep1;: EvalError: Identifier 'dep1' cannot be declared with 'var' in current evaluation scope, consider trying 'let' instead
+function ns(){}: EvalError: Identifier 'ns' cannot be declared with 'var' in current evaluation scope, consider trying 'let' instead
+after: {"dep1":1,"dep2":2,"depVar":3,"nsDep1":1}
+
+Running test: testModuleNestedEvalContexts
+with ({}) { eval("var x = 1"); }: EvalError: Identifier 'x' cannot be declared with 'var' in current evaluation scope, consider trying 'let' instead
+with ({}) { eval("function e(){}"); }: EvalError: Identifier 'e' cannot be declared with 'var' in current evaluation scope, consider trying 'let' instead
+try { throw 1; } catch (_) { eval("var x = 1"); }: EvalError: Identifier 'x' cannot be declared with 'var' in current evaluation scope, consider trying 'let' instead
+{ let z = 1; (() => z); eval("var x = 1"); }: EvalError: Identifier 'x' cannot be declared with 'var' in current evaluation scope, consider trying 'let' instead
+let z = 1; (() => z); eval("var x = 1");: EvalError: Identifier 'x' cannot be declared with 'var' in current evaluation scope, consider trying 'let' instead
+let z = 1; (() => z); var x = 1;: EvalError: Identifier 'x' cannot be declared with 'var' in current evaluation scope, consider trying 'let' instead
+let z = 1; (() => z); function x(){}: EvalError: Identifier 'x' cannot be declared with 'var' in current evaluation scope, consider trying 'let' instead
+
+Running test: testFunctionContextBindings
+function c(){}: SyntaxError: Identifier 'c' has already been declared
+var c = 9;: SyntaxError: Identifier 'c' has already been declared
+function l(){}: SyntaxError: Identifier 'l' has already been declared
+var l = 9;: SyntaxError: Identifier 'l' has already been declared
+function v(){ return 77; }: ok (undefined)
+var missing = 1;: EvalError: Identifier 'missing' cannot be declared with 'var' in current evaluation scope, consider trying 'let' instead
+runOuterBindings: {"c":1,"l":2,"vType":"function","vVal":77}
+function l(){}: SyntaxError: Identifier 'l' has already been declared
+function c(){}: SyntaxError: Identifier 'c' has already been declared
+runOuterTdz: [123,456]
+function a(){}: SyntaxError: Identifier 'a' has already been declared
+function arguments(){}: SyntaxError: Identifier 'arguments' has already been declared
+runNonSimpleParams: [null,0]
+
+Running test: testStrictEvalAndStaticBlock
+function c(){}: SyntaxError: Identifier 'c' has already been declared
+function l(){}: SyntaxError: Identifier 'l' has already been declared
+var missing = 1;: EvalError: Identifier 'missing' cannot be declared with 'var' in current evaluation scope, consider trying 'let' instead
+strictEval: 1,2
+function c(){}: SyntaxError: Identifier 'c' has already been declared
+function l(){}: SyntaxError: Identifier 'l' has already been declared
+var missing = 1;: EvalError: Identifier 'missing' cannot be declared with 'var' in current evaluation scope, consider trying 'let' instead
+staticBlock: [1,2]
diff --git a/deps/v8/test/inspector/debugger/evaluate-on-call-frame-redeclaration.js b/deps/v8/test/inspector/debugger/evaluate-on-call-frame-redeclaration.js
new file mode 100644
index 00000000000..8aa7d87c035
--- /dev/null
+++ b/deps/v8/test/inspector/debugger/evaluate-on-call-frame-redeclaration.js
@@ -0,0 +1,245 @@
+// Copyright 2026 the V8 project authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+const {contextGroup, Protocol} = InspectorTest.start(
+ 'Tests var and function declarations in Debugger.evaluateOnCallFrame.');
+
+function logResult(label, response) {
+ if (response.result.exceptionDetails) {
+ const desc = response.result.exceptionDetails.exception.description;
+ InspectorTest.log(`${label}: ${desc.split('\n')[0]}`);
+ } else {
+ InspectorTest.log(
+ `${label}: ok (${JSON.stringify(response.result.result.value)})`);
+ }
+}
+
+async function evalOnTopFrame(callFrameId, expression) {
+ const response = await Protocol.Debugger.evaluateOnCallFrame({
+ callFrameId,
+ expression,
+ });
+ logResult(expression, response);
+}
+
+InspectorTest.runAsyncTestSuite([
+ async function testModuleExportsRepro() {
+ await Protocol.Debugger.enable();
+ contextGroup.addModule(
+ `
+ export let e1 = 1;
+ export let e2 = 2;
+ export let e3 = 3;
+ export const c = 4;
+ export function fn() { return 'orig'; }
+ export var v = 10;
+ let localLet = 20;
+ const localConst = 30;
+ var localVar = 40;
+ function keepCaptured() { return [localLet, localConst, localVar]; }
+ function f() { debugger; }
+ f();
+ globalThis.moduleExportsAfter = {
+ e1, e2, e3, c, fn: fn(), v, localLet, localConst, localVar,
+ };
+ `,
+ 'mod-exports');
+
+ const {params: {callFrames: [{callFrameId}]}} =
+ await Protocol.Debugger.oncePaused();
+
+ await evalOnTopFrame(callFrameId, 'function e1(){}');
+ await evalOnTopFrame(callFrameId, 'function e2(){}');
+ await evalOnTopFrame(callFrameId, 'function e3(){}');
+ await evalOnTopFrame(callFrameId, 'var e1 = 99;');
+ await evalOnTopFrame(callFrameId, '{ function e1(){} }');
+ await evalOnTopFrame(callFrameId, 'function c(){}');
+ await evalOnTopFrame(callFrameId, 'var c = 99;');
+ await evalOnTopFrame(callFrameId, 'function fn(){}');
+ await evalOnTopFrame(callFrameId, 'function localLet(){}');
+ await evalOnTopFrame(callFrameId, 'var localLet = 99;');
+ await evalOnTopFrame(callFrameId, 'function localConst(){}');
+ await evalOnTopFrame(callFrameId, 'var missing = 1;');
+ await evalOnTopFrame(callFrameId, 'function missing(){}');
+ await evalOnTopFrame(callFrameId, 'var v = 11;');
+ await evalOnTopFrame(callFrameId, 'function v(){ return 42; }');
+ await evalOnTopFrame(callFrameId, 'var localVar = 41;');
+ await evalOnTopFrame(callFrameId, 'function localVar(){ return 84; }');
+
+ await Protocol.Debugger.resume();
+ const {result: {result: {value}}} = await Protocol.Runtime.evaluate({
+ expression: 'JSON.stringify(globalThis.moduleExportsAfter)',
+ });
+ InspectorTest.log('after: ' + value);
+ },
+
+ async function testModuleTopLevel() {
+ contextGroup.addModule(
+ `
+ export let e = 1;
+ debugger;
+ `,
+ 'mod-toplevel');
+
+ const {params: {callFrames: [{callFrameId}]}} =
+ await Protocol.Debugger.oncePaused();
+ await evalOnTopFrame(callFrameId, 'function e(){}');
+ await evalOnTopFrame(callFrameId, 'var e;');
+ await Protocol.Debugger.resume();
+ },
+
+ async function testModuleImports() {
+ contextGroup.addModule(
+ `
+ export let dep1 = 1;
+ export let dep2 = 2;
+ export var depVar = 3;
+ `,
+ 'mod-dep');
+ contextGroup.addModule(
+ `
+ import {dep1, dep2, depVar} from 'mod-dep';
+ import * as ns from 'mod-dep';
+ function keepNs() { return ns.dep1; }
+ function f() { debugger; }
+ f();
+ globalThis.moduleImportsAfter = {dep1, dep2, depVar, nsDep1: keepNs()};
+ `,
+ 'mod-imports');
+
+ const {params: {callFrames: [{callFrameId}]}} =
+ await Protocol.Debugger.oncePaused();
+ await evalOnTopFrame(callFrameId, 'function dep1(){}');
+ await evalOnTopFrame(callFrameId, 'function dep2(){}');
+ await evalOnTopFrame(callFrameId, 'function depVar(){}');
+ await evalOnTopFrame(callFrameId, 'var dep1;');
+ await evalOnTopFrame(callFrameId, 'function ns(){}');
+ await Protocol.Debugger.resume();
+ const {result: {result: {value}}} = await Protocol.Runtime.evaluate({
+ expression: 'JSON.stringify(globalThis.moduleImportsAfter)',
+ });
+ InspectorTest.log('after: ' + value);
+ },
+
+ async function testModuleNestedEvalContexts() {
+ contextGroup.addModule(
+ `
+ export let e = 1;
+ function f() { debugger; }
+ f();
+ `,
+ 'mod-nested');
+
+ const {params: {callFrames: [{callFrameId}]}} =
+ await Protocol.Debugger.oncePaused();
+ await evalOnTopFrame(callFrameId, 'with ({}) { eval("var x = 1"); }');
+ await evalOnTopFrame(callFrameId, 'with ({}) { eval("function e(){}"); }');
+ await evalOnTopFrame(
+ callFrameId, 'try { throw 1; } catch (_) { eval("var x = 1"); }');
+ await evalOnTopFrame(
+ callFrameId, '{ let z = 1; (() => z); eval("var x = 1"); }');
+ await evalOnTopFrame(
+ callFrameId, 'let z = 1; (() => z); eval("var x = 1");');
+ await evalOnTopFrame(
+ callFrameId, 'let z = 1; (() => z); var x = 1;');
+ await evalOnTopFrame(
+ callFrameId, 'let z = 1; (() => z); function x(){}');
+ await Protocol.Debugger.resume();
+ },
+
+ async function testFunctionContextBindings() {
+ contextGroup.addScript(`
+ function runOuterBindings() {
+ const c = 1;
+ let l = 2;
+ var v = 3;
+ function keep() { return [c, l, v]; }
+ function f() { debugger; }
+ f();
+ return {c, l, vType: typeof v, vVal: v()};
+ }
+ function runOuterTdz() {
+ (function f() { debugger; })();
+ let l = 123;
+ const c = 456;
+ function keep() { return [l, c]; }
+ return keep();
+ }
+ function runNonSimpleParams(a = (function f() { debugger; })()) {
+ const keep = () => [a, arguments.length];
+ return keep();
+ }
+ `);
+
+ {
+ const paused = Protocol.Debugger.oncePaused();
+ const run = Protocol.Runtime.evaluate(
+ {expression: 'JSON.stringify(runOuterBindings())'});
+ const {params: {callFrames: [{callFrameId}]}} = await paused;
+ await evalOnTopFrame(callFrameId, 'function c(){}');
+ await evalOnTopFrame(callFrameId, 'var c = 9;');
+ await evalOnTopFrame(callFrameId, 'function l(){}');
+ await evalOnTopFrame(callFrameId, 'var l = 9;');
+ await evalOnTopFrame(callFrameId, 'function v(){ return 77; }');
+ await evalOnTopFrame(callFrameId, 'var missing = 1;');
+ await Protocol.Debugger.resume();
+ const {result: {result: {value}}} = await run;
+ InspectorTest.log('runOuterBindings: ' + value);
+ }
+
+ {
+ const paused = Protocol.Debugger.oncePaused();
+ const run = Protocol.Runtime.evaluate(
+ {expression: 'JSON.stringify(runOuterTdz())'});
+ const {params: {callFrames: [{callFrameId}]}} = await paused;
+ await evalOnTopFrame(callFrameId, 'function l(){}');
+ await evalOnTopFrame(callFrameId, 'function c(){}');
+ await Protocol.Debugger.resume();
+ const {result: {result: {value}}} = await run;
+ InspectorTest.log('runOuterTdz: ' + value);
+ }
+
+ {
+ const paused = Protocol.Debugger.oncePaused();
+ const run = Protocol.Runtime.evaluate(
+ {expression: 'JSON.stringify(runNonSimpleParams())'});
+ const {params: {callFrames: [{callFrameId}]}} = await paused;
+ await evalOnTopFrame(callFrameId, 'function a(){}');
+ await evalOnTopFrame(callFrameId, 'function arguments(){}');
+ await Protocol.Debugger.resume();
+ const {result: {result: {value}}} = await run;
+ InspectorTest.log('runNonSimpleParams: ' + value);
+ }
+ },
+
+ async function testStrictEvalAndStaticBlock() {
+ {
+ const paused = Protocol.Debugger.oncePaused();
+ const run = Protocol.Runtime.evaluate({
+ expression: `eval('"use strict"; const c = 1; let l = 2; (() => [c, l]); (function f() { debugger; })(); [c, l];').toString()`,
+ });
+ const {params: {callFrames: [{callFrameId}]}} = await paused;
+ await evalOnTopFrame(callFrameId, 'function c(){}');
+ await evalOnTopFrame(callFrameId, 'function l(){}');
+ await evalOnTopFrame(callFrameId, 'var missing = 1;');
+ await Protocol.Debugger.resume();
+ const {result: {result: {value}}} = await run;
+ InspectorTest.log('strictEval: ' + value);
+ }
+
+ {
+ const paused = Protocol.Debugger.oncePaused();
+ const run = Protocol.Runtime.evaluate({
+ expression: `(() => { let res; class C { static { const c = 1; let l = 2; (() => [c, l]); (function f() { debugger; })(); res = [c, l]; } } return JSON.stringify(res); })()`,
+ });
+ const {params: {callFrames: [{callFrameId}]}} = await paused;
+ await evalOnTopFrame(callFrameId, 'function c(){}');
+ await evalOnTopFrame(callFrameId, 'function l(){}');
+ await evalOnTopFrame(callFrameId, 'var missing = 1;');
+ await Protocol.Debugger.resume();
+ const {result: {result: {value}}} = await run;
+ InspectorTest.log('staticBlock: ' + value);
+ }
+ },
+]);
diff --git a/deps/v8/test/inspector/isolate-data.cc b/deps/v8/test/inspector/isolate-data.cc
index e2603df09d5..26060fb8de8 100644
--- a/deps/v8/test/inspector/isolate-data.cc
+++ b/deps/v8/test/inspector/isolate-data.cc
@@ -164,17 +164,18 @@ void InspectorIsolateData::RegisterModule(v8::Local<v8::Context> context,
if (!v8::ScriptCompiler::CompileModule(isolate(), source).ToLocal(&module)) {
return;
}
+ modules_[name] = v8::Global<v8::Module>(isolate_.get(), module);
if (!module
->InstantiateModule(context,
&InspectorIsolateData::ModuleResolveCallback)
.FromMaybe(false)) {
+ modules_.erase(name);
return;
}
if (evaluate) {
v8::Local<v8::Value> result;
if (!module->Evaluate(context).ToLocal(&result)) return;
}
- modules_[name] = v8::Global<v8::Module>(isolate_.get(), module);
}
// static
diff --git a/deps/v8/test/mjsunit/compiler/regress-585614985-1.js b/deps/v8/test/mjsunit/compiler/regress-585614985-1.js
new file mode 100644
index 00000000000..5915311a5fb
--- /dev/null
+++ b/deps/v8/test/mjsunit/compiler/regress-585614985-1.js
@@ -0,0 +1,90 @@
+// Copyright 2026 the V8 project authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// Flags: --allow-natives-syntax
+
+function noop() {}
+%NeverOptimizeFunction(noop);
+
+const nullProtoObj = Object.setPrototypeOf({z: 1}, null);
+function Ctor() {}
+Object.setPrototypeOf(Ctor, null);
+new Ctor();
+
+function add4(x) { return x + 4; }
+function add7(x) { return x + 7; }
+
+function pickCallee(cond, val, fn1, fn2) {
+ if (cond) {
+ val + 2; val + 2; val + 2; val + 2; val + 2; val + 2;
+ return fn1;
+ }
+ val + 3; val + 3; val + 3;
+ return fn2;
+}
+
+function toRestArray(...args) { return args; }
+
+function getNullProtoObj(val) {
+ val + 1; val + 1; val + 1; val + 1; val + 1; val + 1;
+ return nullProtoObj;
+}
+
+function test(cond, x, param) {
+ let caught;
+ let l0 = 0, l1 = 1, l2 = 2, l3 = 3, l4 = 4, l5 = 5,
+ l6 = 6, l7 = 7, l8 = 8, l9 = 9, l10 = 10, l11 = 11;
+ let acc = 0;
+ let floor = Math.floor, now = Date.now, sink = noop;
+ let obj = nullProtoObj, ctor = Ctor;
+ let args = toRestArray(x);
+ let savedCaught = 0, callee, fn1 = add4, fn2 = add7;
+ let guard = 7, fetched = 7;
+
+ try {
+ let r = floor(...args);
+ return cond ? args.length + r + acc : 3;
+ } catch {
+ savedCaught = caught = now(...args);
+ }
+
+ acc = caught === null;
+
+ let i = 5;
+ do {
+ sink(l0, l1, l2, l3, l4, l5, l6, l7, l8, l9, l10, l11);
+ fetched = getNullProtoObj(acc);
+ if (fetched instanceof ctor) throw args;
+ callee = pickCallee(cond, acc, fn1, fn2);
+ guard = cond ? fetched : obj;
+ param = caught;
+ while ((param = 0, obj instanceof ctor)) {
+ callee = fn2;
+ noop();
+ }
+ acc = callee(4);
+ if (guard === null) return 0;
+ } while (--i > 0);
+ if (savedCaught === null) return 3;
+ return acc;
+}
+
+%PrepareFunctionForOptimization(toRestArray);
+%PrepareFunctionForOptimization(getNullProtoObj);
+%PrepareFunctionForOptimization(add4);
+%PrepareFunctionForOptimization(add7);
+%PrepareFunctionForOptimization(pickCallee);
+%PrepareFunctionForOptimization(test);
+
+const sym = Symbol('x');
+assertEquals(3, test(false, 1, 99));
+assertEquals(2, test(true, 1, 99));
+assertEquals(11, test(false, sym, 99));
+assertEquals(8, test(true, sym, 99));
+
+%OptimizeFunctionOnNextCall(test);
+assertEquals(3, test(false, 1, 99));
+assertEquals(2, test(true, 1, 99));
+assertEquals(11, test(false, sym, 99));
+assertEquals(8, test(true, sym, 99));
diff --git a/deps/v8/test/mjsunit/compiler/regress-585614985-2.js b/deps/v8/test/mjsunit/compiler/regress-585614985-2.js
new file mode 100644
index 00000000000..f45fa7921b6
--- /dev/null
+++ b/deps/v8/test/mjsunit/compiler/regress-585614985-2.js
@@ -0,0 +1,91 @@
+// Copyright 2026 the V8 project authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// Flags: --allow-natives-syntax
+
+function noop() {}
+%NeverOptimizeFunction(noop);
+
+const nullProtoObj = Object.setPrototypeOf({z: 1}, null);
+const setterObj = Object.defineProperty({}, 'p', {set: Boolean});
+function Ctor() {}
+Object.setPrototypeOf(Ctor, null);
+new Ctor();
+
+function add4(x) { return x + 4; }
+function add7(x) { return x + 7; }
+
+function pickCallee(cond, val, fn1, fn2) {
+ if (cond) {
+ val + 2; val + 2; val + 2; val + 2; val + 2; val + 2;
+ return fn1;
+ }
+ val + 3; val + 3; val + 3;
+ return fn2;
+}
+
+function toRestArray(...args) { return args; }
+
+function getNullProtoObj(val) {
+ val + 1; val + 1; val + 1; val + 1; val + 1; val + 1;
+ return nullProtoObj;
+}
+
+function test(cond, x, param) {
+ let caught;
+ let l0 = 0, l1 = 1, l2 = 2, l3 = 3, l4 = 4, l5 = 5,
+ l6 = 6, l7 = 7, l8 = 8, l9 = 9, l10 = 10, l11 = 11;
+ let acc = 0;
+ let floor = Math.floor, now = Date.now, sink = noop;
+ let obj = nullProtoObj, ctor = Ctor, s = setterObj;
+ let args = toRestArray(x);
+ let callee, fn1 = add4, fn2 = add7;
+ let guard = 7, fetched = 7;
+
+ try {
+ let r = floor(...args);
+ return cond ? args.length + r + acc : 3;
+ } catch {
+ caught = now(...args);
+ }
+
+ acc = caught === null;
+
+ let i = 5;
+ do {
+ sink(l0, l1, l2, l3, l4, l5, l6, l7, l8, l9, l10, l11);
+ fetched = getNullProtoObj(acc);
+ if (fetched instanceof ctor) throw args;
+ callee = pickCallee(cond, acc, fn1, fn2);
+ guard = cond ? fetched : obj;
+ param = caught;
+ s.p = acc;
+ while ((param = 0, obj instanceof ctor)) {
+ callee = fn2;
+ noop();
+ }
+ acc = callee(4);
+ if (guard === null) return 0;
+ } while (--i > 0);
+ return caught === null ? 3 : acc;
+}
+
+%PrepareFunctionForOptimization(toRestArray);
+%PrepareFunctionForOptimization(getNullProtoObj);
+%PrepareFunctionForOptimization(add4);
+%PrepareFunctionForOptimization(add7);
+%PrepareFunctionForOptimization(pickCallee);
+%PrepareFunctionForOptimization(test);
+
+const sym = Symbol('x');
+assertEquals(3, test(false, 1, 99));
+assertEquals(2, test(true, 1, 99));
+assertEquals(11, test(false, sym, 99));
+assertEquals(8, test(true, sym, 99));
+
+%OptimizeFunctionOnNextCall(test);
+assertEquals(3, test(false, 1, 99));
+assertEquals(2, test(true, 1, 99));
+assertEquals(11, test(false, sym, 99));
+assertEquals(8, test(true, sym, 99));
diff --git a/deps/v8/test/mjsunit/compiler/regress-585624821-fast-api.js b/deps/v8/test/mjsunit/compiler/regress-585624821-fast-api.js
new file mode 100644
index 00000000000..7e89c77b204
--- /dev/null
+++ b/deps/v8/test/mjsunit/compiler/regress-585624821-fast-api.js
@@ -0,0 +1,21 @@
+// Copyright 2026 the V8 project authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// Flags: --allow-natives-syntax --expose-fast-api --turbo-fast-api-calls
+
+const fast_c_api = new d8.test.FastCAPI();
+fast_c_api[Symbol.hasInstance] = fast_c_api.is_fast_c_api_object;
+
+function check_instanceof(x) {
+ return x instanceof fast_c_api;
+}
+
+%PrepareFunctionForOptimization(check_instanceof);
+assertTrue(check_instanceof(fast_c_api));
+assertFalse(check_instanceof({}));
+
+fast_c_api.reset_counts();
+%OptimizeFunctionOnNextCall(check_instanceof);
+assertTrue(check_instanceof(fast_c_api));
+assertEquals(1, fast_c_api.fast_call_count() + fast_c_api.slow_call_count());
diff --git a/deps/v8/test/mjsunit/compiler/regress-585624821.js b/deps/v8/test/mjsunit/compiler/regress-585624821.js
new file mode 100644
index 00000000000..07a45ef3b65
--- /dev/null
+++ b/deps/v8/test/mjsunit/compiler/regress-585624821.js
@@ -0,0 +1,68 @@
+// Copyright 2026 the V8 project authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// Flags: --allow-natives-syntax
+
+const matcher = {
+ [Symbol.hasInstance]: Reflect.construct.bind(null, Uint8Array),
+};
+
+function matches(input) {
+ return arguments instanceof matcher;
+}
+
+(function TestInstanceOfBoundReflectConstructTypedArray() {
+ let calls = 0;
+ function test() {
+ const input = {
+ get length() {
+ calls++;
+ return 1;
+ },
+ };
+ return matches(input);
+ }
+
+ %PrepareFunctionForOptimization(matches);
+ %PrepareFunctionForOptimization(test);
+ assertTrue(test());
+ assertEquals(1, calls);
+
+ %OptimizeFunctionOnNextCall(test);
+ calls = 0;
+ assertTrue(test());
+ assertEquals(1, calls);
+})();
+
+(function TestInstanceOfBoundReflectConstructTypedArrayThrows() {
+ let calls = 0;
+ function test(should_throw) {
+ const input = {
+ get length() {
+ calls++;
+ if (should_throw) throw new Error('boom');
+ return 1;
+ },
+ };
+ try {
+ return matches(input);
+ } catch (e) {
+ return false;
+ }
+ }
+
+ %PrepareFunctionForOptimization(matches);
+ %PrepareFunctionForOptimization(test);
+ assertTrue(test(false));
+ assertEquals(1, calls);
+ assertFalse(test(true));
+ assertEquals(2, calls);
+
+ %OptimizeFunctionOnNextCall(test);
+ calls = 0;
+ assertTrue(test(false));
+ assertEquals(1, calls);
+ assertFalse(test(true));
+ assertEquals(2, calls);
+})();
diff --git a/deps/v8/test/mjsunit/compiler/regress-585624828.js b/deps/v8/test/mjsunit/compiler/regress-585624828.js
new file mode 100644
index 00000000000..a4769275c52
--- /dev/null
+++ b/deps/v8/test/mjsunit/compiler/regress-585624828.js
@@ -0,0 +1,89 @@
+// Copyright 2026 the V8 project authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// Flags: --allow-natives-syntax --verify-simplified-lowering
+
+const indexed = 'a'.repeat(16381);
+const minusZeroHolder = [-0];
+
+function checkArrayLengthWithMinusZero(takeWidePath, useWideNumber) {
+ const index = takeWidePath ? (useWideNumber ? 2 ** 40 : -0) : 3;
+ const ch = indexed[index];
+ const arr = new Array(index);
+ const len = arr.length;
+ return [ch, len, 1 / len, Object.is(len, minusZeroHolder[0])];
+}
+
+%PrepareFunctionForOptimization(checkArrayLengthWithMinusZero);
+for (let i = 0; i < 5; i++) {
+ assertEquals(
+ ['a', 3, 1 / 3, false], checkArrayLengthWithMinusZero(false, false));
+ assertEquals(
+ ['a', 0, Infinity, false], checkArrayLengthWithMinusZero(true, false));
+}
+%OptimizeFunctionOnNextCall(checkArrayLengthWithMinusZero);
+assertEquals(
+ ['a', 3, 1 / 3, false], checkArrayLengthWithMinusZero(false, false));
+assertEquals(
+ ['a', 0, Infinity, false], checkArrayLengthWithMinusZero(true, false));
+
+Object.defineProperty(Number.prototype, 'ident', {
+ configurable: true,
+ get() {
+ 'use strict';
+ return this;
+ },
+});
+
+const typedArray = new Uint8Array(16);
+typedArray[0] = 7;
+typedArray[3] = 9;
+
+function checkTaggedTypedArrayWithMinusZero(
+ ta, asString, useWideNumber, useMinusZero) {
+ const raw =
+ asString ? 'text' : (useWideNumber ? 2 ** 40 : (useMinusZero ? -0 : 3));
+ const index = raw.ident;
+ return ta[index];
+}
+
+%PrepareFunctionForOptimization(checkTaggedTypedArrayWithMinusZero);
+for (let i = 0; i < 5; i++) {
+ assertEquals(
+ 9, checkTaggedTypedArrayWithMinusZero(typedArray, false, false, false));
+ assertEquals(
+ 7, checkTaggedTypedArrayWithMinusZero(typedArray, false, false, true));
+}
+%OptimizeFunctionOnNextCall(checkTaggedTypedArrayWithMinusZero);
+assertEquals(
+ 9, checkTaggedTypedArrayWithMinusZero(typedArray, false, false, false));
+assertEquals(
+ 7, checkTaggedTypedArrayWithMinusZero(typedArray, false, false, true));
+
+function checkBigIntWithMinusZero(useMinusZero) {
+ const value = useMinusZero ? -0 : 3;
+ return BigInt(value);
+}
+
+%PrepareFunctionForOptimization(checkBigIntWithMinusZero);
+assertEquals(3n, checkBigIntWithMinusZero(false));
+assertEquals(0n, checkBigIntWithMinusZero(true));
+%OptimizeFunctionOnNextCall(checkBigIntWithMinusZero);
+assertEquals(3n, checkBigIntWithMinusZero(false));
+assertEquals(0n, checkBigIntWithMinusZero(true));
+
+function checkTaggedBigIntWithMinusZero(asString, useMinusZero) {
+ const raw = asString ? 'text' : (useMinusZero ? -0 : 3);
+ const value = raw.ident;
+ return BigInt(value);
+}
+
+%PrepareFunctionForOptimization(checkTaggedBigIntWithMinusZero);
+for (let i = 0; i < 5; i++) {
+ assertEquals(3n, checkTaggedBigIntWithMinusZero(false, false));
+ assertEquals(0n, checkTaggedBigIntWithMinusZero(false, true));
+}
+%OptimizeFunctionOnNextCall(checkTaggedBigIntWithMinusZero);
+assertEquals(3n, checkTaggedBigIntWithMinusZero(false, false));
+assertEquals(0n, checkTaggedBigIntWithMinusZero(false, true));
diff --git a/deps/v8/test/mjsunit/maglev/regress-590253989.js b/deps/v8/test/mjsunit/maglev/regress-590253989.js
new file mode 100644
index 00000000000..57879da8e9f
--- /dev/null
+++ b/deps/v8/test/mjsunit/maglev/regress-590253989.js
@@ -0,0 +1,44 @@
+// Copyright 2026 the V8 project authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// Flags: --allow-natives-syntax --maglev
+
+const keepParentMap = {};
+keepParentMap.a = 1;
+
+function makeHolder() {
+ const o = {};
+ o.a = 1;
+ o.b = 2;
+ const h = {};
+ h.x = o;
+ return h;
+}
+%NeverOptimizeFunction(makeHolder);
+
+const other = {y: 0, x: 0};
+
+function getSecondKey() {
+ const h = makeHolder();
+ const o = h.x;
+ let first = true;
+ for (const key in o) {
+ if (first) {
+ first = false;
+ h.x = o;
+ other.x = 1;
+ other.y = h.x.a;
+ %MajorGCForCompilerTesting();
+ continue;
+ }
+ return key;
+ }
+}
+
+%PrepareFunctionForOptimization(getSecondKey);
+assertEquals('b', getSecondKey());
+assertEquals('b', getSecondKey());
+%OptimizeMaglevOnNextCall(getSecondKey);
+assertEquals('b', getSecondKey());
+if (!isTurboFanned(getSecondKey)) assertMaglevved(getSecondKey);
diff --git a/deps/v8/test/mjsunit/mjsunit.status b/deps/v8/test/mjsunit/mjsunit.status
index fe6529fcf5e..23d149f04be 100644
--- a/deps/v8/test/mjsunit/mjsunit.status
+++ b/deps/v8/test/mjsunit/mjsunit.status
@@ -266,6 +266,7 @@
'regress/regress-crbug-503557995-b': [PASS, ['mode != release or simulator_run', SKIP]],
'regress/regress-crbug-540324230': [PASS, SLOW],
'regress/wasm/regress-810973': [PASS, SLOW],
+ 'sandbox/regress/regress-585869521': [PASS, SLOW],
'sealed-array-reduce': [PASS, SLOW],
'string-replace-gc': [PASS, SLOW],
'tools/processor': [PASS, SLOW],
@@ -879,6 +880,7 @@
'sandbox/regress/regress-349502157': [SKIP],
'sandbox/regress/regress-572826713': [SKIP],
'sandbox/regress/regress-574792351': [SKIP],
+ 'sandbox/regress/regress-581560002': [SKIP],
'sandbox/regress-537948358': [SKIP],
'sandbox/regress-558640961': [SKIP],
'sandbox/wasm-inlining-sigcheck': [SKIP],
diff --git a/deps/v8/test/mjsunit/regress/regress-586878505.js b/deps/v8/test/mjsunit/regress/regress-586878505.js
new file mode 100644
index 00000000000..28556c8a336
--- /dev/null
+++ b/deps/v8/test/mjsunit/regress/regress-586878505.js
@@ -0,0 +1,42 @@
+// Copyright 2026 the V8 project authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+const realm = Realm.create();
+const other = Realm.global(realm);
+Realm.eval(realm, `
+ for (const key of ['name', 'length']) {
+ Object.defineProperty(this, key, {
+ get() { return 'secret'; },
+ set() {},
+ configurable: true,
+ });
+ }
+`);
+
+assertThrows(
+ () => Object.prototype.__lookupGetter__.call(other, 'name'), TypeError);
+assertThrows(
+ () => Object.prototype.__lookupSetter__.call(other, 'name'), TypeError);
+
+const plain = Object.setPrototypeOf({}, other);
+assertThrows(
+ () => Object.prototype.__lookupGetter__.call(plain, 'name'), TypeError);
+assertThrows(
+ () => Object.prototype.__lookupSetter__.call(plain, 'name'), TypeError);
+
+for (const [carrier, key] of [
+ [function() {}, 'name'],
+ [function() {}, 'length'],
+ [[], 'length'],
+ [new String('a'), 'length'],
+]) {
+ Object.setPrototypeOf(carrier, other);
+ assertEquals(undefined, Object.prototype.__lookupGetter__.call(carrier, key));
+ assertEquals(undefined, Object.prototype.__lookupSetter__.call(carrier, key));
+}
+
+const proto = {get name() { return 1; }, set name(v) {}};
+const fn = Object.setPrototypeOf(function() {}, proto);
+assertEquals(undefined, fn.__lookupGetter__('name'));
+assertEquals(undefined, fn.__lookupSetter__('name'));
diff --git a/deps/v8/test/mjsunit/regress/wasm/regress-585624824.js b/deps/v8/test/mjsunit/regress/wasm/regress-585624824.js
new file mode 100644
index 00000000000..88a4e84a24d
--- /dev/null
+++ b/deps/v8/test/mjsunit/regress/wasm/regress-585624824.js
@@ -0,0 +1,49 @@
+// Copyright 2026 the V8 project authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// Flags: --allow-natives-syntax --turbofan
+
+d8.file.execute('test/mjsunit/wasm/wasm-module-builder.js');
+
+let array;
+let truncate = false;
+function sideEffect() {
+ if (truncate) array.length = 0;
+}
+
+const builder = new WasmModuleBuilder();
+const side_effect = builder.addImport('m', 'sideEffect', kSig_v_v);
+builder.addFunction('compare', kSig_i_ii)
+ .addBody([
+ kExprCallFunction, side_effect,
+ kExprLocalGet, 0,
+ kExprLocalGet, 1,
+ kExprI32Sub,
+ ])
+ .exportFunc();
+const compare = builder.instantiate({m: {sideEffect}}).exports.compare;
+
+// Returns a PACKED_ELEMENTS array.
+function makeArray(last) {
+ const a = [3, 2, {}];
+ a[2] = last;
+ return a;
+}
+
+function sort(a) {
+ return a.sort(compare);
+}
+
+%PrepareFunctionForOptimization(sort);
+sort(makeArray(1));
+sort(makeArray(1));
+%OptimizeFunctionOnNextCall(sort);
+sort(makeArray(1));
+
+// The first comparison truncates the receiver. The second one deopts while
+// converting "1" to i32, before compare is entered. The sort must continue
+// from its snapshot of the elements.
+truncate = true;
+array = makeArray('1');
+assertEquals(['1', 2, 3], sort(array));
diff --git a/deps/v8/test/mjsunit/regress/wasm/regress-585625640.js b/deps/v8/test/mjsunit/regress/wasm/regress-585625640.js
new file mode 100644
index 00000000000..edb8bd70fdd
--- /dev/null
+++ b/deps/v8/test/mjsunit/regress/wasm/regress-585625640.js
@@ -0,0 +1,96 @@
+// Copyright 2026 the V8 project authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// Flags: --allow-natives-syntax
+
+d8.file.execute('test/mjsunit/wasm/wasm-module-builder.js');
+
+const builder = new WasmModuleBuilder();
+builder.addFunction('id', kSig_i_i).addBody([kExprLocalGet, 0]).exportFunc();
+const id = builder.instantiate().exports.id;
+
+(function TestDeoptAndVerifier() {
+ function f(x, a, obj, d) {
+ x = x | 0;
+ let y;
+ if (0 < x) {
+ a[0] = d;
+ y = x;
+ } else {
+ a[1] = obj;
+ y = (id(0) - x) | 0;
+ }
+ return y | 0;
+ }
+
+ const obj = {};
+ %PrepareFunctionForOptimization(f);
+ for (let i = 0; i < 5; i++) {
+ f(1, [1.1, 2.2, 3.3, 4.4], obj, 0.5);
+ f(0, [1.1, 2.2, 3.3, 4.4], obj, 0.5);
+ }
+ %OptimizeFunctionOnNextCall(f);
+
+ const a = [1.1, 2.2, 3.3, 4.4];
+ assertEquals(1, f(1, a, obj, 0.5));
+ assertTrue(%HasDoubleElements(a));
+ assertEquals(0.5, a[0]);
+ assertEquals(2.2, a[1]);
+})();
+
+(function TestHoistedElementsTransition() {
+ let leak0 = 0;
+ let leak1 = 0;
+ function f(x, a, b, o1, o2, d) {
+ if (a.length < 4 || b.length < 4) return -1;
+ let y, z0, z1;
+ x = x | 0;
+ if (0 < x) {
+ z0 = a[0];
+ z1 = a[1];
+ b[0] = d;
+ y = x;
+ } else {
+ a[0] = o1;
+ a[1] = o2;
+ b[2] = o1;
+ y = (id(0) - x) | 0;
+ z0 = 1337.7;
+ z1 = 1338.8;
+ }
+ leak0 = z0;
+ leak1 = z1;
+ return y | 0;
+ }
+
+ const source = [1.2, 2.3, 3.4, 4.5];
+ const makeArr = () => source.slice();
+ const o1 = {};
+ const o2 = {};
+
+ const floats = new Float64Array(1);
+ const ints = new Uint32Array(floats.buffer);
+ ints[0] = 0x12345678;
+ ints[1] = 0x42;
+ const d = floats[0];
+
+ %PrepareFunctionForOptimization(f);
+ for (let i = 0; i < 10; i++) {
+ f(i & 1 ? i : -i, makeArr(), makeArr(), o1, o2, d);
+ }
+ %OptimizeFunctionOnNextCall(f);
+
+ const a = makeArr();
+ const b = makeArr();
+ assertEquals(1, f(1, a, b, o1, o2, d));
+ assertTrue(%HasDoubleElements(a));
+ assertTrue(%HasDoubleElements(b));
+ assertEquals(1.2, a[0]);
+ assertEquals(2.3, a[1]);
+ assertEquals(d, b[0]);
+ assertEquals(2.3, b[1]);
+ assertEquals(3.4, b[2]);
+ assertEquals(1.2, leak0);
+ assertEquals(2.3, leak1);
+})();
diff --git a/deps/v8/test/mjsunit/regress/wasm/regress-simd-581962456.js b/deps/v8/test/mjsunit/regress/wasm/regress-simd-581962456.js
new file mode 100644
index 00000000000..fd912919ebb
--- /dev/null
+++ b/deps/v8/test/mjsunit/regress/wasm/regress-simd-581962456.js
@@ -0,0 +1,261 @@
+// Copyright 2026 the V8 project authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// Flags: --allow-natives-syntax
+
+d8.file.execute('test/mjsunit/wasm/wasm-module-builder.js');
+
+// Exercise WebAssembly return_call with positive stack_param_delta where
+// unaligned 16-byte s128 outgoing stack arguments overlap adjacent 8-byte i64
+// caller spill slots across diamond and loop merges.
+(function TestTailCallMultiSlotStackOverlap() {
+ const kNumDomI64 = 12;
+ const kNumDomS128 = 16;
+ const kNumTailS128 = 16;
+ // Use an odd count of i64 stack arguments so s128 stack arguments land at odd
+ // 8-byte frame slot indices (spanning pairs [2k, 2k+1]) after
+ // ConvertToTailCallerLocation.
+ const kNumI64Params = kNumDomI64 + 3;
+ const kTotalS128Params = kNumDomS128 + kNumTailS128;
+
+ const calleeParams = [
+ ...new Array(kNumI64Params).fill(kWasmI64),
+ ...new Array(kTotalS128Params).fill(kWasmS128),
+ ];
+
+ const builder = new WasmModuleBuilder();
+ builder.addMemory(1, 1);
+ builder.exportMemoryAs('memory');
+
+ const noop = builder.addFunction('noop', kSig_v_v).addBody([
+ ...new Array(2000).fill(kExprNop),
+ ]);
+
+ const calleeBody = [
+ // Keep callee above the inlining budget so return_call emits a real tail
+ // call instruction.
+ ...new Array(2000).fill(kExprNop),
+ ];
+ for (let i = 0; i < kTotalS128Params; ++i) {
+ calleeBody.push(
+ ...wasmI32Const(1024 + i * 16),
+ kExprLocalGet, ...wasmUnsignedLeb(kNumI64Params + i),
+ kSimdPrefix, kExprS128StoreMem, 0, ...wasmUnsignedLeb(0));
+ }
+ calleeBody.push(kExprLocalGet, 0);
+ for (let i = 1; i < kNumI64Params; ++i) {
+ calleeBody.push(
+ kExprLocalGet, ...wasmUnsignedLeb(i),
+ ...wasmI64Const(i + 1), kExprI64Mul, kExprI64Add);
+ }
+ const callee =
+ builder.addFunction('callee', makeSig(calleeParams, [kWasmI64]))
+ .addBody(calleeBody);
+
+ // Locals in caller(mode: i32, iters: i32):
+ // 2 .. 2 + kNumDomI64 - 1: dominating i64 locals
+ // 2 + kNumDomI64 .. + kNumDomS128 - 1: dominating s128 locals
+ // phiI64A, phiS128, phiI64B: mixed-width Phis whose spill slots pack an
+ // aligned s128 slot alongside adjacent 8-byte i64 slots.
+ const firstDomI64 = 2;
+ const firstDomS128 = firstDomI64 + kNumDomI64;
+ const phiI64A = firstDomS128 + kNumDomS128;
+ const phiS128 = phiI64A + 1;
+ const phiI64B = phiS128 + 1;
+
+ const v1 = [
+ 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88,
+ 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x01,
+ ];
+ const v2 = [
+ 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10,
+ 0x0f, 0x1e, 0x2d, 0x3c, 0x4b, 0x5a, 0x69, 0x78,
+ ];
+
+ const body = [];
+ for (let i = 0; i < kNumDomS128; ++i) {
+ body.push(
+ ...wasmI32Const(i * 16),
+ kSimdPrefix, kExprS128LoadMem, 0, ...wasmUnsignedLeb(0),
+ kExprLocalSet, ...wasmUnsignedLeb(firstDomS128 + i));
+ }
+ for (let i = 0; i < kNumDomI64; ++i) {
+ body.push(
+ ...wasmI32Const(i * 8),
+ kExprI64LoadMem, 0, ...wasmUnsignedLeb(0),
+ kExprLocalSet, ...wasmUnsignedLeb(firstDomI64 + i));
+ }
+
+ body.push(
+ ...wasmI64Const(0x0102030405060708n),
+ kExprLocalSet, ...wasmUnsignedLeb(phiI64A),
+ ...wasmS128Const(v1),
+ kExprLocalSet, ...wasmUnsignedLeb(phiS128),
+ ...wasmI64Const(0x1112131415161718n),
+ kExprLocalSet, ...wasmUnsignedLeb(phiI64B),
+ kExprLoop, kWasmVoid,
+ kExprLocalGet, 1,
+ kExprIf, kWasmVoid,
+ kExprCallFunction, noop.index,
+ kExprLocalGet, ...wasmUnsignedLeb(phiI64A),
+ ...wasmI64Const(3), kExprI64Add,
+ kExprLocalSet, ...wasmUnsignedLeb(phiI64A),
+ kExprLocalGet, ...wasmUnsignedLeb(phiI64B),
+ ...wasmI64Const(5), kExprI64Add,
+ kExprLocalSet, ...wasmUnsignedLeb(phiI64B),
+ kExprLocalGet, 1,
+ kExprI32Const, 1,
+ kExprI32Sub,
+ kExprLocalTee, 1,
+ kExprBrIf, 1,
+ kExprEnd,
+ kExprEnd,
+ kExprLocalGet, 0,
+ kExprIf, kWasmVoid,
+ ...wasmS128Const(v1),
+ kExprLocalSet, ...wasmUnsignedLeb(phiS128),
+ ...wasmI64Const(0x1111222233334444n),
+ kExprLocalGet, ...wasmUnsignedLeb(phiI64A),
+ kExprI64Add,
+ kExprLocalSet, ...wasmUnsignedLeb(phiI64A),
+ ...wasmI64Const(0x5555666677778888n),
+ kExprLocalGet, ...wasmUnsignedLeb(phiI64B),
+ kExprI64Add,
+ kExprLocalSet, ...wasmUnsignedLeb(phiI64B),
+ kExprElse,
+ ...wasmS128Const(v2),
+ kExprLocalSet, ...wasmUnsignedLeb(phiS128),
+ ...wasmI64Const(0x2222333344445555n),
+ kExprLocalGet, ...wasmUnsignedLeb(phiI64A),
+ kExprI64Add,
+ kExprLocalSet, ...wasmUnsignedLeb(phiI64A),
+ ...wasmI64Const(0x6666777788889999n),
+ kExprLocalGet, ...wasmUnsignedLeb(phiI64B),
+ kExprI64Add,
+ kExprLocalSet, ...wasmUnsignedLeb(phiI64B),
+ kExprEnd);
+
+ for (let i = 0; i < kNumDomI64; ++i) {
+ body.push(kExprLocalGet, ...wasmUnsignedLeb(firstDomI64 + i));
+ }
+ body.push(
+ ...wasmI64Const(0x777788889999aaaan),
+ kExprLocalGet, ...wasmUnsignedLeb(phiI64A),
+ kExprLocalGet, ...wasmUnsignedLeb(phiI64B));
+ for (let i = 0; i < kNumDomS128; ++i) {
+ body.push(kExprLocalGet, ...wasmUnsignedLeb(firstDomS128 + i));
+ }
+ for (let i = 0; i < kNumTailS128; ++i) {
+ body.push(kExprLocalGet, ...wasmUnsignedLeb(phiS128));
+ }
+ body.push(kExprReturnCall, callee.index);
+
+ builder.addFunction('caller', makeSig([kWasmI32, kWasmI32], [kWasmI64]))
+ .addLocals(kWasmI64, kNumDomI64)
+ .addLocals(kWasmS128, kNumDomS128)
+ .addLocals(kWasmI64, 1)
+ .addLocals(kWasmS128, 1)
+ .addLocals(kWasmI64, 1)
+ .addBody(body)
+ .exportFunc();
+
+ const instance = builder.instantiate();
+ const u8 = new Uint8Array(instance.exports.memory.buffer);
+ for (let i = 0; i < 512; ++i) {
+ u8[i] = (i * 37 + 13) & 0xff;
+ }
+
+ const outLen = kTotalS128Params * 16;
+ const ref0 = instance.exports.caller(0, 2);
+ const mem0 = u8.slice(1024, 1024 + outLen);
+ const ref1 = instance.exports.caller(1, 2);
+ const mem1 = u8.slice(1024, 1024 + outLen);
+
+ %WasmTierUpFunction(instance.exports.caller);
+
+ assertEquals(ref0, instance.exports.caller(0, 2));
+ assertEquals(mem0, u8.slice(1024, 1024 + outLen));
+ assertEquals(ref1, instance.exports.caller(1, 2));
+ assertEquals(mem1, u8.slice(1024, 1024 + outLen));
+})();
+
+(function TestReturnCallMixedSimd128AndI64StackParams() {
+ // Tail-call from a function with spilled i64/s128 values to a callee with an
+ // odd number of i64 stack parameters followed by many s128 stack parameters,
+ // so 16-byte outgoing stack parameters span odd/even pairs of 8-byte slots.
+ const kNumI64 = 11;
+ const kNumS128 = 20;
+ const calleeParams = [
+ ...new Array(kNumI64).fill(kWasmI64),
+ ...new Array(kNumS128).fill(kWasmS128),
+ ];
+
+ const builder = new WasmModuleBuilder();
+ builder.addMemory(1, 1);
+ builder.exportMemoryAs('memory');
+
+ const calleeBody = [...new Array(2000).fill(kExprNop)];
+ for (let i = 0; i < kNumS128; ++i) {
+ calleeBody.push(
+ ...wasmI32Const(512 + i * 16),
+ kExprLocalGet, ...wasmUnsignedLeb(kNumI64 + i),
+ kSimdPrefix, kExprS128StoreMem, 0, ...wasmUnsignedLeb(0));
+ }
+ calleeBody.push(kExprLocalGet, 0);
+ for (let i = 1; i < kNumI64; ++i) {
+ calleeBody.push(kExprLocalGet, ...wasmUnsignedLeb(i), kExprI64Add);
+ }
+ const callee =
+ builder.addFunction('callee', makeSig(calleeParams, [kWasmI64]))
+ .addBody(calleeBody);
+
+ const vA = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
+ const vB = [16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1];
+ const callerBody = [
+ kExprLocalGet, 0,
+ kExprIf, kWasmVoid,
+ ...wasmI64Const(0x100000001n), kExprLocalSet, 1,
+ ...wasmS128Const(vA), kExprLocalSet, 2,
+ ...wasmI64Const(0x200000002n), kExprLocalSet, 3,
+ kExprElse,
+ ...wasmI64Const(0x300000003n), kExprLocalSet, 1,
+ ...wasmS128Const(vB), kExprLocalSet, 2,
+ ...wasmI64Const(0x400000004n), kExprLocalSet, 3,
+ kExprEnd,
+ ];
+ for (let i = 0; i < kNumI64 - 2; ++i) {
+ callerBody.push(...wasmI64Const(10 + i));
+ }
+ callerBody.push(kExprLocalGet, 1, kExprLocalGet, 3);
+ for (let i = 0; i < kNumS128; ++i) {
+ callerBody.push(kExprLocalGet, 2);
+ }
+ callerBody.push(kExprReturnCall, callee.index);
+
+ builder.addFunction('main', makeSig([kWasmI32], [kWasmI64]))
+ .addLocals(kWasmI64, 1)
+ .addLocals(kWasmS128, 1)
+ .addLocals(kWasmI64, 1)
+ .addBody(callerBody)
+ .exportFunc();
+
+ const instance = builder.instantiate();
+ const u8 = new Uint8Array(instance.exports.memory.buffer);
+ let sumA = 0x100000001n + 0x200000002n;
+ let sumB = 0x300000003n + 0x400000004n;
+ for (let i = 0; i < kNumI64 - 2; ++i) {
+ sumA += BigInt(10 + i);
+ sumB += BigInt(10 + i);
+ }
+
+ assertEquals(sumA, instance.exports.main(1));
+ for (let i = 0; i < kNumS128; ++i) {
+ assertEquals(vA, Array.from(u8.slice(512 + i * 16, 512 + (i + 1) * 16)));
+ }
+ %WasmTierUpFunction(instance.exports.main);
+ assertEquals(sumB, instance.exports.main(0));
+ for (let i = 0; i < kNumS128; ++i) {
+ assertEquals(vB, Array.from(u8.slice(512 + i * 16, 512 + (i + 1) * 16)));
+ }
+})();
diff --git a/deps/v8/test/mjsunit/sandbox/regress-587212489.js b/deps/v8/test/mjsunit/sandbox/regress-587212489.js
new file mode 100644
index 00000000000..02b5442d66c
--- /dev/null
+++ b/deps/v8/test/mjsunit/sandbox/regress-587212489.js
@@ -0,0 +1,149 @@
+// Copyright 2026 the V8 project authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// Flags: --sandbox-testing --expose-gc
+
+// Regression test verifying that IrRegExpData::capture_name_map_ is
+// initialized once at RegExp creation and cannot be cleared or mutated when
+// CompileIrregexpFromSource re-parses a corrupted in-sandbox pattern string
+// for another subject encoding.
+
+const kSeqOneByteStringType =
+ Sandbox.getInstanceTypeIdFor('SEQ_ONE_BYTE_STRING_TYPE');
+const kSeqTwoByteStringType =
+ Sandbox.getInstanceTypeIdFor('SEQ_TWO_BYTE_STRING_TYPE');
+const kSeqCharsOffset =
+ Sandbox.getFieldOffset(kSeqOneByteStringType, 'chars');
+
+const memory = new DataView(new Sandbox.MemoryView(0, 0x100000000));
+
+function overwriteAsciiChars(str, replacement) {
+ assertEquals(kSeqOneByteStringType, Sandbox.getInstanceTypeIdOf(str));
+ const addr = Sandbox.getAddressOf(str);
+ for (let i = 0; i < replacement.length; i++) {
+ memory.setUint8(addr + kSeqCharsOffset + i, replacement.charCodeAt(i));
+ }
+}
+
+// 1. Deterministic check: mutating original_source from unnamed to named
+// captures (or vice versa) before compiling for UC16 must not alter
+// capture_name_map_ or break ResultsCache / CopyMatches.
+(function testResultsCacheInvariance() {
+ // Internalize via eval so ResultsCache::Lookup hits on subsequent calls.
+ const longOneByte = eval('"' + 'A'.repeat(0x1100) + '"');
+
+ const unnamedSource = ['(.)(?:a*)', '(?:cache0)?'].join('');
+ const reUnnamed = new RegExp(unnamedSource, 'g');
+ longOneByte.replace(reUnnamed, () => 'x');
+ overwriteAsciiChars(unnamedSource, '(?<foo>.)');
+ assertNotNull(reUnnamed.exec('A\u1234'));
+ let unnamedArgc = 0;
+ longOneByte.replace(reUnnamed, (...args) => {
+ unnamedArgc = args.length;
+ return 'x';
+ });
+ assertEquals(4, unnamedArgc);
+
+ const namedSource = ['(?<foo>.)', '(?:cache1)?'].join('');
+ const reNamed = new RegExp(namedSource, 'g');
+ let firstGroups;
+ longOneByte.replace(reNamed, (...args) => {
+ if (firstGroups === undefined) firstGroups = args[args.length - 1];
+ return 'x';
+ });
+ firstGroups.mutated = true;
+ overwriteAsciiChars(namedSource, '(.)(?:a*)');
+ assertNotNull(reNamed.exec('A\u1234'));
+ let secondGroups;
+ longOneByte.replace(reNamed, (...args) => {
+ if (secondGroups === undefined) secondGroups = args[args.length - 1];
+ return 'x';
+ });
+ assertEquals('A', secondGroups.foo);
+ assertEquals(undefined, secondGroups.mutated);
+})();
+
+// 2. Concurrent check: flipping subject's map between 1-byte and 2-byte
+// SeqString maps during SearchRegExpMultiple triggers UC16 compilation
+// mid-loop and must not clear capture_name_map_ to null.
+(function testConcurrentEncodingFlipInReplace() {
+ // Use 0x00414141 ('A' in every byte and '\u4141' as two-byte) followed by an
+ // adjacent tenured string so 2-byte reads stay in initialized OldSpace.
+ const oneByteString = Array(100).fill('A').join('');
+ const paddingString = Array(200).fill('A').join('');
+ const twoByteString = Array(100).fill('\u4141').join('');
+ assertEquals(
+ kSeqOneByteStringType, Sandbox.getInstanceTypeIdOf(oneByteString));
+ assertEquals(
+ kSeqTwoByteStringType, Sandbox.getInstanceTypeIdOf(twoByteString));
+
+ // Tenuring ensures Minor GC does not relocate or scan oneByteString while
+ // the worker toggles its map word.
+ gc();
+ gc();
+
+ const oneByteAddr = Sandbox.getAddressOf(oneByteString);
+ const twoByteAddr = Sandbox.getAddressOf(twoByteString);
+ const oneByteMap = memory.getUint32(oneByteAddr, true);
+ const twoByteMap = memory.getUint32(twoByteAddr, true);
+
+ // Use 25 capture groups so registers_per_match = 52 and
+ // GlobalExecRunner::max_matches() = 98 / 52 = 1, forcing FetchNext() to call
+ // IrregexpExecRaw on every match.
+ function makePreparedRegExp(id) {
+ const patternStr =
+ ['(?<foo>.)', '()'.repeat(24), '(?:' + id + ')?'].join('');
+ const re = new RegExp(patternStr, 'g');
+ re.exec('A');
+ re.lastIndex = 0;
+ overwriteAsciiChars(patternStr, '(.)(?:a*)');
+ return re;
+ }
+
+ const regexps = [];
+ for (let i = 0; i < 300; i++) {
+ regexps.push(makePreparedRegExp(i));
+ }
+
+ const shared = new SharedArrayBuffer(16);
+ const control = new Int32Array(shared);
+ Atomics.store(control, 0, 0);
+ Atomics.store(control, 1, oneByteAddr | 0);
+ Atomics.store(control, 2, oneByteMap | 0);
+ Atomics.store(control, 3, twoByteMap | 0);
+
+ const worker = new Worker(`
+ onmessage = function(e) {
+ const ctrl = new Int32Array(e.data);
+ const mem = new DataView(new Sandbox.MemoryView(0, 0x100000000));
+ const addr = Atomics.load(ctrl, 1) >>> 0;
+ const valA = Atomics.load(ctrl, 2) >>> 0;
+ const valB = Atomics.load(ctrl, 3) >>> 0;
+ postMessage('ready');
+ while (Atomics.load(ctrl, 0) === 0) {
+ for (let i = 0; i < 1000; i++) {
+ mem.setUint32(addr, valA, true);
+ mem.setUint32(addr, valB, true);
+ }
+ }
+ };
+ `, {type: 'string'});
+
+ worker.postMessage(shared);
+ assertEquals('ready', worker.getMessage());
+
+ try {
+ for (const re of regexps) {
+ oneByteString.replace(re, (...args) => {
+ assertEquals('string', typeof args[args.length - 1].foo);
+ return 'x';
+ });
+ }
+ } finally {
+ Atomics.store(control, 0, 1);
+ worker.terminate();
+ memory.setUint32(oneByteAddr, oneByteMap, true);
+ }
+ assertEquals(200, paddingString.length);
+})();
diff --git a/deps/v8/test/mjsunit/sandbox/regress/regress-581560002.js b/deps/v8/test/mjsunit/sandbox/regress/regress-581560002.js
new file mode 100644
index 00000000000..5ab4a47b252
--- /dev/null
+++ b/deps/v8/test/mjsunit/sandbox/regress/regress-581560002.js
@@ -0,0 +1,70 @@
+// Copyright 2026 the V8 project authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// Flags: --sandbox-testing --shared-strings --allow-natives-syntax
+
+d8.file.execute('test/mjsunit/wasm/wasm-module-builder.js');
+
+const kArity = 1000;
+const kIterations = 200;
+const builder = new WasmModuleBuilder();
+const sig = makeSig(new Array(kArity).fill(kWasmI32), [kWasmI32]);
+builder.addFunction('f', sig).addBody([kExprI32Const, 7]).exportFunc();
+builder.addFunction('g', sig).addBody([kExprI32Const, 7]).exportFunc();
+const wasmModule = builder.toModule();
+
+const fnB = new WebAssembly.Instance(wasmModule).exports.g;
+const exportsList = Array.from(
+ {length: kIterations}, () => new WebAssembly.Instance(wasmModule).exports.f);
+
+const mem = new Uint32Array(new Sandbox.MemoryView(0, 0x100000000));
+const kDispatchOffset = Sandbox.getFieldOffset(
+ Sandbox.getInstanceTypeIdFor('JS_FUNCTION'), 'dispatch_handle');
+const handleB = mem[(Sandbox.getAddressOf(fnB) + kDispatchOffset) >>> 2];
+
+const shared = new SharedArrayBuffer(32);
+const control = new Int32Array(shared);
+control[3] = handleB;
+control[7] = 0;
+
+const worker = new Worker(function() {
+ onmessage = function(event) {
+ const control = new Int32Array(event.data);
+ const mem = new Uint32Array(new Sandbox.MemoryView(0, 0x100000000));
+ Atomics.store(control, 5, 1);
+ Atomics.notify(control, 5);
+ while (Atomics.load(control, 0) !== 2) {
+ if (Atomics.load(control, 0) !== 1) continue;
+ const idx = Atomics.load(control, 1) >>> 0;
+ const delay = Atomics.load(control, 6);
+ for (let s = 0; s < delay; ++s) Atomics.load(control, 0);
+ if (Atomics.load(control, 0) === 1) {
+ mem[idx] = Atomics.load(control, 3);
+ %SharedGC();
+ Atomics.store(control, 0, 0);
+ }
+ }
+ };
+}, {type: 'function'});
+
+worker.postMessage(shared);
+Atomics.wait(control, 5, 0);
+
+const targets = [fnB];
+for (let i = 1; i < 32; ++i) targets.push(Function('return ' + i));
+
+for (let i = 0; i < kIterations; ++i) {
+ const fnA = exportsList[i];
+ const idx = (Sandbox.getAddressOf(fnA) + kDispatchOffset) >>> 2;
+ targets[0] = fnA;
+ Atomics.store(control, 1, idx);
+ Atomics.store(control, 6, i & 15);
+ Atomics.store(control, 0, 1);
+ const res = targets[control[7] & 31]();
+ while (Atomics.load(control, 0) === 1) {}
+ assertEquals(7, res);
+}
+
+Atomics.store(control, 0, 2);
+worker.terminate();
diff --git a/deps/v8/test/mjsunit/sandbox/regress/regress-585869521.js b/deps/v8/test/mjsunit/sandbox/regress/regress-585869521.js
new file mode 100644
index 00000000000..528c67e4e91
--- /dev/null
+++ b/deps/v8/test/mjsunit/sandbox/regress/regress-585869521.js
@@ -0,0 +1,67 @@
+// Copyright 2026 the V8 project authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// Flags: --sandbox-testing
+
+// ApplyOptionsToTag (src/objects/js-locale.cc) must not pass a UTF-8 length
+// >= 2^31 to icu::LocaleBuilder::setLanguageTag(), where it is truncated to
+// int32_t. Build a flat one-byte string whose (corrupted) length is 2^31 and
+// whose characters encode to exactly 0xFFFFFFFF UTF-8 bytes: one ASCII 'e'
+// followed by 2^31 - 1 bytes of 0xff (2 UTF-8 bytes each).
+
+if (typeof Intl !== 'undefined') {
+ const memory = new DataView(new Sandbox.MemoryView(0, 0x100000000));
+ const u8 = new Uint8Array(memory.buffer);
+
+ const kHeapObjectTag = 1;
+ const kElementsOffset = 8;
+ const kConsStringFirstOffset = 12;
+ const kStringLengthOffset = 8;
+ const kSeqOneByteCharsOffset = 12;
+ const kFixedArrayHeaderSize = 8;
+
+ const kChunkSize = 536 * 1000 * 1000;
+ const kCorruptedLength = 2 ** 31;
+
+ const keepAlive = [];
+ function allocFlatOneByteChunk(size) {
+ const s = '\xff'.repeat(size);
+ // Flatten the ConsString into a SeqOneByteString in large object space.
+ s.indexOf('a');
+ keepAlive.push(s);
+ return memory.getUint32(
+ Sandbox.getAddressOf(s) + kConsStringFirstOffset, true) -
+ kHeapObjectTag;
+ }
+
+ // Allocate > 2GB of 0xff bytes in (typically) contiguous large pages.
+ const chunks = [
+ allocFlatOneByteChunk(kChunkSize), allocFlatOneByteChunk(kChunkSize),
+ allocFlatOneByteChunk(kChunkSize), allocFlatOneByteChunk(kChunkSize),
+ allocFlatOneByteChunk(100 * 1000 * 1000)
+ ];
+ const f1 = chunks[0];
+
+ // Fill the small gaps between consecutive chunks with 0xff so that there are
+ // no NUL bytes in [f1 + kSeqOneByteCharsOffset, +2^31).
+ for (let i = 0; i < chunks.length - 1; i++) {
+ const gapStart = chunks[i] + kSeqOneByteCharsOffset + kChunkSize;
+ const gapEnd = chunks[i + 1] + kSeqOneByteCharsOffset;
+ if (gapStart <= gapEnd && gapEnd - gapStart < 0x100000) {
+ u8.fill(0xff, gapStart, gapEnd);
+ }
+ }
+ u8[f1 + kSeqOneByteCharsOffset] = 0x65; // 'e'
+
+ // Expose the flat string to JS and corrupt its length.
+ const arr = ['x'];
+ const elements =
+ memory.getUint32(Sandbox.getAddressOf(arr) + kElementsOffset, true) -
+ kHeapObjectTag;
+ memory.setUint32(elements + kFixedArrayHeaderSize, f1 + kHeapObjectTag, true);
+ memory.setUint32(f1 + kStringLengthOffset, kCorruptedLength, true);
+
+ new Intl.Locale(arr[0]);
+ assertUnreachable('Corrupted String length should be caught by SBXCHECK');
+}
diff --git a/deps/v8/test/mjsunit/turbolev/regress-587040688.js b/deps/v8/test/mjsunit/turbolev/regress-587040688.js
new file mode 100644
index 00000000000..e55f18228ed
--- /dev/null
+++ b/deps/v8/test/mjsunit/turbolev/regress-587040688.js
@@ -0,0 +1,130 @@
+// Copyright 2026 the V8 project authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// Flags: --allow-natives-syntax --turbolev
+
+function id(x) {
+ return x;
+}
+%PrepareFunctionForOptimization(id);
+%DisableEagerInlining(id);
+
+(function TestPostLoopSmiUses() {
+ const arr = [1, 2];
+ const a = {s: 0.25};
+ const b = {t: 3.5};
+
+ function inner(exit_early, cond) {
+ let flag = id(exit_early);
+ let p = cond ? 5 : a.s;
+ let z;
+ for (let i = 0;; i++) {
+ z = p | 0;
+ if (flag) {
+ +p;
+ break;
+ }
+ if (i > 1) return -1;
+ p = b.t;
+ }
+ arr[0] = p;
+ return p + z;
+ }
+ %PrepareFunctionForOptimization(inner);
+
+ function outer(cond) {
+ return inner(true, cond);
+ }
+ %PrepareFunctionForOptimization(outer);
+
+ id(true);
+ id(false);
+ inner(true, true);
+ inner(false, false);
+ assertEquals(10, outer(true));
+
+ %OptimizeFunctionOnNextCall(outer);
+ assertEquals(0.25, outer(false));
+ %HeapObjectVerify(arr);
+})();
+
+(function TestDeoptFrameUse() {
+ const b = {t: 3.5};
+
+ function inner(exit_early, cond) {
+ let flag = id(exit_early);
+ let p = cond ? 5 : undefined;
+ let z;
+ let t;
+ for (let i = 0;; i++) {
+ z = p | 0;
+ if (flag) {
+ t = typeof p;
+ break;
+ }
+ if (i > 1) return 'bail';
+ p = b.t;
+ }
+ return t + z;
+ }
+ %PrepareFunctionForOptimization(inner);
+
+ function outer(cond) {
+ return inner(true, cond);
+ }
+ %PrepareFunctionForOptimization(outer);
+
+ id(true);
+ id(false);
+ inner(true, true);
+ inner(false, false);
+ assertEquals('number5', outer(true));
+
+ %OptimizeFunctionOnNextCall(outer);
+ assertEquals('undefined0', outer(false));
+})();
+
+(function TestPostLoopHeapNumberSmiValue() {
+ const arr = [1, 2];
+ const b = {t: 3.5};
+
+ function makeHeapNumber5(x) {
+ return x + 0.5;
+ }
+ %NeverOptimizeFunction(makeHeapNumber5);
+
+ function inner(exit_early, cond, x) {
+ +x;
+ let flag = id(exit_early);
+ let p = cond ? 5 : x;
+ let z;
+ for (let i = 0;; i++) {
+ z = p + 0.5;
+ if (flag) {
+ +p;
+ break;
+ }
+ if (i > 1) return -1;
+ p = b.t;
+ }
+ arr[0] = p;
+ return (p + 1) + z;
+ }
+ %PrepareFunctionForOptimization(inner);
+
+ function outer(cond, x) {
+ return inner(true, cond, x);
+ }
+ %PrepareFunctionForOptimization(outer);
+
+ id(true);
+ id(false);
+ inner(true, true, 1);
+ inner(false, false, 1.5);
+ assertEquals(11.5, outer(true, 1));
+
+ %OptimizeFunctionOnNextCall(outer);
+ assertEquals(11.5, outer(false, makeHeapNumber5(4.5)));
+ %HeapObjectVerify(arr);
+})();
diff --git a/deps/v8/test/mjsunit/turbolev/regress-590253989.js b/deps/v8/test/mjsunit/turbolev/regress-590253989.js
new file mode 100644
index 00000000000..726681f77f7
--- /dev/null
+++ b/deps/v8/test/mjsunit/turbolev/regress-590253989.js
@@ -0,0 +1,43 @@
+// Copyright 2026 the V8 project authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// Flags: --allow-natives-syntax --turbolev
+
+const keep_parent_map = {};
+keep_parent_map.a = 1;
+
+function makeHolder() {
+ const o = {};
+ o.a = 1;
+ o.b = 2;
+ const h = {};
+ h.x = o;
+ return h;
+}
+%NeverOptimizeFunction(makeHolder);
+
+const other = {y: 0, x: 0};
+
+function getSecondKey() {
+ const h = makeHolder();
+ const o = h.x;
+ let first = true;
+ for (const key in o) {
+ if (first) {
+ first = false;
+ h.x = o;
+ other.x = 1;
+ other.y = h.x.a;
+ %MajorGCForCompilerTesting();
+ continue;
+ }
+ return key;
+ }
+}
+
+%PrepareFunctionForOptimization(getSecondKey);
+assertEquals('b', getSecondKey());
+assertEquals('b', getSecondKey());
+%OptimizeFunctionOnNextCall(getSecondKey);
+assertEquals('b', getSecondKey());
diff --git a/deps/v8/test/mjsunit/wasm/regress-585624832.js b/deps/v8/test/mjsunit/wasm/regress-585624832.js
new file mode 100644
index 00000000000..35d6c6cebb3
--- /dev/null
+++ b/deps/v8/test/mjsunit/wasm/regress-585624832.js
@@ -0,0 +1,61 @@
+// Copyright 2026 the V8 project authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// Flags: --no-liftoff
+
+d8.file.execute('test/mjsunit/wasm/wasm-module-builder.js');
+
+const builder = new WasmModuleBuilder();
+const array = builder.addArray(kWasmI64);
+const arrayRef = wasmRefNullType(array);
+builder.addMemory(1, 1, false);
+const get = i => [kExprLocalGet, i];
+const set = i => [kExprLocalSet, i];
+const numbers = [0, 1, 2, 3, 4];
+const old = 8, shifted = 9, firstNumber = 10, remainder = 16, len = 17;
+
+// The cmpxchgs and division constrain rax and rdx. The i64 source of the
+// shift must keep its upper 32 bits through the move cycle into its
+// same-as-input Word32 result.
+const make = builder.addFunction('make',
+ makeSig([kWasmI64, kWasmI64, kWasmI64, ...numbers.map(() => kWasmF64)],
+ [arrayRef])).addLocals(kWasmI64, 9).addLocals(kWasmI32, 1);
+const cmpxchg = [
+ kExprI32Const, 0, ...get(firstNumber + 2), ...get(firstNumber),
+ kAtomicPrefix, kExprI64AtomicCompareExchange, 3, 0
+];
+make.addBody([
+ ...get(2), ...get(0), kExprI64RemU, ...set(remainder),
+ ...get(remainder), kExprI64Const, 32, kExprI64ShrU, ...set(shifted),
+ ...numbers.flatMap(
+ i => [...get(3 + i), kExprI64ReinterpretF64, ...set(firstNumber + i)]),
+ ...cmpxchg, ...set(old),
+ ...get(shifted), kExprI32ConvertI64, ...set(len),
+ ...cmpxchg, kExprDrop,
+ ...get(old), ...get(firstNumber), kExprI64DivU,
+ ...numbers.slice(1).flatMap(i => [...get(firstNumber + i), kExprI64Add]),
+ ...get(remainder), kExprI64Xor, ...get(len), kGCPrefix, kExprArrayNew, array
+]).exportFunc();
+
+builder.addFunction('array_len', makeSig([arrayRef], [kWasmI32]))
+ .addBody([kExprLocalGet, 0, kGCPrefix, kExprArrayLen])
+ .exportFunc();
+
+builder.addFunction('array_get', makeSig([arrayRef, kWasmI32], [kWasmI64]))
+ .addBody([kExprLocalGet, 0, kExprLocalGet, 1, kGCPrefix, kExprArrayGet, array])
+ .exportFunc();
+
+const bits = new BigInt64Array(1);
+const number = new Float64Array(bits.buffer);
+const inputs = numbers.map(i => {
+ bits[0] = BigInt(i + 1);
+ return number[0];
+});
+const wasm = builder.instantiate().exports;
+
+const x = (128n << 32n) | 0x12345678n;
+const arr = wasm.make(-1n, 0n, x, ...inputs);
+assertEquals(128, wasm.array_len(arr));
+assertEquals(x ^ 14n, wasm.array_get(arr, 0));
+assertEquals(x ^ 14n, wasm.array_get(arr, 127));
diff --git a/deps/v8/test/mjsunit/wasm/turboshaft/regress-585625644.js b/deps/v8/test/mjsunit/wasm/turboshaft/regress-585625644.js
new file mode 100644
index 00000000000..ce7e513f77b
--- /dev/null
+++ b/deps/v8/test/mjsunit/wasm/turboshaft/regress-585625644.js
@@ -0,0 +1,186 @@
+// Copyright 2026 the V8 project authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// Flags: --allow-natives-syntax --no-debug-code
+
+d8.file.execute('test/mjsunit/wasm/wasm-module-builder.js');
+
+const builder = new WasmModuleBuilder();
+const pairType = builder.addStruct([
+ makeField(kWasmExternRef, true),
+ makeField(kWasmExternRef, true),
+]);
+const externArrType = builder.addArray(kWasmExternRef);
+const pairArrType = builder.addArray(wasmRefNullType(pairType));
+const f64ArrType = builder.addArray(kWasmF64);
+
+builder.addFunction('id', makeSig([kWasmI32], [kWasmI32]))
+ .addBody([kExprLocalGet, 0])
+ .exportFunc();
+
+builder.addFunction('arrLen', makeSig([kWasmExternRef], [kWasmI32]))
+ .addBody([
+ kExprLocalGet, 0,
+ kGCPrefix, kExprAnyConvertExtern,
+ kGCPrefix, kExprRefCast, kArrayRefCode,
+ kGCPrefix, kExprArrayLen,
+ ])
+ .exportFunc();
+
+builder.addFunction('setExternArr', makeSig(
+ [kWasmExternRef, kWasmExternRef, kWasmExternRef, kWasmI32, kWasmI32], []))
+ .addBody([
+ kExprLocalGet, 0, kGCPrefix, kExprAnyConvertExtern,
+ kGCPrefix, kExprRefCast, externArrType,
+ kExprLocalGet, 3, kExprLocalGet, 1,
+ kGCPrefix, kExprArraySet, externArrType,
+ kExprLocalGet, 0, kGCPrefix, kExprAnyConvertExtern,
+ kGCPrefix, kExprRefCast, externArrType,
+ kExprLocalGet, 4, kExprLocalGet, 2,
+ kGCPrefix, kExprArraySet, externArrType,
+ ])
+ .exportFunc();
+
+builder.addFunction('writeField0', makeSig(
+ [kWasmExternRef, kWasmExternRef, kWasmI32], []))
+ .addBody([
+ kExprLocalGet, 0, kGCPrefix, kExprAnyConvertExtern,
+ kGCPrefix, kExprRefCast, pairArrType,
+ kExprLocalGet, 2,
+ kGCPrefix, kExprArrayGet, pairArrType,
+ kExprLocalGet, 1,
+ kGCPrefix, kExprStructSet, pairType, 0,
+ ])
+ .exportFunc();
+
+builder.addFunction('writeField1', makeSig(
+ [kWasmExternRef, kWasmExternRef, kWasmI32], []))
+ .addBody([
+ kExprLocalGet, 0, kGCPrefix, kExprAnyConvertExtern,
+ kGCPrefix, kExprRefCast, pairArrType,
+ kExprLocalGet, 2,
+ kGCPrefix, kExprArrayGet, pairArrType,
+ kExprLocalGet, 1,
+ kGCPrefix, kExprStructSet, pairType, 1,
+ ])
+ .exportFunc();
+
+builder.addFunction('roundtripF64', makeSig(
+ [kWasmExternRef, kWasmI32, kWasmF64], [kWasmF64]))
+ .addBody([
+ kExprLocalGet, 0, kGCPrefix, kExprAnyConvertExtern,
+ kGCPrefix, kExprRefCast, f64ArrType,
+ kExprLocalGet, 1, kExprLocalGet, 2,
+ kGCPrefix, kExprArraySet, f64ArrType,
+ kExprLocalGet, 0, kGCPrefix, kExprAnyConvertExtern,
+ kGCPrefix, kExprRefCast, f64ArrType,
+ kExprLocalGet, 1,
+ kGCPrefix, kExprArrayGet, f64ArrType,
+ ])
+ .exportFunc();
+
+builder.addFunction('truncF64', makeSig([kWasmF64], [kWasmI32]))
+ .addBody([
+ kExprLocalGet, 0,
+ kExprI64SConvertF64,
+ kExprI32ConvertI64,
+ kExprI32Const, 0,
+ kExprI32And,
+ ])
+ .exportFunc();
+
+builder.addFunction('mkExternArr', makeSig([], [wasmRefType(externArrType)]))
+ .addBody([kExprI32Const, 2, kGCPrefix, kExprArrayNewDefault, externArrType])
+ .exportFunc();
+
+builder.addFunction('mkPairArr', makeSig([], [wasmRefType(pairArrType)]))
+ .addBody([
+ kGCPrefix, kExprStructNewDefault, pairType,
+ kGCPrefix, kExprStructNewDefault, pairType,
+ kGCPrefix, kExprArrayNewFixed, pairArrType, 2,
+ ])
+ .exportFunc();
+
+builder.addFunction('mkF64Arr', makeSig([], [wasmRefType(f64ArrType)]))
+ .addBody([kExprI32Const, 2, kGCPrefix, kExprArrayNewDefault, f64ArrType])
+ .exportFunc();
+
+const {
+ id,
+ arrLen,
+ setExternArr,
+ writeField0,
+ writeField1,
+ roundtripF64,
+ truncF64,
+ mkExternArr,
+ mkPairArr,
+ mkF64Arr,
+} = builder.instantiate().exports;
+
+const extArr = mkExternArr();
+const pairArr = mkPairArr();
+const f64Arr = mkF64Arr();
+const constObj = {x: 1};
+
+const u32View = new Uint32Array(8);
+const f64View = new Float64Array(u32View.buffer);
+
+function keepRegsLive(val) {
+ let m0 = u32View[0];
+ let m1 = u32View[1];
+ let m2 = u32View[4];
+ f64View[2] = val;
+ u32View[3] = m0 ^ m1 ^ m2;
+ return val;
+}
+
+const K = 2 ** 34;
+const step = x => x + x - K;
+const step4 = x => step(step(step(step(x))));
+const step16 = x => step4(step4(step4(step4(x))));
+
+function unreachableLoad(a, d, doubleArr, smiArr, z, off) {
+ let neg = (roundtripF64(f64Arr, 0, -2147483648) | 0) >> 1;
+ if (arrLen(a) === z) {
+ setExternArr(a, doubleArr, smiArr, 0, 1);
+ } else {
+ setExternArr(a, doubleArr, smiArr, 0, 1);
+ }
+ writeField0(d, constObj, 0);
+ writeField1(d, neg, 1);
+ let q = Math.max(-1024, (0 - smiArr.length) | 0);
+ let t = step16(step4(step4(step4(step(step(step(K + q)))))));
+ let idx = t - K - 1 + (off | 0);
+ return keepRegsLive(doubleArr[id(0) ? -0 : idx]);
+}
+
+function main(a, doubleArr, smiArr, z, takeDead) {
+ let r;
+ if (takeDead) {
+ r = unreachableLoad(a, a, doubleArr, smiArr, z, 0);
+ } else {
+ let v = doubleArr[0];
+ u32View[0] = truncF64(v + 128);
+ r = v;
+ }
+ return r + 0.2;
+}
+
+%PrepareFunctionForOptimization(step);
+%PrepareFunctionForOptimization(step4);
+%PrepareFunctionForOptimization(step16);
+%PrepareFunctionForOptimization(keepRegsLive);
+%PrepareFunctionForOptimization(unreachableLoad);
+%PrepareFunctionForOptimization(main);
+
+for (let i = 0; i < 20; i++) {
+ unreachableLoad(extArr, pairArr, [1.5], [], (i % 2) * 2, 1);
+ main(extArr, [3.4], [], i % 2, false);
+ assertThrows(
+ () => main(extArr, [3.4], [], i % 2, true), WebAssembly.RuntimeError);
+}
+
+%OptimizeFunctionOnNextCall(main);
+assertEquals(3.6, main(extArr, [3.4], [], 0, false));
diff --git a/deps/v8/test/unittests/compiler/backend/instruction-unittest.cc b/deps/v8/test/unittests/compiler/backend/instruction-unittest.cc
index 2482979ce85..748a9442c95 100644
--- a/deps/v8/test/unittests/compiler/backend/instruction-unittest.cc
+++ b/deps/v8/test/unittests/compiler/backend/instruction-unittest.cc
@@ -62,7 +62,16 @@ TEST_F(InstructionTest, OperandInterference) {
}
}
- // 128 bit slots can interfere with other slots at a different index.
+ // 128 bit slots can interfere with other slots at a different index, but
+ // never with registers or non-location operands.
+ AllocatedOperand wide_slot(LocationOperand::STACK_SLOT,
+ MachineRepresentation::kSimd128, 1);
+ EXPECT_FALSE(wide_slot.InterferesWith(ConstantOperand(0)));
+ EXPECT_FALSE(ConstantOperand(0).InterferesWith(wide_slot));
+ EXPECT_FALSE(wide_slot.InterferesWith(
+ ImmediateOperand(ImmediateOperand::INLINE_INT32, 0)));
+ EXPECT_FALSE(wide_slot.InterferesWith(
+ AllocatedOperand(LocationOperand::REGISTER, kWord, 1)));
for (int i = 0; i < 10; ++i) {
for (int j = 0; j < 128 / kBitsPerByte / kSystemPointerSize; ++j) {
EXPECT_TRUE(Interfere(LocationOperand::STACK_SLOT,
@@ -186,6 +195,66 @@ TEST_F(InstructionTest, PrepareInsertAfter) {
CHECK(Contains(&to_eliminate, s1, s2));
}
}
+
+ {
+ // Multi-slot stack destinations (such as kSimd128) must eliminate all
+ // narrower interfering stack moves, even when source replacement is also
+ // found in the same ParallelMove.
+ const int kSimd128Slots =
+ ElementSizeInPointers(MachineRepresentation::kSimd128);
+ CHECK_GE(kSimd128Slots, 1);
+
+ InstructionOperand q0 = AllocatedOperand(
+ LocationOperand::REGISTER, MachineRepresentation::kSimd128, 0);
+ InstructionOperand q1 = AllocatedOperand(
+ LocationOperand::REGISTER, MachineRepresentation::kSimd128, 1);
+ InstructionOperand s128_top =
+ AllocatedOperand(LocationOperand::STACK_SLOT,
+ MachineRepresentation::kSimd128, kSimd128Slots - 1);
+
+ ZoneVector<MoveOperands*> to_eliminate(zone());
+ std::vector<InstructionOperand> moves = {q1, q0}; // q1 <- q0
+ for (int i = 0; i < kSimd128Slots; ++i) {
+ InstructionOperand narrow_slot = AllocatedOperand(
+ LocationOperand::STACK_SLOT, MachineRepresentation::kWord32, i);
+ moves.push_back(narrow_slot);
+ moves.push_back(r0);
+ }
+
+ ParallelMove* pm = CreateParallelMove(moves);
+ MoveOperands m_wide(q1, s128_top); // [stack:top|s128] <- q1
+ pm->PrepareInsertAfter(&m_wide, &to_eliminate);
+ CHECK(m_wide.source().Equals(q0));
+ for (int i = 0; i < kSimd128Slots; ++i) {
+ InstructionOperand narrow_slot = AllocatedOperand(
+ LocationOperand::STACK_SLOT, MachineRepresentation::kWord32, i);
+ CHECK(Contains(&to_eliminate, narrow_slot, r0));
+ }
+
+ // A redundant multi-slot stack move must not eliminate earlier narrower
+ // moves.
+ ZoneVector<MoveOperands*> redundant_eliminated(zone());
+ MoveOperands m_redundant(s128_top, s128_top);
+ pm->PrepareInsertAfter(&m_redundant, &redundant_eliminated);
+ CHECK(redundant_eliminated.empty());
+
+ if (kSimd128Slots > 1) {
+ // A shifted multi-slot stack move whose source matches an earlier move's
+ // destination AND whose destination partially overlaps that same earlier
+ // move's destination must both forward the source and eliminate the
+ // overwritten move.
+ InstructionOperand s128_shifted =
+ AllocatedOperand(LocationOperand::STACK_SLOT,
+ MachineRepresentation::kSimd128, kSimd128Slots);
+ ZoneVector<MoveOperands*> shifted_eliminated(zone());
+ std::vector<InstructionOperand> prev_moves = {s128_top, q0};
+ ParallelMove* pm_shifted = CreateParallelMove(prev_moves);
+ MoveOperands m_shifted(s128_top, s128_shifted);
+ pm_shifted->PrepareInsertAfter(&m_shifted, &shifted_eliminated);
+ CHECK(m_shifted.source().Equals(q0));
+ CHECK(Contains(&shifted_eliminated, s128_top, q0));
+ }
+ }
}
} // namespace instruction_unittest
diff --git a/deps/v8/test/unittests/compiler/regalloc/move-optimizer-unittest.cc b/deps/v8/test/unittests/compiler/regalloc/move-optimizer-unittest.cc
index 17077204b0e..ea00d37f747 100644
--- a/deps/v8/test/unittests/compiler/regalloc/move-optimizer-unittest.cc
+++ b/deps/v8/test/unittests/compiler/regalloc/move-optimizer-unittest.cc
@@ -3,6 +3,8 @@
// found in the LICENSE file.
#include "src/compiler/backend/move-optimizer.h"
+
+#include "src/compiler/backend/register-allocator-verifier.h"
#include "src/utils/ostreams.h"
#include "test/unittests/compiler/backend/instruction-sequence-unittest.h"
@@ -85,9 +87,11 @@ class MoveOptimizerTest : public InstructionSequenceTest {
switch (op.type_) {
case kConstant:
return ConstantOperand(op.value_);
- case kFixedSlot:
- return AllocatedOperand(LocationOperand::STACK_SLOT,
- MachineRepresentation::kWord32, op.value_);
+ case kFixedSlot: {
+ MachineRepresentation rep =
+ op.rep_ == kNoRep ? MachineRepresentation::kWord32 : op.rep_;
+ return AllocatedOperand(LocationOperand::STACK_SLOT, rep, op.value_);
+ }
case kFixedRegister: {
MachineRepresentation rep = GetCanonicalRep(op);
CHECK(0 <= op.value_ && op.value_ < GetNumRegs(rep));
@@ -439,6 +443,159 @@ TEST_F(MoveOptimizerTest, ClobberedFPDestinationsAreEliminated) {
CHECK_EQ(0, NonRedundantSize(last_move));
}
+TEST_F(MoveOptimizerTest,
+ CompressesMultiSlotStackDestinationOverMultipleNarrowSlots) {
+ const int kSimd128Slots =
+ ElementSizeInPointers(MachineRepresentation::kSimd128);
+ if (kSimd128Slots <= 1) return;
+
+ StartBlock();
+ Instruction* first_instr = EmitNop();
+ Instruction* last_instr = EmitNop();
+
+ AddMove(first_instr, FPReg(kS128_1, kSimd128), FPReg(kS128_2, kSimd128));
+ for (int i = 0; i < kSimd128Slots; ++i) {
+ AddMove(first_instr, Reg(i % 2), Slot(i));
+ }
+ AddMove(last_instr, FPReg(kS128_2, kSimd128),
+ Slot(kSimd128Slots - 1, kSimd128));
+
+ EndBlock(Last());
+ Optimize();
+
+ ParallelMove* first_move = first_instr->parallel_moves()[0];
+ CHECK(first_move == nullptr || NonRedundantSize(first_move) == 0);
+
+ ParallelMove* last_move = last_instr->parallel_moves()[0];
+ CHECK_EQ(2, NonRedundantSize(last_move));
+ CHECK(
+ Contains(last_move, FPReg(kS128_1, kSimd128), FPReg(kS128_2, kSimd128)));
+ CHECK(Contains(last_move, FPReg(kS128_1, kSimd128),
+ Slot(kSimd128Slots - 1, kSimd128)));
+}
+
+TEST_F(MoveOptimizerTest, ClobberedMultiSlotStackDestinationsAreEliminated) {
+ const int kSimd128Slots =
+ ElementSizeInPointers(MachineRepresentation::kSimd128);
+ StartBlock();
+ Instruction* first_instr = EmitNop();
+ for (int i = 0; i < kSimd128Slots; ++i) {
+ AddMove(first_instr, Reg(0), Slot(i));
+ }
+ EmitOI(Slot(kSimd128Slots - 1, kSimd128), 0, nullptr);
+ Instruction* last_instr = LastInstruction();
+ EndBlock();
+ Optimize();
+
+ ParallelMove* first_move = first_instr->parallel_moves()[0];
+ CHECK_EQ(0, NonRedundantSize(first_move));
+
+ ParallelMove* last_move = last_instr->parallel_moves()[0];
+ CHECK_EQ(0, NonRedundantSize(last_move));
+}
+
+TEST_F(MoveOptimizerTest, MultiSlotStackWriteBlocksOverlappingReadMigration) {
+ const int kSimd128Slots =
+ ElementSizeInPointers(MachineRepresentation::kSimd128);
+ if (kSimd128Slots <= 1) return;
+
+ StartBlock();
+ EmitOI(Slot(kSimd128Slots - 1, kSimd128), 0, nullptr);
+ Instruction* write_instr = LastInstruction();
+ AddMove(write_instr, Slot(0), Reg(0));
+ Instruction* after_instr = EmitNop();
+ EndBlock(Last());
+
+ Optimize();
+
+ // Reading Slot(0) must happen before write_instr overwrites
+ // Slot(0..kSimd128Slots-1), so the move cannot migrate down to after_instr.
+ ParallelMove* write_move = write_instr->parallel_moves()[0];
+ CHECK_EQ(1, NonRedundantSize(write_move));
+ CHECK(Contains(write_move, Slot(0), Reg(0)));
+
+ ParallelMove* after_move = after_instr->parallel_moves()[0];
+ CHECK(after_move == nullptr || NonRedundantSize(after_move) == 0);
+}
+
+TEST_F(MoveOptimizerTest, MergeConflictWithOverlappingMultiSlotStackMove) {
+ const int kSimd128Slots =
+ ElementSizeInPointers(MachineRepresentation::kSimd128);
+ if (kSimd128Slots <= 1) return;
+
+ StartBlock();
+ EndBlock(Branch(Imm(), 1, 2));
+
+ StartBlock();
+ EndBlock(Jump(2));
+ Instruction* b1_last = LastInstruction();
+ AddMove(b1_last, Slot(0), Reg(0));
+ AddMove(b1_last, FPReg(kS128_1, kSimd128), Slot(kSimd128Slots - 1, kSimd128));
+
+ StartBlock();
+ EndBlock(Jump(1));
+ Instruction* b2_last = LastInstruction();
+ AddMove(b2_last, Slot(0), Reg(0));
+
+ StartBlock();
+ EndBlock(Last());
+ Instruction* merge_last = LastInstruction();
+
+ Optimize();
+
+ // Slot(0) -> Reg(0) cannot be hoisted into the merge block because b1_last
+ // overwrites Slot(0..kSimd128Slots-1) in parallel with reading Slot(0).
+ ParallelMove* merge_move = merge_last->parallel_moves()[0];
+ CHECK(merge_move == nullptr || NonRedundantSize(merge_move) == 0);
+ CHECK(Contains(b1_last->parallel_moves()[0], Slot(0), Reg(0)));
+ CHECK(Contains(b2_last->parallel_moves()[0], Slot(0), Reg(0)));
+}
+
+TEST_F(MoveOptimizerTest, VerifierDropsOverlappingMultiSlotStackAssessments) {
+ const int kSimd128Slots =
+ ElementSizeInPointers(MachineRepresentation::kSimd128);
+ if (kSimd128Slots <= 1) return;
+
+ WireBlocks();
+ BlockAssessments assessments(zone(), 0, sequence());
+
+ InstructionOperand q0 =
+ AllocatedOperand(LocationOperand::REGISTER, kSimd128, kS128_1);
+ InstructionOperand r0 = AllocatedOperand(LocationOperand::REGISTER,
+ MachineRepresentation::kWord32, 0);
+ InstructionOperand slot0 = AllocatedOperand(
+ LocationOperand::STACK_SLOT, MachineRepresentation::kWord32, 0);
+ InstructionOperand wide_slot = AllocatedOperand(LocationOperand::STACK_SLOT,
+ kSimd128, kSimd128Slots - 1);
+
+ assessments.AddDefinition(q0, 10);
+ assessments.AddDefinition(r0, 11);
+ for (int i = 0; i < kSimd128Slots; ++i) {
+ InstructionOperand narrow = AllocatedOperand(
+ LocationOperand::STACK_SLOT, MachineRepresentation::kWord32, i);
+ assessments.AddDefinition(narrow, 20 + i);
+ }
+
+ // Overwriting with a multi-slot move must drop all covered narrower slots.
+ ParallelMove* wide_pm = zone()->New<ParallelMove>(zone());
+ wide_pm->AddMove(q0, wide_slot);
+ assessments.PerformParallelMoves(wide_pm);
+ CHECK_EQ(assessments.map().end(), assessments.map().find(slot0));
+ auto wide_it = assessments.map().find(wide_slot);
+ CHECK_NE(assessments.map().end(), wide_it);
+ CHECK_EQ(10, FinalAssessment::cast(wide_it->second)->virtual_register());
+
+ // Subsequently writing a narrower overlapping slot (index 0) must drop the
+ // wider assessment anchored at index kSimd128Slots - 1.
+ ParallelMove* narrow_pm = zone()->New<ParallelMove>(zone());
+ narrow_pm->AddMove(r0, slot0);
+ assessments.PerformParallelMoves(narrow_pm);
+ CHECK_EQ(assessments.map().end(), assessments.map().find(wide_slot));
+ auto slot0_it = assessments.map().find(slot0);
+ CHECK_NE(assessments.map().end(), slot0_it);
+ CHECK_EQ(11, FinalAssessment::cast(slot0_it->second)->virtual_register());
+}
+
} // namespace compiler
} // namespace internal
} // namespace v8
diff --git a/deps/v8/test/unittests/compiler/regalloc/register-allocator-unittest.cc b/deps/v8/test/unittests/compiler/regalloc/register-allocator-unittest.cc
index 3bbfb402e65..b8a6e579d9b 100644
--- a/deps/v8/test/unittests/compiler/regalloc/register-allocator-unittest.cc
+++ b/deps/v8/test/unittests/compiler/regalloc/register-allocator-unittest.cc
@@ -2,6 +2,8 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
+#include <algorithm>
+
#include "src/codegen/assembler-inl.h"
#include "src/compiler/pipeline.h"
#include "src/compiler/turboshaft/pipelines.h"
@@ -855,6 +857,85 @@ TEST_F(RegisterAllocatorTest, AllocateBlockedRegDeferredClampBelowStart) {
Allocate();
}
+TEST_F(RegisterAllocatorTest, TaggedConstantSlotReferenceMap) {
+ StartBlock();
+ VReg tagged_const = DefineConstant();
+ sequence()->MarkAsRepresentation(MachineRepresentation::kTagged,
+ tagged_const.value_);
+ VReg compressed_const = DefineConstant();
+ sequence()->MarkAsRepresentation(MachineRepresentation::kCompressed,
+ compressed_const.value_);
+ VReg untagged_const = DefineConstant();
+
+ // First call uses reference constants in registers before any slot
+ // constraint; their constant spill slots are not yet initialized here.
+ EmitCall(Slot(-1), Reg(tagged_const), Reg(compressed_const));
+ const int call1_index = sequence()->LastInstructionIndex();
+
+ // Second call requires stack slots for all three constants, including
+ // duplicate slot inputs for `tagged_const`.
+ TestOperand call2_inputs[] = {Slot(tagged_const), Slot(tagged_const),
+ Slot(compressed_const), Slot(untagged_const)};
+ EmitCall(Slot(-2), arraysize(call2_inputs), call2_inputs);
+ const int call2_index = sequence()->LastInstructionIndex();
+
+ // Third call uses reference constants in registers rather than slots.
+ EmitCall(Slot(-3), Reg(tagged_const), Reg(compressed_const));
+ const int call3_index = sequence()->LastInstructionIndex();
+
+ // Fourth call again requires stack slots for both reference constants.
+ EmitCall(Slot(-4), Slot(tagged_const), Slot(compressed_const));
+ const int call4_index = sequence()->LastInstructionIndex();
+
+ // Non-call instruction requiring stack slots (e.g. eager deoptimize) has no
+ // ReferenceMap; verify slots are assigned without null-dereferencing it.
+ const Instruction* non_call =
+ EmitI(Slot(tagged_const), Slot(compressed_const));
+
+ Return(Reg(tagged_const));
+ EndBlock(Last());
+
+ Allocate();
+
+ const Instruction* call1 = sequence()->InstructionAt(call1_index);
+ const Instruction* call2 = sequence()->InstructionAt(call2_index);
+ const Instruction* call3 = sequence()->InstructionAt(call3_index);
+ const Instruction* call4 = sequence()->InstructionAt(call4_index);
+ ASSERT_TRUE(call1->HasReferenceMap());
+ ASSERT_TRUE(call2->HasReferenceMap());
+ ASSERT_TRUE(call3->HasReferenceMap());
+ ASSERT_TRUE(call4->HasReferenceMap());
+ ASSERT_FALSE(non_call->HasReferenceMap());
+
+ const InstructionOperand tagged_slot = *call2->InputAt(0);
+ const InstructionOperand compressed_slot = *call2->InputAt(2);
+ const InstructionOperand untagged_slot = *call2->InputAt(3);
+ ASSERT_TRUE(tagged_slot.IsStackSlot());
+ ASSERT_TRUE(compressed_slot.IsStackSlot());
+ ASSERT_TRUE(untagged_slot.IsStackSlot());
+ EXPECT_TRUE(tagged_slot.Equals(*call2->InputAt(1)));
+ EXPECT_TRUE(tagged_slot.Equals(*call4->InputAt(0)));
+ EXPECT_TRUE(compressed_slot.Equals(*call4->InputAt(1)));
+ EXPECT_TRUE(tagged_slot.Equals(*non_call->InputAt(0)));
+ EXPECT_TRUE(compressed_slot.Equals(*non_call->InputAt(1)));
+
+ auto count_in_ref_map = [](const Instruction* call,
+ const InstructionOperand& op) {
+ const auto& refs = call->reference_map()->reference_operands();
+ return std::count(refs.begin(), refs.end(), op);
+ };
+
+ EXPECT_EQ(0, count_in_ref_map(call1, tagged_slot));
+ EXPECT_EQ(0, count_in_ref_map(call1, compressed_slot));
+ EXPECT_EQ(1, count_in_ref_map(call2, tagged_slot));
+ EXPECT_EQ(1, count_in_ref_map(call2, compressed_slot));
+ EXPECT_EQ(0, count_in_ref_map(call2, untagged_slot));
+ EXPECT_EQ(0, count_in_ref_map(call3, tagged_slot));
+ EXPECT_EQ(0, count_in_ref_map(call3, compressed_slot));
+ EXPECT_EQ(1, count_in_ref_map(call4, tagged_slot));
+ EXPECT_EQ(1, count_in_ref_map(call4, compressed_slot));
+}
+
} // namespace
} // namespace compiler
} // namespace internal
diff --git a/deps/v8/test/unittests/compiler/turboshaft/machine-optimization-reducer-unittest.cc b/deps/v8/test/unittests/compiler/turboshaft/machine-optimization-reducer-unittest.cc
index 1f5db37a696..fd832a513cc 100644
--- a/deps/v8/test/unittests/compiler/turboshaft/machine-optimization-reducer-unittest.cc
+++ b/deps/v8/test/unittests/compiler/turboshaft/machine-optimization-reducer-unittest.cc
@@ -559,4 +559,45 @@ TEST_F(MachineOptimizationReducerTest, SelfComparisonLessThan) {
}
}
+TEST_F(MachineOptimizationReducerTest, Float64ToInt64ToFloat64Reversibility) {
+ const RegisterRepresentation rep_f64 = RegisterRepresentation::Float64();
+ base::SmallVector<RegisterRepresentation, 1> reps = {rep_f64};
+
+ // ReversibleFloat64ToInt64 excludes -0, so converting back to Float64 folds
+ // to the original input parameter.
+ {
+ auto test = CreateFromGraph(base::VectorOf(reps), [](auto& t) {
+ auto x = t.template GetParameter<Float64>(0);
+ auto i64 = t.Asm().ReversibleFloat64ToInt64(x);
+ auto f64 = t.Asm().ReversibleInt64ToFloat64(i64);
+ t.Asm().Return(f64);
+ });
+
+ test.Run<MachineOptimizationReducer>();
+ const ReturnOp* ret =
+ test.graph().Get(test.graph().LastOperation()).TryCast<ReturnOp>();
+ ASSERT_NE(ret, nullptr);
+ ASSERT_EQ(ret->return_values().size(), 1u);
+ EXPECT_TRUE(test.graph().Get(ret->return_values()[0]).Is<ParameterOp>());
+ }
+
+ // TruncateFloat64ToInt64OverflowUndefined maps -0 to 0, so converting back to
+ // Float64 must not fold to the original input.
+ {
+ auto test = CreateFromGraph(base::VectorOf(reps), [](auto& t) {
+ auto x = t.template GetParameter<Float64>(0);
+ auto i64 = t.Asm().TruncateFloat64ToInt64OverflowUndefined(x);
+ auto f64 = t.Asm().ReversibleInt64ToFloat64(i64);
+ t.Asm().Return(f64);
+ });
+
+ test.Run<MachineOptimizationReducer>();
+ const ReturnOp* ret =
+ test.graph().Get(test.graph().LastOperation()).TryCast<ReturnOp>();
+ ASSERT_NE(ret, nullptr);
+ ASSERT_EQ(ret->return_values().size(), 1u);
+ EXPECT_TRUE(test.graph().Get(ret->return_values()[0]).Is<ChangeOp>());
+ }
+}
+
} // namespace v8::internal::compiler::turboshaft