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