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