[clang-tools-extra] [clang-tidy] Report presumed location on preprocessed file (PR #245468)
Félix-Antoine Constantin via cfe-commits
cfe-commits at lists.llvm.org
Mon Nov 23 18:29:42 PST 2026
https://github.com/felix642 created https://github.com/llvm/llvm-project/pull/245468
When storing diagnostics, clang-tidy only stores the file name and the offset. The source Manager isn't being kept between the time the diagnostic is saved and the moment is it emitted so the presumed location cannot be reconstructed.
This commit fixes this issue by storing the LineTable in the clang-tidy context whenever a diagnostic is stored. This metada can then be used to reconstruct the original LineTable when the diagnostic is emitted and report the original PresumedLocation.
The flag --fix still applies the corrections to the preprocessed file since we can't guarantee the original file is available on the filesystem.
Assisted-by: Claude Opus 5.5
Fixes: #62405
AI was used to generate most of the code for the tests ([clang-tools-extra/test/clang-tidy/infrastructure/preprocessed-input.cpp](https://github.com/llvm/llvm-project/compare/main...felix642:llvm-project:bugfix/62405-preprocessor-line-directives-ignored-in-diagnostics?expand=1#diff-197f89a15340d6027cd1c5c364a36ca1bf82b406f3a1a00693b140a50ed07cb0)) and gather some ideas.
The newly added code should only apply is the file has line directives and can be turned off with `-fno-diagnostics-use-presumed-location` so the risk is fairly limited.
This is mostly useful to run clang-tidy on a distributed cluster similar to icecream or fastbuild as stated by the original issue.
>From f872c170bcbe396673a2c5006462ad0a01a05e1f Mon Sep 17 00:00:00 2001
From: felix-antoine constantin <felix-antoine.constantin at comact.com>
Date: Mon, 23 Nov 2026 21:07:51 -0500
Subject: [PATCH] [clang-tidy] Report presumed location on preprocessed file
When storing diagnostics, clang-tidy only stores the file name and
offset. The source Manager isn't being kept between the time the
diagnostic is saved and the moment is it emitted so the presumed
location cannot be reconstructed.
This commit fixes this issue by storing the LineTable in the
clang-tidy context whenever a diagnostic is emitted. This metada
can then be used to reconstruct the original LineTable when the
diagnostic is emitted and report the original PresumedLocation.
The flag --fix is still applies the corrections to the preprocessed
file since we can't guarantee the original file is available on the
filesystem.
Assisted-by: Claude Opus 5.5
Fixes: #62405
---
clang-tools-extra/clang-tidy/ClangTidy.cpp | 31 ++++++++
.../ClangTidyDiagnosticConsumer.cpp | 78 +++++++++++++++++--
.../clang-tidy/ClangTidyDiagnosticConsumer.h | 17 ++++
clang-tools-extra/docs/ReleaseNotes.md | 4 +
.../preprocessed-input/compiler-diag.ii | 6 ++
.../Inputs/preprocessed-input/main.ii | 19 +++++
.../infrastructure/preprocessed-input.cpp | 55 +++++++++++++
7 files changed, 202 insertions(+), 8 deletions(-)
create mode 100644 clang-tools-extra/test/clang-tidy/infrastructure/Inputs/preprocessed-input/compiler-diag.ii
create mode 100644 clang-tools-extra/test/clang-tidy/infrastructure/Inputs/preprocessed-input/main.ii
create mode 100644 clang-tools-extra/test/clang-tidy/infrastructure/preprocessed-input.cpp
diff --git a/clang-tools-extra/clang-tidy/ClangTidy.cpp b/clang-tools-extra/clang-tidy/ClangTidy.cpp
index d1ef8de8b4a9cc..5a277218d74c8a 100644
--- a/clang-tools-extra/clang-tidy/ClangTidy.cpp
+++ b/clang-tools-extra/clang-tidy/ClangTidy.cpp
@@ -25,6 +25,7 @@
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/Basic/DiagnosticFrontend.h"
#include "clang/Basic/Sarif.h"
+#include "clang/Basic/SourceManagerInternals.h"
#include "clang/Format/Format.h"
#include "clang/Frontend/ASTConsumers.h"
#include "clang/Frontend/CompilerInstance.h"
@@ -38,6 +39,7 @@
#include "clang/Tooling/DiagnosticsYaml.h" // IWYU pragma: keep
#include "clang/Tooling/Refactoring.h"
#include "clang/Tooling/Tooling.h"
+#include "llvm/ADT/DenseSet.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/FormatVariadic.h"
@@ -123,6 +125,7 @@ class ErrorReporter {
"https://clang.llvm.org/extra/clang-tidy/");
}
+ DiagOpts.ShowPresumedLoc = true;
DiagOpts.setShowColors(Context.getOptions().UseColor.value_or(
llvm::sys::Process::StandardOutHasColors())
? ShowColorsKind::On
@@ -371,6 +374,7 @@ class ErrorReporter {
return {};
const FileID ID = SourceMgr.getOrCreateFileID(*File, SrcMgr::C_User);
+ restoreLineTable(ID, FilePath);
return SourceMgr.getLocForStartOfFile(ID).getLocWithOffset(Offset);
}
@@ -392,6 +396,30 @@ class ErrorReporter {
SarifOS << llvm::formatv("{0:2}", Document);
}
+ /// Restores the line table recorded for \p FilePath during the analysis.
+ void restoreLineTable(FileID ID, StringRef FilePath) {
+ if (!FilesWithLineTableApplied.insert(ID).second)
+ return;
+
+ SmallString<256> AbsolutePath(FilePath);
+ Files.makeAbsolutePath(AbsolutePath, true);
+ const ClangTidyContext::FileLineTable *Table =
+ Context.getLineTable(AbsolutePath);
+ if (!Table)
+ return;
+
+ SmallVector<int> FilenameIDs;
+ for (const std::string &Filename : Table->Filenames)
+ FilenameIDs.push_back(SourceMgr.getLineTableFilenameID(Filename));
+ std::vector<LineEntry> Entries = Table->Entries;
+ for (LineEntry &Entry : Entries)
+ if (Entry.FilenameID >= 0)
+ Entry.FilenameID = FilenameIDs[Entry.FilenameID];
+
+ SourceMgr.getLineTable().AddEntry(ID, Entries);
+ SourceMgr.getSLocEntry(ID).getFile().setHasLineDirectives();
+ }
+
void reportFix(const DiagnosticBuilder &Diag,
const llvm::StringMap<Replacements> &Fix) {
for (const auto &FileAndReplacements : Fix) {
@@ -437,6 +465,8 @@ class ErrorReporter {
Replacements Replaces;
};
+ llvm::DenseSet<FileID> FilesWithLineTableApplied;
+
FileManager Files;
LangOptions LangOpts; // FIXME: use langopts from each original file
DiagnosticOptions DiagOpts;
@@ -549,6 +579,7 @@ ClangTidyASTConsumerFactory::createASTConsumer(CompilerInstance &Compiler,
Context.setSourceManager(SM);
Context.setCurrentFile(File);
Context.setASTContext(&Compiler.getASTContext());
+ Context.setUsePresumedLocations(Compiler.getDiagnosticOpts().ShowPresumedLoc);
auto WorkingDir = Compiler.getSourceManager()
.getFileManager()
diff --git a/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp b/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
index 6af3535de85fbb..b53cf1e2067d52 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
+++ b/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
@@ -50,8 +50,10 @@ class ClangTidyDiagnosticRenderer : public DiagnosticRenderer {
public:
ClangTidyDiagnosticRenderer(const LangOptions &LangOpts,
DiagnosticOptions &DiagOpts,
- ClangTidyError &Error)
- : DiagnosticRenderer(LangOpts, DiagOpts), Error(Error) {}
+ ClangTidyError &Error, ClangTidyContext &Context,
+ SourceManager *SM)
+ : DiagnosticRenderer(LangOpts, DiagOpts), Error(Error), Context(Context),
+ SM(SM) {}
protected:
void emitDiagnosticMessage(FullSourceLoc Loc, PresumedLoc PLoc,
@@ -69,6 +71,7 @@ class ClangTidyDiagnosticRenderer : public DiagnosticRenderer {
Loc.isValid()
? tooling::DiagnosticMessage(Message, Loc.getManager(), Loc)
: tooling::DiagnosticMessage(Message);
+ recordLineTable(Loc);
// Whatever we store here gets decoupled from the current Source Manager, so
// each range must become a character range in a real file now.
@@ -113,6 +116,7 @@ class ClangTidyDiagnosticRenderer : public DiagnosticRenderer {
assert(Range.getBegin().isFileID() && Range.getEnd().isFileID() &&
"Only file locations supported in fix-it hints.");
+ recordLineTable(Range.getBegin());
const tooling::Replacement Replacement(Loc.getManager(), Range,
FixIt.CodeToInsert);
llvm::Error Err =
@@ -141,7 +145,14 @@ class ClangTidyDiagnosticRenderer : public DiagnosticRenderer {
}
private:
+ void recordLineTable(SourceLocation Loc) {
+ if (SM)
+ Context.recordLineTable(*SM, Loc);
+ }
+
ClangTidyError &Error;
+ ClangTidyContext &Context;
+ SourceManager *SM;
};
} // end anonymous namespace
@@ -217,6 +228,55 @@ void ClangTidyContext::setSourceManager(SourceManager *SourceMgr) {
DiagEngine->setSourceManager(SourceMgr);
}
+void ClangTidyContext::recordLineTable(SourceManager &SM, SourceLocation Loc) {
+ if (!UsePresumedLocations || Loc.isInvalid() || !Loc.isFileID() ||
+ !SM.hasLineTable())
+ return;
+
+ const FileID FileID = SM.getFileID(Loc);
+ bool Invalid = false;
+ const SrcMgr::SLocEntry &SLocEntry = SM.getSLocEntry(FileID, &Invalid);
+ if (Invalid || !SLocEntry.isFile() ||
+ !SLocEntry.getFile().hasLineDirectives())
+ return;
+ const OptionalFileEntryRef File = SM.getFileEntryRefForID(FileID);
+ if (!File)
+ return;
+
+ LineTableInfo &SMLineTable = SM.getLineTable();
+ const auto SMEntries =
+ llvm::find_if(SMLineTable, [FileID](const auto &FIDAndEntries) {
+ return FIDAndEntries.first == FileID;
+ });
+ if (SMEntries == SMLineTable.end())
+ return;
+
+ SmallString<256> Path(File->getName());
+ SM.getFileManager().makeAbsolutePath(Path, true);
+ FileLineTable &Table = LineTables[Path];
+ if (SMEntries->second.size() <= Table.Entries.size())
+ return;
+
+ for (LineEntry Entry :
+ llvm::drop_begin(SMEntries->second, Table.Entries.size())) {
+ if (Entry.FilenameID >= 0) {
+ const StringRef Filename = SMLineTable.getFilename(Entry.FilenameID);
+ const auto [It, Inserted] =
+ Table.FilenameIDs.try_emplace(Filename, Table.Filenames.size());
+ if (Inserted)
+ Table.Filenames.emplace_back(Filename);
+ Entry.FilenameID = It->second;
+ }
+ Table.Entries.push_back(Entry);
+ }
+}
+
+const ClangTidyContext::FileLineTable *
+ClangTidyContext::getLineTable(StringRef AbsolutePath) const {
+ const auto It = LineTables.find(AbsolutePath);
+ return It == LineTables.end() ? nullptr : &It->second;
+}
+
static bool parseFileExtensions(llvm::ArrayRef<std::string> AllFileExtensions,
FileExtensionsSet &FileExtensions) {
FileExtensions.clear();
@@ -455,17 +515,19 @@ void ClangTidyDiagnosticConsumer::HandleDiagnostic(
// ClangTidyPluginAction case, forward the diagnostics to it.
forwardDiagnostic(Info);
} else {
+ SourceManager *SM = nullptr;
+ if (Info.hasSourceManager())
+ SM = &Info.getSourceManager();
+ else if (Context.DiagEngine->hasSourceManager())
+ SM = &Context.DiagEngine->getSourceManager();
ClangTidyDiagnosticRenderer Converter(
Context.getLangOpts(), Context.DiagEngine->getDiagnosticOptions(),
- Errors.back());
+ Errors.back(), Context, SM);
SmallString<100> Message;
Info.FormatDiagnostic(Message);
FullSourceLoc Loc;
- if (Info.hasSourceManager())
- Loc = FullSourceLoc(Info.getLocation(), Info.getSourceManager());
- else if (Context.DiagEngine->hasSourceManager())
- Loc = FullSourceLoc(Info.getLocation(),
- Context.DiagEngine->getSourceManager());
+ if (SM)
+ Loc = FullSourceLoc(Info.getLocation(), *SM);
Converter.emitDiagnostic(Loc, DiagLevel, Message, Info.getRanges(),
Info.getFixItHints());
}
diff --git a/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.h b/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.h
index c76f58bc4cc86d..0261bfa87682f5 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.h
+++ b/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.h
@@ -14,8 +14,10 @@
#include "FileExtensionsSet.h"
#include "NoLintDirectiveHandler.h"
#include "clang/Basic/Diagnostic.h"
+#include "clang/Basic/SourceManagerInternals.h"
#include "clang/Tooling/Core/Diagnostic.h"
#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/Support/Regex.h"
#include <optional>
@@ -231,6 +233,18 @@ class ClangTidyContext {
DiagEngine->getDiagnosticIDs()->getDescription(DiagnosticID))};
}
+ struct FileLineTable {
+ std::vector<std::string> Filenames;
+ std::vector<LineEntry> Entries;
+
+ /// Index of each file name in \c Filenames.
+ llvm::StringMap<int> FilenameIDs;
+ };
+
+ void setUsePresumedLocations(bool Value) { UsePresumedLocations = Value; }
+ void recordLineTable(SourceManager &SM, SourceLocation Loc);
+ const FileLineTable *getLineTable(StringRef AbsolutePath) const;
+
void setOptionsCollector(llvm::StringSet<> *Collector) {
OptionsCollector = Collector;
}
@@ -272,6 +286,9 @@ class ClangTidyContext {
NoLintDirectiveHandler NoLintHandler;
llvm::StringSet<> *OptionsCollector = nullptr;
+
+ bool UsePresumedLocations = true;
+ llvm::StringMap<FileLineTable> LineTables;
};
/// Gets the Fix attached to \p Diagnostic.
diff --git a/clang-tools-extra/docs/ReleaseNotes.md b/clang-tools-extra/docs/ReleaseNotes.md
index b7b1a430d63f34..f2ea017120d89a 100644
--- a/clang-tools-extra/docs/ReleaseNotes.md
+++ b/clang-tools-extra/docs/ReleaseNotes.md
@@ -66,6 +66,10 @@ infrastructure are described first, followed by tool-specific sections.
#### Diagnostics
+- clang-tidy will now reports the presumed line location when running on
+ preprocessed files. This behaviour can be disabled using
+ `-fno-diagnostics-use-presumed-location`
+
- Query-based custom clang-tidy checks can now be enabled with the
`Diagnostics.ClangTidy.ExperimentalCustomChecks` clangd configuration option.
Custom checks are subject to `FastCheckFilter`, and therefore require
diff --git a/clang-tools-extra/test/clang-tidy/infrastructure/Inputs/preprocessed-input/compiler-diag.ii b/clang-tools-extra/test/clang-tidy/infrastructure/Inputs/preprocessed-input/compiler-diag.ii
new file mode 100644
index 00000000000000..ad4c82c453060b
--- /dev/null
+++ b/clang-tools-extra/test/clang-tidy/infrastructure/Inputs/preprocessed-input/compiler-diag.ii
@@ -0,0 +1,6 @@
+# 1 "other.cpp"
+# 10 "other.cpp"
+int f() {}
+int g();
+# 20 "other.cpp"
+class C { C(int); };
diff --git a/clang-tools-extra/test/clang-tidy/infrastructure/Inputs/preprocessed-input/main.ii b/clang-tools-extra/test/clang-tidy/infrastructure/Inputs/preprocessed-input/main.ii
new file mode 100644
index 00000000000000..82f57f895fb16e
--- /dev/null
+++ b/clang-tools-extra/test/clang-tidy/infrastructure/Inputs/preprocessed-input/main.ii
@@ -0,0 +1,19 @@
+# 1 "main.cpp"
+# 1 "<built-in>" 1
+# 1 "<built-in>" 3
+# 1 "<command line>" 1
+# 1 "<built-in>" 2
+# 1 "main.cpp" 2
+# 1 "some/dir/foo.h" 1
+# 20 "some/dir/foo.h"
+void definedInHeader(int a) {}
+# 2 "main.cpp" 2
+
+# 50 "main.cpp"
+void definedInHeader(int b);
+
+class A { A(int); };
+# 1 "some/dir/system.h" 1 3
+class S { S(int); };
+# 53 "main.cpp" 2
+class B { B(int); };
diff --git a/clang-tools-extra/test/clang-tidy/infrastructure/preprocessed-input.cpp b/clang-tools-extra/test/clang-tidy/infrastructure/preprocessed-input.cpp
new file mode 100644
index 00000000000000..46edc5d318c9d0
--- /dev/null
+++ b/clang-tools-extra/test/clang-tidy/infrastructure/preprocessed-input.cpp
@@ -0,0 +1,55 @@
+// Diagnostics on a preprocessed input are reported at the location presumed by
+// its line markers, not at the physical location in the preprocessed file.
+
+// RUN: clang-tidy %S/Inputs/preprocessed-input/main.ii \
+// RUN: -checks='-*,google-explicit-constructor,readability-inconsistent-declaration-parameter-name' \
+// RUN: -- -std=c++17 2>&1 \
+// RUN: | FileCheck %s --check-prefix=CHECK-MESSAGES --implicit-check-not='main.ii:'
+
+// The note is located before the warning in the preprocessed file.
+// CHECK-MESSAGES: main.cpp:50:6: warning: function 'definedInHeader' has a definition with different parameter names [readability-inconsistent-declaration-parameter-name]
+// CHECK-MESSAGES-NEXT: 50 | void definedInHeader(int b);
+// CHECK-MESSAGES: some/dir/foo.h:20:6: note: the definition seen here
+// CHECK-MESSAGES-NEXT: 20 | void definedInHeader(int a) {}
+// CHECK-MESSAGES: main.cpp:50:6: note: differing parameters are named here: ('b'), in definition: ('a')
+// CHECK-MESSAGES: main.cpp:52:11: warning: single-argument constructors must be marked explicit
+// Make sure diagnostics in system headers are still suppressed (line marker flag 3).
+// CHECK-MESSAGES-NOT: system.h
+// CHECK-MESSAGES: main.cpp:53:11: warning: single-argument constructors must be marked explicit
+
+// Fixes should be applied to the preprocessed file, and not the fix notes.
+// We cannot assume the presumed location is available on the executor.
+// RUN: rm -rf %t && mkdir -p %t
+// RUN: cp %S/Inputs/preprocessed-input/main.ii %t/main.ii
+// RUN: clang-tidy %t/main.ii -checks='-*,google-explicit-constructor' --fix \
+// RUN: -- -std=c++17 2>&1 \
+// RUN: | FileCheck %s --check-prefix=CHECK-FIX-MESSAGES --implicit-check-not='main.ii:'
+// RUN: FileCheck %s --check-prefix=CHECK-FIXES --input-file=%t/main.ii
+
+// CHECK-FIX-MESSAGES: main.cpp:52:11: warning: single-argument constructors must be marked explicit
+// CHECK-FIX-MESSAGES: main.cpp:52:11: note: FIX-IT applied suggested code changes
+// CHECK-FIX-MESSAGES: main.cpp:53:11: warning: single-argument constructors must be marked explicit
+// CHECK-FIX-MESSAGES: main.cpp:53:11: note: FIX-IT applied suggested code changes
+
+// CHECK-FIXES: class A { explicit A(int); };
+// CHECK-FIXES: class S { S(int); };
+// CHECK-FIXES: class B { explicit B(int); };
+
+// The physical location is reported when presumed locations are disabled.
+// RUN: clang-tidy %S/Inputs/preprocessed-input/main.ii \
+// RUN: -checks='-*,google-explicit-constructor' \
+// RUN: -- -std=c++17 -Xclang -fno-diagnostics-use-presumed-location 2>&1 \
+// RUN: | FileCheck %s --check-prefix=CHECK-NO-PRESUMED --implicit-check-not='main.cpp:'
+
+// CHECK-NO-PRESUMED: main.ii:15:11: warning: single-argument constructors must be marked explicit
+// CHECK-NO-PRESUMED: main.ii:19:11: warning: single-argument constructors must be marked explicit
+
+// Compiler diagnostics are emitted while the input is being preprocessed,
+// Diagnostics emitted afterwards must still take the later line markers into account.
+// RUN: clang-tidy %S/Inputs/preprocessed-input/compiler-diag.ii \
+// RUN: -checks='-*,clang-diagnostic-return-type,google-explicit-constructor' \
+// RUN: -- -std=c++17 2>&1 \
+// RUN: | FileCheck %s --check-prefix=CHECK-COMPILER-DIAG --implicit-check-not='compiler-diag.ii:'
+
+// CHECK-COMPILER-DIAG: other.cpp:10:10: warning: non-void function does not return a value [clang-diagnostic-return-type]
+// CHECK-COMPILER-DIAG: other.cpp:20:11: warning: single-argument constructors must be marked explicit
More information about the cfe-commits
mailing list