[clang] [CIR] -Wreturn-type (1/2): Add an analysis classifying how control reaches a function's end (PR #239774)
Henrich Lauko via cfe-commits
cfe-commits at lists.llvm.org
Tue Dec 1 12:47:51 PST 2026
================
@@ -0,0 +1,712 @@
+//===- CIRFunctionExitAnalysis.cpp - How control leaves 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). Operations implementing RegionBranchOpInterface are
+// walked through their region successors, narrowed by constant operands;
+// break, continue, switches and cleanup scopes are handled on their own.
+// Reachable noreturn calls, user traps and throws are one more kind of exit,
+// the edges CheckFallThrough uses to tell MaybeFallThrough from
+// AlwaysFallThrough.
+//
+//===----------------------------------------------------------------------===//
+
+#include "clang/CIR/Dialect/Analysis/CIRFunctionExitAnalysis.h"
+
+#include "mlir/IR/BuiltinOps.h"
+#include "mlir/IR/Remarks.h"
+#include "mlir/IR/Threading.h"
+#include "mlir/Interfaces/ControlFlowInterfaces.h"
+#include "clang/CIR/Dialect/Analysis/CIRConstantFolding.h"
+#include "clang/CIR/Dialect/IR/CIRDialect.h"
+#include "llvm/ADT/BitmaskEnum.h"
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/DenseSet.h"
+#include "llvm/Support/TimeProfiler.h"
+
+using namespace cir;
+
+namespace {
+
+LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();
+
+/// How control can leave a region or a structured operation.
+enum class Exits : uint8_t {
+ None = 0,
+ /// Falls through to the next operation.
+ Normal = 1 << 0,
+ /// `cir.break` out of the enclosing loop or switch.
+ Break = 1 << 1,
+ /// `cir.continue` to the next loop iteration.
+ Continue = 1 << 2,
+ /// `cir.return` from a return statement, or `cir.co_return`.
+ ExplicitReturn = 1 << 3,
+ /// Reaches the implicit `cir.return` at the end of the body.
+ ImplicitReturn = 1 << 4,
+ /// Noreturn call, trap, throw or `__builtin_unreachable`.
+ NoReturn = 1 << 5,
+ LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/NoReturn)
+};
+
+/// The exits that leave the whole function.
+constexpr Exits functionExits =
+ Exits::ExplicitReturn | Exits::ImplicitReturn | Exits::NoReturn;
+
+/// The exits that leave an enclosing operation too, not just the region.
+constexpr Exits escapingExits = Exits::Break | Exits::Continue | functionExits;
+
+/// Whether control may leave through any of `kinds`.
+bool mayExitVia(Exits exits, Exits kinds) {
+ return (exits & kinds) != Exits::None;
+}
+
+/// The labels gotos can reach. A reached goto may target a label in a region
+/// a walk saw as dead, so the function is walked again until no new label
+/// becomes a target.
+class GotoTargets {
+public:
+ explicit GotoTargets(FuncOp func) : func(func) {}
+
+ /// Forget the gotos the previous walk reached.
+ void startWalk() {
+ reachedGotos.clear();
+ reachedIndirectGoto = false;
+ }
+ void addReachedGoto(GotoOp op) { reachedGotos.insert(op.getLabelAttr()); }
+ /// A cir.indirect_goto can reach every label whose address is taken.
+ void addReachedIndirectGoto() { reachedIndirectGoto = true; }
+ /// Add the labels the walk's gotos target; whether any of them is new.
+ bool finishWalk();
+
+ bool empty() const { return targets.empty(); }
+ bool isTarget(mlir::Operation *op) const {
+ auto label = mlir::dyn_cast<LabelOp>(op);
+ return label && targets.contains(label.getLabelAttr());
+ }
+ /// Whether a target is nested in `op`, so a dead `op` still needs a visit.
+ bool enclosesTarget(mlir::Operation *op) const {
+ return targetAncestors.contains(op);
+ }
+
+private:
+ void addAddressTakenLabels();
+ void updateTargetAncestors();
+
+ FuncOp func;
+ llvm::DenseSet<mlir::StringAttr> targets;
+ llvm::DenseSet<mlir::Operation *> targetAncestors;
+ llvm::DenseSet<mlir::StringAttr> reachedGotos;
+ bool reachedIndirectGoto = false;
+ bool addedAddressTakenLabels = false;
+ /// The function's labels, collected once a goto makes them matter. Never
+ /// empty after that, since a goto only targets a label of this function.
+ llvm::SmallVector<LabelOp> labels;
+};
+
+class FunctionExitAnalyzer {
+public:
+ explicit FunctionExitAnalyzer(FuncOp func) : func(func), gotoTargets(func) {}
+
+ FunctionExitKind run();
+
+ /// Whether `op` may complete normally when control enters it at its start.
+ /// Only exact if no goto can enter `op` through a label inside it.
+ bool mayCompleteWhenEntered(mlir::Operation *op) {
+ return mayExitVia(visitStructured(op, /*entered=*/true), Exits::Normal);
+ }
+
+private:
+ using BranchTerminators =
+ llvm::SmallVectorImpl<mlir::RegionBranchTerminatorOpInterface>;
+
+ /// With `branchTerms`, the reached region branch terminators are collected
+ /// there; otherwise reaching one is a Normal exit.
+ Exits visitRegion(mlir::Region ®ion, bool entered,
+ BranchTerminators *branchTerms = nullptr);
+ Exits visitStructured(mlir::Operation *op, bool entered);
+ Exits visitRegionBranch(mlir::RegionBranchOpInterface op, 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,
+ BranchTerminators *branchTerms);
+
+ FuncOp func;
+ GotoTargets gotoTargets;
+ /// 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;
+
+ /// Makes a switch the innermost one while it is in scope.
+ class SwitchScope {
+ public:
+ SwitchScope(FunctionExitAnalyzer &analyzer, bool entered)
+ : switches(analyzer.switches) {
+ switches.push_back({entered, /*hasDefault=*/false});
+ }
+ SwitchScope(const SwitchScope &) = delete;
+ SwitchScope &operator=(const SwitchScope &) = delete;
+ ~SwitchScope() { switches.pop_back(); }
+
+ /// Whether a default case was dispatched to so far.
+ bool hasDefault() const { return switches.back().hasDefault; }
+
+ private:
+ llvm::SmallVector<SwitchState> &switches;
+ };
+
+ bool inEnteredSwitch() const {
+ return !switches.empty() && switches.back().entered;
+ }
+};
+
+} // namespace
+
+/// The constant values of `op`'s operands, null where unknown, as the region
+/// branch interfaces take them. Only conditions select successors, so only
+/// `!cir.bool` operands are folded.
+static llvm::SmallVector<mlir::Attribute>
+getConstantOperands(mlir::Operation *op) {
+ return llvm::map_to_vector(op->getOperands(), [](mlir::Value value) {
+ return mlir::isa<BoolType>(value.getType()) ? foldToConstant(value)
+ : mlir::Attribute();
+ });
+}
+
+/// Where a `cir.continue` in `loop`'s body goes: where the end of the body
+/// goes.
+static mlir::Region &getLatch(LoopOpInterface loop) {
+ if (mlir::Region *step = loop.maybeGetStep())
+ return *step;
+ if (mlir::Region *cleanup = loop.maybeGetCleanup())
+ return *cleanup;
+ return loop.getCond();
+}
+
+/// `__builtin_assume(0)` is noreturn for the CFG check.
+static bool isAssumeFalse(mlir::Operation *op) {
+ auto assume = mlir::dyn_cast<AssumeOp>(op);
+ return assume && tryFoldConstantBool(assume.getPredicate()) == false;
+}
+
+/// The only operation with regions in a single-block \p region, if any.
+static mlir::Operation *getOnlyRegionOp(mlir::Region ®ion) {
+ 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 reaching
+/// the end of the body.
+// TODO: Drop this once CIRGen emits that handling in the coroutine's planned
+// `unwind` region, leaving only the user's code in `body`.
+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();
+}
+
+FunctionExitKind FunctionExitAnalyzer::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 FunctionExitKind::Unknown;
+ body = &getCoroutineUserBody(coro);
+ }
+
+ // Without gotos, one walk.
+ Exits exits;
+ do {
+ gotoTargets.startWalk();
+ exits = visitRegion(*body, /*entered=*/true);
+ } while (gotoTargets.finishWalk());
+
+ bool explicitReturn = mayExitVia(exits, Exits::ExplicitReturn);
+ if (!mayExitVia(exits, Exits::Normal | Exits::ImplicitReturn))
+ return explicitReturn ? FunctionExitKind::ReturnOnly
+ : FunctionExitKind::NoReturn;
+ if (explicitReturn || mayExitVia(exits, Exits::NoReturn))
+ return FunctionExitKind::MayReachEnd;
+ return FunctionExitKind::MustReachEnd;
+}
+
+bool GotoTargets::finishWalk() {
+ size_t numTargets = targets.size();
+ targets.insert_range(reachedGotos);
+ if (reachedIndirectGoto)
+ addAddressTakenLabels();
+ if (targets.size() == numTargets)
+ return false;
+ updateTargetAncestors();
+ return true;
+}
+
+void GotoTargets::addAddressTakenLabels() {
+ if (addedAddressTakenLabels)
+ return;
+ addedAddressTakenLabels = true;
+ mlir::StringAttr funcName = func.getSymNameAttr();
+ auto addFromOp = [&](mlir::Operation *op) {
+ walkBlockAddressLabels(
+ op, [&](mlir::StringAttr labelFunc, mlir::StringAttr label) {
+ if (labelFunc == funcName)
+ targets.insert(label);
+ });
+ };
+ // 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 GotoTargets::updateTargetAncestors() {
+ if (labels.empty())
+ func.getBody().walk([&](LabelOp label) { labels.push_back(label); });
+ targetAncestors.clear();
+ for (LabelOp label : labels) {
+ if (!targets.contains(label.getLabelAttr()))
+ continue;
+ for (mlir::Operation *parent = label->getParentOp(); parent != func;
+ parent = parent->getParentOp())
+ if (!targetAncestors.insert(parent).second)
+ break;
+ }
+}
+
+Exits FunctionExitAnalyzer::visitRegion(mlir::Region ®ion, bool entered,
+ BranchTerminators *branchTerms) {
+ if (region.empty())
+ return entered ? Exits::Normal : Exits::None;
+
+ // 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) ||
+ gotoTargets.enclosesTarget(&op);
+ };
+ // Most regions have a single block, which an inline map holds without
+ // allocating.
+ Exits exits = Exits::None;
+ llvm::SmallDenseMap<mlir::Block *, bool, 4> visited;
+ llvm::SmallVector<std::pair<mlir::Block *, bool>> worklist;
+ worklist.push_back({®ion.front(), entered});
+ if (!region.hasOneBlock() && (mayHideCase || !gotoTargets.empty()))
+ for (mlir::Block &block : llvm::drop_begin(region))
+ if (llvm::any_of(block, [&](mlir::Operation &op) {
+ return gotoTargets.isTarget(&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 (gotoTargets.isTarget(&op)) {
+ live = true;
+ continue;
+ }
+ if (!mustVisitDead(op))
+ continue;
+ }
+
+ if (op.getNumRegions() != 0) {
+ Exits opExits = visitStructured(&op, live);
+ exits |= opExits & escapingExits;
+ live = mayExitVia(opExits, Exits::Normal);
+ continue;
+ }
+
+ if (!live)
+ continue;
+
+ auto call = mlir::dyn_cast<CallOp>(op);
----------------
xlauko wrote:
Should this also handle `cir.try_call`? `isNoReturn` is on `CIR_CallOpBase`.
https://github.com/llvm/llvm-project/pull/239774
More information about the cfe-commits
mailing list