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