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