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,
517                          bool Complain) 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.push_back(StoredDiagnostic(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, IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
652     const FileSystemOptions &FileSystemOpts, bool OnlyLocalDecls,
653     ArrayRef<RemappedFile> RemappedFiles, bool CaptureDiagnostics,
654     bool AllowPCHWithCompilerErrors, bool UserFilesAreVolatile) {
655   std::unique_ptr<ASTUnit> AST(new ASTUnit(true));
656 
657   // Recover resources if we crash before exiting this method.
658   llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
659     ASTUnitCleanup(AST.get());
660   llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
661     llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
662     DiagCleanup(Diags.get());
663 
664   ConfigureDiags(Diags, *AST, CaptureDiagnostics);
665 
666   AST->OnlyLocalDecls = OnlyLocalDecls;
667   AST->CaptureDiagnostics = CaptureDiagnostics;
668   AST->Diagnostics = Diags;
669   IntrusiveRefCntPtr<vfs::FileSystem> VFS = vfs::getRealFileSystem();
670   AST->FileMgr = new FileManager(FileSystemOpts, VFS);
671   AST->UserFilesAreVolatile = UserFilesAreVolatile;
672   AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
673                                      AST->getFileManager(),
674                                      UserFilesAreVolatile);
675   AST->HSOpts = new HeaderSearchOptions();
676 
677   AST->HeaderInfo.reset(new HeaderSearch(AST->HSOpts,
678                                          AST->getSourceManager(),
679                                          AST->getDiagnostics(),
680                                          AST->ASTFileLangOpts,
681                                          /*Target=*/nullptr));
682 
683   PreprocessorOptions *PPOpts = new PreprocessorOptions();
684 
685   for (const auto &RemappedFile : RemappedFiles)
686     PPOpts->addRemappedFile(RemappedFile.first, RemappedFile.second);
687 
688   // Gather Info for preprocessor construction later on.
689 
690   HeaderSearch &HeaderInfo = *AST->HeaderInfo;
691   unsigned Counter;
692 
693   AST->PP =
694       new Preprocessor(PPOpts, AST->getDiagnostics(), AST->ASTFileLangOpts,
695                        AST->getSourceManager(), HeaderInfo, *AST,
696                        /*IILookup=*/nullptr,
697                        /*OwnsHeaderSearch=*/false);
698   Preprocessor &PP = *AST->PP;
699 
700   AST->Ctx = new ASTContext(AST->ASTFileLangOpts, AST->getSourceManager(),
701                             PP.getIdentifierTable(), PP.getSelectorTable(),
702                             PP.getBuiltinInfo());
703   ASTContext &Context = *AST->Ctx;
704 
705   bool disableValid = false;
706   if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
707     disableValid = true;
708   AST->Reader = new ASTReader(PP, Context,
709                              /*isysroot=*/"",
710                              /*DisableValidation=*/disableValid,
711                              AllowPCHWithCompilerErrors);
712 
713   AST->Reader->setListener(llvm::make_unique<ASTInfoCollector>(
714       *AST->PP, Context, AST->ASTFileLangOpts, AST->TargetOpts, AST->Target,
715       Counter));
716 
717   switch (AST->Reader->ReadAST(Filename, serialization::MK_MainFile,
718                           SourceLocation(), ASTReader::ARR_None)) {
719   case ASTReader::Success:
720     break;
721 
722   case ASTReader::Failure:
723   case ASTReader::Missing:
724   case ASTReader::OutOfDate:
725   case ASTReader::VersionMismatch:
726   case ASTReader::ConfigurationMismatch:
727   case ASTReader::HadErrors:
728     AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
729     return nullptr;
730   }
731 
732   AST->OriginalSourceFile = AST->Reader->getOriginalSourceFile();
733 
734   PP.setCounterValue(Counter);
735 
736   // Attach the AST reader to the AST context as an external AST
737   // source, so that declarations will be deserialized from the
738   // AST file as needed.
739   Context.setExternalSource(AST->Reader);
740 
741   // Create an AST consumer, even though it isn't used.
742   AST->Consumer.reset(new ASTConsumer);
743 
744   // Create a semantic analysis object and tell the AST reader about it.
745   AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
746   AST->TheSema->Initialize();
747   AST->Reader->InitializeSema(*AST->TheSema);
748 
749   // Tell the diagnostic client that we have started a source file.
750   AST->getDiagnostics().getClient()->BeginSourceFile(Context.getLangOpts(),&PP);
751 
752   return AST;
753 }
754 
755 namespace {
756 
757 /// \brief Preprocessor callback class that updates a hash value with the names
758 /// of all macros that have been defined by the translation unit.
759 class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
760   unsigned &Hash;
761 
762 public:
763   explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
764 
765   void MacroDefined(const Token &MacroNameTok,
766                     const MacroDirective *MD) override {
767     Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
768   }
769 };
770 
771 /// \brief Add the given declaration to the hash of all top-level entities.
772 void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
773   if (!D)
774     return;
775 
776   DeclContext *DC = D->getDeclContext();
777   if (!DC)
778     return;
779 
780   if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
781     return;
782 
783   if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
784     if (EnumDecl *EnumD = dyn_cast<EnumDecl>(D)) {
785       // For an unscoped enum include the enumerators in the hash since they
786       // enter the top-level namespace.
787       if (!EnumD->isScoped()) {
788         for (const auto *EI : EnumD->enumerators()) {
789           if (EI->getIdentifier())
790             Hash = llvm::HashString(EI->getIdentifier()->getName(), Hash);
791         }
792       }
793     }
794 
795     if (ND->getIdentifier())
796       Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
797     else if (DeclarationName Name = ND->getDeclName()) {
798       std::string NameStr = Name.getAsString();
799       Hash = llvm::HashString(NameStr, Hash);
800     }
801     return;
802   }
803 
804   if (ImportDecl *ImportD = dyn_cast<ImportDecl>(D)) {
805     if (Module *Mod = ImportD->getImportedModule()) {
806       std::string ModName = Mod->getFullModuleName();
807       Hash = llvm::HashString(ModName, Hash);
808     }
809     return;
810   }
811 }
812 
813 class TopLevelDeclTrackerConsumer : public ASTConsumer {
814   ASTUnit &Unit;
815   unsigned &Hash;
816 
817 public:
818   TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
819     : Unit(_Unit), Hash(Hash) {
820     Hash = 0;
821   }
822 
823   void handleTopLevelDecl(Decl *D) {
824     if (!D)
825       return;
826 
827     // FIXME: Currently ObjC method declarations are incorrectly being
828     // reported as top-level declarations, even though their DeclContext
829     // is the containing ObjC @interface/@implementation.  This is a
830     // fundamental problem in the parser right now.
831     if (isa<ObjCMethodDecl>(D))
832       return;
833 
834     AddTopLevelDeclarationToHash(D, Hash);
835     Unit.addTopLevelDecl(D);
836 
837     handleFileLevelDecl(D);
838   }
839 
840   void handleFileLevelDecl(Decl *D) {
841     Unit.addFileLevelDecl(D);
842     if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
843       for (auto *I : NSD->decls())
844         handleFileLevelDecl(I);
845     }
846   }
847 
848   bool HandleTopLevelDecl(DeclGroupRef D) override {
849     for (Decl *TopLevelDecl : D)
850       handleTopLevelDecl(TopLevelDecl);
851     return true;
852   }
853 
854   // We're not interested in "interesting" decls.
855   void HandleInterestingDecl(DeclGroupRef) override {}
856 
857   void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
858     for (Decl *TopLevelDecl : D)
859       handleTopLevelDecl(TopLevelDecl);
860   }
861 
862   ASTMutationListener *GetASTMutationListener() override {
863     return Unit.getASTMutationListener();
864   }
865 
866   ASTDeserializationListener *GetASTDeserializationListener() override {
867     return Unit.getDeserializationListener();
868   }
869 };
870 
871 class TopLevelDeclTrackerAction : public ASTFrontendAction {
872 public:
873   ASTUnit &Unit;
874 
875   std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
876                                                  StringRef InFile) override {
877     CI.getPreprocessor().addPPCallbacks(
878         llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
879                                            Unit.getCurrentTopLevelHashValue()));
880     return llvm::make_unique<TopLevelDeclTrackerConsumer>(
881         Unit, Unit.getCurrentTopLevelHashValue());
882   }
883 
884 public:
885   TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
886 
887   bool hasCodeCompletionSupport() const override { return false; }
888   TranslationUnitKind getTranslationUnitKind() override {
889     return Unit.getTranslationUnitKind();
890   }
891 };
892 
893 class PrecompilePreambleAction : public ASTFrontendAction {
894   ASTUnit &Unit;
895   bool HasEmittedPreamblePCH;
896 
897 public:
898   explicit PrecompilePreambleAction(ASTUnit &Unit)
899       : Unit(Unit), HasEmittedPreamblePCH(false) {}
900 
901   std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
902                                                  StringRef InFile) override;
903   bool hasEmittedPreamblePCH() const { return HasEmittedPreamblePCH; }
904   void setHasEmittedPreamblePCH() { HasEmittedPreamblePCH = true; }
905   bool shouldEraseOutputFiles() override { return !hasEmittedPreamblePCH(); }
906 
907   bool hasCodeCompletionSupport() const override { return false; }
908   bool hasASTFileSupport() const override { return false; }
909   TranslationUnitKind getTranslationUnitKind() override { return TU_Prefix; }
910 };
911 
912 class PrecompilePreambleConsumer : public PCHGenerator {
913   ASTUnit &Unit;
914   unsigned &Hash;
915   std::vector<Decl *> TopLevelDecls;
916   PrecompilePreambleAction *Action;
917 
918 public:
919   PrecompilePreambleConsumer(ASTUnit &Unit, PrecompilePreambleAction *Action,
920                              const Preprocessor &PP, StringRef isysroot,
921                              raw_ostream *Out)
922     : PCHGenerator(PP, "", nullptr, isysroot, Out, /*AllowASTWithErrors=*/true),
923       Unit(Unit), Hash(Unit.getCurrentTopLevelHashValue()), Action(Action) {
924     Hash = 0;
925   }
926 
927   bool HandleTopLevelDecl(DeclGroupRef DG) override {
928     for (Decl *D : DG) {
929       // FIXME: Currently ObjC method declarations are incorrectly being
930       // reported as top-level declarations, even though their DeclContext
931       // is the containing ObjC @interface/@implementation.  This is a
932       // fundamental problem in the parser right now.
933       if (isa<ObjCMethodDecl>(D))
934         continue;
935       AddTopLevelDeclarationToHash(D, Hash);
936       TopLevelDecls.push_back(D);
937     }
938     return true;
939   }
940 
941   void HandleTranslationUnit(ASTContext &Ctx) override {
942     PCHGenerator::HandleTranslationUnit(Ctx);
943     if (hasEmittedPCH()) {
944       // Translate the top-level declarations we captured during
945       // parsing into declaration IDs in the precompiled
946       // preamble. This will allow us to deserialize those top-level
947       // declarations when requested.
948       for (Decl *D : TopLevelDecls) {
949         // Invalid top-level decls may not have been serialized.
950         if (D->isInvalidDecl())
951           continue;
952         Unit.addTopLevelDeclFromPreamble(getWriter().getDeclID(D));
953       }
954 
955       Action->setHasEmittedPreamblePCH();
956     }
957   }
958 };
959 
960 }
961 
962 std::unique_ptr<ASTConsumer>
963 PrecompilePreambleAction::CreateASTConsumer(CompilerInstance &CI,
964                                             StringRef InFile) {
965   std::string Sysroot;
966   std::string OutputFile;
967   raw_ostream *OS = nullptr;
968   if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
969                                                      OutputFile, OS))
970     return nullptr;
971 
972   if (!CI.getFrontendOpts().RelocatablePCH)
973     Sysroot.clear();
974 
975   CI.getPreprocessor().addPPCallbacks(
976       llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
977                                            Unit.getCurrentTopLevelHashValue()));
978   return llvm::make_unique<PrecompilePreambleConsumer>(
979       Unit, this, CI.getPreprocessor(), Sysroot, OS);
980 }
981 
982 static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag) {
983   return StoredDiag.getLocation().isValid();
984 }
985 
986 static void
987 checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &StoredDiags) {
988   // Get rid of stored diagnostics except the ones from the driver which do not
989   // have a source location.
990   StoredDiags.erase(
991       std::remove_if(StoredDiags.begin(), StoredDiags.end(), isNonDriverDiag),
992       StoredDiags.end());
993 }
994 
995 static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
996                                                               StoredDiagnostics,
997                                   SourceManager &SM) {
998   // The stored diagnostic has the old source manager in it; update
999   // the locations to refer into the new source manager. Since we've
1000   // been careful to make sure that the source manager's state
1001   // before and after are identical, so that we can reuse the source
1002   // location itself.
1003   for (StoredDiagnostic &SD : StoredDiagnostics) {
1004     if (SD.getLocation().isValid()) {
1005       FullSourceLoc Loc(SD.getLocation(), SM);
1006       SD.setLocation(Loc);
1007     }
1008   }
1009 }
1010 
1011 /// Parse the source file into a translation unit using the given compiler
1012 /// invocation, replacing the current translation unit.
1013 ///
1014 /// \returns True if a failure occurred that causes the ASTUnit not to
1015 /// contain any translation-unit information, false otherwise.
1016 bool ASTUnit::Parse(std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer) {
1017   SavedMainFileBuffer.reset();
1018 
1019   if (!Invocation)
1020     return true;
1021 
1022   // Create the compiler instance to use for building the AST.
1023   std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
1024 
1025   // Recover resources if we crash before exiting this method.
1026   llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1027     CICleanup(Clang.get());
1028 
1029   IntrusiveRefCntPtr<CompilerInvocation>
1030     CCInvocation(new CompilerInvocation(*Invocation));
1031 
1032   Clang->setInvocation(CCInvocation.get());
1033   OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1034 
1035   // Set up diagnostics, capturing any diagnostics that would
1036   // otherwise be dropped.
1037   Clang->setDiagnostics(&getDiagnostics());
1038 
1039   // Create the target instance.
1040   Clang->setTarget(TargetInfo::CreateTargetInfo(
1041       Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
1042   if (!Clang->hasTarget())
1043     return true;
1044 
1045   // Inform the target of the language options.
1046   //
1047   // FIXME: We shouldn't need to do this, the target should be immutable once
1048   // created. This complexity should be lifted elsewhere.
1049   Clang->getTarget().adjust(Clang->getLangOpts());
1050 
1051   assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1052          "Invocation must have exactly one source file!");
1053   assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
1054          "FIXME: AST inputs not yet supported here!");
1055   assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
1056          "IR inputs not support here!");
1057 
1058   // Configure the various subsystems.
1059   LangOpts = Clang->getInvocation().LangOpts;
1060   FileSystemOpts = Clang->getFileSystemOpts();
1061   IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1062       createVFSFromCompilerInvocation(Clang->getInvocation(), getDiagnostics());
1063   if (!VFS)
1064     return true;
1065   FileMgr = new FileManager(FileSystemOpts, VFS);
1066   SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1067                                 UserFilesAreVolatile);
1068   TheSema.reset();
1069   Ctx = nullptr;
1070   PP = nullptr;
1071   Reader = nullptr;
1072 
1073   // Clear out old caches and data.
1074   TopLevelDecls.clear();
1075   clearFileLevelDecls();
1076   CleanTemporaryFiles();
1077 
1078   if (!OverrideMainBuffer) {
1079     checkAndRemoveNonDriverDiags(StoredDiagnostics);
1080     TopLevelDeclsInPreamble.clear();
1081   }
1082 
1083   // Create a file manager object to provide access to and cache the filesystem.
1084   Clang->setFileManager(&getFileManager());
1085 
1086   // Create the source manager.
1087   Clang->setSourceManager(&getSourceManager());
1088 
1089   // If the main file has been overridden due to the use of a preamble,
1090   // make that override happen and introduce the preamble.
1091   PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
1092   if (OverrideMainBuffer) {
1093     PreprocessorOpts.addRemappedFile(OriginalSourceFile,
1094                                      OverrideMainBuffer.get());
1095     PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1096     PreprocessorOpts.PrecompiledPreambleBytes.second
1097                                                     = PreambleEndsAtStartOfLine;
1098     PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
1099     PreprocessorOpts.DisablePCHValidation = true;
1100 
1101     // The stored diagnostic has the old source manager in it; update
1102     // the locations to refer into the new source manager. Since we've
1103     // been careful to make sure that the source manager's state
1104     // before and after are identical, so that we can reuse the source
1105     // location itself.
1106     checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
1107 
1108     // Keep track of the override buffer;
1109     SavedMainFileBuffer = std::move(OverrideMainBuffer);
1110   }
1111 
1112   std::unique_ptr<TopLevelDeclTrackerAction> Act(
1113       new TopLevelDeclTrackerAction(*this));
1114 
1115   // Recover resources if we crash before exiting this method.
1116   llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1117     ActCleanup(Act.get());
1118 
1119   if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
1120     goto error;
1121 
1122   if (SavedMainFileBuffer) {
1123     std::string ModName = getPreambleFile(this);
1124     TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
1125                                PreambleDiagnostics, StoredDiagnostics);
1126   }
1127 
1128   if (!Act->Execute())
1129     goto error;
1130 
1131   transferASTDataFromCompilerInstance(*Clang);
1132 
1133   Act->EndSourceFile();
1134 
1135   FailedParseDiagnostics.clear();
1136 
1137   return false;
1138 
1139 error:
1140   // Remove the overridden buffer we used for the preamble.
1141   SavedMainFileBuffer = nullptr;
1142 
1143   // Keep the ownership of the data in the ASTUnit because the client may
1144   // want to see the diagnostics.
1145   transferASTDataFromCompilerInstance(*Clang);
1146   FailedParseDiagnostics.swap(StoredDiagnostics);
1147   StoredDiagnostics.clear();
1148   NumStoredDiagnosticsFromDriver = 0;
1149   return true;
1150 }
1151 
1152 /// \brief Simple function to retrieve a path for a preamble precompiled header.
1153 static std::string GetPreamblePCHPath() {
1154   // FIXME: This is a hack so that we can override the preamble file during
1155   // crash-recovery testing, which is the only case where the preamble files
1156   // are not necessarily cleaned up.
1157   const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1158   if (TmpFile)
1159     return TmpFile;
1160 
1161   SmallString<128> Path;
1162   llvm::sys::fs::createTemporaryFile("preamble", "pch", Path);
1163 
1164   return Path.str();
1165 }
1166 
1167 /// \brief Compute the preamble for the main file, providing the source buffer
1168 /// that corresponds to the main file along with a pair (bytes, start-of-line)
1169 /// that describes the preamble.
1170 ASTUnit::ComputedPreamble
1171 ASTUnit::ComputePreamble(CompilerInvocation &Invocation, unsigned MaxLines) {
1172   FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
1173   PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
1174 
1175   // Try to determine if the main file has been remapped, either from the
1176   // command line (to another file) or directly through the compiler invocation
1177   // (to a memory buffer).
1178   llvm::MemoryBuffer *Buffer = nullptr;
1179   std::unique_ptr<llvm::MemoryBuffer> BufferOwner;
1180   std::string MainFilePath(FrontendOpts.Inputs[0].getFile());
1181   llvm::sys::fs::UniqueID MainFileID;
1182   if (!llvm::sys::fs::getUniqueID(MainFilePath, MainFileID)) {
1183     // Check whether there is a file-file remapping of the main file
1184     for (const auto &RF : PreprocessorOpts.RemappedFiles) {
1185       std::string MPath(RF.first);
1186       llvm::sys::fs::UniqueID MID;
1187       if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
1188         if (MainFileID == MID) {
1189           // We found a remapping. Try to load the resulting, remapped source.
1190           BufferOwner = getBufferForFile(RF.second);
1191           if (!BufferOwner)
1192             return ComputedPreamble(nullptr, nullptr, 0, true);
1193         }
1194       }
1195     }
1196 
1197     // Check whether there is a file-buffer remapping. It supercedes the
1198     // file-file remapping.
1199     for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
1200       std::string MPath(RB.first);
1201       llvm::sys::fs::UniqueID MID;
1202       if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
1203         if (MainFileID == MID) {
1204           // We found a remapping.
1205           BufferOwner.reset();
1206           Buffer = const_cast<llvm::MemoryBuffer *>(RB.second);
1207         }
1208       }
1209     }
1210   }
1211 
1212   // If the main source file was not remapped, load it now.
1213   if (!Buffer && !BufferOwner) {
1214     BufferOwner = getBufferForFile(FrontendOpts.Inputs[0].getFile());
1215     if (!BufferOwner)
1216       return ComputedPreamble(nullptr, nullptr, 0, true);
1217   }
1218 
1219   if (!Buffer)
1220     Buffer = BufferOwner.get();
1221   auto Pre = Lexer::ComputePreamble(Buffer->getBuffer(),
1222                                     *Invocation.getLangOpts(), MaxLines);
1223   return ComputedPreamble(Buffer, std::move(BufferOwner), Pre.first,
1224                           Pre.second);
1225 }
1226 
1227 ASTUnit::PreambleFileHash
1228 ASTUnit::PreambleFileHash::createForFile(off_t Size, time_t ModTime) {
1229   PreambleFileHash Result;
1230   Result.Size = Size;
1231   Result.ModTime = ModTime;
1232   memset(Result.MD5, 0, sizeof(Result.MD5));
1233   return Result;
1234 }
1235 
1236 ASTUnit::PreambleFileHash ASTUnit::PreambleFileHash::createForMemoryBuffer(
1237     const llvm::MemoryBuffer *Buffer) {
1238   PreambleFileHash Result;
1239   Result.Size = Buffer->getBufferSize();
1240   Result.ModTime = 0;
1241 
1242   llvm::MD5 MD5Ctx;
1243   MD5Ctx.update(Buffer->getBuffer().data());
1244   MD5Ctx.final(Result.MD5);
1245 
1246   return Result;
1247 }
1248 
1249 namespace clang {
1250 bool operator==(const ASTUnit::PreambleFileHash &LHS,
1251                 const ASTUnit::PreambleFileHash &RHS) {
1252   return LHS.Size == RHS.Size && LHS.ModTime == RHS.ModTime &&
1253          memcmp(LHS.MD5, RHS.MD5, sizeof(LHS.MD5)) == 0;
1254 }
1255 } // namespace clang
1256 
1257 static std::pair<unsigned, unsigned>
1258 makeStandaloneRange(CharSourceRange Range, const SourceManager &SM,
1259                     const LangOptions &LangOpts) {
1260   CharSourceRange FileRange = Lexer::makeFileCharRange(Range, SM, LangOpts);
1261   unsigned Offset = SM.getFileOffset(FileRange.getBegin());
1262   unsigned EndOffset = SM.getFileOffset(FileRange.getEnd());
1263   return std::make_pair(Offset, EndOffset);
1264 }
1265 
1266 static ASTUnit::StandaloneFixIt makeStandaloneFixIt(const SourceManager &SM,
1267                                                     const LangOptions &LangOpts,
1268                                                     const FixItHint &InFix) {
1269   ASTUnit::StandaloneFixIt OutFix;
1270   OutFix.RemoveRange = makeStandaloneRange(InFix.RemoveRange, SM, LangOpts);
1271   OutFix.InsertFromRange = makeStandaloneRange(InFix.InsertFromRange, SM,
1272                                                LangOpts);
1273   OutFix.CodeToInsert = InFix.CodeToInsert;
1274   OutFix.BeforePreviousInsertions = InFix.BeforePreviousInsertions;
1275   return OutFix;
1276 }
1277 
1278 static ASTUnit::StandaloneDiagnostic
1279 makeStandaloneDiagnostic(const LangOptions &LangOpts,
1280                          const StoredDiagnostic &InDiag) {
1281   ASTUnit::StandaloneDiagnostic OutDiag;
1282   OutDiag.ID = InDiag.getID();
1283   OutDiag.Level = InDiag.getLevel();
1284   OutDiag.Message = InDiag.getMessage();
1285   OutDiag.LocOffset = 0;
1286   if (InDiag.getLocation().isInvalid())
1287     return OutDiag;
1288   const SourceManager &SM = InDiag.getLocation().getManager();
1289   SourceLocation FileLoc = SM.getFileLoc(InDiag.getLocation());
1290   OutDiag.Filename = SM.getFilename(FileLoc);
1291   if (OutDiag.Filename.empty())
1292     return OutDiag;
1293   OutDiag.LocOffset = SM.getFileOffset(FileLoc);
1294   for (const CharSourceRange &Range : InDiag.getRanges())
1295     OutDiag.Ranges.push_back(makeStandaloneRange(Range, SM, LangOpts));
1296   for (const FixItHint &FixIt : InDiag.getFixIts())
1297     OutDiag.FixIts.push_back(makeStandaloneFixIt(SM, LangOpts, FixIt));
1298 
1299   return OutDiag;
1300 }
1301 
1302 /// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1303 /// the source file.
1304 ///
1305 /// This routine will compute the preamble of the main source file. If a
1306 /// non-trivial preamble is found, it will precompile that preamble into a
1307 /// precompiled header so that the precompiled preamble can be used to reduce
1308 /// reparsing time. If a precompiled preamble has already been constructed,
1309 /// this routine will determine if it is still valid and, if so, avoid
1310 /// rebuilding the precompiled preamble.
1311 ///
1312 /// \param AllowRebuild When true (the default), this routine is
1313 /// allowed to rebuild the precompiled preamble if it is found to be
1314 /// out-of-date.
1315 ///
1316 /// \param MaxLines When non-zero, the maximum number of lines that
1317 /// can occur within the preamble.
1318 ///
1319 /// \returns If the precompiled preamble can be used, returns a newly-allocated
1320 /// buffer that should be used in place of the main file when doing so.
1321 /// Otherwise, returns a NULL pointer.
1322 std::unique_ptr<llvm::MemoryBuffer>
1323 ASTUnit::getMainBufferWithPrecompiledPreamble(
1324     const CompilerInvocation &PreambleInvocationIn, bool AllowRebuild,
1325     unsigned MaxLines) {
1326 
1327   IntrusiveRefCntPtr<CompilerInvocation>
1328     PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1329   FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
1330   PreprocessorOptions &PreprocessorOpts
1331     = PreambleInvocation->getPreprocessorOpts();
1332 
1333   ComputedPreamble NewPreamble = ComputePreamble(*PreambleInvocation, MaxLines);
1334 
1335   if (!NewPreamble.Size) {
1336     // We couldn't find a preamble in the main source. Clear out the current
1337     // preamble, if we have one. It's obviously no good any more.
1338     Preamble.clear();
1339     erasePreambleFile(this);
1340 
1341     // The next time we actually see a preamble, precompile it.
1342     PreambleRebuildCounter = 1;
1343     return nullptr;
1344   }
1345 
1346   if (!Preamble.empty()) {
1347     // We've previously computed a preamble. Check whether we have the same
1348     // preamble now that we did before, and that there's enough space in
1349     // the main-file buffer within the precompiled preamble to fit the
1350     // new main file.
1351     if (Preamble.size() == NewPreamble.Size &&
1352         PreambleEndsAtStartOfLine == NewPreamble.PreambleEndsAtStartOfLine &&
1353         memcmp(Preamble.getBufferStart(), NewPreamble.Buffer->getBufferStart(),
1354                NewPreamble.Size) == 0) {
1355       // The preamble has not changed. We may be able to re-use the precompiled
1356       // preamble.
1357 
1358       // Check that none of the files used by the preamble have changed.
1359       bool AnyFileChanged = false;
1360 
1361       // First, make a record of those files that have been overridden via
1362       // remapping or unsaved_files.
1363       llvm::StringMap<PreambleFileHash> OverriddenFiles;
1364       for (const auto &R : PreprocessorOpts.RemappedFiles) {
1365         if (AnyFileChanged)
1366           break;
1367 
1368         vfs::Status Status;
1369         if (FileMgr->getNoncachedStatValue(R.second, Status)) {
1370           // If we can't stat the file we're remapping to, assume that something
1371           // horrible happened.
1372           AnyFileChanged = true;
1373           break;
1374         }
1375 
1376         OverriddenFiles[R.first] = PreambleFileHash::createForFile(
1377             Status.getSize(), Status.getLastModificationTime().toEpochTime());
1378       }
1379 
1380       for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
1381         if (AnyFileChanged)
1382           break;
1383         OverriddenFiles[RB.first] =
1384             PreambleFileHash::createForMemoryBuffer(RB.second);
1385       }
1386 
1387       // Check whether anything has changed.
1388       for (llvm::StringMap<PreambleFileHash>::iterator
1389              F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1390            !AnyFileChanged && F != FEnd;
1391            ++F) {
1392         llvm::StringMap<PreambleFileHash>::iterator Overridden
1393           = OverriddenFiles.find(F->first());
1394         if (Overridden != OverriddenFiles.end()) {
1395           // This file was remapped; check whether the newly-mapped file
1396           // matches up with the previous mapping.
1397           if (Overridden->second != F->second)
1398             AnyFileChanged = true;
1399           continue;
1400         }
1401 
1402         // The file was not remapped; check whether it has changed on disk.
1403         vfs::Status Status;
1404         if (FileMgr->getNoncachedStatValue(F->first(), Status)) {
1405           // If we can't stat the file, assume that something horrible happened.
1406           AnyFileChanged = true;
1407         } else if (Status.getSize() != uint64_t(F->second.Size) ||
1408                    Status.getLastModificationTime().toEpochTime() !=
1409                        uint64_t(F->second.ModTime))
1410           AnyFileChanged = true;
1411       }
1412 
1413       if (!AnyFileChanged) {
1414         // Okay! We can re-use the precompiled preamble.
1415 
1416         // Set the state of the diagnostic object to mimic its state
1417         // after parsing the preamble.
1418         getDiagnostics().Reset();
1419         ProcessWarningOptions(getDiagnostics(),
1420                               PreambleInvocation->getDiagnosticOpts());
1421         getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1422 
1423         return llvm::MemoryBuffer::getMemBufferCopy(
1424             NewPreamble.Buffer->getBuffer(), FrontendOpts.Inputs[0].getFile());
1425       }
1426     }
1427 
1428     // If we aren't allowed to rebuild the precompiled preamble, just
1429     // return now.
1430     if (!AllowRebuild)
1431       return nullptr;
1432 
1433     // We can't reuse the previously-computed preamble. Build a new one.
1434     Preamble.clear();
1435     PreambleDiagnostics.clear();
1436     erasePreambleFile(this);
1437     PreambleRebuildCounter = 1;
1438   } else if (!AllowRebuild) {
1439     // We aren't allowed to rebuild the precompiled preamble; just
1440     // return now.
1441     return nullptr;
1442   }
1443 
1444   // If the preamble rebuild counter > 1, it's because we previously
1445   // failed to build a preamble and we're not yet ready to try
1446   // again. Decrement the counter and return a failure.
1447   if (PreambleRebuildCounter > 1) {
1448     --PreambleRebuildCounter;
1449     return nullptr;
1450   }
1451 
1452   // Create a temporary file for the precompiled preamble. In rare
1453   // circumstances, this can fail.
1454   std::string PreamblePCHPath = GetPreamblePCHPath();
1455   if (PreamblePCHPath.empty()) {
1456     // Try again next time.
1457     PreambleRebuildCounter = 1;
1458     return nullptr;
1459   }
1460 
1461   // We did not previously compute a preamble, or it can't be reused anyway.
1462   SimpleTimer PreambleTimer(WantTiming);
1463   PreambleTimer.setOutput("Precompiling preamble");
1464 
1465   // Save the preamble text for later; we'll need to compare against it for
1466   // subsequent reparses.
1467   StringRef MainFilename = FrontendOpts.Inputs[0].getFile();
1468   Preamble.assign(FileMgr->getFile(MainFilename),
1469                   NewPreamble.Buffer->getBufferStart(),
1470                   NewPreamble.Buffer->getBufferStart() + NewPreamble.Size);
1471   PreambleEndsAtStartOfLine = NewPreamble.PreambleEndsAtStartOfLine;
1472 
1473   PreambleBuffer = llvm::MemoryBuffer::getMemBufferCopy(
1474       NewPreamble.Buffer->getBuffer().slice(0, Preamble.size()), MainFilename);
1475 
1476   // Remap the main source file to the preamble buffer.
1477   StringRef MainFilePath = FrontendOpts.Inputs[0].getFile();
1478   PreprocessorOpts.addRemappedFile(MainFilePath, PreambleBuffer.get());
1479 
1480   // Tell the compiler invocation to generate a temporary precompiled header.
1481   FrontendOpts.ProgramAction = frontend::GeneratePCH;
1482   // FIXME: Generate the precompiled header into memory?
1483   FrontendOpts.OutputFile = PreamblePCHPath;
1484   PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1485   PreprocessorOpts.PrecompiledPreambleBytes.second = false;
1486 
1487   // Create the compiler instance to use for building the precompiled preamble.
1488   std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
1489 
1490   // Recover resources if we crash before exiting this method.
1491   llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1492     CICleanup(Clang.get());
1493 
1494   Clang->setInvocation(&*PreambleInvocation);
1495   OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1496 
1497   // Set up diagnostics, capturing all of the diagnostics produced.
1498   Clang->setDiagnostics(&getDiagnostics());
1499 
1500   // Create the target instance.
1501   Clang->setTarget(TargetInfo::CreateTargetInfo(
1502       Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
1503   if (!Clang->hasTarget()) {
1504     llvm::sys::fs::remove(FrontendOpts.OutputFile);
1505     Preamble.clear();
1506     PreambleRebuildCounter = DefaultPreambleRebuildInterval;
1507     PreprocessorOpts.RemappedFileBuffers.pop_back();
1508     return nullptr;
1509   }
1510 
1511   // Inform the target of the language options.
1512   //
1513   // FIXME: We shouldn't need to do this, the target should be immutable once
1514   // created. This complexity should be lifted elsewhere.
1515   Clang->getTarget().adjust(Clang->getLangOpts());
1516 
1517   assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1518          "Invocation must have exactly one source file!");
1519   assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
1520          "FIXME: AST inputs not yet supported here!");
1521   assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
1522          "IR inputs not support here!");
1523 
1524   // Clear out old caches and data.
1525   getDiagnostics().Reset();
1526   ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
1527   checkAndRemoveNonDriverDiags(StoredDiagnostics);
1528   TopLevelDecls.clear();
1529   TopLevelDeclsInPreamble.clear();
1530   PreambleDiagnostics.clear();
1531 
1532   IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1533       createVFSFromCompilerInvocation(Clang->getInvocation(), getDiagnostics());
1534   if (!VFS)
1535     return nullptr;
1536 
1537   // Create a file manager object to provide access to and cache the filesystem.
1538   Clang->setFileManager(new FileManager(Clang->getFileSystemOpts(), VFS));
1539 
1540   // Create the source manager.
1541   Clang->setSourceManager(new SourceManager(getDiagnostics(),
1542                                             Clang->getFileManager()));
1543 
1544   auto PreambleDepCollector = std::make_shared<DependencyCollector>();
1545   Clang->addDependencyCollector(PreambleDepCollector);
1546 
1547   std::unique_ptr<PrecompilePreambleAction> Act;
1548   Act.reset(new PrecompilePreambleAction(*this));
1549   if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1550     llvm::sys::fs::remove(FrontendOpts.OutputFile);
1551     Preamble.clear();
1552     PreambleRebuildCounter = DefaultPreambleRebuildInterval;
1553     PreprocessorOpts.RemappedFileBuffers.pop_back();
1554     return nullptr;
1555   }
1556 
1557   Act->Execute();
1558 
1559   // Transfer any diagnostics generated when parsing the preamble into the set
1560   // of preamble diagnostics.
1561   for (stored_diag_iterator I = stored_diag_afterDriver_begin(),
1562                             E = stored_diag_end();
1563        I != E; ++I)
1564     PreambleDiagnostics.push_back(
1565         makeStandaloneDiagnostic(Clang->getLangOpts(), *I));
1566 
1567   Act->EndSourceFile();
1568 
1569   checkAndRemoveNonDriverDiags(StoredDiagnostics);
1570 
1571   if (!Act->hasEmittedPreamblePCH()) {
1572     // The preamble PCH failed (e.g. there was a module loading fatal error),
1573     // so no precompiled header was generated. Forget that we even tried.
1574     // FIXME: Should we leave a note for ourselves to try again?
1575     llvm::sys::fs::remove(FrontendOpts.OutputFile);
1576     Preamble.clear();
1577     TopLevelDeclsInPreamble.clear();
1578     PreambleRebuildCounter = DefaultPreambleRebuildInterval;
1579     PreprocessorOpts.RemappedFileBuffers.pop_back();
1580     return nullptr;
1581   }
1582 
1583   // Keep track of the preamble we precompiled.
1584   setPreambleFile(this, FrontendOpts.OutputFile);
1585   NumWarningsInPreamble = getDiagnostics().getNumWarnings();
1586 
1587   // Keep track of all of the files that the source manager knows about,
1588   // so we can verify whether they have changed or not.
1589   FilesInPreamble.clear();
1590   SourceManager &SourceMgr = Clang->getSourceManager();
1591   for (auto &Filename : PreambleDepCollector->getDependencies()) {
1592     const FileEntry *File = Clang->getFileManager().getFile(Filename);
1593     if (!File || File == SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()))
1594       continue;
1595     if (time_t ModTime = File->getModificationTime()) {
1596       FilesInPreamble[File->getName()] = PreambleFileHash::createForFile(
1597           File->getSize(), ModTime);
1598     } else {
1599       llvm::MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File);
1600       FilesInPreamble[File->getName()] =
1601           PreambleFileHash::createForMemoryBuffer(Buffer);
1602     }
1603   }
1604 
1605   PreambleRebuildCounter = 1;
1606   PreprocessorOpts.RemappedFileBuffers.pop_back();
1607 
1608   // If the hash of top-level entities differs from the hash of the top-level
1609   // entities the last time we rebuilt the preamble, clear out the completion
1610   // cache.
1611   if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1612     CompletionCacheTopLevelHashValue = 0;
1613     PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1614   }
1615 
1616   return llvm::MemoryBuffer::getMemBufferCopy(NewPreamble.Buffer->getBuffer(),
1617                                               MainFilename);
1618 }
1619 
1620 void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1621   std::vector<Decl *> Resolved;
1622   Resolved.reserve(TopLevelDeclsInPreamble.size());
1623   ExternalASTSource &Source = *getASTContext().getExternalSource();
1624   for (serialization::DeclID TopLevelDecl : TopLevelDeclsInPreamble) {
1625     // Resolve the declaration ID to an actual declaration, possibly
1626     // deserializing the declaration in the process.
1627     if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
1628       Resolved.push_back(D);
1629   }
1630   TopLevelDeclsInPreamble.clear();
1631   TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1632 }
1633 
1634 void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
1635   // Steal the created target, context, and preprocessor if they have been
1636   // created.
1637   assert(CI.hasInvocation() && "missing invocation");
1638   LangOpts = CI.getInvocation().LangOpts;
1639   TheSema = CI.takeSema();
1640   Consumer = CI.takeASTConsumer();
1641   if (CI.hasASTContext())
1642     Ctx = &CI.getASTContext();
1643   if (CI.hasPreprocessor())
1644     PP = &CI.getPreprocessor();
1645   CI.setSourceManager(nullptr);
1646   CI.setFileManager(nullptr);
1647   if (CI.hasTarget())
1648     Target = &CI.getTarget();
1649   Reader = CI.getModuleManager();
1650   HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure();
1651 }
1652 
1653 StringRef ASTUnit::getMainFileName() const {
1654   if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1655     const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0];
1656     if (Input.isFile())
1657       return Input.getFile();
1658     else
1659       return Input.getBuffer()->getBufferIdentifier();
1660   }
1661 
1662   if (SourceMgr) {
1663     if (const FileEntry *
1664           FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
1665       return FE->getName();
1666   }
1667 
1668   return StringRef();
1669 }
1670 
1671 StringRef ASTUnit::getASTFileName() const {
1672   if (!isMainFileAST())
1673     return StringRef();
1674 
1675   serialization::ModuleFile &
1676     Mod = Reader->getModuleManager().getPrimaryModule();
1677   return Mod.FileName;
1678 }
1679 
1680 ASTUnit *ASTUnit::create(CompilerInvocation *CI,
1681                          IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1682                          bool CaptureDiagnostics,
1683                          bool UserFilesAreVolatile) {
1684   std::unique_ptr<ASTUnit> AST;
1685   AST.reset(new ASTUnit(false));
1686   ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1687   AST->Diagnostics = Diags;
1688   AST->Invocation = CI;
1689   AST->FileSystemOpts = CI->getFileSystemOpts();
1690   IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1691       createVFSFromCompilerInvocation(*CI, *Diags);
1692   if (!VFS)
1693     return nullptr;
1694   AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
1695   AST->UserFilesAreVolatile = UserFilesAreVolatile;
1696   AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1697                                      UserFilesAreVolatile);
1698 
1699   return AST.release();
1700 }
1701 
1702 ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(
1703     CompilerInvocation *CI, IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1704     ASTFrontendAction *Action, ASTUnit *Unit, bool Persistent,
1705     StringRef ResourceFilesPath, bool OnlyLocalDecls, bool CaptureDiagnostics,
1706     bool PrecompilePreamble, bool CacheCodeCompletionResults,
1707     bool IncludeBriefCommentsInCodeCompletion, bool UserFilesAreVolatile,
1708     std::unique_ptr<ASTUnit> *ErrAST) {
1709   assert(CI && "A CompilerInvocation is required");
1710 
1711   std::unique_ptr<ASTUnit> OwnAST;
1712   ASTUnit *AST = Unit;
1713   if (!AST) {
1714     // Create the AST unit.
1715     OwnAST.reset(create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile));
1716     AST = OwnAST.get();
1717     if (!AST)
1718       return nullptr;
1719   }
1720 
1721   if (!ResourceFilesPath.empty()) {
1722     // Override the resources path.
1723     CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1724   }
1725   AST->OnlyLocalDecls = OnlyLocalDecls;
1726   AST->CaptureDiagnostics = CaptureDiagnostics;
1727   if (PrecompilePreamble)
1728     AST->PreambleRebuildCounter = 2;
1729   AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
1730   AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1731   AST->IncludeBriefCommentsInCodeCompletion
1732     = IncludeBriefCommentsInCodeCompletion;
1733 
1734   // Recover resources if we crash before exiting this method.
1735   llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1736     ASTUnitCleanup(OwnAST.get());
1737   llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1738     llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
1739     DiagCleanup(Diags.get());
1740 
1741   // We'll manage file buffers ourselves.
1742   CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1743   CI->getFrontendOpts().DisableFree = false;
1744   ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1745 
1746   // Create the compiler instance to use for building the AST.
1747   std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
1748 
1749   // Recover resources if we crash before exiting this method.
1750   llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1751     CICleanup(Clang.get());
1752 
1753   Clang->setInvocation(CI);
1754   AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1755 
1756   // Set up diagnostics, capturing any diagnostics that would
1757   // otherwise be dropped.
1758   Clang->setDiagnostics(&AST->getDiagnostics());
1759 
1760   // Create the target instance.
1761   Clang->setTarget(TargetInfo::CreateTargetInfo(
1762       Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
1763   if (!Clang->hasTarget())
1764     return nullptr;
1765 
1766   // Inform the target of the language options.
1767   //
1768   // FIXME: We shouldn't need to do this, the target should be immutable once
1769   // created. This complexity should be lifted elsewhere.
1770   Clang->getTarget().adjust(Clang->getLangOpts());
1771 
1772   assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1773          "Invocation must have exactly one source file!");
1774   assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
1775          "FIXME: AST inputs not yet supported here!");
1776   assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
1777          "IR inputs not supported here!");
1778 
1779   // Configure the various subsystems.
1780   AST->TheSema.reset();
1781   AST->Ctx = nullptr;
1782   AST->PP = nullptr;
1783   AST->Reader = nullptr;
1784 
1785   // Create a file manager object to provide access to and cache the filesystem.
1786   Clang->setFileManager(&AST->getFileManager());
1787 
1788   // Create the source manager.
1789   Clang->setSourceManager(&AST->getSourceManager());
1790 
1791   ASTFrontendAction *Act = Action;
1792 
1793   std::unique_ptr<TopLevelDeclTrackerAction> TrackerAct;
1794   if (!Act) {
1795     TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1796     Act = TrackerAct.get();
1797   }
1798 
1799   // Recover resources if we crash before exiting this method.
1800   llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1801     ActCleanup(TrackerAct.get());
1802 
1803   if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1804     AST->transferASTDataFromCompilerInstance(*Clang);
1805     if (OwnAST && ErrAST)
1806       ErrAST->swap(OwnAST);
1807 
1808     return nullptr;
1809   }
1810 
1811   if (Persistent && !TrackerAct) {
1812     Clang->getPreprocessor().addPPCallbacks(
1813         llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
1814                                            AST->getCurrentTopLevelHashValue()));
1815     std::vector<std::unique_ptr<ASTConsumer>> Consumers;
1816     if (Clang->hasASTConsumer())
1817       Consumers.push_back(Clang->takeASTConsumer());
1818     Consumers.push_back(llvm::make_unique<TopLevelDeclTrackerConsumer>(
1819         *AST, AST->getCurrentTopLevelHashValue()));
1820     Clang->setASTConsumer(
1821         llvm::make_unique<MultiplexConsumer>(std::move(Consumers)));
1822   }
1823   if (!Act->Execute()) {
1824     AST->transferASTDataFromCompilerInstance(*Clang);
1825     if (OwnAST && ErrAST)
1826       ErrAST->swap(OwnAST);
1827 
1828     return nullptr;
1829   }
1830 
1831   // Steal the created target, context, and preprocessor.
1832   AST->transferASTDataFromCompilerInstance(*Clang);
1833 
1834   Act->EndSourceFile();
1835 
1836   if (OwnAST)
1837     return OwnAST.release();
1838   else
1839     return AST;
1840 }
1841 
1842 bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1843   if (!Invocation)
1844     return true;
1845 
1846   // We'll manage file buffers ourselves.
1847   Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1848   Invocation->getFrontendOpts().DisableFree = false;
1849   ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1850 
1851   std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
1852   if (PrecompilePreamble) {
1853     PreambleRebuildCounter = 2;
1854     OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
1855   }
1856 
1857   SimpleTimer ParsingTimer(WantTiming);
1858   ParsingTimer.setOutput("Parsing " + getMainFileName());
1859 
1860   // Recover resources if we crash before exiting this method.
1861   llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1862     MemBufferCleanup(OverrideMainBuffer.get());
1863 
1864   return Parse(std::move(OverrideMainBuffer));
1865 }
1866 
1867 std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation(
1868     CompilerInvocation *CI, IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1869     bool OnlyLocalDecls, bool CaptureDiagnostics, bool PrecompilePreamble,
1870     TranslationUnitKind TUKind, bool CacheCodeCompletionResults,
1871     bool IncludeBriefCommentsInCodeCompletion, bool UserFilesAreVolatile) {
1872   // Create the AST unit.
1873   std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
1874   ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1875   AST->Diagnostics = Diags;
1876   AST->OnlyLocalDecls = OnlyLocalDecls;
1877   AST->CaptureDiagnostics = CaptureDiagnostics;
1878   AST->TUKind = TUKind;
1879   AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1880   AST->IncludeBriefCommentsInCodeCompletion
1881     = IncludeBriefCommentsInCodeCompletion;
1882   AST->Invocation = CI;
1883   AST->FileSystemOpts = CI->getFileSystemOpts();
1884   IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1885       createVFSFromCompilerInvocation(*CI, *Diags);
1886   if (!VFS)
1887     return nullptr;
1888   AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
1889   AST->UserFilesAreVolatile = UserFilesAreVolatile;
1890 
1891   // Recover resources if we crash before exiting this method.
1892   llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1893     ASTUnitCleanup(AST.get());
1894   llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1895     llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
1896     DiagCleanup(Diags.get());
1897 
1898   if (AST->LoadFromCompilerInvocation(PrecompilePreamble))
1899     return nullptr;
1900   return AST;
1901 }
1902 
1903 ASTUnit *ASTUnit::LoadFromCommandLine(
1904     const char **ArgBegin, const char **ArgEnd,
1905     IntrusiveRefCntPtr<DiagnosticsEngine> Diags, StringRef ResourceFilesPath,
1906     bool OnlyLocalDecls, bool CaptureDiagnostics,
1907     ArrayRef<RemappedFile> RemappedFiles, bool RemappedFilesKeepOriginalName,
1908     bool PrecompilePreamble, TranslationUnitKind TUKind,
1909     bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1910     bool AllowPCHWithCompilerErrors, bool SkipFunctionBodies,
1911     bool UserFilesAreVolatile, bool ForSerialization,
1912     std::unique_ptr<ASTUnit> *ErrAST) {
1913   assert(Diags.get() && "no DiagnosticsEngine was provided");
1914 
1915   SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
1916 
1917   IntrusiveRefCntPtr<CompilerInvocation> CI;
1918 
1919   {
1920 
1921     CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
1922                                       StoredDiagnostics);
1923 
1924     CI = clang::createInvocationFromCommandLine(
1925                                            llvm::makeArrayRef(ArgBegin, ArgEnd),
1926                                            Diags);
1927     if (!CI)
1928       return nullptr;
1929   }
1930 
1931   // Override any files that need remapping
1932   for (const auto &RemappedFile : RemappedFiles) {
1933     CI->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
1934                                               RemappedFile.second);
1935   }
1936   PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
1937   PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
1938   PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
1939 
1940   // Override the resources path.
1941   CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1942 
1943   CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
1944 
1945   // Create the AST unit.
1946   std::unique_ptr<ASTUnit> AST;
1947   AST.reset(new ASTUnit(false));
1948   ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1949   AST->Diagnostics = Diags;
1950   AST->FileSystemOpts = CI->getFileSystemOpts();
1951   IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1952       createVFSFromCompilerInvocation(*CI, *Diags);
1953   if (!VFS)
1954     return nullptr;
1955   AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
1956   AST->OnlyLocalDecls = OnlyLocalDecls;
1957   AST->CaptureDiagnostics = CaptureDiagnostics;
1958   AST->TUKind = TUKind;
1959   AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1960   AST->IncludeBriefCommentsInCodeCompletion
1961     = IncludeBriefCommentsInCodeCompletion;
1962   AST->UserFilesAreVolatile = UserFilesAreVolatile;
1963   AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
1964   AST->StoredDiagnostics.swap(StoredDiagnostics);
1965   AST->Invocation = CI;
1966   if (ForSerialization)
1967     AST->WriterData.reset(new ASTWriterData());
1968   // Zero out now to ease cleanup during crash recovery.
1969   CI = nullptr;
1970   Diags = nullptr;
1971 
1972   // Recover resources if we crash before exiting this method.
1973   llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1974     ASTUnitCleanup(AST.get());
1975 
1976   if (AST->LoadFromCompilerInvocation(PrecompilePreamble)) {
1977     // Some error occurred, if caller wants to examine diagnostics, pass it the
1978     // ASTUnit.
1979     if (ErrAST) {
1980       AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
1981       ErrAST->swap(AST);
1982     }
1983     return nullptr;
1984   }
1985 
1986   return AST.release();
1987 }
1988 
1989 bool ASTUnit::Reparse(ArrayRef<RemappedFile> RemappedFiles) {
1990   if (!Invocation)
1991     return true;
1992 
1993   clearFileLevelDecls();
1994 
1995   SimpleTimer ParsingTimer(WantTiming);
1996   ParsingTimer.setOutput("Reparsing " + getMainFileName());
1997 
1998   // Remap files.
1999   PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
2000   for (const auto &RB : PPOpts.RemappedFileBuffers)
2001     delete RB.second;
2002 
2003   Invocation->getPreprocessorOpts().clearRemappedFiles();
2004   for (const auto &RemappedFile : RemappedFiles) {
2005     Invocation->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
2006                                                       RemappedFile.second);
2007   }
2008 
2009   // If we have a preamble file lying around, or if we might try to
2010   // build a precompiled preamble, do so now.
2011   std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
2012   if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
2013     OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
2014 
2015   // Clear out the diagnostics state.
2016   getDiagnostics().Reset();
2017   ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
2018   if (OverrideMainBuffer)
2019     getDiagnostics().setNumWarnings(NumWarningsInPreamble);
2020 
2021   // Parse the sources
2022   bool Result = Parse(std::move(OverrideMainBuffer));
2023 
2024   // If we're caching global code-completion results, and the top-level
2025   // declarations have changed, clear out the code-completion cache.
2026   if (!Result && ShouldCacheCodeCompletionResults &&
2027       CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2028     CacheCodeCompletionResults();
2029 
2030   // We now need to clear out the completion info related to this translation
2031   // unit; it'll be recreated if necessary.
2032   CCTUInfo.reset();
2033 
2034   return Result;
2035 }
2036 
2037 //----------------------------------------------------------------------------//
2038 // Code completion
2039 //----------------------------------------------------------------------------//
2040 
2041 namespace {
2042   /// \brief Code completion consumer that combines the cached code-completion
2043   /// results from an ASTUnit with the code-completion results provided to it,
2044   /// then passes the result on to
2045   class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
2046     uint64_t NormalContexts;
2047     ASTUnit &AST;
2048     CodeCompleteConsumer &Next;
2049 
2050   public:
2051     AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
2052                                   const CodeCompleteOptions &CodeCompleteOpts)
2053       : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
2054         AST(AST), Next(Next)
2055     {
2056       // Compute the set of contexts in which we will look when we don't have
2057       // any information about the specific context.
2058       NormalContexts
2059         = (1LL << CodeCompletionContext::CCC_TopLevel)
2060         | (1LL << CodeCompletionContext::CCC_ObjCInterface)
2061         | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
2062         | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
2063         | (1LL << CodeCompletionContext::CCC_Statement)
2064         | (1LL << CodeCompletionContext::CCC_Expression)
2065         | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
2066         | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
2067         | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
2068         | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
2069         | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
2070         | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
2071         | (1LL << CodeCompletionContext::CCC_Recovery);
2072 
2073       if (AST.getASTContext().getLangOpts().CPlusPlus)
2074         NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
2075                        |  (1LL << CodeCompletionContext::CCC_UnionTag)
2076                        |  (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
2077     }
2078 
2079     void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
2080                                     CodeCompletionResult *Results,
2081                                     unsigned NumResults) override;
2082 
2083     void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2084                                    OverloadCandidate *Candidates,
2085                                    unsigned NumCandidates) override {
2086       Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2087     }
2088 
2089     CodeCompletionAllocator &getAllocator() override {
2090       return Next.getAllocator();
2091     }
2092 
2093     CodeCompletionTUInfo &getCodeCompletionTUInfo() override {
2094       return Next.getCodeCompletionTUInfo();
2095     }
2096   };
2097 }
2098 
2099 /// \brief Helper function that computes which global names are hidden by the
2100 /// local code-completion results.
2101 static void CalculateHiddenNames(const CodeCompletionContext &Context,
2102                                  CodeCompletionResult *Results,
2103                                  unsigned NumResults,
2104                                  ASTContext &Ctx,
2105                           llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
2106   bool OnlyTagNames = false;
2107   switch (Context.getKind()) {
2108   case CodeCompletionContext::CCC_Recovery:
2109   case CodeCompletionContext::CCC_TopLevel:
2110   case CodeCompletionContext::CCC_ObjCInterface:
2111   case CodeCompletionContext::CCC_ObjCImplementation:
2112   case CodeCompletionContext::CCC_ObjCIvarList:
2113   case CodeCompletionContext::CCC_ClassStructUnion:
2114   case CodeCompletionContext::CCC_Statement:
2115   case CodeCompletionContext::CCC_Expression:
2116   case CodeCompletionContext::CCC_ObjCMessageReceiver:
2117   case CodeCompletionContext::CCC_DotMemberAccess:
2118   case CodeCompletionContext::CCC_ArrowMemberAccess:
2119   case CodeCompletionContext::CCC_ObjCPropertyAccess:
2120   case CodeCompletionContext::CCC_Namespace:
2121   case CodeCompletionContext::CCC_Type:
2122   case CodeCompletionContext::CCC_Name:
2123   case CodeCompletionContext::CCC_PotentiallyQualifiedName:
2124   case CodeCompletionContext::CCC_ParenthesizedExpression:
2125   case CodeCompletionContext::CCC_ObjCInterfaceName:
2126     break;
2127 
2128   case CodeCompletionContext::CCC_EnumTag:
2129   case CodeCompletionContext::CCC_UnionTag:
2130   case CodeCompletionContext::CCC_ClassOrStructTag:
2131     OnlyTagNames = true;
2132     break;
2133 
2134   case CodeCompletionContext::CCC_ObjCProtocolName:
2135   case CodeCompletionContext::CCC_MacroName:
2136   case CodeCompletionContext::CCC_MacroNameUse:
2137   case CodeCompletionContext::CCC_PreprocessorExpression:
2138   case CodeCompletionContext::CCC_PreprocessorDirective:
2139   case CodeCompletionContext::CCC_NaturalLanguage:
2140   case CodeCompletionContext::CCC_SelectorName:
2141   case CodeCompletionContext::CCC_TypeQualifiers:
2142   case CodeCompletionContext::CCC_Other:
2143   case CodeCompletionContext::CCC_OtherWithMacros:
2144   case CodeCompletionContext::CCC_ObjCInstanceMessage:
2145   case CodeCompletionContext::CCC_ObjCClassMessage:
2146   case CodeCompletionContext::CCC_ObjCCategoryName:
2147     // We're looking for nothing, or we're looking for names that cannot
2148     // be hidden.
2149     return;
2150   }
2151 
2152   typedef CodeCompletionResult Result;
2153   for (unsigned I = 0; I != NumResults; ++I) {
2154     if (Results[I].Kind != Result::RK_Declaration)
2155       continue;
2156 
2157     unsigned IDNS
2158       = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2159 
2160     bool Hiding = false;
2161     if (OnlyTagNames)
2162       Hiding = (IDNS & Decl::IDNS_Tag);
2163     else {
2164       unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
2165                              Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2166                              Decl::IDNS_NonMemberOperator);
2167       if (Ctx.getLangOpts().CPlusPlus)
2168         HiddenIDNS |= Decl::IDNS_Tag;
2169       Hiding = (IDNS & HiddenIDNS);
2170     }
2171 
2172     if (!Hiding)
2173       continue;
2174 
2175     DeclarationName Name = Results[I].Declaration->getDeclName();
2176     if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2177       HiddenNames.insert(Identifier->getName());
2178     else
2179       HiddenNames.insert(Name.getAsString());
2180   }
2181 }
2182 
2183 
2184 void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2185                                             CodeCompletionContext Context,
2186                                             CodeCompletionResult *Results,
2187                                             unsigned NumResults) {
2188   // Merge the results we were given with the results we cached.
2189   bool AddedResult = false;
2190   uint64_t InContexts =
2191       Context.getKind() == CodeCompletionContext::CCC_Recovery
2192         ? NormalContexts : (1LL << Context.getKind());
2193   // Contains the set of names that are hidden by "local" completion results.
2194   llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
2195   typedef CodeCompletionResult Result;
2196   SmallVector<Result, 8> AllResults;
2197   for (ASTUnit::cached_completion_iterator
2198             C = AST.cached_completion_begin(),
2199          CEnd = AST.cached_completion_end();
2200        C != CEnd; ++C) {
2201     // If the context we are in matches any of the contexts we are
2202     // interested in, we'll add this result.
2203     if ((C->ShowInContexts & InContexts) == 0)
2204       continue;
2205 
2206     // If we haven't added any results previously, do so now.
2207     if (!AddedResult) {
2208       CalculateHiddenNames(Context, Results, NumResults, S.Context,
2209                            HiddenNames);
2210       AllResults.insert(AllResults.end(), Results, Results + NumResults);
2211       AddedResult = true;
2212     }
2213 
2214     // Determine whether this global completion result is hidden by a local
2215     // completion result. If so, skip it.
2216     if (C->Kind != CXCursor_MacroDefinition &&
2217         HiddenNames.count(C->Completion->getTypedText()))
2218       continue;
2219 
2220     // Adjust priority based on similar type classes.
2221     unsigned Priority = C->Priority;
2222     CodeCompletionString *Completion = C->Completion;
2223     if (!Context.getPreferredType().isNull()) {
2224       if (C->Kind == CXCursor_MacroDefinition) {
2225         Priority = getMacroUsagePriority(C->Completion->getTypedText(),
2226                                          S.getLangOpts(),
2227                                Context.getPreferredType()->isAnyPointerType());
2228       } else if (C->Type) {
2229         CanQualType Expected
2230           = S.Context.getCanonicalType(
2231                                Context.getPreferredType().getUnqualifiedType());
2232         SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2233         if (ExpectedSTC == C->TypeClass) {
2234           // We know this type is similar; check for an exact match.
2235           llvm::StringMap<unsigned> &CachedCompletionTypes
2236             = AST.getCachedCompletionTypes();
2237           llvm::StringMap<unsigned>::iterator Pos
2238             = CachedCompletionTypes.find(QualType(Expected).getAsString());
2239           if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2240             Priority /= CCF_ExactTypeMatch;
2241           else
2242             Priority /= CCF_SimilarTypeMatch;
2243         }
2244       }
2245     }
2246 
2247     // Adjust the completion string, if required.
2248     if (C->Kind == CXCursor_MacroDefinition &&
2249         Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2250       // Create a new code-completion string that just contains the
2251       // macro name, without its arguments.
2252       CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2253                                     CCP_CodePattern, C->Availability);
2254       Builder.AddTypedTextChunk(C->Completion->getTypedText());
2255       Priority = CCP_CodePattern;
2256       Completion = Builder.TakeString();
2257     }
2258 
2259     AllResults.push_back(Result(Completion, Priority, C->Kind,
2260                                 C->Availability));
2261   }
2262 
2263   // If we did not add any cached completion results, just forward the
2264   // results we were given to the next consumer.
2265   if (!AddedResult) {
2266     Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2267     return;
2268   }
2269 
2270   Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2271                                   AllResults.size());
2272 }
2273 
2274 
2275 
2276 void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
2277                            ArrayRef<RemappedFile> RemappedFiles,
2278                            bool IncludeMacros,
2279                            bool IncludeCodePatterns,
2280                            bool IncludeBriefComments,
2281                            CodeCompleteConsumer &Consumer,
2282                            DiagnosticsEngine &Diag, LangOptions &LangOpts,
2283                            SourceManager &SourceMgr, FileManager &FileMgr,
2284                    SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2285              SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
2286   if (!Invocation)
2287     return;
2288 
2289   SimpleTimer CompletionTimer(WantTiming);
2290   CompletionTimer.setOutput("Code completion @ " + File + ":" +
2291                             Twine(Line) + ":" + Twine(Column));
2292 
2293   IntrusiveRefCntPtr<CompilerInvocation>
2294     CCInvocation(new CompilerInvocation(*Invocation));
2295 
2296   FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
2297   CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
2298   PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
2299 
2300   CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2301                                    CachedCompletionResults.empty();
2302   CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2303   CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2304   CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2305 
2306   assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2307 
2308   FrontendOpts.CodeCompletionAt.FileName = File;
2309   FrontendOpts.CodeCompletionAt.Line = Line;
2310   FrontendOpts.CodeCompletionAt.Column = Column;
2311 
2312   // Set the language options appropriately.
2313   LangOpts = *CCInvocation->getLangOpts();
2314 
2315   // Spell-checking and warnings are wasteful during code-completion.
2316   LangOpts.SpellChecking = false;
2317   CCInvocation->getDiagnosticOpts().IgnoreWarnings = true;
2318 
2319   std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
2320 
2321   // Recover resources if we crash before exiting this method.
2322   llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2323     CICleanup(Clang.get());
2324 
2325   Clang->setInvocation(&*CCInvocation);
2326   OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
2327 
2328   // Set up diagnostics, capturing any diagnostics produced.
2329   Clang->setDiagnostics(&Diag);
2330   CaptureDroppedDiagnostics Capture(true,
2331                                     Clang->getDiagnostics(),
2332                                     StoredDiagnostics);
2333   ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
2334 
2335   // Create the target instance.
2336   Clang->setTarget(TargetInfo::CreateTargetInfo(
2337       Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
2338   if (!Clang->hasTarget()) {
2339     Clang->setInvocation(nullptr);
2340     return;
2341   }
2342 
2343   // Inform the target of the language options.
2344   //
2345   // FIXME: We shouldn't need to do this, the target should be immutable once
2346   // created. This complexity should be lifted elsewhere.
2347   Clang->getTarget().adjust(Clang->getLangOpts());
2348 
2349   assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
2350          "Invocation must have exactly one source file!");
2351   assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
2352          "FIXME: AST inputs not yet supported here!");
2353   assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
2354          "IR inputs not support here!");
2355 
2356 
2357   // Use the source and file managers that we were given.
2358   Clang->setFileManager(&FileMgr);
2359   Clang->setSourceManager(&SourceMgr);
2360 
2361   // Remap files.
2362   PreprocessorOpts.clearRemappedFiles();
2363   PreprocessorOpts.RetainRemappedFileBuffers = true;
2364   for (const auto &RemappedFile : RemappedFiles) {
2365     PreprocessorOpts.addRemappedFile(RemappedFile.first, RemappedFile.second);
2366     OwnedBuffers.push_back(RemappedFile.second);
2367   }
2368 
2369   // Use the code completion consumer we were given, but adding any cached
2370   // code-completion results.
2371   AugmentedCodeCompleteConsumer *AugmentedConsumer
2372     = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
2373   Clang->setCodeCompletionConsumer(AugmentedConsumer);
2374 
2375   // If we have a precompiled preamble, try to use it. We only allow
2376   // the use of the precompiled preamble if we're if the completion
2377   // point is within the main file, after the end of the precompiled
2378   // preamble.
2379   std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
2380   if (!getPreambleFile(this).empty()) {
2381     std::string CompleteFilePath(File);
2382     llvm::sys::fs::UniqueID CompleteFileID;
2383 
2384     if (!llvm::sys::fs::getUniqueID(CompleteFilePath, CompleteFileID)) {
2385       std::string MainPath(OriginalSourceFile);
2386       llvm::sys::fs::UniqueID MainID;
2387       if (!llvm::sys::fs::getUniqueID(MainPath, MainID)) {
2388         if (CompleteFileID == MainID && Line > 1)
2389           OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(
2390               *CCInvocation, false, Line - 1);
2391       }
2392     }
2393   }
2394 
2395   // If the main file has been overridden due to the use of a preamble,
2396   // make that override happen and introduce the preamble.
2397   if (OverrideMainBuffer) {
2398     PreprocessorOpts.addRemappedFile(OriginalSourceFile,
2399                                      OverrideMainBuffer.get());
2400     PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2401     PreprocessorOpts.PrecompiledPreambleBytes.second
2402                                                     = PreambleEndsAtStartOfLine;
2403     PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
2404     PreprocessorOpts.DisablePCHValidation = true;
2405 
2406     OwnedBuffers.push_back(OverrideMainBuffer.release());
2407   } else {
2408     PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2409     PreprocessorOpts.PrecompiledPreambleBytes.second = false;
2410   }
2411 
2412   // Disable the preprocessing record if modules are not enabled.
2413   if (!Clang->getLangOpts().Modules)
2414     PreprocessorOpts.DetailedRecord = false;
2415 
2416   std::unique_ptr<SyntaxOnlyAction> Act;
2417   Act.reset(new SyntaxOnlyAction);
2418   if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
2419     Act->Execute();
2420     Act->EndSourceFile();
2421   }
2422 }
2423 
2424 bool ASTUnit::Save(StringRef File) {
2425   if (HadModuleLoaderFatalFailure)
2426     return true;
2427 
2428   // Write to a temporary file and later rename it to the actual file, to avoid
2429   // possible race conditions.
2430   SmallString<128> TempPath;
2431   TempPath = File;
2432   TempPath += "-%%%%%%%%";
2433   int fd;
2434   if (llvm::sys::fs::createUniqueFile(TempPath.str(), fd, TempPath))
2435     return true;
2436 
2437   // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2438   // unconditionally create a stat cache when we parse the file?
2439   llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
2440 
2441   serialize(Out);
2442   Out.close();
2443   if (Out.has_error()) {
2444     Out.clear_error();
2445     return true;
2446   }
2447 
2448   if (llvm::sys::fs::rename(TempPath.str(), File)) {
2449     llvm::sys::fs::remove(TempPath.str());
2450     return true;
2451   }
2452 
2453   return false;
2454 }
2455 
2456 static bool serializeUnit(ASTWriter &Writer,
2457                           SmallVectorImpl<char> &Buffer,
2458                           Sema &S,
2459                           bool hasErrors,
2460                           raw_ostream &OS) {
2461   Writer.WriteAST(S, std::string(), nullptr, "", hasErrors);
2462 
2463   // Write the generated bitstream to "Out".
2464   if (!Buffer.empty())
2465     OS.write(Buffer.data(), Buffer.size());
2466 
2467   return false;
2468 }
2469 
2470 bool ASTUnit::serialize(raw_ostream &OS) {
2471   bool hasErrors = getDiagnostics().hasErrorOccurred();
2472 
2473   if (WriterData)
2474     return serializeUnit(WriterData->Writer, WriterData->Buffer,
2475                          getSema(), hasErrors, OS);
2476 
2477   SmallString<128> Buffer;
2478   llvm::BitstreamWriter Stream(Buffer);
2479   ASTWriter Writer(Stream);
2480   return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
2481 }
2482 
2483 typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2484 
2485 void ASTUnit::TranslateStoredDiagnostics(
2486                           FileManager &FileMgr,
2487                           SourceManager &SrcMgr,
2488                           const SmallVectorImpl<StandaloneDiagnostic> &Diags,
2489                           SmallVectorImpl<StoredDiagnostic> &Out) {
2490   // Map the standalone diagnostic into the new source manager. We also need to
2491   // remap all the locations to the new view. This includes the diag location,
2492   // any associated source ranges, and the source ranges of associated fix-its.
2493   // FIXME: There should be a cleaner way to do this.
2494 
2495   SmallVector<StoredDiagnostic, 4> Result;
2496   Result.reserve(Diags.size());
2497   for (const StandaloneDiagnostic &SD : Diags) {
2498     // Rebuild the StoredDiagnostic.
2499     if (SD.Filename.empty())
2500       continue;
2501     const FileEntry *FE = FileMgr.getFile(SD.Filename);
2502     if (!FE)
2503       continue;
2504     FileID FID = SrcMgr.translateFile(FE);
2505     SourceLocation FileLoc = SrcMgr.getLocForStartOfFile(FID);
2506     if (FileLoc.isInvalid())
2507       continue;
2508     SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset);
2509     FullSourceLoc Loc(L, SrcMgr);
2510 
2511     SmallVector<CharSourceRange, 4> Ranges;
2512     Ranges.reserve(SD.Ranges.size());
2513     for (const auto &Range : SD.Ranges) {
2514       SourceLocation BL = FileLoc.getLocWithOffset(Range.first);
2515       SourceLocation EL = FileLoc.getLocWithOffset(Range.second);
2516       Ranges.push_back(CharSourceRange::getCharRange(BL, EL));
2517     }
2518 
2519     SmallVector<FixItHint, 2> FixIts;
2520     FixIts.reserve(SD.FixIts.size());
2521     for (const StandaloneFixIt &FixIt : SD.FixIts) {
2522       FixIts.push_back(FixItHint());
2523       FixItHint &FH = FixIts.back();
2524       FH.CodeToInsert = FixIt.CodeToInsert;
2525       SourceLocation BL = FileLoc.getLocWithOffset(FixIt.RemoveRange.first);
2526       SourceLocation EL = FileLoc.getLocWithOffset(FixIt.RemoveRange.second);
2527       FH.RemoveRange = CharSourceRange::getCharRange(BL, EL);
2528     }
2529 
2530     Result.push_back(StoredDiagnostic(SD.Level, SD.ID,
2531                                       SD.Message, Loc, Ranges, FixIts));
2532   }
2533   Result.swap(Out);
2534 }
2535 
2536 void ASTUnit::addFileLevelDecl(Decl *D) {
2537   assert(D);
2538 
2539   // We only care about local declarations.
2540   if (D->isFromASTFile())
2541     return;
2542 
2543   SourceManager &SM = *SourceMgr;
2544   SourceLocation Loc = D->getLocation();
2545   if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2546     return;
2547 
2548   // We only keep track of the file-level declarations of each file.
2549   if (!D->getLexicalDeclContext()->isFileContext())
2550     return;
2551 
2552   SourceLocation FileLoc = SM.getFileLoc(Loc);
2553   assert(SM.isLocalSourceLocation(FileLoc));
2554   FileID FID;
2555   unsigned Offset;
2556   std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
2557   if (FID.isInvalid())
2558     return;
2559 
2560   LocDeclsTy *&Decls = FileDecls[FID];
2561   if (!Decls)
2562     Decls = new LocDeclsTy();
2563 
2564   std::pair<unsigned, Decl *> LocDecl(Offset, D);
2565 
2566   if (Decls->empty() || Decls->back().first <= Offset) {
2567     Decls->push_back(LocDecl);
2568     return;
2569   }
2570 
2571   LocDeclsTy::iterator I = std::upper_bound(Decls->begin(), Decls->end(),
2572                                             LocDecl, llvm::less_first());
2573 
2574   Decls->insert(I, LocDecl);
2575 }
2576 
2577 void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2578                                   SmallVectorImpl<Decl *> &Decls) {
2579   if (File.isInvalid())
2580     return;
2581 
2582   if (SourceMgr->isLoadedFileID(File)) {
2583     assert(Ctx->getExternalSource() && "No external source!");
2584     return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2585                                                          Decls);
2586   }
2587 
2588   FileDeclsTy::iterator I = FileDecls.find(File);
2589   if (I == FileDecls.end())
2590     return;
2591 
2592   LocDeclsTy &LocDecls = *I->second;
2593   if (LocDecls.empty())
2594     return;
2595 
2596   LocDeclsTy::iterator BeginIt =
2597       std::lower_bound(LocDecls.begin(), LocDecls.end(),
2598                        std::make_pair(Offset, (Decl *)nullptr),
2599                        llvm::less_first());
2600   if (BeginIt != LocDecls.begin())
2601     --BeginIt;
2602 
2603   // If we are pointing at a top-level decl inside an objc container, we need
2604   // to backtrack until we find it otherwise we will fail to report that the
2605   // region overlaps with an objc container.
2606   while (BeginIt != LocDecls.begin() &&
2607          BeginIt->second->isTopLevelDeclInObjCContainer())
2608     --BeginIt;
2609 
2610   LocDeclsTy::iterator EndIt = std::upper_bound(
2611       LocDecls.begin(), LocDecls.end(),
2612       std::make_pair(Offset + Length, (Decl *)nullptr), llvm::less_first());
2613   if (EndIt != LocDecls.end())
2614     ++EndIt;
2615 
2616   for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2617     Decls.push_back(DIt->second);
2618 }
2619 
2620 SourceLocation ASTUnit::getLocation(const FileEntry *File,
2621                                     unsigned Line, unsigned Col) const {
2622   const SourceManager &SM = getSourceManager();
2623   SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
2624   return SM.getMacroArgExpandedLocation(Loc);
2625 }
2626 
2627 SourceLocation ASTUnit::getLocation(const FileEntry *File,
2628                                     unsigned Offset) const {
2629   const SourceManager &SM = getSourceManager();
2630   SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
2631   return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2632 }
2633 
2634 /// \brief If \arg Loc is a loaded location from the preamble, returns
2635 /// the corresponding local location of the main file, otherwise it returns
2636 /// \arg Loc.
2637 SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2638   FileID PreambleID;
2639   if (SourceMgr)
2640     PreambleID = SourceMgr->getPreambleFileID();
2641 
2642   if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2643     return Loc;
2644 
2645   unsigned Offs;
2646   if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2647     SourceLocation FileLoc
2648         = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2649     return FileLoc.getLocWithOffset(Offs);
2650   }
2651 
2652   return Loc;
2653 }
2654 
2655 /// \brief If \arg Loc is a local location of the main file but inside the
2656 /// preamble chunk, returns the corresponding loaded location from the
2657 /// preamble, otherwise it returns \arg Loc.
2658 SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2659   FileID PreambleID;
2660   if (SourceMgr)
2661     PreambleID = SourceMgr->getPreambleFileID();
2662 
2663   if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2664     return Loc;
2665 
2666   unsigned Offs;
2667   if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2668       Offs < Preamble.size()) {
2669     SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2670     return FileLoc.getLocWithOffset(Offs);
2671   }
2672 
2673   return Loc;
2674 }
2675 
2676 bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2677   FileID FID;
2678   if (SourceMgr)
2679     FID = SourceMgr->getPreambleFileID();
2680 
2681   if (Loc.isInvalid() || FID.isInvalid())
2682     return false;
2683 
2684   return SourceMgr->isInFileID(Loc, FID);
2685 }
2686 
2687 bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2688   FileID FID;
2689   if (SourceMgr)
2690     FID = SourceMgr->getMainFileID();
2691 
2692   if (Loc.isInvalid() || FID.isInvalid())
2693     return false;
2694 
2695   return SourceMgr->isInFileID(Loc, FID);
2696 }
2697 
2698 SourceLocation ASTUnit::getEndOfPreambleFileID() {
2699   FileID FID;
2700   if (SourceMgr)
2701     FID = SourceMgr->getPreambleFileID();
2702 
2703   if (FID.isInvalid())
2704     return SourceLocation();
2705 
2706   return SourceMgr->getLocForEndOfFile(FID);
2707 }
2708 
2709 SourceLocation ASTUnit::getStartOfMainFileID() {
2710   FileID FID;
2711   if (SourceMgr)
2712     FID = SourceMgr->getMainFileID();
2713 
2714   if (FID.isInvalid())
2715     return SourceLocation();
2716 
2717   return SourceMgr->getLocForStartOfFile(FID);
2718 }
2719 
2720 llvm::iterator_range<PreprocessingRecord::iterator>
2721 ASTUnit::getLocalPreprocessingEntities() const {
2722   if (isMainFileAST()) {
2723     serialization::ModuleFile &
2724       Mod = Reader->getModuleManager().getPrimaryModule();
2725     return Reader->getModulePreprocessedEntities(Mod);
2726   }
2727 
2728   if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
2729     return llvm::make_range(PPRec->local_begin(), PPRec->local_end());
2730 
2731   return llvm::make_range(PreprocessingRecord::iterator(),
2732                           PreprocessingRecord::iterator());
2733 }
2734 
2735 bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
2736   if (isMainFileAST()) {
2737     serialization::ModuleFile &
2738       Mod = Reader->getModuleManager().getPrimaryModule();
2739     for (const Decl *D : Reader->getModuleFileLevelDecls(Mod)) {
2740       if (!Fn(context, D))
2741         return false;
2742     }
2743 
2744     return true;
2745   }
2746 
2747   for (ASTUnit::top_level_iterator TL = top_level_begin(),
2748                                 TLEnd = top_level_end();
2749          TL != TLEnd; ++TL) {
2750     if (!Fn(context, *TL))
2751       return false;
2752   }
2753 
2754   return true;
2755 }
2756 
2757 namespace {
2758 struct PCHLocatorInfo {
2759   serialization::ModuleFile *Mod;
2760   PCHLocatorInfo() : Mod(nullptr) {}
2761 };
2762 }
2763 
2764 static bool PCHLocator(serialization::ModuleFile &M, void *UserData) {
2765   PCHLocatorInfo &Info = *static_cast<PCHLocatorInfo*>(UserData);
2766   switch (M.Kind) {
2767   case serialization::MK_ImplicitModule:
2768   case serialization::MK_ExplicitModule:
2769     return true; // skip dependencies.
2770   case serialization::MK_PCH:
2771     Info.Mod = &M;
2772     return true; // found it.
2773   case serialization::MK_Preamble:
2774     return false; // look in dependencies.
2775   case serialization::MK_MainFile:
2776     return false; // look in dependencies.
2777   }
2778 
2779   return true;
2780 }
2781 
2782 const FileEntry *ASTUnit::getPCHFile() {
2783   if (!Reader)
2784     return nullptr;
2785 
2786   PCHLocatorInfo Info;
2787   Reader->getModuleManager().visit(PCHLocator, &Info);
2788   if (Info.Mod)
2789     return Info.Mod->File;
2790 
2791   return nullptr;
2792 }
2793 
2794 bool ASTUnit::isModuleFile() {
2795   return isMainFileAST() && !ASTFileLangOpts.CurrentModule.empty();
2796 }
2797 
2798 void ASTUnit::PreambleData::countLines() const {
2799   NumLines = 0;
2800   if (empty())
2801     return;
2802 
2803   NumLines = std::count(Buffer.begin(), Buffer.end(), '\n');
2804 
2805   if (Buffer.back() != '\n')
2806     ++NumLines;
2807 }
2808 
2809 #ifndef NDEBUG
2810 ASTUnit::ConcurrencyState::ConcurrencyState() {
2811   Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2812 }
2813 
2814 ASTUnit::ConcurrencyState::~ConcurrencyState() {
2815   delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2816 }
2817 
2818 void ASTUnit::ConcurrencyState::start() {
2819   bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2820   assert(acquired && "Concurrent access to ASTUnit!");
2821 }
2822 
2823 void ASTUnit::ConcurrencyState::finish() {
2824   static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2825 }
2826 
2827 #else // NDEBUG
2828 
2829 ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex = 0; }
2830 ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2831 void ASTUnit::ConcurrencyState::start() {}
2832 void ASTUnit::ConcurrencyState::finish() {}
2833 
2834 #endif
2835