19 #include "clang/Config/config.h"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/Support/CrashRecoveryContext.h"
38 #include "llvm/Support/Errc.h"
39 #include "llvm/Support/FileSystem.h"
40 #include "llvm/Support/Host.h"
41 #include "llvm/Support/LockFileManager.h"
42 #include "llvm/Support/MemoryBuffer.h"
43 #include "llvm/Support/Path.h"
44 #include "llvm/Support/Program.h"
45 #include "llvm/Support/Signals.h"
46 #include "llvm/Support/Timer.h"
47 #include "llvm/Support/raw_ostream.h"
49 #include <system_error>
53 using namespace clang;
55 CompilerInstance::CompilerInstance(
56 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
59 ModuleManager(nullptr),
60 ThePCHContainerOperations(std::move(PCHContainerOps)),
61 BuildGlobalModuleIndex(
false), HaveFullGlobalModuleIndex(
false),
62 ModuleBuildFailed(
false) {}
65 assert(OutputFiles.empty() &&
"Still output files in flight?");
73 return (BuildGlobalModuleIndex ||
74 (ModuleManager && ModuleManager->isGlobalIndexUnavailable() &&
91 VirtualFileSystem.reset();
112 Consumer = std::move(Value);
119 CompletionConsumer.reset(Value);
123 return std::move(TheSema);
127 return ModuleManager;
130 ModuleManager = std::move(Reader);
133 std::shared_ptr<ModuleDependencyCollector>
135 return ModuleDepCollector;
139 std::shared_ptr<ModuleDependencyCollector> Collector) {
140 ModuleDepCollector = std::move(Collector);
148 std::unique_ptr<raw_ostream> StreamOwner;
149 raw_ostream *OS = &llvm::errs();
152 auto FileOS = llvm::make_unique<llvm::raw_fd_ostream>(
154 llvm::sys::fs::F_Append | llvm::sys::fs::F_Text);
156 Diags.
Report(diag::warn_fe_cc_log_diagnostics_failure)
159 FileOS->SetUnbuffered();
161 StreamOwner = std::move(FileOS);
166 auto Logger = llvm::make_unique<LogDiagnosticPrinter>(*OS, DiagOpts,
167 std::move(StreamOwner));
177 StringRef OutputFile) {
178 auto SerializedConsumer =
183 Diags.
takeClient(), std::move(SerializedConsumer)));
186 Diags.
getClient(), std::move(SerializedConsumer)));
191 bool ShouldOwnClient) {
199 bool ShouldOwnClient,
208 Diags->setClient(Client, ShouldOwnClient);
213 if (Opts->VerifyDiagnostics)
258 Diags.
Report(diag::err_fe_remap_missing_from_file) << RB.first;
275 Diags.
Report(diag::err_fe_remap_missing_to_file) << RF.first << RF.second;
283 Diags.
Report(diag::err_fe_remap_missing_from_file) << RF.first;
322 PP->setPTHManager(PTHMgr);
326 PP->createPreprocessingRecord();
330 PP->getFileManager(), PPOpts);
338 PP->getLangOpts(), PP->getTargetInfo().getTriple());
342 if (PP->getLangOpts().Modules && PP->getLangOpts().ImplicitModules)
348 TheDependencyFileGenerator.reset(
357 ModuleDepCollector = std::make_shared<ModuleDependencyCollector>(
361 if (ModuleDepCollector)
364 for (
auto &Listener : DependencyCollectors)
365 Listener->attachToPreprocessor(*PP);
372 if (OutputPath ==
"-")
391 llvm::sys::path::append(SpecificModuleCache,
393 return SpecificModuleCache.str();
410 StringRef Path,
bool DisablePCHValidation,
bool AllowPCHWithCompilerErrors,
411 void *DeserializationListener,
bool OwnDeserializationListener) {
418 DeserializationListener,
419 OwnDeserializationListener, Preamble,
424 StringRef Path, StringRef Sysroot,
bool DisablePCHValidation,
428 void *DeserializationListener,
bool OwnDeserializationListener,
429 bool Preamble,
bool UseGlobalModuleIndex) {
433 PP, Context, PCHContainerRdr, Extensions,
434 Sysroot.empty() ?
"" : Sysroot.data(), DisablePCHValidation,
435 AllowPCHWithCompilerErrors,
false,
442 Reader->setDeserializationListener(
443 static_cast<ASTDeserializationListener *>(DeserializationListener),
444 OwnDeserializationListener);
445 switch (Reader->ReadAST(Path,
495 if (!CompletionConsumer) {
501 if (!CompletionConsumer)
509 if (CompletionConsumer->isOutputBinary() &&
510 llvm::sys::ChangeStdoutToBinary()) {
517 FrontendTimerGroup.reset(
new llvm::TimerGroup(
"Clang front-end time report"));
519 new llvm::Timer(
"Clang front-end timer", *FrontendTimerGroup));
539 TUKind, CompletionConsumer));
545 OutputFiles.push_back(std::move(OutFile));
549 for (OutputFile &OF : OutputFiles) {
550 if (!OF.TempFilename.empty()) {
552 llvm::sys::fs::remove(OF.TempFilename);
558 FileMgr->FixupRelativePath(NewOutFile);
559 if (std::error_code ec =
560 llvm::sys::fs::rename(OF.TempFilename, NewOutFile)) {
562 << OF.TempFilename << OF.Filename << ec.message();
564 llvm::sys::fs::remove(OF.TempFilename);
567 }
else if (!OF.Filename.empty() && EraseFiles)
568 llvm::sys::fs::remove(OF.Filename);
571 NonSeekStream.reset();
574 std::unique_ptr<raw_pwrite_stream>
576 StringRef Extension) {
578 true, InFile, Extension,
583 return llvm::make_unique<llvm::raw_null_ostream>();
586 std::unique_ptr<raw_pwrite_stream>
588 bool RemoveFileOnSignal, StringRef InFile,
589 StringRef Extension,
bool UseTemporary,
590 bool CreateMissingDirectories) {
591 std::string OutputPathName, TempPathName;
594 OutputPath, EC, Binary, RemoveFileOnSignal, InFile, Extension,
595 UseTemporary, CreateMissingDirectories, &OutputPathName, &TempPathName);
605 OutputFile((OutputPathName !=
"-") ? OutputPathName :
"", TempPathName));
611 StringRef OutputPath, std::error_code &
Error,
bool Binary,
612 bool RemoveFileOnSignal, StringRef InFile, StringRef Extension,
613 bool UseTemporary,
bool CreateMissingDirectories,
614 std::string *ResultPathName, std::string *TempPathName) {
615 assert((!CreateMissingDirectories || UseTemporary) &&
616 "CreateMissingDirectories is only allowed when using temporary files");
618 std::string OutFile, TempFile;
619 if (!OutputPath.empty()) {
620 OutFile = OutputPath;
621 }
else if (InFile ==
"-") {
623 }
else if (!Extension.empty()) {
625 llvm::sys::path::replace_extension(Path, Extension);
626 OutFile = Path.str();
631 std::unique_ptr<llvm::raw_fd_ostream> OS;
636 UseTemporary =
false;
638 llvm::sys::fs::file_status Status;
639 llvm::sys::fs::status(OutputPath, Status);
640 if (llvm::sys::fs::exists(Status)) {
642 if (!llvm::sys::fs::can_write(OutputPath)) {
649 if (!llvm::sys::fs::is_regular_file(Status))
650 UseTemporary =
false;
659 TempPath +=
"-%%%%%%%%";
662 llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath);
664 if (CreateMissingDirectories &&
665 EC == llvm::errc::no_such_file_or_directory) {
666 StringRef Parent = llvm::sys::path::parent_path(OutputPath);
667 EC = llvm::sys::fs::create_directories(Parent);
669 EC = llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath);
674 OS.reset(
new llvm::raw_fd_ostream(fd,
true));
675 OSFile = TempFile = TempPath.str();
684 OS.reset(
new llvm::raw_fd_ostream(
686 (Binary ? llvm::sys::fs::F_None : llvm::sys::fs::F_Text)));
692 if (RemoveFileOnSignal)
693 llvm::sys::RemoveFileOnSignal(OSFile);
696 *ResultPathName = OutFile;
698 *TempPathName = TempFile;
700 if (!Binary || OS->supportsSeeking())
701 return std::move(OS);
703 auto B = llvm::make_unique<llvm::buffer_ostream>(*OS);
704 assert(!NonSeekStream);
705 NonSeekStream = std::move(OS);
728 std::unique_ptr<llvm::MemoryBuffer>(Input.
getBuffer()), Kind));
730 "Couldn't establish MainFileID!");
734 StringRef InputFile = Input.
getFile();
737 if (InputFile !=
"-") {
740 File = FileMgr.
getFile(InputFile,
true);
755 Includers.push_back(std::make_pair(FindFile, FindFile->
getDir()));
758 UnusedCurDir, Includers,
768 Diags.
Report(diag::err_fe_error_reading) << InputFile;
781 File = FileMgr.
getVirtualFile(InputFile, (*MB)->getBufferSize(), 0);
784 Diags.
Report(diag::err_cannot_open_file) << InputFile
785 << MB.getError().message();
793 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> SBOrErr =
794 llvm::MemoryBuffer::getSTDIN();
795 if (std::error_code EC = SBOrErr.getError()) {
796 Diags.
Report(diag::err_fe_error_reading_stdin) << EC.message();
799 std::unique_ptr<llvm::MemoryBuffer> SB = std::move(SBOrErr.get());
802 SB->getBufferSize(), 0);
809 "Couldn't establish MainFileID!");
816 assert(
hasDiagnostics() &&
"Diagnostics engine is not initialized!");
818 assert(!
getFrontendOpts().ShowVersion &&
"Client must handle '-version'!");
822 raw_ostream &OS = llvm::errs();
832 auto TO = std::make_shared<TargetOptions>();
851 <<
" based upon " << BACKEND_PACKAGE_STRING
852 <<
" default target " << llvm::sys::getDefaultTargetTriple() <<
"\n";
858 llvm::EnableStatistics();
882 OS << NumWarnings <<
" warning" << (NumWarnings == 1 ?
"" :
"s");
883 if (NumWarnings && NumErrors)
886 OS << NumErrors <<
" error" << (NumErrors == 1 ?
"" :
"s");
887 if (NumWarnings || NumErrors)
888 OS <<
" generated.\n";
917 StringRef ModuleFileName) {
929 Invocation->getLangOpts()->resetNonModularOptions();
936 std::remove_if(PPOpts.
Macros.begin(), PPOpts.
Macros.end(),
937 [&HSOpts](
const std::pair<std::string, bool> &def) {
938 StringRef MacroDef = def.first;
959 FrontendOpts.
OutputFile = ModuleFileName.str();
963 FrontendOpts.
Inputs.clear();
969 Invocation->getDiagnosticOpts().VerifyDiagnostics = 0;
971 Invocation->getModuleHash() &&
"Module hash mismatch!");
988 Instance.createSourceManager(Instance.getFileManager());
1002 std::string InferredModuleMapContent;
1006 FrontendOpts.
Inputs.emplace_back(ModuleMapFile->getName(), IK);
1009 llvm::sys::path::append(FakeModuleMapFile,
"__inferred_module.map");
1010 FrontendOpts.
Inputs.emplace_back(FakeModuleMapFile, IK);
1012 llvm::raw_string_ostream OS(InferredModuleMapContent);
1016 std::unique_ptr<llvm::MemoryBuffer> ModuleMapBuffer =
1017 llvm::MemoryBuffer::getMemBuffer(InferredModuleMapContent);
1018 ModuleMapFile = Instance.getFileManager().getVirtualFile(
1019 FakeModuleMapFile, InferredModuleMapContent.size(), 0);
1029 diag::remark_module_build)
1030 << Module->
Name << ModuleFileName;
1034 const unsigned ThreadStackSize = 8 << 20;
1035 llvm::CrashRecoveryContext CRC;
1036 CRC.RunSafelyOnThread([&]() { Instance.ExecuteAction(CreateModuleAction); },
1040 diag::remark_module_build_done)
1047 Instance.clearOutputFiles(
true);
1055 return !Instance.getDiagnostics().hasErrorOccurred();
1061 StringRef ModuleFileName) {
1064 auto diagnoseBuildFailure = [&] {
1065 Diags.
Report(ModuleNameLoc, diag::err_module_not_built)
1071 StringRef Dir = llvm::sys::path::parent_path(ModuleFileName);
1072 llvm::sys::fs::create_directories(Dir);
1076 llvm::LockFileManager Locked(ModuleFileName);
1078 case llvm::LockFileManager::LFS_Error:
1079 Diags.
Report(ModuleNameLoc, diag::err_module_lock_failure)
1080 << Module->
Name << Locked.getErrorMessage();
1083 case llvm::LockFileManager::LFS_Owned:
1087 diagnoseBuildFailure();
1092 case llvm::LockFileManager::LFS_Shared:
1095 switch (Locked.waitForUnlock()) {
1096 case llvm::LockFileManager::Res_Success:
1099 case llvm::LockFileManager::Res_OwnerDied:
1101 case llvm::LockFileManager::Res_Timeout:
1102 Diags.
Report(ModuleNameLoc, diag::err_module_lock_timeout)
1105 Locked.unsafeRemoveLockFile();
1115 ModuleLoadCapabilities);
1118 Locked == llvm::LockFileManager::LFS_Shared) {
1124 diagnoseBuildFailure();
1128 diagnoseBuildFailure();
1149 for (
auto *MD = LatestLocalMD; MD; MD = MD->getPrevious()) {
1154 if (
auto *DMD = dyn_cast<DefMacroDirective>(MD))
1155 CmdLineDefinition = DMD->getMacroInfo();
1160 if (CurrentDefinition == CmdLineDefinition) {
1162 }
else if (!CurrentDefinition) {
1165 PP.
Diag(ImportLoc, diag::warn_module_config_macro_undef)
1167 auto LatestDef = LatestLocalMD->getDefinition();
1168 assert(LatestDef.isUndefined() &&
1169 "predefined macro went away with no #undef?");
1170 PP.
Diag(LatestDef.getUndefLocation(), diag::note_module_def_undef_here)
1173 }
else if (!CmdLineDefinition) {
1176 PP.
Diag(ImportLoc, diag::warn_module_config_macro_undef)
1178 PP.
Diag(CurrentDefinition->getDefinitionLoc(),
1179 diag::note_module_def_undef_here)
1181 }
else if (!CurrentDefinition->isIdenticalTo(*CmdLineDefinition, PP,
1184 PP.
Diag(ImportLoc, diag::warn_module_config_macro_undef)
1186 PP.
Diag(CurrentDefinition->getDefinitionLoc(),
1187 diag::note_module_def_undef_here)
1195 llvm::raw_fd_ostream Out(TimestampFile.str(), EC, llvm::sys::fs::F_None);
1201 struct stat StatBuf;
1204 assert(!TimestampFile.empty());
1205 llvm::sys::path::append(TimestampFile,
"modules.timestamp");
1208 if (::stat(TimestampFile.c_str(), &StatBuf)) {
1210 if (errno == ENOENT) {
1218 time_t TimeStampModTime = StatBuf.st_mtime;
1219 time_t CurrentTime = time(
nullptr);
1232 llvm::sys::path::native(HSOpts.
ModuleCachePath, ModuleCachePathNative);
1233 for (llvm::sys::fs::directory_iterator Dir(ModuleCachePathNative, EC), DirEnd;
1234 Dir != DirEnd && !EC; Dir.increment(EC)) {
1236 if (!llvm::sys::fs::is_directory(Dir->path()))
1240 for (llvm::sys::fs::directory_iterator File(Dir->path(), EC), FileEnd;
1241 File != FileEnd && !EC; File.increment(EC)) {
1243 StringRef Extension = llvm::sys::path::extension(File->path());
1244 if (Extension !=
".pcm" && Extension !=
".timestamp" &&
1245 llvm::sys::path::filename(File->path()) !=
"modules.idx")
1250 if (::stat(File->path().c_str(), &StatBuf))
1254 time_t FileAccessTime = StatBuf.st_atime;
1255 if (CurrentTime - FileAccessTime <=
1261 llvm::sys::fs::remove(File->path());
1264 std::string TimpestampFilename = File->path() +
".timestamp";
1265 llvm::sys::fs::remove(TimpestampFilename);
1270 if (llvm::sys::fs::directory_iterator(Dir->path(), EC) ==
1271 llvm::sys::fs::directory_iterator() && !EC)
1272 llvm::sys::fs::remove(Dir->path());
1277 if (!ModuleManager) {
1284 !
getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty() &&
1291 std::string Sysroot = HSOpts.
Sysroot;
1293 std::unique_ptr<llvm::Timer> ReadTimer;
1294 if (FrontendTimerGroup)
1295 ReadTimer = llvm::make_unique<llvm::Timer>(
"Reading modules",
1296 *FrontendTimerGroup);
1305 std::move(ReadTimer));
1314 ModuleManager->InitializeSema(
getSema());
1318 if (TheDependencyFileGenerator)
1319 TheDependencyFileGenerator->AttachToASTReader(*ModuleManager);
1320 for (
auto &Listener : DependencyCollectors)
1321 Listener->attachToASTReader(*ModuleManager);
1327 if (FrontendTimerGroup)
1328 Timer.init(
"Preloading " + FileName.str(), *FrontendTimerGroup);
1329 llvm::TimeRegion TimeLoading(FrontendTimerGroup ? &Timer :
nullptr);
1340 void ReadModuleName(StringRef ModuleName)
override {
1341 LoadedModules.push_back(
1345 void registerAll() {
1346 for (
auto *II : LoadedModules) {
1352 LoadedModules.clear();
1355 void markAllUnavailable() {
1356 for (
auto *II : LoadedModules) {
1363 LoadedModules.clear();
1371 auto Listener = llvm::make_unique<ReadModuleNames>(*this);
1372 auto &ListenerRef = *Listener;
1374 std::move(Listener));
1383 ListenerRef.registerAll();
1392 ListenerRef.markAllUnavailable();
1404 bool IsInclusionDirective) {
1406 StringRef ModuleName = Path[0].first->getName();
1412 if (ImportLoc.
isValid() && LastModuleImportLoc == ImportLoc) {
1415 ModuleManager->makeModuleVisible(LastModuleImportResult, Visibility,
1417 return LastModuleImportResult;
1424 = KnownModules.find(Path[0].first);
1425 if (Known != KnownModules.end()) {
1427 Module = Known->second;
1430 Module = PP->getHeaderSearchInfo().lookupModule(ModuleName);
1431 Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
1434 Module = PP->getHeaderSearchInfo().lookupModule(ModuleName);
1439 ModuleBuildFailed =
true;
1443 std::string ModuleFileName =
1444 PP->getHeaderSearchInfo().getModuleFileName(Module);
1445 if (ModuleFileName.empty()) {
1454 ModuleBuildFailed =
true;
1463 if (FrontendTimerGroup)
1464 Timer.init(
"Loading " + ModuleFileName, *FrontendTimerGroup);
1465 llvm::TimeRegion TimeLoading(FrontendTimerGroup ? &Timer :
nullptr);
1469 switch (ModuleManager->ReadAST(ModuleFileName,
1471 ImportLoc, ARRFlags)) {
1478 assert(Module &&
"missing module file");
1482 for (; Pos != PosEnd; ++Pos) {
1483 if (Pos->first == ModuleName)
1487 if (Pos != PosEnd) {
1489 for (; Pos != PosEnd; ++Pos) {
1490 CyclePath += Pos->first;
1491 CyclePath +=
" -> ";
1493 CyclePath += ModuleName;
1496 << ModuleName << CyclePath;
1507 ModuleBuildFailed =
true;
1515 "undiagnosed error in compileAndLoadModule");
1518 KnownModules[Path[0].first] =
nullptr;
1519 ModuleBuildFailed =
true;
1533 KnownModules[Path[0].first] =
nullptr;
1539 KnownModules[Path[0].first] =
nullptr;
1540 ModuleBuildFailed =
true;
1545 Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
1554 if (Path.size() > 1) {
1555 for (
unsigned I = 1, N = Path.size();
I != N; ++
I) {
1556 StringRef
Name = Path[
I].first->getName();
1567 unsigned ED = Name.edit_distance((*J)->Name,
1570 if (ED <= BestEditDistance) {
1571 if (ED < BestEditDistance) {
1573 BestEditDistance = ED;
1576 Best.push_back((*J)->Name);
1581 if (Best.size() == 1) {
1583 diag::err_no_submodule_suggest)
1618 <<
SourceRange(Path.front().second, Path.back().second);
1630 diag::err_module_header_missing)
1635 << Requirement.second << Requirement.first
1636 <<
SourceRange(Path.front().second, Path.back().second);
1638 LastModuleImportLoc = ImportLoc;
1643 ModuleManager->makeModuleVisible(Module, Visibility, ImportLoc);
1648 for (
unsigned I = 0, N = TopModule->
ConfigMacros.size();
I != N; ++
I) {
1653 LastModuleImportLoc = ImportLoc;
1655 return LastModuleImportResult;
1666 ModuleManager->makeModuleVisible(Mod, Visibility, ImportLoc);
1671 if (
getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty())
1680 ModuleManager->loadGlobalIndex();
1685 llvm::sys::fs::create_directories(
1690 ModuleManager->resetForReload();
1691 ModuleManager->loadGlobalIndex();
1692 GlobalIndex = ModuleManager->getGlobalIndex();
1696 if (!HaveFullGlobalModuleIndex && GlobalIndex && !
buildingModule()) {
1698 bool RecreateIndex =
false;
1701 Module *TheModule =
I->second;
1705 Path.push_back(std::make_pair(
1707 std::reverse(Path.begin(), Path.end());
1710 RecreateIndex =
true;
1713 if (RecreateIndex) {
1717 ModuleManager->resetForReload();
1718 ModuleManager->loadGlobalIndex();
1719 GlobalIndex = ModuleManager->getGlobalIndex();
1721 HaveFullGlobalModuleIndex =
true;
std::string OutputFile
The output file, if any.
SourceManager & getSourceManager() const
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.
virtual bool isModelParsingAction() const
Is this action invoked on a model file?
LangOptions & getLangOpts()
ASTReadResult
The result of reading the control block of an AST file, which can fail for various reasons...
bool hasFileManager() const
ASTContext & getASTContext() const
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 ...
std::vector< std::pair< std::string, bool > > Macros
std::string ModuleDependencyOutputDir
The directory to copy module dependencies to when collecting them.
DiagnosticConsumer * getClient()
module_iterator module_begin() const
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.
bool hasASTConsumer() const
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...
void setCodeCompletionConsumer(CodeCompleteConsumer *Value)
setCodeCompletionConsumer - Replace the current code completion consumer; the compiler instance takes...
vfs::FileSystem & getVirtualFileSystem() const
Defines the clang::FileManager interface and associated types.
Module * findModule(StringRef Name) const
Retrieve a module with the given name.
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.
Module * getTopLevelModule()
Retrieve the top-level module for this (sub)module, which may be this module.
Defines the SourceManager interface.
IntrusiveRefCntPtr< FileSystem > getRealFileSystem()
Gets an vfs::FileSystem for the 'real' file system, as seen by the operating system.
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
void createSema(TranslationUnitKind TUKind, CodeCompleteConsumer *CompletionConsumer)
Create the Sema object to be used for parsing.
Abstract base class for actions which can be performed by the frontend.
DiagnosticOptions & getDiagnosticOpts()
std::string HeaderIncludeOutputFile
The file to write header include output to.
bool hasErrorOccurred() const
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...
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
std::unique_ptr< DiagnosticConsumer > takeClient()
Return the current diagnostic client along with ownership of that client.
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)
TargetInfo & getTarget() const
void setSourceManager(SourceManager *Value)
setSourceManager - Replace the current source manager.
std::string getModuleHash() const
Retrieve a module hash string that is suitable for uniquely identifying the conditions under which th...
const FileEntry * getASTFile() const
The serialized AST file for this module, if one was created.
SourceManager & getSourceManager() const
Return the current source manager.
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.
The client can handle an AST file that cannot load because it is missing.
virtual void adjust(const LangOptions &Opts)
Set forced language options.
std::string FindPchSource
If non-empty, search the pch input file as it was a header.
std::string getFullModuleName() const
Retrieve the full name of this module, including the path from its top-level module.
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.
unsigned getNumWarnings() const
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)
class LLVM_ALIGNAS(8) DependentTemplateSpecializationType const IdentifierInfo * Name
Represents a template specialization type whose template cannot be resolved, e.g. ...
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 createFileManager()
Create the file manager and replace any existing one with it.
void createSourceManager(FileManager &FileMgr)
Create the source manager and replace any existing one with it.
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.
const MacroInfo * getMacroInfo(const IdentifierInfo *II) const
unsigned DetailedRecord
Whether we should maintain a detailed record of all macro definitions and expansions.
void setASTContext(ASTContext *Value)
setASTContext - Replace the current AST context.
CodeGenOptions & getCodeGenOpts()
bool buildingModule() const
Returns true if this instance is building a module.
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...
ASTConsumer & getASTConsumer() const
unsigned BuildingImplicitModule
Whether we are performing an implicit module build.
Describes a module or submodule.
FileManager & getFileManager() const
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.
unsigned ShowStats
Show frontend performance metrics and statistics.
void setBuildGlobalModuleIndex(bool Build)
Set the flag indicating whether we should (re)build the global module index.
bool isAvailable() const
Determine whether this module is available for use within the current translation unit...
FrontendOptions & getFrontendOpts()
IntrusiveRefCntPtr< vfs::FileSystem > getVirtualFileSystem() const
Visibility
Describes the different kinds of visibility that a declaration may have.
DiagnosticConsumer & getDiagnosticClient() const
PreprocessorOutputOptions & getPreprocessorOutputOpts()
Concrete class used by the front-end to report problems and issues.
HeaderSearch & getHeaderSearchInfo() const
IntrusiveRefCntPtr< FailedModulesSet > FailedModules
The set of modules that failed to build.
module_iterator module_end() const
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.
const FileEntry * getContainingModuleMapFile(const Module *Module) const
Retrieve the module map file containing the definition of the given module.
IntrusiveRefCntPtr< ASTReader > getModuleManager() const
submodule_iterator submodule_end()
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...
The AST file itself appears corrupted.
detail::InMemoryDirectory::const_iterator I
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.
Preprocessor & getPreprocessor() const
Return the current preprocessor.
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) const
Forwarding function for diagnostics.
std::vector< Module * >::iterator submodule_iterator
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.
bool hasVirtualFileSystem() const
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...
static ErrorCode writeIndex(FileManager &FileMgr, const PCHContainerReader &PCHContainerRdr, StringRef Path)
Write a global index into the given.
llvm::StringMap< Module * >::const_iterator module_iterator
unsigned IsSystem
Whether this is a "system" module (which assumes that all headers in it are system headers)...
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.
void setPreprocessor(Preprocessor *Value)
Replace the current preprocessor.
Module * findSubmodule(StringRef Name) const
Find the submodule with the given name.
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.
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
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.
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...
void setInvocation(CompilerInvocation *Value)
setInvocation - Replace the current invocation.
static InputKind getSourceInputKindFromOptions(const LangOptions &LangOpts)
Determine the appropriate source input kind based on language options.
ModuleBuildStack getModuleBuildStack() const
Retrieve the module build stack.
std::string getSpecificModuleCachePath()
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...
Defines version macros and version-related utility functions for Clang.
Defines the clang::Preprocessor interface.
bool hasDiagnostics() const
void createASTContext()
Create the AST context.
unsigned ShowHeaderIncludes
Show header inclusions (-H).
void setSema(Sema *S)
Replace the current Sema; the compiler instance takes ownership of S.
static TargetInfo * CreateTargetInfo(DiagnosticsEngine &Diags, const std::shared_ptr< TargetOptions > &Opts)
Construct a target for the given options.
DiagnosticsEngine & getDiagnostics() const
Get the current diagnostics engine.
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 ...
StringRef getTopLevelModuleName() const
Retrieve the name of the top-level module.
The AST file was missing.
bool lookupMissingImports(StringRef Name, SourceLocation TriggerLoc) override
Check global module index for missing imports.
std::unique_ptr< Sema > takeSema()
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.
bool hasSourceManager() const
FileSystemOptions & getFileSystemOpts()
bool isNamedPipe() const
Check whether the file is a named pipe (and thus can't be opened by the native FileManager methods)...
The control block was read successfully.
void setPreprocessor(Preprocessor *pp)
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.
const char * getName() const
void print(raw_ostream &OS, unsigned Indent=0) const
Print the module map for this module to the given stream.
CompilerInstance - Helper class for managing a single instance of the Clang compiler.
Encodes a location in the source.
const PCHContainerReader & getPCHContainerReader() const
Return the appropriate PCHContainerReader depending on the current CodeGenOptions.
bool Execute()
Set the source manager's main input file, and run the action.
const TemplateArgument * iterator
File is a PCH file treated as such.
ParsedSourceLocation CodeCompletionAt
If given, enable code completion at the provided location.
bool isValid() const
Return true if this is a valid SourceLocation object.
Options for controlling the compiler diagnostics engine.
static bool compileModuleImpl(CompilerInstance &ImportingInstance, SourceLocation ImportLoc, Module *Module, StringRef ModuleFileName)
Compile a module file for the given module, using the options provided by the importing compiler inst...
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...
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...
std::shared_ptr< PCHContainerOperations > getPCHContainerOperations() const
void InitBuiltinTypes(const TargetInfo &Target, const TargetInfo *AuxTarget=nullptr)
Initialize built-in types.
void pushModuleBuildStack(StringRef moduleName, FullSourceLoc importLoc)
Push an entry to the module build stack.
FileID getMainFileID() const
Returns the FileID of the main source file.
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...
void resetNonModularOptions()
Reset any options that are not considered when building a module.
A global index for a set of module files, providing information about the identifiers within those mo...
The AST file was writtten with a different language/target configuration.
DiagnosticsEngine & getDiagnostics() const
const char * getName() const
FileID getPredefinesFileID() const
Returns the FileID for the preprocessor predefines.
TargetInfo * getAuxTarget() const
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.
void setDeserializationListener(ASTDeserializationListener *Listener, bool TakeOwnership=false)
Set the AST deserialization listener.
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.
FileManager & getFileManager() const
Return the current file manager to the caller.
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.
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.
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
detail::InMemoryDirectory::const_iterator E
FrontendOptions - Options for controlling the behavior of the frontend.
Abstract interface for a module loader.
Defines the Diagnostic-related interfaces.
Encapsulates the data about a macro definition (e.g.
SourceLocation DefinitionLoc
The location of the module definition.
void clearOutputFiles(bool EraseFiles)
clearOutputFiles - Clear the output file list.
void BuryPointer(const void *Ptr)
const FileEntry * getModuleMapFileForUniquing(const Module *M) const
Get the module map file that (along with the module name) uniquely identifies this module...
Abstract interface for callback invocations by the ASTReader.
MacroDirective * getLocalMacroDirectiveHistory(const IdentifierInfo *II) const
Given an identifier, return the latest non-imported macro directive for that identifier.
void setOverridenFilesKeepOriginalName(bool value)
Set true if the SourceManager should report the original file name for contents of files that were ov...
std::pair< std::string, bool > Requirement
An individual requirement: a feature name and a flag indicating the required state of that feature...
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
bool hasASTContext() const
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.
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. ...
~CompilerInstance() override
bool shouldBuildGlobalModuleIndex() const
Indicates whether we should (re)build the global module index.
std::shared_ptr< ModuleDependencyCollector > getModuleDepCollector() 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...
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.
std::vector< std::string > ConfigMacros
The set of "configuration macros", which are macros that (intentionally) change how this module is bu...
bool hasPreprocessor() const
Defines the clang::FrontendAction interface and various convenience abstract classes (clang::ASTFront...
unsigned getNumErrors() const
The AST file was written by a different version of Clang.
#define CLANG_VERSION_STRING
A string that describes the Clang version number, e.g., "1.0".
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)
GlobalModuleIndex * loadGlobalModuleIndex(SourceLocation TriggerLoc) override
Load, create, or return global module.
bool hadMacroDefinition() const
Returns true if this identifier was #defined to some value at any moment.
bool ownsClient() const
Determine whether this DiagnosticsEngine object own its client.
A trivial tuple used to represent a source range.
unsigned PrintShowIncludes
Print cl.exe style /showIncludes info.
const DirectoryEntry * getDir() const
Return the directory the file lives in.
Records the set of modules.
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 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.