[clang] [clang] Support header shadowing diagnostics in Clang header search (PR #162491)

Tom Honermann via cfe-commits cfe-commits at lists.llvm.org
Mon Oct 27 14:47:55 PDT 2025


================
@@ -881,6 +886,35 @@ diagnoseFrameworkInclude(DiagnosticsEngine &Diags, SourceLocation IncludeLoc,
         << IncludeFilename;
 }
 
+/// Return true if a shadow has been detected and the caller should
+/// stop and return the first-found file and module, false otherwise.
+static bool checkAndStoreCandidate(
+    ModuleMap::KnownHeader *SuggestedModule, OptionalFileEntryRef CandidateFile,
+    StringRef CandidateDir, DiagnosticsEngine &Diags, StringRef Filename,
+    SourceLocation IncludeLoc, ModuleMap::KnownHeader &FirstModule,
+    OptionalFileEntryRef &FirstHeader, SmallString<1024> &FirstDir) {
+  if (!FirstHeader) {
+    // Found the first candidate
+    FirstHeader = CandidateFile;
+    FirstDir = CandidateDir;
+    if (SuggestedModule)
+      FirstModule = *SuggestedModule;
+    return false;
+  }
+
+  if (FirstDir != CandidateDir) {
+    // Found a second candidate from a different directory
+    Diags.Report(IncludeLoc, diag::warn_header_shadowed)
+        << Filename << FirstDir << CandidateDir;
+    if (SuggestedModule)
+      *SuggestedModule = FirstModule;
+    return true;
+  }
+
+  // Found a candidate from the same directory as the first one
+  return false;
----------------
tahonermann wrote:

Agreed, but doesn't the current diagnostic implementation already handle that case?
```
$ cat t.c
#include "foo/t1.h"

$ cat foo/t1.h
#include "bar/t2.h"

$ cat foo/bar/t2.h
#include "t3.h"

$ cat foo/t3.h
#warning Found t3.h.

$ clang -fms-compatibility -c t.c
In file included from t.c:1:
In file included from ./foo/t1.h:1:
./foo/bar/t2.h:1:10: warning: #include resolved using non-portable Microsoft search rules as: ./foo/t3.h [-Wmicrosoft-include]
    1 | #include "t3.h"
      |          ^
In file included from t.c:1:
In file included from ./foo/t1.h:1:
In file included from ./foo/bar/t2.h:1:
./foo/t3.h:1:2: warning: Found t3.h. [-W#warnings]
    1 | #warning Found t3.h.
      |  ^
2 warnings generated.

$ clang -fms-compatibility -c -Ifoo t.c
In file included from t.c:1:
In file included from ./foo/t1.h:1:
In file included from ./foo/bar/t2.h:1:
foo/t3.h:1:2: warning: Found t3.h. [-W#warnings]
    1 | #warning Found t3.h.
      |  ^
1 warning generated.
```

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


More information about the cfe-commits mailing list