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