15#include "llvm/ADT/STLExtras.h"
16#include "llvm/Support/BLAKE3.h"
17#include "llvm/Support/StringSaver.h"
21using namespace tooling;
22using namespace dependencies;
27 for (StringRef FileDep : FileDeps) {
28 auto ResolvedFileDep =
35 assert(!std::holds_alternative<std::monostate>(BuildInfo) &&
36 "Using uninitialized ModuleDeps");
37 if (
const auto *CI = std::get_if<CowCompilerInvocation>(&BuildInfo))
38 BuildInfo = CI->getCC1CommandLine();
39 return std::get<std::vector<std::string>>(BuildInfo);
49 std::vector<HeaderSearchOptions::Entry> Entries;
52 llvm::BitVector SearchPathUsage(Entries.size());
53 llvm::DenseSet<const serialization::ModuleFile *>
Visited;
64 if (SearchPathUsage.size() != Entries.size())
65 llvm::report_fatal_error(
66 "Inconsistent search path options between modules detected");
68 for (
auto Idx : SearchPathUsage.set_bits())
69 Opts.
UserEntries.push_back(std::move(Entries[Idx]));
72 std::vector<std::string> VFSOverlayFiles;
75 llvm::BitVector VFSUsage(VFSOverlayFiles.size());
76 llvm::DenseSet<const serialization::ModuleFile *>
Visited;
90 auto VFSMap = PrebuiltModuleVFSMap.find(MF->
FileName);
91 if (VFSMap == PrebuiltModuleVFSMap.end())
93 for (std::size_t I = 0,
E = VFSOverlayFiles.size(); I !=
E; ++I) {
94 if (VFSMap->second.contains(VFSOverlayFiles[I]))
101 if (VFSUsage.size() != VFSOverlayFiles.size())
102 llvm::report_fatal_error(
103 "Inconsistent -ivfsoverlay options between modules detected");
105 for (
auto Idx : VFSUsage.set_bits())
111 bool IsSystemModule) {
116 bool Wsystem_headers =
false;
117 for (StringRef Opt : Opts.
Warnings) {
118 bool isPositive = !Opt.consume_front(
"no-");
119 if (Opt ==
"system-headers")
120 Wsystem_headers = isPositive;
132static std::vector<std::string>
splitString(std::string S,
char Separator) {
134 StringRef(S).split(Segments, Separator, -1,
false);
135 std::vector<std::string>
Result;
136 Result.reserve(Segments.size());
137 for (StringRef Segment : Segments)
138 Result.push_back(Segment.str());
226 [&CI](
const std::pair<std::string, bool> &Def) {
227 StringRef MacroDef = Def.first;
228 return CI.getHeaderSearchOpts().ModulesIgnoreMacros.contains(
229 llvm::CachedHashString(MacroDef.split(
'=').first));
239ModuleDepCollector::getInvocationAdjustedForModuleBuildWithoutOutputs(
253 auto CurrentModuleMapEntry =
255 assert(CurrentModuleMapEntry &&
"module map file entry not found");
264 auto ModuleMapEntry =
266 assert(ModuleMapEntry &&
"module map file entry not found");
273 if (EagerLoadModules && DepModuleMapFiles.contains(*ModuleMapEntry))
278 if (*ModuleMapEntry == *CurrentModuleMapEntry &&
279 !DepModuleMapFiles.contains(*ModuleMapEntry))
306llvm::DenseSet<const FileEntry *> ModuleDepCollector::collectModuleMapFiles(
308 llvm::DenseSet<const FileEntry *> ModuleMapFiles;
309 for (
const ModuleID &MID : ClangModuleDeps) {
311 assert(MD &&
"Inconsistent dependency info");
315 assert(FE &&
"Missing module map file that was previously found");
316 ModuleMapFiles.insert(*FE);
318 return ModuleMapFiles;
321void ModuleDepCollector::addModuleMapFiles(
323 if (EagerLoadModules)
326 for (
const ModuleID &MID : ClangModuleDeps) {
328 assert(MD &&
"Inconsistent dependency info");
333void ModuleDepCollector::addModuleFiles(
335 for (
const ModuleID &MID : ClangModuleDeps) {
336 std::string PCMPath =
338 if (EagerLoadModules)
342 {MID.ModuleName, std::move(PCMPath)});
346void ModuleDepCollector::addModuleFiles(
348 for (
const ModuleID &MID : ClangModuleDeps) {
349 std::string PCMPath =
351 if (EagerLoadModules)
355 {MID.ModuleName, std::move(PCMPath)});
383 CurrentModuleMap->getNameAsRequested());
386 for (
const auto &KV : ModularDeps)
387 if (DirectModularDeps.contains(KV.first))
388 DirectDeps.push_back(KV.second->ID);
391 addModuleMapFiles(CI, DirectDeps);
393 addModuleFiles(CI, DirectDeps);
395 for (
const auto &KV : DirectPrebuiltModularDeps)
402 bool EagerLoadModules,
403 llvm::vfs::FileSystem &
VFS) {
404 llvm::HashBuilder<llvm::TruncatedBLAKE3<16>, llvm::endianness::native>
412 llvm::ErrorOr<std::string> CWD =
VFS.getCurrentWorkingDirectory();
414 HashBuilder.add(*CWD);
418 ArgVec.reserve(4096);
420 Arg.toVector(ArgVec);
421 ArgVec.push_back(
'\0');
423 HashBuilder.add(ArgVec);
431 HashBuilder.add(ID.ModuleName);
432 HashBuilder.add(ID.ContextHash);
435 HashBuilder.add(EagerLoadModules);
437 llvm::BLAKE3Result<16> Hash = HashBuilder.final();
438 std::array<uint64_t, 2> Words;
439 static_assert(
sizeof(Hash) ==
sizeof(Words),
"Hash must match Words");
440 std::memcpy(Words.data(), Hash.data(),
sizeof(Hash));
441 return toString(llvm::APInt(
sizeof(Words) * 8, Words), 36,
false);
444void ModuleDepCollector::associateWithContextHash(
448 bool Inserted = ModuleDepsByID.insert({Deps.
ID, &Deps}).second;
450 assert(Inserted &&
"duplicate module mapping");
463 if (MDC.ContextHash.empty()) {
473 if (std::optional<StringRef>
Filename =
SM.getNonBuiltinFilenameForID(FID))
474 MDC.addFileDep(llvm::sys::path::remove_leading_dotslash(*
Filename));
480 StringRef SearchPath, StringRef RelativePath,
const Module *SuggestedModule,
482 if (!
File && !ModuleImported) {
487 handleImport(SuggestedModule);
497 MDC.RequiredStdCXXModules.push_back(RequiredModule);
501 handleImport(Imported);
504void ModuleDepCollectorPP::handleImport(
const Module *Imported) {
510 if (MDC.isPrebuiltModule(TopLevelModule))
511 MDC.DirectPrebuiltModularDeps.insert(
514 MDC.DirectModularDeps.insert(TopLevelModule);
524 if (PP.isInNamedModule()) {
526 ProvidedModule.
ModuleName = PP.getNamedModuleName();
532 if (PP.isInImplementationUnit())
533 MDC.RequiredStdCXXModules.push_back(ProvidedModule);
535 MDC.ProvidedStdCXXModule = ProvidedModule;
543 if (!MDC.isPrebuiltModule(M))
544 MDC.DirectModularDeps.insert(M);
546 for (
const Module *M : MDC.DirectModularDeps)
547 handleTopLevelModule(M);
551 if (MDC.IsStdModuleP1689Format)
553 MDC.ProvidedStdCXXModule, MDC.RequiredStdCXXModules);
555 for (
auto &&I : MDC.ModularDeps)
558 for (
const Module *M : MDC.DirectModularDeps) {
559 auto It = MDC.ModularDeps.find(M);
561 if (It != MDC.ModularDeps.end())
565 for (
auto &&I : MDC.FileDeps)
568 for (
auto &&I : MDC.DirectPrebuiltModularDeps)
572std::optional<ModuleID>
573ModuleDepCollectorPP::handleTopLevelModule(
const Module *M) {
584 if (
auto ModI = MDC.ModularDeps.find(M); ModI != MDC.ModularDeps.end())
585 return ModI->second->ID;
587 auto OwnedMD = std::make_unique<ModuleDeps>();
607 MDC.ScanInstance.
getASTReader()->getModuleManager().lookup(
623 llvm::DenseSet<const Module *> SeenDeps;
624 addAllSubmodulePrebuiltDeps(M, MD, SeenDeps);
625 addAllSubmoduleDeps(M, MD, SeenDeps);
626 addAllAffectingClangModules(M, MD, SeenDeps);
629 PathBuf.reserve(256);
636 "__inferred_module.map"))
645 MDC.getInvocationAdjustedForModuleBuildWithoutOutputs(
651 MDC.PrebuiltModuleVFSMap,
659 MDC.associateWithContextHash(CI, MD);
662 MDC.addOutputPaths(CI, MD);
664 MD.BuildInfo = std::move(CI);
666 MDC.ModularDeps.insert({M, std::move(OwnedMD)});
672 llvm::function_ref<
void(
const Module *)> F) {
677 llvm::stable_sort(Submodules, [](
const Module *A,
const Module *B) {
680 for (
const Module *SubM : Submodules)
684void ModuleDepCollectorPP::addAllSubmodulePrebuiltDeps(
686 llvm::DenseSet<const Module *> &SeenSubmodules) {
687 addModulePrebuiltDeps(M, MD, SeenSubmodules);
690 addAllSubmodulePrebuiltDeps(SubM, MD, SeenSubmodules);
694void ModuleDepCollectorPP::addModulePrebuiltDeps(
696 llvm::DenseSet<const Module *> &SeenSubmodules) {
699 if (MDC.isPrebuiltModule(
Import->getTopLevelModule()))
700 if (SeenSubmodules.insert(
Import->getTopLevelModule()).second)
704void ModuleDepCollectorPP::addAllSubmoduleDeps(
706 llvm::DenseSet<const Module *> &AddedModules) {
707 addModuleDep(M, MD, AddedModules);
710 addAllSubmoduleDeps(SubM, MD, AddedModules);
714void ModuleDepCollectorPP::addModuleDep(
716 llvm::DenseSet<const Module *> &AddedModules) {
719 !MDC.isPrebuiltModule(
Import)) {
720 if (
auto ImportID = handleTopLevelModule(
Import->getTopLevelModule()))
721 if (AddedModules.insert(
Import->getTopLevelModule()).second)
727void ModuleDepCollectorPP::addAllAffectingClangModules(
729 llvm::DenseSet<const Module *> &AddedModules) {
730 addAffectingClangModule(M, MD, AddedModules);
733 addAllAffectingClangModules(SubM, MD, AddedModules);
736void ModuleDepCollectorPP::addAffectingClangModule(
738 llvm::DenseSet<const Module *> &AddedModules) {
741 "Not quite import not top-level module");
743 !MDC.isPrebuiltModule(Affecting)) {
744 if (
auto ImportID = handleTopLevelModule(Affecting))
745 if (AddedModules.insert(Affecting).second)
752 std::unique_ptr<DependencyOutputOptions> Opts,
757 bool IsStdModuleP1689Format)
758 : ScanInstance(ScanInstance), Consumer(
C), Controller(Controller),
759 PrebuiltModuleVFSMap(
std::move(PrebuiltModuleVFSMap)),
760 Opts(
std::move(Opts)),
763 OptimizeArgs(OptimizeArgs), EagerLoadModules(EagerLoadModules),
764 IsStdModuleP1689Format(IsStdModuleP1689Format) {}
772bool ModuleDepCollector::isPrebuiltModule(
const Module *M) {
774 const auto &PrebuiltModuleFiles =
776 auto PrebuiltModuleFileIt = PrebuiltModuleFiles.find(Name);
777 if (PrebuiltModuleFileIt == PrebuiltModuleFiles.end())
779 assert(
"Prebuilt module came from the expected AST file" &&
786 if (llvm::sys::path::is_absolute(
Path) &&
787 !llvm::sys::path::is_style_windows(llvm::sys::path::Style::native))
789 Storage.assign(
Path.begin(),
Path.end());
791 llvm::sys::path::make_preferred(Storage);
792 return StringRef(Storage.data(), Storage.size());
795void ModuleDepCollector::addFileDep(StringRef
Path) {
796 if (IsStdModuleP1689Format) {
799 FileDeps.emplace_back(
Path);
805 FileDeps.emplace_back(
Path);
808void ModuleDepCollector::addFileDep(
ModuleDeps &MD, StringRef
Path) {
809 MD.FileDeps.emplace_back(
Path);
llvm::DenseSet< const void * > Visited
llvm::MachO::FileType FileType
llvm::MachO::Target Target
static void optimizeHeaderSearchOpts(HeaderSearchOptions &Opts, ASTReader &Reader, const serialization::ModuleFile &MF, const PrebuiltModuleVFSMapT &PrebuiltModuleVFSMap, ScanningOptimizations OptimizeArgs)
static std::vector< std::string > splitString(std::string S, char Separator)
static std::string getModuleContextHash(const ModuleDeps &MD, const CowCompilerInvocation &CI, bool EagerLoadModules, llvm::vfs::FileSystem &VFS)
static void optimizeDiagnosticOpts(DiagnosticOptions &Opts, bool IsSystemModule)
static StringRef makeAbsoluteAndPreferred(CompilerInstance &CI, StringRef Path, SmallVectorImpl< char > &Storage)
static CowCompilerInvocation makeCommonInvocationForModuleBuild(CompilerInvocation CI)
static void forEachSubmoduleSorted(const Module *M, llvm::function_ref< void(const Module *)> F)
static bool needsModules(FrontendInputFile FIF)
Defines the clang::Preprocessor interface.
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
Reads an AST files chain containing the contents of a translation unit.
static TemporarilyOwnedStringRef ResolveImportedPath(SmallString< 0 > &Buf, StringRef Path, ModuleFile &ModF)
Resolve Path in the context of module file M.
Represents a character-granular source range.
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
std::string CoverageNotesFile
The filename with path we use for coverage notes files.
std::string ProfileInstrumentUsePath
Name of the profile file to use as input for -fprofile-instr-use.
std::string SampleProfileFile
Name of the profile file to use with -fprofile-sample-use.
std::string CoverageDataFile
The filename with path we use for coverage data files.
std::string DebugCompilationDir
The string to embed in debug information as the current working directory.
std::string MainFileName
The user provided name for the "main file", if non-empty.
std::string CoverageCompilationDir
The string to embed in coverage mapping as the current working directory.
std::string ProfileRemappingFile
Name of the profile remapping file to apply to the profile data supplied by -fprofile-sample-use or -...
std::string DwarfDebugFlags
The string to embed in the debug information for the compile unit, if non-empty.
CompilerInstance - Helper class for managing a single instance of the Clang compiler.
FileManager & getFileManager() const
Return the current file manager to the caller.
IntrusiveRefCntPtr< ASTReader > getASTReader() const
Preprocessor & getPreprocessor() const
Return the current preprocessor.
HeaderSearchOptions & getHeaderSearchOpts()
CompilerInvocation & getInvocation()
PreprocessorOptions & getPreprocessorOpts()
llvm::vfs::FileSystem & getVirtualFileSystem() const
SourceManager & getSourceManager() const
Return the current source manager.
const FrontendOptions & getFrontendOpts() const
void generateCC1CommandLine(llvm::SmallVectorImpl< const char * > &Args, StringAllocator SA) const
Generate cc1-compatible command line arguments from this instance.
const DependencyOutputOptions & getDependencyOutputOpts() const
const DiagnosticOptions & getDiagnosticOpts() const
Helper class for holding the data necessary to invoke the compiler.
PreprocessorOptions & getPreprocessorOpts()
void clearImplicitModuleBuildOptions()
Disable implicit modules and canonicalize options that are only used by implicit modules.
LangOptions & getLangOpts()
Mutable getters.
DependencyOutputOptions & getDependencyOutputOpts()
void resetNonModularOptions()
Reset all of the options that are not considered when building a module.
FrontendOptions & getFrontendOpts()
std::string getModuleHash() const
Retrieve a module hash string that is suitable for uniquely identifying the conditions under which th...
CodeGenOptions & getCodeGenOpts()
HeaderSearchOptions & getHeaderSearchOpts()
DiagnosticOptions & getDiagnosticOpts()
Same as CompilerInvocation, but with copy-on-write optimization.
FrontendOptions & getMutFrontendOpts()
LangOptions & getMutLangOpts()
Mutable getters.
HeaderSearchOptions & getMutHeaderSearchOpts()
DiagnosticOptions & getMutDiagnosticOpts()
DependencyOutputOptions & getMutDependencyOutputOpts()
std::string OutputFile
The file to write dependency output to.
std::vector< std::string > Targets
A list of names to use as the targets in the dependency file; this list must contain at least one ent...
Options for controlling the compiler diagnostics engine.
std::vector< std::string > Remarks
The list of -R... options used to alter the diagnostic mappings, with the prefixes removed.
std::vector< std::string > Warnings
The list of -W... options used to alter the diagnostic mappings, with the prefixes removed.
std::vector< std::string > UndefPrefixes
The list of prefixes from -Wundef-prefix=... used to generate warnings for undefined macros.
std::vector< std::string > SystemHeaderWarningsModules
The list of -Wsystem-headers-in-module=... options used to override whether -Wsystem-headers is enabl...
std::string DiagnosticSerializationFile
The file to serialize diagnostics to (non-appending).
StringRef getName() const
The name of this FileEntry.
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
OptionalFileEntryRef getOptionalFileRef(StringRef Filename, bool OpenFile=false, bool CacheFailure=true)
Get a FileEntryRef if it exists, without doing anything on error.
bool makeAbsolutePath(SmallVectorImpl< char > &Path) const
Makes Path absolute taking into account FileSystemOptions and the working directory option.
InputKind DashX
The input kind, either specified via -x argument or deduced from the input file name.
std::vector< std::string > ModuleFiles
The list of additional prebuilt module files to load before processing the input.
unsigned IsSystemModule
When using -emit-module, treat the modulemap as a system module.
std::vector< std::string > LLVMArgs
A list of arguments to forward to LLVM's option processing; this should only be used for debugging an...
std::string OutputFile
The output file, if any.
SmallVector< FrontendInputFile, 0 > Inputs
The input files and their types.
frontend::ActionKind ProgramAction
The frontend action to perform.
enum clang::FrontendOptions::@199 ARCMTAction
std::vector< std::string > ModuleMapFiles
The list of module map files to load before processing the input.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
std::string ModuleName
The module currently being compiled as specified by -fmodule-name.
OptionalFileEntryRef getModuleMapFileForUniquing(const Module *M) const
std::error_code canonicalizeModuleMapPath(SmallVectorImpl< char > &Path)
Canonicalize Path in a manner suitable for a module map file.
Describes a module or submodule.
StringRef getTopLevelModuleName() const
Retrieve the name of the top-level module.
llvm::SmallSetVector< Module *, 2 > Imports
The set of modules imported by this module, and on which this module depends.
unsigned IsSystem
Whether this is a "system" module (which assumes that all headers in it are system headers).
std::string Name
The name of this module.
llvm::iterator_range< submodule_iterator > submodules()
llvm::SmallVector< LinkLibrary, 2 > LinkLibraries
The set of libraries or frameworks to link against when an entity from this module is used.
llvm::SmallSetVector< Module *, 2 > AffectingClangModules
The set of top-level modules that affected the compilation of this module, but were not imported.
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
Module * getTopLevelModule()
Retrieve the top-level module for this (sub)module, which may be this module.
OptionalFileEntryRef getASTFile() const
The serialized AST file for this module, if one was created.
bool UseExportAsModuleLinkName
Autolinking uses the framework name for linking purposes when this is false and the export_as name ot...
std::string ImplicitPCHInclude
The implicit PCH included at the start of the translation unit, or empty.
std::vector< std::pair< std::string, bool > > Macros
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
bool isInImportingCXXNamedModules() const
If we're importing a standard C++20 Named Modules.
void addPPCallbacks(std::unique_ptr< PPCallbacks > C)
Module * getCurrentModuleImplementation()
Retrieves the module whose implementation we're current compiling, if any.
HeaderSearch & getHeaderSearchInfo() const
const llvm::SmallSetVector< Module *, 2 > & getAffectingClangModules() const
Get the set of top-level clang modules that affected preprocessing, but were not imported.
Encodes a location in the source.
This class handles loading and caching of source files into memory.
OptionalFileEntryRef getFileEntryRefForID(FileID FID) const
Returns the FileEntryRef for the provided FileID.
FileID getMainFileID() const
Returns the FileID of the main source file.
Token - This structure provides full information about a lexed token.
Information about a module that has been loaded by the ASTReader.
std::string FileName
The file name of the module file.
llvm::SetVector< ModuleFile * > Imports
List of modules which this module directly imported.
llvm::BitVector SearchPathUsage
The bit vector denoting usage of each header search entry (true = used).
llvm::BitVector VFSUsage
The bit vector denoting usage of each VFS entry (true = used).
ModuleKind Kind
The type of this module.
std::string BaseDirectory
The base directory of the module.
CharacteristicKind
Indicates whether a file or directory holds normal user code, system code, or system code which is im...
@ GeneratePCH
Generate pre-compiled header.
@ GenerateModule
Generate pre-compiled module from a module map.
const unsigned VERSION_MINOR
AST file minor version number supported by this version of Clang.
const unsigned VERSION_MAJOR
AST file major version number supported by this version of Clang.
@ MK_ImplicitModule
File is an implicitly-loaded module.
The JSON file list parser is used to communicate input to InstallAPI.
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
void quoteMakeTarget(StringRef Target, SmallVectorImpl< char > &Res)
Quote target names for inclusion in GNU Make dependency files.
@ Asm
Assembly: we accept this only so that we can preprocess it.
@ Result
The result type of a method or function.
std::string getClangFullRepositoryVersion()
Retrieves the full repository version that is an amalgamation of the information in getClangRepositor...
int __ovld __cnfn any(char)
Returns 1 if the most significant bit in any component of x is set; otherwise returns 0.