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