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