[clang] [CIR] Fold unary operations and simple casts (PR #174670)
Andy Kaylor via cfe-commits
cfe-commits at lists.llvm.org
Tue Jan 6 16:58:35 PST 2026
================
@@ -781,9 +841,26 @@ class ScalarExprEmitter : public StmtVisitor<ScalarExprEmitter, mlir::Value> {
return result;
}
+ mlir::Value foldUnaryOp(const UnaryOperator *e) {
+ Expr::EvalResult result;
+ if (!e->EvaluateAsRValue(result, cgf.getContext()))
----------------
andykaylor wrote:
I could do that in `CIRBaseBuilderTy::createCast` and `CIRBaseBuilderTy::createUnaryOp`. That wouldn't fold direct calls to `cir::UnaryOp::create` or `cir::CastOp::create`, but that's consistent with the `llvm::IRBuilder` behavior.
Still, I'm concerned about code like this:
```
cir::ConstantOp c = builder.createConstantInt(loc, 32, 1);
cir::UnaryOp u = builder.createUnaryOp(loc, cir::UnaryOpKind::Minus, c);
```
Can we erase the `cir::ConstantOp` in that case? I think `llvm::IRBuilder` just leaves the folded operations dangling and if they don't get added to blocks they just get deleted, but the MLIR values are always added to a region or block, and so it we don't erase them they are going to stick around until some cleanup pass runs.
My current implementation may have the same problem where it erases constant values, though it's somewhat protected by the visitors not directly returning values as it creates them. Maybe we can just do the folding as you have suggested and document my concern as "don't do that"?
https://github.com/llvm/llvm-project/pull/174670
More information about the cfe-commits
mailing list