[clang] [Fix] Speedup -Wunsafe-buffer-usage when using clang modules. (PR #127161)

via cfe-commits cfe-commits at lists.llvm.org
Thu Feb 13 19:26:20 PST 2025


https://github.com/matts1 created https://github.com/llvm/llvm-project/pull/127161

See https://issues.chromium.org/issues/351909443 for details and benchmarks.

This improves the performance of a file containing a single line, `#include <iostream>`, from ~1 second to ~100ms on my machine.

>From 14560a133284f8d6e01d1bb360b738aa4a513af5 Mon Sep 17 00:00:00 2001
From: Matt Stark <msta at google.com>
Date: Fri, 14 Feb 2025 14:14:03 +1100
Subject: [PATCH] [Fix] Speedup -Wunsafe-buffer-usage when using clang modules.

See https://issues.chromium.org/issues/351909443 for details and benchmarks.

This improves the performance of a file containing a single line, `#include <iostream>`, from ~1 second to ~100ms on my machine.
---
 clang/lib/Sema/AnalysisBasedWarnings.cpp | 19 ++++++++++++++++---
 1 file changed, 16 insertions(+), 3 deletions(-)

diff --git a/clang/lib/Sema/AnalysisBasedWarnings.cpp b/clang/lib/Sema/AnalysisBasedWarnings.cpp
index 589869d018657..b00e8352d9992 100644
--- a/clang/lib/Sema/AnalysisBasedWarnings.cpp
+++ b/clang/lib/Sema/AnalysisBasedWarnings.cpp
@@ -2546,14 +2546,27 @@ static void flushDiagnostics(Sema &S, const sema::FunctionScopeInfo *fscope) {
 class CallableVisitor : public DynamicRecursiveASTVisitor {
 private:
   llvm::function_ref<void(const Decl *)> Callback;
+  const unsigned int TUModuleID;
 
 public:
-  CallableVisitor(llvm::function_ref<void(const Decl *)> Callback)
-      : Callback(Callback) {
+  CallableVisitor(llvm::function_ref<void(const Decl *)> Callback,
+                  unsigned int TUModuleID)
+      : Callback(Callback), TUModuleID(TUModuleID) {
     ShouldVisitTemplateInstantiations = true;
     ShouldVisitImplicitCode = false;
   }
 
+  bool TraverseDecl(Decl *Node) override {
+    // For performance reasons, only validate the current translation unit's
+    // module, and not modules it depends on.
+    // See https://issues.chromium.org/issues/351909443 for details.
+    if (Node->getOwningModuleID() == TUModuleID) {
+      return DynamicRecursiveASTVisitor::TraverseDecl(Node);
+    } else {
+      return true;
+    }
+  }
+
   bool VisitFunctionDecl(FunctionDecl *Node) override {
     if (cast<DeclContext>(Node)->isDependentContext())
       return true; // Not to analyze dependent decl
@@ -2633,7 +2646,7 @@ void clang::sema::AnalysisBasedWarnings::IssueWarnings(
                        SourceLocation()) ||
       (!Diags.isIgnored(diag::warn_unsafe_buffer_libc_call, SourceLocation()) &&
        S.getLangOpts().CPlusPlus /* only warn about libc calls in C++ */)) {
-    CallableVisitor(CallAnalyzers).TraverseTranslationUnitDecl(TU);
+    CallableVisitor(CallAnalyzers, TU->getOwningModuleID()).TraverseTranslationUnitDecl(TU);
   }
 }
 



More information about the cfe-commits mailing list