https://github.com/xlauko created 
https://github.com/llvm/llvm-project/pull/243497

SimplifyConstantLoad replaces a load from a const alloca with the stored value 
when DominanceInfo says the store dominates the load. Before cir-flatten-cfg 
and cir-goto-solver run, DominanceInfo misses two kinds of jumps: a `cir.goto` 
has no CFG edge to its `cir.label`, and a `cir.switch` has none to the 
`cir.case` ops nested in it. So the pattern can fold a load that one of these 
jumps reaches without passing the store, and once the jumps become real 
branches, the IR fails verification with "operand #0 does not dominate this 
use". For example, at -O1:

```c
int g(int c) {
  if (c) goto L;
  {
    const int x = c * 2;
    int y = 0;
  L:
    if (!c) y = x;
    return y;
  }
}
```

The pattern now keeps the load when the store dominates:
- a `cir.label`, because a goto can come from anywhere in the function;
- a `cir.case` whose switch encloses the store. The cases of a switch that the 
store dominates are safe, because that switch runs after the store.

The check walks the store's region only when the function has a label or the 
store is inside a switch, so `cir-simplify` takes the same time as before on 
large C++ files without labels. Tests in `constant-load-fold.cir` cover both 
shapes, plus three cases that must still fold. `constant-load-fold.c` checks 
the C versions at -O1 through ClangIR and classic codegen.

Assisted-by: Claude Code (claude-opus-5-5).


>From 097e59b6bd1fa842d4f01305994b82f52856d77a Mon Sep 17 00:00:00 2001
From: Henrich Lauko <[email protected]>
Date: Mon, 16 Nov 2026 20:53:05 +0000
Subject: [PATCH] [CIR] Do not forward a constant store past a goto label or
 switch case

SimplifyConstantLoad replaces a load from a const alloca with the value of
the one store that DominanceInfo says dominates it. Until cir-flatten-cfg
and cir-goto-solver run, a cir.goto has no CFG edge to its cir.label, and a
cir.switch has none to the cir.case operations nested in it. A store before
a label then seems to dominate a load after the label, the load takes the
stored value, and the IR fails verification once the gotos become branches.
At -O1,

  int g(int c) {
    if (c) goto L;
    {
      const int x = c * 2;
      int y = 0;
    L:
      if (!c) y = x;
      return y;
    }
  }

fails with "operand #0 does not dominate this use". A case label nested in
a block after a const declaration in another case fails the same way.

Keep the load when the store dominates a cir.label, or a cir.case whose
switch encloses the store. The check walks the region of the store, but
only in functions that have labels or for stores inside a switch, so code
without labels does not pay for it.

Assisted-by: Claude Code (claude-opus-5-5).
---
 .../CIR/Dialect/Transforms/CIRSimplify.cpp    |  62 ++++++-
 .../test/CIR/Transforms/constant-load-fold.c  |  55 ++++++
 .../CIR/Transforms/constant-load-fold.cir     | 163 ++++++++++++++++++
 3 files changed, 273 insertions(+), 7 deletions(-)
 create mode 100644 clang/test/CIR/Transforms/constant-load-fold.c

diff --git a/clang/lib/CIR/Dialect/Transforms/CIRSimplify.cpp 
b/clang/lib/CIR/Dialect/Transforms/CIRSimplify.cpp
index 12d7f2ac795dd7..43b6ff5002ccd6 100644
--- a/clang/lib/CIR/Dialect/Transforms/CIRSimplify.cpp
+++ b/clang/lib/CIR/Dialect/Transforms/CIRSimplify.cpp
@@ -93,6 +93,38 @@ cir::StoreOp findDominatingInitOp(cir::AllocaOp alloca, 
cir::LoadOp load,
   return result;
 }
 
