25#include "clang/Config/config.h"
49#include "llvm/ADT/IntrusiveRefCntPtr.h"
50#include "llvm/ADT/STLExtras.h"
51#include "llvm/ADT/Statistic.h"
52#include "llvm/Config/llvm-config.h"
53#include "llvm/Plugins/PassPlugin.h"
54#include "llvm/Support/AdvisoryLock.h"
55#include "llvm/Support/BuryPointer.h"
56#include "llvm/Support/CrashRecoveryContext.h"
57#include "llvm/Support/FileSystem.h"
58#include "llvm/Support/MemoryBuffer.h"
59#include "llvm/Support/Path.h"
60#include "llvm/Support/Signals.h"
61#include "llvm/Support/SmallVectorMemoryBuffer.h"
62#include "llvm/Support/Threading.h"
63#include "llvm/Support/TimeProfiler.h"
64#include "llvm/Support/Timer.h"
65#include "llvm/Support/VirtualFileSystem.h"
66#include "llvm/Support/VirtualOutputBackends.h"
67#include "llvm/Support/VirtualOutputError.h"
68#include "llvm/Support/raw_ostream.h"
69#include "llvm/TargetParser/Host.h"
76CompilerInstance::CompilerInstance(
77 std::shared_ptr<CompilerInvocation> Invocation,
78 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
79 std::shared_ptr<ModuleCache> ModCache)
81 Invocation(
std::move(Invocation)),
82 ModCache(ModCache ?
std::move(ModCache)
84 ThePCHContainerOperations(
std::move(PCHContainerOps)) {
85 assert(this->Invocation &&
"Invocation must not be null");
89 assert(OutputFiles.empty() &&
"Still output files in flight?");
93 return (BuildGlobalModuleIndex ||
94 (TheASTReader && TheASTReader->isGlobalIndexUnavailable() &&
96 !DisableGeneratingGlobalModuleIndex;
101 Diagnostics = std::move(
Value);
105 OwnedVerboseOutputStream.reset();
106 VerboseOutputStream = &
Value;
110 OwnedVerboseOutputStream.swap(
Value);
111 VerboseOutputStream = OwnedVerboseOutputStream.get();
135 auto &TO = AuxTargetOpts = std::make_unique<TargetOptions>();
174 HostLangOpts.CUDAIsDevice =
false;
184 assert(
Value ==
nullptr ||
186 FileMgr = std::move(
Value);
191 SourceMgr = std::move(
Value);
195 PP = std::move(
Value);
199 assert(Context &&
"Compiler instance has no AST context!");
205 Context = std::move(
Value);
207 if (Context && Consumer)
216 Consumer = std::move(
Value);
218 if (Context && Consumer)
223 CompletionConsumer.reset(
Value);
227 return std::move(TheSema);
234 assert(ModCache.get() == &Reader->getModuleManager().getModuleCache() &&
235 "Expected ASTReader to use the same PCM cache");
236 TheASTReader = std::move(Reader);
239std::shared_ptr<ModuleDependencyCollector>
241 return ModuleDepCollector;
245 std::shared_ptr<ModuleDependencyCollector> Collector) {
246 ModuleDepCollector = std::move(Collector);
250 std::shared_ptr<ModuleDependencyCollector> MDC) {
253 for (
auto &Name : HeaderMapFileNames)
258 std::shared_ptr<ModuleDependencyCollector> MDC) {
265 auto PCHDir =
FileMgr.getOptionalDirectoryRef(PCHInclude);
267 MDC->addFile(PCHInclude);
273 llvm::sys::path::native(PCHDir->getName(), DirNative);
274 llvm::vfs::FileSystem &FS =
FileMgr.getVirtualFileSystem();
276 for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
277 Dir != DirEnd && !EC; Dir.increment(EC)) {
286 MDC->addFile(Dir->path());
291 std::shared_ptr<ModuleDependencyCollector> MDC) {
295 if (
auto *RedirectingVFS = dyn_cast<llvm::vfs::RedirectingFileSystem>(&VFS))
296 llvm::vfs::collectVFSEntries(*RedirectingVFS, VFSEntries);
299 for (
auto &E : VFSEntries)
300 MDC->addFile(E.VPath, E.RPath);
305 bool ShouldOwnClient =
false;
308 ShouldOwnClient =
true;
320 llvm::makeIntrusiveRefCnt<llvm::vfs::TracingFileSystem>(std::move(VFS));
328 std::unique_ptr<raw_ostream> StreamOwner;
329 raw_ostream *OS = &llvm::errs();
332 auto FileOS = std::make_unique<llvm::raw_fd_ostream>(
334 llvm::sys::fs::OF_Append | llvm::sys::fs::OF_TextWithCRLF);
336 Diags.
Report(diag::warn_fe_cc_log_diagnostics_failure)
339 FileOS->SetUnbuffered();
341 StreamOwner = std::move(FileOS);
346 auto Logger = std::make_unique<LogDiagnosticPrinter>(*OS, DiagOpts,
347 std::move(StreamOwner));
361 StringRef OutputFile) {
362 auto SerializedConsumer =
367 Diags.
takeClient(), std::move(SerializedConsumer)));
370 Diags.
getClient(), std::move(SerializedConsumer)));
375 bool ShouldOwnClient) {
384 auto Diags = llvm::makeIntrusiveRefCnt<DiagnosticsEngine>(
390 Diags->setClient(Client, ShouldOwnClient);
397 if (Opts.VerifyDiagnostics)
416 assert(VFS &&
"CompilerInstance needs a VFS for creating FileManager");
423 assert(Diagnostics &&
"DiagnosticsEngine needed for creating SourceManager");
424 assert(FileMgr &&
"FileManager needed for creating SourceManager");
425 SourceMgr = llvm::makeIntrusiveRefCnt<SourceManager>(
getDiagnostics(),
439 FileMgr.getVirtualFileRef(RB.first, RB.second->getBufferSize(), 0);
446 SourceMgr.overrideFileContents(FromFile, RB.second->getMemBufferRef());
448 SourceMgr.overrideFileContents(
449 FromFile, std::unique_ptr<llvm::MemoryBuffer>(RB.second));
457 Diags.
Report(diag::err_fe_remap_missing_to_file) << RF.first << RF.second;
467 SourceMgr.overrideFileContents(FromFile, *ToFile);
470 SourceMgr.setOverridenFilesKeepOriginalName(
480 TheASTReader.reset();
486 PP = std::make_shared<Preprocessor>(Invocation->getPreprocessorOpts(),
493 SharedBuiltins = std::make_shared<const Builtin::TargetBuiltins>(
498 PP->createPreprocessingRecord();
502 PP->getFileManager(), PPOpts);
511 const llvm::Triple *HeaderSearchTriple = &PP->getTargetInfo().getTriple();
512 if (PP->getTargetInfo().getTriple().getOS() == llvm::Triple::CUDA &&
513 PP->getAuxTargetInfo())
514 HeaderSearchTriple = &PP->getAuxTargetInfo()->getTriple();
517 PP->getLangOpts(), *HeaderSearchTriple);
521 if (PP->getLangOpts().Modules && PP->getLangOpts().ImplicitModules) {
525 PP->getHeaderSearchInfo().initializeModuleCachePath(
540 ModuleDepCollector = std::make_shared<ModuleDependencyCollector>(
546 if (ModuleDepCollector) {
557 for (
auto &Listener : DependencyCollectors)
558 Listener->attachToPreprocessor(*PP);
565 if (OutputPath ==
"-")
578 if (GetDependencyDirectives)
579 PP->setDependencyDirectivesGetter(*GetDependencyDirectives);
583 PP->getDiagnostics().Report(clang::diag::err_fe_text_encoding_config)
584 << PP->getTextEncoding().getLiteralEncoding();
591 auto Context = llvm::makeIntrusiveRefCnt<ASTContext>(
592 getLangOpts(), PP.getSourceManager(), PP.getIdentifierTable(),
593 PP.getSelectorTable(), PP.getBuiltinInfo(), PP.TUKind);
610 void ReadModuleName(StringRef ModuleName)
override {
613 LoadedModules.push_back(ModuleName.str());
618 for (
const std::string &LoadedModule : LoadedModules)
621 LoadedModules.clear();
624 void markAllUnavailable() {
625 for (
const std::string &LoadedModule : LoadedModules) {
628 M->HasIncompatibleModuleFile =
true;
632 SmallVector<Module *, 2> Stack;
634 while (!Stack.empty()) {
635 Module *Current = Stack.pop_back_val();
639 llvm::append_range(Stack, SubmodulesRange);
643 LoadedModules.clear();
650 bool AllowPCHWithCompilerErrors,
void *DeserializationListener,
651 bool OwnDeserializationListener) {
658 DeserializationListener, OwnDeserializationListener,
Preamble,
663 StringRef Path, StringRef Sysroot,
668 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
669 ArrayRef<std::shared_ptr<DependencyCollector>> DependencyCollectors,
670 void *DeserializationListener,
bool OwnDeserializationListener,
671 bool Preamble,
bool UseGlobalModuleIndex) {
673 PP.getHeaderSearchInfo().getHeaderSearchOpts();
675 auto Reader = llvm::makeIntrusiveRefCnt<ASTReader>(
676 PP, ModCache, &Context, PCHContainerRdr, CodeGenOpts, Extensions,
677 Sysroot.empty() ?
"" : Sysroot.data(), DisableValidation,
678 AllowPCHWithCompilerErrors,
false,
685 Context.setExternalSource(Reader);
687 Reader->setDeserializationListener(
689 OwnDeserializationListener);
691 for (
auto &Listener : DependencyCollectors)
692 Listener->attachToASTReader(*Reader);
694 auto Listener = std::make_unique<ReadModuleNames>(PP);
695 auto &ListenerRef = *Listener;
697 std::move(Listener));
706 PP.setPredefines(Reader->getSuggestedPredefines());
707 ListenerRef.registerAll();
723 ListenerRef.markAllUnavailable();
724 Context.setExternalSource(
nullptr);
750 if (!CompletionConsumer) {
763 timerGroup.reset(
new llvm::TimerGroup(
"clang",
"Clang time report"));
764 FrontendTimer.reset(
new llvm::Timer(
"frontend",
"Front end", *timerGroup));
784 TUKind, CompletionConsumer));
790 if (ExternalSemaSrc) {
791 TheSema->addExternalSource(ExternalSemaSrc);
792 ExternalSemaSrc->InitializeSema(*TheSema);
798 (void)TheSema->APINotes.loadCurrentModuleAPINotes(
810 for (
auto &O : OutputFiles)
811 llvm::handleAllErrors(
813 [&](
const llvm::vfs::TempFileOutputError &E) {
814 getDiagnostics().Report(diag::err_unable_to_rename_temp)
815 << E.getTempPath() << E.getOutputPath()
816 << E.convertToErrorCode().message();
818 [&](
const llvm::vfs::OutputError &E) {
819 getDiagnostics().Report(diag::err_fe_unable_to_open_output)
820 << E.getOutputPath() << E.convertToErrorCode().message();
822 [&](
const llvm::ErrorInfoBase &EIB) {
823 getDiagnostics().Report(diag::err_fe_unable_to_open_output)
824 << O.getPath() << EIB.message();
828 if (DeleteBuiltModules) {
829 for (
auto &
Module : BuiltModules)
830 llvm::sys::fs::remove(
Module.second);
831 BuiltModules.clear();
836 bool Binary, StringRef InFile, StringRef Extension,
bool RemoveFileOnSignal,
837 bool CreateMissingDirectories,
bool ForceUseTemporary,
838 bool SetOnlyIfDifferent) {
840 std::optional<SmallString<128>> PathStorage;
841 if (OutputPath.empty()) {
842 if (InFile ==
"-" || Extension.empty()) {
845 PathStorage.emplace(InFile);
846 llvm::sys::path::replace_extension(*PathStorage, Extension);
847 OutputPath = *PathStorage;
853 CreateMissingDirectories, SetOnlyIfDifferent);
857 return std::make_unique<llvm::raw_null_ostream>();
864 assert(!OutputMgr &&
"Already has an output manager");
865 OutputMgr = std::move(NewOutputs);
869 assert(!OutputMgr &&
"Already has an output manager");
870 OutputMgr = llvm::makeIntrusiveRefCnt<llvm::vfs::OnDiskOutputBackend>();
885 StringRef OutputPath,
bool Binary,
bool RemoveFileOnSignal,
886 bool UseTemporary,
bool CreateMissingDirectories,
bool SetOnlyIfDifferent) {
888 createOutputFileImpl(OutputPath,
Binary, RemoveFileOnSignal, UseTemporary,
889 CreateMissingDirectories, SetOnlyIfDifferent);
891 return std::move(*OS);
893 << OutputPath << errorToErrorCode(OS.takeError()).message();
898CompilerInstance::createOutputFileImpl(StringRef OutputPath,
bool Binary,
899 bool RemoveFileOnSignal,
901 bool CreateMissingDirectories,
902 bool SetOnlyIfDifferent) {
903 assert((!CreateMissingDirectories || UseTemporary) &&
904 "CreateMissingDirectories is only allowed when using temporary files");
908 std::optional<SmallString<128>> AbsPath;
909 if (OutputPath !=
"-" && !llvm::sys::path::is_absolute(OutputPath)) {
911 "File Manager is required to fix up relative path.\n");
913 AbsPath.emplace(OutputPath);
915 OutputPath = *AbsPath;
923 .setDiscardOnSignal(RemoveFileOnSignal)
924 .setAtomicWrite(UseTemporary)
925 .setImplyCreateDirectories(UseTemporary && CreateMissingDirectories)
926 .setOnlyIfDifferent(SetOnlyIfDifferent));
928 return O.takeError();
930 O->discardOnDestroy([](llvm::Error E) { consumeError(std::move(E)); });
931 OutputFiles.push_back(std::move(*O));
932 return OutputFiles.back().createProxy();
953 if (Input.isBuffer()) {
954 SourceMgr.setMainFileID(SourceMgr.createFileID(Input.getBuffer(), Kind));
955 assert(SourceMgr.getMainFileID().isValid() &&
956 "Couldn't establish MainFileID!");
960 StringRef InputFile = Input.getFile();
963 auto FileOrErr = InputFile ==
"-"
965 : FileMgr.getFileRef(InputFile,
true);
967 auto EC = llvm::errorToErrorCode(FileOrErr.takeError());
968 if (InputFile !=
"-")
969 Diags.
Report(diag::err_fe_error_reading) << InputFile << EC.message();
971 Diags.
Report(diag::err_fe_error_reading_stdin) << EC.message();
975 SourceMgr.setMainFileID(
978 assert(SourceMgr.getMainFileID().isValid() &&
979 "Couldn't establish MainFileID!");
985void CompilerInstance::PrepareForExecution() {
1002 assert(
hasDiagnostics() &&
"Diagnostics engine is not initialized!");
1004 assert(!
getFrontendOpts().ShowVersion &&
"Client must handle '-version'!");
1006 llvm::TimeTraceScope TimeScope(
"ExecuteCompiler");
1008 PrepareForExecution();
1029 OS <<
"clang -cc1 version " CLANG_VERSION_STRING <<
" based upon LLVM "
1030 << LLVM_VERSION_STRING <<
" default target "
1031 << llvm::sys::getDefaultTargetTriple() <<
"\n";
1034 llvm::EnableStatistics(
false);
1047 ModuleImportResults.clear();
1050 if (llvm::Error Err = Act.
Execute()) {
1051 consumeError(std::move(Err));
1064 llvm::PrintStatistics(OS);
1067 if (!StatsFile.empty()) {
1068 llvm::sys::fs::OpenFlags FileFlags = llvm::sys::fs::OF_TextWithCRLF;
1070 FileFlags |= llvm::sys::fs::OF_Append;
1073 std::make_unique<llvm::raw_fd_ostream>(StatsFile, EC, FileFlags);
1076 << StatsFile << EC.message();
1078 llvm::PrintStatisticsJSON(*StatS);
1097 OS << NumWarnings <<
" warning" << (NumWarnings == 1 ?
"" :
"s");
1098 if (NumWarnings && NumErrors)
1101 OS << NumErrors <<
" error" << (NumErrors == 1 ?
"" :
"s");
1102 if (NumWarnings || NumErrors) {
1106 OS <<
" when compiling for host";
1108 OS <<
" when compiling for "
1121 if (llvm::sys::DynamicLibrary::LoadLibraryPermanently(Path.c_str(), &
Error))
1128 if (
auto PassPlugin = llvm::PassPlugin::load(Path)) {
1129 PassPlugins.emplace_back(std::make_unique<llvm::PassPlugin>(*PassPlugin));
1132 << Path <<
toString(PassPlugin.takeError());
1137 for (
const FrontendPluginRegistry::entry &Plugin :
1138 FrontendPluginRegistry::entries()) {
1139 std::unique_ptr<PluginASTAction> P(Plugin.instantiate());
1150 if (LLVMArgs.empty())
1153 for (
const std::string &Arg : LLVMArgs)
1154 Args.push_back(Arg.c_str());
1155 return llvm::cl::parseCommandLineOptions(LibraryOptions, Args,
1163 if (LangOpts.OpenCL)
1172std::unique_ptr<CompilerInstance> CompilerInstance::cloneForModuleCompileImpl(
1176 std::optional<ThreadSafeCloneConfig> ThreadSafeConfig) {
1178 auto Invocation = std::make_shared<CompilerInvocation>(
getInvocation());
1180 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
1184 Invocation->resetNonModularOptions();
1188 HeaderSearchOptions &HSOpts = Invocation->getHeaderSearchOpts();
1189 llvm::erase_if(PPOpts.
Macros,
1190 [&HSOpts](
const std::pair<std::string, bool> &def) {
1191 StringRef MacroDef = def.first;
1192 return HSOpts.ModulesIgnoreMacros.contains(
1193 llvm::CachedHashString(MacroDef.split(
'=').first));
1201 [&HSOpts](
const HeaderSearchOptions::Entry &E) {
1202 return HSOpts.ModulesIgnoreSearchPaths.contains(
1203 llvm::CachedHashString(E.Path));
1208 Invocation->getLangOpts().ModuleName =
1212 Invocation->getLangOpts().CurrentModule = std::string(ModuleName);
1217 FrontendOptions &FrontendOpts = Invocation->getFrontendOpts();
1218 FrontendOpts.
OutputFile = ModuleFileName.str();
1225 FrontendOpts.
Inputs = {std::move(Input)};
1230 DiagnosticOptions &DiagOpts = Invocation->getDiagnosticOpts();
1232 DiagOpts.VerifyDiagnostics = 0;
1235 "Module hash mismatch!");
1237 std::shared_ptr<ModuleCache> ModCache;
1238 if (ThreadSafeConfig) {
1239 ModCache = ThreadSafeConfig->getModuleCache();
1241 ModCache = this->ModCache;
1245 auto InstancePtr = std::make_unique<CompilerInstance>(
1247 auto &Instance = *InstancePtr;
1251 Instance.SharedBuiltins = SharedBuiltins;
1253 auto &
Inv = Instance.getInvocation();
1255 if (ThreadSafeConfig) {
1256 Instance.setVirtualFileSystem(ThreadSafeConfig->getVFS());
1257 Instance.createFileManager();
1263 Instance.createFileManager();
1266 if (ThreadSafeConfig) {
1267 Instance.createDiagnostics(&ThreadSafeConfig->getDiagConsumer(),
1270 Instance.createDiagnostics(
1275 Instance.getDiagnostics().setSuppressSystemWarnings(
false);
1277 Instance.createSourceManager();
1278 SourceManager &SourceMgr = Instance.getSourceManager();
1280 if (ThreadSafeConfig) {
1286 SourceMgr.pushModuleBuildStack(
1291 Instance.FailedModules = FailedModules;
1296 Instance.setInheritedDirectoryDependencies(DirectoryDependencies);
1301 if (GetDependencyDirectives)
1302 Instance.GetDependencyDirectives =
1303 GetDependencyDirectives->cloneFor(Instance.getFileManager());
1305 if (ThreadSafeConfig) {
1306 Instance.setModuleDepCollector(ThreadSafeConfig->getModuleDepCollector());
1313 Inv.getDependencyOutputOpts() = DependencyOutputOptions();
1319class PrettyStackTraceBuildModule :
public llvm::PrettyStackTraceEntry {
1320 StringRef ModuleName;
1321 StringRef ModuleFileName;
1324 PrettyStackTraceBuildModule(StringRef ModuleName, StringRef ModuleFileName)
1325 : ModuleName(ModuleName), ModuleFileName(ModuleFileName) {}
1326 void print(raw_ostream &OS)
const override {
1327 OS <<
"Building module '" << ModuleName <<
"' as '" << ModuleFileName
1333std::unique_ptr<llvm::MemoryBuffer>
1336 CompilerInstance &Instance) {
1337 PrettyStackTraceBuildModule CrashInfo(ModuleName,
ModuleFileName);
1338 llvm::TimeTraceScope TimeScope(
"Module Compile", ModuleName);
1355 uint64_t ParentTID = llvm::get_threadid();
1356 bool Crashed = !llvm::CrashRecoveryContext().RunSafelyOnNewStack(
1359 <<
"module_compile_thread: parent=" << ParentTID
1362 auto OS = std::make_unique<llvm::raw_svector_ostream>(Buffer);
1364 std::unique_ptr<FrontendAction> Action =
1365 std::make_unique<GenerateModuleFromModuleMapAction>(std::move(OS));
1367 if (
auto WrapGenModuleAction = Instance.getGenModuleActionWrapper())
1368 Action = WrapGenModuleAction(Instance.getFrontendOpts(),
1371 Instance.ExecuteAction(*Action);
1383 FailedModules = std::move(Instance.FailedModules);
1388 Instance.setSema(
nullptr);
1389 Instance.setASTConsumer(
nullptr);
1392 Instance.clearOutputFiles(
true);
1406 if (Instance.getDiagnostics().hasErrorOccurred() &&
1407 !Instance.getFrontendOpts().AllowPCMWithCompilerErrors)
1412 return std::make_unique<llvm::SmallVectorMemoryBuffer>(
1413 std::move(Buffer), Instance.getFrontendOpts().OutputFile,
1419 StringRef Filename = llvm::sys::path::filename(
File.getName());
1421 if (Filename ==
"module_private.map")
1422 llvm::sys::path::append(PublicFilename,
"module.map");
1423 else if (Filename ==
"module.private.modulemap")
1424 llvm::sys::path::append(PublicFilename,
"module.modulemap");
1426 return std::nullopt;
1427 return FileMgr.getOptionalFileRef(PublicFilename);
1432 std::optional<ThreadSafeCloneConfig> ThreadSafeConfig) {
1448 while (Loc.
isValid() && isModuleMap(SourceMgr.getFileCharacteristic(Loc))) {
1449 ModuleMapFID = SourceMgr.getFileID(Loc);
1450 Loc = SourceMgr.getIncludeLoc(ModuleMapFID);
1454 SourceMgr.getFileEntryRefForID(ModuleMapFID);
1455 assert(ModuleMapFile &&
"Top-level module map with no FileID");
1462 ModuleMapFile = PublicMMFile;
1474 return cloneForModuleCompileImpl(
1475 ImportLoc, ModuleName,
1486 llvm::sys::path::append(FakeModuleMapFile,
"__inferred_module.map");
1488 std::string InferredModuleMapContent;
1489 llvm::raw_string_ostream OS(InferredModuleMapContent);
1492 auto Instance = cloneForModuleCompileImpl(
1493 ImportLoc, ModuleName,
1498 std::unique_ptr<llvm::MemoryBuffer> ModuleMapBuffer =
1499 llvm::MemoryBuffer::getMemBufferCopy(InferredModuleMapContent);
1500 FileEntryRef ModuleMapFile = Instance->getFileManager().getVirtualFileRef(
1501 FakeModuleMapFile, InferredModuleMapContent.size(), 0);
1502 Instance->getSourceManager().overrideFileContents(ModuleMapFile,
1503 std::move(ModuleMapBuffer));
1515 bool *OutOfDate,
bool *Missing) {
1526 ModuleLoadCapabilities);
1556 std::unique_ptr<llvm::MemoryBuffer> Buffer;
1568 diag::err_module_not_built)
1576 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Written =
1581 diag::err_module_not_written)
1586 Buffer = std::move(*Written);
1637 if (llvm::Error Err = Lock->tryLock().moveInto(Owned)) {
1660 switch (Lock->waitForUnlockFor(std::chrono::seconds(Timeout))) {
1661 case llvm::WaitForUnlockResult::Success:
1663 case llvm::WaitForUnlockResult::OwnerDied:
1665 case llvm::WaitForUnlockResult::Timeout:
1672 Lock->unsafeUnlock();
1677 bool OutOfDate =
false;
1678 bool Missing =
false;
1682 if (!OutOfDate && !Missing)
1742 for (
auto *MD = LatestLocalMD; MD; MD = MD->getPrevious()) {
1744 FileID FID = SourceMgr.getFileID(MDLoc);
1750 !SourceMgr.isWrittenInCommandLineFile(MDLoc))
1752 if (
auto *DMD = dyn_cast<DefMacroDirective>(MD))
1753 CmdLineDefinition = DMD->getMacroInfo();
1758 if (CurrentDefinition == CmdLineDefinition) {
1760 }
else if (!CurrentDefinition) {
1763 PP.
Diag(ImportLoc, diag::warn_module_config_macro_undef)
1765 auto LatestDef = LatestLocalMD->getDefinition();
1766 assert(LatestDef.isUndefined() &&
1767 "predefined macro went away with no #undef?");
1768 PP.
Diag(LatestDef.getUndefLocation(), diag::note_module_def_undef_here)
1771 }
else if (!CmdLineDefinition) {
1774 PP.
Diag(ImportLoc, diag::warn_module_config_macro_undef)
1776 PP.
Diag(CurrentDefinition->getDefinitionLoc(),
1777 diag::note_module_def_undef_here)
1779 }
else if (!CurrentDefinition->isIdenticalTo(*CmdLineDefinition, PP,
1782 PP.
Diag(ImportLoc, diag::warn_module_config_macro_undef)
1784 PP.
Diag(CurrentDefinition->getDefinitionLoc(),
1785 diag::note_module_def_undef_here)
1793 for (
const StringRef ConMacro : TopModule->
ConfigMacros) {
1809 .getHeaderSearchInfo()
1810 .getSpecificModuleCachePath()
1817 std::string Sysroot = HSOpts.
Sysroot;
1820 std::unique_ptr<llvm::Timer> ReadTimer;
1823 ReadTimer = std::make_unique<llvm::Timer>(
"reading_modules",
1824 "Reading modules", *timerGroup);
1825 TheASTReader = llvm::makeIntrusiveRefCnt<ASTReader>(
1829 Sysroot.empty() ?
"" : Sysroot.c_str(),
1838 TheASTReader->setDeserializationListener(
1845 TheASTReader->InitializeSema(
getSema());
1849 for (
auto &Listener : DependencyCollectors)
1850 Listener->attachToASTReader(*TheASTReader);
1857 Timer.init(
"preloading." + std::string(
FileName.str()),
1858 "Preloading " + std::string(
FileName.str()), *timerGroup);
1859 llvm::TimeRegion TimeLoading(timerGroup ? &Timer :
nullptr);
1867 bool ConfigMismatchIsRecoverable =
1872 auto Listener = std::make_unique<ReadModuleNames>(*PP);
1873 auto &ListenerRef = *Listener;
1875 std::move(Listener));
1878 switch (TheASTReader->ReadAST(
1881 &LoadedModuleFile)) {
1885 ListenerRef.registerAll();
1891 diag::warn_ast_file_config_mismatch)
1895 ListenerRef.markAllUnavailable();
1907 MS_PrebuiltModulePath,
1908 MS_ModuleBuildPragma
1916 const std::map<std::string, std::string, std::less<>> &BuiltModules,
1918 assert(ModuleFilename.
empty() &&
"Already has a module source?");
1922 auto BuiltModuleIt = BuiltModules.find(ModuleName);
1923 if (BuiltModuleIt != BuiltModules.end()) {
1925 return MS_ModuleBuildPragma;
1935 if (!ModuleFilename.
empty())
1936 return MS_PrebuiltModulePath;
1942 return MS_ModuleCache;
1945 return MS_ModuleNotFound;
1950 bool IsInclusionDirective) {
1954 HS.
lookupModule(ModuleName, ImportLoc,
true, !IsInclusionDirective);
1964 ModuleFileName ModuleFilename;
1965 ModuleSource Source =
1967 SourceLocation ModuleNameLoc = ModuleNameRange.
getBegin();
1968 if (Source == MS_ModuleNotFound) {
1971 << ModuleName << ModuleNameRange;
1974 if (ModuleFilename.
empty()) {
1993 Timer.init(
"loading." + std::string(ModuleFilename.
str()),
1994 "Loading " + std::string(ModuleFilename.
str()), *timerGroup);
1995 llvm::TimeRegion TimeLoading(timerGroup ? &Timer :
nullptr);
1996 llvm::TimeTraceScope TimeScope(
"Module Load", ModuleName);
2000 unsigned ARRFlags = Source == MS_ModuleCache
2003 : Source == MS_PrebuiltModulePath
2007 Source == MS_PrebuiltModulePath
2009 : Source == MS_ModuleBuildPragma
2012 ImportLoc, ARRFlags)) {
2016 assert(Source != MS_ModuleCache &&
2017 "missing module, but file loaded from cache");
2021 M = HS.
lookupModule(ModuleName, ImportLoc,
true, !IsInclusionDirective);
2026 getASTReader()->getModuleManager().makeKey(ModuleFilename))
2031 return ModuleLoadResult();
2040 if (Source == MS_PrebuiltModulePath)
2044 diag::warn_ast_file_config_mismatch)
2053 return ModuleLoadResult();
2057 return ModuleLoadResult();
2061 if (Source != MS_ModuleCache) {
2065 return ModuleLoadResult();
2069 assert(M &&
"missing module, but trying to compile for cache");
2073 ModuleBuildStack::iterator Pos = ModPath.begin(), PosEnd = ModPath.end();
2074 for (; Pos != PosEnd; ++Pos) {
2075 if (Pos->first == ModuleName)
2079 if (Pos != PosEnd) {
2080 SmallString<256> CyclePath;
2081 for (; Pos != PosEnd; ++Pos) {
2082 CyclePath += Pos->first;
2083 CyclePath +=
" -> ";
2085 CyclePath += ModuleName;
2088 << ModuleName << CyclePath;
2093 if (FailedModules.contains(ModuleName)) {
2095 << ModuleName << SourceRange(ImportLoc, ModuleNameLoc);
2103 "undiagnosed error in compileModuleAndReadAST");
2104 FailedModules.insert(ModuleName);
2116 bool IsInclusionDirective) {
2118 StringRef ModuleName = Path[0].getIdentifierInfo()->getName();
2125 auto CacheIt = ModuleImportResults.find(ImportLoc);
2126 if (CacheIt != ModuleImportResults.end()) {
2127 if (CacheIt->second && ModuleName !=
getLangOpts().CurrentModule)
2128 TheASTReader->makeModuleVisible(CacheIt->second,
Visibility, ImportLoc);
2129 return CacheIt->second;
2144 }
else if (ModuleName ==
getLangOpts().CurrentModule) {
2146 Module = PP->getHeaderSearchInfo().lookupModule(
2147 ModuleName, ImportLoc,
true,
2148 !IsInclusionDirective);
2160 ModuleName, ImportLoc,
true, !IsInclusionDirective);
2163 PPCb->moduleLoadSkipped(
Module);
2166 std::vector<clang::Module *> Worklist{
Module};
2167 while (!Worklist.empty()) {
2169 Worklist.pop_back();
2172 Worklist.push_back(SubM);
2177 SourceLocation ModuleNameEndLoc = Path.back().getLoc().getLocWithOffset(
2178 Path.back().getIdentifierInfo()->getLength());
2181 IsInclusionDirective);
2185 DisableGeneratingGlobalModuleIndex =
true;
2197 bool MapPrivateSubModToTopLevel =
false;
2198 for (
unsigned I = 1, N = Path.size(); I != N; ++I) {
2199 StringRef Name = Path[I].getIdentifierInfo()->getName();
2208 PrivateModule.append(
"_Private");
2211 auto &II = PP->getIdentifierTable().get(
2212 PrivateModule, PP->getIdentifierInfo(
Module->
Name)->getTokenID());
2213 PrivPath.emplace_back(Path[0].getLoc(), &II);
2217 if (PP->getHeaderSearchInfo().lookupModule(PrivateModule, ImportLoc,
true,
2218 !IsInclusionDirective) ||
2220 PP->getHeaderSearchInfo()) != MS_ModuleNotFound)
2223 MapPrivateSubModToTopLevel =
true;
2224 PP->markClangModuleAsAffecting(
Module);
2226 diag::warn_no_priv_submodule_use_toplevel, ImportLoc)) {
2228 diag::warn_no_priv_submodule_use_toplevel)
2231 <<
SourceRange(Path[0].getLoc(), Path[I].getLoc())
2235 diag::note_private_top_level_defined);
2243 unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)();
2247 Name.edit_distance(SubModule->Name,
2248 true, BestEditDistance);
2249 if (ED <= BestEditDistance) {
2250 if (ED < BestEditDistance) {
2252 BestEditDistance = ED;
2255 Best.push_back(SubModule->Name);
2260 if (Best.size() == 1) {
2262 diag::err_no_submodule_suggest)
2264 << Best[0] <<
SourceRange(Path[0].getLoc(), Path[I - 1].getLoc())
2277 <<
SourceRange(Path[0].getLoc(), Path[I - 1].getLoc());
2296 <<
SourceRange(Path.front().getLoc(), Path.back().getLoc());
2305 <<
SourceRange(Path.front().getLoc(), Path.back().getLoc());
2324 StringRef ModuleName,
2328 for (
auto &
C : CleanModuleName)
2337 if (std::error_code EC = llvm::sys::fs::createTemporaryFile(
2343 std::string ModuleMapFileName = (CleanModuleName +
".map").str();
2350 std::string NullTerminatedSource(Source.str());
2352 auto Other = cloneForModuleCompileImpl(ImportLoc, ModuleName, Input,
2358 ModuleMapFileName, NullTerminatedSource.size(), 0);
2359 Other->getSourceManager().overrideFileContents(
2360 ModuleMapFile, llvm::MemoryBuffer::getMemBuffer(NullTerminatedSource));
2362 Other->BuiltModules = std::move(BuiltModules);
2363 Other->DeleteBuiltModules =
false;
2366 std::unique_ptr<llvm::MemoryBuffer> Buffer =
2368 BuiltModules = std::move(
Other->BuiltModules);
2371 llvm::raw_fd_ostream OS(FD,
true);
2372 BuiltModules[std::string(ModuleName)] = std::string(
ModuleFileName);
2373 OS << Buffer->getBuffer();
2386 TheASTReader->makeModuleVisible(Mod,
Visibility, ImportLoc);
2392 .getHeaderSearchInfo()
2393 .getSpecificModuleCachePath()
2403 TheASTReader->loadGlobalIndex();
2408 llvm::sys::fs::create_directories(
2409 getPreprocessor().getHeaderSearchInfo().getSpecificModuleCachePath());
2413 .getHeaderSearchInfo()
2414 .getSpecificModuleCachePath())) {
2419 consumeError(std::move(Err));
2422 TheASTReader->resetForReload();
2423 TheASTReader->loadGlobalIndex();
2424 GlobalIndex = TheASTReader->getGlobalIndex();
2428 if (!HaveFullGlobalModuleIndex && GlobalIndex && !
buildingModule()) {
2434 bool RecreateIndex =
false;
2437 Module *TheModule = I->second;
2440 Path.emplace_back(TriggerLoc,
2442 std::reverse(Path.begin(), Path.end());
2445 RecreateIndex =
true;
2448 if (RecreateIndex) {
2452 .getHeaderSearchInfo()
2453 .getSpecificModuleCachePath())) {
2455 consumeError(std::move(Err));
2458 TheASTReader->resetForReload();
2459 TheASTReader->loadGlobalIndex();
2460 GlobalIndex = TheASTReader->getGlobalIndex();
2462 HaveFullGlobalModuleIndex =
true;
2496 ExternalSemaSrc = std::move(ESS);
Defines the clang::ASTContext interface.
Defines a logger where each line is written atomically to the file.
Defines the Diagnostic-related interfaces.
Defines enum values for all the target-independent builtin functions.
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, const Context &Ctx, QualType Ty)
static StringRef getTriple(const Command &Job)
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 ...
bool parseLLVMArgs(llvm::raw_ostream *Errs=nullptr)
Parse the -mllvm options in FrontendOptions::LLVMArgs, setting library options in getLibraryOptions()...
std::unique_ptr< raw_pwrite_stream > createDefaultOutputFile(bool Binary=true, StringRef BaseInput="", StringRef Extension="", bool RemoveFileOnSignal=true, bool CreateMissingDirectories=false, bool ForceUseTemporary=false, bool SetOnlyIfDifferent=false)
Create the default output file (from the invocation's options) and add it to the list of tracked outp...
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.
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.
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.
std::unique_ptr< raw_pwrite_stream > createOutputFile(StringRef OutputPath, bool Binary, bool RemoveFileOnSignal, bool UseTemporary, bool CreateMissingDirectories=false, bool SetOnlyIfDifferent=false)
Create a new output file, optionally deriving the output path name, and add it to the list of tracked...
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()
IntrusiveRefCntPtr< ASTContext > getASTContextPtr() const
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::vector< std::string > LLVMArgs
A list of arguments to forward to LLVM's option processing; this should only be used for debugging an...
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.
AtomicLineLogger & getLogger()
virtual llvm::ErrorOr< std::unique_ptr< llvm::MemoryBuffer > > write(StringRef Path, std::unique_ptr< llvm::MemoryBuffer > 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.
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()
ArrayRef< std::string > getDirectoryDependencies() const
OptionalDirectoryEntryRef Directory
The build directory of this module.
ModuleRef findSubmodule(StringRef Name) const
Find the submodule with the given name.
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 std::unique_ptr< llvm::MemoryBuffer > ExtractPCH(std::unique_ptr< llvm::MemoryBuffer > Buffer) const =0
Returns a buffer with 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.
static std::error_code setConvertersFromOptions(TextEncoding &TE, const clang::LangOptions &Opts, TargetInfo &TInfo)
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.
@ 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.
Top level wrappers for InstallAPI frontend operations.
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 ...
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...
int32_t uint32_t uint32_t __builtin_riscv_mhracc_i32 __builtin_riscv_mhraccu_u32 __builtin_riscv_mhraccsu_i32 __builtin_riscv_mhacc_h1_i32 __builtin_riscv_mhaccsu_h1_i32 __builtin_riscv_mulqr_i32 __builtin_riscv_mqrwacc_i64 __packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 uint8_t
A source location that has been parsed on the command line.