[clang] [analyzer][NFC] Cache the AST-only part of the loop unrolling decision (PR #246977)

Balázs Benics via cfe-commits cfe-commits at lists.llvm.org
Sun Nov 29 06:14:08 PST 2026


https://github.com/steakhal created https://github.com/llvm/llvm-project/pull/246977

- With `unroll-loops=true`, `updateLoopStack()` runs `shouldCompletelyUnroll()` every time a path enters a loop.
- Its first half is a pure function of the loop's AST: it rebuilds the large `forLoopMatcher()` tree, matches it, and evaluates the bound.
- Memoize that half per loop in a `LoopUnrollingCache` owned by `ExprEngine`.
- The path-dependent `isPossiblyEscaped()` still runs on every entry, but now builds its matcher once per call instead of once per visited statement.
- `unroll-loops` is off by default, so only users enabling it benefit.

Analysis-time impact (instructions retired in millions, `unroll-loops=true`; inputs are the reproducers from llvm/llvm-project#105512; ON = default graph trimming, OFF = `graph-trim-interval=0`):

    file                           mode  before   after   change
    ruby-unicode.c                 ON    22710    21334   -6.1%
    ruby-unicode.c                 OFF   24059    22545   -6.3%
    linux-topro.c                  ON    61158    60514   -1.1%
    linux-topro.c                  OFF   61628    61185   -0.7%
    clang-MSP430ISelDAGToDAG.cpp   ON    26295    26356   +0.2% (noise)
    clang-MSP430ISelDAGToDAG.cpp   OFF   26809    26697   -0.4% (noise)

20 clang/lib TUs analyzed with their own compile flags and the same config (instructions retired in billions; user CPU seconds):

| TU | instr before (G) | instr after (G) | change | spread b/a | user s |
|---|---|---|---|---|---|
| CodeGen/CGBuiltin.cpp | 137.0 | 132.4 | -3.37% | 2.86% / 2.06% | 16.9 -> 14.4 |
| CodeGen/CGCall.cpp | 236.6 | 234.2 | -1.00% | 3.57% / 4.43% | 24.2 -> 21.8 |
| Sema/SemaLookup.cpp | 269.4 | 267.6 | -0.66% | 0.22% / 0.18% | 23.2 -> 23.1 |
| AST/ASTContext.cpp | 1003.8 | 998.1 | -0.57% | 1.98% / 0.02% | 92.1 -> 89.2 |
| Sema/SemaDeclCXX.cpp | 880.0 | 875.0 | -0.56% | 0.04% / 0.06% | 77.2 -> 77.2 |
| Sema/SemaTemplate.cpp | 369.6 | 367.6 | -0.53% | 0.09% / 0.02% | 33.2 -> 32.8 |
| Sema/SemaDecl.cpp | 508.7 | 506.2 | -0.48% | 0.05% / 0.13% | 45.8 -> 45.5 |
| Sema/SemaExprCXX.cpp | 282.4 | 281.3 | -0.39% | 0.17% / 0.26% | 26.0 -> 26.1 |
| Sema/SemaOverload.cpp | 542.3 | 540.8 | -0.28% | 0.02% / 0.03% | 47.4 -> 47.0 |
| Sema/SemaExpr.cpp | 693.1 | 691.1 | -0.28% | 0.23% / 0.06% | 63.7 -> 64.1 |
| Sema/SemaInit.cpp | 226.9 | 226.3 | -0.27% | 0.05% / 0.13% | 19.7 -> 19.8 |
| CodeGen/CGStmt.cpp | 89.1 | 88.8 | -0.27% | 0.23% / 0.29% | 8.0 -> 7.9 |
| AST/ExprConstant.cpp | 1354.0 | 1350.5 | -0.26% | 1.39% / 0.05% | 117.6 -> 118.5 |
| Sema/SemaStmt.cpp | 240.9 | 240.3 | -0.23% | 0.06% / 0.03% | 21.4 -> 21.4 |
| CodeGen/CGExpr.cpp | 382.6 | 381.7 | -0.22% | 0.02% / 0.05% | 35.0 -> 34.3 |
| Sema/SemaType.cpp | 253.0 | 252.4 | -0.22% | 0.03% / 0.10% | 22.7 -> 22.5 |
| Sema/SemaChecking.cpp | 649.6 | 648.4 | -0.19% | 0.34% / 0.45% | 58.9 -> 59.0 |
| Sema/SemaDeclAttr.cpp | 508.2 | 507.7 | -0.10% | 0.15% / 0.10% | 47.1 -> 47.2 |
| Parse/ParseDecl.cpp | 172.9 | 172.8 | -0.08% | 0.10% / 0.10% | 15.7 -> 15.7 |
| Parse/ParseExpr.cpp | 65.6 | 65.6 | -0.02% | 0.01% / 0.03% | 5.8 -> 5.9 |
| **Total (20 TUs)** | 8865.7 | 8829.1 | -0.41% | | 801 -> 793 (-1.0%) |

- Diagnostics are byte-identical on all inputs.

Assisted-by: Claude

>From 10c9efa257b953abbd0831298da262d47417f5ca Mon Sep 17 00:00:00 2001
From: Balazs Benics <benicsbalazs at gmail.com>
Date: Sun, 29 Nov 2026 14:08:55 +0000
Subject: [PATCH] [analyzer][NFC] Cache the AST-only part of the loop unrolling
 decision

- With `unroll-loops=true`, `updateLoopStack()` runs `shouldCompletelyUnroll()`
  every time a path enters a loop.
- Its first half is a pure function of the loop's AST: it rebuilds the large
  `forLoopMatcher()` tree, matches it, and evaluates the bound.
- Memoize that half per loop in a `LoopUnrollingCache` owned by `ExprEngine`.
- The path-dependent `isPossiblyEscaped()` still runs on every entry, but now
  builds its matcher once per call instead of once per visited statement.
- `unroll-loops` is off by default, so only users enabling it benefit.

Analysis-time impact (instructions retired in millions, `unroll-loops=true`;
inputs are the reproducers from llvm/llvm-project#105512;
ON = default graph trimming, OFF = `graph-trim-interval=0`):

    file                           mode  before   after   change
    ruby-unicode.c                 ON    22710    21334   -6.1%
    ruby-unicode.c                 OFF   24059    22545   -6.3%
    linux-topro.c                  ON    61158    60514   -1.1%
    linux-topro.c                  OFF   61628    61185   -0.7%
    clang-MSP430ISelDAGToDAG.cpp   ON    26295    26356   +0.2% (noise)
    clang-MSP430ISelDAGToDAG.cpp   OFF   26809    26697   -0.4% (noise)

20 clang/lib TUs analyzed with their own compile flags and the same config
(instructions retired in billions; user CPU seconds):

| TU | instr before (G) | instr after (G) | change | spread b/a | user s |
|---|---|---|---|---|---|
| CodeGen/CGBuiltin.cpp | 137.0 | 132.4 | -3.37% | 2.86% / 2.06% | 16.9 -> 14.4 |
| CodeGen/CGCall.cpp | 236.6 | 234.2 | -1.00% | 3.57% / 4.43% | 24.2 -> 21.8 |
| Sema/SemaLookup.cpp | 269.4 | 267.6 | -0.66% | 0.22% / 0.18% | 23.2 -> 23.1 |
| AST/ASTContext.cpp | 1003.8 | 998.1 | -0.57% | 1.98% / 0.02% | 92.1 -> 89.2 |
| Sema/SemaDeclCXX.cpp | 880.0 | 875.0 | -0.56% | 0.04% / 0.06% | 77.2 -> 77.2 |
| Sema/SemaTemplate.cpp | 369.6 | 367.6 | -0.53% | 0.09% / 0.02% | 33.2 -> 32.8 |
| Sema/SemaDecl.cpp | 508.7 | 506.2 | -0.48% | 0.05% / 0.13% | 45.8 -> 45.5 |
| Sema/SemaExprCXX.cpp | 282.4 | 281.3 | -0.39% | 0.17% / 0.26% | 26.0 -> 26.1 |
| Sema/SemaOverload.cpp | 542.3 | 540.8 | -0.28% | 0.02% / 0.03% | 47.4 -> 47.0 |
| Sema/SemaExpr.cpp | 693.1 | 691.1 | -0.28% | 0.23% / 0.06% | 63.7 -> 64.1 |
| Sema/SemaInit.cpp | 226.9 | 226.3 | -0.27% | 0.05% / 0.13% | 19.7 -> 19.8 |
| CodeGen/CGStmt.cpp | 89.1 | 88.8 | -0.27% | 0.23% / 0.29% | 8.0 -> 7.9 |
| AST/ExprConstant.cpp | 1354.0 | 1350.5 | -0.26% | 1.39% / 0.05% | 117.6 -> 118.5 |
| Sema/SemaStmt.cpp | 240.9 | 240.3 | -0.23% | 0.06% / 0.03% | 21.4 -> 21.4 |
| CodeGen/CGExpr.cpp | 382.6 | 381.7 | -0.22% | 0.02% / 0.05% | 35.0 -> 34.3 |
| Sema/SemaType.cpp | 253.0 | 252.4 | -0.22% | 0.03% / 0.10% | 22.7 -> 22.5 |
| Sema/SemaChecking.cpp | 649.6 | 648.4 | -0.19% | 0.34% / 0.45% | 58.9 -> 59.0 |
| Sema/SemaDeclAttr.cpp | 508.2 | 507.7 | -0.10% | 0.15% / 0.10% | 47.1 -> 47.2 |
| Parse/ParseDecl.cpp | 172.9 | 172.8 | -0.08% | 0.10% / 0.10% | 15.7 -> 15.7 |
| Parse/ParseExpr.cpp | 65.6 | 65.6 | -0.02% | 0.01% / 0.03% | 5.8 -> 5.9 |
| **Total (20 TUs)** | 8865.7 | 8829.1 | -0.41% | | 801 -> 793 (-1.0%) |

- Diagnostics are byte-identical on all inputs.

Assisted-by: Claude
---
 .../Core/PathSensitive/ExprEngine.h           |  8 ++-
 .../Core/PathSensitive/LoopUnrolling.h        | 22 +++++++-
 clang/lib/StaticAnalyzer/Core/ExprEngine.cpp  |  3 +-
 .../lib/StaticAnalyzer/Core/LoopUnrolling.cpp | 52 +++++++++++++------
 4 files changed, 65 insertions(+), 20 deletions(-)

diff --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
index 5344087ed94263..7d00197697ba14 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
@@ -21,18 +21,19 @@
 #include "clang/Analysis/DomainSpecific/ObjCNoReturn.h"
 #include "clang/Analysis/ProgramPoint.h"
 #include "clang/Basic/LLVM.h"
-#include "clang/StaticAnalyzer/Core/CheckerManager.h"
 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h"
+#include "clang/StaticAnalyzer/Core/CheckerManager.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/FunctionSummary.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/LoopUnrolling.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
-#include "clang/StaticAnalyzer/Core/PathSensitive/Store.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/Store.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/WorkList.h"
 #include "llvm/ADT/ArrayRef.h"
 #include <cassert>
@@ -162,6 +163,9 @@ class ExprEngine {
   /// implicitly never returns.
   ObjCNoReturn ObjCNoRet;
 
+  /// AST-derived loop unrolling decisions, shared by all paths.
+  LoopUnrollingCache LoopCache;
+
   /// The BugReporter associated with this engine. It is important that
   /// this object be placed at the very end of member variables so that its
   /// destructor is called before the rest of the ExprEngine is destroyed.
diff --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/LoopUnrolling.h b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/LoopUnrolling.h
index eb2b0b343428f6..3738431a95f5c5 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/LoopUnrolling.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/LoopUnrolling.h
@@ -24,18 +24,36 @@
 #define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_LOOPUNROLLING_H
 
 #include "clang/Analysis/CFG.h"
-#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
+#include "llvm/ADT/DenseMap.h"
 namespace clang {
 namespace ento {
 
+/// Memoizes the part of the loop unrolling decision that depends only on the
+/// AST of a loop (as opposed to the path that reached it), so that the AST
+/// matchers run once per loop instead of every time a path enters the loop.
+struct LoopUnrollingCache {
+  struct Entry {
+    /// The loop counter reference, or null if the loop is not a candidate for
+    /// complete unrolling.
+    const DeclRefExpr *CounterVarRef = nullptr;
+    unsigned MaxStep = 0;
+  };
+  /// The entry of a loop that is not a candidate for complete unrolling.
+  static const Entry NotUnrollable;
+
+  llvm::DenseMap<const Stmt *, Entry> Entries;
+};
+
 /// Returns if the given State indicates that is inside a completely unrolled
 /// loop.
 bool isUnrolledState(ProgramStateRef State);
 
 /// Updates the stack of loops contained by the ProgramState.
 ProgramStateRef updateLoopStack(const Stmt *LoopStmt, ASTContext &ASTCtx,
-                                ExplodedNode* Pred, unsigned maxVisitOnPath);
+                                ExplodedNode *Pred, unsigned maxVisitOnPath,
+                                LoopUnrollingCache &Cache);
 
 /// Updates the given ProgramState. In current implementation it removes the top
 /// element of the stack of loops.
diff --git a/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp b/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
index 7860c349b1c104..d9669b872cf395 100644
--- a/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
+++ b/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
@@ -2478,7 +2478,8 @@ ExplodedNode *ExprEngine::processCFGBlockEntrance(const BlockEntrance &BE,
   // then consider completely unrolling it.
   if (AMgr.options.ShouldUnrollLoops) {
     if (Term)
-      State = updateLoopStack(Term, AMgr.getASTContext(), Pred, MaxBlockVisit);
+      State = updateLoopStack(Term, AMgr.getASTContext(), Pred, MaxBlockVisit,
+                              LoopCache);
     // Is we are inside an unrolled loop then no need the check the counters.
     if (isUnrolledState(State))
       return Engine.makeNode(BE, State.get(), Pred);
diff --git a/clang/lib/StaticAnalyzer/Core/LoopUnrolling.cpp b/clang/lib/StaticAnalyzer/Core/LoopUnrolling.cpp
index 02e076219b612b..3d12d56921ec33 100644
--- a/clang/lib/StaticAnalyzer/Core/LoopUnrolling.cpp
+++ b/clang/lib/StaticAnalyzer/Core/LoopUnrolling.cpp
@@ -224,6 +224,11 @@ static bool isPossiblyEscaped(ExplodedNode *N, const DeclRefExpr *DR) {
       (IsRefParamOrCapture && VD->getType()->isReferenceType()))
     return true;
 
+  // Building the matcher is expensive, so do it once for the whole walk.
+  const auto EscapeMatcher =
+      stmt(anyOf(callByRef(equalsNode(VD)), getAddrTo(equalsNode(VD)),
+                 assignedToRef(equalsNode(VD))));
+
   while (!N->pred_empty()) {
     // FIXME: getStmtForDiagnostics() does nasty things in order to provide
     // a valid statement for body farms, do we need this behavior here?
@@ -251,10 +256,7 @@ static bool isPossiblyEscaped(ExplodedNode *N, const DeclRefExpr *DR) {
     ASTContext &ASTCtx =
         N->getStackFrame()->getAnalysisDeclContext()->getASTContext();
     // Case 3 and 4:
-    auto Match =
-        match(stmt(anyOf(callByRef(equalsNode(VD)), getAddrTo(equalsNode(VD)),
-                         assignedToRef(equalsNode(VD)))),
-              *S, ASTCtx);
+    auto Match = match(EscapeMatcher, *S, ASTCtx);
     if (!Match.empty())
       return true;
 
@@ -268,15 +270,17 @@ static bool isPossiblyEscaped(ExplodedNode *N, const DeclRefExpr *DR) {
   llvm_unreachable("Reached root without finding the declaration of VD");
 }
 
-static bool shouldCompletelyUnroll(const Stmt *LoopStmt, ASTContext &ASTCtx,
-                                   ExplodedNode *Pred, unsigned &maxStep) {
-
-  if (!isLoopStmt(LoopStmt))
-    return false;
+const LoopUnrollingCache::Entry LoopUnrollingCache::NotUnrollable = {nullptr,
+                                                                     0};
 
+/// Returns the loop counter reference of \p LoopStmt and the number of
+/// iterations if the loop has the shape that can be completely unrolled.
+/// This depends only on the AST.
+static LoopUnrollingCache::Entry analyzeLoopShape(const Stmt *LoopStmt,
+                                                  ASTContext &ASTCtx) {
   auto Matches = match(forLoopMatcher(), *LoopStmt, ASTCtx);
   if (Matches.empty())
-    return false;
+    return LoopUnrollingCache::NotUnrollable;
 
   const auto *CounterVarRef = Matches[0].getNodeAs<DeclRefExpr>("initVarRef");
   const Expr *BoundNumExpr = Matches[0].getNodeAs<Expr>("boundNum");
@@ -284,7 +288,7 @@ static bool shouldCompletelyUnroll(const Stmt *LoopStmt, ASTContext &ASTCtx,
   Expr::EvalResult BoundNumResult;
   if (!BoundNumExpr || !BoundNumExpr->EvaluateAsInt(BoundNumResult, ASTCtx,
                                                     Expr::SE_NoSideEffects)) {
-    return false;
+    return LoopUnrollingCache::NotUnrollable;
   }
   llvm::APInt InitNum =
       Matches[0].getNodeAs<IntegerLiteral>("initNum")->getValue();
@@ -294,10 +298,27 @@ static bool shouldCompletelyUnroll(const Stmt *LoopStmt, ASTContext &ASTCtx,
 
   InitNum = InitNum.zext(MaxWidth);
   llvm::APInt BoundNum = BoundNumResult.Val.getInt().zext(MaxWidth);
+  unsigned MaxStep;
   if (CondOp->getOpcode() == BO_GE || CondOp->getOpcode() == BO_LE)
-    maxStep = (BoundNum - InitNum + 1).abs().getZExtValue();
+    MaxStep = (BoundNum - InitNum + 1).abs().getZExtValue();
   else
-    maxStep = (BoundNum - InitNum).abs().getZExtValue();
+    MaxStep = (BoundNum - InitNum).abs().getZExtValue();
+  return {CounterVarRef, MaxStep};
+}
+
+static bool shouldCompletelyUnroll(const Stmt *LoopStmt, ASTContext &ASTCtx,
+                                   ExplodedNode *Pred, unsigned &maxStep,
+                                   LoopUnrollingCache &Cache) {
+  if (!isLoopStmt(LoopStmt))
+    return false;
+
+  auto [It, Inserted] = Cache.Entries.try_emplace(LoopStmt);
+  if (Inserted)
+    It->second = analyzeLoopShape(LoopStmt, ASTCtx);
+  const DeclRefExpr *CounterVarRef = It->second.CounterVarRef;
+  if (!CounterVarRef)
+    return false;
+  maxStep = It->second.MaxStep;
 
   // Check if the counter of the loop is not escaped before.
   return !isPossiblyEscaped(Pred, CounterVarRef);
@@ -324,7 +345,8 @@ static bool madeNewBranch(ExplodedNode *N, const Stmt *LoopStmt) {
 
 // updateLoopStack is called on every basic block, therefore it needs to be fast
 ProgramStateRef updateLoopStack(const Stmt *LoopStmt, ASTContext &ASTCtx,
-                                ExplodedNode *Pred, unsigned maxVisitOnPath) {
+                                ExplodedNode *Pred, unsigned maxVisitOnPath,
+                                LoopUnrollingCache &Cache) {
   auto State = Pred->getState();
   auto SF = Pred->getStackFrame();
 
@@ -342,7 +364,7 @@ ProgramStateRef updateLoopStack(const Stmt *LoopStmt, ASTContext &ASTCtx,
     return State;
   }
   unsigned maxStep;
-  if (!shouldCompletelyUnroll(LoopStmt, ASTCtx, Pred, maxStep)) {
+  if (!shouldCompletelyUnroll(LoopStmt, ASTCtx, Pred, maxStep, Cache)) {
     State = State->add<LoopStack>(
         LoopState::getNormal(LoopStmt, SF, maxVisitOnPath));
     return State;



More information about the cfe-commits mailing list