[CIR] Support __builtin_elementwise_ctzg and __builtin_elementwise_clzg #246181
<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-clang
@llvm/pr-subscribers-clangir
Author: Aman Maurya (amanmaurya92)
<details>
<summary>Changes</summary>
Description
This patch adds support for __builtin_elementwise_ctzg and __builtin_elementwise_clzg in CIRGenFunction::emitBuiltinExpr, establishing parity with classic Clang CodeGen (clang/lib/CodeGen/CGBuiltin.cpp:3438-3505).
This change:
1. Extends CIR_BitClzOp and CIR_BitCtzOp in CIROps.td to accept CIR_ScalarOrVectorOf<CIR_UIntOfWidths<[8, 16, 32, 64, 128]>>.
2. Casts signed scalar/vector operands to unsigned in createBuiltinBitOp for cir::BitCtzOp / cir::BitClzOp and casts the result back to the expression type.
3. Adds isElementwise (forcing poisonZero = true) and vector zero-fallback selection (cir::VecCmpOp + cir::VecTernaryOp) to emitBuiltinBitOpWithFallback.
4. Adds CIR, LLVM IR, and classic CodeGen (OGCG) parity tests in clang/test/CIR/CodeGenBuiltins/builtin-bit.cpp.
Fixes #<!-- -->246134.
Assisted-by: Antigravity (Gemini 4 Hydrogen)
---
Full diff: https://github.com/llvm/llvm-project/pull/246181.diff
3 Files Affected:
````````````diff --git a/clang/include/clang/CIR/Dialect/IR/CIROps.td b/clang/include/clang/CIR/Dialect/IR/CIROps.td
index a0d7b57b46ab70..71148ad429278b 100644
--- a/clang/include/clang/CIR/Dialect/IR/CIROps.td
+++ b/clang/include/clang/CIR/Dialect/IR/CIROps.td
@@ -8129,7 +8129,7 @@ def CIR_BitClrsbOp : CIR_BitOpBase<"clrsb", CIR_SIntOfWidths<[32, 64]>> {
}
def CIR_BitClzOp : CIR_BitZeroCountOpBase<"clz",
- CIR_UIntOfWidths<[8, 16, 32, 64, 128]>
+ CIR_ScalarOrVectorOf<CIR_UIntOfWidths<[8, 16, 32, 64, 128]>>
> {
let summary = "Get the number of leading 0-bits in the input";
let description = [{
@@ -8156,7 +8156,7 @@ def CIR_BitClzOp : CIR_BitZeroCountOpBase<"clz",
}
def CIR_BitCtzOp : CIR_BitZeroCountOpBase<"ctz",
- CIR_UIntOfWidths<[8, 16, 32, 64, 128]>
+ CIR_ScalarOrVectorOf<CIR_UIntOfWidths<[8, 16, 32, 64, 128]>>
> {
let summary = "Get the number of trailing 0-bits in the input";
let description = [{
diff --git a/clang/lib/CIR/CodeGen/CIRGenBuiltin.cpp b/clang/lib/CIR/CodeGen/CIRGenBuiltin.cpp
index ca8a601946ab52..416c0a4e5e5988 100644
--- a/clang/lib/CIR/CodeGen/CIRGenBuiltin.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenBuiltin.cpp
@@ -71,6 +71,31 @@ static mlir::Value createBuiltinBitOp(CIRGenFunction &cgf, const CallExpr *e,
mlir::Value arg, Args... args) {
CIRGenBuilderTy &builder = cgf.getBuilder();
mlir::Location loc = cgf.getLoc(e->getSourceRange());
+ // cir.clz / cir.ctz require unsigned integer (or vector of unsigned integer)
+ // operands, while elementwise builtins also accept signed integer types.
+ if constexpr (std::is_same_v<Op, cir::BitCtzOp> ||
+ std::is_same_v<Op, cir::BitClzOp>) {
+ mlir::Type argTy = arg.getType();
+ auto toUnsignedIntTy = [&](mlir::Type ty) -> mlir::Type {
+ if (auto intTy = mlir::dyn_cast<cir::IntType>(ty))
+ return intTy.isSigned()
+ ? cir::IntType::get(builder.getContext(), intTy.getWidth(),
+ /*isSigned=*/false)
+ : ty;
+ if (auto vecTy = mlir::dyn_cast<cir::VectorType>(ty)) {
+ if (auto intTy = mlir::dyn_cast<cir::IntType>(vecTy.getElementType());
+ intTy && intTy.isSigned()) {
+ auto uElemTy =
+ cir::IntType::get(builder.getContext(), intTy.getWidth(),
+ /*isSigned=*/false);
+ return cir::VectorType::get(uElemTy, vecTy.getSize());
+ }
+ }
+ return ty;
+ };
+ if (mlir::Type uArgTy = toUnsignedIntTy(argTy); uArgTy != argTy)
+ arg = builder.createIntCast(arg, uArgTy);
+ }
auto op = Op::create(builder, loc, arg, args...);
mlir::Value result = op.getResult();
mlir::Type resultTy = cgf.convertType(e->getType());
@@ -95,14 +120,17 @@ static RValue emitBuiltinVectorReduction(CIRGenFunction &cgf,
.getResult());
}
-/// Emit a clz/ctz bit op with optional fallback for __builtin_c[lt]zg.
+/// Emit a clz/ctz bit op with optional fallback for __builtin_c[lt]zg and
+/// __builtin_elementwise_c[lt]zg.
/// When a fallback is present, the result is the fallback value if the input is
/// zero, otherwise the bit count.
template <typename Op>
static RValue emitBuiltinBitOpWithFallback(CIRGenFunction &cgf,
- const CallExpr *e) {
+ const CallExpr *e,
+ bool isElementwise = false) {
bool hasFallback = e->getNumArgs() > 1;
- bool poisonZero = hasFallback || cgf.getTarget().isCLZForZeroUndef();
+ bool poisonZero =
+ hasFallback || isElementwise || cgf.getTarget().isCLZForZeroUndef();
if (!hasFallback) {
assert(!cir::MissingFeatures::builtinCheckKind());
@@ -116,9 +144,18 @@ static RValue emitBuiltinBitOpWithFallback(CIRGenFunction &cgf,
CIRGenBuilderTy &builder = cgf.getBuilder();
mlir::Location loc = cgf.getLoc(e->getSourceRange());
mlir::Value zero = builder.getNullValue(arg.getType(), loc);
+ mlir::Value fallbackValue = cgf.emitScalarExpr(e->getArg(1));
+ if (auto vecTy = mlir::dyn_cast<cir::VectorType>(arg.getType())) {
+ auto elemTy = mlir::cast<cir::IntType>(vecTy.getElementType());
+ auto cmpTy = cir::VectorType::get(builder.getSIntNTy(elemTy.getWidth()),
+ vecTy.getSize());
+ mlir::Value isZero = cir::VecCmpOp::create(builder, loc, cmpTy,
+ cir::CmpOpKind::eq, arg, zero);
+ return RValue::get(
+ cir::VecTernaryOp::create(builder, loc, isZero, fallbackValue, result));
+ }
mlir::Value isZero =
builder.createCompare(loc, cir::CmpOpKind::eq, arg, zero);
- mlir::Value fallbackValue = cgf.emitScalarExpr(e->getArg(1));
return RValue::get(builder.createSelect(loc, isZero, fallbackValue, result));
}
@@ -1456,8 +1493,8 @@ RValue CIRGenFunction::emitBuiltinExpr(const GlobalDecl &gd, unsigned builtinID,
case Builtin::BI__builtin_ctzg:
return emitBuiltinBitOpWithFallback<cir::BitCtzOp>(*this, e);
case Builtin::BI__builtin_elementwise_ctzg:
- cgm.errorNYI(e->getSourceRange(), "__builtin_elementwise_ctzg");
- return RValue::get(nullptr);
+ return emitBuiltinBitOpWithFallback<cir::BitCtzOp>(*this, e,
+ /*isElementwise=*/true);
case Builtin::BI__builtin_clzs:
case Builtin::BI__builtin_clz:
@@ -1469,8 +1506,8 @@ RValue CIRGenFunction::emitBuiltinExpr(const GlobalDecl &gd, unsigned builtinID,
case Builtin::BI__builtin_clzg:
return emitBuiltinBitOpWithFallback<cir::BitClzOp>(*this, e);
case Builtin::BI__builtin_elementwise_clzg:
- cgm.errorNYI(e->getSourceRange(), "__builtin_elementwise_clzg");
- return RValue::get(nullptr);
+ return emitBuiltinBitOpWithFallback<cir::BitClzOp>(*this, e,
+ /*isElementwise=*/true);
case Builtin::BI__builtin_ffs:
case Builtin::BI__builtin_ffsl:
diff --git a/clang/test/CIR/CodeGenBuiltins/builtin-bit.cpp b/clang/test/CIR/CodeGenBuiltins/builtin-bit.cpp
index 99765b22f0dba5..e0726e1570b723 100644
--- a/clang/test/CIR/CodeGenBuiltins/builtin-bit.cpp
+++ b/clang/test/CIR/CodeGenBuiltins/builtin-bit.cpp
@@ -995,3 +995,76 @@ unsigned long long test_builtin_rotateright64(unsigned long long x,
// OGCG-NEXT: %[[AMOUNT:.+]] = load i64, ptr %{{.+}}, align 8
// OGCG-NEXT: %[[CANON_AMOUNT:.+]] = urem i64 %[[AMOUNT]], 64
// OGCG-NEXT: %{{.+}} = call i64 @llvm.fshr.i64(i64 %[[INPUT]], i64 %[[INPUT]], i64 %[[CANON_AMOUNT]])
+
+typedef unsigned int v4u __attribute__((ext_vector_type(4)));
+typedef int v4i __attribute__((ext_vector_type(4)));
+
+unsigned test_elementwise_ctzg(unsigned x) {
+ return __builtin_elementwise_ctzg(x);
+}
+
+// CIR-LABEL: @_Z21test_elementwise_ctzgj
+// CIR: %{{.+}} = cir.ctz %{{.+}} poison_zero : !u32i
+
+// LLVM-LABEL: @_Z21test_elementwise_ctzgj
+// LLVM: %{{.+}} = call i32 @llvm.cttz.i32(i32 %{{.+}}, i1 true)
+
+// OGCG-LABEL: @_Z21test_elementwise_ctzgj
+// OGCG: %{{.+}} = call i32 @llvm.cttz.i32(i32 %{{.+}}, i1 true)
+
+int test_elementwise_ctzg_signed_fallback(int x, int fallback) {
+ return __builtin_elementwise_ctzg(x, fallback);
+}
+
+// CIR-LABEL: @_Z37test_elementwise_ctzg_signed_fallbackii
+// CIR: %[[U:.+]] = cir.cast integral %{{.+}} : !s32i -> !u32i
+// CIR: %[[CTZ:.+]] = cir.ctz %[[U]] poison_zero : !u32i
+// CIR: %[[RES:.+]] = cir.cast integral %[[CTZ]] : !u32i -> !s32i
+// CIR: %[[CMP:.+]] = cir.cmp eq %{{.+}}, %{{.+}} : !s32i
+// CIR: %{{.+}} = cir.select if %[[CMP]] then %{{.+}} else %[[RES]] : (!cir.bool, !s32i, !s32i) -> !s32i
+
+// LLVM-LABEL: @_Z37test_elementwise_ctzg_signed_fallbackii
+// LLVM: %[[CTZ:.+]] = call i32 @llvm.cttz.i32(i32 %{{.+}}, i1 true)
+// LLVM: %[[ISZERO:.+]] = icmp eq i32 %{{.+}}, 0
+// LLVM: %{{.+}} = select i1 %[[ISZERO]], i32 %{{.+}}, i32 %[[CTZ]]
+
+// OGCG-LABEL: @_Z37test_elementwise_ctzg_signed_fallbackii
+// OGCG: %[[CTZ:.+]] = call i32 @llvm.cttz.i32(i32 %{{.+}}, i1 true)
+// OGCG: %[[ISZERO:.+]] = icmp eq i32 %{{.+}}, 0
+// OGCG: %{{.+}} = select i1 %[[ISZERO]], i32 %{{.+}}, i32 %[[CTZ]]
+
+v4u test_elementwise_ctzg_vec(v4u x) {
+ return __builtin_elementwise_ctzg(x);
+}
+
+// CIR-LABEL: @_Z25test_elementwise_ctzg_vecDv4_j
+// CIR: %{{.+}} = cir.ctz %{{.+}} poison_zero : !cir.vector<4 x !u32i>
+
+// LLVM-LABEL: @_Z25test_elementwise_ctzg_vecDv4_j
+// LLVM: %{{.+}} = call <4 x i32> @llvm.cttz.v4i32(<4 x i32> %{{.+}}, i1 true)
+
+// OGCG-LABEL: @_Z25test_elementwise_ctzg_vecDv4_j
+// OGCG: %{{.+}} = call <4 x i32> @llvm.cttz.v4i32(<4 x i32> %{{.+}}, i1 true)
+
+v4i test_elementwise_clzg_vec_fallback(v4i x, v4i fallback) {
+ return __builtin_elementwise_clzg(x, fallback);
+}
+
+// CIR-LABEL: @_Z34test_elementwise_clzg_vec_fallbackDv4_iS_
+// CIR: %[[U:.+]] = cir.cast integral %{{.+}} : !cir.vector<4 x !s32i> -> !cir.vector<4 x !u32i>
+// CIR: %[[CLZ:.+]] = cir.clz %[[U]] poison_zero : !cir.vector<4 x !u32i>
+// CIR: %[[RES:.+]] = cir.cast integral %[[CLZ]] : !cir.vector<4 x !u32i> -> !cir.vector<4 x !s32i>
+// CIR: %[[CMP:.+]] = cir.vec.cmp(eq, %{{.+}}, %{{.+}}) : !cir.vector<4 x !s32i>, !cir.vector<4 x !s32i>
+// CIR: %{{.+}} = cir.vec.ternary(%[[CMP]], %{{.+}}, %[[RES]]) : !cir.vector<4 x !s32i>, !cir.vector<4 x !s32i>
+
+// LLVM-LABEL: @_Z34test_elementwise_clzg_vec_fallbackDv4_iS_
+// LLVM: %[[CLZ:.+]] = call <4 x i32> @llvm.ctlz.v4i32(<4 x i32> %{{.+}}, i1 true)
+// LLVM: %[[ISZERO:.+]] = icmp eq <4 x i32> %{{.+}}, zeroinitializer
+// LLVM: %[[SEXT:.+]] = sext <4 x i1> %[[ISZERO]] to <4 x i32>
+// LLVM: %[[COND:.+]] = icmp ne <4 x i32> %[[SEXT]], zeroinitializer
+// LLVM: %{{.+}} = select <4 x i1> %[[COND]], <4 x i32> %{{.+}}, <4 x i32> %[[CLZ]]
+
+// OGCG-LABEL: @_Z34test_elementwise_clzg_vec_fallbackDv4_iS_
+// OGCG: %[[CLZ:.+]] = call <4 x i32> @llvm.ctlz.v4i32(<4 x i32> %{{.+}}, i1 true)
+// OGCG: %[[ISZERO:.+]] = icmp eq <4 x i32> %{{.+}}, zeroinitializer
+// OGCG: %{{.+}} = select <4 x i1> %[[ISZERO]], <4 x i32> %{{.+}}, <4 x i32> %[[CLZ]]
</details>
Only the elementwise path sees signed operands, so this cast can move into emitBuiltinBitOpWithFallback, emitting the argument once for both paths. getCorrespondingUnsignedType handles vectors, and createIntCast is a no-op on matching types:
QualType argTy = e->getArg(0)->getType();
mlir::Value arg = builder.createIntCast(
cgf.emitScalarExpr(e->getArg(0)),
cgf.convertType(cgf.getContext().getCorrespondingUnsignedType(argTy)));
Comparing into a !cir.bool vector lets createSelect cover both cases, and the LLVM output then matches OGCG (no sext + icmp ne):
mlir::Value isZero;
if (auto vecTy = mlir::dyn_cast<cir::VectorType>(arg.getType())) {
auto boolVecTy = cir::VectorType::get(builder.getBoolTy(), vecTy.getSize(),
vecTy.getKind());
isZero =
builder.createVecCompare(loc, boolVecTy, cir::CmpOpKind::eq, arg, zero);
} else {
isZero = builder.createCompare(loc, cir::CmpOpKind::eq, arg, zero);
}
Please update the clz/ctz descriptions, which still say the input must be an unsigned integer.
Could these go in builtins-elementwise.c with the other elementwise tests? Also, _BitInt(31) operands now fail verification.
Nothing to add besides @xlauko latest round, LGTM
Thanks for the reviews and approval, @xlauko and @bcardosolopes! Merging now.
bcardosolopes
amanmaurya92
Description
This patch adds support for
__builtin_elementwise_ctzgand__builtin_elementwise_clzginCIRGenFunction::emitBuiltinExpr, establishing parity with classic Clang CodeGen (clang/lib/CodeGen/CGBuiltin.cpp:3438-3505).This change:
1. Extends
CIR_BitClzOpandCIR_BitCtzOpinCIROps.tdto acceptCIR_ScalarOrVectorOf<CIR_UIntOfWidths<[8, 16, 32, 64, 128]>>.2. Casts signed scalar/vector operands to unsigned in
createBuiltinBitOpforcir::BitCtzOp/cir::BitClzOpand casts the result back to the expression type.3. Adds
isElementwise(forcingpoisonZero = true) and vector zero-fallback selection (cir::VecCmpOp+cir::VecTernaryOp) toemitBuiltinBitOpWithFallback.4. Adds CIR, LLVM IR, and classic CodeGen (
OGCG) parity tests inclang/test/CIR/CodeGenBuiltins/builtin-bit.cpp.Fixes #246134.
Assisted-by: Antigravity (Gemini 4 Hydrogen)