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 = ComputePreambleBounds(
1321       *PreambleInvocationIn.getLangOpts(), *MainFileBuffer, MaxLines);
1322   if (!Bounds.Size)
1323     return nullptr;
1324 
1325   if (Preamble) {
1326     if (Preamble->CanReuse(PreambleInvocationIn, MainFileBuffer.get(), Bounds,
1327                            VFS.get())) {
1328       // Okay! We can re-use the precompiled preamble.
1329 
1330       // Set the state of the diagnostic object to mimic its state
1331       // after parsing the preamble.
1332       getDiagnostics().Reset();
1333       ProcessWarningOptions(getDiagnostics(),
1334                             PreambleInvocationIn.getDiagnosticOpts());
1335       getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1336 
1337       PreambleRebuildCountdown = 1;
1338       return MainFileBuffer;
1339     } else {
1340       Preamble.reset();
1341       PreambleDiagnostics.clear();
1342       TopLevelDeclsInPreamble.clear();
1343       PreambleSrcLocCache.clear();
1344       PreambleRebuildCountdown = 1;
1345     }
1346   }
1347 
1348   // If the preamble rebuild counter > 1, it's because we previously
1349   // failed to build a preamble and we're not yet ready to try
1350   // again. Decrement the counter and return a failure.
1351   if (PreambleRebuildCountdown > 1) {
1352     --PreambleRebuildCountdown;
1353     return nullptr;
1354   }
1355 
1356   assert(!Preamble && "No Preamble should be stored at that point");
1357   // If we aren't allowed to rebuild the precompiled preamble, just
1358   // return now.
1359   if (!AllowRebuild)
1360     return nullptr;
1361 
1362   ++PreambleCounter;
1363 
1364   SmallVector<StandaloneDiagnostic, 4> NewPreambleDiagsStandalone;
1365   SmallVector<StoredDiagnostic, 4> NewPreambleDiags;
1366   ASTUnitPreambleCallbacks Callbacks;
1367   {
1368     llvm::Optional<CaptureDroppedDiagnostics> Capture;
1369     if (CaptureDiagnostics != CaptureDiagsKind::None)
1370       Capture.emplace(CaptureDiagnostics, *Diagnostics, &NewPreambleDiags,
1371                       &NewPreambleDiagsStandalone);
1372 
1373     // We did not previously compute a preamble, or it can't be reused anyway.
1374     SimpleTimer PreambleTimer(WantTiming);
1375     PreambleTimer.setOutput("Precompiling preamble");
1376 
1377     const bool PreviousSkipFunctionBodies =
1378         PreambleInvocationIn.getFrontendOpts().SkipFunctionBodies;
1379     if (SkipFunctionBodies == SkipFunctionBodiesScope::Preamble)
1380       PreambleInvocationIn.getFrontendOpts().SkipFunctionBodies = true;
1381 
1382     llvm::ErrorOr<PrecompiledPreamble> NewPreamble = PrecompiledPreamble::Build(
1383         PreambleInvocationIn, MainFileBuffer.get(), Bounds, *Diagnostics, VFS,
1384         PCHContainerOps, /*StoreInMemory=*/false, Callbacks);
1385 
1386     PreambleInvocationIn.getFrontendOpts().SkipFunctionBodies =
1387         PreviousSkipFunctionBodies;
1388 
1389     if (NewPreamble) {
1390       Preamble = std::move(*NewPreamble);
1391       PreambleRebuildCountdown = 1;
1392     } else {
1393       switch (static_cast<BuildPreambleError>(NewPreamble.getError().value())) {
1394       case BuildPreambleError::CouldntCreateTempFile:
1395         // Try again next time.
1396         PreambleRebuildCountdown = 1;
1397         return nullptr;
1398       case BuildPreambleError::CouldntCreateTargetInfo:
1399       case BuildPreambleError::BeginSourceFileFailed:
1400       case BuildPreambleError::CouldntEmitPCH:
1401       case BuildPreambleError::BadInputs:
1402         // These erros are more likely to repeat, retry after some period.
1403         PreambleRebuildCountdown = DefaultPreambleRebuildInterval;
1404         return nullptr;
1405       }
1406       llvm_unreachable("unexpected BuildPreambleError");
1407     }
1408   }
1409 
1410   assert(Preamble && "Preamble wasn't built");
1411 
1412   TopLevelDecls.clear();
1413   TopLevelDeclsInPreamble = Callbacks.takeTopLevelDeclIDs();
1414   PreambleTopLevelHashValue = Callbacks.getHash();
1415 
1416   NumWarningsInPreamble = getDiagnostics().getNumWarnings();
1417 
1418   checkAndRemoveNonDriverDiags(NewPreambleDiags);
1419   StoredDiagnostics = std::move(NewPreambleDiags);
1420   PreambleDiagnostics = std::move(NewPreambleDiagsStandalone);
1421 
1422   // If the hash of top-level entities differs from the hash of the top-level
1423   // entities the last time we rebuilt the preamble, clear out the completion
1424   // cache.
1425   if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1426     CompletionCacheTopLevelHashValue = 0;
1427     PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1428   }
1429 
1430   return MainFileBuffer;
1431 }
1432 
1433 void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1434   assert(Preamble && "Should only be called when preamble was built");
1435 
1436   std::vector<Decl *> Resolved;
1437   Resolved.reserve(TopLevelDeclsInPreamble.size());
1438   ExternalASTSource &Source = *getASTContext().getExternalSource();
1439   for (const auto TopLevelDecl : TopLevelDeclsInPreamble) {
1440     // Resolve the declaration ID to an actual declaration, possibly
1441     // deserializing the declaration in the process.
1442     if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
1443       Resolved.push_back(D);
1444   }
1445   TopLevelDeclsInPreamble.clear();
1446   TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1447 }
1448 
1449 void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
1450   // Steal the created target, context, and preprocessor if they have been
1451   // created.
1452   assert(CI.hasInvocation() && "missing invocation");
1453   LangOpts = CI.getInvocation().LangOpts;
1454   TheSema = CI.takeSema();
1455   Consumer = CI.takeASTConsumer();
1456   if (CI.hasASTContext())
1457     Ctx = &CI.getASTContext();
1458   if (CI.hasPreprocessor())
1459     PP = CI.getPreprocessorPtr();
1460   CI.setSourceManager(nullptr);
1461   CI.setFileManager(nullptr);
1462   if (CI.hasTarget())
1463     Target = &CI.getTarget();
1464   Reader = CI.getASTReader();
1465   HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure();
1466 }
1467 
1468 StringRef ASTUnit::getMainFileName() const {
1469   if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1470     const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0];
1471     if (Input.isFile())
1472       return Input.getFile();
1473     else
1474       return Input.getBuffer().getBufferIdentifier();
1475   }
1476 
1477   if (SourceMgr) {
1478     if (const FileEntry *
1479           FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
1480       return FE->getName();
1481   }
1482 
1483   return {};
1484 }
1485 
1486 StringRef ASTUnit::getASTFileName() const {
1487   if (!isMainFileAST())
1488     return {};
1489 
1490   serialization::ModuleFile &
1491     Mod = Reader->getModuleManager().getPrimaryModule();
1492   return Mod.FileName;
1493 }
1494 
1495 std::unique_ptr<ASTUnit>
1496 ASTUnit::create(std::shared_ptr<CompilerInvocation> CI,
1497                 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1498                 CaptureDiagsKind CaptureDiagnostics,
1499                 bool UserFilesAreVolatile) {
1500   std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
1501   ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1502   IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS =
1503       createVFSFromCompilerInvocation(*CI, *Diags);
1504   AST->Diagnostics = Diags;
1505   AST->FileSystemOpts = CI->getFileSystemOpts();
1506   AST->Invocation = std::move(CI);
1507   AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
1508   AST->UserFilesAreVolatile = UserFilesAreVolatile;
1509   AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1510                                      UserFilesAreVolatile);
1511   AST->ModuleCache = new InMemoryModuleCache;
1512 
1513   return AST;
1514 }
1515 
1516 ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(
1517     std::shared_ptr<CompilerInvocation> CI,
1518     std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1519     IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FrontendAction *Action,
1520     ASTUnit *Unit, bool Persistent, StringRef ResourceFilesPath,
1521     bool OnlyLocalDecls, CaptureDiagsKind CaptureDiagnostics,
1522     unsigned PrecompilePreambleAfterNParses, bool CacheCodeCompletionResults,
1523     bool IncludeBriefCommentsInCodeCompletion, bool UserFilesAreVolatile,
1524     std::unique_ptr<ASTUnit> *ErrAST) {
1525   assert(CI && "A CompilerInvocation is required");
1526 
1527   std::unique_ptr<ASTUnit> OwnAST;
1528   ASTUnit *AST = Unit;
1529   if (!AST) {
1530     // Create the AST unit.
1531     OwnAST = create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile);
1532     AST = OwnAST.get();
1533     if (!AST)
1534       return nullptr;
1535   }
1536 
1537   if (!ResourceFilesPath.empty()) {
1538     // Override the resources path.
1539     CI->getHeaderSearchOpts().ResourceDir = std::string(ResourceFilesPath);
1540   }
1541   AST->OnlyLocalDecls = OnlyLocalDecls;
1542   AST->CaptureDiagnostics = CaptureDiagnostics;
1543   if (PrecompilePreambleAfterNParses > 0)
1544     AST->PreambleRebuildCountdown = PrecompilePreambleAfterNParses;
1545   AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
1546   AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1547   AST->IncludeBriefCommentsInCodeCompletion
1548     = IncludeBriefCommentsInCodeCompletion;
1549 
1550   // Recover resources if we crash before exiting this method.
1551   llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1552     ASTUnitCleanup(OwnAST.get());
1553   llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1554     llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
1555     DiagCleanup(Diags.get());
1556 
1557   // We'll manage file buffers ourselves.
1558   CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1559   CI->getFrontendOpts().DisableFree = false;
1560   ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1561 
1562   // Create the compiler instance to use for building the AST.
1563   std::unique_ptr<CompilerInstance> Clang(
1564       new CompilerInstance(std::move(PCHContainerOps)));
1565 
1566   // Recover resources if we crash before exiting this method.
1567   llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1568     CICleanup(Clang.get());
1569 
1570   Clang->setInvocation(std::move(CI));
1571   AST->OriginalSourceFile =
1572       std::string(Clang->getFrontendOpts().Inputs[0].getFile());
1573 
1574   // Set up diagnostics, capturing any diagnostics that would
1575   // otherwise be dropped.
1576   Clang->setDiagnostics(&AST->getDiagnostics());
1577 
1578   // Create the target instance.
1579   Clang->setTarget(TargetInfo::CreateTargetInfo(
1580       Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
1581   if (!Clang->hasTarget())
1582     return nullptr;
1583 
1584   // Inform the target of the language options.
1585   //
1586   // FIXME: We shouldn't need to do this, the target should be immutable once
1587   // created. This complexity should be lifted elsewhere.
1588   Clang->getTarget().adjust(Clang->getLangOpts());
1589 
1590   assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1591          "Invocation must have exactly one source file!");
1592   assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1593              InputKind::Source &&
1594          "FIXME: AST inputs not yet supported here!");
1595   assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1596              Language::LLVM_IR &&
1597          "IR inputs not support here!");
1598 
1599   // Configure the various subsystems.
1600   AST->TheSema.reset();
1601   AST->Ctx = nullptr;
1602   AST->PP = nullptr;
1603   AST->Reader = nullptr;
1604 
1605   // Create a file manager object to provide access to and cache the filesystem.
1606   Clang->setFileManager(&AST->getFileManager());
1607 
1608   // Create the source manager.
1609   Clang->setSourceManager(&AST->getSourceManager());
1610 
1611   FrontendAction *Act = Action;
1612 
1613   std::unique_ptr<TopLevelDeclTrackerAction> TrackerAct;
1614   if (!Act) {
1615     TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1616     Act = TrackerAct.get();
1617   }
1618 
1619   // Recover resources if we crash before exiting this method.
1620   llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1621     ActCleanup(TrackerAct.get());
1622 
1623   if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1624     AST->transferASTDataFromCompilerInstance(*Clang);
1625     if (OwnAST && ErrAST)
1626       ErrAST->swap(OwnAST);
1627 
1628     return nullptr;
1629   }
1630 
1631   if (Persistent && !TrackerAct) {
1632     Clang->getPreprocessor().addPPCallbacks(
1633         std::make_unique<MacroDefinitionTrackerPPCallbacks>(
1634                                            AST->getCurrentTopLevelHashValue()));
1635     std::vector<std::unique_ptr<ASTConsumer>> Consumers;
1636     if (Clang->hasASTConsumer())
1637       Consumers.push_back(Clang->takeASTConsumer());
1638     Consumers.push_back(std::make_unique<TopLevelDeclTrackerConsumer>(
1639         *AST, AST->getCurrentTopLevelHashValue()));
1640     Clang->setASTConsumer(
1641         std::make_unique<MultiplexConsumer>(std::move(Consumers)));
1642   }
1643   if (llvm::Error Err = Act->Execute()) {
1644     consumeError(std::move(Err)); // FIXME this drops errors on the floor.
1645     AST->transferASTDataFromCompilerInstance(*Clang);
1646     if (OwnAST && ErrAST)
1647       ErrAST->swap(OwnAST);
1648 
1649     return nullptr;
1650   }
1651 
1652   // Steal the created target, context, and preprocessor.
1653   AST->transferASTDataFromCompilerInstance(*Clang);
1654 
1655   Act->EndSourceFile();
1656 
1657   if (OwnAST)
1658     return OwnAST.release();
1659   else
1660     return AST;
1661 }
1662 
1663 bool ASTUnit::LoadFromCompilerInvocation(
1664     std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1665     unsigned PrecompilePreambleAfterNParses,
1666     IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
1667   if (!Invocation)
1668     return true;
1669 
1670   assert(VFS && "VFS is null");
1671 
1672   // We'll manage file buffers ourselves.
1673   Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1674   Invocation->getFrontendOpts().DisableFree = false;
1675   getDiagnostics().Reset();
1676   ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1677 
1678   std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
1679   if (PrecompilePreambleAfterNParses > 0) {
1680     PreambleRebuildCountdown = PrecompilePreambleAfterNParses;
1681     OverrideMainBuffer =
1682         getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS);
1683     getDiagnostics().Reset();
1684     ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1685   }
1686 
1687   SimpleTimer ParsingTimer(WantTiming);
1688   ParsingTimer.setOutput("Parsing " + getMainFileName());
1689 
1690   // Recover resources if we crash before exiting this method.
1691   llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1692     MemBufferCleanup(OverrideMainBuffer.get());
1693 
1694   return Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS);
1695 }
1696 
1697 std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation(
1698     std::shared_ptr<CompilerInvocation> CI,
1699     std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1700     IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FileManager *FileMgr,
1701     bool OnlyLocalDecls, CaptureDiagsKind CaptureDiagnostics,
1702     unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
1703     bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1704     bool UserFilesAreVolatile) {
1705   // Create the AST unit.
1706   std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
1707   ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1708   AST->Diagnostics = Diags;
1709   AST->OnlyLocalDecls = OnlyLocalDecls;
1710   AST->CaptureDiagnostics = CaptureDiagnostics;
1711   AST->TUKind = TUKind;
1712   AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1713   AST->IncludeBriefCommentsInCodeCompletion
1714     = IncludeBriefCommentsInCodeCompletion;
1715   AST->Invocation = std::move(CI);
1716   AST->FileSystemOpts = FileMgr->getFileSystemOpts();
1717   AST->FileMgr = FileMgr;
1718   AST->UserFilesAreVolatile = UserFilesAreVolatile;
1719 
1720   // Recover resources if we crash before exiting this method.
1721   llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1722     ASTUnitCleanup(AST.get());
1723   llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1724     llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
1725     DiagCleanup(Diags.get());
1726 
1727   if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
1728                                       PrecompilePreambleAfterNParses,
1729                                       &AST->FileMgr->getVirtualFileSystem()))
1730     return nullptr;
1731   return AST;
1732 }
1733 
1734 ASTUnit *ASTUnit::LoadFromCommandLine(
1735     const char **ArgBegin, const char **ArgEnd,
1736     std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1737     IntrusiveRefCntPtr<DiagnosticsEngine> Diags, StringRef ResourceFilesPath,
1738     bool OnlyLocalDecls, CaptureDiagsKind CaptureDiagnostics,
1739     ArrayRef<RemappedFile> RemappedFiles, bool RemappedFilesKeepOriginalName,
1740     unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
1741     bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1742     bool AllowPCHWithCompilerErrors, SkipFunctionBodiesScope SkipFunctionBodies,
1743     bool SingleFileParse, bool UserFilesAreVolatile, bool ForSerialization,
1744     bool RetainExcludedConditionalBlocks,
1745     llvm::Optional<StringRef> ModuleFormat, std::unique_ptr<ASTUnit> *ErrAST,
1746     IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
1747   assert(Diags.get() && "no DiagnosticsEngine was provided");
1748 
1749   SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
1750 
1751   std::shared_ptr<CompilerInvocation> CI;
1752 
1753   {
1754     CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
1755                                       &StoredDiagnostics, nullptr);
1756 
1757     CI = createInvocationFromCommandLine(
1758         llvm::makeArrayRef(ArgBegin, ArgEnd), Diags, VFS);
1759     if (!CI)
1760       return nullptr;
1761   }
1762 
1763   // Override any files that need remapping
1764   for (const auto &RemappedFile : RemappedFiles) {
1765     CI->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
1766                                               RemappedFile.second);
1767   }
1768   PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
1769   PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
1770   PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
1771   PPOpts.SingleFileParseMode = SingleFileParse;
1772   PPOpts.RetainExcludedConditionalBlocks = RetainExcludedConditionalBlocks;
1773 
1774   // Override the resources path.
1775   CI->getHeaderSearchOpts().ResourceDir = std::string(ResourceFilesPath);
1776 
1777   CI->getFrontendOpts().SkipFunctionBodies =
1778       SkipFunctionBodies == SkipFunctionBodiesScope::PreambleAndMainFile;
1779 
1780   if (ModuleFormat)
1781     CI->getHeaderSearchOpts().ModuleFormat =
1782         std::string(ModuleFormat.getValue());
1783 
1784   // Create the AST unit.
1785   std::unique_ptr<ASTUnit> AST;
1786   AST.reset(new ASTUnit(false));
1787   AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
1788   AST->StoredDiagnostics.swap(StoredDiagnostics);
1789   ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1790   AST->Diagnostics = Diags;
1791   AST->FileSystemOpts = CI->getFileSystemOpts();
1792   if (!VFS)
1793     VFS = llvm::vfs::getRealFileSystem();
1794   VFS = createVFSFromCompilerInvocation(*CI, *Diags, VFS);
1795   AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
1796   AST->ModuleCache = new InMemoryModuleCache;
1797   AST->OnlyLocalDecls = OnlyLocalDecls;
1798   AST->CaptureDiagnostics = CaptureDiagnostics;
1799   AST->TUKind = TUKind;
1800   AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1801   AST->IncludeBriefCommentsInCodeCompletion
1802     = IncludeBriefCommentsInCodeCompletion;
1803   AST->UserFilesAreVolatile = UserFilesAreVolatile;
1804   AST->Invocation = CI;
1805   AST->SkipFunctionBodies = SkipFunctionBodies;
1806   if (ForSerialization)
1807     AST->WriterData.reset(new ASTWriterData(*AST->ModuleCache));
1808   // Zero out now to ease cleanup during crash recovery.
1809   CI = nullptr;
1810   Diags = nullptr;
1811 
1812   // Recover resources if we crash before exiting this method.
1813   llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1814     ASTUnitCleanup(AST.get());
1815 
1816   if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
1817                                       PrecompilePreambleAfterNParses,
1818                                       VFS)) {
1819     // Some error occurred, if caller wants to examine diagnostics, pass it the
1820     // ASTUnit.
1821     if (ErrAST) {
1822       AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
1823       ErrAST->swap(AST);
1824     }
1825     return nullptr;
1826   }
1827 
1828   return AST.release();
1829 }
1830 
1831 bool ASTUnit::Reparse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1832                       ArrayRef<RemappedFile> RemappedFiles,
1833                       IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
1834   if (!Invocation)
1835     return true;
1836 
1837   if (!VFS) {
1838     assert(FileMgr && "FileMgr is null on Reparse call");
1839     VFS = &FileMgr->getVirtualFileSystem();
1840   }
1841 
1842   clearFileLevelDecls();
1843 
1844   SimpleTimer ParsingTimer(WantTiming);
1845   ParsingTimer.setOutput("Reparsing " + getMainFileName());
1846 
1847   // Remap files.
1848   PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
1849   for (const auto &RB : PPOpts.RemappedFileBuffers)
1850     delete RB.second;
1851 
1852   Invocation->getPreprocessorOpts().clearRemappedFiles();
1853   for (const auto &RemappedFile : RemappedFiles) {
1854     Invocation->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
1855                                                       RemappedFile.second);
1856   }
1857 
1858   // If we have a preamble file lying around, or if we might try to
1859   // build a precompiled preamble, do so now.
1860   std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
1861   if (Preamble || PreambleRebuildCountdown > 0)
1862     OverrideMainBuffer =
1863         getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS);
1864 
1865   // Clear out the diagnostics state.
1866   FileMgr.reset();
1867   getDiagnostics().Reset();
1868   ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1869   if (OverrideMainBuffer)
1870     getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1871 
1872   // Parse the sources
1873   bool Result =
1874       Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS);
1875 
1876   // If we're caching global code-completion results, and the top-level
1877   // declarations have changed, clear out the code-completion cache.
1878   if (!Result && ShouldCacheCodeCompletionResults &&
1879       CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
1880     CacheCodeCompletionResults();
1881 
1882   // We now need to clear out the completion info related to this translation
1883   // unit; it'll be recreated if necessary.
1884   CCTUInfo.reset();
1885 
1886   return Result;
1887 }
1888 
1889 void ASTUnit::ResetForParse() {
1890   SavedMainFileBuffer.reset();
1891 
1892   SourceMgr.reset();
1893   TheSema.reset();
1894   Ctx.reset();
1895   PP.reset();
1896   Reader.reset();
1897 
1898   TopLevelDecls.clear();
1899   clearFileLevelDecls();
1900 }
1901 
1902 //----------------------------------------------------------------------------//
1903 // Code completion
1904 //----------------------------------------------------------------------------//
1905 
1906 namespace {
1907 
1908   /// Code completion consumer that combines the cached code-completion
1909   /// results from an ASTUnit with the code-completion results provided to it,
1910   /// then passes the result on to
1911   class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
1912     uint64_t NormalContexts;
1913     ASTUnit &AST;
1914     CodeCompleteConsumer &Next;
1915 
1916   public:
1917     AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
1918                                   const CodeCompleteOptions &CodeCompleteOpts)
1919         : CodeCompleteConsumer(CodeCompleteOpts), AST(AST), Next(Next) {
1920       // Compute the set of contexts in which we will look when we don't have
1921       // any information about the specific context.
1922       NormalContexts
1923         = (1LL << CodeCompletionContext::CCC_TopLevel)
1924         | (1LL << CodeCompletionContext::CCC_ObjCInterface)
1925         | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
1926         | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
1927         | (1LL << CodeCompletionContext::CCC_Statement)
1928         | (1LL << CodeCompletionContext::CCC_Expression)
1929         | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
1930         | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
1931         | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
1932         | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
1933         | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
1934         | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
1935         | (1LL << CodeCompletionContext::CCC_Recovery);
1936 
1937       if (AST.getASTContext().getLangOpts().CPlusPlus)
1938         NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
1939                        |  (1LL << CodeCompletionContext::CCC_UnionTag)
1940                        |  (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
1941     }
1942 
1943     void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
1944                                     CodeCompletionResult *Results,
1945                                     unsigned NumResults) override;
1946 
1947     void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1948                                    OverloadCandidate *Candidates,
1949                                    unsigned NumCandidates,
1950                                    SourceLocation OpenParLoc) override {
1951       Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates,
1952                                      OpenParLoc);
1953     }
1954 
1955     CodeCompletionAllocator &getAllocator() override {
1956       return Next.getAllocator();
1957     }
1958 
1959     CodeCompletionTUInfo &getCodeCompletionTUInfo() override {
1960       return Next.getCodeCompletionTUInfo();
1961     }
1962   };
1963 
1964 } // namespace
1965 
1966 /// Helper function that computes which global names are hidden by the
1967 /// local code-completion results.
1968 static void CalculateHiddenNames(const CodeCompletionContext &Context,
1969                                  CodeCompletionResult *Results,
1970                                  unsigned NumResults,
1971                                  ASTContext &Ctx,
1972                           llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
1973   bool OnlyTagNames = false;
1974   switch (Context.getKind()) {
1975   case CodeCompletionContext::CCC_Recovery:
1976   case CodeCompletionContext::CCC_TopLevel:
1977   case CodeCompletionContext::CCC_ObjCInterface:
1978   case CodeCompletionContext::CCC_ObjCImplementation:
1979   case CodeCompletionContext::CCC_ObjCIvarList:
1980   case CodeCompletionContext::CCC_ClassStructUnion:
1981   case CodeCompletionContext::CCC_Statement:
1982   case CodeCompletionContext::CCC_Expression:
1983   case CodeCompletionContext::CCC_ObjCMessageReceiver:
1984   case CodeCompletionContext::CCC_DotMemberAccess:
1985   case CodeCompletionContext::CCC_ArrowMemberAccess:
1986   case CodeCompletionContext::CCC_ObjCPropertyAccess:
1987   case CodeCompletionContext::CCC_Namespace:
1988   case CodeCompletionContext::CCC_Type:
1989   case CodeCompletionContext::CCC_Symbol:
1990   case CodeCompletionContext::CCC_SymbolOrNewName:
1991   case CodeCompletionContext::CCC_ParenthesizedExpression:
1992   case CodeCompletionContext::CCC_ObjCInterfaceName:
1993     break;
1994 
1995   case CodeCompletionContext::CCC_EnumTag:
1996   case CodeCompletionContext::CCC_UnionTag:
1997   case CodeCompletionContext::CCC_ClassOrStructTag:
1998     OnlyTagNames = true;
1999     break;
2000 
2001   case CodeCompletionContext::CCC_ObjCProtocolName:
2002   case CodeCompletionContext::CCC_MacroName:
2003   case CodeCompletionContext::CCC_MacroNameUse:
2004   case CodeCompletionContext::CCC_PreprocessorExpression:
2005   case CodeCompletionContext::CCC_PreprocessorDirective:
2006   case CodeCompletionContext::CCC_NaturalLanguage:
2007   case CodeCompletionContext::CCC_SelectorName:
2008   case CodeCompletionContext::CCC_TypeQualifiers:
2009   case CodeCompletionContext::CCC_Other:
2010   case CodeCompletionContext::CCC_OtherWithMacros:
2011   case CodeCompletionContext::CCC_ObjCInstanceMessage:
2012   case CodeCompletionContext::CCC_ObjCClassMessage:
2013   case CodeCompletionContext::CCC_ObjCCategoryName:
2014   case CodeCompletionContext::CCC_IncludedFile:
2015   case CodeCompletionContext::CCC_NewName:
2016     // We're looking for nothing, or we're looking for names that cannot
2017     // be hidden.
2018     return;
2019   }
2020 
2021   using Result = CodeCompletionResult;
2022   for (unsigned I = 0; I != NumResults; ++I) {
2023     if (Results[I].Kind != Result::RK_Declaration)
2024       continue;
2025 
2026     unsigned IDNS
2027       = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2028 
2029     bool Hiding = false;
2030     if (OnlyTagNames)
2031       Hiding = (IDNS & Decl::IDNS_Tag);
2032     else {
2033       unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
2034                              Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2035                              Decl::IDNS_NonMemberOperator);
2036       if (Ctx.getLangOpts().CPlusPlus)
2037         HiddenIDNS |= Decl::IDNS_Tag;
2038       Hiding = (IDNS & HiddenIDNS);
2039     }
2040 
2041     if (!Hiding)
2042       continue;
2043 
2044     DeclarationName Name = Results[I].Declaration->getDeclName();
2045     if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2046       HiddenNames.insert(Identifier->getName());
2047     else
2048       HiddenNames.insert(Name.getAsString());
2049   }
2050 }
2051 
2052 void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2053                                             CodeCompletionContext Context,
2054                                             CodeCompletionResult *Results,
2055                                             unsigned NumResults) {
2056   // Merge the results we were given with the results we cached.
2057   bool AddedResult = false;
2058   uint64_t InContexts =
2059       Context.getKind() == CodeCompletionContext::CCC_Recovery
2060         ? NormalContexts : (1LL << Context.getKind());
2061   // Contains the set of names that are hidden by "local" completion results.
2062   llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
2063   using Result = CodeCompletionResult;
2064   SmallVector<Result, 8> AllResults;
2065   for (ASTUnit::cached_completion_iterator
2066             C = AST.cached_completion_begin(),
2067          CEnd = AST.cached_completion_end();
2068        C != CEnd; ++C) {
2069     // If the context we are in matches any of the contexts we are
2070     // interested in, we'll add this result.
2071     if ((C->ShowInContexts & InContexts) == 0)
2072       continue;
2073 
2074     // If we haven't added any results previously, do so now.
2075     if (!AddedResult) {
2076       CalculateHiddenNames(Context, Results, NumResults, S.Context,
2077                            HiddenNames);
2078       AllResults.insert(AllResults.end(), Results, Results + NumResults);
2079       AddedResult = true;
2080     }
2081 
2082     // Determine whether this global completion result is hidden by a local
2083     // completion result. If so, skip it.
2084     if (C->Kind != CXCursor_MacroDefinition &&
2085         HiddenNames.count(C->Completion->getTypedText()))
2086       continue;
2087 
2088     // Adjust priority based on similar type classes.
2089     unsigned Priority = C->Priority;
2090     CodeCompletionString *Completion = C->Completion;
2091     if (!Context.getPreferredType().isNull()) {
2092       if (C->Kind == CXCursor_MacroDefinition) {
2093         Priority = getMacroUsagePriority(C->Completion->getTypedText(),
2094                                          S.getLangOpts(),
2095                                Context.getPreferredType()->isAnyPointerType());
2096       } else if (C->Type) {
2097         CanQualType Expected
2098           = S.Context.getCanonicalType(
2099                                Context.getPreferredType().getUnqualifiedType());
2100         SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2101         if (ExpectedSTC == C->TypeClass) {
2102           // We know this type is similar; check for an exact match.
2103           llvm::StringMap<unsigned> &CachedCompletionTypes
2104             = AST.getCachedCompletionTypes();
2105           llvm::StringMap<unsigned>::iterator Pos
2106             = CachedCompletionTypes.find(QualType(Expected).getAsString());
2107           if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2108             Priority /= CCF_ExactTypeMatch;
2109           else
2110             Priority /= CCF_SimilarTypeMatch;
2111         }
2112       }
2113     }
2114 
2115     // Adjust the completion string, if required.
2116     if (C->Kind == CXCursor_MacroDefinition &&
2117         Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2118       // Create a new code-completion string that just contains the
2119       // macro name, without its arguments.
2120       CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2121                                     CCP_CodePattern, C->Availability);
2122       Builder.AddTypedTextChunk(C->Completion->getTypedText());
2123       Priority = CCP_CodePattern;
2124       Completion = Builder.TakeString();
2125     }
2126 
2127     AllResults.push_back(Result(Completion, Priority, C->Kind,
2128                                 C->Availability));
2129   }
2130 
2131   // If we did not add any cached completion results, just forward the
2132   // results we were given to the next consumer.
2133   if (!AddedResult) {
2134     Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2135     return;
2136   }
2137 
2138   Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2139                                   AllResults.size());
2140 }
2141 
2142 void ASTUnit::CodeComplete(
2143     StringRef File, unsigned Line, unsigned Column,
2144     ArrayRef<RemappedFile> RemappedFiles, bool IncludeMacros,
2145     bool IncludeCodePatterns, bool IncludeBriefComments,
2146     CodeCompleteConsumer &Consumer,
2147     std::shared_ptr<PCHContainerOperations> PCHContainerOps,
2148     DiagnosticsEngine &Diag, LangOptions &LangOpts, SourceManager &SourceMgr,
2149     FileManager &FileMgr, SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2150     SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
2151   if (!Invocation)
2152     return;
2153 
2154   SimpleTimer CompletionTimer(WantTiming);
2155   CompletionTimer.setOutput("Code completion @ " + File + ":" +
2156                             Twine(Line) + ":" + Twine(Column));
2157 
2158   auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation);
2159 
2160   FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
2161   CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
2162   PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
2163 
2164   CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2165                                    CachedCompletionResults.empty();
2166   CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2167   CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2168   CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2169   CodeCompleteOpts.LoadExternal = Consumer.loadExternal();
2170   CodeCompleteOpts.IncludeFixIts = Consumer.includeFixIts();
2171 
2172   assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2173 
2174   FrontendOpts.CodeCompletionAt.FileName = std::string(File);
2175   FrontendOpts.CodeCompletionAt.Line = Line;
2176   FrontendOpts.CodeCompletionAt.Column = Column;
2177 
2178   // Set the language options appropriately.
2179   LangOpts = *CCInvocation->getLangOpts();
2180 
2181   // Spell-checking and warnings are wasteful during code-completion.
2182   LangOpts.SpellChecking = false;
2183   CCInvocation->getDiagnosticOpts().IgnoreWarnings = true;
2184 
2185   std::unique_ptr<CompilerInstance> Clang(
2186       new CompilerInstance(PCHContainerOps));
2187 
2188   // Recover resources if we crash before exiting this method.
2189   llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2190     CICleanup(Clang.get());
2191 
2192   auto &Inv = *CCInvocation;
2193   Clang->setInvocation(std::move(CCInvocation));
2194   OriginalSourceFile =
2195       std::string(Clang->getFrontendOpts().Inputs[0].getFile());
2196 
2197   // Set up diagnostics, capturing any diagnostics produced.
2198   Clang->setDiagnostics(&Diag);
2199   CaptureDroppedDiagnostics Capture(CaptureDiagsKind::All,
2200                                     Clang->getDiagnostics(),
2201                                     &StoredDiagnostics, nullptr);
2202   ProcessWarningOptions(Diag, Inv.getDiagnosticOpts());
2203 
2204   // Create the target instance.
2205   Clang->setTarget(TargetInfo::CreateTargetInfo(
2206       Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
2207   if (!Clang->hasTarget()) {
2208     Clang->setInvocation(nullptr);
2209     return;
2210   }
2211 
2212   // Inform the target of the language options.
2213   //
2214   // FIXME: We shouldn't need to do this, the target should be immutable once
2215   // created. This complexity should be lifted elsewhere.
2216   Clang->getTarget().adjust(Clang->getLangOpts());
2217 
2218   assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
2219          "Invocation must have exactly one source file!");
2220   assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
2221              InputKind::Source &&
2222          "FIXME: AST inputs not yet supported here!");
2223   assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
2224              Language::LLVM_IR &&
2225          "IR inputs not support here!");
2226 
2227   // Use the source and file managers that we were given.
2228   Clang->setFileManager(&FileMgr);
2229   Clang->setSourceManager(&SourceMgr);
2230 
2231   // Remap files.
2232   PreprocessorOpts.clearRemappedFiles();
2233   PreprocessorOpts.RetainRemappedFileBuffers = true;
2234   for (const auto &RemappedFile : RemappedFiles) {
2235     PreprocessorOpts.addRemappedFile(RemappedFile.first, RemappedFile.second);
2236     OwnedBuffers.push_back(RemappedFile.second);
2237   }
2238 
2239   // Use the code completion consumer we were given, but adding any cached
2240   // code-completion results.
2241   AugmentedCodeCompleteConsumer *AugmentedConsumer
2242     = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
2243   Clang->setCodeCompletionConsumer(AugmentedConsumer);
2244 
2245   // If we have a precompiled preamble, try to use it. We only allow
2246   // the use of the precompiled preamble if we're if the completion
2247   // point is within the main file, after the end of the precompiled
2248   // preamble.
2249   std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
2250   if (Preamble) {
2251     std::string CompleteFilePath(File);
2252 
2253     auto &VFS = FileMgr.getVirtualFileSystem();
2254     auto CompleteFileStatus = VFS.status(CompleteFilePath);
2255     if (CompleteFileStatus) {
2256       llvm::sys::fs::UniqueID CompleteFileID = CompleteFileStatus->getUniqueID();
2257 
2258       std::string MainPath(OriginalSourceFile);
2259       auto MainStatus = VFS.status(MainPath);
2260       if (MainStatus) {
2261         llvm::sys::fs::UniqueID MainID = MainStatus->getUniqueID();
2262         if (CompleteFileID == MainID && Line > 1)
2263           OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(
2264               PCHContainerOps, Inv, &VFS, false, Line - 1);
2265       }
2266     }
2267   }
2268 
2269   // If the main file has been overridden due to the use of a preamble,
2270   // make that override happen and introduce the preamble.
2271   if (OverrideMainBuffer) {
2272     assert(Preamble &&
2273            "No preamble was built, but OverrideMainBuffer is not null");
2274 
2275     IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS =
2276         &FileMgr.getVirtualFileSystem();
2277     Preamble->AddImplicitPreamble(Clang->getInvocation(), VFS,
2278                                   OverrideMainBuffer.get());
2279     // FIXME: there is no way to update VFS if it was changed by
2280     // AddImplicitPreamble as FileMgr is accepted as a parameter by this method.
2281     // We use on-disk preambles instead and rely on FileMgr's VFS to ensure the
2282     // PCH files are always readable.
2283     OwnedBuffers.push_back(OverrideMainBuffer.release());
2284   } else {
2285     PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2286     PreprocessorOpts.PrecompiledPreambleBytes.second = false;
2287   }
2288 
2289   // Disable the preprocessing record if modules are not enabled.
2290   if (!Clang->getLangOpts().Modules)
2291     PreprocessorOpts.DetailedRecord = false;
2292 
2293   std::unique_ptr<SyntaxOnlyAction> Act;
2294   Act.reset(new SyntaxOnlyAction);
2295   if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
2296     if (llvm::Error Err = Act->Execute()) {
2297       consumeError(std::move(Err)); // FIXME this drops errors on the floor.
2298     }
2299     Act->EndSourceFile();
2300   }
2301 }
2302 
2303 bool ASTUnit::Save(StringRef File) {
2304   if (HadModuleLoaderFatalFailure)
2305     return true;
2306 
2307   // Write to a temporary file and later rename it to the actual file, to avoid
2308   // possible race conditions.
2309   SmallString<128> TempPath;
2310   TempPath = File;
2311   TempPath += "-%%%%%%%%";
2312   // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2313   // unconditionally create a stat cache when we parse the file?
2314 
2315   if (llvm::Error Err = llvm::writeFileAtomically(
2316           TempPath, File, [this](llvm::raw_ostream &Out) {
2317             return serialize(Out) ? llvm::make_error<llvm::StringError>(
2318                                         "ASTUnit serialization failed",
2319                                         llvm::inconvertibleErrorCode())
2320                                   : llvm::Error::success();
2321           })) {
2322     consumeError(std::move(Err));
2323     return true;
2324   }
2325   return false;
2326 }
2327 
2328 static bool serializeUnit(ASTWriter &Writer,
2329                           SmallVectorImpl<char> &Buffer,
2330                           Sema &S,
2331                           bool hasErrors,
2332                           raw_ostream &OS) {
2333   Writer.WriteAST(S, std::string(), nullptr, "", hasErrors);
2334 
2335   // Write the generated bitstream to "Out".
2336   if (!Buffer.empty())
2337     OS.write(Buffer.data(), Buffer.size());
2338 
2339   return false;
2340 }
2341 
2342 bool ASTUnit::serialize(raw_ostream &OS) {
2343   // For serialization we are lenient if the errors were only warn-as-error kind.
2344   bool hasErrors = getDiagnostics().hasUncompilableErrorOccurred();
2345 
2346   if (WriterData)
2347     return serializeUnit(WriterData->Writer, WriterData->Buffer,
2348                          getSema(), hasErrors, OS);
2349 
2350   SmallString<128> Buffer;
2351   llvm::BitstreamWriter Stream(Buffer);
2352   InMemoryModuleCache ModuleCache;
2353   ASTWriter Writer(Stream, Buffer, ModuleCache, {});
2354   return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
2355 }
2356 
2357 using SLocRemap = ContinuousRangeMap<unsigned, int, 2>;
2358 
2359 void ASTUnit::TranslateStoredDiagnostics(
2360                           FileManager &FileMgr,
2361                           SourceManager &SrcMgr,
2362                           const SmallVectorImpl<StandaloneDiagnostic> &Diags,
2363                           SmallVectorImpl<StoredDiagnostic> &Out) {
2364   // Map the standalone diagnostic into the new source manager. We also need to
2365   // remap all the locations to the new view. This includes the diag location,
2366   // any associated source ranges, and the source ranges of associated fix-its.
2367   // FIXME: There should be a cleaner way to do this.
2368   SmallVector<StoredDiagnostic, 4> Result;
2369   Result.reserve(Diags.size());
2370 
2371   for (const auto &SD : Diags) {
2372     // Rebuild the StoredDiagnostic.
2373     if (SD.Filename.empty())
2374       continue;
2375     auto FE = FileMgr.getFile(SD.Filename);
2376     if (!FE)
2377       continue;
2378     SourceLocation FileLoc;
2379     auto ItFileID = PreambleSrcLocCache.find(SD.Filename);
2380     if (ItFileID == PreambleSrcLocCache.end()) {
2381       FileID FID = SrcMgr.translateFile(*FE);
2382       FileLoc = SrcMgr.getLocForStartOfFile(FID);
2383       PreambleSrcLocCache[SD.Filename] = FileLoc;
2384     } else {
2385       FileLoc = ItFileID->getValue();
2386     }
2387 
2388     if (FileLoc.isInvalid())
2389       continue;
2390     SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset);
2391     FullSourceLoc Loc(L, SrcMgr);
2392 
2393     SmallVector<CharSourceRange, 4> Ranges;
2394     Ranges.reserve(SD.Ranges.size());
2395     for (const auto &Range : SD.Ranges) {
2396       SourceLocation BL = FileLoc.getLocWithOffset(Range.first);
2397       SourceLocation EL = FileLoc.getLocWithOffset(Range.second);
2398       Ranges.push_back(CharSourceRange::getCharRange(BL, EL));
2399     }
2400 
2401     SmallVector<FixItHint, 2> FixIts;
2402     FixIts.reserve(SD.FixIts.size());
2403     for (const auto &FixIt : SD.FixIts) {
2404       FixIts.push_back(FixItHint());
2405       FixItHint &FH = FixIts.back();
2406       FH.CodeToInsert = FixIt.CodeToInsert;
2407       SourceLocation BL = FileLoc.getLocWithOffset(FixIt.RemoveRange.first);
2408       SourceLocation EL = FileLoc.getLocWithOffset(FixIt.RemoveRange.second);
2409       FH.RemoveRange = CharSourceRange::getCharRange(BL, EL);
2410     }
2411 
2412     Result.push_back(StoredDiagnostic(SD.Level, SD.ID,
2413                                       SD.Message, Loc, Ranges, FixIts));
2414   }
2415   Result.swap(Out);
2416 }
2417 
2418 void ASTUnit::addFileLevelDecl(Decl *D) {
2419   assert(D);
2420 
2421   // We only care about local declarations.
2422   if (D->isFromASTFile())
2423     return;
2424 
2425   SourceManager &SM = *SourceMgr;
2426   SourceLocation Loc = D->getLocation();
2427   if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2428     return;
2429 
2430   // We only keep track of the file-level declarations of each file.
2431   if (!D->getLexicalDeclContext()->isFileContext())
2432     return;
2433 
2434   SourceLocation FileLoc = SM.getFileLoc(Loc);
2435   assert(SM.isLocalSourceLocation(FileLoc));
2436   FileID FID;
2437   unsigned Offset;
2438   std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
2439   if (FID.isInvalid())
2440     return;
2441 
2442   std::unique_ptr<LocDeclsTy> &Decls = FileDecls[FID];
2443   if (!Decls)
2444     Decls = std::make_unique<LocDeclsTy>();
2445 
2446   std::pair<unsigned, Decl *> LocDecl(Offset, D);
2447 
2448   if (Decls->empty() || Decls->back().first <= Offset) {
2449     Decls->push_back(LocDecl);
2450     return;
2451   }
2452 
2453   LocDeclsTy::iterator I =
2454       llvm::upper_bound(*Decls, LocDecl, llvm::less_first());
2455 
2456   Decls->insert(I, LocDecl);
2457 }
2458 
2459 void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2460                                   SmallVectorImpl<Decl *> &Decls) {
2461   if (File.isInvalid())
2462     return;
2463 
2464   if (SourceMgr->isLoadedFileID(File)) {
2465     assert(Ctx->getExternalSource() && "No external source!");
2466     return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2467                                                          Decls);
2468   }
2469 
2470   FileDeclsTy::iterator I = FileDecls.find(File);
2471   if (I == FileDecls.end())
2472     return;
2473 
2474   LocDeclsTy &LocDecls = *I->second;
2475   if (LocDecls.empty())
2476     return;
2477 
2478   LocDeclsTy::iterator BeginIt =
2479       llvm::partition_point(LocDecls, [=](std::pair<unsigned, Decl *> LD) {
2480         return LD.first < Offset;
2481       });
2482   if (BeginIt != LocDecls.begin())
2483     --BeginIt;
2484 
2485   // If we are pointing at a top-level decl inside an objc container, we need
2486   // to backtrack until we find it otherwise we will fail to report that the
2487   // region overlaps with an objc container.
2488   while (BeginIt != LocDecls.begin() &&
2489          BeginIt->second->isTopLevelDeclInObjCContainer())
2490     --BeginIt;
2491 
2492   LocDeclsTy::iterator EndIt = llvm::upper_bound(
2493       LocDecls, std::make_pair(Offset + Length, (Decl *)nullptr),
2494       llvm::less_first());
2495   if (EndIt != LocDecls.end())
2496     ++EndIt;
2497 
2498   for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2499     Decls.push_back(DIt->second);
2500 }
2501 
2502 SourceLocation ASTUnit::getLocation(const FileEntry *File,
2503                                     unsigned Line, unsigned Col) const {
2504   const SourceManager &SM = getSourceManager();
2505   SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
2506   return SM.getMacroArgExpandedLocation(Loc);
2507 }
2508 
2509 SourceLocation ASTUnit::getLocation(const FileEntry *File,
2510                                     unsigned Offset) const {
2511   const SourceManager &SM = getSourceManager();
2512   SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
2513   return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2514 }
2515 
2516 /// If \arg Loc is a loaded location from the preamble, returns
2517 /// the corresponding local location of the main file, otherwise it returns
2518 /// \arg Loc.
2519 SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) const {
2520   FileID PreambleID;
2521   if (SourceMgr)
2522     PreambleID = SourceMgr->getPreambleFileID();
2523 
2524   if (Loc.isInvalid() || !Preamble || PreambleID.isInvalid())
2525     return Loc;
2526 
2527   unsigned Offs;
2528   if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble->getBounds().Size) {
2529     SourceLocation FileLoc
2530         = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2531     return FileLoc.getLocWithOffset(Offs);
2532   }
2533 
2534   return Loc;
2535 }
2536 
2537 /// If \arg Loc is a local location of the main file but inside the
2538 /// preamble chunk, returns the corresponding loaded location from the
2539 /// preamble, otherwise it returns \arg Loc.
2540 SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) const {
2541   FileID PreambleID;
2542   if (SourceMgr)
2543     PreambleID = SourceMgr->getPreambleFileID();
2544 
2545   if (Loc.isInvalid() || !Preamble || PreambleID.isInvalid())
2546     return Loc;
2547 
2548   unsigned Offs;
2549   if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2550       Offs < Preamble->getBounds().Size) {
2551     SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2552     return FileLoc.getLocWithOffset(Offs);
2553   }
2554 
2555   return Loc;
2556 }
2557 
2558 bool ASTUnit::isInPreambleFileID(SourceLocation Loc) const {
2559   FileID FID;
2560   if (SourceMgr)
2561     FID = SourceMgr->getPreambleFileID();
2562 
2563   if (Loc.isInvalid() || FID.isInvalid())
2564     return false;
2565 
2566   return SourceMgr->isInFileID(Loc, FID);
2567 }
2568 
2569 bool ASTUnit::isInMainFileID(SourceLocation Loc) const {
2570   FileID FID;
2571   if (SourceMgr)
2572     FID = SourceMgr->getMainFileID();
2573 
2574   if (Loc.isInvalid() || FID.isInvalid())
2575     return false;
2576 
2577   return SourceMgr->isInFileID(Loc, FID);
2578 }
2579 
2580 SourceLocation ASTUnit::getEndOfPreambleFileID() const {
2581   FileID FID;
2582   if (SourceMgr)
2583     FID = SourceMgr->getPreambleFileID();
2584 
2585   if (FID.isInvalid())
2586     return {};
2587 
2588   return SourceMgr->getLocForEndOfFile(FID);
2589 }
2590 
2591 SourceLocation ASTUnit::getStartOfMainFileID() const {
2592   FileID FID;
2593   if (SourceMgr)
2594     FID = SourceMgr->getMainFileID();
2595 
2596   if (FID.isInvalid())
2597     return {};
2598 
2599   return SourceMgr->getLocForStartOfFile(FID);
2600 }
2601 
2602 llvm::iterator_range<PreprocessingRecord::iterator>
2603 ASTUnit::getLocalPreprocessingEntities() const {
2604   if (isMainFileAST()) {
2605     serialization::ModuleFile &
2606       Mod = Reader->getModuleManager().getPrimaryModule();
2607     return Reader->getModulePreprocessedEntities(Mod);
2608   }
2609 
2610   if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
2611     return llvm::make_range(PPRec->local_begin(), PPRec->local_end());
2612 
2613   return llvm::make_range(PreprocessingRecord::iterator(),
2614                           PreprocessingRecord::iterator());
2615 }
2616 
2617 bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
2618   if (isMainFileAST()) {
2619     serialization::ModuleFile &
2620       Mod = Reader->getModuleManager().getPrimaryModule();
2621     for (const auto *D : Reader->getModuleFileLevelDecls(Mod)) {
2622       if (!Fn(context, D))
2623         return false;
2624     }
2625 
2626     return true;
2627   }
2628 
2629   for (ASTUnit::top_level_iterator TL = top_level_begin(),
2630                                 TLEnd = top_level_end();
2631          TL != TLEnd; ++TL) {
2632     if (!Fn(context, *TL))
2633       return false;
2634   }
2635 
2636   return true;
2637 }
2638 
2639 const FileEntry *ASTUnit::getPCHFile() {
2640   if (!Reader)
2641     return nullptr;
2642 
2643   serialization::ModuleFile *Mod = nullptr;
2644   Reader->getModuleManager().visit([&Mod](serialization::ModuleFile &M) {
2645     switch (M.Kind) {
2646     case serialization::MK_ImplicitModule:
2647     case serialization::MK_ExplicitModule:
2648     case serialization::MK_PrebuiltModule:
2649       return true; // skip dependencies.
2650     case serialization::MK_PCH:
2651       Mod = &M;
2652       return true; // found it.
2653     case serialization::MK_Preamble:
2654       return false; // look in dependencies.
2655     case serialization::MK_MainFile:
2656       return false; // look in dependencies.
2657     }
2658 
2659     return true;
2660   });
2661   if (Mod)
2662     return Mod->File;
2663 
2664   return nullptr;
2665 }
2666 
2667 bool ASTUnit::isModuleFile() const {
2668   return isMainFileAST() && getLangOpts().isCompilingModule();
2669 }
2670 
2671 InputKind ASTUnit::getInputKind() const {
2672   auto &LangOpts = getLangOpts();
2673 
2674   Language Lang;
2675   if (LangOpts.OpenCL)
2676     Lang = Language::OpenCL;
2677   else if (LangOpts.CUDA)
2678     Lang = Language::CUDA;
2679   else if (LangOpts.RenderScript)
2680     Lang = Language::RenderScript;
2681   else if (LangOpts.CPlusPlus)
2682     Lang = LangOpts.ObjC ? Language::ObjCXX : Language::CXX;
2683   else
2684     Lang = LangOpts.ObjC ? Language::ObjC : Language::C;
2685 
2686   InputKind::Format Fmt = InputKind::Source;
2687   if (LangOpts.getCompilingModule() == LangOptions::CMK_ModuleMap)
2688     Fmt = InputKind::ModuleMap;
2689 
2690   // We don't know if input was preprocessed. Assume not.
2691   bool PP = false;
2692 
2693   return InputKind(Lang, Fmt, PP);
2694 }
2695 
2696 #ifndef NDEBUG
2697 ASTUnit::ConcurrencyState::ConcurrencyState() {
2698   Mutex = new std::recursive_mutex;
2699 }
2700 
2701 ASTUnit::ConcurrencyState::~ConcurrencyState() {
2702   delete static_cast<std::recursive_mutex *>(Mutex);
2703 }
2704 
2705 void ASTUnit::ConcurrencyState::start() {
2706   bool acquired = static_cast<std::recursive_mutex *>(Mutex)->try_lock();
2707   assert(acquired && "Concurrent access to ASTUnit!");
2708 }
2709 
2710 void ASTUnit::ConcurrencyState::finish() {
2711   static_cast<std::recursive_mutex *>(Mutex)->unlock();
2712 }
2713 
2714 #else // NDEBUG
2715 
2716 ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex = nullptr; }
2717 ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2718 void ASTUnit::ConcurrencyState::start() {}
2719 void ASTUnit::ConcurrencyState::finish() {}
2720 
2721 #endif // NDEBUG
2722