[clang] [CIR] -Wreturn-type (1/2): Add an analysis classifying how control reaches a function's end (PR #239774)

via cfe-commits cfe-commits at lists.llvm.org
Fri Nov 6 11:58:17 PST 2026


llvmorg-github-actions[bot] wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-clangir

Author: Bruno Cardoso Lopes (bcardosolopes)

<details>
<summary>Changes</summary>

Second step towards issuing -Wreturn-type from ClangIR instead of Clang's CFG, building on the `implicit` fall-off terminator from #<!-- -->238696. This PR does not yet hook it up to the rest of Clang warning infrastructure, nor has a flag to substitute the CFG one. That's a  change with more design decisions, rewiring in Sema, etc - better discuss in its own PR (third step), here I'm focusing on the analysis.

Add `cir::analyzeFallOff`, the CIR counterpart of Sema's CFG-based `CheckFallThrough` behind -Wreturn-type. It classifies a function as never, never-and-no-return, maybe or always falling off its end.

- Walks structured CIR: each region reports how control leaves it and region ops combine their regions' exits. Noreturn calls, traps and throws are the edges Sema uses to tell maybe from always; gotos and labels are followed as in the CFG.
- For a coroutine, only the code written in its body is analyzed, with `cir.co_return` as its return.
- `cir::mayFallOff` is a cheap, conservative pre-check that spares most functions the full walk.
- The module entry point analyzes functions in parallel.
- `-cir-fall-off-analysis` reports the result as remarks, for tests.

Cost against Sema's check on the 5 slowest selfhost TUs (ms, -ftime-trace, median of 3). Build is the CFG or CIRGen; the check excludes it.

```
| TU                | Engine  | Build (CFG / CIRGen) | Fall-off check          |
|-------------------|---------|---------------------:|-------------------------|
| CIRDialect.cpp    | CFG     |                388.7 | 42.5                    |
|                   | ClangIR |             11,188.2 | 14.0 (24.0 on 1 thread) |
| OpenACC.cpp       | CFG     |                198.1 | 21.1                    |
|                   | ClangIR |              6,407.4 | 7.1 (12.7 on 1 thread)  |
| SLPVectorizer.cpp | CFG     |                150.3 | 20.6                    |
|                   | ClangIR |              8,178.2 | 8.8 (18.3 on 1 thread)  |
| Disasm.cpp        | CFG     |                 66.3 | 8.8                     |
|                   | ClangIR |                473.9 | 1.0 (0.3 on 1 thread)   |
| OpenMPDialect.cpp | CFG     |                217.2 | 23.6                    |
|                   | ClangIR |              5,981.7 | 4.4 (12.5 on 1 thread)  |
```

Known differences from the CFG check, left for incremental follow-ups (if they make sense):
- Constant conditions are folded only through CIR's folders, while the CFG evaluates them (e.g. `while (alwaysTrue())` with a constexpr call).
- The handlers of a try whose body cannot throw are not analyzed, since CIRGen drops them. 
- Noreturn destructors of temporaries created in a conditional operand (`b ? T() : U()`, `&&`, `||`) are not seen as noreturn.
- Calls to virtual `[[noreturn]]` methods and to `analyzer_noreturn` functions are not marked noreturn by CIRGen.
- Functions CIRGen does not emit (unused inline functions, constexpr-only functions, uncalled lambdas) and blocks are not analyzed (requires ObjC NYIs).

---

Patch is 52.10 KiB, truncated to 20.00 KiB below, full version: https://github.com/llvm/llvm-project/pull/239774.diff


11 Files Affected:

