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