21 #include "clang/Config/config.h" 39 #include "llvm/ADT/Statistic.h" 40 #include "llvm/Support/BuryPointer.h" 41 #include "llvm/Support/CrashRecoveryContext.h" 42 #include "llvm/Support/Errc.h" 43 #include "llvm/Support/FileSystem.h" 44 #include "llvm/Support/Host.h" 45 #include "llvm/Support/LockFileManager.h" 46 #include "llvm/Support/MemoryBuffer.h" 47 #include "llvm/Support/Path.h" 48 #include "llvm/Support/Program.h" 49 #include "llvm/Support/Signals.h" 50 #include "llvm/Support/TimeProfiler.h" 51 #include "llvm/Support/Timer.h" 52 #include "llvm/Support/raw_ostream.h" 56 using namespace clang;
58 CompilerInstance::CompilerInstance(
59 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
63 ModuleCache(SharedModuleCache ? SharedModuleCache
65 ThePCHContainerOperations(
std::move(PCHContainerOps)) {}
68 assert(OutputFiles.empty() &&
"Still output files in flight?");
72 std::shared_ptr<CompilerInvocation>
Value) {
73 Invocation = std::move(Value);
77 return (BuildGlobalModuleIndex ||
78 (TheASTReader && TheASTReader->isGlobalIndexUnavailable() &&
88 OwnedVerboseOutputStream.release();
89 VerboseOutputStream = &
Value;
93 OwnedVerboseOutputStream.swap(Value);
94 VerboseOutputStream = OwnedVerboseOutputStream.get();
109 PP = std::move(Value);
115 if (Context && Consumer)
124 Consumer = std::move(Value);
126 if (Context && Consumer)
131 CompletionConsumer.reset(Value);
135 return std::move(TheSema);
142 assert(ModuleCache.get() == &Reader->getModuleManager().getModuleCache() &&
143 "Expected ASTReader to use the same PCM cache");
144 TheASTReader = std::move(Reader);
147 std::shared_ptr<ModuleDependencyCollector>
149 return ModuleDepCollector;
153 std::shared_ptr<ModuleDependencyCollector> Collector) {
154 ModuleDepCollector = std::move(Collector);
158 std::shared_ptr<ModuleDependencyCollector> MDC) {
161 for (
auto &Name : HeaderMapFileNames)
166 std::shared_ptr<ModuleDependencyCollector> MDC) {
175 MDC->addFile(PCHInclude);
181 llvm::sys::path::native((*PCHDir)->getName(), DirNative);
184 for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
185 Dir != DirEnd && !EC; Dir.increment(EC)) {
193 MDC->addFile(Dir->path());
198 std::shared_ptr<ModuleDependencyCollector> MDC) {
205 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer =
206 llvm::MemoryBuffer::getFile(VFSFile);
209 llvm::vfs::collectVFSFromYAML(std::move(Buffer.get()),
210 nullptr, VFSFile, VFSEntries);
213 for (
auto &E : VFSEntries)
214 MDC->addFile(E.VPath, E.RPath);
222 std::unique_ptr<raw_ostream> StreamOwner;
223 raw_ostream *OS = &llvm::errs();
226 auto FileOS = std::make_unique<llvm::raw_fd_ostream>(
228 llvm::sys::fs::OF_Append | llvm::sys::fs::OF_Text);
230 Diags.
Report(diag::warn_fe_cc_log_diagnostics_failure)
233 FileOS->SetUnbuffered();
235 StreamOwner = std::move(FileOS);
240 auto Logger = std::make_unique<LogDiagnosticPrinter>(*OS, DiagOpts,
241 std::move(StreamOwner));
255 StringRef OutputFile) {
256 auto SerializedConsumer =
261 Diags.
takeClient(), std::move(SerializedConsumer)));
264 Diags.
getClient(), std::move(SerializedConsumer)));
269 bool ShouldOwnClient) {
277 bool ShouldOwnClient,
286 Diags->setClient(Client, ShouldOwnClient);
291 if (Opts->VerifyDiagnostics)
313 VFS = FileMgr ? &FileMgr->getVirtualFileSystem()
316 assert(VFS &&
"FileManager has no VFS?");
318 return FileMgr.get();
339 Diags.
Report(diag::err_fe_remap_missing_from_file) << RB.first;
354 auto ToFile = FileMgr.
getFile(RF.second);
356 Diags.
Report(diag::err_fe_remap_missing_to_file) << RF.first << RF.second;
364 Diags.
Report(diag::err_fe_remap_missing_from_file) << RF.first;
383 TheASTReader.reset();
389 PP = std::make_shared<Preprocessor>(Invocation->getPreprocessorOptsPtr(),
398 PP->createPreprocessingRecord();
402 PP->getFileManager(), PPOpts);
411 const llvm::Triple *HeaderSearchTriple = &PP->getTargetInfo().getTriple();
412 if (PP->getTargetInfo().getTriple().getOS() == llvm::Triple::CUDA &&
413 PP->getAuxTargetInfo())
414 HeaderSearchTriple = &PP->getAuxTargetInfo()->getTriple();
417 PP->getLangOpts(), *HeaderSearchTriple);
421 if (PP->getLangOpts().Modules && PP->getLangOpts().ImplicitModules)
435 ModuleDepCollector = std::make_shared<ModuleDependencyCollector>(
441 if (ModuleDepCollector) {
448 for (
auto &Listener : DependencyCollectors)
449 Listener->attachToPreprocessor(*PP);
456 if (OutputPath ==
"-")
475 llvm::sys::path::append(SpecificModuleCache,
477 return SpecificModuleCache.str();
494 StringRef Path,
bool DisablePCHValidation,
bool AllowPCHWithCompilerErrors,
495 void *DeserializationListener,
bool OwnDeserializationListener) {
502 DeserializationListener, OwnDeserializationListener, Preamble,
507 StringRef Path, StringRef Sysroot,
bool DisablePCHValidation,
511 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
512 ArrayRef<std::shared_ptr<DependencyCollector>> DependencyCollectors,
513 void *DeserializationListener,
bool OwnDeserializationListener,
514 bool Preamble,
bool UseGlobalModuleIndex) {
518 PP, ModuleCache, &Context, PCHContainerRdr, Extensions,
519 Sysroot.empty() ?
"" : Sysroot.data(), DisablePCHValidation,
520 AllowPCHWithCompilerErrors,
false,
522 UseGlobalModuleIndex));
528 Reader->setDeserializationListener(
529 static_cast<ASTDeserializationListener *>(DeserializationListener),
530 OwnDeserializationListener);
532 for (
auto &Listener : DependencyCollectors)
533 Listener->attachToASTReader(*Reader);
535 switch (Reader->ReadAST(Path,
585 if (!CompletionConsumer) {
591 if (!CompletionConsumer)
601 FrontendTimerGroup.reset(
602 new llvm::TimerGroup(
"frontend",
"Clang front-end time report"));
604 new llvm::Timer(
"frontend",
"Clang front-end timer",
605 *FrontendTimerGroup));
625 TUKind, CompletionConsumer));
627 if (ExternalSemaSrc) {
628 TheSema->addExternalSource(ExternalSemaSrc.get());
629 ExternalSemaSrc->InitializeSema(*TheSema);
636 OutputFiles.push_back(std::move(OutFile));
640 for (OutputFile &OF : OutputFiles) {
641 if (!OF.TempFilename.empty()) {
649 FileMgr->FixupRelativePath(NewOutFile);
650 if (std::error_code ec =
651 llvm::sys::fs::rename(OF.TempFilename, NewOutFile)) {
653 << OF.TempFilename << OF.Filename << ec.message();
658 }
else if (!OF.Filename.empty() && EraseFiles)
662 if (DeleteBuiltModules) {
663 for (
auto &
Module : BuiltModules)
665 BuiltModules.clear();
667 NonSeekStream.reset();
670 std::unique_ptr<raw_pwrite_stream>
672 StringRef Extension) {
674 true, InFile, Extension,
679 return std::make_unique<llvm::raw_null_ostream>();
682 std::unique_ptr<raw_pwrite_stream>
684 bool RemoveFileOnSignal, StringRef InFile,
685 StringRef Extension,
bool UseTemporary,
686 bool CreateMissingDirectories) {
687 std::string OutputPathName, TempPathName;
690 OutputPath, EC, Binary, RemoveFileOnSignal, InFile, Extension,
691 UseTemporary, CreateMissingDirectories, &OutputPathName, &TempPathName);
701 OutputFile((OutputPathName !=
"-") ? OutputPathName :
"", TempPathName));
707 StringRef OutputPath, std::error_code &
Error,
bool Binary,
708 bool RemoveFileOnSignal, StringRef InFile, StringRef Extension,
709 bool UseTemporary,
bool CreateMissingDirectories,
710 std::string *ResultPathName, std::string *TempPathName) {
711 assert((!CreateMissingDirectories || UseTemporary) &&
712 "CreateMissingDirectories is only allowed when using temporary files");
714 std::string OutFile, TempFile;
715 if (!OutputPath.empty()) {
716 OutFile = OutputPath;
717 }
else if (InFile ==
"-") {
719 }
else if (!Extension.empty()) {
721 llvm::sys::path::replace_extension(Path, Extension);
722 OutFile = Path.str();
727 std::unique_ptr<llvm::raw_fd_ostream> OS;
732 UseTemporary =
false;
734 llvm::sys::fs::file_status Status;
735 llvm::sys::fs::status(OutputPath, Status);
736 if (llvm::sys::fs::exists(Status)) {
738 if (!llvm::sys::fs::can_write(OutputPath)) {
745 if (!llvm::sys::fs::is_regular_file(Status))
746 UseTemporary =
false;
756 StringRef OutputExtension = llvm::sys::path::extension(OutFile);
758 StringRef(OutFile).drop_back(OutputExtension.size());
759 TempPath +=
"-%%%%%%%%";
760 TempPath += OutputExtension;
764 llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath);
766 if (CreateMissingDirectories &&
767 EC == llvm::errc::no_such_file_or_directory) {
768 StringRef
Parent = llvm::sys::path::parent_path(OutputPath);
769 EC = llvm::sys::fs::create_directories(Parent);
771 EC = llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath);
776 OS.reset(
new llvm::raw_fd_ostream(fd,
true));
777 OSFile = TempFile = TempPath.str();
786 OS.reset(
new llvm::raw_fd_ostream(
788 (Binary ? llvm::sys::fs::OF_None : llvm::sys::fs::OF_Text)));
794 if (RemoveFileOnSignal)
795 llvm::sys::RemoveFileOnSignal(OSFile);
798 *ResultPathName = OutFile;
800 *TempPathName = TempFile;
802 if (!Binary || OS->supportsSeeking())
803 return std::move(OS);
805 auto B = std::make_unique<llvm::buffer_ostream>(*OS);
806 assert(!NonSeekStream);
807 NonSeekStream = std::move(OS);
835 "Couldn't establish MainFileID!");
839 StringRef InputFile = Input.
getFile();
842 if (InputFile !=
"-") {
843 auto FileOrErr = FileMgr.
getFileRef(InputFile,
true);
846 consumeError(FileOrErr.takeError());
847 Diags.
Report(diag::err_fe_error_reading) << InputFile;
868 Diags.
Report(diag::err_cannot_open_file) << InputFile
869 << MB.getError().message();
877 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> SBOrErr =
878 llvm::MemoryBuffer::getSTDIN();
879 if (std::error_code EC = SBOrErr.getError()) {
880 Diags.
Report(diag::err_fe_error_reading_stdin) << EC.message();
883 std::unique_ptr<llvm::MemoryBuffer> SB = std::move(SBOrErr.get());
886 SB->getBufferSize(), 0);
893 "Couldn't establish MainFileID!");
900 assert(
hasDiagnostics() &&
"Diagnostics engine is not initialized!");
902 assert(!
getFrontendOpts().ShowVersion &&
"Client must handle '-version'!");
924 auto TO = std::make_shared<TargetOptions>();
948 OS <<
"clang -cc1 version " CLANG_VERSION_STRING
949 <<
" based upon " << BACKEND_PACKAGE_STRING
950 <<
" default target " << llvm::sys::getDefaultTargetTriple() <<
"\n";
956 llvm::EnableStatistics(
false);
966 consumeError(std::move(Err));
982 OS << NumWarnings <<
" warning" << (NumWarnings == 1 ?
"" :
"s");
983 if (NumWarnings && NumErrors)
986 OS << NumErrors <<
" error" << (NumErrors == 1 ?
"" :
"s");
987 if (NumWarnings || NumErrors) {
991 OS <<
" when compiling for host";
1005 llvm::PrintStatistics(OS);
1008 if (!StatsFile.empty()) {
1010 auto StatS = std::make_unique<llvm::raw_fd_ostream>(
1011 StatsFile, EC, llvm::sys::fs::OF_Text);
1014 << StatsFile << EC.message();
1016 llvm::PrintStatisticsJSON(*StatS);
1026 if (LangOpts.OpenCL)
1041 StringRef OriginalModuleMapFile, StringRef ModuleFileName,
1044 llvm::function_ref<void(CompilerInstance &)> PostBuildStep =
1046 llvm::TimeTraceScope TimeScope(
"Module Compile", ModuleName);
1050 std::make_shared<CompilerInvocation>(ImportingInstance.
getInvocation());
1056 Invocation->getLangOpts()->resetNonModularOptions();
1057 PPOpts.resetNonModularOptions();
1062 PPOpts.Macros.erase(
1063 std::remove_if(PPOpts.Macros.begin(), PPOpts.Macros.end(),
1064 [&HSOpts](
const std::pair<std::string, bool> &def) {
1065 StringRef MacroDef = def.first;
1067 llvm::CachedHashString(MacroDef.split(
'=').first)) > 0;
1069 PPOpts.Macros.end());
1072 Invocation->getLangOpts()->ModuleName =
1076 Invocation->getLangOpts()->CurrentModule = ModuleName;
1085 std::make_shared<PreprocessorOptions::FailedModulesSet>();
1092 FrontendOpts.
OutputFile = ModuleFileName.str();
1099 FrontendOpts.
Inputs = {Input};
1102 PPOpts.RetainRemappedFileBuffers =
true;
1104 Invocation->getDiagnosticOpts().VerifyDiagnostics = 0;
1106 Invocation->getModuleHash() &&
"Module hash mismatch!");
1114 auto &Inv = *Invocation;
1115 Instance.setInvocation(std::move(Invocation));
1124 Instance.createSourceManager(Instance.getFileManager());
1138 diag::remark_module_build)
1139 << ModuleName << ModuleFileName;
1141 PreBuildStep(Instance);
1145 llvm::CrashRecoveryContext CRC;
1146 CRC.RunSafelyOnThread(
1153 PostBuildStep(Instance);
1156 diag::remark_module_build_done)
1163 Instance.clearOutputFiles(
true);
1165 return !Instance.getDiagnostics().hasErrorOccurred();
1172 if (Filename ==
"module_private.map")
1173 llvm::sys::path::append(PublicFilename,
"module.map");
1174 else if (Filename ==
"module.private.modulemap")
1175 llvm::sys::path::append(PublicFilename,
"module.modulemap");
1178 if (
auto FE = FileMgr.
getFile(PublicFilename))
1188 StringRef ModuleFileName) {
1203 ModuleMapFile = PublicMMFile;
1217 llvm::sys::path::append(FakeModuleMapFile,
"__inferred_module.map");
1219 std::string InferredModuleMapContent;
1220 llvm::raw_string_ostream OS(InferredModuleMapContent);
1230 std::unique_ptr<llvm::MemoryBuffer> ModuleMapBuffer =
1231 llvm::MemoryBuffer::getMemBuffer(InferredModuleMapContent);
1232 ModuleMapFile = Instance.getFileManager().getVirtualFile(
1233 FakeModuleMapFile, InferredModuleMapContent.size(), 0);
1234 Instance.getSourceManager().overrideFileContents(
1235 ModuleMapFile, std::move(ModuleMapBuffer));
1261 auto diagnoseBuildFailure = [&] {
1262 Diags.
Report(ModuleNameLoc, diag::err_module_not_built)
1268 StringRef Dir = llvm::sys::path::parent_path(ModuleFileName);
1269 llvm::sys::fs::create_directories(Dir);
1273 llvm::LockFileManager Locked(ModuleFileName);
1275 case llvm::LockFileManager::LFS_Error:
1279 Diags.
Report(ModuleNameLoc, diag::remark_module_lock_failure)
1280 << Module->
Name << Locked.getErrorMessage();
1282 Locked.unsafeRemoveLockFile();
1284 case llvm::LockFileManager::LFS_Owned:
1286 if (!
compileModule(ImportingInstance, ModuleNameLoc, Module,
1288 diagnoseBuildFailure();
1293 case llvm::LockFileManager::LFS_Shared:
1296 switch (Locked.waitForUnlock()) {
1297 case llvm::LockFileManager::Res_Success:
1300 case llvm::LockFileManager::Res_OwnerDied:
1302 case llvm::LockFileManager::Res_Timeout:
1306 Diags.
Report(ModuleNameLoc, diag::remark_module_lock_timeout)
1309 Locked.unsafeRemoveLockFile();
1319 ModuleLoadCapabilities);
1322 Locked == llvm::LockFileManager::LFS_Shared) {
1328 diagnoseBuildFailure();
1332 diagnoseBuildFailure();
1353 for (
auto *MD = LatestLocalMD; MD; MD = MD->getPrevious()) {
1358 if (
auto *DMD = dyn_cast<DefMacroDirective>(MD))
1359 CmdLineDefinition = DMD->getMacroInfo();
1364 if (CurrentDefinition == CmdLineDefinition) {
1366 }
else if (!CurrentDefinition) {
1369 PP.
Diag(ImportLoc, diag::warn_module_config_macro_undef)
1371 auto LatestDef = LatestLocalMD->getDefinition();
1372 assert(LatestDef.isUndefined() &&
1373 "predefined macro went away with no #undef?");
1374 PP.
Diag(LatestDef.getUndefLocation(), diag::note_module_def_undef_here)
1377 }
else if (!CmdLineDefinition) {
1380 PP.
Diag(ImportLoc, diag::warn_module_config_macro_undef)
1382 PP.
Diag(CurrentDefinition->getDefinitionLoc(),
1383 diag::note_module_def_undef_here)
1385 }
else if (!CurrentDefinition->isIdenticalTo(*CmdLineDefinition, PP,
1388 PP.
Diag(ImportLoc, diag::warn_module_config_macro_undef)
1390 PP.
Diag(CurrentDefinition->getDefinitionLoc(),
1391 diag::note_module_def_undef_here)
1399 llvm::raw_fd_ostream Out(TimestampFile.str(), EC, llvm::sys::fs::OF_None);
1405 llvm::sys::fs::file_status StatBuf;
1408 assert(!TimestampFile.empty());
1409 llvm::sys::path::append(TimestampFile,
"modules.timestamp");
1412 if (std::error_code EC = llvm::sys::fs::status(TimestampFile, StatBuf)) {
1414 if (EC == std::errc::no_such_file_or_directory) {
1422 time_t TimeStampModTime =
1423 llvm::sys::toTimeT(StatBuf.getLastModificationTime());
1424 time_t CurrentTime = time(
nullptr);
1437 llvm::sys::path::native(HSOpts.
ModuleCachePath, ModuleCachePathNative);
1438 for (llvm::sys::fs::directory_iterator Dir(ModuleCachePathNative, EC), DirEnd;
1439 Dir != DirEnd && !EC; Dir.increment(EC)) {
1441 if (!llvm::sys::fs::is_directory(Dir->path()))
1445 for (llvm::sys::fs::directory_iterator File(Dir->path(), EC), FileEnd;
1446 File != FileEnd && !EC; File.increment(EC)) {
1448 StringRef Extension = llvm::sys::path::extension(File->path());
1449 if (Extension !=
".pcm" && Extension !=
".timestamp" &&
1450 llvm::sys::path::filename(File->path()) !=
"modules.idx")
1455 if (llvm::sys::fs::status(File->path(), StatBuf))
1459 time_t FileAccessTime = llvm::sys::toTimeT(StatBuf.getLastAccessedTime());
1460 if (CurrentTime - FileAccessTime <=
1469 std::string TimpestampFilename = File->path() +
".timestamp";
1475 if (llvm::sys::fs::directory_iterator(Dir->path(), EC) ==
1476 llvm::sys::fs::directory_iterator() && !EC)
1491 !
getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty() &&
1498 std::string Sysroot = HSOpts.
Sysroot;
1500 std::unique_ptr<llvm::Timer> ReadTimer;
1501 if (FrontendTimerGroup)
1502 ReadTimer = std::make_unique<llvm::Timer>(
"reading_modules",
1504 *FrontendTimerGroup);
1521 TheASTReader->InitializeSema(
getSema());
1525 for (
auto &Listener : DependencyCollectors)
1526 Listener->attachToASTReader(*TheASTReader);
1531 if (FrontendTimerGroup)
1532 Timer.init(
"preloading." + FileName.str(),
"Preloading " + FileName.str(),
1533 *FrontendTimerGroup);
1534 llvm::TimeRegion TimeLoading(FrontendTimerGroup ? &Timer :
nullptr);
1545 void ReadModuleName(StringRef ModuleName)
override {
1546 LoadedModules.push_back(
1550 void registerAll() {
1552 for (
auto *II : LoadedModules)
1554 LoadedModules.clear();
1557 void markAllUnavailable() {
1558 for (
auto *II : LoadedModules) {
1563 M->HasIncompatibleModuleFile =
true;
1569 while (!Stack.empty()) {
1570 Module *Current = Stack.pop_back_val();
1573 Stack.insert(Stack.end(),
1578 LoadedModules.clear();
1588 bool ConfigMismatchIsRecoverable =
1593 auto Listener = std::make_unique<ReadModuleNames>(*this);
1594 auto &ListenerRef = *Listener;
1596 std::move(Listener));
1599 switch (TheASTReader->ReadAST(
1605 ListenerRef.registerAll();
1614 ListenerRef.markAllUnavailable();
1626 MS_PrebuiltModulePath,
1627 MS_ModuleBuildPragma
1635 const std::map<std::string, std::string> &BuiltModules,
1637 assert(ModuleFilename.empty() &&
"Already has a module source?");
1641 auto BuiltModuleIt = BuiltModules.find(ModuleName);
1642 if (BuiltModuleIt != BuiltModules.end()) {
1643 ModuleFilename = BuiltModuleIt->second;
1644 return MS_ModuleBuildPragma;
1652 if (!ModuleFilename.empty())
1653 return MS_PrebuiltModulePath;
1659 return MS_ModuleCache;
1662 return MS_ModuleNotFound;
1673 std::string ModuleFilename;
1676 if (Source == MS_ModuleNotFound) {
1679 << ModuleName <<
SourceRange(ImportLoc, ModuleNameLoc);
1680 ModuleBuildFailed =
true;
1684 if (ModuleFilename.empty()) {
1693 ModuleBuildFailed =
true;
1704 if (FrontendTimerGroup)
1705 Timer.init(
"loading." + ModuleFilename,
"Loading " + ModuleFilename,
1706 *FrontendTimerGroup);
1707 llvm::TimeRegion TimeLoading(FrontendTimerGroup ? &Timer :
nullptr);
1708 llvm::TimeTraceScope TimeScope(
"Module Load", ModuleName);
1712 unsigned ARRFlags = Source == MS_ModuleCache
1714 : Source == MS_PrebuiltModulePath
1718 Source == MS_PrebuiltModulePath
1720 : Source == MS_ModuleBuildPragma
1723 ImportLoc, ARRFlags)) {
1727 assert(Source != MS_ModuleCache &&
1728 "missing module, but file loaded from cache");
1732 M = HS.
lookupModule(ModuleName,
true, !IsInclusionDirective);
1736 if (
auto ModuleFile = FileMgr->getFile(ModuleFilename))
1740 ModuleBuildFailed =
true;
1752 if (Source == MS_PrebuiltModulePath)
1756 diag::warn_module_config_mismatch)
1775 if (Source != MS_ModuleCache) {
1779 ModuleBuildFailed =
true;
1784 assert(M &&
"missing module, but trying to compile for cache");
1788 ModuleBuildStack::iterator Pos = ModPath.begin(), PosEnd = ModPath.end();
1789 for (; Pos != PosEnd; ++Pos) {
1790 if (Pos->first == ModuleName)
1794 if (Pos != PosEnd) {
1796 for (; Pos != PosEnd; ++Pos) {
1797 CyclePath += Pos->first;
1798 CyclePath +=
" -> ";
1800 CyclePath += ModuleName;
1803 << ModuleName << CyclePath;
1814 << ModuleName <<
SourceRange(ImportLoc, ModuleNameLoc);
1815 ModuleBuildFailed =
true;
1824 "undiagnosed error in compileModuleAndReadAST");
1827 ModuleBuildFailed =
true;
1840 bool IsInclusionDirective) {
1842 StringRef ModuleName = Path[0].first->getName();
1848 if (ImportLoc.
isValid() && LastModuleImportLoc == ImportLoc) {
1851 TheASTReader->makeModuleVisible(LastModuleImportResult, Visibility,
1853 return LastModuleImportResult;
1861 Module = *MaybeModule;
1864 Module = PP->getHeaderSearchInfo().lookupModule(
1866 !IsInclusionDirective);
1878 ModuleName, ImportLoc, ModuleNameLoc, IsInclusionDirective);
1897 bool MapPrivateSubModToTopLevel =
false;
1898 if (Path.size() > 1) {
1899 for (
unsigned I = 1, N = Path.size(); I != N; ++I) {
1900 StringRef Name = Path[I].first->getName();
1907 if (!Sub && PP->getLangOpts().ImplicitModules && Name ==
"Private" &&
1910 PrivateModule.append(
"_Private");
1913 auto &II = PP->getIdentifierTable().get(
1914 PrivateModule, PP->getIdentifierInfo(Module->
Name)->getTokenID());
1915 PrivPath.push_back(std::make_pair(&II, Path[0].second));
1917 if (PP->getHeaderSearchInfo().lookupModule(PrivateModule,
true,
1918 !IsInclusionDirective))
1920 loadModule(ImportLoc, PrivPath, Visibility, IsInclusionDirective);
1922 MapPrivateSubModToTopLevel =
true;
1924 diag::warn_no_priv_submodule_use_toplevel, ImportLoc)) {
1926 diag::warn_no_priv_submodule_use_toplevel)
1932 diag::note_private_top_level_defined);
1945 unsigned ED = Name.edit_distance((*J)->Name,
1948 if (ED <= BestEditDistance) {
1949 if (ED < BestEditDistance) {
1951 BestEditDistance = ED;
1954 Best.push_back((*J)->Name);
1959 if (Best.size() == 1) {
1961 diag::err_no_submodule_suggest)
1996 <<
SourceRange(Path.front().second, Path.back().second);
2005 <<
SourceRange(Path.front().second, Path.back().second);
2006 LastModuleImportLoc = ImportLoc;
2011 TheASTReader->makeModuleVisible(Module, Visibility, ImportLoc);
2016 for (
unsigned I = 0, N = TopModule->
ConfigMacros.size(); I != N; ++I) {
2027 LastModuleImportLoc = ImportLoc;
2029 return LastModuleImportResult;
2033 StringRef ModuleName,
2037 for (
auto &
C : CleanModuleName)
2045 if (std::error_code EC = llvm::sys::fs::createTemporaryFile(
2046 CleanModuleName,
"pcm", ModuleFileName)) {
2048 << ModuleFileName << EC.message();
2051 std::string ModuleMapFileName = (CleanModuleName +
".map").str();
2058 std::string NullTerminatedSource(Source.str());
2063 const FileEntry *ModuleMapFile = Other.getFileManager().getVirtualFile(
2064 ModuleMapFileName, NullTerminatedSource.size(), 0);
2065 Other.getSourceManager().overrideFileContents(
2067 llvm::MemoryBuffer::getMemBuffer(NullTerminatedSource.c_str()));
2069 Other.BuiltModules = std::move(BuiltModules);
2070 Other.DeleteBuiltModules =
false;
2074 BuiltModules = std::move(Other.BuiltModules);
2079 ModuleFileName, PreBuildStep, PostBuildStep)) {
2080 BuiltModules[ModuleName] = ModuleFileName.str();
2081 llvm::sys::RemoveFileOnSignal(ModuleFileName);
2093 TheASTReader->makeModuleVisible(Mod, Visibility, ImportLoc);
2098 if (
getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty())
2107 TheASTReader->loadGlobalIndex();
2112 llvm::sys::fs::create_directories(
2121 consumeError(std::move(Err));
2124 TheASTReader->resetForReload();
2125 TheASTReader->loadGlobalIndex();
2126 GlobalIndex = TheASTReader->getGlobalIndex();
2130 if (!HaveFullGlobalModuleIndex && GlobalIndex && !
buildingModule()) {
2132 bool RecreateIndex =
false;
2135 Module *TheModule = I->second;
2139 Path.push_back(std::make_pair(
2141 std::reverse(Path.begin(), Path.end());
2144 RecreateIndex =
true;
2147 if (RecreateIndex) {
2152 consumeError(std::move(Err));
2155 TheASTReader->resetForReload();
2156 TheASTReader->loadGlobalIndex();
2157 GlobalIndex = TheASTReader->getGlobalIndex();
2159 HaveFullGlobalModuleIndex =
true;
2193 ExternalSemaSrc = std::move(ESS);
std::string OutputFile
The output file, if any.
unsigned IsAvailable
Whether this module is available in the current translation unit.
void setExternalSource(IntrusiveRefCntPtr< ExternalASTSource > Source)
Attach an external AST source to the AST context.
Defines the clang::ASTContext interface.
LangOptions & getLangOpts()
ASTReadResult
The result of reading the control block of an AST file, which can fail for various reasons...
std::string OriginalModuleMap
When the input is a module map, the original module map file from which that map was inferred...
std::string Name
The name of this module.
CompilerInvocation & getInvocation()
PreprocessorOptions & getPreprocessorOpts()
void createCodeCompletionConsumer()
Create a code completion consumer using the invocation; note that this will cause the source manager ...
bool hasErrorOccurred() const
std::string ModuleDependencyOutputDir
The directory to copy module dependencies to when collecting them.
DiagnosticConsumer * getClient()
std::string DwarfDebugFlags
The string to embed in the debug information for the compile unit, if non-empty.
SelectorTable & getSelectorTable()
std::string DOTOutputFile
The file to write GraphViz-formatted header dependencies to.
FileManager * createFileManager(IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS=nullptr)
Create the file manager and replace any existing one with it.
std::vector< Module * >::iterator submodule_iterator
VerifyDiagnosticConsumer - Create a diagnostic client which will use markers in the input source to c...
void createFrontendTimer()
Create the frontend timer and replace any existing one with it.
bool RemappedFilesKeepOriginalName
True if the SourceManager should report the original file name for contents of files that were remapp...
Implements support for file system lookup, file system caching, and directory search management...
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
virtual void adjust(LangOptions &Opts)
Set forced language options.
void setCodeCompletionConsumer(CodeCompleteConsumer *Value)
setCodeCompletionConsumer - Replace the current code completion consumer; the compiler instance takes...
Defines the clang::FileManager interface and associated types.
void EndSourceFile()
Perform any per-file post processing, deallocate per-file objects, and run statistics and output file...
void createDiagnostics(DiagnosticConsumer *Client=nullptr, bool ShouldOwnClient=true)
Create the diagnostics engine using the invocation's diagnostic options and replace any existing one ...
submodule_iterator submodule_begin()
static void writeTimestampFile(StringRef TimestampFile)
Write a new timestamp file with the given path.
void ExecuteAction() override
Implement the ExecuteAction interface by running Sema on the already-initialized AST consumer...
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
bool buildingModule() const
Returns true if this instance is building a module.
Module * getTopLevelModule()
Retrieve the top-level module for this (sub)module, which may be this module.
Defines the SourceManager interface.
void createSema(TranslationUnitKind TUKind, CodeCompleteConsumer *CompletionConsumer)
Create the Sema object to be used for parsing.
FileManager & getFileManager() const
std::shared_ptr< PCHContainerOperations > getPCHContainerOperations() const
Abstract base class for actions which can be performed by the frontend.
const FileEntry * getModuleMapFileForUniquing(const Module *M) const
Get the module map file that (along with the module name) uniquely identifies this module...
DiagnosticOptions & getDiagnosticOpts()
std::string HeaderIncludeOutputFile
The file to write header include output to.
std::shared_ptr< HeaderSearchOptions > getHeaderSearchOptsPtr() const
const FileEntry * getASTFile() const
The serialized AST file for this module, if one was created.
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
bool InitializeSourceManager(const FrontendInputFile &Input)
InitializeSourceManager - Initialize the source manager to set InputFile as the main file...
InMemoryModuleCache & getModuleCache() const
void setAuxTarget(TargetInfo *Value)
Replace the current AuxTarget.
ChainedDiagnosticConsumer - Chain two diagnostic clients so that diagnostics go to the first client a...
llvm::StringMap< Module * >::const_iterator module_iterator
A reference to a FileEntry that includes the name of the file as it was accessed by the FileManager's...
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
std::shared_ptr< FailedModulesSet > FailedModules
The set of modules that failed to build.
std::unique_ptr< DiagnosticConsumer > takeClient()
Return the current diagnostic client along with ownership of that client.
ASTContext & getASTContext() const
The client can handle an AST file that cannot load because it is out-of-date relative to its input fi...
void setModuleManager(IntrusiveRefCntPtr< ASTReader > Reader)
virtual void adjustTargetOptions(const CodeGenOptions &CGOpts, TargetOptions &TargetOpts) const
Adjust target options based on codegen options.
void setSourceManager(SourceManager *Value)
setSourceManager - Replace the current source manager.
Abstract interface, implemented by clients of the front-end, which formats and prints fully processed...
DependencyOutputOptions & getDependencyOutputOpts()
CharacteristicKind
Indicates whether a file or directory holds normal user code, system code, or system code which is im...
Builtin::Context & getBuiltinInfo()
void setPredefines(const char *P)
Set the predefines for this Preprocessor.
IntrusiveRefCntPtr< ASTReader > getASTReader() const
float __ovld __cnfn normalize(float p)
Returns a vector in the same direction as p but with a length of 1.
static bool compileModuleImpl(CompilerInstance &ImportingInstance, SourceLocation ImportLoc, StringRef ModuleName, FrontendInputFile Input, StringRef OriginalModuleMapFile, StringRef ModuleFileName, llvm::function_ref< void(CompilerInstance &)> PreBuildStep=[](CompilerInstance &) {}, llvm::function_ref< void(CompilerInstance &)> PostBuildStep=[](CompilerInstance &) {})
Compile a module file for the given module, using the options provided by the importing compiler inst...
The client can handle an AST file that cannot load because it is missing.
void setExternalSemaSource(IntrusiveRefCntPtr< ExternalSemaSource > ESS)
One of these records is kept for each identifier that is lexed.
void setMainFileID(FileID FID)
Set the file ID for the main source file.
void setClient(DiagnosticConsumer *client, bool ShouldOwnClient=true)
Set the diagnostic client associated with this diagnostic object.
static void SetupSerializedDiagnostics(DiagnosticOptions *DiagOpts, DiagnosticsEngine &Diags, StringRef OutputFile)
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
bool BeginSourceFile(CompilerInstance &CI, const FrontendInputFile &Input)
Prepare the action for processing the input file Input.
void createSourceManager(FileManager &FileMgr)
Create the source manager and replace any existing one with it.
static llvm::Error writeIndex(FileManager &FileMgr, const PCHContainerReader &PCHContainerRdr, llvm::StringRef Path)
Write a global index into the given.
static void collectHeaderMaps(const HeaderSearch &HS, std::shared_ptr< ModuleDependencyCollector > MDC)
ShowIncludesDestination ShowIncludesDest
Destination of cl.exe style /showIncludes info.
raw_ostream & getVerboseOutputStream()
Get the current stream for verbose output.
unsigned getNumErrors() const
A source location that has been parsed on the command line.
llvm::SmallPtrSet< ModuleFile *, 4 > HitSet
A set of module files in which we found a result.
void setASTContext(ASTContext *Value)
setASTContext - Replace the current AST context.
void cacheModuleLoad(const IdentifierInfo &II, Module *M)
Cache a module load. M might be nullptr.
CodeGenOptions & getCodeGenOpts()
__DEVICE__ int max(int __a, int __b)
The client can handle an AST file that cannot load because it's compiled configuration doesn't match ...
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
unsigned BuildingImplicitModule
Whether we are performing an implicit module build.
Describes a module or submodule.
void makeModuleVisible(Module *Mod, Module::NameVisibilityKind Visibility, SourceLocation ImportLoc) override
Make the given module visible.
bool SetCodeCompletionPoint(const FileEntry *File, unsigned Line, unsigned Column)
Specify the point at which code-completion will be performed.
StringRef getTopLevelModuleName() const
Retrieve the name of the top-level module.
llvm::ErrorOr< const DirectoryEntry * > getDirectory(StringRef DirName, bool CacheFailure=true)
Lookup, cache, and verify the specified directory (real or virtual).
Module * findModule(StringRef Name) const
Retrieve a module with the given name.
std::error_code make_error_code(BuildPreambleError Error)
void setBuildGlobalModuleIndex(bool Build)
Set the flag indicating whether we should (re)build the global module index.
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
static ModuleSource selectModuleSource(Module *M, StringRef ModuleName, std::string &ModuleFilename, const std::map< std::string, std::string > &BuiltModules, HeaderSearch &HS)
Select a source for loading the named module and compute the filename to load it from.
ModuleBuildStack getModuleBuildStack() const
Retrieve the module build stack.
HeaderSearch & getHeaderSearchInfo() const
FrontendOptions & getFrontendOpts()
Visibility
Describes the different kinds of visibility that a declaration may have.
static bool compileModuleAndReadAST(CompilerInstance &ImportingInstance, SourceLocation ImportLoc, SourceLocation ModuleNameLoc, Module *Module, StringRef ModuleFileName)
Compile a module in a separate compiler instance and read the AST, returning true if the module compi...
PreprocessorOutputOptions & getPreprocessorOutputOpts()
SmallVector< FrontendInputFile, 0 > Inputs
The input files and their types.
Concrete class used by the front-end to report problems and issues.
ASTConsumer & getASTConsumer() const
void setVerboseOutputStream(raw_ostream &Value)
Replace the current stream for verbose output.
Defines the Diagnostic-related interfaces.
bool RetainRemappedFileBuffers
Whether the compiler instance should retain (i.e., not free) the buffers associated with remapped fil...
void setASTConsumer(std::unique_ptr< ASTConsumer > Value)
setASTConsumer - Replace the current AST consumer; the compiler instance takes ownership of Value...
unsigned IsFromModuleFile
Whether this module was loaded from a module file.
submodule_iterator submodule_end()
bool hasASTConsumer() const
void setFileManager(FileManager *Value)
Replace the current file manager and virtual file system.
HeaderSearchOptions & getHeaderSearchOpts()
This abstract interface provides operations for unwrapping containers for serialized ASTs (precompile...
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...
std::shared_ptr< ModuleDependencyCollector > getModuleDepCollector() const
The AST file itself appears corrupted.
bool DisablePCHValidation
When true, disables most of the normal validation performed on precompiled headers.
Languages that the frontend can parse and compile.
Language
The language for the input, used to select and validate the language standard and possible actions...
void createPCHExternalASTSource(StringRef Path, bool DisablePCHValidation, bool AllowPCHWithCompilerErrors, void *DeserializationListener, bool OwnDeserializationListener)
Create an external AST source to read a PCH file and attach it to the AST context.
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...
const FileEntry * getContainingModuleMapFile(const Module *Module) const
Retrieve the module map file containing the definition of the given module.
unsigned IsSystem
Whether this is a "system" module (which assumes that all headers in it are system headers)...
static bool compileModule(CompilerInstance &ImportingInstance, SourceLocation ImportLoc, Module *Module, StringRef ModuleFileName)
Compile a module file for the given module in a separate compiler instance, using the options provide...
bool DetailedRecord
Whether we should maintain a detailed record of all macro definitions and expansions.
Sema - This implements semantic analysis and AST building for C.
static void SetUpDiagnosticLog(DiagnosticOptions *DiagOpts, const CodeGenOptions *CodeGenOpts, DiagnosticsEngine &Diags)
std::string CurrentModule
The name of the current module, of which the main source file is a part.
Module * findSubmodule(StringRef Name) const
Find the submodule with the given name.
Describes the result of attempting to load a module.
bool lookupIdentifier(llvm::StringRef Name, HitSet &Hits)
Look for all of the module files with information about the given identifier, e.g., a global function, variable, or type with that name.
Exposes information about the current target.
void addDependencyCollector(std::shared_ptr< DependencyCollector > Listener)
A simple code-completion consumer that prints the results it receives in a simple format...
File is from a prebuilt module path.
std::string getSpecificModuleCachePath()
const AnnotatedLine * Line
RAII object to temporarily add an AST callback listener.
FileID createFileID(const FileEntry *SourceFile, SourceLocation IncludePos, SrcMgr::CharacteristicKind FileCharacter, int LoadedID=0, unsigned LoadedOffset=0)
Create a new FileID that represents the specified file being #included from the specified IncludePosi...
bool hasFileManager() const
llvm::Optional< Module * > getCachedModuleLoad(const IdentifierInfo &II)
Return a cached module load.
Defines version macros and version-related utility functions for Clang.
void print(raw_ostream &OS, unsigned Indent=0) const
Print the module map for this module to the given stream.
Defines the clang::Preprocessor interface.
ASTReaderListenter implementation to set SuggestedPredefines of ASTReader which is required to use a ...
void createASTContext()
Create the AST context.
unsigned ShowHeaderIncludes
Show header inclusions (-H).
LLVM_READONLY bool isAlphanumeric(unsigned char c)
Return true if this character is an ASCII letter or digit: [a-zA-Z0-9].
static bool checkModuleIsAvailable(const LangOptions &LangOpts, const TargetInfo &TargetInfo, DiagnosticsEngine &Diags, Module *M)
Check that the given module is available, producing a diagnostic if not.
void setSema(Sema *S)
Replace the current Sema; the compiler instance takes ownership of S.
const MacroInfo * getMacroInfo(const IdentifierInfo *II) const
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...
module_iterator module_begin() const
TargetInfo * getAuxTarget() const
static TargetInfo * CreateTargetInfo(DiagnosticsEngine &Diags, const std::shared_ptr< TargetOptions > &Opts)
Construct a target for the given options.
bool isNormal() const
Determines whether this is a normal return, whether or not loading the module was successful...
The result type of a method or function.
void addOutputFile(OutputFile &&OutFile)
addOutputFile - Add an output file onto the list of tracked output files.
static bool EnableCodeCompletion(Preprocessor &PP, StringRef Filename, unsigned Line, unsigned Column)
The client can't handle any AST loading failures.
std::unique_ptr< raw_pwrite_stream > createOutputFile(StringRef OutputPath, bool Binary, bool RemoveFileOnSignal, StringRef BaseInput, StringRef Extension, bool UseTemporary, bool CreateMissingDirectories=false)
Create a new output file and add it to the list of tracked output files, optionally deriving the outp...
void noteBottomOfStack()
Call this once on each thread, as soon after starting the thread as feasible, to note the approximate...
The AST file was missing.
bool lookupMissingImports(StringRef Name, SourceLocation TriggerLoc) override
Check global module index for missing imports.
std::unique_ptr< Sema > takeSema()
In-memory cache for modules.
std::string CPU
If given, the name of the target CPU to generate code for.
SourceManager & getSourceManager() const
const DirectoryEntry * Directory
The build directory of this module.
void overrideFileContents(const FileEntry *SourceFile, llvm::MemoryBuffer *Buffer, bool DoNotFree)
Override the contents of the given source file by providing an already-allocated buffer.
const DirectoryEntry * getDir() const
Return the directory the file lives in.
FileSystemOptions & getFileSystemOpts()
The control block was read successfully.
bool hasPreprocessor() const
void ApplyHeaderSearchOptions(HeaderSearch &HS, const HeaderSearchOptions &HSOpts, const LangOptions &Lang, const llvm::Triple &triple)
Apply the header search options to get given HeaderSearch object.
bool ExecuteAction(FrontendAction &Act)
ExecuteAction - Execute the provided action against the compiler's CompilerInvocation object...
File is a PCH file treated as the preamble.
CompilerInstance - Helper class for managing a single instance of the Clang compiler.
Encodes a location in the source.
static Language getLanguageFromOptions(const LangOptions &LangOpts)
Determine the appropriate source input kind based on language options.
StringRef getName() const
File is a PCH file treated as such.
ParsedSourceLocation CodeCompletionAt
If given, enable code completion at the provided location.
std::string ImplicitPCHInclude
The implicit PCH included at the start of the translation unit, or empty.
bool isNamedPipe() const
Check whether the file is a named pipe (and thus can't be opened by the native FileManager methods)...
MacroDirective * getLocalMacroDirectiveHistory(const IdentifierInfo *II) const
Given an identifier, return the latest non-imported macro directive for that identifier.
unsigned getNumWarnings() const
Options for controlling the compiler diagnostics engine.
virtual void finish()
Callback to inform the diagnostic client that processing of all source files has ended.
All of the names in this module are hidden.
File is an implicitly-loaded module.
IdentifierTable & getIdentifierTable()
Cached information about one file (either on disk or in the virtual file system). ...
void AttachDependencyGraphGen(Preprocessor &PP, StringRef OutputFile, StringRef SysRoot)
AttachDependencyGraphGen - Create a dependency graph generator, and attach it to the given preprocess...
bool PrepareToExecute(CompilerInstance &CI)
Prepare the action to execute on the given compiler instance.
std::string DiagnosticSerializationFile
The file to serialize diagnostics to (non-appending).
Diagnostic consumer that forwards diagnostics along to an existing, already-initialized diagnostic co...
void ProcessWarningOptions(DiagnosticsEngine &Diags, const DiagnosticOptions &Opts, bool ReportDiags=true)
ProcessWarningOptions - Initialize the diagnostic client and process the warning options specified on...
bool hasSourceManager() const
std::unique_ptr< raw_pwrite_stream > createNullOutputFile()
DependencyOutputOptions - Options for controlling the compiler dependency file generation.
std::string ModuleName
The module currently being compiled as specified by -fmodule-name.
const FileEntry * getVirtualFile(StringRef Filename, off_t Size, time_t ModificationTime)
Retrieve a file entry for a "virtual" file that acts as if there were a file with the given name on d...
constexpr size_t DesiredStackSize
The amount of stack space that Clang would like to be provided with.
void pushModuleBuildStack(StringRef moduleName, FullSourceLoc importLoc)
Push an entry to the module build stack.
unsigned GenerateGlobalModuleIndex
Whether we can generate the global module index if needed.
void createPreprocessor(TranslationUnitKind TUKind)
Create the preprocessor, using the invocation, file, and source managers, and replace any existing on...
A global index for a set of module files, providing information about the identifiers within those mo...
bool shouldBuildGlobalModuleIndex() const
Indicates whether we should (re)build the global module index.
module_iterator module_end() const
The AST file was writtten with a different language/target configuration.
std::string OutputFile
The file to write dependency output to.
Abstract interface for a consumer of code-completion information.
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Options controlling the behavior of code completion.
bool hadMacroDefinition() const
Returns true if this identifier was #defined to some value at any moment.
Dataflow Directional Tag Classes.
Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc) const
Based on the way the client configured the DiagnosticsEngine object, classify the specified diagnosti...
bool isValid() const
Return true if this is a valid SourceLocation object.
void setDeserializationListener(ASTDeserializationListener *Listener, bool TakeOwnership=false)
Set the AST deserialization listener.
unsigned IsMissingRequirement
Whether this module is missing a feature from Requirements.
void setPreprocessor(std::shared_ptr< Preprocessor > Value)
Replace the current preprocessor.
FileManager & getFileManager() const
Return the current file manager to the caller.
PreprocessorOptions & getPreprocessorOpts()
static void InitializeFileRemapping(DiagnosticsEngine &Diags, SourceManager &SourceMgr, FileManager &FileMgr, const PreprocessorOptions &InitOpts)
llvm::Error Execute()
Set the source manager's main input file, and run the action.
Reads an AST files chain containing the contents of a translation unit.
File is an explicitly-loaded module.
IntrusiveRefCntPtr< llvm::vfs::FileSystem > createVFSFromCompilerInvocation(const CompilerInvocation &CI, DiagnosticsEngine &Diags)
FileID getMainFileID() const
Returns the FileID of the main source file.
bool loadModuleFile(StringRef FileName)
std::unique_ptr< DiagnosticConsumer > create(StringRef OutputFile, DiagnosticOptions *Diags, bool MergeChildRecords=false)
Returns a DiagnosticConsumer that serializes diagnostics to a bitcode file.
unsigned UseGlobalModuleIndex
Whether we can use the global module index if available.
Used for handling and querying diagnostic IDs.
void setASTMutationListener(ASTMutationListener *Listener)
Attach an AST mutation listener to the AST context.
Helper class for holding the data necessary to invoke the compiler.
static const FileEntry * getPublicModuleMap(const FileEntry *File, FileManager &FileMgr)
static void pruneModuleCache(const HeaderSearchOptions &HSOpts)
Prune the module cache of modules that haven't been accessed in a long time.
SourceManager & getSourceManager() const
Return the current source manager.
static void collectIncludePCH(CompilerInstance &CI, std::shared_ptr< ModuleDependencyCollector > MDC)
FrontendOptions - Options for controlling the behavior of the frontend.
Abstract interface for a module loader.
Encapsulates the data about a macro definition (e.g.
std::string StatsFile
Filename to write statistics to.
SourceLocation DefinitionLoc
The location of the module definition.
void clearOutputFiles(bool EraseFiles)
clearOutputFiles - Clear the output file list.
llvm::ErrorOr< const FileEntry * > getFile(StringRef Filename, bool OpenFile=false, bool CacheFailure=true)
Lookup, cache, and verify the specified file (real or virtual).
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
Abstract interface for callback invocations by the ASTReader.
bool hasDiagnostics() const
TargetInfo & getTarget() const
void setOverridenFilesKeepOriginalName(bool value)
Set true if the SourceManager should report the original file name for contents of files that were ov...
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
std::unique_ptr< raw_pwrite_stream > createDefaultOutputFile(bool Binary=true, StringRef BaseInput="", StringRef Extension="")
Create the default output file (from the invocation's options) and add it to the list of tracked outp...
void setTarget(TargetInfo *Value)
Replace the current Target.
bool hasASTContext() const
unsigned DisableFree
Disable memory freeing on exit.
virtual void Initialize(ASTContext &Context)
Initialize - This is called to initialize the consumer, providing the ASTContext. ...
void setInvocation(std::shared_ptr< CompilerInvocation > Value)
setInvocation - Replace the current invocation.
Preprocessor & getPreprocessor() const
Return the current preprocessor.
~CompilerInstance() override
DiagnosticConsumer & getDiagnosticClient() const
FileID getPredefinesFileID() const
Returns the FileID for the preprocessor predefines.
DiagnosticsEngine & getDiagnostics() const
void InitializePreprocessor(Preprocessor &PP, const PreprocessorOptions &PPOpts, const PCHContainerReader &PCHContainerRdr, const FrontendOptions &FEOpts)
InitializePreprocessor - Initialize the preprocessor getting it and the environment ready to process ...
void setModuleBuildStack(ModuleBuildStack stack)
Set the module build stack.
void createModuleFromSource(SourceLocation ImportLoc, StringRef ModuleName, StringRef Source) override
Attempt to create the given module from the specified source buffer.
TranslationUnitKind
Describes the kind of translation unit being processed.
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string...
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...
const PCHContainerReader & getPCHContainerReader() const
Return the appropriate PCHContainerReader depending on the current CodeGenOptions.
void resolveLinkAsDependencies(Module *Mod)
Use PendingLinkAsModule information to mark top level link names that are going to be replaced by exp...
unsigned HasIncompatibleModuleFile
Whether we tried and failed to load a module file for this module.
std::pair< unsigned, bool > PrecompiledPreambleBytes
If non-zero, the implicit PCH include is actually a precompiled preamble that covers this number of b...
Defines the clang::TargetInfo interface.
The AST file is out-of-date relative to its input files, and needs to be regenerated.
A SourceLocation and its associated SourceManager.
NameVisibilityKind
Describes the visibility of the various names within a particular module.
DiagnosticsEngine & getDiagnostics() const
Get the current diagnostics engine.
std::vector< std::string > ConfigMacros
The set of "configuration macros", which are macros that (intentionally) change how this module is bu...
Defines the clang::FrontendAction interface and various convenience abstract classes (clang::ASTFront...
The AST file was written by a different version of Clang.
ModuleLoadResult loadModule(SourceLocation ImportLoc, ModuleIdPath Path, Module::NameVisibilityKind Visibility, bool IsInclusionDirective) override
Attempt to load the given module.
virtual void setAuxTarget(const TargetInfo *Aux)
void setModuleDepCollector(std::shared_ptr< ModuleDependencyCollector > Collector)
static void collectVFSEntries(CompilerInstance &CI, std::shared_ptr< ModuleDependencyCollector > MDC)
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Defines utilities for dealing with stack allocation and stack space.
static bool readASTFileControlBlock(StringRef Filename, FileManager &FileMgr, const PCHContainerReader &PCHContainerRdr, bool FindModuleFileExtensions, ASTReaderListener &Listener, bool ValidateDiagnosticOptions)
Read the control block for the named AST file.
GlobalModuleIndex * loadGlobalModuleIndex(SourceLocation TriggerLoc) override
Load, create, or return global module.
A trivial tuple used to represent a source range.
LangOptions * getLangOpts()
llvm::ErrorOr< std::unique_ptr< llvm::MemoryBuffer > > getBufferForFile(const FileEntry *Entry, bool isVolatile=false)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful, otherwise returning null.
TargetOptions & getTargetOpts()
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) const
Forwarding function for diagnostics.
llvm::vfs::FileSystem & getVirtualFileSystem() const
This class handles loading and caching of source files into memory.
void setDiagnostics(DiagnosticsEngine *Value)
setDiagnostics - Replace the current diagnostics engine.
void noSignedCharForObjCBool()
std::string getModuleHash() const
Retrieve a module hash string that is suitable for uniquely identifying the conditions under which th...
bool Sub(InterpState &S, CodePtr OpPC)
std::string DiagnosticLogFile
The file to log diagnostic output to.
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
bool ownsClient() const
Determine whether this DiagnosticsEngine object own its client.
StringRef getName() const
virtual bool isModelParsingAction() const
Is this action invoked on a model file?
const FileEntry & getFileEntry() const
llvm::Expected< FileEntryRef > getFileRef(StringRef Filename, bool OpenFile=false, bool CacheFailure=true)
Lookup, cache, and verify the specified file (real or virtual).