← Back to Pull requests

[clang][-Wunsafe-buffer-usage] Cache the analysis gate per diagnostic state #240433

Open
ilyas-mallah opened this pull request with 85 lines diff across 4 files
View on GitHub
ilyas-mallah ilyas-mallah commented on Nov 09, 2026 15:58 UTC
Author

Follow-up to #233604. shouldRunUnsafeBufferUsageAnalysis runs after every function definition, with or without -Wunsafe-buffer-usage, and makes one isIgnored call per diagnostic. The libc-call warning became eight diagnostics, so with the warnings off the gate makes 12 calls per function instead of 5.

The answer is now cached per diagnostic state, keyed and flushed like getPolicyInEffectAt. PredefinedNames is a DenseMap<StringRef>, as aengelke asked in https://github.com/llvm/llvm-project/pull/233604#discussion_r4511893589. The new test changes a subgroup with pragmas between functions and fails if the cache ignores the diagnostic state.

I measured instructions:u with perf stat (release build, no assertions, ASLR off, two runs each) against the same tree without the cache. Interp.cpp at -O3 with its PCH, as CMake builds it: -0.23%. Interp.cpp, SemaDecl.cpp and ParseDecl.cpp with -fsyntax-only: -0.67% to -0.81%. The compile-time tracker measures the clang build at -0.15% instructions:u, nearly all of the +0.166% that #233604 added.

AI usage: Claude Code helped with the test runs and test scaffolding. I traced the issue, made the fix, and validated every change.

