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