clang 20.0.0git
ModuleDependencyCollector.cpp
Go to the documentation of this file.
1//===--- ModuleDependencyCollector.cpp - Collect module dependencies ------===//
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// Collect the dependencies of a set of modules.
10//
11//===----------------------------------------------------------------------===//
12
17#include "llvm/ADT/iterator_range.h"
18#include "llvm/Config/llvm-config.h"
19#include "llvm/Support/FileSystem.h"
20#include "llvm/Support/Path.h"
21#include "llvm/Support/raw_ostream.h"
22
23using namespace clang;
24
25namespace {
26/// Private implementations for ModuleDependencyCollector
27class ModuleDependencyListener : public ASTReaderListener {
29 FileManager &FileMgr;
30public:
31 ModuleDependencyListener(ModuleDependencyCollector &Collector,
32 FileManager &FileMgr)
33 : Collector(Collector), FileMgr(FileMgr) {}
34 bool needsInputFileVisitation() override { return true; }
35 bool needsSystemInputFileVisitation() override { return true; }
36 bool visitInputFile(StringRef Filename, bool IsSystem, bool IsOverridden,
37 bool IsExplicitModule) override {
38 // Run this through the FileManager in order to respect 'use-external-name'
39 // in case we have a VFS overlay.
40 if (auto FE = FileMgr.getOptionalFileRef(Filename))
41 Filename = FE->getName();
42 Collector.addFile(Filename);
43 return true;
44 }
45};
46
47struct ModuleDependencyPPCallbacks : public PPCallbacks {
50 ModuleDependencyPPCallbacks(ModuleDependencyCollector &Collector,
51 SourceManager &SM)
52 : Collector(Collector), SM(SM) {}
53
54 void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
55 StringRef FileName, bool IsAngled,
56 CharSourceRange FilenameRange,
57 OptionalFileEntryRef File, StringRef SearchPath,
58 StringRef RelativePath, const Module *SuggestedModule,
59 bool ModuleImported,
61 if (!File)
62 return;
63 Collector.addFile(File->getName());
64 }
65};
66
67struct ModuleDependencyMMCallbacks : public ModuleMapCallbacks {
69 ModuleDependencyMMCallbacks(ModuleDependencyCollector &Collector)
70 : Collector(Collector) {}
71
72 void moduleMapAddHeader(StringRef HeaderPath) override {
73 if (llvm::sys::path::is_absolute(HeaderPath))
74 Collector.addFile(HeaderPath);
75 }
76 void moduleMapAddUmbrellaHeader(FileEntryRef Header) override {
78 }
79};
80
81} // namespace
82
85 std::make_unique<ModuleDependencyListener>(*this, R.getFileManager()));
86}
87
89 PP.addPPCallbacks(std::make_unique<ModuleDependencyPPCallbacks>(
90 *this, PP.getSourceManager()));
92 std::make_unique<ModuleDependencyMMCallbacks>(*this));
93}
94
95static bool isCaseSensitivePath(StringRef Path) {
96 SmallString<256> TmpDest = Path, UpperDest, RealDest;
97 // Remove component traversals, links, etc.
98 if (llvm::sys::fs::real_path(Path, TmpDest))
99 return true; // Current default value in vfs.yaml
100 Path = TmpDest;
101
102 // Change path to all upper case and ask for its real path, if the latter
103 // exists and is equal to Path, it's not case sensitive. Default to case
104 // sensitive in the absence of realpath, since this is what the VFSWriter
105 // already expects when sensitivity isn't setup.
106 for (auto &C : Path)
107 UpperDest.push_back(toUppercase(C));
108 if (!llvm::sys::fs::real_path(UpperDest, RealDest) && Path == RealDest)
109 return false;
110 return true;
111}
112
114 if (Seen.empty())
115 return;
116
117 StringRef VFSDir = getDest();
118
119 // Default to use relative overlay directories in the VFS yaml file. This
120 // allows crash reproducer scripts to work across machines.
121 VFSWriter.setOverlayDir(VFSDir);
122
123 // Explicitly set case sensitivity for the YAML writer. For that, find out
124 // the sensitivity at the path where the headers all collected to.
125 VFSWriter.setCaseSensitivity(isCaseSensitivePath(VFSDir));
126
127 // Do not rely on real path names when executing the crash reproducer scripts
128 // since we only want to actually use the files we have on the VFS cache.
129 VFSWriter.setUseExternalNames(false);
130
131 std::error_code EC;
132 SmallString<256> YAMLPath = VFSDir;
133 llvm::sys::path::append(YAMLPath, "vfs.yaml");
134 llvm::raw_fd_ostream OS(YAMLPath, EC, llvm::sys::fs::OF_TextWithCRLF);
135 if (EC) {
136 HasErrors = true;
137 return;
138 }
139 VFSWriter.write(OS);
140}
141
142std::error_code ModuleDependencyCollector::copyToRoot(StringRef Src,
143 StringRef Dst) {
144 using namespace llvm::sys;
145 llvm::FileCollector::PathCanonicalizer::PathStorage Paths =
146 Canonicalizer.canonicalize(Src);
147
148 SmallString<256> CacheDst = getDest();
149
150 if (Dst.empty()) {
151 // The common case is to map the virtual path to the same path inside the
152 // cache.
153 path::append(CacheDst, path::relative_path(Paths.CopyFrom));
154 } else {
155 // When collecting entries from input vfsoverlays, copy the external
156 // contents into the cache but still map from the source.
157 if (!fs::exists(Dst))
158 return std::error_code();
159 path::append(CacheDst, Dst);
160 Paths.CopyFrom = Dst;
161 }
162
163 // Copy the file into place.
164 if (std::error_code EC = fs::create_directories(path::parent_path(CacheDst),
165 /*IgnoreExisting=*/true))
166 return EC;
167 if (std::error_code EC = fs::copy_file(Paths.CopyFrom, CacheDst))
168 return EC;
169
170 // Always map a canonical src path to its real path into the YAML, by doing
171 // this we map different virtual src paths to the same entry in the VFS
172 // overlay, which is a way to emulate symlink inside the VFS; this is also
173 // needed for correctness, not doing that can lead to module redefinition
174 // errors.
175 addFileMapping(Paths.VirtualPath, CacheDst);
176 return std::error_code();
177}
178
179void ModuleDependencyCollector::addFile(StringRef Filename, StringRef FileDst) {
180 if (insertSeen(Filename))
181 if (copyToRoot(Filename, FileDst))
182 HasErrors = true;
183}
#define SM(sm)
Definition: Cuda.cpp:83
IndirectLocalPath & Path
StringRef Filename
Definition: Format.cpp:3001
llvm::MachO::FileType FileType
Definition: MachO.h:46
static bool isCaseSensitivePath(StringRef Path)
Defines the clang::Preprocessor interface.
Abstract interface for callback invocations by the ASTReader.
Definition: ASTReader.h:114
virtual bool needsInputFileVisitation()
Returns true if this ASTReaderListener wants to receive the input files of the AST file via visitInpu...
Definition: ASTReader.h:221
virtual bool visitInputFile(StringRef Filename, bool isSystem, bool isOverridden, bool isExplicitModule)
if needsInputFileVisitation returns true, this is called for each non-system input file of the AST Fi...
Definition: ASTReader.h:233
virtual bool needsSystemInputFileVisitation()
Returns true if this ASTReaderListener wants to receive the system input files of the AST file via vi...
Definition: ASTReader.h:225
Reads an AST files chain containing the contents of a translation unit.
Definition: ASTReader.h:378
void addListener(std::unique_ptr< ASTReaderListener > L)
Add an AST callback listener.
Definition: ASTReader.h:1716
FileManager & getFileManager() const
Definition: ASTReader.h:1623
Represents a character-granular source range.
A reference to a FileEntry that includes the name of the file as it was accessed by the FileManager's...
Definition: FileEntry.h:57
StringRef getNameAsRequested() const
The name of this FileEntry, as originally requested without applying any remappings for VFS 'use-exte...
Definition: FileEntry.h:68
Implements support for file system lookup, file system caching, and directory search management.
Definition: FileManager.h:53
OptionalFileEntryRef getOptionalFileRef(StringRef Filename, bool OpenFile=false, bool CacheFailure=true)
Get a FileEntryRef if it exists, without doing anything on error.
Definition: FileManager.h:240
ModuleMap & getModuleMap()
Retrieve the module map.
Definition: HeaderSearch.h:833
Record the location of an inclusion directive, such as an #include or #import statement.
Collects the dependencies for imported modules into a directory.
Definition: Utils.h:136
void attachToASTReader(ASTReader &R) override
virtual void addFileMapping(StringRef VPath, StringRef RPath)
Definition: Utils.h:154
void attachToPreprocessor(Preprocessor &PP) override
virtual void addFile(StringRef Filename, StringRef FileDst={})
virtual bool insertSeen(StringRef Filename)
Definition: Utils.h:151
A mechanism to observe the actions of the module map parser as it reads module map files.
Definition: ModuleMap.h:48
virtual void moduleMapAddHeader(StringRef Filename)
Called when a header is added during module map parsing.
Definition: ModuleMap.h:66
virtual void moduleMapAddUmbrellaHeader(FileEntryRef Header)
Called when an umbrella header is added during module map parsing.
Definition: ModuleMap.h:71
void addModuleMapCallbacks(std::unique_ptr< ModuleMapCallbacks > Callback)
Add a module map callback.
Definition: ModuleMap.h:424
Describes a module or submodule.
Definition: Module.h:105
This interface provides a way to observe the actions of the preprocessor as it does its thing.
Definition: PPCallbacks.h:36
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:137
void addPPCallbacks(std::unique_ptr< PPCallbacks > C)
SourceManager & getSourceManager() const
HeaderSearch & getHeaderSearchInfo() const
Encodes a location in the source.
This class handles loading and caching of source files into memory.
Token - This structure provides full information about a lexed token.
Definition: Token.h:36
CharacteristicKind
Indicates whether a file or directory holds normal user code, system code, or system code which is im...
Definition: SourceManager.h:81
The JSON file list parser is used to communicate input to InstallAPI.
LLVM_READONLY char toUppercase(char c)
Converts the given ASCII character to its uppercase equivalent.
Definition: CharInfo.h:233