1 //===--- ASTUnit.cpp - ASTUnit utility --------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // ASTUnit Implementation.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Frontend/ASTUnit.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/DeclVisitor.h"
18 #include "clang/AST/StmtVisitor.h"
19 #include "clang/AST/TypeOrdering.h"
20 #include "clang/Basic/Diagnostic.h"
21 #include "clang/Basic/MemoryBufferCache.h"
22 #include "clang/Basic/TargetInfo.h"
23 #include "clang/Basic/TargetOptions.h"
24 #include "clang/Basic/VirtualFileSystem.h"
25 #include "clang/Frontend/CompilerInstance.h"
26 #include "clang/Frontend/FrontendActions.h"
27 #include "clang/Frontend/FrontendDiagnostic.h"
28 #include "clang/Frontend/FrontendOptions.h"
29 #include "clang/Frontend/MultiplexConsumer.h"
30 #include "clang/Frontend/Utils.h"
31 #include "clang/Lex/HeaderSearch.h"
32 #include "clang/Lex/Preprocessor.h"
33 #include "clang/Lex/PreprocessorOptions.h"
34 #include "clang/Sema/Sema.h"
35 #include "clang/Serialization/ASTReader.h"
36 #include "clang/Serialization/ASTWriter.h"
37 #include "llvm/ADT/ArrayRef.h"
38 #include "llvm/ADT/StringExtras.h"
39 #include "llvm/ADT/StringSet.h"
40 #include "llvm/Support/CrashRecoveryContext.h"
41 #include "llvm/Support/Host.h"
42 #include "llvm/Support/MemoryBuffer.h"
43 #include "llvm/Support/Mutex.h"
44 #include "llvm/Support/MutexGuard.h"
45 #include "llvm/Support/Timer.h"
46 #include "llvm/Support/raw_ostream.h"
51 using namespace clang;
53 using llvm::TimeRecord;
62 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
64 Start = TimeRecord::getCurrentTime();
67 void setOutput(const Twine &Output) {
69 this->Output = Output.str();
74 TimeRecord Elapsed = TimeRecord::getCurrentTime();
76 llvm::errs() << Output << ':';
77 Elapsed.print(Elapsed, llvm::errs());
84 /// \brief The file in which the precompiled preamble is stored.
85 std::string PreambleFile;
87 /// \brief Erase the preamble file.
88 void CleanPreambleFile();
90 /// \brief Erase temporary files and the preamble file.
95 std::unique_ptr<T> valueOrNull(llvm::ErrorOr<std::unique_ptr<T>> Val) {
98 return std::move(*Val);
102 bool moveOnNoError(llvm::ErrorOr<T> Val, T &Output) {
105 Output = std::move(*Val);
110 static llvm::sys::SmartMutex<false> &getOnDiskMutex() {
111 static llvm::sys::SmartMutex<false> M(/* recursive = */ true);
115 static void cleanupOnDiskMapAtExit();
117 typedef llvm::DenseMap<const ASTUnit *,
118 std::unique_ptr<OnDiskData>> OnDiskDataMap;
119 static OnDiskDataMap &getOnDiskDataMap() {
120 static OnDiskDataMap M;
121 static bool hasRegisteredAtExit = false;
122 if (!hasRegisteredAtExit) {
123 hasRegisteredAtExit = true;
124 atexit(cleanupOnDiskMapAtExit);
129 static void cleanupOnDiskMapAtExit() {
130 // Use the mutex because there can be an alive thread destroying an ASTUnit.
131 llvm::MutexGuard Guard(getOnDiskMutex());
132 for (const auto &I : getOnDiskDataMap()) {
133 // We don't worry about freeing the memory associated with OnDiskDataMap.
134 // All we care about is erasing stale files.
139 static OnDiskData &getOnDiskData(const ASTUnit *AU) {
140 // We require the mutex since we are modifying the structure of the
142 llvm::MutexGuard Guard(getOnDiskMutex());
143 OnDiskDataMap &M = getOnDiskDataMap();
146 D = llvm::make_unique<OnDiskData>();
150 static void erasePreambleFile(const ASTUnit *AU) {
151 getOnDiskData(AU).CleanPreambleFile();
154 static void removeOnDiskEntry(const ASTUnit *AU) {
155 // We require the mutex since we are modifying the structure of the
157 llvm::MutexGuard Guard(getOnDiskMutex());
158 OnDiskDataMap &M = getOnDiskDataMap();
159 OnDiskDataMap::iterator I = M.find(AU);
161 I->second->Cleanup();
166 static void setPreambleFile(const ASTUnit *AU, StringRef preambleFile) {
167 getOnDiskData(AU).PreambleFile = preambleFile;
170 static const std::string &getPreambleFile(const ASTUnit *AU) {
171 return getOnDiskData(AU).PreambleFile;
174 void OnDiskData::CleanPreambleFile() {
175 if (!PreambleFile.empty()) {
176 llvm::sys::fs::remove(PreambleFile);
177 PreambleFile.clear();
181 void OnDiskData::Cleanup() {
185 struct ASTUnit::ASTWriterData {
186 SmallString<128> Buffer;
187 llvm::BitstreamWriter Stream;
190 ASTWriterData(MemoryBufferCache &PCMCache)
191 : Stream(Buffer), Writer(Stream, Buffer, PCMCache, {}) {}
194 void ASTUnit::clearFileLevelDecls() {
195 llvm::DeleteContainerSeconds(FileDecls);
198 /// \brief After failing to build a precompiled preamble (due to
199 /// errors in the source that occurs in the preamble), the number of
200 /// reparses during which we'll skip even trying to precompile the
202 const unsigned DefaultPreambleRebuildInterval = 5;
204 /// \brief Tracks the number of ASTUnit objects that are currently active.
206 /// Used for debugging purposes only.
207 static std::atomic<unsigned> ActiveASTUnitObjects;
209 ASTUnit::ASTUnit(bool _MainFileIsAST)
210 : Reader(nullptr), HadModuleLoaderFatalFailure(false),
211 OnlyLocalDecls(false), CaptureDiagnostics(false),
212 MainFileIsAST(_MainFileIsAST),
213 TUKind(TU_Complete), WantTiming(getenv("LIBCLANG_TIMING")),
214 OwnsRemappedFileBuffers(true),
215 NumStoredDiagnosticsFromDriver(0),
216 PreambleRebuildCounter(0),
217 NumWarningsInPreamble(0),
218 ShouldCacheCodeCompletionResults(false),
219 IncludeBriefCommentsInCodeCompletion(false), UserFilesAreVolatile(false),
220 CompletionCacheTopLevelHashValue(0),
221 PreambleTopLevelHashValue(0),
222 CurrentTopLevelHashValue(0),
223 UnsafeToFree(false) {
224 if (getenv("LIBCLANG_OBJTRACKING"))
225 fprintf(stderr, "+++ %u translation units\n", ++ActiveASTUnitObjects);
228 ASTUnit::~ASTUnit() {
229 // If we loaded from an AST file, balance out the BeginSourceFile call.
230 if (MainFileIsAST && getDiagnostics().getClient()) {
231 getDiagnostics().getClient()->EndSourceFile();
234 clearFileLevelDecls();
236 // Clean up the temporary files and the preamble file.
237 removeOnDiskEntry(this);
239 // Free the buffers associated with remapped files. We are required to
240 // perform this operation here because we explicitly request that the
241 // compiler instance *not* free these buffers for each invocation of the
243 if (Invocation && OwnsRemappedFileBuffers) {
244 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
245 for (const auto &RB : PPOpts.RemappedFileBuffers)
249 ClearCachedCompletionResults();
251 if (getenv("LIBCLANG_OBJTRACKING"))
252 fprintf(stderr, "--- %u translation units\n", --ActiveASTUnitObjects);
255 void ASTUnit::setPreprocessor(std::shared_ptr<Preprocessor> PP) {
256 this->PP = std::move(PP);
259 /// \brief Determine the set of code-completion contexts in which this
260 /// declaration should be shown.
261 static unsigned getDeclShowContexts(const NamedDecl *ND,
262 const LangOptions &LangOpts,
263 bool &IsNestedNameSpecifier) {
264 IsNestedNameSpecifier = false;
266 if (isa<UsingShadowDecl>(ND))
267 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
271 uint64_t Contexts = 0;
272 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
273 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
274 // Types can appear in these contexts.
275 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
276 Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel)
277 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
278 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
279 | (1LL << CodeCompletionContext::CCC_Statement)
280 | (1LL << CodeCompletionContext::CCC_Type)
281 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
283 // In C++, types can appear in expressions contexts (for functional casts).
284 if (LangOpts.CPlusPlus)
285 Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
287 // In Objective-C, message sends can send interfaces. In Objective-C++,
288 // all types are available due to functional casts.
289 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
290 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
292 // In Objective-C, you can only be a subclass of another Objective-C class
293 if (isa<ObjCInterfaceDecl>(ND))
294 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName);
296 // Deal with tag names.
297 if (isa<EnumDecl>(ND)) {
298 Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag);
300 // Part of the nested-name-specifier in C++0x.
301 if (LangOpts.CPlusPlus11)
302 IsNestedNameSpecifier = true;
303 } else if (const RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
304 if (Record->isUnion())
305 Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag);
307 Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
309 if (LangOpts.CPlusPlus)
310 IsNestedNameSpecifier = true;
311 } else if (isa<ClassTemplateDecl>(ND))
312 IsNestedNameSpecifier = true;
313 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
314 // Values can appear in these contexts.
315 Contexts = (1LL << CodeCompletionContext::CCC_Statement)
316 | (1LL << CodeCompletionContext::CCC_Expression)
317 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
318 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
319 } else if (isa<ObjCProtocolDecl>(ND)) {
320 Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName);
321 } else if (isa<ObjCCategoryDecl>(ND)) {
322 Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName);
323 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
324 Contexts = (1LL << CodeCompletionContext::CCC_Namespace);
326 // Part of the nested-name-specifier.
327 IsNestedNameSpecifier = true;
333 void ASTUnit::CacheCodeCompletionResults() {
337 SimpleTimer Timer(WantTiming);
338 Timer.setOutput("Cache global code completions for " + getMainFileName());
340 // Clear out the previous results.
341 ClearCachedCompletionResults();
343 // Gather the set of global code completions.
344 typedef CodeCompletionResult Result;
345 SmallVector<Result, 8> Results;
346 CachedCompletionAllocator = std::make_shared<GlobalCodeCompletionAllocator>();
347 CodeCompletionTUInfo CCTUInfo(CachedCompletionAllocator);
348 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
351 // Translate global code completions into cached completions.
352 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
353 CodeCompletionContext CCContext(CodeCompletionContext::CCC_TopLevel);
355 for (Result &R : Results) {
357 case Result::RK_Declaration: {
358 bool IsNestedNameSpecifier = false;
359 CachedCodeCompletionResult CachedResult;
360 CachedResult.Completion = R.CreateCodeCompletionString(
361 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
362 IncludeBriefCommentsInCodeCompletion);
363 CachedResult.ShowInContexts = getDeclShowContexts(
364 R.Declaration, Ctx->getLangOpts(), IsNestedNameSpecifier);
365 CachedResult.Priority = R.Priority;
366 CachedResult.Kind = R.CursorKind;
367 CachedResult.Availability = R.Availability;
369 // Keep track of the type of this completion in an ASTContext-agnostic
371 QualType UsageType = getDeclUsageType(*Ctx, R.Declaration);
372 if (UsageType.isNull()) {
373 CachedResult.TypeClass = STC_Void;
374 CachedResult.Type = 0;
376 CanQualType CanUsageType
377 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
378 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
380 // Determine whether we have already seen this type. If so, we save
381 // ourselves the work of formatting the type string by using the
382 // temporary, CanQualType-based hash table to find the associated value.
383 unsigned &TypeValue = CompletionTypes[CanUsageType];
384 if (TypeValue == 0) {
385 TypeValue = CompletionTypes.size();
386 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
390 CachedResult.Type = TypeValue;
393 CachedCompletionResults.push_back(CachedResult);
395 /// Handle nested-name-specifiers in C++.
396 if (TheSema->Context.getLangOpts().CPlusPlus && IsNestedNameSpecifier &&
397 !R.StartsNestedNameSpecifier) {
398 // The contexts in which a nested-name-specifier can appear in C++.
400 = (1LL << CodeCompletionContext::CCC_TopLevel)
401 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
402 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
403 | (1LL << CodeCompletionContext::CCC_Statement)
404 | (1LL << CodeCompletionContext::CCC_Expression)
405 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
406 | (1LL << CodeCompletionContext::CCC_EnumTag)
407 | (1LL << CodeCompletionContext::CCC_UnionTag)
408 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag)
409 | (1LL << CodeCompletionContext::CCC_Type)
410 | (1LL << CodeCompletionContext::CCC_PotentiallyQualifiedName)
411 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
413 if (isa<NamespaceDecl>(R.Declaration) ||
414 isa<NamespaceAliasDecl>(R.Declaration))
415 NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
417 if (unsigned RemainingContexts
418 = NNSContexts & ~CachedResult.ShowInContexts) {
419 // If there any contexts where this completion can be a
420 // nested-name-specifier but isn't already an option, create a
421 // nested-name-specifier completion.
422 R.StartsNestedNameSpecifier = true;
423 CachedResult.Completion = R.CreateCodeCompletionString(
424 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
425 IncludeBriefCommentsInCodeCompletion);
426 CachedResult.ShowInContexts = RemainingContexts;
427 CachedResult.Priority = CCP_NestedNameSpecifier;
428 CachedResult.TypeClass = STC_Void;
429 CachedResult.Type = 0;
430 CachedCompletionResults.push_back(CachedResult);
436 case Result::RK_Keyword:
437 case Result::RK_Pattern:
438 // Ignore keywords and patterns; we don't care, since they are so
439 // easily regenerated.
442 case Result::RK_Macro: {
443 CachedCodeCompletionResult CachedResult;
444 CachedResult.Completion = R.CreateCodeCompletionString(
445 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
446 IncludeBriefCommentsInCodeCompletion);
447 CachedResult.ShowInContexts
448 = (1LL << CodeCompletionContext::CCC_TopLevel)
449 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
450 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
451 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
452 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
453 | (1LL << CodeCompletionContext::CCC_Statement)
454 | (1LL << CodeCompletionContext::CCC_Expression)
455 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
456 | (1LL << CodeCompletionContext::CCC_MacroNameUse)
457 | (1LL << CodeCompletionContext::CCC_PreprocessorExpression)
458 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
459 | (1LL << CodeCompletionContext::CCC_OtherWithMacros);
461 CachedResult.Priority = R.Priority;
462 CachedResult.Kind = R.CursorKind;
463 CachedResult.Availability = R.Availability;
464 CachedResult.TypeClass = STC_Void;
465 CachedResult.Type = 0;
466 CachedCompletionResults.push_back(CachedResult);
472 // Save the current top-level hash value.
473 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
476 void ASTUnit::ClearCachedCompletionResults() {
477 CachedCompletionResults.clear();
478 CachedCompletionTypes.clear();
479 CachedCompletionAllocator = nullptr;
484 /// \brief Gathers information from ASTReader that will be used to initialize
486 class ASTInfoCollector : public ASTReaderListener {
489 HeaderSearchOptions &HSOpts;
490 PreprocessorOptions &PPOpts;
491 LangOptions &LangOpt;
492 std::shared_ptr<TargetOptions> &TargetOpts;
493 IntrusiveRefCntPtr<TargetInfo> &Target;
496 bool InitializedLanguage;
498 ASTInfoCollector(Preprocessor &PP, ASTContext &Context,
499 HeaderSearchOptions &HSOpts, PreprocessorOptions &PPOpts,
500 LangOptions &LangOpt,
501 std::shared_ptr<TargetOptions> &TargetOpts,
502 IntrusiveRefCntPtr<TargetInfo> &Target, unsigned &Counter)
503 : PP(PP), Context(Context), HSOpts(HSOpts), PPOpts(PPOpts),
504 LangOpt(LangOpt), TargetOpts(TargetOpts), Target(Target),
505 Counter(Counter), InitializedLanguage(false) {}
507 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
508 bool AllowCompatibleDifferences) override {
509 if (InitializedLanguage)
513 InitializedLanguage = true;
519 virtual bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
520 StringRef SpecificModuleCachePath,
521 bool Complain) override {
522 this->HSOpts = HSOpts;
527 ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool Complain,
528 std::string &SuggestedPredefines) override {
529 this->PPOpts = PPOpts;
533 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
534 bool AllowCompatibleDifferences) override {
535 // If we've already initialized the target, don't do it again.
539 this->TargetOpts = std::make_shared<TargetOptions>(TargetOpts);
541 TargetInfo::CreateTargetInfo(PP.getDiagnostics(), this->TargetOpts);
547 void ReadCounter(const serialization::ModuleFile &M,
548 unsigned Value) override {
554 if (!Target || !InitializedLanguage)
557 // Inform the target of the language options.
559 // FIXME: We shouldn't need to do this, the target should be immutable once
560 // created. This complexity should be lifted elsewhere.
561 Target->adjust(LangOpt);
563 // Initialize the preprocessor.
564 PP.Initialize(*Target);
566 // Initialize the ASTContext
567 Context.InitBuiltinTypes(*Target);
569 // We didn't have access to the comment options when the ASTContext was
570 // constructed, so register them now.
571 Context.getCommentCommandTraits().registerCommentOptions(
572 LangOpt.CommentOpts);
576 /// \brief Diagnostic consumer that saves each diagnostic it is given.
577 class StoredDiagnosticConsumer : public DiagnosticConsumer {
578 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
579 SourceManager *SourceMgr;
582 explicit StoredDiagnosticConsumer(
583 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
584 : StoredDiags(StoredDiags), SourceMgr(nullptr) {}
586 void BeginSourceFile(const LangOptions &LangOpts,
587 const Preprocessor *PP = nullptr) override {
589 SourceMgr = &PP->getSourceManager();
592 void HandleDiagnostic(DiagnosticsEngine::Level Level,
593 const Diagnostic &Info) override;
596 /// \brief RAII object that optionally captures diagnostics, if
597 /// there is no diagnostic client to capture them already.
598 class CaptureDroppedDiagnostics {
599 DiagnosticsEngine &Diags;
600 StoredDiagnosticConsumer Client;
601 DiagnosticConsumer *PreviousClient;
602 std::unique_ptr<DiagnosticConsumer> OwningPreviousClient;
605 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
606 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
607 : Diags(Diags), Client(StoredDiags), PreviousClient(nullptr)
609 if (RequestCapture || Diags.getClient() == nullptr) {
610 OwningPreviousClient = Diags.takeClient();
611 PreviousClient = Diags.getClient();
612 Diags.setClient(&Client, false);
616 ~CaptureDroppedDiagnostics() {
617 if (Diags.getClient() == &Client)
618 Diags.setClient(PreviousClient, !!OwningPreviousClient.release());
622 } // anonymous namespace
624 void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
625 const Diagnostic &Info) {
626 // Default implementation (Warnings/errors count).
627 DiagnosticConsumer::HandleDiagnostic(Level, Info);
629 // Only record the diagnostic if it's part of the source manager we know
630 // about. This effectively drops diagnostics from modules we're building.
631 // FIXME: In the long run, ee don't want to drop source managers from modules.
632 if (!Info.hasSourceManager() || &Info.getSourceManager() == SourceMgr)
633 StoredDiags.emplace_back(Level, Info);
636 IntrusiveRefCntPtr<ASTReader> ASTUnit::getASTReader() const {
640 ASTMutationListener *ASTUnit::getASTMutationListener() {
642 return &WriterData->Writer;
646 ASTDeserializationListener *ASTUnit::getDeserializationListener() {
648 return &WriterData->Writer;
652 std::unique_ptr<llvm::MemoryBuffer>
653 ASTUnit::getBufferForFile(StringRef Filename, std::string *ErrorStr) {
655 auto Buffer = FileMgr->getBufferForFile(Filename);
657 return std::move(*Buffer);
659 *ErrorStr = Buffer.getError().message();
663 /// \brief Configure the diagnostics object for use with ASTUnit.
664 void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
665 ASTUnit &AST, bool CaptureDiagnostics) {
666 assert(Diags.get() && "no DiagnosticsEngine was provided");
667 if (CaptureDiagnostics)
668 Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
671 std::unique_ptr<ASTUnit> ASTUnit::LoadFromASTFile(
672 const std::string &Filename, const PCHContainerReader &PCHContainerRdr,
673 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
674 const FileSystemOptions &FileSystemOpts, bool UseDebugInfo,
675 bool OnlyLocalDecls, ArrayRef<RemappedFile> RemappedFiles,
676 bool CaptureDiagnostics, bool AllowPCHWithCompilerErrors,
677 bool UserFilesAreVolatile) {
678 std::unique_ptr<ASTUnit> AST(new ASTUnit(true));
680 // Recover resources if we crash before exiting this method.
681 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
682 ASTUnitCleanup(AST.get());
683 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
684 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
685 DiagCleanup(Diags.get());
687 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
689 AST->LangOpts = std::make_shared<LangOptions>();
690 AST->OnlyLocalDecls = OnlyLocalDecls;
691 AST->CaptureDiagnostics = CaptureDiagnostics;
692 AST->Diagnostics = Diags;
693 IntrusiveRefCntPtr<vfs::FileSystem> VFS = vfs::getRealFileSystem();
694 AST->FileMgr = new FileManager(FileSystemOpts, VFS);
695 AST->UserFilesAreVolatile = UserFilesAreVolatile;
696 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
697 AST->getFileManager(),
698 UserFilesAreVolatile);
699 AST->PCMCache = new MemoryBufferCache;
700 AST->HSOpts = std::make_shared<HeaderSearchOptions>();
701 AST->HSOpts->ModuleFormat = PCHContainerRdr.getFormat();
702 AST->HeaderInfo.reset(new HeaderSearch(AST->HSOpts,
703 AST->getSourceManager(),
704 AST->getDiagnostics(),
706 /*Target=*/nullptr));
707 AST->PPOpts = std::make_shared<PreprocessorOptions>();
709 for (const auto &RemappedFile : RemappedFiles)
710 AST->PPOpts->addRemappedFile(RemappedFile.first, RemappedFile.second);
712 // Gather Info for preprocessor construction later on.
714 HeaderSearch &HeaderInfo = *AST->HeaderInfo;
717 AST->PP = std::make_shared<Preprocessor>(
718 AST->PPOpts, AST->getDiagnostics(), *AST->LangOpts,
719 AST->getSourceManager(), *AST->PCMCache, HeaderInfo, AST->ModuleLoader,
720 /*IILookup=*/nullptr,
721 /*OwnsHeaderSearch=*/false);
722 Preprocessor &PP = *AST->PP;
724 AST->Ctx = new ASTContext(*AST->LangOpts, AST->getSourceManager(),
725 PP.getIdentifierTable(), PP.getSelectorTable(),
726 PP.getBuiltinInfo());
727 ASTContext &Context = *AST->Ctx;
729 bool disableValid = false;
730 if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
732 AST->Reader = new ASTReader(PP, Context, PCHContainerRdr, { },
734 /*DisableValidation=*/disableValid,
735 AllowPCHWithCompilerErrors);
737 AST->Reader->setListener(llvm::make_unique<ASTInfoCollector>(
738 *AST->PP, Context, *AST->HSOpts, *AST->PPOpts, *AST->LangOpts,
739 AST->TargetOpts, AST->Target, Counter));
741 // Attach the AST reader to the AST context as an external AST
742 // source, so that declarations will be deserialized from the
743 // AST file as needed.
744 // We need the external source to be set up before we read the AST, because
745 // eagerly-deserialized declarations may use it.
746 Context.setExternalSource(AST->Reader);
748 switch (AST->Reader->ReadAST(Filename, serialization::MK_MainFile,
749 SourceLocation(), ASTReader::ARR_None)) {
750 case ASTReader::Success:
753 case ASTReader::Failure:
754 case ASTReader::Missing:
755 case ASTReader::OutOfDate:
756 case ASTReader::VersionMismatch:
757 case ASTReader::ConfigurationMismatch:
758 case ASTReader::HadErrors:
759 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
763 AST->OriginalSourceFile = AST->Reader->getOriginalSourceFile();
765 PP.setCounterValue(Counter);
767 // Create an AST consumer, even though it isn't used.
768 AST->Consumer.reset(new ASTConsumer);
770 // Create a semantic analysis object and tell the AST reader about it.
771 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
772 AST->TheSema->Initialize();
773 AST->Reader->InitializeSema(*AST->TheSema);
775 // Tell the diagnostic client that we have started a source file.
776 AST->getDiagnostics().getClient()->BeginSourceFile(Context.getLangOpts(),&PP);
783 /// \brief Preprocessor callback class that updates a hash value with the names
784 /// of all macros that have been defined by the translation unit.
785 class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
789 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
791 void MacroDefined(const Token &MacroNameTok,
792 const MacroDirective *MD) override {
793 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
797 /// \brief Add the given declaration to the hash of all top-level entities.
798 void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
802 DeclContext *DC = D->getDeclContext();
806 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
809 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
810 if (EnumDecl *EnumD = dyn_cast<EnumDecl>(D)) {
811 // For an unscoped enum include the enumerators in the hash since they
812 // enter the top-level namespace.
813 if (!EnumD->isScoped()) {
814 for (const auto *EI : EnumD->enumerators()) {
815 if (EI->getIdentifier())
816 Hash = llvm::HashString(EI->getIdentifier()->getName(), Hash);
821 if (ND->getIdentifier())
822 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
823 else if (DeclarationName Name = ND->getDeclName()) {
824 std::string NameStr = Name.getAsString();
825 Hash = llvm::HashString(NameStr, Hash);
830 if (ImportDecl *ImportD = dyn_cast<ImportDecl>(D)) {
831 if (Module *Mod = ImportD->getImportedModule()) {
832 std::string ModName = Mod->getFullModuleName();
833 Hash = llvm::HashString(ModName, Hash);
839 class TopLevelDeclTrackerConsumer : public ASTConsumer {
844 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
845 : Unit(_Unit), Hash(Hash) {
849 void handleTopLevelDecl(Decl *D) {
853 // FIXME: Currently ObjC method declarations are incorrectly being
854 // reported as top-level declarations, even though their DeclContext
855 // is the containing ObjC @interface/@implementation. This is a
856 // fundamental problem in the parser right now.
857 if (isa<ObjCMethodDecl>(D))
860 AddTopLevelDeclarationToHash(D, Hash);
861 Unit.addTopLevelDecl(D);
863 handleFileLevelDecl(D);
866 void handleFileLevelDecl(Decl *D) {
867 Unit.addFileLevelDecl(D);
868 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
869 for (auto *I : NSD->decls())
870 handleFileLevelDecl(I);
874 bool HandleTopLevelDecl(DeclGroupRef D) override {
875 for (Decl *TopLevelDecl : D)
876 handleTopLevelDecl(TopLevelDecl);
880 // We're not interested in "interesting" decls.
881 void HandleInterestingDecl(DeclGroupRef) override {}
883 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
884 for (Decl *TopLevelDecl : D)
885 handleTopLevelDecl(TopLevelDecl);
888 ASTMutationListener *GetASTMutationListener() override {
889 return Unit.getASTMutationListener();
892 ASTDeserializationListener *GetASTDeserializationListener() override {
893 return Unit.getDeserializationListener();
897 class TopLevelDeclTrackerAction : public ASTFrontendAction {
901 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
902 StringRef InFile) override {
903 CI.getPreprocessor().addPPCallbacks(
904 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
905 Unit.getCurrentTopLevelHashValue()));
906 return llvm::make_unique<TopLevelDeclTrackerConsumer>(
907 Unit, Unit.getCurrentTopLevelHashValue());
911 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
913 bool hasCodeCompletionSupport() const override { return false; }
914 TranslationUnitKind getTranslationUnitKind() override {
915 return Unit.getTranslationUnitKind();
919 class PrecompilePreambleAction : public ASTFrontendAction {
921 bool HasEmittedPreamblePCH;
924 explicit PrecompilePreambleAction(ASTUnit &Unit)
925 : Unit(Unit), HasEmittedPreamblePCH(false) {}
927 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
928 StringRef InFile) override;
929 bool hasEmittedPreamblePCH() const { return HasEmittedPreamblePCH; }
930 void setHasEmittedPreamblePCH() { HasEmittedPreamblePCH = true; }
931 bool shouldEraseOutputFiles() override { return !hasEmittedPreamblePCH(); }
933 bool hasCodeCompletionSupport() const override { return false; }
934 bool hasASTFileSupport() const override { return false; }
935 TranslationUnitKind getTranslationUnitKind() override { return TU_Prefix; }
938 class PrecompilePreambleConsumer : public PCHGenerator {
941 std::vector<Decl *> TopLevelDecls;
942 PrecompilePreambleAction *Action;
943 std::unique_ptr<raw_ostream> Out;
946 PrecompilePreambleConsumer(ASTUnit &Unit, PrecompilePreambleAction *Action,
947 const Preprocessor &PP, StringRef isysroot,
948 std::unique_ptr<raw_ostream> Out)
949 : PCHGenerator(PP, "", isysroot, std::make_shared<PCHBuffer>(),
950 ArrayRef<std::shared_ptr<ModuleFileExtension>>(),
951 /*AllowASTWithErrors=*/true),
952 Unit(Unit), Hash(Unit.getCurrentTopLevelHashValue()), Action(Action),
953 Out(std::move(Out)) {
957 bool HandleTopLevelDecl(DeclGroupRef DG) override {
959 // FIXME: Currently ObjC method declarations are incorrectly being
960 // reported as top-level declarations, even though their DeclContext
961 // is the containing ObjC @interface/@implementation. This is a
962 // fundamental problem in the parser right now.
963 if (isa<ObjCMethodDecl>(D))
965 AddTopLevelDeclarationToHash(D, Hash);
966 TopLevelDecls.push_back(D);
971 void HandleTranslationUnit(ASTContext &Ctx) override {
972 PCHGenerator::HandleTranslationUnit(Ctx);
973 if (hasEmittedPCH()) {
974 // Write the generated bitstream to "Out".
976 // Make sure it hits disk now.
979 llvm::SmallVector<char, 0> Empty;
980 getPCH() = std::move(Empty);
982 // Translate the top-level declarations we captured during
983 // parsing into declaration IDs in the precompiled
984 // preamble. This will allow us to deserialize those top-level
985 // declarations when requested.
986 for (Decl *D : TopLevelDecls) {
987 // Invalid top-level decls may not have been serialized.
988 if (D->isInvalidDecl())
990 Unit.addTopLevelDeclFromPreamble(getWriter().getDeclID(D));
993 Action->setHasEmittedPreamblePCH();
998 } // anonymous namespace
1000 std::unique_ptr<ASTConsumer>
1001 PrecompilePreambleAction::CreateASTConsumer(CompilerInstance &CI,
1003 std::string Sysroot;
1004 std::string OutputFile;
1005 std::unique_ptr<raw_ostream> OS =
1006 GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
1011 if (!CI.getFrontendOpts().RelocatablePCH)
1014 CI.getPreprocessor().addPPCallbacks(
1015 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
1016 Unit.getCurrentTopLevelHashValue()));
1017 return llvm::make_unique<PrecompilePreambleConsumer>(
1018 Unit, this, CI.getPreprocessor(), Sysroot, std::move(OS));
1021 static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag) {
1022 return StoredDiag.getLocation().isValid();
1026 checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &StoredDiags) {
1027 // Get rid of stored diagnostics except the ones from the driver which do not
1028 // have a source location.
1030 std::remove_if(StoredDiags.begin(), StoredDiags.end(), isNonDriverDiag),
1034 static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
1036 SourceManager &SM) {
1037 // The stored diagnostic has the old source manager in it; update
1038 // the locations to refer into the new source manager. Since we've
1039 // been careful to make sure that the source manager's state
1040 // before and after are identical, so that we can reuse the source
1042 for (StoredDiagnostic &SD : StoredDiagnostics) {
1043 if (SD.getLocation().isValid()) {
1044 FullSourceLoc Loc(SD.getLocation(), SM);
1045 SD.setLocation(Loc);
1050 /// Parse the source file into a translation unit using the given compiler
1051 /// invocation, replacing the current translation unit.
1053 /// \returns True if a failure occurred that causes the ASTUnit not to
1054 /// contain any translation-unit information, false otherwise.
1055 bool ASTUnit::Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1056 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer,
1057 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
1061 // Create the compiler instance to use for building the AST.
1062 std::unique_ptr<CompilerInstance> Clang(
1063 new CompilerInstance(std::move(PCHContainerOps)));
1064 if (FileMgr && VFS) {
1065 assert(VFS == FileMgr->getVirtualFileSystem() &&
1066 "VFS passed to Parse and VFS in FileMgr are different");
1068 Clang->setVirtualFileSystem(VFS);
1071 // Recover resources if we crash before exiting this method.
1072 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1073 CICleanup(Clang.get());
1075 Clang->setInvocation(std::make_shared<CompilerInvocation>(*Invocation));
1076 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1078 // Set up diagnostics, capturing any diagnostics that would
1079 // otherwise be dropped.
1080 Clang->setDiagnostics(&getDiagnostics());
1082 // Create the target instance.
1083 Clang->setTarget(TargetInfo::CreateTargetInfo(
1084 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
1085 if (!Clang->hasTarget())
1088 // Inform the target of the language options.
1090 // FIXME: We shouldn't need to do this, the target should be immutable once
1091 // created. This complexity should be lifted elsewhere.
1092 Clang->getTarget().adjust(Clang->getLangOpts());
1094 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1095 "Invocation must have exactly one source file!");
1096 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1097 InputKind::Source &&
1098 "FIXME: AST inputs not yet supported here!");
1099 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1100 InputKind::LLVM_IR &&
1101 "IR inputs not support here!");
1103 // Configure the various subsystems.
1104 LangOpts = Clang->getInvocation().LangOpts;
1105 FileSystemOpts = Clang->getFileSystemOpts();
1107 Clang->createFileManager();
1108 FileMgr = &Clang->getFileManager();
1113 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1114 UserFilesAreVolatile);
1115 if (!OverrideMainBuffer) {
1116 checkAndRemoveNonDriverDiags(StoredDiagnostics);
1117 TopLevelDeclsInPreamble.clear();
1120 // Create a file manager object to provide access to and cache the filesystem.
1121 Clang->setFileManager(&getFileManager());
1123 // Create the source manager.
1124 Clang->setSourceManager(&getSourceManager());
1126 // If the main file has been overridden due to the use of a preamble,
1127 // make that override happen and introduce the preamble.
1128 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
1129 if (OverrideMainBuffer) {
1130 PreprocessorOpts.addRemappedFile(OriginalSourceFile,
1131 OverrideMainBuffer.get());
1132 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1133 PreprocessorOpts.PrecompiledPreambleBytes.second
1134 = PreambleEndsAtStartOfLine;
1135 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
1136 PreprocessorOpts.DisablePCHValidation = true;
1138 // The stored diagnostic has the old source manager in it; update
1139 // the locations to refer into the new source manager. Since we've
1140 // been careful to make sure that the source manager's state
1141 // before and after are identical, so that we can reuse the source
1143 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
1145 // Keep track of the override buffer;
1146 SavedMainFileBuffer = std::move(OverrideMainBuffer);
1149 std::unique_ptr<TopLevelDeclTrackerAction> Act(
1150 new TopLevelDeclTrackerAction(*this));
1152 // Recover resources if we crash before exiting this method.
1153 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1154 ActCleanup(Act.get());
1156 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
1159 if (SavedMainFileBuffer)
1160 TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
1161 PreambleDiagnostics, StoredDiagnostics);
1163 PreambleSrcLocCache.clear();
1165 if (!Act->Execute())
1168 transferASTDataFromCompilerInstance(*Clang);
1170 Act->EndSourceFile();
1172 FailedParseDiagnostics.clear();
1177 // Remove the overridden buffer we used for the preamble.
1178 SavedMainFileBuffer = nullptr;
1180 // Keep the ownership of the data in the ASTUnit because the client may
1181 // want to see the diagnostics.
1182 transferASTDataFromCompilerInstance(*Clang);
1183 FailedParseDiagnostics.swap(StoredDiagnostics);
1184 StoredDiagnostics.clear();
1185 NumStoredDiagnosticsFromDriver = 0;
1189 /// \brief Simple function to retrieve a path for a preamble precompiled header.
1190 static std::string GetPreamblePCHPath() {
1191 // FIXME: This is a hack so that we can override the preamble file during
1192 // crash-recovery testing, which is the only case where the preamble files
1193 // are not necessarily cleaned up.
1194 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1198 SmallString<128> Path;
1199 llvm::sys::fs::createTemporaryFile("preamble", "pch", Path);
1204 /// \brief Compute the preamble for the main file, providing the source buffer
1205 /// that corresponds to the main file along with a pair (bytes, start-of-line)
1206 /// that describes the preamble.
1207 ASTUnit::ComputedPreamble
1208 ASTUnit::ComputePreamble(CompilerInvocation &Invocation, unsigned MaxLines,
1209 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
1210 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
1211 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
1213 // Try to determine if the main file has been remapped, either from the
1214 // command line (to another file) or directly through the compiler invocation
1215 // (to a memory buffer).
1216 llvm::MemoryBuffer *Buffer = nullptr;
1217 std::unique_ptr<llvm::MemoryBuffer> BufferOwner;
1218 std::string MainFilePath(FrontendOpts.Inputs[0].getFile());
1219 auto MainFileStatus = VFS->status(MainFilePath);
1220 if (MainFileStatus) {
1221 llvm::sys::fs::UniqueID MainFileID = MainFileStatus->getUniqueID();
1223 // Check whether there is a file-file remapping of the main file
1224 for (const auto &RF : PreprocessorOpts.RemappedFiles) {
1225 std::string MPath(RF.first);
1226 auto MPathStatus = VFS->status(MPath);
1228 llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID();
1229 if (MainFileID == MID) {
1230 // We found a remapping. Try to load the resulting, remapped source.
1231 BufferOwner = valueOrNull(VFS->getBufferForFile(RF.second));
1233 return ComputedPreamble(nullptr, nullptr, 0, true);
1238 // Check whether there is a file-buffer remapping. It supercedes the
1239 // file-file remapping.
1240 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
1241 std::string MPath(RB.first);
1242 auto MPathStatus = VFS->status(MPath);
1244 llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID();
1245 if (MainFileID == MID) {
1246 // We found a remapping.
1247 BufferOwner.reset();
1248 Buffer = const_cast<llvm::MemoryBuffer *>(RB.second);
1254 // If the main source file was not remapped, load it now.
1255 if (!Buffer && !BufferOwner) {
1256 BufferOwner = valueOrNull(VFS->getBufferForFile(FrontendOpts.Inputs[0].getFile()));
1258 return ComputedPreamble(nullptr, nullptr, 0, true);
1262 Buffer = BufferOwner.get();
1263 auto Pre = Lexer::ComputePreamble(Buffer->getBuffer(),
1264 *Invocation.getLangOpts(), MaxLines);
1265 return ComputedPreamble(Buffer, std::move(BufferOwner), Pre.first,
1269 ASTUnit::PreambleFileHash
1270 ASTUnit::PreambleFileHash::createForFile(off_t Size, time_t ModTime) {
1271 PreambleFileHash Result;
1273 Result.ModTime = ModTime;
1278 ASTUnit::PreambleFileHash ASTUnit::PreambleFileHash::createForMemoryBuffer(
1279 const llvm::MemoryBuffer *Buffer) {
1280 PreambleFileHash Result;
1281 Result.Size = Buffer->getBufferSize();
1285 MD5Ctx.update(Buffer->getBuffer().data());
1286 MD5Ctx.final(Result.MD5);
1292 bool operator==(const ASTUnit::PreambleFileHash &LHS,
1293 const ASTUnit::PreambleFileHash &RHS) {
1294 return LHS.Size == RHS.Size && LHS.ModTime == RHS.ModTime &&
1297 } // namespace clang
1299 static std::pair<unsigned, unsigned>
1300 makeStandaloneRange(CharSourceRange Range, const SourceManager &SM,
1301 const LangOptions &LangOpts) {
1302 CharSourceRange FileRange = Lexer::makeFileCharRange(Range, SM, LangOpts);
1303 unsigned Offset = SM.getFileOffset(FileRange.getBegin());
1304 unsigned EndOffset = SM.getFileOffset(FileRange.getEnd());
1305 return std::make_pair(Offset, EndOffset);
1308 static ASTUnit::StandaloneFixIt makeStandaloneFixIt(const SourceManager &SM,
1309 const LangOptions &LangOpts,
1310 const FixItHint &InFix) {
1311 ASTUnit::StandaloneFixIt OutFix;
1312 OutFix.RemoveRange = makeStandaloneRange(InFix.RemoveRange, SM, LangOpts);
1313 OutFix.InsertFromRange = makeStandaloneRange(InFix.InsertFromRange, SM,
1315 OutFix.CodeToInsert = InFix.CodeToInsert;
1316 OutFix.BeforePreviousInsertions = InFix.BeforePreviousInsertions;
1320 static ASTUnit::StandaloneDiagnostic
1321 makeStandaloneDiagnostic(const LangOptions &LangOpts,
1322 const StoredDiagnostic &InDiag) {
1323 ASTUnit::StandaloneDiagnostic OutDiag;
1324 OutDiag.ID = InDiag.getID();
1325 OutDiag.Level = InDiag.getLevel();
1326 OutDiag.Message = InDiag.getMessage();
1327 OutDiag.LocOffset = 0;
1328 if (InDiag.getLocation().isInvalid())
1330 const SourceManager &SM = InDiag.getLocation().getManager();
1331 SourceLocation FileLoc = SM.getFileLoc(InDiag.getLocation());
1332 OutDiag.Filename = SM.getFilename(FileLoc);
1333 if (OutDiag.Filename.empty())
1335 OutDiag.LocOffset = SM.getFileOffset(FileLoc);
1336 for (const CharSourceRange &Range : InDiag.getRanges())
1337 OutDiag.Ranges.push_back(makeStandaloneRange(Range, SM, LangOpts));
1338 for (const FixItHint &FixIt : InDiag.getFixIts())
1339 OutDiag.FixIts.push_back(makeStandaloneFixIt(SM, LangOpts, FixIt));
1344 /// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1345 /// the source file.
1347 /// This routine will compute the preamble of the main source file. If a
1348 /// non-trivial preamble is found, it will precompile that preamble into a
1349 /// precompiled header so that the precompiled preamble can be used to reduce
1350 /// reparsing time. If a precompiled preamble has already been constructed,
1351 /// this routine will determine if it is still valid and, if so, avoid
1352 /// rebuilding the precompiled preamble.
1354 /// \param AllowRebuild When true (the default), this routine is
1355 /// allowed to rebuild the precompiled preamble if it is found to be
1358 /// \param MaxLines When non-zero, the maximum number of lines that
1359 /// can occur within the preamble.
1361 /// \returns If the precompiled preamble can be used, returns a newly-allocated
1362 /// buffer that should be used in place of the main file when doing so.
1363 /// Otherwise, returns a NULL pointer.
1364 std::unique_ptr<llvm::MemoryBuffer>
1365 ASTUnit::getMainBufferWithPrecompiledPreamble(
1366 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1367 const CompilerInvocation &PreambleInvocationIn,
1368 IntrusiveRefCntPtr<vfs::FileSystem> VFS, bool AllowRebuild,
1369 unsigned MaxLines) {
1370 assert(VFS && "VFS is null");
1372 auto PreambleInvocation =
1373 std::make_shared<CompilerInvocation>(PreambleInvocationIn);
1374 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
1375 PreprocessorOptions &PreprocessorOpts
1376 = PreambleInvocation->getPreprocessorOpts();
1378 ComputedPreamble NewPreamble =
1379 ComputePreamble(*PreambleInvocation, MaxLines, VFS);
1381 if (!NewPreamble.Size) {
1382 // We couldn't find a preamble in the main source. Clear out the current
1383 // preamble, if we have one. It's obviously no good any more.
1385 erasePreambleFile(this);
1387 // The next time we actually see a preamble, precompile it.
1388 PreambleRebuildCounter = 1;
1392 if (!Preamble.empty()) {
1393 // We've previously computed a preamble. Check whether we have the same
1394 // preamble now that we did before, and that there's enough space in
1395 // the main-file buffer within the precompiled preamble to fit the
1397 if (Preamble.size() == NewPreamble.Size &&
1398 PreambleEndsAtStartOfLine == NewPreamble.PreambleEndsAtStartOfLine &&
1399 memcmp(Preamble.getBufferStart(), NewPreamble.Buffer->getBufferStart(),
1400 NewPreamble.Size) == 0) {
1401 // The preamble has not changed. We may be able to re-use the precompiled
1404 // Check that none of the files used by the preamble have changed.
1405 bool AnyFileChanged = false;
1407 // First, make a record of those files that have been overridden via
1408 // remapping or unsaved_files.
1409 std::map<llvm::sys::fs::UniqueID, PreambleFileHash> OverriddenFiles;
1410 for (const auto &R : PreprocessorOpts.RemappedFiles) {
1415 if (!moveOnNoError(VFS->status(R.second), Status)) {
1416 // If we can't stat the file we're remapping to, assume that something
1417 // horrible happened.
1418 AnyFileChanged = true;
1422 OverriddenFiles[Status.getUniqueID()] = PreambleFileHash::createForFile(
1424 llvm::sys::toTimeT(Status.getLastModificationTime()));
1427 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
1432 if (!moveOnNoError(VFS->status(RB.first), Status)) {
1433 AnyFileChanged = true;
1437 OverriddenFiles[Status.getUniqueID()] =
1438 PreambleFileHash::createForMemoryBuffer(RB.second);
1441 // Check whether anything has changed.
1442 for (llvm::StringMap<PreambleFileHash>::iterator
1443 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1444 !AnyFileChanged && F != FEnd;
1447 if (!moveOnNoError(VFS->status(F->first()), Status)) {
1448 // If we can't stat the file, assume that something horrible happened.
1449 AnyFileChanged = true;
1453 std::map<llvm::sys::fs::UniqueID, PreambleFileHash>::iterator Overridden
1454 = OverriddenFiles.find(Status.getUniqueID());
1455 if (Overridden != OverriddenFiles.end()) {
1456 // This file was remapped; check whether the newly-mapped file
1457 // matches up with the previous mapping.
1458 if (Overridden->second != F->second)
1459 AnyFileChanged = true;
1463 // The file was not remapped; check whether it has changed on disk.
1464 if (Status.getSize() != uint64_t(F->second.Size) ||
1465 llvm::sys::toTimeT(Status.getLastModificationTime()) !=
1467 AnyFileChanged = true;
1470 if (!AnyFileChanged) {
1471 // Okay! We can re-use the precompiled preamble.
1473 // Set the state of the diagnostic object to mimic its state
1474 // after parsing the preamble.
1475 getDiagnostics().Reset();
1476 ProcessWarningOptions(getDiagnostics(),
1477 PreambleInvocation->getDiagnosticOpts());
1478 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1480 return llvm::MemoryBuffer::getMemBufferCopy(
1481 NewPreamble.Buffer->getBuffer(), FrontendOpts.Inputs[0].getFile());
1485 // If we aren't allowed to rebuild the precompiled preamble, just
1490 // We can't reuse the previously-computed preamble. Build a new one.
1492 PreambleDiagnostics.clear();
1493 erasePreambleFile(this);
1494 PreambleRebuildCounter = 1;
1495 } else if (!AllowRebuild) {
1496 // We aren't allowed to rebuild the precompiled preamble; just
1501 // If the preamble rebuild counter > 1, it's because we previously
1502 // failed to build a preamble and we're not yet ready to try
1503 // again. Decrement the counter and return a failure.
1504 if (PreambleRebuildCounter > 1) {
1505 --PreambleRebuildCounter;
1509 // Create a temporary file for the precompiled preamble. In rare
1510 // circumstances, this can fail.
1511 std::string PreamblePCHPath = GetPreamblePCHPath();
1512 if (PreamblePCHPath.empty()) {
1513 // Try again next time.
1514 PreambleRebuildCounter = 1;
1518 // We did not previously compute a preamble, or it can't be reused anyway.
1519 SimpleTimer PreambleTimer(WantTiming);
1520 PreambleTimer.setOutput("Precompiling preamble");
1522 // Save the preamble text for later; we'll need to compare against it for
1523 // subsequent reparses.
1524 StringRef MainFilename = FrontendOpts.Inputs[0].getFile();
1525 Preamble.assign(FileMgr->getFile(MainFilename),
1526 NewPreamble.Buffer->getBufferStart(),
1527 NewPreamble.Buffer->getBufferStart() + NewPreamble.Size);
1528 PreambleEndsAtStartOfLine = NewPreamble.PreambleEndsAtStartOfLine;
1530 PreambleBuffer = llvm::MemoryBuffer::getMemBufferCopy(
1531 NewPreamble.Buffer->getBuffer().slice(0, Preamble.size()), MainFilename);
1533 // Remap the main source file to the preamble buffer.
1534 StringRef MainFilePath = FrontendOpts.Inputs[0].getFile();
1535 PreprocessorOpts.addRemappedFile(MainFilePath, PreambleBuffer.get());
1537 // Tell the compiler invocation to generate a temporary precompiled header.
1538 FrontendOpts.ProgramAction = frontend::GeneratePCH;
1539 // FIXME: Generate the precompiled header into memory?
1540 FrontendOpts.OutputFile = PreamblePCHPath;
1541 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1542 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
1544 // Create the compiler instance to use for building the precompiled preamble.
1545 std::unique_ptr<CompilerInstance> Clang(
1546 new CompilerInstance(std::move(PCHContainerOps)));
1548 // Recover resources if we crash before exiting this method.
1549 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1550 CICleanup(Clang.get());
1552 Clang->setInvocation(std::move(PreambleInvocation));
1553 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1555 // Set up diagnostics, capturing all of the diagnostics produced.
1556 Clang->setDiagnostics(&getDiagnostics());
1558 // Create the target instance.
1559 Clang->setTarget(TargetInfo::CreateTargetInfo(
1560 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
1561 if (!Clang->hasTarget()) {
1562 llvm::sys::fs::remove(FrontendOpts.OutputFile);
1564 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
1565 PreprocessorOpts.RemappedFileBuffers.pop_back();
1569 // Inform the target of the language options.
1571 // FIXME: We shouldn't need to do this, the target should be immutable once
1572 // created. This complexity should be lifted elsewhere.
1573 Clang->getTarget().adjust(Clang->getLangOpts());
1575 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1576 "Invocation must have exactly one source file!");
1577 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1578 InputKind::Source &&
1579 "FIXME: AST inputs not yet supported here!");
1580 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1581 InputKind::LLVM_IR &&
1582 "IR inputs not support here!");
1584 // Clear out old caches and data.
1585 getDiagnostics().Reset();
1586 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
1587 checkAndRemoveNonDriverDiags(StoredDiagnostics);
1588 TopLevelDecls.clear();
1589 TopLevelDeclsInPreamble.clear();
1590 PreambleDiagnostics.clear();
1592 VFS = createVFSFromCompilerInvocation(Clang->getInvocation(),
1593 getDiagnostics(), VFS);
1597 // Create a file manager object to provide access to and cache the filesystem.
1598 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts(), VFS));
1600 // Create the source manager.
1601 Clang->setSourceManager(new SourceManager(getDiagnostics(),
1602 Clang->getFileManager()));
1604 auto PreambleDepCollector = std::make_shared<DependencyCollector>();
1605 Clang->addDependencyCollector(PreambleDepCollector);
1607 std::unique_ptr<PrecompilePreambleAction> Act;
1608 Act.reset(new PrecompilePreambleAction(*this));
1609 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1610 llvm::sys::fs::remove(FrontendOpts.OutputFile);
1612 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
1613 PreprocessorOpts.RemappedFileBuffers.pop_back();
1619 // Transfer any diagnostics generated when parsing the preamble into the set
1620 // of preamble diagnostics.
1621 for (stored_diag_iterator I = stored_diag_afterDriver_begin(),
1622 E = stored_diag_end();
1624 PreambleDiagnostics.push_back(
1625 makeStandaloneDiagnostic(Clang->getLangOpts(), *I));
1627 Act->EndSourceFile();
1629 checkAndRemoveNonDriverDiags(StoredDiagnostics);
1631 if (!Act->hasEmittedPreamblePCH()) {
1632 // The preamble PCH failed (e.g. there was a module loading fatal error),
1633 // so no precompiled header was generated. Forget that we even tried.
1634 // FIXME: Should we leave a note for ourselves to try again?
1635 llvm::sys::fs::remove(FrontendOpts.OutputFile);
1637 TopLevelDeclsInPreamble.clear();
1638 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
1639 PreprocessorOpts.RemappedFileBuffers.pop_back();
1643 // Keep track of the preamble we precompiled.
1644 setPreambleFile(this, FrontendOpts.OutputFile);
1645 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
1647 // Keep track of all of the files that the source manager knows about,
1648 // so we can verify whether they have changed or not.
1649 FilesInPreamble.clear();
1650 SourceManager &SourceMgr = Clang->getSourceManager();
1651 for (auto &Filename : PreambleDepCollector->getDependencies()) {
1652 const FileEntry *File = Clang->getFileManager().getFile(Filename);
1653 if (!File || File == SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()))
1655 if (time_t ModTime = File->getModificationTime()) {
1656 FilesInPreamble[File->getName()] = PreambleFileHash::createForFile(
1657 File->getSize(), ModTime);
1659 llvm::MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File);
1660 FilesInPreamble[File->getName()] =
1661 PreambleFileHash::createForMemoryBuffer(Buffer);
1665 PreambleRebuildCounter = 1;
1666 PreprocessorOpts.RemappedFileBuffers.pop_back();
1668 // If the hash of top-level entities differs from the hash of the top-level
1669 // entities the last time we rebuilt the preamble, clear out the completion
1671 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1672 CompletionCacheTopLevelHashValue = 0;
1673 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1676 return llvm::MemoryBuffer::getMemBufferCopy(NewPreamble.Buffer->getBuffer(),
1680 void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1681 std::vector<Decl *> Resolved;
1682 Resolved.reserve(TopLevelDeclsInPreamble.size());
1683 ExternalASTSource &Source = *getASTContext().getExternalSource();
1684 for (serialization::DeclID TopLevelDecl : TopLevelDeclsInPreamble) {
1685 // Resolve the declaration ID to an actual declaration, possibly
1686 // deserializing the declaration in the process.
1687 if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
1688 Resolved.push_back(D);
1690 TopLevelDeclsInPreamble.clear();
1691 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1694 void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
1695 // Steal the created target, context, and preprocessor if they have been
1697 assert(CI.hasInvocation() && "missing invocation");
1698 LangOpts = CI.getInvocation().LangOpts;
1699 TheSema = CI.takeSema();
1700 Consumer = CI.takeASTConsumer();
1701 if (CI.hasASTContext())
1702 Ctx = &CI.getASTContext();
1703 if (CI.hasPreprocessor())
1704 PP = CI.getPreprocessorPtr();
1705 CI.setSourceManager(nullptr);
1706 CI.setFileManager(nullptr);
1708 Target = &CI.getTarget();
1709 Reader = CI.getModuleManager();
1710 HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure();
1713 StringRef ASTUnit::getMainFileName() const {
1714 if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1715 const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0];
1717 return Input.getFile();
1719 return Input.getBuffer()->getBufferIdentifier();
1723 if (const FileEntry *
1724 FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
1725 return FE->getName();
1731 StringRef ASTUnit::getASTFileName() const {
1732 if (!isMainFileAST())
1735 serialization::ModuleFile &
1736 Mod = Reader->getModuleManager().getPrimaryModule();
1737 return Mod.FileName;
1740 std::unique_ptr<ASTUnit>
1741 ASTUnit::create(std::shared_ptr<CompilerInvocation> CI,
1742 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1743 bool CaptureDiagnostics, bool UserFilesAreVolatile) {
1744 std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
1745 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1746 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1747 createVFSFromCompilerInvocation(*CI, *Diags);
1750 AST->Diagnostics = Diags;
1751 AST->FileSystemOpts = CI->getFileSystemOpts();
1752 AST->Invocation = std::move(CI);
1753 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
1754 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1755 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1756 UserFilesAreVolatile);
1757 AST->PCMCache = new MemoryBufferCache;
1762 ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(
1763 std::shared_ptr<CompilerInvocation> CI,
1764 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1765 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FrontendAction *Action,
1766 ASTUnit *Unit, bool Persistent, StringRef ResourceFilesPath,
1767 bool OnlyLocalDecls, bool CaptureDiagnostics,
1768 unsigned PrecompilePreambleAfterNParses, bool CacheCodeCompletionResults,
1769 bool IncludeBriefCommentsInCodeCompletion, bool UserFilesAreVolatile,
1770 std::unique_ptr<ASTUnit> *ErrAST) {
1771 assert(CI && "A CompilerInvocation is required");
1773 std::unique_ptr<ASTUnit> OwnAST;
1774 ASTUnit *AST = Unit;
1776 // Create the AST unit.
1777 OwnAST = create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile);
1783 if (!ResourceFilesPath.empty()) {
1784 // Override the resources path.
1785 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1787 AST->OnlyLocalDecls = OnlyLocalDecls;
1788 AST->CaptureDiagnostics = CaptureDiagnostics;
1789 if (PrecompilePreambleAfterNParses > 0)
1790 AST->PreambleRebuildCounter = PrecompilePreambleAfterNParses;
1791 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
1792 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1793 AST->IncludeBriefCommentsInCodeCompletion
1794 = IncludeBriefCommentsInCodeCompletion;
1796 // Recover resources if we crash before exiting this method.
1797 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1798 ASTUnitCleanup(OwnAST.get());
1799 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1800 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
1801 DiagCleanup(Diags.get());
1803 // We'll manage file buffers ourselves.
1804 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1805 CI->getFrontendOpts().DisableFree = false;
1806 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1808 // Create the compiler instance to use for building the AST.
1809 std::unique_ptr<CompilerInstance> Clang(
1810 new CompilerInstance(std::move(PCHContainerOps)));
1812 // Recover resources if we crash before exiting this method.
1813 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1814 CICleanup(Clang.get());
1816 Clang->setInvocation(std::move(CI));
1817 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1819 // Set up diagnostics, capturing any diagnostics that would
1820 // otherwise be dropped.
1821 Clang->setDiagnostics(&AST->getDiagnostics());
1823 // Create the target instance.
1824 Clang->setTarget(TargetInfo::CreateTargetInfo(
1825 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
1826 if (!Clang->hasTarget())
1829 // Inform the target of the language options.
1831 // FIXME: We shouldn't need to do this, the target should be immutable once
1832 // created. This complexity should be lifted elsewhere.
1833 Clang->getTarget().adjust(Clang->getLangOpts());
1835 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1836 "Invocation must have exactly one source file!");
1837 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1838 InputKind::Source &&
1839 "FIXME: AST inputs not yet supported here!");
1840 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1841 InputKind::LLVM_IR &&
1842 "IR inputs not support here!");
1844 // Configure the various subsystems.
1845 AST->TheSema.reset();
1848 AST->Reader = nullptr;
1850 // Create a file manager object to provide access to and cache the filesystem.
1851 Clang->setFileManager(&AST->getFileManager());
1853 // Create the source manager.
1854 Clang->setSourceManager(&AST->getSourceManager());
1856 FrontendAction *Act = Action;
1858 std::unique_ptr<TopLevelDeclTrackerAction> TrackerAct;
1860 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1861 Act = TrackerAct.get();
1864 // Recover resources if we crash before exiting this method.
1865 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1866 ActCleanup(TrackerAct.get());
1868 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1869 AST->transferASTDataFromCompilerInstance(*Clang);
1870 if (OwnAST && ErrAST)
1871 ErrAST->swap(OwnAST);
1876 if (Persistent && !TrackerAct) {
1877 Clang->getPreprocessor().addPPCallbacks(
1878 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
1879 AST->getCurrentTopLevelHashValue()));
1880 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
1881 if (Clang->hasASTConsumer())
1882 Consumers.push_back(Clang->takeASTConsumer());
1883 Consumers.push_back(llvm::make_unique<TopLevelDeclTrackerConsumer>(
1884 *AST, AST->getCurrentTopLevelHashValue()));
1885 Clang->setASTConsumer(
1886 llvm::make_unique<MultiplexConsumer>(std::move(Consumers)));
1888 if (!Act->Execute()) {
1889 AST->transferASTDataFromCompilerInstance(*Clang);
1890 if (OwnAST && ErrAST)
1891 ErrAST->swap(OwnAST);
1896 // Steal the created target, context, and preprocessor.
1897 AST->transferASTDataFromCompilerInstance(*Clang);
1899 Act->EndSourceFile();
1902 return OwnAST.release();
1907 bool ASTUnit::LoadFromCompilerInvocation(
1908 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1909 unsigned PrecompilePreambleAfterNParses,
1910 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
1914 assert(VFS && "VFS is null");
1916 // We'll manage file buffers ourselves.
1917 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1918 Invocation->getFrontendOpts().DisableFree = false;
1919 getDiagnostics().Reset();
1920 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1922 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
1923 if (PrecompilePreambleAfterNParses > 0) {
1924 PreambleRebuildCounter = PrecompilePreambleAfterNParses;
1925 OverrideMainBuffer =
1926 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS);
1927 getDiagnostics().Reset();
1928 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1931 SimpleTimer ParsingTimer(WantTiming);
1932 ParsingTimer.setOutput("Parsing " + getMainFileName());
1934 // Recover resources if we crash before exiting this method.
1935 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1936 MemBufferCleanup(OverrideMainBuffer.get());
1938 return Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS);
1941 std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation(
1942 std::shared_ptr<CompilerInvocation> CI,
1943 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1944 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FileManager *FileMgr,
1945 bool OnlyLocalDecls, bool CaptureDiagnostics,
1946 unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
1947 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1948 bool UserFilesAreVolatile) {
1949 // Create the AST unit.
1950 std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
1951 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1952 AST->Diagnostics = Diags;
1953 AST->OnlyLocalDecls = OnlyLocalDecls;
1954 AST->CaptureDiagnostics = CaptureDiagnostics;
1955 AST->TUKind = TUKind;
1956 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1957 AST->IncludeBriefCommentsInCodeCompletion
1958 = IncludeBriefCommentsInCodeCompletion;
1959 AST->Invocation = std::move(CI);
1960 AST->FileSystemOpts = FileMgr->getFileSystemOpts();
1961 AST->FileMgr = FileMgr;
1962 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1964 // Recover resources if we crash before exiting this method.
1965 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1966 ASTUnitCleanup(AST.get());
1967 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1968 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
1969 DiagCleanup(Diags.get());
1971 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
1972 PrecompilePreambleAfterNParses,
1973 AST->FileMgr->getVirtualFileSystem()))
1978 ASTUnit *ASTUnit::LoadFromCommandLine(
1979 const char **ArgBegin, const char **ArgEnd,
1980 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1981 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, StringRef ResourceFilesPath,
1982 bool OnlyLocalDecls, bool CaptureDiagnostics,
1983 ArrayRef<RemappedFile> RemappedFiles, bool RemappedFilesKeepOriginalName,
1984 unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
1985 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1986 bool AllowPCHWithCompilerErrors, bool SkipFunctionBodies,
1987 bool SingleFileParse, bool UserFilesAreVolatile, bool ForSerialization,
1988 llvm::Optional<StringRef> ModuleFormat, std::unique_ptr<ASTUnit> *ErrAST,
1989 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
1990 assert(Diags.get() && "no DiagnosticsEngine was provided");
1992 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
1994 std::shared_ptr<CompilerInvocation> CI;
1998 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
2001 CI = clang::createInvocationFromCommandLine(
2002 llvm::makeArrayRef(ArgBegin, ArgEnd), Diags);
2007 // Override any files that need remapping
2008 for (const auto &RemappedFile : RemappedFiles) {
2009 CI->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
2010 RemappedFile.second);
2012 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
2013 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
2014 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
2015 PPOpts.GeneratePreamble = PrecompilePreambleAfterNParses != 0;
2016 PPOpts.SingleFileParseMode = SingleFileParse;
2018 // Override the resources path.
2019 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
2021 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
2024 CI->getHeaderSearchOpts().ModuleFormat = ModuleFormat.getValue();
2026 // Create the AST unit.
2027 std::unique_ptr<ASTUnit> AST;
2028 AST.reset(new ASTUnit(false));
2029 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
2030 AST->Diagnostics = Diags;
2031 AST->FileSystemOpts = CI->getFileSystemOpts();
2033 VFS = vfs::getRealFileSystem();
2034 VFS = createVFSFromCompilerInvocation(*CI, *Diags, VFS);
2037 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
2038 AST->PCMCache = new MemoryBufferCache;
2039 AST->OnlyLocalDecls = OnlyLocalDecls;
2040 AST->CaptureDiagnostics = CaptureDiagnostics;
2041 AST->TUKind = TUKind;
2042 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
2043 AST->IncludeBriefCommentsInCodeCompletion
2044 = IncludeBriefCommentsInCodeCompletion;
2045 AST->UserFilesAreVolatile = UserFilesAreVolatile;
2046 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
2047 AST->StoredDiagnostics.swap(StoredDiagnostics);
2048 AST->Invocation = CI;
2049 if (ForSerialization)
2050 AST->WriterData.reset(new ASTWriterData(*AST->PCMCache));
2051 // Zero out now to ease cleanup during crash recovery.
2055 // Recover resources if we crash before exiting this method.
2056 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
2057 ASTUnitCleanup(AST.get());
2059 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
2060 PrecompilePreambleAfterNParses,
2062 // Some error occurred, if caller wants to examine diagnostics, pass it the
2065 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
2071 return AST.release();
2074 bool ASTUnit::Reparse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
2075 ArrayRef<RemappedFile> RemappedFiles,
2076 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
2081 assert(FileMgr && "FileMgr is null on Reparse call");
2082 VFS = FileMgr->getVirtualFileSystem();
2085 clearFileLevelDecls();
2087 SimpleTimer ParsingTimer(WantTiming);
2088 ParsingTimer.setOutput("Reparsing " + getMainFileName());
2091 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
2092 for (const auto &RB : PPOpts.RemappedFileBuffers)
2095 Invocation->getPreprocessorOpts().clearRemappedFiles();
2096 for (const auto &RemappedFile : RemappedFiles) {
2097 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
2098 RemappedFile.second);
2101 // If we have a preamble file lying around, or if we might try to
2102 // build a precompiled preamble, do so now.
2103 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
2104 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
2105 OverrideMainBuffer =
2106 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS);
2109 // Clear out the diagnostics state.
2111 getDiagnostics().Reset();
2112 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
2113 if (OverrideMainBuffer)
2114 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
2116 // Parse the sources
2118 Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS);
2120 // If we're caching global code-completion results, and the top-level
2121 // declarations have changed, clear out the code-completion cache.
2122 if (!Result && ShouldCacheCodeCompletionResults &&
2123 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2124 CacheCodeCompletionResults();
2126 // We now need to clear out the completion info related to this translation
2127 // unit; it'll be recreated if necessary.
2133 void ASTUnit::ResetForParse() {
2134 SavedMainFileBuffer.reset();
2142 TopLevelDecls.clear();
2143 clearFileLevelDecls();
2146 //----------------------------------------------------------------------------//
2148 //----------------------------------------------------------------------------//
2151 /// \brief Code completion consumer that combines the cached code-completion
2152 /// results from an ASTUnit with the code-completion results provided to it,
2153 /// then passes the result on to
2154 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
2155 uint64_t NormalContexts;
2157 CodeCompleteConsumer &Next;
2160 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
2161 const CodeCompleteOptions &CodeCompleteOpts)
2162 : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
2163 AST(AST), Next(Next)
2165 // Compute the set of contexts in which we will look when we don't have
2166 // any information about the specific context.
2168 = (1LL << CodeCompletionContext::CCC_TopLevel)
2169 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
2170 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
2171 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
2172 | (1LL << CodeCompletionContext::CCC_Statement)
2173 | (1LL << CodeCompletionContext::CCC_Expression)
2174 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
2175 | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
2176 | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
2177 | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
2178 | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
2179 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
2180 | (1LL << CodeCompletionContext::CCC_Recovery);
2182 if (AST.getASTContext().getLangOpts().CPlusPlus)
2183 NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
2184 | (1LL << CodeCompletionContext::CCC_UnionTag)
2185 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
2188 void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
2189 CodeCompletionResult *Results,
2190 unsigned NumResults) override;
2192 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2193 OverloadCandidate *Candidates,
2194 unsigned NumCandidates) override {
2195 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2198 CodeCompletionAllocator &getAllocator() override {
2199 return Next.getAllocator();
2202 CodeCompletionTUInfo &getCodeCompletionTUInfo() override {
2203 return Next.getCodeCompletionTUInfo();
2206 } // anonymous namespace
2208 /// \brief Helper function that computes which global names are hidden by the
2209 /// local code-completion results.
2210 static void CalculateHiddenNames(const CodeCompletionContext &Context,
2211 CodeCompletionResult *Results,
2212 unsigned NumResults,
2214 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
2215 bool OnlyTagNames = false;
2216 switch (Context.getKind()) {
2217 case CodeCompletionContext::CCC_Recovery:
2218 case CodeCompletionContext::CCC_TopLevel:
2219 case CodeCompletionContext::CCC_ObjCInterface:
2220 case CodeCompletionContext::CCC_ObjCImplementation:
2221 case CodeCompletionContext::CCC_ObjCIvarList:
2222 case CodeCompletionContext::CCC_ClassStructUnion:
2223 case CodeCompletionContext::CCC_Statement:
2224 case CodeCompletionContext::CCC_Expression:
2225 case CodeCompletionContext::CCC_ObjCMessageReceiver:
2226 case CodeCompletionContext::CCC_DotMemberAccess:
2227 case CodeCompletionContext::CCC_ArrowMemberAccess:
2228 case CodeCompletionContext::CCC_ObjCPropertyAccess:
2229 case CodeCompletionContext::CCC_Namespace:
2230 case CodeCompletionContext::CCC_Type:
2231 case CodeCompletionContext::CCC_Name:
2232 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
2233 case CodeCompletionContext::CCC_ParenthesizedExpression:
2234 case CodeCompletionContext::CCC_ObjCInterfaceName:
2237 case CodeCompletionContext::CCC_EnumTag:
2238 case CodeCompletionContext::CCC_UnionTag:
2239 case CodeCompletionContext::CCC_ClassOrStructTag:
2240 OnlyTagNames = true;
2243 case CodeCompletionContext::CCC_ObjCProtocolName:
2244 case CodeCompletionContext::CCC_MacroName:
2245 case CodeCompletionContext::CCC_MacroNameUse:
2246 case CodeCompletionContext::CCC_PreprocessorExpression:
2247 case CodeCompletionContext::CCC_PreprocessorDirective:
2248 case CodeCompletionContext::CCC_NaturalLanguage:
2249 case CodeCompletionContext::CCC_SelectorName:
2250 case CodeCompletionContext::CCC_TypeQualifiers:
2251 case CodeCompletionContext::CCC_Other:
2252 case CodeCompletionContext::CCC_OtherWithMacros:
2253 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2254 case CodeCompletionContext::CCC_ObjCClassMessage:
2255 case CodeCompletionContext::CCC_ObjCCategoryName:
2256 // We're looking for nothing, or we're looking for names that cannot
2261 typedef CodeCompletionResult Result;
2262 for (unsigned I = 0; I != NumResults; ++I) {
2263 if (Results[I].Kind != Result::RK_Declaration)
2267 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2269 bool Hiding = false;
2271 Hiding = (IDNS & Decl::IDNS_Tag);
2273 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
2274 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2275 Decl::IDNS_NonMemberOperator);
2276 if (Ctx.getLangOpts().CPlusPlus)
2277 HiddenIDNS |= Decl::IDNS_Tag;
2278 Hiding = (IDNS & HiddenIDNS);
2284 DeclarationName Name = Results[I].Declaration->getDeclName();
2285 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2286 HiddenNames.insert(Identifier->getName());
2288 HiddenNames.insert(Name.getAsString());
2292 void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2293 CodeCompletionContext Context,
2294 CodeCompletionResult *Results,
2295 unsigned NumResults) {
2296 // Merge the results we were given with the results we cached.
2297 bool AddedResult = false;
2298 uint64_t InContexts =
2299 Context.getKind() == CodeCompletionContext::CCC_Recovery
2300 ? NormalContexts : (1LL << Context.getKind());
2301 // Contains the set of names that are hidden by "local" completion results.
2302 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
2303 typedef CodeCompletionResult Result;
2304 SmallVector<Result, 8> AllResults;
2305 for (ASTUnit::cached_completion_iterator
2306 C = AST.cached_completion_begin(),
2307 CEnd = AST.cached_completion_end();
2309 // If the context we are in matches any of the contexts we are
2310 // interested in, we'll add this result.
2311 if ((C->ShowInContexts & InContexts) == 0)
2314 // If we haven't added any results previously, do so now.
2316 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2318 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2322 // Determine whether this global completion result is hidden by a local
2323 // completion result. If so, skip it.
2324 if (C->Kind != CXCursor_MacroDefinition &&
2325 HiddenNames.count(C->Completion->getTypedText()))
2328 // Adjust priority based on similar type classes.
2329 unsigned Priority = C->Priority;
2330 CodeCompletionString *Completion = C->Completion;
2331 if (!Context.getPreferredType().isNull()) {
2332 if (C->Kind == CXCursor_MacroDefinition) {
2333 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
2335 Context.getPreferredType()->isAnyPointerType());
2336 } else if (C->Type) {
2337 CanQualType Expected
2338 = S.Context.getCanonicalType(
2339 Context.getPreferredType().getUnqualifiedType());
2340 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2341 if (ExpectedSTC == C->TypeClass) {
2342 // We know this type is similar; check for an exact match.
2343 llvm::StringMap<unsigned> &CachedCompletionTypes
2344 = AST.getCachedCompletionTypes();
2345 llvm::StringMap<unsigned>::iterator Pos
2346 = CachedCompletionTypes.find(QualType(Expected).getAsString());
2347 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2348 Priority /= CCF_ExactTypeMatch;
2350 Priority /= CCF_SimilarTypeMatch;
2355 // Adjust the completion string, if required.
2356 if (C->Kind == CXCursor_MacroDefinition &&
2357 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2358 // Create a new code-completion string that just contains the
2359 // macro name, without its arguments.
2360 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2361 CCP_CodePattern, C->Availability);
2362 Builder.AddTypedTextChunk(C->Completion->getTypedText());
2363 Priority = CCP_CodePattern;
2364 Completion = Builder.TakeString();
2367 AllResults.push_back(Result(Completion, Priority, C->Kind,
2371 // If we did not add any cached completion results, just forward the
2372 // results we were given to the next consumer.
2374 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2378 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2382 void ASTUnit::CodeComplete(
2383 StringRef File, unsigned Line, unsigned Column,
2384 ArrayRef<RemappedFile> RemappedFiles, bool IncludeMacros,
2385 bool IncludeCodePatterns, bool IncludeBriefComments,
2386 CodeCompleteConsumer &Consumer,
2387 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
2388 DiagnosticsEngine &Diag, LangOptions &LangOpts, SourceManager &SourceMgr,
2389 FileManager &FileMgr, SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2390 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
2394 SimpleTimer CompletionTimer(WantTiming);
2395 CompletionTimer.setOutput("Code completion @ " + File + ":" +
2396 Twine(Line) + ":" + Twine(Column));
2398 auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation);
2400 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
2401 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
2402 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
2404 CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2405 CachedCompletionResults.empty();
2406 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2407 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2408 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2410 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2412 FrontendOpts.CodeCompletionAt.FileName = File;
2413 FrontendOpts.CodeCompletionAt.Line = Line;
2414 FrontendOpts.CodeCompletionAt.Column = Column;
2416 // Set the language options appropriately.
2417 LangOpts = *CCInvocation->getLangOpts();
2419 // Spell-checking and warnings are wasteful during code-completion.
2420 LangOpts.SpellChecking = false;
2421 CCInvocation->getDiagnosticOpts().IgnoreWarnings = true;
2423 std::unique_ptr<CompilerInstance> Clang(
2424 new CompilerInstance(PCHContainerOps));
2426 // Recover resources if we crash before exiting this method.
2427 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2428 CICleanup(Clang.get());
2430 auto &Inv = *CCInvocation;
2431 Clang->setInvocation(std::move(CCInvocation));
2432 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
2434 // Set up diagnostics, capturing any diagnostics produced.
2435 Clang->setDiagnostics(&Diag);
2436 CaptureDroppedDiagnostics Capture(true,
2437 Clang->getDiagnostics(),
2439 ProcessWarningOptions(Diag, Inv.getDiagnosticOpts());
2441 // Create the target instance.
2442 Clang->setTarget(TargetInfo::CreateTargetInfo(
2443 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
2444 if (!Clang->hasTarget()) {
2445 Clang->setInvocation(nullptr);
2449 // Inform the target of the language options.
2451 // FIXME: We shouldn't need to do this, the target should be immutable once
2452 // created. This complexity should be lifted elsewhere.
2453 Clang->getTarget().adjust(Clang->getLangOpts());
2455 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
2456 "Invocation must have exactly one source file!");
2457 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
2458 InputKind::Source &&
2459 "FIXME: AST inputs not yet supported here!");
2460 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
2461 InputKind::LLVM_IR &&
2462 "IR inputs not support here!");
2464 // Use the source and file managers that we were given.
2465 Clang->setFileManager(&FileMgr);
2466 Clang->setSourceManager(&SourceMgr);
2469 PreprocessorOpts.clearRemappedFiles();
2470 PreprocessorOpts.RetainRemappedFileBuffers = true;
2471 for (const auto &RemappedFile : RemappedFiles) {
2472 PreprocessorOpts.addRemappedFile(RemappedFile.first, RemappedFile.second);
2473 OwnedBuffers.push_back(RemappedFile.second);
2476 // Use the code completion consumer we were given, but adding any cached
2477 // code-completion results.
2478 AugmentedCodeCompleteConsumer *AugmentedConsumer
2479 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
2480 Clang->setCodeCompletionConsumer(AugmentedConsumer);
2482 // If we have a precompiled preamble, try to use it. We only allow
2483 // the use of the precompiled preamble if we're if the completion
2484 // point is within the main file, after the end of the precompiled
2486 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
2487 if (!getPreambleFile(this).empty()) {
2488 std::string CompleteFilePath(File);
2490 auto VFS = FileMgr.getVirtualFileSystem();
2491 auto CompleteFileStatus = VFS->status(CompleteFilePath);
2492 if (CompleteFileStatus) {
2493 llvm::sys::fs::UniqueID CompleteFileID = CompleteFileStatus->getUniqueID();
2495 std::string MainPath(OriginalSourceFile);
2496 auto MainStatus = VFS->status(MainPath);
2498 llvm::sys::fs::UniqueID MainID = MainStatus->getUniqueID();
2499 if (CompleteFileID == MainID && Line > 1)
2500 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(
2501 PCHContainerOps, Inv, VFS, false, Line - 1);
2506 // If the main file has been overridden due to the use of a preamble,
2507 // make that override happen and introduce the preamble.
2508 if (OverrideMainBuffer) {
2509 PreprocessorOpts.addRemappedFile(OriginalSourceFile,
2510 OverrideMainBuffer.get());
2511 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2512 PreprocessorOpts.PrecompiledPreambleBytes.second
2513 = PreambleEndsAtStartOfLine;
2514 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
2515 PreprocessorOpts.DisablePCHValidation = true;
2517 OwnedBuffers.push_back(OverrideMainBuffer.release());
2519 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2520 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
2523 // Disable the preprocessing record if modules are not enabled.
2524 if (!Clang->getLangOpts().Modules)
2525 PreprocessorOpts.DetailedRecord = false;
2527 std::unique_ptr<SyntaxOnlyAction> Act;
2528 Act.reset(new SyntaxOnlyAction);
2529 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
2531 Act->EndSourceFile();
2535 bool ASTUnit::Save(StringRef File) {
2536 if (HadModuleLoaderFatalFailure)
2539 // Write to a temporary file and later rename it to the actual file, to avoid
2540 // possible race conditions.
2541 SmallString<128> TempPath;
2543 TempPath += "-%%%%%%%%";
2545 if (llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath))
2548 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2549 // unconditionally create a stat cache when we parse the file?
2550 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
2554 if (Out.has_error()) {
2559 if (llvm::sys::fs::rename(TempPath, File)) {
2560 llvm::sys::fs::remove(TempPath);
2567 static bool serializeUnit(ASTWriter &Writer,
2568 SmallVectorImpl<char> &Buffer,
2572 Writer.WriteAST(S, std::string(), nullptr, "", hasErrors);
2574 // Write the generated bitstream to "Out".
2575 if (!Buffer.empty())
2576 OS.write(Buffer.data(), Buffer.size());
2581 bool ASTUnit::serialize(raw_ostream &OS) {
2582 // For serialization we are lenient if the errors were only warn-as-error kind.
2583 bool hasErrors = getDiagnostics().hasUncompilableErrorOccurred();
2586 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2587 getSema(), hasErrors, OS);
2589 SmallString<128> Buffer;
2590 llvm::BitstreamWriter Stream(Buffer);
2591 MemoryBufferCache PCMCache;
2592 ASTWriter Writer(Stream, Buffer, PCMCache, {});
2593 return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
2596 typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2598 void ASTUnit::TranslateStoredDiagnostics(
2599 FileManager &FileMgr,
2600 SourceManager &SrcMgr,
2601 const SmallVectorImpl<StandaloneDiagnostic> &Diags,
2602 SmallVectorImpl<StoredDiagnostic> &Out) {
2603 // Map the standalone diagnostic into the new source manager. We also need to
2604 // remap all the locations to the new view. This includes the diag location,
2605 // any associated source ranges, and the source ranges of associated fix-its.
2606 // FIXME: There should be a cleaner way to do this.
2607 SmallVector<StoredDiagnostic, 4> Result;
2608 Result.reserve(Diags.size());
2610 for (const StandaloneDiagnostic &SD : Diags) {
2611 // Rebuild the StoredDiagnostic.
2612 if (SD.Filename.empty())
2614 const FileEntry *FE = FileMgr.getFile(SD.Filename);
2617 SourceLocation FileLoc;
2618 auto ItFileID = PreambleSrcLocCache.find(SD.Filename);
2619 if (ItFileID == PreambleSrcLocCache.end()) {
2620 FileID FID = SrcMgr.translateFile(FE);
2621 FileLoc = SrcMgr.getLocForStartOfFile(FID);
2622 PreambleSrcLocCache[SD.Filename] = FileLoc;
2624 FileLoc = ItFileID->getValue();
2627 if (FileLoc.isInvalid())
2629 SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset);
2630 FullSourceLoc Loc(L, SrcMgr);
2632 SmallVector<CharSourceRange, 4> Ranges;
2633 Ranges.reserve(SD.Ranges.size());
2634 for (const auto &Range : SD.Ranges) {
2635 SourceLocation BL = FileLoc.getLocWithOffset(Range.first);
2636 SourceLocation EL = FileLoc.getLocWithOffset(Range.second);
2637 Ranges.push_back(CharSourceRange::getCharRange(BL, EL));
2640 SmallVector<FixItHint, 2> FixIts;
2641 FixIts.reserve(SD.FixIts.size());
2642 for (const StandaloneFixIt &FixIt : SD.FixIts) {
2643 FixIts.push_back(FixItHint());
2644 FixItHint &FH = FixIts.back();
2645 FH.CodeToInsert = FixIt.CodeToInsert;
2646 SourceLocation BL = FileLoc.getLocWithOffset(FixIt.RemoveRange.first);
2647 SourceLocation EL = FileLoc.getLocWithOffset(FixIt.RemoveRange.second);
2648 FH.RemoveRange = CharSourceRange::getCharRange(BL, EL);
2651 Result.push_back(StoredDiagnostic(SD.Level, SD.ID,
2652 SD.Message, Loc, Ranges, FixIts));
2657 void ASTUnit::addFileLevelDecl(Decl *D) {
2660 // We only care about local declarations.
2661 if (D->isFromASTFile())
2664 SourceManager &SM = *SourceMgr;
2665 SourceLocation Loc = D->getLocation();
2666 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2669 // We only keep track of the file-level declarations of each file.
2670 if (!D->getLexicalDeclContext()->isFileContext())
2673 SourceLocation FileLoc = SM.getFileLoc(Loc);
2674 assert(SM.isLocalSourceLocation(FileLoc));
2677 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
2678 if (FID.isInvalid())
2681 LocDeclsTy *&Decls = FileDecls[FID];
2683 Decls = new LocDeclsTy();
2685 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2687 if (Decls->empty() || Decls->back().first <= Offset) {
2688 Decls->push_back(LocDecl);
2692 LocDeclsTy::iterator I = std::upper_bound(Decls->begin(), Decls->end(),
2693 LocDecl, llvm::less_first());
2695 Decls->insert(I, LocDecl);
2698 void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2699 SmallVectorImpl<Decl *> &Decls) {
2700 if (File.isInvalid())
2703 if (SourceMgr->isLoadedFileID(File)) {
2704 assert(Ctx->getExternalSource() && "No external source!");
2705 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2709 FileDeclsTy::iterator I = FileDecls.find(File);
2710 if (I == FileDecls.end())
2713 LocDeclsTy &LocDecls = *I->second;
2714 if (LocDecls.empty())
2717 LocDeclsTy::iterator BeginIt =
2718 std::lower_bound(LocDecls.begin(), LocDecls.end(),
2719 std::make_pair(Offset, (Decl *)nullptr),
2720 llvm::less_first());
2721 if (BeginIt != LocDecls.begin())
2724 // If we are pointing at a top-level decl inside an objc container, we need
2725 // to backtrack until we find it otherwise we will fail to report that the
2726 // region overlaps with an objc container.
2727 while (BeginIt != LocDecls.begin() &&
2728 BeginIt->second->isTopLevelDeclInObjCContainer())
2731 LocDeclsTy::iterator EndIt = std::upper_bound(
2732 LocDecls.begin(), LocDecls.end(),
2733 std::make_pair(Offset + Length, (Decl *)nullptr), llvm::less_first());
2734 if (EndIt != LocDecls.end())
2737 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2738 Decls.push_back(DIt->second);
2741 SourceLocation ASTUnit::getLocation(const FileEntry *File,
2742 unsigned Line, unsigned Col) const {
2743 const SourceManager &SM = getSourceManager();
2744 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
2745 return SM.getMacroArgExpandedLocation(Loc);
2748 SourceLocation ASTUnit::getLocation(const FileEntry *File,
2749 unsigned Offset) const {
2750 const SourceManager &SM = getSourceManager();
2751 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
2752 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2755 /// \brief If \arg Loc is a loaded location from the preamble, returns
2756 /// the corresponding local location of the main file, otherwise it returns
2758 SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2761 PreambleID = SourceMgr->getPreambleFileID();
2763 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2767 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2768 SourceLocation FileLoc
2769 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2770 return FileLoc.getLocWithOffset(Offs);
2776 /// \brief If \arg Loc is a local location of the main file but inside the
2777 /// preamble chunk, returns the corresponding loaded location from the
2778 /// preamble, otherwise it returns \arg Loc.
2779 SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2782 PreambleID = SourceMgr->getPreambleFileID();
2784 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2788 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2789 Offs < Preamble.size()) {
2790 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2791 return FileLoc.getLocWithOffset(Offs);
2797 bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2800 FID = SourceMgr->getPreambleFileID();
2802 if (Loc.isInvalid() || FID.isInvalid())
2805 return SourceMgr->isInFileID(Loc, FID);
2808 bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2811 FID = SourceMgr->getMainFileID();
2813 if (Loc.isInvalid() || FID.isInvalid())
2816 return SourceMgr->isInFileID(Loc, FID);
2819 SourceLocation ASTUnit::getEndOfPreambleFileID() {
2822 FID = SourceMgr->getPreambleFileID();
2824 if (FID.isInvalid())
2825 return SourceLocation();
2827 return SourceMgr->getLocForEndOfFile(FID);
2830 SourceLocation ASTUnit::getStartOfMainFileID() {
2833 FID = SourceMgr->getMainFileID();
2835 if (FID.isInvalid())
2836 return SourceLocation();
2838 return SourceMgr->getLocForStartOfFile(FID);
2841 llvm::iterator_range<PreprocessingRecord::iterator>
2842 ASTUnit::getLocalPreprocessingEntities() const {
2843 if (isMainFileAST()) {
2844 serialization::ModuleFile &
2845 Mod = Reader->getModuleManager().getPrimaryModule();
2846 return Reader->getModulePreprocessedEntities(Mod);
2849 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
2850 return llvm::make_range(PPRec->local_begin(), PPRec->local_end());
2852 return llvm::make_range(PreprocessingRecord::iterator(),
2853 PreprocessingRecord::iterator());
2856 bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
2857 if (isMainFileAST()) {
2858 serialization::ModuleFile &
2859 Mod = Reader->getModuleManager().getPrimaryModule();
2860 for (const Decl *D : Reader->getModuleFileLevelDecls(Mod)) {
2861 if (!Fn(context, D))
2868 for (ASTUnit::top_level_iterator TL = top_level_begin(),
2869 TLEnd = top_level_end();
2870 TL != TLEnd; ++TL) {
2871 if (!Fn(context, *TL))
2878 const FileEntry *ASTUnit::getPCHFile() {
2882 serialization::ModuleFile *Mod = nullptr;
2883 Reader->getModuleManager().visit([&Mod](serialization::ModuleFile &M) {
2885 case serialization::MK_ImplicitModule:
2886 case serialization::MK_ExplicitModule:
2887 case serialization::MK_PrebuiltModule:
2888 return true; // skip dependencies.
2889 case serialization::MK_PCH:
2891 return true; // found it.
2892 case serialization::MK_Preamble:
2893 return false; // look in dependencies.
2894 case serialization::MK_MainFile:
2895 return false; // look in dependencies.
2906 bool ASTUnit::isModuleFile() {
2907 return isMainFileAST() && getLangOpts().isCompilingModule();
2910 InputKind ASTUnit::getInputKind() const {
2911 auto &LangOpts = getLangOpts();
2913 InputKind::Language Lang;
2914 if (LangOpts.OpenCL)
2915 Lang = InputKind::OpenCL;
2916 else if (LangOpts.CUDA)
2917 Lang = InputKind::CUDA;
2918 else if (LangOpts.RenderScript)
2919 Lang = InputKind::RenderScript;
2920 else if (LangOpts.CPlusPlus)
2921 Lang = LangOpts.ObjC1 ? InputKind::ObjCXX : InputKind::CXX;
2923 Lang = LangOpts.ObjC1 ? InputKind::ObjC : InputKind::C;
2925 InputKind::Format Fmt = InputKind::Source;
2926 if (LangOpts.getCompilingModule() == LangOptions::CMK_ModuleMap)
2927 Fmt = InputKind::ModuleMap;
2929 // We don't know if input was preprocessed. Assume not.
2932 return InputKind(Lang, Fmt, PP);
2935 void ASTUnit::PreambleData::countLines() const {
2940 NumLines = std::count(Buffer.begin(), Buffer.end(), '\n');
2942 if (Buffer.back() != '\n')
2947 ASTUnit::ConcurrencyState::ConcurrencyState() {
2948 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2951 ASTUnit::ConcurrencyState::~ConcurrencyState() {
2952 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2955 void ASTUnit::ConcurrencyState::start() {
2956 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2957 assert(acquired && "Concurrent access to ASTUnit!");
2960 void ASTUnit::ConcurrencyState::finish() {
2961 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2966 ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex = nullptr; }
2967 ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2968 void ASTUnit::ConcurrencyState::start() {}
2969 void ASTUnit::ConcurrencyState::finish() {}