21 #include "clang/Config/config.h" 39 #include "llvm/ADT/Statistic.h" 40 #include "llvm/Support/CrashRecoveryContext.h" 41 #include "llvm/Support/Errc.h" 42 #include "llvm/Support/FileSystem.h" 43 #include "llvm/Support/Host.h" 44 #include "llvm/Support/LockFileManager.h" 45 #include "llvm/Support/MemoryBuffer.h" 46 #include "llvm/Support/Path.h" 47 #include "llvm/Support/Program.h" 48 #include "llvm/Support/Signals.h" 49 #include "llvm/Support/Timer.h" 50 #include "llvm/Support/raw_ostream.h" 52 #include <system_error> 56 using namespace clang;
58 CompilerInstance::CompilerInstance(
59 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
64 ThePCHContainerOperations(
std::move(PCHContainerOps)) {
71 assert(OutputFiles.empty() &&
"Still output files in flight?");
75 std::shared_ptr<CompilerInvocation>
Value) {
76 Invocation = std::move(Value);
80 return (BuildGlobalModuleIndex ||
81 (ModuleManager && ModuleManager->isGlobalIndexUnavailable() &&
98 VirtualFileSystem.reset();
106 PP = std::move(Value);
112 if (Context && Consumer)
121 Consumer = std::move(Value);
123 if (Context && Consumer)
128 CompletionConsumer.reset(Value);
132 return std::move(TheSema);
136 return ModuleManager;
139 assert(PCMCache.get() == &Reader->getModuleManager().getPCMCache() &&
140 "Expected ASTReader to use the same PCM cache");
141 ModuleManager = std::move(Reader);
144 std::shared_ptr<ModuleDependencyCollector>
146 return ModuleDepCollector;
150 std::shared_ptr<ModuleDependencyCollector> Collector) {
151 ModuleDepCollector = std::move(Collector);
155 std::shared_ptr<ModuleDependencyCollector> MDC) {
158 for (
auto &Name : HeaderMapFileNames)
163 std::shared_ptr<ModuleDependencyCollector> MDC) {
172 MDC->addFile(PCHInclude);
178 llvm::sys::path::native(PCHDir->
getName(), DirNative);
182 Dir != DirEnd && !EC; Dir.
increment(EC)) {
190 MDC->addFile(Dir->getName());
195 std::shared_ptr<ModuleDependencyCollector> MDC) {
202 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer =
203 llvm::MemoryBuffer::getFile(VFSFile);
207 VFSFile, VFSEntries);
210 for (
auto &E : VFSEntries)
211 MDC->addFile(E.VPath, E.RPath);
219 std::unique_ptr<raw_ostream> StreamOwner;
220 raw_ostream *OS = &llvm::errs();
223 auto FileOS = llvm::make_unique<llvm::raw_fd_ostream>(
225 llvm::sys::fs::F_Append | llvm::sys::fs::F_Text);
227 Diags.
Report(diag::warn_fe_cc_log_diagnostics_failure)
230 FileOS->SetUnbuffered();
232 StreamOwner = std::move(FileOS);
237 auto Logger = llvm::make_unique<LogDiagnosticPrinter>(*OS, DiagOpts,
238 std::move(StreamOwner));
248 StringRef OutputFile) {
249 auto SerializedConsumer =
254 Diags.
takeClient(), std::move(SerializedConsumer)));
257 Diags.
getClient(), std::move(SerializedConsumer)));
262 bool ShouldOwnClient) {
270 bool ShouldOwnClient,
279 Diags->setClient(Client, ShouldOwnClient);
284 if (Opts->VerifyDiagnostics)
312 return FileMgr.get();
333 Diags.
Report(diag::err_fe_remap_missing_from_file) << RB.first;
350 Diags.
Report(diag::err_fe_remap_missing_to_file) << RF.first << RF.second;
358 Diags.
Report(diag::err_fe_remap_missing_from_file) << RF.first;
385 PP = std::make_shared<Preprocessor>(
396 PTHMgr->setPreprocessor(&*PP);
397 PP->setPTHManager(PTHMgr);
401 PP->createPreprocessingRecord();
405 PP->getFileManager(), PPOpts);
414 const llvm::Triple *HeaderSearchTriple = &PP->getTargetInfo().getTriple();
415 if (PP->getTargetInfo().getTriple().getOS() == llvm::Triple::CUDA &&
416 PP->getAuxTargetInfo())
417 HeaderSearchTriple = &PP->getAuxTargetInfo()->getTriple();
420 PP->getLangOpts(), *HeaderSearchTriple);
424 if (PP->getLangOpts().Modules && PP->getLangOpts().ImplicitModules)
430 TheDependencyFileGenerator.reset(
439 ModuleDepCollector = std::make_shared<ModuleDependencyCollector>(
445 if (ModuleDepCollector) {
452 for (
auto &Listener : DependencyCollectors)
453 Listener->attachToPreprocessor(*PP);
460 if (OutputPath ==
"-")
479 llvm::sys::path::append(SpecificModuleCache,
481 return SpecificModuleCache.str();
498 StringRef Path,
bool DisablePCHValidation,
bool AllowPCHWithCompilerErrors,
499 void *DeserializationListener,
bool OwnDeserializationListener) {
506 TheDependencyFileGenerator.get(),
507 DependencyCollectors,
508 DeserializationListener,
509 OwnDeserializationListener, Preamble,
514 StringRef Path, StringRef Sysroot,
bool DisablePCHValidation,
517 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
519 ArrayRef<std::shared_ptr<DependencyCollector>> DependencyCollectors,
520 void *DeserializationListener,
bool OwnDeserializationListener,
521 bool Preamble,
bool UseGlobalModuleIndex) {
525 PP, &Context, PCHContainerRdr, Extensions,
526 Sysroot.empty() ?
"" : Sysroot.data(), DisablePCHValidation,
527 AllowPCHWithCompilerErrors,
false,
534 Reader->setDeserializationListener(
535 static_cast<ASTDeserializationListener *>(DeserializationListener),
536 OwnDeserializationListener);
540 for (
auto &Listener : DependencyCollectors)
541 Listener->attachToASTReader(*Reader);
543 switch (Reader->ReadAST(Path,
593 if (!CompletionConsumer) {
599 if (!CompletionConsumer)
607 if (CompletionConsumer->isOutputBinary() &&
608 llvm::sys::ChangeStdoutToBinary()) {
615 FrontendTimerGroup.reset(
616 new llvm::TimerGroup(
"frontend",
"Clang front-end time report"));
618 new llvm::Timer(
"frontend",
"Clang front-end timer",
619 *FrontendTimerGroup));
639 TUKind, CompletionConsumer));
641 if (ExternalSemaSrc) {
642 TheSema->addExternalSource(ExternalSemaSrc.get());
643 ExternalSemaSrc->InitializeSema(*TheSema);
650 OutputFiles.push_back(std::move(OutFile));
654 for (OutputFile &OF : OutputFiles) {
655 if (!OF.TempFilename.empty()) {
657 llvm::sys::fs::remove(OF.TempFilename);
663 FileMgr->FixupRelativePath(NewOutFile);
664 if (std::error_code ec =
665 llvm::sys::fs::rename(OF.TempFilename, NewOutFile)) {
667 << OF.TempFilename << OF.Filename << ec.message();
669 llvm::sys::fs::remove(OF.TempFilename);
672 }
else if (!OF.Filename.empty() && EraseFiles)
673 llvm::sys::fs::remove(OF.Filename);
676 if (DeleteBuiltModules) {
677 for (
auto &
Module : BuiltModules)
678 llvm::sys::fs::remove(
Module.second);
679 BuiltModules.clear();
681 NonSeekStream.reset();
684 std::unique_ptr<raw_pwrite_stream>
686 StringRef Extension) {
688 true, InFile, Extension,
693 return llvm::make_unique<llvm::raw_null_ostream>();
696 std::unique_ptr<raw_pwrite_stream>
698 bool RemoveFileOnSignal, StringRef InFile,
699 StringRef Extension,
bool UseTemporary,
700 bool CreateMissingDirectories) {
701 std::string OutputPathName, TempPathName;
704 OutputPath, EC, Binary, RemoveFileOnSignal, InFile, Extension,
705 UseTemporary, CreateMissingDirectories, &OutputPathName, &TempPathName);
715 OutputFile((OutputPathName !=
"-") ? OutputPathName :
"", TempPathName));
721 StringRef OutputPath, std::error_code &
Error,
bool Binary,
722 bool RemoveFileOnSignal, StringRef InFile, StringRef Extension,
723 bool UseTemporary,
bool CreateMissingDirectories,
724 std::string *ResultPathName, std::string *TempPathName) {
725 assert((!CreateMissingDirectories || UseTemporary) &&
726 "CreateMissingDirectories is only allowed when using temporary files");
728 std::string OutFile, TempFile;
729 if (!OutputPath.empty()) {
730 OutFile = OutputPath;
731 }
else if (InFile ==
"-") {
733 }
else if (!Extension.empty()) {
735 llvm::sys::path::replace_extension(Path, Extension);
736 OutFile = Path.str();
741 std::unique_ptr<llvm::raw_fd_ostream> OS;
746 UseTemporary =
false;
748 llvm::sys::fs::file_status Status;
749 llvm::sys::fs::status(OutputPath, Status);
750 if (llvm::sys::fs::exists(Status)) {
752 if (!llvm::sys::fs::can_write(OutputPath)) {
759 if (!llvm::sys::fs::is_regular_file(Status))
760 UseTemporary =
false;
770 StringRef OutputExtension = llvm::sys::path::extension(OutFile);
772 StringRef(OutFile).drop_back(OutputExtension.size());
773 TempPath +=
"-%%%%%%%%";
774 TempPath += OutputExtension;
778 llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath);
780 if (CreateMissingDirectories &&
781 EC == llvm::errc::no_such_file_or_directory) {
782 StringRef
Parent = llvm::sys::path::parent_path(OutputPath);
783 EC = llvm::sys::fs::create_directories(Parent);
785 EC = llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath);
790 OS.reset(
new llvm::raw_fd_ostream(fd,
true));
791 OSFile = TempFile = TempPath.str();
800 OS.reset(
new llvm::raw_fd_ostream(
802 (Binary ? llvm::sys::fs::F_None : llvm::sys::fs::F_Text)));
808 if (RemoveFileOnSignal)
809 llvm::sys::RemoveFileOnSignal(OSFile);
812 *ResultPathName = OutFile;
814 *TempPathName = TempFile;
816 if (!Binary || OS->supportsSeeking())
817 return std::move(OS);
819 auto B = llvm::make_unique<llvm::buffer_ostream>(*OS);
820 assert(!NonSeekStream);
821 NonSeekStream = std::move(OS);
849 "Couldn't establish MainFileID!");
853 StringRef InputFile = Input.
getFile();
856 if (InputFile !=
"-") {
859 File = FileMgr.
getFile(InputFile,
true);
874 Includers.push_back(std::make_pair(FindFile, FindFile->
getDir()));
877 UnusedCurDir, Includers,
888 Diags.
Report(diag::err_fe_error_reading) << InputFile;
901 File = FileMgr.
getVirtualFile(InputFile, (*MB)->getBufferSize(), 0);
904 Diags.
Report(diag::err_cannot_open_file) << InputFile
905 << MB.getError().message();
913 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> SBOrErr =
914 llvm::MemoryBuffer::getSTDIN();
915 if (std::error_code EC = SBOrErr.getError()) {
916 Diags.
Report(diag::err_fe_error_reading_stdin) << EC.message();
919 std::unique_ptr<llvm::MemoryBuffer> SB = std::move(SBOrErr.get());
922 SB->getBufferSize(), 0);
929 "Couldn't establish MainFileID!");
936 assert(
hasDiagnostics() &&
"Diagnostics engine is not initialized!");
938 assert(!
getFrontendOpts().ShowVersion &&
"Client must handle '-version'!");
942 raw_ostream &OS = llvm::errs();
953 auto TO = std::make_shared<TargetOptions>();
974 OS <<
"clang -cc1 version " CLANG_VERSION_STRING
975 <<
" based upon " << BACKEND_PACKAGE_STRING
976 <<
" default target " << llvm::sys::getDefaultTargetTriple() <<
"\n";
982 llvm::EnableStatistics(
false);
1006 OS << NumWarnings <<
" warning" << (NumWarnings == 1 ?
"" :
"s");
1007 if (NumWarnings && NumErrors)
1010 OS << NumErrors <<
" error" << (NumErrors == 1 ?
"" :
"s");
1011 if (NumWarnings || NumErrors) {
1015 OS <<
" when compiling for host";
1029 llvm::PrintStatistics(OS);
1032 if (!StatsFile.empty()) {
1034 auto StatS = llvm::make_unique<llvm::raw_fd_ostream>(StatsFile, EC,
1035 llvm::sys::fs::F_Text);
1038 << StatsFile << EC.message();
1040 llvm::PrintStatisticsJSON(*StatS);
1050 if (LangOpts.OpenCL)
1065 StringRef OriginalModuleMapFile, StringRef ModuleFileName,
1068 llvm::function_ref<void(CompilerInstance &)> PostBuildStep =
1072 std::make_shared<CompilerInvocation>(ImportingInstance.
getInvocation());
1078 Invocation->getLangOpts()->resetNonModularOptions();
1079 PPOpts.resetNonModularOptions();
1084 PPOpts.Macros.erase(
1085 std::remove_if(PPOpts.Macros.begin(), PPOpts.Macros.end(),
1086 [&HSOpts](
const std::pair<std::string, bool> &def) {
1087 StringRef MacroDef = def.first;
1089 llvm::CachedHashString(MacroDef.split(
'=').first)) > 0;
1091 PPOpts.Macros.end());
1094 Invocation->getLangOpts()->CurrentModule = ModuleName;
1103 std::make_shared<PreprocessorOptions::FailedModulesSet>();
1110 FrontendOpts.
OutputFile = ModuleFileName.str();
1117 FrontendOpts.
Inputs = {Input};
1120 PPOpts.RetainRemappedFileBuffers =
true;
1122 Invocation->getDiagnosticOpts().VerifyDiagnostics = 0;
1124 Invocation->getModuleHash() &&
"Module hash mismatch!");
1132 auto &Inv = *Invocation;
1133 Instance.setInvocation(std::move(Invocation));
1144 Instance.createSourceManager(Instance.getFileManager());
1158 diag::remark_module_build)
1159 << ModuleName << ModuleFileName;
1161 PreBuildStep(Instance);
1165 const unsigned ThreadStackSize = 8 << 20;
1166 llvm::CrashRecoveryContext CRC;
1167 CRC.RunSafelyOnThread(
1174 PostBuildStep(Instance);
1177 diag::remark_module_build_done)
1184 Instance.clearOutputFiles(
true);
1186 return !Instance.getDiagnostics().hasErrorOccurred();
1195 StringRef ModuleFileName) {
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));
1251 StringRef ModuleFileName) {
1254 auto diagnoseBuildFailure = [&] {
1255 Diags.
Report(ModuleNameLoc, diag::err_module_not_built)
1261 StringRef Dir = llvm::sys::path::parent_path(ModuleFileName);
1262 llvm::sys::fs::create_directories(Dir);
1266 llvm::LockFileManager Locked(ModuleFileName);
1268 case llvm::LockFileManager::LFS_Error:
1272 Diags.
Report(ModuleNameLoc, diag::remark_module_lock_failure)
1273 << Module->
Name << Locked.getErrorMessage();
1275 Locked.unsafeRemoveLockFile();
1277 case llvm::LockFileManager::LFS_Owned:
1281 diagnoseBuildFailure();
1286 case llvm::LockFileManager::LFS_Shared:
1289 switch (Locked.waitForUnlock()) {
1290 case llvm::LockFileManager::Res_Success:
1293 case llvm::LockFileManager::Res_OwnerDied:
1295 case llvm::LockFileManager::Res_Timeout:
1299 Diags.
Report(ModuleNameLoc, diag::remark_module_lock_timeout)
1302 Locked.unsafeRemoveLockFile();
1312 ModuleLoadCapabilities);
1315 Locked == llvm::LockFileManager::LFS_Shared) {
1321 diagnoseBuildFailure();
1325 diagnoseBuildFailure();
1346 for (
auto *MD = LatestLocalMD; MD; MD = MD->getPrevious()) {
1351 if (
auto *DMD = dyn_cast<DefMacroDirective>(MD))
1352 CmdLineDefinition = DMD->getMacroInfo();
1357 if (CurrentDefinition == CmdLineDefinition) {
1359 }
else if (!CurrentDefinition) {
1362 PP.
Diag(ImportLoc, diag::warn_module_config_macro_undef)
1364 auto LatestDef = LatestLocalMD->getDefinition();
1365 assert(LatestDef.isUndefined() &&
1366 "predefined macro went away with no #undef?");
1367 PP.
Diag(LatestDef.getUndefLocation(), diag::note_module_def_undef_here)
1370 }
else if (!CmdLineDefinition) {
1373 PP.
Diag(ImportLoc, diag::warn_module_config_macro_undef)
1375 PP.
Diag(CurrentDefinition->getDefinitionLoc(),
1376 diag::note_module_def_undef_here)
1378 }
else if (!CurrentDefinition->isIdenticalTo(*CmdLineDefinition, PP,
1381 PP.
Diag(ImportLoc, diag::warn_module_config_macro_undef)
1383 PP.
Diag(CurrentDefinition->getDefinitionLoc(),
1384 diag::note_module_def_undef_here)
1392 llvm::raw_fd_ostream Out(TimestampFile.str(), EC, llvm::sys::fs::F_None);
1398 struct stat StatBuf;
1401 assert(!TimestampFile.empty());
1402 llvm::sys::path::append(TimestampFile,
"modules.timestamp");
1405 if (::stat(TimestampFile.c_str(), &StatBuf)) {
1407 if (errno == ENOENT) {
1415 time_t TimeStampModTime = StatBuf.st_mtime;
1416 time_t CurrentTime = time(
nullptr);
1429 llvm::sys::path::native(HSOpts.
ModuleCachePath, ModuleCachePathNative);
1430 for (llvm::sys::fs::directory_iterator Dir(ModuleCachePathNative, EC), DirEnd;
1431 Dir != DirEnd && !EC; Dir.increment(EC)) {
1433 if (!llvm::sys::fs::is_directory(Dir->path()))
1437 for (llvm::sys::fs::directory_iterator File(Dir->path(), EC), FileEnd;
1438 File != FileEnd && !EC; File.increment(EC)) {
1440 StringRef Extension = llvm::sys::path::extension(File->path());
1441 if (Extension !=
".pcm" && Extension !=
".timestamp" &&
1442 llvm::sys::path::filename(File->path()) !=
"modules.idx")
1447 if (::stat(File->path().c_str(), &StatBuf))
1451 time_t FileAccessTime = StatBuf.st_atime;
1452 if (CurrentTime - FileAccessTime <=
1458 llvm::sys::fs::remove(File->path());
1461 std::string TimpestampFilename = File->path() +
".timestamp";
1462 llvm::sys::fs::remove(TimpestampFilename);
1467 if (llvm::sys::fs::directory_iterator(Dir->path(), EC) ==
1468 llvm::sys::fs::directory_iterator() && !EC)
1469 llvm::sys::fs::remove(Dir->path());
1474 if (!ModuleManager) {
1481 !
getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty() &&
1488 std::string Sysroot = HSOpts.
Sysroot;
1490 std::unique_ptr<llvm::Timer> ReadTimer;
1491 if (FrontendTimerGroup)
1492 ReadTimer = llvm::make_unique<llvm::Timer>(
"reading_modules",
1494 *FrontendTimerGroup);
1503 std::move(ReadTimer));
1512 ModuleManager->InitializeSema(
getSema());
1516 if (TheDependencyFileGenerator)
1517 TheDependencyFileGenerator->AttachToASTReader(*ModuleManager);
1518 for (
auto &Listener : DependencyCollectors)
1519 Listener->attachToASTReader(*ModuleManager);
1525 if (FrontendTimerGroup)
1526 Timer.init(
"preloading." + FileName.str(),
"Preloading " + FileName.str(),
1527 *FrontendTimerGroup);
1528 llvm::TimeRegion TimeLoading(FrontendTimerGroup ? &Timer :
nullptr);
1539 void ReadModuleName(StringRef ModuleName)
override {
1540 LoadedModules.push_back(
1544 void registerAll() {
1545 for (
auto *II : LoadedModules) {
1551 LoadedModules.clear();
1554 void markAllUnavailable() {
1555 for (
auto *II : LoadedModules) {
1566 while (!Stack.empty()) {
1567 Module *Current = Stack.pop_back_val();
1570 Stack.insert(Stack.end(),
1575 LoadedModules.clear();
1583 auto Listener = llvm::make_unique<ReadModuleNames>(*this);
1584 auto &ListenerRef = *Listener;
1586 std::move(Listener));
1595 ListenerRef.registerAll();
1604 ListenerRef.markAllUnavailable();
1616 bool IsInclusionDirective) {
1621 std::string ModuleName;
1625 for (
auto &Piece : Path) {
1626 if (!ModuleName.empty())
1628 ModuleName += Piece.first->getName();
1632 ModuleName = Path[0].first->getName();
1639 if (ImportLoc.
isValid() && LastModuleImportLoc == ImportLoc) {
1642 ModuleManager->makeModuleVisible(LastModuleImportResult, Visibility,
1644 return LastModuleImportResult;
1650 llvm::DenseMap<const IdentifierInfo *, clang::Module *>::iterator Known
1651 = KnownModules.find(Path[0].first);
1652 if (Known != KnownModules.end()) {
1654 Module = Known->second;
1657 Module = PP->getHeaderSearchInfo().lookupModule(ModuleName);
1666 Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
1669 Module = PP->getHeaderSearchInfo().lookupModule(ModuleName);
1671 PP->getHeaderSearchInfo().getHeaderSearchOpts();
1673 std::string ModuleFileName;
1675 ModuleNotFound, ModuleCache, PrebuiltModulePath, ModuleBuildPragma
1676 } Source = ModuleNotFound;
1680 auto BuiltModuleIt = BuiltModules.find(ModuleName);
1681 if (BuiltModuleIt != BuiltModules.end()) {
1682 ModuleFileName = BuiltModuleIt->second;
1683 Source = ModuleBuildPragma;
1690 PP->getHeaderSearchInfo().getPrebuiltModuleFileName(ModuleName);
1691 if (!ModuleFileName.empty())
1692 Source = PrebuiltModulePath;
1696 if (Source == ModuleNotFound && Module) {
1697 ModuleFileName = PP->getHeaderSearchInfo().getCachedModuleFileName(Module);
1698 Source = ModuleCache;
1701 if (Source == ModuleNotFound) {
1704 << ModuleName <<
SourceRange(ImportLoc, ModuleNameLoc);
1705 ModuleBuildFailed =
true;
1709 if (ModuleFileName.empty()) {
1718 ModuleBuildFailed =
true;
1727 if (FrontendTimerGroup)
1728 Timer.init(
"loading." + ModuleFileName,
"Loading " + ModuleFileName,
1729 *FrontendTimerGroup);
1730 llvm::TimeRegion TimeLoading(FrontendTimerGroup ? &Timer :
nullptr);
1734 unsigned ARRFlags = Source == ModuleCache ?
1737 switch (ModuleManager->ReadAST(ModuleFileName,
1738 Source == PrebuiltModulePath
1740 : Source == ModuleBuildPragma
1743 ImportLoc, ARRFlags)) {
1745 if (Source != ModuleCache && !Module) {
1746 Module = PP->getHeaderSearchInfo().lookupModule(ModuleName);
1748 FileMgr->getFile(ModuleFileName) != Module->
getASTFile()) {
1753 ModuleBuildFailed =
true;
1754 KnownModules[Path[0].first] =
nullptr;
1763 if (Source != ModuleCache) {
1767 ModuleBuildFailed =
true;
1768 KnownModules[Path[0].first] =
nullptr;
1773 assert(Module &&
"missing module file");
1776 ModuleBuildStack::iterator Pos = ModPath.begin(), PosEnd = ModPath.end();
1777 for (; Pos != PosEnd; ++Pos) {
1778 if (Pos->first == ModuleName)
1782 if (Pos != PosEnd) {
1784 for (; Pos != PosEnd; ++Pos) {
1785 CyclePath += Pos->first;
1786 CyclePath +=
" -> ";
1788 CyclePath += ModuleName;
1791 << ModuleName << CyclePath;
1802 ModuleBuildFailed =
true;
1810 "undiagnosed error in compileAndLoadModule");
1813 KnownModules[Path[0].first] =
nullptr;
1814 ModuleBuildFailed =
true;
1823 if (Source == PrebuiltModulePath)
1827 diag::warn_module_config_mismatch)
1836 KnownModules[Path[0].first] =
nullptr;
1842 KnownModules[Path[0].first] =
nullptr;
1843 ModuleBuildFailed =
true;
1848 Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
1857 bool MapPrivateSubModToTopLevel =
false;
1858 if (!
getLangOpts().ModulesTS && Path.size() > 1) {
1859 for (
unsigned I = 1, N = Path.size(); I != N; ++I) {
1860 StringRef Name = Path[I].first->getName();
1871 unsigned ED = Name.edit_distance((*J)->Name,
1874 if (ED <= BestEditDistance) {
1875 if (ED < BestEditDistance) {
1877 BestEditDistance = ED;
1880 Best.push_back((*J)->Name);
1885 if (Best.size() == 1) {
1887 diag::err_no_submodule_suggest)
1901 if (!Sub && PP->getLangOpts().ImplicitModules && Name ==
"Private" &&
1904 PrivateModule.append(
"_Private");
1907 auto &II = PP->getIdentifierTable().get(
1908 PrivateModule, PP->getIdentifierInfo(Module->
Name)->getTokenID());
1909 PrivPath.push_back(std::make_pair(&II, Path[0].second));
1911 if (PP->getHeaderSearchInfo().lookupModule(PrivateModule))
1913 loadModule(ImportLoc, PrivPath, Visibility, IsInclusionDirective);
1915 MapPrivateSubModToTopLevel =
true;
1917 diag::warn_no_priv_submodule_use_toplevel, ImportLoc)) {
1919 diag::warn_no_priv_submodule_use_toplevel)
1925 diag::note_private_top_level_defined);
1955 <<
SourceRange(Path.front().second, Path.back().second);
1964 <<
SourceRange(Path.front().second, Path.back().second);
1965 LastModuleImportLoc = ImportLoc;
1970 ModuleManager->makeModuleVisible(Module, Visibility, ImportLoc);
1975 for (
unsigned I = 0, N = TopModule->
ConfigMacros.size(); I != N; ++I) {
1980 LastModuleImportLoc = ImportLoc;
1982 return LastModuleImportResult;
1986 StringRef ModuleName,
1990 for (
auto &
C : CleanModuleName)
1998 if (std::error_code EC = llvm::sys::fs::createTemporaryFile(
1999 CleanModuleName,
"pcm", ModuleFileName)) {
2001 << ModuleFileName << EC.message();
2004 std::string ModuleMapFileName = (CleanModuleName +
".map").str();
2011 std::string NullTerminatedSource(Source.str());
2016 const FileEntry *ModuleMapFile = Other.getFileManager().getVirtualFile(
2017 ModuleMapFileName, NullTerminatedSource.size(), 0);
2018 Other.getSourceManager().overrideFileContents(
2020 llvm::MemoryBuffer::getMemBuffer(NullTerminatedSource.c_str()));
2022 Other.BuiltModules = std::move(BuiltModules);
2023 Other.DeleteBuiltModules =
false;
2027 BuiltModules = std::move(Other.BuiltModules);
2032 ModuleFileName, PreBuildStep, PostBuildStep)) {
2033 BuiltModules[ModuleName] = ModuleFileName.str();
2034 llvm::sys::RemoveFileOnSignal(ModuleFileName);
2046 ModuleManager->makeModuleVisible(Mod, Visibility, ImportLoc);
2051 if (
getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty())
2060 ModuleManager->loadGlobalIndex();
2065 llvm::sys::fs::create_directories(
2070 ModuleManager->resetForReload();
2071 ModuleManager->loadGlobalIndex();
2072 GlobalIndex = ModuleManager->getGlobalIndex();
2076 if (!HaveFullGlobalModuleIndex && GlobalIndex && !
buildingModule()) {
2078 bool RecreateIndex =
false;
2081 Module *TheModule = I->second;
2085 Path.push_back(std::make_pair(
2087 std::reverse(Path.begin(), Path.end());
2090 RecreateIndex =
true;
2093 if (RecreateIndex) {
2097 ModuleManager->resetForReload();
2098 ModuleManager->loadGlobalIndex();
2099 GlobalIndex = ModuleManager->getGlobalIndex();
2101 HaveFullGlobalModuleIndex =
true;
2135 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.
static bool compileAndLoadModule(CompilerInstance &ImportingInstance, SourceLocation ImportLoc, SourceLocation ModuleNameLoc, Module *Module, StringRef ModuleFileName)
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.
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...
MemoryBufferCache & getPCMCache() const
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.
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...
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
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.
Manage memory buffers across multiple users.
static PTHManager * Create(StringRef file, DiagnosticsEngine &Diags)
Create - This method creates PTHManager objects.
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.
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)
std::string FindPchSource
If non-empty, search the pch input file as if it was a header included by this file.
The virtual file system interface.
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)
void loadModuleFromSource(SourceLocation ImportLoc, StringRef ModuleName, StringRef Source) override
Attempt to load the given module from the specified source buffer.
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 void collectHeaderMaps(const HeaderSearch &HS, std::shared_ptr< ModuleDependencyCollector > MDC)
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.
CodeGenOptions & getCodeGenOpts()
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.
Module * findModule(StringRef Name) const
Retrieve a module with the given name.
MemoryBufferCache & getPCMCache() const
std::error_code make_error_code(BuildPreambleError Error)
directory_iterator & increment(std::error_code &EC)
Equivalent to operator++, with an error code.
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.
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.
PreprocessorOutputOptions & getPreprocessorOutputOpts()
Concrete class used by the front-end to report problems and issues.
ASTConsumer & getASTConsumer() const
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.
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...
bool DisablePCHValidation
When true, disables most of the normal validation performed on precompiled headers.
Builds a depdenency file when attached to a Preprocessor (for includes) and ASTReader (for module imp...
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.
static ErrorCode writeIndex(FileManager &FileMgr, const PCHContainerReader &PCHContainerRdr, StringRef Path)
Write a global index into the given.
unsigned IsSystem
Whether this is a "system" module (which assumes that all headers in it are system headers)...
bool DetailedRecord
Whether we should maintain a detailed record of all macro definitions and expansions.
const FileEntry * getFile(StringRef Filename, bool OpenFile=false, bool CacheFailure=true)
Lookup, cache, and verify the specified file (real or virtual).
static DependencyFileGenerator * CreateAndAttachToPreprocessor(Preprocessor &PP, const DependencyOutputOptions &Opts)
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.
const DirectoryEntry * getDirectory(StringRef DirName, bool CacheFailure=true)
Lookup, cache, and verify the specified directory (real or virtual).
Module * findSubmodule(StringRef Name) const
Find the submodule with the given name.
void setVirtualFileSystem(IntrusiveRefCntPtr< vfs::FileSystem > FS)
Replace the current virtual file system.
Describes the result of attempting to load a module.
std::string ShowIncludesPretendHeader
In /showIncludes mode, pretend the main TU is a header with this name.
IntrusiveRefCntPtr< ASTReader > getModuleManager() const
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
Defines version macros and version-related utility functions for Clang.
void finalizeCurrentBuffers()
Finalize the current buffers in the cache.
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.
IntrusiveRefCntPtr< vfs::FileSystem > createVFSFromCompilerInvocation(const CompilerInvocation &CI, DiagnosticsEngine &Diags)
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
FileManager * createFileManager()
Create the file manager and replace any existing one with it.
static InputKind::Language getLanguageFromOptions(const LangOptions &LangOpts)
Determine the appropriate source input kind based on language options.
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.
The result type of a method or function.
virtual void ExecuteAction()=0
Callback to run the program action, using the initialized compiler instance.
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)
std::string AuxTriple
Auxiliary triple for CUDA compilation.
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...
DirectoryLookup - This class represents one entry in the search list that specifies the search order ...
The AST file was missing.
bool lookupMissingImports(StringRef Name, SourceLocation TriggerLoc) override
Check global module index for missing imports.
std::unique_ptr< Sema > takeSema()
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.
void AttachToASTReader(ASTReader &R)
CompilerInstance - Helper class for managing a single instance of the Clang compiler.
Encodes a location in the source.
bool Execute()
Set the source manager's main input file, and run the action.
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.
void collectVFSFromYAML(std::unique_ptr< llvm::MemoryBuffer > Buffer, llvm::SourceMgr::DiagHandlerTy DiagHandler, StringRef YAMLFilePath, SmallVectorImpl< YAMLVFSEntry > &CollectedEntries, void *DiagContext=nullptr, IntrusiveRefCntPtr< FileSystem > ExternalFS=getRealFileSystem())
Collect all pairs of <virtual path, real path> entries from the YAMLFilePath.
unsigned getNumWarnings() const
Options for controlling the compiler diagnostics engine.
std::vector< FrontendInputFile > Inputs
The input files and their types.
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...
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 hasVirtualFileSystem() const
bool hasSourceManager() const
std::unique_ptr< raw_pwrite_stream > createNullOutputFile()
DependencyOutputOptions - Options for controlling the compiler dependency file generation.
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...
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.
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)
Reads an AST files chain containing the contents of a translation unit.
File is an explicitly-loaded module.
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.
llvm::ErrorOr< std::unique_ptr< llvm::MemoryBuffer > > getBufferForFile(const FileEntry *Entry, bool isVolatile=false, bool ShouldCloseOpenFile=true)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful, otherwise returning null.
unsigned UseGlobalModuleIndex
Whether we can use the global module index if available.
vfs::FileSystem & getVirtualFileSystem() const
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 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.
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
void BuryPointer(const void *Ptr)
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.
Cached information about one directory (either on disk or in the virtual file system).
bool hasASTContext() const
char __ovld __cnfn max(char x, char y)
Returns y if x < y, otherwise it returns x.
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
An input iterator over the entries in a virtual path, similar to llvm::sys::fs::directory_iterator.
FileID getPredefinesFileID() const
Returns the FileID for the preprocessor predefines.
DiagnosticsEngine & getDiagnostics() const
IntrusiveRefCntPtr< vfs::FileSystem > getVirtualFileSystem() 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.
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.
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.
void createModuleManager()
}
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.
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.
unsigned PrintShowIncludes
Print cl.exe style /showIncludes info.
TargetOptions & getTargetOpts()
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) const
Forwarding function for diagnostics.
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...
std::string DiagnosticLogFile
The file to log diagnostic output to.
std::string TokenCache
If given, a PTH cache file to use for speeding up header parsing.
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
bool lookupIdentifier(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.
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?