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