← Back to Pull requests

[CIR] Support __builtin_elementwise_ctzg and __builtin_elementwise_clzg #246181

Merged
amanmaurya92 merged 3 files (100 lines) on Dec 04, 2026 16:56 UTC
View on GitHub
amanmaurya92 amanmaurya92 commented on Nov 25, 2026 22:34 UTC
Author

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)

Diff: 100 lines (+77 / -23) across 3 files Reviewer: bcardosolopes Review duration: 12621m
All Vouch review confidence checks passed
Residual risk 0.03 = Change Risk (0.39) × (1 − Review Confidence (0.91)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.39 · 100 lines diff across 3 files
0.39
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.91 · 5 substantive comment(s)
0.91
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
91%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.276
Ai Authored ai_authored
0.050
Real PR Conversation Timeline
8 items
llvmorg-github-actions[bot] llvmorg-github-actions[bot] commented on Nov 25, 2026 22:35 UTC
Bot

<!--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&lt;CIR_UIntOfWidths&lt;[8, 16, 32, 64, 128]&gt;&gt;.
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:

  • (modified) clang/include/clang/CIR/Dialect/IR/CIROps.td (+2-2)

  • (modified) clang/lib/CIR/CodeGen/CIRGenBuiltin.cpp (+45-8)

  • (modified) clang/test/CIR/CodeGenBuiltins/builtin-bit.cpp (+73)
  • ``````

    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>

    xlauko xlauko commented on code on Nov 30, 2026 14:20 UTC
    Code Review
    clang/lib/CIR/CodeGen/CIRGenBuiltin.cpp:1
    @@ -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)

    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)));
    

    xlauko xlauko commented on code on Nov 30, 2026 14:20 UTC
    Code Review
    clang/lib/CIR/CodeGen/CIRGenBuiltin.cpp:1
    @@ -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())) {

    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);
      }
    

    xlauko xlauko commented on code on Nov 30, 2026 14:20 UTC
    Code Review
    clang/include/clang/CIR/Dialect/IR/CIROps.td:1
    @@ -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]>>

    Please update the clz/ctz descriptions, which still say the input must be an unsigned integer.

    xlauko xlauko commented on code on Nov 30, 2026 14:20 UTC
    Code Review
    clang/test/CIR/CodeGenBuiltins/builtin-bit.cpp:1
    @@ -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)));

    Could these go in builtins-elementwise.c with the other elementwise tests? Also, _BitInt(31) operands now fail verification.

    bcardosolopes bcardosolopes approved these changes on Dec 04, 2026 00:13 UTC
    Approved Reviewer

    Nothing to add besides @xlauko latest round, LGTM

    amanmaurya92 amanmaurya92 commented on Dec 04, 2026 16:55 UTC
    Author

    Thanks for the reviews and approval, @xlauko and @bcardosolopes! Merging now.

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