[clang] [CIR] Use the pragma FP environment for __builtin_convertvector (PR #246015)
Henrich Lauko via cfe-commits
cfe-commits at lists.llvm.org
Wed Nov 25 07:53:56 PST 2026
https://github.com/xlauko updated https://github.com/llvm/llvm-project/pull/246015
>From e001dcea7ade3181824d505cbea128d2110774df Mon Sep 17 00:00:00 2001
From: Henrich Lauko <hlauko at nvidia.com>
Date: Wed, 25 Nov 2026 11:25:31 +0000
Subject: [PATCH 1/3] [CIR] Keep complex mul and div constrained in strict FP
functions
In a strictfp function ClangIR emitted plain `fmul`, `fsub`, `fadd`,
`fdiv` and `fcmp` for complex multiplication and division, where
classic codegen emits constrained intrinsics. `cir.complex.fmul` and
`cir.complex.fdiv` had no `fenv` attribute, and LoweringPrepare
expanded them with a builder that has no floating-point state.
This gives both operations the optional `fenv` attribute and the fenv
traits of the scalar operations. CIRGen attaches the attribute, and
LoweringPrepare passes it to the scalar arithmetic, comparisons and
conversions of the expansion. The LLVM IR now has the constrained
intrinsics and metadata of classic codegen, with two differences:
- The range check of the improved division keeps its `oge` predicate,
where classic codegen uses `ugt`. It becomes a quiet `cir.fcmp`,
because a `cir.cmp ge` with `fenv` lowers to the signaling `fcmps`
and would raise an invalid exception for a quiet NaN divisor.
- With the promoted range, the conversions to and from the wider type
get the environment of the division. Classic codegen emits them
outside the scope of the division's FP options, with the default
environment of the function.
Assisted-by: Claude Code (Fable 5.2).
---
.../CIR/Dialect/Builder/CIRBaseBuilder.h | 6 +-
clang/include/clang/CIR/Dialect/IR/CIROps.td | 19 +-
.../Dialect/Transforms/LoweringPrepare.cpp | 168 ++++++++++++------
.../CIR/CodeGen/complex-mul-div-fenv-access.c | 128 +++++++++++++
clang/test/CIR/CodeGen/complex-mul-div.cpp | 4 +-
clang/test/CIR/CodeGen/complex-strict-fp.cpp | 167 +++++++++++++++++
.../complex-mul-div-fenv-effects.cir | 27 +++
.../lowering-prepare-complex-fenv.cir | 94 ++++++++++
8 files changed, 551 insertions(+), 62 deletions(-)
create mode 100644 clang/test/CIR/CodeGen/complex-mul-div-fenv-access.c
create mode 100644 clang/test/CIR/Transforms/complex-mul-div-fenv-effects.cir
create mode 100644 clang/test/CIR/Transforms/lowering-prepare-complex-fenv.cir
diff --git a/clang/include/clang/CIR/Dialect/Builder/CIRBaseBuilder.h b/clang/include/clang/CIR/Dialect/Builder/CIRBaseBuilder.h
index 55b6f2ca24a313..f01dd37cf276e4 100644
--- a/clang/include/clang/CIR/Dialect/Builder/CIRBaseBuilder.h
+++ b/clang/include/clang/CIR/Dialect/Builder/CIRBaseBuilder.h
@@ -358,7 +358,8 @@ class CIRBaseBuilderTy : public mlir::OpBuilder {
cir::ComplexRangeKind rangeKind) {
auto complexTy = mlir::cast<cir::ComplexType>(lhs.getType());
if (cir::isAnyFloatingPointType(complexTy.getElementType()))
- return cir::ComplexFMulOp::create(*this, loc, lhs, rhs, rangeKind);
+ return cir::ComplexFMulOp::create(*this, loc, lhs, rhs, rangeKind,
+ getConstrainedFPAttr());
return cir::ComplexMulOp::create(*this, loc, lhs, rhs);
}
@@ -367,7 +368,8 @@ class CIRBaseBuilderTy : public mlir::OpBuilder {
cir::ComplexRangeKind rangeKind) {
auto complexTy = mlir::cast<cir::ComplexType>(lhs.getType());
if (cir::isAnyFloatingPointType(complexTy.getElementType()))
- return cir::ComplexFDivOp::create(*this, loc, lhs, rhs, rangeKind);
+ return cir::ComplexFDivOp::create(*this, loc, lhs, rhs, rangeKind,
+ getConstrainedFPAttr());
return cir::ComplexDivOp::create(*this, loc, lhs, rhs);
}
diff --git a/clang/include/clang/CIR/Dialect/IR/CIROps.td b/clang/include/clang/CIR/Dialect/IR/CIROps.td
index 01e4d9bfb6d202..2f7eb4aa7ed88a 100644
--- a/clang/include/clang/CIR/Dialect/IR/CIROps.td
+++ b/clang/include/clang/CIR/Dialect/IR/CIROps.td
@@ -7976,19 +7976,24 @@ def CIR_ComplexRangeKind : CIR_I32Enum<
def CIR_ComplexRangeKindAttr
: CIR_EnumAttr<CIR_ComplexRangeKind, "complex_range">;
+// The optional `fenv` attribute describes constraints on the floating-point
+// handling of the operation. LoweringPrepare gives it to the scalar arithmetic,
+// comparisons and conversions the complex operation expands into.
class CIR_ComplexRangeBinOp<string mnemonic>
- : CIR_Op<mnemonic, [Pure, SameOperandsAndResultType]> {
+ : CIR_Op<mnemonic,
+ !listconcat([SameOperandsAndResultType], CIR_FenvOpTraits)> {
let arguments = (ins
CIR_ComplexOfFloatType:$lhs,
CIR_ComplexOfFloatType:$rhs,
- CIR_ComplexRangeKindAttr:$range
+ CIR_ComplexRangeKindAttr:$range,
+ OptionalAttr<CIR_FenvAttr>:$fenv
);
let results = (outs CIR_ComplexOfFloatType:$result);
let assemblyFormat = [{
$lhs `,` $rhs `range` `(` enum($range) `)` `:` qualified(type($result))
- attr-dict
+ (`fenv` `` $fenv^)? attr-dict
}];
let hasLLVMLowering = false;
@@ -8007,11 +8012,15 @@ def CIR_ComplexFMulOp : CIR_ComplexRangeBinOp<"complex.fmul"> {
function is called if one of the intermediate calculations produced
a NaN value.
+ The optional `fenv` attribute describes constraints on the floating-point
+ handling of the operation.
+
Example:
```
%2 = cir.complex.fmul %0, %1 range(basic) : !cir.complex<!cir.float>
%2 = cir.complex.fmul %0, %1 range(full) : !cir.complex<!cir.float>
+ %2 = cir.complex.fmul %0, %1 range(full) : !cir.complex<!cir.float> fenv<>
```
}];
}
@@ -8034,11 +8043,15 @@ def CIR_ComplexFDivOp : CIR_ComplexRangeBinOp<"complex.fdiv"> {
no additional handling for the NaN value will be used. For integers types
`range` attribute will be ignored.
+ The optional `fenv` attribute describes constraints on the floating-point
+ handling of the operation.
+
Example:
```
%2 = cir.complex.fdiv %0, %1 range(basic) : !cir.complex<!cir.float>
%2 = cir.complex.fdiv %0, %1 range(full) : !cir.complex<!cir.float>
+ %2 = cir.complex.fdiv %0, %1 range(full) : !cir.complex<!cir.float> fenv<>
```
}];
}
diff --git a/clang/lib/CIR/Dialect/Transforms/LoweringPrepare.cpp b/clang/lib/CIR/Dialect/Transforms/LoweringPrepare.cpp
index 753b712fc3c445..e41586f046c221 100644
--- a/clang/lib/CIR/Dialect/Transforms/LoweringPrepare.cpp
+++ b/clang/lib/CIR/Dialect/Transforms/LoweringPrepare.cpp
@@ -822,10 +822,68 @@ getComplexDivLibCallName(llvm::APFloat::Semantics semantics) {
}
}
+namespace {
+/// Creates the scalar floating-point arithmetic, comparisons and conversions
+/// that a complex multiplication or division expands into. Each of them gets
+/// the `fenv` attribute of the complex operation, so a constrained operation
+/// expands into constrained ones. With a null attribute the operations are
+/// unconstrained.
+class FenvOpBuilder {
+public:
+ FenvOpBuilder(CIRBaseBuilderTy &builder, mlir::Location loc,
+ cir::FenvAttr fenv)
+ : builder(builder), loc(loc), fenv(fenv) {}
+
+ mlir::Value fadd(mlir::Value lhs, mlir::Value rhs) const {
+ return binOp<cir::FAddOp>(lhs, rhs);
+ }
+ mlir::Value fsub(mlir::Value lhs, mlir::Value rhs) const {
+ return binOp<cir::FSubOp>(lhs, rhs);
+ }
+ mlir::Value fmul(mlir::Value lhs, mlir::Value rhs) const {
+ return binOp<cir::FMulOp>(lhs, rhs);
+ }
+ mlir::Value fdiv(mlir::Value lhs, mlir::Value rhs) const {
+ return binOp<cir::FDivOp>(lhs, rhs);
+ }
+
+ /// Creates a quiet comparison, which raises no exception for a quiet NaN
+ /// operand.
+ mlir::Value fcmp(cir::FCmpOpKind kind, mlir::Value lhs,
+ mlir::Value rhs) const {
+ return cir::FCmpOp::create(builder, loc, kind, lhs, rhs,
+ /*signaling=*/false, fenv);
+ }
+
+ mlir::Value isNaN(mlir::Value operand) const {
+ return fcmp(cir::FCmpOpKind::uno, operand, operand);
+ }
+
+ mlir::Value floatingCast(mlir::Value src, mlir::Type dstTy) const {
+ return cir::CastOp::create(builder, loc, dstTy, cir::CastKind::floating,
+ src, fenv);
+ }
+
+private:
+ template <typename OpTy>
+ mlir::Value binOp(mlir::Value lhs, mlir::Value rhs) const {
+ assert(!cir::MissingFeatures::fastMathFlags());
+ return OpTy::create(builder, loc, lhs, rhs, fenv, cir::FastMathFlagsAttr{});
+ }
+
+ CIRBaseBuilderTy &builder;
+ mlir::Location loc;
+ cir::FenvAttr fenv;
+};
+} // namespace
+
+/// \p fenv is the floating-point environment of a floating-point division. It
+/// is null for an unconstrained one and for an integer division.
static mlir::Value
buildAlgebraicComplexDiv(CIRBaseBuilderTy &builder, mlir::Location loc,
mlir::Value lhsReal, mlir::Value lhsImag,
- mlir::Value rhsReal, mlir::Value rhsImag) {
+ mlir::Value rhsReal, mlir::Value rhsImag,
+ cir::FenvAttr fenv) {
// (a+bi) / (c+di) = ((ac+bd)/(cc+dd)) + ((bc-ad)/(cc+dd))i
mlir::Value &a = lhsReal;
mlir::Value &b = lhsImag;
@@ -835,17 +893,18 @@ buildAlgebraicComplexDiv(CIRBaseBuilderTy &builder, mlir::Location loc,
// The element type of the complex (lhs/rhs) determines whether floating
// point or integer ops are needed.
bool isFP = cir::isFPOrVectorOfFPType(a.getType());
+ FenvOpBuilder fp(builder, loc, fenv);
auto mul = [&](mlir::Location l, mlir::Value x, mlir::Value y) {
- return isFP ? builder.createFMul(l, x, y) : builder.createMul(l, x, y);
+ return isFP ? fp.fmul(x, y) : builder.createMul(l, x, y);
};
auto add = [&](mlir::Location l, mlir::Value x, mlir::Value y) {
- return isFP ? builder.createFAdd(l, x, y) : builder.createAdd(l, x, y);
+ return isFP ? fp.fadd(x, y) : builder.createAdd(l, x, y);
};
auto sub = [&](mlir::Location l, mlir::Value x, mlir::Value y) {
- return isFP ? builder.createFSub(l, x, y) : builder.createSub(l, x, y);
+ return isFP ? fp.fsub(x, y) : builder.createSub(l, x, y);
};
auto div = [&](mlir::Location l, mlir::Value x, mlir::Value y) {
- return isFP ? builder.createFDiv(l, x, y) : builder.createDiv(l, x, y);
+ return isFP ? fp.fdiv(x, y) : builder.createDiv(l, x, y);
};
mlir::Value ac = mul(loc, a, c); // a*c
@@ -866,7 +925,8 @@ buildAlgebraicComplexDiv(CIRBaseBuilderTy &builder, mlir::Location loc,
static mlir::Value
buildRangeReductionComplexDiv(CIRBaseBuilderTy &builder, mlir::Location loc,
mlir::Value lhsReal, mlir::Value lhsImag,
- mlir::Value rhsReal, mlir::Value rhsImag) {
+ mlir::Value rhsReal, mlir::Value rhsImag,
+ cir::FenvAttr fenv) {
// Implements Smith's algorithm for complex division.
// SMITH, R. L. Algorithm 116: Complex division. Commun. ACM 5, 8 (1962).
@@ -896,35 +956,37 @@ buildRangeReductionComplexDiv(CIRBaseBuilderTy &builder, mlir::Location loc,
assert(cir::isFPOrVectorOfFPType(a.getType()) &&
"range-reduction complex divide expects floating-point operands");
+ FenvOpBuilder fp(builder, loc, fenv);
+
auto trueBranchBuilder = [&](mlir::OpBuilder &, mlir::Location) {
- mlir::Value r = builder.createFDiv(loc, d, c); // r := d / c
- mlir::Value rd = builder.createFMul(loc, r, d); // r*d
- mlir::Value tmp = builder.createFAdd(loc, c, rd); // tmp := c + r*d
+ mlir::Value r = fp.fdiv(d, c); // r := d / c
+ mlir::Value rd = fp.fmul(r, d); // r*d
+ mlir::Value tmp = fp.fadd(c, rd); // tmp := c + r*d
- mlir::Value br = builder.createFMul(loc, b, r); // b*r
- mlir::Value abr = builder.createFAdd(loc, a, br); // a + b*r
- mlir::Value e = builder.createFDiv(loc, abr, tmp);
+ mlir::Value br = fp.fmul(b, r); // b*r
+ mlir::Value abr = fp.fadd(a, br); // a + b*r
+ mlir::Value e = fp.fdiv(abr, tmp);
- mlir::Value ar = builder.createFMul(loc, a, r); // a*r
- mlir::Value bar = builder.createFSub(loc, b, ar); // b - a*r
- mlir::Value f = builder.createFDiv(loc, bar, tmp);
+ mlir::Value ar = fp.fmul(a, r); // a*r
+ mlir::Value bar = fp.fsub(b, ar); // b - a*r
+ mlir::Value f = fp.fdiv(bar, tmp);
mlir::Value result = builder.createComplexCreate(loc, e, f);
builder.createYield(loc, result);
};
auto falseBranchBuilder = [&](mlir::OpBuilder &, mlir::Location) {
- mlir::Value r = builder.createFDiv(loc, c, d); // r := c / d
- mlir::Value rc = builder.createFMul(loc, r, c); // r*c
- mlir::Value tmp = builder.createFAdd(loc, d, rc); // tmp := d + r*c
+ mlir::Value r = fp.fdiv(c, d); // r := c / d
+ mlir::Value rc = fp.fmul(r, c); // r*c
+ mlir::Value tmp = fp.fadd(d, rc); // tmp := d + r*c
- mlir::Value ar = builder.createFMul(loc, a, r); // a*r
- mlir::Value arb = builder.createFAdd(loc, ar, b); // a*r + b
- mlir::Value e = builder.createFDiv(loc, arb, tmp);
+ mlir::Value ar = fp.fmul(a, r); // a*r
+ mlir::Value arb = fp.fadd(ar, b); // a*r + b
+ mlir::Value e = fp.fdiv(arb, tmp);
- mlir::Value br = builder.createFMul(loc, b, r); // b*r
- mlir::Value bra = builder.createFSub(loc, br, a); // b*r - a
- mlir::Value f = builder.createFDiv(loc, bra, tmp);
+ mlir::Value br = fp.fmul(b, r); // b*r
+ mlir::Value bra = fp.fsub(br, a); // b*r - a
+ mlir::Value f = fp.fdiv(bra, tmp);
mlir::Value result = builder.createComplexCreate(loc, e, f);
builder.createYield(loc, result);
@@ -932,8 +994,9 @@ buildRangeReductionComplexDiv(CIRBaseBuilderTy &builder, mlir::Location loc,
auto cFabs = cir::FAbsOp::create(builder, loc, c);
auto dFabs = cir::FAbsOp::create(builder, loc, d);
- cir::CmpOp cmpResult =
- builder.createCompare(loc, cir::CmpOpKind::ge, cFabs, dFabs);
+ // A quiet NaN in the divisor must not raise an invalid exception here, so
+ // this is a quiet comparison and not the signaling `cir.cmp ge`.
+ mlir::Value cmpResult = fp.fcmp(cir::FCmpOpKind::oge, cFabs, dFabs);
auto ternary = cir::TernaryOp::create(builder, loc, cmpResult,
trueBranchBuilder, falseBranchBuilder);
@@ -1032,6 +1095,7 @@ static mlir::Value lowerComplexFDiv(LoweringPreparePass &pass,
const clang::TargetInfo &targetInfo) {
cir::ComplexType complexTy = op.getType();
cir::ComplexRangeKind range = op.getRange();
+ cir::FenvAttr fenv = op.getFenvAttr();
switch (range) {
case ComplexRangeKind::Full: {
return buildComplexBinOpLibCall(pass, builder, &getComplexDivLibCallName,
@@ -1040,7 +1104,7 @@ static mlir::Value lowerComplexFDiv(LoweringPreparePass &pass,
}
case ComplexRangeKind::Improved: {
return buildRangeReductionComplexDiv(builder, loc, lhsReal, lhsImag,
- rhsReal, rhsImag);
+ rhsReal, rhsImag, fenv);
}
case ComplexRangeKind::Promoted: {
mlir::Type originalElementType = complexTy.getElementType();
@@ -1051,33 +1115,27 @@ static mlir::Value lowerComplexFDiv(LoweringPreparePass &pass,
if (!higherPrecisionElementType)
return buildRangeReductionComplexDiv(builder, loc, lhsReal, lhsImag,
- rhsReal, rhsImag);
-
- cir::CastKind floatingCastKind = cir::CastKind::floating;
- lhsReal = builder.createCast(floatingCastKind, lhsReal,
- higherPrecisionElementType);
- lhsImag = builder.createCast(floatingCastKind, lhsImag,
- higherPrecisionElementType);
- rhsReal = builder.createCast(floatingCastKind, rhsReal,
- higherPrecisionElementType);
- rhsImag = builder.createCast(floatingCastKind, rhsImag,
- higherPrecisionElementType);
+ rhsReal, rhsImag, fenv);
+
+ FenvOpBuilder fp(builder, loc, fenv);
+ lhsReal = fp.floatingCast(lhsReal, higherPrecisionElementType);
+ lhsImag = fp.floatingCast(lhsImag, higherPrecisionElementType);
+ rhsReal = fp.floatingCast(rhsReal, higherPrecisionElementType);
+ rhsImag = fp.floatingCast(rhsImag, higherPrecisionElementType);
mlir::Value algebraicResult = buildAlgebraicComplexDiv(
- builder, loc, lhsReal, lhsImag, rhsReal, rhsImag);
+ builder, loc, lhsReal, lhsImag, rhsReal, rhsImag, fenv);
mlir::Value resultReal = builder.createComplexReal(loc, algebraicResult);
mlir::Value resultImag = builder.createComplexImag(loc, algebraicResult);
- mlir::Value finalReal =
- builder.createCast(floatingCastKind, resultReal, originalElementType);
- mlir::Value finalImag =
- builder.createCast(floatingCastKind, resultImag, originalElementType);
+ mlir::Value finalReal = fp.floatingCast(resultReal, originalElementType);
+ mlir::Value finalImag = fp.floatingCast(resultImag, originalElementType);
return builder.createComplexCreate(loc, finalReal, finalImag);
}
case ComplexRangeKind::Basic: {
return buildAlgebraicComplexDiv(builder, loc, lhsReal, lhsImag, rhsReal,
- rhsImag);
+ rhsImag, fenv);
}
}
llvm_unreachable("fully covered switch");
@@ -1113,7 +1171,7 @@ void LoweringPreparePass::lowerComplexDivOp(cir::ComplexDivOp op) {
mlir::Value rhsImag = builder.createComplexImag(loc, rhs);
mlir::Value loweredResult = buildAlgebraicComplexDiv(
- builder, loc, lhsReal, lhsImag, rhsReal, rhsImag);
+ builder, loc, lhsReal, lhsImag, rhsReal, rhsImag, /*fenv=*/{});
op.replaceAllUsesWith(loweredResult);
op.erase();
}
@@ -1143,15 +1201,15 @@ static mlir::Value lowerComplexFMul(LoweringPreparePass &pass,
mlir::Location loc, cir::ComplexFMulOp op,
mlir::Value lhsReal, mlir::Value lhsImag,
mlir::Value rhsReal, mlir::Value rhsImag) {
+ FenvOpBuilder fp(builder, loc, op.getFenvAttr());
+
// (a+bi) * (c+di) = (ac-bd) + (ad+bc)i
- mlir::Value resultRealLhs = builder.createFMul(loc, lhsReal, rhsReal); // ac
- mlir::Value resultRealRhs = builder.createFMul(loc, lhsImag, rhsImag); // bd
- mlir::Value resultImagLhs = builder.createFMul(loc, lhsReal, rhsImag); // ad
- mlir::Value resultImagRhs = builder.createFMul(loc, lhsImag, rhsReal); // bc
- mlir::Value resultReal =
- builder.createFSub(loc, resultRealLhs, resultRealRhs);
- mlir::Value resultImag =
- builder.createFAdd(loc, resultImagLhs, resultImagRhs);
+ mlir::Value resultRealLhs = fp.fmul(lhsReal, rhsReal); // ac
+ mlir::Value resultRealRhs = fp.fmul(lhsImag, rhsImag); // bd
+ mlir::Value resultImagLhs = fp.fmul(lhsReal, rhsImag); // ad
+ mlir::Value resultImagRhs = fp.fmul(lhsImag, rhsReal); // bc
+ mlir::Value resultReal = fp.fsub(resultRealLhs, resultRealRhs);
+ mlir::Value resultImag = fp.fadd(resultImagLhs, resultImagRhs);
mlir::Value algebraicResult =
builder.createComplexCreate(loc, resultReal, resultImag);
@@ -1167,8 +1225,8 @@ static mlir::Value lowerComplexFMul(LoweringPreparePass &pass,
// Check whether the real part and the imaginary part of the result are both
// NaN. If so, emit a library call to compute the multiplication instead.
// We check a value against NaN by comparing the value against itself.
- mlir::Value resultRealIsNaN = builder.createIsNaN(loc, resultReal);
- mlir::Value resultImagIsNaN = builder.createIsNaN(loc, resultImag);
+ mlir::Value resultRealIsNaN = fp.isNaN(resultReal);
+ mlir::Value resultImagIsNaN = fp.isNaN(resultImag);
mlir::Value resultRealAndImagAreNaN =
builder.createLogicalAnd(loc, resultRealIsNaN, resultImagIsNaN);
diff --git a/clang/test/CIR/CodeGen/complex-mul-div-fenv-access.c b/clang/test/CIR/CodeGen/complex-mul-div-fenv-access.c
new file mode 100644
index 00000000000000..96fb75ca4cf376
--- /dev/null
+++ b/clang/test/CIR/CodeGen/complex-mul-div-fenv-access.c
@@ -0,0 +1,128 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -fclangir -emit-llvm %s -o %t-cir.ll
+// RUN: FileCheck --input-file=%t-cir.ll %s --check-prefixes=FULL,LLVM-FULL \
+// RUN: --implicit-check-not="{{= f(add|sub|mul|div|cmp|pext|ptrunc) }}"
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -emit-llvm %s -o %t.ll
+// RUN: FileCheck --input-file=%t.ll %s --check-prefixes=FULL,OGCG-FULL
+
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -complex-range=improved -fclangir -emit-llvm %s -o %t-improved-cir.ll
+// RUN: FileCheck --input-file=%t-improved-cir.ll %s --check-prefixes=IMPROVED,LLVM-IMPROVED \
+// RUN: --implicit-check-not="{{= f(add|sub|mul|div|cmp|pext|ptrunc) }}"
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -complex-range=improved -emit-llvm %s -o %t-improved.ll
+// RUN: FileCheck --input-file=%t-improved.ll %s --check-prefixes=IMPROVED,OGCG-IMPROVED
+
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -complex-range=promoted -fclangir -emit-llvm %s -o %t-promoted-cir.ll
+// RUN: FileCheck --input-file=%t-promoted-cir.ll %s --check-prefix=LLVM-PROMOTED \
+// RUN: --implicit-check-not="{{= f(add|sub|mul|div|cmp|pext|ptrunc) }}"
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -complex-range=promoted -emit-llvm %s -o %t-promoted.ll
+// RUN: FileCheck --input-file=%t-promoted.ll %s --check-prefix=OGCG-PROMOTED
+
+// Complex multiplication and division under FENV_ACCESS. The arithmetic,
+// comparisons and conversions of the expansion are constrained intrinsics.
+// The FULL and IMPROVED lines are shared by ClangIR and classic codegen, so
+// both emit the same intrinsics with the same metadata.
+
+#pragma STDC FENV_ACCESS ON
+
+_Complex float a, b, c;
+
+void mul(void) { c = a * b; }
+
+// FULL-LABEL: define{{.*}} void @mul()
+
+// LLVM-FULL: %[[A:.*]] = load { float, float }, ptr @a
+// LLVM-FULL: %[[B:.*]] = load { float, float }, ptr @b
+// LLVM-FULL: %[[A_REAL:.*]] = extractvalue { float, float } %[[A]], 0
+// LLVM-FULL: %[[A_IMAG:.*]] = extractvalue { float, float } %[[A]], 1
+// LLVM-FULL: %[[B_REAL:.*]] = extractvalue { float, float } %[[B]], 0
+// LLVM-FULL: %[[B_IMAG:.*]] = extractvalue { float, float } %[[B]], 1
+
+// OGCG-FULL: %[[A_REAL:.*]] = load float, ptr @a
+// OGCG-FULL: %[[A_IMAG:.*]] = load float, ptr getelementptr inbounds nuw (i8, ptr @a, i64 4)
+// OGCG-FULL: %[[B_REAL:.*]] = load float, ptr @b
+// OGCG-FULL: %[[B_IMAG:.*]] = load float, ptr getelementptr inbounds nuw (i8, ptr @b, i64 4)
+
+// FULL: %[[AC:.*]] = call float @llvm.experimental.constrained.fmul.f32(float %[[A_REAL]], float %[[B_REAL]], metadata !"round.dynamic", metadata !"fpexcept.strict")
+// FULL: %[[BD:.*]] = call float @llvm.experimental.constrained.fmul.f32(float %[[A_IMAG]], float %[[B_IMAG]], metadata !"round.dynamic", metadata !"fpexcept.strict")
+// FULL: %[[AD:.*]] = call float @llvm.experimental.constrained.fmul.f32(float %[[A_REAL]], float %[[B_IMAG]], metadata !"round.dynamic", metadata !"fpexcept.strict")
+// FULL: %[[BC:.*]] = call float @llvm.experimental.constrained.fmul.f32(float %[[A_IMAG]], float %[[B_REAL]], metadata !"round.dynamic", metadata !"fpexcept.strict")
+// FULL: %[[REAL:.*]] = call float @llvm.experimental.constrained.fsub.f32(float %[[AC]], float %[[BD]], metadata !"round.dynamic", metadata !"fpexcept.strict")
+// FULL: %[[IMAG:.*]] = call float @llvm.experimental.constrained.fadd.f32(float %[[AD]], float %[[BC]], metadata !"round.dynamic", metadata !"fpexcept.strict")
+// FULL: call i1 @llvm.experimental.constrained.fcmp.f32(float %[[REAL]], float %[[REAL]], metadata !"uno", metadata !"fpexcept.strict")
+// FULL: call i1 @llvm.experimental.constrained.fcmp.f32(float %[[IMAG]], float %[[IMAG]], metadata !"uno", metadata !"fpexcept.strict")
+// FULL: call {{.*}}<2 x float> @__mulsc3(float {{.*}}%[[A_REAL]], float {{.*}}%[[A_IMAG]], float {{.*}}%[[B_REAL]], float {{.*}}%[[B_IMAG]])
+
+void div(void) { c = a / b; }
+
+// With the full range, division is a call to the runtime library.
+
+// FULL-LABEL: define{{.*}} void @div()
+// FULL: call {{.*}}<2 x float> @__divsc3(
+
+// With the improved range, division uses Smith's algorithm. The range check
+// is a quiet comparison in both codegens. Its predicate differs.
+
+// IMPROVED-LABEL: define{{.*}} void @div()
+
+// LLVM-IMPROVED: %[[A:.*]] = load { float, float }, ptr @a
+// LLVM-IMPROVED: %[[B:.*]] = load { float, float }, ptr @b
+// LLVM-IMPROVED: %[[A_REAL:.*]] = extractvalue { float, float } %[[A]], 0
+// LLVM-IMPROVED: %[[A_IMAG:.*]] = extractvalue { float, float } %[[A]], 1
+// LLVM-IMPROVED: %[[B_REAL:.*]] = extractvalue { float, float } %[[B]], 0
+// LLVM-IMPROVED: %[[B_IMAG:.*]] = extractvalue { float, float } %[[B]], 1
+
+// OGCG-IMPROVED: %[[A_REAL:.*]] = load float, ptr @a
+// OGCG-IMPROVED: %[[A_IMAG:.*]] = load float, ptr getelementptr inbounds nuw (i8, ptr @a, i64 4)
+// OGCG-IMPROVED: %[[B_REAL:.*]] = load float, ptr @b
+// OGCG-IMPROVED: %[[B_IMAG:.*]] = load float, ptr getelementptr inbounds nuw (i8, ptr @b, i64 4)
+
+// IMPROVED: %[[ABS_C:.*]] = call float @llvm.fabs.f32(float %[[B_REAL]])
+// IMPROVED: %[[ABS_D:.*]] = call float @llvm.fabs.f32(float %[[B_IMAG]])
+// LLVM-IMPROVED: call i1 @llvm.experimental.constrained.fcmp.f32(float %[[ABS_C]], float %[[ABS_D]], metadata !"oge", metadata !"fpexcept.strict")
+// OGCG-IMPROVED: call i1 @llvm.experimental.constrained.fcmp.f32(float %[[ABS_C]], float %[[ABS_D]], metadata !"ugt", metadata !"fpexcept.strict")
+
+// IMPROVED: %[[R1:.*]] = call float @llvm.experimental.constrained.fdiv.f32(float %[[B_IMAG]], float %[[B_REAL]], metadata !"round.dynamic", metadata !"fpexcept.strict")
+// IMPROVED: %[[RD:.*]] = call float @llvm.experimental.constrained.fmul.f32(float %[[R1]], float %[[B_IMAG]], metadata !"round.dynamic", metadata !"fpexcept.strict")
+// IMPROVED: %[[TMP1:.*]] = call float @llvm.experimental.constrained.fadd.f32(float %[[B_REAL]], float %[[RD]], metadata !"round.dynamic", metadata !"fpexcept.strict")
+// IMPROVED: %[[BR1:.*]] = call float @llvm.experimental.constrained.fmul.f32(float %[[A_IMAG]], float %[[R1]], metadata !"round.dynamic", metadata !"fpexcept.strict")
+// IMPROVED: %[[ABR:.*]] = call float @llvm.experimental.constrained.fadd.f32(float %[[A_REAL]], float %[[BR1]], metadata !"round.dynamic", metadata !"fpexcept.strict")
+// IMPROVED: call float @llvm.experimental.constrained.fdiv.f32(float %[[ABR]], float %[[TMP1]], metadata !"round.dynamic", metadata !"fpexcept.strict")
+// IMPROVED: %[[AR1:.*]] = call float @llvm.experimental.constrained.fmul.f32(float %[[A_REAL]], float %[[R1]], metadata !"round.dynamic", metadata !"fpexcept.strict")
+// IMPROVED: %[[BAR:.*]] = call float @llvm.experimental.constrained.fsub.f32(float %[[A_IMAG]], float %[[AR1]], metadata !"round.dynamic", metadata !"fpexcept.strict")
+// IMPROVED: call float @llvm.experimental.constrained.fdiv.f32(float %[[BAR]], float %[[TMP1]], metadata !"round.dynamic", metadata !"fpexcept.strict")
+
+// IMPROVED: %[[R2:.*]] = call float @llvm.experimental.constrained.fdiv.f32(float %[[B_REAL]], float %[[B_IMAG]], metadata !"round.dynamic", metadata !"fpexcept.strict")
+// IMPROVED: %[[RC:.*]] = call float @llvm.experimental.constrained.fmul.f32(float %[[R2]], float %[[B_REAL]], metadata !"round.dynamic", metadata !"fpexcept.strict")
+// IMPROVED: %[[TMP2:.*]] = call float @llvm.experimental.constrained.fadd.f32(float %[[B_IMAG]], float %[[RC]], metadata !"round.dynamic", metadata !"fpexcept.strict")
+// IMPROVED: %[[AR2:.*]] = call float @llvm.experimental.constrained.fmul.f32(float %[[A_REAL]], float %[[R2]], metadata !"round.dynamic", metadata !"fpexcept.strict")
+// IMPROVED: %[[ARB:.*]] = call float @llvm.experimental.constrained.fadd.f32(float %[[AR2]], float %[[A_IMAG]], metadata !"round.dynamic", metadata !"fpexcept.strict")
+// IMPROVED: call float @llvm.experimental.constrained.fdiv.f32(float %[[ARB]], float %[[TMP2]], metadata !"round.dynamic", metadata !"fpexcept.strict")
+// IMPROVED: %[[BR2:.*]] = call float @llvm.experimental.constrained.fmul.f32(float %[[A_IMAG]], float %[[R2]], metadata !"round.dynamic", metadata !"fpexcept.strict")
+// IMPROVED: %[[BRA:.*]] = call float @llvm.experimental.constrained.fsub.f32(float %[[BR2]], float %[[A_REAL]], metadata !"round.dynamic", metadata !"fpexcept.strict")
+// IMPROVED: call float @llvm.experimental.constrained.fdiv.f32(float %[[BRA]], float %[[TMP2]], metadata !"round.dynamic", metadata !"fpexcept.strict")
+
+// With the promoted range, division is done in a wider type. Classic codegen
+// converts the operands and the result outside the scope of the division's
+// FP options, so its conversions get the default environment of the
+// function. ClangIR converts as part of the division and gives the
+// conversions its environment, which assumes less.
+
+// LLVM-PROMOTED-LABEL: define{{.*}} void @div()
+// LLVM-PROMOTED-COUNT-4: call double @llvm.experimental.constrained.fpext.f64.f32(float %{{.*}}, metadata !"fpexcept.strict")
+// LLVM-PROMOTED-COUNT-4: call double @llvm.experimental.constrained.fmul.f64(double %{{.*}}, double %{{.*}}, metadata !"round.dynamic", metadata !"fpexcept.strict")
+// LLVM-PROMOTED-COUNT-2: call double @llvm.experimental.constrained.fadd.f64(double %{{.*}}, double %{{.*}}, metadata !"round.dynamic", metadata !"fpexcept.strict")
+// LLVM-PROMOTED: call double @llvm.experimental.constrained.fdiv.f64(double %{{.*}}, double %{{.*}}, metadata !"round.dynamic", metadata !"fpexcept.strict")
+// LLVM-PROMOTED-COUNT-2: call double @llvm.experimental.constrained.fmul.f64(double %{{.*}}, double %{{.*}}, metadata !"round.dynamic", metadata !"fpexcept.strict")
+// LLVM-PROMOTED: call double @llvm.experimental.constrained.fsub.f64(double %{{.*}}, double %{{.*}}, metadata !"round.dynamic", metadata !"fpexcept.strict")
+// LLVM-PROMOTED: call double @llvm.experimental.constrained.fdiv.f64(double %{{.*}}, double %{{.*}}, metadata !"round.dynamic", metadata !"fpexcept.strict")
+// LLVM-PROMOTED-COUNT-2: call float @llvm.experimental.constrained.fptrunc.f32.f64(double %{{.*}}, metadata !"round.dynamic", metadata !"fpexcept.strict")
+
+// OGCG-PROMOTED-LABEL: define{{.*}} void @div()
+// OGCG-PROMOTED-COUNT-4: call double @llvm.experimental.constrained.fpext.f64.f32(float %{{.*}}, metadata !"fpexcept.ignore")
+// OGCG-PROMOTED-COUNT-2: call double @llvm.experimental.constrained.fmul.f64(double %{{.*}}, double %{{.*}}, metadata !"round.dynamic", metadata !"fpexcept.strict")
+// OGCG-PROMOTED: call double @llvm.experimental.constrained.fadd.f64(double %{{.*}}, double %{{.*}}, metadata !"round.dynamic", metadata !"fpexcept.strict")
+// OGCG-PROMOTED-COUNT-2: call double @llvm.experimental.constrained.fmul.f64(double %{{.*}}, double %{{.*}}, metadata !"round.dynamic", metadata !"fpexcept.strict")
+// OGCG-PROMOTED: call double @llvm.experimental.constrained.fadd.f64(double %{{.*}}, double %{{.*}}, metadata !"round.dynamic", metadata !"fpexcept.strict")
+// OGCG-PROMOTED-COUNT-2: call double @llvm.experimental.constrained.fmul.f64(double %{{.*}}, double %{{.*}}, metadata !"round.dynamic", metadata !"fpexcept.strict")
+// OGCG-PROMOTED: call double @llvm.experimental.constrained.fsub.f64(double %{{.*}}, double %{{.*}}, metadata !"round.dynamic", metadata !"fpexcept.strict")
+// OGCG-PROMOTED-COUNT-2: call double @llvm.experimental.constrained.fdiv.f64(double %{{.*}}, double %{{.*}}, metadata !"round.dynamic", metadata !"fpexcept.strict")
+// OGCG-PROMOTED-COUNT-2: call float @llvm.experimental.constrained.fptrunc.f32.f64(double %{{.*}}, metadata !"round.tonearest", metadata !"fpexcept.ignore")
diff --git a/clang/test/CIR/CodeGen/complex-mul-div.cpp b/clang/test/CIR/CodeGen/complex-mul-div.cpp
index 63ccbf895ef4fa..25056f766235fc 100644
--- a/clang/test/CIR/CodeGen/complex-mul-div.cpp
+++ b/clang/test/CIR/CodeGen/complex-mul-div.cpp
@@ -425,7 +425,7 @@ void foo3() {
// CIR-AFTER-IMPROVED: %[[B_IMAG:.*]] = cir.complex.imag %[[TMP_B]] : !cir.complex<!cir.float> -> !cir.float
// CIR-AFTER-IMPROVED: %[[ABS_B_REAL:.*]] = cir.fabs %[[B_REAL]] : !cir.float
// CIR-AFTER-IMPROVED: %[[ABS_B_IMAG:.*]] = cir.fabs %[[B_IMAG]] : !cir.float
-// CIR-AFTER-IMPROVED: %[[ABS_B_CMP:.*]] = cir.cmp ge %[[ABS_B_REAL]], %[[ABS_B_IMAG]] : !cir.float
+// CIR-AFTER-IMPROVED: %[[ABS_B_CMP:.*]] = cir.fcmp oge %[[ABS_B_REAL]], %[[ABS_B_IMAG]] : !cir.float
// CIR-AFTER-IMPROVED: %[[RESULT:.*]] = cir.ternary(%[[ABS_B_CMP]], true {
// CIR-AFTER-IMPROVED: %[[DIV_BI_BR:.*]] = cir.fdiv %[[B_IMAG]], %[[B_REAL]] : !cir.float
// CIR-AFTER-IMPROVED: %[[MUL_DIV_BIBR_BI:.*]] = cir.fmul %[[DIV_BI_BR]], %[[B_IMAG]] : !cir.float
@@ -926,7 +926,7 @@ void foo6() {
// CIR-AFTER-IMPROVED: %[[B_IMAG:.*]] = cir.complex.imag %[[TMP_B]] : !cir.complex<!cir.float> -> !cir.float
// CIR-AFTER-IMPROVED: %[[ABS_B_REAL:.*]] = cir.fabs %[[B_REAL]] : !cir.float
// CIR-AFTER-IMPROVED: %[[ABS_B_IMAG:.*]] = cir.fabs %[[B_IMAG]] : !cir.float
-// CIR-AFTER-IMPROVED: %[[ABS_B_CMP:.*]] = cir.cmp ge %[[ABS_B_REAL]], %[[ABS_B_IMAG]] : !cir.float
+// CIR-AFTER-IMPROVED: %[[ABS_B_CMP:.*]] = cir.fcmp oge %[[ABS_B_REAL]], %[[ABS_B_IMAG]] : !cir.float
// CIR-AFTER-IMPROVED: %[[RESULT:.*]] = cir.ternary(%[[ABS_B_CMP]], true {
// CIR-AFTER-IMPROVED: %[[DIV_BI_BR:.*]] = cir.fdiv %[[B_IMAG]], %[[B_REAL]] : !cir.float
// CIR-AFTER-IMPROVED: %[[MUL_DIV_BIBR_BI:.*]] = cir.fmul %[[DIV_BI_BR]], %[[B_IMAG]] : !cir.float
diff --git a/clang/test/CIR/CodeGen/complex-strict-fp.cpp b/clang/test/CIR/CodeGen/complex-strict-fp.cpp
index 9a7f0a145b28be..864b677336a47a 100644
--- a/clang/test/CIR/CodeGen/complex-strict-fp.cpp
+++ b/clang/test/CIR/CodeGen/complex-strict-fp.cpp
@@ -4,6 +4,7 @@
// RUN: FileCheck --input-file=%t-strict.ll %s -check-prefix=LLVM
// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -Wno-unused-value -ffp-contract=on -fexperimental-strict-floating-point -ffp-exception-behavior=strict -emit-llvm %s -o %t-strict-ogcg.ll
// RUN: FileCheck --input-file=%t-strict-ogcg.ll %s -check-prefix=OGCG
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -Wno-unused-value -fclangir -ffp-contract=on -fexperimental-strict-floating-point -ffp-exception-behavior=strict -emit-cir -mmlir --mlir-print-ir-before=cir-canonicalize %s -o %t-strict-before.cir 2>&1 | FileCheck %s -check-prefix=CIR-BEFORE
void complex_add() {
_Complex float a;
@@ -98,3 +99,169 @@ void complex_sub() {
// OGCG: %[[C_IMAG_PTR:.*]] = getelementptr inbounds nuw { float, float }, ptr %[[C_ADDR]], i32 0, i32 1
// OGCG: store float %[[RESULT_REAL]], ptr %[[C_REAL_PTR]], align 4
// OGCG: store float %[[RESULT_IMAG]], ptr %[[C_IMAG_PTR]], align 4
+
+// With CX_LIMITED_RANGE, multiplication and division expand into scalar
+// arithmetic only. The NaN check, the range check and the runtime library
+// calls of the other ranges are tested in complex-mul-div-fenv-access.c.
+//
+// LoweringPrepare does the expansion, so the CIR prefix sees the scalar
+// operations. Each of them carries the attribute of the complex operation.
+
+void complex_mul() {
+#pragma STDC CX_LIMITED_RANGE ON
+ _Complex float a;
+ _Complex float b;
+ _Complex float c = a * b;
+}
+
+// CIR-BEFORE: cir.func {{.*}}@_Z11complex_mulv()
+// CIR-BEFORE: %{{.*}} = cir.complex.fmul %{{.*}}, %{{.*}} range(basic) : !cir.complex<!cir.float> fenv<{{.*}}except_mode = unknown, strict_except = true>
+
+// CIR: cir.func {{.*}}@_Z11complex_mulv()
+// CIR: %[[A_ADDR:.*]] = cir.alloca "a" {{.*}} : !cir.ptr<!cir.complex<!cir.float>>
+// CIR: %[[B_ADDR:.*]] = cir.alloca "b" {{.*}} : !cir.ptr<!cir.complex<!cir.float>>
+// CIR: %[[C_ADDR:.*]] = cir.alloca "c" {{.*}} init : !cir.ptr<!cir.complex<!cir.float>>
+// CIR: %[[TMP_A:.*]] = cir.load {{.*}} %[[A_ADDR]] : !cir.ptr<!cir.complex<!cir.float>>, !cir.complex<!cir.float>
+// CIR: %[[TMP_B:.*]] = cir.load {{.*}} %[[B_ADDR]] : !cir.ptr<!cir.complex<!cir.float>>, !cir.complex<!cir.float>
+// CIR: %[[A_REAL:.*]] = cir.complex.real %[[TMP_A]] : !cir.complex<!cir.float> -> !cir.float
+// CIR: %[[A_IMAG:.*]] = cir.complex.imag %[[TMP_A]] : !cir.complex<!cir.float> -> !cir.float
+// CIR: %[[B_REAL:.*]] = cir.complex.real %[[TMP_B]] : !cir.complex<!cir.float> -> !cir.float
+// CIR: %[[B_IMAG:.*]] = cir.complex.imag %[[TMP_B]] : !cir.complex<!cir.float> -> !cir.float
+// CIR: %[[MUL_AC:.*]] = cir.fmul %[[A_REAL]], %[[B_REAL]] : !cir.float [[FENV:fenv<.*except_mode = unknown, strict_except = true>]]
+// CIR: %[[MUL_BD:.*]] = cir.fmul %[[A_IMAG]], %[[B_IMAG]] : !cir.float [[FENV]]
+// CIR: %[[MUL_AD:.*]] = cir.fmul %[[A_REAL]], %[[B_IMAG]] : !cir.float [[FENV]]
+// CIR: %[[MUL_BC:.*]] = cir.fmul %[[A_IMAG]], %[[B_REAL]] : !cir.float [[FENV]]
+// CIR: %[[RESULT_REAL:.*]] = cir.fsub %[[MUL_AC]], %[[MUL_BD]] : !cir.float [[FENV]]
+// CIR: %[[RESULT_IMAG:.*]] = cir.fadd %[[MUL_AD]], %[[MUL_BC]] : !cir.float [[FENV]]
+// CIR: %[[RESULT:.*]] = cir.complex.create %[[RESULT_REAL]], %[[RESULT_IMAG]] : !cir.float -> !cir.complex<!cir.float>
+// CIR: cir.store {{.*}} %[[RESULT]], %[[C_ADDR]] : !cir.complex<!cir.float>, !cir.ptr<!cir.complex<!cir.float>>
+
+// LLVM: define {{.*}} @_Z11complex_mulv()
+// LLVM: %[[A_ADDR:.*]] = alloca { float, float }, align 4
+// LLVM: %[[B_ADDR:.*]] = alloca { float, float }, align 4
+// LLVM: %[[C_ADDR:.*]] = alloca { float, float }, align 4
+// LLVM: %[[TMP_A:.*]] = load { float, float }, ptr %[[A_ADDR]], align 4
+// LLVM: %[[TMP_B:.*]] = load { float, float }, ptr %[[B_ADDR]], align 4
+// LLVM: %[[A_REAL:.*]] = extractvalue { float, float } %[[TMP_A]], 0
+// LLVM: %[[A_IMAG:.*]] = extractvalue { float, float } %[[TMP_A]], 1
+// LLVM: %[[B_REAL:.*]] = extractvalue { float, float } %[[TMP_B]], 0
+// LLVM: %[[B_IMAG:.*]] = extractvalue { float, float } %[[TMP_B]], 1
+// LLVM: %[[MUL_AC:.*]] = call float @llvm.experimental.constrained.fmul.f32(float %[[A_REAL]], float %[[B_REAL]], metadata !"round.tonearest", metadata !"fpexcept.strict")
+// LLVM: %[[MUL_BD:.*]] = call float @llvm.experimental.constrained.fmul.f32(float %[[A_IMAG]], float %[[B_IMAG]], metadata !"round.tonearest", metadata !"fpexcept.strict")
+// LLVM: %[[MUL_AD:.*]] = call float @llvm.experimental.constrained.fmul.f32(float %[[A_REAL]], float %[[B_IMAG]], metadata !"round.tonearest", metadata !"fpexcept.strict")
+// LLVM: %[[MUL_BC:.*]] = call float @llvm.experimental.constrained.fmul.f32(float %[[A_IMAG]], float %[[B_REAL]], metadata !"round.tonearest", metadata !"fpexcept.strict")
+// LLVM: %[[RESULT_REAL:.*]] = call float @llvm.experimental.constrained.fsub.f32(float %[[MUL_AC]], float %[[MUL_BD]], metadata !"round.tonearest", metadata !"fpexcept.strict")
+// LLVM: %[[RESULT_IMAG:.*]] = call float @llvm.experimental.constrained.fadd.f32(float %[[MUL_AD]], float %[[MUL_BC]], metadata !"round.tonearest", metadata !"fpexcept.strict")
+// LLVM: %[[TMP_RESULT:.*]] = insertvalue { float, float } {{.*}}, float %[[RESULT_REAL]], 0
+// LLVM: %[[RESULT:.*]] = insertvalue { float, float } %[[TMP_RESULT]], float %[[RESULT_IMAG]], 1
+// LLVM: store { float, float } %[[RESULT]], ptr %[[C_ADDR]], align 4
+
+// OGCG: define {{.*}} @_Z11complex_mulv()
+// OGCG: %[[A_ADDR:.*]] = alloca { float, float }, align 4
+// OGCG: %[[B_ADDR:.*]] = alloca { float, float }, align 4
+// OGCG: %[[C_ADDR:.*]] = alloca { float, float }, align 4
+// OGCG: %[[A_REAL_PTR:.*]] = getelementptr inbounds nuw { float, float }, ptr %[[A_ADDR]], i32 0, i32 0
+// OGCG: %[[A_REAL:.*]] = load float, ptr %[[A_REAL_PTR]], align 4
+// OGCG: %[[A_IMAG_PTR:.*]] = getelementptr inbounds nuw { float, float }, ptr %[[A_ADDR]], i32 0, i32 1
+// OGCG: %[[A_IMAG:.*]] = load float, ptr %[[A_IMAG_PTR]], align 4
+// OGCG: %[[B_REAL_PTR:.*]] = getelementptr inbounds nuw { float, float }, ptr %[[B_ADDR]], i32 0, i32 0
+// OGCG: %[[B_REAL:.*]] = load float, ptr %[[B_REAL_PTR]], align 4
+// OGCG: %[[B_IMAG_PTR:.*]] = getelementptr inbounds nuw { float, float }, ptr %[[B_ADDR]], i32 0, i32 1
+// OGCG: %[[B_IMAG:.*]] = load float, ptr %[[B_IMAG_PTR]], align 4
+// OGCG: %[[MUL_AC:.*]] = call float @llvm.experimental.constrained.fmul.f32(float %[[A_REAL]], float %[[B_REAL]], metadata !"round.tonearest", metadata !"fpexcept.strict")
+// OGCG: %[[MUL_BD:.*]] = call float @llvm.experimental.constrained.fmul.f32(float %[[A_IMAG]], float %[[B_IMAG]], metadata !"round.tonearest", metadata !"fpexcept.strict")
+// OGCG: %[[MUL_AD:.*]] = call float @llvm.experimental.constrained.fmul.f32(float %[[A_REAL]], float %[[B_IMAG]], metadata !"round.tonearest", metadata !"fpexcept.strict")
+// OGCG: %[[MUL_BC:.*]] = call float @llvm.experimental.constrained.fmul.f32(float %[[A_IMAG]], float %[[B_REAL]], metadata !"round.tonearest", metadata !"fpexcept.strict")
+// OGCG: %[[RESULT_REAL:.*]] = call float @llvm.experimental.constrained.fsub.f32(float %[[MUL_AC]], float %[[MUL_BD]], metadata !"round.tonearest", metadata !"fpexcept.strict")
+// OGCG: %[[RESULT_IMAG:.*]] = call float @llvm.experimental.constrained.fadd.f32(float %[[MUL_AD]], float %[[MUL_BC]], metadata !"round.tonearest", metadata !"fpexcept.strict")
+// OGCG: %[[C_REAL_PTR:.*]] = getelementptr inbounds nuw { float, float }, ptr %[[C_ADDR]], i32 0, i32 0
+// OGCG: %[[C_IMAG_PTR:.*]] = getelementptr inbounds nuw { float, float }, ptr %[[C_ADDR]], i32 0, i32 1
+// OGCG: store float %[[RESULT_REAL]], ptr %[[C_REAL_PTR]], align 4
+// OGCG: store float %[[RESULT_IMAG]], ptr %[[C_IMAG_PTR]], align 4
+
+void complex_div() {
+#pragma STDC CX_LIMITED_RANGE ON
+ _Complex float a;
+ _Complex float b;
+ _Complex float c = a / b;
+}
+
+// CIR-BEFORE: cir.func {{.*}}@_Z11complex_divv()
+// CIR-BEFORE: %{{.*}} = cir.complex.fdiv %{{.*}}, %{{.*}} range(basic) : !cir.complex<!cir.float> fenv<{{.*}}except_mode = unknown, strict_except = true>
+
+// CIR: cir.func {{.*}}@_Z11complex_divv()
+// CIR: %[[A_ADDR:.*]] = cir.alloca "a" {{.*}} : !cir.ptr<!cir.complex<!cir.float>>
+// CIR: %[[B_ADDR:.*]] = cir.alloca "b" {{.*}} : !cir.ptr<!cir.complex<!cir.float>>
+// CIR: %[[C_ADDR:.*]] = cir.alloca "c" {{.*}} init : !cir.ptr<!cir.complex<!cir.float>>
+// CIR: %[[TMP_A:.*]] = cir.load {{.*}} %[[A_ADDR]] : !cir.ptr<!cir.complex<!cir.float>>, !cir.complex<!cir.float>
+// CIR: %[[TMP_B:.*]] = cir.load {{.*}} %[[B_ADDR]] : !cir.ptr<!cir.complex<!cir.float>>, !cir.complex<!cir.float>
+// CIR: %[[A_REAL:.*]] = cir.complex.real %[[TMP_A]] : !cir.complex<!cir.float> -> !cir.float
+// CIR: %[[A_IMAG:.*]] = cir.complex.imag %[[TMP_A]] : !cir.complex<!cir.float> -> !cir.float
+// CIR: %[[B_REAL:.*]] = cir.complex.real %[[TMP_B]] : !cir.complex<!cir.float> -> !cir.float
+// CIR: %[[B_IMAG:.*]] = cir.complex.imag %[[TMP_B]] : !cir.complex<!cir.float> -> !cir.float
+// CIR: %[[MUL_AC:.*]] = cir.fmul %[[A_REAL]], %[[B_REAL]] : !cir.float [[FENV:fenv<.*except_mode = unknown, strict_except = true>]]
+// CIR: %[[MUL_BD:.*]] = cir.fmul %[[A_IMAG]], %[[B_IMAG]] : !cir.float [[FENV]]
+// CIR: %[[MUL_CC:.*]] = cir.fmul %[[B_REAL]], %[[B_REAL]] : !cir.float [[FENV]]
+// CIR: %[[MUL_DD:.*]] = cir.fmul %[[B_IMAG]], %[[B_IMAG]] : !cir.float [[FENV]]
+// CIR: %[[ADD_ACBD:.*]] = cir.fadd %[[MUL_AC]], %[[MUL_BD]] : !cir.float [[FENV]]
+// CIR: %[[ADD_CCDD:.*]] = cir.fadd %[[MUL_CC]], %[[MUL_DD]] : !cir.float [[FENV]]
+// CIR: %[[RESULT_REAL:.*]] = cir.fdiv %[[ADD_ACBD]], %[[ADD_CCDD]] : !cir.float [[FENV]]
+// CIR: %[[MUL_BC:.*]] = cir.fmul %[[A_IMAG]], %[[B_REAL]] : !cir.float [[FENV]]
+// CIR: %[[MUL_AD:.*]] = cir.fmul %[[A_REAL]], %[[B_IMAG]] : !cir.float [[FENV]]
+// CIR: %[[SUB_BCAD:.*]] = cir.fsub %[[MUL_BC]], %[[MUL_AD]] : !cir.float [[FENV]]
+// CIR: %[[RESULT_IMAG:.*]] = cir.fdiv %[[SUB_BCAD]], %[[ADD_CCDD]] : !cir.float [[FENV]]
+// CIR: %[[RESULT:.*]] = cir.complex.create %[[RESULT_REAL]], %[[RESULT_IMAG]] : !cir.float -> !cir.complex<!cir.float>
+// CIR: cir.store {{.*}} %[[RESULT]], %[[C_ADDR]] : !cir.complex<!cir.float>, !cir.ptr<!cir.complex<!cir.float>>
+
+// LLVM: define {{.*}} @_Z11complex_divv()
+// LLVM: %[[A_ADDR:.*]] = alloca { float, float }, align 4
+// LLVM: %[[B_ADDR:.*]] = alloca { float, float }, align 4
+// LLVM: %[[C_ADDR:.*]] = alloca { float, float }, align 4
+// LLVM: %[[TMP_A:.*]] = load { float, float }, ptr %[[A_ADDR]], align 4
+// LLVM: %[[TMP_B:.*]] = load { float, float }, ptr %[[B_ADDR]], align 4
+// LLVM: %[[A_REAL:.*]] = extractvalue { float, float } %[[TMP_A]], 0
+// LLVM: %[[A_IMAG:.*]] = extractvalue { float, float } %[[TMP_A]], 1
+// LLVM: %[[B_REAL:.*]] = extractvalue { float, float } %[[TMP_B]], 0
+// LLVM: %[[B_IMAG:.*]] = extractvalue { float, float } %[[TMP_B]], 1
+// LLVM: %[[MUL_AC:.*]] = call float @llvm.experimental.constrained.fmul.f32(float %[[A_REAL]], float %[[B_REAL]], metadata !"round.tonearest", metadata !"fpexcept.strict")
+// LLVM: %[[MUL_BD:.*]] = call float @llvm.experimental.constrained.fmul.f32(float %[[A_IMAG]], float %[[B_IMAG]], metadata !"round.tonearest", metadata !"fpexcept.strict")
+// LLVM: %[[MUL_CC:.*]] = call float @llvm.experimental.constrained.fmul.f32(float %[[B_REAL]], float %[[B_REAL]], metadata !"round.tonearest", metadata !"fpexcept.strict")
+// LLVM: %[[MUL_DD:.*]] = call float @llvm.experimental.constrained.fmul.f32(float %[[B_IMAG]], float %[[B_IMAG]], metadata !"round.tonearest", metadata !"fpexcept.strict")
+// LLVM: %[[ADD_ACBD:.*]] = call float @llvm.experimental.constrained.fadd.f32(float %[[MUL_AC]], float %[[MUL_BD]], metadata !"round.tonearest", metadata !"fpexcept.strict")
+// LLVM: %[[ADD_CCDD:.*]] = call float @llvm.experimental.constrained.fadd.f32(float %[[MUL_CC]], float %[[MUL_DD]], metadata !"round.tonearest", metadata !"fpexcept.strict")
+// LLVM: %[[RESULT_REAL:.*]] = call float @llvm.experimental.constrained.fdiv.f32(float %[[ADD_ACBD]], float %[[ADD_CCDD]], metadata !"round.tonearest", metadata !"fpexcept.strict")
+// LLVM: %[[MUL_BC:.*]] = call float @llvm.experimental.constrained.fmul.f32(float %[[A_IMAG]], float %[[B_REAL]], metadata !"round.tonearest", metadata !"fpexcept.strict")
+// LLVM: %[[MUL_AD:.*]] = call float @llvm.experimental.constrained.fmul.f32(float %[[A_REAL]], float %[[B_IMAG]], metadata !"round.tonearest", metadata !"fpexcept.strict")
+// LLVM: %[[SUB_BCAD:.*]] = call float @llvm.experimental.constrained.fsub.f32(float %[[MUL_BC]], float %[[MUL_AD]], metadata !"round.tonearest", metadata !"fpexcept.strict")
+// LLVM: %[[RESULT_IMAG:.*]] = call float @llvm.experimental.constrained.fdiv.f32(float %[[SUB_BCAD]], float %[[ADD_CCDD]], metadata !"round.tonearest", metadata !"fpexcept.strict")
+// LLVM: %[[TMP_RESULT:.*]] = insertvalue { float, float } {{.*}}, float %[[RESULT_REAL]], 0
+// LLVM: %[[RESULT:.*]] = insertvalue { float, float } %[[TMP_RESULT]], float %[[RESULT_IMAG]], 1
+// LLVM: store { float, float } %[[RESULT]], ptr %[[C_ADDR]], align 4
+
+// OGCG: define {{.*}} @_Z11complex_divv()
+// OGCG: %[[A_ADDR:.*]] = alloca { float, float }, align 4
+// OGCG: %[[B_ADDR:.*]] = alloca { float, float }, align 4
+// OGCG: %[[C_ADDR:.*]] = alloca { float, float }, align 4
+// OGCG: %[[A_REAL_PTR:.*]] = getelementptr inbounds nuw { float, float }, ptr %[[A_ADDR]], i32 0, i32 0
+// OGCG: %[[A_REAL:.*]] = load float, ptr %[[A_REAL_PTR]], align 4
+// OGCG: %[[A_IMAG_PTR:.*]] = getelementptr inbounds nuw { float, float }, ptr %[[A_ADDR]], i32 0, i32 1
+// OGCG: %[[A_IMAG:.*]] = load float, ptr %[[A_IMAG_PTR]], align 4
+// OGCG: %[[B_REAL_PTR:.*]] = getelementptr inbounds nuw { float, float }, ptr %[[B_ADDR]], i32 0, i32 0
+// OGCG: %[[B_REAL:.*]] = load float, ptr %[[B_REAL_PTR]], align 4
+// OGCG: %[[B_IMAG_PTR:.*]] = getelementptr inbounds nuw { float, float }, ptr %[[B_ADDR]], i32 0, i32 1
+// OGCG: %[[B_IMAG:.*]] = load float, ptr %[[B_IMAG_PTR]], align 4
+// OGCG: %[[MUL_AC:.*]] = call float @llvm.experimental.constrained.fmul.f32(float %[[A_REAL]], float %[[B_REAL]], metadata !"round.tonearest", metadata !"fpexcept.strict")
+// OGCG: %[[MUL_BD:.*]] = call float @llvm.experimental.constrained.fmul.f32(float %[[A_IMAG]], float %[[B_IMAG]], metadata !"round.tonearest", metadata !"fpexcept.strict")
+// OGCG: %[[ADD_ACBD:.*]] = call float @llvm.experimental.constrained.fadd.f32(float %[[MUL_AC]], float %[[MUL_BD]], metadata !"round.tonearest", metadata !"fpexcept.strict")
+// OGCG: %[[MUL_CC:.*]] = call float @llvm.experimental.constrained.fmul.f32(float %[[B_REAL]], float %[[B_REAL]], metadata !"round.tonearest", metadata !"fpexcept.strict")
+// OGCG: %[[MUL_DD:.*]] = call float @llvm.experimental.constrained.fmul.f32(float %[[B_IMAG]], float %[[B_IMAG]], metadata !"round.tonearest", metadata !"fpexcept.strict")
+// OGCG: %[[ADD_CCDD:.*]] = call float @llvm.experimental.constrained.fadd.f32(float %[[MUL_CC]], float %[[MUL_DD]], metadata !"round.tonearest", metadata !"fpexcept.strict")
+// OGCG: %[[MUL_BC:.*]] = call float @llvm.experimental.constrained.fmul.f32(float %[[A_IMAG]], float %[[B_REAL]], metadata !"round.tonearest", metadata !"fpexcept.strict")
+// OGCG: %[[MUL_AD:.*]] = call float @llvm.experimental.constrained.fmul.f32(float %[[A_REAL]], float %[[B_IMAG]], metadata !"round.tonearest", metadata !"fpexcept.strict")
+// OGCG: %[[SUB_BCAD:.*]] = call float @llvm.experimental.constrained.fsub.f32(float %[[MUL_BC]], float %[[MUL_AD]], metadata !"round.tonearest", metadata !"fpexcept.strict")
+// OGCG: %[[RESULT_REAL:.*]] = call float @llvm.experimental.constrained.fdiv.f32(float %[[ADD_ACBD]], float %[[ADD_CCDD]], metadata !"round.tonearest", metadata !"fpexcept.strict")
+// OGCG: %[[RESULT_IMAG:.*]] = call float @llvm.experimental.constrained.fdiv.f32(float %[[SUB_BCAD]], float %[[ADD_CCDD]], metadata !"round.tonearest", metadata !"fpexcept.strict")
+// OGCG: %[[C_REAL_PTR:.*]] = getelementptr inbounds nuw { float, float }, ptr %[[C_ADDR]], i32 0, i32 0
+// OGCG: %[[C_IMAG_PTR:.*]] = getelementptr inbounds nuw { float, float }, ptr %[[C_ADDR]], i32 0, i32 1
+// OGCG: store float %[[RESULT_REAL]], ptr %[[C_REAL_PTR]], align 4
+// OGCG: store float %[[RESULT_IMAG]], ptr %[[C_IMAG_PTR]], align 4
diff --git a/clang/test/CIR/Transforms/complex-mul-div-fenv-effects.cir b/clang/test/CIR/Transforms/complex-mul-div-fenv-effects.cir
new file mode 100644
index 00000000000000..106a5a972ec1f1
--- /dev/null
+++ b/clang/test/CIR/Transforms/complex-mul-div-fenv-effects.cir
@@ -0,0 +1,27 @@
+// RUN: cir-opt %s -canonicalize -o - | FileCheck %s
+
+// Without a `fenv` attribute, complex FP multiplication and division have no
+// memory effects, so unused results are erased. A `fenv` attribute gives them
+// read and write effects on the floating-point environment, which keeps them
+// alive.
+
+!complex_f32 = !cir.complex<!cir.float>
+
+// CHECK-LABEL: @dead_unconstrained_is_removed
+// CHECK-NOT: cir.complex.fmul
+// CHECK-NOT: cir.complex.fdiv
+// CHECK: cir.return
+cir.func @dead_unconstrained_is_removed(%a: !complex_f32, %b: !complex_f32) {
+ %0 = cir.complex.fmul %a, %b range(full) : !complex_f32
+ %1 = cir.complex.fdiv %a, %b range(full) : !complex_f32
+ cir.return
+}
+
+// CHECK-LABEL: @dead_constrained_is_not_removed
+// CHECK: cir.complex.fmul %{{.*}}, %{{.*}} range(full) : !cir.complex<!cir.float> fenv<{{.*}}strict_except = true>
+// CHECK: cir.complex.fdiv %{{.*}}, %{{.*}} range(full) : !cir.complex<!cir.float> fenv<{{.*}}strict_except = true>
+cir.func @dead_constrained_is_not_removed(%a: !complex_f32, %b: !complex_f32) {
+ %0 = cir.complex.fmul %a, %b range(full) : !complex_f32 fenv<dynamic_rounding_mode = unknown, except_mode = unknown, strict_except = true>
+ %1 = cir.complex.fdiv %a, %b range(full) : !complex_f32 fenv<dynamic_rounding_mode = unknown, except_mode = unknown, strict_except = true>
+ cir.return
+}
diff --git a/clang/test/CIR/Transforms/lowering-prepare-complex-fenv.cir b/clang/test/CIR/Transforms/lowering-prepare-complex-fenv.cir
new file mode 100644
index 00000000000000..3af1b5dc71ba57
--- /dev/null
+++ b/clang/test/CIR/Transforms/lowering-prepare-complex-fenv.cir
@@ -0,0 +1,94 @@
+// RUN: cir-opt %s --cir-lowering-prepare -o - | FileCheck %s \
+// RUN: -DSTRICT="fenv<dynamic_rounding_mode = unknown, except_mode = unknown, strict_except = true>" \
+// RUN: -DUPWARD="fenv<dynamic_rounding_mode = upward, except_mode = unknown, strict_except = true>" \
+// RUN: --implicit-check-not="{{cir.(f(add|sub|mul|div|cmp)|cast floating) .*(float|double|f80>)$}}"
+
+// LoweringPrepare expands complex FP multiplication and division into scalar
+// operations. The scalar arithmetic, comparisons and conversions carry the
+// `fenv` attribute of the complex operation they come from. The implicit
+// check rejects one whose line ends at its type, that is, one without the
+// attribute.
+
+!complex_f32 = !cir.complex<!cir.float>
+!complex_f80 = !cir.complex<!cir.long_double<!cir.f80>>
+
+module attributes {cir.triple = "x86_64-unknown-linux-gnu"} {
+
+// CHECK-LABEL: cir.func @fmul_full(
+// CHECK-COUNT-4: = cir.fmul %{{.*}}, %{{.*}} : !cir.float [[STRICT]]
+// CHECK: = cir.fsub %{{.*}}, %{{.*}} : !cir.float [[STRICT]]
+// CHECK: = cir.fadd %{{.*}}, %{{.*}} : !cir.float [[STRICT]]
+// CHECK-COUNT-2: = cir.fcmp uno %{{.*}}, %{{.*}} : !cir.float [[STRICT]]
+// CHECK: cir.call @__mulsc3(
+cir.func @fmul_full(%a: !complex_f32, %b: !complex_f32) -> !complex_f32 {
+ %0 = cir.complex.fmul %a, %b range(full) : !complex_f32 fenv<dynamic_rounding_mode = unknown, except_mode = unknown, strict_except = true>
+ cir.return %0 : !complex_f32
+}
+
+// CHECK-LABEL: cir.func @fmul_basic(
+// CHECK-COUNT-4: = cir.fmul %{{.*}}, %{{.*}} : !cir.float [[STRICT]]
+// CHECK: = cir.fsub %{{.*}}, %{{.*}} : !cir.float [[STRICT]]
+// CHECK: = cir.fadd %{{.*}}, %{{.*}} : !cir.float [[STRICT]]
+cir.func @fmul_basic(%a: !complex_f32, %b: !complex_f32) -> !complex_f32 {
+ %0 = cir.complex.fmul %a, %b range(basic) : !complex_f32 fenv<dynamic_rounding_mode = unknown, except_mode = unknown, strict_except = true>
+ cir.return %0 : !complex_f32
+}
+
+// CHECK-LABEL: cir.func @fdiv_full(
+// CHECK: cir.call @__divsc3(
+cir.func @fdiv_full(%a: !complex_f32, %b: !complex_f32) -> !complex_f32 {
+ %0 = cir.complex.fdiv %a, %b range(full) : !complex_f32 fenv<dynamic_rounding_mode = unknown, except_mode = unknown, strict_except = true>
+ cir.return %0 : !complex_f32
+}
+
+// CHECK-LABEL: cir.func @fdiv_basic(
+// CHECK-COUNT-11: = cir.f{{mul|add|sub|div}} %{{.*}}, %{{.*}} : !cir.float [[STRICT]]
+cir.func @fdiv_basic(%a: !complex_f32, %b: !complex_f32) -> !complex_f32 {
+ %0 = cir.complex.fdiv %a, %b range(basic) : !complex_f32 fenv<dynamic_rounding_mode = unknown, except_mode = unknown, strict_except = true>
+ cir.return %0 : !complex_f32
+}
+
+// The range check is a quiet comparison. `cir.fabs` cannot raise an exception
+// and takes no attribute.
+
+// CHECK-LABEL: cir.func @fdiv_improved(
+// CHECK-COUNT-2: = cir.fabs %{{.*}} : !cir.float{{$}}
+// CHECK: = cir.fcmp oge %{{.*}}, %{{.*}} : !cir.float [[STRICT]]
+// CHECK-COUNT-18: = cir.f{{mul|add|sub|div}} %{{.*}}, %{{.*}} : !cir.float [[STRICT]]
+cir.func @fdiv_improved(%a: !complex_f32, %b: !complex_f32) -> !complex_f32 {
+ %0 = cir.complex.fdiv %a, %b range(improved) : !complex_f32 fenv<dynamic_rounding_mode = unknown, except_mode = unknown, strict_except = true>
+ cir.return %0 : !complex_f32
+}
+
+// CHECK-LABEL: cir.func @fdiv_promoted(
+// CHECK-COUNT-4: = cir.cast floating %{{.*}} : !cir.float -> !cir.double [[STRICT]]
+// CHECK-COUNT-11: = cir.f{{mul|add|sub|div}} %{{.*}}, %{{.*}} : !cir.double [[STRICT]]
+// CHECK-COUNT-2: = cir.cast floating %{{.*}} : !cir.double -> !cir.float [[STRICT]]
+cir.func @fdiv_promoted(%a: !complex_f32, %b: !complex_f32) -> !complex_f32 {
+ %0 = cir.complex.fdiv %a, %b range(promoted) : !complex_f32 fenv<dynamic_rounding_mode = unknown, except_mode = unknown, strict_except = true>
+ cir.return %0 : !complex_f32
+}
+
+// x87 long double has no wider type to promote to, so this falls back to
+// range reduction.
+
+// CHECK-LABEL: cir.func @fdiv_promoted_fallback(
+// CHECK: = cir.fcmp oge %{{.*}}, %{{.*}} : !cir.long_double<!cir.f80> [[STRICT]]
+// CHECK-COUNT-18: = cir.f{{mul|add|sub|div}} %{{.*}}, %{{.*}} : !cir.long_double<!cir.f80> [[STRICT]]
+cir.func @fdiv_promoted_fallback(%a: !complex_f80, %b: !complex_f80) -> !complex_f80 {
+ %0 = cir.complex.fdiv %a, %b range(promoted) : !complex_f80 fenv<dynamic_rounding_mode = unknown, except_mode = unknown, strict_except = true>
+ cir.return %0 : !complex_f80
+}
+
+// Each expansion uses the attribute of its own operation.
+
+// CHECK-LABEL: cir.func @two_environments(
+// CHECK-COUNT-6: = cir.f{{mul|add|sub}} %{{.*}}, %{{.*}} : !cir.float [[STRICT]]
+// CHECK-COUNT-11: = cir.f{{mul|add|sub|div}} %{{.*}}, %{{.*}} : !cir.float [[UPWARD]]
+cir.func @two_environments(%a: !complex_f32, %b: !complex_f32) -> !complex_f32 {
+ %0 = cir.complex.fmul %a, %b range(basic) : !complex_f32 fenv<dynamic_rounding_mode = unknown, except_mode = unknown, strict_except = true>
+ %1 = cir.complex.fdiv %0, %b range(basic) : !complex_f32 fenv<dynamic_rounding_mode = upward, except_mode = unknown, strict_except = true>
+ cir.return %1 : !complex_f32
+}
+
+}
>From 2efc4e2f0c26a2540e77bf648f0359527a293488 Mon Sep 17 00:00:00 2001
From: Henrich Lauko <hlauko at nvidia.com>
Date: Wed, 25 Nov 2026 12:45:16 +0000
Subject: [PATCH 2/3] [CIR] Keep complex and bool casts constrained in strict
FP functions
In a strictfp function ClangIR emitted plain `fpext`, `fptrunc`,
`fptosi`, `sitofp`, `uitofp` and `fcmp une` for casts between complex
types and for conversions between floating-point values and bool, where
classic codegen emits constrained intrinsics. CIRGen created the
complex casts and `float_to_bool` without the `fenv` attribute,
LoweringPrepare dropped the attribute when it expanded a complex cast,
and the LLVM lowering of `float_to_bool` and `bool_to_float` ignored
it.
`createCast` now takes an optional `fenv` attribute. CIRGen passes the
current floating-point environment for `float_to_bool` and for the
complex cast kinds that convert floating-point values. The kinds that
only select or pack a part, `float_to_complex` and
`float_complex_to_real`, get none, and the verifier no longer accepts
the attribute on them. LoweringPrepare passes the attribute of a
complex cast to the scalar casts of its expansion. With `fenv`,
`float_to_bool` lowers to the quiet constrained `fcmp` and
`bool_to_float` to the constrained `uitofp`.
For these casts the LLVM IR now has the constrained intrinsics and
metadata of classic codegen. New tests check the complex and bool casts
under -ffp-exception-behavior=strict and FENV_ACCESS, against classic
codegen, through LoweringPrepare, and in the LLVM lowering.
Assisted-by: Claude Code (Fable 5.2).
---
.../CIR/Dialect/Builder/CIRBaseBuilder.h | 14 +-
clang/include/clang/CIR/Dialect/IR/CIROps.td | 11 +-
clang/lib/CIR/CodeGen/CIRGenExprComplex.cpp | 14 +-
clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp | 17 +-
clang/lib/CIR/Dialect/IR/CIRDialect.cpp | 5 +-
.../Dialect/Transforms/LoweringPrepare.cpp | 14 +-
.../CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp | 182 ++++++++++--------
.../CIR/CodeGen/bool-to-float-strict-fp.cpp | 40 ++++
.../CIR/CodeGen/complex-cast-fenv-access.c | 125 ++++++++++++
clang/test/CIR/CodeGen/complex-strict-fp.cpp | 88 +++++++++
clang/test/CIR/IR/invalid-cast.cir | 20 ++
clang/test/CIR/Lowering/fenv.cir | 32 +++
.../lowering-prepare-complex-cast-fenv.cir | 66 +++++++
13 files changed, 523 insertions(+), 105 deletions(-)
create mode 100644 clang/test/CIR/CodeGen/bool-to-float-strict-fp.cpp
create mode 100644 clang/test/CIR/CodeGen/complex-cast-fenv-access.c
create mode 100644 clang/test/CIR/Transforms/lowering-prepare-complex-cast-fenv.cir
diff --git a/clang/include/clang/CIR/Dialect/Builder/CIRBaseBuilder.h b/clang/include/clang/CIR/Dialect/Builder/CIRBaseBuilder.h
index f01dd37cf276e4..c3fa3502d371d9 100644
--- a/clang/include/clang/CIR/Dialect/Builder/CIRBaseBuilder.h
+++ b/clang/include/clang/CIR/Dialect/Builder/CIRBaseBuilder.h
@@ -689,18 +689,22 @@ class CIRBaseBuilderTy : public mlir::OpBuilder {
// Cast/Conversion Operators
//===--------------------------------------------------------------------===//
+ /// \p fenv is the floating-point environment of a cast that converts
+ /// floating-point values. It is null for an unconstrained cast and for a
+ /// cast kind that does no floating-point conversion.
mlir::Value createCast(mlir::Location loc, cir::CastKind kind,
- mlir::Value src, mlir::Type newTy) {
+ mlir::Value src, mlir::Type newTy,
+ cir::FenvAttr fenv = {}) {
if (newTy == src.getType())
return src;
- return cir::CastOp::create(*this, loc, newTy, kind, src);
+ return cir::CastOp::create(*this, loc, newTy, kind, src, fenv);
}
- mlir::Value createCast(cir::CastKind kind, mlir::Value src,
- mlir::Type newTy) {
+ mlir::Value createCast(cir::CastKind kind, mlir::Value src, mlir::Type newTy,
+ cir::FenvAttr fenv = {}) {
if (newTy == src.getType())
return src;
- return createCast(src.getLoc(), kind, src, newTy);
+ return createCast(src.getLoc(), kind, src, newTy, fenv);
}
// Creates a cast from bool or int to an integer type.
diff --git a/clang/include/clang/CIR/Dialect/IR/CIROps.td b/clang/include/clang/CIR/Dialect/IR/CIROps.td
index 2f7eb4aa7ed88a..780d26da591e69 100644
--- a/clang/include/clang/CIR/Dialect/IR/CIROps.td
+++ b/clang/include/clang/CIR/Dialect/IR/CIROps.td
@@ -358,11 +358,12 @@ def CIR_CastOp : CIR_Op<"cast", !listconcat([
- `bool_to_float`
The optional `fenv` attribute describes constraints on the floating-point
- handling of the operation. It is only valid for floating-point cast kinds:
- `floating`, `int_to_float`, `float_to_int`, `float_to_bool`,
- `bool_to_float`, `float_to_complex`, `float_complex_to_real`,
- `float_complex_to_bool`, `float_complex`, `float_complex_to_int_complex`,
- and `int_complex_to_float_complex`.
+ handling of the operation. It is only valid for the cast kinds that convert
+ floating-point values: `floating`, `int_to_float`, `float_to_int`,
+ `float_to_bool`, `bool_to_float`, `float_complex_to_bool`, `float_complex`,
+ `float_complex_to_int_complex`, and `int_complex_to_float_complex`.
+ `float_to_complex` and `float_complex_to_real` only pack or select a part
+ of a complex value and take no attribute.
Example:
diff --git a/clang/lib/CIR/CodeGen/CIRGenExprComplex.cpp b/clang/lib/CIR/CodeGen/CIRGenExprComplex.cpp
index be645e1e931da1..258abf210bd3a5 100644
--- a/clang/lib/CIR/CodeGen/CIRGenExprComplex.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenExprComplex.cpp
@@ -431,8 +431,14 @@ mlir::Value ComplexExprEmitter::emitComplexToComplexCast(mlir::Value val,
else
llvm_unreachable("unexpected src type or dest type");
+ // Only the conversion between integer element types is independent of the
+ // floating-point environment.
+ cir::FenvAttr fenv;
+ if (castOpKind != cir::CastKind::int_complex)
+ fenv = builder.getConstrainedFPAttr();
+
return builder.createCast(cgf.getLoc(loc), castOpKind, val,
- cgf.convertType(destType));
+ cgf.convertType(destType), fenv);
}
mlir::Value ComplexExprEmitter::emitScalarToComplexCast(mlir::Value val,
@@ -769,7 +775,8 @@ mlir::Value CIRGenFunction::emitUnPromotedValue(mlir::Value result,
assert(!mlir::cast<cir::ComplexType>(result.getType()).isIntegerComplex() &&
"integral complex will never be promoted");
return builder.createCast(cir::CastKind::float_complex, result,
- convertType(unPromotionType));
+ convertType(unPromotionType),
+ builder.getConstrainedFPAttr());
}
mlir::Value CIRGenFunction::emitPromotedValue(mlir::Value result,
@@ -777,7 +784,8 @@ mlir::Value CIRGenFunction::emitPromotedValue(mlir::Value result,
assert(!mlir::cast<cir::ComplexType>(result.getType()).isIntegerComplex() &&
"integral complex will never be promoted");
return builder.createCast(cir::CastKind::float_complex, result,
- convertType(promotionType));
+ convertType(promotionType),
+ builder.getConstrainedFPAttr());
}
mlir::Value ComplexExprEmitter::emitPromoted(const Expr *e,
diff --git a/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp b/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp
index c49459c5020fbe..57cd4a1be5e031 100644
--- a/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp
@@ -450,7 +450,8 @@ class ScalarExprEmitter : public StmtVisitor<ScalarExprEmitter, mlir::Value> {
mlir::Value emitFloatToBoolConversion(mlir::Value src, mlir::Location loc) {
cir::BoolType boolTy = builder.getBoolTy();
return cir::CastOp::create(builder, loc, boolTy,
- cir::CastKind::float_to_bool, src);
+ cir::CastKind::float_to_bool, src,
+ builder.getConstrainedFPAttr());
}
mlir::Value emitIntToBoolConversion(mlir::Value srcVal, mlir::Location loc) {
@@ -1804,6 +1805,9 @@ mlir::Value ScalarExprEmitter::emitComplexToScalarConversion(mlir::Location lov,
CastKind kind,
QualType destTy) {
cir::CastKind castOpKind;
+ // Only the conversion of a floating-point complex value to bool compares
+ // floating-point values. The conversions to the real part only select it.
+ cir::FenvAttr fenv;
switch (kind) {
case CK_FloatingComplexToReal:
castOpKind = cir::CastKind::float_complex_to_real;
@@ -1813,6 +1817,7 @@ mlir::Value ScalarExprEmitter::emitComplexToScalarConversion(mlir::Location lov,
break;
case CK_FloatingComplexToBoolean:
castOpKind = cir::CastKind::float_complex_to_bool;
+ fenv = builder.getConstrainedFPAttr();
break;
case CK_IntegralComplexToBoolean:
castOpKind = cir::CastKind::int_complex_to_bool;
@@ -1821,7 +1826,8 @@ mlir::Value ScalarExprEmitter::emitComplexToScalarConversion(mlir::Location lov,
llvm_unreachable("invalid complex-to-scalar cast kind");
}
- return builder.createCast(lov, castOpKind, value, cgf.convertType(destTy));
+ return builder.createCast(lov, castOpKind, value, cgf.convertType(destTy),
+ fenv);
}
mlir::Value ScalarExprEmitter::emitPromoted(const Expr *e,
@@ -3201,7 +3207,12 @@ mlir::Value CIRGenFunction::emitComplexToScalarConversion(mlir::Value src,
auto kind = complexElemTy->isFloatingType()
? cir::CastKind::float_complex_to_bool
: cir::CastKind::int_complex_to_bool;
- return builder.createCast(getLoc(loc), kind, src, convertType(dstTy));
+ // Only the comparison of floating-point values depends on the
+ // floating-point environment.
+ cir::FenvAttr fenv;
+ if (complexElemTy->isFloatingType())
+ fenv = builder.getConstrainedFPAttr();
+ return builder.createCast(getLoc(loc), kind, src, convertType(dstTy), fenv);
}
auto kind = complexElemTy->isFloatingType()
diff --git a/clang/lib/CIR/Dialect/IR/CIRDialect.cpp b/clang/lib/CIR/Dialect/IR/CIRDialect.cpp
index e81db4631eeef4..2954674117f9fb 100644
--- a/clang/lib/CIR/Dialect/IR/CIRDialect.cpp
+++ b/clang/lib/CIR/Dialect/IR/CIRDialect.cpp
@@ -1033,6 +1033,9 @@ OpFoldResult cir::ConstantOp::fold(FoldAdaptor /*adaptor*/) {
// CastOp
//===----------------------------------------------------------------------===//
+/// Returns true for the cast kinds that convert floating-point values.
+/// `float_to_complex` and `float_complex_to_real` only pack or select a part
+/// of a complex value, so they have no floating-point operation to constrain.
static bool isFloatingPointCastKind(cir::CastKind kind) {
switch (kind) {
case cir::CastKind::floating:
@@ -1040,8 +1043,6 @@ static bool isFloatingPointCastKind(cir::CastKind kind) {
case cir::CastKind::float_to_int:
case cir::CastKind::float_to_bool:
case cir::CastKind::bool_to_float:
- case cir::CastKind::float_to_complex:
- case cir::CastKind::float_complex_to_real:
case cir::CastKind::float_complex_to_bool:
case cir::CastKind::float_complex:
case cir::CastKind::float_complex_to_int_complex:
diff --git a/clang/lib/CIR/Dialect/Transforms/LoweringPrepare.cpp b/clang/lib/CIR/Dialect/Transforms/LoweringPrepare.cpp
index e41586f046c221..cd2123d602cdfa 100644
--- a/clang/lib/CIR/Dialect/Transforms/LoweringPrepare.cpp
+++ b/clang/lib/CIR/Dialect/Transforms/LoweringPrepare.cpp
@@ -712,10 +712,13 @@ static mlir::Value lowerComplexToScalarCast(mlir::MLIRContext &ctx,
mlir::Value srcImag = builder.createComplexImag(op.getLoc(), src);
cir::BoolType boolTy = builder.getBoolTy();
+ // The scalar casts get the `fenv` attribute of the complex cast, so a
+ // constrained cast expands into constrained ones.
+ cir::FenvAttr fenv = op.getFenvAttr();
mlir::Value srcRealToBool =
- builder.createCast(op.getLoc(), elemToBoolKind, srcReal, boolTy);
+ builder.createCast(op.getLoc(), elemToBoolKind, srcReal, boolTy, fenv);
mlir::Value srcImagToBool =
- builder.createCast(op.getLoc(), elemToBoolKind, srcImag, boolTy);
+ builder.createCast(op.getLoc(), elemToBoolKind, srcImag, boolTy, fenv);
return builder.createLogicalOr(op.getLoc(), srcRealToBool, srcImagToBool);
}
@@ -732,10 +735,13 @@ static mlir::Value lowerComplexToComplexCast(mlir::MLIRContext &ctx,
mlir::Value srcReal = builder.createComplexReal(op.getLoc(), src);
mlir::Value srcImag = builder.createComplexImag(op.getLoc(), src);
+ // The scalar casts get the `fenv` attribute of the complex cast, so a
+ // constrained cast expands into constrained ones.
+ cir::FenvAttr fenv = op.getFenvAttr();
mlir::Value dstReal = builder.createCast(op.getLoc(), scalarCastKind, srcReal,
- dstComplexElemTy);
+ dstComplexElemTy, fenv);
mlir::Value dstImag = builder.createCast(op.getLoc(), scalarCastKind, srcImag,
- dstComplexElemTy);
+ dstComplexElemTy, fenv);
return builder.createComplexCreate(op.getLoc(), dstReal, dstImag);
}
diff --git a/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp b/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
index e0dd52a9268739..a06bc1f4ea8e75 100644
--- a/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
+++ b/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
@@ -702,6 +702,89 @@ static mlir::Value createConstrainedFPIntrinsicCall(
return intrinsic->getResult(0);
}
+static llvm::StringRef
+convertCmpKindToConstrainedFCmpPredicate(cir::CmpOpKind kind) {
+ using CIR = cir::CmpOpKind;
+ switch (kind) {
+ case CIR::eq:
+ return "oeq";
+ case CIR::ne:
+ return "une";
+ case CIR::lt:
+ return "olt";
+ case CIR::le:
+ return "ole";
+ case CIR::gt:
+ return "ogt";
+ case CIR::ge:
+ return "oge";
+ case CIR::one:
+ return "one";
+ case CIR::uno:
+ return "uno";
+ }
+ llvm_unreachable("Unknown CmpOpKind");
+}
+
+static llvm::StringRef
+convertCmpKindToConstrainedFCmpPredicate(cir::FCmpOpKind kind) {
+ using CIR = cir::FCmpOpKind;
+ switch (kind) {
+ case CIR::_false:
+ return "false";
+ case CIR::oeq:
+ return "oeq";
+ case CIR::ogt:
+ return "ogt";
+ case CIR::oge:
+ return "oge";
+ case CIR::olt:
+ return "olt";
+ case CIR::ole:
+ return "ole";
+ case CIR::one:
+ return "one";
+ case CIR::ord:
+ return "ord";
+ case CIR::ueq:
+ return "ueq";
+ case CIR::ugt:
+ return "ugt";
+ case CIR::uge:
+ return "uge";
+ case CIR::ult:
+ return "ult";
+ case CIR::ule:
+ return "ule";
+ case CIR::une:
+ return "une";
+ case CIR::uno:
+ return "uno";
+ case CIR::_true:
+ return "true";
+ }
+ llvm_unreachable("Unknown FCmpOpKind");
+}
+
+template <typename OpKindTy>
+static mlir::LLVM::CallIntrinsicOp
+createConstrainedFCmpCall(mlir::ConversionPatternRewriter &rewriter,
+ mlir::Location loc, mlir::Value lhs, mlir::Value rhs,
+ OpKindTy kind, bool isSignaling, cir::FenvAttr fenv,
+ mlir::Type llvmResTy) {
+ llvm::SmallVector<mlir::Value, 4> callOperands = {
+ lhs, rhs,
+ createFenvMetadataValue(rewriter, loc,
+ convertCmpKindToConstrainedFCmpPredicate(kind)),
+ createFenvMetadataValue(rewriter, loc,
+ getConstrainedExceptMetadata(fenv))};
+ llvm::StringRef intrinsicName = isSignaling
+ ? "llvm.experimental.constrained.fcmps"
+ : "llvm.experimental.constrained.fcmp";
+ return createCallLLVMIntrinsicOp(rewriter, loc, intrinsicName, llvmResTy,
+ callOperands);
+}
+
template <typename LLVMOp>
mlir::LogicalResult lowerFPOp(mlir::Operation *op, mlir::ValueRange operands,
cir::FastMathFlagsAttr fastmath,
@@ -2072,6 +2155,17 @@ mlir::LogicalResult CIRToLLVMCastOpLowering::matchAndRewrite(
rewriter, castOp.getLoc(), llvmSrcVal.getType(),
rewriter.getZeroAttr(llvmSrcVal.getType()));
+ // A constrained cast is a quiet comparison, which raises no exception for
+ // a quiet NaN.
+ if (cir::FenvAttr fenv = castOp.getFenvAttr()) {
+ mlir::LLVM::CallIntrinsicOp call = createConstrainedFCmpCall(
+ rewriter, castOp.getLoc(), llvmSrcVal, zeroFloat,
+ cir::FCmpOpKind::une, /*isSignaling=*/false, fenv,
+ getTypeConverter()->convertType(castOp.getType()));
+ rewriter.replaceOp(castOp, call.getResult(0));
+ return mlir::success();
+ }
+
// Extend comparison result to either bool (C++) or int (C).
rewriter.replaceOpWithNewOp<mlir::LLVM::FCmpOp>(castOp, kind, llvmSrcVal,
zeroFloat);
@@ -2100,6 +2194,11 @@ mlir::LogicalResult CIRToLLVMCastOpLowering::matchAndRewrite(
mlir::Type dstTy = castOp.getType();
mlir::Value llvmSrcVal = adaptor.getSrc();
mlir::Type llvmDstTy = getTypeConverter()->convertType(dstTy);
+ if (cir::FenvAttr fenv = castOp.getFenvAttr()) {
+ return lowerToConstrainedFPIntrinsic(castOp, llvmSrcVal, fenv, llvmDstTy,
+ rewriter, "uitofp",
+ /*hasRoundingMode=*/true);
+ }
rewriter.replaceOpWithNewOp<mlir::LLVM::UIToFPOp>(castOp, llvmDstTy,
llvmSrcVal);
return mlir::success();
@@ -4126,30 +4225,6 @@ convertCmpKindToFCmpPredicate(cir::FCmpOpKind kind) {
llvm_unreachable("Unknown FCmpOpKind");
}
-static llvm::StringRef
-convertCmpKindToConstrainedFCmpPredicate(cir::CmpOpKind kind) {
- using CIR = cir::CmpOpKind;
- switch (kind) {
- case CIR::eq:
- return "oeq";
- case CIR::ne:
- return "une";
- case CIR::lt:
- return "olt";
- case CIR::le:
- return "ole";
- case CIR::gt:
- return "ogt";
- case CIR::ge:
- return "oge";
- case CIR::one:
- return "one";
- case CIR::uno:
- return "uno";
- }
- llvm_unreachable("Unknown CmpOpKind");
-}
-
static bool isSignalingConstrainedFCmp(cir::CmpOpKind kind) {
using CIR = cir::CmpOpKind;
switch (kind) {
@@ -4167,65 +4242,6 @@ static bool isSignalingConstrainedFCmp(cir::CmpOpKind kind) {
llvm_unreachable("Unknown CmpOpKind");
}
-static llvm::StringRef
-convertCmpKindToConstrainedFCmpPredicate(cir::FCmpOpKind kind) {
- using CIR = cir::FCmpOpKind;
- switch (kind) {
- case CIR::_false:
- return "false";
- case CIR::oeq:
- return "oeq";
- case CIR::ogt:
- return "ogt";
- case CIR::oge:
- return "oge";
- case CIR::olt:
- return "olt";
- case CIR::ole:
- return "ole";
- case CIR::one:
- return "one";
- case CIR::ord:
- return "ord";
- case CIR::ueq:
- return "ueq";
- case CIR::ugt:
- return "ugt";
- case CIR::uge:
- return "uge";
- case CIR::ult:
- return "ult";
- case CIR::ule:
- return "ule";
- case CIR::une:
- return "une";
- case CIR::uno:
- return "uno";
- case CIR::_true:
- return "true";
- }
- llvm_unreachable("Unknown FCmpOpKind");
-}
-
-template <typename OpKindTy>
-static mlir::LLVM::CallIntrinsicOp
-createConstrainedFCmpCall(mlir::ConversionPatternRewriter &rewriter,
- mlir::Location loc, mlir::Value lhs, mlir::Value rhs,
- OpKindTy kind, bool isSignaling, cir::FenvAttr fenv,
- mlir::Type llvmResTy) {
- llvm::SmallVector<mlir::Value, 4> callOperands = {
- lhs, rhs,
- createFenvMetadataValue(rewriter, loc,
- convertCmpKindToConstrainedFCmpPredicate(kind)),
- createFenvMetadataValue(rewriter, loc,
- getConstrainedExceptMetadata(fenv))};
- llvm::StringRef intrinsicName = isSignaling
- ? "llvm.experimental.constrained.fcmps"
- : "llvm.experimental.constrained.fcmp";
- return createCallLLVMIntrinsicOp(rewriter, loc, intrinsicName, llvmResTy,
- callOperands);
-}
-
mlir::LogicalResult CIRToLLVMCmpOpLowering::matchAndRewrite(
cir::CmpOp cmpOp, OpAdaptor adaptor,
mlir::ConversionPatternRewriter &rewriter) const {
diff --git a/clang/test/CIR/CodeGen/bool-to-float-strict-fp.cpp b/clang/test/CIR/CodeGen/bool-to-float-strict-fp.cpp
new file mode 100644
index 00000000000000..d004e8aaa81785
--- /dev/null
+++ b/clang/test/CIR/CodeGen/bool-to-float-strict-fp.cpp
@@ -0,0 +1,40 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -fexperimental-strict-floating-point -ffp-exception-behavior=strict -fclangir -emit-cir %s -o %t.cir
+// RUN: FileCheck --input-file=%t.cir %s -check-prefix=CIR
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -fexperimental-strict-floating-point -ffp-exception-behavior=strict -fclangir -emit-llvm %s -o %t-cir.ll
+// RUN: FileCheck --input-file=%t-cir.ll %s -check-prefix=LLVM
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -fexperimental-strict-floating-point -ffp-exception-behavior=strict -emit-llvm %s -o %t.ll
+// RUN: FileCheck --input-file=%t.ll %s -check-prefix=LLVM
+
+typedef bool v4b __attribute__((ext_vector_type(4)));
+typedef float v4f __attribute__((ext_vector_type(4)));
+
+// The command line makes exceptions strict and keeps rounding to nearest.
+float bool_to_float(bool b) { return b; }
+
+// CIR-LABEL: cir.func {{.*}}@_Z13bool_to_floatb
+// CIR: cir.cast bool_to_float %{{.*}} : !cir.bool -> !cir.float fenv<{{.*}}except_mode = unknown, strict_except = true>
+
+// LLVM-LABEL: define {{.*}}float @_Z13bool_to_floatb
+// LLVM: call float @llvm.experimental.constrained.uitofp.f32.i1(i1 %{{.*}}, metadata !"round.tonearest", metadata !"fpexcept.strict")
+
+double bool_to_double_fenv_access(bool b) {
+#pragma STDC FENV_ACCESS ON
+ return b;
+}
+
+// CIR-LABEL: cir.func {{.*}}@_Z26bool_to_double_fenv_accessb
+// CIR: cir.cast bool_to_float %{{.*}} : !cir.bool -> !cir.double fenv<dynamic_rounding_mode = unknown, except_mode = unknown, strict_except = true>
+
+// LLVM-LABEL: define {{.*}}double @_Z26bool_to_double_fenv_accessb
+// LLVM: call double @llvm.experimental.constrained.uitofp.f64.i1(i1 %{{.*}}, metadata !"round.dynamic", metadata !"fpexcept.strict")
+
+void vec_bool_to_float() {
+ v4b b;
+ v4f f = __builtin_convertvector(b, v4f);
+}
+
+// CIR-LABEL: cir.func {{.*}}@_Z17vec_bool_to_floatv
+// CIR: cir.cast bool_to_float %{{.*}} : !cir.vector<4 x !cir.bool> -> !cir.vector<4 x !cir.float> fenv<{{.*}}except_mode = unknown, strict_except = true>
+
+// LLVM-LABEL: define {{.*}}void @_Z17vec_bool_to_floatv
+// LLVM: call <4 x float> @llvm.experimental.constrained.uitofp.v4f32.v4i1(<4 x i1> %{{.*}}, metadata !"round.tonearest", metadata !"fpexcept.strict")
diff --git a/clang/test/CIR/CodeGen/complex-cast-fenv-access.c b/clang/test/CIR/CodeGen/complex-cast-fenv-access.c
new file mode 100644
index 00000000000000..93a88fa788f839
--- /dev/null
+++ b/clang/test/CIR/CodeGen/complex-cast-fenv-access.c
@@ -0,0 +1,125 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -fclangir -emit-llvm %s -o %t-cir.ll
+// RUN: FileCheck --input-file=%t-cir.ll %s \
+// RUN: --implicit-check-not="{{= (fpext|fptrunc|fptosi|sitofp|fcmp|fadd) }}"
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -emit-llvm %s -o %t.ll
+// RUN: FileCheck --input-file=%t.ll %s
+
+// Complex casts and conversions to bool under FENV_ACCESS. ClangIR and
+// classic codegen share every CHECK line, so both emit the same intrinsics
+// with the same metadata. The implicit check rejects a plain instruction in
+// the ClangIR output that no CHECK line matches.
+
+#pragma STDC FENV_ACCESS ON
+
+_Complex float cf;
+_Complex double cd;
+_Complex int ci;
+_Complex _Float16 ch;
+_Bool b;
+float f;
+double d;
+int i;
+
+void float_complex(void) { cd = cf; }
+
+// CHECK-LABEL: define{{.*}} void @float_complex()
+// CHECK-COUNT-2: call double @llvm.experimental.constrained.fpext.f64.f32(float %{{.*}}, metadata !"fpexcept.strict")
+
+void float_complex_to_int_complex(void) { ci = cf; }
+
+// CHECK-LABEL: define{{.*}} void @float_complex_to_int_complex()
+// CHECK-COUNT-2: call i32 @llvm.experimental.constrained.fptosi.i32.f32(float %{{.*}}, metadata !"fpexcept.strict")
+
+void int_complex_to_float_complex(void) { cf = ci; }
+
+// CHECK-LABEL: define{{.*}} void @int_complex_to_float_complex()
+// CHECK-COUNT-2: call float @llvm.experimental.constrained.sitofp.f32.i32(i32 %{{.*}}, metadata !"round.dynamic", metadata !"fpexcept.strict")
+
+// A narrowing cast rounds, so it takes the rounding mode as well.
+
+_Complex float float_complex_narrowing(_Complex double x) {
+ return (_Complex float)x;
+}
+
+// CHECK-LABEL: define{{.*}} @float_complex_narrowing(
+// CHECK-COUNT-2: call float @llvm.experimental.constrained.fptrunc.f32.f64(double %{{.*}}, metadata !"round.dynamic", metadata !"fpexcept.strict")
+
+// A compound assignment converts the left operand to the type of the
+// computation and the result back.
+
+void compound_assign(_Complex double x) { cf += x; }
+
+// CHECK-LABEL: define{{.*}} void @compound_assign(
+// CHECK-COUNT-2: call double @llvm.experimental.constrained.fpext.f64.f32(float %{{.*}}, metadata !"fpexcept.strict")
+// CHECK-COUNT-2: call double @llvm.experimental.constrained.fadd.f64(double %{{.*}}, double %{{.*}}, metadata !"round.dynamic", metadata !"fpexcept.strict")
+// CHECK-COUNT-2: call float @llvm.experimental.constrained.fptrunc.f32.f64(double %{{.*}}, metadata !"round.dynamic", metadata !"fpexcept.strict")
+
+// A conversion between a real and a complex value of another width converts
+// the real value with a scalar cast.
+
+void real_to_complex(void) { cd = f; }
+
+// CHECK-LABEL: define{{.*}} void @real_to_complex()
+// CHECK: call double @llvm.experimental.constrained.fpext.f64.f32(float %{{.*}}, metadata !"fpexcept.strict")
+
+void complex_to_real(void) { d = cf; }
+
+// CHECK-LABEL: define{{.*}} void @complex_to_real()
+// CHECK: call double @llvm.experimental.constrained.fpext.f64.f32(float %{{.*}}, metadata !"fpexcept.strict")
+
+// A conversion to bool compares both parts with zero. The comparison is
+// quiet.
+
+void float_complex_to_bool(void) { b = cf; }
+
+// CHECK-LABEL: define{{.*}} void @float_complex_to_bool()
+// CHECK: %[[REAL:.*]] = call i1 @llvm.experimental.constrained.fcmp.f32(float %{{.*}}, float 0.000000e+00, metadata !"une", metadata !"fpexcept.strict")
+// CHECK: %[[IMAG:.*]] = call i1 @llvm.experimental.constrained.fcmp.f32(float %{{.*}}, float 0.000000e+00, metadata !"une", metadata !"fpexcept.strict")
+// CHECK: or i1 %[[REAL]], %[[IMAG]]
+
+void float_to_bool(void) { b = f; }
+
+// CHECK-LABEL: define{{.*}} void @float_to_bool()
+// CHECK: call i1 @llvm.experimental.constrained.fcmp.f32(float %{{.*}}, float 0.000000e+00, metadata !"une", metadata !"fpexcept.strict")
+
+// A condition is converted to bool without a cast expression.
+
+void complex_condition(void) {
+ if (cf)
+ i = 1;
+}
+
+// CHECK-LABEL: define{{.*}} void @complex_condition()
+// CHECK-COUNT-2: call i1 @llvm.experimental.constrained.fcmp.f32(float %{{.*}}, float 0.000000e+00, metadata !"une", metadata !"fpexcept.strict")
+
+void float_condition(void) {
+ if (f)
+ i = 1;
+}
+
+// CHECK-LABEL: define{{.*}} void @float_condition()
+// CHECK: call i1 @llvm.experimental.constrained.fcmp.f32(float %{{.*}}, float 0.000000e+00, metadata !"une", metadata !"fpexcept.strict")
+
+// _Float16 arithmetic is done in float on this target. The conversions to and
+// from float are emitted outside the scope of the addition's FP options, so
+// they get the default environment of the function.
+
+void excess_precision(void) { ch = ch + ch; }
+
+// CHECK-LABEL: define{{.*}} void @excess_precision()
+// CHECK-COUNT-4: call float @llvm.experimental.constrained.fpext.f32.f16(half %{{.*}}, metadata !"fpexcept.ignore")
+// CHECK-COUNT-2: call float @llvm.experimental.constrained.fadd.f32(float %{{.*}}, float %{{.*}}, metadata !"round.dynamic", metadata !"fpexcept.strict")
+// CHECK-COUNT-2: call half @llvm.experimental.constrained.fptrunc.f16.f32(float %{{.*}}, metadata !"round.tonearest", metadata !"fpexcept.ignore")
+
+// Without FENV_ACCESS the casts stay plain instructions.
+
+#pragma STDC FENV_ACCESS OFF
+
+void unconstrained(void) {
+ cd = cf;
+ b = cf;
+}
+
+// CHECK-LABEL: define{{.*}} void @unconstrained()
+// CHECK-COUNT-2: fpext float %{{.*}} to double
+// CHECK-COUNT-2: fcmp une float %{{.*}}, 0.000000e+00
diff --git a/clang/test/CIR/CodeGen/complex-strict-fp.cpp b/clang/test/CIR/CodeGen/complex-strict-fp.cpp
index 864b677336a47a..5eed54965ef2e9 100644
--- a/clang/test/CIR/CodeGen/complex-strict-fp.cpp
+++ b/clang/test/CIR/CodeGen/complex-strict-fp.cpp
@@ -265,3 +265,91 @@ void complex_div() {
// OGCG: %[[C_IMAG_PTR:.*]] = getelementptr inbounds nuw { float, float }, ptr %[[C_ADDR]], i32 0, i32 1
// OGCG: store float %[[RESULT_REAL]], ptr %[[C_REAL_PTR]], align 4
// OGCG: store float %[[RESULT_IMAG]], ptr %[[C_IMAG_PTR]], align 4
+
+// LoweringPrepare expands a complex cast into scalar casts of the real and
+// the imaginary part. Each of them carries the attribute of the complex cast.
+
+void complex_cast() {
+ _Complex float a;
+ _Complex double b = a;
+ _Complex int c = a;
+ _Complex float d = c;
+}
+
+// CIR-BEFORE: cir.func {{.*}}@_Z12complex_castv()
+// CIR-BEFORE: %{{.*}} = cir.cast float_complex %{{.*}} : !cir.complex<!cir.float> -> !cir.complex<!cir.double> fenv<{{.*}}except_mode = unknown, strict_except = true>
+// CIR-BEFORE: %{{.*}} = cir.cast float_complex_to_int_complex %{{.*}} : !cir.complex<!cir.float> -> !cir.complex<!s32i> fenv<{{.*}}except_mode = unknown, strict_except = true>
+// CIR-BEFORE: %{{.*}} = cir.cast int_complex_to_float_complex %{{.*}} : !cir.complex<!s32i> -> !cir.complex<!cir.float> fenv<{{.*}}except_mode = unknown, strict_except = true>
+
+// CIR: cir.func {{.*}}@_Z12complex_castv()
+// CIR: %[[A_ADDR:.*]] = cir.alloca "a" {{.*}} : !cir.ptr<!cir.complex<!cir.float>>
+// CIR: %[[C_ADDR:.*]] = cir.alloca "c" {{.*}} init : !cir.ptr<!cir.complex<!s32i>>
+// CIR: %[[TMP_A:.*]] = cir.load {{.*}} %[[A_ADDR]] : !cir.ptr<!cir.complex<!cir.float>>, !cir.complex<!cir.float>
+// CIR: %[[A_REAL:.*]] = cir.complex.real %[[TMP_A]] : !cir.complex<!cir.float> -> !cir.float
+// CIR: %[[A_IMAG:.*]] = cir.complex.imag %[[TMP_A]] : !cir.complex<!cir.float> -> !cir.float
+// CIR: %[[B_REAL:.*]] = cir.cast floating %[[A_REAL]] : !cir.float -> !cir.double [[FENV:fenv<.*except_mode = unknown, strict_except = true>]]
+// CIR: %[[B_IMAG:.*]] = cir.cast floating %[[A_IMAG]] : !cir.float -> !cir.double [[FENV]]
+// CIR: %{{.*}} = cir.complex.create %[[B_REAL]], %[[B_IMAG]] : !cir.double -> !cir.complex<!cir.double>
+// CIR: %[[TMP_A:.*]] = cir.load {{.*}} %[[A_ADDR]] : !cir.ptr<!cir.complex<!cir.float>>, !cir.complex<!cir.float>
+// CIR: %[[A_REAL:.*]] = cir.complex.real %[[TMP_A]] : !cir.complex<!cir.float> -> !cir.float
+// CIR: %[[A_IMAG:.*]] = cir.complex.imag %[[TMP_A]] : !cir.complex<!cir.float> -> !cir.float
+// CIR: %[[C_REAL:.*]] = cir.cast float_to_int %[[A_REAL]] : !cir.float -> !s32i [[FENV]]
+// CIR: %[[C_IMAG:.*]] = cir.cast float_to_int %[[A_IMAG]] : !cir.float -> !s32i [[FENV]]
+// CIR: %{{.*}} = cir.complex.create %[[C_REAL]], %[[C_IMAG]] : !s32i -> !cir.complex<!s32i>
+// CIR: %[[TMP_C:.*]] = cir.load {{.*}} %[[C_ADDR]] : !cir.ptr<!cir.complex<!s32i>>, !cir.complex<!s32i>
+// CIR: %[[C_REAL:.*]] = cir.complex.real %[[TMP_C]] : !cir.complex<!s32i> -> !s32i
+// CIR: %[[C_IMAG:.*]] = cir.complex.imag %[[TMP_C]] : !cir.complex<!s32i> -> !s32i
+// CIR: %[[D_REAL:.*]] = cir.cast int_to_float %[[C_REAL]] : !s32i -> !cir.float [[FENV]]
+// CIR: %[[D_IMAG:.*]] = cir.cast int_to_float %[[C_IMAG]] : !s32i -> !cir.float [[FENV]]
+// CIR: %{{.*}} = cir.complex.create %[[D_REAL]], %[[D_IMAG]] : !cir.float -> !cir.complex<!cir.float>
+
+// LLVM: define {{.*}} @_Z12complex_castv()
+// LLVM-COUNT-2: call double @llvm.experimental.constrained.fpext.f64.f32(float %{{.*}}, metadata !"fpexcept.strict")
+// LLVM-COUNT-2: call i32 @llvm.experimental.constrained.fptosi.i32.f32(float %{{.*}}, metadata !"fpexcept.strict")
+// LLVM-COUNT-2: call float @llvm.experimental.constrained.sitofp.f32.i32(i32 %{{.*}}, metadata !"round.tonearest", metadata !"fpexcept.strict")
+
+// OGCG: define {{.*}} @_Z12complex_castv()
+// OGCG-COUNT-2: call double @llvm.experimental.constrained.fpext.f64.f32(float %{{.*}}, metadata !"fpexcept.strict")
+// OGCG-COUNT-2: call i32 @llvm.experimental.constrained.fptosi.i32.f32(float %{{.*}}, metadata !"fpexcept.strict")
+// OGCG-COUNT-2: call float @llvm.experimental.constrained.sitofp.f32.i32(i32 %{{.*}}, metadata !"round.tonearest", metadata !"fpexcept.strict")
+
+// A conversion to bool compares both parts with zero. The comparison is quiet.
+
+void complex_to_bool() {
+ _Complex float a;
+ bool b = a;
+}
+
+// CIR-BEFORE: cir.func {{.*}}@_Z15complex_to_boolv()
+// CIR-BEFORE: %{{.*}} = cir.cast float_complex_to_bool %{{.*}} : !cir.complex<!cir.float> -> !cir.bool fenv<{{.*}}except_mode = unknown, strict_except = true>
+
+// CIR: cir.func {{.*}}@_Z15complex_to_boolv()
+// CIR: %[[A_REAL:.*]] = cir.complex.real %{{.*}} : !cir.complex<!cir.float> -> !cir.float
+// CIR: %[[A_IMAG:.*]] = cir.complex.imag %{{.*}} : !cir.complex<!cir.float> -> !cir.float
+// CIR: %[[REAL_BOOL:.*]] = cir.cast float_to_bool %[[A_REAL]] : !cir.float -> !cir.bool [[FENV:fenv<.*except_mode = unknown, strict_except = true>]]
+// CIR: %[[IMAG_BOOL:.*]] = cir.cast float_to_bool %[[A_IMAG]] : !cir.float -> !cir.bool [[FENV]]
+// CIR: %{{.*}} = cir.select if %[[REAL_BOOL]] then %{{.*}} else %[[IMAG_BOOL]] : (!cir.bool, !cir.bool, !cir.bool) -> !cir.bool
+
+// LLVM: define {{.*}} @_Z15complex_to_boolv()
+// LLVM: %[[REAL_BOOL:.*]] = call i1 @llvm.experimental.constrained.fcmp.f32(float %{{.*}}, float 0.000000e+00, metadata !"une", metadata !"fpexcept.strict")
+// LLVM: %[[IMAG_BOOL:.*]] = call i1 @llvm.experimental.constrained.fcmp.f32(float %{{.*}}, float 0.000000e+00, metadata !"une", metadata !"fpexcept.strict")
+// LLVM: or i1 %[[REAL_BOOL]], %[[IMAG_BOOL]]
+
+// OGCG: define {{.*}} @_Z15complex_to_boolv()
+// OGCG: %[[REAL_BOOL:.*]] = call i1 @llvm.experimental.constrained.fcmp.f32(float %{{.*}}, float 0.000000e+00, metadata !"une", metadata !"fpexcept.strict")
+// OGCG: %[[IMAG_BOOL:.*]] = call i1 @llvm.experimental.constrained.fcmp.f32(float %{{.*}}, float 0.000000e+00, metadata !"une", metadata !"fpexcept.strict")
+// OGCG: or i1 %[[REAL_BOOL]], %[[IMAG_BOOL]]
+
+void float_to_bool() {
+ float a;
+ bool b = a;
+}
+
+// CIR: cir.func {{.*}}@_Z13float_to_boolv()
+// CIR: %{{.*}} = cir.cast float_to_bool %{{.*}} : !cir.float -> !cir.bool fenv<{{.*}}except_mode = unknown, strict_except = true>
+
+// LLVM: define {{.*}} @_Z13float_to_boolv()
+// LLVM: call i1 @llvm.experimental.constrained.fcmp.f32(float %{{.*}}, float 0.000000e+00, metadata !"une", metadata !"fpexcept.strict")
+
+// OGCG: define {{.*}} @_Z13float_to_boolv()
+// OGCG: call i1 @llvm.experimental.constrained.fcmp.f32(float %{{.*}}, float 0.000000e+00, metadata !"une", metadata !"fpexcept.strict")
diff --git a/clang/test/CIR/IR/invalid-cast.cir b/clang/test/CIR/IR/invalid-cast.cir
index 587cb7791aa0ee..8b24a4bfda45c6 100644
--- a/clang/test/CIR/IR/invalid-cast.cir
+++ b/clang/test/CIR/IR/invalid-cast.cir
@@ -109,3 +109,23 @@ module {
cir.return
}
}
+
+// -----
+
+module {
+ cir.func @fenv_on_float_to_complex(%f: !cir.float) {
+ // expected-error at +1 {{'fenv' is only valid for floating-point cast kinds}}
+ %0 = cir.cast float_to_complex %f : !cir.float -> !cir.complex<!cir.float> fenv<>
+ cir.return
+ }
+}
+
+// -----
+
+module {
+ cir.func @fenv_on_float_complex_to_real(%c: !cir.complex<!cir.float>) {
+ // expected-error at +1 {{'fenv' is only valid for floating-point cast kinds}}
+ %0 = cir.cast float_complex_to_real %c : !cir.complex<!cir.float> -> !cir.float fenv<>
+ cir.return
+ }
+}
diff --git a/clang/test/CIR/Lowering/fenv.cir b/clang/test/CIR/Lowering/fenv.cir
index ad815e18b874a3..fbb14cfda7234c 100644
--- a/clang/test/CIR/Lowering/fenv.cir
+++ b/clang/test/CIR/Lowering/fenv.cir
@@ -181,6 +181,24 @@ module {
cir.return
}
+ // CHECK-LABEL: llvm.func @bool_to_fp_casts
+ cir.func @bool_to_fp_casts(%a: !cir.bool, %v: !cir.vector<4 x !cir.bool>) {
+ // CHECK: %[[RM:.*]] = llvm.mlir.metadata_as_value #llvm.md_string<"round.upward">
+ // CHECK: %[[EB:.*]] = llvm.mlir.metadata_as_value #llvm.md_string<"fpexcept.strict">
+ // CHECK: llvm.call_intrinsic "llvm.experimental.constrained.uitofp"(%{{.*}}, %[[RM]], %[[EB]]) : (i1, !llvm.metadata, !llvm.metadata) -> f32
+ %0 = cir.cast bool_to_float %a : !cir.bool -> !cir.float fenv<dynamic_rounding_mode = upward, except_mode = unknown, strict_except = true>
+ // CHECK: %[[RM2:.*]] = llvm.mlir.metadata_as_value #llvm.md_string<"round.dynamic">
+ // CHECK: %[[EB2:.*]] = llvm.mlir.metadata_as_value #llvm.md_string<"fpexcept.strict">
+ // CHECK: llvm.call_intrinsic "llvm.experimental.constrained.uitofp"(%{{.*}}, %[[RM2]], %[[EB2]]) : (vector<4xi1>, !llvm.metadata, !llvm.metadata) -> vector<4xf32>
+ %1 = cir.cast bool_to_float %v : !cir.vector<4 x !cir.bool> -> !cir.vector<4 x !cir.float> fenv<dynamic_rounding_mode = unknown, except_mode = unknown, strict_except = true>
+ // Without fenv the plain LLVM cast op is used.
+ // CHECK: llvm.uitofp %{{.*}} : i1 to f32
+ %2 = cir.cast bool_to_float %a : !cir.bool -> !cir.float
+ // CHECK: llvm.uitofp %{{.*}} : vector<4xi1> to vector<4xf32>
+ %3 = cir.cast bool_to_float %v : !cir.vector<4 x !cir.bool> -> !cir.vector<4 x !cir.float>
+ cir.return
+ }
+
// CHECK-LABEL: llvm.func @fp_casts
cir.func @fp_casts(%a: !cir.float, %b: !cir.double, %i: !s32i) {
// CHECK: %[[RM:.*]] = llvm.mlir.metadata_as_value #llvm.md_string<"round.tonearest">
@@ -202,6 +220,20 @@ module {
cir.return
}
+ // A constrained conversion to bool is a quiet comparison with zero.
+ // CHECK-LABEL: llvm.func @fp_to_bool_casts
+ cir.func @fp_to_bool_casts(%a: !cir.float) {
+ // CHECK: %[[ZERO:.*]] = llvm.mlir.constant(0.000000e+00 : f32) : f32
+ // CHECK: %[[PRED:.*]] = llvm.mlir.metadata_as_value #llvm.md_string<"une">
+ // CHECK: %[[EB:.*]] = llvm.mlir.metadata_as_value #llvm.md_string<"fpexcept.strict">
+ // CHECK: llvm.call_intrinsic "llvm.experimental.constrained.fcmp"(%{{.*}}, %[[ZERO]], %[[PRED]], %[[EB]]) : (f32, f32, !llvm.metadata, !llvm.metadata) -> i1
+ %0 = cir.cast float_to_bool %a : !cir.float -> !cir.bool fenv<except_mode = unknown, strict_except = true>
+ // Without fenv the plain LLVM comparison is used.
+ // CHECK: llvm.fcmp "une" %{{.*}}, %{{.*}} : f32
+ %1 = cir.cast float_to_bool %a : !cir.float -> !cir.bool
+ cir.return
+ }
+
// CHECK-LABEL: llvm.func @fp_cmp
cir.func @fp_cmp(%a: !cir.float, %b: !cir.float) {
// CHECK: %[[PRED:.*]] = llvm.mlir.metadata_as_value #llvm.md_string<"olt">
diff --git a/clang/test/CIR/Transforms/lowering-prepare-complex-cast-fenv.cir b/clang/test/CIR/Transforms/lowering-prepare-complex-cast-fenv.cir
new file mode 100644
index 00000000000000..7e8a10113d659a
--- /dev/null
+++ b/clang/test/CIR/Transforms/lowering-prepare-complex-cast-fenv.cir
@@ -0,0 +1,66 @@
+// RUN: cir-opt %s --cir-lowering-prepare -o - | FileCheck %s \
+// RUN: -DSTRICT="fenv<dynamic_rounding_mode = unknown, except_mode = unknown, strict_except = true>" \
+// RUN: -DUPWARD="fenv<dynamic_rounding_mode = upward, except_mode = unknown, strict_except = true>"
+
+// LoweringPrepare expands a complex cast into scalar casts of the real and the
+// imaginary part. Both carry the `fenv` attribute of the complex cast.
+
+!s32i = !cir.int<s, 32>
+!complex_f32 = !cir.complex<!cir.float>
+!complex_f64 = !cir.complex<!cir.double>
+!complex_s32 = !cir.complex<!s32i>
+
+module attributes {cir.triple = "x86_64-unknown-linux-gnu"} {
+
+// CHECK-LABEL: cir.func @float_complex(
+// CHECK-COUNT-2: = cir.cast floating %{{.*}} : !cir.float -> !cir.double [[STRICT]]
+cir.func @float_complex(%a: !complex_f32) -> !complex_f64 {
+ %0 = cir.cast float_complex %a : !complex_f32 -> !complex_f64 fenv<dynamic_rounding_mode = unknown, except_mode = unknown, strict_except = true>
+ cir.return %0 : !complex_f64
+}
+
+// CHECK-LABEL: cir.func @float_complex_to_int_complex(
+// CHECK-COUNT-2: = cir.cast float_to_int %{{.*}} : !cir.float -> !s32i [[STRICT]]
+cir.func @float_complex_to_int_complex(%a: !complex_f32) -> !complex_s32 {
+ %0 = cir.cast float_complex_to_int_complex %a : !complex_f32 -> !complex_s32 fenv<dynamic_rounding_mode = unknown, except_mode = unknown, strict_except = true>
+ cir.return %0 : !complex_s32
+}
+
+// CHECK-LABEL: cir.func @int_complex_to_float_complex(
+// CHECK-COUNT-2: = cir.cast int_to_float %{{.*}} : !s32i -> !cir.float [[STRICT]]
+cir.func @int_complex_to_float_complex(%a: !complex_s32) -> !complex_f32 {
+ %0 = cir.cast int_complex_to_float_complex %a : !complex_s32 -> !complex_f32 fenv<dynamic_rounding_mode = unknown, except_mode = unknown, strict_except = true>
+ cir.return %0 : !complex_f32
+}
+
+// CHECK-LABEL: cir.func @float_complex_to_bool(
+// CHECK-COUNT-2: = cir.cast float_to_bool %{{.*}} : !cir.float -> !cir.bool [[STRICT]]
+cir.func @float_complex_to_bool(%a: !complex_f32) -> !cir.bool {
+ %0 = cir.cast float_complex_to_bool %a : !complex_f32 -> !cir.bool fenv<dynamic_rounding_mode = unknown, except_mode = unknown, strict_except = true>
+ cir.return %0 : !cir.bool
+}
+
+// An unconstrained cast expands into unconstrained casts.
+
+// CHECK-LABEL: cir.func @unconstrained(
+// CHECK-COUNT-2: = cir.cast floating %{{.*}} : !cir.float -> !cir.double{{$}}
+// CHECK-COUNT-2: = cir.cast float_to_bool %{{.*}} : !cir.float -> !cir.bool{{$}}
+cir.func @unconstrained(%a: !complex_f32, %p: !cir.ptr<!complex_f64>) -> !cir.bool {
+ %0 = cir.cast float_complex %a : !complex_f32 -> !complex_f64
+ cir.store %0, %p : !complex_f64, !cir.ptr<!complex_f64>
+ %1 = cir.cast float_complex_to_bool %a : !complex_f32 -> !cir.bool
+ cir.return %1 : !cir.bool
+}
+
+// Each expansion uses the attribute of its own cast.
+
+// CHECK-LABEL: cir.func @two_environments(
+// CHECK-COUNT-2: = cir.cast floating %{{.*}} : !cir.float -> !cir.double [[STRICT]]
+// CHECK-COUNT-2: = cir.cast floating %{{.*}} : !cir.double -> !cir.float [[UPWARD]]
+cir.func @two_environments(%a: !complex_f32) -> !complex_f32 {
+ %0 = cir.cast float_complex %a : !complex_f32 -> !complex_f64 fenv<dynamic_rounding_mode = unknown, except_mode = unknown, strict_except = true>
+ %1 = cir.cast float_complex %0 : !complex_f64 -> !complex_f32 fenv<dynamic_rounding_mode = upward, except_mode = unknown, strict_except = true>
+ cir.return %1 : !complex_f32
+}
+
+}
>From 78ef1376653c5a29ef220fc91b2d107cfb3b02fd Mon Sep 17 00:00:00 2001
From: Henrich Lauko <hlauko at nvidia.com>
Date: Wed, 25 Nov 2026 12:51:56 +0000
Subject: [PATCH 3/3] [CIR] Use the pragma FP environment for
__builtin_convertvector
`ScalarExprEmitter::VisitConvertVectorExpr` emitted the conversion
without a `CIRGenFPOptionsRAII`, so the cast got the floating-point
environment of the command line instead of the one that pragmas set at
the expression. With `-ffp-exception-behavior=strict` on the command
line and `#pragma clang fp exceptions(maytrap)` plus
`#pragma STDC FENV_ACCESS ON` in the function, ClangIR lowered the
conversions to constrained intrinsics with `round.tonearest` and
`fpexcept.strict`, where classic codegen emits `round.dynamic` and
`fpexcept.maytrap`.
Install the RAII for the conversion, after the source operand is
emitted, as classic codegen does on each floating-point path.
The test converts between float vectors and signed, unsigned, double
and bool vectors, so it covers the `float_to_bool` and `bool_to_float`
casts too. ClangIR and classic codegen share every LLVM check for them,
and the ClangIR run rejects any plain conversion or `fcmp` instruction
in the file.
Assisted-by: Claude Code (Fable 5.2).
---
clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp | 5 ++-
clang/test/CIR/CodeGen/vector-strict-fp.cpp | 46 ++++++++++++++++++++-
2 files changed, 48 insertions(+), 3 deletions(-)
diff --git a/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp b/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp
index 57cd4a1be5e031..557721c48b7c9d 100644
--- a/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp
@@ -401,8 +401,9 @@ class ScalarExprEmitter : public StmtVisitor<ScalarExprEmitter, mlir::Value> {
mlir::Value VisitConvertVectorExpr(ConvertVectorExpr *e) {
// __builtin_convertvector is an element-wise cast, and is implemented as a
// regular cast. The back end handles casts of vectors correctly.
- return emitScalarConversion(Visit(e->getSrcExpr()),
- e->getSrcExpr()->getType(), e->getType(),
+ mlir::Value src = Visit(e->getSrcExpr());
+ CIRGenFunction::CIRGenFPOptionsRAII fpOptsRAII(cgf, e);
+ return emitScalarConversion(src, e->getSrcExpr()->getType(), e->getType(),
e->getSourceRange().getBegin());
}
diff --git a/clang/test/CIR/CodeGen/vector-strict-fp.cpp b/clang/test/CIR/CodeGen/vector-strict-fp.cpp
index 9e5225c492a430..86cdade419aa92 100644
--- a/clang/test/CIR/CodeGen/vector-strict-fp.cpp
+++ b/clang/test/CIR/CodeGen/vector-strict-fp.cpp
@@ -1,12 +1,16 @@
// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -Wno-unused-value -ffp-contract=on -fexperimental-strict-floating-point -ffp-exception-behavior=strict -fclangir -emit-cir %s -o %t.cir
// RUN: FileCheck --input-file=%t.cir %s -check-prefix=CIR
// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -Wno-unused-value -ffp-contract=on -fexperimental-strict-floating-point -ffp-exception-behavior=strict -fclangir -emit-llvm %s -o %t-cir.ll
-// RUN: FileCheck --input-file=%t-cir.ll %s -check-prefixes=LLVM,SHARED
+// RUN: FileCheck --input-file=%t-cir.ll %s -check-prefixes=LLVM,SHARED \
+// RUN: --implicit-check-not="{{= (sitofp|uitofp|fptosi|fptoui|fptrunc|fpext|fcmp) }}"
// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -Wno-unused-value -ffp-contract=on -fexperimental-strict-floating-point -ffp-exception-behavior=strict -emit-llvm %s -o %t.ll
// RUN: FileCheck --input-file=%t.ll %s -check-prefixes=OGCG,SHARED
typedef float v4f __attribute__((ext_vector_type(4)));
typedef int v4i __attribute__((ext_vector_type(4)));
+typedef unsigned v4u __attribute__((ext_vector_type(4)));
+typedef double v4d __attribute__((ext_vector_type(4)));
+typedef bool v4b __attribute__((ext_vector_type(4)));
void vec_logical_not() {
v4f a;
@@ -106,3 +110,43 @@ void vec_logical_and() {
// OGCG: %[[RESULT_VEC:.*]] = sext <4 x i1> %2 to <4 x i32>
// SHARED: store <4 x i32> %[[RESULT_VEC]], ptr %[[R_ADDR]], align 16
+
+// __builtin_convertvector converts in the floating-point environment that the
+// pragmas set, not in the one from the command line.
+void vec_convert() {
+#pragma clang fp exceptions(maytrap)
+#pragma STDC FENV_ACCESS ON
+ v4i i;
+ v4u u;
+ v4f f;
+ v4d d;
+ v4b b;
+ v4f int_to_float = __builtin_convertvector(i, v4f);
+ v4f uint_to_float = __builtin_convertvector(u, v4f);
+ v4i float_to_int = __builtin_convertvector(f, v4i);
+ v4u float_to_uint = __builtin_convertvector(f, v4u);
+ v4f float_trunc = __builtin_convertvector(d, v4f);
+ v4d float_ext = __builtin_convertvector(f, v4d);
+ v4b float_to_bool = __builtin_convertvector(f, v4b);
+ v4f bool_to_float = __builtin_convertvector(b, v4f);
+}
+
+// CIR-LABEL: cir.func {{.*}}@_Z11vec_convertv(
+// CIR: cir.cast int_to_float %{{.*}} : !cir.vector<4 x !s32i> -> !cir.vector<4 x !cir.float> fenv<dynamic_rounding_mode = unknown, except_mode = unknown, strict_except = false>
+// CIR: cir.cast int_to_float %{{.*}} : !cir.vector<4 x !u32i> -> !cir.vector<4 x !cir.float> fenv<dynamic_rounding_mode = unknown, except_mode = unknown, strict_except = false>
+// CIR: cir.cast float_to_int %{{.*}} : !cir.vector<4 x !cir.float> -> !cir.vector<4 x !s32i> fenv<dynamic_rounding_mode = unknown, except_mode = unknown, strict_except = false>
+// CIR: cir.cast float_to_int %{{.*}} : !cir.vector<4 x !cir.float> -> !cir.vector<4 x !u32i> fenv<dynamic_rounding_mode = unknown, except_mode = unknown, strict_except = false>
+// CIR: cir.cast floating %{{.*}} : !cir.vector<4 x !cir.double> -> !cir.vector<4 x !cir.float> fenv<dynamic_rounding_mode = unknown, except_mode = unknown, strict_except = false>
+// CIR: cir.cast floating %{{.*}} : !cir.vector<4 x !cir.float> -> !cir.vector<4 x !cir.double> fenv<dynamic_rounding_mode = unknown, except_mode = unknown, strict_except = false>
+// CIR: cir.cast float_to_bool %{{.*}} : !cir.vector<4 x !cir.float> -> !cir.vector<4 x !cir.bool> fenv<dynamic_rounding_mode = unknown, except_mode = unknown, strict_except = false>
+// CIR: cir.cast bool_to_float %{{.*}} : !cir.vector<4 x !cir.bool> -> !cir.vector<4 x !cir.float> fenv<dynamic_rounding_mode = unknown, except_mode = unknown, strict_except = false>
+
+// SHARED-LABEL: define {{.*}}@_Z11vec_convertv(
+// SHARED: call <4 x float> @llvm.experimental.constrained.sitofp.v4f32.v4i32(<4 x i32> %{{.*}}, metadata !"round.dynamic", metadata !"fpexcept.maytrap")
+// SHARED: call <4 x float> @llvm.experimental.constrained.uitofp.v4f32.v4i32(<4 x i32> %{{.*}}, metadata !"round.dynamic", metadata !"fpexcept.maytrap")
+// SHARED: call <4 x i32> @llvm.experimental.constrained.fptosi.v4i32.v4f32(<4 x float> %{{.*}}, metadata !"fpexcept.maytrap")
+// SHARED: call <4 x i32> @llvm.experimental.constrained.fptoui.v4i32.v4f32(<4 x float> %{{.*}}, metadata !"fpexcept.maytrap")
+// SHARED: call <4 x float> @llvm.experimental.constrained.fptrunc.v4f32.v4f64(<4 x double> %{{.*}}, metadata !"round.dynamic", metadata !"fpexcept.maytrap")
+// SHARED: call <4 x double> @llvm.experimental.constrained.fpext.v4f64.v4f32(<4 x float> %{{.*}}, metadata !"fpexcept.maytrap")
+// SHARED: call <4 x i1> @llvm.experimental.constrained.fcmp.v4f32(<4 x float> %{{.*}}, <4 x float> zeroinitializer, metadata !"une", metadata !"fpexcept.maytrap")
+// SHARED: call <4 x float> @llvm.experimental.constrained.uitofp.v4f32.v4i1(<4 x i1> %{{.*}}, metadata !"round.dynamic", metadata !"fpexcept.maytrap")
More information about the cfe-commits
mailing list