[clang] [CIR] Add if statement support (PR #134333)

Bruno Cardoso Lopes via cfe-commits cfe-commits at lists.llvm.org
Fri Apr 4 15:01:44 PDT 2025


================
@@ -263,6 +264,72 @@ static void terminateBody(CIRGenBuilderTy &builder, mlir::Region &r,
     b->erase();
 }
 
+mlir::LogicalResult CIRGenFunction::emitIfStmt(const IfStmt &s) {
+  mlir::LogicalResult res = mlir::success();
+  // The else branch of a consteval if statement is always the only branch
+  // that can be runtime evaluated.
+  const Stmt *ConstevalExecuted;
+  if (s.isConsteval()) {
+    ConstevalExecuted = s.isNegatedConsteval() ? s.getThen() : s.getElse();
+    if (!ConstevalExecuted) {
+      // No runtime code execution required
+      return res;
+    }
+  }
+
+  // C99 6.8.4.1: The first substatement is executed if the expression
+  // compares unequal to 0.  The condition must be a scalar type.
+  auto ifStmtBuilder = [&]() -> mlir::LogicalResult {
+    if (s.isConsteval())
+      return emitStmt(ConstevalExecuted, /*useCurrentScope=*/true);
+
+    if (s.getInit())
+      if (emitStmt(s.getInit(), /*useCurrentScope=*/true).failed())
+        return mlir::failure();
+
+    if (s.getConditionVariable())
+      emitDecl(*s.getConditionVariable());
+
+    // During LLVM codegen, if the condition constant folds and can be elided,
+    // it tries to avoid emitting the condition and the dead arm of the if/else.
+    // TODO(cir): we skip this in CIRGen, but should implement this as part of
+    // SSCP or a specific CIR pass.
+    bool CondConstant;
+    if (ConstantFoldsToSimpleInteger(s.getCond(), CondConstant,
----------------
bcardosolopes wrote:

> Wouldn't the same apply here and other places where conditions are constant folded?

I have gone back-n-forth with the general guideline here, hence the inconsistencies. Doing it in MLIR is probably nicer, but if we can "easily" (not too compile time intensive) do it during CIRGen, shouldn't we? A lot of places that don't do it in OG are probably because people usually first try it out in LLVM IR directly, and there are less clang experts than folks writing LLVM passes - all of that to say that sometimes CodeGen is just missing an opportunity we saw fit when writing CIRGen.

I'm still hesitant to do it anywhere it could affect static analysis (doesn't seem like a case we would care here though?)

https://github.com/llvm/llvm-project/pull/134333


More information about the cfe-commits mailing list