Skip to content

[CIR] Generate SelectOp instead of TernaryOp for if cheap enough to evaluate unconditionally #1642

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 23, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 14 additions & 22 deletions clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2516,30 +2516,22 @@ mlir::Value ScalarExprEmitter::VisitAbstractConditionalOperator(
if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) &&
isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) {
bool lhsIsVoid = false;
auto condV = CGF.evaluateExprAsBool(condExpr);
mlir::Value condV = CGF.evaluateExprAsBool(condExpr);
assert(!cir::MissingFeatures::incrementProfileCounter());

return builder
.create<cir::TernaryOp>(
loc, condV, /*thenBuilder=*/
[&](mlir::OpBuilder &b, mlir::Location loc) {
auto lhs = Visit(lhsExpr);
if (!lhs) {
lhs = builder.getNullValue(CGF.VoidTy, loc);
lhsIsVoid = true;
}
builder.create<cir::YieldOp>(loc, lhs);
},
/*elseBuilder=*/
[&](mlir::OpBuilder &b, mlir::Location loc) {
auto rhs = Visit(rhsExpr);
if (lhsIsVoid) {
assert(!rhs && "lhs and rhs types must match");
rhs = builder.getNullValue(CGF.VoidTy, loc);
}
builder.create<cir::YieldOp>(loc, rhs);
})
.getResult();
mlir::Value lhs = Visit(lhsExpr);
if (!lhs) {
lhs = builder.getNullValue(CGF.VoidTy, loc);
lhsIsVoid = true;
}

mlir::Value rhs = Visit(rhsExpr);
if (lhsIsVoid) {
assert(!rhs && "lhs and rhs types must match");
rhs = builder.getNullValue(CGF.VoidTy, loc);
}

return builder.createSelect(loc, condV, lhs, rhs);
}

mlir::Value condV = CGF.emitOpOnBoolExpr(loc, condExpr);
Expand Down
7 changes: 7 additions & 0 deletions clang/test/CIR/CodeGen/ternary.c
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,10 @@ double f1(int cond, int n, ...) {

// Fine enough to check it passes the verifying.
// CIR: cir.ternary

int unconditional_evaluation(_Bool cond) {
return cond ? 123 : 456;
// CIR: %[[TRUE_CONST:.+]] = cir.const #cir.int<123>
// CIR: %[[FALSE_CONST:.+]] = cir.const #cir.int<456>
// CIR: cir.select if {{.+}} then %[[TRUE_CONST]] else %[[FALSE_CONST]] : (!cir.bool, !s32i, !s32i) -> !s32i
}
56 changes: 0 additions & 56 deletions clang/test/CIR/Transforms/ternary-fold.cpp

This file was deleted.

Loading