← Back to Pull requests

[ARM64EC] Implement `-mlong-double-{64,80,128}` options #237057

Open
lhmouse opened this pull request with 1940 lines diff across 33 files
View on GitHub
lhmouse lhmouse commented on Oct 30, 2026 02:47 UTC
Author

[ARM64EC] Implement -mlong-double-{64,80,128} options

This commit implements 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 compatible with aarch64-w64-mingw32
and MSVC. -mlong-double-128 enables float128 in software, same as x86-64.

Operations of 80-bit long double will be implemented in the ARM64EC backend. Its
ABI, 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

Diff: 1940 lines (+1859 / -81) across 33 files Reviewer: lhmouse Review duration: 48965m
All Vouch review confidence checks passed
Residual risk 0.21 = Change Risk (0.93) × (1 − Review Confidence (0.78)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.93 · 1940 lines diff across 33 files
0.93
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.89 · 5 substantive comment(s)
0.89
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
77%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.400
Self Review self_review
0.140
Mass File Touch mass_file_touch
0.080
Real PR Conversation Timeline
65 items
llvmorg-github-actions[bot] llvmorg-github-actions[bot] commented on Oct 30, 2026 02:48 UTC
Bot

<!--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:

  • (modified) clang/include/clang/Basic/TargetInfo.h (+6)

  • (modified) clang/lib/Basic/Targets/AArch64.cpp (+17)

  • (modified) clang/lib/Basic/Targets/AArch64.h (+5)

  • (modified) clang/lib/CodeGen/CGBuiltin.cpp (+428)

  • (modified) clang/lib/CodeGen/CGExpr.cpp (+13-2)

  • (modified) clang/lib/CodeGen/CGExprComplex.cpp (+101-6)

  • (modified) clang/lib/CodeGen/CGExprConstant.cpp (+19-8)

  • (modified) clang/lib/CodeGen/CGExprScalar.cpp (+369-14)

  • (modified) clang/lib/CodeGen/CodeGenFunction.h (+17)

  • (modified) clang/lib/CodeGen/CodeGenTypes.cpp (+7)

  • (modified) clang/lib/Driver/ToolChains/Clang.cpp (+3)

  • (added) clang/test/CodeGen/arm64ec-long-double-modes.c (+31)

  • (added) clang/test/CodeGen/arm64ec-soft-x87-long-double.c (+160)

  • (added) clang/test/Driver/arm64ec-long-double.c (+21)
  • ``````

    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>

    lhmouse lhmouse commented on Oct 30, 2026 02:50 UTC
    Author

    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.

    Copilot Copilot commented on code on Oct 30, 2026 02:56 UTC
    Code Review
    clang/lib/CodeGen/CGBuiltin.cpp:1
    @@ -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 = EmitScalarExpr(E->getArg(0));
    +    llvm::Value *Imag = EmitScalarExpr(E->getArg(1));
    +    Result = RValue::getComplex(Real, Imag);
    +    return true;
    +  }
    +
    +  // `conjl`: Conjugation only flips the sign bit of the imaginary part, which
    +  // is the high half of the image pair, and leaves the real part alone.
    +  if (BaseName == "conjl") {
    +    const auto *CTy = E->getArg(0)->getType()->getAs<ComplexType>();
    +    if (!CTy ||
    +        !CTy->getElementType()->isSpecificBuiltinType(BuiltinType::LongDouble))
    +      return false;
    +    ComplexPairTy Z = EmitComplexExpr(E->getArg(0));
    +    llvm::Constant *SignMask = llvm::ConstantInt::get(
    +        Z.second->getType(), llvm::APInt::getOneBitSet(128, 79));
    +    llvm::Value *Imag = Builder.CreateXor(Z.second, SignMask);
    +    Result = RValue::getComplex(Z.first, Imag);
    +    return true;
    +  }
    +
    +  // `creall` and `cimagl`: They only pick the low or the high half of the
    +  // image pair, which is the real or the imaginary part.
    +  if (BaseName == "creall" || BaseName == "cimagl") {
    +    const auto *CTy = E->getArg(0)->getType()->getAs<ComplexType>();
    +    if (!CTy ||
    +        !CTy->getElementType()->isSpecificBuiltinType(BuiltinType::LongDouble))
    +      return false;
    +    ComplexPairTy Z = EmitComplexExpr(E->getArg(0));
    +    Result = RValue::get(BaseName == "creall" ? Z.first : Z.second);
    +    return true;
    +  }
    +
    +  // Everything else is a function of the C library, which on this target works
    +  // on the 80-bit image itself: a `long double` *is* the image, so its own
    +  // entry point takes and returns it untouched, and the builtin is nothing
    +  // but a call to that entry point.  Nothing is evaluated in `double` and
    +  // rounded back, so that not a single bit is lost.  The variadic `printf`
    +  // and `scanf` families go the same way: their ellipsis arguments are
    +  // forwarded untouched, since the x64 calling convention that ARM64EC
    +  // reproduces passes a 16-byte `long double` by reference.
    +
    +  // `powil` is the only one left that has no entry point of that spelling in
    +  // the C library: there is no `powi` function, and `llvm.powi` only accepts
    +  // real floating-point values.  mingw-w64 CRT provides `__powil` for it.
    +  if (Name == "__builtin_powil") {
    +    llvm::Value *X = EmitScalarExpr(E->getArg(0));
    +    llvm::Value *N = EmitScalarExpr(E->getArg(1));
    +    llvm::FunctionType *FT = llvm::FunctionType::get(
    +        ConvertType(E->getType()), {X->getType(), N->getType()}, false);
    +    Result = RValue::get(
    +        Builder.CreateCall(CGM.CreateRuntimeFunction(FT, "__powil"), {X, N}));
    +    return true;
    +  }
    +
    +  // Both spellings arrive here: `__builtin_sinl` and the `sinl` that the
    +  // header declares are separate builtin identifiers, and they resolve to the
    +  // same entry point.
    +  const FunctionDecl *FD = E->getDirectCallee();
    +  if (FD && getContext().BuiltinInfo.isLibFunction(BuiltinID)) {
    +    Result =
    +        emitLibraryCall(*this, FD, E, CGM.getBuiltinLibFunction(FD, BuiltinID));
    +    return true;
    +  }
    +
    +  if (FD && getContext().BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
    +    Result = emitLibraryCall(*this, FD, E, CGM.getRawFunctionPointer(FD));
    +    return true;
    +  }
    +
    +  return false;

    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.

    Copilot Copilot commented on code on Oct 30, 2026 02:56 UTC
    Code Review
    clang/lib/CodeGen/CGExprScalar.cpp:1
    @@ -3561,6 +3664,10 @@ ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
         llvm::Value *amt;
         CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E);
     
    +    if (CGF.getTarget().hasSoftX87LongDouble() &&
    +        type->isSpecificBuiltinType(BuiltinType::LongDouble))
    +      value = CGF.EmitX87LongDoubleToDouble(value, E->getExprLoc());

    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.

    Copilot Copilot commented on code on Oct 30, 2026 02:56 UTC
    Code Review
    clang/lib/CodeGen/CodeGenTypes.cpp:1
    @@ -477,6 +477,13 @@ llvm::Type *CodeGenTypes::ConvertType(QualType T) {
           break;
         case BuiltinType::LongDouble:
           LongDoubleReferenced = true;
    +      if (getTarget().hasSoftX87LongDouble()) {
    +        // For ARM64EC, the software x87 `long double` is an integer image
    +        // of the value in a 16-byte slot.  All computation goes through
    +        // `double` via runtime helper calls.
    +        ResultType = llvm::IntegerType::get(getLLVMContext(), 128);

    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.

    Copilot Copilot commented on code on Oct 30, 2026 02:56 UTC
    Code Review
    clang/lib/CodeGen/CGBuiltin.cpp:1
    @@ -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));

    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.

    Copilot Copilot commented on code on Oct 30, 2026 02:56 UTC
    Code Review
    clang/lib/CodeGen/CGBuiltin.cpp:1
    @@ -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;

    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.

    Copilot Copilot commented on code on Oct 30, 2026 02:56 UTC
    Code Review
    clang/lib/CodeGen/CGExprScalar.cpp:1
    @@ -985,10 +1017,23 @@ class ScalarExprEmitter
       Value *EmitCompare(const BinaryOperator *E, llvm::CmpInst::Predicate UICmpOpc,
                          llvm::CmpInst::Predicate SICmpOpc,
                          llvm::CmpInst::Predicate FCmpOpc, bool IsSignaling);
    -#define VISITCOMP(CODE, UI, SI, FP, SIG) \
    -    Value *VisitBin##CODE(const BinaryOperator *E) { \
    -      return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
    -                         llvm::FCmpInst::FP, SIG); }
    +  Value *EmitSoftX87LongDoubleComp(const BinaryOperator *E,
    +                                   llvm::CmpInst::Predicate FCmpOpc);
    +  Value *EmitSoftX87LongDoubleBinOp(
    +      const BinOpInfo &Ops,
    +      Value *(ScalarExprEmitter::*Emit)(const BinOpInfo &));
    +#define VISITCOMP(CODE, UI, SI, FP, SIG)                                       \
    +  Value *VisitBin##CODE(const BinaryOperator *E) {                             \
    +    if (CGF.getTarget().hasSoftX87LongDouble() &&                              \
    +        E->getLHS()->getType()->isSpecificBuiltinType(                         \
    +            BuiltinType::LongDouble) &&                                        \
    +        E->getRHS()->getType()->isSpecificBuiltinType(                         \
    +            BuiltinType::LongDouble))                                          \
    +      return EmitSoftX87LongDoubleComp(E, llvm::FCmpInst::FP);                 \

    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.

    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on Oct 30, 2026 02:56 UTC
    Reviewer

    <!-- 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>

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> Prevent invalid i128 floating-point intrinsic emission · New

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> Route atomic long double increments through fallback lowering · New

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> Prevent integer lowering of long double vector arithmetic · New

  • <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> Clear long double padding bits in classification predicates · New

  • <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> Preserve long double NaN payloads and dynamic tags · New

  • <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> Preserve signaling NaN exceptions in floating-point comparisons · New

  • </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:

  • Accepts -mlong-double-{64,80,128} and configures target formats.

  • Represents software x87 values as i128, with image-based operations, double-based arithmetic, and runtime calls.

  • Adds driver and LLVM IR tests for format selection and software x87 lowering.
  • | 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>

    lhmouse lhmouse commented on code on Oct 30, 2026 03:08 UTC
    Code Review
    clang/lib/CodeGen/CGBuiltin.cpp:1
    @@ -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));

    Fixed in 29da274f4cd33a80e943a3f0316fc5ecda624e7e.

    lhmouse lhmouse commented on code on Oct 30, 2026 03:11 UTC
    Code Review
    clang/lib/CodeGen/CGExprScalar.cpp:1
    @@ -985,10 +1017,23 @@ class ScalarExprEmitter
       Value *EmitCompare(const BinaryOperator *E, llvm::CmpInst::Predicate UICmpOpc,
                          llvm::CmpInst::Predicate SICmpOpc,
                          llvm::CmpInst::Predicate FCmpOpc, bool IsSignaling);
    -#define VISITCOMP(CODE, UI, SI, FP, SIG) \
    -    Value *VisitBin##CODE(const BinaryOperator *E) { \
    -      return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
    -                         llvm::FCmpInst::FP, SIG); }
    +  Value *EmitSoftX87LongDoubleComp(const BinaryOperator *E,
    +                                   llvm::CmpInst::Predicate FCmpOpc);
    +  Value *EmitSoftX87LongDoubleBinOp(
    +      const BinOpInfo &Ops,
    +      Value *(ScalarExprEmitter::*Emit)(const BinOpInfo &));
    +#define VISITCOMP(CODE, UI, SI, FP, SIG)                                       \
    +  Value *VisitBin##CODE(const BinaryOperator *E) {                             \
    +    if (CGF.getTarget().hasSoftX87LongDouble() &&                              \
    +        E->getLHS()->getType()->isSpecificBuiltinType(                         \
    +            BuiltinType::LongDouble) &&                                        \
    +        E->getRHS()->getType()->isSpecificBuiltinType(                         \
    +            BuiltinType::LongDouble))                                          \
    +      return EmitSoftX87LongDoubleComp(E, llvm::FCmpInst::FP);                 \

    This is not a strict FP implementation, so WONTFIX.

    lhmouse lhmouse commented on code on Oct 30, 2026 03:29 UTC
    Code Review
    clang/lib/CodeGen/CGBuiltin.cpp:1
    @@ -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;

    Fixed in e618dc3475b726caf96763d41bc629217783ba6a

    lhmouse lhmouse commented on code on Oct 30, 2026 04:51 UTC
    Code Review
    clang/lib/CodeGen/CodeGenTypes.cpp:1
    @@ -477,6 +477,13 @@ llvm::Type *CodeGenTypes::ConvertType(QualType T) {
           break;
         case BuiltinType::LongDouble:
           LongDoubleReferenced = true;
    +      if (getTarget().hasSoftX87LongDouble()) {
    +        // For ARM64EC, the software x87 `long double` is an integer image
    +        // of the value in a 16-byte slot.  All computation goes through
    +        // `double` via runtime helper calls.
    +        ResultType = llvm::IntegerType::get(getLLVMContext(), 128);

    Added software lowering in 13466c8a8f6943a19f971c9809e6b8f7a5b4583f

    lhmouse lhmouse commented on code on Oct 30, 2026 04:57 UTC
    Code Review
    clang/lib/CodeGen/CGExprScalar.cpp:1
    @@ -3561,6 +3664,10 @@ ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
         llvm::Value *amt;
         CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E);
     
    +    if (CGF.getTarget().hasSoftX87LongDouble() &&
    +        type->isSpecificBuiltinType(BuiltinType::LongDouble))
    +      value = CGF.EmitX87LongDoubleToDouble(value, E->getExprLoc());

    Fixed in d0ff68c1c119112d9b3e0ee5e551d2c67c0e1276

    lhmouse lhmouse commented on code on Oct 30, 2026 05:06 UTC
    Code Review
    clang/lib/CodeGen/CGBuiltin.cpp:1
    @@ -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 = EmitScalarExpr(E->getArg(0));
    +    llvm::Value *Imag = EmitScalarExpr(E->getArg(1));
    +    Result = RValue::getComplex(Real, Imag);
    +    return true;
    +  }
    +
    +  // `conjl`: Conjugation only flips the sign bit of the imaginary part, which
    +  // is the high half of the image pair, and leaves the real part alone.
    +  if (BaseName == "conjl") {
    +    const auto *CTy = E->getArg(0)->getType()->getAs<ComplexType>();
    +    if (!CTy ||
    +        !CTy->getElementType()->isSpecificBuiltinType(BuiltinType::LongDouble))
    +      return false;
    +    ComplexPairTy Z = EmitComplexExpr(E->getArg(0));
    +    llvm::Constant *SignMask = llvm::ConstantInt::get(
    +        Z.second->getType(), llvm::APInt::getOneBitSet(128, 79));
    +    llvm::Value *Imag = Builder.CreateXor(Z.second, SignMask);
    +    Result = RValue::getComplex(Z.first, Imag);
    +    return true;
    +  }
    +
    +  // `creall` and `cimagl`: They only pick the low or the high half of the
    +  // image pair, which is the real or the imaginary part.
    +  if (BaseName == "creall" || BaseName == "cimagl") {
    +    const auto *CTy = E->getArg(0)->getType()->getAs<ComplexType>();
    +    if (!CTy ||
    +        !CTy->getElementType()->isSpecificBuiltinType(BuiltinType::LongDouble))
    +      return false;
    +    ComplexPairTy Z = EmitComplexExpr(E->getArg(0));
    +    Result = RValue::get(BaseName == "creall" ? Z.first : Z.second);
    +    return true;
    +  }
    +
    +  // Everything else is a function of the C library, which on this target works
    +  // on the 80-bit image itself: a `long double` *is* the image, so its own
    +  // entry point takes and returns it untouched, and the builtin is nothing
    +  // but a call to that entry point.  Nothing is evaluated in `double` and
    +  // rounded back, so that not a single bit is lost.  The variadic `printf`
    +  // and `scanf` families go the same way: their ellipsis arguments are
    +  // forwarded untouched, since the x64 calling convention that ARM64EC
    +  // reproduces passes a 16-byte `long double` by reference.
    +
    +  // `powil` is the only one left that has no entry point of that spelling in
    +  // the C library: there is no `powi` function, and `llvm.powi` only accepts
    +  // real floating-point values.  mingw-w64 CRT provides `__powil` for it.
    +  if (Name == "__builtin_powil") {
    +    llvm::Value *X = EmitScalarExpr(E->getArg(0));
    +    llvm::Value *N = EmitScalarExpr(E->getArg(1));
    +    llvm::FunctionType *FT = llvm::FunctionType::get(
    +        ConvertType(E->getType()), {X->getType(), N->getType()}, false);
    +    Result = RValue::get(
    +        Builder.CreateCall(CGM.CreateRuntimeFunction(FT, "__powil"), {X, N}));
    +    return true;
    +  }
    +
    +  // Both spellings arrive here: `__builtin_sinl` and the `sinl` that the
    +  // header declares are separate builtin identifiers, and they resolve to the
    +  // same entry point.
    +  const FunctionDecl *FD = E->getDirectCallee();
    +  if (FD && getContext().BuiltinInfo.isLibFunction(BuiltinID)) {
    +    Result =
    +        emitLibraryCall(*this, FD, E, CGM.getBuiltinLibFunction(FD, BuiltinID));
    +    return true;
    +  }
    +
    +  if (FD && getContext().BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
    +    Result = emitLibraryCall(*this, FD, E, CGM.getRawFunctionPointer(FD));
    +    return true;
    +  }
    +
    +  return false;

    Add in 295fe6ac475e3b80ddcbbf2281f8984fcd052f67

    Copilot Copilot commented on code on Oct 30, 2026 05:17 UTC
    Code Review
    clang/lib/CodeGen/CGBuiltin.cpp:1
    @@ -2714,12 +2714,481 @@ 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` and `__builtin_elementwise_abs` both set the sign bit to zero.
    +  // The latter has no library spelling, so it is matched by its full name; a
    +  // vector operand is rejected before it gets here.
    +  if (BaseName == "fabsl" || Name == "__builtin_elementwise_abs") {
    +    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` and `__builtin_elementwise_copysign` both take the magnitude
    +  // from the first operand and the sign bit from the second one.  The latter
    +  // has no library spelling, so it is matched by its full name.
    +  if (BaseName == "copysignl" || Name == "__builtin_elementwise_copysign") {
    +    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;
    +  }
    +
    +  // `__builtin_canonicalizel`: Clear the padding bits and give a pseudo
    +  // denormal, that is, a zero exponent with the integer bit set, the exponent
    +  // one that spells the same number in the normal form.  This is what the x87
    +  // does with an image that is loaded and stored again.
    +  if (Name == "__builtin_canonicalizel") {
    +    if (!E->getType()->isSpecificBuiltinType(BuiltinType::LongDouble))
    +      return false;
    +    llvm::Value *V = EmitScalarExpr(E->getArg(0));
    +    llvm::Type *ImageTy = V->getType();
    +    llvm::Constant *Zero = llvm::ConstantInt::get(ImageTy, 0);
    +    llvm::Constant *ExponentMask =
    +        llvm::ConstantInt::get(ImageTy, llvm::APInt(128, 0x7fffull) << 64);
    +    llvm::Constant *IntegerBit =
    +        llvm::ConstantInt::get(ImageTy, llvm::APInt::getOneBitSet(128, 63));
    +    llvm::Constant *ExponentOne =
    +        llvm::ConstantInt::get(ImageTy, llvm::APInt::getOneBitSet(128, 64));
    +    llvm::Constant *ImageMask =
    +        llvm::ConstantInt::get(ImageTy, llvm::APInt::getLowBitsSet(128, 80));
    +    llvm::Value *IsPseudoDenormal = Builder.CreateAnd(
    +        Builder.CreateICmpEQ(Builder.CreateAnd(V, ExponentMask), Zero),
    +        Builder.CreateICmpNE(Builder.CreateAnd(V, IntegerBit), Zero));
    +    llvm::Value *Normalized = Builder.CreateSelect(
    +        IsPseudoDenormal, Builder.CreateOr(V, ExponentOne), V);
    +    Result = RValue::get(Builder.CreateAnd(Normalized, ImageMask));
    +    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::getLowBitsSet(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::getLowBitsSet(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::getLowBitsSet(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::getLowBitsSet(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, and the payload taken from the tag replaces the low bits of that
    +  // significand.  Only the builtin spelling with a string literal is constant
    +  // evaluated; anything else, including every call through the library
    +  // spelling, falls through to the library, which parses the tag at run time.
    +  if (BaseName == "nanl" || BaseName == "nansl") {
    +    Expr::EvalResult Eval;
    +    if (!E->EvaluateAsRValue(Eval, getContext()) || !Eval.Val.isFloat())
    +      return false;
    +    auto *ImageTy = llvm::cast<llvm::IntegerType>(ConvertType(E->getType()));
    +    Result = RValue::get(llvm::ConstantInt::get(
    +        ImageTy, Eval.Val.getFloat().bitcastToAPInt().zextOrTrunc(
    +                     ImageTy->getBitWidth())));
    +    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();

    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.

    Copilot Copilot commented on code on Oct 30, 2026 05:17 UTC
    Code Review
    clang/lib/CodeGen/CGExprScalar.cpp:1
    @@ -70,6 +71,32 @@ extern cl::opt<bool> EnableSingleByteCoverage;
     
     namespace {
     
    +bool isSoftX87LongDoubleVector(const CodeGenFunction &CGF, QualType Ty) {
    +  const auto *VT = Ty->getAs<VectorType>();
    +  return VT && CGF.getTarget().hasSoftX87LongDouble() &&
    +         VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongDouble);
    +}
    +
    +bool isSoftX87LongDoubleOrVector(const CodeGenFunction &CGF, QualType Ty) {
    +  return CGF.getTarget().hasSoftX87LongDouble() &&
    +         (Ty->isSpecificBuiltinType(BuiltinType::LongDouble) ||
    +          isSoftX87LongDoubleVector(CGF, Ty));

    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.

    Copilot Copilot commented on code on Oct 30, 2026 05:17 UTC
    Code Review
    clang/lib/CodeGen/CGExprScalar.cpp:1
    @@ -1674,14 +1791,43 @@ Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
     
       if (DstType->isVoidType()) return nullptr;
     
    -  llvm::Value *OrigSrc = Src;
    -  QualType OrigSrcType = SrcType;
    -  llvm::Type *SrcTy = Src->getType();
    -
       // Handle conversions to bool first, they are special: comparisons against 0.
       if (DstType->isBooleanType())
         return EmitConversionToBool(Src, SrcType);
     
    +  // If either source type is software x87 long double, conversion will have to
    +  // go through an intermediate conversion to double, which seems to match
    +  // x86-64 emulation on ARM64.
    +  if (CGF.getTarget().hasSoftX87LongDouble()) {

    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.

    Copilot Copilot commented on code on Oct 30, 2026 05:17 UTC
    Code Review
    clang/lib/CodeGen/CGBuiltin.cpp:1
    @@ -2714,12 +2714,481 @@ 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` and `__builtin_elementwise_abs` both set the sign bit to zero.
    +  // The latter has no library spelling, so it is matched by its full name; a
    +  // vector operand is rejected before it gets here.
    +  if (BaseName == "fabsl" || Name == "__builtin_elementwise_abs") {
    +    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` and `__builtin_elementwise_copysign` both take the magnitude
    +  // from the first operand and the sign bit from the second one.  The latter
    +  // has no library spelling, so it is matched by its full name.
    +  if (BaseName == "copysignl" || Name == "__builtin_elementwise_copysign") {
    +    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;
    +  }
    +
    +  // `__builtin_canonicalizel`: Clear the padding bits and give a pseudo
    +  // denormal, that is, a zero exponent with the integer bit set, the exponent
    +  // one that spells the same number in the normal form.  This is what the x87
    +  // does with an image that is loaded and stored again.
    +  if (Name == "__builtin_canonicalizel") {
    +    if (!E->getType()->isSpecificBuiltinType(BuiltinType::LongDouble))
    +      return false;
    +    llvm::Value *V = EmitScalarExpr(E->getArg(0));
    +    llvm::Type *ImageTy = V->getType();
    +    llvm::Constant *Zero = llvm::ConstantInt::get(ImageTy, 0);
    +    llvm::Constant *ExponentMask =
    +        llvm::ConstantInt::get(ImageTy, llvm::APInt(128, 0x7fffull) << 64);
    +    llvm::Constant *IntegerBit =
    +        llvm::ConstantInt::get(ImageTy, llvm::APInt::getOneBitSet(128, 63));
    +    llvm::Constant *ExponentOne =
    +        llvm::ConstantInt::get(ImageTy, llvm::APInt::getOneBitSet(128, 64));
    +    llvm::Constant *ImageMask =
    +        llvm::ConstantInt::get(ImageTy, llvm::APInt::getLowBitsSet(128, 80));
    +    llvm::Value *IsPseudoDenormal = Builder.CreateAnd(
    +        Builder.CreateICmpEQ(Builder.CreateAnd(V, ExponentMask), Zero),
    +        Builder.CreateICmpNE(Builder.CreateAnd(V, IntegerBit), Zero));
    +    llvm::Value *Normalized = Builder.CreateSelect(
    +        IsPseudoDenormal, Builder.CreateOr(V, ExponentOne), V);
    +    Result = RValue::get(Builder.CreateAnd(Normalized, ImageMask));

    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.

    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on Oct 30, 2026 05:17 UTC
    Reviewer

    <!-- 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>

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> Classify long-double predicates instead of library fallback calls · New

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> Add matrix-aware long-double operations or diagnose unsupported cases · New

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> Route long-double fixed-point conversions through double · New

  • <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> Quiet signaling NaNs while preserving sign and payload · New

  • </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>

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> Prevent integer lowering of long double vector arithmetic

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> Route atomic long double increments through fallback lowering

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> Prevent invalid i128 floating-point intrinsic emission

  • <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> Preserve signaling NaN exceptions in floating-point comparisons

  • <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> Preserve long double NaN payloads and dynamic tags

  • <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> Clear long double padding bits in classification predicates

  • </details>

    <sub>Review effort: Balanced</sub>

    lhmouse lhmouse commented on code on Oct 30, 2026 05:28 UTC
    Code Review
    clang/lib/CodeGen/CGBuiltin.cpp:1
    @@ -2714,12 +2714,481 @@ 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` and `__builtin_elementwise_abs` both set the sign bit to zero.
    +  // The latter has no library spelling, so it is matched by its full name; a
    +  // vector operand is rejected before it gets here.
    +  if (BaseName == "fabsl" || Name == "__builtin_elementwise_abs") {
    +    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` and `__builtin_elementwise_copysign` both take the magnitude
    +  // from the first operand and the sign bit from the second one.  The latter
    +  // has no library spelling, so it is matched by its full name.
    +  if (BaseName == "copysignl" || Name == "__builtin_elementwise_copysign") {
    +    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;
    +  }
    +
    +  // `__builtin_canonicalizel`: Clear the padding bits and give a pseudo
    +  // denormal, that is, a zero exponent with the integer bit set, the exponent
    +  // one that spells the same number in the normal form.  This is what the x87
    +  // does with an image that is loaded and stored again.
    +  if (Name == "__builtin_canonicalizel") {
    +    if (!E->getType()->isSpecificBuiltinType(BuiltinType::LongDouble))
    +      return false;
    +    llvm::Value *V = EmitScalarExpr(E->getArg(0));
    +    llvm::Type *ImageTy = V->getType();
    +    llvm::Constant *Zero = llvm::ConstantInt::get(ImageTy, 0);
    +    llvm::Constant *ExponentMask =
    +        llvm::ConstantInt::get(ImageTy, llvm::APInt(128, 0x7fffull) << 64);
    +    llvm::Constant *IntegerBit =
    +        llvm::ConstantInt::get(ImageTy, llvm::APInt::getOneBitSet(128, 63));
    +    llvm::Constant *ExponentOne =
    +        llvm::ConstantInt::get(ImageTy, llvm::APInt::getOneBitSet(128, 64));
    +    llvm::Constant *ImageMask =
    +        llvm::ConstantInt::get(ImageTy, llvm::APInt::getLowBitsSet(128, 80));
    +    llvm::Value *IsPseudoDenormal = Builder.CreateAnd(
    +        Builder.CreateICmpEQ(Builder.CreateAnd(V, ExponentMask), Zero),
    +        Builder.CreateICmpNE(Builder.CreateAnd(V, IntegerBit), Zero));
    +    llvm::Value *Normalized = Builder.CreateSelect(
    +        IsPseudoDenormal, Builder.CreateOr(V, ExponentOne), V);
    +    Result = RValue::get(Builder.CreateAnd(Normalized, ImageMask));
    +    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::getLowBitsSet(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::getLowBitsSet(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::getLowBitsSet(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::getLowBitsSet(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, and the payload taken from the tag replaces the low bits of that
    +  // significand.  Only the builtin spelling with a string literal is constant
    +  // evaluated; anything else, including every call through the library
    +  // spelling, falls through to the library, which parses the tag at run time.
    +  if (BaseName == "nanl" || BaseName == "nansl") {
    +    Expr::EvalResult Eval;
    +    if (!E->EvaluateAsRValue(Eval, getContext()) || !Eval.Val.isFloat())
    +      return false;
    +    auto *ImageTy = llvm::cast<llvm::IntegerType>(ConvertType(E->getType()));
    +    Result = RValue::get(llvm::ConstantInt::get(
    +        ImageTy, Eval.Val.getFloat().bitcastToAPInt().zextOrTrunc(
    +                     ImageTy->getBitWidth())));
    +    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();

    Fixed in 974c9f4e523ac3c11b6a033da02ca89f1d195d31

    lhmouse lhmouse commented on code on Oct 30, 2026 05:49 UTC
    Code Review
    clang/lib/CodeGen/CGExprScalar.cpp:1
    @@ -1674,14 +1791,43 @@ Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
     
       if (DstType->isVoidType()) return nullptr;
     
    -  llvm::Value *OrigSrc = Src;
    -  QualType OrigSrcType = SrcType;
    -  llvm::Type *SrcTy = Src->getType();
    -
       // Handle conversions to bool first, they are special: comparisons against 0.
       if (DstType->isBooleanType())
         return EmitConversionToBool(Src, SrcType);
     
    +  // If either source type is software x87 long double, conversion will have to
    +  // go through an intermediate conversion to double, which seems to match
    +  // x86-64 emulation on ARM64.
    +  if (CGF.getTarget().hasSoftX87LongDouble()) {

    Fixed in 74319fcfa1a1c5d6e8f400a3f522b8a330db0441

    lhmouse lhmouse commented on code on Oct 30, 2026 05:58 UTC
    Code Review
    clang/lib/CodeGen/CGBuiltin.cpp:1
    @@ -2714,12 +2714,481 @@ 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` and `__builtin_elementwise_abs` both set the sign bit to zero.
    +  // The latter has no library spelling, so it is matched by its full name; a
    +  // vector operand is rejected before it gets here.
    +  if (BaseName == "fabsl" || Name == "__builtin_elementwise_abs") {
    +    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` and `__builtin_elementwise_copysign` both take the magnitude
    +  // from the first operand and the sign bit from the second one.  The latter
    +  // has no library spelling, so it is matched by its full name.
    +  if (BaseName == "copysignl" || Name == "__builtin_elementwise_copysign") {
    +    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;
    +  }
    +
    +  // `__builtin_canonicalizel`: Clear the padding bits and give a pseudo
    +  // denormal, that is, a zero exponent with the integer bit set, the exponent
    +  // one that spells the same number in the normal form.  This is what the x87
    +  // does with an image that is loaded and stored again.
    +  if (Name == "__builtin_canonicalizel") {
    +    if (!E->getType()->isSpecificBuiltinType(BuiltinType::LongDouble))
    +      return false;
    +    llvm::Value *V = EmitScalarExpr(E->getArg(0));
    +    llvm::Type *ImageTy = V->getType();
    +    llvm::Constant *Zero = llvm::ConstantInt::get(ImageTy, 0);
    +    llvm::Constant *ExponentMask =
    +        llvm::ConstantInt::get(ImageTy, llvm::APInt(128, 0x7fffull) << 64);
    +    llvm::Constant *IntegerBit =
    +        llvm::ConstantInt::get(ImageTy, llvm::APInt::getOneBitSet(128, 63));
    +    llvm::Constant *ExponentOne =
    +        llvm::ConstantInt::get(ImageTy, llvm::APInt::getOneBitSet(128, 64));
    +    llvm::Constant *ImageMask =
    +        llvm::ConstantInt::get(ImageTy, llvm::APInt::getLowBitsSet(128, 80));
    +    llvm::Value *IsPseudoDenormal = Builder.CreateAnd(
    +        Builder.CreateICmpEQ(Builder.CreateAnd(V, ExponentMask), Zero),
    +        Builder.CreateICmpNE(Builder.CreateAnd(V, IntegerBit), Zero));
    +    llvm::Value *Normalized = Builder.CreateSelect(
    +        IsPseudoDenormal, Builder.CreateOr(V, ExponentOne), V);
    +    Result = RValue::get(Builder.CreateAnd(Normalized, ImageMask));

    Fixed 1d0485c3f9b57283c69d201bf568f508617163e1. Also verified on x86-physical 64 that the behavior matches.

    lhmouse lhmouse commented on code on Oct 30, 2026 06:24 UTC
    Code Review
    clang/lib/CodeGen/CGExprScalar.cpp:1
    @@ -70,6 +71,32 @@ extern cl::opt<bool> EnableSingleByteCoverage;
     
     namespace {
     
    +bool isSoftX87LongDoubleVector(const CodeGenFunction &CGF, QualType Ty) {
    +  const auto *VT = Ty->getAs<VectorType>();
    +  return VT && CGF.getTarget().hasSoftX87LongDouble() &&
    +         VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongDouble);
    +}
    +
    +bool isSoftX87LongDoubleOrVector(const CodeGenFunction &CGF, QualType Ty) {
    +  return CGF.getTarget().hasSoftX87LongDouble() &&
    +         (Ty->isSpecificBuiltinType(BuiltinType::LongDouble) ||
    +          isSoftX87LongDoubleVector(CGF, Ty));

    Fixed in 3a6e894c4949cab0c01728872d17f5f616c1d98e

    lhmouse lhmouse commented on Oct 30, 2026 06:26 UTC
    Author

    Re-running libcxx and mingw-w64 tests now.

    Andarwinux Andarwinux commented on Oct 30, 2026 07:49 UTC
    Contributor

    -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.

    mstorsjo mstorsjo commented on Oct 30, 2026 08:10 UTC
    Contributor

    > -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.

    lhmouse lhmouse commented on Oct 30, 2026 08:18 UTC
    Author

    > -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.

    lhmouse lhmouse commented on Oct 30, 2026 08:21 UTC
    Author

    @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.

    mstorsjo mstorsjo commented on Oct 30, 2026 08:24 UTC
    Contributor

    > 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?

    lhmouse lhmouse commented on Oct 30, 2026 08:26 UTC
    Author

    > > 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?

    I haven't tested it yet. I have read all changes and I think it won't be affected, but I'll test it.

    mstorsjo mstorsjo commented on Oct 30, 2026 08:27 UTC
    Contributor

    > 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?

    > 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.

    lhmouse lhmouse commented on Oct 30, 2026 08:40 UTC
    Author

    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.

    lhmouse lhmouse commented on Oct 30, 2026 10:56 UTC
    Author

    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>

    Andarwinux Andarwinux commented on Oct 30, 2026 11:08 UTC
    Contributor

    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!

  • The major historical mistake

  • long double interoperability between {x86_64,arm64ec,aarch64}-{mingw32,msvc}
  • 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. |

    mstorsjo mstorsjo commented on Oct 30, 2026 11:51 UTC
    Contributor

    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.

    lhmouse lhmouse commented on Oct 30, 2026 12:11 UTC
    Author

    > 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.

    Andarwinux Andarwinux commented on Oct 30, 2026 15:38 UTC
    Contributor

    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.

  • If f80 become the default long double for arm64ec MinGW, users who are unable to build their own toolchains will lose the ability to use llvm-mingw to build arm64ec code compatible with proprietary MSVC DLLs. And this is the primary use case for arm64ec.

  • Then this PR resulted in significant maintenance costs for Clang with only a niche use case.
  • 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.

    lhmouse lhmouse commented on Oct 30, 2026 16:01 UTC
    Author

    There's another option: Leave long double as a true floating-point type and implement it with software in AArch64 backend.

    efriedma-quic efriedma-quic commented on Oct 30, 2026 16:30 UTC
    Reviewer

    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.

    lhmouse lhmouse commented on Oct 31, 2026 06:18 UTC
    Author

    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 ____________/
    

    lhmouse lhmouse commented on Oct 31, 2026 08:07 UTC
    Author

    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>

    Andarwinux Andarwinux commented on Oct 31, 2026 08:45 UTC
    Contributor

    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.

    lhmouse lhmouse commented on Oct 31, 2026 09:54 UTC
    Author

    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.

    Andarwinux Andarwinux commented on Oct 31, 2026 10:02 UTC
    Contributor

    > 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.

    lhmouse lhmouse commented on Oct 31, 2026 10:03 UTC
    Author

    OK I will push the changes for Clang first.

    lhmouse lhmouse commented on Oct 31, 2026 10:21 UTC
    Author

    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.

    davemgreen davemgreen commented on Oct 31, 2026 15:11 UTC
    Reviewer

    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.

    lhmouse lhmouse commented on Oct 31, 2026 15:18 UTC
    Author

    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.

    lhmouse lhmouse commented on Oct 31, 2026 18:56 UTC
    Author

    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.

    lhmouse lhmouse commented on Nov 01, 2026 13:52 UTC
    Author

    @Andarwinux Should I push changes for the llvm subdirectory to this PR?

    Andarwinux Andarwinux commented on Nov 01, 2026 14:03 UTC
    Contributor

    @Andarwinux Should I push changes for the llvm subdirectory to this PR?

    I think it should be fine.

    lhmouse lhmouse commented on Nov 01, 2026 19:33 UTC
    Author

    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.

    arsenm arsenm commented on code on Nov 01, 2026 19:44 UTC
    Code Review
    clang/lib/Basic/Targets/AArch64.cpp:1
    @@ -450,6 +454,11 @@ void AArch64TargetInfo::getTargetDefines(const LangOptions &Opts,
       if (T.isLFI())
         Builder.defineMacro("__LFI__");
     
    +  if (HasFloat128) {

    I would hope you wouldn't need to introduce a new place naming these macros

    lhmouse lhmouse commented on code on Nov 01, 2026 20:03 UTC
    Code Review
    clang/lib/Basic/Targets/AArch64.cpp:1
    @@ -450,6 +454,11 @@ void AArch64TargetInfo::getTargetDefines(const LangOptions &Opts,
       if (T.isLFI())
         Builder.defineMacro("__LFI__");
     
    +  if (HasFloat128) {

    __FLOAT128__ isn't defined for x86-64 so these should be deleted.

    lhmouse lhmouse commented on code on Nov 01, 2026 20:09 UTC
    Code Review
    clang/lib/Basic/Targets/AArch64.cpp:1
    @@ -450,6 +454,11 @@ void AArch64TargetInfo::getTargetDefines(const LangOptions &Opts,
       if (T.isLFI())
         Builder.defineMacro("__LFI__");
     
    +  if (HasFloat128) {

    Deleted now.

    lhmouse lhmouse commented on code on Nov 01, 2026 20:21 UTC
    Code Review
    clang/lib/Basic/Targets/AArch64.cpp:1
    @@ -450,6 +454,11 @@ void AArch64TargetInfo::getTargetDefines(const LangOptions &Opts,
       if (T.isLFI())
         Builder.defineMacro("__LFI__");
     
    +  if (HasFloat128) {

    well, __SIZEOF_FLOAT128__ is a target macro so should indeed be defined. (for d86-64 it's defined in X86.cpp.)

    efriedma-quic efriedma-quic commented on code on Nov 01, 2026 21:51 UTC
    Code Review
    llvm/lib/Target/AArch64/AArch64Arm64ECCallLowering.cpp:1
    @@ -592,16 +603,28 @@ Function *AArch64Arm64ECCallLowering::buildEntryThunk(Function *F) {
       }
     
       if (F->isVarArg()) {
    -    // The 5th argument to variadic entry thunks is used to model the x64 sp
    +    // The last argument to variadic entry thunks is used to model the x64 sp
         // which is passed to the thunk in x4, this can be passed to the callee as
         // the variadic argument start address after skipping over the 32 byte
         // shadow store.
     
         // The EC thunk CC will assign any argument marked as InReg to x4.
    -    Thunk->addParamAttr(5, Attribute::InReg);
    -    Value *Arg = Thunk->getArg(5);
    -    Arg = IRB.CreatePtrAdd(Arg, IRB.getInt64(0x20));
    -    Args.push_back(Arg);
    +    Thunk->addParamAttr(Thunk->arg_size() - 1, Attribute::InReg);
    +    Value *StackArgs = Thunk->getArg(Thunk->arg_size() - 1);
    +
    +    // x4 points at the 32 byte shadow store, so the first stack argument is
    +    // 32 bytes further up.  When the hidden return pointer took the first
    +    // integer argument register, the x64 caller can only pass three of the
    +    // four arguments in registers, and the fourth one, which is the first one
    +    // on the stack, fills the last slot of the callee's register save area.
    +    uint64_t StackOffset = 0x20;
    +    if (TransformDirectToSRet) {

    This looks like an existing bug? Please split it out if possible.

    efriedma-quic efriedma-quic commented on code on Nov 01, 2026 21:54 UTC
    Code Review
    llvm/include/llvm/IR/RuntimeLibcalls.td:1
    @@ -2381,11 +2392,104 @@ def AArch64SystemLibrary : SystemRuntimeLibrary<isAArch64_ExceptArm64EC,
       ["compiler-rt", "libatomic", "llvm-client-runtime", "libm", "libc", "unwind",
        "sme"]>;
     
    +//===----------------------------------------------------------------------===//
    +// ARM64EC helpers for the x87 `long double` format
    +//===----------------------------------------------------------------------===//
    +
    +// These are not the exact x87 soft-float helpers of libgcc: The value stays
    +// an 80-bit x87 image in a 16-byte slot, but every operation on it is carried
    +// out in `double`. These are named with an `__arm64ec_` prefix so they will
    +// not be confused with, or silently bound to, an exact implementation of the
    +// same format.

    Do you have a plan to provide implementations of these routines somewhere?

    lhmouse lhmouse commented on code on Nov 02, 2026 02:04 UTC
    Code Review
    llvm/lib/Target/AArch64/AArch64Arm64ECCallLowering.cpp:1
    @@ -592,16 +603,28 @@ Function *AArch64Arm64ECCallLowering::buildEntryThunk(Function *F) {
       }
     
       if (F->isVarArg()) {
    -    // The 5th argument to variadic entry thunks is used to model the x64 sp
    +    // The last argument to variadic entry thunks is used to model the x64 sp
         // which is passed to the thunk in x4, this can be passed to the callee as
         // the variadic argument start address after skipping over the 32 byte
         // shadow store.
     
         // The EC thunk CC will assign any argument marked as InReg to x4.
    -    Thunk->addParamAttr(5, Attribute::InReg);
    -    Value *Arg = Thunk->getArg(5);
    -    Arg = IRB.CreatePtrAdd(Arg, IRB.getInt64(0x20));
    -    Args.push_back(Arg);
    +    Thunk->addParamAttr(Thunk->arg_size() - 1, Attribute::InReg);
    +    Value *StackArgs = Thunk->getArg(Thunk->arg_size() - 1);
    +
    +    // x4 points at the 32 byte shadow store, so the first stack argument is
    +    // 32 bytes further up.  When the hidden return pointer took the first
    +    // integer argument register, the x64 caller can only pass three of the
    +    // four arguments in registers, and the fourth one, which is the first one
    +    // on the stack, fills the last slot of the callee's register save area.
    +    uint64_t StackOffset = 0x20;
    +    if (TransformDirectToSRet) {

    Will do.

    lhmouse lhmouse commented on code on Nov 02, 2026 02:04 UTC
    Code Review
    llvm/include/llvm/IR/RuntimeLibcalls.td:1
    @@ -2381,11 +2392,104 @@ def AArch64SystemLibrary : SystemRuntimeLibrary<isAArch64_ExceptArm64EC,
       ["compiler-rt", "libatomic", "llvm-client-runtime", "libm", "libc", "unwind",
        "sme"]>;
     
    +//===----------------------------------------------------------------------===//
    +// ARM64EC helpers for the x87 `long double` format
    +//===----------------------------------------------------------------------===//
    +
    +// These are not the exact x87 soft-float helpers of libgcc: The value stays
    +// an 80-bit x87 image in a 16-byte slot, but every operation on it is carried
    +// out in `double`. These are named with an `__arm64ec_` prefix so they will
    +// not be confused with, or silently bound to, an exact implementation of the
    +// same format.

    These will be implemented in compiler-rt, and will be specific to arm64wc-w64-mingw32, since MSVC doesn't nedd them.

    lhmouse lhmouse commented on code on Nov 02, 2026 03:05 UTC
    Code Review
    llvm/lib/Target/AArch64/AArch64Arm64ECCallLowering.cpp:1
    @@ -592,16 +603,28 @@ Function *AArch64Arm64ECCallLowering::buildEntryThunk(Function *F) {
       }
     
       if (F->isVarArg()) {
    -    // The 5th argument to variadic entry thunks is used to model the x64 sp
    +    // The last argument to variadic entry thunks is used to model the x64 sp
         // which is passed to the thunk in x4, this can be passed to the callee as
         // the variadic argument start address after skipping over the 32 byte
         // shadow store.
     
         // The EC thunk CC will assign any argument marked as InReg to x4.
    -    Thunk->addParamAttr(5, Attribute::InReg);
    -    Value *Arg = Thunk->getArg(5);
    -    Arg = IRB.CreatePtrAdd(Arg, IRB.getInt64(0x20));
    -    Args.push_back(Arg);
    +    Thunk->addParamAttr(Thunk->arg_size() - 1, Attribute::InReg);
    +    Value *StackArgs = Thunk->getArg(Thunk->arg_size() - 1);
    +
    +    // x4 points at the 32 byte shadow store, so the first stack argument is
    +    // 32 bytes further up.  When the hidden return pointer took the first
    +    // integer argument register, the x64 caller can only pass three of the
    +    // four arguments in registers, and the fourth one, which is the first one
    +    // on the stack, fills the last slot of the callee's register save area.
    +    uint64_t StackOffset = 0x20;
    +    if (TransformDirectToSRet) {
    lhmouse lhmouse commented on Nov 02, 2026 04:36 UTC
    Author

    I will first try splitting the ARM64EC ABI issues and platform-neutral softmath changes to separate PRs.

    arsenm arsenm commented on code on Nov 02, 2026 05:12 UTC
    Code Review
    llvm/include/llvm/IR/RuntimeLibcalls.td:1
    @@ -2381,11 +2392,104 @@ def AArch64SystemLibrary : SystemRuntimeLibrary<isAArch64_ExceptArm64EC,
       ["compiler-rt", "libatomic", "llvm-client-runtime", "libm", "libc", "unwind",
        "sme"]>;
     
    +//===----------------------------------------------------------------------===//
    +// ARM64EC helpers for the x87 `long double` format
    +//===----------------------------------------------------------------------===//
    +
    +// These are not the exact x87 soft-float helpers of libgcc: The value stays
    +// an 80-bit x87 image in a 16-byte slot, but every operation on it is carried
    +// out in `double`. These are named with an `__arm64ec_` prefix so they will
    +// not be confused with, or silently bound to, an exact implementation of the
    +// same format.
    +defset list<RuntimeLibcallImpl> Arm64ECF80Impls = {
    +  def arm64ec___addxf3 : RuntimeLibcallImpl<ADD_F80, "__arm64ec_addxf3">;

    Why don't these functions have the leading #?

    Reviewers
    Assignees
    lhmouse lhmouse
    Labels
    risk: low confidence: 77.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 92.5% (HIGH) · Higher = larger blast radius
    92.5%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 77.5% · Lower = rushed or shallow review
    77.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 20.8% · Safe to merge
    20.8%