https://github.com/ChenMiaoi created 
https://github.com/llvm/llvm-project/pull/242216

For header guards written as `#if !defined(MACRO)`, the warning for a 
mismatched guard points at `if` instead of the macro name.

Before:
```text
<source>:1:2: warning: 'HEADER_H' is used as a header guard here, followed by 
#define of a different macro [-Wheader-guard]
    1 | #if !defined(HEADER_H)
      |  ^~
<source>:2:9: note: 'HAEDER_H' is defined here; did you mean 'HEADER_H'?
    2 | #define HAEDER_H
      |         ^~~~~~~~
      |         HEADER_H
1 warning generated.
```

After:
```text
<source>:1:14: warning: 'HEADER_H' is used as a header guard here, followed by 
#define of a different macro [-Wheader-guard]
    1 | #if !defined(HEADER_H)
      |              ^~~~~~~~
<source>:2:9: note: 'HAEDER_H' is defined here; did you mean 'HEADER_H'?
    2 | #define HAEDER_H
      |         ^~~~~~~~
      |         HEADER_H
1 warning generated.
```

Carry the macro's source location through expression evaluation using 
`IdentifierLoc` and use it when recording the controlling macro.

>From 6f3301fe31693586f41b3455471a5a2c15517632 Mon Sep 17 00:00:00 2001
From: Chen Miao <[email protected]>
Date: Fri, 13 Nov 2026 17:13:13 +0800
Subject: [PATCH] [clang][Lex] Point header guard warnings at the macro name in
 #if

For header guards written as `#if !defined(MACRO)`, the warning for a
mismatched guard points at `if` instead of the macro name.

Before:
```text
<source>:1:2: warning: 'HEADER_H' is used as a header guard here, followed by 
#define of a different macro [-Wheader-guard]
    1 | #if !defined(HEADER_H)
      |  ^~
<source>:2:9: note: 'HAEDER_H' is defined here; did you mean 'HEADER_H'?
    2 | #define HAEDER_H
      |         ^~~~~~~~
      |         HEADER_H
1 warning generated.
```

After:
```text
<source>:1:14: warning: 'HEADER_H' is used as a header guard here, followed by 
#define of a different macro [-Wheader-guard]
    1 | #if !defined(HEADER_H)
      |              ^~~~~~~~
<source>:2:9: note: 'HAEDER_H' is defined here; did you mean 'HEADER_H'?
    2 | #define HAEDER_H
      |         ^~~~~~~~
      |         HEADER_H
1 warning generated.
```

Carry the macro's source location through expression evaluation using
`IdentifierLoc` and use it when recording the controlling macro.
---
 clang/docs/ReleaseNotes.md             |  3 +++
 clang/include/clang/Lex/Preprocessor.h | 10 ++++++----
 clang/lib/Lex/PPDirectives.cpp         | 13 +++++++------
 clang/lib/Lex/PPExpressions.cpp        | 12 ++++++------
 clang/test/Lexer/header.cpp            |  4 ++--
 5 files changed, 24 insertions(+), 18 deletions(-)

diff --git a/clang/docs/ReleaseNotes.md b/clang/docs/ReleaseNotes.md
index 6ced5d9b986e5..23e7cf3e81a29 100644
--- a/clang/docs/ReleaseNotes.md
+++ b/clang/docs/ReleaseNotes.md
@@ -507,6 +507,9 @@ documentation](CIR/index.md) for more information regarding 
ClangIR's status and
 
 ### Improvements to Clang's diagnostics
 
