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