#include "clang/Frontend/CompilerInstance.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/Basic/CharInfo.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/LangStandard.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/Stack.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Basic/Version.h"
#include "clang/Config/config.h"
#include "clang/Frontend/ChainedDiagnosticConsumer.h"
#include "clang/Frontend/FrontendAction.h"
#include "clang/Frontend/FrontendActions.h"
#include "clang/Frontend/FrontendDiagnostic.h"
#include "clang/Frontend/FrontendPluginRegistry.h"
#include "clang/Frontend/LogDiagnosticPrinter.h"
#include "clang/Frontend/SerializedDiagnosticPrinter.h"
#include "clang/Frontend/TextDiagnosticPrinter.h"
#include "clang/Frontend/Utils.h"
#include "clang/Frontend/VerifyDiagnosticConsumer.h"
#include "clang/Lex/HeaderSearch.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Lex/PreprocessorOptions.h"
#include "clang/Sema/CodeCompleteConsumer.h"
#include "clang/Sema/Sema.h"
#include "clang/Serialization/ASTReader.h"
#include "clang/Serialization/GlobalModuleIndex.h"
#include "clang/Serialization/InMemoryModuleCache.h"
#include "llvm/ADT/ScopeExit.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/BuryPointer.h"
#include "llvm/Support/CrashRecoveryContext.h"
#include "llvm/Support/Errc.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/LockFileManager.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Program.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/TimeProfiler.h"
#include "llvm/Support/Timer.h"
#include "llvm/Support/raw_ostream.h"
#include <time.h>
#include <utility>
using namespace clang;
CompilerInstance::CompilerInstance(
std::shared_ptr<PCHContainerOperations> PCHContainerOps,
InMemoryModuleCache *SharedModuleCache)
: ModuleLoader( SharedModuleCache),
Invocation(new CompilerInvocation()),
ModuleCache(SharedModuleCache ? SharedModuleCache
: new InMemoryModuleCache),
ThePCHContainerOperations(std::move(PCHContainerOps)) {}
CompilerInstance::~CompilerInstance() {
assert(OutputFiles.empty() && "Still output files in flight?");
}
void CompilerInstance::setInvocation(
std::shared_ptr<CompilerInvocation> Value) {
Invocation = std::move(Value);
}
bool CompilerInstance::shouldBuildGlobalModuleIndex() const {
return (BuildGlobalModuleIndex ||
(TheASTReader && TheASTReader->isGlobalIndexUnavailable() &&
getFrontendOpts().GenerateGlobalModuleIndex)) &&
!DisableGeneratingGlobalModuleIndex;
}
void CompilerInstance::setDiagnostics(DiagnosticsEngine *Value) {
Diagnostics = Value;
}
void CompilerInstance::setVerboseOutputStream(raw_ostream &Value) {
OwnedVerboseOutputStream.reset();
VerboseOutputStream = &Value;
}
void CompilerInstance::setVerboseOutputStream(std::unique_ptr<raw_ostream> Value) {
OwnedVerboseOutputStream.swap(Value);
VerboseOutputStream = OwnedVerboseOutputStream.get();
}
void CompilerInstance::setTarget(TargetInfo *Value) { Target = Value; }
void CompilerInstance::setAuxTarget(TargetInfo *Value) { AuxTarget = Value; }
bool CompilerInstance::createTarget() {
setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(),
getInvocation().TargetOpts));
if (!hasTarget())
return false;
if (!getAuxTarget() &&
(getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
getLangOpts().SYCLIsDevice) &&
!getFrontendOpts().AuxTriple.empty()) {
auto TO = std::make_shared<TargetOptions>();
TO->Triple = llvm::Triple::normalize(getFrontendOpts().AuxTriple);
if (getFrontendOpts().AuxTargetCPU)
TO->CPU = getFrontendOpts().AuxTargetCPU.value();
if (getFrontendOpts().AuxTargetFeatures)
TO->FeaturesAsWritten = getFrontendOpts().AuxTargetFeatures.value();
TO->HostTriple = getTarget().getTriple().str();
setAuxTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), TO));
}
if (!getTarget().hasStrictFP() && !getLangOpts().ExpStrictFP) {
if (getLangOpts().RoundingMath) {
getDiagnostics().Report(diag::warn_fe_backend_unsupported_fp_rounding);
getLangOpts().RoundingMath = false;
}
auto FPExc = getLangOpts().getFPExceptionMode();
if (FPExc != LangOptions::FPE_Default && FPExc != LangOptions::FPE_Ignore) {
getDiagnostics().Report(diag::warn_fe_backend_unsupported_fp_exceptions);
getLangOpts().setFPExceptionMode(LangOptions::FPE_Ignore);
}
}
if (getLangOpts().OpenCL &&
!getTarget().validateOpenCLTarget(getLangOpts(), getDiagnostics()))
return false;
getTarget().adjust(getDiagnostics(), getLangOpts());
getTarget().adjustTargetOptions(getCodeGenOpts(), getTargetOpts());
if (auto *Aux = getAuxTarget())
getTarget().setAuxTarget(Aux);
return true;
}
llvm::vfs::FileSystem &CompilerInstance::getVirtualFileSystem() const {
return getFileManager().getVirtualFileSystem();
}
void CompilerInstance::setFileManager(FileManager *Value) {
FileMgr = Value;
}
void CompilerInstance::setSourceManager(SourceManager *Value) {
SourceMgr = Value;
}
void CompilerInstance::setPreprocessor(std::shared_ptr<Preprocessor> Value) {
PP = std::move(Value);
}
void CompilerInstance::setASTContext(ASTContext *Value) {
Context = Value;
if (Context && Consumer)
getASTConsumer().Initialize(getASTContext());
}
void CompilerInstance::setSema(Sema *S) {
TheSema.reset(S);
}
void CompilerInstance::setASTConsumer(std::unique_ptr<ASTConsumer> Value) {
Consumer = std::move(Value);
if (Context && Consumer)
getASTConsumer().Initialize(getASTContext());
}
void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
CompletionConsumer.reset(Value);
}
std::unique_ptr<Sema> CompilerInstance::takeSema() {
return std::move(TheSema);
}
IntrusiveRefCntPtr<ASTReader> CompilerInstance::getASTReader() const {
return TheASTReader;
}
void CompilerInstance::setASTReader(IntrusiveRefCntPtr<ASTReader> Reader) {
assert(ModuleCache.get() == &Reader->getModuleManager().getModuleCache() &&
"Expected ASTReader to use the same PCM cache");
TheASTReader = std::move(Reader);
}
std::shared_ptr<ModuleDependencyCollector>
CompilerInstance::getModuleDepCollector() const {
return ModuleDepCollector;
}
void CompilerInstance::setModuleDepCollector(
std::shared_ptr<ModuleDependencyCollector> Collector) {
ModuleDepCollector = std::move(Collector);
}
static void collectHeaderMaps(const HeaderSearch &HS,
std::shared_ptr<ModuleDependencyCollector> MDC) {
SmallVector<std::string, 4> HeaderMapFileNames;
HS.getHeaderMapFileNames(HeaderMapFileNames);
for (auto &Name : HeaderMapFileNames)
MDC->addFile(Name);
}
static void collectIncludePCH(CompilerInstance &CI,
std::shared_ptr<ModuleDependencyCollector> MDC) {
const PreprocessorOptions &PPOpts = CI.getPreprocessorOpts();
if (PPOpts.ImplicitPCHInclude.empty())
return;
StringRef PCHInclude = PPOpts.ImplicitPCHInclude;
FileManager &FileMgr = CI.getFileManager();
auto PCHDir = FileMgr.getOptionalDirectoryRef(PCHInclude);
if (!PCHDir) {
MDC->addFile(PCHInclude);
return;
}
std::error_code EC;
SmallString<128> DirNative;
llvm::sys::path::native(PCHDir->getName(), DirNative);
llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
SimpleASTReaderListener Validator(CI.getPreprocessor());
for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
Dir != DirEnd && !EC; Dir.increment(EC)) {
if (!ASTReader::readASTFileControlBlock(
Dir->path(), FileMgr, CI.getPCHContainerReader(),
false, Validator,
false))
MDC->addFile(Dir->path());
}
}
static void collectVFSEntries(CompilerInstance &CI,
std::shared_ptr<ModuleDependencyCollector> MDC) {
if (CI.getHeaderSearchOpts().VFSOverlayFiles.empty())
return;
SmallVector<llvm::vfs::YAMLVFSEntry, 16> VFSEntries;
for (const std::string &VFSFile : CI.getHeaderSearchOpts().VFSOverlayFiles) {
llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer =
llvm::MemoryBuffer::getFile(VFSFile);
if (!Buffer)
return;
llvm::vfs::collectVFSFromYAML(std::move(Buffer.get()),
nullptr, VFSFile, VFSEntries);
}
for (auto &E : VFSEntries)
MDC->addFile(E.VPath, E.RPath);
}
static void SetUpDiagnosticLog(DiagnosticOptions *DiagOpts,
const CodeGenOptions *CodeGenOpts,
DiagnosticsEngine &Diags) {
std::error_code EC;
std::unique_ptr<raw_ostream> StreamOwner;
raw_ostream *OS = &llvm::errs();
if (DiagOpts->DiagnosticLogFile != "-") {
auto FileOS = std::make_unique<llvm::raw_fd_ostream>(
DiagOpts->DiagnosticLogFile, EC,
llvm::sys::fs::OF_Append | llvm::sys::fs::OF_TextWithCRLF);
if (EC) {
Diags.Report(diag::warn_fe_cc_log_diagnostics_failure)
<< DiagOpts->DiagnosticLogFile << EC.message();
} else {
FileOS->SetUnbuffered();
OS = FileOS.get();
StreamOwner = std::move(FileOS);
}
}
auto Logger = std::make_unique<LogDiagnosticPrinter>(*OS, DiagOpts,
std::move(StreamOwner));
if (CodeGenOpts)
Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags);
if (Diags.ownsClient()) {
Diags.setClient(
new ChainedDiagnosticConsumer(Diags.takeClient(), std::move(Logger)));
} else {
Diags.setClient(
new ChainedDiagnosticConsumer(Diags.getClient(), std::move(Logger)));
}
}
static void SetupSerializedDiagnostics(DiagnosticOptions *DiagOpts,
DiagnosticsEngine &Diags,
StringRef OutputFile) {
auto SerializedConsumer =
clang::serialized_diags::create(OutputFile, DiagOpts);
if (Diags.ownsClient()) {
Diags.setClient(new ChainedDiagnosticConsumer(
Diags.takeClient(), std::move(SerializedConsumer)));
} else {
Diags.setClient(new ChainedDiagnosticConsumer(
Diags.getClient(), std::move(SerializedConsumer)));
}
}
void CompilerInstance::createDiagnostics(DiagnosticConsumer *Client,
bool ShouldOwnClient) {
Diagnostics = createDiagnostics(&getDiagnosticOpts(), Client,
ShouldOwnClient, &getCodeGenOpts());
}
IntrusiveRefCntPtr<DiagnosticsEngine>
CompilerInstance::createDiagnostics(DiagnosticOptions *Opts,
DiagnosticConsumer *Client,
bool ShouldOwnClient,
const CodeGenOptions *CodeGenOpts) {
IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
IntrusiveRefCntPtr<DiagnosticsEngine>
Diags(new DiagnosticsEngine(DiagID, Opts));
if (Client) {
Diags->setClient(Client, ShouldOwnClient);
} else
Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
if (Opts->VerifyDiagnostics)
Diags->setClient(new VerifyDiagnosticConsumer(*Diags));
if (!Opts->DiagnosticLogFile.empty())
SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags);
if (!Opts->DiagnosticSerializationFile.empty())
SetupSerializedDiagnostics(Opts, *Diags,
Opts->DiagnosticSerializationFile);
ProcessWarningOptions(*Diags, *Opts);
return Diags;
}
FileManager *CompilerInstance::createFileManager(
IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
if (!VFS)
VFS = FileMgr ? &FileMgr->getVirtualFileSystem()
: createVFSFromCompilerInvocation(getInvocation(),
getDiagnostics());
assert(VFS && "FileManager has no VFS?");
FileMgr = new FileManager(getFileSystemOpts(), std::move(VFS));
return FileMgr.get();
}
void CompilerInstance::createSourceManager(FileManager &FileMgr) {
SourceMgr = new SourceManager(getDiagnostics(), FileMgr);
}
static void InitializeFileRemapping(DiagnosticsEngine &Diags,
SourceManager &SourceMgr,
FileManager &FileMgr,
const PreprocessorOptions &InitOpts) {
for (const auto &RB : InitOpts.RemappedFileBuffers) {
const FileEntry *FromFile =
FileMgr.getVirtualFile(RB.first, RB.second->getBufferSize(), 0);
if (!FromFile) {
Diags.Report(diag::err_fe_remap_missing_from_file) << RB.first;
if (!InitOpts.RetainRemappedFileBuffers)
delete RB.second;
continue;
}
if (InitOpts.RetainRemappedFileBuffers)
SourceMgr.overrideFileContents(FromFile, RB.second->getMemBufferRef());
else
SourceMgr.overrideFileContents(
FromFile, std::unique_ptr<llvm::MemoryBuffer>(
const_cast<llvm::MemoryBuffer *>(RB.second)));
}
for (const auto &RF : InitOpts.RemappedFiles) {
auto ToFile = FileMgr.getFile(RF.second);
if (!ToFile) {
Diags.Report(diag::err_fe_remap_missing_to_file) << RF.first << RF.second;
continue;
}
const FileEntry *FromFile =
FileMgr.getVirtualFile(RF.first, (*ToFile)->getSize(), 0);
if (!FromFile) {
Diags.Report(diag::err_fe_remap_missing_from_file) << RF.first;
continue;
}
SourceMgr.overrideFileContents(FromFile, *ToFile);
}
SourceMgr.setOverridenFilesKeepOriginalName(
InitOpts.RemappedFilesKeepOriginalName);
}
void CompilerInstance::createPreprocessor(TranslationUnitKind TUKind) {
const PreprocessorOptions &PPOpts = getPreprocessorOpts();
TheASTReader.reset();
HeaderSearch *HeaderInfo =
new HeaderSearch(getHeaderSearchOptsPtr(), getSourceManager(),
getDiagnostics(), getLangOpts(), &getTarget());
PP = std::make_shared<Preprocessor>(Invocation->getPreprocessorOptsPtr(),
getDiagnostics(), getLangOpts(),
getSourceManager(), *HeaderInfo, *this,
nullptr,
true, TUKind);
getTarget().adjust(getDiagnostics(), getLangOpts());
PP->Initialize(getTarget(), getAuxTarget());
if (PPOpts.DetailedRecord)
PP->createPreprocessingRecord();
InitializeFileRemapping(PP->getDiagnostics(), PP->getSourceManager(),
PP->getFileManager(), PPOpts);
InitializePreprocessor(*PP, PPOpts, getPCHContainerReader(),
getFrontendOpts());
const llvm::Triple *HeaderSearchTriple = &PP->getTargetInfo().getTriple();
if (PP->getTargetInfo().getTriple().getOS() == llvm::Triple::CUDA &&
PP->getAuxTargetInfo())
HeaderSearchTriple = &PP->getAuxTargetInfo()->getTriple();
ApplyHeaderSearchOptions(PP->getHeaderSearchInfo(), getHeaderSearchOpts(),
PP->getLangOpts(), *HeaderSearchTriple);
PP->setPreprocessedOutput(getPreprocessorOutputOpts().ShowCPP);
if (PP->getLangOpts().Modules && PP->getLangOpts().ImplicitModules) {
std::string ModuleHash = getInvocation().getModuleHash();
PP->getHeaderSearchInfo().setModuleHash(ModuleHash);
PP->getHeaderSearchInfo().setModuleCachePath(
getSpecificModuleCachePath(ModuleHash));
}
const DependencyOutputOptions &DepOpts = getDependencyOutputOpts();
if (!DepOpts.OutputFile.empty())
addDependencyCollector(std::make_shared<DependencyFileGenerator>(DepOpts));
if (!DepOpts.DOTOutputFile.empty())
AttachDependencyGraphGen(*PP, DepOpts.DOTOutputFile,
getHeaderSearchOpts().Sysroot);
if (!ModuleDepCollector && !DepOpts.ModuleDependencyOutputDir.empty()) {
ModuleDepCollector = std::make_shared<ModuleDependencyCollector>(
DepOpts.ModuleDependencyOutputDir);
}
if (ModuleDepCollector) {
addDependencyCollector(ModuleDepCollector);
collectHeaderMaps(PP->getHeaderSearchInfo(), ModuleDepCollector);
collectIncludePCH(*this, ModuleDepCollector);
collectVFSEntries(*this, ModuleDepCollector);
}
for (auto &Listener : DependencyCollectors)
Listener->attachToPreprocessor(*PP);
if (DepOpts.ShowHeaderIncludes)
AttachHeaderIncludeGen(*PP, DepOpts);
if (!DepOpts.HeaderIncludeOutputFile.empty()) {
StringRef OutputPath = DepOpts.HeaderIncludeOutputFile;
if (OutputPath == "-")
OutputPath = "";
AttachHeaderIncludeGen(*PP, DepOpts,
true, OutputPath,
false);
}
if (DepOpts.ShowIncludesDest != ShowIncludesDestination::None) {
AttachHeaderIncludeGen(*PP, DepOpts,
true, "",
true, true);
}
}
std::string CompilerInstance::getSpecificModuleCachePath(StringRef ModuleHash) {
SmallString<256> SpecificModuleCache(getHeaderSearchOpts().ModuleCachePath);
if (!SpecificModuleCache.empty() && !getHeaderSearchOpts().DisableModuleHash)
llvm::sys::path::append(SpecificModuleCache, ModuleHash);
return std::string(SpecificModuleCache.str());
}
void CompilerInstance::createASTContext() {
Preprocessor &PP = getPreprocessor();
auto *Context = new ASTContext(getLangOpts(), PP.getSourceManager(),
PP.getIdentifierTable(), PP.getSelectorTable(),
PP.getBuiltinInfo(), PP.TUKind);
Context->InitBuiltinTypes(getTarget(), getAuxTarget());
setASTContext(Context);
}
namespace {
struct ReadModuleNames : ASTReaderListener {
Preprocessor &PP;
llvm::SmallVector<std::string, 8> LoadedModules;
ReadModuleNames(Preprocessor &PP) : PP(PP) {}
void ReadModuleName(StringRef ModuleName) override {
LoadedModules.push_back(ModuleName.str());
}
void registerAll() {
ModuleMap &MM = PP.getHeaderSearchInfo().getModuleMap();
for (const std::string &LoadedModule : LoadedModules)
MM.cacheModuleLoad(*PP.getIdentifierInfo(LoadedModule),
MM.findModule(LoadedModule));
LoadedModules.clear();
}
void markAllUnavailable() {
for (const std::string &LoadedModule : LoadedModules) {
if (Module *M = PP.getHeaderSearchInfo().getModuleMap().findModule(
LoadedModule)) {
M->HasIncompatibleModuleFile = true;
SmallVector<Module *, 2> Stack;
Stack.push_back(M);
while (!Stack.empty()) {
Module *Current = Stack.pop_back_val();
if (Current->IsUnimportable) continue;
Current->IsAvailable = true;
Stack.insert(Stack.end(),
Current->submodule_begin(), Current->submodule_end());
}
}
}
LoadedModules.clear();
}
};
}
void CompilerInstance::createPCHExternalASTSource(
StringRef Path, DisableValidationForModuleKind DisableValidation,
bool AllowPCHWithCompilerErrors, void *DeserializationListener,
bool OwnDeserializationListener) {
bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
TheASTReader = createPCHExternalASTSource(
Path, getHeaderSearchOpts().Sysroot, DisableValidation,
AllowPCHWithCompilerErrors, getPreprocessor(), getModuleCache(),
getASTContext(), getPCHContainerReader(),
getFrontendOpts().ModuleFileExtensions, DependencyCollectors,
DeserializationListener, OwnDeserializationListener, Preamble,
getFrontendOpts().UseGlobalModuleIndex);
}
IntrusiveRefCntPtr<ASTReader> CompilerInstance::createPCHExternalASTSource(
StringRef Path, StringRef Sysroot,
DisableValidationForModuleKind DisableValidation,
bool AllowPCHWithCompilerErrors, Preprocessor &PP,
InMemoryModuleCache &ModuleCache, ASTContext &Context,
const PCHContainerReader &PCHContainerRdr,
ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
ArrayRef<std::shared_ptr<DependencyCollector>> DependencyCollectors,
void *DeserializationListener, bool OwnDeserializationListener,
bool Preamble, bool UseGlobalModuleIndex) {
HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts();
IntrusiveRefCntPtr<ASTReader> Reader(new ASTReader(
PP, ModuleCache, &Context, PCHContainerRdr, Extensions,
Sysroot.empty() ? "" : Sysroot.data(), DisableValidation,
AllowPCHWithCompilerErrors, false,
HSOpts.ModulesValidateSystemHeaders, HSOpts.ValidateASTInputFilesContent,
UseGlobalModuleIndex));
Context.setExternalSource(Reader.get());
Reader->setDeserializationListener(
static_cast<ASTDeserializationListener *>(DeserializationListener),
OwnDeserializationListener);
for (auto &Listener : DependencyCollectors)
Listener->attachToASTReader(*Reader);
auto Listener = std::make_unique<ReadModuleNames>(PP);
auto &ListenerRef = *Listener;
ASTReader::ListenerScope ReadModuleNamesListener(*Reader,
std::move(Listener));
switch (Reader->ReadAST(Path,
Preamble ? serialization::MK_Preamble
: serialization::MK_PCH,
SourceLocation(),
ASTReader::ARR_None)) {
case ASTReader::Success:
PP.setPredefines(Reader->getSuggestedPredefines());
ListenerRef.registerAll();
return Reader;
case ASTReader::Failure:
break;
case ASTReader::Missing:
case ASTReader::OutOfDate:
case ASTReader::VersionMismatch:
case ASTReader::ConfigurationMismatch:
case ASTReader::HadErrors:
break;
}
ListenerRef.markAllUnavailable();
Context.setExternalSource(nullptr);
return nullptr;
}
static bool EnableCodeCompletion(Preprocessor &PP,
StringRef Filename,
unsigned Line,
unsigned Column) {
auto Entry = PP.getFileManager().getFile(Filename);
if (!Entry) {
PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
<< Filename;
return true;
}
PP.SetCodeCompletionPoint(*Entry, Line, Column);
return false;
}
void CompilerInstance::createCodeCompletionConsumer() {
const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
if (!CompletionConsumer) {
setCodeCompletionConsumer(createCodeCompletionConsumer(
getPreprocessor(), Loc.FileName, Loc.Line, Loc.Column,
getFrontendOpts().CodeCompleteOpts, llvm::outs()));
return;
} else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
Loc.Line, Loc.Column)) {
setCodeCompletionConsumer(nullptr);
return;
}
}
void CompilerInstance::createFrontendTimer() {
FrontendTimerGroup.reset(
new llvm::TimerGroup("frontend", "Clang front-end time report"));
FrontendTimer.reset(
new llvm::Timer("frontend", "Clang front-end timer",
*FrontendTimerGroup));
}
CodeCompleteConsumer *
CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
StringRef Filename,
unsigned Line,
unsigned Column,
const CodeCompleteOptions &Opts,
raw_ostream &OS) {
if (EnableCodeCompletion(PP, Filename, Line, Column))
return nullptr;
return new PrintingCodeCompleteConsumer(Opts, OS);
}
void CompilerInstance::createSema(TranslationUnitKind TUKind,
CodeCompleteConsumer *CompletionConsumer) {
TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
TUKind, CompletionConsumer));
if (ExternalSemaSrc) {
TheSema->addExternalSource(ExternalSemaSrc.get());
ExternalSemaSrc->InitializeSema(*TheSema);
}
}
void CompilerInstance::clearOutputFiles(bool EraseFiles) {
assert(!hasASTConsumer() && "ASTConsumer should be reset");
for (OutputFile &OF : OutputFiles) {
if (EraseFiles) {
if (OF.File)
consumeError(OF.File->discard());
if (!OF.Filename.empty())
llvm::sys::fs::remove(OF.Filename);
continue;
}
if (!OF.File)
continue;
if (OF.File->TmpName.empty()) {
consumeError(OF.File->discard());
continue;
}
SmallString<128> NewOutFile(OF.Filename);
FileMgr->FixupRelativePath(NewOutFile);
llvm::Error E = OF.File->keep(NewOutFile);
if (!E)
continue;
getDiagnostics().Report(diag::err_unable_to_rename_temp)
<< OF.File->TmpName << OF.Filename << std::move(E);
llvm::sys::fs::remove(OF.File->TmpName);
}
OutputFiles.clear();
if (DeleteBuiltModules) {
for (auto &Module : BuiltModules)
llvm::sys::fs::remove(Module.second);
BuiltModules.clear();
}
}
std::unique_ptr<raw_pwrite_stream> CompilerInstance::createDefaultOutputFile(
bool Binary, StringRef InFile, StringRef Extension, bool RemoveFileOnSignal,
bool CreateMissingDirectories, bool ForceUseTemporary) {
StringRef OutputPath = getFrontendOpts().OutputFile;
Optional<SmallString<128>> PathStorage;
if (OutputPath.empty()) {
if (InFile == "-" || Extension.empty()) {
OutputPath = "-";
} else {
PathStorage.emplace(InFile);
llvm::sys::path::replace_extension(*PathStorage, Extension);
OutputPath = *PathStorage;
}
}
return createOutputFile(OutputPath, Binary, RemoveFileOnSignal,
getFrontendOpts().UseTemporary || ForceUseTemporary,
CreateMissingDirectories);
}
std::unique_ptr<raw_pwrite_stream> CompilerInstance::createNullOutputFile() {
return std::make_unique<llvm::raw_null_ostream>();
}
std::unique_ptr<raw_pwrite_stream>
CompilerInstance::createOutputFile(StringRef OutputPath, bool Binary,
bool RemoveFileOnSignal, bool UseTemporary,
bool CreateMissingDirectories) {
Expected<std::unique_ptr<raw_pwrite_stream>> OS =
createOutputFileImpl(OutputPath, Binary, RemoveFileOnSignal, UseTemporary,
CreateMissingDirectories);
if (OS)
return std::move(*OS);
getDiagnostics().Report(diag::err_fe_unable_to_open_output)
<< OutputPath << errorToErrorCode(OS.takeError()).message();
return nullptr;
}
Expected<std::unique_ptr<llvm::raw_pwrite_stream>>
CompilerInstance::createOutputFileImpl(StringRef OutputPath, bool Binary,
bool RemoveFileOnSignal,
bool UseTemporary,
bool CreateMissingDirectories) {
assert((!CreateMissingDirectories || UseTemporary) &&
"CreateMissingDirectories is only allowed when using temporary files");
std::unique_ptr<llvm::raw_fd_ostream> OS;
Optional<StringRef> OSFile;
if (UseTemporary) {
if (OutputPath == "-")
UseTemporary = false;
else {
llvm::sys::fs::file_status Status;
llvm::sys::fs::status(OutputPath, Status);
if (llvm::sys::fs::exists(Status)) {
if (!llvm::sys::fs::can_write(OutputPath))
return llvm::errorCodeToError(
make_error_code(llvm::errc::operation_not_permitted));
if (!llvm::sys::fs::is_regular_file(Status))
UseTemporary = false;
}
}
}
Optional<llvm::sys::fs::TempFile> Temp;
if (UseTemporary) {
StringRef OutputExtension = llvm::sys::path::extension(OutputPath);
SmallString<128> TempPath =
StringRef(OutputPath).drop_back(OutputExtension.size());
TempPath += "-%%%%%%%%";
TempPath += OutputExtension;
TempPath += ".tmp";
Expected<llvm::sys::fs::TempFile> ExpectedFile =
llvm::sys::fs::TempFile::create(
TempPath, llvm::sys::fs::all_read | llvm::sys::fs::all_write,
Binary ? llvm::sys::fs::OF_None : llvm::sys::fs::OF_Text);
llvm::Error E = handleErrors(
ExpectedFile.takeError(), [&](const llvm::ECError &E) -> llvm::Error {
std::error_code EC = E.convertToErrorCode();
if (CreateMissingDirectories &&
EC == llvm::errc::no_such_file_or_directory) {
StringRef Parent = llvm::sys::path::parent_path(OutputPath);
EC = llvm::sys::fs::create_directories(Parent);
if (!EC) {
ExpectedFile = llvm::sys::fs::TempFile::create(TempPath);
if (!ExpectedFile)
return llvm::errorCodeToError(
llvm::errc::no_such_file_or_directory);
}
}
return llvm::errorCodeToError(EC);
});
if (E) {
consumeError(std::move(E));
} else {
Temp = std::move(ExpectedFile.get());
OS.reset(new llvm::raw_fd_ostream(Temp->FD, false));
OSFile = Temp->TmpName;
}
}
if (!OS) {
OSFile = OutputPath;
std::error_code EC;
OS.reset(new llvm::raw_fd_ostream(
*OSFile, EC,
(Binary ? llvm::sys::fs::OF_None : llvm::sys::fs::OF_TextWithCRLF)));
if (EC)
return llvm::errorCodeToError(EC);
}
OutputFiles.emplace_back(((OutputPath != "-") ? OutputPath : "").str(),
std::move(Temp));
if (!Binary || OS->supportsSeeking())
return std::move(OS);
return std::make_unique<llvm::buffer_unique_ostream>(std::move(OS));
}
bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input){
return InitializeSourceManager(Input, getDiagnostics(), getFileManager(),
getSourceManager());
}
bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input,
DiagnosticsEngine &Diags,
FileManager &FileMgr,
SourceManager &SourceMgr) {
SrcMgr::CharacteristicKind Kind =
Input.getKind().getFormat() == InputKind::ModuleMap
? Input.isSystem() ? SrcMgr::C_System_ModuleMap
: SrcMgr::C_User_ModuleMap
: Input.isSystem() ? SrcMgr::C_System : SrcMgr::C_User;
if (Input.isBuffer()) {
SourceMgr.setMainFileID(SourceMgr.createFileID(Input.getBuffer(), Kind));
assert(SourceMgr.getMainFileID().isValid() &&
"Couldn't establish MainFileID!");
return true;
}
StringRef InputFile = Input.getFile();
auto FileOrErr = InputFile == "-"
? FileMgr.getSTDIN()
: FileMgr.getFileRef(InputFile, true);
if (!FileOrErr) {
auto EC = llvm::errorToErrorCode(FileOrErr.takeError());
if (InputFile != "-")
Diags.Report(diag::err_fe_error_reading) << InputFile;
else
Diags.Report(diag::err_fe_error_reading_stdin) << EC.message();
return false;
}
SourceMgr.setMainFileID(
SourceMgr.createFileID(*FileOrErr, SourceLocation(), Kind));
assert(SourceMgr.getMainFileID().isValid() &&
"Couldn't establish MainFileID!");
return true;
}
bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
noteBottomOfStack();
auto FinishDiagnosticClient = llvm::make_scope_exit([&]() {
getDiagnosticClient().finish();
});
raw_ostream &OS = getVerboseOutputStream();
if (!Act.PrepareToExecute(*this))
return false;
if (!createTarget())
return false;
if (getFrontendOpts().ProgramAction == frontend::RewriteObjC)
getTarget().noSignedCharForObjCBool();
if (getHeaderSearchOpts().Verbose)
OS << "clang -cc1 version " CLANG_VERSION_STRING
<< " based upon " << BACKEND_PACKAGE_STRING
<< " default target " << llvm::sys::getDefaultTargetTriple() << "\n";
if (getCodeGenOpts().TimePasses)
createFrontendTimer();
if (getFrontendOpts().ShowStats || !getFrontendOpts().StatsFile.empty())
llvm::EnableStatistics(false);
for (const FrontendInputFile &FIF : getFrontendOpts().Inputs) {
if (hasSourceManager() && !Act.isModelParsingAction())
getSourceManager().clearIDTables();
if (Act.BeginSourceFile(*this, FIF)) {
if (llvm::Error Err = Act.Execute()) {
consumeError(std::move(Err)); }
Act.EndSourceFile();
}
}
if (getDiagnosticOpts().ShowCarets) {
unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
if (NumWarnings)
OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
if (NumWarnings && NumErrors)
OS << " and ";
if (NumErrors)
OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
if (NumWarnings || NumErrors) {
OS << " generated";
if (getLangOpts().CUDA) {
if (!getLangOpts().CUDAIsDevice) {
OS << " when compiling for host";
} else {
OS << " when compiling for " << getTargetOpts().CPU;
}
}
OS << ".\n";
}
}
if (getFrontendOpts().ShowStats) {
if (hasFileManager()) {
getFileManager().PrintStats();
OS << '\n';
}
llvm::PrintStatistics(OS);
}
StringRef StatsFile = getFrontendOpts().StatsFile;
if (!StatsFile.empty()) {
std::error_code EC;
auto StatS = std::make_unique<llvm::raw_fd_ostream>(
StatsFile, EC, llvm::sys::fs::OF_TextWithCRLF);
if (EC) {
getDiagnostics().Report(diag::warn_fe_unable_to_open_stats_file)
<< StatsFile << EC.message();
} else {
llvm::PrintStatisticsJSON(*StatS);
}
}
return !getDiagnostics().getClient()->getNumErrors();
}
void CompilerInstance::LoadRequestedPlugins() {
for (const std::string &Path : getFrontendOpts().Plugins) {
std::string Error;
if (llvm::sys::DynamicLibrary::LoadLibraryPermanently(Path.c_str(), &Error))
getDiagnostics().Report(diag::err_fe_unable_to_load_plugin)
<< Path << Error;
}
for (const FrontendPluginRegistry::entry &Plugin :
FrontendPluginRegistry::entries()) {
std::unique_ptr<PluginASTAction> P(Plugin.instantiate());
if (P->getActionType() == PluginASTAction::ReplaceAction) {
getFrontendOpts().ProgramAction = clang::frontend::PluginAction;
getFrontendOpts().ActionName = Plugin.getName().str();
break;
}
}
}
static Language getLanguageFromOptions(const LangOptions &LangOpts) {
if (LangOpts.OpenCL)
return Language::OpenCL;
if (LangOpts.CUDA)
return Language::CUDA;
if (LangOpts.ObjC)
return LangOpts.CPlusPlus ? Language::ObjCXX : Language::ObjC;
return LangOpts.CPlusPlus ? Language::CXX : Language::C;
}
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 &) {}) {
llvm::TimeTraceScope TimeScope("Module Compile", ModuleName);
if (ImportingInstance.getModuleCache().isPCMFinal(ModuleFileName)) {
ImportingInstance.getDiagnostics().Report(
ImportLoc, diag::err_module_rebuild_finalized)
<< ModuleName;
return false;
}
auto Invocation =
std::make_shared<CompilerInvocation>(ImportingInstance.getInvocation());
PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Invocation->getLangOpts()->resetNonModularOptions();
PPOpts.resetNonModularOptions();
HeaderSearchOptions &HSOpts = Invocation->getHeaderSearchOpts();
llvm::erase_if(PPOpts.Macros,
[&HSOpts](const std::pair<std::string, bool> &def) {
StringRef MacroDef = def.first;
return HSOpts.ModulesIgnoreMacros.contains(
llvm::CachedHashString(MacroDef.split('=').first));
});
Invocation->getLangOpts()->ModuleName =
ImportingInstance.getInvocation().getLangOpts()->ModuleName;
Invocation->getLangOpts()->CurrentModule = std::string(ModuleName);
PreprocessorOptions &ImportingPPOpts
= ImportingInstance.getInvocation().getPreprocessorOpts();
if (!ImportingPPOpts.FailedModules)
ImportingPPOpts.FailedModules =
std::make_shared<PreprocessorOptions::FailedModulesSet>();
PPOpts.FailedModules = ImportingPPOpts.FailedModules;
FrontendOptions &FrontendOpts = Invocation->getFrontendOpts();
FrontendOpts.OutputFile = ModuleFileName.str();
FrontendOpts.DisableFree = false;
FrontendOpts.GenerateGlobalModuleIndex = false;
FrontendOpts.BuildingImplicitModule = true;
FrontendOpts.OriginalModuleMap = std::string(OriginalModuleMapFile);
HSOpts.ModulesHashContent = true;
FrontendOpts.Inputs = {Input};
PPOpts.RetainRemappedFileBuffers = true;
Invocation->getDiagnosticOpts().VerifyDiagnostics = 0;
assert(ImportingInstance.getInvocation().getModuleHash() ==
Invocation->getModuleHash() && "Module hash mismatch!");
CompilerInstance Instance(ImportingInstance.getPCHContainerOperations(),
&ImportingInstance.getModuleCache());
auto &Inv = *Invocation;
Instance.setInvocation(std::move(Invocation));
Instance.createDiagnostics(new ForwardingDiagnosticConsumer(
ImportingInstance.getDiagnosticClient()),
true);
Instance.setFileManager(&ImportingInstance.getFileManager());
Instance.createSourceManager(Instance.getFileManager());
SourceManager &SourceMgr = Instance.getSourceManager();
SourceMgr.setModuleBuildStack(
ImportingInstance.getSourceManager().getModuleBuildStack());
SourceMgr.pushModuleBuildStack(ModuleName,
FullSourceLoc(ImportLoc, ImportingInstance.getSourceManager()));
Instance.setModuleDepCollector(ImportingInstance.getModuleDepCollector());
Inv.getDependencyOutputOpts() = DependencyOutputOptions();
ImportingInstance.getDiagnostics().Report(ImportLoc,
diag::remark_module_build)
<< ModuleName << ModuleFileName;
PreBuildStep(Instance);
bool Crashed = !llvm::CrashRecoveryContext().RunSafelyOnThread(
[&]() {
GenerateModuleFromModuleMapAction Action;
Instance.ExecuteAction(Action);
},
DesiredStackSize);
PostBuildStep(Instance);
ImportingInstance.getDiagnostics().Report(ImportLoc,
diag::remark_module_build_done)
<< ModuleName;
if (Crashed) {
Instance.setSema(nullptr);
Instance.setASTConsumer(nullptr);
Instance.clearOutputFiles(true);
}
return !Instance.getDiagnostics().hasErrorOccurred() ||
Instance.getFrontendOpts().AllowPCMWithCompilerErrors;
}
static const FileEntry *getPublicModuleMap(const FileEntry *File,
FileManager &FileMgr) {
StringRef Filename = llvm::sys::path::filename(File->getName());
SmallString<128> PublicFilename(File->getDir()->getName());
if (Filename == "module_private.map")
llvm::sys::path::append(PublicFilename, "module.map");
else if (Filename == "module.private.modulemap")
llvm::sys::path::append(PublicFilename, "module.modulemap");
else
return nullptr;
if (auto FE = FileMgr.getFile(PublicFilename))
return *FE;
return nullptr;
}
static bool compileModule(CompilerInstance &ImportingInstance,
SourceLocation ImportLoc, Module *Module,
StringRef ModuleFileName) {
InputKind IK(getLanguageFromOptions(ImportingInstance.getLangOpts()),
InputKind::ModuleMap);
ModuleMap &ModMap
= ImportingInstance.getPreprocessor().getHeaderSearchInfo().getModuleMap();
bool Result;
if (const FileEntry *ModuleMapFile =
ModMap.getContainingModuleMapFile(Module)) {
if (const FileEntry *PublicMMFile = getPublicModuleMap(
ModuleMapFile, ImportingInstance.getFileManager()))
ModuleMapFile = PublicMMFile;
Result = compileModuleImpl(
ImportingInstance, ImportLoc, Module->getTopLevelModuleName(),
FrontendInputFile(ModuleMapFile->getName(), IK, +Module->IsSystem),
ModMap.getModuleMapFileForUniquing(Module)->getName(),
ModuleFileName);
} else {
SmallString<128> FakeModuleMapFile(Module->Directory->getName());
llvm::sys::path::append(FakeModuleMapFile, "__inferred_module.map");
std::string InferredModuleMapContent;
llvm::raw_string_ostream OS(InferredModuleMapContent);
Module->print(OS);
OS.flush();
Result = compileModuleImpl(
ImportingInstance, ImportLoc, Module->getTopLevelModuleName(),
FrontendInputFile(FakeModuleMapFile, IK, +Module->IsSystem),
ModMap.getModuleMapFileForUniquing(Module)->getName(),
ModuleFileName,
[&](CompilerInstance &Instance) {
std::unique_ptr<llvm::MemoryBuffer> ModuleMapBuffer =
llvm::MemoryBuffer::getMemBuffer(InferredModuleMapContent);
ModuleMapFile = Instance.getFileManager().getVirtualFile(
FakeModuleMapFile, InferredModuleMapContent.size(), 0);
Instance.getSourceManager().overrideFileContents(
ModuleMapFile, std::move(ModuleMapBuffer));
});
}
if (ImportingInstance.getFrontendOpts().GenerateGlobalModuleIndex) {
ImportingInstance.setBuildGlobalModuleIndex(true);
}
return Result;
}
static bool readASTAfterCompileModule(CompilerInstance &ImportingInstance,
SourceLocation ImportLoc,
SourceLocation ModuleNameLoc,
Module *Module, StringRef ModuleFileName,
bool *OutOfDate) {
DiagnosticsEngine &Diags = ImportingInstance.getDiagnostics();
unsigned ModuleLoadCapabilities = ASTReader::ARR_Missing;
if (OutOfDate)
ModuleLoadCapabilities |= ASTReader::ARR_OutOfDate;
ASTReader::ASTReadResult ReadResult =
ImportingInstance.getASTReader()->ReadAST(
ModuleFileName, serialization::MK_ImplicitModule, ImportLoc,
ModuleLoadCapabilities);
if (ReadResult == ASTReader::Success)
return true;
if (OutOfDate && ReadResult == ASTReader::OutOfDate) {
*OutOfDate = true;
return false;
}
if (ReadResult == ASTReader::Missing || !Diags.hasErrorOccurred())
Diags.Report(ModuleNameLoc, diag::err_module_not_built)
<< Module->Name << SourceRange(ImportLoc, ModuleNameLoc);
return false;
}
static bool compileModuleAndReadASTImpl(CompilerInstance &ImportingInstance,
SourceLocation ImportLoc,
SourceLocation ModuleNameLoc,
Module *Module,
StringRef ModuleFileName) {
if (!compileModule(ImportingInstance, ModuleNameLoc, Module,
ModuleFileName)) {
ImportingInstance.getDiagnostics().Report(ModuleNameLoc,
diag::err_module_not_built)
<< Module->Name << SourceRange(ImportLoc, ModuleNameLoc);
return false;
}
return readASTAfterCompileModule(ImportingInstance, ImportLoc, ModuleNameLoc,
Module, ModuleFileName,
nullptr);
}
static bool compileModuleAndReadASTBehindLock(
CompilerInstance &ImportingInstance, SourceLocation ImportLoc,
SourceLocation ModuleNameLoc, Module *Module, StringRef ModuleFileName) {
DiagnosticsEngine &Diags = ImportingInstance.getDiagnostics();
Diags.Report(ModuleNameLoc, diag::remark_module_lock)
<< ModuleFileName << Module->Name;
StringRef Dir = llvm::sys::path::parent_path(ModuleFileName);
llvm::sys::fs::create_directories(Dir);
while (true) {
llvm::LockFileManager Locked(ModuleFileName);
switch (Locked) {
case llvm::LockFileManager::LFS_Error:
Diags.Report(ModuleNameLoc, diag::remark_module_lock_failure)
<< Module->Name << Locked.getErrorMessage();
Locked.unsafeRemoveLockFile();
LLVM_FALLTHROUGH;
case llvm::LockFileManager::LFS_Owned:
return compileModuleAndReadASTImpl(ImportingInstance, ImportLoc,
ModuleNameLoc, Module, ModuleFileName);
case llvm::LockFileManager::LFS_Shared:
break; }
switch (Locked.waitForUnlock()) {
case llvm::LockFileManager::Res_Success:
break; case llvm::LockFileManager::Res_OwnerDied:
continue; case llvm::LockFileManager::Res_Timeout:
Diags.Report(ModuleNameLoc, diag::remark_module_lock_timeout)
<< Module->Name;
Locked.unsafeRemoveLockFile();
continue;
}
bool OutOfDate = false;
if (readASTAfterCompileModule(ImportingInstance, ImportLoc, ModuleNameLoc,
Module, ModuleFileName, &OutOfDate))
return true;
if (!OutOfDate)
return false;
}
}
static bool compileModuleAndReadAST(CompilerInstance &ImportingInstance,
SourceLocation ImportLoc,
SourceLocation ModuleNameLoc,
Module *Module, StringRef ModuleFileName) {
return ImportingInstance.getInvocation()
.getFrontendOpts()
.BuildingImplicitModuleUsesLock
? compileModuleAndReadASTBehindLock(ImportingInstance, ImportLoc,
ModuleNameLoc, Module,
ModuleFileName)
: compileModuleAndReadASTImpl(ImportingInstance, ImportLoc,
ModuleNameLoc, Module,
ModuleFileName);
}
static void checkConfigMacro(Preprocessor &PP, StringRef ConfigMacro,
Module *Mod, SourceLocation ImportLoc) {
IdentifierInfo *Id = PP.getIdentifierInfo(ConfigMacro);
SourceManager &SourceMgr = PP.getSourceManager();
if (!Id->hadMacroDefinition())
return;
auto *LatestLocalMD = PP.getLocalMacroDirectiveHistory(Id);
MacroInfo *CmdLineDefinition = nullptr;
for (auto *MD = LatestLocalMD; MD; MD = MD->getPrevious()) {
FileID FID = SourceMgr.getFileID(MD->getLocation());
if (FID.isInvalid() || FID != PP.getPredefinesFileID())
continue;
if (auto *DMD = dyn_cast<DefMacroDirective>(MD))
CmdLineDefinition = DMD->getMacroInfo();
break;
}
auto *CurrentDefinition = PP.getMacroInfo(Id);
if (CurrentDefinition == CmdLineDefinition) {
} else if (!CurrentDefinition) {
PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
<< true << ConfigMacro << Mod->getFullModuleName();
auto LatestDef = LatestLocalMD->getDefinition();
assert(LatestDef.isUndefined() &&
"predefined macro went away with no #undef?");
PP.Diag(LatestDef.getUndefLocation(), diag::note_module_def_undef_here)
<< true;
return;
} else if (!CmdLineDefinition) {
PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
<< false << ConfigMacro << Mod->getFullModuleName();
PP.Diag(CurrentDefinition->getDefinitionLoc(),
diag::note_module_def_undef_here)
<< false;
} else if (!CurrentDefinition->isIdenticalTo(*CmdLineDefinition, PP,
true)) {
PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
<< false << ConfigMacro << Mod->getFullModuleName();
PP.Diag(CurrentDefinition->getDefinitionLoc(),
diag::note_module_def_undef_here)
<< false;
}
}
static void writeTimestampFile(StringRef TimestampFile) {
std::error_code EC;
llvm::raw_fd_ostream Out(TimestampFile.str(), EC, llvm::sys::fs::OF_None);
}
static void pruneModuleCache(const HeaderSearchOptions &HSOpts) {
llvm::sys::fs::file_status StatBuf;
llvm::SmallString<128> TimestampFile;
TimestampFile = HSOpts.ModuleCachePath;
assert(!TimestampFile.empty());
llvm::sys::path::append(TimestampFile, "modules.timestamp");
if (std::error_code EC = llvm::sys::fs::status(TimestampFile, StatBuf)) {
if (EC == std::errc::no_such_file_or_directory) {
writeTimestampFile(TimestampFile);
}
return;
}
time_t TimeStampModTime =
llvm::sys::toTimeT(StatBuf.getLastModificationTime());
time_t CurrentTime = time(nullptr);
if (CurrentTime - TimeStampModTime <= time_t(HSOpts.ModuleCachePruneInterval))
return;
writeTimestampFile(TimestampFile);
std::error_code EC;
SmallString<128> ModuleCachePathNative;
llvm::sys::path::native(HSOpts.ModuleCachePath, ModuleCachePathNative);
for (llvm::sys::fs::directory_iterator Dir(ModuleCachePathNative, EC), DirEnd;
Dir != DirEnd && !EC; Dir.increment(EC)) {
if (!llvm::sys::fs::is_directory(Dir->path()))
continue;
for (llvm::sys::fs::directory_iterator File(Dir->path(), EC), FileEnd;
File != FileEnd && !EC; File.increment(EC)) {
StringRef Extension = llvm::sys::path::extension(File->path());
if (Extension != ".pcm" && Extension != ".timestamp" &&
llvm::sys::path::filename(File->path()) != "modules.idx")
continue;
if (llvm::sys::fs::status(File->path(), StatBuf))
continue;
time_t FileAccessTime = llvm::sys::toTimeT(StatBuf.getLastAccessedTime());
if (CurrentTime - FileAccessTime <=
time_t(HSOpts.ModuleCachePruneAfter)) {
continue;
}
llvm::sys::fs::remove(File->path());
std::string TimpestampFilename = File->path() + ".timestamp";
llvm::sys::fs::remove(TimpestampFilename);
}
if (llvm::sys::fs::directory_iterator(Dir->path(), EC) ==
llvm::sys::fs::directory_iterator() && !EC)
llvm::sys::fs::remove(Dir->path());
}
}
void CompilerInstance::createASTReader() {
if (TheASTReader)
return;
if (!hasASTContext())
createASTContext();
if (getSourceManager().getModuleBuildStack().empty() &&
!getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty() &&
getHeaderSearchOpts().ModuleCachePruneInterval > 0 &&
getHeaderSearchOpts().ModuleCachePruneAfter > 0) {
pruneModuleCache(getHeaderSearchOpts());
}
HeaderSearchOptions &HSOpts = getHeaderSearchOpts();
std::string Sysroot = HSOpts.Sysroot;
const PreprocessorOptions &PPOpts = getPreprocessorOpts();
const FrontendOptions &FEOpts = getFrontendOpts();
std::unique_ptr<llvm::Timer> ReadTimer;
if (FrontendTimerGroup)
ReadTimer = std::make_unique<llvm::Timer>("reading_modules",
"Reading modules",
*FrontendTimerGroup);
TheASTReader = new ASTReader(
getPreprocessor(), getModuleCache(), &getASTContext(),
getPCHContainerReader(), getFrontendOpts().ModuleFileExtensions,
Sysroot.empty() ? "" : Sysroot.c_str(),
PPOpts.DisablePCHOrModuleValidation,
FEOpts.AllowPCMWithCompilerErrors,
false, HSOpts.ModulesValidateSystemHeaders,
HSOpts.ValidateASTInputFilesContent,
getFrontendOpts().UseGlobalModuleIndex, std::move(ReadTimer));
if (hasASTConsumer()) {
TheASTReader->setDeserializationListener(
getASTConsumer().GetASTDeserializationListener());
getASTContext().setASTMutationListener(
getASTConsumer().GetASTMutationListener());
}
getASTContext().setExternalSource(TheASTReader);
if (hasSema())
TheASTReader->InitializeSema(getSema());
if (hasASTConsumer())
TheASTReader->StartTranslationUnit(&getASTConsumer());
for (auto &Listener : DependencyCollectors)
Listener->attachToASTReader(*TheASTReader);
}
bool CompilerInstance::loadModuleFile(StringRef FileName) {
llvm::Timer Timer;
if (FrontendTimerGroup)
Timer.init("preloading." + FileName.str(), "Preloading " + FileName.str(),
*FrontendTimerGroup);
llvm::TimeRegion TimeLoading(FrontendTimerGroup ? &Timer : nullptr);
if (!TheASTReader)
createASTReader();
bool ConfigMismatchIsRecoverable =
getDiagnostics().getDiagnosticLevel(diag::warn_module_config_mismatch,
SourceLocation())
<= DiagnosticsEngine::Warning;
auto Listener = std::make_unique<ReadModuleNames>(*PP);
auto &ListenerRef = *Listener;
ASTReader::ListenerScope ReadModuleNamesListener(*TheASTReader,
std::move(Listener));
switch (TheASTReader->ReadAST(
FileName, serialization::MK_ExplicitModule, SourceLocation(),
ConfigMismatchIsRecoverable ? ASTReader::ARR_ConfigurationMismatch : 0)) {
case ASTReader::Success:
ListenerRef.registerAll();
return true;
case ASTReader::ConfigurationMismatch:
getDiagnostics().Report(SourceLocation(), diag::warn_module_config_mismatch)
<< FileName;
ListenerRef.markAllUnavailable();
return true;
default:
return false;
}
}
namespace {
enum ModuleSource {
MS_ModuleNotFound,
MS_ModuleCache,
MS_PrebuiltModulePath,
MS_ModuleBuildPragma
};
}
static ModuleSource selectModuleSource(
Module *M, StringRef ModuleName, std::string &ModuleFilename,
const std::map<std::string, std::string, std::less<>> &BuiltModules,
HeaderSearch &HS) {
assert(ModuleFilename.empty() && "Already has a module source?");
auto BuiltModuleIt = BuiltModules.find(ModuleName);
if (BuiltModuleIt != BuiltModules.end()) {
ModuleFilename = BuiltModuleIt->second;
return MS_ModuleBuildPragma;
}
const HeaderSearchOptions &HSOpts = HS.getHeaderSearchOpts();
if (!HSOpts.PrebuiltModuleFiles.empty() ||
!HSOpts.PrebuiltModulePaths.empty()) {
ModuleFilename = HS.getPrebuiltModuleFileName(ModuleName);
if (HSOpts.EnablePrebuiltImplicitModules && ModuleFilename.empty())
ModuleFilename = HS.getPrebuiltImplicitModuleFileName(M);
if (!ModuleFilename.empty())
return MS_PrebuiltModulePath;
}
if (M) {
ModuleFilename = HS.getCachedModuleFileName(M);
return MS_ModuleCache;
}
return MS_ModuleNotFound;
}
ModuleLoadResult CompilerInstance::findOrCompileModuleAndReadAST(
StringRef ModuleName, SourceLocation ImportLoc,
SourceLocation ModuleNameLoc, bool IsInclusionDirective) {
HeaderSearch &HS = PP->getHeaderSearchInfo();
Module *M =
HS.lookupModule(ModuleName, ImportLoc, true, !IsInclusionDirective);
std::string ModuleFilename;
ModuleSource Source =
selectModuleSource(M, ModuleName, ModuleFilename, BuiltModules, HS);
if (Source == MS_ModuleNotFound) {
getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found)
<< ModuleName << SourceRange(ImportLoc, ModuleNameLoc);
return nullptr;
}
if (ModuleFilename.empty()) {
if (M && M->HasIncompatibleModuleFile) {
return ModuleLoadResult::ConfigMismatch;
}
getDiagnostics().Report(ModuleNameLoc, diag::err_module_build_disabled)
<< ModuleName;
return nullptr;
}
if (!getASTReader())
createASTReader();
llvm::Timer Timer;
if (FrontendTimerGroup)
Timer.init("loading." + ModuleFilename, "Loading " + ModuleFilename,
*FrontendTimerGroup);
llvm::TimeRegion TimeLoading(FrontendTimerGroup ? &Timer : nullptr);
llvm::TimeTraceScope TimeScope("Module Load", ModuleName);
unsigned ARRFlags = Source == MS_ModuleCache
? ASTReader::ARR_OutOfDate | ASTReader::ARR_Missing |
ASTReader::ARR_TreatModuleWithErrorsAsOutOfDate
: Source == MS_PrebuiltModulePath
? 0
: ASTReader::ARR_ConfigurationMismatch;
switch (getASTReader()->ReadAST(ModuleFilename,
Source == MS_PrebuiltModulePath
? serialization::MK_PrebuiltModule
: Source == MS_ModuleBuildPragma
? serialization::MK_ExplicitModule
: serialization::MK_ImplicitModule,
ImportLoc, ARRFlags)) {
case ASTReader::Success: {
if (M)
return M;
assert(Source != MS_ModuleCache &&
"missing module, but file loaded from cache");
M = HS.lookupModule(ModuleName, ImportLoc, true, !IsInclusionDirective);
if (M && M->getASTFile())
if (auto ModuleFile = FileMgr->getFile(ModuleFilename))
if (*ModuleFile == M->getASTFile())
return M;
getDiagnostics().Report(ModuleNameLoc, diag::err_module_prebuilt)
<< ModuleName;
return ModuleLoadResult();
}
case ASTReader::OutOfDate:
case ASTReader::Missing:
break;
case ASTReader::ConfigurationMismatch:
if (Source == MS_PrebuiltModulePath)
getDiagnostics().Report(SourceLocation(),
diag::warn_module_config_mismatch)
<< ModuleFilename;
LLVM_FALLTHROUGH;
case ASTReader::VersionMismatch:
case ASTReader::HadErrors:
ModuleLoader::HadFatalFailure = true;
return ModuleLoadResult();
case ASTReader::Failure:
ModuleLoader::HadFatalFailure = true;
return ModuleLoadResult();
}
if (Source != MS_ModuleCache) {
return ModuleLoadResult();
}
assert(M && "missing module, but trying to compile for cache");
ModuleBuildStack ModPath = getSourceManager().getModuleBuildStack();
ModuleBuildStack::iterator Pos = ModPath.begin(), PosEnd = ModPath.end();
for (; Pos != PosEnd; ++Pos) {
if (Pos->first == ModuleName)
break;
}
if (Pos != PosEnd) {
SmallString<256> CyclePath;
for (; Pos != PosEnd; ++Pos) {
CyclePath += Pos->first;
CyclePath += " -> ";
}
CyclePath += ModuleName;
getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle)
<< ModuleName << CyclePath;
return nullptr;
}
if (getPreprocessorOpts().FailedModules &&
getPreprocessorOpts().FailedModules->hasAlreadyFailed(ModuleName)) {
getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_built)
<< ModuleName << SourceRange(ImportLoc, ModuleNameLoc);
return nullptr;
}
if (!compileModuleAndReadAST(*this, ImportLoc, ModuleNameLoc, M,
ModuleFilename)) {
assert(getDiagnostics().hasErrorOccurred() &&
"undiagnosed error in compileModuleAndReadAST");
if (getPreprocessorOpts().FailedModules)
getPreprocessorOpts().FailedModules->addFailed(ModuleName);
return nullptr;
}
return M;
}
ModuleLoadResult
CompilerInstance::loadModule(SourceLocation ImportLoc,
ModuleIdPath Path,
Module::NameVisibilityKind Visibility,
bool IsInclusionDirective) {
StringRef ModuleName = Path[0].first->getName();
SourceLocation ModuleNameLoc = Path[0].second;
if (ImportLoc.isValid() && LastModuleImportLoc == ImportLoc) {
if (LastModuleImportResult && ModuleName != getLangOpts().CurrentModule)
TheASTReader->makeModuleVisible(LastModuleImportResult, Visibility,
ImportLoc);
return LastModuleImportResult;
}
Module *Module = nullptr;
ModuleMap &MM = getPreprocessor().getHeaderSearchInfo().getModuleMap();
if (auto MaybeModule = MM.getCachedModuleLoad(*Path[0].first)) {
Module = *MaybeModule;
} else if (ModuleName == getLangOpts().CurrentModule) {
Module = PP->getHeaderSearchInfo().lookupModule(
ModuleName, ImportLoc, true,
!IsInclusionDirective);
MM.cacheModuleLoad(*Path[0].first, Module);
} else {
ModuleLoadResult Result = findOrCompileModuleAndReadAST(
ModuleName, ImportLoc, ModuleNameLoc, IsInclusionDirective);
if (!Result.isNormal())
return Result;
if (!Result)
DisableGeneratingGlobalModuleIndex = true;
Module = Result;
MM.cacheModuleLoad(*Path[0].first, Module);
}
if (!Module)
return ModuleLoadResult();
bool MapPrivateSubModToTopLevel = false;
for (unsigned I = 1, N = Path.size(); I != N; ++I) {
StringRef Name = Path[I].first->getName();
clang::Module *Sub = Module->findSubmodule(Name);
if (!Sub && PP->getLangOpts().ImplicitModules && Name == "Private" &&
Module == Module->getTopLevelModule()) {
SmallString<128> PrivateModule(Module->Name);
PrivateModule.append("_Private");
SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> PrivPath;
auto &II = PP->getIdentifierTable().get(
PrivateModule, PP->getIdentifierInfo(Module->Name)->getTokenID());
PrivPath.push_back(std::make_pair(&II, Path[0].second));
if (PP->getHeaderSearchInfo().lookupModule(PrivateModule, ImportLoc, true,
!IsInclusionDirective))
Sub = loadModule(ImportLoc, PrivPath, Visibility, IsInclusionDirective);
if (Sub) {
MapPrivateSubModToTopLevel = true;
if (!getDiagnostics().isIgnored(
diag::warn_no_priv_submodule_use_toplevel, ImportLoc)) {
getDiagnostics().Report(Path[I].second,
diag::warn_no_priv_submodule_use_toplevel)
<< Path[I].first << Module->getFullModuleName() << PrivateModule
<< SourceRange(Path[0].second, Path[I].second)
<< FixItHint::CreateReplacement(SourceRange(Path[0].second),
PrivateModule);
getDiagnostics().Report(Sub->DefinitionLoc,
diag::note_private_top_level_defined);
}
}
}
if (!Sub) {
SmallVector<StringRef, 2> Best;
unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)();
for (class Module *SubModule : Module->submodules()) {
unsigned ED =
Name.edit_distance(SubModule->Name,
true, BestEditDistance);
if (ED <= BestEditDistance) {
if (ED < BestEditDistance) {
Best.clear();
BestEditDistance = ED;
}
Best.push_back(SubModule->Name);
}
}
if (Best.size() == 1) {
getDiagnostics().Report(Path[I].second, diag::err_no_submodule_suggest)
<< Path[I].first << Module->getFullModuleName() << Best[0]
<< SourceRange(Path[0].second, Path[I - 1].second)
<< FixItHint::CreateReplacement(SourceRange(Path[I].second),
Best[0]);
Sub = Module->findSubmodule(Best[0]);
}
}
if (!Sub) {
getDiagnostics().Report(Path[I].second, diag::err_no_submodule)
<< Path[I].first << Module->getFullModuleName()
<< SourceRange(Path[0].second, Path[I - 1].second);
break;
}
Module = Sub;
}
if (ModuleName != getLangOpts().CurrentModule) {
if (!Module->IsFromModuleFile && !MapPrivateSubModToTopLevel) {
getDiagnostics().Report(ImportLoc, diag::warn_missing_submodule)
<< Module->getFullModuleName()
<< SourceRange(Path.front().second, Path.back().second);
return ModuleLoadResult::MissingExpected;
}
if (Preprocessor::checkModuleIsAvailable(getLangOpts(), getTarget(),
getDiagnostics(), Module)) {
getDiagnostics().Report(ImportLoc, diag::note_module_import_here)
<< SourceRange(Path.front().second, Path.back().second);
LastModuleImportLoc = ImportLoc;
LastModuleImportResult = ModuleLoadResult();
return ModuleLoadResult();
}
TheASTReader->makeModuleVisible(Module, Visibility, ImportLoc);
}
clang::Module *TopModule = Module->getTopLevelModule();
for (unsigned I = 0, N = TopModule->ConfigMacros.size(); I != N; ++I) {
checkConfigMacro(getPreprocessor(), TopModule->ConfigMacros[I],
Module, ImportLoc);
}
getPreprocessor()
.getHeaderSearchInfo()
.getModuleMap()
.resolveLinkAsDependencies(TopModule);
LastModuleImportLoc = ImportLoc;
LastModuleImportResult = ModuleLoadResult(Module);
return LastModuleImportResult;
}
void CompilerInstance::createModuleFromSource(SourceLocation ImportLoc,
StringRef ModuleName,
StringRef Source) {
SmallString<128> CleanModuleName(ModuleName);
for (auto &C : CleanModuleName)
if (!isAlphanumeric(C))
C = '_';
SmallString<128> ModuleFileName;
if (std::error_code EC = llvm::sys::fs::createTemporaryFile(
CleanModuleName, "pcm", ModuleFileName)) {
getDiagnostics().Report(ImportLoc, diag::err_fe_unable_to_open_output)
<< ModuleFileName << EC.message();
return;
}
std::string ModuleMapFileName = (CleanModuleName + ".map").str();
FrontendInputFile Input(
ModuleMapFileName,
InputKind(getLanguageFromOptions(*Invocation->getLangOpts()),
InputKind::ModuleMap, true));
std::string NullTerminatedSource(Source.str());
auto PreBuildStep = [&](CompilerInstance &Other) {
const FileEntry *ModuleMapFile = Other.getFileManager().getVirtualFile(
ModuleMapFileName, NullTerminatedSource.size(), 0);
Other.getSourceManager().overrideFileContents(
ModuleMapFile, llvm::MemoryBuffer::getMemBuffer(NullTerminatedSource));
Other.BuiltModules = std::move(BuiltModules);
Other.DeleteBuiltModules = false;
};
auto PostBuildStep = [this](CompilerInstance &Other) {
BuiltModules = std::move(Other.BuiltModules);
};
if (compileModuleImpl(*this, ImportLoc, ModuleName, Input, StringRef(),
ModuleFileName, PreBuildStep, PostBuildStep)) {
BuiltModules[std::string(ModuleName)] = std::string(ModuleFileName.str());
llvm::sys::RemoveFileOnSignal(ModuleFileName);
}
}
void CompilerInstance::makeModuleVisible(Module *Mod,
Module::NameVisibilityKind Visibility,
SourceLocation ImportLoc) {
if (!TheASTReader)
createASTReader();
if (!TheASTReader)
return;
TheASTReader->makeModuleVisible(Mod, Visibility, ImportLoc);
}
GlobalModuleIndex *CompilerInstance::loadGlobalModuleIndex(
SourceLocation TriggerLoc) {
if (getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty())
return nullptr;
if (!TheASTReader)
createASTReader();
if (!TheASTReader)
return nullptr;
TheASTReader->loadGlobalIndex();
GlobalModuleIndex *GlobalIndex = TheASTReader->getGlobalIndex();
if (!GlobalIndex && shouldBuildGlobalModuleIndex() && hasFileManager() &&
hasPreprocessor()) {
llvm::sys::fs::create_directories(
getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
if (llvm::Error Err = GlobalModuleIndex::writeIndex(
getFileManager(), getPCHContainerReader(),
getPreprocessor().getHeaderSearchInfo().getModuleCachePath())) {
consumeError(std::move(Err));
return nullptr;
}
TheASTReader->resetForReload();
TheASTReader->loadGlobalIndex();
GlobalIndex = TheASTReader->getGlobalIndex();
}
if (!HaveFullGlobalModuleIndex && GlobalIndex && !buildingModule()) {
ModuleMap &MMap = getPreprocessor().getHeaderSearchInfo().getModuleMap();
bool RecreateIndex = false;
for (ModuleMap::module_iterator I = MMap.module_begin(),
E = MMap.module_end(); I != E; ++I) {
Module *TheModule = I->second;
const FileEntry *Entry = TheModule->getASTFile();
if (!Entry) {
SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
Path.push_back(std::make_pair(
getPreprocessor().getIdentifierInfo(TheModule->Name), TriggerLoc));
std::reverse(Path.begin(), Path.end());
loadModule(TheModule->DefinitionLoc, Path, Module::Hidden, false);
RecreateIndex = true;
}
}
if (RecreateIndex) {
if (llvm::Error Err = GlobalModuleIndex::writeIndex(
getFileManager(), getPCHContainerReader(),
getPreprocessor().getHeaderSearchInfo().getModuleCachePath())) {
consumeError(std::move(Err));
return nullptr;
}
TheASTReader->resetForReload();
TheASTReader->loadGlobalIndex();
GlobalIndex = TheASTReader->getGlobalIndex();
}
HaveFullGlobalModuleIndex = true;
}
return GlobalIndex;
}
bool
CompilerInstance::lookupMissingImports(StringRef Name,
SourceLocation TriggerLoc) {
if (!buildingModule()) {
GlobalModuleIndex *GlobalIndex = loadGlobalModuleIndex(
TriggerLoc);
if (GlobalIndex) {
GlobalModuleIndex::HitSet FoundModules;
if (GlobalIndex->lookupIdentifier(Name, FoundModules))
return true;
}
}
return false;
}
void CompilerInstance::resetAndLeakSema() { llvm::BuryPointer(takeSema()); }
void CompilerInstance::setExternalSemaSource(
IntrusiveRefCntPtr<ExternalSemaSource> ESS) {
ExternalSemaSrc = std::move(ESS);
}