[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
Fri Dec 4 04:53:36 PST 2026


================
@@ -0,0 +1,681 @@
+//===- 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/ADT/TypeSwitch.h"
+#include "llvm/Support/Threading.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)
+};
+
+} // namespace
+
+/// The exits that leave the whole function.
+static constexpr Exits functionExits =
+    Exits::ExplicitReturn | Exits::ImplicitReturn | Exits::NoReturn;
+
+/// The exits that leave an enclosing operation too, not just the region.
+static constexpr Exits escapingExits =
+    Exits::Break | Exits::Continue | functionExits;
+
+/// Whether control may leave through any of `kinds`.
+static bool mayExitVia(Exits exits, Exits kinds) {
+  return (exits & kinds) != Exits::None;
+}
+
+namespace {
+
+/// The labels whose address a global takes, by function. Collected once per
+/// module, when an analysis first reaches an indirect goto; thread-safe.
+class GlobalBlockAddresses {
+public:
+  explicit GlobalBlockAddresses(mlir::ModuleOp module) : module(module) {}
+
+  llvm::ArrayRef<mlir::StringAttr> lookup(mlir::StringAttr func) {
+    llvm::call_once(collected, [&] { collect(); });
+    auto it = labels.find(func);
+    return it == labels.end() ? llvm::ArrayRef<mlir::StringAttr>() : it->second;
+  }
+
+private:
+  void collect() {
+    if (!module)
+      return;
+    for (GlobalOp global : module.getOps<GlobalOp>())
+      global->walk([&](mlir::Operation *op) {
+        walkBlockAddressLabels(
+            op, [&](mlir::StringAttr func, mlir::StringAttr label) {
+              labels[func].push_back(label);
+            });
+      });
+  }
+
+  mlir::ModuleOp module;
+  llvm::once_flag collected;
+  llvm::DenseMap<mlir::StringAttr, llvm::SmallVector<mlir::StringAttr>> labels;
+};
+
+/// 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:
+  GotoTargets(FuncOp func, GlobalBlockAddresses &globalAddresses)
+      : func(func), globalAddresses(globalAddresses) {}
+
+  /// 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;
+  GlobalBlockAddresses &globalAddresses;
+  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:
+  FunctionExitAnalyzer(FuncOp func, GlobalBlockAddresses &globalAddresses)
+      : func(func), gotoTargets(func, globalAddresses) {}
+
+  FunctionExitKind run();
+
+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 &region, 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;
+  ConstantFolder folder;
+  /// 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(ConstantFolder &folder, mlir::Operation *op) {
+  return llvm::map_to_vector(op->getOperands(), [&](mlir::Value value) {
+    return mlir::isa<BoolType>(value.getType()) ? folder.fold(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();
+}
+
+/// Whether `op` is a call known not to return, e.g. to a [[noreturn]]
+/// function.
+static bool isNoReturnCall(mlir::Operation *op) {
+  auto call = mlir::dyn_cast<CIRCallOpInterface>(op);
+  return call && call.isNoReturn();
+}
----------------
xlauko wrote:

Sema also treats a call through a local function pointer whose every value is noreturn as an abnormal edge (`areAllValuesNoReturn`, AnalysisBasedWarnings.cpp:673-683). So `void (*p)() = die; if (x) return 1; p();` gets `may_reach_end` here, while Sema doesn't warn. Fine to mark NYI with a test and a line in the known differences.

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


More information about the cfe-commits mailing list