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