23#include "clang/Config/config.h"
46#include "llvm/ADT/IntrusiveRefCntPtr.h"
47#include "llvm/ADT/STLExtras.h"
48#include "llvm/ADT/ScopeExit.h"
49#include "llvm/ADT/Statistic.h"
50#include "llvm/Config/llvm-config.h"
51#include "llvm/Plugins/PassPlugin.h"
52#include "llvm/Support/AdvisoryLock.h"
53#include "llvm/Support/BuryPointer.h"
54#include "llvm/Support/CrashRecoveryContext.h"
55#include "llvm/Support/Errc.h"
56#include "llvm/Support/FileSystem.h"
57#include "llvm/Support/MemoryBuffer.h"
58#include "llvm/Support/Path.h"
59#include "llvm/Support/Signals.h"
60#include "llvm/Support/SmallVectorMemoryBuffer.h"
61#include "llvm/Support/TimeProfiler.h"
62#include "llvm/Support/Timer.h"
63#include "llvm/Support/VirtualFileSystem.h"
64#include "llvm/Support/VirtualOutputBackends.h"
65#include "llvm/Support/VirtualOutputError.h"
66#include "llvm/Support/raw_ostream.h"
67#include "llvm/TargetParser/Host.h"
74CompilerInstance::CompilerInstance(
75 std::shared_ptr<CompilerInvocation> Invocation,
76 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
77 std::shared_ptr<ModuleCache> ModCache)
79 Invocation(
std::move(Invocation)),
80 ModCache(ModCache ?
std::move(ModCache)
82 ThePCHContainerOperations(
std::move(PCHContainerOps)) {
83 assert(this->Invocation &&
"Invocation must not be null");
87 assert(OutputFiles.empty() &&
"Still output files in flight?");
91 return (BuildGlobalModuleIndex ||
92 (TheASTReader && TheASTReader->isGlobalIndexUnavailable() &&
94 !DisableGeneratingGlobalModuleIndex;
99 Diagnostics = std::move(
Value);
103 OwnedVerboseOutputStream.reset();
104 VerboseOutputStream = &
Value;
108 OwnedVerboseOutputStream.swap(
Value);
109 VerboseOutputStream = OwnedVerboseOutputStream.get();
127 auto &TO = AuxTargetOpts = std::make_unique<TargetOptions>();
168 assert(
Value ==
nullptr ||
170 FileMgr = std::move(
Value);
175 SourceMgr = std::move(
Value);
179 PP = std::move(
Value);
184 Context = std::move(
Value);
186 if (Context && Consumer)
195 Consumer = std::move(
Value);
197 if (Context && Consumer)
202 CompletionConsumer.reset(
Value);
206 return std::move(TheSema);
213 assert(ModCache.get() == &Reader->getModuleManager().getModuleCache() &&
214 "Expected ASTReader to use the same PCM cache");
215 TheASTReader = std::move(Reader);
218std::shared_ptr<ModuleDependencyCollector>
220 return ModuleDepCollector;
224 std::shared_ptr<ModuleDependencyCollector> Collector) {
225 ModuleDepCollector = std::move(Collector);
229 std::shared_ptr<ModuleDependencyCollector> MDC) {
232 for (
auto &Name : HeaderMapFileNames)
237 std::shared_ptr<ModuleDependencyCollector> MDC) {
244 auto PCHDir =
FileMgr.getOptionalDirectoryRef(PCHInclude);
246 MDC->addFile(PCHInclude);
252 llvm::sys::path::native(PCHDir->getName(), DirNative);
253 llvm::vfs::FileSystem &FS =
FileMgr.getVirtualFileSystem();
255 for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
256 Dir != DirEnd && !EC; Dir.increment(EC)) {
265 MDC->addFile(Dir->path());
270 std::shared_ptr<ModuleDependencyCollector> MDC) {
274 if (
auto *RedirectingVFS = dyn_cast<llvm::vfs::RedirectingFileSystem>(&VFS))
275 llvm::vfs::collectVFSEntries(*RedirectingVFS, VFSEntries);
278 for (
auto &E : VFSEntries)
279 MDC->addFile(E.VPath, E.RPath);
293 llvm::makeIntrusiveRefCnt<llvm::vfs::TracingFileSystem>(std::move(VFS));
301 std::unique_ptr<raw_ostream> StreamOwner;
302 raw_ostream *OS = &llvm::errs();
305 auto FileOS = std::make_unique<llvm::raw_fd_ostream>(
307 llvm::sys::fs::OF_Append | llvm::sys::fs::OF_TextWithCRLF);
309 Diags.
Report(diag::warn_fe_cc_log_diagnostics_failure)
312 FileOS->SetUnbuffered();
314 StreamOwner = std::move(FileOS);
319 auto Logger = std::make_unique<LogDiagnosticPrinter>(*OS, DiagOpts,
320 std::move(StreamOwner));
334 StringRef OutputFile) {
335 auto SerializedConsumer =
340 Diags.
takeClient(), std::move(SerializedConsumer)));
343 Diags.
getClient(), std::move(SerializedConsumer)));
348 bool ShouldOwnClient) {
357 auto Diags = llvm::makeIntrusiveRefCnt<DiagnosticsEngine>(
363 Diags->setClient(Client, ShouldOwnClient);
370 if (Opts.VerifyDiagnostics)
389 assert(VFS &&
"CompilerInstance needs a VFS for creating FileManager");
396 assert(Diagnostics &&
"DiagnosticsEngine needed for creating SourceManager");
397 assert(FileMgr &&
"FileManager needed for creating SourceManager");
398 SourceMgr = llvm::makeIntrusiveRefCnt<SourceManager>(
getDiagnostics(),
412 FileMgr.getVirtualFileRef(RB.first, RB.second->getBufferSize(), 0);
419 SourceMgr.overrideFileContents(FromFile, RB.second->getMemBufferRef());
421 SourceMgr.overrideFileContents(
422 FromFile, std::unique_ptr<llvm::MemoryBuffer>(RB.second));
430 Diags.
Report(diag::err_fe_remap_missing_to_file) << RF.first << RF.second;
440 SourceMgr.overrideFileContents(FromFile, *ToFile);
443 SourceMgr.setOverridenFilesKeepOriginalName(
453 TheASTReader.reset();
459 PP = std::make_shared<Preprocessor>(Invocation->getPreprocessorOpts(),
468 PP->createPreprocessingRecord();
472 PP->getFileManager(), PPOpts);
481 const llvm::Triple *HeaderSearchTriple = &PP->getTargetInfo().getTriple();
482 if (PP->getTargetInfo().getTriple().getOS() == llvm::Triple::CUDA &&
483 PP->getAuxTargetInfo())
484 HeaderSearchTriple = &PP->getAuxTargetInfo()->getTriple();
487 PP->getLangOpts(), *HeaderSearchTriple);
491 if (PP->getLangOpts().Modules && PP->getLangOpts().ImplicitModules) {
495 PP->getHeaderSearchInfo().initializeModuleCachePath(
510 ModuleDepCollector = std::make_shared<ModuleDependencyCollector>(
516 if (ModuleDepCollector) {
527 for (
auto &Listener : DependencyCollectors)
528 Listener->attachToPreprocessor(*PP);
535 if (OutputPath ==
"-")
548 if (GetDependencyDirectives)
549 PP->setDependencyDirectivesGetter(*GetDependencyDirectives);
556 auto Context = llvm::makeIntrusiveRefCnt<ASTContext>(
557 getLangOpts(), PP.getSourceManager(), PP.getIdentifierTable(),
558 PP.getSelectorTable(), PP.getBuiltinInfo(), PP.TUKind);
575 void ReadModuleName(StringRef ModuleName)
override {
578 LoadedModules.push_back(ModuleName.str());
583 for (
const std::string &LoadedModule : LoadedModules)
586 LoadedModules.clear();
589 void markAllUnavailable() {
590 for (
const std::string &LoadedModule : LoadedModules) {
593 M->HasIncompatibleModuleFile =
true;
597 SmallVector<Module *, 2> Stack;
599 while (!Stack.empty()) {
600 Module *Current = Stack.pop_back_val();
604 llvm::append_range(Stack, SubmodulesRange);
608 LoadedModules.clear();
615 bool AllowPCHWithCompilerErrors,
void *DeserializationListener,
616 bool OwnDeserializationListener) {
623 DeserializationListener, OwnDeserializationListener,
Preamble,
628 StringRef Path, StringRef Sysroot,
633 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
634 ArrayRef<std::shared_ptr<DependencyCollector>> DependencyCollectors,
635 void *DeserializationListener,
bool OwnDeserializationListener,
636 bool Preamble,
bool UseGlobalModuleIndex) {
638 PP.getHeaderSearchInfo().getHeaderSearchOpts();
640 auto Reader = llvm::makeIntrusiveRefCnt<ASTReader>(
641 PP, ModCache, &Context, PCHContainerRdr, CodeGenOpts, Extensions,
642 Sysroot.empty() ?
"" : Sysroot.data(), DisableValidation,
643 AllowPCHWithCompilerErrors,
false,
650 Context.setExternalSource(Reader);
652 Reader->setDeserializationListener(
654 OwnDeserializationListener);
656 for (
auto &Listener : DependencyCollectors)
657 Listener->attachToASTReader(*Reader);
659 auto Listener = std::make_unique<ReadModuleNames>(PP);
660 auto &ListenerRef = *Listener;
662 std::move(Listener));
671 PP.setPredefines(Reader->getSuggestedPredefines());
672 ListenerRef.registerAll();
688 ListenerRef.markAllUnavailable();
689 Context.setExternalSource(
nullptr);
715 if (!CompletionConsumer) {
728 timerGroup.reset(
new llvm::TimerGroup(
"clang",
"Clang time report"));
729 FrontendTimer.reset(
new llvm::Timer(
"frontend",
"Front end", *timerGroup));
749 TUKind, CompletionConsumer));
755 if (ExternalSemaSrc) {
756 TheSema->addExternalSource(ExternalSemaSrc);
757 ExternalSemaSrc->InitializeSema(*TheSema);
763 (void)TheSema->APINotes.loadCurrentModuleAPINotes(
775 for (
auto &O : OutputFiles)
776 llvm::handleAllErrors(
778 [&](
const llvm::vfs::TempFileOutputError &E) {
779 getDiagnostics().Report(diag::err_unable_to_rename_temp)
780 << E.getTempPath() << E.getOutputPath()
781 << E.convertToErrorCode().message();
783 [&](
const llvm::vfs::OutputError &E) {
784 getDiagnostics().Report(diag::err_fe_unable_to_open_output)
785 << E.getOutputPath() << E.convertToErrorCode().message();
787 [&](
const llvm::ErrorInfoBase &EIB) {
788 getDiagnostics().Report(diag::err_fe_unable_to_open_output)
789 << O.getPath() << EIB.message();
793 if (DeleteBuiltModules) {
794 for (
auto &
Module : BuiltModules)
795 llvm::sys::fs::remove(
Module.second);
796 BuiltModules.clear();
801 bool Binary, StringRef InFile, StringRef Extension,
bool RemoveFileOnSignal,
802 bool CreateMissingDirectories,
bool ForceUseTemporary) {
804 std::optional<SmallString<128>> PathStorage;
805 if (OutputPath.empty()) {
806 if (InFile ==
"-" || Extension.empty()) {
809 PathStorage.emplace(InFile);
810 llvm::sys::path::replace_extension(*PathStorage, Extension);
811 OutputPath = *PathStorage;
817 CreateMissingDirectories);
821 return std::make_unique<llvm::raw_null_ostream>();
828 assert(!OutputMgr &&
"Already has an output manager");
829 OutputMgr = std::move(NewOutputs);
833 assert(!OutputMgr &&
"Already has an output manager");
834 OutputMgr = llvm::makeIntrusiveRefCnt<llvm::vfs::OnDiskOutputBackend>();
848std::unique_ptr<raw_pwrite_stream>
850 bool RemoveFileOnSignal,
bool UseTemporary,
851 bool CreateMissingDirectories) {
853 createOutputFileImpl(OutputPath,
Binary, RemoveFileOnSignal, UseTemporary,
854 CreateMissingDirectories);
856 return std::move(*OS);
858 << OutputPath << errorToErrorCode(OS.takeError()).message();
863CompilerInstance::createOutputFileImpl(StringRef OutputPath,
bool Binary,
864 bool RemoveFileOnSignal,
866 bool CreateMissingDirectories) {
867 assert((!CreateMissingDirectories || UseTemporary) &&
868 "CreateMissingDirectories is only allowed when using temporary files");
872 std::optional<SmallString<128>> AbsPath;
873 if (OutputPath !=
"-" && !llvm::sys::path::is_absolute(OutputPath)) {
875 "File Manager is required to fix up relative path.\n");
877 AbsPath.emplace(OutputPath);
879 OutputPath = *AbsPath;
887 .setDiscardOnSignal(RemoveFileOnSignal)
888 .setAtomicWrite(UseTemporary)
889 .setImplyCreateDirectories(UseTemporary && CreateMissingDirectories));
891 return O.takeError();
893 O->discardOnDestroy([](llvm::Error E) { consumeError(std::move(E)); });
894 OutputFiles.push_back(std::move(*O));
895 return OutputFiles.back().createProxy();
917 SourceMgr.setMainFileID(SourceMgr.createFileID(Input.
getBuffer(), Kind));
918 assert(SourceMgr.getMainFileID().isValid() &&
919 "Couldn't establish MainFileID!");
923 StringRef InputFile = Input.
getFile();
926 auto FileOrErr = InputFile ==
"-"
928 : FileMgr.getFileRef(InputFile,
true);
930 auto EC = llvm::errorToErrorCode(FileOrErr.takeError());
931 if (InputFile !=
"-")
932 Diags.
Report(diag::err_fe_error_reading) << InputFile << EC.message();
934 Diags.
Report(diag::err_fe_error_reading_stdin) << EC.message();
938 SourceMgr.setMainFileID(
941 assert(SourceMgr.getMainFileID().isValid() &&
942 "Couldn't establish MainFileID!");
948void CompilerInstance::PrepareForExecution() {
965 assert(
hasDiagnostics() &&
"Diagnostics engine is not initialized!");
967 assert(!
getFrontendOpts().ShowVersion &&
"Client must handle '-version'!");
969 llvm::TimeTraceScope TimeScope(
"ExecuteCompiler");
971 PrepareForExecution();
992 OS <<
"clang -cc1 version " CLANG_VERSION_STRING <<
" based upon LLVM "
993 << LLVM_VERSION_STRING <<
" default target "
994 << llvm::sys::getDefaultTargetTriple() <<
"\n";
997 llvm::EnableStatistics(
false);
1010 ModuleImportResults.clear();
1013 if (llvm::Error Err = Act.
Execute()) {
1014 consumeError(std::move(Err));
1027 llvm::PrintStatistics(OS);
1030 if (!StatsFile.empty()) {
1031 llvm::sys::fs::OpenFlags FileFlags = llvm::sys::fs::OF_TextWithCRLF;
1033 FileFlags |= llvm::sys::fs::OF_Append;
1036 std::make_unique<llvm::raw_fd_ostream>(StatsFile, EC, FileFlags);
1039 << StatsFile << EC.message();
1041 llvm::PrintStatisticsJSON(*StatS);
1060 OS << NumWarnings <<
" warning" << (NumWarnings == 1 ?
"" :
"s");
1061 if (NumWarnings && NumErrors)
1064 OS << NumErrors <<
" error" << (NumErrors == 1 ?
"" :
"s");
1065 if (NumWarnings || NumErrors) {
1069 OS <<
" when compiling for host";
1071 OS <<
" when compiling for "
1084 if (llvm::sys::DynamicLibrary::LoadLibraryPermanently(Path.c_str(), &
Error))
1091 if (
auto PassPlugin = llvm::PassPlugin::Load(Path)) {
1092 PassPlugins.emplace_back(std::make_unique<llvm::PassPlugin>(*PassPlugin));
1095 << Path <<
toString(PassPlugin.takeError());
1100 for (
const FrontendPluginRegistry::entry &Plugin :
1101 FrontendPluginRegistry::entries()) {
1102 std::unique_ptr<PluginASTAction> P(Plugin.instantiate());
1114 if (LangOpts.OpenCL)
1123std::unique_ptr<CompilerInstance> CompilerInstance::cloneForModuleCompileImpl(
1126 std::optional<ThreadSafeCloneConfig> ThreadSafeConfig) {
1128 auto Invocation = std::make_shared<CompilerInvocation>(
getInvocation());
1130 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
1134 Invocation->resetNonModularOptions();
1138 HeaderSearchOptions &HSOpts = Invocation->getHeaderSearchOpts();
1139 llvm::erase_if(PPOpts.
Macros,
1140 [&HSOpts](
const std::pair<std::string, bool> &def) {
1141 StringRef MacroDef = def.first;
1142 return HSOpts.ModulesIgnoreMacros.contains(
1143 llvm::CachedHashString(MacroDef.split(
'=').first));
1147 Invocation->getLangOpts().ModuleName =
1151 Invocation->getLangOpts().CurrentModule = std::string(ModuleName);
1156 FrontendOptions &FrontendOpts = Invocation->getFrontendOpts();
1157 FrontendOpts.
OutputFile = ModuleFileName.str();
1164 FrontendOpts.
Inputs = {std::move(Input)};
1169 DiagnosticOptions &DiagOpts = Invocation->getDiagnosticOpts();
1171 DiagOpts.VerifyDiagnostics = 0;
1174 "Module hash mismatch!");
1176 std::shared_ptr<ModuleCache> ModCache;
1177 if (ThreadSafeConfig) {
1178 ModCache = ThreadSafeConfig->getModuleCache();
1180 ModCache = this->ModCache;
1184 auto InstancePtr = std::make_unique<CompilerInstance>(
1186 auto &Instance = *InstancePtr;
1188 auto &
Inv = Instance.getInvocation();
1190 if (ThreadSafeConfig) {
1191 Instance.setVirtualFileSystem(ThreadSafeConfig->getVFS());
1192 Instance.createFileManager();
1198 Instance.createFileManager();
1201 if (ThreadSafeConfig) {
1202 Instance.createDiagnostics(&ThreadSafeConfig->getDiagConsumer(),
1205 Instance.createDiagnostics(
1210 Instance.getDiagnostics().setSuppressSystemWarnings(
false);
1212 Instance.createSourceManager();
1213 SourceManager &SourceMgr = Instance.getSourceManager();
1215 if (ThreadSafeConfig) {
1221 SourceMgr.pushModuleBuildStack(
1226 Instance.FailedModules = FailedModules;
1231 if (GetDependencyDirectives)
1232 Instance.GetDependencyDirectives =
1233 GetDependencyDirectives->cloneFor(Instance.getFileManager());
1235 if (ThreadSafeConfig) {
1236 Instance.setModuleDepCollector(ThreadSafeConfig->getModuleDepCollector());
1243 Inv.getDependencyOutputOpts() = DependencyOutputOptions();
1249class PrettyStackTraceBuildModule :
public llvm::PrettyStackTraceEntry {
1250 StringRef ModuleName;
1251 StringRef ModuleFileName;
1254 PrettyStackTraceBuildModule(StringRef ModuleName, StringRef ModuleFileName)
1255 : ModuleName(ModuleName), ModuleFileName(ModuleFileName) {}
1256 void print(raw_ostream &OS)
const override {
1257 OS <<
"Building module '" << ModuleName <<
"' as '" << ModuleFileName
1263std::unique_ptr<llvm::MemoryBuffer>
1266 CompilerInstance &Instance) {
1267 PrettyStackTraceBuildModule CrashInfo(ModuleName,
ModuleFileName);
1268 llvm::TimeTraceScope TimeScope(
"Module Compile", ModuleName);
1285 bool Crashed = !llvm::CrashRecoveryContext().RunSafelyOnNewStack(
1287 auto OS = std::make_unique<llvm::raw_svector_ostream>(Buffer);
1289 std::unique_ptr<FrontendAction> Action =
1290 std::make_unique<GenerateModuleFromModuleMapAction>(std::move(OS));
1292 if (
auto WrapGenModuleAction = Instance.getGenModuleActionWrapper())
1293 Action = WrapGenModuleAction(Instance.getFrontendOpts(),
1296 Instance.ExecuteAction(*Action);
1308 FailedModules = std::move(Instance.FailedModules);
1313 Instance.setSema(
nullptr);
1314 Instance.setASTConsumer(
nullptr);
1317 Instance.clearOutputFiles(
true);
1331 if (Instance.getDiagnostics().hasErrorOccurred() &&
1332 !Instance.getFrontendOpts().AllowPCMWithCompilerErrors)
1335 return std::make_unique<llvm::SmallVectorMemoryBuffer>(
1336 std::move(Buffer), Instance.getFrontendOpts().OutputFile);
1341 StringRef Filename = llvm::sys::path::filename(
File.getName());
1343 if (Filename ==
"module_private.map")
1344 llvm::sys::path::append(PublicFilename,
"module.map");
1345 else if (Filename ==
"module.private.modulemap")
1346 llvm::sys::path::append(PublicFilename,
"module.modulemap");
1348 return std::nullopt;
1349 return FileMgr.getOptionalFileRef(PublicFilename);
1354 std::optional<ThreadSafeCloneConfig> ThreadSafeConfig) {
1370 while (Loc.
isValid() && isModuleMap(SourceMgr.getFileCharacteristic(Loc))) {
1371 ModuleMapFID = SourceMgr.getFileID(Loc);
1372 Loc = SourceMgr.getIncludeLoc(ModuleMapFID);
1376 SourceMgr.getFileEntryRefForID(ModuleMapFID);
1377 assert(ModuleMapFile &&
"Top-level module map with no FileID");
1384 ModuleMapFile = PublicMMFile;
1396 return cloneForModuleCompileImpl(
1397 ImportLoc, ModuleName,
1400 std::move(ThreadSafeConfig));
1408 llvm::sys::path::append(FakeModuleMapFile,
"__inferred_module.map");
1410 std::string InferredModuleMapContent;
1411 llvm::raw_string_ostream OS(InferredModuleMapContent);
1414 auto Instance = cloneForModuleCompileImpl(
1415 ImportLoc, ModuleName,
1418 std::move(ThreadSafeConfig));
1420 std::unique_ptr<llvm::MemoryBuffer> ModuleMapBuffer =
1421 llvm::MemoryBuffer::getMemBufferCopy(InferredModuleMapContent);
1422 FileEntryRef ModuleMapFile = Instance->getFileManager().getVirtualFileRef(
1423 FakeModuleMapFile, InferredModuleMapContent.size(), 0);
1424 Instance->getSourceManager().overrideFileContents(ModuleMapFile,
1425 std::move(ModuleMapBuffer));
1437 bool *OutOfDate,
bool *Missing) {
1448 ModuleLoadCapabilities);
1478 std::unique_ptr<llvm::MemoryBuffer> Buffer;
1490 diag::err_module_not_built)
1502 diag::err_module_not_written)
1520 StringRef ExtractedBuffer = Rdr.
ExtractPCH(*Buffer);
1523 Buffer = llvm::MemoryBuffer::getMemBufferCopy(ExtractedBuffer);
1561 if (llvm::Error Err = Lock->tryLock().moveInto(Owned)) {
1584 switch (Lock->waitForUnlockFor(std::chrono::seconds(Timeout))) {
1585 case llvm::WaitForUnlockResult::Success:
1587 case llvm::WaitForUnlockResult::OwnerDied:
1589 case llvm::WaitForUnlockResult::Timeout:
1596 Lock->unsafeUnlock();
1601 bool OutOfDate =
false;
1602 bool Missing =
false;
1606 if (!OutOfDate && !Missing)
1666 for (
auto *MD = LatestLocalMD; MD; MD = MD->getPrevious()) {
1668 FileID FID = SourceMgr.getFileID(MDLoc);
1674 !SourceMgr.isWrittenInCommandLineFile(MDLoc))
1676 if (
auto *DMD = dyn_cast<DefMacroDirective>(MD))
1677 CmdLineDefinition = DMD->getMacroInfo();
1682 if (CurrentDefinition == CmdLineDefinition) {
1684 }
else if (!CurrentDefinition) {
1687 PP.
Diag(ImportLoc, diag::warn_module_config_macro_undef)
1689 auto LatestDef = LatestLocalMD->getDefinition();
1690 assert(LatestDef.isUndefined() &&
1691 "predefined macro went away with no #undef?");
1692 PP.
Diag(LatestDef.getUndefLocation(), diag::note_module_def_undef_here)
1695 }
else if (!CmdLineDefinition) {
1698 PP.
Diag(ImportLoc, diag::warn_module_config_macro_undef)
1700 PP.
Diag(CurrentDefinition->getDefinitionLoc(),
1701 diag::note_module_def_undef_here)
1703 }
else if (!CurrentDefinition->isIdenticalTo(*CmdLineDefinition, PP,
1706 PP.
Diag(ImportLoc, diag::warn_module_config_macro_undef)
1708 PP.
Diag(CurrentDefinition->getDefinitionLoc(),
1709 diag::note_module_def_undef_here)
1717 for (
const StringRef ConMacro : TopModule->
ConfigMacros) {
1733 .getHeaderSearchInfo()
1734 .getSpecificModuleCachePath()
1741 std::string Sysroot = HSOpts.
Sysroot;
1744 std::unique_ptr<llvm::Timer> ReadTimer;
1747 ReadTimer = std::make_unique<llvm::Timer>(
"reading_modules",
1748 "Reading modules", *timerGroup);
1749 TheASTReader = llvm::makeIntrusiveRefCnt<ASTReader>(
1753 Sysroot.empty() ?
"" : Sysroot.c_str(),
1762 TheASTReader->setDeserializationListener(
1769 TheASTReader->InitializeSema(
getSema());
1773 for (
auto &Listener : DependencyCollectors)
1774 Listener->attachToASTReader(*TheASTReader);
1781 Timer.init(
"preloading." + std::string(
FileName.str()),
1782 "Preloading " + std::string(
FileName.str()), *timerGroup);
1783 llvm::TimeRegion TimeLoading(timerGroup ? &Timer :
nullptr);
1791 bool ConfigMismatchIsRecoverable =
1796 auto Listener = std::make_unique<ReadModuleNames>(*PP);
1797 auto &ListenerRef = *Listener;
1799 std::move(Listener));
1802 switch (TheASTReader->ReadAST(
1805 &LoadedModuleFile)) {
1809 ListenerRef.registerAll();
1815 diag::warn_ast_file_config_mismatch)
1819 ListenerRef.markAllUnavailable();
1831 MS_PrebuiltModulePath,
1832 MS_ModuleBuildPragma
1840 const std::map<std::string, std::string, std::less<>> &BuiltModules,
1842 assert(ModuleFilename.
empty() &&
"Already has a module source?");
1846 auto BuiltModuleIt = BuiltModules.find(ModuleName);
1847 if (BuiltModuleIt != BuiltModules.end()) {
1849 return MS_ModuleBuildPragma;
1859 if (!ModuleFilename.
empty())
1860 return MS_PrebuiltModulePath;
1866 return MS_ModuleCache;
1869 return MS_ModuleNotFound;
1874 bool IsInclusionDirective) {
1878 HS.
lookupModule(ModuleName, ImportLoc,
true, !IsInclusionDirective);
1888 ModuleFileName ModuleFilename;
1889 ModuleSource Source =
1891 SourceLocation ModuleNameLoc = ModuleNameRange.
getBegin();
1892 if (Source == MS_ModuleNotFound) {
1895 << ModuleName << ModuleNameRange;
1898 if (ModuleFilename.
empty()) {
1917 Timer.init(
"loading." + std::string(ModuleFilename.
str()),
1918 "Loading " + std::string(ModuleFilename.
str()), *timerGroup);
1919 llvm::TimeRegion TimeLoading(timerGroup ? &Timer :
nullptr);
1920 llvm::TimeTraceScope TimeScope(
"Module Load", ModuleName);
1924 unsigned ARRFlags = Source == MS_ModuleCache
1927 : Source == MS_PrebuiltModulePath
1931 Source == MS_PrebuiltModulePath
1933 : Source == MS_ModuleBuildPragma
1936 ImportLoc, ARRFlags)) {
1940 assert(Source != MS_ModuleCache &&
1941 "missing module, but file loaded from cache");
1945 M = HS.
lookupModule(ModuleName, ImportLoc,
true, !IsInclusionDirective);
1950 getASTReader()->getModuleManager().makeKey(ModuleFilename))
1955 return ModuleLoadResult();
1964 if (Source == MS_PrebuiltModulePath)
1968 diag::warn_ast_file_config_mismatch)
1977 return ModuleLoadResult();
1981 return ModuleLoadResult();
1985 if (Source != MS_ModuleCache) {
1989 return ModuleLoadResult();
1993 assert(M &&
"missing module, but trying to compile for cache");
1997 ModuleBuildStack::iterator Pos = ModPath.begin(), PosEnd = ModPath.end();
1998 for (; Pos != PosEnd; ++Pos) {
1999 if (Pos->first == ModuleName)
2003 if (Pos != PosEnd) {
2004 SmallString<256> CyclePath;
2005 for (; Pos != PosEnd; ++Pos) {
2006 CyclePath += Pos->first;
2007 CyclePath +=
" -> ";
2009 CyclePath += ModuleName;
2012 << ModuleName << CyclePath;
2017 if (FailedModules.contains(ModuleName)) {
2019 << ModuleName << SourceRange(ImportLoc, ModuleNameLoc);
2027 "undiagnosed error in compileModuleAndReadAST");
2028 FailedModules.insert(ModuleName);
2040 bool IsInclusionDirective) {
2042 StringRef ModuleName = Path[0].getIdentifierInfo()->getName();
2049 auto CacheIt = ModuleImportResults.find(ImportLoc);
2050 if (CacheIt != ModuleImportResults.end()) {
2051 if (CacheIt->second && ModuleName !=
getLangOpts().CurrentModule)
2052 TheASTReader->makeModuleVisible(CacheIt->second,
Visibility, ImportLoc);
2053 return CacheIt->second;
2068 }
else if (ModuleName ==
getLangOpts().CurrentModule) {
2070 Module = PP->getHeaderSearchInfo().lookupModule(
2071 ModuleName, ImportLoc,
true,
2072 !IsInclusionDirective);
2084 ModuleName, ImportLoc,
true, !IsInclusionDirective);
2087 PPCb->moduleLoadSkipped(
Module);
2090 std::vector<clang::Module *> Worklist{
Module};
2091 while (!Worklist.empty()) {
2093 Worklist.pop_back();
2096 Worklist.push_back(SubM);
2101 SourceLocation ModuleNameEndLoc = Path.back().getLoc().getLocWithOffset(
2102 Path.back().getIdentifierInfo()->getLength());
2105 IsInclusionDirective);
2109 DisableGeneratingGlobalModuleIndex =
true;
2121 bool MapPrivateSubModToTopLevel =
false;
2122 for (
unsigned I = 1, N = Path.size(); I != N; ++I) {
2123 StringRef Name = Path[I].getIdentifierInfo()->getName();
2132 PrivateModule.append(
"_Private");
2135 auto &II = PP->getIdentifierTable().get(
2136 PrivateModule, PP->getIdentifierInfo(
Module->
Name)->getTokenID());
2137 PrivPath.emplace_back(Path[0].getLoc(), &II);
2141 if (PP->getHeaderSearchInfo().lookupModule(PrivateModule, ImportLoc,
true,
2142 !IsInclusionDirective) ||
2144 PP->getHeaderSearchInfo()) != MS_ModuleNotFound)
2147 MapPrivateSubModToTopLevel =
true;
2148 PP->markClangModuleAsAffecting(
Module);
2150 diag::warn_no_priv_submodule_use_toplevel, ImportLoc)) {
2152 diag::warn_no_priv_submodule_use_toplevel)
2155 <<
SourceRange(Path[0].getLoc(), Path[I].getLoc())
2159 diag::note_private_top_level_defined);
2167 unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)();
2171 Name.edit_distance(SubModule->Name,
2172 true, BestEditDistance);
2173 if (ED <= BestEditDistance) {
2174 if (ED < BestEditDistance) {
2176 BestEditDistance = ED;
2179 Best.push_back(SubModule->Name);
2184 if (Best.size() == 1) {
2186 diag::err_no_submodule_suggest)
2188 << Best[0] <<
SourceRange(Path[0].getLoc(), Path[I - 1].getLoc())
2201 <<
SourceRange(Path[0].getLoc(), Path[I - 1].getLoc());
2220 <<
SourceRange(Path.front().getLoc(), Path.back().getLoc());
2229 <<
SourceRange(Path.front().getLoc(), Path.back().getLoc());
2248 StringRef ModuleName,
2252 for (
auto &
C : CleanModuleName)
2261 if (std::error_code EC = llvm::sys::fs::createTemporaryFile(
2267 std::string ModuleMapFileName = (CleanModuleName +
".map").str();
2274 std::string NullTerminatedSource(Source.str());
2276 auto Other = cloneForModuleCompileImpl(ImportLoc, ModuleName, Input,
2282 ModuleMapFileName, NullTerminatedSource.size(), 0);
2283 Other->getSourceManager().overrideFileContents(
2284 ModuleMapFile, llvm::MemoryBuffer::getMemBuffer(NullTerminatedSource));
2286 Other->BuiltModules = std::move(BuiltModules);
2287 Other->DeleteBuiltModules =
false;
2290 std::unique_ptr<llvm::MemoryBuffer> Buffer =
2292 BuiltModules = std::move(
Other->BuiltModules);
2295 llvm::raw_fd_ostream OS(FD,
true);
2296 BuiltModules[std::string(ModuleName)] = std::string(
ModuleFileName);
2297 OS << Buffer->getBuffer();
2310 TheASTReader->makeModuleVisible(Mod,
Visibility, ImportLoc);
2316 .getHeaderSearchInfo()
2317 .getSpecificModuleCachePath()
2327 TheASTReader->loadGlobalIndex();
2332 llvm::sys::fs::create_directories(
2333 getPreprocessor().getHeaderSearchInfo().getSpecificModuleCachePath());
2337 .getHeaderSearchInfo()
2338 .getSpecificModuleCachePath())) {
2343 consumeError(std::move(Err));
2346 TheASTReader->resetForReload();
2347 TheASTReader->loadGlobalIndex();
2348 GlobalIndex = TheASTReader->getGlobalIndex();
2352 if (!HaveFullGlobalModuleIndex && GlobalIndex && !
buildingModule()) {
2358 bool RecreateIndex =
false;
2361 Module *TheModule = I->second;
2364 Path.emplace_back(TriggerLoc,
2366 std::reverse(Path.begin(), Path.end());
2369 RecreateIndex =
true;
2372 if (RecreateIndex) {
2376 .getHeaderSearchInfo()
2377 .getSpecificModuleCachePath())) {
2379 consumeError(std::move(Err));
2382 TheASTReader->resetForReload();
2383 TheASTReader->loadGlobalIndex();
2384 GlobalIndex = TheASTReader->getGlobalIndex();
2386 HaveFullGlobalModuleIndex =
true;
2420 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 compileModuleAndReadAST(CompilerInstance &ImportingInstance, SourceLocation ImportLoc, SourceLocation ModuleNameLoc, Module *Module, ModuleFileName 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 readASTAfterCompileModule(CompilerInstance &ImportingInstance, SourceLocation ImportLoc, SourceLocation ModuleNameLoc, Module *Module, ModuleFileName ModuleFileName, bool *OutOfDate, bool *Missing)
Read the AST right after compiling the module.
static CompileOrReadResult compileModuleBehindLockOrRead(CompilerInstance &ImportingInstance, SourceLocation ImportLoc, SourceLocation ModuleNameLoc, Module *Module, ModuleFileName ModuleFileName)
Attempt to compile the module in a separate compiler instance behind a lock (to avoid building the sa...
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)
CompileOrReadResult
The result of compileModuleBehindLockOrRead().
@ Compiled
We successfully compiled the module and we still need to read it.
@ Read
We read a module file compiled by another instance.
@ FailedToRead
We failed to read the module file compiled by another instance.
@ FailedToCompile
We failed to compile 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 ModuleSource selectModuleSource(Module *M, StringRef ModuleName, ModuleFileName &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 compileModuleImpl(CompilerInstance &ImportingInstance, SourceLocation ImportLoc, SourceLocation ModuleNameLoc, Module *Module, ModuleFileName ModuleFileName)
Compile a module in a separate compiler instance.
static void checkConfigMacros(Preprocessor &PP, Module *M, SourceLocation ImportLoc)
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...
static void print(llvm::raw_ostream &OS, const T &V, ASTContext &ASTCtx, QualType Ty)
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.
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
bool loadModuleFile(ModuleFileName FileName, serialization::ModuleFile *&LoadedModuleFile)
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)
GenModuleActionWrapperFunc getGenModuleActionWrapper() const
ModuleLoadResult loadModule(SourceLocation ImportLoc, ModuleIdPath Path, Module::NameVisibilityKind Visibility, bool IsInclusionDirective) override
Attempt to load the given module.
FileSystemOptions & getFileSystemOpts()
llvm::Timer & getFrontendTimer() const
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()
std::unique_ptr< llvm::MemoryBuffer > 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...
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.
std::unique_ptr< CompilerInstance > cloneForModuleCompile(SourceLocation ImportLoc, const Module *Module, StringRef ModuleFileName, std::optional< ThreadSafeCloneConfig > ThreadSafeConfig=std::nullopt)
Creates a new CompilerInstance for compiling a module.
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 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 computeContextHash() const
Compute the context hash - a string that uniquely identifies compiler settings.
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
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.
static bool fixupRelativePath(const FileSystemOptions &FileSystemOpts, SmallVectorImpl< char > &Path)
OptionalFileEntryRef getOptionalFileRef(StringRef Filename, bool OpenFile=false, bool CacheFailure=true, bool IsText=true)
Get a FileEntryRef if it exists, without doing anything on error.
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.
unsigned ImplicitModulesLockTimeoutSeconds
The time in seconds to wait on an implicit module lock before timing out.
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.
llvm::MemoryBuffer & addBuiltPCM(llvm::StringRef Filename, std::unique_ptr< llvm::MemoryBuffer > Buffer, off_t Size, time_t ModTime)
Store a just-built PCM under the Filename.
@ 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 std::error_code write(StringRef Path, llvm::MemoryBufferRef Buffer, off_t &Size, time_t &ModTime)=0
Write the PCM contents to the given path in the module cache.
virtual InMemoryModuleCache & getInMemoryModuleCache()=0
Returns this process's view of the module cache.
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.
Identifies a module file to be loaded.
bool empty() const
Checks whether the module file name is empty.
static ModuleFileName makeExplicit(std::string Name)
Creates a file name for an explicit module.
StringRef str() const
Returns the plain module file name.
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.
void loadAllParsedModules()
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.
const ModuleFileKey * getASTFileKey() const
The serialized AST file key for this module, if one was created.
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.
This abstract interface provides operations for unwrapping containers for serialized ASTs (precompile...
virtual llvm::StringRef ExtractPCH(llvm::MemoryBufferRef Buffer) const =0
Returns the serialized AST inside the PCH container Buffer.
This interface provides a way to observe the actions of the preprocessor as it does its thing.
@ 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.
SourceLocation getBegin() const
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...
@ HeaderSearch
Remove unused header search paths including header maps.
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
@ 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.
std::shared_ptr< ModuleCache > createCrossProcessModuleCache()
Creates new ModuleCache backed by a file system directory that may be operated on by multiple process...
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
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)
constexpr size_t DesiredStackSize
The amount of stack space that Clang would like to be provided with.
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.