[clang] Fix #include_next of a differently named header from a module header (PR #240916)
Abinaya Saravanan via cfe-commits
cfe-commits at lists.llvm.org
Tue Nov 10 21:08:28 PST 2026
https://github.com/quic-asaravan updated https://github.com/llvm/llvm-project/pull/240916
>From a99deda39b8aa6a22c605f8a9fbefd14f9cb6ab9 Mon Sep 17 00:00:00 2001
From: quic-asaravan <quic_asaravan at quicinc.com>
Date: Sun, 1 Nov 2026 22:16:45 -0800
Subject: [PATCH 1/2] Fix #include_next of a differently named header from a
module header
When #include_next is used in a header belonging to a module, clang finds
the directory of the current file by repeatedly looking up the requested
name until a hit equals the current file. If the requested name differs
from the current file's name (e.g. libc++'s __mbstate_t.h doing
search restarts from the first include directory, finding the wrong header.
Look up the current file's own name to locate its directory instead when
the names differ. Use the file's path relative to its search directory
(e.g. "sys/inner.h") rather than just its basename, so that headers found
in a subdirectory of an include directory are located correctly too.
---
clang/include/clang/Lex/HeaderSearch.h | 2 +-
clang/lib/Lex/HeaderSearch.cpp | 12 ++-
clang/lib/Lex/PPDirectives.cpp | 99 ++++++++++++++++---
.../Modules/include_next_different_name.c | 57 +++++++++++
.../include_next_different_name_relative.c | 33 +++++++
5 files changed, 181 insertions(+), 22 deletions(-)
create mode 100644 clang/test/Modules/include_next_different_name.c
create mode 100644 clang/test/Modules/include_next_different_name_relative.c
diff --git a/clang/include/clang/Lex/HeaderSearch.h b/clang/include/clang/Lex/HeaderSearch.h
index adaa126024c3ca..eadaed1659286c 100644
--- a/clang/include/clang/Lex/HeaderSearch.h
+++ b/clang/include/clang/Lex/HeaderSearch.h
@@ -574,7 +574,7 @@ class HeaderSearch {
Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule,
bool *IsMapped, bool *IsFrameworkFound, bool SkipCache = false,
bool BuildSystemModule = false, bool OpenFile = true,
- bool CacheFailures = true);
+ bool CacheFailures = true, bool DiagnoseShadowing = true);
/// Look up a subframework for the specified \#include file.
///
diff --git a/clang/lib/Lex/HeaderSearch.cpp b/clang/lib/Lex/HeaderSearch.cpp
index 824ed8936621a8..50ad38d711fcfa 100644
--- a/clang/lib/Lex/HeaderSearch.cpp
+++ b/clang/lib/Lex/HeaderSearch.cpp
@@ -957,7 +957,8 @@ OptionalFileEntryRef HeaderSearch::LookupFile(
SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule,
bool *IsMapped, bool *IsFrameworkFound, bool SkipCache,
- bool BuildSystemModule, bool OpenFile, bool CacheFailures) {
+ bool BuildSystemModule, bool OpenFile, bool CacheFailures,
+ bool DiagnoseShadowing) {
ConstSearchDirIterator CurDirLocal = nullptr;
ConstSearchDirIterator &CurDir = CurDirArg ? *CurDirArg : CurDirLocal;
@@ -1027,9 +1028,10 @@ OptionalFileEntryRef HeaderSearch::LookupFile(
if (OptionalFileEntryRef FE = getFileAndSuggestModule(
TmpDir, IncludeLoc, IncluderAndDir.second, IncluderIsSystemHeader,
RequestingModule, SuggestedModule)) {
- diagnoseHeaderShadowing(Filename, *FE, IncludeLoc, FromDir, Includers,
- isAngled, &IncluderAndDir - Includers.begin(),
- nullptr);
+ if (DiagnoseShadowing)
+ diagnoseHeaderShadowing(Filename, *FE, IncludeLoc, FromDir, Includers,
+ isAngled, &IncluderAndDir - Includers.begin(),
+ nullptr);
if (!Includer) {
assert(First && "only first includer can have no file");
return FE;
@@ -1168,7 +1170,7 @@ OptionalFileEntryRef HeaderSearch::LookupFile(
// the includers' directories. That file is the one that ends up being used
// (see checkMSVCHeaderSearch() below), so reporting this one as the chosen
// candidate would be wrong.
- if (!MSFE)
+ if (!MSFE && DiagnoseShadowing)
diagnoseHeaderShadowing(Filename, *File, IncludeLoc, FromDir, Includers,
isAngled, -1, It);
diff --git a/clang/lib/Lex/PPDirectives.cpp b/clang/lib/Lex/PPDirectives.cpp
index f1e9aaa72ff048..6fd1b2cfe1d9ee 100644
--- a/clang/lib/Lex/PPDirectives.cpp
+++ b/clang/lib/Lex/PPDirectives.cpp
@@ -1126,23 +1126,90 @@ OptionalFileEntryRef Preprocessor::LookupFile(
if (FromFile) {
// We're supposed to start looking from after a particular file. Search
// the include path until we find that file or run out of files.
- ConstSearchDirIterator TmpCurDir = CurDir;
- ConstSearchDirIterator TmpFromDir = nullptr;
- while (OptionalFileEntryRef FE = HeaderInfo.LookupFile(
- Filename, FilenameLoc, isAngled, TmpFromDir, &TmpCurDir,
- Includers, SearchPath, RelativePath, RequestingModule,
- SuggestedModule, /*IsMapped=*/nullptr,
- /*IsFrameworkFound=*/nullptr, SkipCache)) {
- // Keep looking as if this file did a #include_next.
- TmpFromDir = TmpCurDir;
- ++TmpFromDir;
- if (&FE->getFileEntry() == FromFile) {
- // Found it.
- FromDir = TmpFromDir;
- CurDir = TmpCurDir;
- break;
+ // The #include_next may name a different header than the current file
+ // (e.g. __mbstate_t.h doing #include_next <wchar.h>), in which case
+ // looking up Filename would never find FromFile. Look up the current
+ // file's own name to locate the directory it was found in. That name is
+ // its path relative to the search directory (e.g. "sys/inner.h"), not just
+ // the basename, so that headers in subdirectories are found too.
+ auto FindFromFile = [&](StringRef LocateName) {
+ bool SameName = LocateName == Filename;
+ ConstSearchDirIterator TmpCurDir = CurDir;
+ ConstSearchDirIterator TmpFromDir = nullptr;
+ while (OptionalFileEntryRef FE = HeaderInfo.LookupFile(
+ LocateName, FilenameLoc, isAngled, TmpFromDir, &TmpCurDir,
+ Includers, SameName ? SearchPath : nullptr,
+ SameName ? RelativePath : nullptr, RequestingModule,
+ SameName ? SuggestedModule : nullptr, /*IsMapped=*/nullptr,
+ /*IsFrameworkFound=*/nullptr, SkipCache,
+ /*BuildSystemModule=*/false, /*OpenFile=*/true,
+ /*CacheFailures=*/true, /*DiagnoseShadowing=*/false)) {
+ // Keep looking as if this file did a #include_next.
+ TmpFromDir = TmpCurDir;
+ ++TmpFromDir;
+ if (&FE->getFileEntry() == FromFile) {
+ // Found it.
+ FromDir = TmpFromDir;
+ CurDir = TmpCurDir;
+ return true;
+ }
}
- }
+ return false;
+ };
+
+ // Candidate names for the current file: its path relative to the search
+ // directory it was found in, if known, else to every search directory
+ // that contains it. Search directories are matched by identity rather than
+ // by spelling, as the file may have been reached through a different path
+ // (e.g. "./x/sys/inner.h" for -Ix).
+ // FIXME: If a search directory is nested in another (-Ix -Ix/sub), the file
+ // is reachable under several names ("sys/inner.h" and "inner.h") and we
+ // cannot tell which one it was originally found as. Fixing this requires
+ // recording the search directory when a module header is entered.
+ SmallVector<std::string, 4> Names;
+ StringRef BaseName;
+ if (CurPPLexer)
+ if (OptionalFileEntryRef CurFE = CurPPLexer->getFileEntry()) {
+ StringRef Path = CurFE->getName();
+ BaseName = llvm::sys::path::filename(Path);
+ // Each ancestor directory of the file, with the file's path relative
+ // to it.
+ SmallVector<std::pair<DirectoryEntryRef, std::string>, 8> Ancestors;
+ SmallString<128> Rel(BaseName);
+ for (StringRef Parent = llvm::sys::path::parent_path(Path);
+ !Parent.empty(); Parent = llvm::sys::path::parent_path(Parent)) {
+ if (OptionalDirectoryEntryRef Dir =
+ FileMgr.getOptionalDirectoryRef(Parent))
+ Ancestors.emplace_back(*Dir, Rel.str().str());
+ StringRef Name = llvm::sys::path::filename(Parent);
+ if (Name.empty())
+ break;
+ SmallString<128> NewRel(Name);
+ llvm::sys::path::append(NewRel, Rel);
+ Rel = NewRel;
+ }
+ auto AddRelPath = [&](const DirectoryLookup &DL) {
+ OptionalDirectoryEntryRef Dir = DL.getDirRef();
+ if (!Dir)
+ return;
+ for (const auto &[AncestorDir, AncestorRel] : Ancestors)
+ if (AncestorDir == *Dir) {
+ Names.push_back(AncestorRel);
+ return;
+ }
+ };
+ if (CurDir)
+ AddRelPath(*CurDir);
+ else
+ for (const DirectoryLookup &DL : HeaderInfo.search_dir_range())
+ AddRelPath(DL);
+ }
+ if (!BaseName.empty() && BaseName != Filename)
+ Names.push_back(BaseName.str());
+ Names.push_back(Filename.str());
+ for (const std::string &Name : Names)
+ if (FindFromFile(Name))
+ break;
}
// Do a standard file entry lookup.
diff --git a/clang/test/Modules/include_next_different_name.c b/clang/test/Modules/include_next_different_name.c
new file mode 100644
index 00000000000000..2be45f67fa2acb
--- /dev/null
+++ b/clang/test/Modules/include_next_different_name.c
@@ -0,0 +1,57 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+// RUN: %clang_cc1 -I%t/x -I%t/y -fsyntax-only -verify %t/main.c
+// RUN: %clang_cc1 -I%t/x -I%t/y -fmodules -fimplicit-module-maps \
+// RUN: -fmodules-cache-path=%t/cache -fsyntax-only -verify %t/main.c
+// RUN: %clang_cc1 -I%t/x -I%t/y -fsyntax-only -verify %t/main_sub.c
+// RUN: %clang_cc1 -I%t/x -I%t/y -fmodules -fimplicit-module-maps \
+// RUN: -fmodules-cache-path=%t/cache -fsyntax-only -verify %t/main_sub.c
+
+// A header in a module doing '#include_next' of a header with a different name
+// must continue the search after the directory the current header was found in,
+// not restart from the first include directory.
+
+//--- x/wrapper.h
+#ifndef X_WRAPPER_H
+#define X_WRAPPER_H
+int wrapper_x_marker(void) { return 1; }
+#endif
+
+//--- y/wrapper.h
+#ifndef Y_WRAPPER_H
+#define Y_WRAPPER_H
+int wrapper_y_marker(void) { return 2; }
+#endif
+
+//--- x/inner.h
+#ifndef X_INNER_H
+#define X_INNER_H
+// Found in 'x', so the search must continue in 'y' and find y/wrapper.h.
+#include_next <wrapper.h>
+#endif
+
+//--- x/module.modulemap
+module Inner { header "inner.h" export * }
+
+//--- main.c
+// expected-no-diagnostics
+#include <inner.h>
+int use(void) { return wrapper_y_marker(); }
+
+// The current header lives in a subdirectory of the include directory
+// ("#include <sys/inner.h>"); that subdirectory must be considered when
+// locating the directory the header was found in.
+
+//--- x/sys/inner.h
+#ifndef X_SYS_INNER_H
+#define X_SYS_INNER_H
+#include_next <wrapper.h>
+#endif
+
+//--- x/sys/module.modulemap
+module SysInner { header "inner.h" export * }
+
+//--- main_sub.c
+// expected-no-diagnostics
+#include <sys/inner.h>
+int use_sub(void) { return wrapper_y_marker(); }
diff --git a/clang/test/Modules/include_next_different_name_relative.c b/clang/test/Modules/include_next_different_name_relative.c
new file mode 100644
index 00000000000000..5ca8d3060cd23d
--- /dev/null
+++ b/clang/test/Modules/include_next_different_name_relative.c
@@ -0,0 +1,33 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+// RUN: cd %t && %clang_cc1 -I%t/z -I%t/x -I%t/y -fmodules \
+// RUN: -fimplicit-module-maps -fmodules-cache-path=%t/cache \
+// RUN: -Werror=shadow-header -fsyntax-only main.c
+
+// The current header is reached through a path that is not textually prefixed
+// by its search directory ("./x/sys/inner.h" for -I%t/x), and an unrelated
+// header with the same relative name comes first in the search path. Locating
+// the current header's directory must still work, and must not report
+// -Wshadow-header for the headers it probes.
+
+//--- z/sys/inner.h
+int unrelated_z_marker(void) { return 3; }
+
+//--- x/sys/inner.h
+#ifndef X_SYS_INNER_H
+#define X_SYS_INNER_H
+#include_next <wrapper.h>
+#endif
+
+//--- x/sys/module.modulemap
+module SysInner { header "inner.h" export * }
+
+//--- x/wrapper.h
+int wrapper_x_marker(void) { return 1; }
+
+//--- y/wrapper.h
+int wrapper_y_marker(void) { return 2; }
+
+//--- main.c
+#include "x/sys/inner.h"
+int use(void) { return wrapper_y_marker(); }
>From 9c27aa311dee780fe7501d17b842681e1043217c Mon Sep 17 00:00:00 2001
From: quic-asaravan <quic_asaravan at quicinc.com>
Date: Sun, 1 Nov 2026 22:16:45 -0800
Subject: [PATCH 2/2] [clang][Lex] Fix #include_next of a differently named
header from a module header
For a module header, #include_next finds the current file's directory by
looking up the requested name until a hit equals the current file. This never
succeeds when the names differ (e.g. libc++'s __mbstate_t.h doing
#include_next <wchar.h>), so the search restarts from the first include
directory and finds the wrong header.
Look up the current file's own name, relative to the search directory that
contains it, instead. Don't diagnose -Wshadow-header for these lookups.
Co-Authored-By: Claude Sonnet 5.5 <noreply at anthropic.com>
---
clang/lib/Lex/PPDirectives.cpp | 55 +++++++------------
.../Modules/include_next_nested_search_dirs.c | 51 +++++++++++++++++
2 files changed, 72 insertions(+), 34 deletions(-)
create mode 100644 clang/test/Modules/include_next_nested_search_dirs.c
diff --git a/clang/lib/Lex/PPDirectives.cpp b/clang/lib/Lex/PPDirectives.cpp
index 6fd1b2cfe1d9ee..a506bff37b1b3f 100644
--- a/clang/lib/Lex/PPDirectives.cpp
+++ b/clang/lib/Lex/PPDirectives.cpp
@@ -1126,12 +1126,8 @@ OptionalFileEntryRef Preprocessor::LookupFile(
if (FromFile) {
// We're supposed to start looking from after a particular file. Search
// the include path until we find that file or run out of files.
- // The #include_next may name a different header than the current file
- // (e.g. __mbstate_t.h doing #include_next <wchar.h>), in which case
- // looking up Filename would never find FromFile. Look up the current
- // file's own name to locate the directory it was found in. That name is
- // its path relative to the search directory (e.g. "sys/inner.h"), not just
- // the basename, so that headers in subdirectories are found too.
+ // Filename may differ from FromFile's name (e.g. #include_next <wchar.h>
+ // from __mbstate_t.h), so locate FromFile by its own name instead.
auto FindFromFile = [&](StringRef LocateName) {
bool SameName = LocateName == Filename;
ConstSearchDirIterator TmpCurDir = CurDir;
@@ -1157,30 +1153,33 @@ OptionalFileEntryRef Preprocessor::LookupFile(
return false;
};
- // Candidate names for the current file: its path relative to the search
- // directory it was found in, if known, else to every search directory
- // that contains it. Search directories are matched by identity rather than
- // by spelling, as the file may have been reached through a different path
- // (e.g. "./x/sys/inner.h" for -Ix).
- // FIXME: If a search directory is nested in another (-Ix -Ix/sub), the file
- // is reachable under several names ("sys/inner.h" and "inner.h") and we
- // cannot tell which one it was originally found as. Fixing this requires
- // recording the search directory when a module header is entered.
+ // Candidate names for FromFile: its path relative to each search directory
+ // containing it, innermost first. Directories are matched by identity, as
+ // the file may have been reached via another spelling (e.g. "./x/...").
+ // FIXME: With nested search directories (-Ix -Ix/sub) the original name is
+ // ambiguous; we assume the innermost. Fixing this requires recording the
+ // search directory when a module header is entered.
SmallVector<std::string, 4> Names;
StringRef BaseName;
if (CurPPLexer)
if (OptionalFileEntryRef CurFE = CurPPLexer->getFileEntry()) {
StringRef Path = CurFE->getName();
BaseName = llvm::sys::path::filename(Path);
- // Each ancestor directory of the file, with the file's path relative
- // to it.
- SmallVector<std::pair<DirectoryEntryRef, std::string>, 8> Ancestors;
+ auto IsSearchDir = [&](DirectoryEntryRef Dir) {
+ auto Matches = [&](const DirectoryLookup &DL) {
+ OptionalDirectoryEntryRef DLDir = DL.getDirRef();
+ return DLDir && *DLDir == Dir;
+ };
+ return CurDir ? Matches(*CurDir)
+ : llvm::any_of(HeaderInfo.search_dir_range(), Matches);
+ };
SmallString<128> Rel(BaseName);
for (StringRef Parent = llvm::sys::path::parent_path(Path);
!Parent.empty(); Parent = llvm::sys::path::parent_path(Parent)) {
if (OptionalDirectoryEntryRef Dir =
FileMgr.getOptionalDirectoryRef(Parent))
- Ancestors.emplace_back(*Dir, Rel.str().str());
+ if (IsSearchDir(*Dir))
+ Names.push_back(Rel.str().str());
StringRef Name = llvm::sys::path::filename(Parent);
if (Name.empty())
break;
@@ -1188,22 +1187,10 @@ OptionalFileEntryRef Preprocessor::LookupFile(
llvm::sys::path::append(NewRel, Rel);
Rel = NewRel;
}
- auto AddRelPath = [&](const DirectoryLookup &DL) {
- OptionalDirectoryEntryRef Dir = DL.getDirRef();
- if (!Dir)
- return;
- for (const auto &[AncestorDir, AncestorRel] : Ancestors)
- if (AncestorDir == *Dir) {
- Names.push_back(AncestorRel);
- return;
- }
- };
- if (CurDir)
- AddRelPath(*CurDir);
- else
- for (const DirectoryLookup &DL : HeaderInfo.search_dir_range())
- AddRelPath(DL);
}
+ // A same-name #include_next is most likely how the file was found.
+ if (llvm::is_contained(Names, Filename))
+ Names.insert(Names.begin(), Filename.str());
if (!BaseName.empty() && BaseName != Filename)
Names.push_back(BaseName.str());
Names.push_back(Filename.str());
diff --git a/clang/test/Modules/include_next_nested_search_dirs.c b/clang/test/Modules/include_next_nested_search_dirs.c
new file mode 100644
index 00000000000000..801cd96574b5dd
--- /dev/null
+++ b/clang/test/Modules/include_next_nested_search_dirs.c
@@ -0,0 +1,51 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+// RUN: %clang_cc1 -I%t/inc -I%t/inc/v1 -I%t/sys -fsyntax-only -verify %t/main.c
+// RUN: %clang_cc1 -I%t/inc -I%t/inc/v1 -I%t/sys -fmodules \
+// RUN: -fimplicit-module-maps -fmodules-cache-path=%t/cache -fsyntax-only \
+// RUN: -verify %t/main.c
+
+// One search directory is nested in another (like libc++'s <include> and
+// <include/c++/v1>). Wrapper headers in the inner directory doing
+// '#include_next' must continue after the inner directory, i.e. the header is
+// located under the name relative to the innermost search directory.
+
+//--- inc/v1/header.h
+#ifndef V1_HEADER_H
+#define V1_HEADER_H
+#include_next <header.h>
+#endif
+
+//--- inc/v1/other.h
+#ifndef V1_OTHER_H
+#define V1_OTHER_H
+#include_next <sysother.h>
+#endif
+
+// Same name as the system header but must not be picked.
+//--- inc/v1/sysother.h
+#ifndef V1_SYSOTHER_H
+#define V1_SYSOTHER_H
+#endif
+
+//--- inc/v1/module.modulemap
+module Header { header "header.h" export * }
+module Other { header "other.h" export * }
+
+//--- sys/header.h
+#ifndef SYS_HEADER_H
+#define SYS_HEADER_H
+int sys_header_marker(void);
+#endif
+
+//--- sys/sysother.h
+#ifndef SYS_SYSOTHER_H
+#define SYS_SYSOTHER_H
+int sys_other_marker(void);
+#endif
+
+//--- main.c
+// expected-no-diagnostics
+#include <header.h>
+#include <other.h>
+int use(void) { return sys_header_marker() + sys_other_marker(); }
More information about the cfe-commits
mailing list