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