+/// Return true if a jump that DominanceInfo cannot see may skip `store` and
+/// land in code that `store` dominates. Until cir-flatten-cfg and
+/// cir-goto-solver run, a `cir.goto` has no CFG edge to its `cir.label`, and a
+/// `cir.switch` has none to its `cir.case` operations. A goto may come from
+/// anywhere in the function, so every label that `store` dominates is a
+/// possible target. So is every dominated case whose switch encloses `store`.
+/// Any other dominated case belongs to a switch that `store` dominates too, so
+/// that switch only jumps after `store` has run. `funcHasLabels` tells whether
+/// the function that contains `store` has any label.
+bool mayJumpPast(cir::StoreOp store, bool funcHasLabels,
+                 const DominanceInfo &domInfo) {
+  // Without labels, only an enclosing switch can jump past `store`.
+  if (!funcHasLabels && !store->getParentOfType<cir::SwitchOp>())
+    return false;
+
+  auto isJumpTarget = [&](Operation *op) {
+    if (auto caseOp = dyn_cast<cir::CaseOp>(op)) {
+      auto switchOp = caseOp->getParentOfType<cir::SwitchOp>();
+      return switchOp && switchOp->isProperAncestor(store);
+    }
+    return isa<cir::LabelOp>(op);
+  };
+
+  // Only operations nested in the region of `store` can be dominated by it.
+  WalkResult result = store->getParentRegion()->walk([&](Operation *op) {
+    if (isJumpTarget(op) && domInfo.dominates(store, op))
+      return WalkResult::interrupt();
+    return WalkResult::advance();
+  });
+  return result.wasInterrupted();
+}
+
 /// Simplify `cir.load` that loads from an alloca marked as "constant".
 ///
 /// For example:
