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