22#include "clang/Config/config.h"
44#include "llvm/ADT/IntrusiveRefCntPtr.h"
45#include "llvm/ADT/STLExtras.h"
46#include "llvm/ADT/ScopeExit.h"
47#include "llvm/ADT/Statistic.h"
48#include "llvm/Config/llvm-config.h"
49#include "llvm/Support/AdvisoryLock.h"
50#include "llvm/Support/BuryPointer.h"
51#include "llvm/Support/CrashRecoveryContext.h"
52#include "llvm/Support/Errc.h"
53#include "llvm/Support/FileSystem.h"
54#include "llvm/Support/MemoryBuffer.h"
55#include "llvm/Support/Path.h"
56#include "llvm/Support/Signals.h"
57#include "llvm/Support/TimeProfiler.h"
58#include "llvm/Support/Timer.h"
59#include "llvm/Support/VirtualFileSystem.h"
60#include "llvm/Support/VirtualOutputBackends.h"
61#include "llvm/Support/VirtualOutputError.h"
62#include "llvm/Support/raw_ostream.h"
63#include "llvm/TargetParser/Host.h"
70CompilerInstance::CompilerInstance(
71 std::shared_ptr<CompilerInvocation> Invocation,
72 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
75 Invocation(
std::move(Invocation)),
77 ThePCHContainerOperations(
std::move(PCHContainerOps)) {
78 assert(this->Invocation &&
"Invocation must not be null");
82 assert(OutputFiles.empty() &&
"Still output files in flight?");
86 return (BuildGlobalModuleIndex ||
87 (TheASTReader && TheASTReader->isGlobalIndexUnavailable() &&
89 !DisableGeneratingGlobalModuleIndex;
94 Diagnostics = std::move(
Value);
98 OwnedVerboseOutputStream.reset();
99 VerboseOutputStream = &
Value;
103 OwnedVerboseOutputStream.swap(
Value);
104 VerboseOutputStream = OwnedVerboseOutputStream.get();
122 auto &TO = AuxTargetOpts = std::make_unique<TargetOptions>();
163 assert(
Value ==
nullptr ||
165 FileMgr = std::move(
Value);
170 SourceMgr = std::move(
Value);
174 PP = std::move(
Value);
179 Context = std::move(
Value);
181 if (Context && Consumer)
190 Consumer = std::move(
Value);
192 if (Context && Consumer)
197 CompletionConsumer.reset(
Value);
201 return std::move(TheSema);
208 assert(ModCache.get() == &Reader->getModuleManager().getModuleCache() &&
209 "Expected ASTReader to use the same PCM cache");
210 TheASTReader = std::move(Reader);
213std::shared_ptr<ModuleDependencyCollector>
215 return ModuleDepCollector;
219 std::shared_ptr<ModuleDependencyCollector> Collector) {
220 ModuleDepCollector = std::move(Collector);
224 std::shared_ptr<ModuleDependencyCollector> MDC) {
227 for (
auto &Name : HeaderMapFileNames)
232 std::shared_ptr<ModuleDependencyCollector> MDC) {
239 auto PCHDir =
FileMgr.getOptionalDirectoryRef(PCHInclude);
241 MDC->addFile(PCHInclude);
247 llvm::sys::path::native(PCHDir->getName(), DirNative);
248 llvm::vfs::FileSystem &FS =
FileMgr.getVirtualFileSystem();
250 for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
251 Dir != DirEnd && !EC; Dir.increment(EC)) {
260 MDC->addFile(Dir->path());
265 std::shared_ptr<ModuleDependencyCollector> MDC) {
269 if (
auto *RedirectingVFS = dyn_cast<llvm::vfs::RedirectingFileSystem>(&VFS))
270 llvm::vfs::collectVFSEntries(*RedirectingVFS, VFSEntries);
273 for (
auto &E : VFSEntries)
274 MDC->addFile(E.VPath, E.RPath);
288 llvm::makeIntrusiveRefCnt<llvm::vfs::TracingFileSystem>(std::move(VFS));
296 std::unique_ptr<raw_ostream> StreamOwner;
297 raw_ostream *OS = &llvm::errs();
300 auto FileOS = std::make_unique<llvm::raw_fd_ostream>(
302 llvm::sys::fs::OF_Append | llvm::sys::fs::OF_TextWithCRLF);
304 Diags.
Report(diag::warn_fe_cc_log_diagnostics_failure)
307 FileOS->SetUnbuffered();
309 StreamOwner = std::move(FileOS);
314 auto Logger = std::make_unique<LogDiagnosticPrinter>(*OS, DiagOpts,
315 std::move(StreamOwner));
329 StringRef OutputFile) {
330 auto SerializedConsumer =
335 Diags.
takeClient(), std::move(SerializedConsumer)));
338 Diags.
getClient(), std::move(SerializedConsumer)));
343 bool ShouldOwnClient) {
352 auto Diags = llvm::makeIntrusiveRefCnt<DiagnosticsEngine>(
358 Diags->setClient(Client, ShouldOwnClient);
365 if (Opts.VerifyDiagnostics)
384 assert(VFS &&
"CompilerInstance needs a VFS for creating FileManager");
391 assert(Diagnostics &&
"DiagnosticsEngine needed for creating SourceManager");
392 assert(FileMgr &&
"FileManager needed for creating SourceManager");
393 SourceMgr = llvm::makeIntrusiveRefCnt<SourceManager>(
getDiagnostics(),
407 FileMgr.getVirtualFileRef(RB.first, RB.second->getBufferSize(), 0);
414 SourceMgr.overrideFileContents(FromFile, RB.second->getMemBufferRef());
416 SourceMgr.overrideFileContents(
417 FromFile, std::unique_ptr<llvm::MemoryBuffer>(RB.second));
425 Diags.
Report(diag::err_fe_remap_missing_to_file) << RF.first << RF.second;
435 SourceMgr.overrideFileContents(FromFile, *ToFile);
438 SourceMgr.setOverridenFilesKeepOriginalName(
448 TheASTReader.reset();
454 PP = std::make_shared<Preprocessor>(Invocation->getPreprocessorOpts(),
463 PP->createPreprocessingRecord();
467 PP->getFileManager(), PPOpts);
476 const llvm::Triple *HeaderSearchTriple = &PP->getTargetInfo().getTriple();
477 if (PP->getTargetInfo().getTriple().getOS() == llvm::Triple::CUDA &&
478 PP->getAuxTargetInfo())
479 HeaderSearchTriple = &PP->getAuxTargetInfo()->getTriple();
482 PP->getLangOpts(), *HeaderSearchTriple);
486 if (PP->getLangOpts().Modules && PP->getLangOpts().ImplicitModules) {
488 PP->getHeaderSearchInfo().setModuleHash(ModuleHash);
489 PP->getHeaderSearchInfo().setModuleCachePath(
504 ModuleDepCollector = std::make_shared<ModuleDependencyCollector>(
510 if (ModuleDepCollector) {
521 for (
auto &Listener : DependencyCollectors)
522 Listener->attachToPreprocessor(*PP);
529 if (OutputPath ==
"-")
542 if (GetDependencyDirectives)
543 PP->setDependencyDirectivesGetter(*GetDependencyDirectives);
547 assert(FileMgr &&
"Specific module cache path requires a FileManager");
552 SpecificModuleCache);
554 llvm::sys::path::append(SpecificModuleCache, ModuleHash);
555 return std::string(SpecificModuleCache);
562 auto Context = llvm::makeIntrusiveRefCnt<ASTContext>(
563 getLangOpts(), PP.getSourceManager(), PP.getIdentifierTable(),
564 PP.getSelectorTable(), PP.getBuiltinInfo(), PP.TUKind);
581 void ReadModuleName(StringRef ModuleName)
override {
584 LoadedModules.push_back(ModuleName.str());
589 for (
const std::string &LoadedModule : LoadedModules)
592 LoadedModules.clear();
595 void markAllUnavailable() {
596 for (
const std::string &LoadedModule : LoadedModules) {
599 M->HasIncompatibleModuleFile =
true;
603 SmallVector<Module *, 2> Stack;
605 while (!Stack.empty()) {
606 Module *Current = Stack.pop_back_val();
610 llvm::append_range(Stack, SubmodulesRange);
614 LoadedModules.clear();
621 bool AllowPCHWithCompilerErrors,
void *DeserializationListener,
622 bool OwnDeserializationListener) {
629 DeserializationListener, OwnDeserializationListener,
Preamble,
634 StringRef Path, StringRef Sysroot,
639 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
640 ArrayRef<std::shared_ptr<DependencyCollector>> DependencyCollectors,
641 void *DeserializationListener,
bool OwnDeserializationListener,
642 bool Preamble,
bool UseGlobalModuleIndex) {
644 PP.getHeaderSearchInfo().getHeaderSearchOpts();
646 auto Reader = llvm::makeIntrusiveRefCnt<ASTReader>(
647 PP, ModCache, &Context, PCHContainerRdr, CodeGenOpts, Extensions,
648 Sysroot.empty() ?
"" : Sysroot.data(), DisableValidation,
649 AllowPCHWithCompilerErrors,
false,
656 Context.setExternalSource(Reader);
658 Reader->setDeserializationListener(
660 OwnDeserializationListener);
662 for (
auto &Listener : DependencyCollectors)
663 Listener->attachToASTReader(*Reader);
665 auto Listener = std::make_unique<ReadModuleNames>(PP);
666 auto &ListenerRef = *Listener;
668 std::move(Listener));
670 switch (Reader->ReadAST(Path,
678 PP.setPredefines(Reader->getSuggestedPredefines());
679 ListenerRef.registerAll();
695 ListenerRef.markAllUnavailable();
696 Context.setExternalSource(
nullptr);
722 if (!CompletionConsumer) {
735 timerGroup.reset(
new llvm::TimerGroup(
"clang",
"Clang time report"));
736 FrontendTimer.reset(
new llvm::Timer(
"frontend",
"Front end", *timerGroup));
756 TUKind, CompletionConsumer));
762 if (ExternalSemaSrc) {
763 TheSema->addExternalSource(ExternalSemaSrc);
764 ExternalSemaSrc->InitializeSema(*TheSema);
770 (void)TheSema->APINotes.loadCurrentModuleAPINotes(
782 for (
auto &O : OutputFiles)
783 llvm::handleAllErrors(
785 [&](
const llvm::vfs::TempFileOutputError &E) {
786 getDiagnostics().Report(diag::err_unable_to_rename_temp)
787 << E.getTempPath() << E.getOutputPath()
788 << E.convertToErrorCode().message();
790 [&](
const llvm::vfs::OutputError &E) {
791 getDiagnostics().Report(diag::err_fe_unable_to_open_output)
792 << E.getOutputPath() << E.convertToErrorCode().message();
794 [&](
const llvm::ErrorInfoBase &EIB) {
795 getDiagnostics().Report(diag::err_fe_unable_to_open_output)
796 << O.getPath() << EIB.message();
800 if (DeleteBuiltModules) {
801 for (
auto &
Module : BuiltModules)
802 llvm::sys::fs::remove(
Module.second);
803 BuiltModules.clear();
808 bool Binary, StringRef InFile, StringRef Extension,
bool RemoveFileOnSignal,
809 bool CreateMissingDirectories,
bool ForceUseTemporary) {
811 std::optional<SmallString<128>> PathStorage;
812 if (OutputPath.empty()) {
813 if (InFile ==
"-" || Extension.empty()) {
816 PathStorage.emplace(InFile);
817 llvm::sys::path::replace_extension(*PathStorage, Extension);
818 OutputPath = *PathStorage;
824 CreateMissingDirectories);
828 return std::make_unique<llvm::raw_null_ostream>();
835 assert(!OutputMgr &&
"Already has an output manager");
836 OutputMgr = std::move(NewOutputs);
840 assert(!OutputMgr &&
"Already has an output manager");
841 OutputMgr = llvm::makeIntrusiveRefCnt<llvm::vfs::OnDiskOutputBackend>();
855std::unique_ptr<raw_pwrite_stream>
857 bool RemoveFileOnSignal,
bool UseTemporary,
858 bool CreateMissingDirectories) {
860 createOutputFileImpl(OutputPath,
Binary, RemoveFileOnSignal, UseTemporary,
861 CreateMissingDirectories);
863 return std::move(*OS);
865 << OutputPath << errorToErrorCode(OS.takeError()).message();
870CompilerInstance::createOutputFileImpl(StringRef OutputPath,
bool Binary,
871 bool RemoveFileOnSignal,
873 bool CreateMissingDirectories) {
874 assert((!CreateMissingDirectories || UseTemporary) &&
875 "CreateMissingDirectories is only allowed when using temporary files");
879 std::optional<SmallString<128>> AbsPath;
880 if (OutputPath !=
"-" && !llvm::sys::path::is_absolute(OutputPath)) {
882 "File Manager is required to fix up relative path.\n");
884 AbsPath.emplace(OutputPath);
886 OutputPath = *AbsPath;
894 .setDiscardOnSignal(RemoveFileOnSignal)
895 .setAtomicWrite(UseTemporary)
896 .setImplyCreateDirectories(UseTemporary && CreateMissingDirectories));
898 return O.takeError();
900 O->discardOnDestroy([](llvm::Error E) { consumeError(std::move(E)); });
901 OutputFiles.push_back(std::move(*O));
902 return OutputFiles.back().createProxy();
924 SourceMgr.setMainFileID(SourceMgr.createFileID(Input.
getBuffer(), Kind));
925 assert(SourceMgr.getMainFileID().isValid() &&
926 "Couldn't establish MainFileID!");
930 StringRef InputFile = Input.
getFile();
933 auto FileOrErr = InputFile ==
"-"
935 : FileMgr.getFileRef(InputFile,
true);
937 auto EC = llvm::errorToErrorCode(FileOrErr.takeError());
938 if (InputFile !=
"-")
939 Diags.
Report(diag::err_fe_error_reading) << InputFile << EC.message();
941 Diags.
Report(diag::err_fe_error_reading_stdin) << EC.message();
945 SourceMgr.setMainFileID(
948 assert(SourceMgr.getMainFileID().isValid() &&
949 "Couldn't establish MainFileID!");
956 assert(
hasDiagnostics() &&
"Diagnostics engine is not initialized!");
958 assert(!
getFrontendOpts().ShowVersion &&
"Client must handle '-version'!");
965 auto FinishDiagnosticClient = llvm::make_scope_exit([&]() {
984 OS <<
"clang -cc1 version " CLANG_VERSION_STRING <<
" based upon LLVM "
985 << LLVM_VERSION_STRING <<
" default target "
986 << llvm::sys::getDefaultTargetTriple() <<
"\n";
989 llvm::EnableStatistics(
false);
1003 if (llvm::Error Err = Act.
Execute()) {
1004 consumeError(std::move(Err));
1017 llvm::PrintStatistics(OS);
1020 if (!StatsFile.empty()) {
1021 llvm::sys::fs::OpenFlags FileFlags = llvm::sys::fs::OF_TextWithCRLF;
1023 FileFlags |= llvm::sys::fs::OF_Append;
1026 std::make_unique<llvm::raw_fd_ostream>(StatsFile, EC, FileFlags);
1029 << StatsFile << EC.message();
1031 llvm::PrintStatisticsJSON(*StatS);
1050 OS << NumWarnings <<
" warning" << (NumWarnings == 1 ?
"" :
"s");
1051 if (NumWarnings && NumErrors)
1054 OS << NumErrors <<
" error" << (NumErrors == 1 ?
"" :
"s");
1055 if (NumWarnings || NumErrors) {
1059 OS <<
" when compiling for host";
1061 OS <<
" when compiling for "
1074 if (llvm::sys::DynamicLibrary::LoadLibraryPermanently(Path.c_str(), &
Error))
1080 for (
const FrontendPluginRegistry::entry &Plugin :
1081 FrontendPluginRegistry::entries()) {
1082 std::unique_ptr<PluginASTAction> P(Plugin.instantiate());
1094 if (LangOpts.OpenCL)
1103std::unique_ptr<CompilerInstance> CompilerInstance::cloneForModuleCompileImpl(
1105 StringRef OriginalModuleMapFile, StringRef ModuleFileName,
1106 std::optional<ThreadSafeCloneConfig> ThreadSafeConfig) {
1108 auto Invocation = std::make_shared<CompilerInvocation>(
getInvocation());
1110 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
1114 Invocation->resetNonModularOptions();
1118 HeaderSearchOptions &HSOpts = Invocation->getHeaderSearchOpts();
1119 llvm::erase_if(PPOpts.
Macros,
1120 [&HSOpts](
const std::pair<std::string, bool> &def) {
1121 StringRef MacroDef = def.first;
1122 return HSOpts.ModulesIgnoreMacros.contains(
1123 llvm::CachedHashString(MacroDef.split(
'=').first));
1127 Invocation->getLangOpts().ModuleName =
1131 Invocation->getLangOpts().CurrentModule = std::string(ModuleName);
1136 FrontendOptions &FrontendOpts = Invocation->getFrontendOpts();
1137 FrontendOpts.
OutputFile = ModuleFileName.str();
1144 FrontendOpts.
Inputs = {std::move(Input)};
1149 DiagnosticOptions &DiagOpts = Invocation->getDiagnosticOpts();
1151 DiagOpts.VerifyDiagnostics = 0;
1153 "Module hash mismatch!");
1159 auto InstancePtr = std::make_unique<CompilerInstance>(
1161 auto &Instance = *InstancePtr;
1163 auto &
Inv = Instance.getInvocation();
1165 if (ThreadSafeConfig) {
1166 Instance.setVirtualFileSystem(ThreadSafeConfig->getVFS());
1167 Instance.createFileManager();
1173 Instance.createFileManager();
1176 if (ThreadSafeConfig) {
1177 Instance.createDiagnostics(&ThreadSafeConfig->getDiagConsumer(),
1180 Instance.createDiagnostics(
1185 Instance.getDiagnostics().setSuppressSystemWarnings(
false);
1187 Instance.createSourceManager();
1188 SourceManager &SourceMgr = Instance.getSourceManager();
1190 if (ThreadSafeConfig) {
1196 SourceMgr.pushModuleBuildStack(
1201 Instance.FailedModules = FailedModules;
1203 if (GetDependencyDirectives)
1204 Instance.GetDependencyDirectives =
1205 GetDependencyDirectives->cloneFor(Instance.getFileManager());
1207 if (ThreadSafeConfig) {
1208 Instance.setModuleDepCollector(ThreadSafeConfig->getModuleDepCollector());
1215 Inv.getDependencyOutputOpts() = DependencyOutputOptions();
1221 StringRef ModuleName,
1222 StringRef ModuleFileName,
1223 CompilerInstance &Instance) {
1224 llvm::TimeTraceScope TimeScope(
"Module Compile", ModuleName);
1228 if (
getModuleCache().getInMemoryModuleCache().isPCMFinal(ModuleFileName)) {
1235 << ModuleName << ModuleFileName;
1239 bool Crashed = !llvm::CrashRecoveryContext().RunSafelyOnNewStack(
1254 FailedModules = std::move(Instance.FailedModules);
1259 Instance.setSema(
nullptr);
1260 Instance.setASTConsumer(
nullptr);
1263 Instance.clearOutputFiles(
true);
1274 return !Instance.getDiagnostics().hasErrorOccurred() ||
1275 Instance.getFrontendOpts().AllowPCMWithCompilerErrors;
1280 StringRef Filename = llvm::sys::path::filename(
File.getName());
1282 if (Filename ==
"module_private.map")
1283 llvm::sys::path::append(PublicFilename,
"module.map");
1284 else if (Filename ==
"module.private.modulemap")
1285 llvm::sys::path::append(PublicFilename,
"module.modulemap");
1287 return std::nullopt;
1288 return FileMgr.getOptionalFileRef(PublicFilename);
1293 std::optional<ThreadSafeCloneConfig> ThreadSafeConfig) {
1309 while (Loc.
isValid() && isModuleMap(SourceMgr.getFileCharacteristic(Loc))) {
1310 ModuleMapFID = SourceMgr.getFileID(Loc);
1311 Loc = SourceMgr.getIncludeLoc(ModuleMapFID);
1315 SourceMgr.getFileEntryRefForID(ModuleMapFID);
1316 assert(ModuleMapFile &&
"Top-level module map with no FileID");
1323 ModuleMapFile = PublicMMFile;
1335 return cloneForModuleCompileImpl(
1336 ImportLoc, ModuleName,
1339 std::move(ThreadSafeConfig));
1347 llvm::sys::path::append(FakeModuleMapFile,
"__inferred_module.map");
1349 std::string InferredModuleMapContent;
1350 llvm::raw_string_ostream OS(InferredModuleMapContent);
1353 auto Instance = cloneForModuleCompileImpl(
1354 ImportLoc, ModuleName,
1357 std::move(ThreadSafeConfig));
1359 std::unique_ptr<llvm::MemoryBuffer> ModuleMapBuffer =
1360 llvm::MemoryBuffer::getMemBufferCopy(InferredModuleMapContent);
1361 FileEntryRef ModuleMapFile = Instance->getFileManager().getVirtualFileRef(
1362 FakeModuleMapFile, InferredModuleMapContent.size(), 0);
1363 Instance->getSourceManager().overrideFileContents(ModuleMapFile,
1364 std::move(ModuleMapBuffer));
1374 bool *OutOfDate,
bool *Missing) {
1385 ModuleLoadCapabilities);
1403 Diags.
Report(ModuleNameLoc, diag::err_module_not_built)
1415 StringRef ModuleFileName) {
1418 ModuleNameLoc,
Module, ModuleFileName);
1422 ModuleFileName, *Instance)) {
1424 diag::err_module_not_built)
1456 Diags.
Report(ModuleNameLoc, diag::remark_module_lock)
1465 if (llvm::Error Err = Lock->tryLock().moveInto(Owned)) {
1469 Diags.
Report(ModuleNameLoc, diag::remark_module_lock_failure)
1472 ModuleNameLoc,
Module, ModuleFileName);
1477 ModuleNameLoc,
Module, ModuleFileName);
1482 switch (Lock->waitForUnlockFor(std::chrono::seconds(90))) {
1483 case llvm::WaitForUnlockResult::Success:
1485 case llvm::WaitForUnlockResult::OwnerDied:
1487 case llvm::WaitForUnlockResult::Timeout:
1491 Diags.
Report(ModuleNameLoc, diag::remark_module_lock_timeout)
1494 Lock->unsafeMaybeUnlock();
1499 bool OutOfDate =
false;
1500 bool Missing =
false;
1502 Module, ModuleFileName, &OutOfDate, &Missing))
1504 if (!OutOfDate && !Missing)
1548 for (
auto *MD = LatestLocalMD; MD; MD = MD->getPrevious()) {
1550 FileID FID = SourceMgr.getFileID(MD->getLocation());
1553 if (
auto *DMD = dyn_cast<DefMacroDirective>(MD))
1554 CmdLineDefinition = DMD->getMacroInfo();
1559 if (CurrentDefinition == CmdLineDefinition) {
1561 }
else if (!CurrentDefinition) {
1564 PP.
Diag(ImportLoc, diag::warn_module_config_macro_undef)
1566 auto LatestDef = LatestLocalMD->getDefinition();
1567 assert(LatestDef.isUndefined() &&
1568 "predefined macro went away with no #undef?");
1569 PP.
Diag(LatestDef.getUndefLocation(), diag::note_module_def_undef_here)
1572 }
else if (!CmdLineDefinition) {
1575 PP.
Diag(ImportLoc, diag::warn_module_config_macro_undef)
1577 PP.
Diag(CurrentDefinition->getDefinitionLoc(),
1578 diag::note_module_def_undef_here)
1580 }
else if (!CurrentDefinition->isIdenticalTo(*CmdLineDefinition, PP,
1583 PP.
Diag(ImportLoc, diag::warn_module_config_macro_undef)
1585 PP.
Diag(CurrentDefinition->getDefinitionLoc(),
1586 diag::note_module_def_undef_here)
1594 for (
const StringRef ConMacro : TopModule->
ConfigMacros) {
1609 !
getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty())
1615 std::string Sysroot = HSOpts.
Sysroot;
1618 std::unique_ptr<llvm::Timer> ReadTimer;
1621 ReadTimer = std::make_unique<llvm::Timer>(
"reading_modules",
1622 "Reading modules", *timerGroup);
1623 TheASTReader = llvm::makeIntrusiveRefCnt<ASTReader>(
1627 Sysroot.empty() ?
"" : Sysroot.c_str(),
1636 TheASTReader->setDeserializationListener(
1643 TheASTReader->InitializeSema(
getSema());
1647 for (
auto &Listener : DependencyCollectors)
1648 Listener->attachToASTReader(*TheASTReader);
1657 llvm::TimeRegion TimeLoading(timerGroup ? &Timer :
nullptr);
1665 bool ConfigMismatchIsRecoverable =
1670 auto Listener = std::make_unique<ReadModuleNames>(*PP);
1671 auto &ListenerRef = *Listener;
1673 std::move(Listener));
1676 switch (TheASTReader->ReadAST(
1679 &LoadedModuleFile)) {
1683 ListenerRef.registerAll();
1692 ListenerRef.markAllUnavailable();
1704 MS_PrebuiltModulePath,
1705 MS_ModuleBuildPragma
1712 Module *M, StringRef ModuleName, std::string &ModuleFilename,
1713 const std::map<std::string, std::string, std::less<>> &BuiltModules,
1715 assert(ModuleFilename.empty() &&
"Already has a module source?");
1719 auto BuiltModuleIt = BuiltModules.find(ModuleName);
1720 if (BuiltModuleIt != BuiltModules.end()) {
1721 ModuleFilename = BuiltModuleIt->second;
1722 return MS_ModuleBuildPragma;
1732 if (!ModuleFilename.empty())
1733 return MS_PrebuiltModulePath;
1739 return MS_ModuleCache;
1742 return MS_ModuleNotFound;
1751 HS.
lookupModule(ModuleName, ImportLoc,
true, !IsInclusionDirective);
1761 std::string ModuleFilename;
1762 ModuleSource Source =
1764 if (Source == MS_ModuleNotFound) {
1767 << ModuleName << SourceRange(ImportLoc, ModuleNameLoc);
1770 if (ModuleFilename.empty()) {
1789 Timer.init(
"loading." + ModuleFilename,
"Loading " + ModuleFilename,
1791 llvm::TimeRegion TimeLoading(timerGroup ? &Timer :
nullptr);
1792 llvm::TimeTraceScope TimeScope(
"Module Load", ModuleName);
1796 unsigned ARRFlags = Source == MS_ModuleCache
1799 : Source == MS_PrebuiltModulePath
1803 Source == MS_PrebuiltModulePath
1805 : Source == MS_ModuleBuildPragma
1808 ImportLoc, ARRFlags)) {
1812 assert(Source != MS_ModuleCache &&
1813 "missing module, but file loaded from cache");
1817 M = HS.
lookupModule(ModuleName, ImportLoc,
true, !IsInclusionDirective);
1821 if (
auto ModuleFile = FileMgr->getOptionalFileRef(ModuleFilename))
1827 return ModuleLoadResult();
1836 if (Source == MS_PrebuiltModulePath)
1840 diag::warn_module_config_mismatch)
1849 return ModuleLoadResult();
1853 return ModuleLoadResult();
1857 if (Source != MS_ModuleCache) {
1861 return ModuleLoadResult();
1865 assert(M &&
"missing module, but trying to compile for cache");
1869 ModuleBuildStack::iterator Pos = ModPath.begin(), PosEnd = ModPath.end();
1870 for (; Pos != PosEnd; ++Pos) {
1871 if (Pos->first == ModuleName)
1875 if (Pos != PosEnd) {
1876 SmallString<256> CyclePath;
1877 for (; Pos != PosEnd; ++Pos) {
1878 CyclePath += Pos->first;
1879 CyclePath +=
" -> ";
1881 CyclePath += ModuleName;
1884 << ModuleName << CyclePath;
1889 if (FailedModules.contains(ModuleName)) {
1891 << ModuleName << SourceRange(ImportLoc, ModuleNameLoc);
1899 "undiagnosed error in compileModuleAndReadAST");
1900 FailedModules.insert(ModuleName);
1912 bool IsInclusionDirective) {
1914 StringRef ModuleName = Path[0].getIdentifierInfo()->getName();
1920 if (ImportLoc.
isValid() && LastModuleImportLoc == ImportLoc) {
1922 if (LastModuleImportResult && ModuleName !=
getLangOpts().CurrentModule)
1923 TheASTReader->makeModuleVisible(LastModuleImportResult,
Visibility,
1925 return LastModuleImportResult;
1939 }
else if (ModuleName ==
getLangOpts().CurrentModule) {
1941 Module = PP->getHeaderSearchInfo().lookupModule(
1942 ModuleName, ImportLoc,
true,
1943 !IsInclusionDirective);
1954 ModuleName, ImportLoc, ModuleNameLoc, IsInclusionDirective);
1958 DisableGeneratingGlobalModuleIndex =
true;
1970 bool MapPrivateSubModToTopLevel =
false;
1971 for (
unsigned I = 1, N = Path.size(); I != N; ++I) {
1972 StringRef Name = Path[I].getIdentifierInfo()->getName();
1981 PrivateModule.append(
"_Private");
1984 auto &II = PP->getIdentifierTable().get(
1985 PrivateModule, PP->getIdentifierInfo(
Module->
Name)->getTokenID());
1986 PrivPath.emplace_back(Path[0].getLoc(), &II);
1990 if (PP->getHeaderSearchInfo().lookupModule(PrivateModule, ImportLoc,
true,
1991 !IsInclusionDirective) ||
1993 PP->getHeaderSearchInfo()) != MS_ModuleNotFound)
1996 MapPrivateSubModToTopLevel =
true;
1997 PP->markClangModuleAsAffecting(
Module);
1999 diag::warn_no_priv_submodule_use_toplevel, ImportLoc)) {
2001 diag::warn_no_priv_submodule_use_toplevel)
2004 <<
SourceRange(Path[0].getLoc(), Path[I].getLoc())
2008 diag::note_private_top_level_defined);
2016 unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)();
2020 Name.edit_distance(SubModule->Name,
2021 true, BestEditDistance);
2022 if (ED <= BestEditDistance) {
2023 if (ED < BestEditDistance) {
2025 BestEditDistance = ED;
2028 Best.push_back(SubModule->Name);
2033 if (Best.size() == 1) {
2035 diag::err_no_submodule_suggest)
2037 << Best[0] <<
SourceRange(Path[0].getLoc(), Path[I - 1].getLoc())
2050 <<
SourceRange(Path[0].getLoc(), Path[I - 1].getLoc());
2069 <<
SourceRange(Path.front().getLoc(), Path.back().getLoc());
2078 <<
SourceRange(Path.front().getLoc(), Path.back().getLoc());
2079 LastModuleImportLoc = ImportLoc;
2093 LastModuleImportLoc = ImportLoc;
2095 return LastModuleImportResult;
2099 StringRef ModuleName,
2103 for (
auto &
C : CleanModuleName)
2111 if (std::error_code EC = llvm::sys::fs::createTemporaryFile(
2112 CleanModuleName,
"pcm", ModuleFileName)) {
2114 << ModuleFileName << EC.message();
2117 std::string ModuleMapFileName = (CleanModuleName +
".map").str();
2124 std::string NullTerminatedSource(Source.str());
2126 auto Other = cloneForModuleCompileImpl(ImportLoc, ModuleName, Input,
2127 StringRef(), ModuleFileName);
2132 ModuleMapFileName, NullTerminatedSource.size(), 0);
2133 Other->getSourceManager().overrideFileContents(
2134 ModuleMapFile, llvm::MemoryBuffer::getMemBuffer(NullTerminatedSource));
2136 Other->BuiltModules = std::move(BuiltModules);
2137 Other->DeleteBuiltModules =
false;
2142 BuiltModules = std::move(
Other->BuiltModules);
2145 BuiltModules[std::string(ModuleName)] = std::string(ModuleFileName);
2146 llvm::sys::RemoveFileOnSignal(ModuleFileName);
2158 TheASTReader->makeModuleVisible(Mod,
Visibility, ImportLoc);
2163 if (
getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty())
2172 TheASTReader->loadGlobalIndex();
2177 llvm::sys::fs::create_directories(
2186 consumeError(std::move(Err));
2189 TheASTReader->resetForReload();
2190 TheASTReader->loadGlobalIndex();
2191 GlobalIndex = TheASTReader->getGlobalIndex();
2195 if (!HaveFullGlobalModuleIndex && GlobalIndex && !
buildingModule()) {
2197 bool RecreateIndex =
false;
2200 Module *TheModule = I->second;
2204 Path.emplace_back(TriggerLoc,
2206 std::reverse(Path.begin(), Path.end());
2209 RecreateIndex =
true;
2212 if (RecreateIndex) {
2217 consumeError(std::move(Err));
2220 TheASTReader->resetForReload();
2221 TheASTReader->loadGlobalIndex();
2222 GlobalIndex = TheASTReader->getGlobalIndex();
2224 HaveFullGlobalModuleIndex =
true;
2258 ExternalSemaSrc = std::move(ESS);
Defines the clang::ASTContext interface.
Defines the Diagnostic-related interfaces.
static void collectVFSEntries(CompilerInstance &CI, std::shared_ptr< ModuleDependencyCollector > MDC)
static bool EnableCodeCompletion(Preprocessor &PP, StringRef Filename, unsigned Line, unsigned Column)
static bool compileModuleAndReadASTImpl(CompilerInstance &ImportingInstance, SourceLocation ImportLoc, SourceLocation ModuleNameLoc, Module *Module, StringRef ModuleFileName)
Compile a module in a separate compiler instance and read the AST, returning true if the module compi...
static void SetupSerializedDiagnostics(DiagnosticOptions &DiagOpts, DiagnosticsEngine &Diags, StringRef OutputFile)
static bool compileModuleAndReadASTBehindLock(CompilerInstance &ImportingInstance, SourceLocation ImportLoc, SourceLocation ModuleNameLoc, Module *Module, StringRef ModuleFileName)
Compile a module in a separate compiler instance and read the AST, returning true if the module compi...
static Language getLanguageFromOptions(const LangOptions &LangOpts)
Determine the appropriate source input kind based on language options.
static void checkConfigMacro(Preprocessor &PP, StringRef ConfigMacro, Module *Mod, SourceLocation ImportLoc)
Diagnose differences between the current definition of the given configuration macro and the definiti...
static void collectHeaderMaps(const HeaderSearch &HS, std::shared_ptr< ModuleDependencyCollector > MDC)
static ModuleSource selectModuleSource(Module *M, StringRef ModuleName, std::string &ModuleFilename, const std::map< std::string, std::string, std::less<> > &BuiltModules, HeaderSearch &HS)
Select a source for loading the named module and compute the filename to load it from.
static bool readASTAfterCompileModule(CompilerInstance &ImportingInstance, SourceLocation ImportLoc, SourceLocation ModuleNameLoc, Module *Module, StringRef ModuleFileName, bool *OutOfDate, bool *Missing)
Read the AST right after compiling the module.
static void InitializeFileRemapping(DiagnosticsEngine &Diags, SourceManager &SourceMgr, FileManager &FileMgr, const PreprocessorOptions &InitOpts)
static void collectIncludePCH(CompilerInstance &CI, std::shared_ptr< ModuleDependencyCollector > MDC)
static OptionalFileEntryRef getPublicModuleMap(FileEntryRef File, FileManager &FileMgr)
static void checkConfigMacros(Preprocessor &PP, Module *M, SourceLocation ImportLoc)
static bool compileModuleAndReadAST(CompilerInstance &ImportingInstance, SourceLocation ImportLoc, SourceLocation ModuleNameLoc, Module *Module, StringRef ModuleFileName)
Compile a module in a separate compiler instance and read the AST, returning true if the module compi...
static void SetUpDiagnosticLog(DiagnosticOptions &DiagOpts, const CodeGenOptions *CodeGenOpts, DiagnosticsEngine &Diags)
Defines the clang::FileManager interface and associated types.
Defines the clang::FrontendAction interface and various convenience abstract classes (clang::ASTFront...
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.
Defines the SourceManager interface.
Defines utilities for dealing with stack allocation and stack space.
Defines version macros and version-related utility functions for Clang.
virtual void Initialize(ASTContext &Context)
Initialize - This is called to initialize the consumer, providing the ASTContext.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
void setASTMutationListener(ASTMutationListener *Listener)
Attach an AST mutation listener to the AST context.
void setExternalSource(IntrusiveRefCntPtr< ExternalASTSource > Source)
Attach an external AST source to the AST context.
void ExecuteAction() override
Implement the ExecuteAction interface by running Sema on the already-initialized AST consumer.
Abstract interface for callback invocations by the ASTReader.
RAII object to temporarily add an AST callback listener.
@ ARR_Missing
The client can handle an AST file that cannot load because it is missing.
@ ARR_None
The client can't handle any AST loading failures.
@ ARR_ConfigurationMismatch
The client can handle an AST file that cannot load because it's compiled configuration doesn't match ...
@ ARR_OutOfDate
The client can handle an AST file that cannot load because it is out-of-date relative to its input fi...
@ ARR_TreatModuleWithErrorsAsOutOfDate
If a module file is marked with errors treat it as out-of-date so the caller can rebuild it.
static bool readASTFileControlBlock(StringRef Filename, FileManager &FileMgr, const ModuleCache &ModCache, const PCHContainerReader &PCHContainerRdr, bool FindModuleFileExtensions, ASTReaderListener &Listener, bool ValidateDiagnosticOptions, unsigned ClientLoadCapabilities=ARR_ConfigurationMismatch|ARR_OutOfDate)
Read the control block for the named AST file.
ASTReadResult
The result of reading the control block of an AST file, which can fail for various reasons.
@ Success
The control block was read successfully.
@ ConfigurationMismatch
The AST file was written with a different language/target configuration.
@ OutOfDate
The AST file is out-of-date relative to its input files, and needs to be regenerated.
@ Failure
The AST file itself appears corrupted.
@ VersionMismatch
The AST file was written by a different version of Clang.
@ HadErrors
The AST file has errors.
@ Missing
The AST file was missing.
ChainedDiagnosticConsumer - Chain two diagnostic clients so that diagnostics go to the first client a...
Abstract interface for a consumer of code-completion information.
Options controlling the behavior of code completion.
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
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.
bool hasOutputManager() const
void createPCHExternalASTSource(StringRef Path, DisableValidationForModuleKind DisableValidation, bool AllowPCHWithCompilerErrors, void *DeserializationListener, bool OwnDeserializationListener)
Create an external AST source to read a PCH file and attach it to the AST context.
DiagnosticConsumer & getDiagnosticClient() const
~CompilerInstance() override
void createPreprocessor(TranslationUnitKind TUKind)
Create the preprocessor, using the invocation, file, and source managers, and replace any existing on...
bool lookupMissingImports(StringRef Name, SourceLocation TriggerLoc) override
Check global module index for missing imports.
void setOutputManager(IntrusiveRefCntPtr< llvm::vfs::OutputBackend > NewOutputs)
Set the output manager.
void createDiagnostics(DiagnosticConsumer *Client=nullptr, bool ShouldOwnClient=true)
Create the diagnostics engine using the invocation's diagnostic options and replace any existing one ...
DependencyOutputOptions & getDependencyOutputOpts()
bool hasFileManager() const
TargetInfo * getAuxTarget() const
const PCHContainerReader & getPCHContainerReader() const
Return the appropriate PCHContainerReader depending on the current CodeGenOptions.
DiagnosticsEngine & getDiagnostics() const
Get the current diagnostics engine.
GlobalModuleIndex * loadGlobalModuleIndex(SourceLocation TriggerLoc) override
Load, create, or return global module.
raw_ostream & getVerboseOutputStream()
Get the current stream for verbose output.
std::unique_ptr< raw_pwrite_stream > createDefaultOutputFile(bool Binary=true, StringRef BaseInput="", StringRef Extension="", bool RemoveFileOnSignal=true, bool CreateMissingDirectories=false, bool ForceUseTemporary=false)
Create the default output file (from the invocation's options) and add it to the list of tracked outp...
void setExternalSemaSource(IntrusiveRefCntPtr< ExternalSemaSource > ESS)
bool compileModule(SourceLocation ImportLoc, StringRef ModuleName, StringRef ModuleFileName, CompilerInstance &Instance)
Compile a module file for the given module, using the options provided by the importing compiler inst...
std::string getSpecificModuleCachePath()
std::unique_ptr< CompilerInstance > cloneForModuleCompile(SourceLocation ImportLoc, Module *Module, StringRef ModuleFileName, std::optional< ThreadSafeCloneConfig > ThreadSafeConfig=std::nullopt)
Creates a new CompilerInstance for compiling a module.
ModuleLoadResult loadModule(SourceLocation ImportLoc, ModuleIdPath Path, Module::NameVisibilityKind Visibility, bool IsInclusionDirective) override
Attempt to load the given module.
FileSystemOptions & getFileSystemOpts()
bool InitializeSourceManager(const FrontendInputFile &Input)
InitializeSourceManager - Initialize the source manager to set InputFile as the main file.
void createFileManager()
Create the file manager and replace any existing one with it.
FileManager & getFileManager() const
Return the current file manager to the caller.
void setBuildGlobalModuleIndex(bool Build)
Set the flag indicating whether we should (re)build the global module index.
void createOutputManager()
Create an output manager.
std::unique_ptr< Sema > takeSema()
void printDiagnosticStats()
At the end of a compilation, print the number of warnings/errors.
void setASTConsumer(std::unique_ptr< ASTConsumer > Value)
setASTConsumer - Replace the current AST consumer; the compiler instance takes ownership of Value.
PreprocessorOutputOptions & getPreprocessorOutputOpts()
IntrusiveRefCntPtr< FileManager > getFileManagerPtr() const
ModuleCache & getModuleCache() const
IntrusiveRefCntPtr< ASTReader > getASTReader() const
void setTarget(TargetInfo *Value)
Replace the current Target.
void setModuleDepCollector(std::shared_ptr< ModuleDependencyCollector > Collector)
void addDependencyCollector(std::shared_ptr< DependencyCollector > Listener)
void createASTContext()
Create the AST context.
std::unique_ptr< raw_pwrite_stream > createOutputFile(StringRef OutputPath, bool Binary, bool RemoveFileOnSignal, bool UseTemporary, bool CreateMissingDirectories=false)
Create a new output file, optionally deriving the output path name, and add it to the list of tracked...
bool hasASTContext() const
void createModuleFromSource(SourceLocation ImportLoc, StringRef ModuleName, StringRef Source) override
Attempt to create the given module from the specified source buffer.
Preprocessor & getPreprocessor() const
Return the current preprocessor.
ASTContext & getASTContext() const
IntrusiveRefCntPtr< llvm::vfs::FileSystem > getVirtualFileSystemPtr() const
void LoadRequestedPlugins()
Load the list of plugins requested in the FrontendOptions.
TargetOptions & getTargetOpts()
void createVirtualFileSystem(IntrusiveRefCntPtr< llvm::vfs::FileSystem > BaseFS=llvm::vfs::getRealFileSystem(), DiagnosticConsumer *DC=nullptr)
Create a virtual file system instance based on the invocation.
void setASTReader(IntrusiveRefCntPtr< ASTReader > Reader)
FrontendOptions & getFrontendOpts()
std::shared_ptr< ModuleDependencyCollector > getModuleDepCollector() const
bool hasDiagnostics() const
void setSema(Sema *S)
Replace the current Sema; the compiler instance takes ownership of S.
void setSourceManager(llvm::IntrusiveRefCntPtr< SourceManager > Value)
setSourceManager - Replace the current source manager.
void setASTContext(llvm::IntrusiveRefCntPtr< ASTContext > Value)
setASTContext - Replace the current AST context.
HeaderSearchOptions & getHeaderSearchOpts()
void createFrontendTimer()
Create the frontend timer and replace any existing one with it.
void createSourceManager()
Create the source manager and replace any existing one with it.
CompilerInvocation & getInvocation()
void setVerboseOutputStream(raw_ostream &Value)
Replace the current stream for verbose output.
PreprocessorOptions & getPreprocessorOpts()
ASTConsumer & getASTConsumer() const
void setFileManager(IntrusiveRefCntPtr< FileManager > Value)
Replace the current file manager.
TargetInfo & getTarget() const
llvm::vfs::OutputBackend & getOutputManager()
llvm::vfs::FileSystem & getVirtualFileSystem() const
void createCodeCompletionConsumer()
Create a code completion consumer using the invocation; note that this will cause the source manager ...
void setCodeCompletionConsumer(CodeCompleteConsumer *Value)
setCodeCompletionConsumer - Replace the current code completion consumer; the compiler instance takes...
bool ExecuteAction(FrontendAction &Act)
ExecuteAction - Execute the provided action against the compiler's CompilerInvocation object.
std::shared_ptr< PCHContainerOperations > getPCHContainerOperations() const
void clearOutputFiles(bool EraseFiles)
clearOutputFiles - Clear the output file list.
DiagnosticOptions & getDiagnosticOpts()
LangOptions & getLangOpts()
llvm::vfs::OutputBackend & getOrCreateOutputManager()
CodeGenOptions & getCodeGenOpts()
SourceManager & getSourceManager() const
Return the current source manager.
void setDiagnostics(llvm::IntrusiveRefCntPtr< DiagnosticsEngine > Value)
setDiagnostics - Replace the current diagnostics engine.
bool shouldBuildGlobalModuleIndex() const
Indicates whether we should (re)build the global module index.
bool hasSourceManager() const
bool hasASTConsumer() const
APINotesOptions & getAPINotesOpts()
std::unique_ptr< raw_pwrite_stream > createNullOutputFile()
void setAuxTarget(TargetInfo *Value)
Replace the current AuxTarget.
void makeModuleVisible(Module *Mod, Module::NameVisibilityKind Visibility, SourceLocation ImportLoc) override
Make the given module visible.
bool loadModuleFile(StringRef FileName, serialization::ModuleFile *&LoadedModuleFile)
bool hasPreprocessor() const
void setPreprocessor(std::shared_ptr< Preprocessor > Value)
Replace the current preprocessor.
void createSema(TranslationUnitKind TUKind, CodeCompleteConsumer *CompletionConsumer)
Create the Sema object to be used for parsing.
LangOptions & getLangOpts()
Mutable getters.
FrontendOptions & getFrontendOpts()
std::string getModuleHash() const
Retrieve a module hash string that is suitable for uniquely identifying the conditions under which th...
DependencyOutputOptions - Options for controlling the compiler dependency file generation.
ShowIncludesDestination ShowIncludesDest
Destination of cl.exe style /showIncludes info.
std::string DOTOutputFile
The file to write GraphViz-formatted header dependencies to.
std::string ModuleDependencyOutputDir
The directory to copy module dependencies to when collecting them.
std::string OutputFile
The file to write dependency output to.
std::string HeaderIncludeOutputFile
The file to write header include output to.
unsigned ShowHeaderIncludes
Show header inclusions (-H).
Abstract interface, implemented by clients of the front-end, which formats and prints fully processed...
unsigned getNumErrors() const
virtual void finish()
Callback to inform the diagnostic client that processing of all source files has ended.
unsigned getNumWarnings() const
static llvm::IntrusiveRefCntPtr< DiagnosticIDs > create()
Options for controlling the compiler diagnostics engine.
std::string DiagnosticLogFile
The file to log diagnostic output to.
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).
Concrete class used by the front-end to report problems and issues.
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
bool hasErrorOccurred() const
void setClient(DiagnosticConsumer *client, bool ShouldOwnClient=true)
Set the diagnostic client associated with this diagnostic object.
std::unique_ptr< DiagnosticConsumer > takeClient()
Return the current diagnostic client along with ownership of that client.
DiagnosticConsumer * getClient()
Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc) const
Based on the way the client configured the DiagnosticsEngine object, classify the specified diagnosti...
bool ownsClient() const
Determine whether this DiagnosticsEngine object own its client.
StringRef getName() const
A reference to a FileEntry that includes the name of the file as it was accessed by the FileManager's...
StringRef getName() const
The name of this FileEntry.
StringRef getNameAsRequested() const
The name of this FileEntry, as originally requested without applying any remappings for VFS 'use-exte...
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Implements support for file system lookup, file system caching, and directory search management.
void AddStats(const FileManager &Other)
Import statistics from a child FileManager and add them to this current FileManager.
OptionalFileEntryRef getOptionalFileRef(StringRef Filename, bool OpenFile=false, bool CacheFailure=true)
Get a FileEntryRef if it exists, without doing anything on error.
static bool fixupRelativePath(const FileSystemOptions &FileSystemOpts, SmallVectorImpl< char > &Path)
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Abstract base class for actions which can be performed by the frontend.
virtual void EndSourceFile()
Perform any per-file post processing, deallocate per-file objects, and run statistics and output file...
bool PrepareToExecute(CompilerInstance &CI)
Prepare the action to execute on the given compiler instance.
llvm::Error Execute()
Set the source manager's main input file, and run the action.
bool BeginSourceFile(CompilerInstance &CI, const FrontendInputFile &Input)
Prepare the action for processing the input file Input.
virtual bool isModelParsingAction() const
Is this action invoked on a model file?
FrontendOptions - Options for controlling the behavior of the frontend.
unsigned BuildingImplicitModule
Whether we are performing an implicit module build.
unsigned AllowPCMWithCompilerErrors
Output (and read) PCM files regardless of compiler errors.
unsigned BuildingImplicitModuleUsesLock
Whether to use a filesystem lock when building implicit modules.
unsigned ModulesShareFileManager
Whether to share the FileManager when building modules.
std::optional< std::string > AuxTargetCPU
Auxiliary target CPU for CUDA/HIP compilation.
std::string StatsFile
Filename to write statistics to.
std::string OutputFile
The output file, if any.
std::string ActionName
The name of the action to run when using a plugin action.
ParsedSourceLocation CodeCompletionAt
If given, enable code completion at the provided location.
std::string OriginalModuleMap
When the input is a module map, the original module map file from which that map was inferred,...
unsigned GenerateGlobalModuleIndex
Whether we can generate the global module index if needed.
unsigned DisableFree
Disable memory freeing on exit.
SmallVector< FrontendInputFile, 0 > Inputs
The input files and their types.
frontend::ActionKind ProgramAction
The frontend action to perform.
std::optional< std::vector< std::string > > AuxTargetFeatures
Auxiliary target features for CUDA/HIP compilation.
A global index for a set of module files, providing information about the identifiers within those mo...
llvm::SmallPtrSet< ModuleFile *, 4 > HitSet
A set of module files in which we found a result.
bool lookupIdentifier(llvm::StringRef Name, HitSet &Hits)
Look for all of the module files with information about the given identifier, e.g....
static llvm::Error writeIndex(FileManager &FileMgr, const PCHContainerReader &PCHContainerRdr, llvm::StringRef Path)
Write a global index into the given.
One of these records is kept for each identifier that is lexed.
bool hadMacroDefinition() const
Returns true if this identifier was #defined to some value at any moment.
@ FPE_Default
Used internally to represent initial unspecified value.
@ FPE_Ignore
Assume that floating-point exceptions are masked.
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.
Encapsulates the data about a macro definition (e.g.
The module cache used for compiling modules implicitly.
virtual void prepareForGetLock(StringRef ModuleFilename)=0
May perform any work that only needs to be performed once for multiple calls getLock() with the same ...
virtual void updateModuleTimestamp(StringRef ModuleFilename)=0
Updates the timestamp denoting the last time inputs of the module file were validated.
virtual std::unique_ptr< llvm::AdvisoryLock > getLock(StringRef ModuleFilename)=0
Returns lock for the given module file. The lock is initially unlocked.
Describes the result of attempting to load a module.
bool buildingModule() const
Returns true if this instance is building a module.
ModuleLoader(bool BuildingModule=false)
llvm::StringMap< Module * >::const_iterator module_iterator
module_iterator module_begin() const
OptionalFileEntryRef getModuleMapFileForUniquing(const Module *M) const
std::optional< Module * > getCachedModuleLoad(const IdentifierInfo &II)
Return a cached module load.
module_iterator module_end() const
FileID getContainingModuleMapFileID(const Module *Module) const
Retrieve the module map file containing the definition of the given module.
void resolveLinkAsDependencies(Module *Mod)
Use PendingLinkAsModule information to mark top level link names that are going to be replaced by exp...
void cacheModuleLoad(const IdentifierInfo &II, Module *M)
Cache a module load. M might be nullptr.
Module * findOrLoadModule(StringRef Name)
Describes a module or submodule.
StringRef getTopLevelModuleName() const
Retrieve the name of the top-level module.
Module * findSubmodule(StringRef Name) const
Find the submodule with the given name.
std::vector< std::string > ConfigMacros
The set of "configuration macros", which are macros that (intentionally) change how this module is bu...
unsigned IsUnimportable
Whether this module has declared itself unimportable, either because it's missing a requirement from ...
NameVisibilityKind
Describes the visibility of the various names within a particular module.
@ Hidden
All of the names in this module are hidden.
void print(raw_ostream &OS, unsigned Indent=0, bool Dump=false) const
Print the module map for this module to the given stream.
SourceLocation DefinitionLoc
The location of the module definition.
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()
OptionalDirectoryEntryRef Directory
The build directory of this module.
unsigned IsFromModuleFile
Whether this module was loaded from a module file.
unsigned HasIncompatibleModuleFile
Whether we tried and failed to load a module file for this module.
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
unsigned IsAvailable
Whether this module is available in the current translation unit.
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.
This abstract interface provides operations for unwrapping containers for serialized ASTs (precompile...
@ ReplaceAction
Replace the main action.
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
std::vector< std::pair< std::string, std::string > > RemappedFiles
The set of file remappings, which take existing files on the system (the first part of each pair) and...
std::pair< unsigned, bool > PrecompiledPreambleBytes
If non-zero, the implicit PCH include is actually a precompiled preamble that covers this number of b...
bool RemappedFilesKeepOriginalName
True if the SourceManager should report the original file name for contents of files that were remapp...
bool RetainRemappedFileBuffers
Whether the compiler instance should retain (i.e., not free) the buffers associated with remapped fil...
bool DetailedRecord
Whether we should maintain a detailed record of all macro definitions and expansions.
std::string ImplicitPCHInclude
The implicit PCH included at the start of the translation unit, or empty.
DisableValidationForModuleKind DisablePCHOrModuleValidation
Whether to disable most of the normal validation performed on precompiled headers and module files.
std::vector< std::pair< std::string, bool > > Macros
std::vector< std::pair< std::string, llvm::MemoryBuffer * > > RemappedFileBuffers
The set of file-to-buffer remappings, which take existing files on the system (the first part of each...
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
const MacroInfo * getMacroInfo(const IdentifierInfo *II) const
MacroDirective * getLocalMacroDirectiveHistory(const IdentifierInfo *II) const
Given an identifier, return the latest non-imported macro directive for that identifier.
bool SetCodeCompletionPoint(FileEntryRef File, unsigned Line, unsigned Column)
Specify the point at which code-completion will be performed.
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
SourceManager & getSourceManager() const
static bool checkModuleIsAvailable(const LangOptions &LangOpts, const TargetInfo &TargetInfo, const Module &M, DiagnosticsEngine &Diags)
Check that the given module is available, producing a diagnostic if not.
FileManager & getFileManager() const
FileID getPredefinesFileID() const
Returns the FileID for the preprocessor predefines.
HeaderSearch & getHeaderSearchInfo() const
DiagnosticsEngine & getDiagnostics() const
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) const
Forwarding function for diagnostics.
A simple code-completion consumer that prints the results it receives in a simple format.
Sema - This implements semantic analysis and AST building for C.
ASTReaderListenter implementation to set SuggestedPredefines of ASTReader which is required to use a ...
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
This class handles loading and caching of source files into memory.
ModuleBuildStack getModuleBuildStack() const
Retrieve the module build stack.
A trivial tuple used to represent a source range.
CharacteristicKind getFileCharacteristic() const
Return whether this is a system header or not.
This is a discriminated union of FileInfo and ExpansionInfo.
const FileInfo & getFile() const
Exposes information about the current target.
static TargetInfo * CreateTargetInfo(DiagnosticsEngine &Diags, TargetOptions &Opts)
Construct a target for the given options.
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
virtual void setAuxTarget(const TargetInfo *Aux)
void noSignedCharForObjCBool()
virtual void adjust(DiagnosticsEngine &Diags, LangOptions &Opts, const TargetInfo *Aux)
Set forced language options.
std::string CPU
If given, the name of the target CPU to generate code for.
VerifyDiagnosticConsumer - Create a diagnostic client which will use markers in the input source to c...
Information about a module that has been loaded by the ASTReader.
Defines the clang::TargetInfo interface.
CharacteristicKind
Indicates whether a file or directory holds normal user code, system code, or system code which is im...
@ PluginAction
Run a plugin action,.
@ RewriteObjC
ObjC->C Rewriter.
bool Inv(InterpState &S, CodePtr OpPC)
@ MK_PCH
File is a PCH file treated as such.
@ MK_Preamble
File is a PCH file treated as the preamble.
@ MK_ExplicitModule
File is an explicitly-loaded module.
@ MK_ImplicitModule
File is an implicitly-loaded module.
@ MK_PrebuiltModule
File is from a prebuilt module path.
std::unique_ptr< DiagnosticConsumer > create(StringRef OutputFile, DiagnosticOptions &DiagOpts, bool MergeChildRecords=false)
Returns a DiagnosticConsumer that serializes diagnostics to a bitcode file.
The JSON file list parser is used to communicate input to InstallAPI.
CustomizableOptional< FileEntryRef > OptionalFileEntryRef
ArrayRef< IdentifierLoc > ModuleIdPath
A sequence of identifier/location pairs used to describe a particular module or submodule,...
ArrayRef< std::pair< std::string, FullSourceLoc > > ModuleBuildStack
The stack used when building modules on demand, which is used to provide a link between the source ma...
void ApplyHeaderSearchOptions(HeaderSearch &HS, const HeaderSearchOptions &HSOpts, const LangOptions &Lang, const llvm::Triple &triple)
Apply the header search options to get given HeaderSearch object.
@ Success
Annotation was successful.
void InitializePreprocessor(Preprocessor &PP, const PreprocessorOptions &PPOpts, const PCHContainerReader &PCHContainerRdr, const FrontendOptions &FEOpts, const CodeGenOptions &CodeGenOpts)
InitializePreprocessor - Initialize the preprocessor getting it and the environment ready to process ...
LLVM_READONLY bool isAlphanumeric(unsigned char c)
Return true if this character is an ASCII letter or digit: [a-zA-Z0-9].
@ Module
Module linkage, which indicates that the entity can be referred to from other translation units withi...
Language
The language for the input, used to select and validate the language standard and possible actions.
@ C
Languages that the frontend can parse and compile.
@ Result
The result type of a method or function.
IntrusiveRefCntPtr< llvm::vfs::FileSystem > createVFSFromCompilerInvocation(const CompilerInvocation &CI, DiagnosticsEngine &Diags)
void normalizeModuleCachePath(FileManager &FileMgr, StringRef Path, SmallVectorImpl< char > &NormalizedPath)
constexpr size_t DesiredStackSize
The amount of stack space that Clang would like to be provided with.
IntrusiveRefCntPtr< ModuleCache > createCrossProcessModuleCache()
Creates new ModuleCache backed by a file system directory that may be operated on by multiple process...
void noteBottomOfStack(bool ForceSet=false)
Call this once on each thread, as soon after starting the thread as feasible, to note the approximate...
void ProcessWarningOptions(DiagnosticsEngine &Diags, const DiagnosticOptions &Opts, llvm::vfs::FileSystem &VFS, bool ReportDiags=true)
ProcessWarningOptions - Initialize the diagnostic client and process the warning options specified on...
TranslationUnitKind
Describes the kind of translation unit being processed.
void AttachHeaderIncludeGen(Preprocessor &PP, const DependencyOutputOptions &DepOpts, bool ShowAllHeaders=false, StringRef OutputPath={}, bool ShowDepth=true, bool MSStyle=false)
AttachHeaderIncludeGen - Create a header include list generator, and attach it to the given preproces...
DisableValidationForModuleKind
Whether to disable the normal validation performed on precompiled headers and module files when they ...
@ Other
Other implicit parameter.
Visibility
Describes the different kinds of visibility that a declaration may have.
void AttachDependencyGraphGen(Preprocessor &PP, StringRef OutputFile, StringRef SysRoot)
AttachDependencyGraphGen - Create a dependency graph generator, and attach it to the given preprocess...
A source location that has been parsed on the command line.