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