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