Truly independent web browser
Flap: Compile interpreters for a WebAssembly profile too
Andreas Kling1135c1c78da6
diff --git a/Libraries/LibJS/Flap/benches/compiler.rs b/Libraries/LibJS/Flap/benches/compiler.rsindex 97b245701f8..61e507e6e62 100644--- a/Libraries/LibJS/Flap/benches/compiler.rs+++ b/Libraries/LibJS/Flap/benches/compiler.rs@@ -56,6 +56,7 @@ fn compiler() -> Compiler {has_jscvt: false,enable_assertions: false,profiling: false,+ profile: flapc::Profile::JavaScript,})}diff --git a/Libraries/LibJS/Flap/src/frontend/layout.rs b/Libraries/LibJS/Flap/src/frontend/layout.rsindex c88b259779b..6dc6981026c 100644--- a/Libraries/LibJS/Flap/src/frontend/layout.rs+++ b/Libraries/LibJS/Flap/src/frontend/layout.rs@@ -77,6 +77,8 @@ define_known_layout_constants! {SizeOfExecutionContext => "SIZEOF_EXECUTION_CONTEXT";CanonicalNanBits => "CANON_NAN_BITS";HeapRegionOffsetMask => "HEAP_REGION_OFFSET_MASK";+ SpillAreaOffset => "SPILL_AREA_OFFSET";+ SpillAreaSlots => "SPILL_AREA_SLOTS";}#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]diff --git a/Libraries/LibJS/Flap/src/frontend/parser.rs b/Libraries/LibJS/Flap/src/frontend/parser.rsindex 78c25327637..b9b66cce4fe 100644--- a/Libraries/LibJS/Flap/src/frontend/parser.rs+++ b/Libraries/LibJS/Flap/src/frontend/parser.rs@@ -208,7 +208,13 @@ impl<'a> Lexer<'a> {.trim_start_matches("0x").trim_start_matches("0X").replace('_', "");- let value = i64::from_str_radix(&digits, radix).map_err(|_| {+ // Hexadecimal literals spell bit patterns, so they may set the sign bit.+ let value = if radix == 16 {+ u64::from_str_radix(&digits, radix).map(|value| value as i64)+ } else {+ i64::from_str_radix(&digits, radix)+ };+ let value = value.map_err(|_| {Diagnostic::new(self.filename,SourceSpan {@@ -427,7 +433,16 @@ impl<'a> Parser<'a> {let (annotation, span) = self.consume_identifier("handler annotation")?;match annotation.as_str() {"cold" => temperature = BlockTemperature::Cold,- "terminator" | "fallthrough" => {}+ "terminator" | "fallthrough" | "fallback" => {}+ // The bytecode metadata reads the opcode a raw-bytes handler+ // dispatches on; the handler body does not depend on it.+ "opcode" => {+ self.consume(TokenKind::LeftParen, "'('")?;+ while self.current().kind != TokenKind::RightParen {+ self.advance();+ }+ self.consume(TokenKind::RightParen, "')'")?;+ }_ => {return Err(Diagnostic::new(self.filename,diff --git a/Libraries/LibJS/Flap/src/frontend/specialize.rs b/Libraries/LibJS/Flap/src/frontend/specialize.rsindex 33a0d321e57..ea3edceb9ee 100644--- a/Libraries/LibJS/Flap/src/frontend/specialize.rs+++ b/Libraries/LibJS/Flap/src/frontend/specialize.rs@@ -460,6 +460,8 @@ mod tests {falls_through: false,layout: Default::default(),array: None,+ opcode: None,+ is_fallback: false,},components: Vec::new(),}];@@ -489,6 +491,8 @@ mod tests {falls_through: false,layout: Default::default(),array: None,+ opcode: None,+ is_fallback: false,},components: vec![crate::metadata::SpecializedComponentLayout {bytecode: "Source".to_string(),diff --git a/Libraries/LibJS/Flap/src/hir/definitions.rs b/Libraries/LibJS/Flap/src/hir/definitions.rsindex f09fc27cbea..b7eef2a472d 100644--- a/Libraries/LibJS/Flap/src/hir/definitions.rs+++ b/Libraries/LibJS/Flap/src/hir/definitions.rs@@ -174,6 +174,12 @@ pub(crate) enum Condition {relation: ComparisonRelation,signed: bool,},+ /// A comparison of two f64s with IEEE semantics: false if either is NaN, except for inequality.+ FloatComparison {+ lhs: Value,+ rhs: Value,+ comparison: crate::intrinsic::OrderedFloatComparison,+ },BitTest {value: Value,mask: Value,diff --git a/Libraries/LibJS/Flap/src/hir/intrinsic.rs b/Libraries/LibJS/Flap/src/hir/intrinsic.rsindex 4a9f3e35ea0..28fda19c3b3 100644--- a/Libraries/LibJS/Flap/src/hir/intrinsic.rs+++ b/Libraries/LibJS/Flap/src/hir/intrinsic.rs@@ -115,6 +115,7 @@ fn intrinsic_value_type(ty: IntrinsicValueType) -> Type {IntrinsicValueType::BytecodeOffset => Type::BytecodeOffset,IntrinsicValueType::F32 => Type::F32,IntrinsicValueType::F64 => Type::F64,+ IntrinsicValueType::V128 => Type::V128,IntrinsicValueType::FunctionSymbol => Type::FunctionSymbol,IntrinsicValueType::I32 => Type::I32,IntrinsicValueType::I64 => Type::I64,diff --git a/Libraries/LibJS/Flap/src/hir/mod.rs b/Libraries/LibJS/Flap/src/hir/mod.rsindex df91486ffa9..f0672ce16d5 100644--- a/Libraries/LibJS/Flap/src/hir/mod.rs+++ b/Libraries/LibJS/Flap/src/hir/mod.rs@@ -632,9 +632,6 @@ impl<'a> Checker<'a> {let Some(else_body) = else_body else {let then_body = self.check_scoped_block(then_body)?;let terminal = then_body.last().is_some_and(statement_is_terminal);- if *temperature == BlockTemperature::Cold && !terminal {- return self.error(statement.span, "a continuing if cannot be @cold");- }let captures = collect_captures(&then_body, outer_variable_count);self.statements.push(Statement::new(StatementKindIr::If {@@ -1507,15 +1504,11 @@ impl<'a> Checker<'a> {} else if *mode == ParameterMode::In&& (matches!(argument.kind,- ExpressionKind::Call { .. }- | ExpressionKind::Binary {- operator: BinaryOperator::Add | BinaryOperator::Subtract | BinaryOperator::Multiply,- ..- }- | ExpressionKind::Index { .. }- ) || matches!(&argument.kind, ExpressionKind::Name(name) if name.contains('.') && !name.starts_with('.')))+ ExpressionKind::Call { .. } | ExpressionKind::Index { .. }+ ) || integer_arithmetic_lhs(argument).is_some()+ || matches!(&argument.kind, ExpressionKind::Name(name) if name.contains('.') && !name.starts_with('.'))){- let call = self.check_initializer(argument)?;+ let call = self.check_initializer_with_expected(argument, Some(expected_type))?;if call.return_type.as_ref() != Some(expected_type) {let found = call.return_type@@ -2219,9 +2212,25 @@ impl<'a> Checker<'a> {ty: &Type,operation: IntegerBinaryOperation,) -> Result<Call, Diagnostic> {- let lhs = self.check_materialized_value(lhs, ty)?;+ let mut lhs = self.check_materialized_value(lhs, ty)?;if !matches!(lhs.kind, ValueKind::Variable(_)) {- return self.error(lhs.span, "integer arithmetic requires a binding as its left operand");+ // The arithmetic intrinsics take their left operand in a register, so a literal or constant goes into a+ // binding of its own first.+ let span = lhs.span;+ let destination = self.declare_hidden("arithmetic_lhs", ty.clone(), span);+ self.statements.push(Statement::new(+ StatementKindIr::call(+ [destination],+ Call::new(+ CallTarget::Intrinsic(Intrinsic::LowLevel(LowLevelOperation::Move)),+ vec![lhs],+ vec![ParameterMode::In],+ Some(ty.clone()),+ ),+ ),+ span,+ ));+ lhs = Value::new(ValueKind::Variable(destination), ty.clone(), span);}let rhs = self.check_materialized_value(rhs, ty)?;Ok(Call::new(@@ -2523,6 +2532,20 @@ impl<'a> Checker<'a> {let Some((lhs, lhs_type)) = self.check_scalar_condition_lhs(lhs)? else {return Ok(None);};+ if lhs_type == Type::F64 {+ let rhs = self.check_materialized_value(rhs, &lhs_type)?;+ use crate::intrinsic::OrderedFloatComparison;+ return Ok(Some(Condition::FloatComparison {+ lhs,+ rhs,+ comparison: match relation {+ ComparisonRelation::Less => OrderedFloatComparison::Less,+ ComparisonRelation::LessOrEqual => OrderedFloatComparison::LessOrEqual,+ ComparisonRelation::Greater => OrderedFloatComparison::Greater,+ ComparisonRelation::GreaterOrEqual => OrderedFloatComparison::GreaterOrEqual,+ },+ }));+ }let signed = match lhs_type {Type::I8 | Type::I16 | Type::I32 | Type::I64 => true,Type::U8 | Type::U16 | Type::U32 | Type::U64 => false,@@ -2549,6 +2572,18 @@ impl<'a> Checker<'a> {if lhs_type == Type::Value {return Ok(None);}+ if lhs_type == Type::F64 {+ let rhs = self.check_materialized_value(rhs, &lhs_type)?;+ return Ok(Some(Condition::FloatComparison {+ lhs,+ rhs,+ comparison: if equal {+ crate::intrinsic::OrderedFloatComparison::Equal+ } else {+ crate::intrinsic::OrderedFloatComparison::NotEqual+ },+ }));+ }let rhs = match &rhs.kind {ExpressionKind::Integer(0) => Value::new(ValueKind::Integer(0), lhs_type.clone(), rhs.span),_ => self.check_materialized_value(rhs, &lhs_type)?,@@ -3833,6 +3868,7 @@ pub(crate) fn condition_uses_and_defs(condition: &Condition) -> (Vec<VariableId>Condition::LogicalNot(condition) => condition_uses_and_defs(condition),Condition::ScalarEquality { lhs, rhs, .. } => (direct_value_variables([lhs, rhs]), Vec::new()),Condition::ScalarRelational { lhs, rhs, .. } => (direct_value_variables([lhs, rhs]), Vec::new()),+ Condition::FloatComparison { lhs, rhs, .. } => (direct_value_variables([lhs, rhs]), Vec::new()),Condition::BitTest { value, mask, .. } => (direct_value_variables([value, mask]), Vec::new()),Condition::ValueTag {value, tag, source_tag, ..diff --git a/Libraries/LibJS/Flap/src/identity.rs b/Libraries/LibJS/Flap/src/identity.rsindex 18f0faa3d69..2c9a8d8b22d 100644--- a/Libraries/LibJS/Flap/src/identity.rs+++ b/Libraries/LibJS/Flap/src/identity.rs@@ -60,3 +60,19 @@ impl HandlerId {self.0 as usize}}++/// The handlers one prefix opcode dispatches to on its sub-opcode.+#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) struct SecondaryDispatchTable {+ pub(crate) prefix: u8,+ pub(crate) handlers: Vec<Option<HandlerId>>,+}++/// The dispatch tables a program has beyond its primary opcode table.+#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub(crate) struct DispatchLayout {+ pub(crate) secondary: Vec<SecondaryDispatchTable>,+ /// The handler that runs opcodes nothing else handles. Without one, they+ /// go to the profile's built-in fallback stub.+ pub(crate) fallback: Option<HandlerId>,+}diff --git a/Libraries/LibJS/Flap/src/intrinsic.rs b/Libraries/LibJS/Flap/src/intrinsic.rsindex 351c7589cb5..eda648b9101 100644--- a/Libraries/LibJS/Flap/src/intrinsic.rs+++ b/Libraries/LibJS/Flap/src/intrinsic.rs@@ -366,7 +366,12 @@ pub(crate) enum MemoryWidth {HalfWord,Word,DoubleWord,+ /// An f32 in a floating-point register.Float,+ /// An f64 in a floating-point register.+ Double,+ /// A 128-bit vector, in a floating-point register.+ Vector,}#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]@@ -452,6 +457,7 @@ pub(crate) enum BranchOperation {},AnyEqual,ValueBitsNegative,+ OrderedFloat(OrderedFloatComparison),}intrinsic_names!(BranchOperation {@@ -482,6 +488,12 @@ intrinsic_names!(BranchOperation {Self::Bit(TestCondition::Set) => "branch_bit_set" signatures [signature!([In AnyGpr, In AnyGpr, In Label])];Self::AnyEqual => "branch_any_eq" signatures [signature!([In AnyGpr, In AnyGpr, In AnyGpr, In Label])];Self::ValueBitsNegative => "branch_value_bits_negative" signatures [signature!([In Value, In Label])];+ Self::OrderedFloat(OrderedFloatComparison::Equal) => "branch_float_equal" signatures [signature!([In F64, In F64, In Label])];+ Self::OrderedFloat(OrderedFloatComparison::NotEqual) => "branch_float_not_equal" signatures [signature!([In F64, In F64, In Label])];+ Self::OrderedFloat(OrderedFloatComparison::Less) => "branch_float_less" signatures [signature!([In F64, In F64, In Label])];+ Self::OrderedFloat(OrderedFloatComparison::LessOrEqual) => "branch_float_less_or_equal" signatures [signature!([In F64, In F64, In Label])];+ Self::OrderedFloat(OrderedFloatComparison::Greater) => "branch_float_greater" signatures [signature!([In F64, In F64, In Label])];+ Self::OrderedFloat(OrderedFloatComparison::GreaterOrEqual) => "branch_float_greater_or_equal" signatures [signature!([In F64, In F64, In Label])];});impl BranchOperation {@@ -529,6 +541,11 @@ impl BranchOperation {width: IntegerWidth::U64,condition: SignCondition::NotNegative,},+ Self::OrderedFloat(comparison) => Self::OrderedFloat(match comparison {+ OrderedFloatComparison::Equal => OrderedFloatComparison::NotEqual,+ OrderedFloatComparison::NotEqual => OrderedFloatComparison::Equal,+ _ => return None,+ }),Self::Float(_) | Self::AnyEqual => return None,})}@@ -616,6 +633,538 @@ define_named_intrinsic_enum! {}}+define_named_intrinsic_enum! {+ // Integer and floating-point operations that machine-independent code has no other form for. Integer operands+ // and results are bit patterns: 32-bit ones are zero-extended u32s, whatever their signedness. Truncating a+ // float does not check the range: out-of-range inputs give 0x8000000000000000.+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]+ pub(crate) enum NumericOperation {+ DivideSigned32 => "div_s32" signatures [signature!([In U32, In U32] -> U32)];+ DivideUnsigned32 => "div_u32" signatures [signature!([In U32, In U32] -> U32)];+ RemainderSigned32 => "rem_s32" signatures [signature!([In U32, In U32] -> U32)];+ RemainderUnsigned32 => "rem_u32" signatures [signature!([In U32, In U32] -> U32)];+ DivideSigned64 => "div_s64" signatures [signature!([In U64, In U64] -> U64)];+ DivideUnsigned64 => "div_u64" signatures [signature!([In U64, In U64] -> U64)];+ RemainderSigned64 => "rem_s64" signatures [signature!([In U64, In U64] -> U64)];+ RemainderUnsigned64 => "rem_u64" signatures [signature!([In U64, In U64] -> U64)];+ CountLeadingZeros32 => "clz32" signatures [signature!([In U32] -> U32)];+ CountTrailingZeros32 => "ctz32" signatures [signature!([In U32] -> U32)];+ PopulationCount32 => "popcnt32" signatures [signature!([In U32] -> U32)];+ CountLeadingZeros64 => "clz64" signatures [signature!([In U64] -> U64)];+ CountTrailingZeros64 => "ctz64" signatures [signature!([In U64] -> U64)];+ PopulationCount64 => "popcnt64" signatures [signature!([In U64] -> U64)];+ RotateLeft32 => "rotl32" signatures [signature!([In U32, In U32] -> U32)];+ RotateRight32 => "rotr32" signatures [signature!([In U32, In U32] -> U32)];+ RotateLeft64 => "rotl64" signatures [signature!([In U64, In U64] -> U64)];+ RotateRight64 => "rotr64" signatures [signature!([In U64, In U64] -> U64)];+ Float64FromBits => "f64_from_bits" signatures [signature!([In U64] -> F64)];+ Float64ToBits => "f64_to_bits" signatures [signature!([In F64] -> U64)];+ Float32FromBits => "f32_from_bits" signatures [signature!([In U32] -> F32)];+ Float32ToBits => "f32_to_bits" signatures [signature!([In F32] -> U32)];+ TruncateFloat64ToSigned64 => "truncate_f64_to_s64" signatures [signature!([In F64] -> U64)];+ ConvertSigned64ToFloat32 => "s64_to_f32" signatures [signature!([In U64] -> F32)];+ ConvertSigned64ToFloat64 => "s64_to_f64" signatures [signature!([In U64] -> F64)];+ RoundFloat64ToZero => "trunc_f64" signatures [signature!([In F64] -> F64)];+ RoundFloat64ToNearest => "nearest_f64" signatures [signature!([In F64] -> F64)];+ RoundFloat64Up => "ceil_f64" signatures [signature!([In F64] -> F64)];+ RoundFloat64Down => "floor_f64" signatures [signature!([In F64] -> F64)];+ SquareRootFloat64 => "sqrt_f64" signatures [signature!([In F64] -> F64)];+ AddFloat32 => "add_f32" signatures [signature!([In F32, In F32] -> F32)];+ SubtractFloat32 => "sub_f32" signatures [signature!([In F32, In F32] -> F32)];+ MultiplyFloat32 => "mul_f32" signatures [signature!([In F32, In F32] -> F32)];+ DivideFloat32 => "div_f32" signatures [signature!([In F32, In F32] -> F32)];+ SquareRootFloat32 => "sqrt_f32" signatures [signature!([In F32] -> F32)];+ PromoteFloat32 => "promote_f32" signatures [signature!([In F32] -> F64)];+ DemoteFloat64 => "demote_f64" signatures [signature!([In F64] -> F32)];+ }+}++define_named_intrinsic_enum! {+ // Atomic accesses to 8 to 64 bits of memory, sequentially consistent: loads, and read-modify-write operations,+ // which return the old value, zero-extended. An exchange whose result is unused is a sequentially consistent+ // store. The fence orders the plain accesses around it like a sequentially consistent access would.+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]+ pub(crate) enum AtomicOperation {+ CompareExchange8 => "atomic_cmpxchg8" signatures [signature!([In Memory, In U64, In U64] -> U64)];+ CompareExchange16 => "atomic_cmpxchg16" signatures [signature!([In Memory, In U64, In U64] -> U64)];+ CompareExchange32 => "atomic_cmpxchg32" signatures [signature!([In Memory, In U64, In U64] -> U64)];+ CompareExchange64 => "atomic_cmpxchg64" signatures [signature!([In Memory, In U64, In U64] -> U64)];+ Exchange8 => "atomic_xchg8" signatures [signature!([In Memory, In U64] -> U64)];+ Exchange16 => "atomic_xchg16" signatures [signature!([In Memory, In U64] -> U64)];+ Exchange32 => "atomic_xchg32" signatures [signature!([In Memory, In U64] -> U64)];+ Exchange64 => "atomic_xchg64" signatures [signature!([In Memory, In U64] -> U64)];+ FetchAdd8 => "atomic_add8" signatures [signature!([In Memory, In U64] -> U64)];+ FetchAdd16 => "atomic_add16" signatures [signature!([In Memory, In U64] -> U64)];+ FetchAdd32 => "atomic_add32" signatures [signature!([In Memory, In U64] -> U64)];+ FetchAdd64 => "atomic_add64" signatures [signature!([In Memory, In U64] -> U64)];+ Load8 => "atomic_load8" signatures [signature!([In Memory] -> U64)];+ Load16 => "atomic_load16" signatures [signature!([In Memory] -> U64)];+ Load32 => "atomic_load32" signatures [signature!([In Memory] -> U64)];+ Load64 => "atomic_load64" signatures [signature!([In Memory] -> U64)];+ Fence => "atomic_fence" signatures [signature!([])];+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum AtomicOperationKind {+ CompareExchange,+ Exchange,+ FetchAdd,+ Load,+ Fence,+}++impl AtomicOperation {+ pub(crate) fn kind(self) -> AtomicOperationKind {+ use AtomicOperation::*;+ match self {+ CompareExchange8 | CompareExchange16 | CompareExchange32 | CompareExchange64 => {+ AtomicOperationKind::CompareExchange+ }+ Exchange8 | Exchange16 | Exchange32 | Exchange64 => AtomicOperationKind::Exchange,+ FetchAdd8 | FetchAdd16 | FetchAdd32 | FetchAdd64 => AtomicOperationKind::FetchAdd,+ Load8 | Load16 | Load32 | Load64 => AtomicOperationKind::Load,+ Fence => AtomicOperationKind::Fence,+ }+ }++ pub(crate) fn width(self) -> IntegerWidth {+ use AtomicOperation::*;+ match self {+ CompareExchange8 | Exchange8 | FetchAdd8 | Load8 => IntegerWidth::U8,+ CompareExchange16 | Exchange16 | FetchAdd16 | Load16 => IntegerWidth::U16,+ CompareExchange32 | Exchange32 | FetchAdd32 | Load32 => IntegerWidth::U32,+ CompareExchange64 | Exchange64 | FetchAdd64 | Load64 | Fence => IntegerWidth::U64,+ }+ }+}++define_named_intrinsic_enum! {+ // 128-bit vector operations, most of them one SSE4.1 instruction on x86-64. Lanes are little-endian, the lowest+ // lane in the lowest bytes. Binary operations take the destination's lanes from their left operand. Shifts take+ // their count from the low 64 bits of their right operand. Comparisons set every bit of a true lane.+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]+ pub(crate) enum VectorOperation {+ FromU64Pair => "v128_from_u64x2" signatures [signature!([In U64, In U64] -> V128)];+ And => "v128_and" signatures [signature!([In V128, In V128] -> V128)];+ Or => "v128_or" signatures [signature!([In V128, In V128] -> V128)];+ Xor => "v128_xor" signatures [signature!([In V128, In V128] -> V128)];+ AndNot => "v128_andnot" signatures [signature!([In V128, In V128] -> V128)];+ AddI8 => "v128_add_i8" signatures [signature!([In V128, In V128] -> V128)];+ SubtractI8 => "v128_sub_i8" signatures [signature!([In V128, In V128] -> V128)];+ EqualI8 => "v128_eq_i8" signatures [signature!([In V128, In V128] -> V128)];+ GreaterSignedI8 => "v128_gt_s_i8" signatures [signature!([In V128, In V128] -> V128)];+ AddI16 => "v128_add_i16" signatures [signature!([In V128, In V128] -> V128)];+ SubtractI16 => "v128_sub_i16" signatures [signature!([In V128, In V128] -> V128)];+ EqualI16 => "v128_eq_i16" signatures [signature!([In V128, In V128] -> V128)];+ GreaterSignedI16 => "v128_gt_s_i16" signatures [signature!([In V128, In V128] -> V128)];+ AddI32 => "v128_add_i32" signatures [signature!([In V128, In V128] -> V128)];+ SubtractI32 => "v128_sub_i32" signatures [signature!([In V128, In V128] -> V128)];+ EqualI32 => "v128_eq_i32" signatures [signature!([In V128, In V128] -> V128)];+ GreaterSignedI32 => "v128_gt_s_i32" signatures [signature!([In V128, In V128] -> V128)];+ AddI64 => "v128_add_i64" signatures [signature!([In V128, In V128] -> V128)];+ SubtractI64 => "v128_sub_i64" signatures [signature!([In V128, In V128] -> V128)];+ EqualI64 => "v128_eq_i64" signatures [signature!([In V128, In V128] -> V128)];+ GreaterSignedI64 => "v128_gt_s_i64" signatures [signature!([In V128, In V128] -> V128)];+ AddSaturateSignedI8 => "v128_add_sat_s_i8" signatures [signature!([In V128, In V128] -> V128)];+ AddSaturateUnsignedI8 => "v128_add_sat_u_i8" signatures [signature!([In V128, In V128] -> V128)];+ SubtractSaturateSignedI8 => "v128_sub_sat_s_i8" signatures [signature!([In V128, In V128] -> V128)];+ SubtractSaturateUnsignedI8 => "v128_sub_sat_u_i8" signatures [signature!([In V128, In V128] -> V128)];+ AverageUnsignedI8 => "v128_avgr_u_i8" signatures [signature!([In V128, In V128] -> V128)];+ AddSaturateSignedI16 => "v128_add_sat_s_i16" signatures [signature!([In V128, In V128] -> V128)];+ AddSaturateUnsignedI16 => "v128_add_sat_u_i16" signatures [signature!([In V128, In V128] -> V128)];+ SubtractSaturateSignedI16 => "v128_sub_sat_s_i16" signatures [signature!([In V128, In V128] -> V128)];+ SubtractSaturateUnsignedI16 => "v128_sub_sat_u_i16" signatures [signature!([In V128, In V128] -> V128)];+ AverageUnsignedI16 => "v128_avgr_u_i16" signatures [signature!([In V128, In V128] -> V128)];+ MultiplyI16 => "v128_mul_i16" signatures [signature!([In V128, In V128] -> V128)];+ MultiplyI32 => "v128_mul_i32" signatures [signature!([In V128, In V128] -> V128)];+ MultiplyUnsignedLowI32 => "v128_mul_u32_to_u64" signatures [signature!([In V128, In V128] -> V128)];+ MultiplyHighSignedI16 => "v128_mulhi_s_i16" signatures [signature!([In V128, In V128] -> V128)];+ MultiplyHighUnsignedI16 => "v128_mulhi_u_i16" signatures [signature!([In V128, In V128] -> V128)];+ MultiplyHighRoundScaleI16 => "v128_mulhrs_i16" signatures [signature!([In V128, In V128] -> V128)];+ MultiplyAddI16 => "v128_madd_i16" signatures [signature!([In V128, In V128] -> V128)];+ MultiplyAddUnsignedSignedI8 => "v128_madd_u8_s8" signatures [signature!([In V128, In V128] -> V128)];+ MinimumSignedI8 => "v128_min_s_i8" signatures [signature!([In V128, In V128] -> V128)];+ MinimumUnsignedI8 => "v128_min_u_i8" signatures [signature!([In V128, In V128] -> V128)];+ MaximumSignedI8 => "v128_max_s_i8" signatures [signature!([In V128, In V128] -> V128)];+ MaximumUnsignedI8 => "v128_max_u_i8" signatures [signature!([In V128, In V128] -> V128)];+ MinimumSignedI16 => "v128_min_s_i16" signatures [signature!([In V128, In V128] -> V128)];+ MinimumUnsignedI16 => "v128_min_u_i16" signatures [signature!([In V128, In V128] -> V128)];+ MaximumSignedI16 => "v128_max_s_i16" signatures [signature!([In V128, In V128] -> V128)];+ MaximumUnsignedI16 => "v128_max_u_i16" signatures [signature!([In V128, In V128] -> V128)];+ MinimumSignedI32 => "v128_min_s_i32" signatures [signature!([In V128, In V128] -> V128)];+ MinimumUnsignedI32 => "v128_min_u_i32" signatures [signature!([In V128, In V128] -> V128)];+ MaximumSignedI32 => "v128_max_s_i32" signatures [signature!([In V128, In V128] -> V128)];+ MaximumUnsignedI32 => "v128_max_u_i32" signatures [signature!([In V128, In V128] -> V128)];+ ShiftLeftI16 => "v128_shl_i16" signatures [signature!([In V128, In V128] -> V128)];+ ShiftRightUnsignedI16 => "v128_shr_u_i16" signatures [signature!([In V128, In V128] -> V128)];+ ShiftLeftI32 => "v128_shl_i32" signatures [signature!([In V128, In V128] -> V128)];+ ShiftRightUnsignedI32 => "v128_shr_u_i32" signatures [signature!([In V128, In V128] -> V128)];+ ShiftLeftI64 => "v128_shl_i64" signatures [signature!([In V128, In V128] -> V128)];+ ShiftRightUnsignedI64 => "v128_shr_u_i64" signatures [signature!([In V128, In V128] -> V128)];+ ShiftRightSignedI16 => "v128_shr_s_i16" signatures [signature!([In V128, In V128] -> V128)];+ ShiftRightSignedI32 => "v128_shr_s_i32" signatures [signature!([In V128, In V128] -> V128)];+ Shuffle8 => "v128_shuffle_i8" signatures [signature!([In V128, In V128] -> V128)];+ NarrowSignedI16 => "v128_narrow_s_i16" signatures [signature!([In V128, In V128] -> V128)];+ NarrowUnsignedI16 => "v128_narrow_u_i16" signatures [signature!([In V128, In V128] -> V128)];+ NarrowSignedI32 => "v128_narrow_s_i32" signatures [signature!([In V128, In V128] -> V128)];+ NarrowUnsignedI32 => "v128_narrow_u_i32" signatures [signature!([In V128, In V128] -> V128)];+ InterleaveLowI8 => "v128_interleave_low_i8" signatures [signature!([In V128, In V128] -> V128)];+ InterleaveHighI8 => "v128_interleave_high_i8" signatures [signature!([In V128, In V128] -> V128)];+ InterleaveLowI16 => "v128_interleave_low_i16" signatures [signature!([In V128, In V128] -> V128)];+ InterleaveHighI16 => "v128_interleave_high_i16" signatures [signature!([In V128, In V128] -> V128)];+ InterleaveLowI32 => "v128_interleave_low_i32" signatures [signature!([In V128, In V128] -> V128)];+ InterleaveHighI32 => "v128_interleave_high_i32" signatures [signature!([In V128, In V128] -> V128)];+ InterleaveLowI64 => "v128_interleave_low_i64" signatures [signature!([In V128, In V128] -> V128)];+ InterleaveHighI64 => "v128_interleave_high_i64" signatures [signature!([In V128, In V128] -> V128)];+ AddF32 => "v128_add_f32" signatures [signature!([In V128, In V128] -> V128)];+ SubtractF32 => "v128_sub_f32" signatures [signature!([In V128, In V128] -> V128)];+ MultiplyF32 => "v128_mul_f32" signatures [signature!([In V128, In V128] -> V128)];+ DivideF32 => "v128_div_f32" signatures [signature!([In V128, In V128] -> V128)];+ MinimumF32 => "v128_min_f32" signatures [signature!([In V128, In V128] -> V128)];+ MaximumF32 => "v128_max_f32" signatures [signature!([In V128, In V128] -> V128)];+ EqualF32 => "v128_eq_f32" signatures [signature!([In V128, In V128] -> V128)];+ NotEqualF32 => "v128_ne_f32" signatures [signature!([In V128, In V128] -> V128)];+ LessF32 => "v128_lt_f32" signatures [signature!([In V128, In V128] -> V128)];+ LessOrEqualF32 => "v128_le_f32" signatures [signature!([In V128, In V128] -> V128)];+ UnorderedF32 => "v128_unord_f32" signatures [signature!([In V128, In V128] -> V128)];+ SquareRootF32 => "v128_sqrt_f32" signatures [signature!([In V128] -> V128)];+ CeilF32 => "v128_ceil_f32" signatures [signature!([In V128] -> V128)];+ FloorF32 => "v128_floor_f32" signatures [signature!([In V128] -> V128)];+ TruncF32 => "v128_trunc_f32" signatures [signature!([In V128] -> V128)];+ NearestF32 => "v128_nearest_f32" signatures [signature!([In V128] -> V128)];+ AddF64 => "v128_add_f64" signatures [signature!([In V128, In V128] -> V128)];+ SubtractF64 => "v128_sub_f64" signatures [signature!([In V128, In V128] -> V128)];+ MultiplyF64 => "v128_mul_f64" signatures [signature!([In V128, In V128] -> V128)];+ DivideF64 => "v128_div_f64" signatures [signature!([In V128, In V128] -> V128)];+ MinimumF64 => "v128_min_f64" signatures [signature!([In V128, In V128] -> V128)];+ MaximumF64 => "v128_max_f64" signatures [signature!([In V128, In V128] -> V128)];+ EqualF64 => "v128_eq_f64" signatures [signature!([In V128, In V128] -> V128)];+ NotEqualF64 => "v128_ne_f64" signatures [signature!([In V128, In V128] -> V128)];+ LessF64 => "v128_lt_f64" signatures [signature!([In V128, In V128] -> V128)];+ LessOrEqualF64 => "v128_le_f64" signatures [signature!([In V128, In V128] -> V128)];+ UnorderedF64 => "v128_unord_f64" signatures [signature!([In V128, In V128] -> V128)];+ SquareRootF64 => "v128_sqrt_f64" signatures [signature!([In V128] -> V128)];+ CeilF64 => "v128_ceil_f64" signatures [signature!([In V128] -> V128)];+ FloorF64 => "v128_floor_f64" signatures [signature!([In V128] -> V128)];+ TruncF64 => "v128_trunc_f64" signatures [signature!([In V128] -> V128)];+ NearestF64 => "v128_nearest_f64" signatures [signature!([In V128] -> V128)];+ AbsoluteI8 => "v128_abs_i8" signatures [signature!([In V128] -> V128)];+ AbsoluteI16 => "v128_abs_i16" signatures [signature!([In V128] -> V128)];+ AbsoluteI32 => "v128_abs_i32" signatures [signature!([In V128] -> V128)];+ ExtendLowSignedI8 => "v128_extend_low_s_i8" signatures [signature!([In V128] -> V128)];+ ExtendLowUnsignedI8 => "v128_extend_low_u_i8" signatures [signature!([In V128] -> V128)];+ ExtendLowSignedI16 => "v128_extend_low_s_i16" signatures [signature!([In V128] -> V128)];+ ExtendLowUnsignedI16 => "v128_extend_low_u_i16" signatures [signature!([In V128] -> V128)];+ ExtendLowSignedI32 => "v128_extend_low_s_i32" signatures [signature!([In V128] -> V128)];+ ExtendLowUnsignedI32 => "v128_extend_low_u_i32" signatures [signature!([In V128] -> V128)];+ ConvertSignedI32ToF32 => "v128_convert_s_i32_f32" signatures [signature!([In V128] -> V128)];+ TruncateF32ToSignedI32 => "v128_truncate_f32_s_i32" signatures [signature!([In V128] -> V128)];+ ConvertLowSignedI32ToF64 => "v128_convert_low_s_i32_f64" signatures [signature!([In V128] -> V128)];+ TruncateF64ToSignedI32 => "v128_truncate_f64_s_i32" signatures [signature!([In V128] -> V128)];+ PromoteLowF32 => "v128_promote_low_f32" signatures [signature!([In V128] -> V128)];+ DemoteF64 => "v128_demote_f64" signatures [signature!([In V128] -> V128)];+ HighHalf => "v128_high_half" signatures [signature!([In V128] -> V128)];+ BroadcastLowI32 => "v128_broadcast_low_i32" signatures [signature!([In V128] -> V128)];+ Low64 => "v128_low_u64" signatures [signature!([In V128] -> U64)];+ High64 => "v128_high_u64" signatures [signature!([In V128] -> U64)];+ ByteMask => "v128_bitmask_i8" signatures [signature!([In V128] -> U64)];+ SignMaskF32 => "v128_bitmask_f32" signatures [signature!([In V128] -> U64)];+ SignMaskF64 => "v128_bitmask_f64" signatures [signature!([In V128] -> U64)];+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum VectorOperationKind {+ /// Two u64 halves, the low one first, make a vector.+ FromU64Pair,+ Binary,+ Unary,+ /// A vector gives a u64.+ ToGeneralPurpose,+ /// A vector gives a u32, zero-extended.+ ToGeneralPurpose32,+}++impl VectorOperation {+ pub(crate) fn kind(self) -> VectorOperationKind {+ match self {+ Self::FromU64Pair => VectorOperationKind::FromU64Pair,+ Self::And+ | Self::Or+ | Self::Xor+ | Self::AndNot+ | Self::AddI8+ | Self::SubtractI8+ | Self::EqualI8+ | Self::GreaterSignedI8+ | Self::AddI16+ | Self::SubtractI16+ | Self::EqualI16+ | Self::GreaterSignedI16+ | Self::AddI32+ | Self::SubtractI32+ | Self::EqualI32+ | Self::GreaterSignedI32+ | Self::AddI64+ | Self::SubtractI64+ | Self::EqualI64+ | Self::GreaterSignedI64+ | Self::AddSaturateSignedI8+ | Self::AddSaturateUnsignedI8+ | Self::SubtractSaturateSignedI8+ | Self::SubtractSaturateUnsignedI8+ | Self::AverageUnsignedI8+ | Self::AddSaturateSignedI16+ | Self::AddSaturateUnsignedI16+ | Self::SubtractSaturateSignedI16+ | Self::SubtractSaturateUnsignedI16+ | Self::AverageUnsignedI16+ | Self::MultiplyI16+ | Self::MultiplyI32+ | Self::MultiplyUnsignedLowI32+ | Self::MultiplyHighSignedI16+ | Self::MultiplyHighUnsignedI16+ | Self::MultiplyHighRoundScaleI16+ | Self::MultiplyAddI16+ | Self::MultiplyAddUnsignedSignedI8+ | Self::MinimumSignedI8+ | Self::MinimumUnsignedI8+ | Self::MaximumSignedI8+ | Self::MaximumUnsignedI8+ | Self::MinimumSignedI16+ | Self::MinimumUnsignedI16+ | Self::MaximumSignedI16+ | Self::MaximumUnsignedI16+ | Self::MinimumSignedI32+ | Self::MinimumUnsignedI32+ | Self::MaximumSignedI32+ | Self::MaximumUnsignedI32+ | Self::ShiftLeftI16+ | Self::ShiftRightUnsignedI16+ | Self::ShiftLeftI32+ | Self::ShiftRightUnsignedI32+ | Self::ShiftLeftI64+ | Self::ShiftRightUnsignedI64+ | Self::ShiftRightSignedI16+ | Self::ShiftRightSignedI32+ | Self::Shuffle8+ | Self::NarrowSignedI16+ | Self::NarrowUnsignedI16+ | Self::NarrowSignedI32+ | Self::NarrowUnsignedI32+ | Self::InterleaveLowI8+ | Self::InterleaveHighI8+ | Self::InterleaveLowI16+ | Self::InterleaveHighI16+ | Self::InterleaveLowI32+ | Self::InterleaveHighI32+ | Self::InterleaveLowI64+ | Self::InterleaveHighI64+ | Self::AddF32+ | Self::SubtractF32+ | Self::MultiplyF32+ | Self::DivideF32+ | Self::MinimumF32+ | Self::MaximumF32+ | Self::EqualF32+ | Self::NotEqualF32+ | Self::LessF32+ | Self::LessOrEqualF32+ | Self::UnorderedF32+ | Self::AddF64+ | Self::SubtractF64+ | Self::MultiplyF64+ | Self::DivideF64+ | Self::MinimumF64+ | Self::MaximumF64+ | Self::EqualF64+ | Self::NotEqualF64+ | Self::LessF64+ | Self::LessOrEqualF64+ | Self::UnorderedF64 => VectorOperationKind::Binary,+ Self::SquareRootF32+ | Self::CeilF32+ | Self::FloorF32+ | Self::TruncF32+ | Self::NearestF32+ | Self::SquareRootF64+ | Self::CeilF64+ | Self::FloorF64+ | Self::TruncF64+ | Self::NearestF64+ | Self::AbsoluteI8+ | Self::AbsoluteI16+ | Self::AbsoluteI32+ | Self::ExtendLowSignedI8+ | Self::ExtendLowUnsignedI8+ | Self::ExtendLowSignedI16+ | Self::ExtendLowUnsignedI16+ | Self::ExtendLowSignedI32+ | Self::ExtendLowUnsignedI32+ | Self::ConvertSignedI32ToF32+ | Self::TruncateF32ToSignedI32+ | Self::ConvertLowSignedI32ToF64+ | Self::TruncateF64ToSignedI32+ | Self::PromoteLowF32+ | Self::DemoteF64+ | Self::HighHalf+ | Self::BroadcastLowI32 => VectorOperationKind::Unary,+ Self::Low64 | Self::High64 => VectorOperationKind::ToGeneralPurpose,+ Self::ByteMask | Self::SignMaskF32 | Self::SignMaskF64 => VectorOperationKind::ToGeneralPurpose32,+ }+ }++ pub(crate) fn x86_64_mnemonic(self) -> &'static str {+ match self {+ Self::FromU64Pair => "movq",+ Self::And => "pand",+ Self::Or => "por",+ Self::Xor => "pxor",+ Self::AndNot => "pandn",+ Self::AddI8 => "paddb",+ Self::SubtractI8 => "psubb",+ Self::EqualI8 => "pcmpeqb",+ Self::GreaterSignedI8 => "pcmpgtb",+ Self::AddI16 => "paddw",+ Self::SubtractI16 => "psubw",+ Self::EqualI16 => "pcmpeqw",+ Self::GreaterSignedI16 => "pcmpgtw",+ Self::AddI32 => "paddd",+ Self::SubtractI32 => "psubd",+ Self::EqualI32 => "pcmpeqd",+ Self::GreaterSignedI32 => "pcmpgtd",+ Self::AddI64 => "paddq",+ Self::SubtractI64 => "psubq",+ Self::EqualI64 => "pcmpeqq",+ Self::GreaterSignedI64 => "pcmpgtq",+ Self::AddSaturateSignedI8 => "paddsb",+ Self::AddSaturateUnsignedI8 => "paddusb",+ Self::SubtractSaturateSignedI8 => "psubsb",+ Self::SubtractSaturateUnsignedI8 => "psubusb",+ Self::AverageUnsignedI8 => "pavgb",+ Self::AddSaturateSignedI16 => "paddsw",+ Self::AddSaturateUnsignedI16 => "paddusw",+ Self::SubtractSaturateSignedI16 => "psubsw",+ Self::SubtractSaturateUnsignedI16 => "psubusw",+ Self::AverageUnsignedI16 => "pavgw",+ Self::MultiplyI16 => "pmullw",+ Self::MultiplyI32 => "pmulld",+ Self::MultiplyUnsignedLowI32 => "pmuludq",+ Self::MultiplyHighSignedI16 => "pmulhw",+ Self::MultiplyHighUnsignedI16 => "pmulhuw",+ Self::MultiplyHighRoundScaleI16 => "pmulhrsw",+ Self::MultiplyAddI16 => "pmaddwd",+ Self::MultiplyAddUnsignedSignedI8 => "pmaddubsw",+ Self::MinimumSignedI8 => "pminsb",+ Self::MinimumUnsignedI8 => "pminub",+ Self::MaximumSignedI8 => "pmaxsb",+ Self::MaximumUnsignedI8 => "pmaxub",+ Self::MinimumSignedI16 => "pminsw",+ Self::MinimumUnsignedI16 => "pminuw",+ Self::MaximumSignedI16 => "pmaxsw",+ Self::MaximumUnsignedI16 => "pmaxuw",+ Self::MinimumSignedI32 => "pminsd",+ Self::MinimumUnsignedI32 => "pminud",+ Self::MaximumSignedI32 => "pmaxsd",+ Self::MaximumUnsignedI32 => "pmaxud",+ Self::ShiftLeftI16 => "psllw",+ Self::ShiftRightUnsignedI16 => "psrlw",+ Self::ShiftLeftI32 => "pslld",+ Self::ShiftRightUnsignedI32 => "psrld",+ Self::ShiftLeftI64 => "psllq",+ Self::ShiftRightUnsignedI64 => "psrlq",+ Self::ShiftRightSignedI16 => "psraw",+ Self::ShiftRightSignedI32 => "psrad",+ Self::Shuffle8 => "pshufb",+ Self::NarrowSignedI16 => "packsswb",+ Self::NarrowUnsignedI16 => "packuswb",+ Self::NarrowSignedI32 => "packssdw",+ Self::NarrowUnsignedI32 => "packusdw",+ Self::InterleaveLowI8 => "punpcklbw",+ Self::InterleaveHighI8 => "punpckhbw",+ Self::InterleaveLowI16 => "punpcklwd",+ Self::InterleaveHighI16 => "punpckhwd",+ Self::InterleaveLowI32 => "punpckldq",+ Self::InterleaveHighI32 => "punpckhdq",+ Self::InterleaveLowI64 => "punpcklqdq",+ Self::InterleaveHighI64 => "punpckhqdq",+ Self::AddF32 => "addps",+ Self::SubtractF32 => "subps",+ Self::MultiplyF32 => "mulps",+ Self::DivideF32 => "divps",+ Self::MinimumF32 => "minps",+ Self::MaximumF32 => "maxps",+ Self::EqualF32 => "cmpeqps",+ Self::NotEqualF32 => "cmpneqps",+ Self::LessF32 => "cmpltps",+ Self::LessOrEqualF32 => "cmpleps",+ Self::UnorderedF32 => "cmpunordps",+ Self::SquareRootF32 => "sqrtps",+ Self::CeilF32 => "roundps",+ Self::FloorF32 => "roundps",+ Self::TruncF32 => "roundps",+ Self::NearestF32 => "roundps",+ Self::AddF64 => "addpd",+ Self::SubtractF64 => "subpd",+ Self::MultiplyF64 => "mulpd",+ Self::DivideF64 => "divpd",+ Self::MinimumF64 => "minpd",+ Self::MaximumF64 => "maxpd",+ Self::EqualF64 => "cmpeqpd",+ Self::NotEqualF64 => "cmpneqpd",+ Self::LessF64 => "cmpltpd",+ Self::LessOrEqualF64 => "cmplepd",+ Self::UnorderedF64 => "cmpunordpd",+ Self::SquareRootF64 => "sqrtpd",+ Self::CeilF64 => "roundpd",+ Self::FloorF64 => "roundpd",+ Self::TruncF64 => "roundpd",+ Self::NearestF64 => "roundpd",+ Self::AbsoluteI8 => "pabsb",+ Self::AbsoluteI16 => "pabsw",+ Self::AbsoluteI32 => "pabsd",+ Self::ExtendLowSignedI8 => "pmovsxbw",+ Self::ExtendLowUnsignedI8 => "pmovzxbw",+ Self::ExtendLowSignedI16 => "pmovsxwd",+ Self::ExtendLowUnsignedI16 => "pmovzxwd",+ Self::ExtendLowSignedI32 => "pmovsxdq",+ Self::ExtendLowUnsignedI32 => "pmovzxdq",+ Self::ConvertSignedI32ToF32 => "cvtdq2ps",+ Self::TruncateF32ToSignedI32 => "cvttps2dq",+ Self::ConvertLowSignedI32ToF64 => "cvtdq2pd",+ Self::TruncateF64ToSignedI32 => "cvttpd2dq",+ Self::PromoteLowF32 => "cvtps2pd",+ Self::DemoteF64 => "cvtpd2ps",+ Self::HighHalf => "pshufd",+ Self::BroadcastLowI32 => "pshufd",+ Self::Low64 => "movq",+ Self::High64 => "pextrq",+ Self::ByteMask => "pmovmskb",+ Self::SignMaskF32 => "movmskps",+ Self::SignMaskF64 => "movmskpd",+ }+ }++ /// The immediate operand the x86-64 instruction takes, if any.+ pub(crate) fn x86_64_immediate(self) -> Option<i64> {+ match self {+ Self::CeilF32 => Some(10),+ Self::FloorF32 => Some(9),+ Self::TruncF32 => Some(11),+ Self::NearestF32 => Some(8),+ Self::CeilF64 => Some(10),+ Self::FloorF64 => Some(9),+ Self::TruncF64 => Some(11),+ Self::NearestF64 => Some(8),+ Self::HighHalf => Some(238),+ Self::BroadcastLowI32 => Some(0),+ Self::High64 => Some(1),+ _ => None,+ }+ }+}+define_named_intrinsic_enum! {#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]pub(crate) enum AddressOperation {@@ -675,6 +1224,17 @@ pub(crate) enum ComparisonDomain {UnsignedInteger,}+/// A comparison of two floats with IEEE semantics: false if either is NaN, except for inequality, which is true.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]+pub(crate) enum OrderedFloatComparison {+ Equal,+ NotEqual,+ Less,+ LessOrEqual,+ Greater,+ GreaterOrEqual,+}+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]pub(crate) enum IntegerComparisonOperation {Equal,@@ -685,6 +1245,7 @@ pub(crate) enum IntegerComparisonOperation {},BitsSet,BitsClear,+ Float(OrderedFloatComparison),}intrinsic_names!(IntegerComparisonOperation {@@ -704,6 +1265,12 @@ intrinsic_names!(IntegerComparisonOperation {Self::Relational { relation: ComparisonRelation::GreaterOrEqual, domain: ComparisonDomain::UnsignedInteger } => "greater_than_or_equal_unsigned";Self::BitsSet => "bits_set";Self::BitsClear => "bits_clear";+ Self::Float(OrderedFloatComparison::Equal) => "float_equal";+ Self::Float(OrderedFloatComparison::NotEqual) => "float_not_equal";+ Self::Float(OrderedFloatComparison::Less) => "float_less";+ Self::Float(OrderedFloatComparison::LessOrEqual) => "float_less_or_equal";+ Self::Float(OrderedFloatComparison::Greater) => "float_greater";+ Self::Float(OrderedFloatComparison::GreaterOrEqual) => "float_greater_or_equal";});#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]@@ -843,6 +1410,7 @@ define_named_intrinsic_enum! {Dispatch => "dispatch" signatures [signature!([])];DispatchVariable => "dispatch_variable" signatures [signature!([In AnyGpr])];GotoHandler => "goto_handler" signatures [signature!([In AnyGpr])];+ DispatchSecondary => "dispatch_secondary" signatures [signature!([In AnyGpr, In AnyGpr])];Exit => "exit" signatures [signature!([])];JumpBytecode => "jump" signatures [signature!([In BytecodeOffset])];JumpLabel => "jmp" signatures [signature!([In Label])];@@ -853,7 +1421,12 @@ impl ControlOperation {pub(crate) fn writes_machine_state(self) -> bool {matches!(self,- Self::DispatchNext | Self::DispatchVariable | Self::GotoHandler | Self::Exit | Self::JumpBytecode+ Self::DispatchNext+ | Self::DispatchVariable+ | Self::GotoHandler+ | Self::DispatchSecondary+ | Self::Exit+ | Self::JumpBytecode)}@@ -884,6 +1457,8 @@ intrinsic_names!(MemoryOperation {Self::LoadCellPointer => "load_cell_ptr" signatures [signature!([Out AnyGpr, In Memory])];Self::LoadNonnullCellPointer => "load_nonnull_cell_ptr" signatures [signature!([Out AnyGpr, In Memory])];Self::Load { width: MemoryWidth::Float, signed: false } => "loadf32" signatures [signature!([Out F32, In Memory])];+ Self::Load { width: MemoryWidth::Double, signed: false } => "loadf64" signatures [signature!([Out F64, In Memory])];+ Self::Load { width: MemoryWidth::Vector, signed: false } => "load128" signatures [signature!([Out V128, In Memory])];Self::LoadPair(PairWidth::Word) => "load_pair32" signatures [signature!([In Memory, In Memory] -> (U32, U32)), signature!([Out AnyGpr, Out AnyGpr, In Memory, In Memory])];Self::LoadPair(PairWidth::DoubleWord) => "load_pair64" signatures [signature!([In Memory, In Memory] -> (U64, U64)), signature!([Out AnyGpr, Out AnyGpr, In Memory, In Memory])];Self::Store(MemoryWidth::Byte) => "store8" signatures [signature!([In Memory, In AnyGpr])];@@ -891,6 +1466,8 @@ intrinsic_names!(MemoryOperation {Self::Store(MemoryWidth::Word) => "store32" signatures [signature!([In Memory, In AnyGpr])];Self::Store(MemoryWidth::DoubleWord) => "store64" signatures [signature!([In Memory, In AnyGpr])];Self::Store(MemoryWidth::Float) => "storef32" signatures [signature!([In Memory, In F32])];+ Self::Store(MemoryWidth::Double) => "storef64" signatures [signature!([In Memory, In F64])];+ Self::Store(MemoryWidth::Vector) => "store128" signatures [signature!([In Memory, In V128])];Self::StorePair(PairWidth::Word) => "store_pair32" signatures [signature!([In Memory, In Memory, In AnyGpr, In AnyGpr])];Self::StorePair(PairWidth::DoubleWord) => "store_pair64" signatures [signature!([In Memory, In Memory, In AnyGpr, In AnyGpr])];});@@ -909,7 +1486,8 @@ impl MemoryOperation {MemoryWidth::Byte => 1,MemoryWidth::HalfWord => 2,MemoryWidth::Word | MemoryWidth::Float => 4,- MemoryWidth::DoubleWord => 8,+ MemoryWidth::DoubleWord | MemoryWidth::Double => 8,+ MemoryWidth::Vector => 16,}}@@ -985,7 +1563,10 @@ define_intrinsic_families! {IntegerComparison(IntegerComparisonOperation),LowLevel(LowLevelOperation),Memory(MemoryOperation),+ Numeric(NumericOperation),+ Atomic(AtomicOperation),Operand(OperandOperation),+ Vector(VectorOperation),Value(ValueOperation),}@@ -1006,6 +1587,7 @@ pub(crate) enum IntrinsicValueType {U16,U32,U64,+ V128,Value,ValueTag,Vm,@@ -1096,6 +1678,10 @@ impl Intrinsic {..IntrinsicEffects::PURE},Self::Memory(operation) => operation.effects(),+ Self::Atomic(_) => IntrinsicEffects {+ memory: ModRef::ReadWrite,+ ..IntrinsicEffects::PURE+ },Self::Operand(operation) => IntrinsicEffects {memory: match operation {OperandOperation::Decode => ModRef::None,@@ -1124,7 +1710,9 @@ impl Intrinsic {| Self::IntegerBinary(_)| Self::IntegerComparison(_)| Self::LowLevel(_)- | Self::Value(_) => IntrinsicEffects::PURE,+ | Self::Numeric(_)+ | Self::Value(_)+ | Self::Vector(_) => IntrinsicEffects::PURE,}}diff --git a/Libraries/LibJS/Flap/src/lib.rs b/Libraries/LibJS/Flap/src/lib.rsindex 8d1f029dc70..4f5570aef71 100644--- a/Libraries/LibJS/Flap/src/lib.rs+++ b/Libraries/LibJS/Flap/src/lib.rs@@ -30,6 +30,7 @@ pub(crate) mod identity;pub(crate) mod intrinsic;pub(crate) mod low_ir;pub mod metadata;+pub(crate) mod profile;pub mod runtime_interface;pub mod rust_bytecode;pub(crate) mod ssa;@@ -56,6 +57,7 @@ use types::BlockTemperature;pub use frontend::diagnostic::{SourceLocation, SourceSpan};pub use low_ir::Program as LowProgram;+pub use profile::Profile;pub use ssa::report::{FixedPointOptimizationReport, FunctionOptimizationReport, OptimizationRecord, OptimizationRemark,OptimizationRemarkKind, OptimizationReport, PassRunReport,@@ -95,6 +97,8 @@ pub struct CompileOptions {/// a `_profiling` suffix so both variants can be linked together. The/// plain variant compiles those functions to nothing.pub profiling: bool,+ /// The virtual machine the interpreter is compiled for.+ pub profile: Profile,}/// Controls optional diagnostics collected while optimizing a program.@@ -166,6 +170,7 @@ pub struct PreparedProgram {struct BytecodeMetadata {handler_layouts: Vec<BytecodeHandlerLayout>,dispatch_handlers: Vec<Option<HandlerId>>,+ dispatch: identity::DispatchLayout,}/// Textual assembly produced by a Flap backend.@@ -437,9 +442,20 @@ impl Compiler {.iter().map(|specialization| specialization.definition.clone()),);+ let encoding = self.options.profile.instruction_encoding();+ if self.options.profile == Profile::WebAssembly+ && self.options.target.architecture == Architecture::Aarch64+ && self.options.target.object_format == ObjectFormat::Coff+ {+ return Err(CompileError::new(+ CompileStage::Parse,+ None,+ "the WebAssembly profile is not implemented for AArch64 Windows",+ ));+ }// The interpreter dispatches on a single opcode byte, so a table beyond// 256 entries would have unreachable handlers.- if ops.len() > DISPATCH_TABLE_SIZE {+ if encoding == profile::InstructionEncoding::FixedLayout && ops.len() > DISPATCH_TABLE_SIZE {return Err(CompileError::new(CompileStage::Parse,None,@@ -483,6 +499,7 @@ impl Compiler {.enumerate().map(|(index, typed_handler)| {let mut function = ssa::lowering::lower_handler(typed_handler)?;+ function.exact_u32_arithmetic = self.options.profile == Profile::WebAssembly;ssa::inline::inline_calls(&mut function, &ssa_inline_functions)?;ssa::optimize::resolve_constants(&mut function, &constants);Ok(HandlerTemplate {@@ -516,27 +533,51 @@ impl Compiler {for handler in &mut handlers {ssa::optimize::resolve_layout_constants(&mut handler.function, &constants)?;+ check_profile_registers(&handler.function, self.options.profile)?;}let handler_ids = handlers.iter().map(|handler| (handler.name(), handler.id)).collect::<HashMap<_, _>>();- let dispatch_handlers = ops- .iter()- .map(|op| handler_ids.get(op.name.as_str()).copied())- .collect();+ let (dispatch_handlers, dispatch) = match encoding {+ profile::InstructionEncoding::FixedLayout => (+ ops.iter()+ .map(|op| handler_ids.get(op.name.as_str()).copied())+ .collect(),+ identity::DispatchLayout::default(),+ ),+ profile::InstructionEncoding::RawBytes => raw_bytes_dispatch(&ops, &handler_ids)?,+ };let ops_by_name = ops.iter().map(|op| (op.name.as_str(), op)).collect::<HashMap<_, _>>();let handler_layouts = handlers.iter().map(|handler| {- BytecodeHandlerLayout::new(+ let op = ops_by_name.get(handler.name()).copied();+ let mut layout = BytecodeHandlerLayout::new(handler.name(),&handler.function.parameter_names,&handler.function.parameter_types,- ops_by_name.get(handler.name()).copied(),+ op,)- .map_err(|message| CompileError::new(CompileStage::Semantic, Some(handler.name()), message))+ .map_err(|message| CompileError::new(CompileStage::Semantic, Some(handler.name()), message))?;+ if encoding == profile::InstructionEncoding::RawBytes {+ if !handler.function.parameter_names.is_empty() {+ return Err(CompileError::new(+ CompileStage::Semantic,+ Some(handler.name()),+ "a raw-bytes handler decodes its own immediates and cannot declare parameters",+ ));+ }+ // `dispatch_next` steps over a primary opcode byte. Prefixed handlers+ // decode the length of their sub-opcode themselves.+ layout.size = match op.and_then(|op| op.opcode) {+ Some(metadata::RawOpcode::Primary(_)) => Some(1),+ _ => None,+ };+ layout.slow_path = None;+ }+ Ok(layout)}).collect::<Result<Vec<_>, _>>()?;@@ -546,6 +587,7 @@ impl Compiler {bytecode: BytecodeMetadata {handler_layouts,dispatch_handlers,+ dispatch,},handlers,},@@ -566,6 +608,7 @@ impl Compiler {}}program.dispatch_handlers = prepared.bytecode.dispatch_handlers.clone();+ program.dispatch = prepared.bytecode.dispatch.clone();for template in &prepared.handlers {let mut handler = low_ir::lowering::lower_handler_with_constants(@@ -660,6 +703,117 @@ impl Compiler {}}+/// The number of entries of each secondary dispatch table. Sub-opcodes are+/// LEB128 values, so handlers bounds check them before dispatching.+pub(crate) const SECONDARY_DISPATCH_TABLE_SIZE: usize = 512;++/// Build the dispatch tables of a raw-bytes program from the `@opcode`+/// annotations of its handlers.+fn raw_bytes_dispatch(+ ops: &[metadata::InstructionDefinition],+ handler_ids: &HashMap<&str, HandlerId>,+) -> Result<(Vec<Option<HandlerId>>, identity::DispatchLayout), CompileError> {+ let mut primary = vec![None; DISPATCH_TABLE_SIZE];+ let mut dispatch = identity::DispatchLayout::default();+ let semantic_error = |op: &metadata::InstructionDefinition, message: String| {+ CompileError::new(CompileStage::Semantic, Some(&op.name), message)+ };+ for op in ops {+ let Some(&id) = handler_ids.get(op.name.as_str()) else {+ continue;+ };+ if op.is_fallback {+ if op.opcode.is_some() {+ return Err(semantic_error(+ op,+ "a @fallback handler cannot have an opcode".to_string(),+ ));+ }+ if dispatch.fallback.replace(id).is_some() {+ return Err(semantic_error(+ op,+ "a program can only have one @fallback handler".to_string(),+ ));+ }+ continue;+ }+ let slot = match op.opcode {+ None => {+ return Err(semantic_error(+ op,+ "a raw-bytes handler needs an @opcode or @fallback annotation".to_string(),+ ));+ }+ Some(metadata::RawOpcode::Primary(opcode)) => &mut primary[usize::from(opcode)],+ Some(metadata::RawOpcode::Prefixed { prefix, sub_opcode }) => {+ if !(0xfb..=0xff).contains(&prefix) {+ return Err(semantic_error(+ op,+ format!("secondary dispatch tables exist for the prefixes 0xfb to 0xff, not {prefix:#x}"),+ ));+ }+ if sub_opcode as usize >= SECONDARY_DISPATCH_TABLE_SIZE {+ return Err(semantic_error(+ op,+ format!("sub-opcode {sub_opcode:#x} exceeds the {SECONDARY_DISPATCH_TABLE_SIZE}-entry table"),+ ));+ }+ let index = match dispatch.secondary.iter().position(|table| table.prefix == prefix) {+ Some(index) => index,+ None => {+ dispatch.secondary.push(identity::SecondaryDispatchTable {+ prefix,+ handlers: vec![None; SECONDARY_DISPATCH_TABLE_SIZE],+ });+ dispatch.secondary.len() - 1+ }+ };+ &mut dispatch.secondary[index].handlers[sub_opcode as usize]+ }+ };+ if slot.replace(id).is_some() {+ return Err(semantic_error(+ op,+ "another handler already has this opcode".to_string(),+ ));+ }+ }+ dispatch.secondary.sort_by_key(|table| table.prefix);+ Ok((primary, dispatch))+}++/// Reject handlers that name interpreter registers their profile does not pin.+fn check_profile_registers(function: &ssa::Function, profile: Profile) -> Result<(), CompileError> {+ use types::{InterpreterRegister, RegisterReference};+ let check = |register: InterpreterRegister| {+ if profile.has_register(register) {+ return Ok(());+ }+ Err(CompileError::new(+ CompileStage::Semantic,+ Some(&function.name),+ format!(+ "the {profile:?} profile has no interpreter register '{}'",+ register.as_str()+ ),+ ))+ };+ for value in &function.values {+ if let ssa::ValueDefinition::Constant(ssa::Constant::MachineRegister(RegisterReference::Interpreter(+ register,+ ))) = &value.definition+ {+ check(*register)?;+ }+ }+ for instruction in &function.instructions {+ if let ssa::Operation::MachineAssign { destination, .. } = &instruction.operation {+ check(*destination)?;+ }+ }+ Ok(())+}+#[cfg(test)]mod tests {use super::*;@@ -693,6 +847,7 @@ const HEAP_REGION_OFFSET_MASK = 0x3FFFFFFFFFFhas_jscvt: false,enable_assertions: false,profiling: false,+ profile: Profile::JavaScript,})}diff --git a/Libraries/LibJS/Flap/src/low_ir/lowering.rs b/Libraries/LibJS/Flap/src/low_ir/lowering.rsindex c973993847f..107b028300f 100644--- a/Libraries/LibJS/Flap/src/low_ir/lowering.rs+++ b/Libraries/LibJS/Flap/src/low_ir/lowering.rs@@ -1530,6 +1530,9 @@ fn select_branch(function: &FunctionUses<'_>, condition: ValueId) -> Option<SeleComparisonDomain::Value => return None,},),+ IntegerComparisonOperation::Float(comparison) => {+ MachineOperation::Branch(BranchOperation::OrderedFloat(comparison))+ }IntegerComparisonOperation::BitsSet => {MachineOperation::branch_bits(MemoryWidth::DoubleWord, TestCondition::Set)}@@ -2069,11 +2072,7 @@ fn lower_edge_copies(let ty = copies[0].2.clone();let temporary = Operand::VirtualRegister(VirtualRegister::with_class(format!("ssa_edge_temporary_{}", *temporary_index),- if is_fpr(&ty) {- RegisterClass::FloatingPoint- } else {- RegisterClass::GeneralPurpose- },+ ty.register_class().unwrap_or(RegisterClass::GeneralPurpose),));*temporary_index += 1;output.push(copy_instruction(temporary.clone(), destination.clone(), &ty));@@ -2448,6 +2447,17 @@ fn lower_instruction({emit!(output; MachineOperation::Move(IntegerWidth::U64) => [destination.clone(), lhs.clone()];);emit!(output; MachineOperation::IntegerBinary { operation: IntegerBinaryOperation::Binary(BinaryOperation::And), width: IntegerWidth::U16 } => [destination.clone(), rhs.clone()];);+ } else if function.exact_u32_arithmetic+ && !operation.supports_narrow_result()+ && function.values[instruction.results[0].0].ty == Type::U32+ {+ let lhs = folded_32bit_operation_source(function, instruction.inputs[0])+ .map(|(_, source)| value_operand(function, source))+ .unwrap_or_else(|| Ok(lhs.clone()))?;+ let rhs = folded_32bit_operation_source(function, instruction.inputs[1])+ .map(|(_, source)| value_operand(function, source))+ .unwrap_or_else(|| Ok(rhs.clone()))?;+ emit!(output; narrow_integer_operation(machine_operation) => [destination.clone(), lhs, rhs];);} else if operation.supports_narrow_result()&& integer_result_can_stay_narrow(function, instruction.results[0]){@@ -2490,6 +2500,68 @@ fn lower_instruction(results.into_iter().chain(inputs).collect(),));}+ Operation::Intrinsic(Intrinsic::Atomic(operation))+ if operation.kind() == crate::intrinsic::AtomicOperationKind::Fence =>+ {+ output.push(machine_instruction(MachineOperation::Atomic(*operation), Vec::new()));+ }+ Operation::Intrinsic(Intrinsic::Atomic(operation))+ if operation.kind() == crate::intrinsic::AtomicOperationKind::Load =>+ {+ let [destination] = require_results(&results, operation.name())?;+ let [memory] = require_inputs(&inputs, operation.name())?;+ output.push(machine_instruction(+ MachineOperation::Atomic(*operation),+ vec![destination.clone(), memory.clone()],+ ));+ }+ Operation::Intrinsic(Intrinsic::Atomic(operation)) => {+ // The old value comes back in the register the operand was in.+ let [destination] = require_results(&results, operation.name())?;+ let (memory, operand, replacement) = match inputs.as_slice() {+ [memory, operand] => (memory.clone(), operand.clone(), None),+ [memory, operand, replacement] => (memory.clone(), operand.clone(), Some(replacement.clone())),+ _ => return Err(format!("'{}' expects a memory operand and values", operation.name())),+ };+ emit!(output; MachineOperation::Move(IntegerWidth::U64) => [destination.clone(), operand];);+ let mut operands = vec![destination.clone(), memory];+ operands.extend(replacement);+ output.push(machine_instruction(MachineOperation::Atomic(*operation), operands));+ }+ Operation::Intrinsic(Intrinsic::Vector(operation)) => {+ if operation.kind() == crate::intrinsic::VectorOperationKind::Binary {+ let [destination] = require_results(&results, operation.name())?;+ let [lhs, rhs] = require_inputs(&inputs, operation.name())?;+ emit!(output; MachineOperation::FloatMove => [destination.clone(), lhs.clone()];);+ emit!(output; MachineOperation::Vector(*operation) => [destination.clone(), rhs.clone()];);+ } else {+ output.push(machine_instruction(+ MachineOperation::Vector(*operation),+ results.into_iter().chain(inputs).collect(),+ ));+ }+ }+ Operation::Intrinsic(Intrinsic::Numeric(operation)) => {+ use crate::intrinsic::NumericOperation::*;+ match operation {+ RotateLeft32 | RotateRight32 | RotateLeft64 | RotateRight64 => {+ let [destination] = require_results(&results, operation.name())?;+ let [value, count] = require_inputs(&inputs, operation.name())?;+ emit!(output; MachineOperation::Move(IntegerWidth::U64) => [destination.clone(), value.clone()];);+ emit!(output; MachineOperation::Numeric(*operation) => [destination.clone(), count.clone()];);+ }+ AddFloat32 | SubtractFloat32 | MultiplyFloat32 | DivideFloat32 => {+ let [destination] = require_results(&results, operation.name())?;+ let [lhs, rhs] = require_inputs(&inputs, operation.name())?;+ emit!(output; MachineOperation::FloatMove => [destination.clone(), lhs.clone()];);+ emit!(output; MachineOperation::Numeric(*operation) => [destination.clone(), rhs.clone()];);+ }+ _ => output.push(machine_instruction(+ MachineOperation::Numeric(*operation),+ results.into_iter().chain(inputs).collect(),+ )),+ }+ }Operation::Intrinsic(Intrinsic::Operand(OperandOperation::LoadPair)) => {let [lhs, rhs] = require_results(&results, "load_operand_pair")?;let [Operand::BytecodeField(lhs_field), Operand::BytecodeField(rhs_field)] = inputs.as_slice() else {@@ -3561,8 +3633,12 @@ fn operand_load_index(instruction: InstructionId, result_index: usize) -> OperanOperand::VirtualRegister(format!("ssa_operand_load_{}_{}_index", instruction.0, result_index).into())}+/// Whether values of `ty` live in floating-point registers, which vectors do too.fn is_fpr(ty: &Type) -> bool {- ty.register_class() == Some(RegisterClass::FloatingPoint)+ matches!(+ ty.register_class(),+ Some(RegisterClass::FloatingPoint | RegisterClass::Vector)+ )}fn layout_operand(constants: &LayoutConstants, known: KnownLayoutConstant) -> Result<Operand, String> {diff --git a/Libraries/LibJS/Flap/src/low_ir/mod.rs b/Libraries/LibJS/Flap/src/low_ir/mod.rsindex ec28543f446..8898cbe0e68 100644--- a/Libraries/LibJS/Flap/src/low_ir/mod.rs+++ b/Libraries/LibJS/Flap/src/low_ir/mod.rs@@ -87,6 +87,17 @@ impl VirtualRegister {}}+ /// A register created after interning, with the next free index of its function.+ pub(crate) fn interned(name: impl Into<String>, function: HandlerId, index: u32, class: RegisterClass) -> Self {+ Self {+ id: Some(VirtualRegisterId { function, index }),+ name: name.into().into(),+ class,+ origin: VirtualRegisterOrigin::Named,+ identity_hash: 0,+ }+ }+pub(crate) fn ssa(function: HandlerId, index: u32, value: usize, class: RegisterClass) -> Self {Self {id: Some(VirtualRegisterId { function, index }),@@ -544,6 +555,7 @@ pub struct Program {pub(crate) runtime: RuntimeConstants,pub(crate) handlers: Vec<Handler>,pub(crate) dispatch_handlers: Vec<Option<HandlerId>>,+ pub(crate) dispatch: crate::identity::DispatchLayout,}impl Program {@@ -552,6 +564,7 @@ impl Program {runtime: RuntimeConstants::default(),handlers: Vec::new(),dispatch_handlers: Vec::new(),+ dispatch: Default::default(),}}}diff --git a/Libraries/LibJS/Flap/src/main.rs b/Libraries/LibJS/Flap/src/main.rsindex 814986d6df3..306c787a372 100644--- a/Libraries/LibJS/Flap/src/main.rs+++ b/Libraries/LibJS/Flap/src/main.rs@@ -5,12 +5,12 @@*/use flapc::{- Architecture, CompilationUnit, CompileOptions, Compiler, ObjectFormat, OptimizationReportOptions, SourceInput,- Target,+ Architecture, CompilationUnit, CompileOptions, Compiler, ObjectFormat, OptimizationReportOptions, Profile,+ SourceInput, Target,};use std::fs;-const USAGE: &str = "Usage: flapc --arch x86_64 --input <file.flap> --output <file.S> [--constants <file>] [--optimization-report <file>] [--dump-changed-ir]";+const USAGE: &str = "Usage: flapc --arch x86_64 --input <file.flap> --output <file.S> [--profile js|wasm] [--constants <file>] [--optimization-report <file>] [--dump-changed-ir]";struct CommandLine {options: CompileOptions,@@ -81,6 +81,7 @@ fn parse_command_line() -> Result<CommandLine, String> {let mut optimization_report_path = None;let mut dump_changed_ir = false;let mut profiling = false;+ let mut profile = Profile::JavaScript;while let Some(argument) = args.next() {match argument.as_str() {@@ -103,6 +104,13 @@ fn parse_command_line() -> Result<CommandLine, String> {other => return Err(format!("Unknown object format: {other}")),};}+ "--profile" => {+ profile = match required_value(&mut args, "--profile")?.as_str() {+ "js" => Profile::JavaScript,+ "wasm" => Profile::WebAssembly,+ other => return Err(format!("Unknown profile: {other}")),+ };+ }"--input" => input_path = Some(required_value(&mut args, "--input")?),"--output" => output_path = Some(required_value(&mut args, "--output")?),"--constants" => constants_path = Some(required_value(&mut args, "--constants")?),@@ -126,6 +134,7 @@ fn parse_command_line() -> Result<CommandLine, String> {has_jscvt,enable_assertions,profiling,+ profile,},input_path: input_path.ok_or(USAGE)?,output_path: output_path.ok_or(USAGE)?,diff --git a/Libraries/LibJS/Flap/src/metadata.rs b/Libraries/LibJS/Flap/src/metadata.rsindex 322e5294f1b..61f619229c5 100644--- a/Libraries/LibJS/Flap/src/metadata.rs+++ b/Libraries/LibJS/Flap/src/metadata.rs@@ -208,6 +208,19 @@ pub struct InstructionDefinition {pub falls_through: bool,pub layout: OpLayout,pub array: Option<ArrayLayout>,+ /// The opcode a raw-bytes instruction dispatches on (`@opcode(...)`).+ pub opcode: Option<RawOpcode>,+ /// The handler runs every opcode that has no handler of its own+ /// (`@fallback`).+ pub is_fallback: bool,+}++/// The encoding of a raw-bytes instruction: a primary opcode byte, or a prefix+/// byte followed by a LEB128 sub-opcode.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]+pub enum RawOpcode {+ Primary(u8),+ Prefixed { prefix: u8, sub_opcode: u32 },}#[derive(Debug, Clone)]@@ -352,6 +365,8 @@ pub fn parse_flap_metadata(source_name: &str, content: &str) -> Result<Vec<Instr.split_whitespace().any(|token| token == annotation)};+ let opcode = parse_opcode_annotation(&declaration[close + 1..])+ .map_err(|message| ParseError::new(source_name, start_line, 1, format!("handler '{name}': {message}")))?;let mut op = InstructionDefinition {name: name.to_string(),parent: "Instruction".to_string(),@@ -360,6 +375,8 @@ pub fn parse_flap_metadata(source_name: &str, content: &str) -> Result<Vec<Instrfalls_through: has_annotation("@fallthrough"),layout: OpLayout::default(),array: None,+ opcode,+ is_fallback: has_annotation("@fallback"),};if op.falls_through && !op.is_terminator {return Err(ParseError::new(@@ -376,6 +393,41 @@ pub fn parse_flap_metadata(source_name: &str, content: &str) -> Result<Vec<InstrOk(ops)}+fn parse_integer_literal(text: &str) -> Option<u64> {+ let text = text.trim();+ if let Some(hexadecimal) = text.strip_prefix("0x").or_else(|| text.strip_prefix("0X")) {+ return u64::from_str_radix(hexadecimal, 16).ok();+ }+ text.parse().ok()+}++/// Parse the `@opcode(primary)` or `@opcode(prefix, sub_opcode)` annotation+/// that follows a handler's parameter list, if it has one.+fn parse_opcode_annotation(annotations: &str) -> Result<Option<RawOpcode>, String> {+ let Some(start) = annotations.find("@opcode") else {+ return Ok(None);+ };+ let rest = annotations[start + "@opcode".len()..].trim_start();+ let arguments = rest+ .strip_prefix('(')+ .and_then(|rest| rest.split_once(')'))+ .map(|(arguments, _)| arguments)+ .ok_or("malformed @opcode annotation")?;+ let values = arguments+ .split(',')+ .map(|argument| parse_integer_literal(argument).ok_or(format!("invalid opcode '{}'", argument.trim())))+ .collect::<Result<Vec<_>, _>>()?;+ let byte = |value: u64| u8::try_from(value).map_err(|_| format!("opcode {value:#x} does not fit in a byte"));+ match values.as_slice() {+ [primary] => Ok(Some(RawOpcode::Primary(byte(*primary)?))),+ [prefix, sub_opcode] => Ok(Some(RawOpcode::Prefixed {+ prefix: byte(*prefix)?,+ sub_opcode: u32::try_from(*sub_opcode).map_err(|_| format!("sub-opcode {sub_opcode:#x} is too large"))?,+ })),+ _ => Err("@opcode takes an opcode byte, or a prefix byte and a sub-opcode".to_string()),+ }+}+fn find_matching_parenthesis(source: &str, open: usize) -> Option<usize> {let mut depth = 0i32;for (offset, character) in source[open..].char_indices() {@@ -878,6 +930,8 @@ pub fn derive_specialized_instructions(falls_through: ops_by_name[last_component.bytecode.as_str()].falls_through,layout: OpLayout::default(),array: None,+ opcode: None,+ is_fallback: false,};validate_op(&mut definition)?;derived.push(SpecializedInstruction { definition, components });diff --git a/Libraries/LibJS/Flap/src/profile.rs b/Libraries/LibJS/Flap/src/profile.rsnew file mode 100644index 00000000000..a6b7e7b8e8f--- /dev/null+++ b/Libraries/LibJS/Flap/src/profile.rs@@ -0,0 +1,144 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Descriptions of the virtual machines Flap compiles interpreters for.+//!+//! The compiler pipeline is shared, but each virtual machine decides how its+//! instructions are encoded, which interpreter state its handlers keep pinned+//! in registers, which runtime constants the generated code needs, how the+//! entry, exit, and fallback stubs talk to the runtime, and what the generated+//! symbols are called.++use crate::Architecture;+use crate::frontend::layout::KnownLayoutConstant;+use crate::types::InterpreterRegister;++/// The virtual machine an interpreter is compiled for.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]+pub enum Profile {+ /// The LibJS bytecode interpreter: fixed-layout instructions whose+ /// operands index NaN-boxed values, entered with a `VM*`.+ JavaScript,+ /// The in-place WebAssembly interpreter: handlers run directly on a+ /// function's binary code, decode their own immediates, and keep the+ /// operand stack and locals in 8-byte machine stack slots.+ WebAssembly,+}++/// How the bytes of one instruction are laid out.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum InstructionEncoding {+ /// Every handler parameter is a field at a fixed offset of a fixed-size+ /// instruction record, and `dispatch_next` advances by the record size.+ FixedLayout,+ /// Instructions are raw bytes that start with an opcode byte. Handlers+ /// take no parameters and decode their own immediates, so `dispatch_next`+ /// only steps over the opcode byte, and handlers with immediates compute+ /// the next instruction themselves.+ RawBytes,+}++/// How the pinned program counter addresses the current instruction.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum ProgramCounterAddressing {+ /// `pc` is a 32-bit offset from the program base `pb`.+ BaseRelative,+ /// `ip` is a pointer to the current instruction.+ Absolute,+}++impl Profile {+ /// The name every global symbol of the generated interpreter starts with.+ pub fn symbol_prefix(self) -> &'static str {+ match self {+ Self::JavaScript => "js_interpreter",+ Self::WebAssembly => "wasm_interpreter",+ }+ }++ pub(crate) fn instruction_encoding(self) -> InstructionEncoding {+ match self {+ Self::JavaScript => InstructionEncoding::FixedLayout,+ Self::WebAssembly => InstructionEncoding::RawBytes,+ }+ }++ pub(crate) fn program_counter_addressing(self) -> ProgramCounterAddressing {+ match self {+ Self::JavaScript => ProgramCounterAddressing::BaseRelative,+ Self::WebAssembly => ProgramCounterAddressing::Absolute,+ }+ }++ /// The pinned interpreter registers handlers of this profile may name.+ pub(crate) fn registers(self) -> &'static [InterpreterRegister] {+ use InterpreterRegister::*;+ match self {+ Self::JavaScript => &[+ ProgramCounter,+ ProgramBase,+ Values,+ ExecutionContext,+ DispatchTable,+ HeapRegionBase,+ StackPointer,+ FramePointer,+ ],+ Self::WebAssembly => &[+ InstructionPointer,+ SideTablePointer,+ ValueStackPointer,+ MemoryBase,+ DispatchTable,+ StackPointer,+ FramePointer,+ ],+ }+ }++ pub(crate) fn has_register(self, register: InterpreterRegister) -> bool {+ self.registers().contains(®ister)+ }++ /// The layout constants the generated entry, exit, and dispatch code of+ /// this profile cannot be emitted without.+ pub(crate) fn required_runtime_constants(self, architecture: Architecture) -> &'static [KnownLayoutConstant] {+ use KnownLayoutConstant::*;+ match (self, architecture) {+ (Self::JavaScript, Architecture::X86_64) => &[+ SlowPathContinuationBit,+ VmRunningExecutionContext,+ VmBreakpointController,+ VmHeapRegionBase,+ ExecutionContextExecutable,+ ExecutionContextProgramCounter,+ ExecutableBytecodeData,+ ExecutableDispatchTableIndex,+ VmDispatchTables,+ DispatchTableIndexMask,+ SizeOfExecutionContext,+ CanonicalNanBits,+ ],+ (Self::JavaScript, Architecture::Aarch64) => &[+ Int32Tag,+ BooleanTag,+ SlowPathContinuationBit,+ VmRunningExecutionContext,+ VmBreakpointController,+ VmHeapRegionBase,+ ExecutionContextExecutable,+ ExecutionContextProgramCounter,+ ExecutableBytecodeData,+ ExecutableDispatchTableIndex,+ VmDispatchTables,+ DispatchTableIndexMask,+ SizeOfExecutionContext,+ CanonicalNanBits,+ ],+ (Self::WebAssembly, _) => &[],+ }+ }+}diff --git a/Libraries/LibJS/Flap/src/ssa/lowering.rs b/Libraries/LibJS/Flap/src/ssa/lowering.rsindex 58dfcdc53aa..71cadbddfd6 100644--- a/Libraries/LibJS/Flap/src/ssa/lowering.rs+++ b/Libraries/LibJS/Flap/src/ssa/lowering.rs@@ -1397,6 +1397,11 @@ impl Lowerer<'_> {vec![lhs, rhs],)}+ Condition::FloatComparison { lhs, rhs, comparison } => {+ let lhs = self.lower_value(lhs)?;+ let rhs = self.lower_value(rhs)?;+ self.append_integer_comparison(IntegerComparisonOperation::Float(*comparison), vec![lhs, rhs])+ }Condition::BitTest { value, mask, set } => {let value = self.lower_value(value)?;let mask = self.lower_value(mask)?;diff --git a/Libraries/LibJS/Flap/src/ssa/memory_optimize.rs b/Libraries/LibJS/Flap/src/ssa/memory_optimize.rsindex c5d080f9351..a9f1ba322e5 100644--- a/Libraries/LibJS/Flap/src/ssa/memory_optimize.rs+++ b/Libraries/LibJS/Flap/src/ssa/memory_optimize.rs@@ -85,6 +85,9 @@ pub(super) fn run(function: &mut Function, analyses: &mut AnalysisManager) -> bo// NB: A load that traps carries an assertion about what it loaded, so it can only reuse// a load that made the same assertion. Reusing a plain load would drop the check.let traps = function.instructions[instruction_id.0].effects.may_trap;+ // OPTIMIZATION: A cold block reloads what a hot block already loaded instead of reusing it. Reusing the+ // value would keep it live through the hot path up to the cold branch, which costs a register there.+ let in_cold_block = function.blocks[block.0].layout == super::BlockLayout::Cold;let key = location_key(function, location);let forwarded_load =available_loads@@ -94,6 +97,9 @@ pub(super) fn run(function: &mut Function, analyses: &mut AnalysisManager) -> bo.rev().find_map(|(load, loaded_location, value)| {((!traps || function.instructions[load.0].effects.may_trap)+ && (!in_cold_block+ || function.blocks[analysis.instruction_layout.block(*load).0].layout+ == super::BlockLayout::Cold)&& dominates_instruction(&analysis, *load, *instruction_id)&& alias(function, loaded_location, location) == AliasResult::Must&& function.values[value.0].ty == *result_typediff --git a/Libraries/LibJS/Flap/src/ssa/mod.rs b/Libraries/LibJS/Flap/src/ssa/mod.rsindex ec22b749e31..681bf4ba43b 100644--- a/Libraries/LibJS/Flap/src/ssa/mod.rs+++ b/Libraries/LibJS/Flap/src/ssa/mod.rs@@ -401,6 +401,9 @@ pub(crate) struct Function {pub(crate) instructions: Vec<Instruction>,pub(crate) values: Vec<Value>,pub(crate) entry: BlockId,+ /// Whether u32 additions, subtractions, and multiplications wrap to 32 bits in their results, as the+ /// WebAssembly profile requires. Without it, only their low 32 bits are meaningful.+ pub(crate) exact_u32_arithmetic: bool,constant_values: HashMap<(Type, Constant), ValueId>,}@@ -434,6 +437,7 @@ impl Function {instructions: Vec::new(),values,entry: BlockId(0),+ exact_u32_arithmetic: false,constant_values: HashMap::default(),}}diff --git a/Libraries/LibJS/Flap/src/ssa/optimize.rs b/Libraries/LibJS/Flap/src/ssa/optimize.rsindex 360ab38a42a..62529199619 100644--- a/Libraries/LibJS/Flap/src/ssa/optimize.rs+++ b/Libraries/LibJS/Flap/src/ssa/optimize.rs@@ -1167,11 +1167,15 @@ fn instruction_is_globally_movable(instruction: &super::Instruction) -> bool {| Operation::Intrinsic(Intrinsic::FloatingPoint(_))| Operation::Intrinsic(Intrinsic::IntegerBinary(_))| Operation::Intrinsic(Intrinsic::IntegerComparison(_))- | Operation::Intrinsic(Intrinsic::Operand(_)) => true,+ | Operation::Intrinsic(Intrinsic::Operand(_))+ | Operation::Intrinsic(Intrinsic::Vector(_)) => true,Operation::Intrinsic(Intrinsic::Value(operation)) => {*operation != ValueOperation::Reuse && !operation.is_rematerialized()}- Operation::Intrinsic(Intrinsic::Aggregate(_))+ // Divisions must stay behind the checks that guard them against trapping.+ Operation::Intrinsic(Intrinsic::Numeric(_))+ | Operation::Intrinsic(Intrinsic::Atomic(_))+ | Operation::Intrinsic(Intrinsic::Aggregate(_))| Operation::Intrinsic(Intrinsic::Assertion(_))| Operation::Intrinsic(Intrinsic::Branch(_))| Operation::Intrinsic(Intrinsic::Bytecode(_))diff --git a/Libraries/LibJS/Flap/src/target/aarch64.rs b/Libraries/LibJS/Flap/src/target/aarch64.rsindex 5164d806049..55a530cc069 100644--- a/Libraries/LibJS/Flap/src/target/aarch64.rs+++ b/Libraries/LibJS/Flap/src/target/aarch64.rs@@ -14,7 +14,7 @@ use super::description::{};use super::emitter::{SimpleInstruction, SimpleOperand, emit_file_header, emit_handlers, emit_label, emit_program,- emit_simple_instruction, integer, native, pair, simple, single, w, word,+ emit_simple_instruction, integer, native, pair, quad, simple, single, vector, w, word,};use super::ir::{MachineCondition as Condition, MachineFunction as Handler, MachineInstruction, MachineMemoryAddress,@@ -28,6 +28,7 @@ use crate::{Architecture, CompileOptions, ObjectFormat};use std::fmt::Write;pub(crate) mod finalize;+mod wasm;#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]pub(crate) enum AddSubtractOperation {@@ -102,7 +103,7 @@ impl AddressIndexShift {match (width, scale) {(MemoryWidth::HalfWord, 2) => Some(Self::One),(MemoryWidth::Word | MemoryWidth::Float, 4) => Some(Self::Two),- (MemoryWidth::DoubleWord, 8) => Some(Self::Three),+ (MemoryWidth::DoubleWord | MemoryWidth::Double, 8) => Some(Self::Three),_ => None,}}@@ -117,6 +118,40 @@ pub(crate) enum MemoryAddressing {ShiftedRegister(AddressIndexShift),}+/// One operand of a generic instruction, which the WebAssembly profile's numeric, vector, and atomic operations+/// expand into. Registers and immediates take the instruction's operands in order.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]+pub(crate) enum Slot {+ /// A register's number between a prefix and a suffix, like `w` and `` for w0, or `v` and `.4s` for v0.4s.+ Register(&'static str, &'static str),+ Immediate,+ HexImmediate,+ Literal(&'static str),+}++fn generic_instruction(mnemonic: &'static str, slots: [Option<Slot>; 4]) -> SimpleInstruction {+ let mut operands = [None; 4];+ let mut index = 0;+ for (operand, slot) in operands.iter_mut().zip(slots) {+ *operand = slot.map(|slot| match slot {+ Slot::Register(prefix, suffix) => {+ index += 1;+ SimpleOperand::Register(index - 1, super::emitter::SimpleRegister::Numbered(prefix, suffix))+ }+ Slot::Immediate => {+ index += 1;+ SimpleOperand::HashImmediate(index - 1, false)+ }+ Slot::HexImmediate => {+ index += 1;+ SimpleOperand::HashImmediate(index - 1, true)+ }+ Slot::Literal(text) => SimpleOperand::Literal(text),+ });+ }+ (mnemonic, operands)+}+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]pub(crate) enum ConditionFlags {Equal,@@ -144,7 +179,11 @@ pub(crate) enum FloatConversion {fn load_instruction(width: MemoryWidth, signed: bool, addressing: MemoryAddressing) -> SimpleInstruction {let mnemonic = match (width, signed, addressing) {(- MemoryWidth::DoubleWord | MemoryWidth::Float | MemoryWidth::Word,+ MemoryWidth::DoubleWord+ | MemoryWidth::Float+ | MemoryWidth::Double+ | MemoryWidth::Vector+ | MemoryWidth::Word,false,MemoryAddressing::UnscaledImmediate,) => "ldur",@@ -153,19 +192,29 @@ fn load_instruction(width: MemoryWidth, signed: bool, addressing: MemoryAddressi(MemoryWidth::HalfWord, true, MemoryAddressing::UnscaledImmediate) => "ldursh",(MemoryWidth::Byte, false, MemoryAddressing::UnscaledImmediate) => "ldurb",(MemoryWidth::Byte, true, MemoryAddressing::UnscaledImmediate) => "ldursb",- (MemoryWidth::DoubleWord | MemoryWidth::Float | MemoryWidth::Word, false, _) => "ldr",+ (+ MemoryWidth::DoubleWord+ | MemoryWidth::Float+ | MemoryWidth::Double+ | MemoryWidth::Vector+ | MemoryWidth::Word,+ false,+ _,+ ) => "ldr",(MemoryWidth::Word, true, _) => "ldrsw",(MemoryWidth::HalfWord, false, _) => "ldrh",(MemoryWidth::HalfWord, true, _) => "ldrsh",(MemoryWidth::Byte, false, _) => "ldrb",(MemoryWidth::Byte, true, _) => "ldrsb",- (MemoryWidth::DoubleWord | MemoryWidth::Float, true, _) => {+ (MemoryWidth::DoubleWord | MemoryWidth::Float | MemoryWidth::Double | MemoryWidth::Vector, true, _) => {unreachable!("unsupported finalized AArch64 signed load")}};let destination = match width {MemoryWidth::DoubleWord => native(0),MemoryWidth::Float => single(0),+ MemoryWidth::Double => native(0),+ MemoryWidth::Vector => quad(0),MemoryWidth::Word if signed => native(0),MemoryWidth::Word | MemoryWidth::HalfWord | MemoryWidth::Byte => word(0),};@@ -174,18 +223,32 @@ fn load_instruction(width: MemoryWidth, signed: bool, addressing: MemoryAddressifn store_instruction(width: MemoryWidth, addressing: MemoryAddressing) -> SimpleInstruction {let mnemonic = match (width, addressing) {- (MemoryWidth::DoubleWord | MemoryWidth::Float | MemoryWidth::Word, MemoryAddressing::UnscaledImmediate) => {- "stur"- }+ (+ MemoryWidth::DoubleWord+ | MemoryWidth::Float+ | MemoryWidth::Double+ | MemoryWidth::Vector+ | MemoryWidth::Word,+ MemoryAddressing::UnscaledImmediate,+ ) => "stur",(MemoryWidth::HalfWord, MemoryAddressing::UnscaledImmediate) => "sturh",(MemoryWidth::Byte, MemoryAddressing::UnscaledImmediate) => "sturb",- (MemoryWidth::DoubleWord | MemoryWidth::Float | MemoryWidth::Word, _) => "str",+ (+ MemoryWidth::DoubleWord+ | MemoryWidth::Float+ | MemoryWidth::Double+ | MemoryWidth::Vector+ | MemoryWidth::Word,+ _,+ ) => "str",(MemoryWidth::HalfWord, _) => "strh",(MemoryWidth::Byte, _) => "strb",};let source = match width {MemoryWidth::DoubleWord => native(1),MemoryWidth::Float => single(1),+ MemoryWidth::Double => native(1),+ MemoryWidth::Vector => quad(1),MemoryWidth::Word | MemoryWidth::HalfWord | MemoryWidth::Byte => word(1),};simple!(mnemonic; source, SimpleOperand::Resolved(0, ""))@@ -242,19 +305,19 @@ define_machine_opcodes! {[AdvanceInstructionPointer] => Self::AdvanceInstructionPointer => [[R]] printing simple!("add"; SimpleOperand::Literal("x21"), SimpleOperand::Literal("x21"), word(0), SimpleOperand::Literal("uxtw"));[Load { width: MemoryWidth, signed: bool, addressing: MemoryAddressing }] => opcode @ Self::Load { width, signed, addressing } => {match opcode {- Self::Load { width: MemoryWidth::Float, .. } => operands_match(operands, &[FR, A]),+ Self::Load { width: MemoryWidth::Float | MemoryWidth::Double | MemoryWidth::Vector, .. } => operands_match(operands, &[FR, A]),_ => operands_match(operands, &[R, A]),}} encoding {let Self::Load { width, signed, addressing } = opcode else { unreachable!() };- (!signed || !matches!(width, MemoryWidth::DoubleWord | MemoryWidth::Float))+ (!signed || !matches!(width, MemoryWidth::DoubleWord | MemoryWidth::Float | MemoryWidth::Double | MemoryWidth::Vector))&& address(1).is_some_and(|address| {memory_address_is_encodable(width, addressing, address)})} printing load_instruction(width, signed, addressing);[Store { width: MemoryWidth, addressing: MemoryAddressing }] => opcode @ Self::Store { width, addressing } => {match opcode {- Self::Store { width: MemoryWidth::Float, .. } => operands_match(operands, &[A, FR]),+ Self::Store { width: MemoryWidth::Float | MemoryWidth::Double | MemoryWidth::Vector, .. } => operands_match(operands, &[A, FR]),_ => operands_match(operands, &[A, R]),}} encoding {@@ -317,6 +380,7 @@ define_machine_opcodes! {[BranchCondition(Condition)] => Self::BranchCondition(condition) => [[L]] printing simple!(condition.aarch64_mnemonic(); SimpleOperand::Label(0));[Break] => Self::Break => [[]] printing simple!("brk"; SimpleOperand::Literal("#0"));[MoveFloatBits64] => Self::MoveFloatBits64 => [[AR, AR]] printing simple!("fmov"; native(0), native(1));+ [MoveVector] => Self::MoveVector => [[FR, FR]] printing simple!("mov"; vector(0, "16b"), vector(1, "16b"));[CompareDouble] => Self::CompareDouble => [[FR, FR]] printing simple!("fcmp"; native(0), native(1));[FloatArithmetic(FloatBinaryOperation)] => Self::FloatArithmetic(operation) => [[FR, FR, FR]] printing simple!(match operation {FloatBinaryOperation::Add => "fadd",@@ -404,6 +468,7 @@ define_machine_opcodes! {[MultiplySubtract64] => Self::MultiplySubtract64 => [[R, R, R, R]] printing simple!("msub"; native(0), native(1), native(2), native(3));[SignedDivide32] => Self::SignedDivide32 => [[R, R, R]] printing simple!("sdiv"; word(0), word(1), word(2));[MultiplySubtract32] => Self::MultiplySubtract32 => [[R, R, R, R]] printing simple!("msub"; word(0), word(1), word(2), word(3));+ [Generic(&'static str, [Option<Slot>; 4])] => Self::Generic(mnemonic, slots) => any printing generic_instruction(mnemonic, slots);}pub(crate) struct ImmediateMove {@@ -514,7 +579,8 @@ pub(crate) fn unsigned_memory_offset_fits(width: MemoryWidth, offset: i64) -> boMemoryWidth::Byte => (0..=4095).contains(&offset),MemoryWidth::HalfWord => (0..=8190).contains(&offset) && offset % 2 == 0,MemoryWidth::Word | MemoryWidth::Float => (0..=16380).contains(&offset) && offset % 4 == 0,- MemoryWidth::DoubleWord => (0..=32760).contains(&offset) && offset % 8 == 0,+ MemoryWidth::DoubleWord | MemoryWidth::Double => (0..=32760).contains(&offset) && offset % 8 == 0,+ MemoryWidth::Vector => (0..=65520).contains(&offset) && offset % 16 == 0,}}@@ -624,7 +690,13 @@ impl Opcode {}_ => false,};- if operands.iter().any(is_floating_point) {+ let is_vector = |operand: &super::ir::Operand| {+ matches!(operand, super::ir::Operand::VirtualRegister(register)+ if register.class() == crate::types::RegisterClass::Vector)+ };+ if operands.iter().any(is_vector) {+ Self::MoveVector+ } else if operands.iter().any(is_floating_point) {Self::MoveFloatBits64} else {Self::MoveRegister(IntegerWidth::U64)@@ -769,6 +841,29 @@ pub(crate) fn generate(program: &Program, options: &CompileOptions) -> String {emit_file_header(&mut out, "//", false);+ if program.profile == crate::Profile::WebAssembly {+ // The atomic operations use the large system extensions, which the runtime checks for.+ w!(out, ".arch_extension lse");+ return emit_program(+ out,+ program,+ " ",+ |out| generate_wasm_entry_point(out, program, object_format),+ |_| {},+ |out| {+ emit_handlers(+ out,+ program,+ "//",+ |out, _| emit_handler_alignment(out, object_format),+ emit_instruction,+ |_| {},+ )+ },+ |out| generate_wasm_exit_point(out, object_format),+ );+ }+emit_program(out,program,@@ -819,6 +914,83 @@ fn generate_exit_point(out: &mut String, fmt: ObjectFormat) {w!(out);}+/// The entry point of the WebAssembly interpreter:+/// `void wasm_interpreter(u8 const* ip, u64 argument)`.+///+/// It saves the callee-saved registers in a frame whose base becomes `fp` (x29), loads `ip` (x21) and the dispatch+/// table (x19), hands `argument` to the first handler in `vsp` (x27), and dispatches. Handlers build the frames of+/// WebAssembly functions below it and must restore `fp` to this frame before they `exit`. If the runtime has a spill+/// area, the frame keeps it free above the stack pointer, for the first handler to spill to before it moves the+/// stack pointer.+fn generate_wasm_entry_point(out: &mut String, program: &Program, fmt: ObjectFormat) {+ let frame_size = frame_size_for_format(fmt);+ w!(out, " stp x29, x30, [sp, #-{frame_size}]!");+ if matches!(fmt, ObjectFormat::Coff) {+ w!(out, " .seh_save_fplr_x {frame_size}");+ } else {+ w!(out, " .cfi_def_cfa_offset {frame_size}");+ w!(out, " .cfi_offset x29, {}", cfi_offset(fmt, 0));+ w!(out, " .cfi_offset x30, {}", cfi_offset(fmt, 8));+ }+ w!(out, " mov x29, sp");+ if matches!(fmt, ObjectFormat::Coff) {+ w!(out, " .seh_set_fp");+ } else {+ w!(out, " .cfi_def_cfa_register x29");+ }+ emit_saved_register_pairs(out, fmt, FrameAction::Save);+ w!(out, " str d8, [sp, #96]");+ if matches!(fmt, ObjectFormat::Coff) {+ w!(out, " .seh_save_freg d8, 96");+ w!(out, " .seh_endprologue");+ } else {+ w!(out, " .cfi_offset d8, {}", cfi_offset(fmt, 96));+ }+ let spill_area = match (+ runtime(program).get(KnownLayoutConstant::SpillAreaOffset),+ runtime(program).get(KnownLayoutConstant::SpillAreaSlots),+ ) {+ (Some(offset), Some(slots)) => (offset + slots * 8 + 15) & !15,+ _ => 0,+ };+ if spill_area != 0 {+ emit_add_imm(out, "sp", "sp", -spill_area);+ }+ w!(out, " mov x21, x0 // ip");+ w!(out, " mov x27, x1 // vsp = argument");+ emit_symbol_addr(out, "x19", "asm_dispatch_table", fmt);+ w!(out, " ldrb w9, [x21]");+ emit_dispatch_tail(out);+ w!(out);+}++fn generate_wasm_exit_point(out: &mut String, fmt: ObjectFormat) {+ let frame_size = frame_size_for_format(fmt);+ w!(out, ".Lexit:");+ if matches!(fmt, ObjectFormat::Coff) {+ w!(out, " .seh_startepilogue");+ }+ w!(out, " mov sp, x29");+ emit_saved_register_pairs(out, fmt, FrameAction::Restore);+ w!(out, " ldr d8, [sp, #96]");+ if matches!(fmt, ObjectFormat::Elf) {+ w!(out, " .cfi_restore d8");+ } else if matches!(fmt, ObjectFormat::Coff) {+ w!(out, " .seh_save_freg d8, 96");+ }+ w!(out, " ldp x29, x30, [sp], #{frame_size}");+ if matches!(fmt, ObjectFormat::Elf) {+ w!(out, " .cfi_restore x29");+ w!(out, " .cfi_restore x30");+ w!(out, " .cfi_def_cfa sp, 0");+ } else if matches!(fmt, ObjectFormat::Coff) {+ w!(out, " .seh_save_fplr_x {frame_size}");+ w!(out, " .seh_endepilogue");+ }+ w!(out, " ret");+ w!(out);+}+fn generate_entry_point(out: &mut String, program: &Program, fmt: ObjectFormat) {// void js_interpreter(u8 const* bytecode, u32 entry_point, Value* values, VM* vm)// AAPCS64: x0=bytecode, w1=entry_point, x2=values, x3=vm@@ -1260,6 +1432,7 @@ mod tests {has_jscvt: false,enable_assertions: false,profiling: false,+ profile: crate::Profile::JavaScript,}}@@ -1304,6 +1477,7 @@ mod tests {instructions,}],dispatch_handlers: vec![Some(crate::identity::HandlerId::new(0))],+ dispatch: Default::default(),}}diff --git a/Libraries/LibJS/Flap/src/target/aarch64/finalize.rs b/Libraries/LibJS/Flap/src/target/aarch64/finalize.rsindex df56d1d4335..b8ef6f77c2d 100644--- a/Libraries/LibJS/Flap/src/target/aarch64/finalize.rs+++ b/Libraries/LibJS/Flap/src/target/aarch64/finalize.rs@@ -1829,7 +1829,10 @@ impl Backend for Aarch64Backend {let [opcode_scratch, target_scratch] = scratches.physical_registers();use crate::target::registers::aarch64::X25;- emit!(emit.output, Aarch64; Opcode::SetInstructionPointer => [register X25];);+ // An absolute instruction pointer is already in x21.+ if emit.profile.program_counter_addressing() == crate::profile::ProgramCounterAddressing::BaseRelative {+ emit!(emit.output, Aarch64; Opcode::SetInstructionPointer => [register X25];);+ }dispatch_from_instruction_pointer(emit, opcode_scratch, target_scratch).map_err(|error| memory_address_compile_error(emit.handler, error))}@@ -1841,7 +1844,16 @@ impl Backend for Aarch64Backend {scratches: &[AllocatedOperand],) -> Result<(), CompileError> {let [opcode_scratch, target_scratch] = scratches.physical_registers();- emit!(emit.output, Aarch64; Opcode::AdvanceInstructionPointer => [register size];);+ if emit.profile.program_counter_addressing() == crate::profile::ProgramCounterAddressing::Absolute {+ emit!(emit.output, Aarch64;+ Opcode::AddSubtractRegister {+ operation: AddSubtractOperation::Add,+ flags: FlagUpdate::Preserve,+ } => [register X21, register X21, register size];+ );+ } else {+ emit!(emit.output, Aarch64; Opcode::AdvanceInstructionPointer => [register size];);+ }dispatch_from_instruction_pointer(emit, opcode_scratch, target_scratch).map_err(|error| memory_address_compile_error(emit.handler, error))}@@ -2209,7 +2221,13 @@ impl Backend for Aarch64Backend {fn goto_handler(&self, emit: &mut Emit<'_>, operands: &[AllocatedOperand]) -> Result<(), CompileError> {let [target, opcode_scratch, target_scratch] = operands.physical_registers();- emit!(emit.output, Aarch64; Opcode::SetInstructionPointer => [register target];);+ if emit.profile.program_counter_addressing() == crate::profile::ProgramCounterAddressing::Absolute {+ if target != X21 {+ emit!(emit.output, Aarch64; Opcode::MoveRegister(IntegerWidth::U64) => [register X21, register target];);+ }+ } else {+ emit!(emit.output, Aarch64; Opcode::SetInstructionPointer => [register target];);+ }dispatch_from_instruction_pointer(emit, opcode_scratch, target_scratch).map_err(|error| memory_address_compile_error(emit.handler, error))}@@ -2511,6 +2529,49 @@ impl Backend for Aarch64Backend {Ok(())}+ fn branch_ordered_float(+ &self,+ emit: &mut Emit<'_>,+ lhs: PhysicalRegister,+ rhs: PhysicalRegister,+ comparison: crate::intrinsic::OrderedFloatComparison,+ target: &Label,+ ) -> Result<(), CompileError> {+ super::wasm::branch_ordered_float(emit, lhs, rhs, comparison, target);+ Ok(())+ }++ fn dispatch_secondary(&self, emit: &mut Emit<'_>, operands: &[AllocatedOperand]) -> Result<(), CompileError> {+ super::wasm::dispatch_secondary(emit, operands)+ }++ fn finalize_numeric(+ &self,+ emit: &mut Emit<'_>,+ operation: crate::intrinsic::NumericOperation,+ operands: &[AllocatedOperand],+ ) -> Result<(), CompileError> {+ super::wasm::finalize_numeric(emit, operation, operands)+ }++ fn finalize_atomic(+ &self,+ emit: &mut Emit<'_>,+ operation: crate::intrinsic::AtomicOperation,+ operands: &[AllocatedOperand],+ ) -> Result<(), CompileError> {+ super::wasm::finalize_atomic(emit, operation, operands)+ }++ fn finalize_vector(+ &self,+ emit: &mut Emit<'_>,+ operation: crate::intrinsic::VectorOperation,+ operands: &[AllocatedOperand],+ ) -> Result<(), CompileError> {+ super::wasm::finalize_vector(emit, operation, operands)+ }+fn finalize_binary_operation(&self,emit: &mut Emit<'_>,@@ -2518,6 +2579,15 @@ impl Backend for Aarch64Backend {width: IntegerWidth,operands: &[AllocatedOperand],) -> Result<(), CompileError> {+ if width == IntegerWidth::U32+ && matches!(+ operation,+ BinaryOperation::Add | BinaryOperation::Subtract | BinaryOperation::Multiply+ )+ {+ super::wasm::arithmetic32(emit, operation, operands);+ return Ok(());+ }if operation == BinaryOperation::Multiply {multiply(emit, width, operands);return Ok(());diff --git a/Libraries/LibJS/Flap/src/target/aarch64/wasm.rs b/Libraries/LibJS/Flap/src/target/aarch64/wasm.rsnew file mode 100644index 00000000000..c7e4ef71ef9--- /dev/null+++ b/Libraries/LibJS/Flap/src/target/aarch64/wasm.rs@@ -0,0 +1,882 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! AArch64 expansions of the numeric, vector, and atomic operations that only the WebAssembly profile uses.+//!+//! The vector operations are specified by the x86-64 instructions they map to (see `VectorOperation`), so their+//! expansions here reproduce those instructions' results exactly, including how they treat NaNs, out-of-range+//! conversions, and shift counts. v16 to v19 are scratch vector registers that no handler allocates; x9 and x10 are+//! the usual scratch registers.++use super::{Opcode, Slot};+use crate::intrinsic::{+ AtomicOperation, AtomicOperationKind, NumericOperation, OrderedFloatComparison, VectorOperation,+};+use crate::low_ir::Label;+use crate::target::finalize_support::{AllocatedOperands, Emit, machine_address};+use crate::target::ir::{AllocatedOperand, MachineCondition, MachineInstruction, MachineOpcode, MachineOperand};+use crate::target::machine_verify::emit_machine_instructions as emit;+use crate::target::registers::{+ PhysicalRegister,+ aarch64::{D16, D17, D18, D19, X9, X10},+};+use crate::{CompileError, ObjectFormat};++/// One operand of a generic instruction.+#[derive(Clone, Copy)]+enum Part {+ Register(&'static str, &'static str, PhysicalRegister),+ Immediate(i64),+ HexImmediate(i64),+ Literal(&'static str),+}++fn x(register: PhysicalRegister) -> Part {+ Part::Register("x", "", register)+}++fn w(register: PhysicalRegister) -> Part {+ Part::Register("w", "", register)+}++fn d(register: PhysicalRegister) -> Part {+ Part::Register("d", "", register)+}++fn s(register: PhysicalRegister) -> Part {+ Part::Register("s", "", register)+}++fn b(register: PhysicalRegister) -> Part {+ Part::Register("b", "", register)+}++/// A vector register with an arrangement or lane suffix, like `.4s` or `.d[1]`.+fn v(register: PhysicalRegister, suffix: &'static str) -> Part {+ Part::Register("v", suffix, register)+}++fn table(register: PhysicalRegister) -> Part {+ Part::Register("{v", ".16b}", register)+}++fn instruction(emit: &mut Emit<'_>, mnemonic: &'static str, parts: &[Part]) {+ assert!(+ parts.len() <= 4,+ "a generic AArch64 instruction takes at most four operands"+ );+ let mut slots = [None; 4];+ let mut operands = Vec::with_capacity(parts.len());+ for (slot, part) in slots.iter_mut().zip(parts) {+ *slot = Some(match *part {+ Part::Register(prefix, suffix, register) => {+ operands.push(MachineOperand::PhysicalRegister(register));+ Slot::Register(prefix, suffix)+ }+ Part::Immediate(value) => {+ operands.push(MachineOperand::Immediate(value));+ Slot::Immediate+ }+ Part::HexImmediate(value) => {+ operands.push(MachineOperand::Immediate(value));+ Slot::HexImmediate+ }+ Part::Literal(text) => Slot::Literal(text),+ });+ }+ emit.output.push(MachineInstruction {+ opcode: MachineOpcode::Aarch64(Opcode::Generic(mnemonic, slots)),+ operands,+ });+}++/// Materialize a 64-bit constant with movz and movk.+fn move_constant(emit: &mut Emit<'_>, destination: PhysicalRegister, value: u64) {+ const SHIFTS: [&str; 4] = ["lsl #0", "lsl #16", "lsl #32", "lsl #48"];+ let mut first = true;+ for (index, shift) in SHIFTS.into_iter().enumerate() {+ let chunk = (value >> (index * 16)) & 0xffff;+ if chunk == 0 && (value != 0 || index != 0) {+ continue;+ }+ let mnemonic = if first { "movz" } else { "movk" };+ instruction(+ emit,+ mnemonic,+ &[x(destination), Part::HexImmediate(chunk as i64), Part::Literal(shift)],+ );+ first = false;+ }+}++/// Fill every 32-bit lane of `destination` with `value`.+fn splat32(emit: &mut Emit<'_>, destination: PhysicalRegister, value: u32) {+ move_constant(emit, X9, u64::from(value));+ instruction(emit, "dup", &[v(destination, ".4s"), w(X9)]);+}++/// Fill both 64-bit lanes of `destination` with `value`.+fn splat64(emit: &mut Emit<'_>, destination: PhysicalRegister, value: u64) {+ move_constant(emit, X9, value);+ instruction(emit, "dup", &[v(destination, ".2d"), x(X9)]);+}++fn move_vector(emit: &mut Emit<'_>, destination: PhysicalRegister, source: PhysicalRegister) {+ if destination != source {+ instruction(emit, "mov", &[v(destination, ".16b"), v(source, ".16b")]);+ }+}++/// 32-bit addition, subtraction, and multiplication, which leave the upper half of the destination clear.+pub(crate) fn arithmetic32(+ emit: &mut Emit<'_>,+ operation: crate::intrinsic::BinaryOperation,+ operands: &[AllocatedOperand],+) {+ use crate::intrinsic::BinaryOperation;+ let destination = operands.physical_register(0);+ let lhs = operands.physical_register(1);+ let mnemonic = match operation {+ BinaryOperation::Add => "add",+ BinaryOperation::Subtract => "sub",+ _ => "mul",+ };+ let rhs = match *operands.operand(2) {+ AllocatedOperand::Immediate(value) => {+ let value = value as u32;+ if operation != BinaryOperation::Multiply && value <= 4095 {+ instruction(+ emit,+ mnemonic,+ &[w(destination), w(lhs), Part::Immediate(i64::from(value))],+ );+ return;+ }+ if operation != BinaryOperation::Multiply && value.wrapping_neg() <= 4095 {+ let inverse = if operation == BinaryOperation::Add {+ "sub"+ } else {+ "add"+ };+ instruction(+ emit,+ inverse,+ &[w(destination), w(lhs), Part::Immediate(i64::from(value.wrapping_neg()))],+ );+ return;+ }+ move_constant(emit, X9, u64::from(value));+ X9+ }+ _ => operands.physical_register(2),+ };+ instruction(emit, mnemonic, &[w(destination), w(lhs), w(rhs)]);+}++pub(crate) fn branch_ordered_float(+ emit: &mut Emit<'_>,+ lhs: PhysicalRegister,+ rhs: PhysicalRegister,+ comparison: OrderedFloatComparison,+ target: &Label,+) {+ // fcmp sets N, Z, C, and V so that an unordered comparison satisfies none of mi, ls, gt, ge, and eq, and does+ // satisfy ne.+ let condition = match comparison {+ OrderedFloatComparison::Equal => MachineCondition::Equal,+ OrderedFloatComparison::NotEqual => MachineCondition::NotEqual,+ OrderedFloatComparison::Less => MachineCondition::Negative,+ OrderedFloatComparison::LessOrEqual => MachineCondition::UnsignedLessOrEqual,+ OrderedFloatComparison::Greater => MachineCondition::SignedGreater,+ OrderedFloatComparison::GreaterOrEqual => MachineCondition::SignedGreaterOrEqual,+ };+ emit!(emit.output, Aarch64;+ Opcode::CompareDouble => [register lhs, register rhs];+ Opcode::BranchCondition(condition) => [label target.clone()];+ );+}++fn secondary_table_page(prefix: u8, format: ObjectFormat) -> Option<(&'static str, &'static str)> {+ let mach_o = format == ObjectFormat::MachO;+ Some(match (prefix, mach_o) {+ (0xfb, false) => ("asm_dispatch_table_fb", ":lo12:asm_dispatch_table_fb"),+ (0xfc, false) => ("asm_dispatch_table_fc", ":lo12:asm_dispatch_table_fc"),+ (0xfd, false) => ("asm_dispatch_table_fd", ":lo12:asm_dispatch_table_fd"),+ (0xfe, false) => ("asm_dispatch_table_fe", ":lo12:asm_dispatch_table_fe"),+ (0xff, false) => ("asm_dispatch_table_ff", ":lo12:asm_dispatch_table_ff"),+ (0xfb, true) => ("asm_dispatch_table_fb@PAGE", "asm_dispatch_table_fb@PAGEOFF"),+ (0xfc, true) => ("asm_dispatch_table_fc@PAGE", "asm_dispatch_table_fc@PAGEOFF"),+ (0xfd, true) => ("asm_dispatch_table_fd@PAGE", "asm_dispatch_table_fd@PAGEOFF"),+ (0xfe, true) => ("asm_dispatch_table_fe@PAGE", "asm_dispatch_table_fe@PAGEOFF"),+ (0xff, true) => ("asm_dispatch_table_ff@PAGE", "asm_dispatch_table_ff@PAGEOFF"),+ _ => return None,+ })+}++pub(crate) fn dispatch_secondary(emit: &mut Emit<'_>, operands: &[AllocatedOperand]) -> Result<(), CompileError> {+ let prefix = operands.immediate(0);+ let index = operands.physical_register(1);+ let Some((page, offset)) = u8::try_from(prefix)+ .ok()+ .and_then(|prefix| secondary_table_page(prefix, emit.object_format))+ else {+ return Err(crate::target::finalize_support::finalization_error(+ emit.handler,+ "secondary dispatch tables only exist for the 0xfb to 0xff prefixes",+ ));+ };+ instruction(emit, "adrp", &[x(X9), Part::Literal(page)]);+ instruction(emit, "add", &[x(X9), x(X9), Part::Literal(offset)]);+ instruction(+ emit,+ "ldr",+ &[x(X10), Part::Register("[x", "", X9), x(index), Part::Literal("lsl #3]")],+ );+ instruction(emit, "br", &[x(X10)]);+ Ok(())+}++pub(crate) fn finalize_numeric(+ emit: &mut Emit<'_>,+ operation: NumericOperation,+ operands: &[AllocatedOperand],+) -> Result<(), CompileError> {+ use NumericOperation::*;+ let narrow = matches!(+ operation,+ DivideSigned32+ | DivideUnsigned32+ | RemainderSigned32+ | RemainderUnsigned32+ | CountLeadingZeros32+ | CountTrailingZeros32+ | PopulationCount32+ | RotateLeft32+ | RotateRight32+ );+ let gpr = if narrow { w } else { x };+ match operation {+ DivideSigned32 | DivideUnsigned32 | DivideSigned64 | DivideUnsigned64 => {+ let [destination, dividend, divisor] = operands.physical_registers();+ let mnemonic = if matches!(operation, DivideSigned32 | DivideSigned64) {+ "sdiv"+ } else {+ "udiv"+ };+ instruction(emit, mnemonic, &[gpr(destination), gpr(dividend), gpr(divisor)]);+ }+ RemainderSigned32 | RemainderUnsigned32 | RemainderSigned64 | RemainderUnsigned64 => {+ let [destination, dividend, divisor] = operands.physical_registers();+ let mnemonic = if matches!(operation, RemainderSigned32 | RemainderSigned64) {+ "sdiv"+ } else {+ "udiv"+ };+ instruction(emit, mnemonic, &[gpr(X9), gpr(dividend), gpr(divisor)]);+ instruction(emit, "msub", &[gpr(destination), gpr(X9), gpr(divisor), gpr(dividend)]);+ }+ CountLeadingZeros32 | CountLeadingZeros64 => {+ let [destination, source] = operands.physical_registers();+ instruction(emit, "clz", &[gpr(destination), gpr(source)]);+ }+ CountTrailingZeros32 | CountTrailingZeros64 => {+ let [destination, source] = operands.physical_registers();+ instruction(emit, "rbit", &[gpr(X9), gpr(source)]);+ instruction(emit, "clz", &[gpr(destination), gpr(X9)]);+ }+ PopulationCount32 | PopulationCount64 => {+ let [destination, source] = operands.physical_registers();+ if narrow {+ instruction(emit, "fmov", &[s(D16), w(source)]);+ } else {+ instruction(emit, "fmov", &[d(D16), x(source)]);+ }+ instruction(emit, "cnt", &[v(D16, ".8b"), v(D16, ".8b")]);+ instruction(emit, "addv", &[b(D16), v(D16, ".8b")]);+ instruction(emit, "fmov", &[w(destination), s(D16)]);+ }+ RotateLeft32 | RotateLeft64 | RotateRight32 | RotateRight64 => {+ let [destination, count] = operands.physical_registers();+ if matches!(operation, RotateLeft32 | RotateLeft64) {+ instruction(emit, "neg", &[gpr(X9), gpr(count)]);+ instruction(emit, "ror", &[gpr(destination), gpr(destination), gpr(X9)]);+ } else {+ instruction(emit, "ror", &[gpr(destination), gpr(destination), gpr(count)]);+ }+ }+ Float64FromBits => {+ let [destination, source] = operands.physical_registers();+ instruction(emit, "fmov", &[d(destination), x(source)]);+ }+ Float32FromBits => {+ let [destination, source] = operands.physical_registers();+ instruction(emit, "fmov", &[s(destination), w(source)]);+ }+ Float64ToBits => {+ let [destination, source] = operands.physical_registers();+ instruction(emit, "fmov", &[x(destination), d(source)]);+ }+ Float32ToBits => {+ let [destination, source] = operands.physical_registers();+ instruction(emit, "fmov", &[w(destination), s(source)]);+ }+ TruncateFloat64ToSigned64 => {+ // Only in-range values reach this, so saturation never differs from x86-64's result.+ let [destination, source] = operands.physical_registers();+ instruction(emit, "fcvtzs", &[x(destination), d(source)]);+ }+ ConvertSigned64ToFloat32 => {+ let [destination, source] = operands.physical_registers();+ instruction(emit, "scvtf", &[s(destination), x(source)]);+ }+ ConvertSigned64ToFloat64 => {+ let [destination, source] = operands.physical_registers();+ instruction(emit, "scvtf", &[d(destination), x(source)]);+ }+ RoundFloat64ToZero | RoundFloat64ToNearest | RoundFloat64Up | RoundFloat64Down | SquareRootFloat64 => {+ let [destination, source] = operands.physical_registers();+ let mnemonic = match operation {+ RoundFloat64ToZero => "frintz",+ RoundFloat64ToNearest => "frintn",+ RoundFloat64Up => "frintp",+ RoundFloat64Down => "frintm",+ _ => "fsqrt",+ };+ instruction(emit, mnemonic, &[d(destination), d(source)]);+ }+ SquareRootFloat32 => {+ let [destination, source] = operands.physical_registers();+ instruction(emit, "fsqrt", &[s(destination), s(source)]);+ }+ PromoteFloat32 => {+ let [destination, source] = operands.physical_registers();+ instruction(emit, "fcvt", &[d(destination), s(source)]);+ }+ DemoteFloat64 => {+ let [destination, source] = operands.physical_registers();+ instruction(emit, "fcvt", &[s(destination), d(source)]);+ }+ AddFloat32 | SubtractFloat32 | MultiplyFloat32 | DivideFloat32 => {+ let [destination, rhs] = operands.physical_registers();+ let mnemonic = match operation {+ AddFloat32 => "fadd",+ SubtractFloat32 => "fsub",+ MultiplyFloat32 => "fmul",+ _ => "fdiv",+ };+ instruction(emit, mnemonic, &[s(destination), s(destination), s(rhs)]);+ }+ }+ Ok(())+}++pub(crate) fn finalize_atomic(+ emit: &mut Emit<'_>,+ operation: AtomicOperation,+ operands: &[AllocatedOperand],+) -> Result<(), CompileError> {+ use crate::intrinsic::IntegerWidth;+ let width = operation.width();+ let (suffix, gpr): (&'static str, fn(PhysicalRegister) -> Part) = match width {+ IntegerWidth::U8 => ("b", w),+ IntegerWidth::U16 => ("h", w),+ IntegerWidth::U32 => ("", w),+ IntegerWidth::U64 => ("", x),+ };+ if operation.kind() == AtomicOperationKind::Fence {+ instruction(emit, "dmb", &[Part::Literal("ish")]);+ return Ok(());+ }+ let destination = operands.physical_register(0);+ let address = machine_address(operands.operand(1));+ // The atomic instructions only take a base register.+ let base = if address.index.is_none() && address.displacement.unwrap_or(0) == 0 {+ address.base+ } else {+ let mut base = address.base;+ if let Some(index) = address.index {+ let shift = address.scale.unwrap_or(1).trailing_zeros();+ let shift = match shift {+ 0 => "lsl #0",+ 1 => "lsl #1",+ 2 => "lsl #2",+ _ => "lsl #3",+ };+ instruction(emit, "add", &[x(X9), x(base), x(index), Part::Literal(shift)]);+ base = X9;+ }+ let displacement = address.displacement.unwrap_or(0);+ if displacement != 0 {+ if (0..=4095).contains(&displacement) {+ instruction(emit, "add", &[x(X9), x(base), Part::Immediate(displacement)]);+ } else if (-4095..0).contains(&displacement) {+ instruction(emit, "sub", &[x(X9), x(base), Part::Immediate(-displacement)]);+ } else {+ move_constant(emit, X10, displacement as u64);+ instruction(emit, "add", &[x(X9), x(base), x(X10)]);+ }+ }+ X9+ };+ let memory = Part::Register("[x", "]", base);+ // The acquire-release forms make every atomic access sequentially consistent with the others.+ match operation.kind() {+ AtomicOperationKind::Load => {+ let mnemonic = match width {+ IntegerWidth::U8 => "ldarb",+ IntegerWidth::U16 => "ldarh",+ _ => "ldar",+ };+ instruction(emit, mnemonic, &[gpr(destination), memory]);+ }+ AtomicOperationKind::CompareExchange => {+ let replacement = operands.physical_register(2);+ let mnemonic = match suffix {+ "b" => "casalb",+ "h" => "casalh",+ _ => "casal",+ };+ instruction(emit, mnemonic, &[gpr(destination), gpr(replacement), memory]);+ }+ AtomicOperationKind::Exchange | AtomicOperationKind::FetchAdd => {+ let exchange = operation.kind() == AtomicOperationKind::Exchange;+ let mnemonic = match (exchange, suffix) {+ (true, "b") => "swpalb",+ (true, "h") => "swpalh",+ (true, _) => "swpal",+ (false, "b") => "ldaddalb",+ (false, "h") => "ldaddalh",+ (false, _) => "ldaddal",+ };+ instruction(emit, mnemonic, &[gpr(destination), gpr(destination), memory]);+ }+ AtomicOperationKind::Fence => unreachable!(),+ }+ Ok(())+}++pub(crate) fn finalize_vector(+ emit: &mut Emit<'_>,+ operation: VectorOperation,+ operands: &[AllocatedOperand],+) -> Result<(), CompileError> {+ use crate::intrinsic::VectorOperationKind;+ match operation.kind() {+ VectorOperationKind::FromU64Pair => {+ let [destination, low, high] = operands.physical_registers();+ instruction(emit, "fmov", &[d(destination), x(low)]);+ instruction(emit, "mov", &[v(destination, ".d[1]"), x(high)]);+ }+ VectorOperationKind::Binary => {+ let [destination, rhs] = operands.physical_registers();+ vector_binary(emit, operation, destination, rhs);+ }+ VectorOperationKind::Unary => {+ let [destination, source] = operands.physical_registers();+ vector_unary(emit, operation, destination, source);+ }+ VectorOperationKind::ToGeneralPurpose | VectorOperationKind::ToGeneralPurpose32 => {+ let [destination, source] = operands.physical_registers();+ vector_to_general_purpose(emit, operation, destination, source);+ }+ }+ Ok(())+}++/// The mnemonic and arrangement of the binary operations that are one instruction, `destination = op(destination,+/// rhs)`.+fn single_binary(operation: VectorOperation) -> Option<(&'static str, &'static str)> {+ use VectorOperation::*;+ Some(match operation {+ And => ("and", ".16b"),+ Or => ("orr", ".16b"),+ Xor => ("eor", ".16b"),+ AddI8 => ("add", ".16b"),+ SubtractI8 => ("sub", ".16b"),+ EqualI8 => ("cmeq", ".16b"),+ GreaterSignedI8 => ("cmgt", ".16b"),+ AddI16 => ("add", ".8h"),+ SubtractI16 => ("sub", ".8h"),+ EqualI16 => ("cmeq", ".8h"),+ GreaterSignedI16 => ("cmgt", ".8h"),+ AddI32 => ("add", ".4s"),+ SubtractI32 => ("sub", ".4s"),+ EqualI32 => ("cmeq", ".4s"),+ GreaterSignedI32 => ("cmgt", ".4s"),+ AddI64 => ("add", ".2d"),+ SubtractI64 => ("sub", ".2d"),+ EqualI64 => ("cmeq", ".2d"),+ GreaterSignedI64 => ("cmgt", ".2d"),+ AddSaturateSignedI8 => ("sqadd", ".16b"),+ AddSaturateUnsignedI8 => ("uqadd", ".16b"),+ SubtractSaturateSignedI8 => ("sqsub", ".16b"),+ SubtractSaturateUnsignedI8 => ("uqsub", ".16b"),+ AverageUnsignedI8 => ("urhadd", ".16b"),+ AddSaturateSignedI16 => ("sqadd", ".8h"),+ AddSaturateUnsignedI16 => ("uqadd", ".8h"),+ SubtractSaturateSignedI16 => ("sqsub", ".8h"),+ SubtractSaturateUnsignedI16 => ("uqsub", ".8h"),+ AverageUnsignedI16 => ("urhadd", ".8h"),+ MultiplyI16 => ("mul", ".8h"),+ MultiplyI32 => ("mul", ".4s"),+ MinimumSignedI8 => ("smin", ".16b"),+ MinimumUnsignedI8 => ("umin", ".16b"),+ MaximumSignedI8 => ("smax", ".16b"),+ MaximumUnsignedI8 => ("umax", ".16b"),+ MinimumSignedI16 => ("smin", ".8h"),+ MinimumUnsignedI16 => ("umin", ".8h"),+ MaximumSignedI16 => ("smax", ".8h"),+ MaximumUnsignedI16 => ("umax", ".8h"),+ MinimumSignedI32 => ("smin", ".4s"),+ MinimumUnsignedI32 => ("umin", ".4s"),+ MaximumSignedI32 => ("smax", ".4s"),+ MaximumUnsignedI32 => ("umax", ".4s"),+ InterleaveLowI8 => ("zip1", ".16b"),+ InterleaveHighI8 => ("zip2", ".16b"),+ InterleaveLowI16 => ("zip1", ".8h"),+ InterleaveHighI16 => ("zip2", ".8h"),+ InterleaveLowI32 => ("zip1", ".4s"),+ InterleaveHighI32 => ("zip2", ".4s"),+ InterleaveLowI64 => ("zip1", ".2d"),+ InterleaveHighI64 => ("zip2", ".2d"),+ AddF32 => ("fadd", ".4s"),+ SubtractF32 => ("fsub", ".4s"),+ MultiplyF32 => ("fmul", ".4s"),+ DivideF32 => ("fdiv", ".4s"),+ EqualF32 => ("fcmeq", ".4s"),+ AddF64 => ("fadd", ".2d"),+ SubtractF64 => ("fsub", ".2d"),+ MultiplyF64 => ("fmul", ".2d"),+ DivideF64 => ("fdiv", ".2d"),+ EqualF64 => ("fcmeq", ".2d"),+ _ => return None,+ })+}++fn vector_binary(+ emit: &mut Emit<'_>,+ operation: VectorOperation,+ destination: PhysicalRegister,+ rhs: PhysicalRegister,+) {+ use VectorOperation::*;+ if let Some((mnemonic, arrangement)) = single_binary(operation) {+ instruction(+ emit,+ mnemonic,+ &[+ v(destination, arrangement),+ v(destination, arrangement),+ v(rhs, arrangement),+ ],+ );+ return;+ }+ let [lhs, result] = [destination, destination];+ match operation {+ // pandn complements its left operand.+ AndNot => instruction(emit, "bic", &[v(result, ".16b"), v(rhs, ".16b"), v(lhs, ".16b")]),+ // pmuludq multiplies the low halves of the 64-bit lanes.+ MultiplyUnsignedLowI32 => {+ instruction(emit, "xtn", &[v(D16, ".2s"), v(lhs, ".2d")]);+ instruction(emit, "xtn", &[v(D17, ".2s"), v(rhs, ".2d")]);+ instruction(emit, "umull", &[v(result, ".2d"), v(D16, ".2s"), v(D17, ".2s")]);+ }+ MultiplyHighSignedI16 | MultiplyHighUnsignedI16 => {+ let (low, high) = if operation == MultiplyHighSignedI16 {+ ("smull", "smull2")+ } else {+ ("umull", "umull2")+ };+ instruction(emit, low, &[v(D16, ".4s"), v(lhs, ".4h"), v(rhs, ".4h")]);+ instruction(emit, high, &[v(D17, ".4s"), v(lhs, ".8h"), v(rhs, ".8h")]);+ instruction(emit, "uzp2", &[v(result, ".8h"), v(D16, ".8h"), v(D17, ".8h")]);+ }+ // pmulhrsw is (a * b + 0x4000) >> 15, truncated to 16 bits, so -0x8000 * -0x8000 gives -0x8000.+ MultiplyHighRoundScaleI16 => {+ instruction(emit, "smull", &[v(D16, ".4s"), v(lhs, ".4h"), v(rhs, ".4h")]);+ instruction(emit, "smull2", &[v(D17, ".4s"), v(lhs, ".8h"), v(rhs, ".8h")]);+ instruction(emit, "rshrn", &[v(D16, ".4h"), v(D16, ".4s"), Part::Immediate(15)]);+ instruction(emit, "rshrn2", &[v(D16, ".8h"), v(D17, ".4s"), Part::Immediate(15)]);+ move_vector(emit, result, D16);+ }+ // pmaddwd adds adjacent products of signed 16-bit lanes into 32-bit lanes, wrapping.+ MultiplyAddI16 => {+ instruction(emit, "smull", &[v(D16, ".4s"), v(lhs, ".4h"), v(rhs, ".4h")]);+ instruction(emit, "smull2", &[v(D17, ".4s"), v(lhs, ".8h"), v(rhs, ".8h")]);+ instruction(emit, "addp", &[v(result, ".4s"), v(D16, ".4s"), v(D17, ".4s")]);+ }+ // pmaddubsw multiplies unsigned bytes of its left operand with signed bytes of its right one, and adds+ // adjacent products into 16-bit lanes with signed saturation.+ MultiplyAddUnsignedSignedI8 => {+ instruction(emit, "ushll", &[v(D16, ".8h"), v(lhs, ".8b"), Part::Immediate(0)]);+ instruction(emit, "ushll2", &[v(D17, ".8h"), v(lhs, ".16b"), Part::Immediate(0)]);+ instruction(emit, "sshll", &[v(D18, ".8h"), v(rhs, ".8b"), Part::Immediate(0)]);+ instruction(emit, "sshll2", &[v(D19, ".8h"), v(rhs, ".16b"), Part::Immediate(0)]);+ instruction(emit, "mul", &[v(D16, ".8h"), v(D16, ".8h"), v(D18, ".8h")]);+ instruction(emit, "mul", &[v(D17, ".8h"), v(D17, ".8h"), v(D19, ".8h")]);+ instruction(emit, "uzp1", &[v(D18, ".8h"), v(D16, ".8h"), v(D17, ".8h")]);+ instruction(emit, "uzp2", &[v(D19, ".8h"), v(D16, ".8h"), v(D17, ".8h")]);+ instruction(emit, "sqadd", &[v(result, ".8h"), v(D18, ".8h"), v(D19, ".8h")]);+ }+ // The shifts take their count from the low 64 bits of the right operand, and shift every bit out for+ // counts of at least the lane width. ushl and sshl shift right for negative counts, and by the low byte of+ // the count, so the count is clamped to the lane width first.+ ShiftLeftI16+ | ShiftRightUnsignedI16+ | ShiftRightSignedI16+ | ShiftLeftI32+ | ShiftRightUnsignedI32+ | ShiftRightSignedI32+ | ShiftLeftI64+ | ShiftRightUnsignedI64 => {+ let (arrangement, width) = match operation {+ ShiftLeftI16 | ShiftRightUnsignedI16 | ShiftRightSignedI16 => (".8h", 16),+ ShiftLeftI32 | ShiftRightUnsignedI32 | ShiftRightSignedI32 => (".4s", 32),+ _ => (".2d", 64),+ };+ instruction(emit, "fmov", &[x(X9), d(rhs)]);+ instruction(emit, "mov", &[x(X10), Part::Immediate(width)]);+ instruction(emit, "cmp", &[x(X9), x(X10)]);+ instruction(emit, "csel", &[x(X9), x(X9), x(X10), Part::Literal("lo")]);+ if !matches!(operation, ShiftLeftI16 | ShiftLeftI32 | ShiftLeftI64) {+ instruction(emit, "neg", &[x(X9), x(X9)]);+ }+ if width == 64 {+ instruction(emit, "dup", &[v(D16, arrangement), x(X9)]);+ } else {+ instruction(emit, "dup", &[v(D16, arrangement), w(X9)]);+ }+ let mnemonic = if matches!(operation, ShiftRightSignedI16 | ShiftRightSignedI32) {+ "sshl"+ } else {+ "ushl"+ };+ instruction(+ emit,+ mnemonic,+ &[v(result, arrangement), v(lhs, arrangement), v(D16, arrangement)],+ );+ }+ // pshufb picks the byte its index's low four bits select, or zero if the index has its top bit set. tbl+ // gives zero for any index above 15.+ Shuffle8 => {+ instruction(emit, "movi", &[v(D16, ".16b"), Part::HexImmediate(0x8f)]);+ instruction(emit, "and", &[v(D16, ".16b"), v(rhs, ".16b"), v(D16, ".16b")]);+ instruction(emit, "tbl", &[v(result, ".16b"), table(lhs), v(D16, ".16b")]);+ }+ NarrowSignedI16 | NarrowUnsignedI16 | NarrowSignedI32 | NarrowUnsignedI32 => {+ let (low, high) = if matches!(operation, NarrowSignedI16 | NarrowSignedI32) {+ ("sqxtn", "sqxtn2")+ } else {+ ("sqxtun", "sqxtun2")+ };+ let (narrow_low, narrow_high, wide) = if matches!(operation, NarrowSignedI16 | NarrowUnsignedI16) {+ (".8b", ".16b", ".8h")+ } else {+ (".4h", ".8h", ".4s")+ };+ instruction(emit, low, &[v(D16, narrow_low), v(lhs, wide)]);+ instruction(emit, high, &[v(D16, narrow_high), v(rhs, wide)]);+ move_vector(emit, result, D16);+ }+ // minps and maxps give their right operand unless the left one compares strictly smaller or larger, so for+ // NaNs and for zeros of either sign.+ MinimumF32 | MaximumF32 | MinimumF64 | MaximumF64 => {+ let arrangement = if matches!(operation, MinimumF32 | MaximumF32) {+ ".4s"+ } else {+ ".2d"+ };+ if matches!(operation, MinimumF32 | MinimumF64) {+ instruction(+ emit,+ "fcmgt",+ &[v(D16, arrangement), v(rhs, arrangement), v(lhs, arrangement)],+ );+ } else {+ instruction(+ emit,+ "fcmgt",+ &[v(D16, arrangement), v(lhs, arrangement), v(rhs, arrangement)],+ );+ }+ instruction(emit, "bsl", &[v(D16, ".16b"), v(lhs, ".16b"), v(rhs, ".16b")]);+ move_vector(emit, result, D16);+ }+ NotEqualF32 | NotEqualF64 => {+ let arrangement = if operation == NotEqualF32 { ".4s" } else { ".2d" };+ instruction(+ emit,+ "fcmeq",+ &[v(result, arrangement), v(lhs, arrangement), v(rhs, arrangement)],+ );+ instruction(emit, "mvn", &[v(result, ".16b"), v(result, ".16b")]);+ }+ LessF32 | LessF64 => {+ let arrangement = if operation == LessF32 { ".4s" } else { ".2d" };+ instruction(+ emit,+ "fcmgt",+ &[v(result, arrangement), v(rhs, arrangement), v(lhs, arrangement)],+ );+ }+ LessOrEqualF32 | LessOrEqualF64 => {+ let arrangement = if operation == LessOrEqualF32 { ".4s" } else { ".2d" };+ instruction(+ emit,+ "fcmge",+ &[v(result, arrangement), v(rhs, arrangement), v(lhs, arrangement)],+ );+ }+ UnorderedF32 | UnorderedF64 => {+ let arrangement = if operation == UnorderedF32 { ".4s" } else { ".2d" };+ instruction(+ emit,+ "fcmeq",+ &[v(D16, arrangement), v(lhs, arrangement), v(lhs, arrangement)],+ );+ instruction(+ emit,+ "fcmeq",+ &[v(D17, arrangement), v(rhs, arrangement), v(rhs, arrangement)],+ );+ instruction(emit, "and", &[v(D16, ".16b"), v(D16, ".16b"), v(D17, ".16b")]);+ instruction(emit, "mvn", &[v(result, ".16b"), v(D16, ".16b")]);+ }+ _ => unreachable!("'{}' is not a binary vector operation", operation.name()),+ }+}++fn vector_unary(+ emit: &mut Emit<'_>,+ operation: VectorOperation,+ destination: PhysicalRegister,+ source: PhysicalRegister,+) {+ use VectorOperation::*;+ let simple = |mnemonic: &'static str, destination_arrangement: &'static str, source_arrangement: &'static str| {+ (mnemonic, destination_arrangement, source_arrangement)+ };+ let single = match operation {+ SquareRootF32 => Some(simple("fsqrt", ".4s", ".4s")),+ CeilF32 => Some(simple("frintp", ".4s", ".4s")),+ FloorF32 => Some(simple("frintm", ".4s", ".4s")),+ TruncF32 => Some(simple("frintz", ".4s", ".4s")),+ NearestF32 => Some(simple("frintn", ".4s", ".4s")),+ SquareRootF64 => Some(simple("fsqrt", ".2d", ".2d")),+ CeilF64 => Some(simple("frintp", ".2d", ".2d")),+ FloorF64 => Some(simple("frintm", ".2d", ".2d")),+ TruncF64 => Some(simple("frintz", ".2d", ".2d")),+ NearestF64 => Some(simple("frintn", ".2d", ".2d")),+ AbsoluteI8 => Some(simple("abs", ".16b", ".16b")),+ AbsoluteI16 => Some(simple("abs", ".8h", ".8h")),+ AbsoluteI32 => Some(simple("abs", ".4s", ".4s")),+ ConvertSignedI32ToF32 => Some(simple("scvtf", ".4s", ".4s")),+ PromoteLowF32 => Some(simple("fcvtl", ".2d", ".2s")),+ // cvtpd2ps clears the upper half, as does writing a 64-bit arrangement.+ DemoteF64 => Some(simple("fcvtn", ".2s", ".2d")),+ HighHalf => Some(simple("dup", ".2d", ".d[1]")),+ BroadcastLowI32 => Some(simple("dup", ".4s", ".s[0]")),+ _ => None,+ };+ if let Some((mnemonic, destination_arrangement, source_arrangement)) = single {+ instruction(+ emit,+ mnemonic,+ &[v(destination, destination_arrangement), v(source, source_arrangement)],+ );+ return;+ }+ match operation {+ ExtendLowSignedI8 | ExtendLowUnsignedI8 | ExtendLowSignedI16 | ExtendLowUnsignedI16 | ExtendLowSignedI32+ | ExtendLowUnsignedI32 => {+ let mnemonic = if matches!(operation, ExtendLowSignedI8 | ExtendLowSignedI16 | ExtendLowSignedI32) {+ "sshll"+ } else {+ "ushll"+ };+ let (wide, narrow) = match operation {+ ExtendLowSignedI8 | ExtendLowUnsignedI8 => (".8h", ".8b"),+ ExtendLowSignedI16 | ExtendLowUnsignedI16 => (".4s", ".4h"),+ _ => (".2d", ".2s"),+ };+ instruction(+ emit,+ mnemonic,+ &[v(destination, wide), v(source, narrow), Part::Immediate(0)],+ );+ }+ ConvertLowSignedI32ToF64 => {+ instruction(emit, "sshll", &[v(D16, ".2d"), v(source, ".2s"), Part::Immediate(0)]);+ instruction(emit, "scvtf", &[v(destination, ".2d"), v(D16, ".2d")]);+ }+ // cvttps2dq gives 0x80000000 for NaNs and values out of range, where fcvtzs saturates and gives zero for+ // NaNs. Values below the range already give 0x80000000.+ TruncateF32ToSignedI32 => {+ instruction(emit, "fcvtzs", &[v(D16, ".4s"), v(source, ".4s")]);+ splat32(emit, D17, 0x4f00_0000);+ instruction(emit, "fcmgt", &[v(D17, ".4s"), v(D17, ".4s"), v(source, ".4s")]);+ splat32(emit, D18, 0x8000_0000);+ instruction(emit, "bsl", &[v(D17, ".16b"), v(D16, ".16b"), v(D18, ".16b")]);+ move_vector(emit, destination, D17);+ }+ // cvttpd2dq gives 0x80000000 for NaNs and values whose truncation is out of range, and clears the upper+ // half.+ TruncateF64ToSignedI32 => {+ instruction(emit, "fcvtzs", &[v(D16, ".2d"), v(source, ".2d")]);+ splat64(emit, D17, 0x41e0_0000_0000_0000);+ instruction(emit, "fcmgt", &[v(D17, ".2d"), v(D17, ".2d"), v(source, ".2d")]);+ splat64(emit, D18, 0xc1e0_0000_0020_0000);+ instruction(emit, "fcmgt", &[v(D18, ".2d"), v(source, ".2d"), v(D18, ".2d")]);+ instruction(emit, "and", &[v(D17, ".16b"), v(D17, ".16b"), v(D18, ".16b")]);+ instruction(emit, "xtn", &[v(D16, ".2s"), v(D16, ".2d")]);+ instruction(emit, "xtn", &[v(D17, ".2s"), v(D17, ".2d")]);+ splat32(emit, D18, 0x8000_0000);+ instruction(emit, "bsl", &[v(D17, ".8b"), v(D16, ".8b"), v(D18, ".8b")]);+ move_vector(emit, destination, D17);+ }+ _ => unreachable!("'{}' is not a unary vector operation", operation.name()),+ }+}++fn vector_to_general_purpose(+ emit: &mut Emit<'_>,+ operation: VectorOperation,+ destination: PhysicalRegister,+ source: PhysicalRegister,+) {+ use VectorOperation::*;+ match operation {+ Low64 => instruction(emit, "fmov", &[x(destination), d(source)]),+ High64 => instruction(emit, "mov", &[x(destination), v(source, ".d[1]")]),+ // Gather the sign bits of the bytes: each shift-and-accumulate doubles the bits a lane holds, until the low+ // byte of each 64-bit half holds the bits of its eight bytes.+ ByteMask => {+ instruction(emit, "ushr", &[v(D16, ".16b"), v(source, ".16b"), Part::Immediate(7)]);+ instruction(emit, "usra", &[v(D16, ".8h"), v(D16, ".8h"), Part::Immediate(7)]);+ instruction(emit, "usra", &[v(D16, ".4s"), v(D16, ".4s"), Part::Immediate(14)]);+ instruction(emit, "usra", &[v(D16, ".2d"), v(D16, ".2d"), Part::Immediate(28)]);+ instruction(emit, "umov", &[w(X9), v(D16, ".b[0]")]);+ instruction(emit, "umov", &[w(X10), v(D16, ".b[8]")]);+ instruction(emit, "orr", &[w(destination), w(X9), w(X10), Part::Literal("lsl #8")]);+ }+ SignMaskF32 => {+ instruction(emit, "ushr", &[v(D16, ".4s"), v(source, ".4s"), Part::Immediate(31)]);+ instruction(emit, "usra", &[v(D16, ".2d"), v(D16, ".2d"), Part::Immediate(31)]);+ instruction(emit, "mov", &[w(X9), v(D16, ".s[0]")]);+ instruction(emit, "mov", &[w(X10), v(D16, ".s[2]")]);+ instruction(emit, "orr", &[w(destination), w(X9), w(X10), Part::Literal("lsl #2")]);+ }+ SignMaskF64 => {+ instruction(emit, "ushr", &[v(D16, ".2d"), v(source, ".2d"), Part::Immediate(63)]);+ instruction(emit, "mov", &[x(X9), v(D16, ".d[0]")]);+ instruction(emit, "mov", &[x(X10), v(D16, ".d[1]")]);+ instruction(emit, "orr", &[x(destination), x(X9), x(X10), Part::Literal("lsl #1")]);+ }+ _ => unreachable!("'{}' does not give a general-purpose value", operation.name()),+ }+}diff --git a/Libraries/LibJS/Flap/src/target/allocator.rs b/Libraries/LibJS/Flap/src/target/allocator.rsindex 64d177e363c..4969a21c240 100644--- a/Libraries/LibJS/Flap/src/target/allocator.rs+++ b/Libraries/LibJS/Flap/src/target/allocator.rs@@ -215,6 +215,7 @@ pub(crate) fn allocate_program(program: TargetProgram) -> Result<AllocatedProgralet allocated = AllocatedProgram {runtime: program.runtime,dispatch_handlers: program.dispatch_handlers,+ dispatch: program.dispatch,architecture: program.architecture,functions,};@@ -251,8 +252,22 @@ pub(crate) fn allocate_handler(.filter(|instruction| instruction.opcode.operation() != crate::target::description::Operation::Cold).collect::<Vec<_>>();let successors = instruction_successors(&analyzed);- let assignments = allocate(handler, &analyzed, &successors, arch)?;- let mut rewritten = rewrite(handler, &handler.instructions, &assignments, runtime)?;+ let assignments = match allocate(handler, &analyzed, &successors, arch) {+ Ok(assignments) => assignments,+ Err(error) => match crate::target::spill::SpillArea::of(runtime) {+ Some(area) => return allocate_with_spills(handler, runtime, area, error),+ None => return Err(error),+ },+ };+ finish_allocation(handler, &assignments, runtime)+}++fn finish_allocation(+ handler: &TargetFunction,+ assignments: &AllocationPlan,+ runtime: &RuntimeConstants,+) -> Result<ControlFlowGraph<AllocatedOperand, SelectedOpcode>, CompileError> {+ let mut rewritten = rewrite(handler, &handler.instructions, assignments, runtime)?;invert_branches_over_jumps(&mut rewritten);remove_unreferenced_labels(&mut rewritten);invert_branches_over_jumps(&mut rewritten);@@ -260,6 +275,127 @@ pub(crate) fn allocate_handler(build_allocated_graph(handler, rewritten)}+/// Allocate a handler that does not fit in the registers by spilling values to the profile's spill area, one at a+/// time, until it does. Handlers that fit never get here, so their code does not change.+fn allocate_with_spills(+ handler: &TargetFunction,+ runtime: &RuntimeConstants,+ area: crate::target::spill::SpillArea,+ original_error: CompileError,+) -> Result<ControlFlowGraph<AllocatedOperand, SelectedOpcode>, CompileError> {+ let mut function = handler.clone();+ let try_allocate = |function: &TargetFunction| {+ let analyzed = function+ .instructions+ .iter()+ .filter(|instruction| instruction.opcode.operation() != crate::target::description::Operation::Cold)+ .collect::<Vec<_>>();+ let successors = instruction_successors(&analyzed);+ allocate(function, &analyzed, &successors, function.architecture)+ };+ if crate::target::spill::isolate_fixed_operands(&mut function)+ && let Ok(assignments) = try_allocate(&function)+ {+ return finish_allocation(&function, &assignments, runtime);+ }+ let mut slot = 0;+ // Rematerializing takes no slot, so this is bounded by the number of values rather than of slots.+ for _ in 0..function.virtual_registers.len() {+ // Spill from the class that is over capacity somewhere, and from the other one if nothing in it can be.+ let first = pressured_class(&function).unwrap_or(VirtualRegisterClass::GeneralPurpose);+ let others = match first {+ VirtualRegisterClass::GeneralPurpose => [VirtualRegisterClass::FloatingPoint, VirtualRegisterClass::Vector],+ VirtualRegisterClass::FloatingPoint => [VirtualRegisterClass::Vector, VirtualRegisterClass::GeneralPurpose],+ VirtualRegisterClass::Vector => [+ VirtualRegisterClass::FloatingPoint,+ VirtualRegisterClass::GeneralPurpose,+ ],+ };+ if ![first, others[0], others[1]]+ .into_iter()+ .any(|class| crate::target::spill::spill_one_register(&mut function, &area, &mut slot, class))+ {+ break;+ }+ let analyzed = function+ .instructions+ .iter()+ .filter(|instruction| instruction.opcode.operation() != crate::target::description::Operation::Cold)+ .collect::<Vec<_>>();+ let successors = instruction_successors(&analyzed);+ if let Ok(assignments) = allocate(&function, &analyzed, &successors, function.architecture) {+ return finish_allocation(&function, &assignments, runtime);+ }+ }+ Err(original_error)+}++/// For each instruction of `function`, the indices of the virtual registers live right after it. Cold annotations+/// execute nothing, and nothing is live after them.+pub(crate) fn live_after_each_instruction(function: &TargetFunction) -> Option<Vec<Vec<u32>>> {+ let mut positions = Vec::with_capacity(function.instructions.len());+ let analyzed = function+ .instructions+ .iter()+ .enumerate()+ .filter(|(_, instruction)| instruction.opcode.operation() != crate::target::description::Operation::Cold)+ .map(|(index, instruction)| {+ positions.push(index);+ instruction+ })+ .collect::<Vec<_>>();+ let successors = instruction_successors(&analyzed);+ let names = Names::new(function.id, &function.virtual_registers);+ let liveness = compute_liveness(&function.name, &analyzed, &successors, &names, function.architecture).ok()?;+ let mut live_after = vec![Vec::new(); function.instructions.len()];+ for (analyzed_index, live) in liveness.live_out.into_iter().enumerate() {+ live_after[positions[analyzed_index]] = live;+ }+ Some(live_after)+}++/// The register class whose live values outnumber its allocatable registers somewhere in `function`, preferring+/// floating point, whose pool is the smaller one.+fn pressured_class(function: &TargetFunction) -> Option<VirtualRegisterClass> {+ let analyzed = function+ .instructions+ .iter()+ .filter(|instruction| instruction.opcode.operation() != crate::target::description::Operation::Cold)+ .collect::<Vec<_>>();+ let successors = instruction_successors(&analyzed);+ let names = Names::new(function.id, &function.virtual_registers);+ let liveness = compute_liveness(&function.name, &analyzed, &successors, &names, function.architecture).ok()?;+ let registers = register_info_for(function.architecture);+ let mut over_gpr = false;+ let mut over_fpr = false;+ for live in &liveness.live_in {+ let gpr = live+ .iter()+ .filter(|register| names.name(**register).class() == VirtualRegisterClass::GeneralPurpose)+ .count();+ let fpr = live.len() - gpr;+ over_gpr |= gpr >= registers.temporaries.len();+ over_fpr |= fpr >= registers.fp_temporaries.len();+ }+ if over_fpr {+ // Vectors share the floating-point registers, so spilling either kind relieves both.+ let vectors_live = liveness+ .live_in+ .iter()+ .flatten()+ .any(|register| names.name(*register).class() == VirtualRegisterClass::Vector);+ Some(if vectors_live {+ VirtualRegisterClass::Vector+ } else {+ VirtualRegisterClass::FloatingPoint+ })+ } else if over_gpr {+ Some(VirtualRegisterClass::GeneralPurpose)+ } else {+ None+ }+}+fn build_allocated_graph(handler: &TargetFunction,instructions: Vec<AllocatedInstruction>,@@ -594,7 +730,7 @@ impl ColoringContext<'_> {fn pool_mask(&self, class: VirtualRegisterClass) -> RegisterSet {match class {VirtualRegisterClass::GeneralPurpose => self.gpr_mask,- VirtualRegisterClass::FloatingPoint => self.fpr_mask,+ VirtualRegisterClass::FloatingPoint | VirtualRegisterClass::Vector => self.fpr_mask,}}@@ -2709,61 +2845,4 @@ mod tests {}assert_eq!(instruction.operands[3].register_name(), Some("x9"));}-- #[test]- fn and_immediate_keeps_live_virtuals_off_x86_scratch_registers() {- // x86_64 lowers large `and` immediates through rax, or through r11- // when the destination is rax. Temps live across the instruction- // must avoid both scratch registers.- let out = allocated(- vec![- instruction!(Operation::Move(IntegerWidth::U64), register("base"), immediate(100)),- instruction!(- Operation::Move(IntegerWidth::U64),- register("index"),- immediate(0x123456789)- ),- instruction!(- Operation::IntegerBinary {- operation: IntegerBinaryOperation::Binary(BinaryOperation::And),- width: IntegerWidth::U64- },- register("index"),- immediate(0x3ffffffff)- ),- instruction!(- Operation::IntegerBinary {- operation: IntegerBinaryOperation::Binary(BinaryOperation::Add),- width: IntegerWidth::U64- },- register("index"),- register("base")- ),- instruction!(Operation::StoreOperand, immediate(0), register("index")),- instruction!(Operation::Control(ControlOperation::DispatchNext)),- ],- Architecture::X86_64,- );- for insn in &out {- if is_operation(insn, Operation::Move(IntegerWidth::U64))- && insn.operands.len() == 2- && let AllocatedOperand::Immediate(100) = insn.operands[1]- && let Some(name) = insn.operands[0].register_name()- {- assert_ne!(name, "rax", "live virtual must avoid rax");- assert_ne!(name, "r11", "live virtual must avoid r11");- }- if is_operation(- insn,- Operation::IntegerBinary {- operation: IntegerBinaryOperation::Binary(BinaryOperation::And),- width: IntegerWidth::U64,- },- ) && let Some(name) = insn.operands.first().and_then(AllocatedOperand::register_name)- {- assert_ne!(name, "rax", "and dst must avoid rax");- assert_ne!(name, "r11", "and dst must avoid r11");- }- }- }}diff --git a/Libraries/LibJS/Flap/src/target/backend.rs b/Libraries/LibJS/Flap/src/target/backend.rsindex 93c11af942f..ecfdb6a383c 100644--- a/Libraries/LibJS/Flap/src/target/backend.rs+++ b/Libraries/LibJS/Flap/src/target/backend.rs@@ -191,6 +191,10 @@ pub(crate) trait Backend: Sync {fn goto_handler(&self, emit: &mut Emit<'_>, operands: &[AllocatedOperand]) -> Result<(), CompileError>;+ /// Jump to the handler a prefix opcode's secondary table holds for a sub-opcode. The caller checks that the+ /// sub-opcode is in the table's range.+ fn dispatch_secondary(&self, emit: &mut Emit<'_>, operands: &[AllocatedOperand]) -> Result<(), CompileError>;+fn goto_bytecode_target(&self, emit: &mut Emit<'_>, operands: &[AllocatedOperand]) -> Result<(), CompileError>;fn finalize_execution_context_store(@@ -282,6 +286,36 @@ pub(crate) trait Backend: Sync {);fn finalize_divide(&self, emit: &mut Emit<'_>, width: IntegerWidth, operands: &[AllocatedOperand]);++ fn branch_ordered_float(+ &self,+ emit: &mut Emit<'_>,+ lhs: PhysicalRegister,+ rhs: PhysicalRegister,+ comparison: crate::intrinsic::OrderedFloatComparison,+ target: &Label,+ ) -> Result<(), CompileError>;++ fn finalize_numeric(+ &self,+ emit: &mut Emit<'_>,+ operation: crate::intrinsic::NumericOperation,+ operands: &[AllocatedOperand],+ ) -> Result<(), CompileError>;++ fn finalize_vector(+ &self,+ emit: &mut Emit<'_>,+ operation: crate::intrinsic::VectorOperation,+ operands: &[AllocatedOperand],+ ) -> Result<(), CompileError>;++ fn finalize_atomic(+ &self,+ emit: &mut Emit<'_>,+ operation: crate::intrinsic::AtomicOperation,+ operands: &[AllocatedOperand],+ ) -> Result<(), CompileError>;}pub(crate) struct X86_64Backend;diff --git a/Libraries/LibJS/Flap/src/target/description.rs b/Libraries/LibJS/Flap/src/target/description.rsindex 218760ca389..831b6529a48 100644--- a/Libraries/LibJS/Flap/src/target/description.rs+++ b/Libraries/LibJS/Flap/src/target/description.rs@@ -179,6 +179,9 @@ pub(crate) enum Operation {ToggleBit,ClearBit,Float(FloatingPointOperation),+ Numeric(crate::intrinsic::NumericOperation),+ Vector(crate::intrinsic::VectorOperation),+ Atomic(crate::intrinsic::AtomicOperation),FloatMove,Branch(BranchOperation),AssertNonzero,@@ -759,6 +762,44 @@ use x86_64::{R11, RAX, RCX, RDX, XMM3};const X86_64_LARGE_IMMEDIATE_STORE_DESCRIPTION: InstructionDescription =plain(&[Memory, GprInOrImm]).scratches(&[R11], &[]);+fn numeric_description(operation: crate::intrinsic::NumericOperation) -> &'static InstructionDescription {+ use crate::intrinsic::NumericOperation::*;+ match operation {+ DivideSigned32 | DivideUnsigned32 | DivideSigned64 | DivideUnsigned64 => {+ &const {+ plain(&[GprOut, GprIn, GprIn])+ .x86_64(spec().outputs(&[RAX]).fixed(&[(0, RAX)]).scratches(&[RDX]))+ .aarch64(spec().scratches(&[X9]))+ }+ }+ RemainderSigned32 | RemainderUnsigned32 | RemainderSigned64 | RemainderUnsigned64 => {+ &const {+ plain(&[GprOut, GprIn, GprIn])+ .x86_64(spec().outputs(&[RDX]).fixed(&[(0, RDX)]).scratches(&[RAX]))+ .aarch64(spec().scratches(&[X9]))+ }+ }+ CountLeadingZeros32 | CountTrailingZeros32 | PopulationCount32 | CountLeadingZeros64 | CountTrailingZeros64+ | PopulationCount64 => &const { plain(&[GprOut, GprIn]) },+ RotateLeft32 | RotateRight32 | RotateLeft64 | RotateRight64 => {+ &const { plain(&[GprInOut, GprIn]).x86_64(spec().fixed(&[(1, RCX)])) }+ }+ Float64FromBits | Float32FromBits | ConvertSigned64ToFloat32 | ConvertSigned64ToFloat64 => {+ &const { plain(&[FprOut, GprIn]) }+ }+ Float64ToBits | Float32ToBits | TruncateFloat64ToSigned64 => &const { plain(&[GprOut, FprIn]) },+ RoundFloat64ToZero+ | RoundFloat64ToNearest+ | RoundFloat64Up+ | RoundFloat64Down+ | SquareRootFloat64+ | SquareRootFloat32+ | PromoteFloat32+ | DemoteFloat64 => &const { plain(&[FprOut, FprIn]) },+ AddFloat32 | SubtractFloat32 | MultiplyFloat32 | DivideFloat32 => &const { plain(&[FprInOut, FprIn]) },+ }+}+fn lookup_operation(operation: Operation) -> &'static InstructionDescription {use BinaryOperation::*;use IntegerWidth::*;@@ -774,6 +815,9 @@ fn lookup_operation(operation: Operation) -> &'static InstructionDescription {Operation::Control(ControlOperation::DispatchNext | ControlOperation::Dispatch) => {&const { plain(&[]).terminal().scratches(&[RAX], &[X9, X10]) }}+ Operation::Control(ControlOperation::DispatchSecondary) => {+ &const { plain(&[Imm, GprIn]).terminal().scratches(&[RAX], &[X9, X10]) }+ }Operation::Control(ControlOperation::DispatchVariable | ControlOperation::GotoHandler) => {&const { plain(&[GprIn]).terminal().scratches(&[RAX], &[X9, X10]) }}@@ -865,12 +909,13 @@ fn lookup_operation(operation: Operation) -> &'static InstructionDescription {}Operation::LoadLabel => &const { plain(&[GprOut, Imm]).scratches(&[], &[X9]) },Operation::Memory(MemoryOperation::Load {- width: MemoryWidth::Word | MemoryWidth::DoubleWord | MemoryWidth::Float,+ width:+ MemoryWidth::Word | MemoryWidth::DoubleWord | MemoryWidth::Float | MemoryWidth::Double | MemoryWidth::Vector,signed: true,..}) => unreachable!("unsupported signed load width"),Operation::Memory(MemoryOperation::Load {- width: MemoryWidth::Float,+ width: MemoryWidth::Float | MemoryWidth::Double | MemoryWidth::Vector,signed: false,}) => &const { plain(&[FprOut, Memory]).pre_scratches(&[], &[X9]) },Operation::Memory(MemoryOperation::Load { .. }) => {@@ -881,7 +926,7 @@ fn lookup_operation(operation: Operation) -> &'static InstructionDescription {)) => &const { plain(&[Memory, GprInOrImm]).pre_scratches(&[], &[X9, X10]) },Operation::StoreExecutionContext => &const { plain(&[Memory]).pre_scratches(&[R11], &[X9, X10]) },Operation::Store64IndexedOffset => &const { plain(&[GprIn, GprIn, Imm, Imm, GprIn]).pre_scratches(&[], &[X9]) },- Operation::Memory(MemoryOperation::Store(MemoryWidth::Float)) => {+ Operation::Memory(MemoryOperation::Store(MemoryWidth::Float | MemoryWidth::Double | MemoryWidth::Vector)) => {&const { plain(&[Memory, FprIn]).pre_scratches(&[], &[X9, X10]) }}Operation::Memory(MemoryOperation::LoadPair(_)) => {@@ -944,9 +989,9 @@ fn lookup_operation(operation: Operation) -> &'static InstructionDescription {Operation::IntegerBinary {operation: IntegerBinaryOperation::Binary(And),width: U64,- } => &const { plain(&[GprInOut, GprInOrImm]).scratches(&[RAX, R11], &[X9]) },+ } => &const { plain(&[GprInOut, GprInOrImm]).scratches(&[], &[X9]) },Operation::IntegerBinary {- operation: IntegerBinaryOperation::Binary(And | Or | Xor),+ operation: IntegerBinaryOperation::Binary(And | Or | Xor | Add | Multiply),width: U32,} => {&const {@@ -955,6 +1000,16 @@ fn lookup_operation(operation: Operation) -> &'static InstructionDescription {.coalesces(&[(0, 1), (0, 2)])}}+ Operation::IntegerBinary {+ operation: IntegerBinaryOperation::Binary(Subtract),+ width: U32,+ } => {+ &const {+ plain(&[GprOut, GprIn, GprInOrImm])+ .scratches(&[], &[X9])+ .coalesces(&[(0, 1)])+ }+ }Operation::Or32Branch(_) => {&const {plain(&[GprOut, GprIn, GprInOrImm])@@ -976,6 +1031,30 @@ fn lookup_operation(operation: Operation) -> &'static InstructionDescription {.coalesces(&[(0, 1)])}}+ Operation::Numeric(operation) => numeric_description(operation),+ Operation::Atomic(operation) => match operation.kind() {+ crate::intrinsic::AtomicOperationKind::CompareExchange => {+ &const {+ plain(&[GprInOut, Memory, GprIn])+ .x86_64(spec().fixed(&[(0, RAX)]))+ .aarch64(spec().scratches(&[X9, X10]))+ }+ }+ crate::intrinsic::AtomicOperationKind::Exchange | crate::intrinsic::AtomicOperationKind::FetchAdd => {+ &const { plain(&[GprInOut, Memory]).aarch64(spec().scratches(&[X9, X10])) }+ }+ crate::intrinsic::AtomicOperationKind::Load => {+ &const { plain(&[GprOut, Memory]).aarch64(spec().scratches(&[X9, X10])) }+ }+ crate::intrinsic::AtomicOperationKind::Fence => &const { plain(&[]) },+ },+ Operation::Vector(operation) => match operation.kind() {+ crate::intrinsic::VectorOperationKind::FromU64Pair => &const { plain(&[FprOut, GprIn, GprIn]) },+ crate::intrinsic::VectorOperationKind::Binary => &const { plain(&[FprInOut, FprIn]) },+ crate::intrinsic::VectorOperationKind::Unary => &const { plain(&[FprOut, FprIn]) },+ crate::intrinsic::VectorOperationKind::ToGeneralPurpose+ | crate::intrinsic::VectorOperationKind::ToGeneralPurpose32 => &const { plain(&[GprOut, FprIn]) },+ },Operation::Modulo(_) => {&const {plain(&[GprOut, GprIn, GprIn])@@ -1071,7 +1150,9 @@ fn lookup_operation(operation: Operation) -> &'static InstructionDescription {.pre_scratches(&[], &[X9])}}- Operation::Branch(BranchOperation::Float(_)) => &const { plain(&[FprIn, FprIn, Label]) },+ Operation::Branch(BranchOperation::Float(_) | BranchOperation::OrderedFloat(_)) => {+ &const { plain(&[FprIn, FprIn, Label]) }+ }Operation::AssertNonzero => &const { plain(&[GprIn]) },Operation::StorePairIndexed(PairWidth::Word) => unreachable!("indexed 32-bit pair stores are unsupported"),Operation::Memory(@@ -1100,12 +1181,12 @@ mod tests {use super::*;#[test]- fn and_declares_x86_large_immediate_scratch_operands() {+ fn and_needs_no_x86_scratch_registers() {let info = lookup_operation(Operation::IntegerBinary {operation: IntegerBinaryOperation::Binary(BinaryOperation::And),width: IntegerWidth::U64,});- assert_eq!(info.x86_64.trailing_scratch_registers, &[RAX, R11]);+ assert!(info.x86_64.trailing_scratch_registers.is_empty());}#[test]diff --git a/Libraries/LibJS/Flap/src/target/emitter.rs b/Libraries/LibJS/Flap/src/target/emitter.rsindex 159d3879689..c77ae307253 100644--- a/Libraries/LibJS/Flap/src/target/emitter.rs+++ b/Libraries/LibJS/Flap/src/target/emitter.rs@@ -28,6 +28,12 @@ pub(crate) enum SimpleRegister {Pair(PairWidth),Word,Single,+ Quad,+ /// An AArch64 vector register with the given arrangement, like v0.16b.+ Vector(&'static str),+ /// The register's number between a prefix and a suffix, like the `w` and `` of w0 or the `{v` and `.16b}` of+ /// {v0.16b}.+ Numbered(&'static str, &'static str),}#[derive(Clone, Copy)]@@ -88,6 +94,14 @@ pub(crate) const fn single(index: usize) -> SimpleOperand {SimpleOperand::Register(index, SimpleRegister::Single)}+pub(crate) const fn quad(index: usize) -> SimpleOperand {+ SimpleOperand::Register(index, SimpleRegister::Quad)+}++pub(crate) const fn vector(index: usize, arrangement: &'static str) -> SimpleOperand {+ SimpleOperand::Register(index, SimpleRegister::Vector(arrangement))+}+fn simple_register_name(register: PhysicalRegister, format: SimpleRegister) -> String {match format {SimpleRegister::Native => register.as_str().to_string(),@@ -96,6 +110,9 @@ fn simple_register_name(register: PhysicalRegister, format: SimpleRegister) -> SSimpleRegister::Pair(PairWidth::DoubleWord) => register.as_str().to_string(),SimpleRegister::Word => register.word_name(),SimpleRegister::Single => register.single_name(),+ SimpleRegister::Quad => register.quad_name(),+ SimpleRegister::Vector(arrangement) => format!("v{}.{arrangement}", register.number()),+ SimpleRegister::Numbered(prefix, suffix) => format!("{prefix}{}{suffix}", register.number()),}}@@ -211,7 +228,75 @@ pub(crate) fn resolve_label(op: &Operand, handler: &Handler) -> String {}}+/// The handler that the dispatch table entries without a handler of their own+/// point at.+fn fallback_handler_name(program: &MachineProgram) -> &str {+ program+ .dispatch+ .fallback+ .and_then(|fallback| program.functions.iter().find(|function| function.id == fallback))+ .map_or("fallback", |function| function.name.as_str())+}++fn emit_read_only_data_section(out: &mut String, program: &MachineProgram) {+ match program.target.object_format {+ ObjectFormat::MachO => w!(out, ".section __DATA,__const"),+ ObjectFormat::Elf => w!(out, ".section .data.rel.ro"),+ ObjectFormat::Coff => w!(out, ".section .rdata,\"dr\""),+ }+}++/// The dispatch tables of a raw-bytes program: the primary table indexed by+/// opcode byte, one table per prefix opcode indexed by sub-opcode, and the+/// handler ranges of the primary table.+fn emit_raw_bytes_dispatch_tables(out: &mut String, program: &MachineProgram) {+ emit_read_only_data_section(out, program);+ w!(out, ".p2align 3");+ let handler_names = program+ .functions+ .iter()+ .map(|handler| (handler.id, handler.name.as_str()))+ .collect::<HashMap<_, _>>();+ let fallback = fallback_handler_name(program);+ let name = |handler: &Option<crate::identity::HandlerId>| {+ handler+ .and_then(|handler| handler_names.get(&handler).copied())+ .unwrap_or(fallback)+ };+ let dispatch_table = program.interpreter_symbol("dispatch_table");+ w!(out, ".globl CSYM({dispatch_table})");+ w!(out, "CSYM({dispatch_table}):");+ w!(out, "asm_dispatch_table:");+ for index in 0..DISPATCH_TABLE_SIZE {+ let handler = program.dispatch_handlers.get(index).copied().flatten();+ w!(out, " .quad asm_handler_{}", name(&handler));+ }+ w!(out);+ for table in &program.dispatch.secondary {+ w!(out, "asm_dispatch_table_{:02x}:", table.prefix);+ for handler in &table.handlers {+ w!(out, " .quad asm_handler_{}", name(handler));+ }+ w!(out);+ }+ let handler_ranges = program.interpreter_symbol("handler_ranges");+ w!(out, ".globl CSYM({handler_ranges})");+ w!(out, ".p2align 3");+ w!(out, "CSYM({handler_ranges}):");+ for index in 0..DISPATCH_TABLE_SIZE {+ let handler = program.dispatch_handlers.get(index).copied().flatten();+ emit_handler_range(out, name(&handler));+ }+ w!(out);+ w!(out, ".text");+ w!(out);+}+pub(crate) fn emit_dispatch_tables(out: &mut String, program: &MachineProgram) {+ if program.profile.instruction_encoding() == crate::profile::InstructionEncoding::RawBytes {+ emit_raw_bytes_dispatch_tables(out, program);+ return;+ }match program.target.object_format {ObjectFormat::MachO => w!(out, ".section __DATA,__const"),ObjectFormat::Elf => w!(out, ".section .data.rel.ro"),@@ -220,7 +305,7 @@ pub(crate) fn emit_dispatch_tables(out: &mut String, program: &MachineProgram) {w!(out, ".p2align 3");// The runtime picks a dispatch table for each executable (see// VmDispatchTables), so both tables are global.- let dispatch_table = program.global_symbol("js_interpreter_dispatch_table");+ let dispatch_table = program.interpreter_symbol("dispatch_table");w!(out, ".globl CSYM({dispatch_table})");w!(out, "CSYM({dispatch_table}):");w!(out, "asm_dispatch_table:");@@ -241,7 +326,7 @@ pub(crate) fn emit_dispatch_tables(out: &mut String, program: &MachineProgram) {}w!(out);- let debug_dispatch_table = program.global_symbol("js_interpreter_debug_dispatch_table");+ let debug_dispatch_table = program.interpreter_symbol("debug_dispatch_table");w!(out, ".globl CSYM({debug_dispatch_table})");w!(out, "CSYM({debug_dispatch_table}):");w!(out, "asm_debug_dispatch_table:");@@ -250,7 +335,7 @@ pub(crate) fn emit_dispatch_tables(out: &mut String, program: &MachineProgram) {}w!(out);- let handler_ranges = program.global_symbol("js_interpreter_handler_ranges");+ let handler_ranges = program.interpreter_symbol("handler_ranges");w!(out, ".globl CSYM({handler_ranges})");w!(out, ".p2align 3");w!(out, "CSYM({handler_ranges}):");@@ -353,13 +438,20 @@ pub(crate) fn emit_program(&mut out,program.target.object_format,seh_indentation,- &program.global_symbol("js_interpreter"),+ &program.interpreter_symbol(""),);emit_entry(&mut out);emit_fallback(&mut out);emit_handler_bodies(&mut out);emit_exit(&mut out);emit_proc_end(&mut out, program.target.object_format);+ if program.profile == crate::Profile::WebAssembly {+ // Runtimes recognize faults inside the interpreter by its code range. Mach-O does not allow global labels+ // inside a function's unwind information, so the end follows it.+ let end = program.interpreter_symbol("end");+ w!(out, ".globl CSYM({end})");+ w!(out, "CSYM({end}):");+ }emit_file_trailer(&mut out, program.target.object_format);out}diff --git a/Libraries/LibJS/Flap/src/target/finalize.rs b/Libraries/LibJS/Flap/src/target/finalize.rsindex 4b52b63a215..7c5d39bddb8 100644--- a/Libraries/LibJS/Flap/src/target/finalize.rs+++ b/Libraries/LibJS/Flap/src/target/finalize.rs@@ -67,6 +67,7 @@ fn finalize_function(function: AllocatedFunction, runtime: &RuntimeConstants) ->has_jscvt: false,enable_assertions: false,profiling: false,+ profile: crate::Profile::JavaScript,};finalize_function_for_target(function, runtime, &options)}@@ -92,7 +93,9 @@ pub(crate) fn finalize_program(let machine = MachineProgram {runtime,dispatch_handlers: program.dispatch_handlers,+ dispatch: program.dispatch,target,+ profile: options.profile,profiling: options.profiling,functions,};@@ -312,6 +315,14 @@ fn finalize_instruction(return Ok(());}+ if let Operation::Branch(BranchOperation::OrderedFloat(comparison)) = operation {+ let operands = &instruction.operands;+ let [lhs, rhs] = [operands.physical_register(0), operands.physical_register(1)];+ let target = operands.label(2);+ emit.last_fp_compare = None;+ return backend.branch_ordered_float(emit, lhs, rhs, comparison, &target);+ }+if let Operation::Branch(BranchOperation::Float(condition)) = operation {finalize_float_branch(backend, emit, condition, &instruction.operands);return Ok(());@@ -384,6 +395,9 @@ fn finalize_instruction(Operation::Control(ControlOperation::GotoHandler) => {backend.goto_handler(emit, operands)?;}+ Operation::Control(ControlOperation::DispatchSecondary) => {+ backend.dispatch_secondary(emit, operands)?;+ }Operation::Control(ControlOperation::JumpBytecode) => {backend.goto_bytecode_target(emit, operands)?;}@@ -439,6 +453,9 @@ fn finalize_instruction(return emit.error("operation Cold was not expanded into legal machine instructions");}Operation::Modulo(width) => backend.finalize_divide(emit, width, operands),+ Operation::Numeric(operation) => backend.finalize_numeric(emit, operation, operands)?,+ Operation::Vector(operation) => backend.finalize_vector(emit, operation, operands)?,+ Operation::Atomic(operation) => backend.finalize_atomic(emit, operation, operands)?,_ => emit.output.push(MachineInstruction {opcode,operands: instruction.operands,@@ -493,6 +510,7 @@ mod tests {has_jscvt: false,enable_assertions: false,profiling: false,+ profile: crate::Profile::JavaScript,}}diff --git a/Libraries/LibJS/Flap/src/target/finalize_support.rs b/Libraries/LibJS/Flap/src/target/finalize_support.rsindex 2cd0746fd45..e8ef2b9821b 100644--- a/Libraries/LibJS/Flap/src/target/finalize_support.rs+++ b/Libraries/LibJS/Flap/src/target/finalize_support.rs@@ -37,6 +37,8 @@ pub(crate) struct Emit<'a> {/// handlers switch to the dispatch table of the frame they continue in/// (see `VmDispatchTables`).pub(crate) profiling: bool,+ /// The virtual machine the handlers are compiled for.+ pub(crate) profile: crate::Profile,/// Distinguishes the local labels a single function generates.unique_counter: u64,/// The operands of the most recent floating-point comparison, so that a@@ -62,6 +64,7 @@ impl<'a> Emit<'a> {enable_assertions: options.enable_assertions,has_jscvt: options.has_jscvt,profiling: options.profiling,+ profile: options.profile,unique_counter: 0,last_fp_compare: None,}diff --git a/Libraries/LibJS/Flap/src/target/ir.rs b/Libraries/LibJS/Flap/src/target/ir.rsindex 0d8b4b7a40a..1fa2f92a909 100644--- a/Libraries/LibJS/Flap/src/target/ir.rs+++ b/Libraries/LibJS/Flap/src/target/ir.rs@@ -7,7 +7,6 @@//! Legal target IR before and after physical register allocation.use crate::Architecture;-use crate::frontend::layout::KnownLayoutConstant;use crate::identity::HandlerId;#[cfg(test)]pub(crate) use crate::low_ir::MemoryAddress;@@ -231,6 +230,7 @@ pub(crate) type AllocatedInstruction = crate::low_ir::Instruction<AllocatedOperapub(crate) use crate::low_ir::RuntimeConstants;/// A legal target function before physical register allocation.+#[derive(Clone)]pub(crate) struct Function {pub(crate) id: HandlerId,pub(crate) name: String,@@ -245,6 +245,7 @@ pub(crate) struct Function {pub struct Program {pub(crate) runtime: RuntimeConstants,pub(crate) dispatch_handlers: Vec<Option<HandlerId>>,+ pub(crate) dispatch: crate::identity::DispatchLayout,pub(crate) architecture: Architecture,pub(crate) functions: Vec<Function>,}@@ -262,6 +263,7 @@ pub(crate) struct AllocatedFunction {pub struct AllocatedProgram {pub(crate) runtime: RuntimeConstants,pub(crate) dispatch_handlers: Vec<Option<HandlerId>>,+ pub(crate) dispatch: crate::identity::DispatchLayout,pub(crate) architecture: Architecture,pub(crate) functions: Vec<AllocatedFunction>,}@@ -316,7 +318,9 @@ pub(crate) struct MachineFunction {pub struct MachineProgram {pub(crate) runtime: RuntimeConstants,pub(crate) dispatch_handlers: Vec<Option<HandlerId>>,+ pub(crate) dispatch: crate::identity::DispatchLayout,pub(crate) target: crate::Target,+ pub(crate) profile: crate::Profile,pub(crate) profiling: bool,pub(crate) functions: Vec<MachineFunction>,}@@ -330,35 +334,24 @@ impl MachineProgram {name.to_string()}}++ /// The global symbol of the interpreter's entry point, or with a+ /// `suffix`, of one of its tables.+ pub(crate) fn interpreter_symbol(&self, suffix: &str) -> String {+ let prefix = self.profile.symbol_prefix();+ if suffix.is_empty() {+ self.global_symbol(prefix)+ } else {+ self.global_symbol(&format!("{prefix}_{suffix}"))+ }+ }}impl MachineProgram {pub(crate) fn missing_required_runtime_constant(&self) -> Option<&'static str> {- use KnownLayoutConstant::*;-- let architecture_constants: &[KnownLayoutConstant] = match self.target.architecture {- Architecture::X86_64 => &[],- Architecture::Aarch64 => &[Int32Tag, BooleanTag],- };- architecture_constants+ self.profile+ .required_runtime_constants(self.target.architecture).iter()- .chain(- [- SlowPathContinuationBit,- VmRunningExecutionContext,- VmBreakpointController,- VmHeapRegionBase,- ExecutionContextExecutable,- ExecutionContextProgramCounter,- ExecutableBytecodeData,- ExecutableDispatchTableIndex,- VmDispatchTables,- DispatchTableIndexMask,- SizeOfExecutionContext,- CanonicalNanBits,- ]- .iter(),- ).find_map(|constant| self.runtime.get(*constant).is_none().then_some(constant.name()))}}diff --git a/Libraries/LibJS/Flap/src/target/mod.rs b/Libraries/LibJS/Flap/src/target/mod.rsindex 0fd3409282c..7f9f8718ec7 100644--- a/Libraries/LibJS/Flap/src/target/mod.rs+++ b/Libraries/LibJS/Flap/src/target/mod.rs@@ -17,5 +17,6 @@ pub(crate) mod ir;pub(crate) mod machine_verify;pub(crate) mod registers;pub(crate) mod selection;+pub(crate) mod spill;pub(crate) mod verify;pub(crate) mod x86_64;diff --git a/Libraries/LibJS/Flap/src/target/registers.rs b/Libraries/LibJS/Flap/src/target/registers.rsindex 8eb68c81565..59779d6958d 100644--- a/Libraries/LibJS/Flap/src/target/registers.rs+++ b/Libraries/LibJS/Flap/src/target/registers.rs@@ -91,6 +91,14 @@ impl PhysicalRegister {format!("s{}", self.number)}+ /// The name of the whole 128-bit register: q0 on AArch64, and the native name on x86-64.+ pub(crate) fn quad_name(self) -> String {+ match self.architecture {+ Architecture::Aarch64 => format!("q{}", self.number),+ Architecture::X86_64 => self.name.to_string(),+ }+ }+pub(crate) fn integer_name(self, width: IntegerWidth) -> String {match (self.architecture, width) {(_, IntegerWidth::U64) => self.as_str().to_string(),@@ -228,6 +236,9 @@ pub(crate) mod aarch64 {D7 = fpr("d7", 7);D8 = fpr("d8", 8);D16 = fpr("d16", 16);+ D17 = fpr("d17", 17);+ D18 = fpr("d18", 18);+ D19 = fpr("d19", 19);}}@@ -238,6 +249,13 @@ pub(crate) mod aarch64 {/// is derived by subtracting the fixed execution-context size. AArch64 keeps/// the heap region base in x24.///+/// The WebAssembly profile reuses the same callee-saved registers under its+/// own names: r13 holds the instruction pointer `ip`, r14 the side-table+/// pointer `stp`, rbx the value stack pointer `vsp`, r15 the base of memory 0,+/// and rbp the frame pointer `fp` of the running function. On AArch64, x21+/// holds `ip`, x26 `stp`, x27 `vsp`, x28 the base of memory 0, and x29 `fp`;+/// v16 to v19 are scratch for the vector operations' expansions.+////// `temporaries` and `fp_temporaries` are the allocatable register pools./// Registers used as hidden instruction-expansion scratch are deliberately/// excluded from these lists.@@ -270,6 +288,10 @@ pub(crate) const X86_64_REGS: TargetRegisterInfo = TargetRegisterInfo {Some(x86_64::R15),Some(x86_64::RSP),Some(x86_64::RBP),+ Some(x86_64::R13),+ Some(x86_64::R14),+ Some(x86_64::RBX),+ Some(x86_64::R15),],temporaries: &[x86_64::RAX,@@ -314,6 +336,10 @@ pub(crate) const AARCH64_REGS: TargetRegisterInfo = TargetRegisterInfo {Some(aarch64::X24),Some(aarch64::SP),Some(aarch64::X29),+ Some(aarch64::X21),+ Some(aarch64::X26),+ Some(aarch64::X27),+ Some(aarch64::X28),],// x9 and x10 are reserved as instruction-expansion scratch, and x16 and// x17 are the procedure call standard's veneer registers, which thediff --git a/Libraries/LibJS/Flap/src/target/selection.rs b/Libraries/LibJS/Flap/src/target/selection.rsindex 5c9872909f3..cb7c9cf73b6 100644--- a/Libraries/LibJS/Flap/src/target/selection.rs+++ b/Libraries/LibJS/Flap/src/target/selection.rs@@ -31,6 +31,9 @@ pub(crate) fn select_program(orient_commutative_updates(&mut handler.instructions);split_rematerializable_live_ranges_across_calls(&mut handler.instructions);materialize_constant_register_inputs(&mut handler.instructions);+ if architecture == Architecture::X86_64 {+ materialize_wide_immediates(&mut handler.instructions);+ }// Splitting and constant materialization create new virtual registers, so interning must follow them.let virtual_registers = low_ir::intern_virtual_registers(handler.id, &mut handler.instructions);let mut instructions = Vec::with_capacity(handler.instructions.len());@@ -98,6 +101,7 @@ pub(crate) fn select_program(Ok(Program {runtime: program.runtime,dispatch_handlers: program.dispatch_handlers,+ dispatch: program.dispatch,architecture,functions,})@@ -127,6 +131,92 @@ fn materialize_constant_register_inputs(instructions: &mut Vec<low_ir::Instructi*instructions = materialized;}+/// x86-64 compares, combines, and multiplies 64-bit registers only with sign-extended 32-bit immediates, so other+/// immediates go into a register first, which also spares the operations scratch registers of their own.+fn materialize_wide_immediates(instructions: &mut Vec<low_ir::Instruction>) {+ let mut materialized = Vec::with_capacity(instructions.len());+ for (instruction_index, mut instruction) in std::mem::take(instructions).into_iter().enumerate() {+ let compares_64_bits = matches!(+ instruction.opcode,+ Operation::Branch(+ crate::intrinsic::BranchOperation::Equality {+ width: IntegerWidth::U64,+ ..+ } | crate::intrinsic::BranchOperation::Ordered {+ width: IntegerWidth::U64,+ ..+ }+ ) | Operation::AssertBranch(+ crate::intrinsic::BranchOperation::Equality {+ width: IntegerWidth::U64,+ ..+ } | crate::intrinsic::BranchOperation::Ordered {+ width: IntegerWidth::U64,+ ..+ }+ )+ );+ let combines_64_bits = matches!(+ instruction.opcode,+ Operation::IntegerBinary {+ operation: crate::intrinsic::IntegerBinaryOperation::Binary(+ crate::target::description::BinaryOperation::Add+ | crate::target::description::BinaryOperation::Subtract+ | crate::target::description::BinaryOperation::And+ | crate::target::description::BinaryOperation::Or+ | crate::target::description::BinaryOperation::Xor+ ),+ width: IntegerWidth::U64,+ }+ );+ // Masking with 0xffffffff is a 32-bit move, which needs no immediate.+ let is_low_half_mask = matches!(+ instruction.opcode,+ Operation::IntegerBinary {+ operation: crate::intrinsic::IntegerBinaryOperation::Binary(+ crate::target::description::BinaryOperation::And+ ),+ ..+ }+ ) && matches!(instruction.operands.get(1), Some(LowOperand::Immediate(value)) if *value as u64 == 0xffff_ffff);+ let multiplies_64_bits = matches!(+ instruction.opcode,+ Operation::IntegerBinary {+ operation: crate::intrinsic::IntegerBinaryOperation::Binary(+ crate::target::description::BinaryOperation::Multiply+ ),+ width: IntegerWidth::U64,+ }+ );+ // A multiplication can take its immediate in any input position, the others take it second.+ let candidates = if multiplies_64_bits {+ 1..instruction.operands.len()+ } else if compares_64_bits || combines_64_bits {+ 1..instruction.operands.len().min(2)+ } else {+ 0..0+ };+ for position in candidates {+ if is_low_half_mask {+ break;+ }+ let operand = &mut instruction.operands[position];+ if !matches!(operand, LowOperand::Immediate(value) if i32::try_from(*value).is_err()) {+ continue;+ }+ let register = LowOperand::VirtualRegister(low_ir::VirtualRegister::new(format!(+ "wide_immediate_{instruction_index}_{position}"+ )));+ materialized.push(low_ir::Instruction {+ opcode: Operation::Move(IntegerWidth::U64),+ operands: vec![register.clone(), std::mem::replace(operand, register)],+ });+ }+ materialized.push(instruction);+ }+ *instructions = materialized;+}+fn legalize_operand(operand: &mut LowOperand,operation: Operation,diff --git a/Libraries/LibJS/Flap/src/target/spill.rs b/Libraries/LibJS/Flap/src/target/spill.rsnew file mode 100644index 00000000000..e5976ccf929--- /dev/null+++ b/Libraries/LibJS/Flap/src/target/spill.rs@@ -0,0 +1,398 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Spilling for handlers that do not fit in the allocatable registers.+//!+//! A runtime that keeps a spill area at a fixed offset from the machine stack pointer describes it with the+//! SPILL_AREA_OFFSET and SPILL_AREA_SLOTS layout constants. Without them, allocation stays spill-free and fails+//! instead. A spilled value lives in its slot: every instruction that reads it loads it into a fresh register first,+//! and every instruction that writes it stores that register afterwards. The slot is addressed from the stack pointer,+//! so a value that is live across a write of a register to `sp` moves to the same slot from the new stack pointer+//! right before the write. Values move in the order they were spilled, which is the order of their slots, so that is+//! only safe when the write lowers `sp`, which is what moving into a new frame does.++use crate::frontend::layout::KnownLayoutConstant;+use crate::low_ir::analysis::virtual_register_access;+use crate::low_ir::{AddressDisplacement, AddressRegister, MemoryAddress, VirtualRegister};+use crate::target::description::{MemoryWidth, OperandKind, Operation};+use crate::target::ir::{Function, Instruction, Operand, RuntimeConstants};+use crate::types::{InterpreterRegister, RegisterClass};++#[derive(Debug, Clone, Copy)]+pub(crate) struct SpillArea {+ pub(crate) offset: i64,+ pub(crate) slots: u32,+}++impl SpillArea {+ pub(crate) fn of(runtime: &RuntimeConstants) -> Option<Self> {+ let offset = runtime.get(KnownLayoutConstant::SpillAreaOffset)?;+ let slots = runtime.get(KnownLayoutConstant::SpillAreaSlots)?;+ Some(Self {+ offset,+ slots: u32::try_from(slots).ok()?,+ })+ }+}++#[derive(Debug, Default, Clone)]+struct Candidate {+ first: usize,+ last: usize,+ occurrences: usize,+ definitions: usize,+ excluded: bool,+ /// The interpreter register the value is a copy of, if its only definition copies one.+ copy_of: Option<InterpreterRegister>,+}++fn writes_interpreter_register(instruction: &Instruction, register: InterpreterRegister) -> bool {+ let description = instruction.opcode.description();+ let count = instruction.operands.len();+ instruction.operands.iter().enumerate().any(|(position, operand)| {+ *operand == Operand::InterpreterRegister(register)+ && matches!(+ description.operand_kind(position, count),+ Some(OperandKind::GprOut | OperandKind::GprInOut | OperandKind::RegisterOut)+ )+ })+}++fn writes_stack_pointer(instruction: &Instruction) -> bool {+ writes_interpreter_register(instruction, InterpreterRegister::StackPointer)+}++/// Give every operand that must be in a particular register a virtual register of its own, connected to the value by+/// moves, so that the value itself is free to live elsewhere. Returns false if there was no such operand.+pub(crate) fn isolate_fixed_operands(function: &mut Function) -> bool {+ let architecture = function.architecture;+ let instructions = std::mem::take(&mut function.instructions);+ let mut rewritten = Vec::with_capacity(instructions.len());+ let mut changed = false;+ for (index, mut instruction) in instructions.into_iter().enumerate() {+ let fixed = instruction.opcode.description().arch(architecture).fixed_operands;+ if fixed.is_empty() {+ rewritten.push(instruction);+ continue;+ }+ let access = virtual_register_access(&instruction, Some(architecture));+ let mut after = Vec::new();+ for &(position, _) in fixed {+ let Some(Operand::VirtualRegister(register)) = instruction.operands.get(position).cloned() else {+ continue;+ };+ if register.class() != RegisterClass::GeneralPurpose {+ continue;+ }+ let isolated = VirtualRegister::interned(+ format!("fixed_{index}_{position}"),+ function.id,+ function.virtual_registers.len() as u32,+ register.class(),+ );+ function.virtual_registers.push(isolated.clone());+ let move_instruction = |destination: &VirtualRegister, source: &VirtualRegister| {+ let mut operands = vec![+ Operand::VirtualRegister(destination.clone()),+ Operand::VirtualRegister(source.clone()),+ ];+ let opcode = Operation::Move(crate::target::description::IntegerWidth::U64)+ .select_for_operands(architecture, &operands);+ opcode.add_contract_operands(&mut operands);+ Instruction { opcode, operands }+ };+ if access.reads.contains(®ister) {+ rewritten.push(move_instruction(&isolated, ®ister));+ }+ if access.definitions.contains(®ister) {+ after.push(move_instruction(®ister, &isolated));+ }+ instruction.operands[position] = Operand::VirtualRegister(isolated);+ changed = true;+ }+ rewritten.push(instruction);+ rewritten.extend(after);+ }+ function.instructions = rewritten;+ changed+}++/// Rewrite one virtual register of `class` in `function` to live in the spill area from slot `next_slot` on, which+/// then moves past the slots it took. A vector takes two slots, starting on a 16-byte boundary. Returns false if no+/// register of that class can be spilled, or its slots do not fit.+pub(crate) fn spill_one_register(+ function: &mut Function,+ area: &SpillArea,+ next_slot: &mut u32,+ class: RegisterClass,+) -> bool {+ let mut slot = *next_slot;+ let slot_count = if class == RegisterClass::Vector { 2 } else { 1 };+ if class == RegisterClass::Vector && (area.offset + i64::from(slot) * 8) % 16 != 0 {+ slot += 1;+ }+ let slots_left = slot + slot_count <= area.slots;+ let architecture = function.architecture;+ let mut candidates = vec![Candidate::default(); function.virtual_registers.len()];+ let mut stack_pointer_writes = Vec::new();+ // The register each write to `sp` copies, if it is a plain move of one.+ let mut stack_pointer_sources = Vec::new();+ let mut calls = Vec::new();+ for (index, instruction) in function.instructions.iter().enumerate() {+ if writes_stack_pointer(instruction) {+ stack_pointer_writes.push(index);+ let source = match (instruction.opcode.operation(), instruction.operands.as_slice()) {+ (+ Operation::Move(crate::target::description::IntegerWidth::U64),+ [+ Operand::InterpreterRegister(InterpreterRegister::StackPointer),+ Operand::VirtualRegister(source),+ ],+ ) => Some(AddressRegister::Virtual(source.clone())),+ (+ Operation::Move(crate::target::description::IntegerWidth::U64),+ [+ Operand::InterpreterRegister(InterpreterRegister::StackPointer),+ Operand::InterpreterRegister(source),+ ],+ ) => Some(AddressRegister::Interpreter(*source)),+ _ => None,+ };+ stack_pointer_sources.push(source);+ }+ if instruction.opcode.description().is_call {+ calls.push(index);+ }+ let has_label = instruction+ .operands+ .iter()+ .any(|operand| matches!(operand, Operand::Label(_)));+ let access = virtual_register_access(instruction, Some(architecture));+ let copied_register = match (instruction.opcode.operation(), instruction.operands.as_slice()) {+ (+ Operation::Move(crate::target::description::IntegerWidth::U64),+ [Operand::VirtualRegister(_), Operand::InterpreterRegister(register)],+ ) => Some(*register),+ _ => None,+ };+ for register in &access.definitions {+ if let Some(id) = register.id() {+ let candidate = &mut candidates[id.index() as usize];+ candidate.definitions += 1;+ candidate.copy_of = copied_register;+ }+ }+ for operand in &instruction.operands {+ let mut note = |register: &VirtualRegister, excluded: bool| {+ let Some(id) = register.id() else {+ return;+ };+ let candidate = &mut candidates[id.index() as usize];+ if candidate.occurrences == 0 {+ candidate.first = index;+ }+ candidate.last = index;+ candidate.occurrences += 1;+ candidate.excluded |= excluded;+ };+ match operand {+ Operand::VirtualRegister(register) => {+ let defines_on_a_branch = has_label && access.definitions.contains(register);+ note(register, defines_on_a_branch);+ }+ Operand::Address(address) => {+ for register in [&address.base].into_iter().chain(address.index.as_ref()) {+ if let AddressRegister::Virtual(register) = register {+ note(register, false);+ }+ }+ }+ _ => {}+ }+ }+ }++ // A copy of an interpreter register can be reread from that register instead of a slot, as long as nothing+ // writes the register before the copy's last use.+ let rematerializes = |candidate: &Candidate| {+ candidate.definitions == 1+ && candidate.copy_of.is_some_and(|register| {+ function.instructions[candidate.first..=candidate.last]+ .iter()+ .all(|instruction| !writes_interpreter_register(instruction, register))+ })+ };+ let live_after = crate::target::allocator::live_after_each_instruction(function).unwrap_or_default();+ let live_after_instruction = |instruction: usize, register: usize| {+ live_after+ .get(instruction)+ .is_some_and(|live| live.binary_search(&(register as u32)).is_ok())+ };+ let mut best: Option<(usize, u64)> = None;+ for (index, candidate) in candidates.iter().enumerate() {+ let register = &function.virtual_registers[index];+ let rematerialized = rematerializes(candidate);+ if candidate.excluded+ || (!slots_left && !rematerialized)+ || candidate.occurrences == 0+ || register.class() != class+ || register.to_string().starts_with("spill_")+ || (!rematerialized+ && stack_pointer_writes+ .iter()+ .zip(&stack_pointer_sources)+ .any(|(&write, source)| {+ // The new stack pointer must be at hand to move the value, so it cannot be the value itself.+ live_after_instruction(write, index)+ && source.as_ref().is_none_or(+ |source| matches!(source, AddressRegister::Virtual(source) if source == register),+ )+ }))+ {+ continue;+ }+ // Prefer values live across a call, which clobbers every register they could be in, then copies of+ // interpreter registers, which cost nothing to reread, then long-lived values that are rarely used: spilling+ // them frees a register for longest at the cost of the fewest loads and stores.+ let mut score = ((candidate.last - candidate.first) as u64 * 1024) / candidate.occurrences as u64;+ if rematerialized {+ score += 1 << 40;+ }+ if calls.iter().any(|&call| live_after_instruction(call, index)) {+ score += 1 << 41;+ }+ // Moving a value into a new frame costs a load and a store at every write to sp it lives across.+ if !rematerialized+ && stack_pointer_writes+ .iter()+ .any(|&write| live_after_instruction(write, index))+ {+ score /= 4;+ }+ if best.is_none_or(|(_, best_score)| score > best_score) {+ best = Some((index, score));+ }+ }+ let Some((victim_index, _)) = best else {+ return false;+ };+ let victim = function.virtual_registers[victim_index].clone();+ let rematerialized_register = rematerializes(&candidates[victim_index])+ .then(|| candidates[victim_index].copy_of)+ .flatten();+ // A value that is reread from its interpreter register needs no slot.+ if rematerialized_register.is_none() {+ *next_slot = slot + slot_count;+ }++ let slot_address = Operand::Address(MemoryAddress {+ base: AddressRegister::Interpreter(InterpreterRegister::StackPointer),+ index: None,+ scale: None,+ displacement: Some(AddressDisplacement::Immediate(area.offset + i64::from(slot) * 8)),+ });+ let slot_width = match class {+ RegisterClass::GeneralPurpose => MemoryWidth::DoubleWord,+ RegisterClass::FloatingPoint => MemoryWidth::Double,+ RegisterClass::Vector => MemoryWidth::Vector,+ };+ let instructions = std::mem::take(&mut function.instructions);+ let mut rewritten = Vec::with_capacity(instructions.len() + 8);+ for (index, mut instruction) in instructions.into_iter().enumerate() {+ // Before a write to `sp` the value is live across, move it to its slot in the new frame.+ let moves_frames = rematerialized_register.is_none() && live_after_instruction(index, victim_index);+ if moves_frames && let Some(position) = stack_pointer_writes.iter().position(|&write| write == index) {+ let new_stack_pointer = stack_pointer_sources[position]+ .clone()+ .expect("only values live across moves into sp are spilled");+ let new_slot = Operand::Address(MemoryAddress {+ base: new_stack_pointer,+ index: None,+ scale: None,+ displacement: Some(AddressDisplacement::Immediate(area.offset + i64::from(slot) * 8)),+ });+ let carrier = VirtualRegister::interned(+ format!("spill_{slot}_{index}_move"),+ function.id,+ function.virtual_registers.len() as u32,+ class,+ );+ function.virtual_registers.push(carrier.clone());+ let mut operands = vec![Operand::VirtualRegister(carrier.clone()), slot_address.clone()];+ let opcode = Operation::load(slot_width, false).select_for_operands(architecture, &operands);+ opcode.add_contract_operands(&mut operands);+ rewritten.push(Instruction { opcode, operands });+ let mut operands = vec![new_slot, Operand::VirtualRegister(carrier)];+ let opcode = Operation::store(slot_width).select_for_operands(architecture, &operands);+ opcode.add_contract_operands(&mut operands);+ rewritten.push(Instruction { opcode, operands });+ }+ let access = virtual_register_access(&instruction, Some(architecture));+ let reads = access.reads.contains(&victim)+ || instruction.operands.iter().any(|operand| {+ matches!(operand, Operand::Address(address)+ if [&address.base].into_iter().chain(address.index.as_ref()).any(|register| {+ matches!(register, AddressRegister::Virtual(register) if *register == victim)+ }))+ });+ let defines = access.definitions.contains(&victim);+ if !reads && !defines {+ rewritten.push(instruction);+ continue;+ }+ let replacement = VirtualRegister::interned(+ format!("spill_{slot}_{index}"),+ function.id,+ function.virtual_registers.len() as u32,+ class,+ );+ function.virtual_registers.push(replacement.clone());+ for operand in &mut instruction.operands {+ match operand {+ Operand::VirtualRegister(register) if *register == victim => *register = replacement.clone(),+ Operand::Address(address) => {+ for register in std::iter::once(&mut address.base).chain(address.index.as_mut()) {+ if matches!(register, AddressRegister::Virtual(register) if *register == victim) {+ *register = AddressRegister::Virtual(replacement.clone());+ }+ }+ }+ _ => {}+ }+ }+ if let Some(register) = rematerialized_register {+ if defines {+ // The copy itself goes away; every read rereads the register.+ continue;+ }+ let mut operands = vec![+ Operand::VirtualRegister(replacement.clone()),+ Operand::InterpreterRegister(register),+ ];+ let opcode = Operation::Move(crate::target::description::IntegerWidth::U64)+ .select_for_operands(architecture, &operands);+ opcode.add_contract_operands(&mut operands);+ rewritten.push(Instruction { opcode, operands });+ rewritten.push(instruction);+ continue;+ }+ if reads {+ let mut operands = vec![Operand::VirtualRegister(replacement.clone()), slot_address.clone()];+ let opcode = Operation::load(slot_width, false).select_for_operands(architecture, &operands);+ opcode.add_contract_operands(&mut operands);+ rewritten.push(Instruction { opcode, operands });+ }+ rewritten.push(instruction);+ if defines {+ let mut operands = vec![slot_address.clone(), Operand::VirtualRegister(replacement)];+ let opcode = Operation::store(slot_width).select_for_operands(architecture, &operands);+ opcode.add_contract_operands(&mut operands);+ rewritten.push(Instruction { opcode, operands });+ }+ }+ function.instructions = rewritten;+ true+}diff --git a/Libraries/LibJS/Flap/src/target/verify.rs b/Libraries/LibJS/Flap/src/target/verify.rsindex 67598784057..2f21cf62d86 100644--- a/Libraries/LibJS/Flap/src/target/verify.rs+++ b/Libraries/LibJS/Flap/src/target/verify.rs@@ -387,17 +387,6 @@ mod tests {Operand::PhysicalRegister(aarch64::X1),],);- assert_invalid_arity(- Architecture::X86_64,- Operation::IntegerBinary {- operation: IntegerBinaryOperation::Binary(BinaryOperation::And),- width: IntegerWidth::U64,- },- vec![- Operand::PhysicalRegister(x86_64::RDX),- Operand::Immediate(0x3_ffff_ffff),- ],- );assert_invalid_arity(Architecture::Aarch64,Operation::load_pair(PairWidth::DoubleWord),diff --git a/Libraries/LibJS/Flap/src/target/x86_64.rs b/Libraries/LibJS/Flap/src/target/x86_64.rsindex 1424bb903eb..514c9cd61a1 100644--- a/Libraries/LibJS/Flap/src/target/x86_64.rs+++ b/Libraries/LibJS/Flap/src/target/x86_64.rs@@ -24,6 +24,7 @@ use super::ir::{};use super::machine_verify::{define_machine_opcodes, operands_match};use crate::frontend::layout::KnownLayoutConstant;+use crate::intrinsic::{AtomicOperation, VectorOperation};use crate::runtime_interface::{BREAKPOINT_CHECK, FALLBACK_HANDLER};use crate::{Architecture, CompileOptions, ObjectFormat};use std::fmt::Write;@@ -81,6 +82,19 @@ pub(crate) enum FloatConversion {DoubleToSigned64Truncate,}+fn atomic_size_prefix(width: IntegerWidth) -> &'static str {+ match width {+ IntegerWidth::U8 => "BYTE PTR ",+ IntegerWidth::U16 => "WORD PTR ",+ IntegerWidth::U32 => "DWORD PTR ",+ IntegerWidth::U64 => "QWORD PTR ",+ }+}++fn is_vector_register(operand: &super::ir::Operand) -> bool {+ matches!(operand, super::ir::Operand::VirtualRegister(register) if register.class() == crate::types::RegisterClass::Vector)+}+fn load_instruction(width: MemoryWidth, signed: bool) -> SimpleInstruction {match (width, signed) {(MemoryWidth::DoubleWord, false) => {@@ -89,6 +103,12 @@ fn load_instruction(width: MemoryWidth, signed: bool) -> SimpleInstruction {(MemoryWidth::Float, false) => {simple!("movss"; native(0), SimpleOperand::Resolved(1, "DWORD PTR "))}+ (MemoryWidth::Double, false) => {+ simple!("movsd"; native(0), SimpleOperand::Resolved(1, "QWORD PTR "))+ }+ (MemoryWidth::Vector, false) => {+ simple!("movdqu"; native(0), SimpleOperand::Resolved(1, "XMMWORD PTR "))+ }(MemoryWidth::Word, false) => {simple!("mov"; word(0), SimpleOperand::Resolved(1, "DWORD PTR "))}@@ -104,7 +124,14 @@ fn load_instruction(width: MemoryWidth, signed: bool) -> SimpleInstruction {(MemoryWidth::Byte, true) => {simple!("movsx"; word(0), SimpleOperand::Resolved(1, "BYTE PTR "))}- (MemoryWidth::Word | MemoryWidth::DoubleWord | MemoryWidth::Float, true) => {+ (+ MemoryWidth::Word+ | MemoryWidth::DoubleWord+ | MemoryWidth::Float+ | MemoryWidth::Double+ | MemoryWidth::Vector,+ true,+ ) => {unreachable!("unsupported finalized x86-64 signed load")}}@@ -135,6 +162,12 @@ fn store_instruction(width: MemoryWidth) -> SimpleInstruction {MemoryWidth::Float => {simple!("movss"; SimpleOperand::Resolved(0, "DWORD PTR "), native(1))}+ MemoryWidth::Double => {+ simple!("movsd"; SimpleOperand::Resolved(0, "QWORD PTR "), native(1))+ }+ MemoryWidth::Vector => {+ simple!("movdqu"; SimpleOperand::Resolved(0, "XMMWORD PTR "), native(1))+ }}}@@ -161,7 +194,7 @@ define_machine_opcodes! {[LoadValuesAddress] => Self::LoadValuesAddress => [[R, A]];[Load { width: MemoryWidth, signed: bool }] => opcode @ Self::Load { width, signed } => {match opcode {- Self::Load { width: MemoryWidth::Float, .. } => operands_match(operands, &[FR, A]),+ Self::Load { width: MemoryWidth::Float | MemoryWidth::Double | MemoryWidth::Vector, .. } => operands_match(operands, &[FR, A]),_ => operands_match(operands, &[R, A]),}} encoding {@@ -170,13 +203,13 @@ define_machine_opcodes! {} printing load_instruction(width, signed);[LoadExecutionContext { width: MemoryWidth, signed: bool }] => opcode @ Self::LoadExecutionContext { .. } => {match opcode {- Self::LoadExecutionContext { width: MemoryWidth::Float, .. } => operands_match(operands, &[FR, A]),+ Self::LoadExecutionContext { width: MemoryWidth::Float | MemoryWidth::Double | MemoryWidth::Vector, .. } => operands_match(operands, &[FR, A]),_ => operands_match(operands, &[R, A]),}};[LoadAdditiveDisplacement { width: MemoryWidth, signed: bool }] => opcode @ Self::LoadAdditiveDisplacement { width, signed } => {match opcode {- Self::LoadAdditiveDisplacement { width: MemoryWidth::Float, .. } => operands_match(operands, &[FR, A]),+ Self::LoadAdditiveDisplacement { width: MemoryWidth::Float | MemoryWidth::Double | MemoryWidth::Vector, .. } => operands_match(operands, &[FR, A]),_ => operands_match(operands, &[R, A]),}} encoding {@@ -186,13 +219,13 @@ define_machine_opcodes! {[StoreLargeImmediate(MemoryWidth)] => Self::StoreLargeImmediate(_) => any;[Store(MemoryWidth)] => opcode @ Self::Store(width) => {match opcode {- Self::Store(MemoryWidth::Float) => operands_match(operands, &[A, FR]),+ Self::Store(MemoryWidth::Float | MemoryWidth::Double | MemoryWidth::Vector) => operands_match(operands, &[A, FR]),_ => operands_match(operands, &[A, RI]),}} printing store_instruction(width);[StoreAdditiveDisplacement(MemoryWidth)] => opcode @ Self::StoreAdditiveDisplacement(width) => {match opcode {- Self::StoreAdditiveDisplacement(MemoryWidth::Float) => operands_match(operands, &[A, FR]),+ Self::StoreAdditiveDisplacement(MemoryWidth::Float | MemoryWidth::Double | MemoryWidth::Vector) => operands_match(operands, &[A, FR]),_ => operands_match(operands, &[A, RI]),}} printing store_instruction(width);@@ -207,7 +240,7 @@ define_machine_opcodes! {} printing match width {MemoryWidth::Byte => simple!(operation.mnemonic(); SimpleOperand::Resolved(0, "BYTE PTR "), SimpleOperand::ResolvedInteger(1, IntegerWidth::U8)),MemoryWidth::Word => simple!(operation.mnemonic(); SimpleOperand::Resolved(0, "DWORD PTR "), SimpleOperand::ResolvedInteger(1, IntegerWidth::U32)),- MemoryWidth::HalfWord | MemoryWidth::DoubleWord | MemoryWidth::Float => unreachable!("unsupported x86-64 memory update width"),+ MemoryWidth::HalfWord | MemoryWidth::DoubleWord | MemoryWidth::Float | MemoryWidth::Double | MemoryWidth::Vector => unreachable!("unsupported x86-64 memory update width"),};[SignExtend32To64] => Self::SignExtend32To64 => [[R, R]] printing simple!("movsxd"; native(0), integer(1, IntegerWidth::U32));[Move64Register] => Self::Move64Register => [[R, R]] printing simple!("mov"; native(0), native(1));@@ -234,6 +267,9 @@ define_machine_opcodes! {[Multiply64Register] => Self::Multiply64Register => [[R, R]] printing simple!("imul"; native(0), native(1));[Multiply64Immediate] => Self::Multiply64Immediate => [[R, R, RI]] printing simple!("imul"; native(0), native(1), SimpleOperand::Resolved(2, ""));[Multiply32] => Self::Multiply32 => [[R, R]] printing simple!("imul"; integer(0, IntegerWidth::U32), integer(1, IntegerWidth::U32));+ [Multiply32Immediate] => Self::Multiply32Immediate => [[R, R, I]] encoding {+ immediate(2).is_some_and(|value| i32::try_from(value).is_ok())+ } printing simple!("imul"; integer(0, IntegerWidth::U32), integer(1, IntegerWidth::U32), SimpleOperand::Immediate(2));[Increment32Register] => Self::Increment32Register => [[R]] printing simple!("inc"; integer(0, IntegerWidth::U32));[Decrement32Register] => Self::Decrement32Register => [[R]] printing simple!("dec"; integer(0, IntegerWidth::U32));[Negate32Register] => Self::Negate32Register => [[R]] printing simple!("neg"; integer(0, IntegerWidth::U32));@@ -271,7 +307,7 @@ define_machine_opcodes! {})} printing match width {MemoryWidth::Byte => simple!("test"; SimpleOperand::Resolved(0, "BYTE PTR "), SimpleOperand::Immediate(1)),- MemoryWidth::HalfWord | MemoryWidth::Word | MemoryWidth::DoubleWord | MemoryWidth::Float => unreachable!("unsupported finalized x86-64 immediate memory test width"),+ MemoryWidth::HalfWord | MemoryWidth::Word | MemoryWidth::DoubleWord | MemoryWidth::Float | MemoryWidth::Double | MemoryWidth::Vector => unreachable!("unsupported finalized x86-64 immediate memory test width"),};[BitTest64Immediate] => Self::BitTest64Immediate => [[R, I]] encoding {immediate(1).is_some_and(|value| (0..64).contains(&value))@@ -279,6 +315,25 @@ define_machine_opcodes! {[JumpCondition(Condition)] => Self::JumpCondition(condition) => [[L]] printing simple!(condition.x86_64_mnemonic(); SimpleOperand::Label(0));[UndefinedInstruction] => Self::UndefinedInstruction => [[]] printing simple!("ud2");[MoveFloatBits64] => Self::MoveFloatBits64 => [[AR, AR]] printing simple!("movq"; native(0), native(1));+ [MoveVector] => Self::MoveVector => [[FR, FR]] printing simple!("movaps"; native(0), native(1));+ [VectorBinary(VectorOperation)] => Self::VectorBinary(operation) => [[FR, FR]] printing simple!(operation.x86_64_mnemonic(); native(0), native(1));+ [VectorUnary(VectorOperation)] => Self::VectorUnary(operation) => [[FR, FR]] printing match operation.x86_64_immediate() {+ Some(immediate) => simple!(operation.x86_64_mnemonic(); native(0), native(1), SimpleOperand::Value(immediate)),+ None => simple!(operation.x86_64_mnemonic(); native(0), native(1)),+ };+ [VectorToGeneralPurpose(VectorOperation)] => Self::VectorToGeneralPurpose(operation) => [[R, FR]] printing match (operation.kind(), operation.x86_64_immediate()) {+ (crate::intrinsic::VectorOperationKind::ToGeneralPurpose32, _) => simple!(operation.x86_64_mnemonic(); word(0), native(1)),+ (_, Some(immediate)) => simple!(operation.x86_64_mnemonic(); native(0), native(1), SimpleOperand::Value(immediate)),+ (_, None) => simple!(operation.x86_64_mnemonic(); native(0), native(1)),+ };+ [AtomicUpdate(AtomicOperation)] => Self::AtomicUpdate(operation) => [[R, A]] printing match operation.kind() {+ crate::intrinsic::AtomicOperationKind::Exchange => simple!("xchg"; SimpleOperand::Resolved(1, atomic_size_prefix(operation.width())), integer(0, operation.width())),+ _ => simple!("lock xadd"; SimpleOperand::Resolved(1, atomic_size_prefix(operation.width())), integer(0, operation.width())),+ };+ [MemoryFence] => Self::MemoryFence => [[]] printing simple!("mfence");+ [AtomicCompareExchange(AtomicOperation)] => Self::AtomicCompareExchange(operation) => [[R, A, R]] printing simple!("lock cmpxchg"; SimpleOperand::Resolved(1, atomic_size_prefix(operation.width())), integer(2, operation.width()));+ [ZeroExtend(IntegerWidth)] => Self::ZeroExtend(width) => [[R]] printing simple!("movzx"; word(0), integer(0, width));+ [InsertHigh64] => Self::InsertHigh64 => [[FR, R]] printing simple!("pinsrq"; native(0), native(1), SimpleOperand::Value(1));[CompareDouble] => Self::CompareDouble => [[FR, FR]] printing simple!("ucomisd"; native(0), native(1));[JumpParity] => Self::JumpParity => [[L]] printing simple!("jp"; SimpleOperand::Label(0));[FloatArithmetic(FloatBinaryOperation)] => Self::FloatArithmetic(operation) => [[FR, FR]] printing simple!(float_arithmetic_mnemonic(operation); native(0), native(1));@@ -321,6 +376,38 @@ define_machine_opcodes! {[SignExtendRaxToRdx] => Self::SignExtendRaxToRdx => [[]] printing simple!("cqo");[SignedDivide64Register] => Self::SignedDivide64Register => [[R]] printing simple!("idiv"; native(0));[SignedDivide32Register] => Self::SignedDivide32Register => [[R]] printing simple!("idiv"; integer(0, IntegerWidth::U32));+ [LoadSecondaryDispatchTable(u8)] => Self::LoadSecondaryDispatchTable(prefix) => [[R]] printing simple!("lea"; native(0), SimpleOperand::Literal(match prefix {+ 0xfb => "[rip + asm_dispatch_table_fb]",+ 0xfc => "[rip + asm_dispatch_table_fc]",+ 0xfd => "[rip + asm_dispatch_table_fd]",+ 0xfe => "[rip + asm_dispatch_table_fe]",+ 0xff => "[rip + asm_dispatch_table_ff]",+ _ => unreachable!("secondary dispatch tables only exist for the 0xfb to 0xff prefixes"),+ }));+ [UnsignedDivide(IntegerWidth)] => Self::UnsignedDivide(width) => [[R]] printing simple!("div"; integer(0, width));+ [CountLeadingZeros(IntegerWidth)] => Self::CountLeadingZeros(width) => [[R, R]] printing simple!("lzcnt"; integer(0, width), integer(1, width));+ [CountTrailingZeros(IntegerWidth)] => Self::CountTrailingZeros(width) => [[R, R]] printing simple!("tzcnt"; integer(0, width), integer(1, width));+ [PopulationCount(IntegerWidth)] => Self::PopulationCount(width) => [[R, R]] printing simple!("popcnt"; integer(0, width), integer(1, width));+ [RotateLeft(IntegerWidth)] => Self::RotateLeft(width) => [[R]] printing simple!("rol"; integer(0, width), SimpleOperand::Literal("cl"));+ [RotateRight(IntegerWidth)] => Self::RotateRight(width) => [[R]] printing simple!("ror"; integer(0, width), SimpleOperand::Literal("cl"));+ [MoveGprToFpr64] => Self::MoveGprToFpr64 => [[FR, R]] printing simple!("movq"; native(0), native(1));+ [MoveFprToGpr64] => Self::MoveFprToGpr64 => [[R, FR]] printing simple!("movq"; native(0), native(1));+ [MoveGprToFpr32] => Self::MoveGprToFpr32 => [[FR, R]] printing simple!("movd"; native(0), word(1));+ [MoveFprToGpr32] => Self::MoveFprToGpr32 => [[R, FR]] printing simple!("movd"; word(0), native(1));+ [TruncateDoubleToSigned64] => Self::TruncateDoubleToSigned64 => [[R, FR]] printing simple!("cvttsd2si"; native(0), native(1));+ [ConvertSigned64ToSingle] => Self::ConvertSigned64ToSingle => [[FR, R]] printing simple!("cvtsi2ss"; native(0), native(1));+ [ConvertSigned64ToDouble] => Self::ConvertSigned64ToDouble => [[FR, R]] printing simple!("cvtsi2sd"; native(0), native(1));+ [RoundDouble(i64)] => Self::RoundDouble(mode) => [[FR, FR]] printing simple!("roundsd"; native(0), native(1), SimpleOperand::Value(mode));+ [SquareRootDouble] => Self::SquareRootDouble => [[FR, FR]] printing simple!("sqrtsd"; native(0), native(1));+ [SquareRootSingle] => Self::SquareRootSingle => [[FR, FR]] printing simple!("sqrtss"; native(0), native(1));+ [SingleToDouble] => Self::SingleToDouble => [[FR, FR]] printing simple!("cvtss2sd"; native(0), native(1));+ [DoubleToSingle] => Self::DoubleToSingle => [[FR, FR]] printing simple!("cvtsd2ss"; native(0), native(1));+ [SingleArithmetic(FloatBinaryOperation)] => Self::SingleArithmetic(operation) => [[FR, FR]] printing simple!(match operation {+ FloatBinaryOperation::Add => "addss",+ FloatBinaryOperation::Subtract => "subss",+ FloatBinaryOperation::Multiply => "mulss",+ FloatBinaryOperation::Divide => "divss",+ }; native(0), native(1));}impl Opcode {@@ -407,6 +494,7 @@ impl Opcode {Self::Move32Register}}+ Operation::FloatMove if operands.iter().any(is_vector_register) => Self::MoveVector,Operation::FloatMove => Self::MoveFloatBits64,Operation::Float(operation) => match operation {FloatingPointOperation::Binary(operation) => Self::FloatArithmetic(operation),@@ -543,6 +631,27 @@ pub(crate) fn generate(program: &Program, options: &CompileOptions) -> String {emit_file_header(&mut out, "#", true);+ if program.profile == crate::Profile::WebAssembly {+ return emit_program(+ out,+ program,+ "",+ |out| generate_wasm_entry_point(out, program, object_format),+ |_| {},+ |out| {+ emit_handlers(+ out,+ program,+ "#",+ |out, cold| w!(out, "{}", if cold { ".p2align 4" } else { ".p2align 6" }),+ |out, instruction, handler| emit_instruction(out, instruction, handler, program),+ |_| {},+ )+ },+ |out| generate_wasm_exit_point(out, object_format),+ );+ }+emit_program(out,program,@@ -585,6 +694,72 @@ fn generate_exit_point(out: &mut String, fmt: ObjectFormat, abi: X86_64Abi) {w!(out);}+/// The entry point of the WebAssembly interpreter:+/// `void wasm_interpreter(u8 const* ip, u64 argument)`.+///+/// It saves the callee-saved registers in a frame whose base becomes `fp`,+/// loads `ip` and the dispatch table, hands `argument` to the first handler in+/// `vsp`, and dispatches. Handlers build the frames of WebAssembly functions+/// below it and must restore `fp` to this frame before they `exit`. If the+/// runtime has a spill area, the frame keeps it free above the stack pointer,+/// for the first handler to spill to before it moves the stack pointer.+///+/// The interpreter and the runtime functions its handlers call use the System V+/// calling convention on Windows too, so that calls need no shadow space below+/// the spill area.+fn generate_wasm_entry_point(out: &mut String, program: &Program, object_format: ObjectFormat) {+ let coff = object_format == ObjectFormat::Coff;+ w!(out, " push rbp");+ if coff {+ w!(out, " .seh_pushreg rbp");+ } else {+ w!(out, " .cfi_def_cfa_offset 16");+ w!(out, " .cfi_offset rbp, -16");+ }+ w!(out, " mov rbp, rsp");+ if coff {+ w!(out, " .seh_setframe rbp, 0");+ for (register, _) in SYSV_SAVED_REGISTERS {+ w!(out, " push {register}");+ w!(out, " .seh_pushreg {register}");+ }+ } else {+ w!(out, " .cfi_def_cfa_register rbp");+ emit_saved_registers(out, X86_64Abi::SysV);+ }+ let spill_area = match (+ runtime(program).get(KnownLayoutConstant::SpillAreaOffset),+ runtime(program).get(KnownLayoutConstant::SpillAreaSlots),+ ) {+ (Some(offset), Some(slots)) => (offset + slots * 8 + 15) & !15,+ _ => 0,+ };+ w!(out, " sub rsp, {}", 8 + spill_area);+ if coff {+ w!(out, " .seh_stackalloc {}", 8 + spill_area);+ w!(out, " .seh_endprologue");+ }+ w!(out, " mov r13, rdi # ip");+ w!(out, " mov rbx, rsi # vsp = argument");+ w!(out, " lea r12, [rip + asm_dispatch_table]");+ w!(out, " movzx eax, BYTE PTR [r13]");+ w!(out, " jmp [r12 + rax * 8]");+ w!(out);+}++fn generate_wasm_exit_point(out: &mut String, fmt: ObjectFormat) {+ w!(out, ".Lexit:");+ w!(out, " lea rsp, [rbp - 40]");+ emit_restored_registers(out, fmt, X86_64Abi::SysV);+ w!(out, " pop rbp");+ if matches!(fmt, ObjectFormat::Elf) {+ w!(out, " .cfi_restore rbp");+ w!(out, " .cfi_def_cfa rsp, 8");+ }+ w!(out, " ret");+ w!(out);+}+fn generate_entry_point(out: &mut String, program: &Program, abi: X86_64Abi) {w!(out, " push rbp");if abi.is_win64() {@@ -853,11 +1028,13 @@ mod tests {(KnownLayoutConstant::SizeOfExecutionContext, 120),]),dispatch_handlers: Vec::new(),+ dispatch: Default::default(),target: crate::Target {architecture: Architecture::X86_64,object_format: ObjectFormat::MachO,},functions: Vec::new(),+ profile: crate::Profile::JavaScript,profiling: false,}}diff --git a/Libraries/LibJS/Flap/src/target/x86_64/finalize.rs b/Libraries/LibJS/Flap/src/target/x86_64/finalize.rsindex 728ca2c3ec6..6be37dd45a9 100644--- a/Libraries/LibJS/Flap/src/target/x86_64/finalize.rs+++ b/Libraries/LibJS/Flap/src/target/x86_64/finalize.rs@@ -9,6 +9,7 @@use super::Opcode;use crate::frontend::layout::KnownLayoutConstant;use crate::low_ir::Label;+use crate::profile::ProgramCounterAddressing;use crate::runtime_interface::{RawNativeReturnConvention, raw_native_return_convention};use crate::target::backend::{Backend, X86_64Backend};use crate::target::description::ArchitectureOpcode;@@ -383,7 +384,7 @@ pub(crate) fn store(MemoryWidth::HalfWord => (value as u16).into(),MemoryWidth::Word => (value as u32).into(),MemoryWidth::DoubleWord => value,- MemoryWidth::Float => {+ MemoryWidth::Float | MemoryWidth::Double | MemoryWidth::Vector => {unreachable!("floating immediate store was validated")}}),@@ -1113,6 +1114,16 @@ fn push_stack_adjustment(emit: &mut Emit<'_>, operation: super::AluOperation, vafn dispatch_from_instruction_pointer(emit: &mut Emit<'_>, opcode_scratch: PhysicalRegister) {use crate::target::registers::x86_64::{R12, R13, R14};+ if emit.profile.program_counter_addressing() == ProgramCounterAddressing::Absolute {+ emit!(emit.output, X86_64;+ Opcode::Load {+ width: MemoryWidth::Byte,+ signed: false,+ } => [register opcode_scratch, address MachineMemoryAddress::offset(R13, 0)];+ Opcode::JumpMemory => [address MachineMemoryAddress::scaled(R12, opcode_scratch, 8, 0)];+ );+ return;+ }emit!(emit.output, X86_64;Opcode::Load {width: MemoryWidth::Byte,@@ -1122,6 +1133,15 @@ fn dispatch_from_instruction_pointer(emit: &mut Emit<'_>, opcode_scratch: Physic);}+/// The width of the pinned program counter: a 32-bit offset from the program+/// base, or a pointer.+fn program_counter_width(emit: &Emit<'_>) -> IntegerWidth {+ match emit.profile.program_counter_addressing() {+ ProgramCounterAddressing::BaseRelative => IntegerWidth::U32,+ ProgramCounterAddressing::Absolute => IntegerWidth::U64,+ }+}+impl Backend for X86_64Backend {fn branch_float(&self,@@ -1280,7 +1300,8 @@ impl Backend for X86_64Backend {fn helper_call(&self, emit: &mut Emit<'_>, function: crate::low_ir::Relocation, argument_count: usize) {use crate::target::registers::x86_64::{RCX, RDI, RDX, RSI};- if emit.object_format != ObjectFormat::Coff {+ // The WebAssembly runtime's functions use the System V calling convention on Windows too.+ if emit.object_format != ObjectFormat::Coff || emit.profile == crate::Profile::WebAssembly {emit!(emit.output, X86_64; Opcode::Move64Register => [register RDI, register RCX];);if argument_count == 2 {emit!(emit.output, X86_64; Opcode::Move64Register => [register RSI, register RDX];);@@ -1470,7 +1491,7 @@ impl Backend for X86_64Backend {emit!(emit.output, X86_64;Opcode::AluRegister {operation: super::AluOperation::Add,- width: IntegerWidth::U32,+ width: program_counter_width(emit),} => [register R13, register size];);dispatch_from_instruction_pointer(emit, opcode_scratch);@@ -1489,7 +1510,7 @@ impl Backend for X86_64Backend {emit!(emit.output, X86_64;Opcode::AluImmediate {operation: super::AluOperation::Add,- width: IntegerWidth::U32,+ width: program_counter_width(emit),} => [register R13, immediate size.into()];);dispatch_from_instruction_pointer(emit, opcode_scratch);@@ -1737,12 +1758,30 @@ impl Backend for X86_64Backend {Ok(())}+ fn dispatch_secondary(&self, emit: &mut Emit<'_>, operands: &[AllocatedOperand]) -> Result<(), CompileError> {+ let prefix = operands.immediate(0);+ let index = operands.physical_register(1);+ let scratch = operands.physical_register(2);+ let Ok(prefix) = u8::try_from(prefix) else {+ return finalize_error(emit.handler, "a secondary dispatch table prefix must be a byte");+ };+ emit!(emit.output, X86_64;+ Opcode::LoadSecondaryDispatchTable(prefix) => [register scratch];+ Opcode::JumpMemory => [address MachineMemoryAddress::scaled(scratch, index, 8, 0)];+ );+ Ok(())+ }+fn goto_handler(&self, emit: &mut Emit<'_>, operands: &[AllocatedOperand]) -> Result<(), CompileError> {let [target, opcode_scratch] = [operands.physical_register(0), operands.physical_register(1)];use crate::target::registers::x86_64::R13;if target != R13 {- emit!(emit.output, X86_64; Opcode::Move32Register => [register R13, register target];);+ if program_counter_width(emit) == IntegerWidth::U64 {+ emit!(emit.output, X86_64; Opcode::Move64Register => [register R13, register target];);+ } else {+ emit!(emit.output, X86_64; Opcode::Move32Register => [register R13, register target];);+ }}dispatch_from_instruction_pointer(emit, opcode_scratch);Ok(())@@ -1967,6 +2006,30 @@ impl Backend for X86_64Backend {width: IntegerWidth,operands: &[AllocatedOperand],) -> Result<(), CompileError> {+ if operation == BinaryOperation::Multiply && width == IntegerWidth::U32 {+ let [destination, lhs, rhs] = operands else {+ unreachable!("allocated operation and operands were verified");+ };+ let destination = verified_register(destination);+ let lhs = verified_register(lhs);+ match rhs {+ AllocatedOperand::Immediate(value) => {+ emit!(emit.output, X86_64; Opcode::Multiply32Immediate => [register destination, register lhs, immediate *value];);+ }+ rhs => {+ let rhs = verified_register(rhs);+ if destination == lhs {+ emit!(emit.output, X86_64; Opcode::Multiply32 => [register destination, register rhs];);+ } else if destination == rhs {+ emit!(emit.output, X86_64; Opcode::Multiply32 => [register destination, register lhs];);+ } else {+ push_move_register(emit, destination, lhs, IntegerWidth::U32);+ emit!(emit.output, X86_64; Opcode::Multiply32 => [register destination, register rhs];);+ }+ }+ }+ return Ok(());+ }if operation == BinaryOperation::Multiply {return multiply(emit, width, operands);}@@ -1974,24 +2037,11 @@ impl Backend for X86_64Backend {let alu_operation =super::AluOperation::from_binary(operation).expect("allocated x86-64 ALU operation was verified");match (operation, width, operands) {- (BinaryOperation::And, IntegerWidth::U64, [destination, rhs, scratch, _reserved_scratch]) => {+ (BinaryOperation::And, IntegerWidth::U64, [destination, AllocatedOperand::Immediate(value)])+ if *value as u64 == 0xffff_ffff =>+ {let destination = verified_register(destination);- let scratch = verified_register(scratch);- match rhs {- AllocatedOperand::Immediate(value) if *value as u64 == 0xffff_ffff => {- push_move_register(emit, destination, destination, IntegerWidth::U32);- }- AllocatedOperand::Immediate(value) if i32::try_from(*value).is_ok() => {- push_alu_immediate(emit, alu_operation, width, destination, *value);- }- AllocatedOperand::Immediate(value) => {- emit!(emit.output, X86_64; Opcode::MoveAbsolute64Immediate => [register scratch, immediate *value];);- push_alu_register(emit, alu_operation, width, destination, scratch);- }- rhs => {- push_alu_register(emit, alu_operation, width, destination, verified_register(rhs));- }- }+ push_move_register(emit, destination, destination, IntegerWidth::U32);}(BinaryOperation::And | BinaryOperation::Or | BinaryOperation::Xor,@@ -2013,7 +2063,29 @@ impl Backend for X86_64Backend {}}(- BinaryOperation::And | BinaryOperation::Or | BinaryOperation::Xor,+ BinaryOperation::Subtract,+ IntegerWidth::U32,+ [destination, lhs, AllocatedOperand::PhysicalRegister(rhs)],+ ) if destination.physical_register() == Some(*rhs)+ && destination.physical_register() != lhs.physical_register() =>+ {+ // destination = lhs - destination+ let destination = verified_register(destination);+ emit!(emit.output, X86_64; Opcode::Negate32Register => [register destination];);+ push_alu_register(+ emit,+ super::AluOperation::Add,+ IntegerWidth::U32,+ destination,+ verified_register(lhs),+ );+ }+ (+ BinaryOperation::And+ | BinaryOperation::Or+ | BinaryOperation::Xor+ | BinaryOperation::Add+ | BinaryOperation::Subtract,IntegerWidth::U32,[destination, lhs, rhs],) => {@@ -2207,6 +2279,227 @@ impl Backend for X86_64Backend {}}+ fn branch_ordered_float(+ &self,+ emit: &mut Emit<'_>,+ lhs: PhysicalRegister,+ rhs: PhysicalRegister,+ comparison: crate::intrinsic::OrderedFloatComparison,+ target: &Label,+ ) -> Result<(), CompileError> {+ use super::Condition;+ use crate::intrinsic::OrderedFloatComparison::*;+ // ucomisd reports an unordered comparison as "equal and below", so the relations are tested through the+ // "above" conditions, which an unordered comparison never satisfies.+ let (first, second, condition) = match comparison {+ Less => (rhs, lhs, Condition::UnsignedGreater),+ LessOrEqual => (rhs, lhs, Condition::UnsignedGreaterOrEqual),+ Greater => (lhs, rhs, Condition::UnsignedGreater),+ GreaterOrEqual => (lhs, rhs, Condition::UnsignedGreaterOrEqual),+ Equal | NotEqual => (lhs, rhs, Condition::Equal),+ };+ emit!(emit.output, X86_64; Opcode::CompareDouble => [register first, register second];);+ match comparison {+ Equal => {+ let unordered = emit.unique_label("unordered");+ emit!(emit.output, X86_64;+ Opcode::JumpCondition(Condition::FloatUnordered) => [label unordered.clone()];+ Opcode::JumpCondition(Condition::Equal) => [label target.clone()];+ Opcode::Label => [label unordered];+ );+ }+ NotEqual => {+ emit!(emit.output, X86_64;+ Opcode::JumpCondition(Condition::FloatUnordered) => [label target.clone()];+ Opcode::JumpCondition(Condition::NotEqual) => [label target.clone()];+ );+ }+ _ => {+ emit!(emit.output, X86_64; Opcode::JumpCondition(condition) => [label target.clone()];);+ }+ }+ Ok(())+ }++ fn finalize_atomic(+ &self,+ emit: &mut Emit<'_>,+ operation: crate::intrinsic::AtomicOperation,+ operands: &[AllocatedOperand],+ ) -> Result<(), CompileError> {+ match operation.kind() {+ crate::intrinsic::AtomicOperationKind::Fence => {+ emit!(emit.output, X86_64; Opcode::MemoryFence => [];);+ return Ok(());+ }+ // Plain loads are sequentially consistent with the locked read-modify-write instructions.+ crate::intrinsic::AtomicOperationKind::Load => {+ let destination = operands.physical_register(0);+ let address = machine_address(operands.operand(1));+ let width = match operation.width() {+ IntegerWidth::U8 => MemoryWidth::Byte,+ IntegerWidth::U16 => MemoryWidth::HalfWord,+ IntegerWidth::U32 => MemoryWidth::Word,+ IntegerWidth::U64 => MemoryWidth::DoubleWord,+ };+ emit!(emit.output, X86_64; Opcode::Load { width, signed: false } => [register destination, address address];);+ return Ok(());+ }+ _ => {}+ }+ let destination = operands.physical_register(0);+ let address = machine_address(operands.operand(1));+ if operation.kind() == crate::intrinsic::AtomicOperationKind::CompareExchange {+ let replacement = operands.physical_register(2);+ emit!(emit.output, X86_64; Opcode::AtomicCompareExchange(operation) => [register destination, address address, register replacement];);+ } else {+ emit!(emit.output, X86_64; Opcode::AtomicUpdate(operation) => [register destination, address address];);+ }+ // Narrow operations leave the register's upper bits as they were.+ match operation.width() {+ IntegerWidth::U8 | IntegerWidth::U16 => {+ emit!(emit.output, X86_64; Opcode::ZeroExtend(operation.width()) => [register destination];);+ }+ IntegerWidth::U32 => push_move_register(emit, destination, destination, IntegerWidth::U32),+ IntegerWidth::U64 => {}+ }+ Ok(())+ }++ fn finalize_vector(+ &self,+ emit: &mut Emit<'_>,+ operation: crate::intrinsic::VectorOperation,+ operands: &[AllocatedOperand],+ ) -> Result<(), CompileError> {+ use crate::intrinsic::VectorOperationKind;+ match operation.kind() {+ VectorOperationKind::FromU64Pair => {+ let [destination, low, high] = operands.physical_registers();+ emit!(emit.output, X86_64;+ Opcode::MoveGprToFpr64 => [register destination, register low];+ Opcode::InsertHigh64 => [register destination, register high];+ );+ }+ VectorOperationKind::Binary => {+ let [destination, rhs] = operands.physical_registers();+ emit!(emit.output, X86_64; Opcode::VectorBinary(operation) => [register destination, register rhs];);+ }+ VectorOperationKind::Unary => {+ let [destination, source] = operands.physical_registers();+ emit!(emit.output, X86_64; Opcode::VectorUnary(operation) => [register destination, register source];);+ }+ VectorOperationKind::ToGeneralPurpose | VectorOperationKind::ToGeneralPurpose32 => {+ let [destination, source] = operands.physical_registers();+ emit!(emit.output, X86_64; Opcode::VectorToGeneralPurpose(operation) => [register destination, register source];);+ }+ }+ Ok(())+ }++ fn finalize_numeric(+ &self,+ emit: &mut Emit<'_>,+ operation: crate::intrinsic::NumericOperation,+ operands: &[AllocatedOperand],+ ) -> Result<(), CompileError> {+ use crate::intrinsic::NumericOperation::*;+ use crate::target::registers::x86_64::{RAX, RDX};+ let width = match operation {+ DivideSigned32 | DivideUnsigned32 | RemainderSigned32 | RemainderUnsigned32 | CountLeadingZeros32+ | CountTrailingZeros32 | PopulationCount32 | RotateLeft32 | RotateRight32 => IntegerWidth::U32,+ _ => IntegerWidth::U64,+ };+ match operation {+ DivideSigned32 | DivideUnsigned32 | RemainderSigned32 | RemainderUnsigned32 | DivideSigned64+ | DivideUnsigned64 | RemainderSigned64 | RemainderUnsigned64 => {+ let [_, dividend, divisor, _] = operands.physical_registers();+ let signed = matches!(+ operation,+ DivideSigned32 | RemainderSigned32 | DivideSigned64 | RemainderSigned64+ );+ if dividend != RAX {+ push_move_register(emit, RAX, dividend, width);+ }+ if signed {+ if width == IntegerWidth::U32 {+ emit!(emit.output, X86_64; Opcode::SignExtendEaxToEdx => []; Opcode::SignedDivide32Register => [register divisor];);+ } else {+ emit!(emit.output, X86_64; Opcode::SignExtendRaxToRdx => []; Opcode::SignedDivide64Register => [register divisor];);+ }+ } else {+ push_alu_register(emit, super::AluOperation::Xor, IntegerWidth::U32, RDX, RDX);+ emit!(emit.output, X86_64; Opcode::UnsignedDivide(width) => [register divisor];);+ }+ }+ CountLeadingZeros32 | CountLeadingZeros64 => {+ let [destination, source] = operands.physical_registers();+ emit!(emit.output, X86_64; Opcode::CountLeadingZeros(width) => [register destination, register source];);+ }+ CountTrailingZeros32 | CountTrailingZeros64 => {+ let [destination, source] = operands.physical_registers();+ emit!(emit.output, X86_64; Opcode::CountTrailingZeros(width) => [register destination, register source];);+ }+ PopulationCount32 | PopulationCount64 => {+ let [destination, source] = operands.physical_registers();+ emit!(emit.output, X86_64; Opcode::PopulationCount(width) => [register destination, register source];);+ }+ RotateLeft32 | RotateLeft64 => {+ let [destination, _] = operands.physical_registers();+ emit!(emit.output, X86_64; Opcode::RotateLeft(width) => [register destination];);+ }+ RotateRight32 | RotateRight64 => {+ let [destination, _] = operands.physical_registers();+ emit!(emit.output, X86_64; Opcode::RotateRight(width) => [register destination];);+ }+ Float64FromBits+ | Float32FromBits+ | Float64ToBits+ | Float32ToBits+ | TruncateFloat64ToSigned64+ | ConvertSigned64ToFloat32+ | ConvertSigned64ToFloat64+ | RoundFloat64ToZero+ | RoundFloat64ToNearest+ | RoundFloat64Up+ | RoundFloat64Down+ | SquareRootFloat64+ | SquareRootFloat32+ | PromoteFloat32+ | DemoteFloat64+ | AddFloat32+ | SubtractFloat32+ | MultiplyFloat32+ | DivideFloat32 => {+ let [destination, source] = operands.physical_registers();+ let opcode = match operation {+ Float64FromBits => Opcode::MoveGprToFpr64,+ Float32FromBits => Opcode::MoveGprToFpr32,+ Float64ToBits => Opcode::MoveFprToGpr64,+ Float32ToBits => Opcode::MoveFprToGpr32,+ TruncateFloat64ToSigned64 => Opcode::TruncateDoubleToSigned64,+ ConvertSigned64ToFloat32 => Opcode::ConvertSigned64ToSingle,+ ConvertSigned64ToFloat64 => Opcode::ConvertSigned64ToDouble,+ RoundFloat64ToNearest => Opcode::RoundDouble(0),+ RoundFloat64Down => Opcode::RoundDouble(1),+ RoundFloat64Up => Opcode::RoundDouble(2),+ RoundFloat64ToZero => Opcode::RoundDouble(3),+ SquareRootFloat64 => Opcode::SquareRootDouble,+ SquareRootFloat32 => Opcode::SquareRootSingle,+ PromoteFloat32 => Opcode::SingleToDouble,+ DemoteFloat64 => Opcode::DoubleToSingle,+ AddFloat32 => Opcode::SingleArithmetic(crate::intrinsic::FloatBinaryOperation::Add),+ SubtractFloat32 => Opcode::SingleArithmetic(crate::intrinsic::FloatBinaryOperation::Subtract),+ MultiplyFloat32 => Opcode::SingleArithmetic(crate::intrinsic::FloatBinaryOperation::Multiply),+ DivideFloat32 => Opcode::SingleArithmetic(crate::intrinsic::FloatBinaryOperation::Divide),+ _ => unreachable!(),+ };+ emit!(emit.output, X86_64; opcode => [register destination, register source];);+ }+ }+ Ok(())+ }+fn finalize_divide(&self, emit: &mut Emit<'_>, width: IntegerWidth, operands: &[AllocatedOperand]) {let [_, dividend, divisor, accumulator] = operands.physical_registers();diff --git a/Libraries/LibJS/Flap/src/types.rs b/Libraries/LibJS/Flap/src/types.rsindex 34ddca5e0ed..424ab3ddacd 100644--- a/Libraries/LibJS/Flap/src/types.rs+++ b/Libraries/LibJS/Flap/src/types.rs@@ -86,6 +86,8 @@ macro_rules! define_named_types {pub(crate) enum RegisterClass {GeneralPurpose,FloatingPoint,+ /// 128-bit vectors, which live in the floating-point registers.+ Vector,}#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]@@ -144,6 +146,10 @@ define_interpreter_registers! {HeapRegionBase => "heap_region_base", Type::U64, false;StackPointer => "sp", Type::U64, true;FramePointer => "fp", Type::U64, true;+ InstructionPointer => "ip", Type::U64, true;+ SideTablePointer => "stp", Type::U64, true;+ ValueStackPointer => "vsp", Type::U64, true;+ MemoryBase => "memory_base", Type::U64, true;}#[derive(Debug, Clone, PartialEq, Eq, Hash)]@@ -228,6 +234,7 @@ define_named_types! {source {F64 => "f64", Some(8), false;F32 => "f32", Some(4), false;+ V128 => "v128", Some(16), false;InlineInt32 => "Int32", Some(4), false;SlotIndex => "SlotIndex", Some(4), false;BytecodeOffset => "BytecodeOffset", Some(4), false;@@ -282,6 +289,7 @@ impl Type {pub(crate) fn register_class(&self) -> Option<RegisterClass> {match self {Type::F32 | Type::F64 => Some(RegisterClass::FloatingPoint),+ Type::V128 => Some(RegisterClass::Vector),_ if self.width().is_some() => Some(RegisterClass::GeneralPurpose),_ => None,}@@ -328,7 +336,7 @@ impl Type {width: MemoryWidth::Float,signed: false,},- Type::F64 => return None,+ Type::F64 | Type::V128 => return None,_ if self.width() == Some(8) => MemoryOperation::Load {width: MemoryWidth::DoubleWord,signed: false,diff --git a/Libraries/LibJS/Flap/tests/assertions.rs b/Libraries/LibJS/Flap/tests/assertions.rsindex 3f8216d0ba8..08f63272c25 100644--- a/Libraries/LibJS/Flap/tests/assertions.rs+++ b/Libraries/LibJS/Flap/tests/assertions.rs@@ -16,6 +16,7 @@ fn compile(body: &str, architecture: Architecture, enabled: bool) -> String {has_jscvt: false,enable_assertions: enabled,profiling: false,+ profile: flapc::Profile::JavaScript,}).compile(CompilationUnit {source: SourceInput {diff --git a/Libraries/LibJS/Flap/tests/closures.rs b/Libraries/LibJS/Flap/tests/closures.rsindex 9d62058a069..5f36178ad75 100644--- a/Libraries/LibJS/Flap/tests/closures.rs+++ b/Libraries/LibJS/Flap/tests/closures.rs@@ -15,6 +15,7 @@ fn compile(source: &str, architecture: Architecture) -> Result<String, String> {has_jscvt: false,enable_assertions: true,profiling: false,+ profile: flapc::Profile::JavaScript,}).compile(CompilationUnit {source: SourceInput {diff --git a/Libraries/LibJS/Flap/tests/interpreter-assembly/aarch64.S b/Libraries/LibJS/Flap/tests/interpreter-assembly/aarch64.Sindex 684512dd461..2023edcec4b 100644--- a/Libraries/LibJS/Flap/tests/interpreter-assembly/aarch64.S+++ b/Libraries/LibJS/Flap/tests/interpreter-assembly/aarch64.S@@ -5150,41 +5150,41 @@ asm_handler_PutByValue_hot_end:.p2align 4asm_handler_GetById:ldr w0, [x21, #8]- ldr x0, [x27, x0, lsl #3]- lsr x9, x0, #48+ ldr x3, [x27, x0, lsl #3]+ lsr x9, x3, #48mov w10, #65529cmp x9, x10b.ne .Lasm_GetById.ssa_block_14- and x1, x0, #0x3ffffffffff- add x1, x1, x24- ldr x2, [x1, #24]- cbz x2, .Lasm_GetById.assert_failure_0- ldr x4, [x28, #88]- cbz x4, .Lasm_GetById.assert_predicate_failure_120- ldr x3, [x4, #152]- cbz x3, .Lasm_GetById.assert_failure_1- ldr w5, [x21, #20]- ldr x3, [x3, x5, lsl #3]- cbz x3, .Lasm_GetById.ssa_block_1- and x3, x3, #0xfffffffffffffffc- cbz x3, .Lasm_GetById.assert_predicate_failure_335- ldr x9, [x3, #24]- cmp x9, x2+ and x3, x3, #0x3ffffffffff+ add x3, x3, x24+ ldr x0, [x3, #24]+ cbz x0, .Lasm_GetById.assert_failure_0+ ldr x1, [x28, #88]+ cbz x1, .Lasm_GetById.assert_predicate_failure_123+ ldr x2, [x1, #152]+ cbz x2, .Lasm_GetById.assert_failure_1+ ldr w4, [x21, #20]+ ldr x2, [x2, x4, lsl #3]+ cbz x2, .Lasm_GetById.ssa_block_1+ and x2, x2, #0xfffffffffffffffc+ cbz x2, .Lasm_GetById.assert_predicate_failure_338+ ldr x9, [x2, #24]+ cmp x9, x0b.ne .Lasm_GetById.ssa_block_15- ldr w5, [x3]- cmp w5, #6+ ldr w1, [x2]+ cmp w1, #6b.eq .Lasm_GetById.ssa_block_1- ldr x5, [x3, #32]- cbnz x5, .Lasm_GetById.ssa_block_18- mov x5, x1+ ldr x1, [x2, #32]+ cbnz x1, .Lasm_GetById.ssa_block_18+ mov x1, x3.Lasm_GetById.ssa_block_16:- ldp w6, w7, [x3, #4]- ldr w9, [x2, #52]- cmp w9, w7+ ldp w4, w5, [x2, #4]+ ldr w9, [x0, #52]+ cmp w9, w5b.ne .Lasm_GetById.ssa_block_1- ldr x0, [x5, #32]+ ldr x0, [x1, #32]cbz x0, .Lasm_GetById.assert_failure_2- ldr x0, [x0, x6, lsl #3]+ ldr x0, [x0, x4, lsl #3]lsr x9, x0, #48mov w10, #65532cmp x9, x10@@ -5196,48 +5196,48 @@ asm_handler_GetById:ldr x10, [x19, x9, lsl #3]br x10.Lasm_GetById.ssa_block_15:- ldr x3, [x4, #152]- cbz x3, .Lasm_GetById.assert_failure_3- ldr w5, [x21, #20]- ldr x3, [x3, x5, lsl #3]- mov x5, x3- and x5, x5, #0x3- cmp x5, #1+ ldr x1, [x1, #152]+ cbz x1, .Lasm_GetById.assert_failure_3+ ldr w2, [x21, #20]+ ldr x1, [x1, x2, lsl #3]+ mov x2, x1+ and x2, x2, #0x3+ cmp x2, #1b.ne .Lasm_GetById.ssa_block_1- and x3, x3, #0xfffffffffffffffc- add x3, x3, #64- ldr x9, [x3, #24]- cmp x9, x2+ and x1, x1, #0xfffffffffffffffc+ add x1, x1, #64+ ldr x9, [x1, #24]+ cmp x9, x0b.eq .Lasm_GetById.ssa_block_11- add x3, x3, #64- ldr x9, [x3, #24]- cmp x9, x2+ add x1, x1, #64+ ldr x9, [x1, #24]+ cmp x9, x0b.eq .Lasm_GetById.ssa_block_11- add x3, x3, #64- ldr x9, [x3, #24]- cmp x9, x2+ add x1, x1, #64+ ldr x9, [x1, #24]+ cmp x9, x0b.ne .Lasm_GetById.ssa_block_1.Lasm_GetById.ssa_block_11:- ldr w5, [x3]- cmp w5, #6+ ldr w2, [x1]+ cmp w2, #6b.eq .Lasm_GetById.ssa_block_1- ldr w5, [x3, #8]- ldr w9, [x2, #52]- cmp w9, w5+ ldr w2, [x1, #8]+ ldr w9, [x0, #52]+ cmp w9, w2b.ne .Lasm_GetById.ssa_block_1- ldr x2, [x3, #32]- cbnz x2, .Lasm_GetById.ssa_block_12+ ldr x0, [x1, #32]+ cbnz x0, .Lasm_GetById.ssa_block_12.Lasm_GetById.ssa_block_13:- ldr x1, [x1, #32]- cbz x1, .Lasm_GetById.assert_failure_4- ldr w2, [x3, #4]- ldr x1, [x1, x2, lsl #3]- lsr x9, x1, #48+ ldr x0, [x3, #32]+ cbz x0, .Lasm_GetById.assert_failure_4+ ldr w1, [x1, #4]+ ldr x0, [x0, x1, lsl #3]+ lsr x9, x0, #48mov w10, #65532cmp x9, x10b.eq .Lasm_GetById.ssa_block_1ldr w9, [x21, #4]- str x1, [x27, x9, lsl #3]+ str x0, [x27, x9, lsl #3]ldrb w9, [x21, #24]add x21, x21, #24ldr x10, [x19, x9, lsl #3]@@ -5294,8 +5294,8 @@ asm_handler_PutById_hot_end:.p2align 4asm_handler_GetByValue:ldr w0, [x21, #16]- ldr x1, [x27, x0, lsl #3]- lsr x9, x1, #48+ ldr x2, [x27, x0, lsl #3]+ lsr x9, x2, #48cmp x9, x22b.ne .Lasm_GetByValue.ssa_block_5ldr w0, [x21, #12]@@ -5306,10 +5306,10 @@ asm_handler_GetByValue:b.ne .Lasm_GetByValue.ssa_block_8and x3, x3, #0x3ffffffffffadd x3, x3, x24- ldrh w2, [x3, #12]- mov w0, w1- tbnz x2, #3, .Lasm_GetByValue.ssa_block_20- tbz x2, #4, 1f+ ldrh w1, [x3, #12]+ mov w0, w2+ tbnz x1, #3, .Lasm_GetByValue.ssa_block_20+ tbz x1, #4, 1fb .Lasm_GetByValue.ssa_block_11:ldrb w1, [x3, #14]@@ -5319,7 +5319,7 @@ asm_handler_GetByValue:cmp x0, x1b.hs .Lasm_GetByValue.ssa_block_1ldr x1, [x3, #40]- cbz x1, .Lasm_GetByValue.assert_predicate_failure_69+ cbz x1, .Lasm_GetByValue.assert_predicate_failure_70ldur w2, [x1, #-8]cmp x0, x2b.hs .Lasm_GetByValue.ssa_block_1@@ -5482,7 +5482,7 @@ asm_handler_GetByValue:mov w9, #65530cmp w0, w9b.ne .Lasm_GetByValue.ssa_block_1- sxtw x0, w1+ sxtw x0, w2tbz w0, #31, 1fb .Lasm_GetByValue.ssa_block_11:@@ -5531,7 +5531,7 @@ asm_handler_GetByValue:lsr x9, x0, #48mov w10, #65530cmp x9, x10- b.ne .Lasm_GetByValue.assert_predicate_failure_292+ b.ne .Lasm_GetByValue.assert_predicate_failure_293ldr w9, [x21, #8]str x0, [x27, x9, lsl #3]ldrb w9, [x21, #32]@@ -5540,8 +5540,8 @@ asm_handler_GetByValue:br x10.Lasm_GetByValue.ssa_block_5:ldr w0, [x21, #12]- ldr x2, [x27, x0, lsl #3]- lsr x9, x2, #48+ ldr x1, [x27, x0, lsl #3]+ lsr x9, x1, #48mov w10, #65529cmp x9, x10b.ne .Lasm_GetByValue.ssa_block_1@@ -5550,11 +5550,11 @@ asm_handler_GetByValue:cbz x3, .Lasm_GetByValue.assert_failure_2ldr w4, [x21, #24]ldr x3, [x3, x4, lsl #3]- and x2, x2, #0x3ffffffffff- add x2, x2, x24+ and x1, x1, #0x3ffffffffff+ add x1, x1, x24cmp x3, #3b.eq .Lasm_GetByValue.ssa_block_6- cbz x0, .Lasm_GetByValue.assert_predicate_failure_226+ cbz x0, .Lasm_GetByValue.assert_predicate_failure_227ldr x0, [x0, #152]cbz x0, .Lasm_GetByValue.assert_failure_3ldr w3, [x21, #24]@@ -5564,22 +5564,22 @@ asm_handler_GetByValue:b.eq .Lasm_GetByValue.ssa_block_2and x0, x0, #0xfffffffffffffffcldr x9, [x0, #48]- cmp x9, x1+ cmp x9, x2b.ne .Lasm_GetByValue.ssa_block_3- ldr x1, [x2, #24]- cbz x1, .Lasm_GetByValue.assert_failure_4+ ldr x2, [x1, #24]+ cbz x2, .Lasm_GetByValue.assert_failure_4ldp x4, x3, [x0, #24]- cmp x4, x1+ cmp x4, x2b.ne .Lasm_GetByValue.ssa_block_3ldr w4, [x0]cmp w4, #6b.eq .Lasm_GetByValue.ssa_block_3ldr w4, [x0, #8]- ldr w9, [x1, #52]+ ldr w9, [x2, #52]cmp w9, w4b.ne .Lasm_GetByValue.ssa_block_3cbnz x3, .Lasm_GetByValue.ssa_block_3- ldr x1, [x2, #32]+ ldr x1, [x1, #32]cbz x1, .Lasm_GetByValue.assert_failure_5ldr w0, [x0, #4]ldr x0, [x1, x0, lsl #3]@@ -14101,6 +14101,8 @@ asm_handler_PostfixDecrement_cold_end:asm_handler_ToInt32_cold:// Cold paths for ToInt32.Lasm_ToInt32.ssa_block_2:+ ldr w0, [x21, #8]+ ldr x0, [x27, x0, lsl #3]lsr x1, x0, #48cmp x1, x22ccmp x1, x23, #4, ne@@ -14378,29 +14380,29 @@ asm_handler_PutByValue_cold_end:asm_handler_GetById_cold:// Cold paths for GetById.Lasm_GetById.ssa_block_24:- ldrb w9, [x3, #12]+ ldrb w9, [x2, #12]cbz w9, .Lasm_GetById.ssa_block_3- ldrh w0, [x1, #12]+ ldrh w0, [x3, #12]tbnz x0, #9, 1fb .Lasm_GetById.ssa_block_31:- ldr w0, [x2, #112]- ldr x0, [x1, x0, lsl #3]+ ldr w0, [x1, #112]+ ldr x0, [x3, x0, lsl #3]cbz x0, .Lasm_GetById.ssa_block_3- ldr w3, [x2, #120]- ldr x5, [x0, x3, lsl #3]+ ldr w2, [x1, #120]+ ldr x5, [x0, x2, lsl #3]cbz x5, .Lasm_GetById.ssa_block_3- ldr w4, [x2, #124]+ ldr w4, [x1, #124]ldr x5, [x5, x4, lsl #3]- cmp x5, x1+ cmp x5, x3b.ne .Lasm_GetById.ssa_block_3- ldr w1, [x2, #116]+ ldr w1, [x1, #116]ldr x0, [x0, x1, lsl #3]cbnz x0, .Lasm_GetById.ssa_block_50movz x0, #0x7fff, lsl #48b .Lasm_GetById.ssa_block_51.Lasm_GetById.ssa_block_50:- ldr x0, [x0, x3, lsl #3]+ ldr x0, [x0, x2, lsl #3]cbz x0, .Lasm_GetById.ssa_block_3ldr x0, [x0, x4, lsl #3]cbz x0, .Lasm_GetById.ssa_block_3@@ -14419,23 +14421,23 @@ asm_handler_GetById_cold:ldr x10, [x19, x9, lsl #3]br x10.Lasm_GetById.ssa_block_25:- ldr w3, [x2, #104]+ ldr w2, [x1, #104]mov x0, x20ldr x0, [x0, #80]cbz x0, .Lasm_GetById.assert_failure_5- and w3, w3, #0xffff- lsl x3, x3, #4- adds x3, x3, x0- ldr w4, [x3, #8]+ and w2, w2, #0xffff+ lsl x2, x2, #4+ adds x2, x2, x0+ ldr w4, [x2, #8]cmp x4, #1- b.hs .Lasm_GetById.assert_predicate_failure_157+ b.hs .Lasm_GetById.assert_predicate_failure_160mov x0, x20ldp x0, x6, [x0, #16]cbz x0, .Lasm_GetById.assert_failure_6cbz x6, .Lasm_GetById.assert_failure_7add x5, x0, #128cmp x5, x0- b.lo .Lasm_GetById.assert_predicate_failure_166+ b.lo .Lasm_GetById.assert_predicate_failure_169cmp x5, x6b.hi .Lasm_GetById.ssa_block_3mov x6, x20@@ -14443,31 +14445,31 @@ asm_handler_GetById_cold:mov x6, x7add x6, x6, #8, lsl #12cmp x6, x7- b.lo .Lasm_GetById.assert_predicate_failure_174+ b.lo .Lasm_GetById.assert_predicate_failure_177cmp x6, x29b.hi .Lasm_GetById.ssa_block_3mov x6, x20str x5, [x6, #16]stp w4, w4, [x0, #116]str wzr, [x0, #104]- ldr x4, [x2, #24]+ ldr x4, [x1, #24]cbz x4, .Lasm_GetById.assert_failure_8ldr x4, [x4, #16]cbz x4, .Lasm_GetById.assert_failure_9- stp x2, x4, [x0, #0]- ldp x2, x4, [x28, #32]- cbz x2, .Lasm_GetById.assert_predicate_failure_199- cbz x4, .Lasm_GetById.assert_predicate_failure_201- stp x2, x4, [x0, #32]- ldr x2, [x28, #48]- str x2, [x0, #48]- and x1, x1, #0x3ffffffffff- movz x2, #0xfff9, lsl #48- orr x1, x1, x2- str x1, [x0, #80]+ stp x1, x4, [x0, #0]+ ldp x1, x4, [x28, #32]+ cbz x1, .Lasm_GetById.assert_predicate_failure_202+ cbz x4, .Lasm_GetById.assert_predicate_failure_204+ stp x1, x4, [x0, #32]+ ldr x1, [x28, #48]+ str x1, [x0, #48]+ and x3, x3, #0x3ffffffffff+ movz x1, #0xfff9, lsl #48+ orr x3, x3, x1+ str x3, [x0, #80]mov x1, #0- add x2, x0, #16- stp x1, x1, [x2, #0]+ add x3, x0, #16+ stp x1, x1, [x3, #0]str xzr, [x0, #88]str wzr, [x0, #64]str wzr, [x0, #68]@@ -14480,26 +14482,26 @@ asm_handler_GetById_cold:strb wzr, [x0, #124]strb wzr, [x0, #125]sub w1, w21, w26- ldp w2, w4, [x21, #4]+ ldp w3, w4, [x21, #4]str w1, [x28, #64]str x28, [x0, #96]add x1, x1, #1- stp w1, w2, [x0, #108]+ stp w1, w3, [x0, #108]mov x1, x20str x0, [x1]mov x28, x0add x27, x28, #128- ldr x2, [x3]+ ldr x2, [x2]cbz x2, .Lasm_GetById.assert_failure_10mov x9, x2mov x0, x20blr x9and x1, x1, #0xffcmp x1, #2- b.hs .Lasm_GetById.assert_predicate_failure_265+ b.hs .Lasm_GetById.assert_predicate_failure_268cbnz x1, .Lasm_GetById.ssa_block_6ldr x1, [x28, #96]- cbz x1, .Lasm_GetById.assert_predicate_failure_274+ cbz x1, .Lasm_GetById.assert_predicate_failure_277mov x2, x20str x1, [x2]str x28, [x2, #16]@@ -14564,17 +14566,17 @@ asm_handler_GetById_cold:ldr x10, [x19, x9, lsl #3]br x10.Lasm_GetById.ssa_block_18:- ldr x6, [x3, #40]- cbz x6, .Lasm_GetById.ssa_block_1- ldrb w9, [x6, #11]+ ldr x4, [x2, #40]+ cbz x4, .Lasm_GetById.ssa_block_1+ ldrb w9, [x4, #11]cbz w9, .Lasm_GetById.ssa_block_1b .Lasm_GetById.ssa_block_16.Lasm_GetById.ssa_block_17:and x0, x0, #0x3ffffffffffadd x0, x0, x24- ldr x2, [x0, #16]- cbz x2, .Lasm_GetById.ssa_block_5- ldrh w0, [x2, #12]+ ldr x1, [x0, #16]+ cbz x1, .Lasm_GetById.ssa_block_5+ ldrh w0, [x1, #12]tbnz x0, #1, 1fb .Lasm_GetById.ssa_block_31:@@ -14609,10 +14611,10 @@ asm_handler_GetById_cold:cbnz w0, .Lasm_GetById.ssa_block_4mov x0, x20ldr x28, [x0]- cbz x28, .Lasm_GetById.assert_predicate_failure_23+ cbz x28, .Lasm_GetById.assert_predicate_failure_26add x27, x28, #128ldr x0, [x28, #88]- cbz x0, .Lasm_GetById.assert_predicate_failure_29+ cbz x0, .Lasm_GetById.assert_predicate_failure_32ldr x26, [x0, #40]cbz x26, .Lasm_GetById.assert_failure_19mov w25, #0@@ -14629,10 +14631,10 @@ asm_handler_GetById_cold:1:mov x0, x20ldr x28, [x0]- cbz x28, .Lasm_GetById.assert_predicate_failure_47+ cbz x28, .Lasm_GetById.assert_predicate_failure_50add x27, x28, #128ldr x0, [x28, #88]- cbz x0, .Lasm_GetById.assert_predicate_failure_53+ cbz x0, .Lasm_GetById.assert_predicate_failure_56ldr x26, [x0, #40]cbz x26, .Lasm_GetById.assert_failure_20ldr w25, [x28, #64]@@ -14641,16 +14643,19 @@ asm_handler_GetById_cold:ldr x10, [x19, x9, lsl #3]br x10.Lasm_GetById.ssa_block_12:- ldr x1, [x3, #40]- cbz x1, .Lasm_GetById.ssa_block_1- ldrb w9, [x1, #11]+ ldr x2, [x1, #40]+ cbz x2, .Lasm_GetById.ssa_block_1+ ldrb w9, [x2, #11]cbz w9, .Lasm_GetById.ssa_block_1- mov x1, x2+ mov x3, x0b .Lasm_GetById.ssa_block_13.Lasm_GetById.ssa_block_1:- ldr x1, [x4, #152]+ ldr x0, [x28, #88]+ ldr x1, [x0, #152]cbz x1, .Lasm_GetById.assert_failure_21ldr w2, [x21, #20]+ ldr w0, [x21, #8]+ ldr x0, [x27, x0, lsl #3]lsl x2, x2, #3adds x1, x1, x2bl CSYM(asm_try_get_by_id_cache)@@ -14910,12 +14915,12 @@ asm_handler_PutByIdWithThis_cold_end:asm_handler_GetByValue_cold:// Cold paths for GetByValue.Lasm_GetByValue.ssa_block_37:- and x1, x1, #0x3ffffffffff- add x1, x1, x24- ldr x3, [x1, #16]- ldr x1, [x2, #24]- cbz x1, .Lasm_GetByValue.assert_failure_6- mov x0, x1+ and x0, x0, #0x3ffffffffff+ add x0, x0, x24+ ldr x3, [x0, #16]+ ldr x2, [x1, #24]+ cbz x2, .Lasm_GetByValue.assert_failure_6+ mov x0, x2eor x0, x0, x3mov w4, w0movz x9, #0x79b9, lsl #0@@ -14933,16 +14938,16 @@ asm_handler_GetByValue_cold:cmp x9, x3b.ne .Lasm_GetByValue.ssa_block_2ldr x9, [x0, #16]- cmp x9, x1+ cmp x9, x2b.ne .Lasm_GetByValue.ssa_block_2ldr w3, [x0]cmp w3, #3b.ne .Lasm_GetByValue.ssa_block_2ldr w3, [x0, #8]- ldr w9, [x1, #52]+ ldr w9, [x2, #52]cmp w9, w3b.ne .Lasm_GetByValue.ssa_block_2- ldr x1, [x2, #32]+ ldr x1, [x1, #32]cbz x1, .Lasm_GetByValue.assert_failure_8ldr w0, [x0, #4]ldr x0, [x1, x0, lsl #3]@@ -15047,7 +15052,9 @@ asm_handler_GetByValue_cold:ldr x10, [x19, x9, lsl #3]br x10.Lasm_GetByValue.ssa_block_6:- lsr x9, x1, #48+ ldr w0, [x21, #16]+ ldr x0, [x27, x0, lsl #3]+ lsr x9, x0, #48mov w10, #65530cmp x9, x10b.eq .Lasm_GetByValue.ssa_block_37@@ -22120,11 +22127,11 @@ asm_assertion_failure_traps:brk #0.Lasm_GetById.assert_failure_0:brk #0-.Lasm_GetById.assert_predicate_failure_120:+.Lasm_GetById.assert_predicate_failure_123:brk #0.Lasm_GetById.assert_failure_1:brk #0-.Lasm_GetById.assert_predicate_failure_335:+.Lasm_GetById.assert_predicate_failure_338:brk #0.Lasm_GetById.assert_failure_2:brk #0@@ -22134,39 +22141,39 @@ asm_assertion_failure_traps:brk #0.Lasm_GetById.assert_failure_5:brk #0-.Lasm_GetById.assert_predicate_failure_157:+.Lasm_GetById.assert_predicate_failure_160:brk #0.Lasm_GetById.assert_failure_6:brk #0.Lasm_GetById.assert_failure_7:brk #0-.Lasm_GetById.assert_predicate_failure_166:+.Lasm_GetById.assert_predicate_failure_169:brk #0-.Lasm_GetById.assert_predicate_failure_174:+.Lasm_GetById.assert_predicate_failure_177:brk #0.Lasm_GetById.assert_failure_8:brk #0.Lasm_GetById.assert_failure_9:brk #0-.Lasm_GetById.assert_predicate_failure_199:+.Lasm_GetById.assert_predicate_failure_202:brk #0-.Lasm_GetById.assert_predicate_failure_201:+.Lasm_GetById.assert_predicate_failure_204:brk #0.Lasm_GetById.assert_failure_10:brk #0-.Lasm_GetById.assert_predicate_failure_265:+.Lasm_GetById.assert_predicate_failure_268:brk #0-.Lasm_GetById.assert_predicate_failure_274:+.Lasm_GetById.assert_predicate_failure_277:brk #0-.Lasm_GetById.assert_predicate_failure_23:+.Lasm_GetById.assert_predicate_failure_26:brk #0-.Lasm_GetById.assert_predicate_failure_29:+.Lasm_GetById.assert_predicate_failure_32:brk #0.Lasm_GetById.assert_failure_19:brk #0-.Lasm_GetById.assert_predicate_failure_47:+.Lasm_GetById.assert_predicate_failure_50:brk #0-.Lasm_GetById.assert_predicate_failure_53:+.Lasm_GetById.assert_predicate_failure_56:brk #0.Lasm_GetById.assert_failure_20:brk #0@@ -22182,15 +22189,15 @@ asm_assertion_failure_traps:brk #0.Lasm_PutById.assert_failure_2:brk #0-.Lasm_GetByValue.assert_predicate_failure_69:+.Lasm_GetByValue.assert_predicate_failure_70:brk #0.Lasm_GetByValue.assert_failure_0:brk #0-.Lasm_GetByValue.assert_predicate_failure_292:+.Lasm_GetByValue.assert_predicate_failure_293:brk #0.Lasm_GetByValue.assert_failure_2:brk #0-.Lasm_GetByValue.assert_predicate_failure_226:+.Lasm_GetByValue.assert_predicate_failure_227:brk #0.Lasm_GetByValue.assert_failure_3:brk #0diff --git a/Libraries/LibJS/Flap/tests/interpreter-assembly/x86_64.S b/Libraries/LibJS/Flap/tests/interpreter-assembly/x86_64.Sindex 9055d09394e..d0e807f10c6 100644--- a/Libraries/LibJS/Flap/tests/interpreter-assembly/x86_64.S+++ b/Libraries/LibJS/Flap/tests/interpreter-assembly/x86_64.S@@ -3240,15 +3240,15 @@ asm_handler_End_hot_end:.p2align 6asm_handler_GetLexicalEnvironment:- mov rcx, QWORD PTR [rbx - 96]- test rcx, rcx+ mov rax, QWORD PTR [rbx - 96]+ test rax, raxjz .Lasm_GetLexicalEnvironment.assert_predicate_failure_3- movabs rax, 4398046511103- and rcx, rax- movabs rax, -2251799813685248- or rcx, rax+ movabs rcx, 4398046511103+ and rax, rcx+ movabs rcx, -2251799813685248+ or rax, rcxmov r11d, DWORD PTR [r14 + r13 + 4]- mov QWORD PTR [rbx + r11 * 8], rcx+ mov QWORD PTR [rbx + r11 * 8], raxadd r13d, 8movzx eax, BYTE PTR [r14 + r13]jmp [r12 + rax * 8]@@ -4960,33 +4960,33 @@ asm_handler_PutByValue:je .Lasm_PutByValue.ssa_block_20jmp .Lasm_PutByValue.ssa_block_6.Lasm_PutByValue.ssa_block_15:- lea rcx, [rsi + rax * 1]- movabs rax, 4398046511103- and rcx, rax- add rcx, rdx- mov BYTE PTR [rcx], dil+ lea rax, [rsi + rax * 1]+ movabs rcx, 4398046511103+ and rax, rcx+ add rax, rdx+ mov BYTE PTR [rax], diladd r13d, 32movzx eax, BYTE PTR [r14 + r13]jmp [r12 + rax * 8].Lasm_PutByValue.ssa_block_16:- lea rcx, [rsi + rax * 2]- movabs rax, 4398046511103- and rcx, rax- add rcx, rdx- mov WORD PTR [rcx], di+ lea rax, [rsi + rax * 2]+ movabs rcx, 4398046511103+ and rax, rcx+ add rax, rdx+ mov WORD PTR [rax], diadd r13d, 32movzx eax, BYTE PTR [r14 + r13]jmp [r12 + rax * 8].Lasm_PutByValue.ssa_block_17:- lea rcx, [rsi + rax * 1]- movabs rax, 4398046511103- and rcx, rax- add rcx, rdx+ lea rax, [rsi + rax * 1]+ movabs rcx, 4398046511103+ and rax, rcx+ add rax, rdxtest edi, edijns .Lasm_PutByValue.ssa_block_22xor rdi, rdi.Lasm_PutByValue.ssa_block_23:- mov BYTE PTR [rcx], dil+ mov BYTE PTR [rax], diladd r13d, 32movzx eax, BYTE PTR [r14 + r13]jmp [r12 + rax * 8]@@ -4996,33 +4996,33 @@ asm_handler_PutByValue:mov rdi, 255jmp .Lasm_PutByValue.ssa_block_23.Lasm_PutByValue.ssa_block_18:- lea rcx, [rsi + rax * 4]- movabs rax, 4398046511103- and rcx, rax- add rcx, rdx- mov DWORD PTR [rcx], edi+ lea rax, [rsi + rax * 4]+ movabs rcx, 4398046511103+ and rax, rcx+ add rax, rdx+ mov DWORD PTR [rax], ediadd r13d, 32movzx eax, BYTE PTR [r14 + r13]jmp [r12 + rax * 8].Lasm_PutByValue.ssa_block_19:- lea rcx, [rsi + rax * 4]- movabs rax, 4398046511103- and rcx, rax- add rcx, rdx+ lea rax, [rsi + rax * 4]+ movabs rcx, 4398046511103+ and rax, rcx+ add rax, rdxcvtsi2sd xmm0, edicvtsd2ss xmm0, xmm0- movss DWORD PTR [rcx], xmm0+ movss DWORD PTR [rax], xmm0add r13d, 32movzx eax, BYTE PTR [r14 + r13]jmp [r12 + rax * 8].Lasm_PutByValue.ssa_block_20:- lea rcx, [rsi + rax * 8]- movabs rax, 4398046511103- and rcx, rax- add rcx, rdx+ lea rax, [rsi + rax * 8]+ movabs rcx, 4398046511103+ and rax, rcx+ add rax, rdxcvtsi2sd xmm0, edi- movq rax, xmm0- mov QWORD PTR [rcx], rax+ movq rcx, xmm0+ mov QWORD PTR [rax], rcxadd r13d, 32movzx eax, BYTE PTR [r14 + r13]jmp [r12 + rax * 8]@@ -5032,13 +5032,13 @@ asm_handler_PutByValue:and r8w, 32760cmp r8w, 32760je .Lasm_PutByValue.ssa_block_6- lea rcx, [rsi + rax * 4]- movabs rax, 4398046511103- and rcx, rax- add rcx, rdx+ lea rax, [rsi + rax * 4]+ movabs rcx, 4398046511103+ and rax, rcx+ add rax, rdxmovq xmm0, rdicvtsd2ss xmm0, xmm0- movss DWORD PTR [rcx], xmm0+ movss DWORD PTR [rax], xmm0add r13d, 32movzx eax, BYTE PTR [r14 + r13]jmp [r12 + rax * 8]@@ -5062,11 +5062,11 @@ asm_handler_PutByValue:and r8w, 32760cmp r8w, 32760je .Lasm_PutByValue.ssa_block_6- lea rcx, [rsi + rax * 8]- movabs rax, 4398046511103- and rcx, rax- add rcx, rdx- mov QWORD PTR [rcx], rdi+ lea rax, [rsi + rax * 8]+ movabs rcx, 4398046511103+ and rax, rcx+ add rax, rdx+ mov QWORD PTR [rax], rdiadd r13d, 32movzx eax, BYTE PTR [r14 + r13]jmp [r12 + rax * 8]@@ -5082,11 +5082,11 @@ asm_handler_PutByValue:.Lasm_PutByValue.ssa_block_36:movsxd rdi, edi.Lasm_PutByValue.ssa_block_38:- lea rcx, [rsi + rax * 1]- movabs rax, 4398046511103- and rcx, rax- add rcx, rdx- mov BYTE PTR [rcx], dil+ lea rax, [rsi + rax * 1]+ movabs rcx, 4398046511103+ and rax, rcx+ add rax, rdx+ mov BYTE PTR [rax], diladd r13d, 32movzx eax, BYTE PTR [r14 + r13]jmp [r12 + rax * 8]@@ -5102,11 +5102,11 @@ asm_handler_PutByValue:.Lasm_PutByValue.ssa_block_40:movsxd rdi, edi.Lasm_PutByValue.ssa_block_42:- lea rcx, [rsi + rax * 2]- movabs rax, 4398046511103- and rcx, rax- add rcx, rdx- mov WORD PTR [rcx], di+ lea rax, [rsi + rax * 2]+ movabs rcx, 4398046511103+ and rax, rcx+ add rax, rdx+ mov WORD PTR [rax], diadd r13d, 32movzx eax, BYTE PTR [r14 + r13]jmp [r12 + rax * 8]@@ -5122,10 +5122,10 @@ asm_handler_PutByValue:.Lasm_PutByValue.ssa_block_44:movsxd rdi, edi.Lasm_PutByValue.ssa_block_46:- lea rcx, [rsi + rax * 4]- movabs rax, 4398046511103- and rcx, rax- add rdx, rcx+ lea rax, [rsi + rax * 4]+ movabs rcx, 4398046511103+ and rax, rcx+ add rdx, raxmov DWORD PTR [rdx], ediadd r13d, 32movzx eax, BYTE PTR [r14 + r13]@@ -5138,49 +5138,49 @@ asm_handler_PutByValue:test rax, raxjz .Lasm_PutByValue.assert_failure_1mov ecx, DWORD PTR [r14 + r13 + 24]- mov rcx, QWORD PTR [rax + rcx * 8]- test rcx, rcx+ mov rax, QWORD PTR [rax + rcx * 8]+ test rax, raxjz .Lasm_PutByValue.ssa_block_1- cmp rcx, 3+ cmp rax, 3je .Lasm_PutByValue.ssa_block_2- and rcx, -4- mov eax, DWORD PTR [r14 + r13 + 4]- mov rsi, QWORD PTR [rbx + rax * 8]+ and rax, -4+ mov ecx, DWORD PTR [r14 + r13 + 4]+ mov rsi, QWORD PTR [rbx + rcx * 8]mov r11, rsishr r11, 48cmp r11w, 65529jne .Lasm_PutByValue.ssa_block_1- cmp QWORD PTR [rcx + 48], rdx+ cmp QWORD PTR [rax + 48], rdxjne .Lasm_PutByValue.ssa_block_3movabs r11, 4398046511103and rsi, r11add rsi, r15- mov rax, QWORD PTR [rsi + 24]- test rax, rax+ mov rcx, QWORD PTR [rsi + 24]+ test rcx, rcxjz .Lasm_PutByValue.assert_failure_2- mov rdi, QWORD PTR [rcx + 24]- mov rdx, QWORD PTR [rcx + 32]- cmp rdi, rax+ mov rdi, QWORD PTR [rax + 24]+ mov rdx, QWORD PTR [rax + 32]+ cmp rdi, rcxjne .Lasm_PutByValue.ssa_block_3test rdx, rdxjnz .Lasm_PutByValue.ssa_block_3- mov edx, DWORD PTR [rcx + 4]- mov edi, DWORD PTR [rcx + 8]- cmp DWORD PTR [rax + 52], edi+ mov edx, DWORD PTR [rax + 4]+ mov edi, DWORD PTR [rax + 8]+ cmp DWORD PTR [rcx + 52], edijne .Lasm_PutByValue.ssa_block_3- mov rax, QWORD PTR [rsi + 32]- test rax, rax+ mov rcx, QWORD PTR [rsi + 32]+ test rcx, rcxjz .Lasm_PutByValue.assert_failure_3- mov rsi, QWORD PTR [rax + rdx * 8]+ mov rsi, QWORD PTR [rcx + rdx * 8]mov r11, rsishr r11, 48cmp r11w, 65532je .Lasm_PutByValue.ssa_block_3- cmp BYTE PTR [rcx + 13], 0+ cmp BYTE PTR [rax + 13], 0jz .Lasm_PutByValue.ssa_block_3- mov ecx, DWORD PTR [r14 + r13 + 12]- mov rcx, QWORD PTR [rbx + rcx * 8]- mov QWORD PTR [rax + rdx * 8], rcx+ mov eax, DWORD PTR [r14 + r13 + 12]+ mov rax, QWORD PTR [rbx + rax * 8]+ mov QWORD PTR [rcx + rdx * 8], raxadd r13d, 32movzx eax, BYTE PTR [r14 + r13]jmp [r12 + rax * 8]@@ -5189,49 +5189,48 @@ asm_handler_PutByValue_hot_end:.p2align 6asm_handler_GetById:mov eax, DWORD PTR [r14 + r13 + 8]- mov rcx, QWORD PTR [rbx + rax * 8]- mov r11, rcx+ mov rsi, QWORD PTR [rbx + rax * 8]+ mov r11, rsishr r11, 48cmp r11w, 65529jne .Lasm_GetById.ssa_block_14- mov rdx, rcxmovabs r11, 4398046511103- and rdx, r11- add rdx, r15- mov rsi, QWORD PTR [rdx + 24]- test rsi, rsi- jz .Lasm_GetById.assert_failure_0- mov r8, QWORD PTR [rbx - 40]- test r8, r8- jz .Lasm_GetById.assert_predicate_failure_120- mov rax, QWORD PTR [r8 + 152]+ and rsi, r11+ add rsi, r15+ mov rax, QWORD PTR [rsi + 24]test rax, rax+ jz .Lasm_GetById.assert_failure_0+ mov rcx, QWORD PTR [rbx - 40]+ test rcx, rcx+ jz .Lasm_GetById.assert_predicate_failure_123+ mov rdx, QWORD PTR [rcx + 152]+ test rdx, rdxjz .Lasm_GetById.assert_failure_1mov edi, DWORD PTR [r14 + r13 + 20]- mov rdi, QWORD PTR [rax + rdi * 8]- test rdi, rdi+ mov rdx, QWORD PTR [rdx + rdi * 8]+ test rdx, rdxjz .Lasm_GetById.ssa_block_1- and rdi, -4- test rdi, rdi- jz .Lasm_GetById.assert_predicate_failure_335- cmp QWORD PTR [rdi + 24], rsi+ and rdx, -4+ test rdx, rdx+ jz .Lasm_GetById.assert_predicate_failure_338+ cmp QWORD PTR [rdx + 24], raxjne .Lasm_GetById.ssa_block_15- mov eax, DWORD PTR [rdi]- cmp eax, 6+ mov ecx, DWORD PTR [rdx]+ cmp ecx, 6je .Lasm_GetById.ssa_block_1- mov rax, QWORD PTR [rdi + 32]- test rax, rax+ mov rcx, QWORD PTR [rdx + 32]+ test rcx, rcxjnz .Lasm_GetById.ssa_block_18- mov rax, rdx+ mov rcx, rsi.Lasm_GetById.ssa_block_16:- mov r9d, DWORD PTR [rdi + 4]- mov r10d, DWORD PTR [rdi + 8]- cmp DWORD PTR [rsi + 52], r10d+ mov edi, DWORD PTR [rdx + 4]+ mov r8d, DWORD PTR [rdx + 8]+ cmp DWORD PTR [rax + 52], r8djne .Lasm_GetById.ssa_block_1- mov rax, QWORD PTR [rax + 32]+ mov rax, QWORD PTR [rcx + 32]test rax, raxjz .Lasm_GetById.assert_failure_2- mov rax, QWORD PTR [rax + r9 * 8]+ mov rax, QWORD PTR [rax + rdi * 8]mov r11, raxshr r11, 48cmp r11w, 65532@@ -5242,41 +5241,41 @@ asm_handler_GetById:movzx eax, BYTE PTR [r14 + r13]jmp [r12 + rax * 8].Lasm_GetById.ssa_block_15:- mov rax, QWORD PTR [r8 + 152]- test rax, rax+ mov rcx, QWORD PTR [rcx + 152]+ test rcx, rcxjz .Lasm_GetById.assert_failure_3- mov edi, DWORD PTR [r14 + r13 + 20]- mov rdi, QWORD PTR [rax + rdi * 8]- mov r9, rdi- and r9, 3- cmp r9, 1+ mov edx, DWORD PTR [r14 + r13 + 20]+ mov rcx, QWORD PTR [rcx + rdx * 8]+ mov rdx, rcx+ and rdx, 3+ cmp rdx, 1jne .Lasm_GetById.ssa_block_1- and rdi, -4- add rdi, 64- cmp QWORD PTR [rdi + 24], rsi+ and rcx, -4+ add rcx, 64+ cmp QWORD PTR [rcx + 24], raxje .Lasm_GetById.ssa_block_11- add rdi, 64- cmp QWORD PTR [rdi + 24], rsi+ add rcx, 64+ cmp QWORD PTR [rcx + 24], raxje .Lasm_GetById.ssa_block_11- add rdi, 64- cmp QWORD PTR [rdi + 24], rsi+ add rcx, 64+ cmp QWORD PTR [rcx + 24], raxjne .Lasm_GetById.ssa_block_1.Lasm_GetById.ssa_block_11:- mov eax, DWORD PTR [rdi]- cmp eax, 6+ mov edx, DWORD PTR [rcx]+ cmp edx, 6je .Lasm_GetById.ssa_block_1- mov eax, DWORD PTR [rdi + 8]- cmp DWORD PTR [rsi + 52], eax+ mov edx, DWORD PTR [rcx + 8]+ cmp DWORD PTR [rax + 52], edxjne .Lasm_GetById.ssa_block_1- mov rax, QWORD PTR [rdi + 32]+ mov rax, QWORD PTR [rcx + 32]test rax, raxjnz .Lasm_GetById.ssa_block_12.Lasm_GetById.ssa_block_13:- mov rax, QWORD PTR [rdx + 32]+ mov rax, QWORD PTR [rsi + 32]test rax, raxjz .Lasm_GetById.assert_failure_4- mov edx, DWORD PTR [rdi + 4]- mov rax, QWORD PTR [rax + rdx * 8]+ mov ecx, DWORD PTR [rcx + 4]+ mov rax, QWORD PTR [rax + rcx * 8]mov r11, raxshr r11, 48cmp r11w, 65532@@ -5291,16 +5290,16 @@ asm_handler_GetById_hot_end:.p2align 6asm_handler_PutById:mov eax, DWORD PTR [r14 + r13 + 4]- mov rsi, QWORD PTR [rbx + rax * 8]- mov r11, rsi+ mov rdx, QWORD PTR [rbx + rax * 8]+ mov r11, rdxshr r11, 48cmp r11w, 65529jne .Lasm_PutById.ssa_block_2movabs r11, 4398046511103- and rsi, r11- add rsi, r15- mov rdx, QWORD PTR [rsi + 24]- test rdx, rdx+ and rdx, r11+ add rdx, r15+ mov rcx, QWORD PTR [rdx + 24]+ test rcx, rcxjz .Lasm_PutById.assert_failure_0mov rax, QWORD PTR [rbx - 40]test rax, rax@@ -5308,36 +5307,36 @@ asm_handler_PutById:mov rax, QWORD PTR [rax + 152]test rax, raxjz .Lasm_PutById.assert_failure_1- mov ecx, DWORD PTR [r14 + r13 + 20]- mov rcx, QWORD PTR [rax + rcx * 8]- test rcx, rcx+ mov esi, DWORD PTR [r14 + r13 + 20]+ mov rax, QWORD PTR [rax + rsi * 8]+ test rax, raxjz .Lasm_PutById.ssa_block_2- and rcx, -4- test rcx, rcx+ and rax, -4+ test rax, raxjz .Lasm_PutById.assert_predicate_failure_23- mov rdi, QWORD PTR [rcx + 24]- mov rax, QWORD PTR [rcx + 32]- cmp rdi, rdx+ mov rdi, QWORD PTR [rax + 24]+ mov rsi, QWORD PTR [rax + 32]+ cmp rdi, rcxjne .Lasm_PutById.ssa_block_2- test rax, rax+ test rsi, rsijnz .Lasm_PutById.ssa_block_2- mov edi, DWORD PTR [rcx + 4]- mov eax, DWORD PTR [rcx + 8]- cmp DWORD PTR [rdx + 52], eax+ mov esi, DWORD PTR [rax + 4]+ mov edi, DWORD PTR [rax + 8]+ cmp DWORD PTR [rcx + 52], edijne .Lasm_PutById.ssa_block_2- mov rax, QWORD PTR [rsi + 32]- test rax, rax+ mov rcx, QWORD PTR [rdx + 32]+ test rcx, rcxjz .Lasm_PutById.assert_failure_2- mov rdx, QWORD PTR [rax + rdi * 8]+ mov rdx, QWORD PTR [rcx + rsi * 8]mov r11, rdxshr r11, 48cmp r11w, 65532je .Lasm_PutById.ssa_block_2- cmp BYTE PTR [rcx + 13], 0+ cmp BYTE PTR [rax + 13], 0jz .Lasm_PutById.ssa_block_2- mov ecx, DWORD PTR [r14 + r13 + 12]- mov rcx, QWORD PTR [rbx + rcx * 8]- mov QWORD PTR [rax + rdi * 8], rcx+ mov eax, DWORD PTR [r14 + r13 + 12]+ mov rax, QWORD PTR [rbx + rax * 8]+ mov QWORD PTR [rcx + rsi * 8], raxadd r13d, 32movzx eax, BYTE PTR [r14 + r13]jmp [r12 + rax * 8]@@ -5374,7 +5373,7 @@ asm_handler_GetByValue:jae .Lasm_GetByValue.ssa_block_1mov rcx, QWORD PTR [rsi + 40]test rcx, rcx- jz .Lasm_GetByValue.assert_predicate_failure_69+ jz .Lasm_GetByValue.assert_predicate_failure_70mov edx, DWORD PTR [rcx - 8]cmp rax, rdxjae .Lasm_GetByValue.ssa_block_1@@ -5420,11 +5419,11 @@ asm_handler_GetByValue:movzx esi, BYTE PTR [rsi + 72]cmp rsi, 2jae .Lasm_GetByValue.ssa_switch_20_after_preferred- lea rdx, [rdx + rax * 1]- movabs rax, 4398046511103- and rdx, rax- add rdx, rcx- movzx eax, BYTE PTR [rdx]+ lea rax, [rdx + rax * 1]+ movabs rdx, 4398046511103+ and rax, rdx+ add rax, rcx+ movzx eax, BYTE PTR [rax]movabs r11, 9221683186994511872or rax, r11mov r11d, DWORD PTR [r14 + r13 + 8]@@ -5449,39 +5448,39 @@ asm_handler_GetByValue:je .Lasm_GetByValue.ssa_block_31jmp .Lasm_GetByValue.ssa_block_4.Lasm_GetByValue.ssa_block_25:- lea rdx, [rdx + rax * 4]- movabs rax, 4398046511103- and rdx, rax- add rdx, rcx- mov eax, DWORD PTR [rdx]+ lea rax, [rdx + rax * 4]+ movabs rdx, 4398046511103+ and rax, rdx+ add rax, rcx+ mov eax, DWORD PTR [rax]jmp .Lasm_GetByValue.ssa_block_11.Lasm_GetByValue.ssa_block_26:- lea rdx, [rdx + rax * 2]- movabs rax, 4398046511103- and rdx, rax- add rdx, rcx- movzx eax, WORD PTR [rdx]+ lea rax, [rdx + rax * 2]+ movabs rdx, 4398046511103+ and rax, rdx+ add rax, rcx+ movzx eax, WORD PTR [rax]jmp .Lasm_GetByValue.ssa_block_11.Lasm_GetByValue.ssa_block_27:- lea rdx, [rdx + rax * 1]- movabs rax, 4398046511103- and rdx, rax- add rdx, rcx- movsx eax, BYTE PTR [rdx]+ lea rax, [rdx + rax * 1]+ movabs rdx, 4398046511103+ and rax, rdx+ add rax, rcx+ movsx eax, BYTE PTR [rax]jmp .Lasm_GetByValue.ssa_block_11.Lasm_GetByValue.ssa_block_28:- lea rdx, [rdx + rax * 2]- movabs rax, 4398046511103- and rdx, rax- add rdx, rcx- movsx eax, WORD PTR [rdx]+ lea rax, [rdx + rax * 2]+ movabs rdx, 4398046511103+ and rax, rdx+ add rax, rcx+ movsx eax, WORD PTR [rax]jmp .Lasm_GetByValue.ssa_block_11.Lasm_GetByValue.ssa_block_29:- lea rdx, [rdx + rax * 4]- movabs rax, 4398046511103- and rdx, rax- add rdx, rcx- mov eax, DWORD PTR [rdx]+ lea rax, [rdx + rax * 4]+ movabs rdx, 4398046511103+ and rax, rdx+ add rax, rcx+ mov eax, DWORD PTR [rax]test eax, eaxjs .Lasm_GetByValue.ssa_block_12.Lasm_GetByValue.ssa_block_11:@@ -5493,11 +5492,11 @@ asm_handler_GetByValue:movzx eax, BYTE PTR [r14 + r13]jmp [r12 + rax * 8].Lasm_GetByValue.ssa_block_30:- lea rdx, [rdx + rax * 4]- movabs rax, 4398046511103- and rdx, rax- add rdx, rcx- movss xmm0, DWORD PTR [rdx]+ lea rax, [rdx + rax * 4]+ movabs rdx, 4398046511103+ and rax, rdx+ add rax, rcx+ movss xmm0, DWORD PTR [rax]cvtss2sd xmm0, xmm0movq rax, xmm0movabs rcx, -9223372036854775808@@ -5511,10 +5510,10 @@ asm_handler_GetByValue:jne .Lasm_GetByValue.ssa_block_10jmp .Lasm_GetByValue.ssa_block_9.Lasm_GetByValue.ssa_block_31:- lea rdx, [rdx + rax * 8]- movabs rax, 4398046511103- and rdx, rax- add rcx, rdx+ lea rax, [rdx + rax * 8]+ movabs rdx, 4398046511103+ and rax, rdx+ add rcx, raxmov rax, QWORD PTR [rcx]movq xmm0, raxmovabs rcx, -9223372036854775808@@ -5601,7 +5600,7 @@ asm_handler_GetByValue:mov r11, raxshr r11, 48cmp r11w, 65530- jne .Lasm_GetByValue.assert_predicate_failure_292+ jne .Lasm_GetByValue.assert_predicate_failure_293mov r11d, DWORD PTR [r14 + r13 + 8]mov QWORD PTR [rbx + r11 * 8], raxadd r13d, 32@@ -5609,56 +5608,56 @@ asm_handler_GetByValue:jmp [r12 + rax * 8].Lasm_GetByValue.ssa_block_5:mov eax, DWORD PTR [r14 + r13 + 12]- mov rsi, QWORD PTR [rbx + rax * 8]- mov r11, rsi+ mov rcx, QWORD PTR [rbx + rax * 8]+ mov r11, rcxshr r11, 48cmp r11w, 65529jne .Lasm_GetByValue.ssa_block_1mov rax, QWORD PTR [rbx - 40]- mov rcx, QWORD PTR [rax + 152]- test rcx, rcx+ mov rsi, QWORD PTR [rax + 152]+ test rsi, rsijz .Lasm_GetByValue.assert_failure_2mov edi, DWORD PTR [r14 + r13 + 24]- mov rcx, QWORD PTR [rcx + rdi * 8]+ mov rsi, QWORD PTR [rsi + rdi * 8]movabs r11, 4398046511103- and rsi, r11- add rsi, r15- cmp rcx, 3+ and rcx, r11+ add rcx, r15+ cmp rsi, 3je .Lasm_GetByValue.ssa_block_6test rax, rax- jz .Lasm_GetByValue.assert_predicate_failure_226+ jz .Lasm_GetByValue.assert_predicate_failure_227mov rax, QWORD PTR [rax + 152]test rax, raxjz .Lasm_GetByValue.assert_failure_3- mov ecx, DWORD PTR [r14 + r13 + 24]- mov rcx, QWORD PTR [rax + rcx * 8]- test rcx, rcx+ mov esi, DWORD PTR [r14 + r13 + 24]+ mov rax, QWORD PTR [rax + rsi * 8]+ test rax, raxjz .Lasm_GetByValue.ssa_block_1- cmp rcx, 3+ cmp rax, 3je .Lasm_GetByValue.ssa_block_2- and rcx, -4- cmp QWORD PTR [rcx + 48], rdx+ and rax, -4+ cmp QWORD PTR [rax + 48], rdxjne .Lasm_GetByValue.ssa_block_3- mov rax, QWORD PTR [rsi + 24]- test rax, rax+ mov rdx, QWORD PTR [rcx + 24]+ test rdx, rdxjz .Lasm_GetByValue.assert_failure_4- mov rdi, QWORD PTR [rcx + 24]- mov rdx, QWORD PTR [rcx + 32]- cmp rdi, rax+ mov rdi, QWORD PTR [rax + 24]+ mov rsi, QWORD PTR [rax + 32]+ cmp rdi, rdxjne .Lasm_GetByValue.ssa_block_3- mov edi, DWORD PTR [rcx]+ mov edi, DWORD PTR [rax]cmp edi, 6je .Lasm_GetByValue.ssa_block_3- mov edi, DWORD PTR [rcx + 8]- cmp DWORD PTR [rax + 52], edi+ mov edi, DWORD PTR [rax + 8]+ cmp DWORD PTR [rdx + 52], edijne .Lasm_GetByValue.ssa_block_3- test rdx, rdx+ test rsi, rsijnz .Lasm_GetByValue.ssa_block_3- mov rax, QWORD PTR [rsi + 32]- test rax, rax+ mov rcx, QWORD PTR [rcx + 32]+ test rcx, rcxjz .Lasm_GetByValue.assert_failure_5- mov ecx, DWORD PTR [rcx + 4]- mov rax, QWORD PTR [rax + rcx * 8]+ mov eax, DWORD PTR [rax + 4]+ mov rax, QWORD PTR [rcx + rax * 8]mov r11, raxshr r11, 48cmp r11w, 65532@@ -5673,18 +5672,18 @@ asm_handler_GetByValue_hot_end:.p2align 6asm_handler_GetLength:mov eax, DWORD PTR [r14 + r13 + 12]- mov rdx, QWORD PTR [rbx + rax * 8]- mov rax, rdx+ mov rcx, QWORD PTR [rbx + rax * 8]+ mov rax, rcxshr rax, 48cmp ax, 65529jne .Lasm_GetLength.ssa_block_2movabs r11, 4398046511103- and rdx, r11- add rdx, r15- movzx eax, WORD PTR [rdx + 12]+ and rcx, r11+ add rcx, r15+ movzx eax, WORD PTR [rcx + 12]test eax, 4jz .Lasm_GetLength.ssa_block_6- mov eax, DWORD PTR [rdx + 16]+ mov eax, DWORD PTR [rcx + 16]test eax, eaxjs .Lasm_GetLength.ssa_block_3movabs r11, 9221683186994511872@@ -5695,8 +5694,8 @@ asm_handler_GetLength:movzx eax, BYTE PTR [r14 + r13]jmp [r12 + rax * 8].Lasm_GetLength.ssa_block_6:- mov rsi, QWORD PTR [rdx + 24]- test rsi, rsi+ mov rdx, QWORD PTR [rcx + 24]+ test rdx, rdxjz .Lasm_GetLength.assert_failure_0mov rax, QWORD PTR [rbx - 40]test rax, rax@@ -5704,30 +5703,30 @@ asm_handler_GetLength:mov rax, QWORD PTR [rax + 152]test rax, raxjz .Lasm_GetLength.assert_failure_1- mov ecx, DWORD PTR [r14 + r13 + 20]- mov rcx, QWORD PTR [rax + rcx * 8]- test rcx, rcx+ mov esi, DWORD PTR [r14 + r13 + 20]+ mov rax, QWORD PTR [rax + rsi * 8]+ test rax, raxjz .Lasm_GetLength.ssa_block_1- and rcx, -4- test rcx, rcx+ and rax, -4+ test rax, raxjz .Lasm_GetLength.assert_predicate_failure_43- mov rdi, QWORD PTR [rcx + 24]- mov rax, QWORD PTR [rcx + 32]- cmp rdi, rsi+ mov rdi, QWORD PTR [rax + 24]+ mov rsi, QWORD PTR [rax + 32]+ cmp rdi, rdxjne .Lasm_GetLength.ssa_block_1- mov edi, DWORD PTR [rcx]+ mov edi, DWORD PTR [rax]cmp edi, 6je .Lasm_GetLength.ssa_block_1- test rax, rax+ test rsi, rsijnz .Lasm_GetLength.ssa_block_1- mov eax, DWORD PTR [rcx + 8]- mov ecx, DWORD PTR [rcx + 4]- cmp DWORD PTR [rsi + 52], eax+ mov esi, DWORD PTR [rax + 4]+ mov eax, DWORD PTR [rax + 8]+ cmp DWORD PTR [rdx + 52], eaxjne .Lasm_GetLength.ssa_block_1- mov rax, QWORD PTR [rdx + 32]+ mov rax, QWORD PTR [rcx + 32]test rax, raxjz .Lasm_GetLength.assert_failure_2- mov rax, QWORD PTR [rax + rcx * 8]+ mov rax, QWORD PTR [rax + rsi * 8]mov r11, raxshr r11, 48cmp r11w, 65532@@ -5741,9 +5740,9 @@ asm_handler_GetLength:cmp ax, 65530jne .Lasm_GetLength.ssa_block_1movabs r11, 4398046511103- and rdx, r11- add rdx, r15- mov eax, DWORD PTR [rdx + 12]+ and rcx, r11+ add rcx, r15+ mov eax, DWORD PTR [rcx + 12]test eax, eaxjs .Lasm_GetLength.ssa_block_1movabs r11, 9221683186994511872@@ -5972,48 +5971,48 @@ asm_handler_Call:test rax, raxjz .Lasm_Call.assert_failure_0mov rdi, QWORD PTR [rax + 16]- mov rdx, QWORD PTR [rax + 24]- bt rdx, 32+ mov rax, QWORD PTR [rax + 24]+ bt rax, 32jnc .Lasm_Call.ssa_block_1- bt rdx, 33+ bt rax, 33jc .Lasm_Call.ssa_block_2movabs r9, 9221964661971222528- bt rdx, 34+ bt rax, 34jnc .Lasm_Call.ssa_block_9- mov eax, DWORD PTR [r14 + r13 + 20]- mov r9, QWORD PTR [rbx + rax * 8]- bt rdx, 35+ mov edx, DWORD PTR [r14 + r13 + 20]+ mov r9, QWORD PTR [rbx + rdx * 8]+ bt rax, 35jc .Lasm_Call.ssa_block_9- mov rax, r9- shr rax, 48- mov rsi, rax+ mov rdx, r9+ shr rdx, 48+ mov rsi, rdxand si, 65534cmp si, 32766jne .Lasm_Call.ssa_block_13- mov rax, QWORD PTR [rcx + 24]- test rax, rax+ mov rdx, QWORD PTR [rcx + 24]+ test rdx, rdxjz .Lasm_Call.assert_failure_1- mov rax, QWORD PTR [rax + 16]- test rax, rax+ mov rdx, QWORD PTR [rdx + 16]+ test rdx, rdxjz .Lasm_Call.assert_failure_2- mov rax, QWORD PTR [rax + 32]- test rax, rax+ mov rdx, QWORD PTR [rdx + 32]+ test rdx, rdxjz .Lasm_Call.assert_failure_3- mov r9, QWORD PTR [rax + 32]- movabs rax, 4398046511103- and r9, rax- movabs rax, -1970324836974592- or r9, rax+ mov r9, QWORD PTR [rdx + 32]+ movabs rdx, 4398046511103+ and r9, rdx+ movabs rdx, -1970324836974592+ or r9, rdxjmp .Lasm_Call.ssa_block_9.Lasm_Call.ssa_block_13:- cmp ax, 65529+ cmp dx, 65529jne .Lasm_Call.ssa_block_2.Lasm_Call.ssa_block_9:- mov eax, DWORD PTR [r14 + r13 + 24]- mov edx, edx- cmp rdx, rax+ mov esi, DWORD PTR [r14 + r13 + 24]+ mov edx, eax+ cmp rdx, rsijae .Lasm_Call.ssa_block_27- mov rdx, rax+ mov rdx, rsi.Lasm_Call.ssa_block_27:test rdi, rdijz .Lasm_Call.assert_predicate_failure_280@@ -6257,22 +6256,21 @@ asm_handler_Call:mov rdi, QWORD PTR [rbp - 48]call r11mov rcx, rdx- mov rdx, raxand rcx, 255cmp rcx, 2jae .Lasm_Call.assert_predicate_failure_258test rcx, rcxjnz .Lasm_Call.ssa_block_4- mov rax, QWORD PTR [rbx - 32]- test rax, rax+ mov rcx, QWORD PTR [rbx - 32]+ test rcx, rcxjz .Lasm_Call.assert_predicate_failure_264- mov rcx, QWORD PTR [rbp - 48]- mov QWORD PTR [rcx], rax+ mov rdx, QWORD PTR [rbp - 48]+ mov QWORD PTR [rdx], rcxlea r11, [rbx - 128]- mov QWORD PTR [rcx + 16], r11- lea rbx, [rax + 128]+ mov QWORD PTR [rdx + 16], r11+ lea rbx, [rcx + 128]mov r11d, DWORD PTR [r14 + r13 + 12]- mov QWORD PTR [rbx + r11 * 8], rdx+ mov QWORD PTR [rbx + r11 * 8], raxmov ecx, DWORD PTR [r14 + r13 + 8]add r13d, ecxmovzx eax, BYTE PTR [r14 + r13]@@ -13795,6 +13793,8 @@ asm_handler_PostfixDecrement_cold_end:asm_handler_ToInt32_cold:# Cold paths for ToInt32.Lasm_ToInt32.ssa_block_2:+ mov eax, DWORD PTR [r14 + r13 + 8]+ mov rax, QWORD PTR [rbx + rax * 8]mov rcx, raxshr rcx, 48cmp rcx, 32762@@ -14060,71 +14060,71 @@ asm_handler_PutByValue_cold_end:asm_handler_GetById_cold:# Cold paths for GetById.Lasm_GetById.ssa_block_24:- cmp BYTE PTR [rdi + 12], 0+ cmp BYTE PTR [rdx + 12], 0jz .Lasm_GetById.ssa_block_3- movzx ecx, WORD PTR [rdx + 12]- test ecx, 512+ movzx eax, WORD PTR [rsi + 12]+ test eax, 512jz .Lasm_GetById.ssa_block_3- mov ecx, DWORD PTR [rax + 112]- mov rcx, QWORD PTR [rdx + rcx * 8]- test rcx, rcx+ mov eax, DWORD PTR [rcx + 112]+ mov rax, QWORD PTR [rsi + rax * 8]+ test rax, raxjz .Lasm_GetById.ssa_block_3- mov esi, DWORD PTR [rax + 120]- mov r8, QWORD PTR [rcx + rsi * 8]+ mov edx, DWORD PTR [rcx + 120]+ mov r8, QWORD PTR [rax + rdx * 8]test r8, r8jz .Lasm_GetById.ssa_block_3- mov edi, DWORD PTR [rax + 124]+ mov edi, DWORD PTR [rcx + 124]mov r8, QWORD PTR [r8 + rdi * 8]- cmp r8, rdx+ cmp r8, rsijne .Lasm_GetById.ssa_block_3- mov eax, DWORD PTR [rax + 116]- mov rax, QWORD PTR [rcx + rax * 8]+ mov ecx, DWORD PTR [rcx + 116]+ mov rax, QWORD PTR [rax + rcx * 8]test rax, raxjnz .Lasm_GetById.ssa_block_50- movabs rcx, 9223090561878065152+ movabs rax, 9223090561878065152jmp .Lasm_GetById.ssa_block_51.Lasm_GetById.ssa_block_50:- mov rax, QWORD PTR [rax + rsi * 8]+ mov rax, QWORD PTR [rax + rdx * 8]test rax, raxjz .Lasm_GetById.ssa_block_3- mov rcx, QWORD PTR [rax + rdi * 8]- test rcx, rcx+ mov rax, QWORD PTR [rax + rdi * 8]+ test rax, raxjz .Lasm_GetById.ssa_block_3- movzx eax, WORD PTR [rcx + 12]- test eax, 2048+ movzx ecx, WORD PTR [rax + 12]+ test ecx, 2048jnz .Lasm_GetById.ssa_block_3- movabs rax, 4398046511103- and rcx, rax- movabs rax, -1970324836974592- or rcx, rax+ movabs rcx, 4398046511103+ and rax, rcx+ movabs rcx, -1970324836974592+ or rax, rcx.Lasm_GetById.ssa_block_51:mov r11d, DWORD PTR [r14 + r13 + 4]- mov QWORD PTR [rbx + r11 * 8], rcx+ mov QWORD PTR [rbx + r11 * 8], raxadd r13d, 24movzx eax, BYTE PTR [r14 + r13]jmp [r12 + rax * 8].Lasm_GetById.ssa_block_25:- mov esi, DWORD PTR [rax + 104]- mov rcx, QWORD PTR [rbp - 48]- mov rcx, QWORD PTR [rcx + 80]- test rcx, rcx+ mov edx, DWORD PTR [rcx + 104]+ mov rax, QWORD PTR [rbp - 48]+ mov rax, QWORD PTR [rax + 80]+ test rax, raxjz .Lasm_GetById.assert_failure_5- and esi, 65535- shl rsi, 4- add rsi, rcx- mov edi, DWORD PTR [rsi + 8]+ and edx, 65535+ shl rdx, 4+ add rdx, rax+ mov edi, DWORD PTR [rdx + 8]cmp rdi, 1- jae .Lasm_GetById.assert_predicate_failure_157- mov rcx, QWORD PTR [rbp - 48]- mov r9, QWORD PTR [rcx + 24]- mov rcx, QWORD PTR [rcx + 16]- test rcx, rcx+ jae .Lasm_GetById.assert_predicate_failure_160+ mov rax, QWORD PTR [rbp - 48]+ mov r9, QWORD PTR [rax + 24]+ mov rax, QWORD PTR [rax + 16]+ test rax, raxjz .Lasm_GetById.assert_failure_6test r9, r9jz .Lasm_GetById.assert_failure_7- lea r8, [rcx + 128]- cmp r8, rcx- jb .Lasm_GetById.assert_predicate_failure_166+ lea r8, [rax + 128]+ cmp r8, rax+ jb .Lasm_GetById.assert_predicate_failure_169cmp r8, r9ja .Lasm_GetById.ssa_block_3mov r9, QWORD PTR [rbp - 48]@@ -14132,86 +14132,85 @@ asm_handler_GetById_cold:mov r9, r10add r9, 32768cmp r9, r10- jb .Lasm_GetById.assert_predicate_failure_174+ jb .Lasm_GetById.assert_predicate_failure_177cmp r9, rbpja .Lasm_GetById.ssa_block_3mov r9, QWORD PTR [rbp - 48]mov QWORD PTR [r9 + 16], r8- mov DWORD PTR [rcx + 116], edi- mov DWORD PTR [rcx + 120], edi- mov DWORD PTR [rcx + 104], 0- mov rdi, QWORD PTR [rax + 24]+ mov DWORD PTR [rax + 116], edi+ mov DWORD PTR [rax + 120], edi+ mov DWORD PTR [rax + 104], 0+ mov rdi, QWORD PTR [rcx + 24]test rdi, rdijz .Lasm_GetById.assert_failure_8mov rdi, QWORD PTR [rdi + 16]test rdi, rdijz .Lasm_GetById.assert_failure_9- mov QWORD PTR [rcx], rax- mov QWORD PTR [rcx + 8], rdi- mov rax, QWORD PTR [rbx - 96]+ mov QWORD PTR [rax], rcx+ mov QWORD PTR [rax + 8], rdi+ mov rcx, QWORD PTR [rbx - 96]mov rdi, QWORD PTR [rbx - 88]- test rax, rax- jz .Lasm_GetById.assert_predicate_failure_199+ test rcx, rcx+ jz .Lasm_GetById.assert_predicate_failure_202test rdi, rdi- jz .Lasm_GetById.assert_predicate_failure_201- mov QWORD PTR [rcx + 32], rax- mov QWORD PTR [rcx + 40], rdi- mov rax, QWORD PTR [rbx - 80]- mov QWORD PTR [rcx + 48], rax- movabs rax, 4398046511103- and rdx, rax- movabs rax, -1970324836974592- or rdx, rax- mov QWORD PTR [rcx + 80], rdx- xor rax, rax- lea rdx, [rcx + 16]- mov QWORD PTR [rdx], rax- mov QWORD PTR [rdx + 8], rax- mov QWORD PTR [rcx + 88], 0- mov DWORD PTR [rcx + 64], 0- mov DWORD PTR [rcx + 68], 0- mov DWORD PTR [rcx + 72], 4294967295- mov BYTE PTR [rcx + 76], 0- mov BYTE PTR [rcx + 77], 0- mov BYTE PTR [rcx + 78], 0- mov BYTE PTR [rcx + 79], 0- mov BYTE PTR [rcx + 124], 0- mov BYTE PTR [rcx + 125], 0- mov eax, r13d- mov edx, DWORD PTR [r14 + r13 + 4]+ jz .Lasm_GetById.assert_predicate_failure_204+ mov QWORD PTR [rax + 32], rcx+ mov QWORD PTR [rax + 40], rdi+ mov rcx, QWORD PTR [rbx - 80]+ mov QWORD PTR [rax + 48], rcx+ movabs rcx, 4398046511103+ and rsi, rcx+ movabs rcx, -1970324836974592+ or rsi, rcx+ mov QWORD PTR [rax + 80], rsi+ xor rcx, rcx+ lea rsi, [rax + 16]+ mov QWORD PTR [rsi], rcx+ mov QWORD PTR [rsi + 8], rcx+ mov QWORD PTR [rax + 88], 0+ mov DWORD PTR [rax + 64], 0+ mov DWORD PTR [rax + 68], 0+ mov DWORD PTR [rax + 72], 4294967295+ mov BYTE PTR [rax + 76], 0+ mov BYTE PTR [rax + 77], 0+ mov BYTE PTR [rax + 78], 0+ mov BYTE PTR [rax + 79], 0+ mov BYTE PTR [rax + 124], 0+ mov BYTE PTR [rax + 125], 0+ mov ecx, r13d+ mov esi, DWORD PTR [r14 + r13 + 4]mov edi, DWORD PTR [r14 + r13 + 8]- mov DWORD PTR [rbx - 64], eax+ mov DWORD PTR [rbx - 64], ecxlea r11, [rbx - 128]- mov QWORD PTR [rcx + 96], r11- lea rax, [rax + 1]- mov DWORD PTR [rcx + 108], eax- mov DWORD PTR [rcx + 112], edx- mov rax, QWORD PTR [rbp - 48]- mov QWORD PTR [rax], rcx- lea rbx, [rcx + 128]- mov rdx, QWORD PTR [rsi]+ mov QWORD PTR [rax + 96], r11+ lea rcx, [rcx + 1]+ mov DWORD PTR [rax + 108], ecx+ mov DWORD PTR [rax + 112], esi+ mov rcx, QWORD PTR [rbp - 48]+ mov QWORD PTR [rcx], rax+ lea rbx, [rax + 128]+ mov rdx, QWORD PTR [rdx]test rdx, rdxjz .Lasm_GetById.assert_failure_10mov r11, rdxmov rdi, QWORD PTR [rbp - 48]call r11mov rcx, rdx- mov rdx, raxand rcx, 255cmp rcx, 2- jae .Lasm_GetById.assert_predicate_failure_265+ jae .Lasm_GetById.assert_predicate_failure_268test rcx, rcxjnz .Lasm_GetById.ssa_block_6- mov rax, QWORD PTR [rbx - 32]- test rax, rax- jz .Lasm_GetById.assert_predicate_failure_274- mov rcx, QWORD PTR [rbp - 48]- mov QWORD PTR [rcx], rax+ mov rcx, QWORD PTR [rbx - 32]+ test rcx, rcx+ jz .Lasm_GetById.assert_predicate_failure_277+ mov rdx, QWORD PTR [rbp - 48]+ mov QWORD PTR [rdx], rcxlea r11, [rbx - 128]- mov QWORD PTR [rcx + 16], r11- lea rbx, [rax + 128]+ mov QWORD PTR [rdx + 16], r11+ lea rbx, [rcx + 128]mov r11d, DWORD PTR [r14 + r13 + 4]- mov QWORD PTR [rbx + r11 * 8], rdx+ mov QWORD PTR [rbx + r11 * 8], raxadd r13d, 24movzx eax, BYTE PTR [r14 + r13]jmp [r12 + rax * 8]@@ -14261,23 +14260,23 @@ asm_handler_GetById_cold:movzx eax, BYTE PTR [r14 + r13]jmp [r12 + rax * 8].Lasm_GetById.ssa_block_18:- mov r9, QWORD PTR [rdi + 40]- test r9, r9+ mov rdi, QWORD PTR [rdx + 40]+ test rdi, rdijz .Lasm_GetById.ssa_block_1- cmp BYTE PTR [r9 + 11], 0+ cmp BYTE PTR [rdi + 11], 0jz .Lasm_GetById.ssa_block_1jmp .Lasm_GetById.ssa_block_16.Lasm_GetById.ssa_block_17:movabs r11, 4398046511103and rax, r11add rax, r15- mov rax, QWORD PTR [rax + 16]- test rax, rax+ mov rcx, QWORD PTR [rax + 16]+ test rcx, rcxjz .Lasm_GetById.ssa_block_5- movzx ecx, WORD PTR [rax + 12]- test ecx, 2+ movzx eax, WORD PTR [rcx + 12]+ test eax, 2jz .Lasm_GetById.ssa_block_3- test ecx, 1024+ test eax, 1024jz .Lasm_GetById.ssa_block_25jmp .Lasm_GetById.ssa_block_24.Lasm_GetById.ssa_block_3:@@ -14315,10 +14314,10 @@ asm_handler_GetById_cold:mov rbx, QWORD PTR [rax]add rbx, 128test rbx, rbx- jz .Lasm_GetById.assert_predicate_failure_23+ jz .Lasm_GetById.assert_predicate_failure_26mov rax, QWORD PTR [rbx - 40]test rax, rax- jz .Lasm_GetById.assert_predicate_failure_29+ jz .Lasm_GetById.assert_predicate_failure_32mov r14, QWORD PTR [rax + 40]test r14, r14jz .Lasm_GetById.assert_failure_19@@ -14326,6 +14325,7 @@ asm_handler_GetById_cold:movzx eax, BYTE PTR [r14 + r13]jmp [r12 + rax * 8].Lasm_GetById.ssa_block_6:+ mov rdx, raxmov rcx, QWORD PTR [rbp - 48]mov rdi, rcxmov rsi, rdx@@ -14336,10 +14336,10 @@ asm_handler_GetById_cold:mov rbx, QWORD PTR [rax]add rbx, 128test rbx, rbx- jz .Lasm_GetById.assert_predicate_failure_47+ jz .Lasm_GetById.assert_predicate_failure_50mov rax, QWORD PTR [rbx - 40]test rax, rax- jz .Lasm_GetById.assert_predicate_failure_53+ jz .Lasm_GetById.assert_predicate_failure_56mov r14, QWORD PTR [rax + 40]test r14, r14jz .Lasm_GetById.assert_failure_20@@ -14347,18 +14347,21 @@ asm_handler_GetById_cold:movzx eax, BYTE PTR [r14 + r13]jmp [r12 + rax * 8].Lasm_GetById.ssa_block_12:- mov rdx, QWORD PTR [rdi + 40]+ mov rdx, QWORD PTR [rcx + 40]test rdx, rdxjz .Lasm_GetById.ssa_block_1cmp BYTE PTR [rdx + 11], 0jz .Lasm_GetById.ssa_block_1- mov rdx, rax+ mov rsi, raxjmp .Lasm_GetById.ssa_block_13.Lasm_GetById.ssa_block_1:- mov rdx, QWORD PTR [r8 + 152]+ mov rax, QWORD PTR [rbx - 40]+ mov rdx, QWORD PTR [rax + 152]test rdx, rdxjz .Lasm_GetById.assert_failure_21mov eax, DWORD PTR [r14 + r13 + 20]+ mov ecx, DWORD PTR [r14 + r13 + 8]+ mov rcx, QWORD PTR [rbx + rcx * 8]shl rax, 3add rdx, raxmov rdi, rcx@@ -14613,14 +14616,14 @@ asm_handler_GetByValue_cold:# Cold paths for GetByValue.Lasm_GetByValue.ssa_block_37:movabs r11, 4398046511103- and rdx, r11- add rdx, r15- mov rdx, QWORD PTR [rdx + 16]- mov rcx, QWORD PTR [rsi + 24]- test rcx, rcx+ and rax, r11+ add rax, r15+ mov rsi, QWORD PTR [rax + 16]+ mov rdx, QWORD PTR [rcx + 24]+ test rdx, rdxjz .Lasm_GetByValue.assert_failure_6- mov rax, rcx- xor rax, rdx+ mov rax, rdx+ xor rax, rsimov edi, eaximul rdi, rdi, -1640531527shr edi, 21@@ -14630,17 +14633,17 @@ asm_handler_GetByValue_cold:jz .Lasm_GetByValue.assert_failure_7shl rdi, 6add rax, rdi- cmp QWORD PTR [rax + 48], rdx+ cmp QWORD PTR [rax + 48], rsijne .Lasm_GetByValue.ssa_block_2- cmp QWORD PTR [rax + 16], rcx+ cmp QWORD PTR [rax + 16], rdxjne .Lasm_GetByValue.ssa_block_2- mov edx, DWORD PTR [rax]- cmp edx, 3+ mov esi, DWORD PTR [rax]+ cmp esi, 3jne .Lasm_GetByValue.ssa_block_2- mov edx, DWORD PTR [rax + 8]- cmp DWORD PTR [rcx + 52], edx+ mov esi, DWORD PTR [rax + 8]+ cmp DWORD PTR [rdx + 52], esijne .Lasm_GetByValue.ssa_block_2- mov rcx, QWORD PTR [rsi + 32]+ mov rcx, QWORD PTR [rcx + 32]test rcx, rcxjz .Lasm_GetByValue.assert_failure_8mov eax, DWORD PTR [rax + 4]@@ -14743,7 +14746,9 @@ asm_handler_GetByValue_cold:movzx eax, BYTE PTR [r14 + r13]jmp [r12 + rax * 8].Lasm_GetByValue.ssa_block_6:- mov r11, rdx+ mov eax, DWORD PTR [r14 + r13 + 16]+ mov rax, QWORD PTR [rbx + rax * 8]+ mov r11, raxshr r11, 48cmp r11w, 65530je .Lasm_GetByValue.ssa_block_37@@ -15335,6 +15340,7 @@ asm_handler_SetGlobal_cold_end:asm_handler_Call_cold:# Cold paths for Call.Lasm_Call.ssa_block_4:+ mov rdx, raxmov rcx, QWORD PTR [rbp - 48]mov rdi, rcxmov rsi, rdx@@ -21559,11 +21565,11 @@ asm_assertion_failure_traps:ud2.Lasm_GetById.assert_failure_0:ud2-.Lasm_GetById.assert_predicate_failure_120:+.Lasm_GetById.assert_predicate_failure_123:ud2.Lasm_GetById.assert_failure_1:ud2-.Lasm_GetById.assert_predicate_failure_335:+.Lasm_GetById.assert_predicate_failure_338:ud2.Lasm_GetById.assert_failure_2:ud2@@ -21573,39 +21579,39 @@ asm_assertion_failure_traps:ud2.Lasm_GetById.assert_failure_5:ud2-.Lasm_GetById.assert_predicate_failure_157:+.Lasm_GetById.assert_predicate_failure_160:ud2.Lasm_GetById.assert_failure_6:ud2.Lasm_GetById.assert_failure_7:ud2-.Lasm_GetById.assert_predicate_failure_166:+.Lasm_GetById.assert_predicate_failure_169:ud2-.Lasm_GetById.assert_predicate_failure_174:+.Lasm_GetById.assert_predicate_failure_177:ud2.Lasm_GetById.assert_failure_8:ud2.Lasm_GetById.assert_failure_9:ud2-.Lasm_GetById.assert_predicate_failure_199:+.Lasm_GetById.assert_predicate_failure_202:ud2-.Lasm_GetById.assert_predicate_failure_201:+.Lasm_GetById.assert_predicate_failure_204:ud2.Lasm_GetById.assert_failure_10:ud2-.Lasm_GetById.assert_predicate_failure_265:+.Lasm_GetById.assert_predicate_failure_268:ud2-.Lasm_GetById.assert_predicate_failure_274:+.Lasm_GetById.assert_predicate_failure_277:ud2-.Lasm_GetById.assert_predicate_failure_23:+.Lasm_GetById.assert_predicate_failure_26:ud2-.Lasm_GetById.assert_predicate_failure_29:+.Lasm_GetById.assert_predicate_failure_32:ud2.Lasm_GetById.assert_failure_19:ud2-.Lasm_GetById.assert_predicate_failure_47:+.Lasm_GetById.assert_predicate_failure_50:ud2-.Lasm_GetById.assert_predicate_failure_53:+.Lasm_GetById.assert_predicate_failure_56:ud2.Lasm_GetById.assert_failure_20:ud2@@ -21621,15 +21627,15 @@ asm_assertion_failure_traps:ud2.Lasm_PutById.assert_failure_2:ud2-.Lasm_GetByValue.assert_predicate_failure_69:+.Lasm_GetByValue.assert_predicate_failure_70:ud2.Lasm_GetByValue.assert_failure_0:ud2-.Lasm_GetByValue.assert_predicate_failure_292:+.Lasm_GetByValue.assert_predicate_failure_293:ud2.Lasm_GetByValue.assert_failure_2:ud2-.Lasm_GetByValue.assert_predicate_failure_226:+.Lasm_GetByValue.assert_predicate_failure_227:ud2.Lasm_GetByValue.assert_failure_3:ud2diff --git a/Libraries/LibJS/Flap/tests/interpreter_assembly.rs b/Libraries/LibJS/Flap/tests/interpreter_assembly.rsindex 97483b28c72..78865121f4b 100644--- a/Libraries/LibJS/Flap/tests/interpreter_assembly.rs+++ b/Libraries/LibJS/Flap/tests/interpreter_assembly.rs@@ -20,6 +20,7 @@ fn compile_interpreter(architecture: Architecture) -> String {has_jscvt: false,enable_assertions: true,profiling: false,+ profile: flapc::Profile::JavaScript,});compiler.compile(CompilationUnit {diff --git a/Libraries/LibJS/Flap/tests/profiling.rs b/Libraries/LibJS/Flap/tests/profiling.rsindex fad47ddbefe..79415577f70 100644--- a/Libraries/LibJS/Flap/tests/profiling.rs+++ b/Libraries/LibJS/Flap/tests/profiling.rs@@ -29,6 +29,7 @@ fn compile(architecture: Architecture, profiling: bool) -> String {has_jscvt: false,enable_assertions: true,profiling,+ profile: flapc::Profile::JavaScript,}).compile(CompilationUnit {source: SourceInput {diff --git a/Libraries/LibJS/Flap/tests/wasm_profile.rs b/Libraries/LibJS/Flap/tests/wasm_profile.rsnew file mode 100644index 00000000000..b7e3d4aee71--- /dev/null+++ b/Libraries/LibJS/Flap/tests/wasm_profile.rs@@ -0,0 +1,1068 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++use flapc::{Architecture, CompilationUnit, CompileOptions, Compiler, ObjectFormat, Profile, SourceInput, Target};++fn compiler(architecture: Architecture) -> Compiler {+ Compiler::new(CompileOptions {+ target: Target {+ architecture,+ object_format: ObjectFormat::Elf,+ },+ has_jscvt: false,+ enable_assertions: true,+ profiling: false,+ profile: Profile::WebAssembly,+ })+}++fn compile_with_constants(source: &str, constants: &str) -> Result<String, String> {+ compiler(Architecture::X86_64)+ .compile(CompilationUnit {+ source: SourceInput {+ name: "wasm.flap",+ contents: source,+ },+ constants: Some(SourceInput {+ name: "layout.conf",+ contents: constants,+ }),+ })+ .map(|assembly| assembly.as_str().to_owned())+ .map_err(|error| error.to_string())+}++fn compile(source: &str) -> Result<String, String> {+ compile_with_constants(source, "")+}++fn handler<'a>(assembly: &'a str, name: &str) -> &'a str {+ let start = assembly+ .find(&format!("asm_handler_{name}:\n"))+ .unwrap_or_else(|| panic!("missing handler {name}"));+ let end = assembly[start..].find(&format!("asm_handler_{name}_hot_end:")).unwrap();+ &assembly[start..start + end]+}++const PROGRAM: &str = r#"+handler Nop() @opcode(0x01) {+ dispatch_next;+}++handler LocalGet() @opcode(0x20) {+ let code: Sequence<u8> = alias(ip);+ let index: u64 = alias(code[1]);+ let locals: Sequence<u64> = alias(fp);+ let stack: Sequence<u64> = alias(vsp);+ stack[0] = locals[index];+ dispatch_variable(2);+}++handler Saturating() @opcode(0xfc, 7) {+ dispatch_variable(2);+}++handler Fallback() @fallback {+ exit;+}+"#;++#[test]+fn dispatches_on_the_byte_the_instruction_pointer_points_at() {+ let assembly = compile(PROGRAM).unwrap();+ let nop = handler(&assembly, "Nop");+ assert!(nop.contains("add r13, 1\n"), "{nop}");+ assert!(+ nop.contains("movzx eax, BYTE PTR [r13]\n jmp [r12 + rax * 8]"),+ "{nop}"+ );+ assert!(!assembly.contains("r14 + r13"));++ let local_get = handler(&assembly, "LocalGet");+ assert!(local_get.contains("BYTE PTR [r13 + 1]"), "{local_get}");+ assert!(local_get.contains("[rbp + rax * 8]"), "{local_get}");+ assert!(local_get.contains("QWORD PTR [rbx]"), "{local_get}");+}++#[test]+fn builds_dispatch_tables_from_opcode_annotations() {+ let assembly = compile(PROGRAM).unwrap();+ let table = assembly+ .split("asm_dispatch_table:\n")+ .nth(1)+ .unwrap()+ .lines()+ .take(256)+ .collect::<Vec<_>>();+ assert_eq!(table[0x00], " .quad asm_handler_Fallback");+ assert_eq!(table[0x01], " .quad asm_handler_Nop");+ assert_eq!(table[0x20], " .quad asm_handler_LocalGet");+ assert_eq!(table[0xfc], " .quad asm_handler_Fallback");++ let secondary = assembly+ .split("asm_dispatch_table_fc:\n")+ .nth(1)+ .unwrap()+ .lines()+ .take(512)+ .collect::<Vec<_>>();+ assert_eq!(secondary.len(), 512);+ assert_eq!(secondary[7], " .quad asm_handler_Saturating");+ assert_eq!(secondary[8], " .quad asm_handler_Fallback");++ assert!(assembly.contains(".globl CSYM(wasm_interpreter)\n"));+ assert!(assembly.contains(".globl CSYM(wasm_interpreter_dispatch_table)\n"));+ assert!(assembly.contains(".globl CSYM(wasm_interpreter_end)\n"));+ assert!(!assembly.contains("js_interpreter"));+ assert!(!assembly.contains("asm_debugger_trampoline"));+}++#[test]+fn rejects_handlers_without_an_encoding() {+ let error = compile("handler Unencoded() { dispatch_next; }").unwrap_err();+ assert!(error.contains("needs an @opcode or @fallback annotation"), "{error}");++ let error = compile("handler A() @opcode(0x10) { dispatch_next; }\nhandler B() @opcode(0x10) { dispatch_next; }")+ .unwrap_err();+ assert!(error.contains("another handler already has this opcode"), "{error}");++ let error = compile("handler A(dst: out Operand) @opcode(0x10) { dispatch_next; }").unwrap_err();+ assert!(error.contains("cannot declare parameters"), "{error}");++ let error = compile("handler A() @opcode(0xfc, 7) { dispatch_next; }").unwrap_err();+ assert!(+ error.contains("variable-length handler must use variable dispatch"),+ "{error}"+ );+}++#[test]+fn rejects_registers_of_other_profiles() {+ let error = compile("handler A() @opcode(0x10) { let base: u64 = pb; dispatch_variable(base); }").unwrap_err();+ assert!(+ error.contains("the WebAssembly profile has no interpreter register 'pb'"),+ "{error}"+ );+}++fn compile_for(target: Target, source: &str) -> Result<String, String> {+ Compiler::new(CompileOptions {+ target,+ has_jscvt: false,+ enable_assertions: true,+ profiling: false,+ profile: Profile::WebAssembly,+ })+ .compile(CompilationUnit {+ source: SourceInput {+ name: "wasm.flap",+ contents: source,+ },+ constants: None,+ })+ .map(|assembly| assembly.as_str().to_owned())+ .map_err(|error| error.to_string())+}++fn compile_aarch64(source: &str) -> Result<String, String> {+ compile_for(+ Target {+ architecture: Architecture::Aarch64,+ object_format: ObjectFormat::Elf,+ },+ source,+ )+}++#[test]+fn is_not_available_for_aarch64_windows() {+ let error = compile_for(+ Target {+ architecture: Architecture::Aarch64,+ object_format: ObjectFormat::Coff,+ },+ PROGRAM,+ )+ .unwrap_err();+ assert!(error.contains("not implemented for AArch64 Windows"), "{error}");+}++#[test]+fn dispatches_on_the_byte_the_instruction_pointer_points_at_on_aarch64() {+ let assembly = compile_aarch64(PROGRAM).unwrap();+ let nop = handler(&assembly, "Nop");+ assert!(nop.contains("ldrb w9, [x21, #1]\n"), "{nop}");+ assert!(nop.contains("add x21, x21, #1\n"), "{nop}");+ assert!(nop.contains("ldr x10, [x19, x9, lsl #3]\n br x10"), "{nop}");+ assert!(!assembly.contains("x26, w25"), "{assembly}");++ let local_get = handler(&assembly, "LocalGet");+ assert!(local_get.contains("[x21, #1]"), "{local_get}");+ assert!(local_get.contains("[x29, "), "{local_get}");+ assert!(local_get.contains("[x27]"), "{local_get}");++ let entry = assembly.split("CSYM(wasm_interpreter):\n").nth(1).unwrap();+ assert!(entry.contains("mov x21, x0"), "{entry}");+ assert!(entry.contains("mov x27, x1"), "{entry}");+ assert!(entry.contains(":lo12:asm_dispatch_table"), "{entry}");+ assert!(assembly.contains(".Lexit:\n mov sp, x29\n"), "{assembly}");+}++#[test]+fn dispatches_prefixed_opcodes_through_their_secondary_table_on_aarch64() {+ let assembly = compile_aarch64(+ r#"+handler Prefix() @opcode(0xfc) {+ let bytes: Sequence<u8> = alias(ip);+ let sub_opcode: u64 = alias(bytes[1]);+ dispatch_secondary(0xfc, sub_opcode);+}++handler Saturating() @opcode(0xfc, 3) {+ dispatch_variable(2);+}++handler Fallback() @fallback {+ exit();+}+"#,+ )+ .unwrap();+ let prefix = handler(&assembly, "Prefix");+ assert!(prefix.contains("adrp x9, asm_dispatch_table_fc\n"), "{prefix}");+ assert!(prefix.contains("add x9, x9, :lo12:asm_dispatch_table_fc\n"), "{prefix}");+ assert!(prefix.contains("ldr x10, [x9, x"), "{prefix}");+ assert!(prefix.contains(", lsl #3]\n br x10"), "{prefix}");+}++#[test]+fn compiles_atomic_operations_on_aarch64() {+ let assembly = compile_aarch64(+ r#"+handler Atomics() @opcode(0x01) {+ let slots: Sequence<u64> = alias(vsp);+ let address = slots[0];+ let value = slots[1];+ let old = atomic_cmpxchg32([address, 4], value, 7);+ let swapped = atomic_xchg8([address, 0], old);+ let added = atomic_add64([address, 8], swapped);+ let loaded = atomic_load16([address, 0]);+ atomic_fence();+ slots[2] = added + loaded;+ dispatch_next;+}++handler Fallback() @fallback {+ exit();+}+"#,+ )+ .unwrap();+ let atomics = handler(&assembly, "Atomics");+ for expected in [+ "add x9, x",+ ", #4\n",+ "casal w",+ "swpalb w",+ "ldaddal x",+ "ldarh w",+ "dmb ish",+ ] {+ assert!(atomics.contains(expected), "missing {expected}: {atomics}");+ }+}++#[test]+fn compiles_atomic_loads_and_fences_on_x86_64() {+ let assembly = compile(+ r#"+handler Atomics() @opcode(0x01) {+ let slots: Sequence<u64> = alias(vsp);+ let address = slots[0];+ let loaded = atomic_load8([address, 3]);+ atomic_fence();+ slots[1] = loaded;+ dispatch_next;+}++handler Fallback() @fallback {+ exit();+}+"#,+ )+ .unwrap();+ let atomics = handler(&assembly, "Atomics");+ assert!(atomics.contains("movzx e"), "{atomics}");+ assert!(atomics.contains("BYTE PTR [r"), "{atomics}");+ assert!(atomics.contains("mfence"), "{atomics}");+}++#[test]+fn compiles_numeric_and_vector_operations_on_aarch64() {+ let assembly = compile_aarch64(+ r#"+handler Numbers() @opcode(0x01) {+ let slots: Sequence<u64> = alias(vsp);+ let a = slots[0];+ let b = slots[1];+ let narrow_a = u32(a);+ let narrow_b = u32(b);+ let quotient = div_u32(narrow_a, narrow_b);+ let remainder = rem_s64(a, b);+ let zeros = ctz64(a);+ let ones = popcnt32(narrow_b);+ let rotated = rotl32(narrow_a, narrow_b);+ let narrow = quotient + ones + rotated;+ let wide: u64 = alias(narrow);+ slots[2] = remainder + zeros + wide;+ dispatch_next;+}++handler Vectors() @opcode(0x02) {+ let top: u64 = vsp;+ let mut a: v128;+ load128(a, [top, 0]);+ let mut b: v128;+ load128(b, [top, 16]);+ let sum = v128_add_i32(a, b);+ let smaller = v128_min_f32(sum, b);+ let shuffled = v128_shuffle_i8(smaller, a);+ store128([top, 32], shuffled);+ let slots: Sequence<u64> = alias(top);+ let mask = v128_bitmask_i8(shuffled);+ let high = v128_high_u64(a);+ slots[7] = mask + high;+ dispatch_next;+}++handler Fallback() @fallback {+ exit();+}+"#,+ )+ .unwrap();+ let numbers = handler(&assembly, "Numbers");+ for expected in [+ "udiv w",+ "sdiv x9, x",+ "msub x",+ "rbit x9, x",+ "cnt v16.8b, v16.8b",+ "neg w9, w",+ "ror w",+ ] {+ assert!(numbers.contains(expected), "missing {expected}: {numbers}");+ }+ let vectors = handler(&assembly, "Vectors");+ for expected in [+ "add v",+ ".4s\n",+ "fcmgt v16.4s, v",+ "bsl v16.16b, v",+ "movi v16.16b, #0x8f",+ "tbl v",+ "usra v16.2d, v16.2d, #28",+ ", v",+ ".d[1]\n",+ ] {+ assert!(vectors.contains(expected), "missing {expected}: {vectors}");+ }+}++#[test]+fn calls_runtime_functions_with_the_system_v_convention_on_windows() {+ let assembly = compile_for(+ Target {+ architecture: Architecture::X86_64,+ object_format: ObjectFormat::Coff,+ },+ r#"+handler Grow() @opcode(0x01) {+ let slots: Sequence<u64> = alias(vsp);+ let context = slots[0];+ let result: u64 = call_helper(wasm_runtime_memory_grow, context);+ slots[1] = result;+ dispatch_next;+}++handler Fallback() @fallback {+ exit();+}+"#,+ )+ .unwrap();+ let grow = handler(&assembly, "Grow");+ assert!(+ grow.contains("mov rdi, rcx\n call CSYM(wasm_runtime_memory_grow)"),+ "{grow}"+ );+ let entry = assembly.split("CSYM(wasm_interpreter):\n").nth(1).unwrap();+ assert!(entry.contains(".seh_pushreg rbx"), "{entry}");+ assert!(entry.contains(".seh_endprologue"), "{entry}");+ assert!(entry.contains("mov r13, rdi"), "{entry}");+ assert!(!entry.contains(".cfi_"), "{entry}");+}++/// Twelve values live at once, more than there are allocatable registers.+const HIGH_PRESSURE: &str = r#"+handler Sum() @opcode(0x01) {+ let slots: Sequence<u64> = alias(vsp);+ let a = slots[0];+ let b = slots[1];+ let c = slots[2];+ let d = slots[3];+ let e = slots[4];+ let f = slots[5];+ let g = slots[6];+ let h = slots[7];+ let i = slots[8];+ let j = slots[9];+ let k = slots[10];+ let l = slots[11];+ slots[12] = a + l;+ slots[13] = b + k;+ slots[14] = c + j;+ slots[15] = d + i;+ slots[16] = e + h;+ slots[17] = f + g;+ slots[18] = a + b + c + d + e + f + g + h + i + j + k + l;+ dispatch_next;+}++handler Fallback() @fallback {+ exit();+}+"#;++#[test]+fn spills_to_the_spill_area_when_registers_run_out() {+ let error = compile(HIGH_PRESSURE).unwrap_err();+ assert!(error.contains("could not allocate spill-free handler"), "{error}");++ let assembly = compile_with_constants(+ HIGH_PRESSURE,+ "const SPILL_AREA_OFFSET = 64\nconst SPILL_AREA_SLOTS = 8\n",+ )+ .unwrap();+ let sum = handler(&assembly, "Sum");+ assert!(sum.contains("QWORD PTR [rsp + 64]"), "{sum}");+ assert!(!sum.contains("QWORD PTR [rsp + 128]"), "{sum}");+}++const FLOAT_PRESSURE: &str = r#"+handler FloatSum() @opcode(0x01) {+ let slots: Sequence<u64> = alias(vsp);+ let a = f64_from_bits(slots[0]);+ let b = f64_from_bits(slots[1]);+ let c = f64_from_bits(slots[2]);+ let d = f64_from_bits(slots[3]);+ let e = f64_from_bits(slots[4]);+ let f = f64_from_bits(slots[5]);+ let ab = a + b;+ let abc = ab + c;+ let abcd = abc + d;+ let abcde = abcd + e;+ let sum = abcde + f;+ let fe = f * e;+ let fed = fe * d;+ let fedc = fed * c;+ let fedcb = fedc * b;+ let product = fedcb * a;+ slots[6] = f64_to_bits(sum);+ slots[7] = f64_to_bits(product);+ dispatch_next;+}++handler Fallback() @fallback {+ exit();+}+"#;++#[test]+fn spills_floating_point_values() {+ let error = compile(FLOAT_PRESSURE).unwrap_err();+ assert!(error.contains("could not allocate spill-free handler"), "{error}");++ let assembly = compile_with_constants(+ FLOAT_PRESSURE,+ "const SPILL_AREA_OFFSET = 64\nconst SPILL_AREA_SLOTS = 8\n",+ )+ .unwrap();+ let sum = handler(&assembly, "FloatSum");+ assert!(sum.contains("movsd QWORD PTR [rsp + 64], xmm"), "{sum}");+}++const VECTOR_PRESSURE: &str = r#"+handler Reverse() @opcode(0x01) {+ let top: u64 = vsp;+ let mut a: v128;+ load128(a, [top, 0]);+ let mut b: v128;+ load128(b, [top, 16]);+ let mut c: v128;+ load128(c, [top, 32]);+ let mut d: v128;+ load128(d, [top, 48]);+ let mut e: v128;+ load128(e, [top, 64]);+ let mut f: v128;+ load128(f, [top, 80]);+ store128([top, 96], f);+ store128([top, 112], e);+ store128([top, 128], d);+ store128([top, 144], c);+ store128([top, 160], b);+ store128([top, 176], a);+ dispatch_next;+}++handler Fallback() @fallback {+ exit();+}+"#;++#[test]+fn keeps_and_spills_vectors_whole() {+ let error = compile(VECTOR_PRESSURE).unwrap_err();+ assert!(error.contains("could not allocate spill-free handler"), "{error}");++ let assembly = compile_with_constants(+ VECTOR_PRESSURE,+ "const SPILL_AREA_OFFSET = 8\nconst SPILL_AREA_SLOTS = 8\n",+ )+ .unwrap();+ let reverse = handler(&assembly, "Reverse");+ // Vector slots take 16 bytes each, starting on a 16-byte boundary.+ assert!(reverse.contains("movdqu XMMWORD PTR [rsp + 16], xmm"), "{reverse}");+ assert!(reverse.contains("movdqu XMMWORD PTR [rsp + 32], xmm"), "{reverse}");+ assert!(+ !reverse.contains("[rsp + 8]") && !reverse.contains("[rsp + 24]"),+ "{reverse}"+ );+}++#[test]+fn moves_vectors_with_full_width_moves() {+ let assembly = compile(+ r#"+handler Swap() @opcode(0x01) {+ let top: u64 = vsp;+ let mut a: v128;+ load128(a, [top, 0]);+ let mut b: v128;+ load128(b, [top, 16]);+ let mut first: v128 = a;+ let mut second: v128 = b;+ let slots: Sequence<u64> = alias(top);+ let flag = slots[4];+ if flag != 0 {+ first = b;+ second = a;+ }+ store128([top, 32], first);+ store128([top, 48], second);+ dispatch_next;+}++handler Fallback() @fallback {+ exit();+}+"#,+ )+ .unwrap();+ let swap = handler(&assembly, "Swap");+ assert!(swap.contains("movaps xmm"), "{swap}");+ assert!(!swap.contains("movq xmm"), "{swap}");+}++const ACROSS_CALL: &str = r#"+handler Call() @opcode(0x01) {+ let slots: Sequence<u64> = alias(vsp);+ let kept = slots[0];+ let current: u64 = ip;+ let result: u64 = call_helper(wasm_helper, kept);+ let sum = result + kept;+ slots[1] = sum;+ let next = current + 1;+ ip = next;+ dispatch;+}++handler Fallback() @fallback {+ exit();+}+"#;++#[test]+fn spills_values_live_across_calls_first() {+ let error = compile(ACROSS_CALL).unwrap_err();+ assert!(error.contains("could not allocate spill-free handler"), "{error}");++ // One slot is enough: the copy of ip is reread from ip, so only the value is stored.+ let assembly = compile_with_constants(+ ACROSS_CALL,+ "const SPILL_AREA_OFFSET = 64\nconst SPILL_AREA_SLOTS = 1\n",+ )+ .unwrap();+ let call = handler(&assembly, "Call");+ assert!(call.contains("QWORD PTR [rsp + 64]"), "{call}");+ assert!(call.contains("call "), "{call}");+}++#[test]+fn compiles_atomic_operations() {+ let assembly = compile(+ r#"+handler Atomics() @opcode(0x01) {+ let slots: Sequence<u64> = alias(vsp);+ let address = slots[0];+ let value = slots[1];+ let old = atomic_cmpxchg32([address, 4], value, 7);+ let swapped = atomic_xchg8([address, 0], old);+ let added = atomic_add64([address, 8], swapped);+ slots[2] = added;+ dispatch_next;+}++handler Fallback() @fallback {+ exit();+}+"#,+ )+ .unwrap();+ let atomics = handler(&assembly, "Atomics");+ for expected in [+ "lock cmpxchg DWORD PTR [",+ "xchg BYTE PTR [",+ "movzx e",+ "lock xadd QWORD PTR [",+ ] {+ assert!(atomics.contains(expected), "missing {expected}: {atomics}");+ }+}++#[test]+fn compiles_vector_operations_to_sse_instructions() {+ let assembly = compile(+ r#"+handler Vectors() @opcode(0x01) {+ let top: u64 = vsp;+ let mut a: v128;+ load128(a, [top, 0]);+ let mut b: v128;+ load128(b, [top, 16]);+ let sum = v128_add_i32(a, b);+ let rounded = v128_floor_f64(sum);+ store128([top, 32], rounded);+ let slots: Sequence<u64> = alias(top);+ let low = slots[6];+ let splat = v128_from_u64x2(low, low);+ let mask = v128_bitmask_i8(splat);+ let high = v128_high_u64(a);+ slots[7] = mask + high;+ dispatch_next;+}++handler Fallback() @fallback {+ exit();+}+"#,+ )+ .unwrap();+ let vectors = handler(&assembly, "Vectors");+ for expected in [+ "paddd xmm",+ "roundpd xmm",+ ", 9\n",+ "pinsrq xmm",+ "pmovmskb e",+ "pextrq r",+ ] {+ assert!(vectors.contains(expected), "missing {expected}: {vectors}");+ }+}++const ACROSS_STACK_POINTER_WRITE: &str = r#"+handler NewFrame() @opcode(0x01) {+ let slots: Sequence<u64> = alias(vsp);+ let a = slots[0];+ let b = slots[1];+ let c = slots[2];+ let d = slots[3];+ let e = slots[4];+ let f = slots[5];+ let g = slots[6];+ let h = slots[7];+ let i = slots[8];+ let j = slots[9];+ let old_stack_pointer: u64 = sp;+ let new_stack_pointer = old_stack_pointer - 512;+ sp = new_stack_pointer;+ slots[10] = a + j;+ slots[11] = b + i;+ slots[12] = c + h;+ slots[13] = d + g;+ slots[14] = e + f;+ slots[15] = a + b + c + d + e + f + g + h + i + j;+ dispatch_next;+}++handler Fallback() @fallback {+ exit();+}+"#;++#[test]+fn spills_values_live_across_writes_to_the_stack_pointer() {+ let assembly = compile_with_constants(+ ACROSS_STACK_POINTER_WRITE,+ "const SPILL_AREA_OFFSET = 0\nconst SPILL_AREA_SLOTS = 8\n",+ )+ .unwrap();+ let frame = handler(&assembly, "NewFrame");+ let write = frame.find("mov rsp, ").expect("the handler writes rsp");+ let (before, after) = frame.split_at(write);+ // A value spilled before the write moves to its slot below the new stack pointer, and is reread from there.+ let new_stack_pointer = after["mov rsp, ".len()..].lines().next().unwrap().trim();+ assert!(+ before.contains(&format!("QWORD PTR [{new_stack_pointer}"))+ || before.contains(&format!("QWORD PTR [{new_stack_pointer} +")),+ "{frame}"+ );+ assert!(after.contains("QWORD PTR [rsp"), "{frame}");+}++#[test]+fn does_not_spill_handlers_that_fit() {+ let assembly =+ compile_with_constants(PROGRAM, "const SPILL_AREA_OFFSET = 64\nconst SPILL_AREA_SLOTS = 8\n").unwrap();+ assert!(!assembly.contains("rsp +"));+}++#[test]+fn wraps_u32_arithmetic_to_32_bits() {+ let assembly = compile(+ r#"+handler Arithmetic() @opcode(0x01) {+ let slots: Sequence<u64> = alias(vsp);+ let lhs = u32(slots[0]);+ let rhs = u32(slots[1]);+ let sum = lhs + rhs;+ let difference = rhs - lhs;+ let product = lhs * rhs;+ let wide_sum: u64 = alias(sum);+ let wide_difference: u64 = alias(difference);+ let wide_product: u64 = alias(product);+ slots[1] = wide_sum;+ slots[2] = wide_difference;+ slots[3] = wide_product;+ dispatch_next;+}++handler Fallback() @fallback {+ exit();+}+"#,+ )+ .unwrap();+ let arithmetic = handler(&assembly, "Arithmetic");+ assert!(arithmetic.contains("add e"), "{arithmetic}");+ assert!(arithmetic.contains("sub e"), "{arithmetic}");+ assert!(arithmetic.contains("imul e"), "{arithmetic}");+ assert!(+ !arithmetic+ .lines()+ .any(|line| line.trim_start().starts_with("add r") && !line.contains("r13")),+ "{arithmetic}"+ );+}++#[test]+fn accepts_literal_left_operands_and_nested_arguments() {+ let assembly = compile(+ r#"+inline fn advance(length: u64) {+ let current: u64 = ip;+ let next = current + length;+ ip = next;+ dispatch;+}++handler Skip() @opcode(0x01) {+ let slots: Sequence<u64> = alias(vsp);+ let length = slots[0];+ let extra = slots[1];+ advance(1 + length + (extra >> 1));+}++handler Fallback() @fallback {+ exit();+}+"#,+ )+ .unwrap();+ let skip = handler(&assembly, "Skip");+ assert!(skip.contains("mov r13, "), "{skip}");+}++#[test]+fn materializes_wide_immediates() {+ let assembly = compile(+ r#"+handler Wide() @opcode(0x01) {+ let slots: Sequence<u64> = alias(vsp);+ let value = slots[0];+ let flipped = value ^ 0x8000000000000000;+ slots[1] = flipped;+ let masked = value & 0x3ffffffff;+ slots[2] = masked;+ let low = value & 0xffffffff;+ slots[3] = low;+ let spread = value * 0x0101010101010101;+ slots[4] = spread;+ if value == 0x8000000000000000 {+ exit();+ }+ dispatch_next;+}++handler Fallback() @fallback {+ exit();+}+"#,+ )+ .unwrap();+ let wide = handler(&assembly, "Wide");+ assert!(+ wide.contains("0x8000000000000000") || wide.contains("9223372036854775808"),+ "{wide}"+ );+ assert!(wide.contains("xor r"), "{wide}");+ assert!(wide.contains("and r"), "{wide}");+ assert!(wide.contains("imul r"), "{wide}");+ assert!(+ wide.lines().any(|line| line.trim_start().starts_with("mov e")),+ "{wide}"+ );+ assert!(wide.contains("cmp r"), "{wide}");+}++#[test]+fn cold_blocks_reload_instead_of_reusing_hot_loads() {+ let assembly = compile(+ r#"+handler Reload() @opcode(0x01) {+ let slots: Sequence<u64> = alias(vsp);+ let value = slots[1];+ let flag = slots[0];+ if flag == 0 @cold {+ let again = slots[1];+ slots[3] = again;+ exit();+ }+ slots[2] = value;+ dispatch_next;+}++handler Fallback() @fallback {+ exit();+}+"#,+ )+ .unwrap();+ // The cold block is laid out away from the handler, so this counts the loads in both.+ assert_eq!(assembly.matches("QWORD PTR [rbx + 8]").count(), 2, "{assembly}");+}++#[test]+fn compiles_numeric_operations_to_single_instructions() {+ let assembly = compile_with_constants(+ r#"+handler Numeric() @opcode(0x01) {+ let slots: Sequence<u64> = alias(vsp);+ let lhs = u32(slots[0]);+ let rhs = u32(slots[1]);+ let quotient = div_u32(lhs, rhs);+ let remainder = rem_s32(lhs, rhs);+ let leading = clz32(lhs);+ let trailing = ctz64(slots[2]);+ let population = popcnt64(slots[3]);+ let rotated = rotl32(lhs, rhs);+ let float = f64_from_bits(slots[4]);+ let truncated = trunc_f64(float);+ let bits = f64_to_bits(truncated);+ let wide_quotient: u64 = alias(quotient);+ let wide_remainder: u64 = alias(remainder);+ let wide_leading: u64 = alias(leading);+ let wide_rotated: u64 = alias(rotated);+ slots[5] = wide_quotient;+ slots[6] = wide_remainder;+ slots[7] = wide_leading;+ slots[8] = trailing;+ slots[9] = population;+ slots[10] = wide_rotated;+ slots[11] = bits;+ dispatch_next;+}++handler Fallback() @fallback {+ exit();+}+"#,+ "const SPILL_AREA_OFFSET = 64\nconst SPILL_AREA_SLOTS = 8\n",+ )+ .unwrap();+ let numeric = handler(&assembly, "Numeric");+ for instruction in [+ "div ecx",+ "idiv ecx",+ "lzcnt e",+ "tzcnt r",+ "popcnt r",+ "rol e",+ "movq xmm",+ "roundsd xmm0, xmm0, 3",+ ] {+ assert!(numeric.contains(instruction), "missing {instruction}:\n{numeric}");+ }+}++#[test]+fn moves_continuing_cold_ifs_out_of_line() {+ let assembly = compile(+ r#"+handler Decode() @opcode(0x01) {+ let bytes: Sequence<u8> = alias(ip);+ let first: u64 = alias(bytes[1]);+ let mut length: u64 = 2;+ if first >= 128 @cold {+ let mut byte: u64 = first;+ while byte >= 128 {+ byte = alias(bytes[length]);+ length = length + 1;+ }+ }+ dispatch_variable(length);+}++handler Fallback() @fallback {+ exit();+}+"#,+ )+ .unwrap();+ let hot = handler(&assembly, "Decode");+ assert!(!hot.contains("cmp rax, 128\n jb"), "{hot}");+ let cold = assembly.split("asm_handler_Decode_cold:").nth(1).unwrap();+ let cold = cold.split("asm_handler_Decode_cold_end:").next().unwrap();+ assert!(cold.contains("cmp"), "{cold}");+}++#[test]+fn rereads_copies_of_interpreter_registers_instead_of_spilling_them() {+ let source = HIGH_PRESSURE+ .replace(+ " let slots: Sequence<u64> = alias(vsp);",+ " let start: u64 = ip;\n let slots: Sequence<u64> = alias(vsp);",+ )+ .replace(+ " dispatch_next;\n}\n\nhandler Fallback",+ " let next = start + 1;\n ip = next;\n dispatch;\n}\n\nhandler Fallback",+ );+ let assembly =+ compile_with_constants(&source, "const SPILL_AREA_OFFSET = 64\nconst SPILL_AREA_SLOTS = 8\n").unwrap();+ let sum = handler(&assembly, "Sum");+ assert!(sum.contains(", r13\n"), "{sum}");+ assert!(+ !sum.lines()+ .any(|line| line.contains("PTR [rsp") && line.trim_start().starts_with("mov r") && line.contains("r13")),+ "{sum}"+ );+}++#[test]+fn compares_floats_with_ieee_semantics() {+ let assembly = compile(+ r#"+handler Compare() @opcode(0x01) {+ let slots: Sequence<u64> = alias(vsp);+ let lhs = f64_from_bits(slots[0]);+ let rhs = f64_from_bits(slots[1]);+ let mut result: u64 = 0;+ if lhs < rhs {+ result = 1;+ }+ if lhs != rhs {+ result = result + 2;+ }+ slots[2] = result;+ dispatch_next;+}++handler Fallback() @fallback {+ exit();+}+"#,+ )+ .unwrap();+ let compare = handler(&assembly, "Compare");+ // An unordered comparison sets the "below" flags, so a less-than tests the swapped operands for "above".+ assert!(compare.contains("ucomisd xmm1, xmm0\n ja "), "{compare}");+ assert!(compare.contains("jp "), "{compare}");+}++#[test]+fn dispatches_prefixed_opcodes_through_their_secondary_table() {+ let assembly = compile(+ r#"+handler Prefix() @opcode(0xfc) {+ let bytes: Sequence<u8> = alias(ip);+ let sub_opcode: u64 = alias(bytes[1]);+ dispatch_secondary(0xfc, sub_opcode);+}++handler Saturating() @opcode(0xfc, 3) {+ dispatch_variable(2);+}++handler Fallback() @fallback {+ exit();+}+"#,+ )+ .unwrap();+ let prefix = handler(&assembly, "Prefix");+ assert!(prefix.contains("lea rax, [rip + asm_dispatch_table_fc]"), "{prefix}");+ assert!(prefix.contains("jmp [rax + "), "{prefix}");++ // 0xff is free for a runtime's own prefixed forms.+ let assembly = compile(+ r#"+handler Internal() @opcode(0xff) {+ let bytes: Sequence<u8> = alias(ip);+ let sub_opcode: u64 = alias(bytes[1]);+ dispatch_secondary(0xff, sub_opcode);+}++handler Quickened() @opcode(0xff, 0x28) {+ dispatch_variable(2);+}++handler Fallback() @fallback {+ exit();+}+"#,+ )+ .unwrap();+ assert!(assembly.contains("asm_dispatch_table_ff:"), "{assembly}");+ assert!(handler(&assembly, "Internal").contains("[rip + asm_dispatch_table_ff]"));++ let error = compile("handler A() @opcode(0x10, 3) { dispatch_variable(2); }").unwrap_err();+ assert!(+ error.contains("secondary dispatch tables exist for the prefixes"),+ "{error}"+ );+}diff --git a/Libraries/LibJS/Rust/build.rs b/Libraries/LibJS/Rust/build.rsindex 6d6889cc564..cb112f81f0c 100644--- a/Libraries/LibJS/Rust/build.rs+++ b/Libraries/LibJS/Rust/build.rs@@ -298,6 +298,7 @@ fn interpreter_compiler(target: &Target, profiling: bool) -> flapc::Compiler {has_jscvt: target.is_apple && matches!(target.architecture, flapc::Architecture::Aarch64),enable_assertions: true,profiling,+ profile: flapc::Profile::JavaScript,})}