#include "clang/Frontend/ASTUnit.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/CommentCommandTraits.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclBase.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclGroup.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/AST/DeclarationName.h"
#include "clang/AST/ExternalASTSource.h"
#include "clang/AST/PrettyPrinter.h"
#include "clang/AST/Type.h"
#include "clang/AST/TypeOrdering.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/IdentifierTable.h"
#include "clang/Basic/LLVM.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Basic/LangStandard.h"
#include "clang/Basic/Module.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Basic/TargetOptions.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/CompilerInvocation.h"
#include "clang/Frontend/FrontendAction.h"
#include "clang/Frontend/FrontendActions.h"
#include "clang/Frontend/FrontendDiagnostic.h"
#include "clang/Frontend/FrontendOptions.h"
#include "clang/Frontend/MultiplexConsumer.h"
#include "clang/Frontend/PrecompiledPreamble.h"
#include "clang/Frontend/Utils.h"
#include "clang/Lex/HeaderSearch.h"
#include "clang/Lex/HeaderSearchOptions.h"
#include "clang/Lex/Lexer.h"
#include "clang/Lex/PPCallbacks.h"
#include "clang/Lex/PreprocessingRecord.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Lex/PreprocessorOptions.h"
#include "clang/Lex/Token.h"
#include "clang/Sema/CodeCompleteConsumer.h"
#include "clang/Sema/CodeCompleteOptions.h"
#include "clang/Sema/Sema.h"
#include "clang/Serialization/ASTBitCodes.h"
#include "clang/Serialization/ASTReader.h"
#include "clang/Serialization/ASTWriter.h"
#include "clang/Serialization/ContinuousRangeMap.h"
#include "clang/Serialization/InMemoryModuleCache.h"
#include "clang/Serialization/ModuleFile.h"
#include "clang/Serialization/PCHContainerOperations.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/IntrusiveRefCntPtr.h"
#include "llvm/ADT/None.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/ScopeExit.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/ADT/Twine.h"
#include "llvm/ADT/iterator_range.h"
#include "llvm/Bitstream/BitstreamWriter.h"
#include "llvm/Support/Allocator.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/CrashRecoveryContext.h"
#include "llvm/Support/DJB.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/ErrorOr.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/FileUtilities.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Timer.h"
#include "llvm/Support/VirtualFileSystem.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <atomic>
#include <cassert>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <memory>
#include <mutex>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
using namespace clang;
using llvm::TimeRecord;
namespace {
class SimpleTimer {
bool WantTiming;
TimeRecord Start;
std::string Output;
public:
explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
if (WantTiming)
Start = TimeRecord::getCurrentTime();
}
~SimpleTimer() {
if (WantTiming) {
TimeRecord Elapsed = TimeRecord::getCurrentTime();
Elapsed -= Start;
llvm::errs() << Output << ':';
Elapsed.print(Elapsed, llvm::errs());
llvm::errs() << '\n';
}
}
void setOutput(const Twine &Output) {
if (WantTiming)
this->Output = Output.str();
}
};
}
template <class T>
static std::unique_ptr<T> valueOrNull(llvm::ErrorOr<std::unique_ptr<T>> Val) {
if (!Val)
return nullptr;
return std::move(*Val);
}
template <class T>
static bool moveOnNoError(llvm::ErrorOr<T> Val, T &Output) {
if (!Val)
return false;
Output = std::move(*Val);
return true;
}
static std::unique_ptr<llvm::MemoryBuffer>
getBufferForFileHandlingRemapping(const CompilerInvocation &Invocation,
llvm::vfs::FileSystem *VFS,
StringRef FilePath, bool isVolatile) {
const auto &PreprocessorOpts = Invocation.getPreprocessorOpts();
llvm::MemoryBuffer *Buffer = nullptr;
std::unique_ptr<llvm::MemoryBuffer> BufferOwner;
auto FileStatus = VFS->status(FilePath);
if (FileStatus) {
llvm::sys::fs::UniqueID MainFileID = FileStatus->getUniqueID();
for (const auto &RF : PreprocessorOpts.RemappedFiles) {
std::string MPath(RF.first);
auto MPathStatus = VFS->status(MPath);
if (MPathStatus) {
llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID();
if (MainFileID == MID) {
BufferOwner = valueOrNull(VFS->getBufferForFile(RF.second, -1, true, isVolatile));
if (!BufferOwner)
return nullptr;
}
}
}
for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
std::string MPath(RB.first);
auto MPathStatus = VFS->status(MPath);
if (MPathStatus) {
llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID();
if (MainFileID == MID) {
BufferOwner.reset();
Buffer = const_cast<llvm::MemoryBuffer *>(RB.second);
}
}
}
}
if (!Buffer && !BufferOwner) {
BufferOwner = valueOrNull(VFS->getBufferForFile(FilePath, -1, true, isVolatile));
if (!BufferOwner)
return nullptr;
}
if (BufferOwner)
return BufferOwner;
if (!Buffer)
return nullptr;
return llvm::MemoryBuffer::getMemBufferCopy(Buffer->getBuffer(), FilePath);
}
struct ASTUnit::ASTWriterData {
SmallString<128> Buffer;
llvm::BitstreamWriter Stream;
ASTWriter Writer;
ASTWriterData(InMemoryModuleCache &ModuleCache)
: Stream(Buffer), Writer(Stream, Buffer, ModuleCache, {}) {}
};
void ASTUnit::clearFileLevelDecls() {
FileDecls.clear();
}
const unsigned DefaultPreambleRebuildInterval = 5;
static std::atomic<unsigned> ActiveASTUnitObjects;
ASTUnit::ASTUnit(bool _MainFileIsAST)
: MainFileIsAST(_MainFileIsAST), WantTiming(getenv("LIBCLANG_TIMING")),
ShouldCacheCodeCompletionResults(false),
IncludeBriefCommentsInCodeCompletion(false), UserFilesAreVolatile(false),
UnsafeToFree(false) {
if (getenv("LIBCLANG_OBJTRACKING"))
fprintf(stderr, "+++ %u translation units\n", ++ActiveASTUnitObjects);
}
ASTUnit::~ASTUnit() {
if (MainFileIsAST && getDiagnostics().getClient()) {
getDiagnostics().getClient()->EndSourceFile();
}
clearFileLevelDecls();
if (Invocation && OwnsRemappedFileBuffers) {
PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
for (const auto &RB : PPOpts.RemappedFileBuffers)
delete RB.second;
}
ClearCachedCompletionResults();
if (getenv("LIBCLANG_OBJTRACKING"))
fprintf(stderr, "--- %u translation units\n", --ActiveASTUnitObjects);
}
void ASTUnit::setPreprocessor(std::shared_ptr<Preprocessor> PP) {
this->PP = std::move(PP);
}
void ASTUnit::enableSourceFileDiagnostics() {
assert(getDiagnostics().getClient() && Ctx &&
"Bad context for source file");
getDiagnostics().getClient()->BeginSourceFile(Ctx->getLangOpts(), PP.get());
}
static uint64_t getDeclShowContexts(const NamedDecl *ND,
const LangOptions &LangOpts,
bool &IsNestedNameSpecifier) {
IsNestedNameSpecifier = false;
if (isa<UsingShadowDecl>(ND))
ND = ND->getUnderlyingDecl();
if (!ND)
return 0;
uint64_t Contexts = 0;
if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND) ||
isa<TypeAliasTemplateDecl>(ND)) {
if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel)
| (1LL << CodeCompletionContext::CCC_ObjCIvarList)
| (1LL << CodeCompletionContext::CCC_ClassStructUnion)
| (1LL << CodeCompletionContext::CCC_Statement)
| (1LL << CodeCompletionContext::CCC_Type)
| (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
if (LangOpts.CPlusPlus)
Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND)) {
if (ID->getDefinition())
Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName);
}
if (isa<EnumDecl>(ND)) {
Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag);
if (LangOpts.CPlusPlus11)
IsNestedNameSpecifier = true;
} else if (const auto *Record = dyn_cast<RecordDecl>(ND)) {
if (Record->isUnion())
Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag);
else
Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
if (LangOpts.CPlusPlus)
IsNestedNameSpecifier = true;
} else if (isa<ClassTemplateDecl>(ND))
IsNestedNameSpecifier = true;
} else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Contexts = (1LL << CodeCompletionContext::CCC_Statement)
| (1LL << CodeCompletionContext::CCC_Expression)
| (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
| (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
} else if (isa<ObjCProtocolDecl>(ND)) {
Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName);
} else if (isa<ObjCCategoryDecl>(ND)) {
Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName);
} else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Contexts = (1LL << CodeCompletionContext::CCC_Namespace);
IsNestedNameSpecifier = true;
}
return Contexts;
}
void ASTUnit::CacheCodeCompletionResults() {
if (!TheSema)
return;
SimpleTimer Timer(WantTiming);
Timer.setOutput("Cache global code completions for " + getMainFileName());
ClearCachedCompletionResults();
using Result = CodeCompletionResult;
SmallVector<Result, 8> Results;
CachedCompletionAllocator = std::make_shared<GlobalCodeCompletionAllocator>();
CodeCompletionTUInfo CCTUInfo(CachedCompletionAllocator);
TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
CCTUInfo, Results);
llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
CodeCompletionContext CCContext(CodeCompletionContext::CCC_TopLevel);
for (auto &R : Results) {
switch (R.Kind) {
case Result::RK_Declaration: {
bool IsNestedNameSpecifier = false;
CachedCodeCompletionResult CachedResult;
CachedResult.Completion = R.CreateCodeCompletionString(
*TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
IncludeBriefCommentsInCodeCompletion);
CachedResult.ShowInContexts = getDeclShowContexts(
R.Declaration, Ctx->getLangOpts(), IsNestedNameSpecifier);
CachedResult.Priority = R.Priority;
CachedResult.Kind = R.CursorKind;
CachedResult.Availability = R.Availability;
QualType UsageType = getDeclUsageType(*Ctx, R.Declaration);
if (UsageType.isNull()) {
CachedResult.TypeClass = STC_Void;
CachedResult.Type = 0;
} else {
CanQualType CanUsageType
= Ctx->getCanonicalType(UsageType.getUnqualifiedType());
CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
unsigned &TypeValue = CompletionTypes[CanUsageType];
if (TypeValue == 0) {
TypeValue = CompletionTypes.size();
CachedCompletionTypes[QualType(CanUsageType).getAsString()]
= TypeValue;
}
CachedResult.Type = TypeValue;
}
CachedCompletionResults.push_back(CachedResult);
if (TheSema->Context.getLangOpts().CPlusPlus && IsNestedNameSpecifier &&
!R.StartsNestedNameSpecifier) {
uint64_t NNSContexts
= (1LL << CodeCompletionContext::CCC_TopLevel)
| (1LL << CodeCompletionContext::CCC_ObjCIvarList)
| (1LL << CodeCompletionContext::CCC_ClassStructUnion)
| (1LL << CodeCompletionContext::CCC_Statement)
| (1LL << CodeCompletionContext::CCC_Expression)
| (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
| (1LL << CodeCompletionContext::CCC_EnumTag)
| (1LL << CodeCompletionContext::CCC_UnionTag)
| (1LL << CodeCompletionContext::CCC_ClassOrStructTag)
| (1LL << CodeCompletionContext::CCC_Type)
| (1LL << CodeCompletionContext::CCC_SymbolOrNewName)
| (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
if (isa<NamespaceDecl>(R.Declaration) ||
isa<NamespaceAliasDecl>(R.Declaration))
NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
if (uint64_t RemainingContexts
= NNSContexts & ~CachedResult.ShowInContexts) {
R.StartsNestedNameSpecifier = true;
CachedResult.Completion = R.CreateCodeCompletionString(
*TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
IncludeBriefCommentsInCodeCompletion);
CachedResult.ShowInContexts = RemainingContexts;
CachedResult.Priority = CCP_NestedNameSpecifier;
CachedResult.TypeClass = STC_Void;
CachedResult.Type = 0;
CachedCompletionResults.push_back(CachedResult);
}
}
break;
}
case Result::RK_Keyword:
case Result::RK_Pattern:
break;
case Result::RK_Macro: {
CachedCodeCompletionResult CachedResult;
CachedResult.Completion = R.CreateCodeCompletionString(
*TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
IncludeBriefCommentsInCodeCompletion);
CachedResult.ShowInContexts
= (1LL << CodeCompletionContext::CCC_TopLevel)
| (1LL << CodeCompletionContext::CCC_ObjCInterface)
| (1LL << CodeCompletionContext::CCC_ObjCImplementation)
| (1LL << CodeCompletionContext::CCC_ObjCIvarList)
| (1LL << CodeCompletionContext::CCC_ClassStructUnion)
| (1LL << CodeCompletionContext::CCC_Statement)
| (1LL << CodeCompletionContext::CCC_Expression)
| (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
| (1LL << CodeCompletionContext::CCC_MacroNameUse)
| (1LL << CodeCompletionContext::CCC_PreprocessorExpression)
| (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
| (1LL << CodeCompletionContext::CCC_OtherWithMacros);
CachedResult.Priority = R.Priority;
CachedResult.Kind = R.CursorKind;
CachedResult.Availability = R.Availability;
CachedResult.TypeClass = STC_Void;
CachedResult.Type = 0;
CachedCompletionResults.push_back(CachedResult);
break;
}
}
}
CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
}
void ASTUnit::ClearCachedCompletionResults() {
CachedCompletionResults.clear();
CachedCompletionTypes.clear();
CachedCompletionAllocator = nullptr;
}
namespace {
class ASTInfoCollector : public ASTReaderListener {
Preprocessor &PP;
ASTContext *Context;
HeaderSearchOptions &HSOpts;
PreprocessorOptions &PPOpts;
LangOptions &LangOpt;
std::shared_ptr<TargetOptions> &TargetOpts;
IntrusiveRefCntPtr<TargetInfo> &Target;
unsigned &Counter;
bool InitializedLanguage = false;
public:
ASTInfoCollector(Preprocessor &PP, ASTContext *Context,
HeaderSearchOptions &HSOpts, PreprocessorOptions &PPOpts,
LangOptions &LangOpt,
std::shared_ptr<TargetOptions> &TargetOpts,
IntrusiveRefCntPtr<TargetInfo> &Target, unsigned &Counter)
: PP(PP), Context(Context), HSOpts(HSOpts), PPOpts(PPOpts),
LangOpt(LangOpt), TargetOpts(TargetOpts), Target(Target),
Counter(Counter) {}
bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
bool AllowCompatibleDifferences) override {
if (InitializedLanguage)
return false;
LangOpt = LangOpts;
InitializedLanguage = true;
updated();
return false;
}
bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
StringRef SpecificModuleCachePath,
bool Complain) override {
this->HSOpts = HSOpts;
return false;
}
bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool Complain,
std::string &SuggestedPredefines) override {
this->PPOpts = PPOpts;
return false;
}
bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
bool AllowCompatibleDifferences) override {
if (Target)
return false;
this->TargetOpts = std::make_shared<TargetOptions>(TargetOpts);
Target =
TargetInfo::CreateTargetInfo(PP.getDiagnostics(), this->TargetOpts);
updated();
return false;
}
void ReadCounter(const serialization::ModuleFile &M,
unsigned Value) override {
Counter = Value;
}
private:
void updated() {
if (!Target || !InitializedLanguage)
return;
Target->adjust(PP.getDiagnostics(), LangOpt);
PP.Initialize(*Target);
if (!Context)
return;
Context->InitBuiltinTypes(*Target);
Context->setPrintingPolicy(PrintingPolicy(LangOpt));
Context->getCommentCommandTraits().registerCommentOptions(
LangOpt.CommentOpts);
}
};
class FilterAndStoreDiagnosticConsumer : public DiagnosticConsumer {
SmallVectorImpl<StoredDiagnostic> *StoredDiags;
SmallVectorImpl<ASTUnit::StandaloneDiagnostic> *StandaloneDiags;
bool CaptureNonErrorsFromIncludes = true;
const LangOptions *LangOpts = nullptr;
SourceManager *SourceMgr = nullptr;
public:
FilterAndStoreDiagnosticConsumer(
SmallVectorImpl<StoredDiagnostic> *StoredDiags,
SmallVectorImpl<ASTUnit::StandaloneDiagnostic> *StandaloneDiags,
bool CaptureNonErrorsFromIncludes)
: StoredDiags(StoredDiags), StandaloneDiags(StandaloneDiags),
CaptureNonErrorsFromIncludes(CaptureNonErrorsFromIncludes) {
assert((StoredDiags || StandaloneDiags) &&
"No output collections were passed to StoredDiagnosticConsumer.");
}
void BeginSourceFile(const LangOptions &LangOpts,
const Preprocessor *PP = nullptr) override {
this->LangOpts = &LangOpts;
if (PP)
SourceMgr = &PP->getSourceManager();
}
void HandleDiagnostic(DiagnosticsEngine::Level Level,
const Diagnostic &Info) override;
};
class CaptureDroppedDiagnostics {
DiagnosticsEngine &Diags;
FilterAndStoreDiagnosticConsumer Client;
DiagnosticConsumer *PreviousClient = nullptr;
std::unique_ptr<DiagnosticConsumer> OwningPreviousClient;
public:
CaptureDroppedDiagnostics(
CaptureDiagsKind CaptureDiagnostics, DiagnosticsEngine &Diags,
SmallVectorImpl<StoredDiagnostic> *StoredDiags,
SmallVectorImpl<ASTUnit::StandaloneDiagnostic> *StandaloneDiags)
: Diags(Diags),
Client(StoredDiags, StandaloneDiags,
CaptureDiagnostics !=
CaptureDiagsKind::AllWithoutNonErrorsFromIncludes) {
if (CaptureDiagnostics != CaptureDiagsKind::None ||
Diags.getClient() == nullptr) {
OwningPreviousClient = Diags.takeClient();
PreviousClient = Diags.getClient();
Diags.setClient(&Client, false);
}
}
~CaptureDroppedDiagnostics() {
if (Diags.getClient() == &Client)
Diags.setClient(PreviousClient, !!OwningPreviousClient.release());
}
};
}
static ASTUnit::StandaloneDiagnostic
makeStandaloneDiagnostic(const LangOptions &LangOpts,
const StoredDiagnostic &InDiag);
static bool isInMainFile(const clang::Diagnostic &D) {
if (!D.hasSourceManager() || !D.getLocation().isValid())
return false;
auto &M = D.getSourceManager();
return M.isWrittenInMainFile(M.getExpansionLoc(D.getLocation()));
}
void FilterAndStoreDiagnosticConsumer::HandleDiagnostic(
DiagnosticsEngine::Level Level, const Diagnostic &Info) {
DiagnosticConsumer::HandleDiagnostic(Level, Info);
if (!Info.hasSourceManager() || &Info.getSourceManager() == SourceMgr) {
if (!CaptureNonErrorsFromIncludes && Level <= DiagnosticsEngine::Warning &&
!isInMainFile(Info)) {
return;
}
StoredDiagnostic *ResultDiag = nullptr;
if (StoredDiags) {
StoredDiags->emplace_back(Level, Info);
ResultDiag = &StoredDiags->back();
}
if (StandaloneDiags) {
llvm::Optional<StoredDiagnostic> StoredDiag = None;
if (!ResultDiag) {
StoredDiag.emplace(Level, Info);
ResultDiag = StoredDiag.getPointer();
}
StandaloneDiags->push_back(
makeStandaloneDiagnostic(*LangOpts, *ResultDiag));
}
}
}
IntrusiveRefCntPtr<ASTReader> ASTUnit::getASTReader() const {
return Reader;
}
ASTMutationListener *ASTUnit::getASTMutationListener() {
if (WriterData)
return &WriterData->Writer;
return nullptr;
}
ASTDeserializationListener *ASTUnit::getDeserializationListener() {
if (WriterData)
return &WriterData->Writer;
return nullptr;
}
std::unique_ptr<llvm::MemoryBuffer>
ASTUnit::getBufferForFile(StringRef Filename, std::string *ErrorStr) {
assert(FileMgr);
auto Buffer = FileMgr->getBufferForFile(Filename, UserFilesAreVolatile);
if (Buffer)
return std::move(*Buffer);
if (ErrorStr)
*ErrorStr = Buffer.getError().message();
return nullptr;
}
void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
ASTUnit &AST,
CaptureDiagsKind CaptureDiagnostics) {
assert(Diags.get() && "no DiagnosticsEngine was provided");
if (CaptureDiagnostics != CaptureDiagsKind::None)
Diags->setClient(new FilterAndStoreDiagnosticConsumer(
&AST.StoredDiagnostics, nullptr,
CaptureDiagnostics != CaptureDiagsKind::AllWithoutNonErrorsFromIncludes));
}
std::unique_ptr<ASTUnit> ASTUnit::LoadFromASTFile(
const std::string &Filename, const PCHContainerReader &PCHContainerRdr,
WhatToLoad ToLoad, IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
const FileSystemOptions &FileSystemOpts, bool UseDebugInfo,
bool OnlyLocalDecls, CaptureDiagsKind CaptureDiagnostics,
bool AllowASTWithCompilerErrors, bool UserFilesAreVolatile,
IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
std::unique_ptr<ASTUnit> AST(new ASTUnit(true));
llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
ASTUnitCleanup(AST.get());
llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
DiagCleanup(Diags.get());
ConfigureDiags(Diags, *AST, CaptureDiagnostics);
AST->LangOpts = std::make_shared<LangOptions>();
AST->OnlyLocalDecls = OnlyLocalDecls;
AST->CaptureDiagnostics = CaptureDiagnostics;
AST->Diagnostics = Diags;
AST->FileMgr = new FileManager(FileSystemOpts, VFS);
AST->UserFilesAreVolatile = UserFilesAreVolatile;
AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
AST->getFileManager(),
UserFilesAreVolatile);
AST->ModuleCache = new InMemoryModuleCache;
AST->HSOpts = std::make_shared<HeaderSearchOptions>();
AST->HSOpts->ModuleFormat = std::string(PCHContainerRdr.getFormat());
AST->HeaderInfo.reset(new HeaderSearch(AST->HSOpts,
AST->getSourceManager(),
AST->getDiagnostics(),
AST->getLangOpts(),
nullptr));
AST->PPOpts = std::make_shared<PreprocessorOptions>();
HeaderSearch &HeaderInfo = *AST->HeaderInfo;
unsigned Counter;
AST->PP = std::make_shared<Preprocessor>(
AST->PPOpts, AST->getDiagnostics(), *AST->LangOpts,
AST->getSourceManager(), HeaderInfo, AST->ModuleLoader,
nullptr,
false);
Preprocessor &PP = *AST->PP;
if (ToLoad >= LoadASTOnly)
AST->Ctx = new ASTContext(*AST->LangOpts, AST->getSourceManager(),
PP.getIdentifierTable(), PP.getSelectorTable(),
PP.getBuiltinInfo(),
AST->getTranslationUnitKind());
DisableValidationForModuleKind disableValid =
DisableValidationForModuleKind::None;
if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
disableValid = DisableValidationForModuleKind::All;
AST->Reader = new ASTReader(
PP, *AST->ModuleCache, AST->Ctx.get(), PCHContainerRdr, {},
"",
disableValid, AllowASTWithCompilerErrors);
AST->Reader->setListener(std::make_unique<ASTInfoCollector>(
*AST->PP, AST->Ctx.get(), *AST->HSOpts, *AST->PPOpts, *AST->LangOpts,
AST->TargetOpts, AST->Target, Counter));
if (AST->Ctx)
AST->Ctx->setExternalSource(AST->Reader);
switch (AST->Reader->ReadAST(Filename, serialization::MK_MainFile,
SourceLocation(), ASTReader::ARR_None)) {
case ASTReader::Success:
break;
case ASTReader::Failure:
case ASTReader::Missing:
case ASTReader::OutOfDate:
case ASTReader::VersionMismatch:
case ASTReader::ConfigurationMismatch:
case ASTReader::HadErrors:
AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
return nullptr;
}
AST->OriginalSourceFile = std::string(AST->Reader->getOriginalSourceFile());
PP.setCounterValue(Counter);
if (ToLoad >= LoadASTOnly)
AST->Consumer.reset(new ASTConsumer);
if (ToLoad >= LoadEverything) {
AST->TheSema.reset(new Sema(PP, *AST->Ctx, *AST->Consumer));
AST->TheSema->Initialize();
AST->Reader->InitializeSema(*AST->TheSema);
}
AST->getDiagnostics().getClient()->BeginSourceFile(PP.getLangOpts(), &PP);
return AST;
}
static void AddDefinedMacroToHash(const Token &MacroNameTok, unsigned &Hash) {
Hash = llvm::djbHash(MacroNameTok.getIdentifierInfo()->getName(), Hash);
}
namespace {
class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
unsigned &Hash;
public:
explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) {}
void MacroDefined(const Token &MacroNameTok,
const MacroDirective *MD) override {
AddDefinedMacroToHash(MacroNameTok, Hash);
}
};
}
static void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
if (!D)
return;
DeclContext *DC = D->getDeclContext();
if (!DC)
return;
if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
return;
if (const auto *ND = dyn_cast<NamedDecl>(D)) {
if (const auto *EnumD = dyn_cast<EnumDecl>(D)) {
if (!EnumD->isScoped()) {
for (const auto *EI : EnumD->enumerators()) {
if (EI->getIdentifier())
Hash = llvm::djbHash(EI->getIdentifier()->getName(), Hash);
}
}
}
if (ND->getIdentifier())
Hash = llvm::djbHash(ND->getIdentifier()->getName(), Hash);
else if (DeclarationName Name = ND->getDeclName()) {
std::string NameStr = Name.getAsString();
Hash = llvm::djbHash(NameStr, Hash);
}
return;
}
if (const auto *ImportD = dyn_cast<ImportDecl>(D)) {
if (const Module *Mod = ImportD->getImportedModule()) {
std::string ModName = Mod->getFullModuleName();
Hash = llvm::djbHash(ModName, Hash);
}
return;
}
}
namespace {
class TopLevelDeclTrackerConsumer : public ASTConsumer {
ASTUnit &Unit;
unsigned &Hash;
public:
TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
: Unit(_Unit), Hash(Hash) {
Hash = 0;
}
void handleTopLevelDecl(Decl *D) {
if (!D)
return;
if (isa<ObjCMethodDecl>(D))
return;
AddTopLevelDeclarationToHash(D, Hash);
Unit.addTopLevelDecl(D);
handleFileLevelDecl(D);
}
void handleFileLevelDecl(Decl *D) {
Unit.addFileLevelDecl(D);
if (auto *NSD = dyn_cast<NamespaceDecl>(D)) {
for (auto *I : NSD->decls())
handleFileLevelDecl(I);
}
}
bool HandleTopLevelDecl(DeclGroupRef D) override {
for (auto *TopLevelDecl : D)
handleTopLevelDecl(TopLevelDecl);
return true;
}
void HandleInterestingDecl(DeclGroupRef) override {}
void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
for (auto *TopLevelDecl : D)
handleTopLevelDecl(TopLevelDecl);
}
ASTMutationListener *GetASTMutationListener() override {
return Unit.getASTMutationListener();
}
ASTDeserializationListener *GetASTDeserializationListener() override {
return Unit.getDeserializationListener();
}
};
class TopLevelDeclTrackerAction : public ASTFrontendAction {
public:
ASTUnit &Unit;
std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
StringRef InFile) override {
CI.getPreprocessor().addPPCallbacks(
std::make_unique<MacroDefinitionTrackerPPCallbacks>(
Unit.getCurrentTopLevelHashValue()));
return std::make_unique<TopLevelDeclTrackerConsumer>(
Unit, Unit.getCurrentTopLevelHashValue());
}
public:
TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
bool hasCodeCompletionSupport() const override { return false; }
TranslationUnitKind getTranslationUnitKind() override {
return Unit.getTranslationUnitKind();
}
};
class ASTUnitPreambleCallbacks : public PreambleCallbacks {
public:
unsigned getHash() const { return Hash; }
std::vector<Decl *> takeTopLevelDecls() { return std::move(TopLevelDecls); }
std::vector<serialization::DeclID> takeTopLevelDeclIDs() {
return std::move(TopLevelDeclIDs);
}
void AfterPCHEmitted(ASTWriter &Writer) override {
TopLevelDeclIDs.reserve(TopLevelDecls.size());
for (const auto *D : TopLevelDecls) {
if (D->isInvalidDecl())
continue;
TopLevelDeclIDs.push_back(Writer.getDeclID(D));
}
}
void HandleTopLevelDecl(DeclGroupRef DG) override {
for (auto *D : DG) {
if (isa<ObjCMethodDecl>(D))
continue;
AddTopLevelDeclarationToHash(D, Hash);
TopLevelDecls.push_back(D);
}
}
std::unique_ptr<PPCallbacks> createPPCallbacks() override {
return std::make_unique<MacroDefinitionTrackerPPCallbacks>(Hash);
}
private:
unsigned Hash = 0;
std::vector<Decl *> TopLevelDecls;
std::vector<serialization::DeclID> TopLevelDeclIDs;
llvm::SmallVector<ASTUnit::StandaloneDiagnostic, 4> PreambleDiags;
};
}
static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag) {
return StoredDiag.getLocation().isValid();
}
static void
checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &StoredDiags) {
llvm::erase_if(StoredDiags, isNonDriverDiag);
}
static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
StoredDiagnostics,
SourceManager &SM) {
for (auto &SD : StoredDiagnostics) {
if (SD.getLocation().isValid()) {
FullSourceLoc Loc(SD.getLocation(), SM);
SD.setLocation(Loc);
}
}
}
bool ASTUnit::Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer,
IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
if (!Invocation)
return true;
if (VFS && FileMgr)
assert(VFS == &FileMgr->getVirtualFileSystem() &&
"VFS passed to Parse and VFS in FileMgr are different");
auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation);
if (OverrideMainBuffer) {
assert(Preamble &&
"No preamble was built, but OverrideMainBuffer is not null");
Preamble->AddImplicitPreamble(*CCInvocation, VFS, OverrideMainBuffer.get());
}
std::unique_ptr<CompilerInstance> Clang(
new CompilerInstance(std::move(PCHContainerOps)));
auto CleanOnError = llvm::make_scope_exit([&]() {
SavedMainFileBuffer = nullptr;
transferASTDataFromCompilerInstance(*Clang);
FailedParseDiagnostics.swap(StoredDiagnostics);
StoredDiagnostics.clear();
NumStoredDiagnosticsFromDriver = 0;
});
if (VFS && FileMgr && &FileMgr->getVirtualFileSystem() == VFS)
Clang->setFileManager(&*FileMgr);
else
FileMgr = Clang->createFileManager(std::move(VFS));
llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
CICleanup(Clang.get());
Clang->setInvocation(CCInvocation);
OriginalSourceFile =
std::string(Clang->getFrontendOpts().Inputs[0].getFile());
Clang->setDiagnostics(&getDiagnostics());
if (!Clang->createTarget())
return true;
assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
"Invocation must have exactly one source file!");
assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
InputKind::Source &&
"FIXME: AST inputs not yet supported here!");
assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
Language::LLVM_IR &&
"IR inputs not support here!");
LangOpts = Clang->getInvocation().LangOpts;
FileSystemOpts = Clang->getFileSystemOpts();
ResetForParse();
SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
UserFilesAreVolatile);
if (!OverrideMainBuffer) {
checkAndRemoveNonDriverDiags(StoredDiagnostics);
TopLevelDeclsInPreamble.clear();
}
Clang->setSourceManager(&getSourceManager());
if (OverrideMainBuffer) {
checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
SavedMainFileBuffer = std::move(OverrideMainBuffer);
}
std::unique_ptr<TopLevelDeclTrackerAction> Act(
new TopLevelDeclTrackerAction(*this));
llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
ActCleanup(Act.get());
if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
return true;
if (SavedMainFileBuffer)
TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
PreambleDiagnostics, StoredDiagnostics);
else
PreambleSrcLocCache.clear();
if (llvm::Error Err = Act->Execute()) {
consumeError(std::move(Err)); return true;
}
transferASTDataFromCompilerInstance(*Clang);
Act->EndSourceFile();
FailedParseDiagnostics.clear();
CleanOnError.release();
return false;
}
static std::pair<unsigned, unsigned>
makeStandaloneRange(CharSourceRange Range, const SourceManager &SM,
const LangOptions &LangOpts) {
CharSourceRange FileRange = Lexer::makeFileCharRange(Range, SM, LangOpts);
unsigned Offset = SM.getFileOffset(FileRange.getBegin());
unsigned EndOffset = SM.getFileOffset(FileRange.getEnd());
return std::make_pair(Offset, EndOffset);
}
static ASTUnit::StandaloneFixIt makeStandaloneFixIt(const SourceManager &SM,
const LangOptions &LangOpts,
const FixItHint &InFix) {
ASTUnit::StandaloneFixIt OutFix;
OutFix.RemoveRange = makeStandaloneRange(InFix.RemoveRange, SM, LangOpts);
OutFix.InsertFromRange = makeStandaloneRange(InFix.InsertFromRange, SM,
LangOpts);
OutFix.CodeToInsert = InFix.CodeToInsert;
OutFix.BeforePreviousInsertions = InFix.BeforePreviousInsertions;
return OutFix;
}
static ASTUnit::StandaloneDiagnostic
makeStandaloneDiagnostic(const LangOptions &LangOpts,
const StoredDiagnostic &InDiag) {
ASTUnit::StandaloneDiagnostic OutDiag;
OutDiag.ID = InDiag.getID();
OutDiag.Level = InDiag.getLevel();
OutDiag.Message = std::string(InDiag.getMessage());
OutDiag.LocOffset = 0;
if (InDiag.getLocation().isInvalid())
return OutDiag;
const SourceManager &SM = InDiag.getLocation().getManager();
SourceLocation FileLoc = SM.getFileLoc(InDiag.getLocation());
OutDiag.Filename = std::string(SM.getFilename(FileLoc));
if (OutDiag.Filename.empty())
return OutDiag;
OutDiag.LocOffset = SM.getFileOffset(FileLoc);
for (const auto &Range : InDiag.getRanges())
OutDiag.Ranges.push_back(makeStandaloneRange(Range, SM, LangOpts));
for (const auto &FixIt : InDiag.getFixIts())
OutDiag.FixIts.push_back(makeStandaloneFixIt(SM, LangOpts, FixIt));
return OutDiag;
}
std::unique_ptr<llvm::MemoryBuffer>
ASTUnit::getMainBufferWithPrecompiledPreamble(
std::shared_ptr<PCHContainerOperations> PCHContainerOps,
CompilerInvocation &PreambleInvocationIn,
IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS, bool AllowRebuild,
unsigned MaxLines) {
auto MainFilePath =
PreambleInvocationIn.getFrontendOpts().Inputs[0].getFile();
std::unique_ptr<llvm::MemoryBuffer> MainFileBuffer =
getBufferForFileHandlingRemapping(PreambleInvocationIn, VFS.get(),
MainFilePath, UserFilesAreVolatile);
if (!MainFileBuffer)
return nullptr;
PreambleBounds Bounds = ComputePreambleBounds(
*PreambleInvocationIn.getLangOpts(), *MainFileBuffer, MaxLines);
if (!Bounds.Size)
return nullptr;
if (Preamble) {
if (Preamble->CanReuse(PreambleInvocationIn, *MainFileBuffer, Bounds,
*VFS)) {
getDiagnostics().Reset();
ProcessWarningOptions(getDiagnostics(),
PreambleInvocationIn.getDiagnosticOpts());
getDiagnostics().setNumWarnings(NumWarningsInPreamble);
PreambleRebuildCountdown = 1;
return MainFileBuffer;
} else {
Preamble.reset();
PreambleDiagnostics.clear();
TopLevelDeclsInPreamble.clear();
PreambleSrcLocCache.clear();
PreambleRebuildCountdown = 1;
}
}
if (PreambleRebuildCountdown > 1) {
--PreambleRebuildCountdown;
return nullptr;
}
assert(!Preamble && "No Preamble should be stored at that point");
if (!AllowRebuild)
return nullptr;
++PreambleCounter;
SmallVector<StandaloneDiagnostic, 4> NewPreambleDiagsStandalone;
SmallVector<StoredDiagnostic, 4> NewPreambleDiags;
ASTUnitPreambleCallbacks Callbacks;
{
llvm::Optional<CaptureDroppedDiagnostics> Capture;
if (CaptureDiagnostics != CaptureDiagsKind::None)
Capture.emplace(CaptureDiagnostics, *Diagnostics, &NewPreambleDiags,
&NewPreambleDiagsStandalone);
SimpleTimer PreambleTimer(WantTiming);
PreambleTimer.setOutput("Precompiling preamble");
const bool PreviousSkipFunctionBodies =
PreambleInvocationIn.getFrontendOpts().SkipFunctionBodies;
if (SkipFunctionBodies == SkipFunctionBodiesScope::Preamble)
PreambleInvocationIn.getFrontendOpts().SkipFunctionBodies = true;
llvm::ErrorOr<PrecompiledPreamble> NewPreamble = PrecompiledPreamble::Build(
PreambleInvocationIn, MainFileBuffer.get(), Bounds, *Diagnostics, VFS,
PCHContainerOps, false, Callbacks);
PreambleInvocationIn.getFrontendOpts().SkipFunctionBodies =
PreviousSkipFunctionBodies;
if (NewPreamble) {
Preamble = std::move(*NewPreamble);
PreambleRebuildCountdown = 1;
} else {
switch (static_cast<BuildPreambleError>(NewPreamble.getError().value())) {
case BuildPreambleError::CouldntCreateTempFile:
PreambleRebuildCountdown = 1;
return nullptr;
case BuildPreambleError::CouldntCreateTargetInfo:
case BuildPreambleError::BeginSourceFileFailed:
case BuildPreambleError::CouldntEmitPCH:
case BuildPreambleError::BadInputs:
PreambleRebuildCountdown = DefaultPreambleRebuildInterval;
return nullptr;
}
llvm_unreachable("unexpected BuildPreambleError");
}
}
assert(Preamble && "Preamble wasn't built");
TopLevelDecls.clear();
TopLevelDeclsInPreamble = Callbacks.takeTopLevelDeclIDs();
PreambleTopLevelHashValue = Callbacks.getHash();
NumWarningsInPreamble = getDiagnostics().getNumWarnings();
checkAndRemoveNonDriverDiags(NewPreambleDiags);
StoredDiagnostics = std::move(NewPreambleDiags);
PreambleDiagnostics = std::move(NewPreambleDiagsStandalone);
if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
CompletionCacheTopLevelHashValue = 0;
PreambleTopLevelHashValue = CurrentTopLevelHashValue;
}
return MainFileBuffer;
}
void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
assert(Preamble && "Should only be called when preamble was built");
std::vector<Decl *> Resolved;
Resolved.reserve(TopLevelDeclsInPreamble.size());
ExternalASTSource &Source = *getASTContext().getExternalSource();
for (const auto TopLevelDecl : TopLevelDeclsInPreamble) {
if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
Resolved.push_back(D);
}
TopLevelDeclsInPreamble.clear();
TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
}
void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
assert(CI.hasInvocation() && "missing invocation");
LangOpts = CI.getInvocation().LangOpts;
TheSema = CI.takeSema();
Consumer = CI.takeASTConsumer();
if (CI.hasASTContext())
Ctx = &CI.getASTContext();
if (CI.hasPreprocessor())
PP = CI.getPreprocessorPtr();
CI.setSourceManager(nullptr);
CI.setFileManager(nullptr);
if (CI.hasTarget())
Target = &CI.getTarget();
Reader = CI.getASTReader();
HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure();
}
StringRef ASTUnit::getMainFileName() const {
if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0];
if (Input.isFile())
return Input.getFile();
else
return Input.getBuffer().getBufferIdentifier();
}
if (SourceMgr) {
if (const FileEntry *
FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
return FE->getName();
}
return {};
}
StringRef ASTUnit::getASTFileName() const {
if (!isMainFileAST())
return {};
serialization::ModuleFile &
Mod = Reader->getModuleManager().getPrimaryModule();
return Mod.FileName;
}
std::unique_ptr<ASTUnit>
ASTUnit::create(std::shared_ptr<CompilerInvocation> CI,
IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
CaptureDiagsKind CaptureDiagnostics,
bool UserFilesAreVolatile) {
std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
ConfigureDiags(Diags, *AST, CaptureDiagnostics);
IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS =
createVFSFromCompilerInvocation(*CI, *Diags);
AST->Diagnostics = Diags;
AST->FileSystemOpts = CI->getFileSystemOpts();
AST->Invocation = std::move(CI);
AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
AST->UserFilesAreVolatile = UserFilesAreVolatile;
AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
UserFilesAreVolatile);
AST->ModuleCache = new InMemoryModuleCache;
return AST;
}
ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(
std::shared_ptr<CompilerInvocation> CI,
std::shared_ptr<PCHContainerOperations> PCHContainerOps,
IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FrontendAction *Action,
ASTUnit *Unit, bool Persistent, StringRef ResourceFilesPath,
bool OnlyLocalDecls, CaptureDiagsKind CaptureDiagnostics,
unsigned PrecompilePreambleAfterNParses, bool CacheCodeCompletionResults,
bool UserFilesAreVolatile, std::unique_ptr<ASTUnit> *ErrAST) {
assert(CI && "A CompilerInvocation is required");
std::unique_ptr<ASTUnit> OwnAST;
ASTUnit *AST = Unit;
if (!AST) {
OwnAST = create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile);
AST = OwnAST.get();
if (!AST)
return nullptr;
}
if (!ResourceFilesPath.empty()) {
CI->getHeaderSearchOpts().ResourceDir = std::string(ResourceFilesPath);
}
AST->OnlyLocalDecls = OnlyLocalDecls;
AST->CaptureDiagnostics = CaptureDiagnostics;
if (PrecompilePreambleAfterNParses > 0)
AST->PreambleRebuildCountdown = PrecompilePreambleAfterNParses;
AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
AST->IncludeBriefCommentsInCodeCompletion = false;
llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
ASTUnitCleanup(OwnAST.get());
llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
DiagCleanup(Diags.get());
CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
CI->getFrontendOpts().DisableFree = false;
ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
std::unique_ptr<CompilerInstance> Clang(
new CompilerInstance(std::move(PCHContainerOps)));
llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
CICleanup(Clang.get());
Clang->setInvocation(std::move(CI));
AST->OriginalSourceFile =
std::string(Clang->getFrontendOpts().Inputs[0].getFile());
Clang->setDiagnostics(&AST->getDiagnostics());
if (!Clang->createTarget())
return nullptr;
assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
"Invocation must have exactly one source file!");
assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
InputKind::Source &&
"FIXME: AST inputs not yet supported here!");
assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
Language::LLVM_IR &&
"IR inputs not support here!");
AST->TheSema.reset();
AST->Ctx = nullptr;
AST->PP = nullptr;
AST->Reader = nullptr;
Clang->setFileManager(&AST->getFileManager());
Clang->setSourceManager(&AST->getSourceManager());
FrontendAction *Act = Action;
std::unique_ptr<TopLevelDeclTrackerAction> TrackerAct;
if (!Act) {
TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
Act = TrackerAct.get();
}
llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
ActCleanup(TrackerAct.get());
if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
AST->transferASTDataFromCompilerInstance(*Clang);
if (OwnAST && ErrAST)
ErrAST->swap(OwnAST);
return nullptr;
}
if (Persistent && !TrackerAct) {
Clang->getPreprocessor().addPPCallbacks(
std::make_unique<MacroDefinitionTrackerPPCallbacks>(
AST->getCurrentTopLevelHashValue()));
std::vector<std::unique_ptr<ASTConsumer>> Consumers;
if (Clang->hasASTConsumer())
Consumers.push_back(Clang->takeASTConsumer());
Consumers.push_back(std::make_unique<TopLevelDeclTrackerConsumer>(
*AST, AST->getCurrentTopLevelHashValue()));
Clang->setASTConsumer(
std::make_unique<MultiplexConsumer>(std::move(Consumers)));
}
if (llvm::Error Err = Act->Execute()) {
consumeError(std::move(Err)); AST->transferASTDataFromCompilerInstance(*Clang);
if (OwnAST && ErrAST)
ErrAST->swap(OwnAST);
return nullptr;
}
AST->transferASTDataFromCompilerInstance(*Clang);
Act->EndSourceFile();
if (OwnAST)
return OwnAST.release();
else
return AST;
}
bool ASTUnit::LoadFromCompilerInvocation(
std::shared_ptr<PCHContainerOperations> PCHContainerOps,
unsigned PrecompilePreambleAfterNParses,
IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
if (!Invocation)
return true;
assert(VFS && "VFS is null");
Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
Invocation->getFrontendOpts().DisableFree = false;
getDiagnostics().Reset();
ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
if (PrecompilePreambleAfterNParses > 0) {
PreambleRebuildCountdown = PrecompilePreambleAfterNParses;
OverrideMainBuffer =
getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS);
getDiagnostics().Reset();
ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
}
SimpleTimer ParsingTimer(WantTiming);
ParsingTimer.setOutput("Parsing " + getMainFileName());
llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
MemBufferCleanup(OverrideMainBuffer.get());
return Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS);
}
std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation(
std::shared_ptr<CompilerInvocation> CI,
std::shared_ptr<PCHContainerOperations> PCHContainerOps,
IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FileManager *FileMgr,
bool OnlyLocalDecls, CaptureDiagsKind CaptureDiagnostics,
unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
bool UserFilesAreVolatile) {
std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
ConfigureDiags(Diags, *AST, CaptureDiagnostics);
AST->Diagnostics = Diags;
AST->OnlyLocalDecls = OnlyLocalDecls;
AST->CaptureDiagnostics = CaptureDiagnostics;
AST->TUKind = TUKind;
AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
AST->IncludeBriefCommentsInCodeCompletion
= IncludeBriefCommentsInCodeCompletion;
AST->Invocation = std::move(CI);
AST->FileSystemOpts = FileMgr->getFileSystemOpts();
AST->FileMgr = FileMgr;
AST->UserFilesAreVolatile = UserFilesAreVolatile;
llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
ASTUnitCleanup(AST.get());
llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
DiagCleanup(Diags.get());
if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
PrecompilePreambleAfterNParses,
&AST->FileMgr->getVirtualFileSystem()))
return nullptr;
return AST;
}
ASTUnit *ASTUnit::LoadFromCommandLine(
const char **ArgBegin, const char **ArgEnd,
std::shared_ptr<PCHContainerOperations> PCHContainerOps,
IntrusiveRefCntPtr<DiagnosticsEngine> Diags, StringRef ResourceFilesPath,
bool OnlyLocalDecls, CaptureDiagsKind CaptureDiagnostics,
ArrayRef<RemappedFile> RemappedFiles, bool RemappedFilesKeepOriginalName,
unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
bool AllowPCHWithCompilerErrors, SkipFunctionBodiesScope SkipFunctionBodies,
bool SingleFileParse, bool UserFilesAreVolatile, bool ForSerialization,
bool RetainExcludedConditionalBlocks,
llvm::Optional<StringRef> ModuleFormat, std::unique_ptr<ASTUnit> *ErrAST,
IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
assert(Diags.get() && "no DiagnosticsEngine was provided");
SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
std::shared_ptr<CompilerInvocation> CI;
{
CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
&StoredDiagnostics, nullptr);
CreateInvocationOptions CIOpts;
CIOpts.VFS = VFS;
CIOpts.Diags = Diags;
CIOpts.ProbePrecompiled = true; CI = createInvocation(llvm::makeArrayRef(ArgBegin, ArgEnd),
std::move(CIOpts));
if (!CI)
return nullptr;
}
for (const auto &RemappedFile : RemappedFiles) {
CI->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
RemappedFile.second);
}
PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
PPOpts.SingleFileParseMode = SingleFileParse;
PPOpts.RetainExcludedConditionalBlocks = RetainExcludedConditionalBlocks;
CI->getHeaderSearchOpts().ResourceDir = std::string(ResourceFilesPath);
CI->getFrontendOpts().SkipFunctionBodies =
SkipFunctionBodies == SkipFunctionBodiesScope::PreambleAndMainFile;
if (ModuleFormat)
CI->getHeaderSearchOpts().ModuleFormat = std::string(*ModuleFormat);
std::unique_ptr<ASTUnit> AST;
AST.reset(new ASTUnit(false));
AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
AST->StoredDiagnostics.swap(StoredDiagnostics);
ConfigureDiags(Diags, *AST, CaptureDiagnostics);
AST->Diagnostics = Diags;
AST->FileSystemOpts = CI->getFileSystemOpts();
if (!VFS)
VFS = llvm::vfs::getRealFileSystem();
VFS = createVFSFromCompilerInvocation(*CI, *Diags, VFS);
AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
AST->ModuleCache = new InMemoryModuleCache;
AST->OnlyLocalDecls = OnlyLocalDecls;
AST->CaptureDiagnostics = CaptureDiagnostics;
AST->TUKind = TUKind;
AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
AST->IncludeBriefCommentsInCodeCompletion
= IncludeBriefCommentsInCodeCompletion;
AST->UserFilesAreVolatile = UserFilesAreVolatile;
AST->Invocation = CI;
AST->SkipFunctionBodies = SkipFunctionBodies;
if (ForSerialization)
AST->WriterData.reset(new ASTWriterData(*AST->ModuleCache));
CI = nullptr;
Diags = nullptr;
llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
ASTUnitCleanup(AST.get());
if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
PrecompilePreambleAfterNParses,
VFS)) {
if (ErrAST) {
AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
ErrAST->swap(AST);
}
return nullptr;
}
return AST.release();
}
bool ASTUnit::Reparse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
ArrayRef<RemappedFile> RemappedFiles,
IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
if (!Invocation)
return true;
if (!VFS) {
assert(FileMgr && "FileMgr is null on Reparse call");
VFS = &FileMgr->getVirtualFileSystem();
}
clearFileLevelDecls();
SimpleTimer ParsingTimer(WantTiming);
ParsingTimer.setOutput("Reparsing " + getMainFileName());
PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
for (const auto &RB : PPOpts.RemappedFileBuffers)
delete RB.second;
Invocation->getPreprocessorOpts().clearRemappedFiles();
for (const auto &RemappedFile : RemappedFiles) {
Invocation->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
RemappedFile.second);
}
std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
if (Preamble || PreambleRebuildCountdown > 0)
OverrideMainBuffer =
getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS);
FileMgr.reset();
getDiagnostics().Reset();
ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
if (OverrideMainBuffer)
getDiagnostics().setNumWarnings(NumWarningsInPreamble);
bool Result =
Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS);
if (!Result && ShouldCacheCodeCompletionResults &&
CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
CacheCodeCompletionResults();
CCTUInfo.reset();
return Result;
}
void ASTUnit::ResetForParse() {
SavedMainFileBuffer.reset();
SourceMgr.reset();
TheSema.reset();
Ctx.reset();
PP.reset();
Reader.reset();
TopLevelDecls.clear();
clearFileLevelDecls();
}
namespace {
class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
uint64_t NormalContexts;
ASTUnit &AST;
CodeCompleteConsumer &Next;
public:
AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
const CodeCompleteOptions &CodeCompleteOpts)
: CodeCompleteConsumer(CodeCompleteOpts), AST(AST), Next(Next) {
NormalContexts
= (1LL << CodeCompletionContext::CCC_TopLevel)
| (1LL << CodeCompletionContext::CCC_ObjCInterface)
| (1LL << CodeCompletionContext::CCC_ObjCImplementation)
| (1LL << CodeCompletionContext::CCC_ObjCIvarList)
| (1LL << CodeCompletionContext::CCC_Statement)
| (1LL << CodeCompletionContext::CCC_Expression)
| (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
| (1LL << CodeCompletionContext::CCC_DotMemberAccess)
| (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
| (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
| (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
| (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
| (1LL << CodeCompletionContext::CCC_Recovery);
if (AST.getASTContext().getLangOpts().CPlusPlus)
NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
| (1LL << CodeCompletionContext::CCC_UnionTag)
| (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
}
void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
CodeCompletionResult *Results,
unsigned NumResults) override;
void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
OverloadCandidate *Candidates,
unsigned NumCandidates,
SourceLocation OpenParLoc,
bool Braced) override {
Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates,
OpenParLoc, Braced);
}
CodeCompletionAllocator &getAllocator() override {
return Next.getAllocator();
}
CodeCompletionTUInfo &getCodeCompletionTUInfo() override {
return Next.getCodeCompletionTUInfo();
}
};
}
static void CalculateHiddenNames(const CodeCompletionContext &Context,
CodeCompletionResult *Results,
unsigned NumResults,
ASTContext &Ctx,
llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
bool OnlyTagNames = false;
switch (Context.getKind()) {
case CodeCompletionContext::CCC_Recovery:
case CodeCompletionContext::CCC_TopLevel:
case CodeCompletionContext::CCC_ObjCInterface:
case CodeCompletionContext::CCC_ObjCImplementation:
case CodeCompletionContext::CCC_ObjCIvarList:
case CodeCompletionContext::CCC_ClassStructUnion:
case CodeCompletionContext::CCC_Statement:
case CodeCompletionContext::CCC_Expression:
case CodeCompletionContext::CCC_ObjCMessageReceiver:
case CodeCompletionContext::CCC_DotMemberAccess:
case CodeCompletionContext::CCC_ArrowMemberAccess:
case CodeCompletionContext::CCC_ObjCPropertyAccess:
case CodeCompletionContext::CCC_Namespace:
case CodeCompletionContext::CCC_Type:
case CodeCompletionContext::CCC_Symbol:
case CodeCompletionContext::CCC_SymbolOrNewName:
case CodeCompletionContext::CCC_ParenthesizedExpression:
case CodeCompletionContext::CCC_ObjCInterfaceName:
break;
case CodeCompletionContext::CCC_EnumTag:
case CodeCompletionContext::CCC_UnionTag:
case CodeCompletionContext::CCC_ClassOrStructTag:
OnlyTagNames = true;
break;
case CodeCompletionContext::CCC_ObjCProtocolName:
case CodeCompletionContext::CCC_MacroName:
case CodeCompletionContext::CCC_MacroNameUse:
case CodeCompletionContext::CCC_PreprocessorExpression:
case CodeCompletionContext::CCC_PreprocessorDirective:
case CodeCompletionContext::CCC_NaturalLanguage:
case CodeCompletionContext::CCC_SelectorName:
case CodeCompletionContext::CCC_TypeQualifiers:
case CodeCompletionContext::CCC_Other:
case CodeCompletionContext::CCC_OtherWithMacros:
case CodeCompletionContext::CCC_ObjCInstanceMessage:
case CodeCompletionContext::CCC_ObjCClassMessage:
case CodeCompletionContext::CCC_ObjCCategoryName:
case CodeCompletionContext::CCC_IncludedFile:
case CodeCompletionContext::CCC_Attribute:
case CodeCompletionContext::CCC_NewName:
return;
}
using Result = CodeCompletionResult;
for (unsigned I = 0; I != NumResults; ++I) {
if (Results[I].Kind != Result::RK_Declaration)
continue;
unsigned IDNS
= Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
bool Hiding = false;
if (OnlyTagNames)
Hiding = (IDNS & Decl::IDNS_Tag);
else {
unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
Decl::IDNS_NonMemberOperator);
if (Ctx.getLangOpts().CPlusPlus)
HiddenIDNS |= Decl::IDNS_Tag;
Hiding = (IDNS & HiddenIDNS);
}
if (!Hiding)
continue;
DeclarationName Name = Results[I].Declaration->getDeclName();
if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
HiddenNames.insert(Identifier->getName());
else
HiddenNames.insert(Name.getAsString());
}
}
void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
CodeCompletionContext Context,
CodeCompletionResult *Results,
unsigned NumResults) {
bool AddedResult = false;
uint64_t InContexts =
Context.getKind() == CodeCompletionContext::CCC_Recovery
? NormalContexts : (1LL << Context.getKind());
llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
using Result = CodeCompletionResult;
SmallVector<Result, 8> AllResults;
for (ASTUnit::cached_completion_iterator
C = AST.cached_completion_begin(),
CEnd = AST.cached_completion_end();
C != CEnd; ++C) {
if ((C->ShowInContexts & InContexts) == 0)
continue;
if (!AddedResult) {
CalculateHiddenNames(Context, Results, NumResults, S.Context,
HiddenNames);
AllResults.insert(AllResults.end(), Results, Results + NumResults);
AddedResult = true;
}
if (C->Kind != CXCursor_MacroDefinition &&
HiddenNames.count(C->Completion->getTypedText()))
continue;
unsigned Priority = C->Priority;
CodeCompletionString *Completion = C->Completion;
if (!Context.getPreferredType().isNull()) {
if (C->Kind == CXCursor_MacroDefinition) {
Priority = getMacroUsagePriority(C->Completion->getTypedText(),
S.getLangOpts(),
Context.getPreferredType()->isAnyPointerType());
} else if (C->Type) {
CanQualType Expected
= S.Context.getCanonicalType(
Context.getPreferredType().getUnqualifiedType());
SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
if (ExpectedSTC == C->TypeClass) {
llvm::StringMap<unsigned> &CachedCompletionTypes
= AST.getCachedCompletionTypes();
llvm::StringMap<unsigned>::iterator Pos
= CachedCompletionTypes.find(QualType(Expected).getAsString());
if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
Priority /= CCF_ExactTypeMatch;
else
Priority /= CCF_SimilarTypeMatch;
}
}
}
if (C->Kind == CXCursor_MacroDefinition &&
Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
CCP_CodePattern, C->Availability);
Builder.AddTypedTextChunk(C->Completion->getTypedText());
Priority = CCP_CodePattern;
Completion = Builder.TakeString();
}
AllResults.push_back(Result(Completion, Priority, C->Kind,
C->Availability));
}
if (!AddedResult) {
Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
return;
}
Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
AllResults.size());
}
void ASTUnit::CodeComplete(
StringRef File, unsigned Line, unsigned Column,
ArrayRef<RemappedFile> RemappedFiles, bool IncludeMacros,
bool IncludeCodePatterns, bool IncludeBriefComments,
CodeCompleteConsumer &Consumer,
std::shared_ptr<PCHContainerOperations> PCHContainerOps,
DiagnosticsEngine &Diag, LangOptions &LangOpts, SourceManager &SourceMgr,
FileManager &FileMgr, SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
if (!Invocation)
return;
SimpleTimer CompletionTimer(WantTiming);
CompletionTimer.setOutput("Code completion @ " + File + ":" +
Twine(Line) + ":" + Twine(Column));
auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation);
FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
CodeCompleteOpts.IncludeMacros = IncludeMacros &&
CachedCompletionResults.empty();
CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
CodeCompleteOpts.LoadExternal = Consumer.loadExternal();
CodeCompleteOpts.IncludeFixIts = Consumer.includeFixIts();
assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
FrontendOpts.CodeCompletionAt.FileName = std::string(File);
FrontendOpts.CodeCompletionAt.Line = Line;
FrontendOpts.CodeCompletionAt.Column = Column;
LangOpts = *CCInvocation->getLangOpts();
LangOpts.SpellChecking = false;
CCInvocation->getDiagnosticOpts().IgnoreWarnings = true;
std::unique_ptr<CompilerInstance> Clang(
new CompilerInstance(PCHContainerOps));
llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
CICleanup(Clang.get());
auto &Inv = *CCInvocation;
Clang->setInvocation(std::move(CCInvocation));
OriginalSourceFile =
std::string(Clang->getFrontendOpts().Inputs[0].getFile());
Clang->setDiagnostics(&Diag);
CaptureDroppedDiagnostics Capture(CaptureDiagsKind::All,
Clang->getDiagnostics(),
&StoredDiagnostics, nullptr);
ProcessWarningOptions(Diag, Inv.getDiagnosticOpts());
if (!Clang->createTarget()) {
Clang->setInvocation(nullptr);
return;
}
assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
"Invocation must have exactly one source file!");
assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
InputKind::Source &&
"FIXME: AST inputs not yet supported here!");
assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
Language::LLVM_IR &&
"IR inputs not support here!");
Clang->setFileManager(&FileMgr);
Clang->setSourceManager(&SourceMgr);
PreprocessorOpts.clearRemappedFiles();
PreprocessorOpts.RetainRemappedFileBuffers = true;
for (const auto &RemappedFile : RemappedFiles) {
PreprocessorOpts.addRemappedFile(RemappedFile.first, RemappedFile.second);
OwnedBuffers.push_back(RemappedFile.second);
}
AugmentedCodeCompleteConsumer *AugmentedConsumer
= new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
Clang->setCodeCompletionConsumer(AugmentedConsumer);
auto getUniqueID =
[&FileMgr](StringRef Filename) -> Optional<llvm::sys::fs::UniqueID> {
if (auto Status = FileMgr.getVirtualFileSystem().status(Filename))
return Status->getUniqueID();
return None;
};
auto hasSameUniqueID = [getUniqueID](StringRef LHS, StringRef RHS) {
if (LHS == RHS)
return true;
if (auto LHSID = getUniqueID(LHS))
if (auto RHSID = getUniqueID(RHS))
return *LHSID == *RHSID;
return false;
};
std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
if (Preamble && Line > 1 && hasSameUniqueID(File, OriginalSourceFile)) {
OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(
PCHContainerOps, Inv, &FileMgr.getVirtualFileSystem(), false, Line - 1);
}
if (OverrideMainBuffer) {
assert(Preamble &&
"No preamble was built, but OverrideMainBuffer is not null");
IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS =
&FileMgr.getVirtualFileSystem();
Preamble->AddImplicitPreamble(Clang->getInvocation(), VFS,
OverrideMainBuffer.get());
OwnedBuffers.push_back(OverrideMainBuffer.release());
} else {
PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
PreprocessorOpts.PrecompiledPreambleBytes.second = false;
}
if (!Clang->getLangOpts().Modules)
PreprocessorOpts.DetailedRecord = false;
std::unique_ptr<SyntaxOnlyAction> Act;
Act.reset(new SyntaxOnlyAction);
if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
if (llvm::Error Err = Act->Execute()) {
consumeError(std::move(Err)); }
Act->EndSourceFile();
}
}
bool ASTUnit::Save(StringRef File) {
if (HadModuleLoaderFatalFailure)
return true;
SmallString<128> TempPath;
TempPath = File;
TempPath += "-%%%%%%%%";
if (llvm::Error Err = llvm::writeFileAtomically(
TempPath, File, [this](llvm::raw_ostream &Out) {
return serialize(Out) ? llvm::make_error<llvm::StringError>(
"ASTUnit serialization failed",
llvm::inconvertibleErrorCode())
: llvm::Error::success();
})) {
consumeError(std::move(Err));
return true;
}
return false;
}
static bool serializeUnit(ASTWriter &Writer,
SmallVectorImpl<char> &Buffer,
Sema &S,
bool hasErrors,
raw_ostream &OS) {
Writer.WriteAST(S, std::string(), nullptr, "", hasErrors);
if (!Buffer.empty())
OS.write(Buffer.data(), Buffer.size());
return false;
}
bool ASTUnit::serialize(raw_ostream &OS) {
bool hasErrors = getDiagnostics().hasUncompilableErrorOccurred();
if (WriterData)
return serializeUnit(WriterData->Writer, WriterData->Buffer,
getSema(), hasErrors, OS);
SmallString<128> Buffer;
llvm::BitstreamWriter Stream(Buffer);
InMemoryModuleCache ModuleCache;
ASTWriter Writer(Stream, Buffer, ModuleCache, {});
return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
}
using SLocRemap = ContinuousRangeMap<unsigned, int, 2>;
void ASTUnit::TranslateStoredDiagnostics(
FileManager &FileMgr,
SourceManager &SrcMgr,
const SmallVectorImpl<StandaloneDiagnostic> &Diags,
SmallVectorImpl<StoredDiagnostic> &Out) {
SmallVector<StoredDiagnostic, 4> Result;
Result.reserve(Diags.size());
for (const auto &SD : Diags) {
if (SD.Filename.empty())
continue;
auto FE = FileMgr.getFile(SD.Filename);
if (!FE)
continue;
SourceLocation FileLoc;
auto ItFileID = PreambleSrcLocCache.find(SD.Filename);
if (ItFileID == PreambleSrcLocCache.end()) {
FileID FID = SrcMgr.translateFile(*FE);
FileLoc = SrcMgr.getLocForStartOfFile(FID);
PreambleSrcLocCache[SD.Filename] = FileLoc;
} else {
FileLoc = ItFileID->getValue();
}
if (FileLoc.isInvalid())
continue;
SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset);
FullSourceLoc Loc(L, SrcMgr);
SmallVector<CharSourceRange, 4> Ranges;
Ranges.reserve(SD.Ranges.size());
for (const auto &Range : SD.Ranges) {
SourceLocation BL = FileLoc.getLocWithOffset(Range.first);
SourceLocation EL = FileLoc.getLocWithOffset(Range.second);
Ranges.push_back(CharSourceRange::getCharRange(BL, EL));
}
SmallVector<FixItHint, 2> FixIts;
FixIts.reserve(SD.FixIts.size());
for (const auto &FixIt : SD.FixIts) {
FixIts.push_back(FixItHint());
FixItHint &FH = FixIts.back();
FH.CodeToInsert = FixIt.CodeToInsert;
SourceLocation BL = FileLoc.getLocWithOffset(FixIt.RemoveRange.first);
SourceLocation EL = FileLoc.getLocWithOffset(FixIt.RemoveRange.second);
FH.RemoveRange = CharSourceRange::getCharRange(BL, EL);
}
Result.push_back(StoredDiagnostic(SD.Level, SD.ID,
SD.Message, Loc, Ranges, FixIts));
}
Result.swap(Out);
}
void ASTUnit::addFileLevelDecl(Decl *D) {
assert(D);
if (D->isFromASTFile())
return;
SourceManager &SM = *SourceMgr;
SourceLocation Loc = D->getLocation();
if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
return;
if (!D->getLexicalDeclContext()->isFileContext())
return;
SourceLocation FileLoc = SM.getFileLoc(Loc);
assert(SM.isLocalSourceLocation(FileLoc));
FileID FID;
unsigned Offset;
std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
if (FID.isInvalid())
return;
std::unique_ptr<LocDeclsTy> &Decls = FileDecls[FID];
if (!Decls)
Decls = std::make_unique<LocDeclsTy>();
std::pair<unsigned, Decl *> LocDecl(Offset, D);
if (Decls->empty() || Decls->back().first <= Offset) {
Decls->push_back(LocDecl);
return;
}
LocDeclsTy::iterator I =
llvm::upper_bound(*Decls, LocDecl, llvm::less_first());
Decls->insert(I, LocDecl);
}
void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
SmallVectorImpl<Decl *> &Decls) {
if (File.isInvalid())
return;
if (SourceMgr->isLoadedFileID(File)) {
assert(Ctx->getExternalSource() && "No external source!");
return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
Decls);
}
FileDeclsTy::iterator I = FileDecls.find(File);
if (I == FileDecls.end())
return;
LocDeclsTy &LocDecls = *I->second;
if (LocDecls.empty())
return;
LocDeclsTy::iterator BeginIt =
llvm::partition_point(LocDecls, [=](std::pair<unsigned, Decl *> LD) {
return LD.first < Offset;
});
if (BeginIt != LocDecls.begin())
--BeginIt;
while (BeginIt != LocDecls.begin() &&
BeginIt->second->isTopLevelDeclInObjCContainer())
--BeginIt;
LocDeclsTy::iterator EndIt = llvm::upper_bound(
LocDecls, std::make_pair(Offset + Length, (Decl *)nullptr),
llvm::less_first());
if (EndIt != LocDecls.end())
++EndIt;
for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
Decls.push_back(DIt->second);
}
SourceLocation ASTUnit::getLocation(const FileEntry *File,
unsigned Line, unsigned Col) const {
const SourceManager &SM = getSourceManager();
SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
return SM.getMacroArgExpandedLocation(Loc);
}
SourceLocation ASTUnit::getLocation(const FileEntry *File,
unsigned Offset) const {
const SourceManager &SM = getSourceManager();
SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
}
SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) const {
FileID PreambleID;
if (SourceMgr)
PreambleID = SourceMgr->getPreambleFileID();
if (Loc.isInvalid() || !Preamble || PreambleID.isInvalid())
return Loc;
unsigned Offs;
if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble->getBounds().Size) {
SourceLocation FileLoc
= SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
return FileLoc.getLocWithOffset(Offs);
}
return Loc;
}
SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) const {
FileID PreambleID;
if (SourceMgr)
PreambleID = SourceMgr->getPreambleFileID();
if (Loc.isInvalid() || !Preamble || PreambleID.isInvalid())
return Loc;
unsigned Offs;
if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
Offs < Preamble->getBounds().Size) {
SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
return FileLoc.getLocWithOffset(Offs);
}
return Loc;
}
bool ASTUnit::isInPreambleFileID(SourceLocation Loc) const {
FileID FID;
if (SourceMgr)
FID = SourceMgr->getPreambleFileID();
if (Loc.isInvalid() || FID.isInvalid())
return false;
return SourceMgr->isInFileID(Loc, FID);
}
bool ASTUnit::isInMainFileID(SourceLocation Loc) const {
FileID FID;
if (SourceMgr)
FID = SourceMgr->getMainFileID();
if (Loc.isInvalid() || FID.isInvalid())
return false;
return SourceMgr->isInFileID(Loc, FID);
}
SourceLocation ASTUnit::getEndOfPreambleFileID() const {
FileID FID;
if (SourceMgr)
FID = SourceMgr->getPreambleFileID();
if (FID.isInvalid())
return {};
return SourceMgr->getLocForEndOfFile(FID);
}
SourceLocation ASTUnit::getStartOfMainFileID() const {
FileID FID;
if (SourceMgr)
FID = SourceMgr->getMainFileID();
if (FID.isInvalid())
return {};
return SourceMgr->getLocForStartOfFile(FID);
}
llvm::iterator_range<PreprocessingRecord::iterator>
ASTUnit::getLocalPreprocessingEntities() const {
if (isMainFileAST()) {
serialization::ModuleFile &
Mod = Reader->getModuleManager().getPrimaryModule();
return Reader->getModulePreprocessedEntities(Mod);
}
if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
return llvm::make_range(PPRec->local_begin(), PPRec->local_end());
return llvm::make_range(PreprocessingRecord::iterator(),
PreprocessingRecord::iterator());
}
bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
if (isMainFileAST()) {
serialization::ModuleFile &
Mod = Reader->getModuleManager().getPrimaryModule();
for (const auto *D : Reader->getModuleFileLevelDecls(Mod)) {
if (!Fn(context, D))
return false;
}
return true;
}
for (ASTUnit::top_level_iterator TL = top_level_begin(),
TLEnd = top_level_end();
TL != TLEnd; ++TL) {
if (!Fn(context, *TL))
return false;
}
return true;
}
const FileEntry *ASTUnit::getPCHFile() {
if (!Reader)
return nullptr;
serialization::ModuleFile *Mod = nullptr;
Reader->getModuleManager().visit([&Mod](serialization::ModuleFile &M) {
switch (M.Kind) {
case serialization::MK_ImplicitModule:
case serialization::MK_ExplicitModule:
case serialization::MK_PrebuiltModule:
return true; case serialization::MK_PCH:
Mod = &M;
return true; case serialization::MK_Preamble:
return false; case serialization::MK_MainFile:
return false; }
return true;
});
if (Mod)
return Mod->File;
return nullptr;
}
bool ASTUnit::isModuleFile() const {
return isMainFileAST() && getLangOpts().isCompilingModule();
}
InputKind ASTUnit::getInputKind() const {
auto &LangOpts = getLangOpts();
Language Lang;
if (LangOpts.OpenCL)
Lang = Language::OpenCL;
else if (LangOpts.CUDA)
Lang = Language::CUDA;
else if (LangOpts.RenderScript)
Lang = Language::RenderScript;
else if (LangOpts.CPlusPlus)
Lang = LangOpts.ObjC ? Language::ObjCXX : Language::CXX;
else
Lang = LangOpts.ObjC ? Language::ObjC : Language::C;
InputKind::Format Fmt = InputKind::Source;
if (LangOpts.getCompilingModule() == LangOptions::CMK_ModuleMap)
Fmt = InputKind::ModuleMap;
bool PP = false;
return InputKind(Lang, Fmt, PP);
}
#ifndef NDEBUG
ASTUnit::ConcurrencyState::ConcurrencyState() {
Mutex = new std::recursive_mutex;
}
ASTUnit::ConcurrencyState::~ConcurrencyState() {
delete static_cast<std::recursive_mutex *>(Mutex);
}
void ASTUnit::ConcurrencyState::start() {
bool acquired = static_cast<std::recursive_mutex *>(Mutex)->try_lock();
assert(acquired && "Concurrent access to ASTUnit!");
}
void ASTUnit::ConcurrencyState::finish() {
static_cast<std::recursive_mutex *>(Mutex)->unlock();
}
#else
ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex = nullptr; }
ASTUnit::ConcurrencyState::~ConcurrencyState() {}
void ASTUnit::ConcurrencyState::start() {}
void ASTUnit::ConcurrencyState::finish() {}
#endif