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