[ARM64EC] Implement `-mlong-double-{64,80,128}` options #237057
<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-llvm-transforms
@llvm/pr-subscribers-llvm-selectiondag
@llvm/pr-subscribers-llvm-ir
@llvm/pr-subscribers-platform-windows
@llvm/pr-subscribers-clang-codegen
@llvm/pr-subscribers-clang
@llvm/pr-subscribers-backend-aarch64
Author: LIU Hao (lhmouse)
<details>
<summary>Changes</summary>
This commits implement the three options for arm64ec-w64-mingw32. -mlong-double-80 is made default to fix the interoperability bug with x86_64-w64-mingw32. This also introduces an ABI break with old ARM64EC binaries.
-mlong-double-64 is the old behavior that is compativle with aarch64-w64-mingw32 and MSVC. -mlong-double-128 enables float128 in software, same as x86-64.
The new, default option -mlong-double-80 changes long double to a pseudo floating-point type: The type exists in the frontend only; for the middle-end and backend, it's an 128-bit integer that provides storage for a value. The way how the frontend emit IR for an operation varies:
1. The ABI of such long double is the same with an 128-bit integer. For x86-64 it's passed and returned in memory.
2. Load/store operations are performed with integer instructions, and are exact.
3. Bitwise operations, such as fabsl and isnan, are performed directly in the frontend with integer instructions.
4. Arithmetic operations of builtin operators are performed by first converting long double to double, doing the arithmetic, then converting the result back. This matches how x86-64 emulation works by default on Windows on ARM64 with only 53-bit precision, and should be more efficient than a strict softmath implementation, which the AArch64 backend doesn't support yet.
5. Other builtin functions result in external calls to mingw-w64 CRT directly.
These changes have been verified on my ARM64 tablet with a patched mingw-w64 CRT. No regressions are introduced.
Assisted-by: DeepSeek V4.1 Flash
---
Patch is 75.67 KiB, truncated to 20.00 KiB below, full version: https://github.com/llvm/llvm-project/pull/237057.diff
14 Files Affected:
````````````diff --git a/clang/include/clang/Basic/TargetInfo.h b/clang/include/clang/Basic/TargetInfo.h
index a6523e8eaaa437..32aeb5f645b3db 100644
--- a/clang/include/clang/Basic/TargetInfo.h
+++ b/clang/include/clang/Basic/TargetInfo.h
@@ -709,6 +709,12 @@ class TargetInfo : public TransferrableTargetInfo,
/// Whether half args and returns are supported.
virtual bool allowHalfArgsAndReturns() const { return HalfArgsAndReturns; }
+ /// Determine whether the target has the x87-specific `long double` type
+ /// without a physical x87. The target arm64ec-w64-mingw32 has this property.
+ /// On such a target, `long double` is an integer image and is not a true
+ /// floating-point type.
+ virtual bool hasSoftX87LongDouble() const { return false; }
+
/// Determine whether the __float128 type is supported on this target.
virtual bool hasFloat128Type() const { return HasFloat128; }
diff --git a/clang/lib/Basic/Targets/AArch64.cpp b/clang/lib/Basic/Targets/AArch64.cpp
index 7ddf9d87ad163e..01da8b879df053 100644
--- a/clang/lib/Basic/Targets/AArch64.cpp
+++ b/clang/lib/Basic/Targets/AArch64.cpp
@@ -206,6 +206,10 @@ AArch64TargetInfo::AArch64TargetInfo(const llvm::Triple &Triple,
this->MCountName = "\01_mcount";
else if (Triple.getOS() == llvm::Triple::UnknownOS)
this->MCountName = Triple.isGNUEnvironment() ? "\01_mcount" : "mcount";
+
+ // This should be compatible with x86-64.
+ if (Triple.isWindowsArm64EC() && !Triple.isWindowsMSVCEnvironment())
+ HasFloat128 = true;
}
StringRef AArch64TargetInfo::getABI() const { return ABI; }
@@ -450,6 +454,11 @@ void AArch64TargetInfo::getTargetDefines(const LangOptions &Opts,
if (T.isLFI())
Builder.defineMacro("__LFI__");
+ if (HasFloat128) {
+ Builder.defineMacro("__FLOAT128__");
+ Builder.defineMacro("__SIZEOF_FLOAT128__", "16");
+ }
+
// Inline assembly supports AArch64 flag outputs.
Builder.defineMacro("__GCC_ASM_FLAG_OUTPUTS__");
@@ -1831,6 +1840,14 @@ WindowsARM64TargetInfo::WindowsARM64TargetInfo(const llvm::Triple &Triple,
SizeType = UnsignedLongLong;
PtrDiffType = SignedLongLong;
IntPtrType = SignedLongLong;
+
+ if (Triple.isWindowsArm64EC() && !Triple.isWindowsMSVCEnvironment()) {
+ // arm64ec-w64-mingw32 should be interoperable with x86_64-w64-mingw32,
+ // which by default has `long double` as the x87-specific extended
+ // precision format.
+ LongDoubleWidth = LongDoubleAlign = SuitableAlign = 128;
+ LongDoubleFormat = &llvm::APFloat::x87DoubleExtended();
+ }
}
TargetInfo::BuiltinVaListKind
diff --git a/clang/lib/Basic/Targets/AArch64.h b/clang/lib/Basic/Targets/AArch64.h
index 00e84cc4864399..c17a092265ddb1 100644
--- a/clang/lib/Basic/Targets/AArch64.h
+++ b/clang/lib/Basic/Targets/AArch64.h
@@ -295,6 +295,11 @@ class LLVM_LIBRARY_VISIBILITY WindowsARM64TargetInfo
BuiltinVaListKind getBuiltinVaListKind() const override;
CallingConvCheckResult checkCallingConvention(CallingConv CC) const override;
+
+ bool hasSoftX87LongDouble() const override {
+ return Triple.isWindowsArm64EC() &&
+ LongDoubleFormat == &llvm::APFloat::x87DoubleExtended();
+ }
};
// Windows ARM, MS (C++) ABI
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index e154b9e752fd5c..9b3b28c85a03e3 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -2714,12 +2714,440 @@ static void ClearPadding(CodeGenFunction &CGF, Address Src,
}
}
+/// Lower builtins that operate on ARM64EC's software x87 long double. The
+/// ones that are required to be exact (fabs, copysign, signbit, isnan, isinf,
+/// isfinite, isnormal, fpclassify) are implemented with integer operations on
+/// the image itself; everything else is evaluated in `double` exactly like the
+/// C library does for its own long double entry points. Return false when the
+/// builtin does not involve such a value.
+bool CodeGenFunction::EmitSoftX87LongDoubleBuiltin(unsigned BuiltinID,
+ const CallExpr *E,
+ RValue &Result) {
+ // The 'nan' and 'inf' families produce a `long double`, so they do not
+ // consume one but do need the integer image constructed below: they are the
+ // only builtins that yield a constant. Match the bare name, since some of
+ // them are also reachable with a `__builtin_` prefix.
+ std::string Name = getContext().BuiltinInfo.getName(BuiltinID);
+ StringRef BaseName = Name;
+ BaseName.consume_front("__builtin_");
+ bool ProducesLongDouble = false;
+ for (const char *Str : {"nanl", "nansl", "infl", "huge_vall"})
+ ProducesLongDouble |= BaseName == Str;
+
+ // Everything below rewrites a call into its binary64 equivalent, which only
+ // makes sense when a `long double` is *consumed*.
+ bool ConsumesLongDouble = false;
+ for (const Expr *Arg : E->arguments()) {
+ QualType Ty = Arg->getType();
+ if (const auto *CTy = Ty->getAs<ComplexType>())
+ Ty = CTy->getElementType();
+ ConsumesLongDouble |= Ty->isSpecificBuiltinType(BuiltinType::LongDouble);
+ }
+
+ if (!ProducesLongDouble && !ConsumesLongDouble)
+ return false;
+
+ // `fabsl`: Set the sign bit to zero.
+ if (BaseName == "fabsl") {
+ if (!E->getType()->isSpecificBuiltinType(BuiltinType::LongDouble))
+ return false;
+ llvm::Value *V = EmitScalarExpr(E->getArg(0));
+ llvm::Constant *MagnitudeMask = llvm::ConstantInt::get(
+ V->getType(), ~llvm::APInt::getOneBitSet(128, 79));
+ Result = RValue::get(Builder.CreateAnd(V, MagnitudeMask));
+ return true;
+ }
+
+ // `copysignl`: Take the magnitude from the first operand and the sign bit
+ // from the second one.
+ if (BaseName == "copysignl") {
+ if (!E->getType()->isSpecificBuiltinType(BuiltinType::LongDouble))
+ return false;
+ llvm::Value *X = EmitScalarExpr(E->getArg(0));
+ llvm::Value *Y = EmitScalarExpr(E->getArg(1));
+ llvm::Constant *MagnitudeMask = llvm::ConstantInt::get(
+ X->getType(), ~llvm::APInt::getOneBitSet(128, 79));
+ llvm::Value *Magnitude = Builder.CreateAnd(X, MagnitudeMask);
+ llvm::Value *Sign = Builder.CreateAnd(Y, Builder.CreateNot(MagnitudeMask));
+ Result = RValue::get(Builder.CreateOr(Magnitude, Sign));
+ return true;
+ }
+
+ // `signbit`: Take the sign bit and normalize it to boolean.
+ if (Name == "__builtin_signbit" || BaseName == "signbitl") {
+ if (!E->getArg(0)->getType()->isSpecificBuiltinType(
+ BuiltinType::LongDouble))
+ return false;
+ llvm::Value *V = EmitScalarExpr(E->getArg(0));
+ llvm::Value *Sign =
+ Builder.CreateTrunc(Builder.CreateLShr(V, 79), Builder.getInt1Ty());
+ Result = RValue::get(Builder.CreateZExt(Sign, ConvertType(E->getType())));
+ return true;
+ }
+
+ // `__builtin_isnan`: Check if the value is a NaN. An unnormal or pseudo
+ // denormal image is undefined behavior, since it will never be produced in a
+ // constant expression.
+ if (Name == "__builtin_isnan") {
+ if (!E->getArg(0)->getType()->isSpecificBuiltinType(
+ BuiltinType::LongDouble))
+ return false;
+ llvm::Value *V = EmitScalarExpr(E->getArg(0));
+ llvm::Constant *MagnitudeMask = llvm::ConstantInt::get(
+ V->getType(), ~llvm::APInt::getOneBitSet(128, 79));
+ llvm::Value *Magnitude = Builder.CreateAnd(V, MagnitudeMask);
+ llvm::APInt InfinityImage(128, 0x8000000000000000ull);
+ InfinityImage |= llvm::APInt(128, 0x7fffull) << 64;
+ llvm::Constant *Infinity =
+ llvm::ConstantInt::get(V->getType(), InfinityImage);
+ llvm::Value *IsNan = Builder.CreateICmpUGT(Magnitude, Infinity);
+ Result = RValue::get(Builder.CreateZExt(IsNan, ConvertType(E->getType())));
+ return true;
+ }
+
+ // `__builtin_isinf`: Check if the value is a (positive or negative) infinity.
+ if (Name == "__builtin_isinf") {
+ if (!E->getArg(0)->getType()->isSpecificBuiltinType(
+ BuiltinType::LongDouble))
+ return false;
+ llvm::Value *V = EmitScalarExpr(E->getArg(0));
+ llvm::Constant *MagnitudeMask = llvm::ConstantInt::get(
+ V->getType(), ~llvm::APInt::getOneBitSet(128, 79));
+ llvm::Value *Magnitude = Builder.CreateAnd(V, MagnitudeMask);
+ llvm::APInt InfinityImage(128, 0x8000000000000000ull);
+ InfinityImage |= llvm::APInt(128, 0x7fffull) << 64;
+ llvm::Constant *Infinity =
+ llvm::ConstantInt::get(V->getType(), InfinityImage);
+ llvm::Value *IsInf = Builder.CreateICmpEQ(Magnitude, Infinity);
+ Result = RValue::get(Builder.CreateZExt(IsInf, ConvertType(E->getType())));
+ return true;
+ }
+
+ // `__builtin_isinf_sign`: Return 1 or -1 depending on the sign of an
+ // infinity, and zero for everything else.
+ if (Name == "__builtin_isinf_sign") {
+ if (!E->getArg(0)->getType()->isSpecificBuiltinType(
+ BuiltinType::LongDouble))
+ return false;
+ llvm::Value *V = EmitScalarExpr(E->getArg(0));
+ llvm::Constant *MagnitudeMask = llvm::ConstantInt::get(
+ V->getType(), ~llvm::APInt::getOneBitSet(128, 79));
+ llvm::Value *Magnitude = Builder.CreateAnd(V, MagnitudeMask);
+ llvm::APInt InfinityImage(128, 0x8000000000000000ull);
+ InfinityImage |= llvm::APInt(128, 0x7fffull) << 64;
+ llvm::Constant *Infinity =
+ llvm::ConstantInt::get(V->getType(), InfinityImage);
+ llvm::Type *IntTy = ConvertType(E->getType());
+ llvm::Value *Sign =
+ Builder.CreateTrunc(Builder.CreateLShr(V, 79), Builder.getInt1Ty());
+ llvm::Value *Signed = Builder.CreateSelect(
+ Sign, llvm::ConstantInt::get(IntTy, -1, /*isSigned=*/true),
+ llvm::ConstantInt::get(IntTy, 1));
+ llvm::Value *IsInf = Builder.CreateICmpEQ(Magnitude, Infinity);
+ Result = RValue::get(
+ Builder.CreateSelect(IsInf, Signed, llvm::ConstantInt::get(IntTy, 0)));
+ return true;
+ }
+
+ // `__builtin_isfinite`: Check if the value is neither an infinity nor a NaN.
+ if (Name == "__builtin_isfinite") {
+ if (!E->getArg(0)->getType()->isSpecificBuiltinType(
+ BuiltinType::LongDouble))
+ return false;
+ llvm::Value *V = EmitScalarExpr(E->getArg(0));
+ llvm::Constant *MagnitudeMask = llvm::ConstantInt::get(
+ V->getType(), ~llvm::APInt::getOneBitSet(128, 79));
+ llvm::Value *Magnitude = Builder.CreateAnd(V, MagnitudeMask);
+ llvm::APInt InfinityImage(128, 0x8000000000000000ull);
+ InfinityImage |= llvm::APInt(128, 0x7fffull) << 64;
+ llvm::Constant *Infinity =
+ llvm::ConstantInt::get(V->getType(), InfinityImage);
+ llvm::Value *IsFinite = Builder.CreateICmpULT(Magnitude, Infinity);
+ Result =
+ RValue::get(Builder.CreateZExt(IsFinite, ConvertType(E->getType())));
+ return true;
+ }
+
+ // `__builtin_isnormal`: Check if the value is finite and nonzero. A
+ // canonical image has the explicit integer bit set when the exponent is
+ // nonzero, so the exponent alone decides; an unnormal is undefined behaviour.
+ if (Name == "__builtin_isnormal") {
+ if (!E->getArg(0)->getType()->isSpecificBuiltinType(
+ BuiltinType::LongDouble))
+ return false;
+ llvm::Value *V = EmitScalarExpr(E->getArg(0));
+ llvm::Value *Exp = Builder.CreateAnd(
+ Builder.CreateTrunc(Builder.CreateLShr(V, 64), Builder.getInt16Ty()),
+ Builder.getInt16(0x7FFF));
+ llvm::Value *IsNormal =
+ Builder.CreateAnd(Builder.CreateICmpNE(Exp, Builder.getInt16(0)),
+ Builder.CreateICmpNE(Exp, Builder.getInt16(0x7FFF)));
+ Result =
+ RValue::get(Builder.CreateZExt(IsNormal, ConvertType(E->getType())));
+ return true;
+ }
+
+ // `__builtin_fpclassify`: Pick the first five arguments that correspond to a
+ // NaN, an infinity, a normal, a subnormal and a zero respectively.
+ if (Name == "__builtin_fpclassify") {
+ if (!E->getArg(5)->getType()->isSpecificBuiltinType(
+ BuiltinType::LongDouble))
+ return false;
+ llvm::Value *V = EmitScalarExpr(E->getArg(5));
+ llvm::Value *Exp = Builder.CreateAnd(
+ Builder.CreateTrunc(Builder.CreateLShr(V, 64), Builder.getInt16Ty()),
+ Builder.getInt16(0x7FFF));
+ llvm::Value *Man = Builder.CreateTrunc(V, Builder.getInt64Ty());
+ llvm::Value *ExpZero = Builder.CreateICmpEQ(Exp, Builder.getInt16(0));
+ llvm::Value *ExpAllOnes =
+ Builder.CreateICmpEQ(Exp, Builder.getInt16(0x7FFF));
+ llvm::Value *ManZero = Builder.CreateICmpEQ(Man, Builder.getInt64(0));
+ // Infinity is the all-ones exponent with nothing but the integer bit set;
+ // any other value with that exponent is a NaN. An unnormal, whose integer
+ // bit is clear, is undefined behaviour.
+ llvm::Value *IsInf = Builder.CreateAnd(
+ ExpAllOnes,
+ Builder.CreateICmpEQ(Man, Builder.getInt64(0x8000000000000000ull)));
+ llvm::Value *IsNaN =
+ Builder.CreateAnd(ExpAllOnes, Builder.CreateNot(IsInf));
+ llvm::Value *IsNormal = Builder.CreateAnd(Builder.CreateNot(ExpZero),
+ Builder.CreateNot(ExpAllOnes));
+ llvm::Value *IsSubnormal =
+ Builder.CreateAnd(ExpZero, Builder.CreateNot(ManZero));
+ llvm::Value *R = EmitScalarExpr(E->getArg(4)); // zero
+ R = Builder.CreateSelect(IsSubnormal, EmitScalarExpr(E->getArg(3)), R);
+ R = Builder.CreateSelect(IsNormal, EmitScalarExpr(E->getArg(2)), R);
+ R = Builder.CreateSelect(IsInf, EmitScalarExpr(E->getArg(1)), R);
+ R = Builder.CreateSelect(IsNaN, EmitScalarExpr(E->getArg(0)), R);
+ Result = RValue::get(R);
+ return true;
+ }
+
+ // `infl` and `huge_vall`: Infinity has the significand 0x8000000000000000
+ // with an all-ones exponent, and the six padding bytes are zeroes. They
+ // take no argument at all, so there is nothing to check.
+ if (BaseName == "infl" || BaseName == "huge_vall") {
+ llvm::APInt Image(128, 0x8000000000000000ull);
+ Image |= llvm::APInt(128, 0x7fffull) << 64;
+ llvm::Type *ImageTy = llvm::IntegerType::get(getLLVMContext(), 128);
+ Result = RValue::get(llvm::ConstantInt::get(ImageTy, Image));
+ return true;
+ }
+
+ // `nanl` and `nansl`: The quiet NaN has the significand 0xc000000000000000
+ // and the signalling one has 0xa000000000000000, both with an all-ones
+ // exponent. The payload of the tag argument is not propagated, but the
+ // argument is still evaluated, since it may have side effects.
+ if (BaseName == "nanl" || BaseName == "nansl") {
+ if (!E->getArg(0)->getType()->isPointerType())
+ return false;
+ EmitScalarExpr(E->getArg(0));
+ llvm::APInt Image(128, BaseName == "nansl" ? 0xa000000000000000ull
+ : 0xc000000000000000ull);
+ Image |= llvm::APInt(128, 0x7fffull) << 64;
+ llvm::Type *ImageTy = llvm::IntegerType::get(getLLVMContext(), 128);
+ Result = RValue::get(llvm::ConstantInt::get(ImageTy, Image));
+ return true;
+ }
+
+ // `__builtin_isunordered`: True if either operand is a NaN.
+ // `__builtin_isgreater`, `__builtin_isgreaterequal`, `__builtin_isless` and
+ // `__builtin_islessequal`: Perform ordered comparisons of two operands.
+ // `__builtin_islessgreater`: True if the operands are ordered and unequal;
+ // that is, if either of `x < y` and `x > y` holds.
+ struct BuiltinComparison {
+ const char *Name;
+ CmpInst::Predicate Predicate;
+ };
+ static constexpr BuiltinComparison BuiltinComparisons[] = {
+ {"__builtin_isunordered", CmpInst::FCMP_UNO},
+ {"__builtin_isgreater", CmpInst::FCMP_OGT},
+ {"__builtin_isgreaterequal", CmpInst::FCMP_OGE},
+ {"__builtin_isless", CmpInst::FCMP_OLT},
+ {"__builtin_islessequal", CmpInst::FCMP_OLE},
+ {"__builtin_islessgreater", CmpInst::FCMP_ONE},
+ };
+ for (const auto &BC : BuiltinComparisons)
+ if (Name == BC.Name) {
+ if (!E->getArg(0)->getType()->isSpecificBuiltinType(
+ BuiltinType::LongDouble) ||
+ !E->getArg(1)->getType()->isSpecificBuiltinType(
+ BuiltinType::LongDouble))
+ return false;
+ llvm::Value *A = EmitScalarExpr(E->getArg(0));
+ llvm::Value *B = EmitScalarExpr(E->getArg(1));
+ llvm::Value *Cmp = EmitSoftX87LongDoubleComparison(A, B, BC.Predicate);
+ Result = RValue::get(Builder.CreateZExt(Cmp, ConvertType(E->getType())));
+ return true;
+ }
+
+ // `__builtin_isfpclass`: Test the image against a mask of class bits. The
+ // second argument is an integer constant expression built out of the
+ // `__FPCLASS_*` values, whose bits number the classes in this order:
+ // signalling NaN, quiet NaN, -inf, negative normal, negative subnormal,
+ // -0, +0, positive subnormal, positive normal and +inf. So the value only
+ // has to be mapped to the ordinal of the class it belongs to, and the bit
+ // of the mask with that index decides.
+ if (Name == "__builtin_isfpclass") {
+ if (!E->getArg(0)->getType()->isSpecificBuiltinType(
+ BuiltinType::LongDouble))
+ return false;
+ Expr::EvalResult MaskResult;
+ if (!E->getArg(1)->EvaluateAsInt(MaskResult, getContext()))
+ return false;
+ const uint64_t Mask = MaskResult.Val.getInt().getLimitedValue();
+ llvm::Value *V = EmitScalarExpr(E->getArg(0));
+ llvm::Value *Exp = Builder.CreateAnd(
+ Builder.CreateTrunc(Builder.CreateLShr(V, 64), Builder.getInt16Ty()),
+ Builder.getInt16(0x7FFF));
+ llvm::Value *Man = Builder.CreateTrunc(V, Builder.getInt64Ty());
+ llvm::Value *Negative =
+ Builder.CreateTrunc(Builder.CreateLShr(V, 79), Builder.getInt1Ty());
+ llvm::Value *ExpZero = Builder.CreateICmpEQ(Exp, Builder.getInt16(0));
+ llvm::Value *ExpAllOnes =
+ Builder.CreateICmpEQ(Exp, Builder.getInt16(0x7FFF));
+ llvm::Value *ManZero = Builder.CreateICmpEQ(Man, Builder.getInt64(0));
+ // Infinity is the all-ones exponent with nothing but the integer bit
+ // set, and a NaN is any other image with that exponent, quiet when bit
+ // 62 of the significand is set. An unnormal, whose integer bit is
+ // clear, is undefined behaviour.
+ llvm::Value *Infinity = Builder.CreateAnd(
+ ExpAllOnes,
+ Builder.CreateICmpEQ(Man, Builder.getInt64(0x8000000000000000ull)));
+ llvm::Value *Quiet = Builder.CreateICmpNE(
+ Builder.CreateAnd(Man, Builder.getInt64(0x4000000000000000ull)),
+ Builder.getInt64(0));
+ // The magnitudes are numbered 2 to 5 from the largest downwards, and the
+ // positive classes continue the sequence in the reverse order, which makes
+ // them `11 - Magnitude`. A NaN takes 0 or 1 instead of a magnitude.
+ llvm::Value *Magnitude = Builder.getInt64(2);
+ Magnitude = Builder.CreateSelect(Builder.CreateNot(ExpAllOnes),
+ Builder.getInt64(3), Magnitude);
+ Magnitude = Builder.CreateSelect(ExpZero, Builder.getInt64(4), Magnitude);
+ Magnitude = Builder.CreateSelect(Builder.CreateAnd(ExpZero, ManZero),
+ Builder.getInt64(5), Magnitude);
+ Magnitude = Builder.CreateSelect(
+ Negative, Magnitude,
+ Builder.CreateSub(Builder.getInt64(11), Magnitude));
+ llvm::Value *Ordinal =
+ Builder.CreateSelect(Quiet, Builder.getInt64(1), Builder.getInt64(0));
+ Ordinal = Builder.CreateSelect(
+ Builder.CreateAnd(ExpAllOnes, Builder.CreateNot(Infinity)), Ordinal,
+ Magnitude);
+ llvm::Value *Bit =
+ Builder.CreateAnd(Builder.CreateLShr(Builder.getInt64(Mask), Ordinal),
+ Builder.getInt64(1));
+ Result = RValue::get(
+ Builder.CreateZExt(Builder.CreateICmpNE(Bit, Builder.getInt64(0)),
+ ConvertType(E->getType())));
+ return true;
+ }
+
+ // `__builtin_complex`: Assemble a complex value out of a real and an
+ // imaginary part, which become the low and high halves of the image pair.
+ // Its operands are "custom type checked", so they are not promoted: both
+ // have the same real floating type already, and they have to be the `long
+ // double` one for this lowering to apply.
+ if (Name == "__builtin_complex") {
+ if (!E->getArg(0)->getType()->isSpecificBuiltinType(
+ BuiltinType::LongDouble) ||
+ !E->getArg(1)->getType()->isSpecificBuiltinType(
+ BuiltinType::LongDouble))
+ return false;
+ llvm::Value *Real = EmitScalarE...
[truncated]
</details>
cc @mstorsjo @cjacek
Although much of the commit is AI-generated, I spent two days reviewing every change and removed parts that looked apparently incorrect.
__arm64ec_x87ld_to_double and __arm64ec_double_to_x87ld will have to be implemented in compiler-rt, which I will do later.
Unhandled non-library builtins still reach floating-point intrinsic emission with an i128 operand: nonconstant __builtin_elementwise_abs(x) and __builtin_canonicalizel(x) produce invalid llvm.fabs.i128 and llvm.canonicalize.i128 calls. Add image-aware lowering for these builtins and other affected elementwise operations, or diagnose unsupported operations before they reach the generic emitter.
Atomic long double increment/decrement never reaches this conversion: the earlier fast path accepts the power-of-two i128 width and calls ConstantFP::get(i128, 1.0), failing during code generation. At line 3495, require Ty->isFloatingPointTy() && llvm::has_single_bit(Ty->getScalarSizeInBits()) so these operations use the existing load/convert/compare-exchange fallback.
Recursive vector lowering also turns long double vector elements into i128, but the arithmetic handlers recognize only scalar LongDouble. Adding two values of typedef long double V __attribute__((vector_size(32))) therefore emits integer add <2 x i128>, adding encodings rather than values. Add per-lane software lowering, or reject unsupported vector arithmetic instead of silently miscompiling it.
This mask retains the unspecified padding bytes, so a valid 1.0L image with bit 80 set is reported as NaN; the related predicates also misclassify finite values and infinities. Use llvm::APInt::getLowBitsSet(128, 79) to clear both sign and padding before comparing magnitudes. Apply the same change to isinf, isinf_sign, and isfinite at CGBuiltin.cpp:2815,2834,2859, and test nonzero padding.
This discards the NaN tag, so __builtin_nanl("1") can retain payload 1 in a global initializer but produce the default payload when returned from a function. Dynamic nanl(tag) calls also ignore the tag. Preserve payload-aware constant evaluation when constructing the image, and call the library for nonconstant nanl tags.
This bypass drops SIG and emits exception-free integer comparisons even when floating-point exceptions are observable. Relational comparisons with quiet NaNs and equality comparisons with signaling NaNs then fail to raise FE_INVALID; the boolean conversion at CGExprScalar.cpp:482–488 likewise loses the signaling-NaN exception. Preserve signaling and exception-mode information and provide exception-aware lowering without narrowing the exact x87 comparison result.
<!-- ccr-overview-v2 -->
🟡 Changes recommended
Unresolved issues produce invalid IR for long-double builtins, cause code-generation failures for atomic increment/decrement, and silently miscompile vector arithmetic as integer operations.
<details open>
<summary><strong>6 open issues</strong></summary>
</details>
<details>
<summary><strong>What changed in this PR</strong></summary>
Adds selectable long double formats for ARM64EC MinGW, defaulting to x87-compatible storage for interoperability with x86-64 MinGW. The default changes the ABI relative to existing ARM64EC binaries.
Changes:
-mlong-double-{64,80,128} and configures target formats.i128, with image-based operations, double-based arithmetic, and runtime calls.| File | Description |
| ---- | ----------- |
| clang/test/Driver/arm64ec-long-double.c | Tests option forwarding and unsupported targets. |
| clang/test/CodeGen/arm64ec-soft-x87-long-double.c | Tests software x87 operations and storage. |
| clang/test/CodeGen/arm64ec-long-double-modes.c | Tests all three format modes. |
| clang/lib/Driver/ToolChains/Clang.cpp | Accepts format options for non-MSVC ARM64EC. |
| clang/lib/CodeGen/CodeGenTypes.cpp | Maps software x87 values to i128. |
| clang/lib/CodeGen/CodeGenFunction.h | Declares software x87 lowering helpers. |
| clang/lib/CodeGen/CGExprScalar.cpp | Adds scalar arithmetic, conversions, and comparisons. |
| clang/lib/CodeGen/CGExprConstant.cpp | Emits x87 constants as integer images. |
| clang/lib/CodeGen/CGExprComplex.cpp | Adds software x87 complex operations. |
| clang/lib/CodeGen/CGExpr.cpp | Handles complex increment and decrement. |
| clang/lib/CodeGen/CGBuiltin.cpp | Adds image-aware builtin and library-call lowering. |
| clang/lib/Basic/Targets/AArch64.h | Reports software x87 target support. |
| clang/lib/Basic/Targets/AArch64.cpp | Sets the default format and enables float128 support. |
| clang/include/clang/Basic/TargetInfo.h | Adds the software x87 capability interface. |
</details>
<sub>Review effort: Balanced</sub>
Fixed in 29da274f4cd33a80e943a3f0316fc5ecda624e7e.
This is not a strict FP implementation, so WONTFIX.
Fixed in e618dc3475b726caf96763d41bc629217783ba6a
Added software lowering in 13466c8a8f6943a19f971c9809e6b8f7a5b4583f
Fixed in d0ff68c1c119112d9b3e0ee5e551d2c67c0e1276
Add in 295fe6ac475e3b80ddcbbf2281f8984fcd052f67
Nonconstant __builtin_iszero, __builtin_issubnormal, and __builtin_issignaling calls with long double reach the library fallback because their builtin definitions carry FunctionWithBuiltinPrefix. This emits calls to names such as iszero, which are not MinGW long-double library entry points, rather than classifying the value. Handle these predicates here by reusing the image classifier with the corresponding class masks.
With -fenable-matrix, long double matrices are accepted and lowered to vectors of i128, but this predicate excludes matrix types. Matrix addition therefore reaches MatrixBuilder::CreateAdd and adds the integer encodings instead of the floating-point values. Add matrix-aware software lowering, including scalar/matrix operations, or diagnose unsupported operations before emitting integer arithmetic.
With -ffixed-point, conversions between long double and _Accum or _Fract take the earlier fixed-point dispatch and never reach this conversion logic. Both directions pass an i128 type to FixedPointBuilder::getAccommodatingFloatType, which requires floating-point semantics and aborts. Route these conversions through double before the fixed-point dispatch.
This leaves signaling NaNs unchanged: for example, the supported image 0x7fffa000000000000000 survives both the select and the padding mask with its quiet bit clear. __builtin_canonicalizel normally lowers to llvm.canonicalize, which requires a quiet NaN result for signaling input, independently of exception handling. Quiet NaN images while preserving their sign and payload before returning them.
<!-- ccr-overview-v2 -->
🟡 Changes recommended
Unresolved long-double lowering defects can abort fixed-point conversions, miscompile matrix arithmetic, and emit calls to unavailable classification functions.
<details open>
<summary><strong>4 open issues</strong></summary>
</details>
<details>
<summary><strong>1 previously missed issue</strong></summary>
In code that hasn't changed since last review
<details>
<summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Honor assembler labels before long-double image lowering</summary>
clang/lib/CodeGen/CGBuiltin.cpp:2748
The early image lowering ignores assembler labels: long double fabsl(long double) __asm__("custom_fabsl"); followed by fabsl(x) now clears a bit instead of calling custom_fabsl. The existing BuiltinIDIfNoAsmLabel guard runs only after this helper returns. Honor AsmLabelAttr before the image-level special cases and call the labeled function.
</details>
</details>
<details>
<summary><strong>6 resolved since last review</strong></summary>
</details>
<sub>Review effort: Balanced</sub>
Fixed in 974c9f4e523ac3c11b6a033da02ca89f1d195d31
Fixed in 74319fcfa1a1c5d6e8f400a3f522b8a330db0441
Fixed 1d0485c3f9b57283c69d201bf568f508617163e1. Also verified on x86-physical 64 that the behavior matches.
Fixed in 3a6e894c4949cab0c01728872d17f5f616c1d98e
Re-running libcxx and mingw-w64 tests now.
-mlong-double-80 is made default to fix the interoperability bug with x86_64-w64-mingw32. This also introduces an ABI break with old ARM64EC binaries.
I think this need a RFC.
> -mlong-double-80 is made default to fix the interoperability bug with x86_64-w64-mingw32. This also introduces an ABI break with old ARM64EC binaries.
> I think this need a RFC.
I think that's a bit overkill. The ecosystem of active mingw developers isn't very big (and those who are interested in arm64ec is even smaller), and all of them are already CCd on this PR.
As a high level idea, I think making specifically the mingw variant of arm64ec use 80 bit long doubles to make it more compatible with x86_64 mingw (which indeed is the main target it needs to be consistent and compatible with), is very reasonable to do. The current state is indeed inconsistent, even though the problem is practically not very big.
Whether it makes sense to do this mainly boils down to whether the implementation is sane, reasonable and acceptable - or if the current inconsistency is less of a burden than very messy code. (I haven't had time to actually review it in detail yet.)
If people switch to 64 bit long doubles on x86_64 mingw and consistently on arm64ec mingw with -mlong-double-64, I would expect that to still work and still stay compatible as well.
> -mlong-double-80 is made default to fix the interoperability bug with x86_64-w64-mingw32. This also introduces an ABI break with old ARM64EC binaries.
> I think this need a RFC.
1. If (as you may think) x87 long double is rare => the impact is minimal, so doesn't need an RFC.
2. If x87 long double is used widely => this is a serious bug and should be fixed, so doesn't need an RFC.
@mstorsjo
If people switch to 64 bit long doubles on x86_64 mingw and consistently on arm64ec mingw with -mlong-double-64, I would expect that to still work and still stay compatible as well.
It doesn't solve any existent issues but brings new issues by creating a parallel universe.
> If people switch to 64 bit long doubles on x86_64 mingw and consistently on arm64ec mingw with -mlong-double-64, I would expect that to still work and still stay compatible as well.
> It doesn't solve any existent issues but brings new issues by creating a parallel universe.
You did not answer the question: With this patch in place, does -mlong-double-64 on arm64ec revert things back to the way they were before, which should be compatible with x86_64 with -mlong-double-64?
> > If people switch to 64 bit long doubles on x86_64 mingw and consistently on arm64ec mingw with -mlong-double-64, I would expect that to still work and still stay compatible as well.
>
>
> It doesn't solve any existent issues but brings new issues by creating a parallel universe.
> You did not answer the question: With this patch in place, does-mlong-double-64on arm64ec revert things back to the way they were before, which should be compatible with x86_64 with-mlong-double-64?
I haven't tested it yet. I have read all changes and I think it won't be affected, but I'll test it.
> You did not answer the question: With this patch in place, does-mlong-double-64on arm64ec revert things back to the way they were before, which should be compatible with x86_64 with-mlong-double-64?
> I haven't tested it yet. I have read all changes and I think it won't be affected, but I'll test it.
Ok, thank you. Yes I think a few testcases that does that would be good to include, to check that it still works as expected.
To be fair, I don't quite like this implementation: Such a long double type only exists in the frontend, so any arithmetic operations must be either handled in the frontend using integer operations, or converted to operations on double to the middle-end; the fact that this is a floating-point type must not leak into the middle end, where it would be miscompiled as arithmetic operations on integers.
But this is still much simpler than implementing x87 soft float in the AArch64 backend which nobody other than ARM64EC would use.
libcxx test results with -mlong-double-64:
| | |
|---|---|
| Discovered | 11527 |
| Passed | 10234 (88.78%) |
| Unsupported | 1223 |
| Expectedly Failed | 55 |
| Failed | 15 |
Failed tests are: locale time.get.byname, printf/fmemopen, aligned_alloc, sized delete, text_encoding, remove_all/toctou, shared_timed_mutex; none related to long dobule
<details>
<summary>Failed tests</summary>
<pre>
llvm-lit.py: D:\lh_mouse\GitHub\MINGW-packages\mingw-w64-llvm\src\llvm-project\libcxx\utils\libcxx\test\config.py:24: note: (llvm-libc++-mingw.cfg.in) All available features: buildhost=win32, buildhost=windows, c++29, c++experimental, can-create-symlinks, character-conversion-warnings, clang, clang-24, clang-24.0, clang-24.0.0, diagnose-if-support, enable-benchmarks=no, gcc-style-warnings, has-128-bit-atomics, has-64-bit-atomics, has-fblocks, has-fconstexpr-steps, large_tests, libcpp-abi-version=1, libcpp-assertion-semantic=quick_enforce, libcpp-hardening-mode=none, libcpp-has-no-availability-markup, locale.en_US.UTF-8, locale.fr_CA.ISO8859-1, locale.fr_FR.UTF-8, locale.ja_JP.UTF-8, locale.ru_RU.UTF-8, locale.zh_CN.UTF-8, long_tests, no-tzdb, objective-c++, optimization=none, std-at-least-c++03, std-at-least-c++11, std-at-least-c++14, std-at-least-c++17, std-at-least-c++20, std-at-least-c++23, std-at-least-c++26, std-at-least-c++29, stdlib=libc++, stdlib=llvm-libc++, target=arm64ec-w64-mingw32, verify-support, windows
-- Testing: 11527 tests, 8 workers --
Testing:
FAIL: llvm-libc++-mingw.cfg.in :: std/text/text_encoding/text_encoding.members/environment.pass.cpp (4 of 11527)
Testing:
FAIL: llvm-libc++-mingw.cfg.in :: std/input.output/iostream.format/print.fun/println.blank_line.sh.cpp (8 of 11527)
Testing:
FAIL: llvm-libc++-mingw.cfg.in :: std/input.output/filesystems/fs.op.funcs/fs.op.remove_all/toctou.pass.cpp (9 of 11527)
Testing:
FAIL: llvm-libc++-mingw.cfg.in :: std/input.output/iostream.format/print.fun/println.sh.cpp (11 of 11527)
Testing:
FAIL: llvm-libc++-mingw.cfg.in :: std/localization/locale.categories/category.time/locale.time.get.byname/get_one.pass.cpp (22 of 11527)
Testing:
FAIL: llvm-libc++-mingw.cfg.in :: std/localization/locale.categories/category.time/locale.time.get.byname/get_date.pass.cpp (25 of 11527)
Testing:
FAIL: llvm-libc++-mingw.cfg.in :: std/thread/thread.mutex/thread.mutex.requirements/thread.sharedtimedmutex.requirements/thread.sharedtimedmutex.class/try_lock_until_deadlock_bug.pass.cpp (43 of 11527)
Testing:
FAIL: llvm-libc++-mingw.cfg.in :: std/localization/locale.categories/category.time/locale.time.get.byname/get_date_wide.pass.cpp (44 of 11527)
Testing:
FAIL: llvm-libc++-mingw.cfg.in :: libcxx/text/text_encoding/environment.windows.pass.cpp (51 of 11527)
Testing:
FAIL: llvm-libc++-mingw.cfg.in :: std/input.output/iostream.format/std.manip/setfill_wchar_max.pass.cpp (58 of 11527)
Testing:
FAIL: llvm-libc++-mingw.cfg.in :: std/language.support/support.dynamic/new.delete/new.delete.array/sized_delete_array.pass.cpp (61 of 11527)
Testing:
FAIL: llvm-libc++-mingw.cfg.in :: std/language.support/support.dynamic/new.delete/new.delete.single/sized_delete.pass.cpp (62 of 11527)
Testing:
FAIL: llvm-libc++-mingw.cfg.in :: std/depr/depr.c.headers/stdlib_h.aligned_alloc.compile.pass.cpp (63 of 11527)
Testing:
FAIL: llvm-libc++-mingw.cfg.in :: std/language.support/support.runtime/cstdlib.aligned_alloc.compile.pass.cpp (64 of 11527)
Testing:
FAIL: llvm-libc++-mingw.cfg.in :: std/input.output/iostream.format/print.fun/no_file_description.pass.cpp (67 of 11527)
</pre>
</details>
I think that's a bit overkill. The ecosystem of active mingw developers isn't very big (and those who are interested in arm64ec is even smaller), and all of them are already CCd on this PR.
1. I think the community should also be involved in this.
2. I think the Clang Area Team should evaluate the complexity this PR introduces to Clang, as it's not just a driver option.
If more people had been involved in the decisions related to MinGW back then, I believe this wouldn’t be an issue at all today. Shouldn’t we learn from the lessons of history?
It doesn't solve any existent issues
What? I'm not sure what you mean, but in fact, this solves all the existent issues!
but brings new issues by creating a parallel universe.
What parallel universe?
If you're talking about compatibility or consistency with old binaries, then this also applies to this PR.
As a high level idea, I think making specifically the mingw variant of arm64ec use 80 bit long doubles to make it more compatible with x86_64 mingw (which indeed is the main target it needs to be consistent and compatible with), is very reasonable to do.
arm64ec is indeed designed for compatibility and consistency, but not with MinGW, rather, with MSVC.
If a program is difficult to port to aarch64 so arm64ec is needed, you can almost assume it lacks good cross-platform design and relies on MSVC. If it can be compiled with MinGW, it’s hard to imagine why it couldn’t be ported to aarch64.
Of course, there are some exceptions, such as drivers and wine. But even in those cases, the reason they use arm64ec is not for compatibility with MinGW.
If we truly care about consistency and compatibility, then rather than create new consistency and compatibility issue to address existing one, we should address all consistency and compatibility issues at once.
I used an LLM to generate a table to show the differences between the two methods:
| Aspect | Switch x86-64 MinGW long double to f64 | Switch arm64ec MinGW long double to f80 |
|---|---|---|
| Resulting formats | All six targets (x86-64 MinGW, aarch64 MinGW, arm64ec MinGW, x86-64 MSVC, aarch64 MSVC, arm64ec MSVC) use f64. | x86-64 MinGW and arm64ec MinGW use f80; the other four targets use f64. |
| Consistency | Fully unified long double format across all six targets. | Two different long double formats across the six targets. |
| Implementation effort | Requires only minor mingw-w64 changes. | Requires substantial Clang changes. |
| ABI compatibility | Breaks compatibility with existing x86-64 MinGW binaries. | Breaks compatibility with existing arm64ec MinGW binaries and arm64ec MinGW/MSVC compatibility. |
| Cross-target compatibility | All six targets share the same f64 long double format and are mutually compatible. | Only x86-64 MinGW and arm64ec MinGW share the same f80 long double format; the other four targets use f64. |
| Performance | Eliminates the x87 dependency. | Degrades arm64ec MinGW long double performance. |
2. I think the Clang Area Team should evaluate the complexity this PR introduces to Clang, as it's not just a driver option.
Sure, whether the complexity introduced is acceptable clearly is something that needs to be evaluated, and if the complexity is high it can be reasonable to defer to the Clang Area Team.
arm64ec is indeed designed for compatibility and consistency, but not with MinGW, rather, with MSVC.
Well when Microsoft designed arm64ec, they obviously didn't care think about mingw interop, nobody claims that.
But if you are building code with an arm64ec mingw target triple, the assumption is that it is binary compatible with x86_64 mingw.
There is generally limited ability for interop between mingw and msvc object files/DLLs anyway - the C++ ABIs are entirely different, there are various nuances elsewhere that differ (e.g. the -export: embedded COFF directives for i386 differ in whether the leading underscore is implicit or explicit), the C runtimes have implemented things differently with what's done inline in headers vs statically linked in the import libraries. Interop between MSVC and mingw works across DLL boundaries, with C-only APIs. Linking object files or static libraries from one environment in the other environment is not assumed to work (and if it does, that's a lucky coincidence).
If a program is difficult to port to aarch64 so arm64ec is needed, you can almost assume it lacks good cross-platform design and relies on MSVC. If it can be compiled with MinGW, it’s hard to imagine why it couldn’t be ported to aarch64.
This doesn't have anything to do with the matter at hand. Yes if you can rebuild everything for aarch64, that's great. But you may also wish to load a binary x86_64 plugin DLL, or you may wish to provide an arm64ec plugin to a host x86_64 executable, etc.
The use case for arm64ec is indeed mostly quite niche, and if most people don't need to use it, that's best.
But if you do build for an arm64ec target, the architecture of arm64ec is such that you can mix and match arm64ec and x86_64 object files as you wish, even within one single DLL.
If we truly care about consistency and compatibility, then rather than create new consistency and compatibility issue to address existing one, we should address all consistency and compatibility issues at once.
This PR does not create a new consistency issue. There is no implied compatibility across arm64ec mingw vs msvc as things stand.
I used an LLM to generate a table to show the differences between the two methods:
As one who has spent a significant amount of work in this area, I would love if x86_64 (and i386) wouldn't use the 80 bit long doubles.
But I'm not willing to put in the effort to try to change the whole mingw ecosystem (including changing defaults across GCC, and/or possibly for all relevant downstream distributors) on x86 to a different form of long doubles.
> I think that's a bit overkill. The ecosystem of active mingw developers isn't very big (and those who are interested in arm64ec is even smaller), and all of them are already CCd on this PR.
> 1. I think the community should also be involved in this.
2. I think the Clang Area Team should evaluate the complexity this PR introduces to Clang, as it's not just a driver option.
Yes, definitely.
If more people had been involved in the decisions related to MinGW back then, I believe this wouldn’t be an issue at all today. Shouldn’t we learn from the lessons of history?
That's a hypothesis against the fact.
> It doesn't solve any existent issues
> What? I'm not sure what you mean, but in fact, this solves all the existent issues!
> The major historical mistake
long double interoperability between {x86_64,arm64ec,aarch64}-{mingw32,msvc}
I don't want to repeat myself over and over. That's just what has happened, and people will continue to use 80-bit long double on x86-64, because they sometimes find it useful. Also hey look, Microsoft also decided to preserve x87 state during a context switch, even it's completely unused by MSVC for AMD64 since the beginning, so x87 is always there, and working somehow.
I think your question is beyond the scope of this PR. It is about how to make ARM64EC compatible with current x86-64; it's not about how people should adopt -mlong-double-64 when compiling their code for x86-64.
> but brings new issues by creating a parallel universe.
> What parallel universe?
> If you're talking about compatibility or consistency with old binaries, then this also applies to this PR.
It doesn't apply to this PR. I haven't heard of any use of arm64ec-w64-mingw32 in production. The cost of this move should be very little. OTOH the cost of moving from 80-bit long double to 64-bit on x86-64 is relatively large.
It's actually not about long double, but about alignof(max_align_t) as a side effect.
> As a high level idea, I think making specifically the mingw variant of arm64ec use 80 bit long doubles to make it more compatible with x86_64 mingw (which indeed is the main target it needs to be consistent and compatible with), is very reasonable to do.
> arm64ec is indeed designed for compatibility and consistency, but not with MinGW, rather, with MSVC.
I think I said arm64ec-<b>w64-mingw32</b> should be compatible with x86_64-<b>w64-mingw32</b> and arm64ec-<b>pc-windows-msvc</b> should be compatible with x86_64-<b>pc-windows-msvc</b>.
Why should arm64ec-w64-mingw32 be compatible with x86_64-pc-windows-msvc? The C++ ABI has never been compatible at all. And if people want to be compatible with MSVC, why don't they build for arm64ec-pc-windows instead?
---
Sorry but it could be lengthy to comment on every paragraph of your input. I think it's better to first persuade users of x87 long double to stop using it, before we start discussion about -mlong-double-64.
But if you are building code with an arm64ec mingw target triple, the assumption is that it is binary compatible with x86_64 mingw.
But if you do build for an arm64ec target, the architecture of arm64ec is such that you can mix and match arm64ec and x86_64 object files as you wish, even within one single DLL.
If you can build for arm64ec from source code, it’s best to build everything as arm64ec for best performance, rather than some as arm64ec and others as x86-64 and then linking together. So I think in-DLL long double compatibility isn't very meaningful.
This doesn't have anything to do with the matter at hand. Yes if you can rebuild everything for aarch64, that's great. But you may also wish to load a binary x86_64 plugin DLL, or you may wish to provide an arm64ec plugin to a host x86_64 executable, etc.
This situation generally happens when you need to interface with modules you cannot control for some reason (usually because they are proprietary) and in such cases, you can generally assume they were compiled with MSVC, so, long double is f64: If it can be compiled with MinGW, it’s hard to imagine why it couldn’t be ported to aarch64.
This PR does not create a new consistency issue. There is no implied compatibility across arm64ec mingw vs msvc as things stand.
As you said, Interop between MSVC and mingw works across DLL boundaries, with C-only APIs.
So, long double compatibility between MinGW and MSVC is a practical issue.
I don't want to repeat myself over and over. That's just what has happened, and people will continue to use 80-bit long double on x86-64, because they sometimes find it useful.
If they actually depend on this, then they are unable to support MSVC and non-x86, unless there is some emulation solution, in which case, it's not a problem.
In my experience, long double either comes from long double routines from the standard library (e.g stdio or math) or used as the largest type supported on the current platform with no assumption about the precision.
Also hey look, Microsoft also decided to preserve x87 state during a context switch, even it's completely unused by MSVC for AMD64 since the beginning, so x87 is always there, and working somehow.
This is clearly not kept for C/C++ users.
Just because the x87 state is preserved doesn't mean using it is encouraged.
I think your question is beyond the scope of this PR. It is about how to make ARM64EC compatible with current x86-64; it's not about how people should adopt -mlong-double-64 when compiling their code for x86-64.
I think I said arm64ec-w64-mingw32 should be compatible with x86_64-w64-mingw32 and arm64ec-pc-windows-msvc should be compatible with x86_64-pc-windows-msvc.
> Why should arm64ec-w64-mingw32 be compatible with x86_64-pc-windows-msvc? The C++ ABI has never been compatible at all.
"Interop between MSVC and mingw works across DLL boundaries, with C-only APIs."
And if people want to be compatible with MSVC, why don't they build for arm64ec-pc-windows instead?
This is another question: People indeed can, and that's exactly what they're doing. People use arm64ec almost exclusively as a workaround for compatibility with proprietary code compiled with MSVC.
Also, ClangIR is built by default now, and -fclangir will eventually become the default. When that happens, you’ll need to reimplement these things in ClangIR. Or, maybe ClangIR team is willing to do the porting work themselves?
For the Clang Area Team, should “reject this PR and let MinGW set -mlong-double-64 as the default on x86-64 to address the issue this PR is trying to address” be considered as an alternative when evaluating maintenance costs?
I think the question is: Is the long double compatibility issue with arm64ec important enough?
1. If this is a correctness issue that must be fixed, and the Clang Area Team considers the maintenance costs acceptable, then this PR should be merged.
2. If this is a correctness issue that must be fixed, and the Clang Area Team considers the maintenance costs unacceptable, then this PR should be rejected and -mlong-double-64 should be the default for MinGW.
3. If this is a known but minor issue, and the Clang Area Team considers the maintenance costs acceptable, then this PR should be merged as a compatibility option disabled by default.
4. If this is a known but minor issue, and the Clang Area Team considers the maintenance costs unacceptable, then this PR should be rejected and the current state should be maintained.
Personally, I still believe since the use case for arm64ec is compatibility with MSVC (DLL), so only option 2 or 4 is acceptable.
There's another option: Leave long double as a true floating-point type and implement it with software in AArch64 backend.
I'm very concerned about maintaining the soft-float codegen. It's complicated in a way that's hard to maintain: it's duplicating a bunch of code and adding a bunch of checks that are only used in extremely obscure circumstances. And arithmetic is rounded in a weird way. I don't think we want to do this.
If you wanted to add an option that enables AST support and errors out if someone actually tries to use it, like we do with vectorcall, I think I'd be okay with that.
I think I should delete the vector and matrix part in this change. Clang doesn't use compatible layout for vectors of long doubles. This isn't a new issue; it's already very different for x86_64 on Linux. Thus there's likely no code which uses vectors of long doubles.
GCC layout for typedef V long double __attribute__((__vector_size__(32))):
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
v v v v v v v v v v . . . . . . v v v v v v v v v v . . . . . .
\__________ elem[0] _________/\____ padding ___/\__________ elem[1] _________/\____ padding ___/
Clang layout:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
v v v v v v v v v v v v v v v v v v v v . . . . . . . . . . . .
\__________ elem[0] _________/\__________ elem[1] _________/\_____________ padding ____________/
Yes this PR is complicated and includes many pieces of changes scattering around here and there. I'm switching my plan to implement x87 long double in the ARm64EC backend. Once that is done, I'll file another PR.
<details>
<summary>My current change set to Clang seems minimal:</summary>
diff --git a/clang/lib/Basic/Targets/AArch64.cpp b/clang/lib/Basic/Targets/AArch64.cpp
index 7ddf9d87ad16..01da8b879df0 100644
--- a/clang/lib/Basic/Targets/AArch64.cpp
+++ b/clang/lib/Basic/Targets/AArch64.cpp
@@ -206,6 +206,10 @@ AArch64TargetInfo::AArch64TargetInfo(const llvm::Triple &Triple,
this->MCountName = "\01_mcount";
else if (Triple.getOS() == llvm::Triple::UnknownOS)
this->MCountName = Triple.isGNUEnvironment() ? "\01_mcount" : "mcount";
+
+ // This should be compatible with x86-64.
+ if (Triple.isWindowsArm64EC() && !Triple.isWindowsMSVCEnvironment())
+ HasFloat128 = true;
}
StringRef AArch64TargetInfo::getABI() const { return ABI; }
@@ -450,6 +454,11 @@ void AArch64TargetInfo::getTargetDefines(const LangOptions &Opts,
if (T.isLFI())
Builder.defineMacro("__LFI__");
+ if (HasFloat128) {
+ Builder.defineMacro("__FLOAT128__");
+ Builder.defineMacro("__SIZEOF_FLOAT128__", "16");
+ }
+
// Inline assembly supports AArch64 flag outputs.
Builder.defineMacro("__GCC_ASM_FLAG_OUTPUTS__");
@@ -1831,6 +1840,14 @@ WindowsARM64TargetInfo::WindowsARM64TargetInfo(const llvm::Triple &Triple,
SizeType = UnsignedLongLong;
PtrDiffType = SignedLongLong;
IntPtrType = SignedLongLong;
+
+ if (Triple.isWindowsArm64EC() && !Triple.isWindowsMSVCEnvironment()) {
+ // arm64ec-w64-mingw32 should be interoperable with x86_64-w64-mingw32,
+ // which by default has `long double` as the x87-specific extended
+ // precision format.
+ LongDoubleWidth = LongDoubleAlign = SuitableAlign = 128;
+ LongDoubleFormat = &llvm::APFloat::x87DoubleExtended();
+ }
}
TargetInfo::BuiltinVaListKind
diff --git a/clang/lib/CodeGen/Targets/AArch64.cpp b/clang/lib/CodeGen/Targets/AArch64.cpp
index e493f717af58..1003a0fd7c84 100644
--- a/clang/lib/CodeGen/Targets/AArch64.cpp
+++ b/clang/lib/CodeGen/Targets/AArch64.cpp
@@ -383,6 +383,13 @@ ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty, bool IsVariadicFn,
Ty, IsNamedArg);
}
+ // ARM64EC supports the x87 `long double` type, which is passed as a 128-bit
+ // integer image.
+ if (getTarget().getTriple().isWindowsArm64EC() &&
+ Ty->isSpecificBuiltinType(BuiltinType::LongDouble) &&
+ &getTarget().getLongDoubleFormat() == &llvm::APFloat::x87DoubleExtended())
+ return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 128));
+
// Handle illegal vector types here.
if (isIllegalVectorType(Ty))
return coerceIllegalVector(Ty, NSRN, NPRN);
@@ -557,6 +564,13 @@ ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy,
if (RetTy->isVoidType())
return ABIArgInfo::getIgnore();
+ // ARM64EC supports the x87 `long double` type, which is returned as a
+ // 128-bit integer image.
+ if (getTarget().getTriple().isWindowsArm64EC() &&
+ RetTy->isSpecificBuiltinType(BuiltinType::LongDouble) &&
+ &getTarget().getLongDoubleFormat() == &llvm::APFloat::x87DoubleExtended())
+ return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 128));
+
if (const auto *VT = RetTy->getAs<VectorType>()) {
if (VT->getVectorKind() == VectorKind::SveFixedLengthData ||
VT->getVectorKind() == VectorKind::SveFixedLengthPredicate) {
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp b/clang/lib/Driver/ToolChains/Clang.cpp
index 1bce61d2cfbe..b97e1faf3635 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -6347,6 +6347,9 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA,
else if (TC.getTriple().isPPC() &&
(A->getOption().getID() != options::OPT_mlong_double_80))
A->render(Args, CmdArgs);
+ else if (TC.getTriple().isWindowsArm64EC() &&
+ !TC.getTriple().isWindowsMSVCEnvironment())
+ A->render(Args, CmdArgs);
else
D.Diag(diag::err_drv_unsupported_opt_for_target)
<< A->getAsString(Args) << TripleStr;
</details>
Just push new changes to this PR. Keep creating new PR will only cause more trouble and lose all the previous discussion. That's why I suggested you create a RFC first.
Just push new changes to this PR. Keep creating new PR will only cause more trouble and lose all the previous discussion. That's why I suggested you create a RFC first.
I think I need a force push.
> Just push new changes to this PR. Keep creating new PR will only cause more trouble and lose all the previous discussion. That's why I suggested you create a RFC first.
> I think I need a force push.
Since this PR hasn't actually been reviewed by real humans yet, you are indeed free to do a force push.
OK I will push the changes for Clang first.
The changes now include only:
1. Accept -mlong-double-{64,80,128} for ARM64EC non-MSVC targets (arm64ec-w64-mingw32-gnu is the only one at the moment).
2. Allow -mlong-double-128 (for softmath).
3. Make default long double for this target the same as x86-64.
4. Add ABI for arguments and return values; same as int128.
5. Recycle all tests in the old changes. The frontend now uses x86_fp80 instead of i128.
I am going to be pretty strongly against trying to generate code for fp80 in the AArch64 backend. We should be trying to remove use of that type, not adding the difficulties of needing to support and maintain it.
I am going to be pretty strongly against trying to generate code for fp80 in the AArch64 backend. We should be trying to remove use of that type, not adding the difficulties of needing to support and maintain it.
The code in the backend is very simple; it's currently a placeholder so we just need to register it. It's softmath so there's no code to generate. The complexity will be in compiler-rt, for those softmath routines.
The backend currently assumes that the sign bit is the MSB of the softened type, so there's gonna be a little change.
All tests now pass (clang LIT, mingw-w64 CRT, libcxx), except checks for precision \[and those don't pass on main\]. This PR should be complete.
I'll have to spend some time on polishing the remaining changes from the AI, and file PRs for individual parts.
@Andarwinux Should I push changes for the llvm subdirectory to this PR?
@Andarwinux Should I push changes for the llvm subdirectory to this PR?
I think it should be fine.
The changes to ARM64EC backend have been pushed.
This effects a change to an x86-32 test: The 10-byte long double is stored in a 12-byte slot, which takes up 2.5 integer registers. Previously, the compiler generated movzx for the last load, to zero out the padding bytes. DAGTypeLegalizer::SoftenFloatRes_BITCAST() now uses DAG.getAnyExtOrTrunc() so the zero-extension is eliminated; the compiler now generates three full-integer loads.
I would hope you wouldn't need to introduce a new place naming these macros
__FLOAT128__ isn't defined for x86-64 so these should be deleted.
Deleted now.
well, __SIZEOF_FLOAT128__ is a target macro so should indeed be defined. (for d86-64 it's defined in X86.cpp.)
This looks like an existing bug? Please split it out if possible.
Do you have a plan to provide implementations of these routines somewhere?
Will do.
These will be implemented in compiler-rt, and will be specific to arm64wc-w64-mingw32, since MSVC doesn't nedd them.
I will first try splitting the ARM64EC ABI issues and platform-neutral softmath changes to separate PRs.
Why don't these functions have the leading #?
lhmouse
[ARM64EC] Implement
-mlong-double-{64,80,128}optionsThis commit implements the three options for arm64ec-w64-mingw32.
-mlong-double-80is made default to fix the interoperability bug with x86_64-w64-mingw32. This also
introduces an ABI break with old ARM64EC binaries.
-mlong-double-64is the old behavior that is compatible with aarch64-w64-mingw32and MSVC.
-mlong-double-128enables float128 in software, same as x86-64.Operations of 80-bit
long doublewill be implemented in the ARM64EC backend. ItsABI, including its calling convention, is the same as a 128-bit structure: For ARM64
code it's passed and returned in an integer register pair; for x86-64 it's passed
and returned in memory. The difference is handled in entry/exit thunks.
Assisted-by: DeepSeek V4.1 Flash