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