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   }
1895 
1896   SimpleTimer ParsingTimer(WantTiming);
1897   ParsingTimer.setOutput("Parsing " + getMainFileName());
1898 
1899   // Recover resources if we crash before exiting this method.
1900   llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1901     MemBufferCleanup(OverrideMainBuffer.get());
1902 
1903   return Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer));
1904 }
1905 
1906 std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation(
1907     std::shared_ptr<CompilerInvocation> CI,
1908     std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1909     IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FileManager *FileMgr,
1910     bool OnlyLocalDecls, bool CaptureDiagnostics,
1911     unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
1912     bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1913     bool UserFilesAreVolatile) {
1914   // Create the AST unit.
1915   std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
1916   ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1917   AST->Diagnostics = Diags;
1918   AST->OnlyLocalDecls = OnlyLocalDecls;
1919   AST->CaptureDiagnostics = CaptureDiagnostics;
1920   AST->TUKind = TUKind;
1921   AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1922   AST->IncludeBriefCommentsInCodeCompletion
1923     = IncludeBriefCommentsInCodeCompletion;
1924   AST->Invocation = std::move(CI);
1925   AST->FileSystemOpts = FileMgr->getFileSystemOpts();
1926   AST->FileMgr = FileMgr;
1927   AST->UserFilesAreVolatile = UserFilesAreVolatile;
1928 
1929   // Recover resources if we crash before exiting this method.
1930   llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1931     ASTUnitCleanup(AST.get());
1932   llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1933     llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
1934     DiagCleanup(Diags.get());
1935 
1936   if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
1937                                       PrecompilePreambleAfterNParses))
1938     return nullptr;
1939   return AST;
1940 }
1941 
1942 ASTUnit *ASTUnit::LoadFromCommandLine(
1943     const char **ArgBegin, const char **ArgEnd,
1944     std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1945     IntrusiveRefCntPtr<DiagnosticsEngine> Diags, StringRef ResourceFilesPath,
1946     bool OnlyLocalDecls, bool CaptureDiagnostics,
1947     ArrayRef<RemappedFile> RemappedFiles, bool RemappedFilesKeepOriginalName,
1948     unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
1949     bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1950     bool AllowPCHWithCompilerErrors, bool SkipFunctionBodies,
1951     bool UserFilesAreVolatile, bool ForSerialization,
1952     llvm::Optional<StringRef> ModuleFormat, std::unique_ptr<ASTUnit> *ErrAST) {
1953   assert(Diags.get() && "no DiagnosticsEngine was provided");
1954 
1955   SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
1956 
1957   std::shared_ptr<CompilerInvocation> CI;
1958 
1959   {
1960 
1961     CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
1962                                       StoredDiagnostics);
1963 
1964     CI = clang::createInvocationFromCommandLine(
1965         llvm::makeArrayRef(ArgBegin, ArgEnd), Diags);
1966     if (!CI)
1967       return nullptr;
1968   }
1969 
1970   // Override any files that need remapping
1971   for (const auto &RemappedFile : RemappedFiles) {
1972     CI->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
1973                                               RemappedFile.second);
1974   }
1975   PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
1976   PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
1977   PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
1978 
1979   // Override the resources path.
1980   CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1981 
1982   CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
1983 
1984   if (ModuleFormat)
1985     CI->getHeaderSearchOpts().ModuleFormat = ModuleFormat.getValue();
1986 
1987   // Create the AST unit.
1988   std::unique_ptr<ASTUnit> AST;
1989   AST.reset(new ASTUnit(false));
1990   ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1991   AST->Diagnostics = Diags;
1992   AST->FileSystemOpts = CI->getFileSystemOpts();
1993   IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1994       createVFSFromCompilerInvocation(*CI, *Diags);
1995   if (!VFS)
1996     return nullptr;
1997   AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
1998   AST->OnlyLocalDecls = OnlyLocalDecls;
1999   AST->CaptureDiagnostics = CaptureDiagnostics;
2000   AST->TUKind = TUKind;
2001   AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
2002   AST->IncludeBriefCommentsInCodeCompletion
2003     = IncludeBriefCommentsInCodeCompletion;
2004   AST->UserFilesAreVolatile = UserFilesAreVolatile;
2005   AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
2006   AST->StoredDiagnostics.swap(StoredDiagnostics);
2007   AST->Invocation = CI;
2008   if (ForSerialization)
2009     AST->WriterData.reset(new ASTWriterData());
2010   // Zero out now to ease cleanup during crash recovery.
2011   CI = nullptr;
2012   Diags = nullptr;
2013 
2014   // Recover resources if we crash before exiting this method.
2015   llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
2016     ASTUnitCleanup(AST.get());
2017 
2018   if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
2019                                       PrecompilePreambleAfterNParses)) {
2020     // Some error occurred, if caller wants to examine diagnostics, pass it the
2021     // ASTUnit.
2022     if (ErrAST) {
2023       AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
2024       ErrAST->swap(AST);
2025     }
2026     return nullptr;
2027   }
2028 
2029   return AST.release();
2030 }
2031 
2032 bool ASTUnit::Reparse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
2033                       ArrayRef<RemappedFile> RemappedFiles) {
2034   if (!Invocation)
2035     return true;
2036 
2037   clearFileLevelDecls();
2038 
2039   SimpleTimer ParsingTimer(WantTiming);
2040   ParsingTimer.setOutput("Reparsing " + getMainFileName());
2041 
2042   // Remap files.
2043   PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
2044   for (const auto &RB : PPOpts.RemappedFileBuffers)
2045     delete RB.second;
2046 
2047   Invocation->getPreprocessorOpts().clearRemappedFiles();
2048   for (const auto &RemappedFile : RemappedFiles) {
2049     Invocation->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
2050                                                       RemappedFile.second);
2051   }
2052 
2053   // If we have a preamble file lying around, or if we might try to
2054   // build a precompiled preamble, do so now.
2055   std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
2056   if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
2057     OverrideMainBuffer =
2058         getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation);
2059 
2060   // Clear out the diagnostics state.
2061   FileMgr.reset();
2062   getDiagnostics().Reset();
2063   ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
2064   if (OverrideMainBuffer)
2065     getDiagnostics().setNumWarnings(NumWarningsInPreamble);
2066 
2067   // Parse the sources
2068   bool Result =
2069       Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer));
2070 
2071   // If we're caching global code-completion results, and the top-level
2072   // declarations have changed, clear out the code-completion cache.
2073   if (!Result && ShouldCacheCodeCompletionResults &&
2074       CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2075     CacheCodeCompletionResults();
2076 
2077   // We now need to clear out the completion info related to this translation
2078   // unit; it'll be recreated if necessary.
2079   CCTUInfo.reset();
2080 
2081   return Result;
2082 }
2083 
2084 //----------------------------------------------------------------------------//
2085 // Code completion
2086 //----------------------------------------------------------------------------//
2087 
2088 namespace {
2089   /// \brief Code completion consumer that combines the cached code-completion
2090   /// results from an ASTUnit with the code-completion results provided to it,
2091   /// then passes the result on to
2092   class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
2093     uint64_t NormalContexts;
2094     ASTUnit &AST;
2095     CodeCompleteConsumer &Next;
2096 
2097   public:
2098     AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
2099                                   const CodeCompleteOptions &CodeCompleteOpts)
2100       : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
2101         AST(AST), Next(Next)
2102     {
2103       // Compute the set of contexts in which we will look when we don't have
2104       // any information about the specific context.
2105       NormalContexts
2106         = (1LL << CodeCompletionContext::CCC_TopLevel)
2107         | (1LL << CodeCompletionContext::CCC_ObjCInterface)
2108         | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
2109         | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
2110         | (1LL << CodeCompletionContext::CCC_Statement)
2111         | (1LL << CodeCompletionContext::CCC_Expression)
2112         | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
2113         | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
2114         | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
2115         | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
2116         | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
2117         | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
2118         | (1LL << CodeCompletionContext::CCC_Recovery);
2119 
2120       if (AST.getASTContext().getLangOpts().CPlusPlus)
2121         NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
2122                        |  (1LL << CodeCompletionContext::CCC_UnionTag)
2123                        |  (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
2124     }
2125 
2126     void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
2127                                     CodeCompletionResult *Results,
2128                                     unsigned NumResults) override;
2129 
2130     void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2131                                    OverloadCandidate *Candidates,
2132                                    unsigned NumCandidates) override {
2133       Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2134     }
2135 
2136     CodeCompletionAllocator &getAllocator() override {
2137       return Next.getAllocator();
2138     }
2139 
2140     CodeCompletionTUInfo &getCodeCompletionTUInfo() override {
2141       return Next.getCodeCompletionTUInfo();
2142     }
2143   };
2144 } // anonymous namespace
2145 
2146 /// \brief Helper function that computes which global names are hidden by the
2147 /// local code-completion results.
2148 static void CalculateHiddenNames(const CodeCompletionContext &Context,
2149                                  CodeCompletionResult *Results,
2150                                  unsigned NumResults,
2151                                  ASTContext &Ctx,
2152                           llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
2153   bool OnlyTagNames = false;
2154   switch (Context.getKind()) {
2155   case CodeCompletionContext::CCC_Recovery:
2156   case CodeCompletionContext::CCC_TopLevel:
2157   case CodeCompletionContext::CCC_ObjCInterface:
2158   case CodeCompletionContext::CCC_ObjCImplementation:
2159   case CodeCompletionContext::CCC_ObjCIvarList:
2160   case CodeCompletionContext::CCC_ClassStructUnion:
2161   case CodeCompletionContext::CCC_Statement:
2162   case CodeCompletionContext::CCC_Expression:
2163   case CodeCompletionContext::CCC_ObjCMessageReceiver:
2164   case CodeCompletionContext::CCC_DotMemberAccess:
2165   case CodeCompletionContext::CCC_ArrowMemberAccess:
2166   case CodeCompletionContext::CCC_ObjCPropertyAccess:
2167   case CodeCompletionContext::CCC_Namespace:
2168   case CodeCompletionContext::CCC_Type:
2169   case CodeCompletionContext::CCC_Name:
2170   case CodeCompletionContext::CCC_PotentiallyQualifiedName:
2171   case CodeCompletionContext::CCC_ParenthesizedExpression:
2172   case CodeCompletionContext::CCC_ObjCInterfaceName:
2173     break;
2174 
2175   case CodeCompletionContext::CCC_EnumTag:
2176   case CodeCompletionContext::CCC_UnionTag:
2177   case CodeCompletionContext::CCC_ClassOrStructTag:
2178     OnlyTagNames = true;
2179     break;
2180 
2181   case CodeCompletionContext::CCC_ObjCProtocolName:
2182   case CodeCompletionContext::CCC_MacroName:
2183   case CodeCompletionContext::CCC_MacroNameUse:
2184   case CodeCompletionContext::CCC_PreprocessorExpression:
2185   case CodeCompletionContext::CCC_PreprocessorDirective:
2186   case CodeCompletionContext::CCC_NaturalLanguage:
2187   case CodeCompletionContext::CCC_SelectorName:
2188   case CodeCompletionContext::CCC_TypeQualifiers:
2189   case CodeCompletionContext::CCC_Other:
2190   case CodeCompletionContext::CCC_OtherWithMacros:
2191   case CodeCompletionContext::CCC_ObjCInstanceMessage:
2192   case CodeCompletionContext::CCC_ObjCClassMessage:
2193   case CodeCompletionContext::CCC_ObjCCategoryName:
2194     // We're looking for nothing, or we're looking for names that cannot
2195     // be hidden.
2196     return;
2197   }
2198 
2199   typedef CodeCompletionResult Result;
2200   for (unsigned I = 0; I != NumResults; ++I) {
2201     if (Results[I].Kind != Result::RK_Declaration)
2202       continue;
2203 
2204     unsigned IDNS
2205       = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2206 
2207     bool Hiding = false;
2208     if (OnlyTagNames)
2209       Hiding = (IDNS & Decl::IDNS_Tag);
2210     else {
2211       unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
2212                              Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2213                              Decl::IDNS_NonMemberOperator);
2214       if (Ctx.getLangOpts().CPlusPlus)
2215         HiddenIDNS |= Decl::IDNS_Tag;
2216       Hiding = (IDNS & HiddenIDNS);
2217     }
2218 
2219     if (!Hiding)
2220       continue;
2221 
2222     DeclarationName Name = Results[I].Declaration->getDeclName();
2223     if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2224       HiddenNames.insert(Identifier->getName());
2225     else
2226       HiddenNames.insert(Name.getAsString());
2227   }
2228 }
2229 
2230 void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2231                                             CodeCompletionContext Context,
2232                                             CodeCompletionResult *Results,
2233                                             unsigned NumResults) {
2234   // Merge the results we were given with the results we cached.
2235   bool AddedResult = false;
2236   uint64_t InContexts =
2237       Context.getKind() == CodeCompletionContext::CCC_Recovery
2238         ? NormalContexts : (1LL << Context.getKind());
2239   // Contains the set of names that are hidden by "local" completion results.
2240   llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
2241   typedef CodeCompletionResult Result;
2242   SmallVector<Result, 8> AllResults;
2243   for (ASTUnit::cached_completion_iterator
2244             C = AST.cached_completion_begin(),
2245          CEnd = AST.cached_completion_end();
2246        C != CEnd; ++C) {
2247     // If the context we are in matches any of the contexts we are
2248     // interested in, we'll add this result.
2249     if ((C->ShowInContexts & InContexts) == 0)
2250       continue;
2251 
2252     // If we haven't added any results previously, do so now.
2253     if (!AddedResult) {
2254       CalculateHiddenNames(Context, Results, NumResults, S.Context,
2255                            HiddenNames);
2256       AllResults.insert(AllResults.end(), Results, Results + NumResults);
2257       AddedResult = true;
2258     }
2259 
2260     // Determine whether this global completion result is hidden by a local
2261     // completion result. If so, skip it.
2262     if (C->Kind != CXCursor_MacroDefinition &&
2263         HiddenNames.count(C->Completion->getTypedText()))
2264       continue;
2265 
2266     // Adjust priority based on similar type classes.
2267     unsigned Priority = C->Priority;
2268     CodeCompletionString *Completion = C->Completion;
2269     if (!Context.getPreferredType().isNull()) {
2270       if (C->Kind == CXCursor_MacroDefinition) {
2271         Priority = getMacroUsagePriority(C->Completion->getTypedText(),
2272                                          S.getLangOpts(),
2273                                Context.getPreferredType()->isAnyPointerType());
2274       } else if (C->Type) {
2275         CanQualType Expected
2276           = S.Context.getCanonicalType(
2277                                Context.getPreferredType().getUnqualifiedType());
2278         SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2279         if (ExpectedSTC == C->TypeClass) {
2280           // We know this type is similar; check for an exact match.
2281           llvm::StringMap<unsigned> &CachedCompletionTypes
2282             = AST.getCachedCompletionTypes();
2283           llvm::StringMap<unsigned>::iterator Pos
2284             = CachedCompletionTypes.find(QualType(Expected).getAsString());
2285           if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2286             Priority /= CCF_ExactTypeMatch;
2287           else
2288             Priority /= CCF_SimilarTypeMatch;
2289         }
2290       }
2291     }
2292 
2293     // Adjust the completion string, if required.
2294     if (C->Kind == CXCursor_MacroDefinition &&
2295         Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2296       // Create a new code-completion string that just contains the
2297       // macro name, without its arguments.
2298       CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2299                                     CCP_CodePattern, C->Availability);
2300       Builder.AddTypedTextChunk(C->Completion->getTypedText());
2301       Priority = CCP_CodePattern;
2302       Completion = Builder.TakeString();
2303     }
2304 
2305     AllResults.push_back(Result(Completion, Priority, C->Kind,
2306                                 C->Availability));
2307   }
2308 
2309   // If we did not add any cached completion results, just forward the
2310   // results we were given to the next consumer.
2311   if (!AddedResult) {
2312     Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2313     return;
2314   }
2315 
2316   Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2317                                   AllResults.size());
2318 }
2319 
2320 void ASTUnit::CodeComplete(
2321     StringRef File, unsigned Line, unsigned Column,
2322     ArrayRef<RemappedFile> RemappedFiles, bool IncludeMacros,
2323     bool IncludeCodePatterns, bool IncludeBriefComments,
2324     CodeCompleteConsumer &Consumer,
2325     std::shared_ptr<PCHContainerOperations> PCHContainerOps,
2326     DiagnosticsEngine &Diag, LangOptions &LangOpts, SourceManager &SourceMgr,
2327     FileManager &FileMgr, SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2328     SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
2329   if (!Invocation)
2330     return;
2331 
2332   SimpleTimer CompletionTimer(WantTiming);
2333   CompletionTimer.setOutput("Code completion @ " + File + ":" +
2334                             Twine(Line) + ":" + Twine(Column));
2335 
2336   auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation);
2337 
2338   FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
2339   CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
2340   PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
2341 
2342   CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2343                                    CachedCompletionResults.empty();
2344   CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2345   CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2346   CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2347 
2348   assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2349 
2350   FrontendOpts.CodeCompletionAt.FileName = File;
2351   FrontendOpts.CodeCompletionAt.Line = Line;
2352   FrontendOpts.CodeCompletionAt.Column = Column;
2353 
2354   // Set the language options appropriately.
2355   LangOpts = *CCInvocation->getLangOpts();
2356 
2357   // Spell-checking and warnings are wasteful during code-completion.
2358   LangOpts.SpellChecking = false;
2359   CCInvocation->getDiagnosticOpts().IgnoreWarnings = true;
2360 
2361   std::unique_ptr<CompilerInstance> Clang(
2362       new CompilerInstance(PCHContainerOps));
2363 
2364   // Recover resources if we crash before exiting this method.
2365   llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2366     CICleanup(Clang.get());
2367 
2368   auto &Inv = *CCInvocation;
2369   Clang->setInvocation(std::move(CCInvocation));
2370   OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
2371 
2372   // Set up diagnostics, capturing any diagnostics produced.
2373   Clang->setDiagnostics(&Diag);
2374   CaptureDroppedDiagnostics Capture(true,
2375                                     Clang->getDiagnostics(),
2376                                     StoredDiagnostics);
2377   ProcessWarningOptions(Diag, Inv.getDiagnosticOpts());
2378 
2379   // Create the target instance.
2380   Clang->setTarget(TargetInfo::CreateTargetInfo(
2381       Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
2382   if (!Clang->hasTarget()) {
2383     Clang->setInvocation(nullptr);
2384     return;
2385   }
2386 
2387   // Inform the target of the language options.
2388   //
2389   // FIXME: We shouldn't need to do this, the target should be immutable once
2390   // created. This complexity should be lifted elsewhere.
2391   Clang->getTarget().adjust(Clang->getLangOpts());
2392 
2393   assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
2394          "Invocation must have exactly one source file!");
2395   assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
2396          "FIXME: AST inputs not yet supported here!");
2397   assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
2398          "IR inputs not support here!");
2399 
2400 
2401   // Use the source and file managers that we were given.
2402   Clang->setFileManager(&FileMgr);
2403   Clang->setSourceManager(&SourceMgr);
2404 
2405   // Remap files.
2406   PreprocessorOpts.clearRemappedFiles();
2407   PreprocessorOpts.RetainRemappedFileBuffers = true;
2408   for (const auto &RemappedFile : RemappedFiles) {
2409     PreprocessorOpts.addRemappedFile(RemappedFile.first, RemappedFile.second);
2410     OwnedBuffers.push_back(RemappedFile.second);
2411   }
2412 
2413   // Use the code completion consumer we were given, but adding any cached
2414   // code-completion results.
2415   AugmentedCodeCompleteConsumer *AugmentedConsumer
2416     = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
2417   Clang->setCodeCompletionConsumer(AugmentedConsumer);
2418 
2419   // If we have a precompiled preamble, try to use it. We only allow
2420   // the use of the precompiled preamble if we're if the completion
2421   // point is within the main file, after the end of the precompiled
2422   // preamble.
2423   std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
2424   if (!getPreambleFile(this).empty()) {
2425     std::string CompleteFilePath(File);
2426     llvm::sys::fs::UniqueID CompleteFileID;
2427 
2428     if (!llvm::sys::fs::getUniqueID(CompleteFilePath, CompleteFileID)) {
2429       std::string MainPath(OriginalSourceFile);
2430       llvm::sys::fs::UniqueID MainID;
2431       if (!llvm::sys::fs::getUniqueID(MainPath, MainID)) {
2432         if (CompleteFileID == MainID && Line > 1)
2433           OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(
2434               PCHContainerOps, Inv, false, Line - 1);
2435       }
2436     }
2437   }
2438 
2439   // If the main file has been overridden due to the use of a preamble,
2440   // make that override happen and introduce the preamble.
2441   if (OverrideMainBuffer) {
2442     PreprocessorOpts.addRemappedFile(OriginalSourceFile,
2443                                      OverrideMainBuffer.get());
2444     PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2445     PreprocessorOpts.PrecompiledPreambleBytes.second
2446                                                     = PreambleEndsAtStartOfLine;
2447     PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
2448     PreprocessorOpts.DisablePCHValidation = true;
2449 
2450     OwnedBuffers.push_back(OverrideMainBuffer.release());
2451   } else {
2452     PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2453     PreprocessorOpts.PrecompiledPreambleBytes.second = false;
2454   }
2455 
2456   // Disable the preprocessing record if modules are not enabled.
2457   if (!Clang->getLangOpts().Modules)
2458     PreprocessorOpts.DetailedRecord = false;
2459 
2460   std::unique_ptr<SyntaxOnlyAction> Act;
2461   Act.reset(new SyntaxOnlyAction);
2462   if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
2463     Act->Execute();
2464     Act->EndSourceFile();
2465   }
2466 }
2467 
2468 bool ASTUnit::Save(StringRef File) {
2469   if (HadModuleLoaderFatalFailure)
2470     return true;
2471 
2472   // Write to a temporary file and later rename it to the actual file, to avoid
2473   // possible race conditions.
2474   SmallString<128> TempPath;
2475   TempPath = File;
2476   TempPath += "-%%%%%%%%";
2477   int fd;
2478   if (llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath))
2479     return true;
2480 
2481   // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2482   // unconditionally create a stat cache when we parse the file?
2483   llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
2484 
2485   serialize(Out);
2486   Out.close();
2487   if (Out.has_error()) {
2488     Out.clear_error();
2489     return true;
2490   }
2491 
2492   if (llvm::sys::fs::rename(TempPath, File)) {
2493     llvm::sys::fs::remove(TempPath);
2494     return true;
2495   }
2496 
2497   return false;
2498 }
2499 
2500 static bool serializeUnit(ASTWriter &Writer,
2501                           SmallVectorImpl<char> &Buffer,
2502                           Sema &S,
2503                           bool hasErrors,
2504                           raw_ostream &OS) {
2505   Writer.WriteAST(S, std::string(), nullptr, "", hasErrors);
2506 
2507   // Write the generated bitstream to "Out".
2508   if (!Buffer.empty())
2509     OS.write(Buffer.data(), Buffer.size());
2510 
2511   return false;
2512 }
2513 
2514 bool ASTUnit::serialize(raw_ostream &OS) {
2515   // For serialization we are lenient if the errors were only warn-as-error kind.
2516   bool hasErrors = getDiagnostics().hasUncompilableErrorOccurred();
2517 
2518   if (WriterData)
2519     return serializeUnit(WriterData->Writer, WriterData->Buffer,
2520                          getSema(), hasErrors, OS);
2521 
2522   SmallString<128> Buffer;
2523   llvm::BitstreamWriter Stream(Buffer);
2524   ASTWriter Writer(Stream, { });
2525   return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
2526 }
2527 
2528 typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2529 
2530 void ASTUnit::TranslateStoredDiagnostics(
2531                           FileManager &FileMgr,
2532                           SourceManager &SrcMgr,
2533                           const SmallVectorImpl<StandaloneDiagnostic> &Diags,
2534                           SmallVectorImpl<StoredDiagnostic> &Out) {
2535   // Map the standalone diagnostic into the new source manager. We also need to
2536   // remap all the locations to the new view. This includes the diag location,
2537   // any associated source ranges, and the source ranges of associated fix-its.
2538   // FIXME: There should be a cleaner way to do this.
2539 
2540   SmallVector<StoredDiagnostic, 4> Result;
2541   Result.reserve(Diags.size());
2542   for (const StandaloneDiagnostic &SD : Diags) {
2543     // Rebuild the StoredDiagnostic.
2544     if (SD.Filename.empty())
2545       continue;
2546     const FileEntry *FE = FileMgr.getFile(SD.Filename);
2547     if (!FE)
2548       continue;
2549     FileID FID = SrcMgr.translateFile(FE);
2550     SourceLocation FileLoc = SrcMgr.getLocForStartOfFile(FID);
2551     if (FileLoc.isInvalid())
2552       continue;
2553     SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset);
2554     FullSourceLoc Loc(L, SrcMgr);
2555 
2556     SmallVector<CharSourceRange, 4> Ranges;
2557     Ranges.reserve(SD.Ranges.size());
2558     for (const auto &Range : SD.Ranges) {
2559       SourceLocation BL = FileLoc.getLocWithOffset(Range.first);
2560       SourceLocation EL = FileLoc.getLocWithOffset(Range.second);
2561       Ranges.push_back(CharSourceRange::getCharRange(BL, EL));
2562     }
2563 
2564     SmallVector<FixItHint, 2> FixIts;
2565     FixIts.reserve(SD.FixIts.size());
2566     for (const StandaloneFixIt &FixIt : SD.FixIts) {
2567       FixIts.push_back(FixItHint());
2568       FixItHint &FH = FixIts.back();
2569       FH.CodeToInsert = FixIt.CodeToInsert;
2570       SourceLocation BL = FileLoc.getLocWithOffset(FixIt.RemoveRange.first);
2571       SourceLocation EL = FileLoc.getLocWithOffset(FixIt.RemoveRange.second);
2572       FH.RemoveRange = CharSourceRange::getCharRange(BL, EL);
2573     }
2574 
2575     Result.push_back(StoredDiagnostic(SD.Level, SD.ID,
2576                                       SD.Message, Loc, Ranges, FixIts));
2577   }
2578   Result.swap(Out);
2579 }
2580 
2581 void ASTUnit::addFileLevelDecl(Decl *D) {
2582   assert(D);
2583 
2584   // We only care about local declarations.
2585   if (D->isFromASTFile())
2586     return;
2587 
2588   SourceManager &SM = *SourceMgr;
2589   SourceLocation Loc = D->getLocation();
2590   if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2591     return;
2592 
2593   // We only keep track of the file-level declarations of each file.
2594   if (!D->getLexicalDeclContext()->isFileContext())
2595     return;
2596 
2597   SourceLocation FileLoc = SM.getFileLoc(Loc);
2598   assert(SM.isLocalSourceLocation(FileLoc));
2599   FileID FID;
2600   unsigned Offset;
2601   std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
2602   if (FID.isInvalid())
2603     return;
2604 
2605   LocDeclsTy *&Decls = FileDecls[FID];
2606   if (!Decls)
2607     Decls = new LocDeclsTy();
2608 
2609   std::pair<unsigned, Decl *> LocDecl(Offset, D);
2610 
2611   if (Decls->empty() || Decls->back().first <= Offset) {
2612     Decls->push_back(LocDecl);
2613     return;
2614   }
2615 
2616   LocDeclsTy::iterator I = std::upper_bound(Decls->begin(), Decls->end(),
2617                                             LocDecl, llvm::less_first());
2618 
2619   Decls->insert(I, LocDecl);
2620 }
2621 
2622 void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2623                                   SmallVectorImpl<Decl *> &Decls) {
2624   if (File.isInvalid())
2625     return;
2626 
2627   if (SourceMgr->isLoadedFileID(File)) {
2628     assert(Ctx->getExternalSource() && "No external source!");
2629     return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2630                                                          Decls);
2631   }
2632 
2633   FileDeclsTy::iterator I = FileDecls.find(File);
2634   if (I == FileDecls.end())
2635     return;
2636 
2637   LocDeclsTy &LocDecls = *I->second;
2638   if (LocDecls.empty())
2639     return;
2640 
2641   LocDeclsTy::iterator BeginIt =
2642       std::lower_bound(LocDecls.begin(), LocDecls.end(),
2643                        std::make_pair(Offset, (Decl *)nullptr),
2644                        llvm::less_first());
2645   if (BeginIt != LocDecls.begin())
2646     --BeginIt;
2647 
2648   // If we are pointing at a top-level decl inside an objc container, we need
2649   // to backtrack until we find it otherwise we will fail to report that the
2650   // region overlaps with an objc container.
2651   while (BeginIt != LocDecls.begin() &&
2652          BeginIt->second->isTopLevelDeclInObjCContainer())
2653     --BeginIt;
2654 
2655   LocDeclsTy::iterator EndIt = std::upper_bound(
2656       LocDecls.begin(), LocDecls.end(),
2657       std::make_pair(Offset + Length, (Decl *)nullptr), llvm::less_first());
2658   if (EndIt != LocDecls.end())
2659     ++EndIt;
2660 
2661   for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2662     Decls.push_back(DIt->second);
2663 }
2664 
2665 SourceLocation ASTUnit::getLocation(const FileEntry *File,
2666                                     unsigned Line, unsigned Col) const {
2667   const SourceManager &SM = getSourceManager();
2668   SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
2669   return SM.getMacroArgExpandedLocation(Loc);
2670 }
2671 
2672 SourceLocation ASTUnit::getLocation(const FileEntry *File,
2673                                     unsigned Offset) const {
2674   const SourceManager &SM = getSourceManager();
2675   SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
2676   return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2677 }
2678 
2679 /// \brief If \arg Loc is a loaded location from the preamble, returns
2680 /// the corresponding local location of the main file, otherwise it returns
2681 /// \arg Loc.
2682 SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2683   FileID PreambleID;
2684   if (SourceMgr)
2685     PreambleID = SourceMgr->getPreambleFileID();
2686 
2687   if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2688     return Loc;
2689 
2690   unsigned Offs;
2691   if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2692     SourceLocation FileLoc
2693         = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2694     return FileLoc.getLocWithOffset(Offs);
2695   }
2696 
2697   return Loc;
2698 }
2699 
2700 /// \brief If \arg Loc is a local location of the main file but inside the
2701 /// preamble chunk, returns the corresponding loaded location from the
2702 /// preamble, otherwise it returns \arg Loc.
2703 SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2704   FileID PreambleID;
2705   if (SourceMgr)
2706     PreambleID = SourceMgr->getPreambleFileID();
2707 
2708   if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2709     return Loc;
2710 
2711   unsigned Offs;
2712   if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2713       Offs < Preamble.size()) {
2714     SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2715     return FileLoc.getLocWithOffset(Offs);
2716   }
2717 
2718   return Loc;
2719 }
2720 
2721 bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2722   FileID FID;
2723   if (SourceMgr)
2724     FID = SourceMgr->getPreambleFileID();
2725 
2726   if (Loc.isInvalid() || FID.isInvalid())
2727     return false;
2728 
2729   return SourceMgr->isInFileID(Loc, FID);
2730 }
2731 
2732 bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2733   FileID FID;
2734   if (SourceMgr)
2735     FID = SourceMgr->getMainFileID();
2736 
2737   if (Loc.isInvalid() || FID.isInvalid())
2738     return false;
2739 
2740   return SourceMgr->isInFileID(Loc, FID);
2741 }
2742 
2743 SourceLocation ASTUnit::getEndOfPreambleFileID() {
2744   FileID FID;
2745   if (SourceMgr)
2746     FID = SourceMgr->getPreambleFileID();
2747 
2748   if (FID.isInvalid())
2749     return SourceLocation();
2750 
2751   return SourceMgr->getLocForEndOfFile(FID);
2752 }
2753 
2754 SourceLocation ASTUnit::getStartOfMainFileID() {
2755   FileID FID;
2756   if (SourceMgr)
2757     FID = SourceMgr->getMainFileID();
2758 
2759   if (FID.isInvalid())
2760     return SourceLocation();
2761 
2762   return SourceMgr->getLocForStartOfFile(FID);
2763 }
2764 
2765 llvm::iterator_range<PreprocessingRecord::iterator>
2766 ASTUnit::getLocalPreprocessingEntities() const {
2767   if (isMainFileAST()) {
2768     serialization::ModuleFile &
2769       Mod = Reader->getModuleManager().getPrimaryModule();
2770     return Reader->getModulePreprocessedEntities(Mod);
2771   }
2772 
2773   if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
2774     return llvm::make_range(PPRec->local_begin(), PPRec->local_end());
2775 
2776   return llvm::make_range(PreprocessingRecord::iterator(),
2777                           PreprocessingRecord::iterator());
2778 }
2779 
2780 bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
2781   if (isMainFileAST()) {
2782     serialization::ModuleFile &
2783       Mod = Reader->getModuleManager().getPrimaryModule();
2784     for (const Decl *D : Reader->getModuleFileLevelDecls(Mod)) {
2785       if (!Fn(context, D))
2786         return false;
2787     }
2788 
2789     return true;
2790   }
2791 
2792   for (ASTUnit::top_level_iterator TL = top_level_begin(),
2793                                 TLEnd = top_level_end();
2794          TL != TLEnd; ++TL) {
2795     if (!Fn(context, *TL))
2796       return false;
2797   }
2798 
2799   return true;
2800 }
2801 
2802 const FileEntry *ASTUnit::getPCHFile() {
2803   if (!Reader)
2804     return nullptr;
2805 
2806   serialization::ModuleFile *Mod = nullptr;
2807   Reader->getModuleManager().visit([&Mod](serialization::ModuleFile &M) {
2808     switch (M.Kind) {
2809     case serialization::MK_ImplicitModule:
2810     case serialization::MK_ExplicitModule:
2811     case serialization::MK_PrebuiltModule:
2812       return true; // skip dependencies.
2813     case serialization::MK_PCH:
2814       Mod = &M;
2815       return true; // found it.
2816     case serialization::MK_Preamble:
2817       return false; // look in dependencies.
2818     case serialization::MK_MainFile:
2819       return false; // look in dependencies.
2820     }
2821 
2822     return true;
2823   });
2824   if (Mod)
2825     return Mod->File;
2826 
2827   return nullptr;
2828 }
2829 
2830 bool ASTUnit::isModuleFile() {
2831   return isMainFileAST() && ASTFileLangOpts.isCompilingModule();
2832 }
2833 
2834 void ASTUnit::PreambleData::countLines() const {
2835   NumLines = 0;
2836   if (empty())
2837     return;
2838 
2839   NumLines = std::count(Buffer.begin(), Buffer.end(), '\n');
2840 
2841   if (Buffer.back() != '\n')
2842     ++NumLines;
2843 }
2844 
2845 #ifndef NDEBUG
2846 ASTUnit::ConcurrencyState::ConcurrencyState() {
2847   Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2848 }
2849 
2850 ASTUnit::ConcurrencyState::~ConcurrencyState() {
2851   delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2852 }
2853 
2854 void ASTUnit::ConcurrencyState::start() {
2855   bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2856   assert(acquired && "Concurrent access to ASTUnit!");
2857 }
2858 
2859 void ASTUnit::ConcurrencyState::finish() {
2860   static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2861 }
2862 
2863 #else // NDEBUG
2864 
2865 ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex = nullptr; }
2866 ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2867 void ASTUnit::ConcurrencyState::start() {}
2868 void ASTUnit::ConcurrencyState::finish() {}
2869 
2870 #endif // NDEBUG
2871