+- Fixed `-Wheader-guard` warnings pointing at `if` instead of the macro name
+  in `#if !defined(...)` header guards.
+
 - Fixed a false-positive `-Wimplicit-fallthrough` warning when
   consecutive switch labels share a body and are annotated with
   attributes like `[[unlikely]]`. (#GH230802)
diff --git a/clang/include/clang/Lex/Preprocessor.h 
b/clang/include/clang/Lex/Preprocessor.h
index 2d0c24b92334a..8d15ed7e8afd8 100644
--- a/clang/include/clang/Lex/Preprocessor.h
+++ b/clang/include/clang/Lex/Preprocessor.h
@@ -2740,17 +2740,19 @@ class Preprocessor {
   /// Evaluate an integer constant expression that may occur after a
   /// \#if or \#elif directive and return a \p DirectiveEvalResult object.
   ///
-  /// If the expression is equivalent to "!defined(X)" return X in IfNDefMacro.
-  DirectiveEvalResult EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro,
+  /// If the expression is equivalent to "!defined(X)", return X and its
+  /// location in IfNDefMacro.
+  DirectiveEvalResult EvaluateDirectiveExpression(IdentifierLoc &IfNDefMacro,
                                                   bool CheckForEoD = true);
 
   /// Evaluate an integer constant expression that may occur after a
   /// \#if or \#elif directive and return a \p DirectiveEvalResult object.
   ///
-  /// If the expression is equivalent to "!defined(X)" return X in IfNDefMacro.
+  /// If the expression is equivalent to "!defined(X)", return X and its
+  /// location in IfNDefMacro.
   /// \p EvaluatedDefined will contain the result of whether "defined" appeared
   /// in the evaluated expression or not.
-  DirectiveEvalResult EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro,
+  DirectiveEvalResult EvaluateDirectiveExpression(IdentifierLoc &IfNDefMacro,
                                                   Token &Tok,
                                                   bool &EvaluatedDefined,
                                                   bool CheckForEoD = true);
diff --git a/clang/lib/Lex/PPDirectives.cpp b/clang/lib/Lex/PPDirectives.cpp
index 5ff165e3ddf81..ecb9e42c88bc0 100644
--- a/clang/lib/Lex/PPDirectives.cpp
+++ b/clang/lib/Lex/PPDirectives.cpp
@@ -864,7 +864,7 @@ void 
Preprocessor::SkipExcludedConditionalBlock(SourceLocation HashTokenLoc,
           // looked up, etc, inside the #elif expression.
           assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
           CurPPLexer->LexingRawMode = false;
-          IdentifierInfo *IfNDefMacro = nullptr;
+          IdentifierLoc IfNDefMacro;
           DirectiveEvalResult DER = EvaluateDirectiveExpression(IfNDefMacro);
           // Stop if Lexer became invalid after hitting code completion token.
           if (!CurPPLexer)
@@ -3583,9 +3583,10 @@ void Preprocessor::HandleIfDirective(Token &IfToken,
   ++NumIf;
 
   // Parse and evaluate the conditional expression.
-  IdentifierInfo *IfNDefMacro = nullptr;
+  IdentifierLoc IfNDefMacro;
   const DirectiveEvalResult DER = EvaluateDirectiveExpression(IfNDefMacro);
   const bool ConditionalTrue = DER.Conditional;
+  const IdentifierInfo *IfNDefMacroInfo = IfNDefMacro.getIdentifierInfo();
   // Lexer might become invalid if we hit code completion point while 
evaluating
   // expression.
   if (!CurPPLexer)
@@ -3594,9 +3595,9 @@ void Preprocessor::HandleIfDirective(Token &IfToken,
   // If this condition is equivalent to #ifndef X, and if this is the first
   // directive seen, handle it for the multiple-include optimization.
   if (CurPPLexer->getConditionalStackDepth() == 0) {
-    if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
-      // FIXME: Pass in the location of the macro name, not the 'if' token.
-      CurPPLexer->MIOpt.EnterTopLevelIfndef(IfNDefMacro, 
IfToken.getLocation());
+    if (!ReadAnyTokensBeforeDirective && IfNDefMacroInfo && ConditionalTrue)
+      CurPPLexer->MIOpt.EnterTopLevelIfndef(IfNDefMacroInfo,
+                                            IfNDefMacro.getLoc());
     else
       CurPPLexer->MIOpt.EnterTopLevelConditional();
   }
@@ -3854,7 +3855,7 @@ Preprocessor::LexEmbedParameters(Token &CurTok, bool 
ForHasEmbed) {
 
     // We do not consume the ( because EvaluateDirectiveExpression will lex
     // the next token for us.
-    IdentifierInfo *ParameterIfNDef = nullptr;
+    IdentifierLoc ParameterIfNDef;
     bool EvaluatedDefined;
     DirectiveEvalResult LimitEvalResult = EvaluateDirectiveExpression(
         ParameterIfNDef, CurTok, EvaluatedDefined, /*CheckForEOD=*/false);
diff --git a/clang/lib/Lex/PPExpressions.cpp b/clang/lib/Lex/PPExpressions.cpp
index 2fcf449458e29..8ccfe50d20493 100644
--- a/clang/lib/Lex/PPExpressions.cpp
+++ b/clang/lib/Lex/PPExpressions.cpp
@@ -94,8 +94,8 @@ struct DefinedTracker {
     Unknown              // Something else.
   } State;
   /// TheMacro - When the state is DefinedMacro or NotDefinedMacro, this
-  /// indicates the macro that was checked.
-  IdentifierInfo *TheMacro;
+  /// indicates the macro that was checked and its location.
+  IdentifierLoc TheMacro;
   bool IncludedUndefinedIds = false;
 };
 
@@ -219,7 +219,7 @@ static bool EvaluateDefined(PPValue &Result, Token 
&PeekTok, DefinedTracker &DT,
 
   // Success, remember that we saw defined(X).
   DT.State = DefinedTracker::DefinedMacro;
-  DT.TheMacro = II;
+  DT.TheMacro = IdentifierLoc(macroToken.getLocation(), II);
   return false;
 }
 
@@ -887,9 +887,9 @@ static bool EvaluateDirectiveSubExpr(PPValue &LHS, unsigned 
MinPrec,
 
 /// EvaluateDirectiveExpression - Evaluate an integer constant expression that
 /// may occur after a #if or #elif directive.  If the expression is equivalent
-/// to "!defined(X)" return X in IfNDefMacro.
+/// to "!defined(X)" return X and its location in IfNDefMacro.
 Preprocessor::DirectiveEvalResult
-Preprocessor::EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro,
+Preprocessor::EvaluateDirectiveExpression(IdentifierLoc &IfNDefMacro,
                                           Token &Tok, bool &EvaluatedDefined,
                                           bool CheckForEoD) {
   SaveAndRestore PPDir(ParsingIfOrElifDirective, true);
@@ -974,7 +974,7 @@ Preprocessor::EvaluateDirectiveExpression(IdentifierInfo 
*&IfNDefMacro,
 }
 
 Preprocessor::DirectiveEvalResult
-Preprocessor::EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro,
+Preprocessor::EvaluateDirectiveExpression(IdentifierLoc &IfNDefMacro,
                                           bool CheckForEoD) {
   Token Tok;
   bool EvaluatedDefined;
diff --git a/clang/test/Lexer/header.cpp b/clang/test/Lexer/header.cpp
index 34ed2686b0e72..36b062c029b9b 100644
--- a/clang/test/Lexer/header.cpp
+++ b/clang/test/Lexer/header.cpp
@@ -20,9 +20,9 @@
 
 #include "Inputs/bad-header-guard-defined.h"
 // CHECK: In file included from {{.*}}header.cpp:{{[0-9]*}}:
-// CHECK: {{.*}}bad-header-guard-defined.h:1:2: warning: 'foo' is used as a 
header guard here, followed by #define of a different macro
+// CHECK: {{.*}}bad-header-guard-defined.h:1:14: warning: 'foo' is used as a 
header guard here, followed by #define of a different macro
 // CHECK: {{^}}#if !defined(foo)
-// CHECK: {{^}} ^~
+// CHECK: {{^}}             ^~~
 // CHECK: {{.*}}bad-header-guard-defined.h:2:9: note: 'goo' is defined here; 
did you mean 'foo'?
 // CHECK: {{^}}#define goo
 // CHECK: {{^}}        ^~~

_______________________________________________
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to