67#include "llvm/ADT/ArrayRef.h"
68#include "llvm/ADT/DenseMap.h"
69#include "llvm/ADT/IntrusiveRefCntPtr.h"
70#include "llvm/ADT/STLExtras.h"
71#include "llvm/ADT/ScopeExit.h"
72#include "llvm/ADT/SmallVector.h"
73#include "llvm/ADT/StringMap.h"
74#include "llvm/ADT/StringRef.h"
75#include "llvm/ADT/StringSet.h"
76#include "llvm/ADT/Twine.h"
77#include "llvm/ADT/iterator_range.h"
78#include "llvm/Bitstream/BitstreamWriter.h"
79#include "llvm/Support/Allocator.h"
80#include "llvm/Support/CrashRecoveryContext.h"
81#include "llvm/Support/DJB.h"
82#include "llvm/Support/ErrorHandling.h"
83#include "llvm/Support/ErrorOr.h"
84#include "llvm/Support/MemoryBuffer.h"
85#include "llvm/Support/SaveAndRestore.h"
86#include "llvm/Support/Timer.h"
87#include "llvm/Support/VirtualFileSystem.h"
88#include "llvm/Support/raw_ostream.h"
103using namespace clang;
105using llvm::TimeRecord;
115 explicit SimpleTimer(
bool WantTiming) : WantTiming(WantTiming) {
117 Start = TimeRecord::getCurrentTime();
122 TimeRecord Elapsed = TimeRecord::getCurrentTime();
124 llvm::errs() << Output <<
':';
125 Elapsed.print(Elapsed, llvm::errs());
126 llvm::errs() <<
'\n';
130 void setOutput(
const Twine &Output) {
132 this->Output = Output.str();
139static std::unique_ptr<T>
valueOrNull(llvm::ErrorOr<std::unique_ptr<T>> Val) {
142 return std::move(*Val);
149 Output = std::move(*Val);
155static std::unique_ptr<llvm::MemoryBuffer>
157 llvm::vfs::FileSystem *VFS,
158 StringRef FilePath,
bool isVolatile) {
164 llvm::MemoryBuffer *Buffer =
nullptr;
165 std::unique_ptr<llvm::MemoryBuffer> BufferOwner;
166 auto FileStatus = VFS->status(FilePath);
168 llvm::sys::fs::UniqueID MainFileID = FileStatus->getUniqueID();
171 for (
const auto &RF : PreprocessorOpts.RemappedFiles) {
172 std::string MPath(RF.first);
173 auto MPathStatus = VFS->status(MPath);
175 llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID();
176 if (MainFileID == MID) {
178 BufferOwner =
valueOrNull(VFS->getBufferForFile(RF.second, -1,
true, isVolatile));
187 for (
const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
188 std::string MPath(RB.first);
189 auto MPathStatus = VFS->status(MPath);
191 llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID();
192 if (MainFileID == MID) {
195 Buffer =
const_cast<llvm::MemoryBuffer *
>(RB.second);
202 if (!Buffer && !BufferOwner) {
203 BufferOwner =
valueOrNull(VFS->getBufferForFile(FilePath, -1,
true, isVolatile));
212 return llvm::MemoryBuffer::getMemBufferCopy(Buffer->getBuffer(), FilePath);
215void ASTUnit::clearFileLevelDecls() {
230ASTUnit::ASTUnit(
bool _MainFileIsAST)
232 MainFileIsAST(_MainFileIsAST), WantTiming(getenv(
"LIBCLANG_TIMING")),
233 ShouldCacheCodeCompletionResults(
false),
234 IncludeBriefCommentsInCodeCompletion(
false), UserFilesAreVolatile(
false),
235 UnsafeToFree(
false) {
236 if (getenv(
"LIBCLANG_OBJTRACKING"))
246 clearFileLevelDecls();
252 if (Invocation && OwnsRemappedFileBuffers) {
254 for (
const auto &RB : PPOpts.RemappedFileBuffers)
258 ClearCachedCompletionResults();
260 if (getenv(
"LIBCLANG_OBJTRACKING"))
265 this->PP = std::move(PP);
270 "Bad context for source file");
278 bool &IsNestedNameSpecifier) {
279 IsNestedNameSpecifier =
false;
286 uint64_t Contexts = 0;
300 if (LangOpts.CPlusPlus)
309 if (
const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND)) {
311 if (ID->getDefinition())
322 if (LangOpts.CPlusPlus11)
323 IsNestedNameSpecifier =
true;
324 }
else if (
const auto *
Record = dyn_cast<RecordDecl>(ND)) {
330 if (LangOpts.CPlusPlus)
331 IsNestedNameSpecifier =
true;
333 IsNestedNameSpecifier =
true;
348 IsNestedNameSpecifier =
true;
354void ASTUnit::CacheCodeCompletionResults() {
358 SimpleTimer Timer(WantTiming);
359 Timer.setOutput(
"Cache global code completions for " +
getMainFileName());
362 ClearCachedCompletionResults();
365 using Result = CodeCompletionResult;
366 SmallVector<Result, 8> Results;
367 CachedCompletionAllocator = std::make_shared<GlobalCodeCompletionAllocator>();
368 CodeCompletionTUInfo CCTUInfo(CachedCompletionAllocator);
369 TheSema->CodeCompletion().GatherGlobalCodeCompletions(
370 *CachedCompletionAllocator, CCTUInfo, Results);
373 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
376 for (
auto &R : Results) {
378 case Result::RK_Declaration: {
379 bool IsNestedNameSpecifier =
false;
381 CachedResult.
Completion =
R.CreateCodeCompletionString(
382 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
383 IncludeBriefCommentsInCodeCompletion);
385 R.Declaration, Ctx->getLangOpts(), IsNestedNameSpecifier);
386 CachedResult.Priority =
R.Priority;
387 CachedResult.Kind =
R.CursorKind;
388 CachedResult.Availability =
R.Availability;
395 CachedResult.Type = 0;
404 unsigned &TypeValue = CompletionTypes[CanUsageType];
405 if (TypeValue == 0) {
406 TypeValue = CompletionTypes.size();
407 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
411 CachedResult.Type = TypeValue;
414 CachedCompletionResults.push_back(CachedResult);
417 if (TheSema->Context.getLangOpts().CPlusPlus && IsNestedNameSpecifier &&
418 !
R.StartsNestedNameSpecifier) {
438 if (uint64_t RemainingContexts
439 = NNSContexts & ~CachedResult.ShowInContexts) {
443 R.StartsNestedNameSpecifier =
true;
444 CachedResult.Completion =
R.CreateCodeCompletionString(
445 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
446 IncludeBriefCommentsInCodeCompletion);
447 CachedResult.ShowInContexts = RemainingContexts;
450 CachedResult.Type = 0;
451 CachedCompletionResults.push_back(CachedResult);
457 case Result::RK_Keyword:
458 case Result::RK_Pattern:
463 case Result::RK_Macro: {
465 CachedResult.
Completion =
R.CreateCodeCompletionString(
466 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
467 IncludeBriefCommentsInCodeCompletion);
468 CachedResult.ShowInContexts
482 CachedResult.Priority =
R.Priority;
483 CachedResult.Kind =
R.CursorKind;
484 CachedResult.Availability =
R.Availability;
486 CachedResult.Type = 0;
487 CachedCompletionResults.push_back(CachedResult);
494 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
497void ASTUnit::ClearCachedCompletionResults() {
498 CachedCompletionResults.clear();
499 CachedCompletionTypes.clear();
500 CachedCompletionAllocator =
nullptr;
508 HeaderSearchOptions &HSOpts;
509 std::string &ContextHash;
510 PreprocessorOptions &PPOpts;
511 LangOptions &LangOpts;
512 CodeGenOptions &CodeGenOpts;
513 TargetOptions &TargetOpts;
517 ASTInfoCollector(HeaderSearchOptions &HSOpts, std::string &ContextHash,
518 PreprocessorOptions &PPOpts, LangOptions &LangOpts,
519 CodeGenOptions &CodeGenOpts, TargetOptions &TargetOpts,
521 : HSOpts(HSOpts), ContextHash(ContextHash), PPOpts(PPOpts),
522 LangOpts(LangOpts), CodeGenOpts(CodeGenOpts), TargetOpts(TargetOpts),
525 bool ReadLanguageOptions(
const LangOptions &NewLangOpts,
526 StringRef ModuleFilename,
bool Complain,
527 bool AllowCompatibleDifferences)
override {
528 LangOpts = NewLangOpts;
532 bool ReadCodeGenOptions(
const CodeGenOptions &NewCodeGenOpts,
533 StringRef ModuleFilename,
bool Complain,
534 bool AllowCompatibleDifferences)
override {
535 CodeGenOpts = NewCodeGenOpts;
539 bool ReadHeaderSearchOptions(
const HeaderSearchOptions &NewHSOpts,
540 StringRef ModuleFilename,
541 StringRef NewContextHash,
542 bool Complain)
override {
544 ContextHash = NewContextHash;
548 bool ReadHeaderSearchPaths(
const HeaderSearchOptions &NewHSOpts,
549 bool Complain)
override {
556 bool ReadPreprocessorOptions(
const PreprocessorOptions &NewPPOpts,
557 StringRef ModuleFilename,
bool ReadMacros,
559 std::string &SuggestedPredefines)
override {
564 bool ReadTargetOptions(
const TargetOptions &NewTargetOpts,
565 StringRef ModuleFilename,
bool Complain,
566 bool AllowCompatibleDifferences)
override {
567 TargetOpts = NewTargetOpts;
571 void ReadCounter(
const serialization::ModuleFile &M,
572 uint32_t NewCounter)
override {
573 Counter = NewCounter;
581 bool CaptureNonErrorsFromIncludes)
582 : StoredDiags(StoredDiags), StandaloneDiags(StandaloneDiags),
583 CaptureNonErrorsFromIncludes(CaptureNonErrorsFromIncludes) {
584 assert((StoredDiags || StandaloneDiags) &&
585 "No output collections were passed to StoredDiagnosticConsumer.");
590 this->LangOpts = &LangOpts;
619 StoredDiags->emplace_back(Level, Info);
620 ResultDiag = &StoredDiags->back();
623 if (StandaloneDiags) {
624 std::optional<StoredDiagnostic> StoredDiag;
626 StoredDiag.emplace(Level, Info);
627 ResultDiag = &*StoredDiag;
629 StandaloneDiags->emplace_back(*LangOpts, *ResultDiag);
639 Client(StoredDiags, StandaloneDiags,
640 CaptureDiagnostics !=
643 Diags.getClient() ==
nullptr) {
644 OwningPreviousClient = Diags.takeClient();
645 PreviousClient = Diags.getClient();
646 Diags.setClient(&Client, false);
651 if (Diags.getClient() == &Client)
652 Diags.setClient(PreviousClient, !!OwningPreviousClient.release());
661 return &WriterData->Writer;
667 return &WriterData->Writer;
671std::unique_ptr<llvm::MemoryBuffer>
674 auto Buffer = FileMgr->getBufferForFile(Filename, UserFilesAreVolatile);
676 return std::move(*Buffer);
678 *ErrorStr = Buffer.getError().message();
686 assert(Diags.get() &&
"no DiagnosticsEngine was provided");
689 &AST.StoredDiagnostics,
nullptr,
696 std::shared_ptr<DiagnosticOptions> DiagOpts,
699 const LangOptions *ProvidedLangOpts,
bool OnlyLocalDecls,
701 bool UserFilesAreVolatile) {
702 std::unique_ptr<ASTUnit> AST(
new ASTUnit(
true));
705 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
706 ASTUnitCleanup(AST.get());
708 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
709 DiagCleanup(Diags.get());
711 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
713 std::unique_ptr<LangOptions> LocalLangOpts;
715 if (ProvidedLangOpts)
716 return *ProvidedLangOpts;
717 LocalLangOpts = std::make_unique<LangOptions>();
718 return *LocalLangOpts;
721 AST->LangOpts = std::make_unique<LangOptions>(LangOpts);
722 AST->OnlyLocalDecls = OnlyLocalDecls;
723 AST->CaptureDiagnostics = CaptureDiagnostics;
724 AST->DiagOpts = DiagOpts;
725 AST->Diagnostics = Diags;
726 AST->UserFilesAreVolatile = UserFilesAreVolatile;
727 AST->HSOpts = std::make_unique<HeaderSearchOptions>(HSOpts);
728 AST->HSOpts->ModuleFormat = std::string(PCHContainerRdr.
getFormats().front());
729 AST->PPOpts = std::make_shared<PreprocessorOptions>();
730 AST->CodeGenOpts = std::make_unique<CodeGenOptions>();
731 AST->TargetOpts = std::make_shared<TargetOptions>();
736 std::string ContextHash;
737 unsigned Counter = 0;
741 ASTInfoCollector Collector(*AST->HSOpts, ContextHash, *AST->PPOpts,
742 *AST->LangOpts, *AST->CodeGenOpts,
743 *AST->TargetOpts, Counter);
745 Filename, TmpFileMgr, *AST->ModCache, PCHContainerRdr,
748 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_ast_file);
753 *AST->Diagnostics, std::move(VFS));
755 AST->FileMgr = llvm::makeIntrusiveRefCnt<FileManager>(FileSystemOpts, VFS);
757 AST->SourceMgr = llvm::makeIntrusiveRefCnt<SourceManager>(
758 AST->getDiagnostics(), AST->getFileManager(), UserFilesAreVolatile);
760 AST->HSOpts->PrebuiltModuleFiles = HSOpts.PrebuiltModuleFiles;
761 AST->HSOpts->PrebuiltModulePaths = HSOpts.PrebuiltModulePaths;
762 AST->HeaderInfo = std::make_unique<HeaderSearch>(
763 AST->getHeaderSearchOpts(), AST->getSourceManager(),
764 AST->getDiagnostics(), AST->getLangOpts(),
766 AST->HeaderInfo->initializeModuleCachePath(std::move(ContextHash));
768 AST->PP = std::make_shared<Preprocessor>(
769 *AST->PPOpts, AST->getDiagnostics(), *AST->LangOpts,
770 AST->getSourceManager(), *AST->HeaderInfo, AST->ModuleLoader,
775 AST->Ctx = llvm::makeIntrusiveRefCnt<ASTContext>(
776 *AST->LangOpts, AST->getSourceManager(), AST->PP->getIdentifierTable(),
777 AST->PP->getSelectorTable(), AST->PP->getBuiltinInfo(),
778 AST->getTranslationUnitKind());
782 if (::getenv(
"LIBCLANG_DISABLE_PCH_VALIDATION"))
784 AST->Reader = llvm::makeIntrusiveRefCnt<ASTReader>(
785 *AST->PP, *AST->ModCache, AST->Ctx.get(), PCHContainerRdr,
786 *AST->CodeGenOpts,
ArrayRef<std::shared_ptr<ModuleFileExtension>>(),
788 disableValid, AllowASTWithCompilerErrors,
791 true, HSOpts.ValidateASTInputFilesContent);
798 AST->Ctx->setExternalSource(AST->Reader);
806 AST->Target->adjust(AST->PP->getDiagnostics(), *AST->LangOpts,
810 AST->PP->Initialize(*AST->Target);
812 AST->PP->setCounterValue(Counter);
816 AST->Ctx->InitBuiltinTypes(*AST->Target);
823 AST->Ctx->getCommentCommandTraits().registerCommentOptions(
824 AST->LangOpts->CommentOpts);
833 if (
auto FE = llvm::expectedToOptional(TmpFileMgr.
getSTDIN()))
835 auto Buf = llvm::MemoryBuffer::getMemBufferCopy(
836 (*BufRef)->getBuffer(), (*BufRef)->getBufferIdentifier());
837 off_t BufSize = Buf->getBufferSize();
838 AST->ModCache->getInMemoryModuleCache().addBuiltPCM(
839 "-", std::move(Buf), BufSize, 0);
844 AST->HSOpts->ForceCheckCXX20ModulesInputFiles =
845 HSOpts.ForceCheckCXX20ModulesInputFiles;
858 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_ast_file);
865 AST->HSOpts->UserEntries = HSOpts.UserEntries;
866 AST->HSOpts->SystemHeaderPrefixes = HSOpts.SystemHeaderPrefixes;
867 AST->HSOpts->VFSOverlayFiles = HSOpts.VFSOverlayFiles;
868 AST->LangOpts->PICLevel = LangOpts.PICLevel;
869 AST->LangOpts->PIE = LangOpts.PIE;
871 AST->OriginalSourceFile = std::string(AST->Reader->getOriginalSourceFile());
873 Module *M = AST->HeaderInfo->lookupModule(AST->getLangOpts().CurrentModule);
874 if (M && AST->getLangOpts().isCompilingModule() && M->
isNamedModule())
875 AST->Ctx->setCurrentNamedModule(M);
883 AST->TheSema = std::make_unique<Sema>(*AST->PP, *AST->Ctx, *AST->Consumer);
884 AST->TheSema->Initialize();
885 AST->Reader->InitializeSema(*AST->TheSema);
889 AST->getDiagnostics().getClient()->BeginSourceFile(AST->PP->getLangOpts(),
904class MacroDefinitionTrackerPPCallbacks :
public PPCallbacks {
908 explicit MacroDefinitionTrackerPPCallbacks(
unsigned &Hash) : Hash(Hash) {}
910 void MacroDefined(
const Token &MacroNameTok,
911 const MacroDirective *MD)
override {
930 if (
const auto *ND = dyn_cast<NamedDecl>(D)) {
931 if (
const auto *EnumD = dyn_cast<EnumDecl>(D)) {
934 if (!EnumD->isScoped()) {
935 for (
const auto *EI : EnumD->enumerators()) {
936 if (EI->getIdentifier())
937 Hash = llvm::djbHash(EI->getIdentifier()->getName(), Hash);
942 if (ND->getIdentifier())
943 Hash = llvm::djbHash(ND->getIdentifier()->getName(), Hash);
945 std::string NameStr = Name.getAsString();
946 Hash = llvm::djbHash(NameStr, Hash);
951 if (
const auto *ImportD = dyn_cast<ImportDecl>(D)) {
952 if (
const Module *Mod = ImportD->getImportedModule()) {
953 std::string ModName = Mod->getFullModuleName();
954 Hash = llvm::djbHash(ModName, Hash);
962class TopLevelDeclTrackerConsumer :
public ASTConsumer {
967 TopLevelDeclTrackerConsumer(ASTUnit &_Unit,
unsigned &Hash)
968 : Unit(_Unit), Hash(Hash) {
972 void handleTopLevelDecl(Decl *D) {
986 handleFileLevelDecl(D);
989 void handleFileLevelDecl(Decl *D) {
991 if (
auto *NSD = dyn_cast<NamespaceDecl>(D)) {
992 for (
auto *I : NSD->decls())
993 handleFileLevelDecl(I);
997 bool HandleTopLevelDecl(DeclGroupRef D)
override {
998 for (
auto *TopLevelDecl : D)
999 handleTopLevelDecl(TopLevelDecl);
1004 void HandleInterestingDecl(DeclGroupRef)
override {}
1006 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D)
override {
1007 for (
auto *TopLevelDecl : D)
1008 handleTopLevelDecl(TopLevelDecl);
1011 ASTMutationListener *GetASTMutationListener()
override {
1015 ASTDeserializationListener *GetASTDeserializationListener()
override {
1024 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
1025 StringRef InFile)
override {
1027 std::make_unique<MacroDefinitionTrackerPPCallbacks>(
1029 return std::make_unique<TopLevelDeclTrackerConsumer>(
1034 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
1036 bool hasCodeCompletionSupport()
const override {
return false; }
1045 unsigned getHash()
const {
return Hash; }
1047 std::vector<Decl *> takeTopLevelDecls() {
return std::move(TopLevelDecls); }
1049 std::vector<LocalDeclID> takeTopLevelDeclIDs() {
1050 return std::move(TopLevelDeclIDs);
1053 void AfterPCHEmitted(ASTWriter &Writer)
override {
1054 TopLevelDeclIDs.reserve(TopLevelDecls.size());
1055 for (
const auto *D : TopLevelDecls) {
1057 if (D->isInvalidDecl())
1059 TopLevelDeclIDs.push_back(Writer.
getDeclID(D));
1063 void HandleTopLevelDecl(DeclGroupRef DG)
override {
1064 for (
auto *D : DG) {
1072 TopLevelDecls.push_back(D);
1076 std::unique_ptr<PPCallbacks> createPPCallbacks()
override {
1077 return std::make_unique<MacroDefinitionTrackerPPCallbacks>(Hash);
1082 std::vector<Decl *> TopLevelDecls;
1083 std::vector<LocalDeclID> TopLevelDeclIDs;
1084 llvm::SmallVector<StandaloneDiagnostic, 4> PreambleDiags;
1108 for (
auto &SD : StoredDiagnostics) {
1109 if (SD.getLocation().isValid()) {
1111 SD.setLocation(Loc);
1121bool ASTUnit::Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1122 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer,
1128 assert(VFS == &FileMgr->getVirtualFileSystem() &&
1129 "VFS passed to Parse and VFS in FileMgr are different");
1131 CCInvocation = std::make_shared<CompilerInvocation>(*Invocation);
1132 if (OverrideMainBuffer) {
1134 "No preamble was built, but OverrideMainBuffer is not null");
1135 Preamble->AddImplicitPreamble(*CCInvocation, VFS, OverrideMainBuffer.get());
1140 auto Clang = std::make_unique<CompilerInstance>(CCInvocation,
1141 std::move(PCHContainerOps));
1144 llvm::scope_exit CleanOnError([&]() {
1146 SavedMainFileBuffer =
nullptr;
1150 transferASTDataFromCompilerInstance(*Clang);
1151 FailedParseDiagnostics.swap(StoredDiagnostics);
1152 StoredDiagnostics.clear();
1153 NumStoredDiagnosticsFromDriver = 0;
1159 if (VFS && FileMgr && &FileMgr->getVirtualFileSystem() == VFS) {
1160 Clang->setVirtualFileSystem(std::move(VFS));
1161 Clang->setFileManager(FileMgr);
1163 Clang->setVirtualFileSystem(std::move(VFS));
1164 Clang->createFileManager();
1165 FileMgr = Clang->getFileManagerPtr();
1169 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1170 CICleanup(Clang.get());
1172 OriginalSourceFile =
1173 std::string(Clang->getFrontendOpts().Inputs[0].getFile());
1180 if (!Clang->createTarget())
1183 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1184 "Invocation must have exactly one source file!");
1185 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1187 "FIXME: AST inputs not yet supported here!");
1188 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1190 "IR inputs not support here!");
1194 std::make_unique<LangOptions>(Clang->getInvocation().getLangOpts());
1195 FileSystemOpts = Clang->getFileSystemOpts();
1199 SourceMgr = llvm::makeIntrusiveRefCnt<SourceManager>(
1201 if (!OverrideMainBuffer) {
1203 TopLevelDeclsInPreamble.clear();
1211 if (OverrideMainBuffer) {
1220 SavedMainFileBuffer = std::move(OverrideMainBuffer);
1223 std::unique_ptr<TopLevelDeclTrackerAction> Act(
1224 new TopLevelDeclTrackerAction(*
this));
1227 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1228 ActCleanup(Act.get());
1230 if (!Act->BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0]))
1233 if (SavedMainFileBuffer) {
1234 StoredDiagnostics.clear();
1235 StoredDiagnostics.reserve(PreambleDiagnostics.size());
1236 llvm::transform(std::move(PreambleDiagnostics),
1237 std::back_inserter(StoredDiagnostics),
1238 [&](
auto &&StandaloneDiag) {
1241 std::move(StandaloneDiag), PreambleSrcLocCache);
1244 PreambleSrcLocCache.clear();
1246 if (llvm::Error Err = Act->Execute()) {
1247 consumeError(std::move(Err));
1251 transferASTDataFromCompilerInstance(*Clang);
1253 Act->EndSourceFile();
1255 FailedParseDiagnostics.clear();
1257 CleanOnError.release();
1282std::unique_ptr<llvm::MemoryBuffer>
1283ASTUnit::getMainBufferWithPrecompiledPreamble(
1284 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1287 unsigned MaxLines) {
1290 std::unique_ptr<llvm::MemoryBuffer> MainFileBuffer =
1292 MainFilePath, UserFilesAreVolatile);
1293 if (!MainFileBuffer)
1297 PreambleInvocationIn.
getLangOpts(), *MainFileBuffer, MaxLines);
1302 if (Preamble->CanReuse(PreambleInvocationIn, *MainFileBuffer, Bounds,
1313 PreambleRebuildCountdown = 1;
1314 return MainFileBuffer;
1317 PreambleDiagnostics.clear();
1318 TopLevelDeclsInPreamble.clear();
1319 PreambleSrcLocCache.clear();
1320 PreambleRebuildCountdown = 1;
1327 if (PreambleRebuildCountdown > 1) {
1328 --PreambleRebuildCountdown;
1332 assert(!Preamble &&
"No Preamble should be stored at that point");
1340 SmallVector<StandaloneDiagnostic, 4> NewPreambleDiagsStandalone;
1341 SmallVector<StoredDiagnostic, 4> NewPreambleDiags;
1342 ASTUnitPreambleCallbacks Callbacks;
1344 std::optional<CaptureDroppedDiagnostics>
Capture;
1346 Capture.emplace(CaptureDiagnostics, *Diagnostics, &NewPreambleDiags,
1347 &NewPreambleDiagsStandalone);
1350 SimpleTimer PreambleTimer(WantTiming);
1351 PreambleTimer.setOutput(
"Precompiling preamble");
1353 const bool PreviousSkipFunctionBodies =
1359 PreambleInvocationIn, MainFileBuffer.get(), Bounds, Diagnostics, VFS,
1360 PCHContainerOps, StorePreamblesInMemory, PreambleStoragePath,
1364 PreviousSkipFunctionBodies;
1367 Preamble = std::move(*NewPreamble);
1368 PreambleRebuildCountdown = 1;
1373 PreambleRebuildCountdown = 1;
1383 llvm_unreachable(
"unexpected BuildPreambleError");
1387 assert(Preamble &&
"Preamble wasn't built");
1389 TopLevelDecls.clear();
1390 TopLevelDeclsInPreamble = Callbacks.takeTopLevelDeclIDs();
1391 PreambleTopLevelHashValue = Callbacks.getHash();
1396 StoredDiagnostics = std::move(NewPreambleDiags);
1397 PreambleDiagnostics = std::move(NewPreambleDiagsStandalone);
1402 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1403 CompletionCacheTopLevelHashValue = 0;
1404 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1407 return MainFileBuffer;
1410void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1411 assert(Preamble &&
"Should only be called when preamble was built");
1413 std::vector<Decl *> Resolved;
1414 Resolved.reserve(TopLevelDeclsInPreamble.size());
1416 serialization::ModuleFile &MF = Reader->getModuleManager().getPrimaryModule();
1417 for (
const auto TopLevelDecl : TopLevelDeclsInPreamble) {
1420 if (Decl *D = Reader->GetLocalDecl(MF, TopLevelDecl))
1421 Resolved.push_back(D);
1423 TopLevelDeclsInPreamble.clear();
1424 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1451 if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1456 return Input.
getBuffer().getBufferIdentifier();
1461 SourceMgr->getFileEntryRefForID(SourceMgr->getMainFileID()))
1462 return FE->getName();
1473 Mod = Reader->getModuleManager().getPrimaryModule();
1477std::unique_ptr<ASTUnit>
1479 std::shared_ptr<DiagnosticOptions> DiagOpts,
1482 bool UserFilesAreVolatile) {
1483 std::unique_ptr<ASTUnit> AST(
new ASTUnit(
false));
1484 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1487 AST->DiagOpts = std::move(DiagOpts);
1488 AST->Diagnostics = std::move(Diags);
1489 AST->FileSystemOpts = CI->getFileSystemOpts();
1490 AST->Invocation = std::move(CI);
1492 llvm::makeIntrusiveRefCnt<FileManager>(AST->FileSystemOpts, VFS);
1493 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1494 AST->SourceMgr = llvm::makeIntrusiveRefCnt<SourceManager>(
1495 AST->getDiagnostics(), *AST->FileMgr, UserFilesAreVolatile);
1502 std::shared_ptr<CompilerInvocation> CI,
1503 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1504 std::shared_ptr<DiagnosticOptions> DiagOpts,
1506 ASTUnit *Unit,
bool Persistent, StringRef ResourceFilesPath,
1508 unsigned PrecompilePreambleAfterNParses,
bool CacheCodeCompletionResults,
1509 bool UserFilesAreVolatile, std::unique_ptr<ASTUnit> *ErrAST) {
1510 assert(CI &&
"A CompilerInvocation is required");
1512 std::unique_ptr<ASTUnit> OwnAST;
1513 ASTUnit *AST = Unit;
1517 create(CI, DiagOpts, Diags, CaptureDiagnostics, UserFilesAreVolatile);
1523 if (!ResourceFilesPath.empty()) {
1525 CI->getHeaderSearchOpts().ResourceDir = std::string(ResourceFilesPath);
1527 AST->OnlyLocalDecls = OnlyLocalDecls;
1528 AST->CaptureDiagnostics = CaptureDiagnostics;
1529 if (PrecompilePreambleAfterNParses > 0)
1530 AST->PreambleRebuildCountdown = PrecompilePreambleAfterNParses;
1532 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1533 AST->IncludeBriefCommentsInCodeCompletion =
false;
1536 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1537 ASTUnitCleanup(OwnAST.get());
1539 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
1540 DiagCleanup(Diags.get());
1543 CI->getPreprocessorOpts().RetainRemappedFileBuffers =
true;
1544 CI->getFrontendOpts().DisableFree =
false;
1549 auto Clang = std::make_unique<CompilerInstance>(std::move(CI),
1550 std::move(PCHContainerOps));
1553 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1554 CICleanup(Clang.get());
1556 AST->OriginalSourceFile =
1557 std::string(Clang->getFrontendOpts().Inputs[0].getFile());
1564 if (!Clang->createTarget())
1567 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1568 "Invocation must have exactly one source file!");
1569 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1571 "FIXME: AST inputs not yet supported here!");
1572 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1574 "IR inputs not support here!");
1577 AST->TheSema.reset();
1580 AST->Reader =
nullptr;
1591 std::unique_ptr<TopLevelDeclTrackerAction> TrackerAct;
1593 TrackerAct.reset(
new TopLevelDeclTrackerAction(*AST));
1594 Act = TrackerAct.get();
1598 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1599 ActCleanup(TrackerAct.get());
1601 if (!Act->
BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0])) {
1602 AST->transferASTDataFromCompilerInstance(*Clang);
1603 if (OwnAST && ErrAST)
1604 ErrAST->swap(OwnAST);
1609 if (Persistent && !TrackerAct) {
1610 Clang->getPreprocessor().addPPCallbacks(
1611 std::make_unique<MacroDefinitionTrackerPPCallbacks>(
1613 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
1614 if (Clang->hasASTConsumer())
1615 Consumers.push_back(Clang->takeASTConsumer());
1616 Consumers.push_back(std::make_unique<TopLevelDeclTrackerConsumer>(
1618 Clang->setASTConsumer(
1619 std::make_unique<MultiplexConsumer>(std::move(Consumers)));
1621 if (llvm::Error Err = Act->
Execute()) {
1622 consumeError(std::move(Err));
1623 AST->transferASTDataFromCompilerInstance(*Clang);
1624 if (OwnAST && ErrAST)
1625 ErrAST->swap(OwnAST);
1631 AST->transferASTDataFromCompilerInstance(*Clang);
1636 return OwnAST.release();
1641bool ASTUnit::LoadFromCompilerInvocation(
1642 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1643 unsigned PrecompilePreambleAfterNParses,
1648 assert(VFS &&
"VFS is null");
1651 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers =
true;
1652 Invocation->getFrontendOpts().DisableFree =
false;
1657 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
1658 if (PrecompilePreambleAfterNParses > 0) {
1659 PreambleRebuildCountdown = PrecompilePreambleAfterNParses;
1660 OverrideMainBuffer =
1661 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS);
1667 SimpleTimer ParsingTimer(WantTiming);
1671 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1672 MemBufferCleanup(OverrideMainBuffer.get());
1674 return Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS);
1677std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation(
1678 std::shared_ptr<CompilerInvocation> CI,
1679 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1680 std::shared_ptr<DiagnosticOptions> DiagOpts,
1685 bool CacheCodeCompletionResults,
bool IncludeBriefCommentsInCodeCompletion,
1686 bool UserFilesAreVolatile) {
1688 std::unique_ptr<ASTUnit> AST(
new ASTUnit(
false));
1689 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1690 AST->DiagOpts = DiagOpts;
1691 AST->Diagnostics = Diags;
1692 AST->OnlyLocalDecls = OnlyLocalDecls;
1693 AST->CaptureDiagnostics = CaptureDiagnostics;
1694 AST->TUKind = TUKind;
1695 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1696 AST->IncludeBriefCommentsInCodeCompletion
1697 = IncludeBriefCommentsInCodeCompletion;
1698 AST->Invocation = std::move(CI);
1699 AST->FileSystemOpts = FileMgr->getFileSystemOpts();
1700 AST->FileMgr = FileMgr;
1701 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1704 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1705 ASTUnitCleanup(AST.get());
1707 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
1708 DiagCleanup(Diags.get());
1710 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
1711 PrecompilePreambleAfterNParses,
1712 AST->FileMgr->getVirtualFileSystemPtr()))
1724 assert(FileMgr &&
"FileMgr is null on Reparse call");
1725 VFS = FileMgr->getVirtualFileSystemPtr();
1728 clearFileLevelDecls();
1730 SimpleTimer ParsingTimer(WantTiming);
1735 for (
const auto &RB : PPOpts.RemappedFileBuffers)
1740 Invocation->getPreprocessorOpts().addRemappedFile(
RemappedFile.first,
1746 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
1747 if (Preamble || PreambleRebuildCountdown > 0)
1748 OverrideMainBuffer =
1749 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS);
1756 if (OverrideMainBuffer)
1761 Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS);
1765 if (!
Result && ShouldCacheCodeCompletionResults &&
1766 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
1767 CacheCodeCompletionResults();
1777 SavedMainFileBuffer.reset();
1785 TopLevelDecls.clear();
1786 clearFileLevelDecls();
1799 uint64_t NormalContexts;
1832 unsigned NumResults)
override;
1834 void ProcessOverloadCandidates(
Sema &S,
unsigned CurrentArg,
1836 unsigned NumCandidates,
1838 bool Braced)
override {
1839 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates,
1840 OpenParLoc, Braced);
1843 CodeCompletionAllocator &getAllocator()
override {
1844 return Next.getAllocator();
1847 CodeCompletionTUInfo &getCodeCompletionTUInfo()
override {
1848 return Next.getCodeCompletionTUInfo();
1858 unsigned NumResults,
1860 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
1861 bool OnlyTagNames =
false;
1862 switch (Context.getKind()) {
1887 OnlyTagNames =
true;
1913 for (
unsigned I = 0; I != NumResults; ++I) {
1914 if (Results[I].Kind != Result::RK_Declaration)
1920 bool Hiding =
false;
1929 Hiding = (IDNS & HiddenIDNS);
1937 HiddenNames.insert(Identifier->getName());
1943void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(
Sema &S,
1946 unsigned NumResults) {
1948 bool AddedResult =
false;
1951 ? NormalContexts : (1LL << Context.getKind());
1953 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
1962 if ((
C->ShowInContexts & InContexts) == 0)
1969 AllResults.insert(AllResults.end(), Results, Results + NumResults);
1976 HiddenNames.count(
C->Completion->getTypedText()))
1980 unsigned Priority =
C->Priority;
1982 if (!Context.getPreferredType().isNull()) {
1986 Context.getPreferredType()->isAnyPointerType());
1987 }
else if (
C->Type) {
1990 Context.getPreferredType().getUnqualifiedType());
1992 if (ExpectedSTC ==
C->TypeClass) {
1994 llvm::StringMap<unsigned> &CachedCompletionTypes
1996 llvm::StringMap<unsigned>::iterator Pos
1998 if (Pos != CachedCompletionTypes.end() && Pos->second ==
C->Type)
2013 Builder.AddTypedTextChunk(
C->Completion->getTypedText());
2015 Completion = Builder.TakeString();
2018 AllResults.push_back(
Result(Completion, Priority,
C->Kind,
2025 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2029 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2036 bool IncludeCodePatterns,
bool IncludeBriefComments,
2038 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
2044 std::unique_ptr<SyntaxOnlyAction> Act) {
2048 SimpleTimer CompletionTimer(WantTiming);
2049 CompletionTimer.setOutput(
"Code completion @ " +
File +
":" +
2052 auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation);
2059 CachedCompletionResults.empty();
2061 CodeCompleteOpts.
IncludeGlobals = CachedCompletionResults.empty();
2063 CodeCompleteOpts.
LoadExternal = Consumer.loadExternal();
2066 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2073 LangOpts = CCInvocation->getLangOpts();
2076 LangOpts.SpellChecking =
false;
2077 CCInvocation->getDiagnosticOpts().IgnoreWarnings =
true;
2079 auto Clang = std::make_unique<CompilerInstance>(std::move(CCInvocation),
2083 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2084 CICleanup(Clang.get());
2086 auto &Inv = Clang->getInvocation();
2087 OriginalSourceFile =
2088 std::string(Clang->getFrontendOpts().Inputs[0].getFile());
2091 Clang->setDiagnostics(
Diag);
2093 Clang->getDiagnostics(),
2094 &StoredDiagnostics,
nullptr);
2096 FileMgr->getVirtualFileSystem());
2099 if (!Clang->createTarget()) {
2103 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
2104 "Invocation must have exactly one source file!");
2105 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
2107 "FIXME: AST inputs not yet supported here!");
2108 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
2110 "IR inputs not support here!");
2113 Clang->setVirtualFileSystem(FileMgr->getVirtualFileSystemPtr());
2114 Clang->setFileManager(FileMgr);
2115 Clang->setSourceManager(SourceMgr);
2127 AugmentedCodeCompleteConsumer *AugmentedConsumer
2128 =
new AugmentedCodeCompleteConsumer(*
this, Consumer, CodeCompleteOpts);
2129 Clang->setCodeCompletionConsumer(AugmentedConsumer);
2132 [&FileMgr](StringRef Filename) -> std::optional<llvm::sys::fs::UniqueID> {
2133 if (
auto Status = FileMgr->getVirtualFileSystem().status(Filename))
2134 return Status->getUniqueID();
2135 return std::nullopt;
2138 auto hasSameUniqueID = [getUniqueID](StringRef LHS, StringRef RHS) {
2141 if (
auto LHSID = getUniqueID(LHS))
2142 if (
auto RHSID = getUniqueID(RHS))
2143 return *LHSID == *RHSID;
2151 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
2152 if (Preamble &&
Line > 1 && hasSameUniqueID(
File, OriginalSourceFile)) {
2153 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(
2154 PCHContainerOps, Inv, FileMgr->getVirtualFileSystemPtr(),
false,
2160 if (OverrideMainBuffer) {
2162 "No preamble was built, but OverrideMainBuffer is not null");
2165 FileMgr->getVirtualFileSystemPtr();
2166 Preamble->AddImplicitPreamble(Clang->getInvocation(), VFS,
2167 OverrideMainBuffer.get());
2172 OwnedBuffers.push_back(OverrideMainBuffer.release());
2179 if (!Clang->getLangOpts().Modules)
2185 if (Act->BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0])) {
2186 if (llvm::Error Err = Act->Execute()) {
2187 consumeError(std::move(Err));
2189 Act->EndSourceFile();
2194 if (HadModuleLoaderFatalFailure)
2200 if (llvm::Error Err = llvm::writeToOutput(
2201 File, [
this](llvm::raw_ostream &Out) {
2202 return serialize(Out) ? llvm::make_error<llvm::StringError>(
2203 "ASTUnit serialization failed",
2204 llvm::inconvertibleErrorCode())
2205 : llvm::Error::success();
2207 consumeError(std::move(Err));
2214 Sema &S, raw_ostream &OS) {
2215 Writer.
WriteAST(&S, std::string(),
nullptr,
"");
2218 if (!Buffer.empty())
2219 OS.write(Buffer.data(), Buffer.size());
2229 llvm::BitstreamWriter Stream(Buffer);
2231 ASTWriter Writer(Stream, Buffer, *ModCache, *CodeGenOpts, {});
2244 if (Loc.
isInvalid() || !
SM.isLocalSourceLocation(Loc))
2252 assert(
SM.isLocalSourceLocation(FileLoc));
2253 auto [FID, Offset] =
SM.getDecomposedLoc(FileLoc);
2254 if (FID.isInvalid())
2257 std::unique_ptr<LocDeclsTy> &Decls = FileDecls[FID];
2259 Decls = std::make_unique<LocDeclsTy>();
2261 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2263 if (Decls->empty() || Decls->back().first <= Offset) {
2264 Decls->push_back(LocDecl);
2268 LocDeclsTy::iterator I =
2269 llvm::upper_bound(*Decls, LocDecl, llvm::less_first());
2271 Decls->insert(I, LocDecl);
2276 if (
File.isInvalid())
2279 if (SourceMgr->isLoadedFileID(
File)) {
2280 assert(Ctx->getExternalSource() &&
"No external source!");
2281 return Ctx->getExternalSource()->FindFileRegionDecls(
File, Offset, Length,
2285 FileDeclsTy::iterator I = FileDecls.find(
File);
2286 if (I == FileDecls.end())
2289 LocDeclsTy &LocDecls = *I->second;
2290 if (LocDecls.empty())
2293 LocDeclsTy::iterator BeginIt =
2294 llvm::partition_point(LocDecls, [=](std::pair<unsigned, Decl *> LD) {
2295 return LD.first < Offset;
2297 if (BeginIt != LocDecls.begin())
2303 while (BeginIt != LocDecls.begin() &&
2304 BeginIt->second->isTopLevelDeclInObjCContainer())
2307 LocDeclsTy::iterator EndIt = llvm::upper_bound(
2308 LocDecls, std::make_pair(Offset + Length, (
Decl *)
nullptr),
2309 llvm::less_first());
2310 if (EndIt != LocDecls.end())
2313 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2314 Decls.push_back(DIt->second);
2318 unsigned Line,
unsigned Col)
const {
2321 return SM.getMacroArgExpandedLocation(Loc);
2325 unsigned Offset)
const {
2337 PreambleID = SourceMgr->getPreambleFileID();
2343 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble->getBounds().Size) {
2345 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2358 PreambleID = SourceMgr->getPreambleFileID();
2364 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2365 Offs < Preamble->getBounds().Size) {
2366 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2376 FID = SourceMgr->getPreambleFileID();
2381 return SourceMgr->isInFileID(Loc, FID);
2387 FID = SourceMgr->getMainFileID();
2392 return SourceMgr->isInFileID(Loc, FID);
2398 FID = SourceMgr->getPreambleFileID();
2403 return SourceMgr->getLocForEndOfFile(FID);
2409 FID = SourceMgr->getMainFileID();
2414 return SourceMgr->getLocForStartOfFile(FID);
2417llvm::iterator_range<PreprocessingRecord::iterator>
2421 Mod = Reader->getModuleManager().getPrimaryModule();
2422 return Reader->getModulePreprocessedEntities(Mod);
2426 return llvm::make_range(PPRec->local_begin(), PPRec->local_end());
2435 Mod = Reader->getModuleManager().getPrimaryModule();
2436 for (
const auto *D : Reader->getModuleFileLevelDecls(Mod)) {
2437 if (!Fn(context, D))
2446 TL != TLEnd; ++TL) {
2447 if (!Fn(context, *TL))
2456 return std::nullopt;
2479 return std::nullopt;
2490 if (LangOpts.OpenCL)
2492 else if (LangOpts.CUDA)
2494 else if (LangOpts.CPlusPlus)
2510ASTUnit::ConcurrencyState::ConcurrencyState() {
2511 Mutex =
new std::recursive_mutex;
2514ASTUnit::ConcurrencyState::~ConcurrencyState() {
2515 delete static_cast<std::recursive_mutex *
>(Mutex);
2518void ASTUnit::ConcurrencyState::start() {
2519 bool acquired =
static_cast<std::recursive_mutex *
>(Mutex)->try_lock();
2520 assert(acquired &&
"Concurrent access to ASTUnit!");
2523void ASTUnit::ConcurrencyState::finish() {
2524 static_cast<std::recursive_mutex *
>(Mutex)->unlock();
2529ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex =
nullptr; }
2530ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2531void ASTUnit::ConcurrencyState::start() {}
2532void ASTUnit::ConcurrencyState::finish() {}
Defines the clang::ASTContext interface.
static void checkAndSanitizeDiags(SmallVectorImpl< StoredDiagnostic > &StoredDiagnostics, SourceManager &SM)
static void CalculateHiddenNames(const CodeCompletionContext &Context, CodeCompletionResult *Results, unsigned NumResults, ASTContext &Ctx, llvm::StringSet< llvm::BumpPtrAllocator > &HiddenNames)
Helper function that computes which global names are hidden by the local code-completion results.
static uint64_t getDeclShowContexts(const NamedDecl *ND, const LangOptions &LangOpts, bool &IsNestedNameSpecifier)
Determine the set of code-completion contexts in which this declaration should be shown.
static void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash)
Add the given declaration to the hash of all top-level entities.
static bool moveOnNoError(llvm::ErrorOr< T > Val, T &Output)
static std::unique_ptr< T > valueOrNull(llvm::ErrorOr< std::unique_ptr< T > > Val)
static bool serializeUnit(ASTWriter &Writer, SmallVectorImpl< char > &Buffer, Sema &S, raw_ostream &OS)
static std::unique_ptr< llvm::MemoryBuffer > getBufferForFileHandlingRemapping(const CompilerInvocation &Invocation, llvm::vfs::FileSystem *VFS, StringRef FilePath, bool isVolatile)
Get a source buffer for MainFilePath, handling all file-to-file and file-to-buffer remappings inside ...
const unsigned DefaultPreambleRebuildInterval
After failing to build a precompiled preamble (due to errors in the source that occurs in the preambl...
static void checkAndRemoveNonDriverDiags(SmallVectorImpl< StoredDiagnostic > &StoredDiags)
static bool isInMainFile(const clang::Diagnostic &D)
static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag)
static std::atomic< unsigned > ActiveASTUnitObjects
Tracks the number of ASTUnit objects that are currently active.
static void AddDefinedMacroToHash(const Token &MacroNameTok, unsigned &Hash)
Add the given macro to the hash of all top-level entities.
Defines the Diagnostic-related interfaces.
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
Defines the clang::FileManager interface and associated types.
Defines the clang::FrontendAction interface and various convenience abstract classes (clang::ASTFront...
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
Result
Implement __builtin_bit_cast and related operations.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Record Record
Defines the clang::Module class, which describes a module in the source code.
Defines the PPCallbacks interface.
Defines the clang::Preprocessor interface.
This file declares facilities that support code completion.
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
Defines the clang::TargetOptions class.
Allows QualTypes to be sorted and hence used in maps and sets.
C Language Family Type Representation.
ASTConsumer - This is an abstract interface that should be implemented by clients that read ASTs.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
const LangOptions & getLangOpts() const
Abstract base class to use for AST consumer-based frontend actions.
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
Abstract interface for callback invocations by the ASTReader.
@ ARR_None
The client can't handle any AST loading failures.
static bool readASTFileControlBlock(StringRef Filename, FileManager &FileMgr, const ModuleCache &ModCache, const PCHContainerReader &PCHContainerRdr, bool FindModuleFileExtensions, ASTReaderListener &Listener, bool ValidateDiagnosticOptions, unsigned ClientLoadCapabilities=ARR_ConfigurationMismatch|ARR_OutOfDate)
Read the control block for the named AST file.
@ Success
The control block was read successfully.
@ ConfigurationMismatch
The AST file was written with a different language/target configuration.
@ OutOfDate
The AST file is out-of-date relative to its input files, and needs to be regenerated.
@ Failure
The AST file itself appears corrupted.
@ VersionMismatch
The AST file was written by a different version of Clang.
@ HadErrors
The AST file has errors.
@ Missing
The AST file was missing.
Utility class for loading a ASTContext from an AST file.
unsigned & getCurrentTopLevelHashValue()
Retrieve a reference to the current top-level name hash value.
void enableSourceFileDiagnostics()
Enable source-range based diagnostic messages.
void addFileLevelDecl(Decl *D)
Add a new local file-level declaration.
const FileManager & getFileManager() const
void CodeComplete(StringRef File, unsigned Line, unsigned Column, ArrayRef< RemappedFile > RemappedFiles, bool IncludeMacros, bool IncludeCodePatterns, bool IncludeBriefComments, CodeCompleteConsumer &Consumer, std::shared_ptr< PCHContainerOperations > PCHContainerOps, llvm::IntrusiveRefCntPtr< DiagnosticsEngine > Diag, LangOptions &LangOpts, llvm::IntrusiveRefCntPtr< SourceManager > SourceMgr, llvm::IntrusiveRefCntPtr< FileManager > FileMgr, SmallVectorImpl< StoredDiagnostic > &StoredDiagnostics, SmallVectorImpl< const llvm::MemoryBuffer * > &OwnedBuffers, std::unique_ptr< SyntaxOnlyAction > Act)
Perform code completion at the given file, line, and column within this translation unit.
cached_completion_iterator cached_completion_end()
static std::unique_ptr< ASTUnit > LoadFromASTFile(StringRef Filename, const PCHContainerReader &PCHContainerRdr, WhatToLoad ToLoad, IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS, std::shared_ptr< DiagnosticOptions > DiagOpts, IntrusiveRefCntPtr< DiagnosticsEngine > Diags, const FileSystemOptions &FileSystemOpts, const HeaderSearchOptions &HSOpts, const LangOptions *LangOpts=nullptr, bool OnlyLocalDecls=false, CaptureDiagsKind CaptureDiagnostics=CaptureDiagsKind::None, bool AllowASTWithCompilerErrors=false, bool UserFilesAreVolatile=false)
Create a ASTUnit from an AST file.
bool serialize(raw_ostream &OS)
Serialize this translation unit with the given output stream.
ASTDeserializationListener * getDeserializationListener()
bool Reparse(std::shared_ptr< PCHContainerOperations > PCHContainerOps, ArrayRef< RemappedFile > RemappedFiles={}, IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS=nullptr)
Reparse the source files using the same command-line options that were originally used to produce thi...
std::unique_ptr< llvm::MemoryBuffer > getBufferForFile(StringRef Filename, std::string *ErrorStr=nullptr)
llvm::StringMap< unsigned > & getCachedCompletionTypes()
Retrieve the mapping from formatted type names to unique type identifiers.
const DiagnosticsEngine & getDiagnostics() const
SourceLocation getLocation(const FileEntry *File, unsigned Line, unsigned Col) const
Get the source location for the given file:line:col triplet.
void ResetForParse()
Free data that will be re-generated on the next parse.
llvm::IntrusiveRefCntPtr< SourceManager > getSourceManagerPtr()
InputKind getInputKind() const
Determine the input kind this AST unit represents.
std::optional< StringRef > getPCHFile()
Get the PCH file if one was included.
StringRef getMainFileName() const
SourceLocation mapLocationToPreamble(SourceLocation Loc) const
If Loc is a local location of the main file but inside the preamble chunk, returns the corresponding ...
cached_completion_iterator cached_completion_begin()
const LangOptions & getLangOpts() const
bool isMainFileAST() const
std::vector< Decl * >::iterator top_level_iterator
const SourceManager & getSourceManager() const
SourceLocation getEndOfPreambleFileID() const
std::vector< CachedCodeCompletionResult >::iterator cached_completion_iterator
llvm::IntrusiveRefCntPtr< DiagnosticsEngine > getDiagnosticsPtr()
static ASTUnit * LoadFromCompilerInvocationAction(std::shared_ptr< CompilerInvocation > CI, std::shared_ptr< PCHContainerOperations > PCHContainerOps, std::shared_ptr< DiagnosticOptions > DiagOpts, IntrusiveRefCntPtr< DiagnosticsEngine > Diags, FrontendAction *Action=nullptr, ASTUnit *Unit=nullptr, bool Persistent=true, StringRef ResourceFilesPath=StringRef(), bool OnlyLocalDecls=false, CaptureDiagsKind CaptureDiagnostics=CaptureDiagsKind::None, unsigned PrecompilePreambleAfterNParses=0, bool CacheCodeCompletionResults=false, bool UserFilesAreVolatile=false, std::unique_ptr< ASTUnit > *ErrAST=nullptr)
Create an ASTUnit from a source file, via a CompilerInvocation object, by invoking the optionally pro...
@ LoadASTOnly
Load the AST, but do not restore Sema state.
@ LoadEverything
Load everything, including Sema.
top_level_iterator top_level_end()
SourceLocation getStartOfMainFileID() const
IntrusiveRefCntPtr< ASTReader > getASTReader() const
IntrusiveRefCntPtr< FileManager > getFileManagerPtr()
bool(*)(void *context, const Decl *D) DeclVisitorFn
Type for a function iterating over a number of declarations.
bool visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn)
Iterate over local declarations (locally parsed if this is a parsed source file or the loaded declara...
IntrusiveRefCntPtr< llvm::vfs::FileSystem > getVirtualFileSystemPtr()
llvm::iterator_range< PreprocessingRecord::iterator > getLocalPreprocessingEntities() const
Returns an iterator range for the local preprocessing entities of the local Preprocessor,...
top_level_iterator top_level_begin()
ASTMutationListener * getASTMutationListener()
TranslationUnitKind getTranslationUnitKind() const
Determine what kind of translation unit this AST represents.
void setPreprocessor(std::shared_ptr< Preprocessor > pp)
StringRef getASTFileName() const
If this ASTUnit came from an AST file, returns the filename for it.
bool Save(StringRef File)
Save this translation unit to a file with the given name.
static std::unique_ptr< ASTUnit > create(std::shared_ptr< CompilerInvocation > CI, std::shared_ptr< DiagnosticOptions > DiagOpts, IntrusiveRefCntPtr< DiagnosticsEngine > Diags, CaptureDiagsKind CaptureDiagnostics, bool UserFilesAreVolatile)
Create a ASTUnit. Gets ownership of the passed CompilerInvocation.
void addTopLevelDecl(Decl *D)
Add a new top-level declaration.
bool isInMainFileID(SourceLocation Loc) const
bool isModuleFile() const
Returns true if the ASTUnit was constructed from a serialized module file.
void findFileRegionDecls(FileID File, unsigned Offset, unsigned Length, SmallVectorImpl< Decl * > &Decls)
Get the decls that are contained in a file in the Offset/Length range.
const ASTContext & getASTContext() const
bool isInPreambleFileID(SourceLocation Loc) const
SourceLocation mapLocationFromPreamble(SourceLocation Loc) const
If Loc is a loaded location from the preamble, returns the corresponding local location of the main f...
std::pair< std::string, llvm::MemoryBuffer * > RemappedFile
A mapping from a file name to the memory buffer that stores the remapped contents of that file.
Writes an AST file containing the contents of a translation unit.
LocalDeclID getDeclID(const Decl *D)
Determine the local declaration ID of an already-emitted declaration.
ASTFileSignature WriteAST(llvm::PointerUnion< Sema *, Preprocessor * > Subject, StringRef OutputFile, Module *WritingModule, StringRef isysroot)
Write a precompiled header or a module with the AST produced by the Sema object, or a dependency scan...
RAII object that optionally captures and filters diagnostics, if there is no diagnostic client to cap...
~CaptureDroppedDiagnostics()
CaptureDroppedDiagnostics(CaptureDiagsKind CaptureDiagnostics, DiagnosticsEngine &Diags, SmallVectorImpl< StoredDiagnostic > *StoredDiags, SmallVectorImpl< StandaloneDiagnostic > *StandaloneDiags)
Abstract interface for a consumer of code-completion information.
Options controlling the behavior of code completion.
unsigned IncludeCodePatterns
Show code patterns in code completion results.
unsigned IncludeFixIts
Include results after corrections (small fix-its), e.g.
unsigned LoadExternal
Hint whether to load data from the external AST to provide full results.
unsigned IncludeMacros
Show macros in code completion results.
unsigned IncludeBriefComments
Show brief documentation comments in code completion results.
unsigned IncludeGlobals
Show top-level decls in code completion results.
A builder class used to construct new code-completion strings.
The context in which code completion occurred, so that the code-completion consumer can process the r...
@ CCC_TypeQualifiers
Code completion within a type-qualifier list.
@ CCC_ObjCMessageReceiver
Code completion occurred where an Objective-C message receiver is expected.
@ CCC_PreprocessorExpression
Code completion occurred within a preprocessor expression.
@ CCC_ObjCCategoryName
Code completion where an Objective-C category name is expected.
@ CCC_ObjCIvarList
Code completion occurred within the instance variable list of an Objective-C interface,...
@ CCC_Statement
Code completion occurred where a statement (or declaration) is expected in a function,...
@ CCC_Type
Code completion occurred where a type name is expected.
@ CCC_ArrowMemberAccess
Code completion occurred on the right-hand side of a member access expression using the arrow operato...
@ CCC_ClassStructUnion
Code completion occurred within a class, struct, or union.
@ CCC_ObjCInterface
Code completion occurred within an Objective-C interface, protocol, or category interface.
@ CCC_ObjCPropertyAccess
Code completion occurred on the right-hand side of an Objective-C property access expression.
@ CCC_Expression
Code completion occurred where an expression is expected.
@ CCC_SelectorName
Code completion for a selector, as in an @selector expression.
@ CCC_TopLevelOrExpression
Code completion at a top level, i.e.
@ CCC_EnumTag
Code completion occurred after the "enum" keyword, to indicate an enumeration name.
@ CCC_UnionTag
Code completion occurred after the "union" keyword, to indicate a union name.
@ CCC_ParenthesizedExpression
Code completion in a parenthesized expression, which means that we may also have types here in C and ...
@ CCC_TopLevel
Code completion occurred within a "top-level" completion context, e.g., at namespace or global scope.
@ CCC_ClassOrStructTag
Code completion occurred after the "struct" or "class" keyword, to indicate a struct or class name.
@ CCC_ObjCClassMessage
Code completion where an Objective-C class message is expected.
@ CCC_ObjCImplementation
Code completion occurred within an Objective-C implementation or category implementation.
@ CCC_IncludedFile
Code completion inside the filename part of a include directive.
@ CCC_ObjCInstanceMessage
Code completion where an Objective-C instance message is expected.
@ CCC_SymbolOrNewName
Code completion occurred where both a new name and an existing symbol is permissible.
@ CCC_Recovery
An unknown context, in which we are recovering from a parsing error and don't know which completions ...
@ CCC_ObjCProtocolName
Code completion occurred where a protocol name is expected.
@ CCC_OtherWithMacros
An unspecified code-completion context where we should also add macro completions.
@ CCC_NewName
Code completion occurred where a new name is expected.
@ CCC_MacroNameUse
Code completion occurred where a macro name is expected (without any arguments, in the case of a func...
@ CCC_Symbol
Code completion occurred where an existing name(such as type, functionor variable) is expected.
@ CCC_Attribute
Code completion of an attribute name.
@ CCC_Other
An unspecified code-completion context.
@ CCC_DotMemberAccess
Code completion occurred on the right-hand side of a member access expression using the dot operator.
@ CCC_MacroName
Code completion occurred where an macro is being defined.
@ CCC_Namespace
Code completion occurred where a namespace or namespace alias is expected.
@ CCC_PreprocessorDirective
Code completion occurred where a preprocessor directive is expected.
@ CCC_NaturalLanguage
Code completion occurred in a context where natural language is expected, e.g., a comment or string l...
@ CCC_ObjCInterfaceName
Code completion where the name of an Objective-C class is expected.
@ CCC_ObjCClassForwardDecl
Captures a result of code completion.
const NamedDecl * Declaration
When Kind == RK_Declaration or RK_Pattern, the declaration we are referring to.
A "string" used to describe how code completion can be performed for an entity.
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
CompilerInstance - Helper class for managing a single instance of the Clang compiler.
std::shared_ptr< Preprocessor > getPreprocessorPtr()
std::unique_ptr< Sema > takeSema()
IntrusiveRefCntPtr< ASTContext > getASTContextPtr() const
IntrusiveRefCntPtr< ASTReader > getASTReader() const
std::shared_ptr< ModuleCache > getModuleCachePtr() const
bool hasASTContext() const
Preprocessor & getPreprocessor() const
Return the current preprocessor.
IntrusiveRefCntPtr< TargetInfo > getTargetPtr() const
std::shared_ptr< CompilerInvocation > getInvocationPtr()
bool hadModuleLoaderFatalFailure() const
void setSourceManager(llvm::IntrusiveRefCntPtr< SourceManager > Value)
setSourceManager - Replace the current source manager.
CompilerInvocation & getInvocation()
std::unique_ptr< ASTConsumer > takeASTConsumer()
takeASTConsumer - Remove the current AST consumer and give ownership to the caller.
void setFileManager(IntrusiveRefCntPtr< FileManager > Value)
Replace the current file manager.
bool hasPreprocessor() const
Helper class for holding the data necessary to invoke the compiler.
PreprocessorOptions & getPreprocessorOpts()
LangOptions & getLangOpts()
Mutable getters.
FrontendOptions & getFrontendOpts()
DiagnosticOptions & getDiagnosticOpts()
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
bool isFileContext() const
bool isTranslationUnit() const
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
Decl - This represents one declaration (or definition), e.g.
bool isFromASTFile() const
Determine whether this declaration came from an AST file (such as a precompiled header or module) rat...
unsigned getIdentifierNamespace() const
SourceLocation getLocation() const
@ IDNS_NonMemberOperator
This declaration is a C++ operator declared in a non-class context.
@ IDNS_Ordinary
Ordinary names.
@ IDNS_Type
Types, declared with 'struct foo', typedefs, etc.
@ IDNS_Member
Members, declared with object declarations within tag definitions.
@ IDNS_Namespace
Namespaces, declared with 'namespace foo {}'.
@ IDNS_Tag
Tags, declared with 'struct foo;' and referenced with 'struct foo'.
DeclContext * getDeclContext()
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
The name of a declaration.
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
std::string getAsString() const
Retrieve the human-readable string for this name.
virtual void EndSourceFile()
Callback to inform the diagnostic client that processing of a source file has ended.
virtual void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, const Diagnostic &Info)
Handle this diagnostic, reporting it to the user or capturing it to a log as needed.
virtual void BeginSourceFile(const LangOptions &LangOpts, const Preprocessor *PP=nullptr)
Callback to inform the diagnostic client that processing of a source file is beginning.
A little helper class (which is basically a smart pointer that forwards info from DiagnosticsEngine a...
const SourceLocation & getLocation() const
SourceManager & getSourceManager() const
bool hasSourceManager() const
Concrete class used by the front-end to report problems and issues.
void setNumWarnings(unsigned NumWarnings)
Level
The level of the diagnostic, after it has been through mapping.
DiagnosticConsumer * getClient()
unsigned getNumWarnings() const
void Reset(bool soft=false)
Reset the state of the diagnostic object to its initial configuration.
Cached information about one file (either on disk or in the virtual file system).
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Implements support for file system lookup, file system caching, and directory search management.
llvm::vfs::FileSystem & getVirtualFileSystem() const
llvm::ErrorOr< std::unique_ptr< llvm::MemoryBuffer > > getBufferForFile(FileEntryRef Entry, bool isVolatile=false, bool RequiresNullTerminator=true, std::optional< int64_t > MaybeLimit=std::nullopt, bool IsText=true)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
llvm::Expected< FileEntryRef > getSTDIN()
Get the FileEntryRef for stdin, returning an error if stdin cannot be read.
Keeps track of options that affect how file operations are performed.
Diagnostic consumer that saves each diagnostic it is given.
void BeginSourceFile(const LangOptions &LangOpts, const Preprocessor *PP=nullptr) override
Callback to inform the diagnostic client that processing of a source file is beginning.
FilterAndStoreDiagnosticConsumer(SmallVectorImpl< StoredDiagnostic > *StoredDiags, SmallVectorImpl< StandaloneDiagnostic > *StandaloneDiags, bool CaptureNonErrorsFromIncludes)
void HandleDiagnostic(DiagnosticsEngine::Level Level, const Diagnostic &Info) override
Handle this diagnostic, reporting it to the user or capturing it to a log as needed.
Abstract base class for actions which can be performed by the frontend.
virtual void EndSourceFile()
Perform any per-file post processing, deallocate per-file objects, and run statistics and output file...
llvm::Error Execute()
Set the source manager's main input file, and run the action.
virtual TranslationUnitKind getTranslationUnitKind()
For AST-based actions, the kind of translation unit we're handling.
bool BeginSourceFile(CompilerInstance &CI, const FrontendInputFile &Input)
Prepare the action for processing the input file Input.
FrontendOptions - Options for controlling the behavior of the frontend.
unsigned SkipFunctionBodies
Skip over function bodies to speed up parsing in cases you do not need them (e.g.
CodeCompleteOptions CodeCompleteOpts
ParsedSourceLocation CodeCompletionAt
If given, enable code completion at the provided location.
SmallVector< FrontendInputFile, 0 > Inputs
The input files and their types.
A SourceLocation and its associated SourceManager.
One of these records is kept for each identifier that is lexed.
StringRef getName() const
Return the actual identifier string.
@ CMK_ModuleMap
Compiling a module from a module map.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
bool isCompilingModule() const
Are we compiling a module?
Identifies a module file to be loaded.
static ModuleFileName makeExplicit(std::string Name)
Creates a file name for an explicit module.
static ModuleFileName makeInMemory(StringRef Name)
Creates a file name for an in-memory module.
Describes a module or submodule.
bool isNamedModule() const
Does this Module is a named module of a standard named module?
This represents a decl that may have a name.
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
This abstract interface provides operations for unwrapping containers for serialized ASTs (precompile...
virtual llvm::ArrayRef< llvm::StringRef > getFormats() const =0
Equivalent to the format passed to -fmodule-format=.
This interface provides a way to observe the actions of the preprocessor as it does its thing.
A set of callbacks to gather useful information while building a preamble.
static llvm::ErrorOr< PrecompiledPreamble > Build(const CompilerInvocation &Invocation, const llvm::MemoryBuffer *MainFileBuffer, PreambleBounds Bounds, IntrusiveRefCntPtr< DiagnosticsEngine > Diagnostics, IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS, std::shared_ptr< PCHContainerOperations > PCHContainerOps, bool StoreInMemory, StringRef StoragePath, PreambleCallbacks &Callbacks)
Try to build PrecompiledPreamble for Invocation.
Iteration over the preprocessed entities.
A record of the steps taken while preprocessing a source file, including the various preprocessing di...
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
std::pair< unsigned, bool > PrecompiledPreambleBytes
If non-zero, the implicit PCH include is actually a precompiled preamble that covers this number of b...
bool RetainRemappedFileBuffers
Whether the compiler instance should retain (i.e., not free) the buffers associated with remapped fil...
bool DetailedRecord
Whether we should maintain a detailed record of all macro definitions and expansions.
void clearRemappedFiles()
void addRemappedFile(StringRef From, StringRef To)
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
void addPPCallbacks(std::unique_ptr< PPCallbacks > C)
SourceManager & getSourceManager() const
A (possibly-)qualified type.
bool isNull() const
Return true if this QualType doesn't point to a type yet.
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Sema - This implements semantic analysis and AST building for C.
const LangOptions & getLangOpts() const
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
This class handles loading and caching of source files into memory.
bool isWrittenInMainFile(SourceLocation Loc) const
Returns true if the spelling location for the given location is in the main file buffer.
Represents a diagnostic in a form that can be retained until its corresponding source manager is dest...
const FullSourceLoc & getLocation() const
static TargetInfo * CreateTargetInfo(DiagnosticsEngine &Diags, TargetOptions &Opts)
Construct a target for the given options.
Token - This structure provides full information about a lexed token.
IdentifierInfo * getIdentifierInfo() const
Information about a module that has been loaded by the ASTReader.
ModuleFileName FileName
The file name of the module file.
ModuleKind Kind
The type of this module.
@ CXCursor_MacroDefinition
Defines the clang::TargetInfo interface.
@ VFS
Remove unused -ivfsoverlay arguments.
@ MK_PCH
File is a PCH file treated as such.
@ MK_Preamble
File is a PCH file treated as the preamble.
@ MK_MainFile
File is a PCH file treated as the actual main file.
@ MK_ExplicitModule
File is an explicitly-loaded module.
@ MK_ImplicitModule
File is an implicitly-loaded module.
@ MK_PrebuiltModule
File is from a prebuilt module path.
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
bool isa(CodeGen::Address addr)
CustomizableOptional< FileEntryRef > OptionalFileEntryRef
IntrusiveRefCntPtr< llvm::vfs::FileSystem > createVFSFromOverlayFiles(ArrayRef< std::string > VFSOverlayFiles, DiagnosticsEngine &Diags, IntrusiveRefCntPtr< llvm::vfs::FileSystem > BaseFS)
@ CCP_NestedNameSpecifier
Priority for a nested-name-specifier.
@ CCP_CodePattern
Priority for a code pattern.
std::shared_ptr< ModuleCache > createCrossProcessModuleCache()
Creates new ModuleCache backed by a file system directory that may be operated on by multiple process...
@ Parse
Parse the block; this code is always used.
Language
The language for the input, used to select and validate the language standard and possible actions.
@ C
Languages that the frontend can parse and compile.
@ Result
The result type of a method or function.
SimplifiedTypeClass
A simplified classification of types used when determining "similar" types for code completion.
CaptureDiagsKind
Enumerates the available kinds for capturing diagnostics.
@ AllWithoutNonErrorsFromIncludes
IntrusiveRefCntPtr< llvm::vfs::FileSystem > createVFSFromCompilerInvocation(const CompilerInvocation &CI, DiagnosticsEngine &Diags)
void ProcessWarningOptions(DiagnosticsEngine &Diags, const DiagnosticOptions &Opts, llvm::vfs::FileSystem &VFS, bool ReportDiags=true)
ProcessWarningOptions - Initialize the diagnostic client and process the warning options specified on...
TranslationUnitKind
Describes the kind of translation unit being processed.
@ TU_Complete
The translation unit is a complete translation unit.
@ CCF_ExactTypeMatch
Divide by this factor when a code-completion result's type exactly matches the type we expect.
@ CCF_SimilarTypeMatch
Divide by this factor when a code-completion result's type is similar to the type we expect (e....
SimplifiedTypeClass getSimplifiedTypeClass(CanQualType T)
Determine the simplified type class of the given canonical type.
unsigned getMacroUsagePriority(StringRef MacroName, const LangOptions &LangOpts, bool PreferredTypeIsPointer=false)
Determine the priority to be given to a macro code completion result with the given name.
DisableValidationForModuleKind
Whether to disable the normal validation performed on precompiled headers and module files when they ...
@ None
Perform validation, don't disable it.
@ All
Disable validation for all kinds.
PreambleBounds ComputePreambleBounds(const LangOptions &LangOpts, const llvm::MemoryBufferRef &Buffer, unsigned MaxLines)
Runs lexer to compute suggested preamble bounds.
@ CouldntCreateTargetInfo
llvm::StringRef getAsString(SyncScope S)
QualType getDeclUsageType(ASTContext &C, NestedNameSpecifier Qualifier, const NamedDecl *ND)
Determine the type that this declaration will have if it is used as a type or in an expression.
StoredDiagnostic translateStandaloneDiag(FileManager &FileMgr, SourceManager &SrcMgr, const StandaloneDiagnostic &StandaloneDiag, llvm::StringMap< SourceLocation > &SrcLocCache)
Translates StandaloneDiag into a StoredDiagnostic, associating it with the provided FileManager and S...
__LIBC_ATTRS FILE * stderr
A cached code-completion result, which may be introduced in one of many different contexts.
CodeCompletionString * Completion
The code-completion string corresponding to this completion result.
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
unsigned Size
Size of the preamble in bytes.
Describes how types, statements, expressions, and declarations should be printed.