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