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 LangOptions &LangOpt;
490 std::shared_ptr<TargetOptions> &TargetOpts;
491 IntrusiveRefCntPtr<TargetInfo> &Target;
494 bool InitializedLanguage;
496 ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
497 std::shared_ptr<TargetOptions> &TargetOpts,
498 IntrusiveRefCntPtr<TargetInfo> &Target, unsigned &Counter)
499 : PP(PP), Context(Context), LangOpt(LangOpt), TargetOpts(TargetOpts),
500 Target(Target), Counter(Counter), InitializedLanguage(false) {}
502 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
503 bool AllowCompatibleDifferences) override {
504 if (InitializedLanguage)
508 InitializedLanguage = true;
514 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
515 bool AllowCompatibleDifferences) override {
516 // If we've already initialized the target, don't do it again.
520 this->TargetOpts = std::make_shared<TargetOptions>(TargetOpts);
522 TargetInfo::CreateTargetInfo(PP.getDiagnostics(), this->TargetOpts);
528 void ReadCounter(const serialization::ModuleFile &M,
529 unsigned Value) override {
535 if (!Target || !InitializedLanguage)
538 // Inform the target of the language options.
540 // FIXME: We shouldn't need to do this, the target should be immutable once
541 // created. This complexity should be lifted elsewhere.
542 Target->adjust(LangOpt);
544 // Initialize the preprocessor.
545 PP.Initialize(*Target);
547 // Initialize the ASTContext
548 Context.InitBuiltinTypes(*Target);
550 // We didn't have access to the comment options when the ASTContext was
551 // constructed, so register them now.
552 Context.getCommentCommandTraits().registerCommentOptions(
553 LangOpt.CommentOpts);
557 /// \brief Diagnostic consumer that saves each diagnostic it is given.
558 class StoredDiagnosticConsumer : public DiagnosticConsumer {
559 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
560 SourceManager *SourceMgr;
563 explicit StoredDiagnosticConsumer(
564 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
565 : StoredDiags(StoredDiags), SourceMgr(nullptr) {}
567 void BeginSourceFile(const LangOptions &LangOpts,
568 const Preprocessor *PP = nullptr) override {
570 SourceMgr = &PP->getSourceManager();
573 void HandleDiagnostic(DiagnosticsEngine::Level Level,
574 const Diagnostic &Info) override;
577 /// \brief RAII object that optionally captures diagnostics, if
578 /// there is no diagnostic client to capture them already.
579 class CaptureDroppedDiagnostics {
580 DiagnosticsEngine &Diags;
581 StoredDiagnosticConsumer Client;
582 DiagnosticConsumer *PreviousClient;
583 std::unique_ptr<DiagnosticConsumer> OwningPreviousClient;
586 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
587 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
588 : Diags(Diags), Client(StoredDiags), PreviousClient(nullptr)
590 if (RequestCapture || Diags.getClient() == nullptr) {
591 OwningPreviousClient = Diags.takeClient();
592 PreviousClient = Diags.getClient();
593 Diags.setClient(&Client, false);
597 ~CaptureDroppedDiagnostics() {
598 if (Diags.getClient() == &Client)
599 Diags.setClient(PreviousClient, !!OwningPreviousClient.release());
603 } // anonymous namespace
605 void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
606 const Diagnostic &Info) {
607 // Default implementation (Warnings/errors count).
608 DiagnosticConsumer::HandleDiagnostic(Level, Info);
610 // Only record the diagnostic if it's part of the source manager we know
611 // about. This effectively drops diagnostics from modules we're building.
612 // FIXME: In the long run, ee don't want to drop source managers from modules.
613 if (!Info.hasSourceManager() || &Info.getSourceManager() == SourceMgr)
614 StoredDiags.emplace_back(Level, Info);
617 IntrusiveRefCntPtr<ASTReader> ASTUnit::getASTReader() const {
621 ASTMutationListener *ASTUnit::getASTMutationListener() {
623 return &WriterData->Writer;
627 ASTDeserializationListener *ASTUnit::getDeserializationListener() {
629 return &WriterData->Writer;
633 std::unique_ptr<llvm::MemoryBuffer>
634 ASTUnit::getBufferForFile(StringRef Filename, std::string *ErrorStr) {
636 auto Buffer = FileMgr->getBufferForFile(Filename);
638 return std::move(*Buffer);
640 *ErrorStr = Buffer.getError().message();
644 /// \brief Configure the diagnostics object for use with ASTUnit.
645 void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
646 ASTUnit &AST, bool CaptureDiagnostics) {
647 assert(Diags.get() && "no DiagnosticsEngine was provided");
648 if (CaptureDiagnostics)
649 Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
652 std::unique_ptr<ASTUnit> ASTUnit::LoadFromASTFile(
653 const std::string &Filename, const PCHContainerReader &PCHContainerRdr,
654 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
655 const FileSystemOptions &FileSystemOpts, bool UseDebugInfo,
656 bool OnlyLocalDecls, ArrayRef<RemappedFile> RemappedFiles,
657 bool CaptureDiagnostics, bool AllowPCHWithCompilerErrors,
658 bool UserFilesAreVolatile) {
659 std::unique_ptr<ASTUnit> AST(new ASTUnit(true));
661 // Recover resources if we crash before exiting this method.
662 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
663 ASTUnitCleanup(AST.get());
664 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
665 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
666 DiagCleanup(Diags.get());
668 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
670 AST->OnlyLocalDecls = OnlyLocalDecls;
671 AST->CaptureDiagnostics = CaptureDiagnostics;
672 AST->Diagnostics = Diags;
673 IntrusiveRefCntPtr<vfs::FileSystem> VFS = vfs::getRealFileSystem();
674 AST->FileMgr = new FileManager(FileSystemOpts, VFS);
675 AST->UserFilesAreVolatile = UserFilesAreVolatile;
676 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
677 AST->getFileManager(),
678 UserFilesAreVolatile);
679 AST->PCMCache = new MemoryBufferCache;
680 AST->HSOpts = std::make_shared<HeaderSearchOptions>();
681 AST->HSOpts->ModuleFormat = PCHContainerRdr.getFormat();
682 AST->HeaderInfo.reset(new HeaderSearch(AST->HSOpts,
683 AST->getSourceManager(),
684 AST->getDiagnostics(),
685 AST->ASTFileLangOpts,
686 /*Target=*/nullptr));
688 auto PPOpts = std::make_shared<PreprocessorOptions>();
690 for (const auto &RemappedFile : RemappedFiles)
691 PPOpts->addRemappedFile(RemappedFile.first, RemappedFile.second);
693 // Gather Info for preprocessor construction later on.
695 HeaderSearch &HeaderInfo = *AST->HeaderInfo;
698 AST->PP = std::make_shared<Preprocessor>(
699 std::move(PPOpts), AST->getDiagnostics(), AST->ASTFileLangOpts,
700 AST->getSourceManager(), *AST->PCMCache, HeaderInfo, *AST,
701 /*IILookup=*/nullptr,
702 /*OwnsHeaderSearch=*/false);
703 Preprocessor &PP = *AST->PP;
705 AST->Ctx = new ASTContext(AST->ASTFileLangOpts, AST->getSourceManager(),
706 PP.getIdentifierTable(), PP.getSelectorTable(),
707 PP.getBuiltinInfo());
708 ASTContext &Context = *AST->Ctx;
710 bool disableValid = false;
711 if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
713 AST->Reader = new ASTReader(PP, Context, PCHContainerRdr, { },
715 /*DisableValidation=*/disableValid,
716 AllowPCHWithCompilerErrors);
718 AST->Reader->setListener(llvm::make_unique<ASTInfoCollector>(
719 *AST->PP, Context, AST->ASTFileLangOpts, AST->TargetOpts, AST->Target,
722 // Attach the AST reader to the AST context as an external AST
723 // source, so that declarations will be deserialized from the
724 // AST file as needed.
725 // We need the external source to be set up before we read the AST, because
726 // eagerly-deserialized declarations may use it.
727 Context.setExternalSource(AST->Reader);
729 switch (AST->Reader->ReadAST(Filename, serialization::MK_MainFile,
730 SourceLocation(), ASTReader::ARR_None)) {
731 case ASTReader::Success:
734 case ASTReader::Failure:
735 case ASTReader::Missing:
736 case ASTReader::OutOfDate:
737 case ASTReader::VersionMismatch:
738 case ASTReader::ConfigurationMismatch:
739 case ASTReader::HadErrors:
740 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
744 AST->OriginalSourceFile = AST->Reader->getOriginalSourceFile();
746 PP.setCounterValue(Counter);
748 // Create an AST consumer, even though it isn't used.
749 AST->Consumer.reset(new ASTConsumer);
751 // Create a semantic analysis object and tell the AST reader about it.
752 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
753 AST->TheSema->Initialize();
754 AST->Reader->InitializeSema(*AST->TheSema);
756 // Tell the diagnostic client that we have started a source file.
757 AST->getDiagnostics().getClient()->BeginSourceFile(Context.getLangOpts(),&PP);
764 /// \brief Preprocessor callback class that updates a hash value with the names
765 /// of all macros that have been defined by the translation unit.
766 class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
770 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
772 void MacroDefined(const Token &MacroNameTok,
773 const MacroDirective *MD) override {
774 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
778 /// \brief Add the given declaration to the hash of all top-level entities.
779 void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
783 DeclContext *DC = D->getDeclContext();
787 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
790 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
791 if (EnumDecl *EnumD = dyn_cast<EnumDecl>(D)) {
792 // For an unscoped enum include the enumerators in the hash since they
793 // enter the top-level namespace.
794 if (!EnumD->isScoped()) {
795 for (const auto *EI : EnumD->enumerators()) {
796 if (EI->getIdentifier())
797 Hash = llvm::HashString(EI->getIdentifier()->getName(), Hash);
802 if (ND->getIdentifier())
803 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
804 else if (DeclarationName Name = ND->getDeclName()) {
805 std::string NameStr = Name.getAsString();
806 Hash = llvm::HashString(NameStr, Hash);
811 if (ImportDecl *ImportD = dyn_cast<ImportDecl>(D)) {
812 if (Module *Mod = ImportD->getImportedModule()) {
813 std::string ModName = Mod->getFullModuleName();
814 Hash = llvm::HashString(ModName, Hash);
820 class TopLevelDeclTrackerConsumer : public ASTConsumer {
825 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
826 : Unit(_Unit), Hash(Hash) {
830 void handleTopLevelDecl(Decl *D) {
834 // FIXME: Currently ObjC method declarations are incorrectly being
835 // reported as top-level declarations, even though their DeclContext
836 // is the containing ObjC @interface/@implementation. This is a
837 // fundamental problem in the parser right now.
838 if (isa<ObjCMethodDecl>(D))
841 AddTopLevelDeclarationToHash(D, Hash);
842 Unit.addTopLevelDecl(D);
844 handleFileLevelDecl(D);
847 void handleFileLevelDecl(Decl *D) {
848 Unit.addFileLevelDecl(D);
849 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
850 for (auto *I : NSD->decls())
851 handleFileLevelDecl(I);
855 bool HandleTopLevelDecl(DeclGroupRef D) override {
856 for (Decl *TopLevelDecl : D)
857 handleTopLevelDecl(TopLevelDecl);
861 // We're not interested in "interesting" decls.
862 void HandleInterestingDecl(DeclGroupRef) override {}
864 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
865 for (Decl *TopLevelDecl : D)
866 handleTopLevelDecl(TopLevelDecl);
869 ASTMutationListener *GetASTMutationListener() override {
870 return Unit.getASTMutationListener();
873 ASTDeserializationListener *GetASTDeserializationListener() override {
874 return Unit.getDeserializationListener();
878 class TopLevelDeclTrackerAction : public ASTFrontendAction {
882 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
883 StringRef InFile) override {
884 CI.getPreprocessor().addPPCallbacks(
885 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
886 Unit.getCurrentTopLevelHashValue()));
887 return llvm::make_unique<TopLevelDeclTrackerConsumer>(
888 Unit, Unit.getCurrentTopLevelHashValue());
892 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
894 bool hasCodeCompletionSupport() const override { return false; }
895 TranslationUnitKind getTranslationUnitKind() override {
896 return Unit.getTranslationUnitKind();
900 class PrecompilePreambleAction : public ASTFrontendAction {
902 bool HasEmittedPreamblePCH;
905 explicit PrecompilePreambleAction(ASTUnit &Unit)
906 : Unit(Unit), HasEmittedPreamblePCH(false) {}
908 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
909 StringRef InFile) override;
910 bool hasEmittedPreamblePCH() const { return HasEmittedPreamblePCH; }
911 void setHasEmittedPreamblePCH() { HasEmittedPreamblePCH = true; }
912 bool shouldEraseOutputFiles() override { return !hasEmittedPreamblePCH(); }
914 bool hasCodeCompletionSupport() const override { return false; }
915 bool hasASTFileSupport() const override { return false; }
916 TranslationUnitKind getTranslationUnitKind() override { return TU_Prefix; }
919 class PrecompilePreambleConsumer : public PCHGenerator {
922 std::vector<Decl *> TopLevelDecls;
923 PrecompilePreambleAction *Action;
924 std::unique_ptr<raw_ostream> Out;
927 PrecompilePreambleConsumer(ASTUnit &Unit, PrecompilePreambleAction *Action,
928 const Preprocessor &PP, StringRef isysroot,
929 std::unique_ptr<raw_ostream> Out)
930 : PCHGenerator(PP, "", isysroot, std::make_shared<PCHBuffer>(),
931 ArrayRef<std::shared_ptr<ModuleFileExtension>>(),
932 /*AllowASTWithErrors=*/true),
933 Unit(Unit), Hash(Unit.getCurrentTopLevelHashValue()), Action(Action),
934 Out(std::move(Out)) {
938 bool HandleTopLevelDecl(DeclGroupRef DG) override {
940 // FIXME: Currently ObjC method declarations are incorrectly being
941 // reported as top-level declarations, even though their DeclContext
942 // is the containing ObjC @interface/@implementation. This is a
943 // fundamental problem in the parser right now.
944 if (isa<ObjCMethodDecl>(D))
946 AddTopLevelDeclarationToHash(D, Hash);
947 TopLevelDecls.push_back(D);
952 void HandleTranslationUnit(ASTContext &Ctx) override {
953 PCHGenerator::HandleTranslationUnit(Ctx);
954 if (hasEmittedPCH()) {
955 // Write the generated bitstream to "Out".
957 // Make sure it hits disk now.
960 llvm::SmallVector<char, 0> Empty;
961 getPCH() = std::move(Empty);
963 // Translate the top-level declarations we captured during
964 // parsing into declaration IDs in the precompiled
965 // preamble. This will allow us to deserialize those top-level
966 // declarations when requested.
967 for (Decl *D : TopLevelDecls) {
968 // Invalid top-level decls may not have been serialized.
969 if (D->isInvalidDecl())
971 Unit.addTopLevelDeclFromPreamble(getWriter().getDeclID(D));
974 Action->setHasEmittedPreamblePCH();
979 } // anonymous namespace
981 std::unique_ptr<ASTConsumer>
982 PrecompilePreambleAction::CreateASTConsumer(CompilerInstance &CI,
985 std::string OutputFile;
986 std::unique_ptr<raw_ostream> OS =
987 GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
992 if (!CI.getFrontendOpts().RelocatablePCH)
995 CI.getPreprocessor().addPPCallbacks(
996 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
997 Unit.getCurrentTopLevelHashValue()));
998 return llvm::make_unique<PrecompilePreambleConsumer>(
999 Unit, this, CI.getPreprocessor(), Sysroot, std::move(OS));
1002 static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag) {
1003 return StoredDiag.getLocation().isValid();
1007 checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &StoredDiags) {
1008 // Get rid of stored diagnostics except the ones from the driver which do not
1009 // have a source location.
1011 std::remove_if(StoredDiags.begin(), StoredDiags.end(), isNonDriverDiag),
1015 static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
1017 SourceManager &SM) {
1018 // The stored diagnostic has the old source manager in it; update
1019 // the locations to refer into the new source manager. Since we've
1020 // been careful to make sure that the source manager's state
1021 // before and after are identical, so that we can reuse the source
1023 for (StoredDiagnostic &SD : StoredDiagnostics) {
1024 if (SD.getLocation().isValid()) {
1025 FullSourceLoc Loc(SD.getLocation(), SM);
1026 SD.setLocation(Loc);
1031 /// Parse the source file into a translation unit using the given compiler
1032 /// invocation, replacing the current translation unit.
1034 /// \returns True if a failure occurred that causes the ASTUnit not to
1035 /// contain any translation-unit information, false otherwise.
1036 bool ASTUnit::Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1037 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer,
1038 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
1042 // Create the compiler instance to use for building the AST.
1043 std::unique_ptr<CompilerInstance> Clang(
1044 new CompilerInstance(std::move(PCHContainerOps)));
1045 if (FileMgr && VFS) {
1046 assert(VFS == FileMgr->getVirtualFileSystem() &&
1047 "VFS passed to Parse and VFS in FileMgr are different");
1049 Clang->setVirtualFileSystem(VFS);
1052 // Recover resources if we crash before exiting this method.
1053 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1054 CICleanup(Clang.get());
1056 Clang->setInvocation(std::make_shared<CompilerInvocation>(*Invocation));
1057 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1059 // Set up diagnostics, capturing any diagnostics that would
1060 // otherwise be dropped.
1061 Clang->setDiagnostics(&getDiagnostics());
1063 // Create the target instance.
1064 Clang->setTarget(TargetInfo::CreateTargetInfo(
1065 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
1066 if (!Clang->hasTarget())
1069 // Inform the target of the language options.
1071 // FIXME: We shouldn't need to do this, the target should be immutable once
1072 // created. This complexity should be lifted elsewhere.
1073 Clang->getTarget().adjust(Clang->getLangOpts());
1075 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1076 "Invocation must have exactly one source file!");
1077 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1078 InputKind::Source &&
1079 "FIXME: AST inputs not yet supported here!");
1080 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1081 InputKind::LLVM_IR &&
1082 "IR inputs not support here!");
1084 // Configure the various subsystems.
1085 LangOpts = Clang->getInvocation().LangOpts;
1086 FileSystemOpts = Clang->getFileSystemOpts();
1088 Clang->createFileManager();
1089 FileMgr = &Clang->getFileManager();
1094 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1095 UserFilesAreVolatile);
1096 if (!OverrideMainBuffer) {
1097 checkAndRemoveNonDriverDiags(StoredDiagnostics);
1098 TopLevelDeclsInPreamble.clear();
1101 // Create a file manager object to provide access to and cache the filesystem.
1102 Clang->setFileManager(&getFileManager());
1104 // Create the source manager.
1105 Clang->setSourceManager(&getSourceManager());
1107 // If the main file has been overridden due to the use of a preamble,
1108 // make that override happen and introduce the preamble.
1109 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
1110 if (OverrideMainBuffer) {
1111 PreprocessorOpts.addRemappedFile(OriginalSourceFile,
1112 OverrideMainBuffer.get());
1113 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1114 PreprocessorOpts.PrecompiledPreambleBytes.second
1115 = PreambleEndsAtStartOfLine;
1116 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
1117 PreprocessorOpts.DisablePCHValidation = true;
1119 // The stored diagnostic has the old source manager in it; update
1120 // the locations to refer into the new source manager. Since we've
1121 // been careful to make sure that the source manager's state
1122 // before and after are identical, so that we can reuse the source
1124 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
1126 // Keep track of the override buffer;
1127 SavedMainFileBuffer = std::move(OverrideMainBuffer);
1130 std::unique_ptr<TopLevelDeclTrackerAction> Act(
1131 new TopLevelDeclTrackerAction(*this));
1133 // Recover resources if we crash before exiting this method.
1134 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1135 ActCleanup(Act.get());
1137 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
1140 if (SavedMainFileBuffer)
1141 TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
1142 PreambleDiagnostics, StoredDiagnostics);
1144 if (!Act->Execute())
1147 transferASTDataFromCompilerInstance(*Clang);
1149 Act->EndSourceFile();
1151 FailedParseDiagnostics.clear();
1156 // Remove the overridden buffer we used for the preamble.
1157 SavedMainFileBuffer = nullptr;
1159 // Keep the ownership of the data in the ASTUnit because the client may
1160 // want to see the diagnostics.
1161 transferASTDataFromCompilerInstance(*Clang);
1162 FailedParseDiagnostics.swap(StoredDiagnostics);
1163 StoredDiagnostics.clear();
1164 NumStoredDiagnosticsFromDriver = 0;
1168 /// \brief Simple function to retrieve a path for a preamble precompiled header.
1169 static std::string GetPreamblePCHPath() {
1170 // FIXME: This is a hack so that we can override the preamble file during
1171 // crash-recovery testing, which is the only case where the preamble files
1172 // are not necessarily cleaned up.
1173 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1177 SmallString<128> Path;
1178 llvm::sys::fs::createTemporaryFile("preamble", "pch", Path);
1183 /// \brief Compute the preamble for the main file, providing the source buffer
1184 /// that corresponds to the main file along with a pair (bytes, start-of-line)
1185 /// that describes the preamble.
1186 ASTUnit::ComputedPreamble
1187 ASTUnit::ComputePreamble(CompilerInvocation &Invocation, unsigned MaxLines,
1188 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
1189 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
1190 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
1192 // Try to determine if the main file has been remapped, either from the
1193 // command line (to another file) or directly through the compiler invocation
1194 // (to a memory buffer).
1195 llvm::MemoryBuffer *Buffer = nullptr;
1196 std::unique_ptr<llvm::MemoryBuffer> BufferOwner;
1197 std::string MainFilePath(FrontendOpts.Inputs[0].getFile());
1198 auto MainFileStatus = VFS->status(MainFilePath);
1199 if (MainFileStatus) {
1200 llvm::sys::fs::UniqueID MainFileID = MainFileStatus->getUniqueID();
1202 // Check whether there is a file-file remapping of the main file
1203 for (const auto &RF : PreprocessorOpts.RemappedFiles) {
1204 std::string MPath(RF.first);
1205 auto MPathStatus = VFS->status(MPath);
1207 llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID();
1208 if (MainFileID == MID) {
1209 // We found a remapping. Try to load the resulting, remapped source.
1210 BufferOwner = valueOrNull(VFS->getBufferForFile(RF.second));
1212 return ComputedPreamble(nullptr, nullptr, 0, true);
1217 // Check whether there is a file-buffer remapping. It supercedes the
1218 // file-file remapping.
1219 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
1220 std::string MPath(RB.first);
1221 auto MPathStatus = VFS->status(MPath);
1223 llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID();
1224 if (MainFileID == MID) {
1225 // We found a remapping.
1226 BufferOwner.reset();
1227 Buffer = const_cast<llvm::MemoryBuffer *>(RB.second);
1233 // If the main source file was not remapped, load it now.
1234 if (!Buffer && !BufferOwner) {
1235 BufferOwner = valueOrNull(VFS->getBufferForFile(FrontendOpts.Inputs[0].getFile()));
1237 return ComputedPreamble(nullptr, nullptr, 0, true);
1241 Buffer = BufferOwner.get();
1242 auto Pre = Lexer::ComputePreamble(Buffer->getBuffer(),
1243 *Invocation.getLangOpts(), MaxLines);
1244 return ComputedPreamble(Buffer, std::move(BufferOwner), Pre.first,
1248 ASTUnit::PreambleFileHash
1249 ASTUnit::PreambleFileHash::createForFile(off_t Size, time_t ModTime) {
1250 PreambleFileHash Result;
1252 Result.ModTime = ModTime;
1257 ASTUnit::PreambleFileHash ASTUnit::PreambleFileHash::createForMemoryBuffer(
1258 const llvm::MemoryBuffer *Buffer) {
1259 PreambleFileHash Result;
1260 Result.Size = Buffer->getBufferSize();
1264 MD5Ctx.update(Buffer->getBuffer().data());
1265 MD5Ctx.final(Result.MD5);
1271 bool operator==(const ASTUnit::PreambleFileHash &LHS,
1272 const ASTUnit::PreambleFileHash &RHS) {
1273 return LHS.Size == RHS.Size && LHS.ModTime == RHS.ModTime &&
1276 } // namespace clang
1278 static std::pair<unsigned, unsigned>
1279 makeStandaloneRange(CharSourceRange Range, const SourceManager &SM,
1280 const LangOptions &LangOpts) {
1281 CharSourceRange FileRange = Lexer::makeFileCharRange(Range, SM, LangOpts);
1282 unsigned Offset = SM.getFileOffset(FileRange.getBegin());
1283 unsigned EndOffset = SM.getFileOffset(FileRange.getEnd());
1284 return std::make_pair(Offset, EndOffset);
1287 static ASTUnit::StandaloneFixIt makeStandaloneFixIt(const SourceManager &SM,
1288 const LangOptions &LangOpts,
1289 const FixItHint &InFix) {
1290 ASTUnit::StandaloneFixIt OutFix;
1291 OutFix.RemoveRange = makeStandaloneRange(InFix.RemoveRange, SM, LangOpts);
1292 OutFix.InsertFromRange = makeStandaloneRange(InFix.InsertFromRange, SM,
1294 OutFix.CodeToInsert = InFix.CodeToInsert;
1295 OutFix.BeforePreviousInsertions = InFix.BeforePreviousInsertions;
1299 static ASTUnit::StandaloneDiagnostic
1300 makeStandaloneDiagnostic(const LangOptions &LangOpts,
1301 const StoredDiagnostic &InDiag) {
1302 ASTUnit::StandaloneDiagnostic OutDiag;
1303 OutDiag.ID = InDiag.getID();
1304 OutDiag.Level = InDiag.getLevel();
1305 OutDiag.Message = InDiag.getMessage();
1306 OutDiag.LocOffset = 0;
1307 if (InDiag.getLocation().isInvalid())
1309 const SourceManager &SM = InDiag.getLocation().getManager();
1310 SourceLocation FileLoc = SM.getFileLoc(InDiag.getLocation());
1311 OutDiag.Filename = SM.getFilename(FileLoc);
1312 if (OutDiag.Filename.empty())
1314 OutDiag.LocOffset = SM.getFileOffset(FileLoc);
1315 for (const CharSourceRange &Range : InDiag.getRanges())
1316 OutDiag.Ranges.push_back(makeStandaloneRange(Range, SM, LangOpts));
1317 for (const FixItHint &FixIt : InDiag.getFixIts())
1318 OutDiag.FixIts.push_back(makeStandaloneFixIt(SM, LangOpts, FixIt));
1323 /// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1324 /// the source file.
1326 /// This routine will compute the preamble of the main source file. If a
1327 /// non-trivial preamble is found, it will precompile that preamble into a
1328 /// precompiled header so that the precompiled preamble can be used to reduce
1329 /// reparsing time. If a precompiled preamble has already been constructed,
1330 /// this routine will determine if it is still valid and, if so, avoid
1331 /// rebuilding the precompiled preamble.
1333 /// \param AllowRebuild When true (the default), this routine is
1334 /// allowed to rebuild the precompiled preamble if it is found to be
1337 /// \param MaxLines When non-zero, the maximum number of lines that
1338 /// can occur within the preamble.
1340 /// \returns If the precompiled preamble can be used, returns a newly-allocated
1341 /// buffer that should be used in place of the main file when doing so.
1342 /// Otherwise, returns a NULL pointer.
1343 std::unique_ptr<llvm::MemoryBuffer>
1344 ASTUnit::getMainBufferWithPrecompiledPreamble(
1345 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1346 const CompilerInvocation &PreambleInvocationIn,
1347 IntrusiveRefCntPtr<vfs::FileSystem> VFS, bool AllowRebuild,
1348 unsigned MaxLines) {
1349 assert(VFS && "VFS is null");
1351 auto PreambleInvocation =
1352 std::make_shared<CompilerInvocation>(PreambleInvocationIn);
1353 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
1354 PreprocessorOptions &PreprocessorOpts
1355 = PreambleInvocation->getPreprocessorOpts();
1357 ComputedPreamble NewPreamble =
1358 ComputePreamble(*PreambleInvocation, MaxLines, VFS);
1360 if (!NewPreamble.Size) {
1361 // We couldn't find a preamble in the main source. Clear out the current
1362 // preamble, if we have one. It's obviously no good any more.
1364 erasePreambleFile(this);
1366 // The next time we actually see a preamble, precompile it.
1367 PreambleRebuildCounter = 1;
1371 if (!Preamble.empty()) {
1372 // We've previously computed a preamble. Check whether we have the same
1373 // preamble now that we did before, and that there's enough space in
1374 // the main-file buffer within the precompiled preamble to fit the
1376 if (Preamble.size() == NewPreamble.Size &&
1377 PreambleEndsAtStartOfLine == NewPreamble.PreambleEndsAtStartOfLine &&
1378 memcmp(Preamble.getBufferStart(), NewPreamble.Buffer->getBufferStart(),
1379 NewPreamble.Size) == 0) {
1380 // The preamble has not changed. We may be able to re-use the precompiled
1383 // Check that none of the files used by the preamble have changed.
1384 bool AnyFileChanged = false;
1386 // First, make a record of those files that have been overridden via
1387 // remapping or unsaved_files.
1388 std::map<llvm::sys::fs::UniqueID, PreambleFileHash> OverriddenFiles;
1389 for (const auto &R : PreprocessorOpts.RemappedFiles) {
1394 if (!moveOnNoError(VFS->status(R.second), Status)) {
1395 // If we can't stat the file we're remapping to, assume that something
1396 // horrible happened.
1397 AnyFileChanged = true;
1401 OverriddenFiles[Status.getUniqueID()] = PreambleFileHash::createForFile(
1403 llvm::sys::toTimeT(Status.getLastModificationTime()));
1406 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
1411 if (!moveOnNoError(VFS->status(RB.first), Status)) {
1412 AnyFileChanged = true;
1416 OverriddenFiles[Status.getUniqueID()] =
1417 PreambleFileHash::createForMemoryBuffer(RB.second);
1420 // Check whether anything has changed.
1421 for (llvm::StringMap<PreambleFileHash>::iterator
1422 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1423 !AnyFileChanged && F != FEnd;
1426 if (!moveOnNoError(VFS->status(F->first()), Status)) {
1427 // If we can't stat the file, assume that something horrible happened.
1428 AnyFileChanged = true;
1432 std::map<llvm::sys::fs::UniqueID, PreambleFileHash>::iterator Overridden
1433 = OverriddenFiles.find(Status.getUniqueID());
1434 if (Overridden != OverriddenFiles.end()) {
1435 // This file was remapped; check whether the newly-mapped file
1436 // matches up with the previous mapping.
1437 if (Overridden->second != F->second)
1438 AnyFileChanged = true;
1442 // The file was not remapped; check whether it has changed on disk.
1443 if (Status.getSize() != uint64_t(F->second.Size) ||
1444 llvm::sys::toTimeT(Status.getLastModificationTime()) !=
1446 AnyFileChanged = true;
1449 if (!AnyFileChanged) {
1450 // Okay! We can re-use the precompiled preamble.
1452 // Set the state of the diagnostic object to mimic its state
1453 // after parsing the preamble.
1454 getDiagnostics().Reset();
1455 ProcessWarningOptions(getDiagnostics(),
1456 PreambleInvocation->getDiagnosticOpts());
1457 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1459 return llvm::MemoryBuffer::getMemBufferCopy(
1460 NewPreamble.Buffer->getBuffer(), FrontendOpts.Inputs[0].getFile());
1464 // If we aren't allowed to rebuild the precompiled preamble, just
1469 // We can't reuse the previously-computed preamble. Build a new one.
1471 PreambleDiagnostics.clear();
1472 erasePreambleFile(this);
1473 PreambleRebuildCounter = 1;
1474 } else if (!AllowRebuild) {
1475 // We aren't allowed to rebuild the precompiled preamble; just
1480 // If the preamble rebuild counter > 1, it's because we previously
1481 // failed to build a preamble and we're not yet ready to try
1482 // again. Decrement the counter and return a failure.
1483 if (PreambleRebuildCounter > 1) {
1484 --PreambleRebuildCounter;
1488 // Create a temporary file for the precompiled preamble. In rare
1489 // circumstances, this can fail.
1490 std::string PreamblePCHPath = GetPreamblePCHPath();
1491 if (PreamblePCHPath.empty()) {
1492 // Try again next time.
1493 PreambleRebuildCounter = 1;
1497 // We did not previously compute a preamble, or it can't be reused anyway.
1498 SimpleTimer PreambleTimer(WantTiming);
1499 PreambleTimer.setOutput("Precompiling preamble");
1501 // Save the preamble text for later; we'll need to compare against it for
1502 // subsequent reparses.
1503 StringRef MainFilename = FrontendOpts.Inputs[0].getFile();
1504 Preamble.assign(FileMgr->getFile(MainFilename),
1505 NewPreamble.Buffer->getBufferStart(),
1506 NewPreamble.Buffer->getBufferStart() + NewPreamble.Size);
1507 PreambleEndsAtStartOfLine = NewPreamble.PreambleEndsAtStartOfLine;
1509 PreambleBuffer = llvm::MemoryBuffer::getMemBufferCopy(
1510 NewPreamble.Buffer->getBuffer().slice(0, Preamble.size()), MainFilename);
1512 // Remap the main source file to the preamble buffer.
1513 StringRef MainFilePath = FrontendOpts.Inputs[0].getFile();
1514 PreprocessorOpts.addRemappedFile(MainFilePath, PreambleBuffer.get());
1516 // Tell the compiler invocation to generate a temporary precompiled header.
1517 FrontendOpts.ProgramAction = frontend::GeneratePCH;
1518 // FIXME: Generate the precompiled header into memory?
1519 FrontendOpts.OutputFile = PreamblePCHPath;
1520 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1521 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
1523 // Create the compiler instance to use for building the precompiled preamble.
1524 std::unique_ptr<CompilerInstance> Clang(
1525 new CompilerInstance(std::move(PCHContainerOps)));
1527 // Recover resources if we crash before exiting this method.
1528 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1529 CICleanup(Clang.get());
1531 Clang->setInvocation(std::move(PreambleInvocation));
1532 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1534 // Set up diagnostics, capturing all of the diagnostics produced.
1535 Clang->setDiagnostics(&getDiagnostics());
1537 // Create the target instance.
1538 Clang->setTarget(TargetInfo::CreateTargetInfo(
1539 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
1540 if (!Clang->hasTarget()) {
1541 llvm::sys::fs::remove(FrontendOpts.OutputFile);
1543 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
1544 PreprocessorOpts.RemappedFileBuffers.pop_back();
1548 // Inform the target of the language options.
1550 // FIXME: We shouldn't need to do this, the target should be immutable once
1551 // created. This complexity should be lifted elsewhere.
1552 Clang->getTarget().adjust(Clang->getLangOpts());
1554 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1555 "Invocation must have exactly one source file!");
1556 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1557 InputKind::Source &&
1558 "FIXME: AST inputs not yet supported here!");
1559 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1560 InputKind::LLVM_IR &&
1561 "IR inputs not support here!");
1563 // Clear out old caches and data.
1564 getDiagnostics().Reset();
1565 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
1566 checkAndRemoveNonDriverDiags(StoredDiagnostics);
1567 TopLevelDecls.clear();
1568 TopLevelDeclsInPreamble.clear();
1569 PreambleDiagnostics.clear();
1571 VFS = createVFSFromCompilerInvocation(Clang->getInvocation(),
1572 getDiagnostics(), VFS);
1576 // Create a file manager object to provide access to and cache the filesystem.
1577 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts(), VFS));
1579 // Create the source manager.
1580 Clang->setSourceManager(new SourceManager(getDiagnostics(),
1581 Clang->getFileManager()));
1583 auto PreambleDepCollector = std::make_shared<DependencyCollector>();
1584 Clang->addDependencyCollector(PreambleDepCollector);
1586 std::unique_ptr<PrecompilePreambleAction> Act;
1587 Act.reset(new PrecompilePreambleAction(*this));
1588 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1589 llvm::sys::fs::remove(FrontendOpts.OutputFile);
1591 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
1592 PreprocessorOpts.RemappedFileBuffers.pop_back();
1598 // Transfer any diagnostics generated when parsing the preamble into the set
1599 // of preamble diagnostics.
1600 for (stored_diag_iterator I = stored_diag_afterDriver_begin(),
1601 E = stored_diag_end();
1603 PreambleDiagnostics.push_back(
1604 makeStandaloneDiagnostic(Clang->getLangOpts(), *I));
1606 Act->EndSourceFile();
1608 checkAndRemoveNonDriverDiags(StoredDiagnostics);
1610 if (!Act->hasEmittedPreamblePCH()) {
1611 // The preamble PCH failed (e.g. there was a module loading fatal error),
1612 // so no precompiled header was generated. Forget that we even tried.
1613 // FIXME: Should we leave a note for ourselves to try again?
1614 llvm::sys::fs::remove(FrontendOpts.OutputFile);
1616 TopLevelDeclsInPreamble.clear();
1617 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
1618 PreprocessorOpts.RemappedFileBuffers.pop_back();
1622 // Keep track of the preamble we precompiled.
1623 setPreambleFile(this, FrontendOpts.OutputFile);
1624 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
1626 // Keep track of all of the files that the source manager knows about,
1627 // so we can verify whether they have changed or not.
1628 FilesInPreamble.clear();
1629 SourceManager &SourceMgr = Clang->getSourceManager();
1630 for (auto &Filename : PreambleDepCollector->getDependencies()) {
1631 const FileEntry *File = Clang->getFileManager().getFile(Filename);
1632 if (!File || File == SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()))
1634 if (time_t ModTime = File->getModificationTime()) {
1635 FilesInPreamble[File->getName()] = PreambleFileHash::createForFile(
1636 File->getSize(), ModTime);
1638 llvm::MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File);
1639 FilesInPreamble[File->getName()] =
1640 PreambleFileHash::createForMemoryBuffer(Buffer);
1644 PreambleRebuildCounter = 1;
1645 PreprocessorOpts.RemappedFileBuffers.pop_back();
1647 // If the hash of top-level entities differs from the hash of the top-level
1648 // entities the last time we rebuilt the preamble, clear out the completion
1650 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1651 CompletionCacheTopLevelHashValue = 0;
1652 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1655 return llvm::MemoryBuffer::getMemBufferCopy(NewPreamble.Buffer->getBuffer(),
1659 void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1660 std::vector<Decl *> Resolved;
1661 Resolved.reserve(TopLevelDeclsInPreamble.size());
1662 ExternalASTSource &Source = *getASTContext().getExternalSource();
1663 for (serialization::DeclID TopLevelDecl : TopLevelDeclsInPreamble) {
1664 // Resolve the declaration ID to an actual declaration, possibly
1665 // deserializing the declaration in the process.
1666 if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
1667 Resolved.push_back(D);
1669 TopLevelDeclsInPreamble.clear();
1670 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1673 void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
1674 // Steal the created target, context, and preprocessor if they have been
1676 assert(CI.hasInvocation() && "missing invocation");
1677 LangOpts = CI.getInvocation().LangOpts;
1678 TheSema = CI.takeSema();
1679 Consumer = CI.takeASTConsumer();
1680 if (CI.hasASTContext())
1681 Ctx = &CI.getASTContext();
1682 if (CI.hasPreprocessor())
1683 PP = CI.getPreprocessorPtr();
1684 CI.setSourceManager(nullptr);
1685 CI.setFileManager(nullptr);
1687 Target = &CI.getTarget();
1688 Reader = CI.getModuleManager();
1689 HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure();
1692 StringRef ASTUnit::getMainFileName() const {
1693 if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1694 const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0];
1696 return Input.getFile();
1698 return Input.getBuffer()->getBufferIdentifier();
1702 if (const FileEntry *
1703 FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
1704 return FE->getName();
1710 StringRef ASTUnit::getASTFileName() const {
1711 if (!isMainFileAST())
1714 serialization::ModuleFile &
1715 Mod = Reader->getModuleManager().getPrimaryModule();
1716 return Mod.FileName;
1719 std::unique_ptr<ASTUnit>
1720 ASTUnit::create(std::shared_ptr<CompilerInvocation> CI,
1721 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1722 bool CaptureDiagnostics, bool UserFilesAreVolatile) {
1723 std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
1724 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1725 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1726 createVFSFromCompilerInvocation(*CI, *Diags);
1729 AST->Diagnostics = Diags;
1730 AST->FileSystemOpts = CI->getFileSystemOpts();
1731 AST->Invocation = std::move(CI);
1732 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
1733 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1734 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1735 UserFilesAreVolatile);
1736 AST->PCMCache = new MemoryBufferCache;
1741 ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(
1742 std::shared_ptr<CompilerInvocation> CI,
1743 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1744 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FrontendAction *Action,
1745 ASTUnit *Unit, bool Persistent, StringRef ResourceFilesPath,
1746 bool OnlyLocalDecls, bool CaptureDiagnostics,
1747 unsigned PrecompilePreambleAfterNParses, bool CacheCodeCompletionResults,
1748 bool IncludeBriefCommentsInCodeCompletion, bool UserFilesAreVolatile,
1749 std::unique_ptr<ASTUnit> *ErrAST) {
1750 assert(CI && "A CompilerInvocation is required");
1752 std::unique_ptr<ASTUnit> OwnAST;
1753 ASTUnit *AST = Unit;
1755 // Create the AST unit.
1756 OwnAST = create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile);
1762 if (!ResourceFilesPath.empty()) {
1763 // Override the resources path.
1764 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1766 AST->OnlyLocalDecls = OnlyLocalDecls;
1767 AST->CaptureDiagnostics = CaptureDiagnostics;
1768 if (PrecompilePreambleAfterNParses > 0)
1769 AST->PreambleRebuildCounter = PrecompilePreambleAfterNParses;
1770 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
1771 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1772 AST->IncludeBriefCommentsInCodeCompletion
1773 = IncludeBriefCommentsInCodeCompletion;
1775 // Recover resources if we crash before exiting this method.
1776 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1777 ASTUnitCleanup(OwnAST.get());
1778 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1779 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
1780 DiagCleanup(Diags.get());
1782 // We'll manage file buffers ourselves.
1783 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1784 CI->getFrontendOpts().DisableFree = false;
1785 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1787 // Create the compiler instance to use for building the AST.
1788 std::unique_ptr<CompilerInstance> Clang(
1789 new CompilerInstance(std::move(PCHContainerOps)));
1791 // Recover resources if we crash before exiting this method.
1792 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1793 CICleanup(Clang.get());
1795 Clang->setInvocation(std::move(CI));
1796 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1798 // Set up diagnostics, capturing any diagnostics that would
1799 // otherwise be dropped.
1800 Clang->setDiagnostics(&AST->getDiagnostics());
1802 // Create the target instance.
1803 Clang->setTarget(TargetInfo::CreateTargetInfo(
1804 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
1805 if (!Clang->hasTarget())
1808 // Inform the target of the language options.
1810 // FIXME: We shouldn't need to do this, the target should be immutable once
1811 // created. This complexity should be lifted elsewhere.
1812 Clang->getTarget().adjust(Clang->getLangOpts());
1814 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1815 "Invocation must have exactly one source file!");
1816 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1817 InputKind::Source &&
1818 "FIXME: AST inputs not yet supported here!");
1819 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1820 InputKind::LLVM_IR &&
1821 "IR inputs not support here!");
1823 // Configure the various subsystems.
1824 AST->TheSema.reset();
1827 AST->Reader = nullptr;
1829 // Create a file manager object to provide access to and cache the filesystem.
1830 Clang->setFileManager(&AST->getFileManager());
1832 // Create the source manager.
1833 Clang->setSourceManager(&AST->getSourceManager());
1835 FrontendAction *Act = Action;
1837 std::unique_ptr<TopLevelDeclTrackerAction> TrackerAct;
1839 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1840 Act = TrackerAct.get();
1843 // Recover resources if we crash before exiting this method.
1844 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1845 ActCleanup(TrackerAct.get());
1847 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1848 AST->transferASTDataFromCompilerInstance(*Clang);
1849 if (OwnAST && ErrAST)
1850 ErrAST->swap(OwnAST);
1855 if (Persistent && !TrackerAct) {
1856 Clang->getPreprocessor().addPPCallbacks(
1857 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
1858 AST->getCurrentTopLevelHashValue()));
1859 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
1860 if (Clang->hasASTConsumer())
1861 Consumers.push_back(Clang->takeASTConsumer());
1862 Consumers.push_back(llvm::make_unique<TopLevelDeclTrackerConsumer>(
1863 *AST, AST->getCurrentTopLevelHashValue()));
1864 Clang->setASTConsumer(
1865 llvm::make_unique<MultiplexConsumer>(std::move(Consumers)));
1867 if (!Act->Execute()) {
1868 AST->transferASTDataFromCompilerInstance(*Clang);
1869 if (OwnAST && ErrAST)
1870 ErrAST->swap(OwnAST);
1875 // Steal the created target, context, and preprocessor.
1876 AST->transferASTDataFromCompilerInstance(*Clang);
1878 Act->EndSourceFile();
1881 return OwnAST.release();
1886 bool ASTUnit::LoadFromCompilerInvocation(
1887 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1888 unsigned PrecompilePreambleAfterNParses,
1889 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
1893 assert(VFS && "VFS is null");
1895 // We'll manage file buffers ourselves.
1896 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1897 Invocation->getFrontendOpts().DisableFree = false;
1898 getDiagnostics().Reset();
1899 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1901 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
1902 if (PrecompilePreambleAfterNParses > 0) {
1903 PreambleRebuildCounter = PrecompilePreambleAfterNParses;
1904 OverrideMainBuffer =
1905 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS);
1906 getDiagnostics().Reset();
1907 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1910 SimpleTimer ParsingTimer(WantTiming);
1911 ParsingTimer.setOutput("Parsing " + getMainFileName());
1913 // Recover resources if we crash before exiting this method.
1914 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1915 MemBufferCleanup(OverrideMainBuffer.get());
1917 return Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS);
1920 std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation(
1921 std::shared_ptr<CompilerInvocation> CI,
1922 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1923 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FileManager *FileMgr,
1924 bool OnlyLocalDecls, bool CaptureDiagnostics,
1925 unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
1926 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1927 bool UserFilesAreVolatile) {
1928 // Create the AST unit.
1929 std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
1930 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1931 AST->Diagnostics = Diags;
1932 AST->OnlyLocalDecls = OnlyLocalDecls;
1933 AST->CaptureDiagnostics = CaptureDiagnostics;
1934 AST->TUKind = TUKind;
1935 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1936 AST->IncludeBriefCommentsInCodeCompletion
1937 = IncludeBriefCommentsInCodeCompletion;
1938 AST->Invocation = std::move(CI);
1939 AST->FileSystemOpts = FileMgr->getFileSystemOpts();
1940 AST->FileMgr = FileMgr;
1941 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1943 // Recover resources if we crash before exiting this method.
1944 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1945 ASTUnitCleanup(AST.get());
1946 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1947 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
1948 DiagCleanup(Diags.get());
1950 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
1951 PrecompilePreambleAfterNParses,
1952 AST->FileMgr->getVirtualFileSystem()))
1957 ASTUnit *ASTUnit::LoadFromCommandLine(
1958 const char **ArgBegin, const char **ArgEnd,
1959 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1960 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, StringRef ResourceFilesPath,
1961 bool OnlyLocalDecls, bool CaptureDiagnostics,
1962 ArrayRef<RemappedFile> RemappedFiles, bool RemappedFilesKeepOriginalName,
1963 unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
1964 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1965 bool AllowPCHWithCompilerErrors, bool SkipFunctionBodies,
1966 bool UserFilesAreVolatile, bool ForSerialization,
1967 llvm::Optional<StringRef> ModuleFormat, std::unique_ptr<ASTUnit> *ErrAST,
1968 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
1969 assert(Diags.get() && "no DiagnosticsEngine was provided");
1971 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
1973 std::shared_ptr<CompilerInvocation> CI;
1977 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
1980 CI = clang::createInvocationFromCommandLine(
1981 llvm::makeArrayRef(ArgBegin, ArgEnd), Diags);
1986 // Override any files that need remapping
1987 for (const auto &RemappedFile : RemappedFiles) {
1988 CI->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
1989 RemappedFile.second);
1991 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
1992 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
1993 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
1994 PPOpts.GeneratePreamble = PrecompilePreambleAfterNParses != 0;
1996 // Override the resources path.
1997 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1999 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
2002 CI->getHeaderSearchOpts().ModuleFormat = ModuleFormat.getValue();
2004 // Create the AST unit.
2005 std::unique_ptr<ASTUnit> AST;
2006 AST.reset(new ASTUnit(false));
2007 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
2008 AST->Diagnostics = Diags;
2009 AST->FileSystemOpts = CI->getFileSystemOpts();
2011 VFS = vfs::getRealFileSystem();
2012 VFS = createVFSFromCompilerInvocation(*CI, *Diags, VFS);
2015 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
2016 AST->PCMCache = new MemoryBufferCache;
2017 AST->OnlyLocalDecls = OnlyLocalDecls;
2018 AST->CaptureDiagnostics = CaptureDiagnostics;
2019 AST->TUKind = TUKind;
2020 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
2021 AST->IncludeBriefCommentsInCodeCompletion
2022 = IncludeBriefCommentsInCodeCompletion;
2023 AST->UserFilesAreVolatile = UserFilesAreVolatile;
2024 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
2025 AST->StoredDiagnostics.swap(StoredDiagnostics);
2026 AST->Invocation = CI;
2027 if (ForSerialization)
2028 AST->WriterData.reset(new ASTWriterData(*AST->PCMCache));
2029 // Zero out now to ease cleanup during crash recovery.
2033 // Recover resources if we crash before exiting this method.
2034 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
2035 ASTUnitCleanup(AST.get());
2037 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
2038 PrecompilePreambleAfterNParses,
2040 // Some error occurred, if caller wants to examine diagnostics, pass it the
2043 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
2049 return AST.release();
2052 bool ASTUnit::Reparse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
2053 ArrayRef<RemappedFile> RemappedFiles,
2054 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
2059 assert(FileMgr && "FileMgr is null on Reparse call");
2060 VFS = FileMgr->getVirtualFileSystem();
2063 clearFileLevelDecls();
2065 SimpleTimer ParsingTimer(WantTiming);
2066 ParsingTimer.setOutput("Reparsing " + getMainFileName());
2069 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
2070 for (const auto &RB : PPOpts.RemappedFileBuffers)
2073 Invocation->getPreprocessorOpts().clearRemappedFiles();
2074 for (const auto &RemappedFile : RemappedFiles) {
2075 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
2076 RemappedFile.second);
2079 // If we have a preamble file lying around, or if we might try to
2080 // build a precompiled preamble, do so now.
2081 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
2082 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
2083 OverrideMainBuffer =
2084 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS);
2087 // Clear out the diagnostics state.
2089 getDiagnostics().Reset();
2090 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
2091 if (OverrideMainBuffer)
2092 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
2094 // Parse the sources
2096 Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS);
2098 // If we're caching global code-completion results, and the top-level
2099 // declarations have changed, clear out the code-completion cache.
2100 if (!Result && ShouldCacheCodeCompletionResults &&
2101 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2102 CacheCodeCompletionResults();
2104 // We now need to clear out the completion info related to this translation
2105 // unit; it'll be recreated if necessary.
2111 void ASTUnit::ResetForParse() {
2112 SavedMainFileBuffer.reset();
2120 TopLevelDecls.clear();
2121 clearFileLevelDecls();
2124 //----------------------------------------------------------------------------//
2126 //----------------------------------------------------------------------------//
2129 /// \brief Code completion consumer that combines the cached code-completion
2130 /// results from an ASTUnit with the code-completion results provided to it,
2131 /// then passes the result on to
2132 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
2133 uint64_t NormalContexts;
2135 CodeCompleteConsumer &Next;
2138 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
2139 const CodeCompleteOptions &CodeCompleteOpts)
2140 : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
2141 AST(AST), Next(Next)
2143 // Compute the set of contexts in which we will look when we don't have
2144 // any information about the specific context.
2146 = (1LL << CodeCompletionContext::CCC_TopLevel)
2147 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
2148 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
2149 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
2150 | (1LL << CodeCompletionContext::CCC_Statement)
2151 | (1LL << CodeCompletionContext::CCC_Expression)
2152 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
2153 | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
2154 | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
2155 | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
2156 | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
2157 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
2158 | (1LL << CodeCompletionContext::CCC_Recovery);
2160 if (AST.getASTContext().getLangOpts().CPlusPlus)
2161 NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
2162 | (1LL << CodeCompletionContext::CCC_UnionTag)
2163 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
2166 void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
2167 CodeCompletionResult *Results,
2168 unsigned NumResults) override;
2170 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2171 OverloadCandidate *Candidates,
2172 unsigned NumCandidates) override {
2173 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2176 CodeCompletionAllocator &getAllocator() override {
2177 return Next.getAllocator();
2180 CodeCompletionTUInfo &getCodeCompletionTUInfo() override {
2181 return Next.getCodeCompletionTUInfo();
2184 } // anonymous namespace
2186 /// \brief Helper function that computes which global names are hidden by the
2187 /// local code-completion results.
2188 static void CalculateHiddenNames(const CodeCompletionContext &Context,
2189 CodeCompletionResult *Results,
2190 unsigned NumResults,
2192 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
2193 bool OnlyTagNames = false;
2194 switch (Context.getKind()) {
2195 case CodeCompletionContext::CCC_Recovery:
2196 case CodeCompletionContext::CCC_TopLevel:
2197 case CodeCompletionContext::CCC_ObjCInterface:
2198 case CodeCompletionContext::CCC_ObjCImplementation:
2199 case CodeCompletionContext::CCC_ObjCIvarList:
2200 case CodeCompletionContext::CCC_ClassStructUnion:
2201 case CodeCompletionContext::CCC_Statement:
2202 case CodeCompletionContext::CCC_Expression:
2203 case CodeCompletionContext::CCC_ObjCMessageReceiver:
2204 case CodeCompletionContext::CCC_DotMemberAccess:
2205 case CodeCompletionContext::CCC_ArrowMemberAccess:
2206 case CodeCompletionContext::CCC_ObjCPropertyAccess:
2207 case CodeCompletionContext::CCC_Namespace:
2208 case CodeCompletionContext::CCC_Type:
2209 case CodeCompletionContext::CCC_Name:
2210 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
2211 case CodeCompletionContext::CCC_ParenthesizedExpression:
2212 case CodeCompletionContext::CCC_ObjCInterfaceName:
2215 case CodeCompletionContext::CCC_EnumTag:
2216 case CodeCompletionContext::CCC_UnionTag:
2217 case CodeCompletionContext::CCC_ClassOrStructTag:
2218 OnlyTagNames = true;
2221 case CodeCompletionContext::CCC_ObjCProtocolName:
2222 case CodeCompletionContext::CCC_MacroName:
2223 case CodeCompletionContext::CCC_MacroNameUse:
2224 case CodeCompletionContext::CCC_PreprocessorExpression:
2225 case CodeCompletionContext::CCC_PreprocessorDirective:
2226 case CodeCompletionContext::CCC_NaturalLanguage:
2227 case CodeCompletionContext::CCC_SelectorName:
2228 case CodeCompletionContext::CCC_TypeQualifiers:
2229 case CodeCompletionContext::CCC_Other:
2230 case CodeCompletionContext::CCC_OtherWithMacros:
2231 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2232 case CodeCompletionContext::CCC_ObjCClassMessage:
2233 case CodeCompletionContext::CCC_ObjCCategoryName:
2234 // We're looking for nothing, or we're looking for names that cannot
2239 typedef CodeCompletionResult Result;
2240 for (unsigned I = 0; I != NumResults; ++I) {
2241 if (Results[I].Kind != Result::RK_Declaration)
2245 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2247 bool Hiding = false;
2249 Hiding = (IDNS & Decl::IDNS_Tag);
2251 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
2252 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2253 Decl::IDNS_NonMemberOperator);
2254 if (Ctx.getLangOpts().CPlusPlus)
2255 HiddenIDNS |= Decl::IDNS_Tag;
2256 Hiding = (IDNS & HiddenIDNS);
2262 DeclarationName Name = Results[I].Declaration->getDeclName();
2263 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2264 HiddenNames.insert(Identifier->getName());
2266 HiddenNames.insert(Name.getAsString());
2270 void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2271 CodeCompletionContext Context,
2272 CodeCompletionResult *Results,
2273 unsigned NumResults) {
2274 // Merge the results we were given with the results we cached.
2275 bool AddedResult = false;
2276 uint64_t InContexts =
2277 Context.getKind() == CodeCompletionContext::CCC_Recovery
2278 ? NormalContexts : (1LL << Context.getKind());
2279 // Contains the set of names that are hidden by "local" completion results.
2280 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
2281 typedef CodeCompletionResult Result;
2282 SmallVector<Result, 8> AllResults;
2283 for (ASTUnit::cached_completion_iterator
2284 C = AST.cached_completion_begin(),
2285 CEnd = AST.cached_completion_end();
2287 // If the context we are in matches any of the contexts we are
2288 // interested in, we'll add this result.
2289 if ((C->ShowInContexts & InContexts) == 0)
2292 // If we haven't added any results previously, do so now.
2294 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2296 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2300 // Determine whether this global completion result is hidden by a local
2301 // completion result. If so, skip it.
2302 if (C->Kind != CXCursor_MacroDefinition &&
2303 HiddenNames.count(C->Completion->getTypedText()))
2306 // Adjust priority based on similar type classes.
2307 unsigned Priority = C->Priority;
2308 CodeCompletionString *Completion = C->Completion;
2309 if (!Context.getPreferredType().isNull()) {
2310 if (C->Kind == CXCursor_MacroDefinition) {
2311 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
2313 Context.getPreferredType()->isAnyPointerType());
2314 } else if (C->Type) {
2315 CanQualType Expected
2316 = S.Context.getCanonicalType(
2317 Context.getPreferredType().getUnqualifiedType());
2318 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2319 if (ExpectedSTC == C->TypeClass) {
2320 // We know this type is similar; check for an exact match.
2321 llvm::StringMap<unsigned> &CachedCompletionTypes
2322 = AST.getCachedCompletionTypes();
2323 llvm::StringMap<unsigned>::iterator Pos
2324 = CachedCompletionTypes.find(QualType(Expected).getAsString());
2325 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2326 Priority /= CCF_ExactTypeMatch;
2328 Priority /= CCF_SimilarTypeMatch;
2333 // Adjust the completion string, if required.
2334 if (C->Kind == CXCursor_MacroDefinition &&
2335 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2336 // Create a new code-completion string that just contains the
2337 // macro name, without its arguments.
2338 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2339 CCP_CodePattern, C->Availability);
2340 Builder.AddTypedTextChunk(C->Completion->getTypedText());
2341 Priority = CCP_CodePattern;
2342 Completion = Builder.TakeString();
2345 AllResults.push_back(Result(Completion, Priority, C->Kind,
2349 // If we did not add any cached completion results, just forward the
2350 // results we were given to the next consumer.
2352 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2356 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2360 void ASTUnit::CodeComplete(
2361 StringRef File, unsigned Line, unsigned Column,
2362 ArrayRef<RemappedFile> RemappedFiles, bool IncludeMacros,
2363 bool IncludeCodePatterns, bool IncludeBriefComments,
2364 CodeCompleteConsumer &Consumer,
2365 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
2366 DiagnosticsEngine &Diag, LangOptions &LangOpts, SourceManager &SourceMgr,
2367 FileManager &FileMgr, SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2368 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
2372 SimpleTimer CompletionTimer(WantTiming);
2373 CompletionTimer.setOutput("Code completion @ " + File + ":" +
2374 Twine(Line) + ":" + Twine(Column));
2376 auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation);
2378 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
2379 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
2380 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
2382 CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2383 CachedCompletionResults.empty();
2384 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2385 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2386 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2388 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2390 FrontendOpts.CodeCompletionAt.FileName = File;
2391 FrontendOpts.CodeCompletionAt.Line = Line;
2392 FrontendOpts.CodeCompletionAt.Column = Column;
2394 // Set the language options appropriately.
2395 LangOpts = *CCInvocation->getLangOpts();
2397 // Spell-checking and warnings are wasteful during code-completion.
2398 LangOpts.SpellChecking = false;
2399 CCInvocation->getDiagnosticOpts().IgnoreWarnings = true;
2401 std::unique_ptr<CompilerInstance> Clang(
2402 new CompilerInstance(PCHContainerOps));
2404 // Recover resources if we crash before exiting this method.
2405 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2406 CICleanup(Clang.get());
2408 auto &Inv = *CCInvocation;
2409 Clang->setInvocation(std::move(CCInvocation));
2410 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
2412 // Set up diagnostics, capturing any diagnostics produced.
2413 Clang->setDiagnostics(&Diag);
2414 CaptureDroppedDiagnostics Capture(true,
2415 Clang->getDiagnostics(),
2417 ProcessWarningOptions(Diag, Inv.getDiagnosticOpts());
2419 // Create the target instance.
2420 Clang->setTarget(TargetInfo::CreateTargetInfo(
2421 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
2422 if (!Clang->hasTarget()) {
2423 Clang->setInvocation(nullptr);
2427 // Inform the target of the language options.
2429 // FIXME: We shouldn't need to do this, the target should be immutable once
2430 // created. This complexity should be lifted elsewhere.
2431 Clang->getTarget().adjust(Clang->getLangOpts());
2433 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
2434 "Invocation must have exactly one source file!");
2435 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
2436 InputKind::Source &&
2437 "FIXME: AST inputs not yet supported here!");
2438 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
2439 InputKind::LLVM_IR &&
2440 "IR inputs not support here!");
2442 // Use the source and file managers that we were given.
2443 Clang->setFileManager(&FileMgr);
2444 Clang->setSourceManager(&SourceMgr);
2447 PreprocessorOpts.clearRemappedFiles();
2448 PreprocessorOpts.RetainRemappedFileBuffers = true;
2449 for (const auto &RemappedFile : RemappedFiles) {
2450 PreprocessorOpts.addRemappedFile(RemappedFile.first, RemappedFile.second);
2451 OwnedBuffers.push_back(RemappedFile.second);
2454 // Use the code completion consumer we were given, but adding any cached
2455 // code-completion results.
2456 AugmentedCodeCompleteConsumer *AugmentedConsumer
2457 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
2458 Clang->setCodeCompletionConsumer(AugmentedConsumer);
2460 // If we have a precompiled preamble, try to use it. We only allow
2461 // the use of the precompiled preamble if we're if the completion
2462 // point is within the main file, after the end of the precompiled
2464 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
2465 if (!getPreambleFile(this).empty()) {
2466 std::string CompleteFilePath(File);
2468 auto VFS = FileMgr.getVirtualFileSystem();
2469 auto CompleteFileStatus = VFS->status(CompleteFilePath);
2470 if (CompleteFileStatus) {
2471 llvm::sys::fs::UniqueID CompleteFileID = CompleteFileStatus->getUniqueID();
2473 std::string MainPath(OriginalSourceFile);
2474 auto MainStatus = VFS->status(MainPath);
2476 llvm::sys::fs::UniqueID MainID = MainStatus->getUniqueID();
2477 if (CompleteFileID == MainID && Line > 1)
2478 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(
2479 PCHContainerOps, Inv, VFS, false, Line - 1);
2484 // If the main file has been overridden due to the use of a preamble,
2485 // make that override happen and introduce the preamble.
2486 if (OverrideMainBuffer) {
2487 PreprocessorOpts.addRemappedFile(OriginalSourceFile,
2488 OverrideMainBuffer.get());
2489 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2490 PreprocessorOpts.PrecompiledPreambleBytes.second
2491 = PreambleEndsAtStartOfLine;
2492 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
2493 PreprocessorOpts.DisablePCHValidation = true;
2495 OwnedBuffers.push_back(OverrideMainBuffer.release());
2497 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2498 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
2501 // Disable the preprocessing record if modules are not enabled.
2502 if (!Clang->getLangOpts().Modules)
2503 PreprocessorOpts.DetailedRecord = false;
2505 std::unique_ptr<SyntaxOnlyAction> Act;
2506 Act.reset(new SyntaxOnlyAction);
2507 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
2509 Act->EndSourceFile();
2513 bool ASTUnit::Save(StringRef File) {
2514 if (HadModuleLoaderFatalFailure)
2517 // Write to a temporary file and later rename it to the actual file, to avoid
2518 // possible race conditions.
2519 SmallString<128> TempPath;
2521 TempPath += "-%%%%%%%%";
2523 if (llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath))
2526 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2527 // unconditionally create a stat cache when we parse the file?
2528 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
2532 if (Out.has_error()) {
2537 if (llvm::sys::fs::rename(TempPath, File)) {
2538 llvm::sys::fs::remove(TempPath);
2545 static bool serializeUnit(ASTWriter &Writer,
2546 SmallVectorImpl<char> &Buffer,
2550 Writer.WriteAST(S, std::string(), nullptr, "", hasErrors);
2552 // Write the generated bitstream to "Out".
2553 if (!Buffer.empty())
2554 OS.write(Buffer.data(), Buffer.size());
2559 bool ASTUnit::serialize(raw_ostream &OS) {
2560 // For serialization we are lenient if the errors were only warn-as-error kind.
2561 bool hasErrors = getDiagnostics().hasUncompilableErrorOccurred();
2564 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2565 getSema(), hasErrors, OS);
2567 SmallString<128> Buffer;
2568 llvm::BitstreamWriter Stream(Buffer);
2569 MemoryBufferCache PCMCache;
2570 ASTWriter Writer(Stream, Buffer, PCMCache, {});
2571 return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
2574 typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2576 void ASTUnit::TranslateStoredDiagnostics(
2577 FileManager &FileMgr,
2578 SourceManager &SrcMgr,
2579 const SmallVectorImpl<StandaloneDiagnostic> &Diags,
2580 SmallVectorImpl<StoredDiagnostic> &Out) {
2581 // Map the standalone diagnostic into the new source manager. We also need to
2582 // remap all the locations to the new view. This includes the diag location,
2583 // any associated source ranges, and the source ranges of associated fix-its.
2584 // FIXME: There should be a cleaner way to do this.
2586 SmallVector<StoredDiagnostic, 4> Result;
2587 Result.reserve(Diags.size());
2588 const FileEntry *PreviousFE = nullptr;
2590 for (const StandaloneDiagnostic &SD : Diags) {
2591 // Rebuild the StoredDiagnostic.
2592 if (SD.Filename.empty())
2594 const FileEntry *FE = FileMgr.getFile(SD.Filename);
2597 if (FE != PreviousFE) {
2598 FID = SrcMgr.translateFile(FE);
2601 SourceLocation FileLoc = SrcMgr.getLocForStartOfFile(FID);
2602 if (FileLoc.isInvalid())
2604 SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset);
2605 FullSourceLoc Loc(L, SrcMgr);
2607 SmallVector<CharSourceRange, 4> Ranges;
2608 Ranges.reserve(SD.Ranges.size());
2609 for (const auto &Range : SD.Ranges) {
2610 SourceLocation BL = FileLoc.getLocWithOffset(Range.first);
2611 SourceLocation EL = FileLoc.getLocWithOffset(Range.second);
2612 Ranges.push_back(CharSourceRange::getCharRange(BL, EL));
2615 SmallVector<FixItHint, 2> FixIts;
2616 FixIts.reserve(SD.FixIts.size());
2617 for (const StandaloneFixIt &FixIt : SD.FixIts) {
2618 FixIts.push_back(FixItHint());
2619 FixItHint &FH = FixIts.back();
2620 FH.CodeToInsert = FixIt.CodeToInsert;
2621 SourceLocation BL = FileLoc.getLocWithOffset(FixIt.RemoveRange.first);
2622 SourceLocation EL = FileLoc.getLocWithOffset(FixIt.RemoveRange.second);
2623 FH.RemoveRange = CharSourceRange::getCharRange(BL, EL);
2626 Result.push_back(StoredDiagnostic(SD.Level, SD.ID,
2627 SD.Message, Loc, Ranges, FixIts));
2632 void ASTUnit::addFileLevelDecl(Decl *D) {
2635 // We only care about local declarations.
2636 if (D->isFromASTFile())
2639 SourceManager &SM = *SourceMgr;
2640 SourceLocation Loc = D->getLocation();
2641 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2644 // We only keep track of the file-level declarations of each file.
2645 if (!D->getLexicalDeclContext()->isFileContext())
2648 SourceLocation FileLoc = SM.getFileLoc(Loc);
2649 assert(SM.isLocalSourceLocation(FileLoc));
2652 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
2653 if (FID.isInvalid())
2656 LocDeclsTy *&Decls = FileDecls[FID];
2658 Decls = new LocDeclsTy();
2660 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2662 if (Decls->empty() || Decls->back().first <= Offset) {
2663 Decls->push_back(LocDecl);
2667 LocDeclsTy::iterator I = std::upper_bound(Decls->begin(), Decls->end(),
2668 LocDecl, llvm::less_first());
2670 Decls->insert(I, LocDecl);
2673 void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2674 SmallVectorImpl<Decl *> &Decls) {
2675 if (File.isInvalid())
2678 if (SourceMgr->isLoadedFileID(File)) {
2679 assert(Ctx->getExternalSource() && "No external source!");
2680 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2684 FileDeclsTy::iterator I = FileDecls.find(File);
2685 if (I == FileDecls.end())
2688 LocDeclsTy &LocDecls = *I->second;
2689 if (LocDecls.empty())
2692 LocDeclsTy::iterator BeginIt =
2693 std::lower_bound(LocDecls.begin(), LocDecls.end(),
2694 std::make_pair(Offset, (Decl *)nullptr),
2695 llvm::less_first());
2696 if (BeginIt != LocDecls.begin())
2699 // If we are pointing at a top-level decl inside an objc container, we need
2700 // to backtrack until we find it otherwise we will fail to report that the
2701 // region overlaps with an objc container.
2702 while (BeginIt != LocDecls.begin() &&
2703 BeginIt->second->isTopLevelDeclInObjCContainer())
2706 LocDeclsTy::iterator EndIt = std::upper_bound(
2707 LocDecls.begin(), LocDecls.end(),
2708 std::make_pair(Offset + Length, (Decl *)nullptr), llvm::less_first());
2709 if (EndIt != LocDecls.end())
2712 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2713 Decls.push_back(DIt->second);
2716 SourceLocation ASTUnit::getLocation(const FileEntry *File,
2717 unsigned Line, unsigned Col) const {
2718 const SourceManager &SM = getSourceManager();
2719 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
2720 return SM.getMacroArgExpandedLocation(Loc);
2723 SourceLocation ASTUnit::getLocation(const FileEntry *File,
2724 unsigned Offset) const {
2725 const SourceManager &SM = getSourceManager();
2726 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
2727 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2730 /// \brief If \arg Loc is a loaded location from the preamble, returns
2731 /// the corresponding local location of the main file, otherwise it returns
2733 SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2736 PreambleID = SourceMgr->getPreambleFileID();
2738 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2742 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2743 SourceLocation FileLoc
2744 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2745 return FileLoc.getLocWithOffset(Offs);
2751 /// \brief If \arg Loc is a local location of the main file but inside the
2752 /// preamble chunk, returns the corresponding loaded location from the
2753 /// preamble, otherwise it returns \arg Loc.
2754 SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2757 PreambleID = SourceMgr->getPreambleFileID();
2759 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2763 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2764 Offs < Preamble.size()) {
2765 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2766 return FileLoc.getLocWithOffset(Offs);
2772 bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2775 FID = SourceMgr->getPreambleFileID();
2777 if (Loc.isInvalid() || FID.isInvalid())
2780 return SourceMgr->isInFileID(Loc, FID);
2783 bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2786 FID = SourceMgr->getMainFileID();
2788 if (Loc.isInvalid() || FID.isInvalid())
2791 return SourceMgr->isInFileID(Loc, FID);
2794 SourceLocation ASTUnit::getEndOfPreambleFileID() {
2797 FID = SourceMgr->getPreambleFileID();
2799 if (FID.isInvalid())
2800 return SourceLocation();
2802 return SourceMgr->getLocForEndOfFile(FID);
2805 SourceLocation ASTUnit::getStartOfMainFileID() {
2808 FID = SourceMgr->getMainFileID();
2810 if (FID.isInvalid())
2811 return SourceLocation();
2813 return SourceMgr->getLocForStartOfFile(FID);
2816 llvm::iterator_range<PreprocessingRecord::iterator>
2817 ASTUnit::getLocalPreprocessingEntities() const {
2818 if (isMainFileAST()) {
2819 serialization::ModuleFile &
2820 Mod = Reader->getModuleManager().getPrimaryModule();
2821 return Reader->getModulePreprocessedEntities(Mod);
2824 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
2825 return llvm::make_range(PPRec->local_begin(), PPRec->local_end());
2827 return llvm::make_range(PreprocessingRecord::iterator(),
2828 PreprocessingRecord::iterator());
2831 bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
2832 if (isMainFileAST()) {
2833 serialization::ModuleFile &
2834 Mod = Reader->getModuleManager().getPrimaryModule();
2835 for (const Decl *D : Reader->getModuleFileLevelDecls(Mod)) {
2836 if (!Fn(context, D))
2843 for (ASTUnit::top_level_iterator TL = top_level_begin(),
2844 TLEnd = top_level_end();
2845 TL != TLEnd; ++TL) {
2846 if (!Fn(context, *TL))
2853 const FileEntry *ASTUnit::getPCHFile() {
2857 serialization::ModuleFile *Mod = nullptr;
2858 Reader->getModuleManager().visit([&Mod](serialization::ModuleFile &M) {
2860 case serialization::MK_ImplicitModule:
2861 case serialization::MK_ExplicitModule:
2862 case serialization::MK_PrebuiltModule:
2863 return true; // skip dependencies.
2864 case serialization::MK_PCH:
2866 return true; // found it.
2867 case serialization::MK_Preamble:
2868 return false; // look in dependencies.
2869 case serialization::MK_MainFile:
2870 return false; // look in dependencies.
2881 bool ASTUnit::isModuleFile() {
2882 return isMainFileAST() && ASTFileLangOpts.isCompilingModule();
2885 void ASTUnit::PreambleData::countLines() const {
2890 NumLines = std::count(Buffer.begin(), Buffer.end(), '\n');
2892 if (Buffer.back() != '\n')
2897 ASTUnit::ConcurrencyState::ConcurrencyState() {
2898 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2901 ASTUnit::ConcurrencyState::~ConcurrencyState() {
2902 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2905 void ASTUnit::ConcurrencyState::start() {
2906 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2907 assert(acquired && "Concurrent access to ASTUnit!");
2910 void ASTUnit::ConcurrencyState::finish() {
2911 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2916 ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex = nullptr; }
2917 ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2918 void ASTUnit::ConcurrencyState::start() {}
2919 void ASTUnit::ConcurrencyState::finish() {}