Diff: 85 lines (+75 / -10) across 4 files Reviewer: kazutakahirata Review duration: 36184m
All Vouch review confidence checks passed
Residual risk 0.03 = Change Risk (0.34) × (1 − Review Confidence (0.90)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.34 · 85 lines diff across 4 files
0.34
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.88 · 5 substantive comment(s)
0.88
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
90%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.266
Real PR Conversation Timeline
11 items
llvmorg-github-actions[bot] llvmorg-github-actions[bot] commented on Nov 09, 2026 15:59 UTC
Bot

<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-clang

@llvm/pr-subscribers-clang-analysis

Author: Ilyas Mallah (ilyas-mallah)

<details>
<summary>Changes</summary>

Follow-up to #<!-- -->233604. shouldRunUnsafeBufferUsageAnalysis runs after every function definition, with or without -Wunsafe-buffer-usage, and makes one isIgnored call per diagnostic. The libc-call warning became eight diagnostics, so with the warnings off the gate makes 12 calls per function instead of 5.

The answer is now cached per diagnostic state, keyed and flushed like getPolicyInEffectAt. PredefinedNames is a DenseMap&lt;StringRef&gt;, as aengelke asked in https://github.com/llvm/llvm-project/pull/233604#discussion_r4511893589. The new test changes a subgroup with pragmas between functions and fails if the cache ignores the diagnostic state.

I measured instructions:u with perf stat (release build, no assertions, ASLR off, two runs each) against the same tree without the cache. Interp.cpp at -O3 with its PCH, as CMake builds it: -0.23%. Interp.cpp, SemaDecl.cpp and ParseDecl.cpp with -fsyntax-only: -0.67% to -0.81%. I couldn't reproduce the tracker's setup, so I can't say how much of its +0.166% this recovers.

AI usage: Claude Code helped with the test runs and test scaffolding. I traced the issue, made the fix, and validated every change.

---
Full diff: https://github.com/llvm/llvm-project/pull/240433.diff

4 Files Affected:

  • (modified) clang/include/clang/Sema/AnalysisBasedWarnings.h (+11-1)

  • (modified) clang/lib/Analysis/UnsafeBufferUsage.cpp (+4-4)

  • (modified) clang/lib/Sema/AnalysisBasedWarnings.cpp (+26-5)

  • (added) clang/test/SemaCXX/warn-unsafe-buffer-usage-in-libc-call-pragma.cpp (+36)
  • ``````

    diff --git a/clang/include/clang/Sema/AnalysisBasedWarnings.h b/clang/include/clang/Sema/AnalysisBasedWarnings.h
    index ea54f7e5ee8aa6..9e217aa36c1660 100644
    --- a/clang/include/clang/Sema/AnalysisBasedWarnings.h
    +++ b/clang/include/clang/Sema/AnalysisBasedWarnings.h
    @@ -71,6 +71,15 @@ class AnalysisBasedWarnings {
       llvm::DenseMap<const void *, Policy>
           PolicyCache[static_cast<unsigned>(DiagStateSystemClass::NUM_CLASSES)];
     
    +  /// Caches results for shouldRunUnsafeBufferUsageAnalysis(), keyed like
    +  /// PolicyCache and flushed with it.
    +  llvm::DenseMap<const void *, bool>
    +      UnsafeBufferUsageCache[static_cast<unsigned>(
    +          DiagStateSystemClass::NUM_CLASSES)];
    +
    +  /// \return true iff a -Wunsafe-buffer-usage analysis is enabled at \p Loc.
    +  bool shouldRunUnsafeBufferUsageAnalysis(SourceLocation Loc);
    +
       /// \name Statistics
       /// @{
     
    @@ -139,7 +148,8 @@ class AnalysisBasedWarnings {
       // will override the policy used to issue warnings.
       Policy &getPolicyOverrides() { return PolicyOverrides; }
     
    -  /// Drop cached getPolicyInEffectAt() results (diagnostic state changed).
    +  /// Drop cached getPolicyInEffectAt() and shouldRunUnsafeBufferUsageAnalysis()
    +  /// results (diagnostic state changed).
       void clearPolicyCache();
     
       void PrintStats() const;
    diff --git a/clang/lib/Analysis/UnsafeBufferUsage.cpp b/clang/lib/Analysis/UnsafeBufferUsage.cpp
    index b68fc2f20dc56f..388beffb14c534 100644
    --- a/clang/lib/Analysis/UnsafeBufferUsage.cpp
    +++ b/clang/lib/Analysis/UnsafeBufferUsage.cpp
    @@ -28,10 +28,10 @@
     #include "clang/Lex/Preprocessor.h"
     #include "llvm/ADT/APInt.h"
     #include "llvm/ADT/APSInt.h"
    +#include "llvm/ADT/DenseMap.h"
     #include "llvm/ADT/STLExtras.h"
     #include "llvm/ADT/STLFunctionalExtras.h"
     #include "llvm/ADT/SmallVector.h"
    -#include "llvm/ADT/StringMap.h"
     #include "llvm/ADT/StringRef.h"
     #include <cstddef>
     #include <optional>
    @@ -1159,9 +1159,9 @@ hasUnsafeFormatOrSArg(ASTContext &Ctx, const CallExpr *Call,
     // match.
     static std::optional<UnsafeLibcFunctionFamily>
     getPredefinedUnsafeLibcFuncFamily(const FunctionDecl &Node) {
    -  static const llvm::StringMap<UnsafeLibcFunctionFamily> PredefinedNames = [] {
    -    using F = UnsafeLibcFunctionFamily;
    -    llvm::StringMap<F> M;
    +  using F = UnsafeLibcFunctionFamily;
    +  static const llvm::DenseMap<StringRef, F> PredefinedNames = [] {
    +    llvm::DenseMap<StringRef, F> M;
         auto Add = [&](F Family, std::initializer_list<StringRef> Names) {
           for (StringRef N : Names)
             M[N] = Family;
    diff --git a/clang/lib/Sema/AnalysisBasedWarnings.cpp b/clang/lib/Sema/AnalysisBasedWarnings.cpp
    index de5eb3f093e41b..9b9f627afd8f6d 100644
    --- a/clang/lib/Sema/AnalysisBasedWarnings.cpp
    +++ b/clang/lib/Sema/AnalysisBasedWarnings.cpp
    @@ -2925,6 +2925,8 @@ sema::AnalysisBasedWarnings::getPolicyInEffectAt(SourceLocation Loc) {
     void sema::AnalysisBasedWarnings::clearPolicyCache() {
       for (auto &M : PolicyCache)
         M.clear();
    +  for (auto &M : UnsafeBufferUsageCache)
    +    M.clear();
     }
     
     void sema::AnalysisBasedWarnings::clearOverrides() {
    @@ -3103,8 +3105,8 @@ LifetimeSafetyTUAnalysis(Sema &S, TranslationUnitDecl *TU,
       }
     }
     
    -static bool shouldRunUnsafeBufferUsageAnalysis(const Sema &S,
    -                                               SourceLocation Loc) {
    +static bool isUnsafeBufferUsageAnalysisEnabledAt(const Sema &S,
    +                                                 SourceLocation Loc) {
       const DiagnosticsEngine &Diags = S.getDiagnostics();
       return !Diags.isIgnored(diag::warn_unsafe_buffer_operation, Loc) ||
              !Diags.isIgnored(diag::warn_unsafe_buffer_variable, Loc) ||
    @@ -3116,6 +3118,25 @@ static bool shouldRunUnsafeBufferUsageAnalysis(const Sema &S,
                !Diags.isIgnored(diag::warn_unsafe_buffer_format_attr_call, Loc)));
     }
     
    +// This runs at the end of every function definition, so the answer is cached
    +// on the diagnostic state at Loc like getPolicyInEffectAt().
    +bool sema::AnalysisBasedWarnings::shouldRunUnsafeBufferUsageAnalysis(
    +    SourceLocation Loc) {
    +  DiagnosticsEngine &D = S.getDiagnostics();
    +  if (D.hasDiagSuppressionMapping() || Loc.isInvalid())
    +    return isUnsafeBufferUsageAnalysisEnabledAt(S, Loc);
    +
    +  const void *StateKey = D.getDiagStateKeyForLoc(Loc);
    +  auto &Cache = UnsafeBufferUsageCache[static_cast<unsigned>(
    +      D.getDiagStateSystemClassForLoc(Loc))];
    +  auto It = Cache.find(StateKey);
    +  if (It != Cache.end())
    +    return It->second;
    +  bool Enabled = isUnsafeBufferUsageAnalysisEnabledAt(S, Loc);
    +  Cache[StateKey] = Enabled;
    +  return Enabled;
    +}
    +
     /// \return true iff fix-its should be emitted along with -Wunsafe-buffer-usage
     /// warnings
     static bool shouldEmitUnsafeBufferUsageSuggestions(const Sema &S) {
    @@ -3156,7 +3177,7 @@ void clang::sema::AnalysisBasedWarnings::IssueWarnings(
             return;
     
           // Perform unsafe buffer usage analysis:
    -      if (shouldRunUnsafeBufferUsageAnalysis(S, Node->getBeginLoc())) {
    +      if (shouldRunUnsafeBufferUsageAnalysis(Node->getBeginLoc())) {
             clang::checkUnsafeBufferUsage(Node, R,
                                           /*EmitSuggestion =*/true);
           }
    @@ -3166,7 +3187,7 @@ void clang::sema::AnalysisBasedWarnings::IssueWarnings(
         // Emit per-function analysis-based warnings that require the whole-TU
         // reasoning. Check if any of them is enabled at all before scanning the
         // AST:
    -    if (shouldRunUnsafeBufferUsageAnalysis(S, SourceLocation())) {
    +    if (shouldRunUnsafeBufferUsageAnalysis(SourceLocation())) {
           CallableVisitor(CallAnalyzers, TU->getOwningModule())
               .TraverseTranslationUnitDecl(TU);
         }
    @@ -3445,7 +3466,7 @@ void clang::sema::AnalysisBasedWarnings::IssueWarnings(
                                     shouldSuggestUnsafeBufferUsageSuggestions(S));
     
         // Perform unsafe buffer usage analysis:
    -    if (shouldRunUnsafeBufferUsageAnalysis(S, D->getBeginLoc())) {
    +    if (shouldRunUnsafeBufferUsageAnalysis(D->getBeginLoc())) {
           clang::checkUnsafeBufferUsage(
               D, R, /*UnsafeBufferUsageShouldEmitSuggestions=*/false);
         }
    diff --git a/clang/test/SemaCXX/warn-unsafe-buffer-usage-in-libc-call-pragma.cpp b/clang/test/SemaCXX/warn-unsafe-buffer-usage-in-libc-call-pragma.cpp
    new file mode 100644
    index 00000000000000..e8f2350a0882de
    --- /dev/null
    +++ b/clang/test/SemaCXX/warn-unsafe-buffer-usage-in-libc-call-pragma.cpp
    @@ -0,0 +1,36 @@
    +// RUN: %clang_cc1 -std=c++20 -verify %s
    +
    +// The analysis is skipped for a function when none of its warnings is
    +// enabled, so changing a libc-call subgroup with a pragma between functions
    +// has to change what runs.
    +
    +typedef __SIZE_TYPE__ size_t;
    +
    +void *memcpy(void *, const void *, size_t);
    +
    +void before(void *p, const void *q, size_t n) {
    +  memcpy(p, q, n);
    +}
    +
    +#pragma clang diagnostic warning "-Wunsafe-buffer-usage-in-libc-call-memory"
    +
    +void enabled(void *p, const void *q, size_t n) {
    +  memcpy(p, q, n); // expected-warning{{function 'memcpy' is unsafe}}
    +}
    +
    +// A function is checked after the pragmas that follow it are read, so this
    +// declaration makes ignored() the first function checked once they apply.
    +void ignored(void *p, const void *q, size_t n);
    +
    +#pragma clang diagnostic push
    +#pragma clang diagnostic ignored "-Wunsafe-buffer-usage-in-libc-call-memory"
    +
    +void ignored(void *p, const void *q, size_t n) {
    +  memcpy(p, q, n);
    +}
    +
    +#pragma clang diagnostic pop
    +
    +void enabled_again(void *p, const void *q, size_t n) {
    +  memcpy(p, q, n); // expected-warning{{function 'memcpy' is unsafe}}
    +}
    
    
    ``````

    </details>

    kazutakahirata kazutakahirata commented on code on Nov 09, 2026 17:17 UTC
    Code Review
    clang/lib/Sema/AnalysisBasedWarnings.cpp:1
    @@ -3116,6 +3118,25 @@ static bool shouldRunUnsafeBufferUsageAnalysis(const Sema &S,
                !Diags.isIgnored(diag::warn_unsafe_buffer_format_attr_call, Loc)));
     }
     
    +// This runs at the end of every function definition, so the answer is cached
    +// on the diagnostic state at Loc like getPolicyInEffectAt().
    +bool sema::AnalysisBasedWarnings::shouldRunUnsafeBufferUsageAnalysis(
    +    SourceLocation Loc) {
    +  DiagnosticsEngine &D = S.getDiagnostics();
    +  if (D.hasDiagSuppressionMapping() || Loc.isInvalid())
    +    return isUnsafeBufferUsageAnalysisEnabledAt(S, Loc);
    +
    +  const void *StateKey = D.getDiagStateKeyForLoc(Loc);
    +  auto &Cache = UnsafeBufferUsageCache[static_cast<unsigned>(
    +      D.getDiagStateSystemClassForLoc(Loc))];
    +  auto It = Cache.find(StateKey);
    +  if (It != Cache.end())
    +    return It->second;
    +  bool Enabled = isUnsafeBufferUsageAnalysisEnabledAt(S, Loc);
    +  Cache[StateKey] = Enabled;
    +  return Enabled;

    Nit: Could we use try_emplace here to avoid a second DenseMap lookup on cache misses?

      auto [It, Inserted] = Cache.try_emplace(StateKey);
      if (Inserted)
        It->second = isUnsafeBufferUsageAnalysisEnabledAt(S, Loc);
      return It->second;
    

    ilyas-mallah ilyas-mallah commented on code on Nov 09, 2026 20:58 UTC
    Code Review
    clang/lib/Sema/AnalysisBasedWarnings.cpp:1
    @@ -3116,6 +3118,25 @@ static bool shouldRunUnsafeBufferUsageAnalysis(const Sema &S,
                !Diags.isIgnored(diag::warn_unsafe_buffer_format_attr_call, Loc)));
     }
     
    +// This runs at the end of every function definition, so the answer is cached
    +// on the diagnostic state at Loc like getPolicyInEffectAt().
    +bool sema::AnalysisBasedWarnings::shouldRunUnsafeBufferUsageAnalysis(
    +    SourceLocation Loc) {
    +  DiagnosticsEngine &D = S.getDiagnostics();
    +  if (D.hasDiagSuppressionMapping() || Loc.isInvalid())
    +    return isUnsafeBufferUsageAnalysisEnabledAt(S, Loc);
    +
    +  const void *StateKey = D.getDiagStateKeyForLoc(Loc);
    +  auto &Cache = UnsafeBufferUsageCache[static_cast<unsigned>(
    +      D.getDiagStateSystemClassForLoc(Loc))];
    +  auto It = Cache.find(StateKey);
    +  if (It != Cache.end())
    +    return It->second;
    +  bool Enabled = isUnsafeBufferUsageAnalysisEnabledAt(S, Loc);
    +  Cache[StateKey] = Enabled;
    +  return Enabled;

    Done!

    ilyas-mallah ilyas-mallah commented on Nov 27, 2026 13:02 UTC
    Author

    @aengelke @kazutakahirata CI hadn't run on the last head, so I merged main. Linux and Windows pass now. The macOS job stops at CMake configure because the runner's CMake needs a newer macOS. This is the compile-time follow-up to #233604. Could one of you take a look?

    aengelke aengelke commented on Nov 27, 2026 13:04 UTC
    Contributor

    /compile-time

    llvm-compile-time-bot llvm-compile-time-bot commented on Nov 27, 2026 13:35 UTC
    Bot

    Compile-time results for dad92a8d0c3890de680d4e188028924af15e1e51 (base 3f679c2a42e1a018b4539bb81e31529deb4ce647):
    https://llvm-compile-time-tracker.com/compare.php?from=3f679c2a42e1a018b4539bb81e31529deb4ce647&to=dad92a8d0c3890de680d4e188028924af15e1e51&stat=instructions%3Au

    | Config | instructions:u |
    |:--|--:|
    | stage1-O3 | +0.00% |
    | stage1-ReleaseThinLTO | +0.00% |
    | stage1-ReleaseLTO-g | +0.02% |
    | stage1-O0-g | +0.01% |
    | stage1-aarch64-O3 | +0.00% |
    | stage1-aarch64-O0-g | +0.02% |
    | stage2-O3 | +0.00% |
    | stage2-O0-g | +0.00% |
    | clang build | -0.15% |

    Changes in bold are likely significant.

    ilyas-mallah ilyas-mallah commented on Nov 27, 2026 14:14 UTC
    Author

    @aengelke The clang build takes 0.15% fewer instructions with this, nearly all of the 0.166% that #233604 added. The other configs stay within 0.02%.

    aengelke aengelke commented on Nov 27, 2026 14:17 UTC
    Contributor

    Yes, I read that. Nevertheless, I'm not at all familiar with clang/Sema and therefore can't review this.

    ilyas-mallah ilyas-mallah commented on Nov 27, 2026 15:05 UTC
    Author

    @AaronBallman @Sirraide Could one of you review the Sema change? It caches the check that decides whether to run the unsafe buffer analysis per diagnostic state, the way #212213 cached the warning policy.

    ilyas-mallah ilyas-mallah commented on Dec 04, 2026 14:11 UTC
    Author

    @AaronBallman @Sirraide Weekly ping on the Sema change. CI is green and the branch is mergeable. Is the per diagnostic state cache acceptable as written, or would you rather see it somewhere else?

    Assignees
    ilyas-mallah ilyas-mallah
    Labels
    risk: low confidence: 90.2% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 34% (LOW) · Higher = larger blast radius
    34%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 90.2% · Lower = rushed or shallow review
    90.2%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 3.3% · Safe to merge
    3.3%