clang 23.0.0git
DependencyFile.cpp
Go to the documentation of this file.
1//===--- DependencyFile.cpp - Generate dependency file --------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This code generates dependency files.
10//
11//===----------------------------------------------------------------------===//
12
19#include "clang/Lex/ModuleMap.h"
23#include "llvm/ADT/StringSet.h"
24#include "llvm/Support/FileSystem.h"
25#include "llvm/Support/Path.h"
26#include "llvm/Support/raw_ostream.h"
27#include <optional>
28
29using namespace clang;
30
31namespace {
32struct DepCollectorPPCallbacks : public PPCallbacks {
33 DependencyCollector &DepCollector;
34 Preprocessor &PP;
35 DepCollectorPPCallbacks(DependencyCollector &L, Preprocessor &PP)
36 : DepCollector(L), PP(PP) {}
37
38 void LexedFileChanged(FileID FID, LexedFileChangeReason Reason,
40 SourceLocation Loc) override {
41 if (Reason != PPCallbacks::LexedFileChangeReason::EnterFile)
42 return;
43
44 // Dependency generation really does want to go all the way to the
45 // file entry for a source location to find out what is depended on.
46 // We do not want #line markers to affect dependency generation!
47 if (std::optional<StringRef> Filename =
48 PP.getSourceManager().getNonBuiltinFilenameForID(FID))
49 DepCollector.maybeAddDependency(
50 llvm::sys::path::remove_leading_dotslash(*Filename),
51 /*FromModule*/ false, isSystem(FileType), /*IsModuleFile*/ false,
52 /*IsDirectModuleImport*/ false, /*IsMissing*/ false);
53 }
54
55 void FileSkipped(const FileEntryRef &SkippedFile, const Token &FilenameTok,
57 StringRef Filename =
58 llvm::sys::path::remove_leading_dotslash(SkippedFile.getName());
59 DepCollector.maybeAddDependency(Filename, /*FromModule=*/false,
60 /*IsSystem=*/isSystem(FileType),
61 /*IsModuleFile=*/false,
62 /*IsDirectModuleImport=*/false,
63 /*IsMissing=*/false);
64 }
65
66 void EmbedDirective(SourceLocation, StringRef, bool,
68 const LexEmbedParametersResult &) override {
69 assert(File && "expected to only be called when the file is found");
70 StringRef FileName =
71 llvm::sys::path::remove_leading_dotslash(File->getName());
72 DepCollector.maybeAddDependency(FileName,
73 /*FromModule*/ false,
74 /*IsSystem*/ false,
75 /*IsModuleFile*/ false,
76 /*IsDirectModuleImport*/ false,
77 /*IsMissing*/ false);
78 }
79
80 bool EmbedFileNotFound(StringRef FileName) override {
81 DepCollector.maybeAddDependency(
82 llvm::sys::path::remove_leading_dotslash(FileName),
83 /*FromModule=*/false,
84 /*IsSystem=*/false,
85 /*IsModuleFile=*/false,
86 /*IsDirectModuleImport=*/false,
87 /*IsMissing=*/true);
88 // Return true to silence the file not found diagnostic.
89 return true;
90 }
91
92 void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
93 StringRef FileName, bool IsAngled,
94 CharSourceRange FilenameRange,
95 OptionalFileEntryRef File, StringRef SearchPath,
96 StringRef RelativePath, const Module *SuggestedModule,
97 bool ModuleImported,
99 if (!File)
100 DepCollector.maybeAddDependency(FileName, /*FromModule*/ false,
101 /*IsSystem*/ false,
102 /*IsModuleFile*/ false,
103 /*IsDirectModuleImport*/ false,
104 /*IsMissing*/ true);
105 // Files that actually exist are handled by FileChanged.
106 }
107
108 void HasEmbed(SourceLocation, StringRef, bool,
109 OptionalFileEntryRef File) override {
110 if (!File)
111 return;
112 StringRef Filename =
113 llvm::sys::path::remove_leading_dotslash(File->getName());
114 DepCollector.maybeAddDependency(Filename,
115 /*FromModule=*/false, false,
116 /*IsModuleFile=*/false,
117 /*IsDirectModuleImport=*/false,
118 /*IsMissing=*/false);
119 }
120
121 void HasInclude(SourceLocation Loc, StringRef SpelledFilename, bool IsAngled,
124 if (!File)
125 return;
126 StringRef Filename =
127 llvm::sys::path::remove_leading_dotslash(File->getName());
128 DepCollector.maybeAddDependency(Filename, /*FromModule=*/false,
129 /*IsSystem=*/isSystem(FileType),
130 /*IsModuleFile=*/false,
131 /*IsDirectModuleImport=*/false,
132 /*IsMissing=*/false);
133 }
134
135 void EndOfMainFile() override {
136 DepCollector.finishedMainFile(PP.getDiagnostics());
137 }
138};
139
140struct DepCollectorMMCallbacks : public ModuleMapCallbacks {
141 DependencyCollector &DepCollector;
142 DepCollectorMMCallbacks(DependencyCollector &DC) : DepCollector(DC) {}
143
144 void moduleMapFileRead(SourceLocation Loc, FileEntryRef Entry,
145 bool IsSystem) override {
146 StringRef Filename = Entry.getName();
147 DepCollector.maybeAddDependency(Filename, /*FromModule*/ false,
148 /*IsSystem*/ IsSystem,
149 /*IsModuleFile*/ false,
150 /*IsDirectModuleImport*/ false,
151 /*IsMissing*/ false);
152 }
153};
154
155struct DepCollectorASTListener : public ASTReaderListener {
156 DependencyCollector &DepCollector;
157 FileManager &FileMgr;
158 DepCollectorASTListener(DependencyCollector &L, FileManager &FileMgr)
159 : DepCollector(L), FileMgr(FileMgr) {}
160 bool needsInputFileVisitation() override { return true; }
161 bool needsSystemInputFileVisitation() override {
162 return DepCollector.needSystemDependencies();
163 }
164 void visitModuleFile(ModuleFileName Filename, serialization::ModuleKind Kind,
165 bool DirectlyImported) override {
166 DepCollector.maybeAddDependency(Filename, /*FromModule*/ true,
167 /*IsSystem*/ false, /*IsModuleFile*/ true,
168 /*IsDirectModuleImport*/ DirectlyImported,
169 /*IsMissing*/ false);
170 }
171 bool visitInputFile(StringRef Filename, bool IsSystem,
172 bool IsOverridden, bool IsExplicitModule) override {
173 if (IsOverridden || IsExplicitModule)
174 return true;
175
176 // Run this through the FileManager in order to respect 'use-external-name'
177 // in case we have a VFS overlay.
178 if (auto FE = FileMgr.getOptionalFileRef(Filename))
179 Filename = FE->getName();
180
181 DepCollector.maybeAddDependency(Filename, /*FromModule*/ true, IsSystem,
182 /*IsModuleFile*/ false,
183 /*IsDirectModuleImport*/ false,
184 /*IsMissing*/ false);
185 return true;
186 }
187};
188} // end anonymous namespace
189
191 bool FromModule, bool IsSystem,
192 bool IsModuleFile,
193 bool IsDirectModuleImport,
194 bool IsMissing) {
195 if (sawDependency(Filename, FromModule, IsSystem, IsModuleFile,
196 IsDirectModuleImport, IsMissing))
197 addDependency(Filename);
198}
199
200bool DependencyCollector::addDependency(StringRef Filename) {
201 StringRef SearchPath;
202#ifdef _WIN32
203 // Make the search insensitive to case and separators.
204 llvm::SmallString<256> TmpPath = Filename;
205 llvm::sys::path::native(TmpPath);
206 std::transform(TmpPath.begin(), TmpPath.end(), TmpPath.begin(), ::tolower);
207 SearchPath = TmpPath.str();
208#else
209 SearchPath = Filename;
210#endif
211
212 if (Seen.insert(SearchPath).second) {
213 Dependencies.push_back(std::string(Filename));
214 return true;
215 }
216 return false;
217}
218
219static bool isSpecialFilename(StringRef Filename) {
220 return Filename == "<built-in>";
221}
222
223bool DependencyCollector::sawDependency(StringRef Filename, bool FromModule,
224 bool IsSystem, bool IsModuleFile,
225 bool IsDirectModuleImport,
226 bool IsMissing) {
227 return !isSpecialFilename(Filename) &&
228 (needSystemDependencies() || !IsSystem);
229}
230
233 PP.addPPCallbacks(std::make_unique<DepCollectorPPCallbacks>(*this, PP));
235 std::make_unique<DepCollectorMMCallbacks>(*this));
236}
238 R.addListener(
239 std::make_unique<DepCollectorASTListener>(*this, R.getFileManager()));
240}
241
243 const DependencyOutputOptions &Opts)
244 : OutputFile(Opts.OutputFile), Targets(Opts.Targets),
245 IncludeSystemHeaders(Opts.IncludeSystemHeaders),
246 PhonyTarget(Opts.UsePhonyTargets),
247 AddMissingHeaderDeps(Opts.AddMissingHeaderDeps), SeenMissingHeader(false),
248 IncludeModuleFiles(
249 static_cast<ModuleFileDepsKind>(Opts.IncludeModuleFiles)),
250 OutputFormat(Opts.OutputFormat), InputFileIndex(0) {
251 for (const auto &ExtraDep : Opts.ExtraDeps) {
252 if (addDependency(ExtraDep.first))
253 ++InputFileIndex;
254 }
255}
256
258 // Disable the "file not found" diagnostic if the -MG option was given.
259 if (AddMissingHeaderDeps)
261
263}
264
265bool DependencyFileGenerator::sawDependency(StringRef Filename, bool FromModule,
266 bool IsSystem, bool IsModuleFile,
267 bool IsDirectModuleImport,
268 bool IsMissing) {
269 if (IsMissing) {
270 // Handle the case of missing file from an inclusion directive.
271 if (AddMissingHeaderDeps)
272 return true;
273 SeenMissingHeader = true;
274 return false;
275 }
276 if (IsModuleFile) {
277 if (IncludeModuleFiles == MFDK_None)
278 return false;
279 if (IncludeModuleFiles == MFDK_Direct && !IsDirectModuleImport)
280 return false;
281 }
282
283 if (isSpecialFilename(Filename))
284 return false;
285
286 if (IncludeSystemHeaders)
287 return true;
288
289 return !IsSystem;
290}
291
295
296/// Print the filename, with escaping or quoting that accommodates the three
297/// most likely tools that use dependency files: GNU Make, BSD Make, and
298/// NMake/Jom.
299///
300/// BSD Make is the simplest case: It does no escaping at all. This means
301/// characters that are normally delimiters, i.e. space and # (the comment
302/// character) simply aren't supported in filenames.
303///
304/// GNU Make does allow space and # in filenames, but to avoid being treated
305/// as a delimiter or comment, these must be escaped with a backslash. Because
306/// backslash is itself the escape character, if a backslash appears in a
307/// filename, it should be escaped as well. (As a special case, $ is escaped
308/// as $$, which is the normal Make way to handle the $ character.)
309/// For compatibility with BSD Make and historical practice, if GNU Make
310/// un-escapes characters in a filename but doesn't find a match, it will
311/// retry with the unmodified original string.
312///
313/// GCC tries to accommodate both Make formats by escaping any space or #
314/// characters in the original filename, but not escaping backslashes. The
315/// apparent intent is so that filenames with backslashes will be handled
316/// correctly by BSD Make, and by GNU Make in its fallback mode of using the
317/// unmodified original string; filenames with # or space characters aren't
318/// supported by BSD Make at all, but will be handled correctly by GNU Make
319/// due to the escaping.
320///
321/// A corner case that GCC gets only partly right is when the original filename
322/// has a backslash immediately followed by space or #. GNU Make would expect
323/// this backslash to be escaped; however GCC escapes the original backslash
324/// only when followed by space, not #. It will therefore take a dependency
325/// from a directive such as
326/// #include "a\ b\#c.h"
327/// and emit it as
328/// a\\\ b\\#c.h
329/// which GNU Make will interpret as
330/// a\ b\
331/// followed by a comment. Failing to find this file, it will fall back to the
332/// original string, which probably doesn't exist either; in any case it won't
333/// find
334/// a\ b\#c.h
335/// which is the actual filename specified by the include directive.
336///
337/// Clang does what GCC does, rather than what GNU Make expects.
338///
339/// NMake/Jom has a different set of scary characters, but wraps filespecs in
340/// double-quotes to avoid misinterpreting them; see
341/// https://msdn.microsoft.com/en-us/library/dd9y37ha.aspx for NMake info,
342/// https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx
343/// for Windows file-naming info.
344static void PrintFilename(raw_ostream &OS, StringRef Filename,
345 DependencyOutputFormat OutputFormat) {
346 // Convert filename to platform native path
347 llvm::SmallString<256> NativePath;
348 llvm::sys::path::native(Filename.str(), NativePath);
349
350 if (OutputFormat == DependencyOutputFormat::NMake) {
351 // Add quotes if needed. These are the characters listed as "special" to
352 // NMake, that are legal in a Windows filespec, and that could cause
353 // misinterpretation of the dependency string.
354 if (NativePath.find_first_of(" #${}^!") != StringRef::npos)
355 OS << '\"' << NativePath << '\"';
356 else
357 OS << NativePath;
358 return;
359 }
360 assert(OutputFormat == DependencyOutputFormat::Make);
361 for (unsigned i = 0, e = NativePath.size(); i != e; ++i) {
362 if (NativePath[i] == '#') // Handle '#' the broken gcc way.
363 OS << '\\';
364 else if (NativePath[i] == ' ') { // Handle space correctly.
365 OS << '\\';
366 unsigned j = i;
367 while (j > 0 && NativePath[--j] == '\\')
368 OS << '\\';
369 } else if (NativePath[i] == '$') // $ is escaped by $$.
370 OS << '$';
371 OS << NativePath[i];
372 }
373}
374
376 if (SeenMissingHeader) {
377 llvm::sys::fs::remove(OutputFile);
378 return;
379 }
380
381 std::error_code EC;
382 llvm::raw_fd_ostream OS(OutputFile, EC, llvm::sys::fs::OF_TextWithCRLF);
383 if (EC) {
384 Diags.Report(diag::err_fe_error_opening) << OutputFile << EC.message();
385 return;
386 }
387
389}
390
392 // Write out the dependency targets, trying to avoid overly long
393 // lines when possible. We try our best to emit exactly the same
394 // dependency file as GCC>=10, assuming the included files are the
395 // same.
396 const unsigned MaxColumns = 75;
397 unsigned Columns = 0;
398
399 for (StringRef Target : Targets) {
400 unsigned N = Target.size();
401 if (Columns == 0) {
402 Columns += N;
403 } else if (Columns + N + 2 > MaxColumns) {
404 Columns = N + 2;
405 OS << " \\\n ";
406 } else {
407 Columns += N + 1;
408 OS << ' ';
409 }
410 // Targets already quoted as needed.
411 OS << Target;
412 }
413
414 OS << ':';
415 Columns += 1;
416
417 // Now add each dependency in the order it was seen, but avoiding
418 // duplicates.
420 for (StringRef File : Files) {
421 if (File == "<stdin>")
422 continue;
423 // Start a new line if this would exceed the column limit. Make
424 // sure to leave space for a trailing " \" in case we need to
425 // break the line on the next iteration.
426 unsigned N = File.size();
427 if (Columns + (N + 1) + 2 > MaxColumns) {
428 OS << " \\\n ";
429 Columns = 2;
430 }
431 OS << ' ';
432 PrintFilename(OS, File, OutputFormat);
433 Columns += N + 1;
434 }
435 OS << '\n';
436
437 // Create phony targets if requested.
438 if (PhonyTarget && !Files.empty()) {
439 unsigned Index = 0;
440 for (auto I = Files.begin(), E = Files.end(); I != E; ++I) {
441 if (Index++ == InputFileIndex)
442 continue;
443 PrintFilename(OS, *I, OutputFormat);
444 OS << ":\n";
445 }
446 }
447}
static void PrintFilename(raw_ostream &OS, StringRef Filename, DependencyOutputFormat OutputFormat)
Print the filename, with escaping or quoting that accommodates the three most likely tools that use d...
static bool isSpecialFilename(StringRef Filename)
Defines the clang::FileManager interface and associated types.
llvm::MachO::FileType FileType
Definition MachO.h:46
Defines the PPCallbacks interface.
Defines the clang::Preprocessor interface.
Defines the SourceManager interface.
Abstract interface for callback invocations by the ASTReader.
Definition ASTReader.h:117
Reads an AST files chain containing the contents of a translation unit.
Definition ASTReader.h:428
bool addDependency(StringRef Filename)
Return true if the filename was added to the list of dependencies, false otherwise.
virtual void attachToPreprocessor(Preprocessor &PP)
virtual void maybeAddDependency(StringRef Filename, bool FromModule, bool IsSystem, bool IsModuleFile, bool IsDirectModuleImport, bool IsMissing)
Add a dependency Filename if it has not been seen before and sawDependency() returns true.
ArrayRef< std::string > getDependencies() const
Definition Utils.h:69
virtual void attachToASTReader(ASTReader &R)
virtual bool sawDependency(StringRef Filename, bool FromModule, bool IsSystem, bool IsModuleFile, bool IsDirectModuleImport, bool IsMissing)
Called when a new file is seen.
virtual bool needSystemDependencies()
Return true if system files should be passed to sawDependency().
Definition Utils.h:83
void outputDependencyFile(llvm::raw_ostream &OS)
void attachToPreprocessor(Preprocessor &PP) override
void finishedMainFile(DiagnosticsEngine &Diags) override
Called when the end of the main file is reached.
bool sawDependency(StringRef Filename, bool FromModule, bool IsSystem, bool IsModuleFile, bool IsDirectModuleImport, bool IsMissing) final
Called when a new file is seen.
DependencyFileGenerator(const DependencyOutputOptions &Opts)
DependencyOutputOptions - Options for controlling the compiler dependency file generation.
std::vector< std::pair< std::string, ExtraDepKind > > ExtraDeps
A list of extra dependencies (filename and kind) to be used for every target.
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:233
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
StringRef getName() const
The name of this FileEntry.
Definition FileEntry.h:61
ModuleMap & getModuleMap()
Retrieve the module map.
A mechanism to observe the actions of the module map loader as it reads module map files.
Definition ModuleMap.h:49
void addModuleMapCallbacks(std::unique_ptr< ModuleMapCallbacks > Callback)
Add a module map callback.
Definition ModuleMap.h:434
This interface provides a way to observe the actions of the preprocessor as it does its thing.
Definition PPCallbacks.h:37
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
void addPPCallbacks(std::unique_ptr< PPCallbacks > C)
HeaderSearch & getHeaderSearchInfo() const
void SetSuppressIncludeNotFoundError(bool Suppress)
CharacteristicKind
Indicates whether a file or directory holds normal user code, system code, or system code which is im...
bool isSystem(CharacteristicKind CK)
Determine whether a file / directory characteristic is for system code.
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
ModuleKind
Specifies the kind of module that has been loaded.
Definition ModuleFile.h:44
The JSON file list parser is used to communicate input to InstallAPI.
CustomizableOptional< FileEntryRef > OptionalFileEntryRef
Definition FileEntry.h:208
@ Module
Module linkage, which indicates that the entity can be referred to from other translation units withi...
Definition Linkage.h:54
ModuleFileDepsKind
ModuleFileDepsKind - Whether to include module file dependencies.
@ MFDK_Direct
Include only directly imported module file dependencies.
@ MFDK_None
Do not include module file dependencies.
DependencyOutputFormat
DependencyOutputFormat - Format for the compiler dependency file.
#define false
Definition stdbool.h:26