22#include "clang/Config/config.h"
42#include "llvm/ADT/ScopeExit.h"
43#include "llvm/ADT/Statistic.h"
44#include "llvm/Config/llvm-config.h"
45#include "llvm/Support/BuryPointer.h"
46#include "llvm/Support/CrashRecoveryContext.h"
47#include "llvm/Support/Errc.h"
48#include "llvm/Support/FileSystem.h"
49#include "llvm/Support/LockFileManager.h"
50#include "llvm/Support/MemoryBuffer.h"
51#include "llvm/Support/Path.h"
52#include "llvm/Support/Program.h"
53#include "llvm/Support/Signals.h"
54#include "llvm/Support/TimeProfiler.h"
55#include "llvm/Support/Timer.h"
56#include "llvm/Support/raw_ostream.h"
57#include "llvm/TargetParser/Host.h"
64CompilerInstance::CompilerInstance(
65 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
69 ModuleCache(SharedModuleCache ? SharedModuleCache
71 ThePCHContainerOperations(
std::move(PCHContainerOps)) {}
74 assert(OutputFiles.empty() &&
"Still output files in flight?");
78 std::shared_ptr<CompilerInvocation>
Value) {
79 Invocation = std::move(
Value);
83 return (BuildGlobalModuleIndex ||
84 (TheASTReader && TheASTReader->isGlobalIndexUnavailable() &&
86 !DisableGeneratingGlobalModuleIndex;
94 OwnedVerboseOutputStream.reset();
95 VerboseOutputStream = &
Value;
99 OwnedVerboseOutputStream.swap(
Value);
100 VerboseOutputStream = OwnedVerboseOutputStream.get();
119 auto TO = std::make_shared<TargetOptions>();
175 PP = 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(ModuleCache.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) {
241 MDC->addFile(PCHInclude);
247 llvm::sys::path::native(PCHDir->getName(), DirNative);
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) {
272 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer =
273 llvm::MemoryBuffer::getFile(VFSFile);
276 llvm::vfs::collectVFSFromYAML(std::move(Buffer.get()),
277 nullptr, VFSFile, VFSEntries);
280 for (
auto &E : VFSEntries)
281 MDC->addFile(E.VPath, E.RPath);
289 std::unique_ptr<raw_ostream> StreamOwner;
290 raw_ostream *
OS = &llvm::errs();
293 auto FileOS = std::make_unique<llvm::raw_fd_ostream>(
295 llvm::sys::fs::OF_Append | llvm::sys::fs::OF_TextWithCRLF);
297 Diags.
Report(diag::warn_fe_cc_log_diagnostics_failure)
300 FileOS->SetUnbuffered();
302 StreamOwner = std::move(FileOS);
307 auto Logger = std::make_unique<LogDiagnosticPrinter>(*
OS, DiagOpts,
308 std::move(StreamOwner));
322 StringRef OutputFile) {
323 auto SerializedConsumer =
328 Diags.
takeClient(), std::move(SerializedConsumer)));
331 Diags.
getClient(), std::move(SerializedConsumer)));
336 bool ShouldOwnClient) {
344 bool ShouldOwnClient,
353 Diags->setClient(Client, ShouldOwnClient);
360 if (Opts->VerifyDiagnostics)
382 VFS = FileMgr ? &FileMgr->getVirtualFileSystem()
385 assert(VFS &&
"FileManager has no VFS?");
387 return FileMgr.get();
408 Diags.
Report(diag::err_fe_remap_missing_from_file) << RB.first;
422 FromFile, std::unique_ptr<llvm::MemoryBuffer>(
423 const_cast<llvm::MemoryBuffer *
>(RB.second)));
431 Diags.
Report(diag::err_fe_remap_missing_to_file) << RF.first << RF.second;
439 Diags.
Report(diag::err_fe_remap_missing_from_file) << RF.first;
458 TheASTReader.reset();
464 PP = std::make_shared<Preprocessor>(Invocation->getPreprocessorOptsPtr(),
473 PP->createPreprocessingRecord();
477 PP->getFileManager(), PPOpts);
486 const llvm::Triple *HeaderSearchTriple = &PP->getTargetInfo().getTriple();
487 if (PP->getTargetInfo().getTriple().getOS() == llvm::Triple::CUDA &&
488 PP->getAuxTargetInfo())
489 HeaderSearchTriple = &PP->getAuxTargetInfo()->getTriple();
492 PP->getLangOpts(), *HeaderSearchTriple);
496 if (PP->getLangOpts().Modules && PP->getLangOpts().ImplicitModules) {
498 PP->getHeaderSearchInfo().setModuleHash(ModuleHash);
499 PP->getHeaderSearchInfo().setModuleCachePath(
514 ModuleDepCollector = std::make_shared<ModuleDependencyCollector>(
520 if (ModuleDepCollector) {
527 for (
auto &Listener : DependencyCollectors)
528 Listener->attachToPreprocessor(*PP);
535 if (OutputPath ==
"-")
553 llvm::sys::path::append(SpecificModuleCache, ModuleHash);
554 return std::string(SpecificModuleCache.str());
580 void ReadModuleName(StringRef ModuleName)
override {
583 LoadedModules.push_back(ModuleName.str());
588 for (
const std::string &LoadedModule : LoadedModules)
591 LoadedModules.clear();
594 void markAllUnavailable() {
595 for (
const std::string &LoadedModule : LoadedModules) {
598 M->HasIncompatibleModuleFile =
true;
604 while (!Stack.empty()) {
605 Module *Current = Stack.pop_back_val();
606 if (Current->IsUnimportable)
continue;
607 Current->IsAvailable =
true;
608 Stack.insert(Stack.end(),
609 Current->submodule_begin(), Current->submodule_end());
613 LoadedModules.clear();
620 bool AllowPCHWithCompilerErrors,
void *DeserializationListener,
621 bool OwnDeserializationListener) {
628 DeserializationListener, OwnDeserializationListener,
Preamble,
633 StringRef Path, StringRef Sysroot,
638 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
639 ArrayRef<std::shared_ptr<DependencyCollector>> DependencyCollectors,
640 void *DeserializationListener,
bool OwnDeserializationListener,
641 bool Preamble,
bool UseGlobalModuleIndex) {
645 PP, ModuleCache, &Context, PCHContainerRdr, Extensions,
646 Sysroot.empty() ?
"" : Sysroot.data(), DisableValidation,
647 AllowPCHWithCompilerErrors,
false,
649 UseGlobalModuleIndex));
655 Reader->setDeserializationListener(
657 OwnDeserializationListener);
659 for (
auto &Listener : DependencyCollectors)
660 Listener->attachToASTReader(*Reader);
662 auto Listener = std::make_unique<ReadModuleNames>(PP);
663 auto &ListenerRef = *Listener;
665 std::move(Listener));
667 switch (Reader->ReadAST(Path,
676 ListenerRef.registerAll();
692 ListenerRef.markAllUnavailable();
719 if (!CompletionConsumer) {
732 FrontendTimerGroup.reset(
733 new llvm::TimerGroup(
"frontend",
"Clang front-end time report"));
735 new llvm::Timer(
"frontend",
"Clang front-end timer",
736 *FrontendTimerGroup));
756 TUKind, CompletionConsumer));
758 if (ExternalSemaSrc) {
759 TheSema->addExternalSource(ExternalSemaSrc.get());
760 ExternalSemaSrc->InitializeSema(*TheSema);
770 for (OutputFile &OF : OutputFiles) {
773 consumeError(OF.File->discard());
774 if (!OF.Filename.empty())
775 llvm::sys::fs::remove(OF.Filename);
782 if (OF.File->TmpName.empty()) {
783 consumeError(OF.File->discard());
787 llvm::Error E = OF.File->keep(OF.Filename);
792 << OF.File->TmpName << OF.Filename << std::move(E);
794 llvm::sys::fs::remove(OF.File->TmpName);
797 if (DeleteBuiltModules) {
798 for (
auto &
Module : BuiltModules)
799 llvm::sys::fs::remove(
Module.second);
800 BuiltModules.clear();
805 bool Binary, StringRef InFile, StringRef Extension,
bool RemoveFileOnSignal,
806 bool CreateMissingDirectories,
bool ForceUseTemporary) {
808 std::optional<SmallString<128>> PathStorage;
809 if (OutputPath.empty()) {
810 if (InFile ==
"-" || Extension.empty()) {
813 PathStorage.emplace(InFile);
814 llvm::sys::path::replace_extension(*PathStorage, Extension);
815 OutputPath = *PathStorage;
821 CreateMissingDirectories);
825 return std::make_unique<llvm::raw_null_ostream>();
828std::unique_ptr<raw_pwrite_stream>
830 bool RemoveFileOnSignal,
bool UseTemporary,
831 bool CreateMissingDirectories) {
833 createOutputFileImpl(OutputPath, Binary, RemoveFileOnSignal, UseTemporary,
834 CreateMissingDirectories);
836 return std::move(*
OS);
838 << OutputPath << errorToErrorCode(
OS.takeError()).message();
843CompilerInstance::createOutputFileImpl(StringRef OutputPath,
bool Binary,
844 bool RemoveFileOnSignal,
846 bool CreateMissingDirectories) {
847 assert((!CreateMissingDirectories || UseTemporary) &&
848 "CreateMissingDirectories is only allowed when using temporary files");
852 std::optional<SmallString<128>> AbsPath;
853 if (OutputPath !=
"-" && !llvm::sys::path::is_absolute(OutputPath)) {
855 "File Manager is required to fix up relative path.\n");
857 AbsPath.emplace(OutputPath);
858 FileMgr->FixupRelativePath(*AbsPath);
859 OutputPath = *AbsPath;
862 std::unique_ptr<llvm::raw_fd_ostream>
OS;
863 std::optional<StringRef> OSFile;
866 if (OutputPath ==
"-")
867 UseTemporary =
false;
869 llvm::sys::fs::file_status Status;
870 llvm::sys::fs::status(OutputPath, Status);
871 if (llvm::sys::fs::exists(Status)) {
873 if (!llvm::sys::fs::can_write(OutputPath))
874 return llvm::errorCodeToError(
879 if (!llvm::sys::fs::is_regular_file(Status))
880 UseTemporary =
false;
885 std::optional<llvm::sys::fs::TempFile> Temp;
891 StringRef OutputExtension = llvm::sys::path::extension(OutputPath);
893 StringRef(OutputPath).drop_back(OutputExtension.size());
894 TempPath +=
"-%%%%%%%%";
895 TempPath += OutputExtension;
898 llvm::sys::fs::TempFile::create(
899 TempPath, llvm::sys::fs::all_read | llvm::sys::fs::all_write,
900 Binary ? llvm::sys::fs::OF_None : llvm::sys::fs::OF_Text);
902 llvm::Error E = handleErrors(
903 ExpectedFile.takeError(), [&](
const llvm::ECError &E) -> llvm::Error {
904 std::error_code EC = E.convertToErrorCode();
905 if (CreateMissingDirectories &&
906 EC == llvm::errc::no_such_file_or_directory) {
907 StringRef Parent = llvm::sys::path::parent_path(OutputPath);
908 EC = llvm::sys::fs::create_directories(Parent);
910 ExpectedFile = llvm::sys::fs::TempFile::create(TempPath);
912 return llvm::errorCodeToError(
913 llvm::errc::no_such_file_or_directory);
916 return llvm::errorCodeToError(EC);
920 consumeError(std::move(E));
922 Temp = std::move(ExpectedFile.get());
923 OS.reset(
new llvm::raw_fd_ostream(Temp->FD,
false));
924 OSFile = Temp->TmpName;
934 OS.reset(
new llvm::raw_fd_ostream(
936 (Binary ? llvm::sys::fs::OF_None : llvm::sys::fs::OF_TextWithCRLF)));
938 return llvm::errorCodeToError(EC);
943 OutputFiles.emplace_back(((OutputPath !=
"-") ? OutputPath :
"").str(),
946 if (!Binary ||
OS->supportsSeeking())
947 return std::move(
OS);
949 return std::make_unique<llvm::buffer_unique_ostream>(std::move(
OS));
973 "Couldn't establish MainFileID!");
977 StringRef InputFile = Input.
getFile();
980 auto FileOrErr = InputFile ==
"-"
984 auto EC = llvm::errorToErrorCode(FileOrErr.takeError());
985 if (InputFile !=
"-")
986 Diags.
Report(diag::err_fe_error_reading) << InputFile << EC.message();
988 Diags.
Report(diag::err_fe_error_reading_stdin) << EC.message();
996 "Couldn't establish MainFileID!");
1003 assert(
hasDiagnostics() &&
"Diagnostics engine is not initialized!");
1005 assert(!
getFrontendOpts().ShowVersion &&
"Client must handle '-version'!");
1012 auto FinishDiagnosticClient = llvm::make_scope_exit([&]() {
1031 OS <<
"clang -cc1 version " CLANG_VERSION_STRING <<
" based upon LLVM "
1032 << LLVM_VERSION_STRING <<
" default target "
1033 << llvm::sys::getDefaultTargetTriple() <<
"\n";
1039 llvm::EnableStatistics(
false);
1048 if (llvm::Error Err = Act.
Execute()) {
1049 consumeError(std::move(Err));
1062 OS << NumWarnings <<
" warning" << (NumWarnings == 1 ?
"" :
"s");
1063 if (NumWarnings && NumErrors)
1066 OS << NumErrors <<
" error" << (NumErrors == 1 ?
"" :
"s");
1067 if (NumWarnings || NumErrors) {
1071 OS <<
" when compiling for host";
1085 llvm::PrintStatistics(
OS);
1088 if (!StatsFile.empty()) {
1089 llvm::sys::fs::OpenFlags FileFlags = llvm::sys::fs::OF_TextWithCRLF;
1091 FileFlags |= llvm::sys::fs::OF_Append;
1094 std::make_unique<llvm::raw_fd_ostream>(StatsFile, EC, FileFlags);
1097 << StatsFile << EC.message();
1099 llvm::PrintStatisticsJSON(*StatS);
1110 if (llvm::sys::DynamicLibrary::LoadLibraryPermanently(Path.c_str(), &
Error))
1116 for (
const FrontendPluginRegistry::entry &Plugin :
1117 FrontendPluginRegistry::entries()) {
1118 std::unique_ptr<PluginASTAction>
P(Plugin.instantiate());
1130 if (LangOpts.OpenCL)
1145 StringRef OriginalModuleMapFile, StringRef ModuleFileName,
1150 llvm::TimeTraceScope TimeScope(
"Module Compile", ModuleName);
1156 ImportLoc, diag::err_module_rebuild_finalized)
1163 std::make_shared<CompilerInvocation>(ImportingInstance.
getInvocation());
1174 llvm::erase_if(PPOpts.
Macros,
1175 [&HSOpts](
const std::pair<std::string, bool> &def) {
1176 StringRef MacroDef = def.first;
1177 return HSOpts.ModulesIgnoreMacros.contains(
1178 llvm::CachedHashString(MacroDef.split(
'=').first));
1182 Invocation->getLangOpts()->ModuleName =
1186 Invocation->getLangOpts()->CurrentModule = std::string(ModuleName);
1195 std::make_shared<PreprocessorOptions::FailedModulesSet>();
1202 FrontendOpts.
OutputFile = ModuleFileName.str();
1209 FrontendOpts.
Inputs = {Input};
1214 Invocation->getDiagnosticOpts().VerifyDiagnostics = 0;
1216 Invocation->getModuleHash() &&
"Module hash mismatch!");
1224 auto &
Inv = *Invocation;
1225 Instance.setInvocation(std::move(Invocation));
1236 Instance.createSourceManager(Instance.getFileManager());
1253 diag::remark_module_build)
1254 << ModuleName << ModuleFileName;
1256 PreBuildStep(Instance);
1260 bool Crashed = !llvm::CrashRecoveryContext().RunSafelyOnThread(
1263 Instance.ExecuteAction(Action);
1267 PostBuildStep(Instance);
1270 diag::remark_module_build_done)
1276 Instance.setSema(
nullptr);
1277 Instance.setASTConsumer(
nullptr);
1280 Instance.clearOutputFiles(
true);
1285 return !Instance.getDiagnostics().hasErrorOccurred() ||
1286 Instance.getFrontendOpts().AllowPCMWithCompilerErrors;
1291 StringRef
Filename = llvm::sys::path::filename(
File.getName());
1293 if (
Filename ==
"module_private.map")
1294 llvm::sys::path::append(PublicFilename,
"module.map");
1295 else if (
Filename ==
"module.private.modulemap")
1296 llvm::sys::path::append(PublicFilename,
"module.modulemap");
1298 return std::nullopt;
1307 StringRef ModuleFileName) {
1322 ModuleMapFile = PublicMMFile;
1324 StringRef ModuleMapFilePath = ModuleMapFile->getNameAsRequested();
1337 llvm::sys::path::append(FakeModuleMapFile,
"__inferred_module.map");
1339 std::string InferredModuleMapContent;
1340 llvm::raw_string_ostream
OS(InferredModuleMapContent);
1350 std::unique_ptr<llvm::MemoryBuffer> ModuleMapBuffer =
1351 llvm::MemoryBuffer::getMemBuffer(InferredModuleMapContent);
1352 const FileEntry *ModuleMapFile = Instance.getFileManager().getVirtualFile(
1353 FakeModuleMapFile, InferredModuleMapContent.size(), 0);
1354 Instance.getSourceManager().overrideFileContents(
1355 ModuleMapFile, std::move(ModuleMapBuffer));
1384 ModuleLoadCapabilities);
1396 Diags.
Report(ModuleNameLoc, diag::err_module_not_built)
1408 StringRef ModuleFileName) {
1412 diag::err_module_not_built)
1435 Diags.
Report(ModuleNameLoc, diag::remark_module_lock)
1440 StringRef Dir = llvm::sys::path::parent_path(ModuleFileName);
1441 llvm::sys::fs::create_directories(Dir);
1444 llvm::LockFileManager Locked(ModuleFileName);
1446 case llvm::LockFileManager::LFS_Error:
1450 Diags.
Report(ModuleNameLoc, diag::remark_module_lock_failure)
1453 Locked.unsafeRemoveLockFile();
1455 case llvm::LockFileManager::LFS_Owned:
1458 ModuleNameLoc,
Module, ModuleFileName);
1460 case llvm::LockFileManager::LFS_Shared:
1466 switch (Locked.waitForUnlock()) {
1467 case llvm::LockFileManager::Res_Success:
1469 case llvm::LockFileManager::Res_OwnerDied:
1471 case llvm::LockFileManager::Res_Timeout:
1475 Diags.
Report(ModuleNameLoc, diag::remark_module_lock_timeout)
1478 Locked.unsafeRemoveLockFile();
1483 bool OutOfDate =
false;
1485 Module, ModuleFileName, &OutOfDate))
1524 if (!
Id->hadMacroDefinition())
1530 for (
auto *MD = LatestLocalMD; MD; MD = MD->getPrevious()) {
1535 if (
auto *DMD = dyn_cast<DefMacroDirective>(MD))
1536 CmdLineDefinition = DMD->getMacroInfo();
1541 if (CurrentDefinition == CmdLineDefinition) {
1543 }
else if (!CurrentDefinition) {
1546 PP.
Diag(ImportLoc, diag::warn_module_config_macro_undef)
1548 auto LatestDef = LatestLocalMD->getDefinition();
1549 assert(LatestDef.isUndefined() &&
1550 "predefined macro went away with no #undef?");
1551 PP.
Diag(LatestDef.getUndefLocation(), diag::note_module_def_undef_here)
1554 }
else if (!CmdLineDefinition) {
1557 PP.
Diag(ImportLoc, diag::warn_module_config_macro_undef)
1559 PP.
Diag(CurrentDefinition->getDefinitionLoc(),
1560 diag::note_module_def_undef_here)
1562 }
else if (!CurrentDefinition->isIdenticalTo(*CmdLineDefinition, PP,
1565 PP.
Diag(ImportLoc, diag::warn_module_config_macro_undef)
1567 PP.
Diag(CurrentDefinition->getDefinitionLoc(),
1568 diag::note_module_def_undef_here)
1576 llvm::raw_fd_ostream Out(TimestampFile.str(), EC, llvm::sys::fs::OF_None);
1582 llvm::sys::fs::file_status StatBuf;
1585 assert(!TimestampFile.empty());
1586 llvm::sys::path::append(TimestampFile,
"modules.timestamp");
1589 if (std::error_code EC = llvm::sys::fs::status(TimestampFile, StatBuf)) {
1591 if (EC == std::errc::no_such_file_or_directory) {
1599 time_t TimeStampModTime =
1600 llvm::sys::toTimeT(StatBuf.getLastModificationTime());
1601 time_t CurrentTime = time(
nullptr);
1614 llvm::sys::path::native(HSOpts.
ModuleCachePath, ModuleCachePathNative);
1615 for (llvm::sys::fs::directory_iterator Dir(ModuleCachePathNative, EC), DirEnd;
1616 Dir != DirEnd && !EC; Dir.increment(EC)) {
1618 if (!llvm::sys::fs::is_directory(Dir->path()))
1622 for (llvm::sys::fs::directory_iterator
File(Dir->path(), EC), FileEnd;
1623 File != FileEnd && !EC;
File.increment(EC)) {
1625 StringRef Extension = llvm::sys::path::extension(
File->path());
1626 if (Extension !=
".pcm" && Extension !=
".timestamp" &&
1627 llvm::sys::path::filename(
File->path()) !=
"modules.idx")
1632 if (llvm::sys::fs::status(
File->path(), StatBuf))
1636 time_t FileAccessTime = llvm::sys::toTimeT(StatBuf.getLastAccessedTime());
1637 if (CurrentTime - FileAccessTime <=
1643 llvm::sys::fs::remove(
File->path());
1646 std::string TimpestampFilename =
File->path() +
".timestamp";
1647 llvm::sys::fs::remove(TimpestampFilename);
1652 if (llvm::sys::fs::directory_iterator(Dir->path(), EC) ==
1653 llvm::sys::fs::directory_iterator() && !EC)
1654 llvm::sys::fs::remove(Dir->path());
1668 !
getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty() &&
1675 std::string Sysroot = HSOpts.
Sysroot;
1678 std::unique_ptr<llvm::Timer> ReadTimer;
1680 if (FrontendTimerGroup)
1681 ReadTimer = std::make_unique<llvm::Timer>(
"reading_modules",
1683 *FrontendTimerGroup);
1687 Sysroot.empty() ?
"" : Sysroot.c_str(),
1694 TheASTReader->setDeserializationListener(
1701 TheASTReader->InitializeSema(
getSema());
1705 for (
auto &Listener : DependencyCollectors)
1706 Listener->attachToASTReader(*TheASTReader);
1711 if (FrontendTimerGroup)
1712 Timer.init(
"preloading." + FileName.str(),
"Preloading " + FileName.str(),
1713 *FrontendTimerGroup);
1714 llvm::TimeRegion TimeLoading(FrontendTimerGroup ? &Timer :
nullptr);
1722 bool ConfigMismatchIsRecoverable =
1727 auto Listener = std::make_unique<ReadModuleNames>(*PP);
1728 auto &ListenerRef = *Listener;
1730 std::move(Listener));
1733 switch (TheASTReader->ReadAST(
1739 ListenerRef.registerAll();
1748 ListenerRef.markAllUnavailable();
1760 MS_PrebuiltModulePath,
1761 MS_ModuleBuildPragma
1768 Module *M, StringRef ModuleName, std::string &ModuleFilename,
1769 const std::map<std::string, std::string, std::less<>> &BuiltModules,
1771 assert(ModuleFilename.empty() &&
"Already has a module source?");
1775 auto BuiltModuleIt = BuiltModules.find(ModuleName);
1776 if (BuiltModuleIt != BuiltModules.end()) {
1777 ModuleFilename = BuiltModuleIt->second;
1778 return MS_ModuleBuildPragma;
1788 if (!ModuleFilename.empty())
1789 return MS_PrebuiltModulePath;
1795 return MS_ModuleCache;
1798 return MS_ModuleNotFound;
1807 HS.
lookupModule(ModuleName, ImportLoc,
true, !IsInclusionDirective);
1810 std::string ModuleFilename;
1811 ModuleSource Source =
1813 if (Source == MS_ModuleNotFound) {
1816 << ModuleName <<
SourceRange(ImportLoc, ModuleNameLoc);
1819 if (ModuleFilename.empty()) {
1837 if (FrontendTimerGroup)
1838 Timer.init(
"loading." + ModuleFilename,
"Loading " + ModuleFilename,
1839 *FrontendTimerGroup);
1840 llvm::TimeRegion TimeLoading(FrontendTimerGroup ? &Timer :
nullptr);
1841 llvm::TimeTraceScope TimeScope(
"Module Load", ModuleName);
1845 unsigned ARRFlags = Source == MS_ModuleCache
1848 : Source == MS_PrebuiltModulePath
1852 Source == MS_PrebuiltModulePath
1854 : Source == MS_ModuleBuildPragma
1857 ImportLoc, ARRFlags)) {
1861 assert(Source != MS_ModuleCache &&
1862 "missing module, but file loaded from cache");
1866 M = HS.
lookupModule(ModuleName, ImportLoc,
true, !IsInclusionDirective);
1870 if (
auto ModuleFile = FileMgr->getFile(ModuleFilename))
1885 if (Source == MS_PrebuiltModulePath)
1889 diag::warn_module_config_mismatch)
1906 if (Source != MS_ModuleCache) {
1914 assert(M &&
"missing module, but trying to compile for cache");
1918 ModuleBuildStack::iterator Pos = ModPath.begin(), PosEnd = ModPath.end();
1919 for (; Pos != PosEnd; ++Pos) {
1920 if (Pos->first == ModuleName)
1924 if (Pos != PosEnd) {
1926 for (; Pos != PosEnd; ++Pos) {
1927 CyclePath += Pos->first;
1928 CyclePath +=
" -> ";
1930 CyclePath += ModuleName;
1933 << ModuleName << CyclePath;
1942 << ModuleName <<
SourceRange(ImportLoc, ModuleNameLoc);
1950 "undiagnosed error in compileModuleAndReadAST");
1964 bool IsInclusionDirective) {
1966 StringRef ModuleName = Path[0].first->getName();
1972 if (ImportLoc.
isValid() && LastModuleImportLoc == ImportLoc) {
1974 if (LastModuleImportResult && ModuleName !=
getLangOpts().CurrentModule)
1975 TheASTReader->makeModuleVisible(LastModuleImportResult,
Visibility,
1977 return LastModuleImportResult;
1986 }
else if (ModuleName ==
getLangOpts().CurrentModule) {
1989 ModuleName, ImportLoc,
true,
1990 !IsInclusionDirective);
1995 ModuleName, ImportLoc, ModuleNameLoc, IsInclusionDirective);
1999 DisableGeneratingGlobalModuleIndex =
true;
2011 bool MapPrivateSubModToTopLevel =
false;
2012 for (
unsigned I = 1, N = Path.size(); I != N; ++I) {
2013 StringRef Name = Path[I].first->getName();
2022 PrivateModule.append(
"_Private");
2027 PrivPath.push_back(std::make_pair(&II, Path[0].second));
2030 !IsInclusionDirective))
2033 MapPrivateSubModToTopLevel =
true;
2036 diag::warn_no_priv_submodule_use_toplevel, ImportLoc)) {
2038 diag::warn_no_priv_submodule_use_toplevel)
2044 diag::note_private_top_level_defined);
2052 unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)();
2056 Name.edit_distance(SubModule->Name,
2057 true, BestEditDistance);
2058 if (ED <= BestEditDistance) {
2059 if (ED < BestEditDistance) {
2061 BestEditDistance = ED;
2064 Best.push_back(SubModule->Name);
2069 if (Best.size() == 1) {
2072 <<
SourceRange(Path[0].second, Path[I - 1].second)
2085 <<
SourceRange(Path[0].second, Path[I - 1].second);
2104 <<
SourceRange(Path.front().second, Path.back().second);
2113 <<
SourceRange(Path.front().second, Path.back().second);
2114 LastModuleImportLoc = ImportLoc;
2124 for (
unsigned I = 0, N = TopModule->
ConfigMacros.size(); I != N; ++I) {
2135 LastModuleImportLoc = ImportLoc;
2137 return LastModuleImportResult;
2141 StringRef ModuleName,
2145 for (
auto &
C : CleanModuleName)
2153 if (std::error_code EC = llvm::sys::fs::createTemporaryFile(
2154 CleanModuleName,
"pcm", ModuleFileName)) {
2156 << ModuleFileName << EC.message();
2159 std::string ModuleMapFileName = (CleanModuleName +
".map").str();
2166 std::string NullTerminatedSource(Source.str());
2171 const FileEntry *ModuleMapFile = Other.getFileManager().getVirtualFile(
2172 ModuleMapFileName, NullTerminatedSource.size(), 0);
2173 Other.getSourceManager().overrideFileContents(
2174 ModuleMapFile, llvm::MemoryBuffer::getMemBuffer(NullTerminatedSource));
2176 Other.BuiltModules = std::move(BuiltModules);
2177 Other.DeleteBuiltModules =
false;
2181 BuiltModules = std::move(Other.BuiltModules);
2186 ModuleFileName, PreBuildStep, PostBuildStep)) {
2187 BuiltModules[std::string(ModuleName)] = std::string(ModuleFileName.str());
2188 llvm::sys::RemoveFileOnSignal(ModuleFileName);
2200 TheASTReader->makeModuleVisible(Mod,
Visibility, ImportLoc);
2205 if (
getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty())
2214 TheASTReader->loadGlobalIndex();
2219 llvm::sys::fs::create_directories(
2228 consumeError(std::move(Err));
2231 TheASTReader->resetForReload();
2232 TheASTReader->loadGlobalIndex();
2233 GlobalIndex = TheASTReader->getGlobalIndex();
2237 if (!HaveFullGlobalModuleIndex && GlobalIndex && !
buildingModule()) {
2239 bool RecreateIndex =
false;
2242 Module *TheModule = I->second;
2246 Path.push_back(std::make_pair(
2248 std::reverse(Path.begin(), Path.end());
2251 RecreateIndex =
true;
2254 if (RecreateIndex) {
2259 consumeError(std::move(Err));
2262 TheASTReader->resetForReload();
2263 TheASTReader->loadGlobalIndex();
2264 GlobalIndex = TheASTReader->getGlobalIndex();
2266 HaveFullGlobalModuleIndex =
true;
2300 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 compileModuleImpl(CompilerInstance &ImportingInstance, SourceLocation ImportLoc, StringRef ModuleName, FrontendInputFile Input, StringRef OriginalModuleMapFile, StringRef ModuleFileName, llvm::function_ref< void(CompilerInstance &)> PreBuildStep=[](CompilerInstance &) {}, llvm::function_ref< void(CompilerInstance &)> PostBuildStep=[](CompilerInstance &) {})
Compile a module file for the given module, using the options provided by the importing compiler inst...
static bool EnableCodeCompletion(Preprocessor &PP, StringRef Filename, unsigned Line, unsigned Column)
static void pruneModuleCache(const HeaderSearchOptions &HSOpts)
Prune the module cache of modules that haven't been accessed in a long time.
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 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 bool readASTAfterCompileModule(CompilerInstance &ImportingInstance, SourceLocation ImportLoc, SourceLocation ModuleNameLoc, Module *Module, StringRef ModuleFileName, bool *OutOfDate)
Read the AST right after compiling the module.
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 void SetUpDiagnosticLog(DiagnosticOptions *DiagOpts, const CodeGenOptions *CodeGenOpts, DiagnosticsEngine &Diags)
static void writeTimestampFile(StringRef TimestampFile)
Write a new timestamp file with the given path.
static void InitializeFileRemapping(DiagnosticsEngine &Diags, SourceManager &SourceMgr, FileManager &FileMgr, const PreprocessorOptions &InitOpts)
static bool compileModule(CompilerInstance &ImportingInstance, SourceLocation ImportLoc, Module *Module, StringRef ModuleFileName)
Compile a module file for the given module in a separate compiler instance, using the options provide...
static void SetupSerializedDiagnostics(DiagnosticOptions *DiagOpts, DiagnosticsEngine &Diags, StringRef OutputFile)
static void collectIncludePCH(CompilerInstance &CI, std::shared_ptr< ModuleDependencyCollector > MDC)
static OptionalFileEntryRef getPublicModuleMap(FileEntryRef File, FileManager &FileMgr)
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...
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.
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.
Abstract interface for callback invocations by the ASTReader.
RAII object to temporarily add an AST callback listener.
Reads an AST files chain containing the contents of a translation unit.
@ 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 InMemoryModuleCache &ModuleCache, const PCHContainerReader &PCHContainerRdr, bool FindModuleFileExtensions, ASTReaderListener &Listener, bool ValidateDiagnosticOptions)
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.
void setFileManager(FileManager *Value)
Replace the current file manager and virtual file system.
void setSourceManager(SourceManager *Value)
setSourceManager - Replace the current source manager.
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 createSourceManager(FileManager &FileMgr)
Create the source manager and replace any existing one with it.
void createDiagnostics(DiagnosticConsumer *Client=nullptr, bool ShouldOwnClient=true)
Create the diagnostics engine using the invocation's diagnostic options and replace any existing one ...
FileManager * createFileManager(IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS=nullptr)
Create the file manager and replace any existing one with it.
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)
std::string getSpecificModuleCachePath()
ModuleLoadResult loadModule(SourceLocation ImportLoc, ModuleIdPath Path, Module::NameVisibilityKind Visibility, bool IsInclusionDirective) override
Attempt to load the given module.
void setInvocation(std::shared_ptr< CompilerInvocation > Value)
setInvocation - Replace the current invocation.
FileSystemOptions & getFileSystemOpts()
bool InitializeSourceManager(const FrontendInputFile &Input)
InitializeSourceManager - Initialize the source manager to set InputFile as the main file.
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.
std::unique_ptr< Sema > takeSema()
bool loadModuleFile(StringRef FileName)
void setASTConsumer(std::unique_ptr< ASTConsumer > Value)
setASTConsumer - Replace the current AST consumer; the compiler instance takes ownership of Value.
PreprocessorOutputOptions & getPreprocessorOutputOpts()
IntrusiveRefCntPtr< ASTReader > getASTReader() const
void setTarget(TargetInfo *Value)
Replace the current Target.
void setModuleDepCollector(std::shared_ptr< ModuleDependencyCollector > Collector)
InMemoryModuleCache & getModuleCache() const
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.
std::shared_ptr< HeaderSearchOptions > getHeaderSearchOptsPtr() const
void setASTContext(ASTContext *Value)
setASTContext - Replace the current AST context.
Preprocessor & getPreprocessor() const
Return the current preprocessor.
ASTContext & getASTContext() const
void LoadRequestedPlugins()
Load the list of plugins requested in the FrontendOptions.
TargetOptions & getTargetOpts()
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.
HeaderSearchOptions & getHeaderSearchOpts()
void createFrontendTimer()
Create the frontend timer and replace any existing one with it.
void setDiagnostics(DiagnosticsEngine *Value)
setDiagnostics - Replace the current diagnostics engine.
CompilerInvocation & getInvocation()
void setVerboseOutputStream(raw_ostream &Value)
Replace the current stream for verbose output.
PreprocessorOptions & getPreprocessorOpts()
ASTConsumer & getASTConsumer() const
TargetInfo & getTarget() const
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()
CodeGenOptions & getCodeGenOpts()
SourceManager & getSourceManager() const
Return the current source manager.
bool shouldBuildGlobalModuleIndex() const
Indicates whether we should (re)build the global module index.
bool hasSourceManager() const
bool hasASTConsumer() const
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 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.
PreprocessorOptions & getPreprocessorOpts()
LangOptions * getLangOpts()
FrontendOptions & getFrontendOpts()
Helper class for holding the data necessary to invoke the compiler.
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
Used for handling and querying diagnostic IDs.
Options for controlling the compiler diagnostics engine.
std::string DiagnosticLogFile
The file to log diagnostic output to.
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.
Cached information about one file (either on disk or in the virtual file system).
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.
llvm::vfs::FileSystem & getVirtualFileSystem() const
OptionalFileEntryRef getOptionalFileRef(StringRef Filename, bool OpenFile=false, bool CacheFailure=true)
Get a FileEntryRef if it exists, without doing anything on error.
llvm::Expected< FileEntryRef > getSTDIN()
Get the FileEntryRef for stdin, returning an error if stdin cannot be read.
const FileEntry * getVirtualFile(StringRef Filename, off_t Size, time_t ModificationTime)
llvm::ErrorOr< const FileEntry * > getFile(StringRef Filename, bool OpenFile=false, bool CacheFailure=true)
Lookup, cache, and verify the specified file (real or virtual).
OptionalDirectoryEntryRef getOptionalDirectoryRef(StringRef DirName, bool CacheFailure=true)
Get a DirectoryEntryRef if it exists, without doing anything on error.
llvm::Expected< FileEntryRef > getFileRef(StringRef Filename, bool OpenFile=false, bool CacheFailure=true)
Lookup, cache, and verify the specified file (real or virtual).
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Diagnostic consumer that forwards diagnostics along to an existing, already-initialized diagnostic co...
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 SourceLocation and its associated SourceManager.
A global index for a set of module files, providing information about the identifiers within those mo...
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.
tok::TokenKind getTokenID() const
If this is a source-language token (e.g.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
In-memory cache for modules.
bool isPCMFinal(llvm::StringRef Filename) const
Check whether the PCM is final and has been shown to work.
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.
@ FPE_Default
Used internally to represent initial unspecified value.
@ FPE_Ignore
Assume that floating-point exceptions are masked.
Encapsulates the data about a macro definition (e.g.
Describes the result of attempting to load a module.
Abstract interface for a module loader.
bool buildingModule() const
Returns true if this instance is building a module.
llvm::StringMap< Module * >::const_iterator module_iterator
OptionalFileEntryRef getContainingModuleMapFile(const Module *Module) const
Retrieve the module map file containing the definition of the given module.
Module * findModule(StringRef Name) const
Retrieve a module with the given name.
module_iterator module_begin() const
OptionalFileEntryRef getModuleMapFileForUniquing(const Module *M) const
Get the module map file that (along with the module name) uniquely identifies this module.
std::optional< Module * > getCachedModuleLoad(const IdentifierInfo &II)
Return a cached module load.
module_iterator module_end() const
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.
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...
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()
const DirectoryEntry * Directory
The build directory of this module.
unsigned IsFromModuleFile
Whether this module was loaded from a module file.
OptionalFileEntryRefDegradesToFileEntryPtr getASTFile() const
The serialized AST file for this module, if one was created.
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.
Module * getTopLevelModule()
Retrieve the top-level module for this (sub)module, which may be this module.
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...
void resetNonModularOptions()
Reset any options that are not considered when building a module.
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::shared_ptr< FailedModulesSet > FailedModules
The set of modules that failed to build.
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.
void markClangModuleAsAffecting(Module *M)
Mark the given clang module as affecting the current clang module or translation unit.
bool SetCodeCompletionPoint(const FileEntry *File, unsigned Line, unsigned Column)
Specify the point at which code-completion will be performed.
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.
const TranslationUnitKind TUKind
The kind of translation unit we are processing.
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
SourceManager & getSourceManager() const
FileManager & getFileManager() const
FileID getPredefinesFileID() const
Returns the FileID for the preprocessor predefines.
static bool checkModuleIsAvailable(const LangOptions &LangOpts, const TargetInfo &TargetInfo, DiagnosticsEngine &Diags, Module *M)
Check that the given module is available, producing a diagnostic if not.
HeaderSearch & getHeaderSearchInfo() const
void setPredefines(std::string P)
Set the predefines for this Preprocessor.
IdentifierTable & getIdentifierTable()
Builtin::Context & getBuiltinInfo()
DiagnosticsEngine & getDiagnostics() const
SelectorTable & getSelectorTable()
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.
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
void setModuleBuildStack(ModuleBuildStack stack)
Set the module build stack.
void overrideFileContents(const FileEntry *SourceFile, const llvm::MemoryBufferRef &Buffer)
Override the contents of the given source file by providing an already-allocated buffer.
void setOverridenFilesKeepOriginalName(bool value)
Set true if the SourceManager should report the original file name for contents of files that were ov...
ModuleBuildStack getModuleBuildStack() const
Retrieve the module build stack.
FileID getMainFileID() const
Returns the FileID of the main source file.
void pushModuleBuildStack(StringRef moduleName, FullSourceLoc importLoc)
Push an entry to the module build stack.
FileID createFileID(const FileEntry *SourceFile, SourceLocation IncludePos, SrcMgr::CharacteristicKind FileCharacter, int LoadedID=0, SourceLocation::UIntTy LoadedOffset=0)
Create a new FileID that represents the specified file being #included from the specified IncludePosi...
void setMainFileID(FileID FID)
Set the file ID for the main source file.
A trivial tuple used to represent a source range.
Exposes information about the current target.
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
virtual void adjustTargetOptions(const CodeGenOptions &CGOpts, TargetOptions &TargetOpts) const
Adjust target options based on codegen options.
static TargetInfo * CreateTargetInfo(DiagnosticsEngine &Diags, const std::shared_ptr< TargetOptions > &Opts)
Construct a target for the given options.
virtual void setAuxTarget(const TargetInfo *Aux)
void noSignedCharForObjCBool()
virtual void adjust(DiagnosticsEngine &Diags, LangOptions &Opts)
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...
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 *Diags, bool MergeChildRecords=false)
Returns a DiagnosticConsumer that serializes diagnostics to a bitcode file.
void ProcessWarningOptions(DiagnosticsEngine &Diags, const DiagnosticOptions &Opts, bool ReportDiags=true)
ProcessWarningOptions - Initialize the diagnostic client and process the warning options specified on...
void ApplyHeaderSearchOptions(HeaderSearch &HS, const HeaderSearchOptions &HSOpts, const LangOptions &Lang, const llvm::Triple &triple)
Apply the header search options to get given HeaderSearch object.
void noteBottomOfStack()
Call this once on each thread, as soon after starting the thread as feasible, to note the approximate...
std::error_code make_error_code(BuildPreambleError Error)
LLVM_READONLY bool isAlphanumeric(unsigned char c)
Return true if this character is an ASCII letter or digit: [a-zA-Z0-9].
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)
constexpr size_t DesiredStackSize
The amount of stack space that Clang would like to be provided with.
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...
void InitializePreprocessor(Preprocessor &PP, const PreprocessorOptions &PPOpts, const PCHContainerReader &PCHContainerRdr, const FrontendOptions &FEOpts)
InitializePreprocessor - Initialize the preprocessor getting it and the environment ready to process ...
DisableValidationForModuleKind
Whether to disable the normal validation performed on precompiled headers and module files when they ...
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.