@@ -103,8 +135,11 @@ cir::StoreOp findDominatingInitOp(cir::AllocaOp alloca, 
cir::LoadOp load,
 ///
 /// All uses of the load above could be replaced with the SSA value `%init`.
 struct SimplifyConstantLoad final : public OpRewritePattern<LoadOp> {
-  SimplifyConstantLoad(MLIRContext *context, RewriteDominanceInfo &domInfo)
-      : OpRewritePattern(context), domInfo(domInfo) {}
+  SimplifyConstantLoad(
+      MLIRContext *context, RewriteDominanceInfo &domInfo,
+      const llvm::SmallPtrSetImpl<Operation *> &funcsWithLabels)
+      : OpRewritePattern(context), domInfo(domInfo),
+        funcsWithLabels(funcsWithLabels) {}
 
   LogicalResult matchAndRewrite(LoadOp op,
                                 PatternRewriter &rewriter) const override {
@@ -125,12 +160,19 @@ struct SimplifyConstantLoad final : public 
OpRewritePattern<LoadOp> {
       return mlir::failure();
     }
 
+    // A goto or a switch may skip the store and still reach the load.
+    bool funcHasLabels =
+        funcsWithLabels.contains(op->getParentOfType<cir::FuncOp>());
+    if (mayJumpPast(initStoreOp, funcHasLabels, domInfo.getDominanceInfo()))
+      return mlir::failure();
+
     rewriter.replaceOp(op, initStoreOp.getValue());
     return mlir::success();
   }
 
 private:
   RewriteDominanceInfo &domInfo;
+  const llvm::SmallPtrSetImpl<Operation *> &funcsWithLabels;
 };
 
 /// Simplify suitable ternary operations into select operations.
@@ -421,8 +463,9 @@ struct CIRSimplifyPass : public 
impl::CIRSimplifyBase<CIRSimplifyPass> {
   void runOnOperation() override;
 };
 
-void populateMergeCleanupPatterns(RewritePatternSet &patterns,
-                                  RewriteDominanceInfo &domInfo) {
+void populateMergeCleanupPatterns(
+    RewritePatternSet &patterns, RewriteDominanceInfo &domInfo,
+    const llvm::SmallPtrSetImpl<Operation *> &funcsWithLabels) {
   // clang-format off
   patterns.add<
     SimplifyTernary,
@@ -431,21 +474,26 @@ void populateMergeCleanupPatterns(RewritePatternSet 
&patterns,
     SimplifyVecSplat
   >(patterns.getContext());
   // clang-format on
-  patterns.add<SimplifyConstantLoad>(patterns.getContext(), domInfo);
+  patterns.add<SimplifyConstantLoad>(patterns.getContext(), domInfo,
+                                     funcsWithLabels);
 }
 
 void CIRSimplifyPass::runOnOperation() {
   // Collect rewrite patterns. SimplifyConstantLoad queries dominance, so the
   // dominance info doubles as the driver's listener to stay coherent.
   RewriteDominanceInfo domInfo;
+  llvm::SmallPtrSet<Operation *, 4> funcsWithLabels;
   RewritePatternSet patterns(&getContext());
-  populateMergeCleanupPatterns(patterns, domInfo);
+  populateMergeCleanupPatterns(patterns, domInfo, funcsWithLabels);
 
-  // Collect operations to apply patterns.
+  // Collect operations to apply patterns, and the functions that have labels.
+  // No pattern adds a label, so the set stays complete during the rewrite.
   llvm::SmallVector<Operation *, 16> ops;
   getOperation()->walk([&](Operation *op) {
     if (isa<TernaryOp, SelectOp, SwitchOp, VecSplatOp, LoadOp>(op))
       ops.push_back(op);
+    else if (isa<LabelOp>(op))
+      funcsWithLabels.insert(op->getParentOfType<cir::FuncOp>());
   });
 
   // Apply patterns. Scope the rewrite to the body region, which encloses
diff --git a/clang/test/CIR/Transforms/constant-load-fold.c 
b/clang/test/CIR/Transforms/constant-load-fold.c
new file mode 100644
index 00000000000000..02effc7b9101b3
--- /dev/null
+++ b/clang/test/CIR/Transforms/constant-load-fold.c
@@ -0,0 +1,55 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -O1 -fclangir -emit-cir %s 
-o %t.cir
+// RUN: FileCheck --input-file=%t.cir %s -check-prefix=CIR
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -O1 -fclangir -emit-llvm 
%s -o %t-cir.ll
+// RUN: FileCheck --input-file=%t-cir.ll %s -check-prefix=LLVM
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -O1 -emit-llvm %s -o %t.ll
+// RUN: FileCheck --input-file=%t.ll %s -check-prefix=LLVM
+
+int g(void);
+void use(int);
+
+// The goto to L skips the initialization of x, so the load of x after L must
+// not be replaced with the initializer.
+void skip_init_with_goto(int c) {
+  if (c)
+    goto L;
+  {
+    const int x = g();
+  L:
+    if (!c)
+      use(x);
+  }
+}
+
+// CIR-LABEL: cir.func {{.*}} @skip_init_with_goto
+// CIR: %[[X:.*]] = cir.alloca "x" {{.*}} const
+// CIR: cir.label "L"
+// CIR: %[[V:.*]] = cir.load {{.*}} %[[X]]
+// CIR: cir.call @use(%[[V]])
+
+// LLVM-LABEL: define {{.*}} void @skip_init_with_goto(
+// LLVM: %[[X:.*]] = {{.*}}call i32 @g()
+// LLVM: call void @use(i32 noundef %[[X]])
+
+// The switch enters case 1 without initializing x.
+void skip_init_with_case(int c) {
+  switch (c) {
+  case 0: {
+    const int x = g();
+  case 1:
+    if (c == 0)
+      use(x);
+  }
+  }
+}
+
+// CIR-LABEL: cir.func {{.*}} @skip_init_with_case
+// CIR: %[[X:.*]] = cir.alloca "x" {{.*}} const
+// CIR: cir.case(equal, [#cir.int<1> : !s32i])
+// CIR: %[[V:.*]] = cir.load {{.*}} %[[X]]
+// CIR: cir.call @use(%[[V]])
+
+// LLVM-LABEL: define {{.*}} void @skip_init_with_case(
+// LLVM: %[[X:.*]] = {{.*}}call i32 @g()
+// LLVM: %[[V:.*]] = phi i32 [ %[[X]], %{{.*}} ]
+// LLVM: call void @use(i32 noundef %[[V]])
diff --git a/clang/test/CIR/Transforms/constant-load-fold.cir 
b/clang/test/CIR/Transforms/constant-load-fold.cir
index fdc3b1470f903e..b78683421ba2d6 100644
--- a/clang/test/CIR/Transforms/constant-load-fold.cir
+++ b/clang/test/CIR/Transforms/constant-load-fold.cir
@@ -3,6 +3,7 @@
 !s32i = !cir.int<s, 32>
 
 cir.func private @use_ptr(!cir.ptr<!s32i>)
+cir.func private @use(!s32i)
 
 // CHECK-LABEL: cir.func @fold_constant_load
 // CHECK: %[[ALLOCA:.*]] = cir.alloca "x" {{.*}} const
@@ -138,3 +139,165 @@ cir.func @do_not_fold_atomic_store() -> !s32i {
   %value = cir.load %x : !cir.ptr<!s32i>, !s32i
   cir.return %value : !s32i
 }
+
+// Before cir-goto-solver runs, DominanceInfo does not see the jump from a
+// cir.goto to its cir.label. The goto skips the store, so the load must stay.
+// CHECK-LABEL: cir.func @do_not_fold_past_label
+// CHECK: cir.label "L"
+// CHECK-NEXT: %[[VALUE:.*]] = cir.load
+// CHECK-NEXT: cir.return %[[VALUE]]
+cir.func @do_not_fold_past_label(%cond: !cir.bool) -> !s32i {
+  %x = cir.alloca "x" align(4) init const : !cir.ptr<!s32i>
+  cir.if %cond {
+    cir.goto "L"
+  }
+  %init = cir.const #cir.int<113> : !s32i
+  cir.store %init, %x : !s32i, !cir.ptr<!s32i>
+  cir.br ^bb1
+^bb1:
+  cir.label "L"
+  %value = cir.load %x : !cir.ptr<!s32i>, !s32i
+  cir.return %value : !s32i
+}
+
+// Nothing branches to ^bb1, so DominanceInfo treats it as dominated by the
+// store. A goto to "L" still enters it and reaches the load through ^bb2
+// without running the store.
+// CHECK-LABEL: cir.func @do_not_fold_past_label_without_predecessors
+// CHECK: cir.label "L"
+// CHECK: %[[VALUE:.*]] = cir.load
+// CHECK-NEXT: cir.return %[[VALUE]]
+cir.func @do_not_fold_past_label_without_predecessors(%cond: !cir.bool) -> 
!s32i {
+  %x = cir.alloca "x" align(4) init const : !cir.ptr<!s32i>
+  cir.if %cond {
+    cir.goto "L"
+  }
+  %init = cir.const #cir.int<114> : !s32i
+  cir.store %init, %x : !s32i, !cir.ptr<!s32i>
+  cir.br ^bb2
+^bb1:
+  cir.label "L"
+  cir.br ^bb2
+^bb2:
+  %value = cir.load %x : !cir.ptr<!s32i>, !s32i
+  cir.return %value : !s32i
+}
+
+// The label follows the load, but the loop takes a goto to "L" back to the
+// load without running the store.
+// CHECK-LABEL: cir.func @do_not_fold_label_after_load_in_loop
+// CHECK: cir.while
+// CHECK: %[[VALUE:.*]] = cir.load
+// CHECK-NEXT: cir.call @use(%[[VALUE]])
+cir.func @do_not_fold_label_after_load_in_loop(%cond: !cir.bool) {
+  %x = cir.alloca "x" align(4) init const : !cir.ptr<!s32i>
+  cir.if %cond {
+    cir.goto "L"
+  }
+  %init = cir.const #cir.int<115> : !s32i
+  cir.store %init, %x : !s32i, !cir.ptr<!s32i>
+  cir.while {
+    cir.condition(%cond)
+  } do {
+    cir.scope {
+      %value = cir.load %x : !cir.ptr<!s32i>, !s32i
+      cir.call @use(%value) : (!s32i) -> ()
+      cir.br ^bb1
+    ^bb1:
+      cir.label "L"
+      cir.yield
+    }
+    cir.yield
+  }
+  cir.return
+}
+
+// A goto to "L" still runs the store, so the load folds.
+// CHECK-LABEL: cir.func @fold_past_label_before_store
+// CHECK: cir.label "L"
+// CHECK-NEXT: %[[INIT:.*]] = cir.const #cir.int<116>
+// CHECK-NOT: cir.load
+// CHECK: cir.return %[[INIT]]
+cir.func @fold_past_label_before_store(%cond: !cir.bool) -> !s32i {
+  %x = cir.alloca "x" align(4) init const : !cir.ptr<!s32i>
+  cir.if %cond {
+    cir.goto "L"
+  }
+  cir.br ^bb1
+^bb1:
+  cir.label "L"
+  %init = cir.const #cir.int<116> : !s32i
+  cir.store %init, %x : !s32i, !cir.ptr<!s32i>
+  %value = cir.load %x : !cir.ptr<!s32i>, !s32i
+  cir.return %value : !s32i
+}
+
+// Before cir-flatten-cfg runs, DominanceInfo does not see the jump from a
+// cir.switch to its cases. The switch can enter case 1 without running the
+// store in case 0, so the load must stay.
+// CHECK-LABEL: cir.func @do_not_fold_past_nested_case
+// CHECK: cir.case(equal, [#cir.int<1> : !s32i])
+// CHECK-NEXT: %[[VALUE:.*]] = cir.load
+// CHECK-NEXT: cir.call @use(%[[VALUE]])
+cir.func @do_not_fold_past_nested_case(%c: !s32i) {
+  %x = cir.alloca "x" align(4) init const : !cir.ptr<!s32i>
+  cir.switch(%c : !s32i) {
+    cir.case(equal, [#cir.int<0> : !s32i]) {
+      %init = cir.const #cir.int<117> : !s32i
+      cir.store %init, %x : !s32i, !cir.ptr<!s32i>
+      cir.case(equal, [#cir.int<1> : !s32i]) {
+        %value = cir.load %x : !cir.ptr<!s32i>, !s32i
+        cir.call @use(%value) : (!s32i) -> ()
+        cir.yield
+      }
+      cir.yield
+    }
+    cir.yield
+  }
+  cir.return
+}
+
+// The store runs before the switch, so no case can skip it.
+// CHECK-LABEL: cir.func @fold_into_case
+// CHECK: %[[INIT:.*]] = cir.const #cir.int<118>
+// CHECK: cir.switch
+// CHECK-NOT: cir.load
+// CHECK: cir.call @use(%[[INIT]])
+cir.func @fold_into_case(%c: !s32i) {
+  %x = cir.alloca "x" align(4) init const : !cir.ptr<!s32i>
+  %init = cir.const #cir.int<118> : !s32i
+  cir.store %init, %x : !s32i, !cir.ptr<!s32i>
+  cir.switch(%c : !s32i) {
+    cir.case(equal, [#cir.int<0> : !s32i]) {
+      %value = cir.load %x : !cir.ptr<!s32i>, !s32i
+      cir.call @use(%value) : (!s32i) -> ()
+      cir.yield
+    }
+    cir.yield
+  }
+  cir.return
+}
+
+// The store and the load share a case, and no other case lies between them.
+// CHECK-LABEL: cir.func @fold_within_case
+// CHECK: %[[INIT:.*]] = cir.const #cir.int<119>
+// CHECK-NOT: cir.load
+// CHECK: cir.call @use(%[[INIT]])
+cir.func @fold_within_case(%c: !s32i) {
+  %x = cir.alloca "x" align(4) init const : !cir.ptr<!s32i>
+  cir.switch(%c : !s32i) {
+    cir.case(equal, [#cir.int<0> : !s32i]) {
+      %init = cir.const #cir.int<119> : !s32i
+      cir.store %init, %x : !s32i, !cir.ptr<!s32i>
+      %value = cir.load %x : !cir.ptr<!s32i>, !s32i
+      cir.call @use(%value) : (!s32i) -> ()
+      cir.break
+    }
+    cir.case(equal, [#cir.int<1> : !s32i]) {
+      cir.call @use(%c) : (!s32i) -> ()
+      cir.yield
+    }
+    cir.yield
+  }
+  cir.return
+}

_______________________________________________
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to