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