- (added) clang/include/clang/CIR/Dialect/Analysis/CIRFallOffAnalysis.h (+66) 
- (modified) clang/include/clang/CIR/Dialect/Passes.h (+1) 
- (modified) clang/include/clang/CIR/Dialect/Passes.td (+14) 
- (added) clang/lib/CIR/Dialect/Analysis/CIRFallOffAnalysis.cpp (+713) 
- (modified) clang/lib/CIR/Dialect/Analysis/CMakeLists.txt (+1) 
- (modified) clang/lib/CIR/Dialect/Transforms/CMakeLists.txt (+2) 
- (added) clang/lib/CIR/Dialect/Transforms/FallOffAnalysisPass.cpp (+36) 
- (added) clang/test/CIR/Analysis/fall-off-coroutine.cpp (+182) 
- (added) clang/test/CIR/Analysis/fall-off.c (+180) 
- (added) clang/test/CIR/Analysis/fall-off.cpp (+281) 
- (modified) clang/tools/cir-opt/cir-opt.cpp (+4) 


``````````diff
diff --git a/clang/include/clang/CIR/Dialect/Analysis/CIRFallOffAnalysis.h b/clang/include/clang/CIR/Dialect/Analysis/CIRFallOffAnalysis.h
new file mode 100644
index 00000000000000..4896ba7ca5dfb3
--- /dev/null
+++ b/clang/include/clang/CIR/Dialect/Analysis/CIRFallOffAnalysis.h
@@ -0,0 +1,66 @@
+//===- CIRFallOffAnalysis.h - Can control flow off the end of a function --===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// This file declares an analysis that classifies whether control can reach the
+// end of a function body, the CIR counterpart of the CFG-based fall-off check
+// behind -Wreturn-type. It runs on CIRGen output, where the terminator emitted
+// for flowing off the end of a body is marked `implicit`.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef CLANG_CIR_DIALECT_ANALYSIS_CIRFALLOFFANALYSIS_H
+#define CLANG_CIR_DIALECT_ANALYSIS_CIRFALLOFFANALYSIS_H
+
+#include "clang/CIR/Dialect/IR/CIRDialect.h"
+#include "llvm/ADT/STLFunctionalExtras.h"
+#include "llvm/ADT/SmallVector.h"
+
+namespace mlir {
+class ModuleOp;
+} // namespace mlir
+
+namespace cir {
+
+/// How control can reach the end of a function body. Mirrors the
+/// classification used by Sema's CFG-based fall-off check.
+enum class FallOffKind {
+  /// The function was not analyzed (e.g. it has no body).
+  Unknown,
+  /// Control never reaches the end of the body, but a return is reachable.
+  Never,
+  /// Control never reaches the end of the body and no return is reachable.
+  NeverAndNoReturn,
+  /// Control reaches the end of the body on some paths only.
+  Maybe,
+  /// Control reaches the end of the body on every path that completes.
+  Always,
+};
+
+llvm::StringRef stringifyFallOffKind(FallOffKind kind);
+
+/// Classify whether control can flow off the end of `func`'s body.
+FallOffKind analyzeFallOff(cir::FuncOp func);
+
+/// A cheap, conservative check of whether control may reach the end of
+/// `func`. When false, analyzeFallOff(func) is never or never-and-no-return.
+bool mayFallOff(cir::FuncOp func);
+
+struct FallOffResult {
+  cir::FuncOp func;
+  FallOffKind kind = FallOffKind::Unknown;
+};
+
+/// analyzeFallOff over the definitions `filter` accepts (all if null), in
+/// parallel when allowed: `filter` may run concurrently. In module order.
+llvm::SmallVector<FallOffResult>
+analyzeFallOff(mlir::ModuleOp module,
+               llvm::function_ref<bool(cir::FuncOp)> filter = nullptr);
+
+} // namespace cir
+
+#endif // CLANG_CIR_DIALECT_ANALYSIS_CIRFALLOFFANALYSIS_H
diff --git a/clang/include/clang/CIR/Dialect/Passes.h b/clang/include/clang/CIR/Dialect/Passes.h
index 7c09a42bed949f..42570fb7f66462 100644
--- a/clang/include/clang/CIR/Dialect/Passes.h
+++ b/clang/include/clang/CIR/Dialect/Passes.h
@@ -41,6 +41,7 @@ createCallConvLoweringPass(cir::CallConvTarget target,
 std::unique_ptr<Pass> createHoistAllocasPass();
 std::unique_ptr<Pass> createLoweringPreparePass();
 std::unique_ptr<Pass> createGotoSolverPass();
+std::unique_ptr<Pass> createFallOffAnalysisPass();
 std::unique_ptr<Pass> createIdiomRecognizerPass();
 std::unique_ptr<Pass> createLibOptPass();
 
diff --git a/clang/include/clang/CIR/Dialect/Passes.td b/clang/include/clang/CIR/Dialect/Passes.td
index 787a9d8f29b899..e696f4dcdba556 100644
--- a/clang/include/clang/CIR/Dialect/Passes.td
+++ b/clang/include/clang/CIR/Dialect/Passes.td
@@ -88,6 +88,20 @@ def CIRFlattenCFG : Pass<"cir-flatten-cfg"> {
   let dependentDialects = ["cir::CIRDialect"];
 }
 
+def FallOffAnalysis : Pass<"cir-fall-off-analysis", "mlir::ModuleOp"> {
+  let summary = "Report how control reaches the end of each function";
+  let description = [{
+    Runs the fall-off analysis behind ClangIR's -Wreturn-type on every
+    function definition and emits a remark per function with its
+    classification: never, never-and-no-return, maybe, always or unknown.
+    This exposes the analysis to cir-opt tests; clang calls the analysis
+    directly and reports -Wreturn-type, not these remarks. The IR is not
+    modified.
+  }];
+  let constructor = "mlir::createFallOffAnalysisPass()";
+  let dependentDialects = ["cir::CIRDialect"];
+}
+
 def GotoSolver : Pass<"cir-goto-solver", "mlir::ModuleOp"> {
   let summary = "Replaces goto operations with branches";
   let description = [{
diff --git a/clang/lib/CIR/Dialect/Analysis/CIRFallOffAnalysis.cpp b/clang/lib/CIR/Dialect/Analysis/CIRFallOffAnalysis.cpp
new file mode 100644
index 00000000000000..21e4efd37bb6cc
--- /dev/null
+++ b/clang/lib/CIR/Dialect/Analysis/CIRFallOffAnalysis.cpp
@@ -0,0 +1,713 @@
+//===- CIRFallOffAnalysis.cpp - Can control flow off the end of a function ===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// A reachability walk over structured CIR. Each region reports how control
+// leaves it (falling through, break, continue, explicit return, or reaching an
+// `implicit` terminator), and each structured operation combines the exits of
+// its regions according to its semantics. Reachable noreturn calls, user
+// traps and throws are recorded as the abnormal and fake edges Sema's CFG
+// check uses to tell "maybe" from "always".
+//
+//===----------------------------------------------------------------------===//
+
+#include "clang/CIR/Dialect/Analysis/CIRFallOffAnalysis.h"
+
+#include "mlir/IR/BuiltinOps.h"
+#include "mlir/IR/Matchers.h"
+#include "mlir/IR/Threading.h"
+#include "mlir/Interfaces/SideEffectInterfaces.h"
+#include "clang/CIR/Dialect/IR/CIRDialect.h"
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/DenseSet.h"
+#include "llvm/Support/TimeProfiler.h"
+
+using namespace cir;
+
+namespace {
+
+/// How control can leave a region or a structured operation.
+struct Exits {
+  bool normal = false;
+  bool breaks = false;
+  bool continues = false;
+  bool explicitReturn = false;
+  bool implicitReturn = false;
+  // Outcomes of a reachable `cir.condition` terminating the region.
+  bool condTrue = false;
+  bool condFalse = false;
+
+  /// Merge the exits that escape an enclosed operation.
+  void mergeEscaping(const Exits &other) {
+    breaks |= other.breaks;
+    continues |= other.continues;
+    explicitReturn |= other.explicitReturn;
+    implicitReturn |= other.implicitReturn;
+  }
+
+  bool any() const {
+    return normal || breaks || continues || explicitReturn || implicitReturn;
+  }
+};
+
+class FallOffAnalyzer {
+public:
+  explicit FallOffAnalyzer(FuncOp func, bool tailOnly = false)
+      : func(func), tailOnly(tailOnly) {}
+
+  FallOffKind run();
+
+  /// Conservatively, whether `op` alone completes when entered at the top. A
+  /// label inside it, or dead code that may hold one, means yes.
+  bool mayCompleteFromTop(mlir::Operation *op) {
+    assert(tailOnly && "needs a tail-only analyzer");
+    return visitStructured(op, /*entered=*/true).normal || unsure;
+  }
+
+private:
+  Exits visitRegion(mlir::Region &region, bool entered);
+  Exits visitStructured(mlir::Operation *op, bool entered);
+  Exits visitLoop(LoopOpInterface loop, bool entered);
+  Exits visitSwitch(SwitchOp op, bool entered);
+  Exits visitCleanupScope(CleanupScopeOp op, bool entered);
+  void visitTerminator(mlir::Operation *op, Exits &exits,
+                       llvm::SmallVectorImpl<mlir::Block *> &liveSuccessors);
+  void addAddressTakenLabels();
+  void updateLabelAncestors();
+
+  /// Whether a dead operation still needs a visit because a label inside it
+  /// can be reached through a goto.
+  bool containsTargetedLabel(mlir::Operation *op) const {
+    return labelAncestors.contains(op);
+  }
+  bool isTargetedLabel(mlir::Operation *op) const {
+    auto label = mlir::dyn_cast<LabelOp>(op);
+    return label && targetedLabels.contains(label.getLabelAttr());
+  }
+
+  FuncOp func;
+  bool tailOnly;
+  bool unsure = false;
+  bool abnormalEdge = false;
+  bool fakeEdge = false;
+  /// Labels control can reach through a goto or an indirect branch, and the
+  /// operations enclosing them.
+  llvm::DenseSet<mlir::StringAttr> targetedLabels;
+  llvm::DenseSet<mlir::Operation *> labelAncestors;
+  /// Labels targeted by the gotos reached so far.
+  llvm::DenseSet<mlir::StringAttr> reachedGotoTargets;
+  /// Whether a cir.indirect_goto is reachable; it can reach every label whose
+  /// address is taken.
+  bool reachedIndirectGoto = false;
+  bool addedAddressTakenLabels = false;
+  /// The function's labels, collected once a goto makes them matter.
+  std::optional<llvm::SmallVector<LabelOp>> labels;
+  /// The enclosing switches, innermost last. A reachable switch dispatches to
+  /// all of its cases, wherever they are nested in its body.
+  struct SwitchState {
+    bool entered = false;
+    bool hasDefault = false;
+  };
+  llvm::SmallVector<SwitchState> switches;
+
+  bool inEnteredSwitch() const {
+    return !switches.empty() && switches.back().entered;
+  }
+};
+
+} // namespace
+
+/// Fold `value` to a constant through side-effect-free operations.
+static mlir::Attribute foldToConstant(mlir::Value value, unsigned depth = 0) {
+  mlir::Attribute attr;
+  if (mlir::matchPattern(value, mlir::m_Constant(&attr)))
+    return attr;
+
+  constexpr unsigned maxDepth = 8;
+  if (depth >= maxDepth)
+    return {};
+
+  // C conditions such as `while (1)` or `x || 1` convert between int and
+  // bool, which the cast folder leaves alone.
+  if (auto cast = value.getDefiningOp<CastOp>()) {
+    if (cast.getKind() == CastKind::int_to_bool) {
+      if (auto intAttr = mlir::dyn_cast_if_present<IntAttr>(
+              foldToConstant(cast.getSrc(), depth + 1)))
+        return BoolAttr::get(value.getContext(), !intAttr.getValue().isZero());
+      return {};
+    }
+    if (cast.getKind() == CastKind::bool_to_int) {
+      if (auto boolAttr = mlir::dyn_cast_if_present<BoolAttr>(
+              foldToConstant(cast.getSrc(), depth + 1)))
+        return IntAttr::get(cast.getType(), boolAttr.getValue() ? 1 : 0);
+      return {};
+    }
+  }
+
+  // `x || 1` and `x && 0` become a cir.ternary whose arms yield the same
+  // constant, which the CFG check folds too.
+  if (auto ternary = value.getDefiningOp<TernaryOp>()) {
+    auto foldArm = [&](mlir::Region &arm) -> mlir::Attribute {
+      if (!arm.hasOneBlock() || !arm.front().mightHaveTerminator())
+        return {};
+      auto yield = mlir::dyn_cast<YieldOp>(arm.front().getTerminator());
+      if (!yield || yield.getNumOperands() != 1)
+        return {};
+      return foldToConstant(yield.getOperand(0), depth + 1);
+    };
+    mlir::Attribute trueValue = foldArm(ternary.getTrueRegion());
+    mlir::Attribute falseValue = foldArm(ternary.getFalseRegion());
+    if (auto cond = mlir::dyn_cast_if_present<BoolAttr>(
+            foldToConstant(ternary.getCond(), depth + 1)))
+      return cond.getValue() ? trueValue : falseValue;
+    return trueValue == falseValue ? trueValue : mlir::Attribute();
+  }
+
+  mlir::Operation *def = value.getDefiningOp();
+  if (!def || def->getNumResults() != 1 || def->getNumRegions() != 0 ||
+      !mlir::isMemoryEffectFree(def))
+    return {};
+  llvm::SmallVector<mlir::Attribute> operands;
+  for (mlir::Value operand : def->getOperands()) {
+    operands.push_back(foldToConstant(operand, depth + 1));
+    if (!operands.back())
+      return {};
+  }
+  llvm::SmallVector<mlir::OpFoldResult> results;
+  if (mlir::failed(def->fold(operands, results)) || results.size() != 1)
+    return {};
+  return mlir::dyn_cast_if_present<mlir::Attribute>(results.front());
+}
+
+static std::optional<bool> getConstantBool(mlir::Value value) {
+  mlir::Attribute attr = foldToConstant(value);
+  if (auto boolAttr = mlir::dyn_cast_if_present<BoolAttr>(attr))
+    return boolAttr.getValue();
+  return std::nullopt;
+}
+
+static bool isNoReturnCall(mlir::Operation *op) {
+  return mlir::isa<CallOp>(op) &&
+         op->hasAttr(CIRDialect::getNoReturnAttrName());
+}
+
+/// `__builtin_assume(0)` is noreturn for the CFG check.
+static bool isAssumeFalse(mlir::Operation *op) {
+  auto assume = mlir::dyn_cast<AssumeOp>(op);
+  return assume && getConstantBool(assume.getPredicate()) == false;
+}
+
+/// The only operation with regions in a single-block \p region, if any.
+static mlir::Operation *getOnlyRegionOp(mlir::Region &region) {
+  if (!region.hasOneBlock())
+    return nullptr;
+  mlir::Operation *found = nullptr;
+  for (mlir::Operation &op : region.front()) {
+    if (op.getNumRegions() == 0)
+      continue;
+    if (found)
+      return nullptr;
+    found = &op;
+  }
+  return found;
+}
+
+/// The code written in a coroutine's body, without the implicit `try` (and the
+/// `if` around it) CIRGen adds with exceptions: leaving those is not fall-off.
+static mlir::Region &getCoroutineUserBody(CoroutineOp coro) {
+  mlir::Operation *op = getOnlyRegionOp(coro.getBody());
+  if (auto ifOp = mlir::dyn_cast_if_present<IfOp>(op);
+      ifOp && ifOp.getElseRegion().empty())
+    op = getOnlyRegionOp(ifOp.getThenRegion());
+  if (auto scope = mlir::dyn_cast_if_present<ScopeOp>(op))
+    op = getOnlyRegionOp(scope.getScopeRegion());
+  if (auto tryOp = mlir::dyn_cast_if_present<TryOp>(op))
+    return tryOp.getTryRegion();
+  return coro.getBody();
+}
+
+FallOffKind FallOffAnalyzer::run() {
+  // For a coroutine, the end is that of the code written in its body, and
+  // co_return is its return.
+  mlir::Region *body = &func.getBody();
+  if (func.getCoroutineKind().has_value()) {
+    CoroutineOp coro;
+    func.walk<mlir::WalkOrder::PreOrder>([&](CoroutineOp op) {
+      coro = op;
+      return mlir::WalkResult::interrupt();
+    });
+    if (!coro)
+      return FallOffKind::Unknown;
+    body = &getCoroutineUserBody(coro);
+  }
+
+  // A reached goto may target a label in a region already walked as dead, so
+  // walk again until no new label is targeted; without gotos, once.
+  Exits exits;
+  while (true) {
+    abnormalEdge = fakeEdge = reachedIndirectGoto = false;
+    reachedGotoTargets.clear();
+    exits = visitRegion(*body, /*entered=*/true);
+
+    size_t numTargeted = targetedLabels.size();
+    targetedLabels.insert_range(reachedGotoTargets);
+    if (reachedIndirectGoto)
+      addAddressTakenLabels();
+    if (targetedLabels.size() == numTargeted)
+      break;
+    updateLabelAncestors();
+  }
+
+  bool plainEdge = exits.implicitReturn || exits.normal;
+  if (!plainEdge)
+    return exits.explicitReturn ? FallOffKind::Never
+                                : FallOffKind::NeverAndNoReturn;
+  if (abnormalEdge || fakeEdge || exits.explicitReturn)
+    return FallOffKind::Maybe;
+  return FallOffKind::Always;
+}
+
+void FallOffAnalyzer::addAddressTakenLabels() {
+  if (addedAddressTakenLabels)
+    return;
+  addedAddressTakenLabels = true;
+  mlir::StringAttr funcName = func.getSymNameAttr();
+  auto addFromAttr = [&](mlir::Attribute attr) {
+    attr.walk(
+        [&](BlockAddrInfoAttr info) {
+          if (info.getFunc().getAttr() == funcName)
+            targetedLabels.insert(info.getLabel());
+        },
+        [&](BlockAddrDiffAttr diff) {
+          if (diff.getFunc().getAttr() == funcName) {
+            targetedLabels.insert(diff.getLhsLabel());
+            targetedLabels.insert(diff.getRhsLabel());
+          }
+        });
+  };
+  auto addFromOp = [&](mlir::Operation *op) {
+    if (auto blockAddr = mlir::dyn_cast<BlockAddressOp>(op))
+      targetedLabels.insert(blockAddr.getBlockAddrInfo().getLabel());
+    else if (mlir::isa<ConstantOp, GlobalOp>(op))
+      for (mlir::NamedAttribute attr : op->getAttrs())
+        addFromAttr(attr.getValue());
+  };
+  // As in the CFG, addresses taken in static initializers count too.
+  func.getBody().walk(addFromOp);
+  if (auto module = func->getParentOfType<mlir::ModuleOp>())
+    for (GlobalOp global : module.getOps<GlobalOp>())
+      global->walk(addFromOp);
+}
+
+void FallOffAnalyzer::updateLabelAncestors() {
+  if (!labels) {
+    labels.emplace();
+    func.getBody().walk([&](LabelOp label) { labels->push_back(label); });
+  }
+  labelAncestors.clear();
+  for (LabelOp label : *labels) {
+    if (!targetedLabels.contains(label.getLabelAttr()))
+      continue;
+    for (mlir::Operation *parent = label->getParentOp(); parent != func;
+         parent = parent->getParentOp())
+      if (!labelAncestors.insert(parent).second)
+        break;
+  }
+}
+
+Exits FallOffAnalyzer::visitRegion(mlir::Region &region, bool entered) {
+  Exits exits;
+  if (region.empty()) {
+    exits.normal = entered;
+    return exits;
+  }
+
+  // Dead code is still walked when a goto or a switch dispatch may enter it,
+  // and walked again if it turns out live.
+  bool mayHideCase = inEnteredSwitch();
+  auto mustVisitDead = [&](mlir::Operation &op) {
+    return (mayHideCase && op.getNumRegions() != 0) ||
+           containsTargetedLabel(&op);
+  };
+  // Most regions have a single block, which an inline map holds without
+  // allocating.
+  llvm::SmallDenseMap<mlir::Block *, bool, 4> visited;
+  llvm::SmallVector<std::pair<mlir::Block *, bool>> worklist;
+  worklist.push_back({&region.front(), entered});
+  if (!region.hasOneBlock() && (mayHideCase || !targetedLabels.empty()))
+    for (mlir::Block &block : llvm::drop_begin(region))
+      if (llvm::any_of(block, [&](mlir::Operation &op) {
+            return isTargetedLabel(&op) || mustVisitDead(op);
+          }))
+        worklist.push_back({&block, false});
+
+  while (!worklist.empty()) {
+    auto [block, live] = worklist.pop_back_val();
+    auto [it, inserted] = visited.try_emplace(block, live);
+    if (!inserted) {
+      if (it->second || !live)
+        continue;
+      it->second = true;
+    }
+
+    // Querying the terminator trait once per block rather than per operation
+    // is measurably faster.
+    mlir::Operation *terminator =
+        block->mightHaveTerminator() ? &block->back() : nullptr;
+    llvm::SmallVector<mlir::Block *> liveSuccessors;
+    for (mlir::Operation &op : *block) {
+      if (!live) {
+        if (isTargetedLabel(&op)) {
+          live = true;
+          continue;
+        }
+        if (!mustVisitDead(op)) {
+          if (tailOnly && (op.getNumRegions() != 0 || mlir::isa<LabelOp>(op)))
+            unsure = true;
+          continue;
+        }
+      }
+
+      if (op.getNumRegions() != 0) {
+        Exits opExits = visitStructured(&op, live);
+        exits.mergeEscaping(opExits);
+        live = opExits.normal;
+        continue;
+      }
+
+      if (!live)
+        continue;
+
+      if (isNoReturnCall(&op) || isAssumeFalse(&op)) {
+        abnormalEdge = true;
+        live = false;
+      } else if (mlir::isa<ThrowOp>(op)) {
+        fakeEdge = true;
+        live = false;
+      } else if (&op == terminator) {
+        visitTerminator(&op, exits, liveSuccessors);
+        live = false;
+      } else if (tailOnly && mlir::isa<LabelOp>(op)) {
+        unsure = true;
+      }
+    }
+
+    // A block without a terminator falls through to the region's parent.
+    if (live)
+      exits.normal = true;
+
+    for (mlir::Block *succ : liveSuccessors)
+      worklist.push_back({succ, true});
+  }
+  if (tailOnly && visited.size() != llvm::range_size(region))
+    unsure = true;
+  return exits;
+}
+
+void FallOffAnalyzer::visitTerminator(
+    mlir::Operation *op, Exits &exits,
+    llvm::SmallVectorImpl<mlir::Block *> &liveSuccessors) {
+  if (mlir::isa<YieldOp>(op)) {
+    exits.normal = true;
+  } else if (auto condOp = mlir::dyn_cast<ConditionOp>(op)) {
+    std::optional<bool> cond = getConstantBool(condOp.getCondition());
+    exits.condTrue |= cond.value_or(true);
+    exits.condFalse |= !cond.value_or(false);
+  } else if (mlir::isa<CoReturnOp>(op)) {
+    exits.explicitReturn = true;
+  } else if (auto retOp = mlir::dyn_cast<ReturnOp>(op)) {
+    if (retOp.getImplicit())
+      exits.implicitReturn = true;
+    else
+      exits.explicitReturn = true;
+  } else if (mlir::isa<TrapOp, UnreachableOp>(op)) {
+    // User traps and __built...
[truncated]

``````````

</details>


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


More information about the cfe-commits mailing list