1 //===--- ASTUnit.cpp - ASTUnit utility --------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // ASTUnit Implementation.
11 //
12 //===----------------------------------------------------------------------===//
13 
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"
47 #include <atomic>
48 #include <cstdio>
49 #include <cstdlib>
50 
51 using namespace clang;
52 
53 using llvm::TimeRecord;
54 
55 namespace {
56   class SimpleTimer {
57     bool WantTiming;
58     TimeRecord Start;
59     std::string Output;
60 
61   public:
62     explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
63       if (WantTiming)
64         Start = TimeRecord::getCurrentTime();
65     }
66 
67     void setOutput(const Twine &Output) {
68       if (WantTiming)
69         this->Output = Output.str();
70     }
71 
72     ~SimpleTimer() {
73       if (WantTiming) {
74         TimeRecord Elapsed = TimeRecord::getCurrentTime();
75         Elapsed -= Start;
76         llvm::errs() << Output << ':';
77         Elapsed.print(Elapsed, llvm::errs());
78         llvm::errs() << '\n';
79       }
80     }
81   };
82 
83   template <class T>
84   std::unique_ptr<T> valueOrNull(llvm::ErrorOr<std::unique_ptr<T>> Val) {
85     if (!Val)
86       return nullptr;
87     return std::move(*Val);
88   }
89 
90   template <class T>
91   bool moveOnNoError(llvm::ErrorOr<T> Val, T &Output) {
92     if (!Val)
93       return false;
94     Output = std::move(*Val);
95     return true;
96   }
97 
98 /// \brief Get a source buffer for \p MainFilePath, handling all file-to-file
99 /// and file-to-buffer remappings inside \p Invocation.
100 static std::unique_ptr<llvm::MemoryBuffer>
101 getBufferForFileHandlingRemapping(const CompilerInvocation &Invocation,
102                                   vfs::FileSystem *VFS,
103                                   StringRef FilePath) {
104   const auto &PreprocessorOpts = Invocation.getPreprocessorOpts();
105 
106   // Try to determine if the main file has been remapped, either from the
107   // command line (to another file) or directly through the compiler
108   // invocation (to a memory buffer).
109   llvm::MemoryBuffer *Buffer = nullptr;
110   std::unique_ptr<llvm::MemoryBuffer> BufferOwner;
111   auto FileStatus = VFS->status(FilePath);
112   if (FileStatus) {
113     llvm::sys::fs::UniqueID MainFileID = FileStatus->getUniqueID();
114 
115     // Check whether there is a file-file remapping of the main file
116     for (const auto &RF : PreprocessorOpts.RemappedFiles) {
117       std::string MPath(RF.first);
118       auto MPathStatus = VFS->status(MPath);
119       if (MPathStatus) {
120         llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID();
121         if (MainFileID == MID) {
122           // We found a remapping. Try to load the resulting, remapped source.
123           BufferOwner = valueOrNull(VFS->getBufferForFile(RF.second));
124           if (!BufferOwner)
125             return nullptr;
126         }
127       }
128     }
129 
130     // Check whether there is a file-buffer remapping. It supercedes the
131     // file-file remapping.
132     for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
133       std::string MPath(RB.first);
134       auto MPathStatus = VFS->status(MPath);
135       if (MPathStatus) {
136         llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID();
137         if (MainFileID == MID) {
138           // We found a remapping.
139           BufferOwner.reset();
140           Buffer = const_cast<llvm::MemoryBuffer *>(RB.second);
141         }
142       }
143     }
144   }
145 
146   // If the main source file was not remapped, load it now.
147   if (!Buffer && !BufferOwner) {
148     BufferOwner = valueOrNull(VFS->getBufferForFile(FilePath));
149     if (!BufferOwner)
150       return nullptr;
151   }
152 
153   if (BufferOwner)
154     return BufferOwner;
155   if (!Buffer)
156     return nullptr;
157   return llvm::MemoryBuffer::getMemBufferCopy(Buffer->getBuffer(), FilePath);
158 }
159 }
160 
161 struct ASTUnit::ASTWriterData {
162   SmallString<128> Buffer;
163   llvm::BitstreamWriter Stream;
164   ASTWriter Writer;
165 
166   ASTWriterData(MemoryBufferCache &PCMCache)
167       : Stream(Buffer), Writer(Stream, Buffer, PCMCache, {}) {}
168 };
169 
170 void ASTUnit::clearFileLevelDecls() {
171   llvm::DeleteContainerSeconds(FileDecls);
172 }
173 
174 /// \brief After failing to build a precompiled preamble (due to
175 /// errors in the source that occurs in the preamble), the number of
176 /// reparses during which we'll skip even trying to precompile the
177 /// preamble.
178 const unsigned DefaultPreambleRebuildInterval = 5;
179 
180 /// \brief Tracks the number of ASTUnit objects that are currently active.
181 ///
182 /// Used for debugging purposes only.
183 static std::atomic<unsigned> ActiveASTUnitObjects;
184 
185 ASTUnit::ASTUnit(bool _MainFileIsAST)
186   : Reader(nullptr), HadModuleLoaderFatalFailure(false),
187     OnlyLocalDecls(false), CaptureDiagnostics(false),
188     MainFileIsAST(_MainFileIsAST),
189     TUKind(TU_Complete), WantTiming(getenv("LIBCLANG_TIMING")),
190     OwnsRemappedFileBuffers(true),
191     NumStoredDiagnosticsFromDriver(0),
192     PreambleRebuildCounter(0),
193     NumWarningsInPreamble(0),
194     ShouldCacheCodeCompletionResults(false),
195     IncludeBriefCommentsInCodeCompletion(false), UserFilesAreVolatile(false),
196     CompletionCacheTopLevelHashValue(0),
197     PreambleTopLevelHashValue(0),
198     CurrentTopLevelHashValue(0),
199     UnsafeToFree(false) {
200   if (getenv("LIBCLANG_OBJTRACKING"))
201     fprintf(stderr, "+++ %u translation units\n", ++ActiveASTUnitObjects);
202 }
203 
204 ASTUnit::~ASTUnit() {
205   // If we loaded from an AST file, balance out the BeginSourceFile call.
206   if (MainFileIsAST && getDiagnostics().getClient()) {
207     getDiagnostics().getClient()->EndSourceFile();
208   }
209 
210   clearFileLevelDecls();
211 
212   // Free the buffers associated with remapped files. We are required to
213   // perform this operation here because we explicitly request that the
214   // compiler instance *not* free these buffers for each invocation of the
215   // parser.
216   if (Invocation && OwnsRemappedFileBuffers) {
217     PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
218     for (const auto &RB : PPOpts.RemappedFileBuffers)
219       delete RB.second;
220   }
221 
222   ClearCachedCompletionResults();
223 
224   if (getenv("LIBCLANG_OBJTRACKING"))
225     fprintf(stderr, "--- %u translation units\n", --ActiveASTUnitObjects);
226 }
227 
228 void ASTUnit::setPreprocessor(std::shared_ptr<Preprocessor> PP) {
229   this->PP = std::move(PP);
230 }
231 
232 /// \brief Determine the set of code-completion contexts in which this
233 /// declaration should be shown.
234 static unsigned getDeclShowContexts(const NamedDecl *ND,
235                                     const LangOptions &LangOpts,
236                                     bool &IsNestedNameSpecifier) {
237   IsNestedNameSpecifier = false;
238 
239   if (isa<UsingShadowDecl>(ND))
240     ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
241   if (!ND)
242     return 0;
243 
244   uint64_t Contexts = 0;
245   if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
246       isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND) ||
247       isa<TypeAliasTemplateDecl>(ND)) {
248     // Types can appear in these contexts.
249     if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
250       Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel)
251                |  (1LL << CodeCompletionContext::CCC_ObjCIvarList)
252                |  (1LL << CodeCompletionContext::CCC_ClassStructUnion)
253                |  (1LL << CodeCompletionContext::CCC_Statement)
254                |  (1LL << CodeCompletionContext::CCC_Type)
255                |  (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
256 
257     // In C++, types can appear in expressions contexts (for functional casts).
258     if (LangOpts.CPlusPlus)
259       Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
260 
261     // In Objective-C, message sends can send interfaces. In Objective-C++,
262     // all types are available due to functional casts.
263     if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
264       Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
265 
266     // In Objective-C, you can only be a subclass of another Objective-C class
267     if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND)) {
268       // Objective-C interfaces can be used in a class property expression.
269       if (ID->getDefinition())
270         Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
271       Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName);
272     }
273 
274     // Deal with tag names.
275     if (isa<EnumDecl>(ND)) {
276       Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag);
277 
278       // Part of the nested-name-specifier in C++0x.
279       if (LangOpts.CPlusPlus11)
280         IsNestedNameSpecifier = true;
281     } else if (const RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
282       if (Record->isUnion())
283         Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag);
284       else
285         Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
286 
287       if (LangOpts.CPlusPlus)
288         IsNestedNameSpecifier = true;
289     } else if (isa<ClassTemplateDecl>(ND))
290       IsNestedNameSpecifier = true;
291   } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
292     // Values can appear in these contexts.
293     Contexts = (1LL << CodeCompletionContext::CCC_Statement)
294              | (1LL << CodeCompletionContext::CCC_Expression)
295              | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
296              | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
297   } else if (isa<ObjCProtocolDecl>(ND)) {
298     Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName);
299   } else if (isa<ObjCCategoryDecl>(ND)) {
300     Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName);
301   } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
302     Contexts = (1LL << CodeCompletionContext::CCC_Namespace);
303 
304     // Part of the nested-name-specifier.
305     IsNestedNameSpecifier = true;
306   }
307 
308   return Contexts;
309 }
310 
311 void ASTUnit::CacheCodeCompletionResults() {
312   if (!TheSema)
313     return;
314 
315   SimpleTimer Timer(WantTiming);
316   Timer.setOutput("Cache global code completions for " + getMainFileName());
317 
318   // Clear out the previous results.
319   ClearCachedCompletionResults();
320 
321   // Gather the set of global code completions.
322   typedef CodeCompletionResult Result;
323   SmallVector<Result, 8> Results;
324   CachedCompletionAllocator = std::make_shared<GlobalCodeCompletionAllocator>();
325   CodeCompletionTUInfo CCTUInfo(CachedCompletionAllocator);
326   TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
327                                        CCTUInfo, Results);
328 
329   // Translate global code completions into cached completions.
330   llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
331   CodeCompletionContext CCContext(CodeCompletionContext::CCC_TopLevel);
332 
333   for (Result &R : Results) {
334     switch (R.Kind) {
335     case Result::RK_Declaration: {
336       bool IsNestedNameSpecifier = false;
337       CachedCodeCompletionResult CachedResult;
338       CachedResult.Completion = R.CreateCodeCompletionString(
339           *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
340           IncludeBriefCommentsInCodeCompletion);
341       CachedResult.ShowInContexts = getDeclShowContexts(
342           R.Declaration, Ctx->getLangOpts(), IsNestedNameSpecifier);
343       CachedResult.Priority = R.Priority;
344       CachedResult.Kind = R.CursorKind;
345       CachedResult.Availability = R.Availability;
346 
347       // Keep track of the type of this completion in an ASTContext-agnostic
348       // way.
349       QualType UsageType = getDeclUsageType(*Ctx, R.Declaration);
350       if (UsageType.isNull()) {
351         CachedResult.TypeClass = STC_Void;
352         CachedResult.Type = 0;
353       } else {
354         CanQualType CanUsageType
355           = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
356         CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
357 
358         // Determine whether we have already seen this type. If so, we save
359         // ourselves the work of formatting the type string by using the
360         // temporary, CanQualType-based hash table to find the associated value.
361         unsigned &TypeValue = CompletionTypes[CanUsageType];
362         if (TypeValue == 0) {
363           TypeValue = CompletionTypes.size();
364           CachedCompletionTypes[QualType(CanUsageType).getAsString()]
365             = TypeValue;
366         }
367 
368         CachedResult.Type = TypeValue;
369       }
370 
371       CachedCompletionResults.push_back(CachedResult);
372 
373       /// Handle nested-name-specifiers in C++.
374       if (TheSema->Context.getLangOpts().CPlusPlus && IsNestedNameSpecifier &&
375           !R.StartsNestedNameSpecifier) {
376         // The contexts in which a nested-name-specifier can appear in C++.
377         uint64_t NNSContexts
378           = (1LL << CodeCompletionContext::CCC_TopLevel)
379           | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
380           | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
381           | (1LL << CodeCompletionContext::CCC_Statement)
382           | (1LL << CodeCompletionContext::CCC_Expression)
383           | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
384           | (1LL << CodeCompletionContext::CCC_EnumTag)
385           | (1LL << CodeCompletionContext::CCC_UnionTag)
386           | (1LL << CodeCompletionContext::CCC_ClassOrStructTag)
387           | (1LL << CodeCompletionContext::CCC_Type)
388           | (1LL << CodeCompletionContext::CCC_PotentiallyQualifiedName)
389           | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
390 
391         if (isa<NamespaceDecl>(R.Declaration) ||
392             isa<NamespaceAliasDecl>(R.Declaration))
393           NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
394 
395         if (unsigned RemainingContexts
396                                 = NNSContexts & ~CachedResult.ShowInContexts) {
397           // If there any contexts where this completion can be a
398           // nested-name-specifier but isn't already an option, create a
399           // nested-name-specifier completion.
400           R.StartsNestedNameSpecifier = true;
401           CachedResult.Completion = R.CreateCodeCompletionString(
402               *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
403               IncludeBriefCommentsInCodeCompletion);
404           CachedResult.ShowInContexts = RemainingContexts;
405           CachedResult.Priority = CCP_NestedNameSpecifier;
406           CachedResult.TypeClass = STC_Void;
407           CachedResult.Type = 0;
408           CachedCompletionResults.push_back(CachedResult);
409         }
410       }
411       break;
412     }
413 
414     case Result::RK_Keyword:
415     case Result::RK_Pattern:
416       // Ignore keywords and patterns; we don't care, since they are so
417       // easily regenerated.
418       break;
419 
420     case Result::RK_Macro: {
421       CachedCodeCompletionResult CachedResult;
422       CachedResult.Completion = R.CreateCodeCompletionString(
423           *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
424           IncludeBriefCommentsInCodeCompletion);
425       CachedResult.ShowInContexts
426         = (1LL << CodeCompletionContext::CCC_TopLevel)
427         | (1LL << CodeCompletionContext::CCC_ObjCInterface)
428         | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
429         | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
430         | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
431         | (1LL << CodeCompletionContext::CCC_Statement)
432         | (1LL << CodeCompletionContext::CCC_Expression)
433         | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
434         | (1LL << CodeCompletionContext::CCC_MacroNameUse)
435         | (1LL << CodeCompletionContext::CCC_PreprocessorExpression)
436         | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
437         | (1LL << CodeCompletionContext::CCC_OtherWithMacros);
438 
439       CachedResult.Priority = R.Priority;
440       CachedResult.Kind = R.CursorKind;
441       CachedResult.Availability = R.Availability;
442       CachedResult.TypeClass = STC_Void;
443       CachedResult.Type = 0;
444       CachedCompletionResults.push_back(CachedResult);
445       break;
446     }
447     }
448   }
449 
450   // Save the current top-level hash value.
451   CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
452 }
453 
454 void ASTUnit::ClearCachedCompletionResults() {
455   CachedCompletionResults.clear();
456   CachedCompletionTypes.clear();
457   CachedCompletionAllocator = nullptr;
458 }
459 
460 namespace {
461 
462 /// \brief Gathers information from ASTReader that will be used to initialize
463 /// a Preprocessor.
464 class ASTInfoCollector : public ASTReaderListener {
465   Preprocessor &PP;
466   ASTContext *Context;
467   HeaderSearchOptions &HSOpts;
468   PreprocessorOptions &PPOpts;
469   LangOptions &LangOpt;
470   std::shared_ptr<TargetOptions> &TargetOpts;
471   IntrusiveRefCntPtr<TargetInfo> &Target;
472   unsigned &Counter;
473 
474   bool InitializedLanguage;
475 public:
476   ASTInfoCollector(Preprocessor &PP, ASTContext *Context,
477                    HeaderSearchOptions &HSOpts, PreprocessorOptions &PPOpts,
478                    LangOptions &LangOpt,
479                    std::shared_ptr<TargetOptions> &TargetOpts,
480                    IntrusiveRefCntPtr<TargetInfo> &Target, unsigned &Counter)
481       : PP(PP), Context(Context), HSOpts(HSOpts), PPOpts(PPOpts),
482         LangOpt(LangOpt), TargetOpts(TargetOpts), Target(Target),
483         Counter(Counter), InitializedLanguage(false) {}
484 
485   bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
486                            bool AllowCompatibleDifferences) override {
487     if (InitializedLanguage)
488       return false;
489 
490     LangOpt = LangOpts;
491     InitializedLanguage = true;
492 
493     updated();
494     return false;
495   }
496 
497   virtual bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
498                                        StringRef SpecificModuleCachePath,
499                                        bool Complain) override {
500     this->HSOpts = HSOpts;
501     return false;
502   }
503 
504   virtual bool
505   ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool Complain,
506                           std::string &SuggestedPredefines) override {
507     this->PPOpts = PPOpts;
508     return false;
509   }
510 
511   bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
512                          bool AllowCompatibleDifferences) override {
513     // If we've already initialized the target, don't do it again.
514     if (Target)
515       return false;
516 
517     this->TargetOpts = std::make_shared<TargetOptions>(TargetOpts);
518     Target =
519         TargetInfo::CreateTargetInfo(PP.getDiagnostics(), this->TargetOpts);
520 
521     updated();
522     return false;
523   }
524 
525   void ReadCounter(const serialization::ModuleFile &M,
526                    unsigned Value) override {
527     Counter = Value;
528   }
529 
530 private:
531   void updated() {
532     if (!Target || !InitializedLanguage)
533       return;
534 
535     // Inform the target of the language options.
536     //
537     // FIXME: We shouldn't need to do this, the target should be immutable once
538     // created. This complexity should be lifted elsewhere.
539     Target->adjust(LangOpt);
540 
541     // Initialize the preprocessor.
542     PP.Initialize(*Target);
543 
544     if (!Context)
545       return;
546 
547     // Initialize the ASTContext
548     Context->InitBuiltinTypes(*Target);
549 
550     // Adjust printing policy based on language options.
551     Context->setPrintingPolicy(PrintingPolicy(LangOpt));
552 
553     // We didn't have access to the comment options when the ASTContext was
554     // constructed, so register them now.
555     Context->getCommentCommandTraits().registerCommentOptions(
556         LangOpt.CommentOpts);
557   }
558 };
559 
560   /// \brief Diagnostic consumer that saves each diagnostic it is given.
561 class StoredDiagnosticConsumer : public DiagnosticConsumer {
562   SmallVectorImpl<StoredDiagnostic> *StoredDiags;
563   SmallVectorImpl<ASTUnit::StandaloneDiagnostic> *StandaloneDiags;
564   const LangOptions *LangOpts;
565   SourceManager *SourceMgr;
566 
567 public:
568   StoredDiagnosticConsumer(
569       SmallVectorImpl<StoredDiagnostic> *StoredDiags,
570       SmallVectorImpl<ASTUnit::StandaloneDiagnostic> *StandaloneDiags)
571       : StoredDiags(StoredDiags), StandaloneDiags(StandaloneDiags),
572         LangOpts(nullptr), SourceMgr(nullptr) {
573     assert((StoredDiags || StandaloneDiags) &&
574            "No output collections were passed to StoredDiagnosticConsumer.");
575   }
576 
577   void BeginSourceFile(const LangOptions &LangOpts,
578                        const Preprocessor *PP = nullptr) override {
579     this->LangOpts = &LangOpts;
580     if (PP)
581       SourceMgr = &PP->getSourceManager();
582   }
583 
584   void HandleDiagnostic(DiagnosticsEngine::Level Level,
585                         const Diagnostic &Info) override;
586 };
587 
588 /// \brief RAII object that optionally captures diagnostics, if
589 /// there is no diagnostic client to capture them already.
590 class CaptureDroppedDiagnostics {
591   DiagnosticsEngine &Diags;
592   StoredDiagnosticConsumer Client;
593   DiagnosticConsumer *PreviousClient;
594   std::unique_ptr<DiagnosticConsumer> OwningPreviousClient;
595 
596 public:
597   CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
598                             SmallVectorImpl<StoredDiagnostic> *StoredDiags,
599                             SmallVectorImpl<ASTUnit::StandaloneDiagnostic> *StandaloneDiags)
600       : Diags(Diags), Client(StoredDiags, StandaloneDiags), PreviousClient(nullptr)
601   {
602     if (RequestCapture || Diags.getClient() == nullptr) {
603       OwningPreviousClient = Diags.takeClient();
604       PreviousClient = Diags.getClient();
605       Diags.setClient(&Client, false);
606     }
607   }
608 
609   ~CaptureDroppedDiagnostics() {
610     if (Diags.getClient() == &Client)
611       Diags.setClient(PreviousClient, !!OwningPreviousClient.release());
612   }
613 };
614 
615 } // anonymous namespace
616 
617 static ASTUnit::StandaloneDiagnostic
618 makeStandaloneDiagnostic(const LangOptions &LangOpts,
619                          const StoredDiagnostic &InDiag);
620 
621 void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
622                                                 const Diagnostic &Info) {
623   // Default implementation (Warnings/errors count).
624   DiagnosticConsumer::HandleDiagnostic(Level, Info);
625 
626   // Only record the diagnostic if it's part of the source manager we know
627   // about. This effectively drops diagnostics from modules we're building.
628   // FIXME: In the long run, ee don't want to drop source managers from modules.
629   if (!Info.hasSourceManager() || &Info.getSourceManager() == SourceMgr) {
630     StoredDiagnostic *ResultDiag = nullptr;
631     if (StoredDiags) {
632       StoredDiags->emplace_back(Level, Info);
633       ResultDiag = &StoredDiags->back();
634     }
635 
636     if (StandaloneDiags) {
637       llvm::Optional<StoredDiagnostic> StoredDiag = llvm::None;
638       if (!ResultDiag) {
639         StoredDiag.emplace(Level, Info);
640         ResultDiag = StoredDiag.getPointer();
641       }
642       StandaloneDiags->push_back(
643           makeStandaloneDiagnostic(*LangOpts, *ResultDiag));
644     }
645   }
646 }
647 
648 IntrusiveRefCntPtr<ASTReader> ASTUnit::getASTReader() const {
649   return Reader;
650 }
651 
652 ASTMutationListener *ASTUnit::getASTMutationListener() {
653   if (WriterData)
654     return &WriterData->Writer;
655   return nullptr;
656 }
657 
658 ASTDeserializationListener *ASTUnit::getDeserializationListener() {
659   if (WriterData)
660     return &WriterData->Writer;
661   return nullptr;
662 }
663 
664 std::unique_ptr<llvm::MemoryBuffer>
665 ASTUnit::getBufferForFile(StringRef Filename, std::string *ErrorStr) {
666   assert(FileMgr);
667   auto Buffer = FileMgr->getBufferForFile(Filename);
668   if (Buffer)
669     return std::move(*Buffer);
670   if (ErrorStr)
671     *ErrorStr = Buffer.getError().message();
672   return nullptr;
673 }
674 
675 /// \brief Configure the diagnostics object for use with ASTUnit.
676 void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
677                              ASTUnit &AST, bool CaptureDiagnostics) {
678   assert(Diags.get() && "no DiagnosticsEngine was provided");
679   if (CaptureDiagnostics)
680     Diags->setClient(new StoredDiagnosticConsumer(&AST.StoredDiagnostics, nullptr));
681 }
682 
683 std::unique_ptr<ASTUnit> ASTUnit::LoadFromASTFile(
684     const std::string &Filename, const PCHContainerReader &PCHContainerRdr,
685     WhatToLoad ToLoad, IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
686     const FileSystemOptions &FileSystemOpts, bool UseDebugInfo,
687     bool OnlyLocalDecls, ArrayRef<RemappedFile> RemappedFiles,
688     bool CaptureDiagnostics, bool AllowPCHWithCompilerErrors,
689     bool UserFilesAreVolatile) {
690   std::unique_ptr<ASTUnit> AST(new ASTUnit(true));
691 
692   // Recover resources if we crash before exiting this method.
693   llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
694     ASTUnitCleanup(AST.get());
695   llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
696     llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
697     DiagCleanup(Diags.get());
698 
699   ConfigureDiags(Diags, *AST, CaptureDiagnostics);
700 
701   AST->LangOpts = std::make_shared<LangOptions>();
702   AST->OnlyLocalDecls = OnlyLocalDecls;
703   AST->CaptureDiagnostics = CaptureDiagnostics;
704   AST->Diagnostics = Diags;
705   IntrusiveRefCntPtr<vfs::FileSystem> VFS = vfs::getRealFileSystem();
706   AST->FileMgr = new FileManager(FileSystemOpts, VFS);
707   AST->UserFilesAreVolatile = UserFilesAreVolatile;
708   AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
709                                      AST->getFileManager(),
710                                      UserFilesAreVolatile);
711   AST->PCMCache = new MemoryBufferCache;
712   AST->HSOpts = std::make_shared<HeaderSearchOptions>();
713   AST->HSOpts->ModuleFormat = PCHContainerRdr.getFormat();
714   AST->HeaderInfo.reset(new HeaderSearch(AST->HSOpts,
715                                          AST->getSourceManager(),
716                                          AST->getDiagnostics(),
717                                          AST->getLangOpts(),
718                                          /*Target=*/nullptr));
719   AST->PPOpts = std::make_shared<PreprocessorOptions>();
720 
721   for (const auto &RemappedFile : RemappedFiles)
722     AST->PPOpts->addRemappedFile(RemappedFile.first, RemappedFile.second);
723 
724   // Gather Info for preprocessor construction later on.
725 
726   HeaderSearch &HeaderInfo = *AST->HeaderInfo;
727   unsigned Counter;
728 
729   AST->PP = std::make_shared<Preprocessor>(
730       AST->PPOpts, AST->getDiagnostics(), *AST->LangOpts,
731       AST->getSourceManager(), *AST->PCMCache, HeaderInfo, AST->ModuleLoader,
732       /*IILookup=*/nullptr,
733       /*OwnsHeaderSearch=*/false);
734   Preprocessor &PP = *AST->PP;
735 
736   if (ToLoad >= LoadASTOnly)
737     AST->Ctx = new ASTContext(*AST->LangOpts, AST->getSourceManager(),
738                               PP.getIdentifierTable(), PP.getSelectorTable(),
739                               PP.getBuiltinInfo());
740 
741   bool disableValid = false;
742   if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
743     disableValid = true;
744   AST->Reader = new ASTReader(PP, AST->Ctx.get(), PCHContainerRdr, { },
745                               /*isysroot=*/"",
746                               /*DisableValidation=*/disableValid,
747                               AllowPCHWithCompilerErrors);
748 
749   AST->Reader->setListener(llvm::make_unique<ASTInfoCollector>(
750       *AST->PP, AST->Ctx.get(), *AST->HSOpts, *AST->PPOpts, *AST->LangOpts,
751       AST->TargetOpts, AST->Target, Counter));
752 
753   // Attach the AST reader to the AST context as an external AST
754   // source, so that declarations will be deserialized from the
755   // AST file as needed.
756   // We need the external source to be set up before we read the AST, because
757   // eagerly-deserialized declarations may use it.
758   if (AST->Ctx)
759     AST->Ctx->setExternalSource(AST->Reader);
760 
761   switch (AST->Reader->ReadAST(Filename, serialization::MK_MainFile,
762                           SourceLocation(), ASTReader::ARR_None)) {
763   case ASTReader::Success:
764     break;
765 
766   case ASTReader::Failure:
767   case ASTReader::Missing:
768   case ASTReader::OutOfDate:
769   case ASTReader::VersionMismatch:
770   case ASTReader::ConfigurationMismatch:
771   case ASTReader::HadErrors:
772     AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
773     return nullptr;
774   }
775 
776   AST->OriginalSourceFile = AST->Reader->getOriginalSourceFile();
777 
778   PP.setCounterValue(Counter);
779 
780   // Create an AST consumer, even though it isn't used.
781   if (ToLoad >= LoadASTOnly)
782     AST->Consumer.reset(new ASTConsumer);
783 
784   // Create a semantic analysis object and tell the AST reader about it.
785   if (ToLoad >= LoadEverything) {
786     AST->TheSema.reset(new Sema(PP, *AST->Ctx, *AST->Consumer));
787     AST->TheSema->Initialize();
788     AST->Reader->InitializeSema(*AST->TheSema);
789   }
790 
791   // Tell the diagnostic client that we have started a source file.
792   AST->getDiagnostics().getClient()->BeginSourceFile(PP.getLangOpts(), &PP);
793 
794   return AST;
795 }
796 
797 namespace {
798 
799 /// \brief Add the given macro to the hash of all top-level entities.
800 void AddDefinedMacroToHash(const Token &MacroNameTok, unsigned &Hash) {
801   Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
802 }
803 
804 /// \brief Preprocessor callback class that updates a hash value with the names
805 /// of all macros that have been defined by the translation unit.
806 class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
807   unsigned &Hash;
808 
809 public:
810   explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
811 
812   void MacroDefined(const Token &MacroNameTok,
813                     const MacroDirective *MD) override {
814     AddDefinedMacroToHash(MacroNameTok, Hash);
815   }
816 };
817 
818 /// \brief Add the given declaration to the hash of all top-level entities.
819 void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
820   if (!D)
821     return;
822 
823   DeclContext *DC = D->getDeclContext();
824   if (!DC)
825     return;
826 
827   if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
828     return;
829 
830   if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
831     if (EnumDecl *EnumD = dyn_cast<EnumDecl>(D)) {
832       // For an unscoped enum include the enumerators in the hash since they
833       // enter the top-level namespace.
834       if (!EnumD->isScoped()) {
835         for (const auto *EI : EnumD->enumerators()) {
836           if (EI->getIdentifier())
837             Hash = llvm::HashString(EI->getIdentifier()->getName(), Hash);
838         }
839       }
840     }
841 
842     if (ND->getIdentifier())
843       Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
844     else if (DeclarationName Name = ND->getDeclName()) {
845       std::string NameStr = Name.getAsString();
846       Hash = llvm::HashString(NameStr, Hash);
847     }
848     return;
849   }
850 
851   if (ImportDecl *ImportD = dyn_cast<ImportDecl>(D)) {
852     if (Module *Mod = ImportD->getImportedModule()) {
853       std::string ModName = Mod->getFullModuleName();
854       Hash = llvm::HashString(ModName, Hash);
855     }
856     return;
857   }
858 }
859 
860 class TopLevelDeclTrackerConsumer : public ASTConsumer {
861   ASTUnit &Unit;
862   unsigned &Hash;
863 
864 public:
865   TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
866     : Unit(_Unit), Hash(Hash) {
867     Hash = 0;
868   }
869 
870   void handleTopLevelDecl(Decl *D) {
871     if (!D)
872       return;
873 
874     // FIXME: Currently ObjC method declarations are incorrectly being
875     // reported as top-level declarations, even though their DeclContext
876     // is the containing ObjC @interface/@implementation.  This is a
877     // fundamental problem in the parser right now.
878     if (isa<ObjCMethodDecl>(D))
879       return;
880 
881     AddTopLevelDeclarationToHash(D, Hash);
882     Unit.addTopLevelDecl(D);
883 
884     handleFileLevelDecl(D);
885   }
886 
887   void handleFileLevelDecl(Decl *D) {
888     Unit.addFileLevelDecl(D);
889     if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
890       for (auto *I : NSD->decls())
891         handleFileLevelDecl(I);
892     }
893   }
894 
895   bool HandleTopLevelDecl(DeclGroupRef D) override {
896     for (Decl *TopLevelDecl : D)
897       handleTopLevelDecl(TopLevelDecl);
898     return true;
899   }
900 
901   // We're not interested in "interesting" decls.
902   void HandleInterestingDecl(DeclGroupRef) override {}
903 
904   void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
905     for (Decl *TopLevelDecl : D)
906       handleTopLevelDecl(TopLevelDecl);
907   }
908 
909   ASTMutationListener *GetASTMutationListener() override {
910     return Unit.getASTMutationListener();
911   }
912 
913   ASTDeserializationListener *GetASTDeserializationListener() override {
914     return Unit.getDeserializationListener();
915   }
916 };
917 
918 class TopLevelDeclTrackerAction : public ASTFrontendAction {
919 public:
920   ASTUnit &Unit;
921 
922   std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
923                                                  StringRef InFile) override {
924     CI.getPreprocessor().addPPCallbacks(
925         llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
926                                            Unit.getCurrentTopLevelHashValue()));
927     return llvm::make_unique<TopLevelDeclTrackerConsumer>(
928         Unit, Unit.getCurrentTopLevelHashValue());
929   }
930 
931 public:
932   TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
933 
934   bool hasCodeCompletionSupport() const override { return false; }
935   TranslationUnitKind getTranslationUnitKind() override {
936     return Unit.getTranslationUnitKind();
937   }
938 };
939 
940 class ASTUnitPreambleCallbacks : public PreambleCallbacks {
941 public:
942   unsigned getHash() const { return Hash; }
943 
944   std::vector<Decl *> takeTopLevelDecls() { return std::move(TopLevelDecls); }
945 
946   std::vector<serialization::DeclID> takeTopLevelDeclIDs() {
947     return std::move(TopLevelDeclIDs);
948   }
949 
950   void AfterPCHEmitted(ASTWriter &Writer) override {
951     TopLevelDeclIDs.reserve(TopLevelDecls.size());
952     for (Decl *D : TopLevelDecls) {
953       // Invalid top-level decls may not have been serialized.
954       if (D->isInvalidDecl())
955         continue;
956       TopLevelDeclIDs.push_back(Writer.getDeclID(D));
957     }
958   }
959 
960   void HandleTopLevelDecl(DeclGroupRef DG) override {
961     for (Decl *D : DG) {
962       // FIXME: Currently ObjC method declarations are incorrectly being
963       // reported as top-level declarations, even though their DeclContext
964       // is the containing ObjC @interface/@implementation.  This is a
965       // fundamental problem in the parser right now.
966       if (isa<ObjCMethodDecl>(D))
967         continue;
968       AddTopLevelDeclarationToHash(D, Hash);
969       TopLevelDecls.push_back(D);
970     }
971   }
972 
973   void HandleMacroDefined(const Token &MacroNameTok,
974                           const MacroDirective *MD) override {
975     AddDefinedMacroToHash(MacroNameTok, Hash);
976   }
977 
978 private:
979   unsigned Hash = 0;
980   std::vector<Decl *> TopLevelDecls;
981   std::vector<serialization::DeclID> TopLevelDeclIDs;
982   llvm::SmallVector<ASTUnit::StandaloneDiagnostic, 4> PreambleDiags;
983 };
984 
985 } // anonymous namespace
986 
987 static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag) {
988   return StoredDiag.getLocation().isValid();
989 }
990 
991 static void
992 checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &StoredDiags) {
993   // Get rid of stored diagnostics except the ones from the driver which do not
994   // have a source location.
995   StoredDiags.erase(
996       std::remove_if(StoredDiags.begin(), StoredDiags.end(), isNonDriverDiag),
997       StoredDiags.end());
998 }
999 
1000 static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
1001                                                               StoredDiagnostics,
1002                                   SourceManager &SM) {
1003   // The stored diagnostic has the old source manager in it; update
1004   // the locations to refer into the new source manager. Since we've
1005   // been careful to make sure that the source manager's state
1006   // before and after are identical, so that we can reuse the source
1007   // location itself.
1008   for (StoredDiagnostic &SD : StoredDiagnostics) {
1009     if (SD.getLocation().isValid()) {
1010       FullSourceLoc Loc(SD.getLocation(), SM);
1011       SD.setLocation(Loc);
1012     }
1013   }
1014 }
1015 
1016 static IntrusiveRefCntPtr<vfs::FileSystem> createVFSOverlayForPreamblePCH(
1017     StringRef PCHFilename,
1018     IntrusiveRefCntPtr<vfs::FileSystem> RealFS,
1019     IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
1020   // We want only the PCH file from the real filesystem to be available,
1021   // so we create an in-memory VFS with just that and overlay it on top.
1022   auto Buf = RealFS->getBufferForFile(PCHFilename);
1023   if (!Buf)
1024     return VFS;
1025   IntrusiveRefCntPtr<vfs::InMemoryFileSystem>
1026       PCHFS(new vfs::InMemoryFileSystem());
1027   PCHFS->addFile(PCHFilename, 0, std::move(*Buf));
1028   IntrusiveRefCntPtr<vfs::OverlayFileSystem>
1029       Overlay(new vfs::OverlayFileSystem(VFS));
1030   Overlay->pushOverlay(PCHFS);
1031   return Overlay;
1032 }
1033 
1034 /// Parse the source file into a translation unit using the given compiler
1035 /// invocation, replacing the current translation unit.
1036 ///
1037 /// \returns True if a failure occurred that causes the ASTUnit not to
1038 /// contain any translation-unit information, false otherwise.
1039 bool ASTUnit::Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1040                     std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer,
1041                     IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
1042   if (!Invocation)
1043     return true;
1044 
1045   // Create the compiler instance to use for building the AST.
1046   std::unique_ptr<CompilerInstance> Clang(
1047       new CompilerInstance(std::move(PCHContainerOps)));
1048   if (FileMgr && VFS) {
1049     assert(VFS == FileMgr->getVirtualFileSystem() &&
1050            "VFS passed to Parse and VFS in FileMgr are different");
1051   } else if (VFS) {
1052     Clang->setVirtualFileSystem(VFS);
1053   }
1054 
1055   // Make sure we can access the PCH file even if we're using a VFS
1056   if (!VFS && FileMgr)
1057     VFS = FileMgr->getVirtualFileSystem();
1058   IntrusiveRefCntPtr<vfs::FileSystem> RealFS = vfs::getRealFileSystem();
1059   if (OverrideMainBuffer && VFS && RealFS && VFS != RealFS &&
1060       !VFS->exists(Preamble->GetPCHPath())) {
1061     // We have a slight inconsistency here -- we're using the VFS to
1062     // read files, but the PCH was generated in the real file system.
1063     VFS = createVFSOverlayForPreamblePCH(Preamble->GetPCHPath(), RealFS, VFS);
1064     if (FileMgr) {
1065       FileMgr = new FileManager(FileMgr->getFileSystemOpts(), VFS);
1066       Clang->setFileManager(FileMgr.get());
1067     }
1068     else {
1069       Clang->setVirtualFileSystem(VFS);
1070     }
1071   }
1072 
1073   // Recover resources if we crash before exiting this method.
1074   llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1075     CICleanup(Clang.get());
1076 
1077   Clang->setInvocation(std::make_shared<CompilerInvocation>(*Invocation));
1078   OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1079 
1080   // Set up diagnostics, capturing any diagnostics that would
1081   // otherwise be dropped.
1082   Clang->setDiagnostics(&getDiagnostics());
1083 
1084   // Create the target instance.
1085   Clang->setTarget(TargetInfo::CreateTargetInfo(
1086       Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
1087   if (!Clang->hasTarget())
1088     return true;
1089 
1090   // Inform the target of the language options.
1091   //
1092   // FIXME: We shouldn't need to do this, the target should be immutable once
1093   // created. This complexity should be lifted elsewhere.
1094   Clang->getTarget().adjust(Clang->getLangOpts());
1095 
1096   assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1097          "Invocation must have exactly one source file!");
1098   assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1099              InputKind::Source &&
1100          "FIXME: AST inputs not yet supported here!");
1101   assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1102              InputKind::LLVM_IR &&
1103          "IR inputs not support here!");
1104 
1105   // Configure the various subsystems.
1106   LangOpts = Clang->getInvocation().LangOpts;
1107   FileSystemOpts = Clang->getFileSystemOpts();
1108   if (!FileMgr) {
1109     Clang->createFileManager();
1110     FileMgr = &Clang->getFileManager();
1111   }
1112 
1113   ResetForParse();
1114 
1115   SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1116                                 UserFilesAreVolatile);
1117   if (!OverrideMainBuffer) {
1118     checkAndRemoveNonDriverDiags(StoredDiagnostics);
1119     TopLevelDeclsInPreamble.clear();
1120   }
1121 
1122   // Create a file manager object to provide access to and cache the filesystem.
1123   Clang->setFileManager(&getFileManager());
1124 
1125   // Create the source manager.
1126   Clang->setSourceManager(&getSourceManager());
1127 
1128   // If the main file has been overridden due to the use of a preamble,
1129   // make that override happen and introduce the preamble.
1130   if (OverrideMainBuffer) {
1131     assert(Preamble && "No preamble was built, but OverrideMainBuffer is not null");
1132     Preamble->AddImplicitPreamble(Clang->getInvocation(), OverrideMainBuffer.get());
1133 
1134     // The stored diagnostic has the old source manager in it; update
1135     // the locations to refer into the new source manager. Since we've
1136     // been careful to make sure that the source manager's state
1137     // before and after are identical, so that we can reuse the source
1138     // location itself.
1139     checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
1140 
1141     // Keep track of the override buffer;
1142     SavedMainFileBuffer = std::move(OverrideMainBuffer);
1143   }
1144 
1145   std::unique_ptr<TopLevelDeclTrackerAction> Act(
1146       new TopLevelDeclTrackerAction(*this));
1147 
1148   // Recover resources if we crash before exiting this method.
1149   llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1150     ActCleanup(Act.get());
1151 
1152   if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
1153     goto error;
1154 
1155   if (SavedMainFileBuffer)
1156     TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
1157                                PreambleDiagnostics, StoredDiagnostics);
1158   else
1159     PreambleSrcLocCache.clear();
1160 
1161   if (!Act->Execute())
1162     goto error;
1163 
1164   transferASTDataFromCompilerInstance(*Clang);
1165 
1166   Act->EndSourceFile();
1167 
1168   FailedParseDiagnostics.clear();
1169 
1170   return false;
1171 
1172 error:
1173   // Remove the overridden buffer we used for the preamble.
1174   SavedMainFileBuffer = nullptr;
1175 
1176   // Keep the ownership of the data in the ASTUnit because the client may
1177   // want to see the diagnostics.
1178   transferASTDataFromCompilerInstance(*Clang);
1179   FailedParseDiagnostics.swap(StoredDiagnostics);
1180   StoredDiagnostics.clear();
1181   NumStoredDiagnosticsFromDriver = 0;
1182   return true;
1183 }
1184 
1185 static std::pair<unsigned, unsigned>
1186 makeStandaloneRange(CharSourceRange Range, const SourceManager &SM,
1187                     const LangOptions &LangOpts) {
1188   CharSourceRange FileRange = Lexer::makeFileCharRange(Range, SM, LangOpts);
1189   unsigned Offset = SM.getFileOffset(FileRange.getBegin());
1190   unsigned EndOffset = SM.getFileOffset(FileRange.getEnd());
1191   return std::make_pair(Offset, EndOffset);
1192 }
1193 
1194 static ASTUnit::StandaloneFixIt makeStandaloneFixIt(const SourceManager &SM,
1195                                                     const LangOptions &LangOpts,
1196                                                     const FixItHint &InFix) {
1197   ASTUnit::StandaloneFixIt OutFix;
1198   OutFix.RemoveRange = makeStandaloneRange(InFix.RemoveRange, SM, LangOpts);
1199   OutFix.InsertFromRange = makeStandaloneRange(InFix.InsertFromRange, SM,
1200                                                LangOpts);
1201   OutFix.CodeToInsert = InFix.CodeToInsert;
1202   OutFix.BeforePreviousInsertions = InFix.BeforePreviousInsertions;
1203   return OutFix;
1204 }
1205 
1206 static ASTUnit::StandaloneDiagnostic
1207 makeStandaloneDiagnostic(const LangOptions &LangOpts,
1208                          const StoredDiagnostic &InDiag) {
1209   ASTUnit::StandaloneDiagnostic OutDiag;
1210   OutDiag.ID = InDiag.getID();
1211   OutDiag.Level = InDiag.getLevel();
1212   OutDiag.Message = InDiag.getMessage();
1213   OutDiag.LocOffset = 0;
1214   if (InDiag.getLocation().isInvalid())
1215     return OutDiag;
1216   const SourceManager &SM = InDiag.getLocation().getManager();
1217   SourceLocation FileLoc = SM.getFileLoc(InDiag.getLocation());
1218   OutDiag.Filename = SM.getFilename(FileLoc);
1219   if (OutDiag.Filename.empty())
1220     return OutDiag;
1221   OutDiag.LocOffset = SM.getFileOffset(FileLoc);
1222   for (const CharSourceRange &Range : InDiag.getRanges())
1223     OutDiag.Ranges.push_back(makeStandaloneRange(Range, SM, LangOpts));
1224   for (const FixItHint &FixIt : InDiag.getFixIts())
1225     OutDiag.FixIts.push_back(makeStandaloneFixIt(SM, LangOpts, FixIt));
1226 
1227   return OutDiag;
1228 }
1229 
1230 /// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1231 /// the source file.
1232 ///
1233 /// This routine will compute the preamble of the main source file. If a
1234 /// non-trivial preamble is found, it will precompile that preamble into a
1235 /// precompiled header so that the precompiled preamble can be used to reduce
1236 /// reparsing time. If a precompiled preamble has already been constructed,
1237 /// this routine will determine if it is still valid and, if so, avoid
1238 /// rebuilding the precompiled preamble.
1239 ///
1240 /// \param AllowRebuild When true (the default), this routine is
1241 /// allowed to rebuild the precompiled preamble if it is found to be
1242 /// out-of-date.
1243 ///
1244 /// \param MaxLines When non-zero, the maximum number of lines that
1245 /// can occur within the preamble.
1246 ///
1247 /// \returns If the precompiled preamble can be used, returns a newly-allocated
1248 /// buffer that should be used in place of the main file when doing so.
1249 /// Otherwise, returns a NULL pointer.
1250 std::unique_ptr<llvm::MemoryBuffer>
1251 ASTUnit::getMainBufferWithPrecompiledPreamble(
1252     std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1253     const CompilerInvocation &PreambleInvocationIn,
1254     IntrusiveRefCntPtr<vfs::FileSystem> VFS, bool AllowRebuild,
1255     unsigned MaxLines) {
1256 
1257   auto MainFilePath =
1258       PreambleInvocationIn.getFrontendOpts().Inputs[0].getFile();
1259   std::unique_ptr<llvm::MemoryBuffer> MainFileBuffer =
1260       getBufferForFileHandlingRemapping(PreambleInvocationIn, VFS.get(),
1261                                         MainFilePath);
1262   if (!MainFileBuffer)
1263     return nullptr;
1264 
1265   PreambleBounds Bounds =
1266       ComputePreambleBounds(*PreambleInvocationIn.getLangOpts(),
1267                             MainFileBuffer.get(), MaxLines);
1268   if (!Bounds.Size)
1269     return nullptr;
1270 
1271   if (Preamble) {
1272     if (Preamble->CanReuse(PreambleInvocationIn, MainFileBuffer.get(), Bounds,
1273                            VFS.get())) {
1274       // Okay! We can re-use the precompiled preamble.
1275 
1276       // Set the state of the diagnostic object to mimic its state
1277       // after parsing the preamble.
1278       getDiagnostics().Reset();
1279       ProcessWarningOptions(getDiagnostics(),
1280                             PreambleInvocationIn.getDiagnosticOpts());
1281       getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1282 
1283       PreambleRebuildCounter = 1;
1284       return MainFileBuffer;
1285     } else {
1286       Preamble.reset();
1287       PreambleDiagnostics.clear();
1288       TopLevelDeclsInPreamble.clear();
1289       PreambleRebuildCounter = 1;
1290     }
1291   }
1292 
1293   // If the preamble rebuild counter > 1, it's because we previously
1294   // failed to build a preamble and we're not yet ready to try
1295   // again. Decrement the counter and return a failure.
1296   if (PreambleRebuildCounter > 1) {
1297     --PreambleRebuildCounter;
1298     return nullptr;
1299   }
1300 
1301   assert(!Preamble && "No Preamble should be stored at that point");
1302   // If we aren't allowed to rebuild the precompiled preamble, just
1303   // return now.
1304   if (!AllowRebuild)
1305     return nullptr;
1306 
1307   SmallVector<StandaloneDiagnostic, 4> NewPreambleDiagsStandalone;
1308   SmallVector<StoredDiagnostic, 4> NewPreambleDiags;
1309   ASTUnitPreambleCallbacks Callbacks;
1310   {
1311     llvm::Optional<CaptureDroppedDiagnostics> Capture;
1312     if (CaptureDiagnostics)
1313       Capture.emplace(/*RequestCapture=*/true, *Diagnostics, &NewPreambleDiags,
1314                       &NewPreambleDiagsStandalone);
1315 
1316     // We did not previously compute a preamble, or it can't be reused anyway.
1317     SimpleTimer PreambleTimer(WantTiming);
1318     PreambleTimer.setOutput("Precompiling preamble");
1319 
1320     llvm::ErrorOr<PrecompiledPreamble> NewPreamble = PrecompiledPreamble::Build(
1321         PreambleInvocationIn, MainFileBuffer.get(), Bounds, *Diagnostics, VFS,
1322         PCHContainerOps, Callbacks);
1323     if (NewPreamble) {
1324       Preamble = std::move(*NewPreamble);
1325       PreambleRebuildCounter = 1;
1326     } else {
1327       switch (static_cast<BuildPreambleError>(NewPreamble.getError().value())) {
1328       case BuildPreambleError::CouldntCreateTempFile:
1329       case BuildPreambleError::PreambleIsEmpty:
1330         // Try again next time.
1331         PreambleRebuildCounter = 1;
1332         return nullptr;
1333       case BuildPreambleError::CouldntCreateTargetInfo:
1334       case BuildPreambleError::BeginSourceFileFailed:
1335       case BuildPreambleError::CouldntEmitPCH:
1336       case BuildPreambleError::CouldntCreateVFSOverlay:
1337         // These erros are more likely to repeat, retry after some period.
1338         PreambleRebuildCounter = DefaultPreambleRebuildInterval;
1339         return nullptr;
1340       }
1341       llvm_unreachable("unexpected BuildPreambleError");
1342     }
1343   }
1344 
1345   assert(Preamble && "Preamble wasn't built");
1346 
1347   TopLevelDecls.clear();
1348   TopLevelDeclsInPreamble = Callbacks.takeTopLevelDeclIDs();
1349   PreambleTopLevelHashValue = Callbacks.getHash();
1350 
1351   NumWarningsInPreamble = getDiagnostics().getNumWarnings();
1352 
1353   checkAndRemoveNonDriverDiags(NewPreambleDiags);
1354   StoredDiagnostics = std::move(NewPreambleDiags);
1355   PreambleDiagnostics = std::move(NewPreambleDiagsStandalone);
1356 
1357   // If the hash of top-level entities differs from the hash of the top-level
1358   // entities the last time we rebuilt the preamble, clear out the completion
1359   // cache.
1360   if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1361     CompletionCacheTopLevelHashValue = 0;
1362     PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1363   }
1364 
1365   return MainFileBuffer;
1366 }
1367 
1368 void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1369   assert(Preamble && "Should only be called when preamble was built");
1370 
1371   std::vector<Decl *> Resolved;
1372   Resolved.reserve(TopLevelDeclsInPreamble.size());
1373   ExternalASTSource &Source = *getASTContext().getExternalSource();
1374   for (serialization::DeclID TopLevelDecl : TopLevelDeclsInPreamble) {
1375     // Resolve the declaration ID to an actual declaration, possibly
1376     // deserializing the declaration in the process.
1377     if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
1378       Resolved.push_back(D);
1379   }
1380   TopLevelDeclsInPreamble.clear();
1381   TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1382 }
1383 
1384 void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
1385   // Steal the created target, context, and preprocessor if they have been
1386   // created.
1387   assert(CI.hasInvocation() && "missing invocation");
1388   LangOpts = CI.getInvocation().LangOpts;
1389   TheSema = CI.takeSema();
1390   Consumer = CI.takeASTConsumer();
1391   if (CI.hasASTContext())
1392     Ctx = &CI.getASTContext();
1393   if (CI.hasPreprocessor())
1394     PP = CI.getPreprocessorPtr();
1395   CI.setSourceManager(nullptr);
1396   CI.setFileManager(nullptr);
1397   if (CI.hasTarget())
1398     Target = &CI.getTarget();
1399   Reader = CI.getModuleManager();
1400   HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure();
1401 }
1402 
1403 StringRef ASTUnit::getMainFileName() const {
1404   if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1405     const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0];
1406     if (Input.isFile())
1407       return Input.getFile();
1408     else
1409       return Input.getBuffer()->getBufferIdentifier();
1410   }
1411 
1412   if (SourceMgr) {
1413     if (const FileEntry *
1414           FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
1415       return FE->getName();
1416   }
1417 
1418   return StringRef();
1419 }
1420 
1421 StringRef ASTUnit::getASTFileName() const {
1422   if (!isMainFileAST())
1423     return StringRef();
1424 
1425   serialization::ModuleFile &
1426     Mod = Reader->getModuleManager().getPrimaryModule();
1427   return Mod.FileName;
1428 }
1429 
1430 std::unique_ptr<ASTUnit>
1431 ASTUnit::create(std::shared_ptr<CompilerInvocation> CI,
1432                 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1433                 bool CaptureDiagnostics, bool UserFilesAreVolatile) {
1434   std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
1435   ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1436   IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1437       createVFSFromCompilerInvocation(*CI, *Diags);
1438   if (!VFS)
1439     return nullptr;
1440   AST->Diagnostics = Diags;
1441   AST->FileSystemOpts = CI->getFileSystemOpts();
1442   AST->Invocation = std::move(CI);
1443   AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
1444   AST->UserFilesAreVolatile = UserFilesAreVolatile;
1445   AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1446                                      UserFilesAreVolatile);
1447   AST->PCMCache = new MemoryBufferCache;
1448 
1449   return AST;
1450 }
1451 
1452 ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(
1453     std::shared_ptr<CompilerInvocation> CI,
1454     std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1455     IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FrontendAction *Action,
1456     ASTUnit *Unit, bool Persistent, StringRef ResourceFilesPath,
1457     bool OnlyLocalDecls, bool CaptureDiagnostics,
1458     unsigned PrecompilePreambleAfterNParses, bool CacheCodeCompletionResults,
1459     bool IncludeBriefCommentsInCodeCompletion, bool UserFilesAreVolatile,
1460     std::unique_ptr<ASTUnit> *ErrAST) {
1461   assert(CI && "A CompilerInvocation is required");
1462 
1463   std::unique_ptr<ASTUnit> OwnAST;
1464   ASTUnit *AST = Unit;
1465   if (!AST) {
1466     // Create the AST unit.
1467     OwnAST = create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile);
1468     AST = OwnAST.get();
1469     if (!AST)
1470       return nullptr;
1471   }
1472 
1473   if (!ResourceFilesPath.empty()) {
1474     // Override the resources path.
1475     CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1476   }
1477   AST->OnlyLocalDecls = OnlyLocalDecls;
1478   AST->CaptureDiagnostics = CaptureDiagnostics;
1479   if (PrecompilePreambleAfterNParses > 0)
1480     AST->PreambleRebuildCounter = PrecompilePreambleAfterNParses;
1481   AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
1482   AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1483   AST->IncludeBriefCommentsInCodeCompletion
1484     = IncludeBriefCommentsInCodeCompletion;
1485 
1486   // Recover resources if we crash before exiting this method.
1487   llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1488     ASTUnitCleanup(OwnAST.get());
1489   llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1490     llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
1491     DiagCleanup(Diags.get());
1492 
1493   // We'll manage file buffers ourselves.
1494   CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1495   CI->getFrontendOpts().DisableFree = false;
1496   ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1497 
1498   // Create the compiler instance to use for building the AST.
1499   std::unique_ptr<CompilerInstance> Clang(
1500       new CompilerInstance(std::move(PCHContainerOps)));
1501 
1502   // Recover resources if we crash before exiting this method.
1503   llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1504     CICleanup(Clang.get());
1505 
1506   Clang->setInvocation(std::move(CI));
1507   AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1508 
1509   // Set up diagnostics, capturing any diagnostics that would
1510   // otherwise be dropped.
1511   Clang->setDiagnostics(&AST->getDiagnostics());
1512 
1513   // Create the target instance.
1514   Clang->setTarget(TargetInfo::CreateTargetInfo(
1515       Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
1516   if (!Clang->hasTarget())
1517     return nullptr;
1518 
1519   // Inform the target of the language options.
1520   //
1521   // FIXME: We shouldn't need to do this, the target should be immutable once
1522   // created. This complexity should be lifted elsewhere.
1523   Clang->getTarget().adjust(Clang->getLangOpts());
1524 
1525   assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1526          "Invocation must have exactly one source file!");
1527   assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1528              InputKind::Source &&
1529          "FIXME: AST inputs not yet supported here!");
1530   assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1531              InputKind::LLVM_IR &&
1532          "IR inputs not support here!");
1533 
1534   // Configure the various subsystems.
1535   AST->TheSema.reset();
1536   AST->Ctx = nullptr;
1537   AST->PP = nullptr;
1538   AST->Reader = nullptr;
1539 
1540   // Create a file manager object to provide access to and cache the filesystem.
1541   Clang->setFileManager(&AST->getFileManager());
1542 
1543   // Create the source manager.
1544   Clang->setSourceManager(&AST->getSourceManager());
1545 
1546   FrontendAction *Act = Action;
1547 
1548   std::unique_ptr<TopLevelDeclTrackerAction> TrackerAct;
1549   if (!Act) {
1550     TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1551     Act = TrackerAct.get();
1552   }
1553 
1554   // Recover resources if we crash before exiting this method.
1555   llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1556     ActCleanup(TrackerAct.get());
1557 
1558   if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1559     AST->transferASTDataFromCompilerInstance(*Clang);
1560     if (OwnAST && ErrAST)
1561       ErrAST->swap(OwnAST);
1562 
1563     return nullptr;
1564   }
1565 
1566   if (Persistent && !TrackerAct) {
1567     Clang->getPreprocessor().addPPCallbacks(
1568         llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
1569                                            AST->getCurrentTopLevelHashValue()));
1570     std::vector<std::unique_ptr<ASTConsumer>> Consumers;
1571     if (Clang->hasASTConsumer())
1572       Consumers.push_back(Clang->takeASTConsumer());
1573     Consumers.push_back(llvm::make_unique<TopLevelDeclTrackerConsumer>(
1574         *AST, AST->getCurrentTopLevelHashValue()));
1575     Clang->setASTConsumer(
1576         llvm::make_unique<MultiplexConsumer>(std::move(Consumers)));
1577   }
1578   if (!Act->Execute()) {
1579     AST->transferASTDataFromCompilerInstance(*Clang);
1580     if (OwnAST && ErrAST)
1581       ErrAST->swap(OwnAST);
1582 
1583     return nullptr;
1584   }
1585 
1586   // Steal the created target, context, and preprocessor.
1587   AST->transferASTDataFromCompilerInstance(*Clang);
1588 
1589   Act->EndSourceFile();
1590 
1591   if (OwnAST)
1592     return OwnAST.release();
1593   else
1594     return AST;
1595 }
1596 
1597 bool ASTUnit::LoadFromCompilerInvocation(
1598     std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1599     unsigned PrecompilePreambleAfterNParses,
1600     IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
1601   if (!Invocation)
1602     return true;
1603 
1604   assert(VFS && "VFS is null");
1605 
1606   // We'll manage file buffers ourselves.
1607   Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1608   Invocation->getFrontendOpts().DisableFree = false;
1609   getDiagnostics().Reset();
1610   ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1611 
1612   std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
1613   if (PrecompilePreambleAfterNParses > 0) {
1614     PreambleRebuildCounter = PrecompilePreambleAfterNParses;
1615     OverrideMainBuffer =
1616         getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS);
1617     getDiagnostics().Reset();
1618     ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1619   }
1620 
1621   SimpleTimer ParsingTimer(WantTiming);
1622   ParsingTimer.setOutput("Parsing " + getMainFileName());
1623 
1624   // Recover resources if we crash before exiting this method.
1625   llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1626     MemBufferCleanup(OverrideMainBuffer.get());
1627 
1628   return Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS);
1629 }
1630 
1631 std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation(
1632     std::shared_ptr<CompilerInvocation> CI,
1633     std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1634     IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FileManager *FileMgr,
1635     bool OnlyLocalDecls, bool CaptureDiagnostics,
1636     unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
1637     bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1638     bool UserFilesAreVolatile) {
1639   // Create the AST unit.
1640   std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
1641   ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1642   AST->Diagnostics = Diags;
1643   AST->OnlyLocalDecls = OnlyLocalDecls;
1644   AST->CaptureDiagnostics = CaptureDiagnostics;
1645   AST->TUKind = TUKind;
1646   AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1647   AST->IncludeBriefCommentsInCodeCompletion
1648     = IncludeBriefCommentsInCodeCompletion;
1649   AST->Invocation = std::move(CI);
1650   AST->FileSystemOpts = FileMgr->getFileSystemOpts();
1651   AST->FileMgr = FileMgr;
1652   AST->UserFilesAreVolatile = UserFilesAreVolatile;
1653 
1654   // Recover resources if we crash before exiting this method.
1655   llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1656     ASTUnitCleanup(AST.get());
1657   llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1658     llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
1659     DiagCleanup(Diags.get());
1660 
1661   if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
1662                                       PrecompilePreambleAfterNParses,
1663                                       AST->FileMgr->getVirtualFileSystem()))
1664     return nullptr;
1665   return AST;
1666 }
1667 
1668 ASTUnit *ASTUnit::LoadFromCommandLine(
1669     const char **ArgBegin, const char **ArgEnd,
1670     std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1671     IntrusiveRefCntPtr<DiagnosticsEngine> Diags, StringRef ResourceFilesPath,
1672     bool OnlyLocalDecls, bool CaptureDiagnostics,
1673     ArrayRef<RemappedFile> RemappedFiles, bool RemappedFilesKeepOriginalName,
1674     unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
1675     bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1676     bool AllowPCHWithCompilerErrors, bool SkipFunctionBodies,
1677     bool SingleFileParse, bool UserFilesAreVolatile, bool ForSerialization,
1678     llvm::Optional<StringRef> ModuleFormat, std::unique_ptr<ASTUnit> *ErrAST,
1679     IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
1680   assert(Diags.get() && "no DiagnosticsEngine was provided");
1681 
1682   SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
1683 
1684   std::shared_ptr<CompilerInvocation> CI;
1685 
1686   {
1687 
1688     CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
1689                                       &StoredDiagnostics, nullptr);
1690 
1691     CI = clang::createInvocationFromCommandLine(
1692         llvm::makeArrayRef(ArgBegin, ArgEnd), Diags, VFS);
1693     if (!CI)
1694       return nullptr;
1695   }
1696 
1697   // Override any files that need remapping
1698   for (const auto &RemappedFile : RemappedFiles) {
1699     CI->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
1700                                               RemappedFile.second);
1701   }
1702   PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
1703   PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
1704   PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
1705   PPOpts.SingleFileParseMode = SingleFileParse;
1706 
1707   // Override the resources path.
1708   CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1709 
1710   CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
1711 
1712   if (ModuleFormat)
1713     CI->getHeaderSearchOpts().ModuleFormat = ModuleFormat.getValue();
1714 
1715   // Create the AST unit.
1716   std::unique_ptr<ASTUnit> AST;
1717   AST.reset(new ASTUnit(false));
1718   ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1719   AST->Diagnostics = Diags;
1720   AST->FileSystemOpts = CI->getFileSystemOpts();
1721   if (!VFS)
1722     VFS = vfs::getRealFileSystem();
1723   VFS = createVFSFromCompilerInvocation(*CI, *Diags, VFS);
1724   if (!VFS)
1725     return nullptr;
1726   AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
1727   AST->PCMCache = new MemoryBufferCache;
1728   AST->OnlyLocalDecls = OnlyLocalDecls;
1729   AST->CaptureDiagnostics = CaptureDiagnostics;
1730   AST->TUKind = TUKind;
1731   AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1732   AST->IncludeBriefCommentsInCodeCompletion
1733     = IncludeBriefCommentsInCodeCompletion;
1734   AST->UserFilesAreVolatile = UserFilesAreVolatile;
1735   AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
1736   AST->StoredDiagnostics.swap(StoredDiagnostics);
1737   AST->Invocation = CI;
1738   if (ForSerialization)
1739     AST->WriterData.reset(new ASTWriterData(*AST->PCMCache));
1740   // Zero out now to ease cleanup during crash recovery.
1741   CI = nullptr;
1742   Diags = nullptr;
1743 
1744   // Recover resources if we crash before exiting this method.
1745   llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1746     ASTUnitCleanup(AST.get());
1747 
1748   if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
1749                                       PrecompilePreambleAfterNParses,
1750                                       VFS)) {
1751     // Some error occurred, if caller wants to examine diagnostics, pass it the
1752     // ASTUnit.
1753     if (ErrAST) {
1754       AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
1755       ErrAST->swap(AST);
1756     }
1757     return nullptr;
1758   }
1759 
1760   return AST.release();
1761 }
1762 
1763 bool ASTUnit::Reparse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1764                       ArrayRef<RemappedFile> RemappedFiles,
1765                       IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
1766   if (!Invocation)
1767     return true;
1768 
1769   if (!VFS) {
1770     assert(FileMgr && "FileMgr is null on Reparse call");
1771     VFS = FileMgr->getVirtualFileSystem();
1772   }
1773 
1774   clearFileLevelDecls();
1775 
1776   SimpleTimer ParsingTimer(WantTiming);
1777   ParsingTimer.setOutput("Reparsing " + getMainFileName());
1778 
1779   // Remap files.
1780   PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
1781   for (const auto &RB : PPOpts.RemappedFileBuffers)
1782     delete RB.second;
1783 
1784   Invocation->getPreprocessorOpts().clearRemappedFiles();
1785   for (const auto &RemappedFile : RemappedFiles) {
1786     Invocation->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
1787                                                       RemappedFile.second);
1788   }
1789 
1790   // If we have a preamble file lying around, or if we might try to
1791   // build a precompiled preamble, do so now.
1792   std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
1793   if (Preamble || PreambleRebuildCounter > 0)
1794     OverrideMainBuffer =
1795         getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS);
1796 
1797 
1798   // Clear out the diagnostics state.
1799   FileMgr.reset();
1800   getDiagnostics().Reset();
1801   ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1802   if (OverrideMainBuffer)
1803     getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1804 
1805   // Parse the sources
1806   bool Result =
1807       Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS);
1808 
1809   // If we're caching global code-completion results, and the top-level
1810   // declarations have changed, clear out the code-completion cache.
1811   if (!Result && ShouldCacheCodeCompletionResults &&
1812       CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
1813     CacheCodeCompletionResults();
1814 
1815   // We now need to clear out the completion info related to this translation
1816   // unit; it'll be recreated if necessary.
1817   CCTUInfo.reset();
1818 
1819   return Result;
1820 }
1821 
1822 void ASTUnit::ResetForParse() {
1823   SavedMainFileBuffer.reset();
1824 
1825   SourceMgr.reset();
1826   TheSema.reset();
1827   Ctx.reset();
1828   PP.reset();
1829   Reader.reset();
1830 
1831   TopLevelDecls.clear();
1832   clearFileLevelDecls();
1833 }
1834 
1835 //----------------------------------------------------------------------------//
1836 // Code completion
1837 //----------------------------------------------------------------------------//
1838 
1839 namespace {
1840   /// \brief Code completion consumer that combines the cached code-completion
1841   /// results from an ASTUnit with the code-completion results provided to it,
1842   /// then passes the result on to
1843   class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
1844     uint64_t NormalContexts;
1845     ASTUnit &AST;
1846     CodeCompleteConsumer &Next;
1847 
1848   public:
1849     AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
1850                                   const CodeCompleteOptions &CodeCompleteOpts)
1851       : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
1852         AST(AST), Next(Next)
1853     {
1854       // Compute the set of contexts in which we will look when we don't have
1855       // any information about the specific context.
1856       NormalContexts
1857         = (1LL << CodeCompletionContext::CCC_TopLevel)
1858         | (1LL << CodeCompletionContext::CCC_ObjCInterface)
1859         | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
1860         | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
1861         | (1LL << CodeCompletionContext::CCC_Statement)
1862         | (1LL << CodeCompletionContext::CCC_Expression)
1863         | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
1864         | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
1865         | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
1866         | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
1867         | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
1868         | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
1869         | (1LL << CodeCompletionContext::CCC_Recovery);
1870 
1871       if (AST.getASTContext().getLangOpts().CPlusPlus)
1872         NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
1873                        |  (1LL << CodeCompletionContext::CCC_UnionTag)
1874                        |  (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
1875     }
1876 
1877     void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
1878                                     CodeCompletionResult *Results,
1879                                     unsigned NumResults) override;
1880 
1881     void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1882                                    OverloadCandidate *Candidates,
1883                                    unsigned NumCandidates) override {
1884       Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
1885     }
1886 
1887     CodeCompletionAllocator &getAllocator() override {
1888       return Next.getAllocator();
1889     }
1890 
1891     CodeCompletionTUInfo &getCodeCompletionTUInfo() override {
1892       return Next.getCodeCompletionTUInfo();
1893     }
1894   };
1895 } // anonymous namespace
1896 
1897 /// \brief Helper function that computes which global names are hidden by the
1898 /// local code-completion results.
1899 static void CalculateHiddenNames(const CodeCompletionContext &Context,
1900                                  CodeCompletionResult *Results,
1901                                  unsigned NumResults,
1902                                  ASTContext &Ctx,
1903                           llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
1904   bool OnlyTagNames = false;
1905   switch (Context.getKind()) {
1906   case CodeCompletionContext::CCC_Recovery:
1907   case CodeCompletionContext::CCC_TopLevel:
1908   case CodeCompletionContext::CCC_ObjCInterface:
1909   case CodeCompletionContext::CCC_ObjCImplementation:
1910   case CodeCompletionContext::CCC_ObjCIvarList:
1911   case CodeCompletionContext::CCC_ClassStructUnion:
1912   case CodeCompletionContext::CCC_Statement:
1913   case CodeCompletionContext::CCC_Expression:
1914   case CodeCompletionContext::CCC_ObjCMessageReceiver:
1915   case CodeCompletionContext::CCC_DotMemberAccess:
1916   case CodeCompletionContext::CCC_ArrowMemberAccess:
1917   case CodeCompletionContext::CCC_ObjCPropertyAccess:
1918   case CodeCompletionContext::CCC_Namespace:
1919   case CodeCompletionContext::CCC_Type:
1920   case CodeCompletionContext::CCC_Name:
1921   case CodeCompletionContext::CCC_PotentiallyQualifiedName:
1922   case CodeCompletionContext::CCC_ParenthesizedExpression:
1923   case CodeCompletionContext::CCC_ObjCInterfaceName:
1924     break;
1925 
1926   case CodeCompletionContext::CCC_EnumTag:
1927   case CodeCompletionContext::CCC_UnionTag:
1928   case CodeCompletionContext::CCC_ClassOrStructTag:
1929     OnlyTagNames = true;
1930     break;
1931 
1932   case CodeCompletionContext::CCC_ObjCProtocolName:
1933   case CodeCompletionContext::CCC_MacroName:
1934   case CodeCompletionContext::CCC_MacroNameUse:
1935   case CodeCompletionContext::CCC_PreprocessorExpression:
1936   case CodeCompletionContext::CCC_PreprocessorDirective:
1937   case CodeCompletionContext::CCC_NaturalLanguage:
1938   case CodeCompletionContext::CCC_SelectorName:
1939   case CodeCompletionContext::CCC_TypeQualifiers:
1940   case CodeCompletionContext::CCC_Other:
1941   case CodeCompletionContext::CCC_OtherWithMacros:
1942   case CodeCompletionContext::CCC_ObjCInstanceMessage:
1943   case CodeCompletionContext::CCC_ObjCClassMessage:
1944   case CodeCompletionContext::CCC_ObjCCategoryName:
1945     // We're looking for nothing, or we're looking for names that cannot
1946     // be hidden.
1947     return;
1948   }
1949 
1950   typedef CodeCompletionResult Result;
1951   for (unsigned I = 0; I != NumResults; ++I) {
1952     if (Results[I].Kind != Result::RK_Declaration)
1953       continue;
1954 
1955     unsigned IDNS
1956       = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
1957 
1958     bool Hiding = false;
1959     if (OnlyTagNames)
1960       Hiding = (IDNS & Decl::IDNS_Tag);
1961     else {
1962       unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
1963                              Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
1964                              Decl::IDNS_NonMemberOperator);
1965       if (Ctx.getLangOpts().CPlusPlus)
1966         HiddenIDNS |= Decl::IDNS_Tag;
1967       Hiding = (IDNS & HiddenIDNS);
1968     }
1969 
1970     if (!Hiding)
1971       continue;
1972 
1973     DeclarationName Name = Results[I].Declaration->getDeclName();
1974     if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
1975       HiddenNames.insert(Identifier->getName());
1976     else
1977       HiddenNames.insert(Name.getAsString());
1978   }
1979 }
1980 
1981 void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
1982                                             CodeCompletionContext Context,
1983                                             CodeCompletionResult *Results,
1984                                             unsigned NumResults) {
1985   // Merge the results we were given with the results we cached.
1986   bool AddedResult = false;
1987   uint64_t InContexts =
1988       Context.getKind() == CodeCompletionContext::CCC_Recovery
1989         ? NormalContexts : (1LL << Context.getKind());
1990   // Contains the set of names that are hidden by "local" completion results.
1991   llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
1992   typedef CodeCompletionResult Result;
1993   SmallVector<Result, 8> AllResults;
1994   for (ASTUnit::cached_completion_iterator
1995             C = AST.cached_completion_begin(),
1996          CEnd = AST.cached_completion_end();
1997        C != CEnd; ++C) {
1998     // If the context we are in matches any of the contexts we are
1999     // interested in, we'll add this result.
2000     if ((C->ShowInContexts & InContexts) == 0)
2001       continue;
2002 
2003     // If we haven't added any results previously, do so now.
2004     if (!AddedResult) {
2005       CalculateHiddenNames(Context, Results, NumResults, S.Context,
2006                            HiddenNames);
2007       AllResults.insert(AllResults.end(), Results, Results + NumResults);
2008       AddedResult = true;
2009     }
2010 
2011     // Determine whether this global completion result is hidden by a local
2012     // completion result. If so, skip it.
2013     if (C->Kind != CXCursor_MacroDefinition &&
2014         HiddenNames.count(C->Completion->getTypedText()))
2015       continue;
2016 
2017     // Adjust priority based on similar type classes.
2018     unsigned Priority = C->Priority;
2019     CodeCompletionString *Completion = C->Completion;
2020     if (!Context.getPreferredType().isNull()) {
2021       if (C->Kind == CXCursor_MacroDefinition) {
2022         Priority = getMacroUsagePriority(C->Completion->getTypedText(),
2023                                          S.getLangOpts(),
2024                                Context.getPreferredType()->isAnyPointerType());
2025       } else if (C->Type) {
2026         CanQualType Expected
2027           = S.Context.getCanonicalType(
2028                                Context.getPreferredType().getUnqualifiedType());
2029         SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2030         if (ExpectedSTC == C->TypeClass) {
2031           // We know this type is similar; check for an exact match.
2032           llvm::StringMap<unsigned> &CachedCompletionTypes
2033             = AST.getCachedCompletionTypes();
2034           llvm::StringMap<unsigned>::iterator Pos
2035             = CachedCompletionTypes.find(QualType(Expected).getAsString());
2036           if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2037             Priority /= CCF_ExactTypeMatch;
2038           else
2039             Priority /= CCF_SimilarTypeMatch;
2040         }
2041       }
2042     }
2043 
2044     // Adjust the completion string, if required.
2045     if (C->Kind == CXCursor_MacroDefinition &&
2046         Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2047       // Create a new code-completion string that just contains the
2048       // macro name, without its arguments.
2049       CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2050                                     CCP_CodePattern, C->Availability);
2051       Builder.AddTypedTextChunk(C->Completion->getTypedText());
2052       Priority = CCP_CodePattern;
2053       Completion = Builder.TakeString();
2054     }
2055 
2056     AllResults.push_back(Result(Completion, Priority, C->Kind,
2057                                 C->Availability));
2058   }
2059 
2060   // If we did not add any cached completion results, just forward the
2061   // results we were given to the next consumer.
2062   if (!AddedResult) {
2063     Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2064     return;
2065   }
2066 
2067   Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2068                                   AllResults.size());
2069 }
2070 
2071 void ASTUnit::CodeComplete(
2072     StringRef File, unsigned Line, unsigned Column,
2073     ArrayRef<RemappedFile> RemappedFiles, bool IncludeMacros,
2074     bool IncludeCodePatterns, bool IncludeBriefComments,
2075     CodeCompleteConsumer &Consumer,
2076     std::shared_ptr<PCHContainerOperations> PCHContainerOps,
2077     DiagnosticsEngine &Diag, LangOptions &LangOpts, SourceManager &SourceMgr,
2078     FileManager &FileMgr, SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2079     SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
2080   if (!Invocation)
2081     return;
2082 
2083   SimpleTimer CompletionTimer(WantTiming);
2084   CompletionTimer.setOutput("Code completion @ " + File + ":" +
2085                             Twine(Line) + ":" + Twine(Column));
2086 
2087   auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation);
2088 
2089   FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
2090   CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
2091   PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
2092 
2093   CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2094                                    CachedCompletionResults.empty();
2095   CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2096   CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2097   CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2098 
2099   assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2100 
2101   FrontendOpts.CodeCompletionAt.FileName = File;
2102   FrontendOpts.CodeCompletionAt.Line = Line;
2103   FrontendOpts.CodeCompletionAt.Column = Column;
2104 
2105   // Set the language options appropriately.
2106   LangOpts = *CCInvocation->getLangOpts();
2107 
2108   // Spell-checking and warnings are wasteful during code-completion.
2109   LangOpts.SpellChecking = false;
2110   CCInvocation->getDiagnosticOpts().IgnoreWarnings = true;
2111 
2112   std::unique_ptr<CompilerInstance> Clang(
2113       new CompilerInstance(PCHContainerOps));
2114 
2115   // Recover resources if we crash before exiting this method.
2116   llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2117     CICleanup(Clang.get());
2118 
2119   auto &Inv = *CCInvocation;
2120   Clang->setInvocation(std::move(CCInvocation));
2121   OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
2122 
2123   // Set up diagnostics, capturing any diagnostics produced.
2124   Clang->setDiagnostics(&Diag);
2125   CaptureDroppedDiagnostics Capture(true,
2126                                     Clang->getDiagnostics(),
2127                                     &StoredDiagnostics, nullptr);
2128   ProcessWarningOptions(Diag, Inv.getDiagnosticOpts());
2129 
2130   // Create the target instance.
2131   Clang->setTarget(TargetInfo::CreateTargetInfo(
2132       Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
2133   if (!Clang->hasTarget()) {
2134     Clang->setInvocation(nullptr);
2135     return;
2136   }
2137 
2138   // Inform the target of the language options.
2139   //
2140   // FIXME: We shouldn't need to do this, the target should be immutable once
2141   // created. This complexity should be lifted elsewhere.
2142   Clang->getTarget().adjust(Clang->getLangOpts());
2143 
2144   assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
2145          "Invocation must have exactly one source file!");
2146   assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
2147              InputKind::Source &&
2148          "FIXME: AST inputs not yet supported here!");
2149   assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
2150              InputKind::LLVM_IR &&
2151          "IR inputs not support here!");
2152 
2153   // Use the source and file managers that we were given.
2154   Clang->setFileManager(&FileMgr);
2155   Clang->setSourceManager(&SourceMgr);
2156 
2157   // Remap files.
2158   PreprocessorOpts.clearRemappedFiles();
2159   PreprocessorOpts.RetainRemappedFileBuffers = true;
2160   for (const auto &RemappedFile : RemappedFiles) {
2161     PreprocessorOpts.addRemappedFile(RemappedFile.first, RemappedFile.second);
2162     OwnedBuffers.push_back(RemappedFile.second);
2163   }
2164 
2165   // Use the code completion consumer we were given, but adding any cached
2166   // code-completion results.
2167   AugmentedCodeCompleteConsumer *AugmentedConsumer
2168     = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
2169   Clang->setCodeCompletionConsumer(AugmentedConsumer);
2170 
2171   // If we have a precompiled preamble, try to use it. We only allow
2172   // the use of the precompiled preamble if we're if the completion
2173   // point is within the main file, after the end of the precompiled
2174   // preamble.
2175   std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
2176   if (Preamble) {
2177     std::string CompleteFilePath(File);
2178 
2179     auto VFS = FileMgr.getVirtualFileSystem();
2180     auto CompleteFileStatus = VFS->status(CompleteFilePath);
2181     if (CompleteFileStatus) {
2182       llvm::sys::fs::UniqueID CompleteFileID = CompleteFileStatus->getUniqueID();
2183 
2184       std::string MainPath(OriginalSourceFile);
2185       auto MainStatus = VFS->status(MainPath);
2186       if (MainStatus) {
2187         llvm::sys::fs::UniqueID MainID = MainStatus->getUniqueID();
2188         if (CompleteFileID == MainID && Line > 1)
2189           OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(
2190               PCHContainerOps, Inv, VFS, false, Line - 1);
2191       }
2192     }
2193   }
2194 
2195   // If the main file has been overridden due to the use of a preamble,
2196   // make that override happen and introduce the preamble.
2197   if (OverrideMainBuffer) {
2198     assert(Preamble && "No preamble was built, but OverrideMainBuffer is not null");
2199     Preamble->AddImplicitPreamble(Clang->getInvocation(), OverrideMainBuffer.get());
2200     OwnedBuffers.push_back(OverrideMainBuffer.release());
2201   } else {
2202     PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2203     PreprocessorOpts.PrecompiledPreambleBytes.second = false;
2204   }
2205 
2206   // Disable the preprocessing record if modules are not enabled.
2207   if (!Clang->getLangOpts().Modules)
2208     PreprocessorOpts.DetailedRecord = false;
2209 
2210   std::unique_ptr<SyntaxOnlyAction> Act;
2211   Act.reset(new SyntaxOnlyAction);
2212   if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
2213     Act->Execute();
2214     Act->EndSourceFile();
2215   }
2216 }
2217 
2218 bool ASTUnit::Save(StringRef File) {
2219   if (HadModuleLoaderFatalFailure)
2220     return true;
2221 
2222   // Write to a temporary file and later rename it to the actual file, to avoid
2223   // possible race conditions.
2224   SmallString<128> TempPath;
2225   TempPath = File;
2226   TempPath += "-%%%%%%%%";
2227   int fd;
2228   if (llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath))
2229     return true;
2230 
2231   // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2232   // unconditionally create a stat cache when we parse the file?
2233   llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
2234 
2235   serialize(Out);
2236   Out.close();
2237   if (Out.has_error()) {
2238     Out.clear_error();
2239     return true;
2240   }
2241 
2242   if (llvm::sys::fs::rename(TempPath, File)) {
2243     llvm::sys::fs::remove(TempPath);
2244     return true;
2245   }
2246 
2247   return false;
2248 }
2249 
2250 static bool serializeUnit(ASTWriter &Writer,
2251                           SmallVectorImpl<char> &Buffer,
2252                           Sema &S,
2253                           bool hasErrors,
2254                           raw_ostream &OS) {
2255   Writer.WriteAST(S, std::string(), nullptr, "", hasErrors);
2256 
2257   // Write the generated bitstream to "Out".
2258   if (!Buffer.empty())
2259     OS.write(Buffer.data(), Buffer.size());
2260 
2261   return false;
2262 }
2263 
2264 bool ASTUnit::serialize(raw_ostream &OS) {
2265   // For serialization we are lenient if the errors were only warn-as-error kind.
2266   bool hasErrors = getDiagnostics().hasUncompilableErrorOccurred();
2267 
2268   if (WriterData)
2269     return serializeUnit(WriterData->Writer, WriterData->Buffer,
2270                          getSema(), hasErrors, OS);
2271 
2272   SmallString<128> Buffer;
2273   llvm::BitstreamWriter Stream(Buffer);
2274   MemoryBufferCache PCMCache;
2275   ASTWriter Writer(Stream, Buffer, PCMCache, {});
2276   return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
2277 }
2278 
2279 typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2280 
2281 void ASTUnit::TranslateStoredDiagnostics(
2282                           FileManager &FileMgr,
2283                           SourceManager &SrcMgr,
2284                           const SmallVectorImpl<StandaloneDiagnostic> &Diags,
2285                           SmallVectorImpl<StoredDiagnostic> &Out) {
2286   // Map the standalone diagnostic into the new source manager. We also need to
2287   // remap all the locations to the new view. This includes the diag location,
2288   // any associated source ranges, and the source ranges of associated fix-its.
2289   // FIXME: There should be a cleaner way to do this.
2290   SmallVector<StoredDiagnostic, 4> Result;
2291   Result.reserve(Diags.size());
2292 
2293   for (const StandaloneDiagnostic &SD : Diags) {
2294     // Rebuild the StoredDiagnostic.
2295     if (SD.Filename.empty())
2296       continue;
2297     const FileEntry *FE = FileMgr.getFile(SD.Filename);
2298     if (!FE)
2299       continue;
2300     SourceLocation FileLoc;
2301     auto ItFileID = PreambleSrcLocCache.find(SD.Filename);
2302     if (ItFileID == PreambleSrcLocCache.end()) {
2303       FileID FID = SrcMgr.translateFile(FE);
2304       FileLoc = SrcMgr.getLocForStartOfFile(FID);
2305       PreambleSrcLocCache[SD.Filename] = FileLoc;
2306     } else {
2307       FileLoc = ItFileID->getValue();
2308     }
2309 
2310     if (FileLoc.isInvalid())
2311       continue;
2312     SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset);
2313     FullSourceLoc Loc(L, SrcMgr);
2314 
2315     SmallVector<CharSourceRange, 4> Ranges;
2316     Ranges.reserve(SD.Ranges.size());
2317     for (const auto &Range : SD.Ranges) {
2318       SourceLocation BL = FileLoc.getLocWithOffset(Range.first);
2319       SourceLocation EL = FileLoc.getLocWithOffset(Range.second);
2320       Ranges.push_back(CharSourceRange::getCharRange(BL, EL));
2321     }
2322 
2323     SmallVector<FixItHint, 2> FixIts;
2324     FixIts.reserve(SD.FixIts.size());
2325     for (const StandaloneFixIt &FixIt : SD.FixIts) {
2326       FixIts.push_back(FixItHint());
2327       FixItHint &FH = FixIts.back();
2328       FH.CodeToInsert = FixIt.CodeToInsert;
2329       SourceLocation BL = FileLoc.getLocWithOffset(FixIt.RemoveRange.first);
2330       SourceLocation EL = FileLoc.getLocWithOffset(FixIt.RemoveRange.second);
2331       FH.RemoveRange = CharSourceRange::getCharRange(BL, EL);
2332     }
2333 
2334     Result.push_back(StoredDiagnostic(SD.Level, SD.ID,
2335                                       SD.Message, Loc, Ranges, FixIts));
2336   }
2337   Result.swap(Out);
2338 }
2339 
2340 void ASTUnit::addFileLevelDecl(Decl *D) {
2341   assert(D);
2342 
2343   // We only care about local declarations.
2344   if (D->isFromASTFile())
2345     return;
2346 
2347   SourceManager &SM = *SourceMgr;
2348   SourceLocation Loc = D->getLocation();
2349   if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2350     return;
2351 
2352   // We only keep track of the file-level declarations of each file.
2353   if (!D->getLexicalDeclContext()->isFileContext())
2354     return;
2355 
2356   SourceLocation FileLoc = SM.getFileLoc(Loc);
2357   assert(SM.isLocalSourceLocation(FileLoc));
2358   FileID FID;
2359   unsigned Offset;
2360   std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
2361   if (FID.isInvalid())
2362     return;
2363 
2364   LocDeclsTy *&Decls = FileDecls[FID];
2365   if (!Decls)
2366     Decls = new LocDeclsTy();
2367 
2368   std::pair<unsigned, Decl *> LocDecl(Offset, D);
2369 
2370   if (Decls->empty() || Decls->back().first <= Offset) {
2371     Decls->push_back(LocDecl);
2372     return;
2373   }
2374 
2375   LocDeclsTy::iterator I = std::upper_bound(Decls->begin(), Decls->end(),
2376                                             LocDecl, llvm::less_first());
2377 
2378   Decls->insert(I, LocDecl);
2379 }
2380 
2381 void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2382                                   SmallVectorImpl<Decl *> &Decls) {
2383   if (File.isInvalid())
2384     return;
2385 
2386   if (SourceMgr->isLoadedFileID(File)) {
2387     assert(Ctx->getExternalSource() && "No external source!");
2388     return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2389                                                          Decls);
2390   }
2391 
2392   FileDeclsTy::iterator I = FileDecls.find(File);
2393   if (I == FileDecls.end())
2394     return;
2395 
2396   LocDeclsTy &LocDecls = *I->second;
2397   if (LocDecls.empty())
2398     return;
2399 
2400   LocDeclsTy::iterator BeginIt =
2401       std::lower_bound(LocDecls.begin(), LocDecls.end(),
2402                        std::make_pair(Offset, (Decl *)nullptr),
2403                        llvm::less_first());
2404   if (BeginIt != LocDecls.begin())
2405     --BeginIt;
2406 
2407   // If we are pointing at a top-level decl inside an objc container, we need
2408   // to backtrack until we find it otherwise we will fail to report that the
2409   // region overlaps with an objc container.
2410   while (BeginIt != LocDecls.begin() &&
2411          BeginIt->second->isTopLevelDeclInObjCContainer())
2412     --BeginIt;
2413 
2414   LocDeclsTy::iterator EndIt = std::upper_bound(
2415       LocDecls.begin(), LocDecls.end(),
2416       std::make_pair(Offset + Length, (Decl *)nullptr), llvm::less_first());
2417   if (EndIt != LocDecls.end())
2418     ++EndIt;
2419 
2420   for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2421     Decls.push_back(DIt->second);
2422 }
2423 
2424 SourceLocation ASTUnit::getLocation(const FileEntry *File,
2425                                     unsigned Line, unsigned Col) const {
2426   const SourceManager &SM = getSourceManager();
2427   SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
2428   return SM.getMacroArgExpandedLocation(Loc);
2429 }
2430 
2431 SourceLocation ASTUnit::getLocation(const FileEntry *File,
2432                                     unsigned Offset) const {
2433   const SourceManager &SM = getSourceManager();
2434   SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
2435   return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2436 }
2437 
2438 /// \brief If \arg Loc is a loaded location from the preamble, returns
2439 /// the corresponding local location of the main file, otherwise it returns
2440 /// \arg Loc.
2441 SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) const {
2442   FileID PreambleID;
2443   if (SourceMgr)
2444     PreambleID = SourceMgr->getPreambleFileID();
2445 
2446   if (Loc.isInvalid() || !Preamble || PreambleID.isInvalid())
2447     return Loc;
2448 
2449   unsigned Offs;
2450   if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble->getBounds().Size) {
2451     SourceLocation FileLoc
2452         = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2453     return FileLoc.getLocWithOffset(Offs);
2454   }
2455 
2456   return Loc;
2457 }
2458 
2459 /// \brief If \arg Loc is a local location of the main file but inside the
2460 /// preamble chunk, returns the corresponding loaded location from the
2461 /// preamble, otherwise it returns \arg Loc.
2462 SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) const {
2463   FileID PreambleID;
2464   if (SourceMgr)
2465     PreambleID = SourceMgr->getPreambleFileID();
2466 
2467   if (Loc.isInvalid() || !Preamble || PreambleID.isInvalid())
2468     return Loc;
2469 
2470   unsigned Offs;
2471   if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2472       Offs < Preamble->getBounds().Size) {
2473     SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2474     return FileLoc.getLocWithOffset(Offs);
2475   }
2476 
2477   return Loc;
2478 }
2479 
2480 bool ASTUnit::isInPreambleFileID(SourceLocation Loc) const {
2481   FileID FID;
2482   if (SourceMgr)
2483     FID = SourceMgr->getPreambleFileID();
2484 
2485   if (Loc.isInvalid() || FID.isInvalid())
2486     return false;
2487 
2488   return SourceMgr->isInFileID(Loc, FID);
2489 }
2490 
2491 bool ASTUnit::isInMainFileID(SourceLocation Loc) const {
2492   FileID FID;
2493   if (SourceMgr)
2494     FID = SourceMgr->getMainFileID();
2495 
2496   if (Loc.isInvalid() || FID.isInvalid())
2497     return false;
2498 
2499   return SourceMgr->isInFileID(Loc, FID);
2500 }
2501 
2502 SourceLocation ASTUnit::getEndOfPreambleFileID() const {
2503   FileID FID;
2504   if (SourceMgr)
2505     FID = SourceMgr->getPreambleFileID();
2506 
2507   if (FID.isInvalid())
2508     return SourceLocation();
2509 
2510   return SourceMgr->getLocForEndOfFile(FID);
2511 }
2512 
2513 SourceLocation ASTUnit::getStartOfMainFileID() const {
2514   FileID FID;
2515   if (SourceMgr)
2516     FID = SourceMgr->getMainFileID();
2517 
2518   if (FID.isInvalid())
2519     return SourceLocation();
2520 
2521   return SourceMgr->getLocForStartOfFile(FID);
2522 }
2523 
2524 llvm::iterator_range<PreprocessingRecord::iterator>
2525 ASTUnit::getLocalPreprocessingEntities() const {
2526   if (isMainFileAST()) {
2527     serialization::ModuleFile &
2528       Mod = Reader->getModuleManager().getPrimaryModule();
2529     return Reader->getModulePreprocessedEntities(Mod);
2530   }
2531 
2532   if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
2533     return llvm::make_range(PPRec->local_begin(), PPRec->local_end());
2534 
2535   return llvm::make_range(PreprocessingRecord::iterator(),
2536                           PreprocessingRecord::iterator());
2537 }
2538 
2539 bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
2540   if (isMainFileAST()) {
2541     serialization::ModuleFile &
2542       Mod = Reader->getModuleManager().getPrimaryModule();
2543     for (const Decl *D : Reader->getModuleFileLevelDecls(Mod)) {
2544       if (!Fn(context, D))
2545         return false;
2546     }
2547 
2548     return true;
2549   }
2550 
2551   for (ASTUnit::top_level_iterator TL = top_level_begin(),
2552                                 TLEnd = top_level_end();
2553          TL != TLEnd; ++TL) {
2554     if (!Fn(context, *TL))
2555       return false;
2556   }
2557 
2558   return true;
2559 }
2560 
2561 const FileEntry *ASTUnit::getPCHFile() {
2562   if (!Reader)
2563     return nullptr;
2564 
2565   serialization::ModuleFile *Mod = nullptr;
2566   Reader->getModuleManager().visit([&Mod](serialization::ModuleFile &M) {
2567     switch (M.Kind) {
2568     case serialization::MK_ImplicitModule:
2569     case serialization::MK_ExplicitModule:
2570     case serialization::MK_PrebuiltModule:
2571       return true; // skip dependencies.
2572     case serialization::MK_PCH:
2573       Mod = &M;
2574       return true; // found it.
2575     case serialization::MK_Preamble:
2576       return false; // look in dependencies.
2577     case serialization::MK_MainFile:
2578       return false; // look in dependencies.
2579     }
2580 
2581     return true;
2582   });
2583   if (Mod)
2584     return Mod->File;
2585 
2586   return nullptr;
2587 }
2588 
2589 bool ASTUnit::isModuleFile() const {
2590   return isMainFileAST() && getLangOpts().isCompilingModule();
2591 }
2592 
2593 InputKind ASTUnit::getInputKind() const {
2594   auto &LangOpts = getLangOpts();
2595 
2596   InputKind::Language Lang;
2597   if (LangOpts.OpenCL)
2598     Lang = InputKind::OpenCL;
2599   else if (LangOpts.CUDA)
2600     Lang = InputKind::CUDA;
2601   else if (LangOpts.RenderScript)
2602     Lang = InputKind::RenderScript;
2603   else if (LangOpts.CPlusPlus)
2604     Lang = LangOpts.ObjC1 ? InputKind::ObjCXX : InputKind::CXX;
2605   else
2606     Lang = LangOpts.ObjC1 ? InputKind::ObjC : InputKind::C;
2607 
2608   InputKind::Format Fmt = InputKind::Source;
2609   if (LangOpts.getCompilingModule() == LangOptions::CMK_ModuleMap)
2610     Fmt = InputKind::ModuleMap;
2611 
2612   // We don't know if input was preprocessed. Assume not.
2613   bool PP = false;
2614 
2615   return InputKind(Lang, Fmt, PP);
2616 }
2617 
2618 #ifndef NDEBUG
2619 ASTUnit::ConcurrencyState::ConcurrencyState() {
2620   Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2621 }
2622 
2623 ASTUnit::ConcurrencyState::~ConcurrencyState() {
2624   delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2625 }
2626 
2627 void ASTUnit::ConcurrencyState::start() {
2628   bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2629   assert(acquired && "Concurrent access to ASTUnit!");
2630 }
2631 
2632 void ASTUnit::ConcurrencyState::finish() {
2633   static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2634 }
2635 
2636 #else // NDEBUG
2637 
2638 ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex = nullptr; }
2639 ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2640 void ASTUnit::ConcurrencyState::start() {}
2641 void ASTUnit::ConcurrencyState::finish() {}
2642 
2643 #endif // NDEBUG
2644