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