[clang] [clang] Extend -Wunused-but-set-variable to static globals (PR #178342)

John Paul Jepko via cfe-commits cfe-commits at lists.llvm.org
Thu Feb 19 11:51:49 PST 2026


================
@@ -1620,6 +1620,43 @@ void Sema::ActOnEndOfTranslationUnit() {
   if (Context.hasAnyFunctionEffects())
     performFunctionEffectAnalysis(Context.getTranslationUnitDecl());
 
+  // Diagnose unused-but-set static globals in a deterministic order.
+  // Not tracking shadowing info for static globals; there's nothing to shadow.
+  struct LocAndDiag {
+    SourceLocation Loc;
+    PartialDiagnostic PD;
+  };
+  SmallVector<LocAndDiag, 16> DeclDiags;
+  auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
+    DeclDiags.push_back(LocAndDiag{Loc, std::move(PD)});
+  };
+
+  // For -Wunused-but-set-variable we only care about variables that were
+  // referenced by the TU end.
+  SmallVector<const VarDecl *, 16> DeclsToErase;
+  for (const auto &Ref : RefsMinusAssignments) {
+    const VarDecl *VD = Ref.first;
+    // Only diagnose static file vars defined in the main file to match
+    // -Wunused-variable behavior and avoid false positives from header vars.
----------------
jpjepko wrote:

I determined this experimentally at first but I believe this is where it happens:

https://github.com/llvm/llvm-project/blob/c3745fe4ea78c40b1eb595718e4ed2ca2d22e090/clang/lib/Sema/SemaDecl.cpp#L1945-L1949

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


More information about the cfe-commits mailing list