ASTUnit.cpp revision 0e4e4d37c1309007566f8892aa97b1e03d1dc9ef
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/Frontend/PCHWriter.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/ASTConsumer.h"
18#include "clang/AST/DeclVisitor.h"
19#include "clang/AST/TypeOrdering.h"
20#include "clang/AST/StmtVisitor.h"
21#include "clang/Driver/Compilation.h"
22#include "clang/Driver/Driver.h"
23#include "clang/Driver/Job.h"
24#include "clang/Driver/Tool.h"
25#include "clang/Frontend/CompilerInstance.h"
26#include "clang/Frontend/FrontendActions.h"
27#include "clang/Frontend/FrontendDiagnostic.h"
28#include "clang/Frontend/FrontendOptions.h"
29#include "clang/Frontend/PCHReader.h"
30#include "clang/Lex/HeaderSearch.h"
31#include "clang/Lex/Preprocessor.h"
32#include "clang/Basic/TargetOptions.h"
33#include "clang/Basic/TargetInfo.h"
34#include "clang/Basic/Diagnostic.h"
35#include "llvm/ADT/StringSet.h"
36#include "llvm/Support/MemoryBuffer.h"
37#include "llvm/System/Host.h"
38#include "llvm/System/Path.h"
39#include "llvm/Support/raw_ostream.h"
40#include "llvm/Support/Timer.h"
41#include <cstdlib>
42#include <cstdio>
43#include <sys/stat.h>
44using namespace clang;
45
46/// \brief After failing to build a precompiled preamble (due to
47/// errors in the source that occurs in the preamble), the number of
48/// reparses during which we'll skip even trying to precompile the
49/// preamble.
50const unsigned DefaultPreambleRebuildInterval = 5;
51
52ASTUnit::ASTUnit(bool _MainFileIsAST)
53  : CaptureDiagnostics(false), MainFileIsAST(_MainFileIsAST),
54    CompleteTranslationUnit(true), ConcurrencyCheckValue(CheckUnlocked),
55    PreambleRebuildCounter(0), SavedMainFileBuffer(0),
56    ShouldCacheCodeCompletionResults(false) {
57}
58
59ASTUnit::~ASTUnit() {
60  ConcurrencyCheckValue = CheckLocked;
61  CleanTemporaryFiles();
62  if (!PreambleFile.empty())
63    llvm::sys::Path(PreambleFile).eraseFromDisk();
64
65  // Free the buffers associated with remapped files. We are required to
66  // perform this operation here because we explicitly request that the
67  // compiler instance *not* free these buffers for each invocation of the
68  // parser.
69  if (Invocation.get()) {
70    PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
71    for (PreprocessorOptions::remapped_file_buffer_iterator
72           FB = PPOpts.remapped_file_buffer_begin(),
73           FBEnd = PPOpts.remapped_file_buffer_end();
74         FB != FBEnd;
75         ++FB)
76      delete FB->second;
77  }
78
79  delete SavedMainFileBuffer;
80
81  ClearCachedCompletionResults();
82
83  for (unsigned I = 0, N = Timers.size(); I != N; ++I)
84    delete Timers[I];
85}
86
87void ASTUnit::CleanTemporaryFiles() {
88  for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
89    TemporaryFiles[I].eraseFromDisk();
90  TemporaryFiles.clear();
91}
92
93/// \brief Determine the set of code-completion contexts in which this
94/// declaration should be shown.
95static unsigned getDeclShowContexts(NamedDecl *ND,
96                                    const LangOptions &LangOpts,
97                                    bool &IsNestedNameSpecifier) {
98  IsNestedNameSpecifier = false;
99
100  if (isa<UsingShadowDecl>(ND))
101    ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
102  if (!ND)
103    return 0;
104
105  unsigned Contexts = 0;
106  if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
107      isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
108    // Types can appear in these contexts.
109    if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
110      Contexts |= (1 << (CodeCompletionContext::CCC_TopLevel - 1))
111                | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
112                | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
113                | (1 << (CodeCompletionContext::CCC_Statement - 1))
114                | (1 << (CodeCompletionContext::CCC_Type - 1));
115
116    // In C++, types can appear in expressions contexts (for functional casts).
117    if (LangOpts.CPlusPlus)
118      Contexts |= (1 << (CodeCompletionContext::CCC_Expression - 1));
119
120    // In Objective-C, message sends can send interfaces. In Objective-C++,
121    // all types are available due to functional casts.
122    if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
123      Contexts |= (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
124
125    // Deal with tag names.
126    if (isa<EnumDecl>(ND)) {
127      Contexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1));
128
129      // Part of the nested-name-specifier in C++0x.
130      if (LangOpts.CPlusPlus0x)
131        IsNestedNameSpecifier = true;
132    } else if (RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
133      if (Record->isUnion())
134        Contexts |= (1 << (CodeCompletionContext::CCC_UnionTag - 1));
135      else
136        Contexts |= (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
137
138      if (LangOpts.CPlusPlus)
139        IsNestedNameSpecifier = true;
140    } else if (isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND))
141      IsNestedNameSpecifier = true;
142  } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
143    // Values can appear in these contexts.
144    Contexts = (1 << (CodeCompletionContext::CCC_Statement - 1))
145             | (1 << (CodeCompletionContext::CCC_Expression - 1))
146             | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
147  } else if (isa<ObjCProtocolDecl>(ND)) {
148    Contexts = (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
149  } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
150    Contexts = (1 << (CodeCompletionContext::CCC_Namespace - 1));
151
152    // Part of the nested-name-specifier.
153    IsNestedNameSpecifier = true;
154  }
155
156  return Contexts;
157}
158
159void ASTUnit::CacheCodeCompletionResults() {
160  if (!TheSema)
161    return;
162
163  llvm::Timer *CachingTimer = 0;
164  if (TimerGroup.get()) {
165    CachingTimer = new llvm::Timer("Cache global code completions",
166                                   *TimerGroup);
167    CachingTimer->startTimer();
168    Timers.push_back(CachingTimer);
169  }
170
171  // Clear out the previous results.
172  ClearCachedCompletionResults();
173
174  // Gather the set of global code completions.
175  typedef CodeCompleteConsumer::Result Result;
176  llvm::SmallVector<Result, 8> Results;
177  TheSema->GatherGlobalCodeCompletions(Results);
178
179  // Translate global code completions into cached completions.
180  llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
181
182  for (unsigned I = 0, N = Results.size(); I != N; ++I) {
183    switch (Results[I].Kind) {
184    case Result::RK_Declaration: {
185      bool IsNestedNameSpecifier = false;
186      CachedCodeCompletionResult CachedResult;
187      CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
188      CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
189                                                        Ctx->getLangOptions(),
190                                                        IsNestedNameSpecifier);
191      CachedResult.Priority = Results[I].Priority;
192      CachedResult.Kind = Results[I].CursorKind;
193
194      // Keep track of the type of this completion in an ASTContext-agnostic
195      // way.
196      QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
197      if (UsageType.isNull()) {
198        CachedResult.TypeClass = STC_Void;
199        CachedResult.Type = 0;
200      } else {
201        CanQualType CanUsageType
202          = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
203        CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
204
205        // Determine whether we have already seen this type. If so, we save
206        // ourselves the work of formatting the type string by using the
207        // temporary, CanQualType-based hash table to find the associated value.
208        unsigned &TypeValue = CompletionTypes[CanUsageType];
209        if (TypeValue == 0) {
210          TypeValue = CompletionTypes.size();
211          CachedCompletionTypes[QualType(CanUsageType).getAsString()]
212            = TypeValue;
213        }
214
215        CachedResult.Type = TypeValue;
216      }
217
218      CachedCompletionResults.push_back(CachedResult);
219
220      /// Handle nested-name-specifiers in C++.
221      if (TheSema->Context.getLangOptions().CPlusPlus &&
222          IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
223        // The contexts in which a nested-name-specifier can appear in C++.
224        unsigned NNSContexts
225          = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
226          | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
227          | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
228          | (1 << (CodeCompletionContext::CCC_Statement - 1))
229          | (1 << (CodeCompletionContext::CCC_Expression - 1))
230          | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
231          | (1 << (CodeCompletionContext::CCC_EnumTag - 1))
232          | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
233          | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1))
234          | (1 << (CodeCompletionContext::CCC_Type - 1));
235
236        if (isa<NamespaceDecl>(Results[I].Declaration) ||
237            isa<NamespaceAliasDecl>(Results[I].Declaration))
238          NNSContexts |= (1 << (CodeCompletionContext::CCC_Namespace - 1));
239
240        if (unsigned RemainingContexts
241                                = NNSContexts & ~CachedResult.ShowInContexts) {
242          // If there any contexts where this completion can be a
243          // nested-name-specifier but isn't already an option, create a
244          // nested-name-specifier completion.
245          Results[I].StartsNestedNameSpecifier = true;
246          CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
247          CachedResult.ShowInContexts = RemainingContexts;
248          CachedResult.Priority = CCP_NestedNameSpecifier;
249          CachedResult.TypeClass = STC_Void;
250          CachedResult.Type = 0;
251          CachedCompletionResults.push_back(CachedResult);
252        }
253      }
254      break;
255    }
256
257    case Result::RK_Keyword:
258    case Result::RK_Pattern:
259      // Ignore keywords and patterns; we don't care, since they are so
260      // easily regenerated.
261      break;
262
263    case Result::RK_Macro: {
264      CachedCodeCompletionResult CachedResult;
265      CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
266      CachedResult.ShowInContexts
267        = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
268        | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
269        | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
270        | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
271        | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
272        | (1 << (CodeCompletionContext::CCC_Statement - 1))
273        | (1 << (CodeCompletionContext::CCC_Expression - 1))
274        | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
275      CachedResult.Priority = Results[I].Priority;
276      CachedResult.Kind = Results[I].CursorKind;
277      CachedResult.TypeClass = STC_Void;
278      CachedResult.Type = 0;
279      CachedCompletionResults.push_back(CachedResult);
280      break;
281    }
282    }
283    Results[I].Destroy();
284  }
285
286  if (CachingTimer)
287    CachingTimer->stopTimer();
288}
289
290void ASTUnit::ClearCachedCompletionResults() {
291  for (unsigned I = 0, N = CachedCompletionResults.size(); I != N; ++I)
292    delete CachedCompletionResults[I].Completion;
293  CachedCompletionResults.clear();
294  CachedCompletionTypes.clear();
295}
296
297namespace {
298
299/// \brief Gathers information from PCHReader that will be used to initialize
300/// a Preprocessor.
301class PCHInfoCollector : public PCHReaderListener {
302  LangOptions &LangOpt;
303  HeaderSearch &HSI;
304  std::string &TargetTriple;
305  std::string &Predefines;
306  unsigned &Counter;
307
308  unsigned NumHeaderInfos;
309
310public:
311  PCHInfoCollector(LangOptions &LangOpt, HeaderSearch &HSI,
312                   std::string &TargetTriple, std::string &Predefines,
313                   unsigned &Counter)
314    : LangOpt(LangOpt), HSI(HSI), TargetTriple(TargetTriple),
315      Predefines(Predefines), Counter(Counter), NumHeaderInfos(0) {}
316
317  virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
318    LangOpt = LangOpts;
319    return false;
320  }
321
322  virtual bool ReadTargetTriple(llvm::StringRef Triple) {
323    TargetTriple = Triple;
324    return false;
325  }
326
327  virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
328                                    llvm::StringRef OriginalFileName,
329                                    std::string &SuggestedPredefines) {
330    Predefines = Buffers[0].Data;
331    for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
332      Predefines += Buffers[I].Data;
333    }
334    return false;
335  }
336
337  virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
338    HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
339  }
340
341  virtual void ReadCounter(unsigned Value) {
342    Counter = Value;
343  }
344};
345
346class StoredDiagnosticClient : public DiagnosticClient {
347  llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags;
348
349public:
350  explicit StoredDiagnosticClient(
351                          llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
352    : StoredDiags(StoredDiags) { }
353
354  virtual void HandleDiagnostic(Diagnostic::Level Level,
355                                const DiagnosticInfo &Info);
356};
357
358/// \brief RAII object that optionally captures diagnostics, if
359/// there is no diagnostic client to capture them already.
360class CaptureDroppedDiagnostics {
361  Diagnostic &Diags;
362  StoredDiagnosticClient Client;
363  DiagnosticClient *PreviousClient;
364
365public:
366  CaptureDroppedDiagnostics(bool RequestCapture, Diagnostic &Diags,
367                           llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
368    : Diags(Diags), Client(StoredDiags), PreviousClient(Diags.getClient())
369  {
370    if (RequestCapture || Diags.getClient() == 0)
371      Diags.setClient(&Client);
372  }
373
374  ~CaptureDroppedDiagnostics() {
375    Diags.setClient(PreviousClient);
376  }
377};
378
379} // anonymous namespace
380
381void StoredDiagnosticClient::HandleDiagnostic(Diagnostic::Level Level,
382                                              const DiagnosticInfo &Info) {
383  StoredDiags.push_back(StoredDiagnostic(Level, Info));
384}
385
386const std::string &ASTUnit::getOriginalSourceFileName() {
387  return OriginalSourceFile;
388}
389
390const std::string &ASTUnit::getPCHFileName() {
391  assert(isMainFileAST() && "Not an ASTUnit from a PCH file!");
392  return static_cast<PCHReader *>(Ctx->getExternalSource())->getFileName();
393}
394
395ASTUnit *ASTUnit::LoadFromPCHFile(const std::string &Filename,
396                                  llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
397                                  bool OnlyLocalDecls,
398                                  RemappedFile *RemappedFiles,
399                                  unsigned NumRemappedFiles,
400                                  bool CaptureDiagnostics) {
401  llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true));
402
403  if (!Diags.getPtr()) {
404    // No diagnostics engine was provided, so create our own diagnostics object
405    // with the default options.
406    DiagnosticOptions DiagOpts;
407    Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
408  }
409
410  AST->CaptureDiagnostics = CaptureDiagnostics;
411  AST->OnlyLocalDecls = OnlyLocalDecls;
412  AST->Diagnostics = Diags;
413  AST->FileMgr.reset(new FileManager);
414  AST->SourceMgr.reset(new SourceManager(AST->getDiagnostics()));
415  AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager()));
416
417  // If requested, capture diagnostics in the ASTUnit.
418  CaptureDroppedDiagnostics Capture(CaptureDiagnostics, AST->getDiagnostics(),
419                                    AST->StoredDiagnostics);
420
421  for (unsigned I = 0; I != NumRemappedFiles; ++I) {
422    // Create the file entry for the file that we're mapping from.
423    const FileEntry *FromFile
424      = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
425                                    RemappedFiles[I].second->getBufferSize(),
426                                             0);
427    if (!FromFile) {
428      AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
429        << RemappedFiles[I].first;
430      delete RemappedFiles[I].second;
431      continue;
432    }
433
434    // Override the contents of the "from" file with the contents of
435    // the "to" file.
436    AST->getSourceManager().overrideFileContents(FromFile,
437                                                 RemappedFiles[I].second);
438  }
439
440  // Gather Info for preprocessor construction later on.
441
442  LangOptions LangInfo;
443  HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
444  std::string TargetTriple;
445  std::string Predefines;
446  unsigned Counter;
447
448  llvm::OwningPtr<PCHReader> Reader;
449
450  Reader.reset(new PCHReader(AST->getSourceManager(), AST->getFileManager(),
451                             AST->getDiagnostics()));
452  Reader->setListener(new PCHInfoCollector(LangInfo, HeaderInfo, TargetTriple,
453                                           Predefines, Counter));
454
455  switch (Reader->ReadPCH(Filename)) {
456  case PCHReader::Success:
457    break;
458
459  case PCHReader::Failure:
460  case PCHReader::IgnorePCH:
461    AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
462    return NULL;
463  }
464
465  AST->OriginalSourceFile = Reader->getOriginalSourceFile();
466
467  // PCH loaded successfully. Now create the preprocessor.
468
469  // Get information about the target being compiled for.
470  //
471  // FIXME: This is broken, we should store the TargetOptions in the PCH.
472  TargetOptions TargetOpts;
473  TargetOpts.ABI = "";
474  TargetOpts.CXXABI = "itanium";
475  TargetOpts.CPU = "";
476  TargetOpts.Features.clear();
477  TargetOpts.Triple = TargetTriple;
478  AST->Target.reset(TargetInfo::CreateTargetInfo(AST->getDiagnostics(),
479                                                 TargetOpts));
480  AST->PP.reset(new Preprocessor(AST->getDiagnostics(), LangInfo,
481                                 *AST->Target.get(),
482                                 AST->getSourceManager(), HeaderInfo));
483  Preprocessor &PP = *AST->PP.get();
484
485  PP.setPredefines(Reader->getSuggestedPredefines());
486  PP.setCounterValue(Counter);
487  Reader->setPreprocessor(PP);
488
489  // Create and initialize the ASTContext.
490
491  AST->Ctx.reset(new ASTContext(LangInfo,
492                                AST->getSourceManager(),
493                                *AST->Target.get(),
494                                PP.getIdentifierTable(),
495                                PP.getSelectorTable(),
496                                PP.getBuiltinInfo(),
497                                /* size_reserve = */0));
498  ASTContext &Context = *AST->Ctx.get();
499
500  Reader->InitializeContext(Context);
501
502  // Attach the PCH reader to the AST context as an external AST
503  // source, so that declarations will be deserialized from the
504  // PCH file as needed.
505  PCHReader *ReaderPtr = Reader.get();
506  llvm::OwningPtr<ExternalASTSource> Source(Reader.take());
507  Context.setExternalSource(Source);
508
509  // Create an AST consumer, even though it isn't used.
510  AST->Consumer.reset(new ASTConsumer);
511
512  // Create a semantic analysis object and tell the PCH reader about it.
513  AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
514  AST->TheSema->Initialize();
515  ReaderPtr->InitializeSema(*AST->TheSema);
516
517  return AST.take();
518}
519
520namespace {
521
522class TopLevelDeclTrackerConsumer : public ASTConsumer {
523  ASTUnit &Unit;
524
525public:
526  TopLevelDeclTrackerConsumer(ASTUnit &_Unit) : Unit(_Unit) {}
527
528  void HandleTopLevelDecl(DeclGroupRef D) {
529    for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
530      Decl *D = *it;
531      // FIXME: Currently ObjC method declarations are incorrectly being
532      // reported as top-level declarations, even though their DeclContext
533      // is the containing ObjC @interface/@implementation.  This is a
534      // fundamental problem in the parser right now.
535      if (isa<ObjCMethodDecl>(D))
536        continue;
537      Unit.addTopLevelDecl(D);
538    }
539  }
540
541  // We're not interested in "interesting" decls.
542  void HandleInterestingDecl(DeclGroupRef) {}
543};
544
545class TopLevelDeclTrackerAction : public ASTFrontendAction {
546public:
547  ASTUnit &Unit;
548
549  virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
550                                         llvm::StringRef InFile) {
551    return new TopLevelDeclTrackerConsumer(Unit);
552  }
553
554public:
555  TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
556
557  virtual bool hasCodeCompletionSupport() const { return false; }
558  virtual bool usesCompleteTranslationUnit()  {
559    return Unit.isCompleteTranslationUnit();
560  }
561};
562
563class PrecompilePreambleConsumer : public PCHGenerator {
564  ASTUnit &Unit;
565  std::vector<Decl *> TopLevelDecls;
566
567public:
568  PrecompilePreambleConsumer(ASTUnit &Unit,
569                             const Preprocessor &PP, bool Chaining,
570                             const char *isysroot, llvm::raw_ostream *Out)
571    : PCHGenerator(PP, Chaining, isysroot, Out), Unit(Unit) { }
572
573  virtual void HandleTopLevelDecl(DeclGroupRef D) {
574    for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
575      Decl *D = *it;
576      // FIXME: Currently ObjC method declarations are incorrectly being
577      // reported as top-level declarations, even though their DeclContext
578      // is the containing ObjC @interface/@implementation.  This is a
579      // fundamental problem in the parser right now.
580      if (isa<ObjCMethodDecl>(D))
581        continue;
582      TopLevelDecls.push_back(D);
583    }
584  }
585
586  virtual void HandleTranslationUnit(ASTContext &Ctx) {
587    PCHGenerator::HandleTranslationUnit(Ctx);
588    if (!Unit.getDiagnostics().hasErrorOccurred()) {
589      // Translate the top-level declarations we captured during
590      // parsing into declaration IDs in the precompiled
591      // preamble. This will allow us to deserialize those top-level
592      // declarations when requested.
593      for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
594        Unit.addTopLevelDeclFromPreamble(
595                                      getWriter().getDeclID(TopLevelDecls[I]));
596    }
597  }
598};
599
600class PrecompilePreambleAction : public ASTFrontendAction {
601  ASTUnit &Unit;
602
603public:
604  explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
605
606  virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
607                                         llvm::StringRef InFile) {
608    std::string Sysroot;
609    llvm::raw_ostream *OS = 0;
610    bool Chaining;
611    if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
612                                                       OS, Chaining))
613      return 0;
614
615    const char *isysroot = CI.getFrontendOpts().RelocatablePCH ?
616                             Sysroot.c_str() : 0;
617    return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Chaining,
618                                          isysroot, OS);
619  }
620
621  virtual bool hasCodeCompletionSupport() const { return false; }
622  virtual bool hasASTFileSupport() const { return false; }
623  virtual bool usesCompleteTranslationUnit() { return false; }
624};
625
626}
627
628/// Parse the source file into a translation unit using the given compiler
629/// invocation, replacing the current translation unit.
630///
631/// \returns True if a failure occurred that causes the ASTUnit not to
632/// contain any translation-unit information, false otherwise.
633bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
634  delete SavedMainFileBuffer;
635  SavedMainFileBuffer = 0;
636
637  if (!Invocation.get())
638    return true;
639
640  // Create the compiler instance to use for building the AST.
641  CompilerInstance Clang;
642  Clang.setInvocation(Invocation.take());
643  OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
644
645  // Set up diagnostics, capturing any diagnostics that would
646  // otherwise be dropped.
647  Clang.setDiagnostics(&getDiagnostics());
648  CaptureDroppedDiagnostics Capture(CaptureDiagnostics,
649                                    getDiagnostics(),
650                                    StoredDiagnostics);
651  Clang.setDiagnosticClient(getDiagnostics().getClient());
652
653  // Create the target instance.
654  Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
655                                               Clang.getTargetOpts()));
656  if (!Clang.hasTarget()) {
657    Clang.takeDiagnosticClient();
658    return true;
659  }
660
661  // Inform the target of the language options.
662  //
663  // FIXME: We shouldn't need to do this, the target should be immutable once
664  // created. This complexity should be lifted elsewhere.
665  Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
666
667  assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
668         "Invocation must have exactly one source file!");
669  assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
670         "FIXME: AST inputs not yet supported here!");
671  assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
672         "IR inputs not support here!");
673
674  // Configure the various subsystems.
675  // FIXME: Should we retain the previous file manager?
676  FileMgr.reset(new FileManager);
677  SourceMgr.reset(new SourceManager(getDiagnostics()));
678  TheSema.reset();
679  Ctx.reset();
680  PP.reset();
681
682  // Clear out old caches and data.
683  TopLevelDecls.clear();
684  CleanTemporaryFiles();
685  PreprocessedEntitiesByFile.clear();
686
687  if (!OverrideMainBuffer)
688    StoredDiagnostics.clear();
689
690  // Create a file manager object to provide access to and cache the filesystem.
691  Clang.setFileManager(&getFileManager());
692
693  // Create the source manager.
694  Clang.setSourceManager(&getSourceManager());
695
696  // If the main file has been overridden due to the use of a preamble,
697  // make that override happen and introduce the preamble.
698  PreprocessorOptions &PreprocessorOpts = Clang.getPreprocessorOpts();
699  std::string PriorImplicitPCHInclude;
700  if (OverrideMainBuffer) {
701    PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
702    PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
703    PreprocessorOpts.PrecompiledPreambleBytes.second
704                                                    = PreambleEndsAtStartOfLine;
705    PriorImplicitPCHInclude = PreprocessorOpts.ImplicitPCHInclude;
706    PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
707    PreprocessorOpts.DisablePCHValidation = true;
708
709    // Keep track of the override buffer;
710    SavedMainFileBuffer = OverrideMainBuffer;
711
712    // The stored diagnostic has the old source manager in it; update
713    // the locations to refer into the new source manager. Since we've
714    // been careful to make sure that the source manager's state
715    // before and after are identical, so that we can reuse the source
716    // location itself.
717    for (unsigned I = 0, N = StoredDiagnostics.size(); I != N; ++I) {
718      FullSourceLoc Loc(StoredDiagnostics[I].getLocation(),
719                        getSourceManager());
720      StoredDiagnostics[I].setLocation(Loc);
721    }
722  }
723
724  llvm::OwningPtr<TopLevelDeclTrackerAction> Act;
725  Act.reset(new TopLevelDeclTrackerAction(*this));
726  if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
727                            Clang.getFrontendOpts().Inputs[0].first))
728    goto error;
729
730  Act->Execute();
731
732  // Steal the created target, context, and preprocessor, and take back the
733  // source and file managers.
734  TheSema.reset(Clang.takeSema());
735  Consumer.reset(Clang.takeASTConsumer());
736  Ctx.reset(Clang.takeASTContext());
737  PP.reset(Clang.takePreprocessor());
738  Clang.takeSourceManager();
739  Clang.takeFileManager();
740  Target.reset(Clang.takeTarget());
741
742  Act->EndSourceFile();
743
744  // Remove the overridden buffer we used for the preamble.
745  if (OverrideMainBuffer) {
746    PreprocessorOpts.eraseRemappedFile(
747                               PreprocessorOpts.remapped_file_buffer_end() - 1);
748    PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
749  }
750
751  Clang.takeDiagnosticClient();
752
753  Invocation.reset(Clang.takeInvocation());
754
755  // If we were asked to cache code-completion results and don't have any
756  // results yet, do so now.
757  if (ShouldCacheCodeCompletionResults && CachedCompletionResults.empty())
758    CacheCodeCompletionResults();
759
760  return false;
761
762error:
763  // Remove the overridden buffer we used for the preamble.
764  if (OverrideMainBuffer) {
765    PreprocessorOpts.eraseRemappedFile(
766                               PreprocessorOpts.remapped_file_buffer_end() - 1);
767    PreprocessorOpts.DisablePCHValidation = true;
768    PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
769  }
770
771  Clang.takeSourceManager();
772  Clang.takeFileManager();
773  Clang.takeDiagnosticClient();
774  Invocation.reset(Clang.takeInvocation());
775  return true;
776}
777
778/// \brief Simple function to retrieve a path for a preamble precompiled header.
779static std::string GetPreamblePCHPath() {
780  // FIXME: This is lame; sys::Path should provide this function (in particular,
781  // it should know how to find the temporary files dir).
782  // FIXME: This is really lame. I copied this code from the Driver!
783  std::string Error;
784  const char *TmpDir = ::getenv("TMPDIR");
785  if (!TmpDir)
786    TmpDir = ::getenv("TEMP");
787  if (!TmpDir)
788    TmpDir = ::getenv("TMP");
789  if (!TmpDir)
790    TmpDir = "/tmp";
791  llvm::sys::Path P(TmpDir);
792  P.appendComponent("preamble");
793  P.appendSuffix("pch");
794  if (P.createTemporaryFileOnDisk())
795    return std::string();
796
797  return P.str();
798}
799
800/// \brief Compute the preamble for the main file, providing the source buffer
801/// that corresponds to the main file along with a pair (bytes, start-of-line)
802/// that describes the preamble.
803std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
804ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
805                         unsigned MaxLines, bool &CreatedBuffer) {
806  FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
807  PreprocessorOptions &PreprocessorOpts
808    = Invocation.getPreprocessorOpts();
809  CreatedBuffer = false;
810
811  // Try to determine if the main file has been remapped, either from the
812  // command line (to another file) or directly through the compiler invocation
813  // (to a memory buffer).
814  llvm::MemoryBuffer *Buffer = 0;
815  llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
816  if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
817    // Check whether there is a file-file remapping of the main file
818    for (PreprocessorOptions::remapped_file_iterator
819          M = PreprocessorOpts.remapped_file_begin(),
820          E = PreprocessorOpts.remapped_file_end();
821         M != E;
822         ++M) {
823      llvm::sys::PathWithStatus MPath(M->first);
824      if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
825        if (MainFileStatus->uniqueID == MStatus->uniqueID) {
826          // We found a remapping. Try to load the resulting, remapped source.
827          if (CreatedBuffer) {
828            delete Buffer;
829            CreatedBuffer = false;
830          }
831
832          Buffer = llvm::MemoryBuffer::getFile(M->second);
833          if (!Buffer)
834            return std::make_pair((llvm::MemoryBuffer*)0,
835                                  std::make_pair(0, true));
836          CreatedBuffer = true;
837
838          // Remove this remapping. We've captured the buffer already.
839          M = PreprocessorOpts.eraseRemappedFile(M);
840          E = PreprocessorOpts.remapped_file_end();
841        }
842      }
843    }
844
845    // Check whether there is a file-buffer remapping. It supercedes the
846    // file-file remapping.
847    for (PreprocessorOptions::remapped_file_buffer_iterator
848           M = PreprocessorOpts.remapped_file_buffer_begin(),
849           E = PreprocessorOpts.remapped_file_buffer_end();
850         M != E;
851         ++M) {
852      llvm::sys::PathWithStatus MPath(M->first);
853      if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
854        if (MainFileStatus->uniqueID == MStatus->uniqueID) {
855          // We found a remapping.
856          if (CreatedBuffer) {
857            delete Buffer;
858            CreatedBuffer = false;
859          }
860
861          Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
862
863          // Remove this remapping. We've captured the buffer already.
864          M = PreprocessorOpts.eraseRemappedFile(M);
865          E = PreprocessorOpts.remapped_file_buffer_end();
866        }
867      }
868    }
869  }
870
871  // If the main source file was not remapped, load it now.
872  if (!Buffer) {
873    Buffer = llvm::MemoryBuffer::getFile(FrontendOpts.Inputs[0].second);
874    if (!Buffer)
875      return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
876
877    CreatedBuffer = true;
878  }
879
880  return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer, MaxLines));
881}
882
883static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
884                                                      bool DeleteOld,
885                                                      unsigned NewSize,
886                                                      llvm::StringRef NewName) {
887  llvm::MemoryBuffer *Result
888    = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
889  memcpy(const_cast<char*>(Result->getBufferStart()),
890         Old->getBufferStart(), Old->getBufferSize());
891  memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
892         ' ', NewSize - Old->getBufferSize() - 1);
893  const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
894
895  if (DeleteOld)
896    delete Old;
897
898  return Result;
899}
900
901/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
902/// the source file.
903///
904/// This routine will compute the preamble of the main source file. If a
905/// non-trivial preamble is found, it will precompile that preamble into a
906/// precompiled header so that the precompiled preamble can be used to reduce
907/// reparsing time. If a precompiled preamble has already been constructed,
908/// this routine will determine if it is still valid and, if so, avoid
909/// rebuilding the precompiled preamble.
910///
911/// \param AllowRebuild When true (the default), this routine is
912/// allowed to rebuild the precompiled preamble if it is found to be
913/// out-of-date.
914///
915/// \param MaxLines When non-zero, the maximum number of lines that
916/// can occur within the preamble.
917///
918/// \returns If the precompiled preamble can be used, returns a newly-allocated
919/// buffer that should be used in place of the main file when doing so.
920/// Otherwise, returns a NULL pointer.
921llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
922                                                           bool AllowRebuild,
923                                                           unsigned MaxLines) {
924  CompilerInvocation PreambleInvocation(*Invocation);
925  FrontendOptions &FrontendOpts = PreambleInvocation.getFrontendOpts();
926  PreprocessorOptions &PreprocessorOpts
927    = PreambleInvocation.getPreprocessorOpts();
928
929  bool CreatedPreambleBuffer = false;
930  std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
931    = ComputePreamble(PreambleInvocation, MaxLines, CreatedPreambleBuffer);
932
933  if (!NewPreamble.second.first) {
934    // We couldn't find a preamble in the main source. Clear out the current
935    // preamble, if we have one. It's obviously no good any more.
936    Preamble.clear();
937    if (!PreambleFile.empty()) {
938      llvm::sys::Path(PreambleFile).eraseFromDisk();
939      PreambleFile.clear();
940    }
941    if (CreatedPreambleBuffer)
942      delete NewPreamble.first;
943
944    // The next time we actually see a preamble, precompile it.
945    PreambleRebuildCounter = 1;
946    return 0;
947  }
948
949  if (!Preamble.empty()) {
950    // We've previously computed a preamble. Check whether we have the same
951    // preamble now that we did before, and that there's enough space in
952    // the main-file buffer within the precompiled preamble to fit the
953    // new main file.
954    if (Preamble.size() == NewPreamble.second.first &&
955        PreambleEndsAtStartOfLine == NewPreamble.second.second &&
956        NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
957        memcmp(&Preamble[0], NewPreamble.first->getBufferStart(),
958               NewPreamble.second.first) == 0) {
959      // The preamble has not changed. We may be able to re-use the precompiled
960      // preamble.
961
962      // Check that none of the files used by the preamble have changed.
963      bool AnyFileChanged = false;
964
965      // First, make a record of those files that have been overridden via
966      // remapping or unsaved_files.
967      llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
968      for (PreprocessorOptions::remapped_file_iterator
969                R = PreprocessorOpts.remapped_file_begin(),
970             REnd = PreprocessorOpts.remapped_file_end();
971           !AnyFileChanged && R != REnd;
972           ++R) {
973        struct stat StatBuf;
974        if (stat(R->second.c_str(), &StatBuf)) {
975          // If we can't stat the file we're remapping to, assume that something
976          // horrible happened.
977          AnyFileChanged = true;
978          break;
979        }
980
981        OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
982                                                   StatBuf.st_mtime);
983      }
984      for (PreprocessorOptions::remapped_file_buffer_iterator
985                R = PreprocessorOpts.remapped_file_buffer_begin(),
986             REnd = PreprocessorOpts.remapped_file_buffer_end();
987           !AnyFileChanged && R != REnd;
988           ++R) {
989        // FIXME: Should we actually compare the contents of file->buffer
990        // remappings?
991        OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
992                                                   0);
993      }
994
995      // Check whether anything has changed.
996      for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
997             F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
998           !AnyFileChanged && F != FEnd;
999           ++F) {
1000        llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1001          = OverriddenFiles.find(F->first());
1002        if (Overridden != OverriddenFiles.end()) {
1003          // This file was remapped; check whether the newly-mapped file
1004          // matches up with the previous mapping.
1005          if (Overridden->second != F->second)
1006            AnyFileChanged = true;
1007          continue;
1008        }
1009
1010        // The file was not remapped; check whether it has changed on disk.
1011        struct stat StatBuf;
1012        if (stat(F->first(), &StatBuf)) {
1013          // If we can't stat the file, assume that something horrible happened.
1014          AnyFileChanged = true;
1015        } else if (StatBuf.st_size != F->second.first ||
1016                   StatBuf.st_mtime != F->second.second)
1017          AnyFileChanged = true;
1018      }
1019
1020      if (!AnyFileChanged) {
1021        // Okay! We can re-use the precompiled preamble.
1022
1023        // Set the state of the diagnostic object to mimic its state
1024        // after parsing the preamble.
1025        getDiagnostics().Reset();
1026        getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1027        if (StoredDiagnostics.size() > NumStoredDiagnosticsInPreamble)
1028          StoredDiagnostics.erase(
1029            StoredDiagnostics.begin() + NumStoredDiagnosticsInPreamble,
1030                                  StoredDiagnostics.end());
1031
1032        // Create a version of the main file buffer that is padded to
1033        // buffer size we reserved when creating the preamble.
1034        return CreatePaddedMainFileBuffer(NewPreamble.first,
1035                                          CreatedPreambleBuffer,
1036                                          PreambleReservedSize,
1037                                          FrontendOpts.Inputs[0].second);
1038      }
1039    }
1040
1041    // If we aren't allowed to rebuild the precompiled preamble, just
1042    // return now.
1043    if (!AllowRebuild)
1044      return 0;
1045
1046    // We can't reuse the previously-computed preamble. Build a new one.
1047    Preamble.clear();
1048    llvm::sys::Path(PreambleFile).eraseFromDisk();
1049    PreambleRebuildCounter = 1;
1050  } else if (!AllowRebuild) {
1051    // We aren't allowed to rebuild the precompiled preamble; just
1052    // return now.
1053    return 0;
1054  }
1055
1056  // If the preamble rebuild counter > 1, it's because we previously
1057  // failed to build a preamble and we're not yet ready to try
1058  // again. Decrement the counter and return a failure.
1059  if (PreambleRebuildCounter > 1) {
1060    --PreambleRebuildCounter;
1061    return 0;
1062  }
1063
1064  // We did not previously compute a preamble, or it can't be reused anyway.
1065  llvm::Timer *PreambleTimer = 0;
1066  if (TimerGroup.get()) {
1067    PreambleTimer = new llvm::Timer("Precompiling preamble", *TimerGroup);
1068    PreambleTimer->startTimer();
1069    Timers.push_back(PreambleTimer);
1070  }
1071
1072  // Create a new buffer that stores the preamble. The buffer also contains
1073  // extra space for the original contents of the file (which will be present
1074  // when we actually parse the file) along with more room in case the file
1075  // grows.
1076  PreambleReservedSize = NewPreamble.first->getBufferSize();
1077  if (PreambleReservedSize < 4096)
1078    PreambleReservedSize = 8191;
1079  else
1080    PreambleReservedSize *= 2;
1081
1082  // Save the preamble text for later; we'll need to compare against it for
1083  // subsequent reparses.
1084  Preamble.assign(NewPreamble.first->getBufferStart(),
1085                  NewPreamble.first->getBufferStart()
1086                                                  + NewPreamble.second.first);
1087  PreambleEndsAtStartOfLine = NewPreamble.second.second;
1088
1089  llvm::MemoryBuffer *PreambleBuffer
1090    = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
1091                                                FrontendOpts.Inputs[0].second);
1092  memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
1093         NewPreamble.first->getBufferStart(), Preamble.size());
1094  memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
1095         ' ', PreambleReservedSize - Preamble.size() - 1);
1096  const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
1097
1098  // Remap the main source file to the preamble buffer.
1099  llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
1100  PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1101
1102  // Tell the compiler invocation to generate a temporary precompiled header.
1103  FrontendOpts.ProgramAction = frontend::GeneratePCH;
1104  // FIXME: Set ChainedPCH unconditionally, once it is ready.
1105  if (::getenv("LIBCLANG_CHAINING"))
1106    FrontendOpts.ChainedPCH = true;
1107  // FIXME: Generate the precompiled header into memory?
1108  FrontendOpts.OutputFile = GetPreamblePCHPath();
1109
1110  // Create the compiler instance to use for building the precompiled preamble.
1111  CompilerInstance Clang;
1112  Clang.setInvocation(&PreambleInvocation);
1113  OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1114
1115  // Set up diagnostics, capturing all of the diagnostics produced.
1116  Clang.setDiagnostics(&getDiagnostics());
1117  CaptureDroppedDiagnostics Capture(CaptureDiagnostics,
1118                                    getDiagnostics(),
1119                                    StoredDiagnostics);
1120  Clang.setDiagnosticClient(getDiagnostics().getClient());
1121
1122  // Create the target instance.
1123  Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1124                                               Clang.getTargetOpts()));
1125  if (!Clang.hasTarget()) {
1126    Clang.takeDiagnosticClient();
1127    llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1128    Preamble.clear();
1129    if (CreatedPreambleBuffer)
1130      delete NewPreamble.first;
1131    if (PreambleTimer)
1132      PreambleTimer->stopTimer();
1133    PreambleRebuildCounter = DefaultPreambleRebuildInterval;
1134    return 0;
1135  }
1136
1137  // Inform the target of the language options.
1138  //
1139  // FIXME: We shouldn't need to do this, the target should be immutable once
1140  // created. This complexity should be lifted elsewhere.
1141  Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1142
1143  assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1144         "Invocation must have exactly one source file!");
1145  assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1146         "FIXME: AST inputs not yet supported here!");
1147  assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1148         "IR inputs not support here!");
1149
1150  // Clear out old caches and data.
1151  StoredDiagnostics.clear();
1152  TopLevelDecls.clear();
1153  TopLevelDeclsInPreamble.clear();
1154
1155  // Create a file manager object to provide access to and cache the filesystem.
1156  Clang.setFileManager(new FileManager);
1157
1158  // Create the source manager.
1159  Clang.setSourceManager(new SourceManager(getDiagnostics()));
1160
1161  llvm::OwningPtr<PrecompilePreambleAction> Act;
1162  Act.reset(new PrecompilePreambleAction(*this));
1163  if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1164                            Clang.getFrontendOpts().Inputs[0].first)) {
1165    Clang.takeDiagnosticClient();
1166    Clang.takeInvocation();
1167    llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1168    Preamble.clear();
1169    if (CreatedPreambleBuffer)
1170      delete NewPreamble.first;
1171    if (PreambleTimer)
1172      PreambleTimer->stopTimer();
1173    PreambleRebuildCounter = DefaultPreambleRebuildInterval;
1174
1175    return 0;
1176  }
1177
1178  Act->Execute();
1179  Act->EndSourceFile();
1180  Clang.takeDiagnosticClient();
1181  Clang.takeInvocation();
1182
1183  if (Diagnostics->hasErrorOccurred()) {
1184    // There were errors parsing the preamble, so no precompiled header was
1185    // generated. Forget that we even tried.
1186    // FIXME: Should we leave a note for ourselves to try again?
1187    llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1188    Preamble.clear();
1189    if (CreatedPreambleBuffer)
1190      delete NewPreamble.first;
1191    if (PreambleTimer)
1192      PreambleTimer->stopTimer();
1193    TopLevelDeclsInPreamble.clear();
1194    PreambleRebuildCounter = DefaultPreambleRebuildInterval;
1195    return 0;
1196  }
1197
1198  // Keep track of the preamble we precompiled.
1199  PreambleFile = FrontendOpts.OutputFile;
1200  NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
1201  NumWarningsInPreamble = getDiagnostics().getNumWarnings();
1202
1203  // Keep track of all of the files that the source manager knows about,
1204  // so we can verify whether they have changed or not.
1205  FilesInPreamble.clear();
1206  SourceManager &SourceMgr = Clang.getSourceManager();
1207  const llvm::MemoryBuffer *MainFileBuffer
1208    = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1209  for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1210                                     FEnd = SourceMgr.fileinfo_end();
1211       F != FEnd;
1212       ++F) {
1213    const FileEntry *File = F->second->Entry;
1214    if (!File || F->second->getRawBuffer() == MainFileBuffer)
1215      continue;
1216
1217    FilesInPreamble[File->getName()]
1218      = std::make_pair(F->second->getSize(), File->getModificationTime());
1219  }
1220
1221  if (PreambleTimer)
1222    PreambleTimer->stopTimer();
1223
1224  PreambleRebuildCounter = 1;
1225  return CreatePaddedMainFileBuffer(NewPreamble.first,
1226                                    CreatedPreambleBuffer,
1227                                    PreambleReservedSize,
1228                                    FrontendOpts.Inputs[0].second);
1229}
1230
1231void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1232  std::vector<Decl *> Resolved;
1233  Resolved.reserve(TopLevelDeclsInPreamble.size());
1234  ExternalASTSource &Source = *getASTContext().getExternalSource();
1235  for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1236    // Resolve the declaration ID to an actual declaration, possibly
1237    // deserializing the declaration in the process.
1238    Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1239    if (D)
1240      Resolved.push_back(D);
1241  }
1242  TopLevelDeclsInPreamble.clear();
1243  TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1244}
1245
1246unsigned ASTUnit::getMaxPCHLevel() const {
1247  if (!getOnlyLocalDecls())
1248    return Decl::MaxPCHLevel;
1249
1250  unsigned Result = 0;
1251  if (isMainFileAST() || SavedMainFileBuffer)
1252    ++Result;
1253  return Result;
1254}
1255
1256ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
1257                                   llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
1258                                             bool OnlyLocalDecls,
1259                                             bool CaptureDiagnostics,
1260                                             bool PrecompilePreamble,
1261                                             bool CompleteTranslationUnit,
1262                                             bool CacheCodeCompletionResults) {
1263  if (!Diags.getPtr()) {
1264    // No diagnostics engine was provided, so create our own diagnostics object
1265    // with the default options.
1266    DiagnosticOptions DiagOpts;
1267    Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
1268  }
1269
1270  // Create the AST unit.
1271  llvm::OwningPtr<ASTUnit> AST;
1272  AST.reset(new ASTUnit(false));
1273  AST->Diagnostics = Diags;
1274  AST->CaptureDiagnostics = CaptureDiagnostics;
1275  AST->OnlyLocalDecls = OnlyLocalDecls;
1276  AST->CompleteTranslationUnit = CompleteTranslationUnit;
1277  AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1278  AST->Invocation.reset(CI);
1279  CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1280
1281  if (getenv("LIBCLANG_TIMING"))
1282    AST->TimerGroup.reset(
1283                  new llvm::TimerGroup(CI->getFrontendOpts().Inputs[0].second));
1284
1285
1286  llvm::MemoryBuffer *OverrideMainBuffer = 0;
1287  // FIXME: When C++ PCH is ready, allow use of it for a precompiled preamble.
1288  if (PrecompilePreamble && !CI->getLangOpts().CPlusPlus) {
1289    AST->PreambleRebuildCounter = 1;
1290    OverrideMainBuffer = AST->getMainBufferWithPrecompiledPreamble();
1291  }
1292
1293  llvm::Timer *ParsingTimer = 0;
1294  if (AST->TimerGroup.get()) {
1295    ParsingTimer = new llvm::Timer("Initial parse", *AST->TimerGroup);
1296    ParsingTimer->startTimer();
1297    AST->Timers.push_back(ParsingTimer);
1298  }
1299
1300  bool Failed = AST->Parse(OverrideMainBuffer);
1301  if (ParsingTimer)
1302    ParsingTimer->stopTimer();
1303
1304  return Failed? 0 : AST.take();
1305}
1306
1307ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1308                                      const char **ArgEnd,
1309                                    llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
1310                                      llvm::StringRef ResourceFilesPath,
1311                                      bool OnlyLocalDecls,
1312                                      RemappedFile *RemappedFiles,
1313                                      unsigned NumRemappedFiles,
1314                                      bool CaptureDiagnostics,
1315                                      bool PrecompilePreamble,
1316                                      bool CompleteTranslationUnit,
1317                                      bool CacheCodeCompletionResults) {
1318  if (!Diags.getPtr()) {
1319    // No diagnostics engine was provided, so create our own diagnostics object
1320    // with the default options.
1321    DiagnosticOptions DiagOpts;
1322    Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
1323  }
1324
1325  llvm::SmallVector<const char *, 16> Args;
1326  Args.push_back("<clang>"); // FIXME: Remove dummy argument.
1327  Args.insert(Args.end(), ArgBegin, ArgEnd);
1328
1329  // FIXME: Find a cleaner way to force the driver into restricted modes. We
1330  // also want to force it to use clang.
1331  Args.push_back("-fsyntax-only");
1332
1333  // FIXME: We shouldn't have to pass in the path info.
1334  driver::Driver TheDriver("clang", llvm::sys::getHostTriple(),
1335                           "a.out", false, false, *Diags);
1336
1337  // Don't check that inputs exist, they have been remapped.
1338  TheDriver.setCheckInputsExist(false);
1339
1340  llvm::OwningPtr<driver::Compilation> C(
1341    TheDriver.BuildCompilation(Args.size(), Args.data()));
1342
1343  // We expect to get back exactly one command job, if we didn't something
1344  // failed.
1345  const driver::JobList &Jobs = C->getJobs();
1346  if (Jobs.size() != 1 || !isa<driver::Command>(Jobs.begin())) {
1347    llvm::SmallString<256> Msg;
1348    llvm::raw_svector_ostream OS(Msg);
1349    C->PrintJob(OS, C->getJobs(), "; ", true);
1350    Diags->Report(diag::err_fe_expected_compiler_job) << OS.str();
1351    return 0;
1352  }
1353
1354  const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
1355  if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
1356    Diags->Report(diag::err_fe_expected_clang_command);
1357    return 0;
1358  }
1359
1360  const driver::ArgStringList &CCArgs = Cmd->getArguments();
1361  llvm::OwningPtr<CompilerInvocation> CI(new CompilerInvocation);
1362  CompilerInvocation::CreateFromArgs(*CI,
1363                                     const_cast<const char **>(CCArgs.data()),
1364                                     const_cast<const char **>(CCArgs.data()) +
1365                                     CCArgs.size(),
1366                                     *Diags);
1367
1368  // Override any files that need remapping
1369  for (unsigned I = 0; I != NumRemappedFiles; ++I)
1370    CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1371                                              RemappedFiles[I].second);
1372
1373  // Override the resources path.
1374  CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1375
1376  CI->getFrontendOpts().DisableFree = true;
1377  return LoadFromCompilerInvocation(CI.take(), Diags, OnlyLocalDecls,
1378                                    CaptureDiagnostics, PrecompilePreamble,
1379                                    CompleteTranslationUnit,
1380                                    CacheCodeCompletionResults);
1381}
1382
1383bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
1384  if (!Invocation.get())
1385    return true;
1386
1387  llvm::Timer *ReparsingTimer = 0;
1388  if (TimerGroup.get()) {
1389    ReparsingTimer = new llvm::Timer("Reparse", *TimerGroup);
1390    ReparsingTimer->startTimer();
1391    Timers.push_back(ReparsingTimer);
1392  }
1393
1394  // Remap files.
1395  Invocation->getPreprocessorOpts().clearRemappedFiles();
1396  for (unsigned I = 0; I != NumRemappedFiles; ++I)
1397    Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1398                                                      RemappedFiles[I].second);
1399
1400  // If we have a preamble file lying around, or if we might try to
1401  // build a precompiled preamble, do so now.
1402  llvm::MemoryBuffer *OverrideMainBuffer = 0;
1403  if (!PreambleFile.empty() || PreambleRebuildCounter > 0)
1404    OverrideMainBuffer = getMainBufferWithPrecompiledPreamble();
1405
1406  // Clear out the diagnostics state.
1407  if (!OverrideMainBuffer)
1408    getDiagnostics().Reset();
1409
1410  // Parse the sources
1411  bool Result = Parse(OverrideMainBuffer);
1412  if (ReparsingTimer)
1413    ReparsingTimer->stopTimer();
1414  return Result;
1415}
1416
1417//----------------------------------------------------------------------------//
1418// Code completion
1419//----------------------------------------------------------------------------//
1420
1421namespace {
1422  /// \brief Code completion consumer that combines the cached code-completion
1423  /// results from an ASTUnit with the code-completion results provided to it,
1424  /// then passes the result on to
1425  class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
1426    unsigned NormalContexts;
1427    ASTUnit &AST;
1428    CodeCompleteConsumer &Next;
1429
1430  public:
1431    AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
1432                                  bool IncludeMacros, bool IncludeCodePatterns,
1433                                  bool IncludeGlobals)
1434      : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
1435                             Next.isOutputBinary()), AST(AST), Next(Next)
1436    {
1437      // Compute the set of contexts in which we will look when we don't have
1438      // any information about the specific context.
1439      NormalContexts
1440        = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
1441        | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
1442        | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
1443        | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
1444        | (1 << (CodeCompletionContext::CCC_Statement - 1))
1445        | (1 << (CodeCompletionContext::CCC_Expression - 1))
1446        | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
1447        | (1 << (CodeCompletionContext::CCC_MemberAccess - 1))
1448        | (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
1449
1450      if (AST.getASTContext().getLangOptions().CPlusPlus)
1451        NormalContexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1))
1452                    | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
1453                    | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
1454    }
1455
1456    virtual void ProcessCodeCompleteResults(Sema &S,
1457                                            CodeCompletionContext Context,
1458                                            Result *Results,
1459                                            unsigned NumResults);
1460
1461    virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1462                                           OverloadCandidate *Candidates,
1463                                           unsigned NumCandidates) {
1464      Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
1465    }
1466  };
1467}
1468
1469/// \brief Helper function that computes which global names are hidden by the
1470/// local code-completion results.
1471void CalculateHiddenNames(const CodeCompletionContext &Context,
1472                          CodeCompleteConsumer::Result *Results,
1473                          unsigned NumResults,
1474                          ASTContext &Ctx,
1475                          llvm::StringSet<> &HiddenNames) {
1476  bool OnlyTagNames = false;
1477  switch (Context.getKind()) {
1478  case CodeCompletionContext::CCC_Other:
1479  case CodeCompletionContext::CCC_TopLevel:
1480  case CodeCompletionContext::CCC_ObjCInterface:
1481  case CodeCompletionContext::CCC_ObjCImplementation:
1482  case CodeCompletionContext::CCC_ObjCIvarList:
1483  case CodeCompletionContext::CCC_ClassStructUnion:
1484  case CodeCompletionContext::CCC_Statement:
1485  case CodeCompletionContext::CCC_Expression:
1486  case CodeCompletionContext::CCC_ObjCMessageReceiver:
1487  case CodeCompletionContext::CCC_MemberAccess:
1488  case CodeCompletionContext::CCC_Namespace:
1489  case CodeCompletionContext::CCC_Type:
1490    break;
1491
1492  case CodeCompletionContext::CCC_EnumTag:
1493  case CodeCompletionContext::CCC_UnionTag:
1494  case CodeCompletionContext::CCC_ClassOrStructTag:
1495    OnlyTagNames = true;
1496    break;
1497
1498  case CodeCompletionContext::CCC_ObjCProtocolName:
1499    // If we're just looking for protocol names, nothing can hide them.
1500    return;
1501  }
1502
1503  typedef CodeCompleteConsumer::Result Result;
1504  for (unsigned I = 0; I != NumResults; ++I) {
1505    if (Results[I].Kind != Result::RK_Declaration)
1506      continue;
1507
1508    unsigned IDNS
1509      = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
1510
1511    bool Hiding = false;
1512    if (OnlyTagNames)
1513      Hiding = (IDNS & Decl::IDNS_Tag);
1514    else {
1515      unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
1516                             Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
1517                             Decl::IDNS_NonMemberOperator);
1518      if (Ctx.getLangOptions().CPlusPlus)
1519        HiddenIDNS |= Decl::IDNS_Tag;
1520      Hiding = (IDNS & HiddenIDNS);
1521    }
1522
1523    if (!Hiding)
1524      continue;
1525
1526    DeclarationName Name = Results[I].Declaration->getDeclName();
1527    if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
1528      HiddenNames.insert(Identifier->getName());
1529    else
1530      HiddenNames.insert(Name.getAsString());
1531  }
1532}
1533
1534
1535void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
1536                                            CodeCompletionContext Context,
1537                                            Result *Results,
1538                                            unsigned NumResults) {
1539  // Merge the results we were given with the results we cached.
1540  bool AddedResult = false;
1541  unsigned InContexts
1542    = (Context.getKind() == CodeCompletionContext::CCC_Other? NormalContexts
1543                                            : (1 << (Context.getKind() - 1)));
1544
1545  // Contains the set of names that are hidden by "local" completion results.
1546  llvm::StringSet<> HiddenNames;
1547
1548  typedef CodeCompleteConsumer::Result Result;
1549  llvm::SmallVector<Result, 8> AllResults;
1550  for (ASTUnit::cached_completion_iterator
1551            C = AST.cached_completion_begin(),
1552         CEnd = AST.cached_completion_end();
1553       C != CEnd; ++C) {
1554    // If the context we are in matches any of the contexts we are
1555    // interested in, we'll add this result.
1556    if ((C->ShowInContexts & InContexts) == 0)
1557      continue;
1558
1559    // If we haven't added any results previously, do so now.
1560    if (!AddedResult) {
1561      CalculateHiddenNames(Context, Results, NumResults, S.Context,
1562                           HiddenNames);
1563      AllResults.insert(AllResults.end(), Results, Results + NumResults);
1564      AddedResult = true;
1565    }
1566
1567    // Determine whether this global completion result is hidden by a local
1568    // completion result. If so, skip it.
1569    if (C->Kind != CXCursor_MacroDefinition &&
1570        HiddenNames.count(C->Completion->getTypedText()))
1571      continue;
1572
1573    // Adjust priority based on similar type classes.
1574    unsigned Priority = C->Priority;
1575    if (!Context.getPreferredType().isNull()) {
1576      if (C->Kind == CXCursor_MacroDefinition) {
1577        Priority = getMacroUsagePriority(C->Completion->getTypedText(),
1578                               Context.getPreferredType()->isAnyPointerType());
1579      } else if (C->Type) {
1580        CanQualType Expected
1581          = S.Context.getCanonicalType(
1582                               Context.getPreferredType().getUnqualifiedType());
1583        SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
1584        if (ExpectedSTC == C->TypeClass) {
1585          // We know this type is similar; check for an exact match.
1586          llvm::StringMap<unsigned> &CachedCompletionTypes
1587            = AST.getCachedCompletionTypes();
1588          llvm::StringMap<unsigned>::iterator Pos
1589            = CachedCompletionTypes.find(QualType(Expected).getAsString());
1590          if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
1591            Priority /= CCF_ExactTypeMatch;
1592          else
1593            Priority /= CCF_SimilarTypeMatch;
1594        }
1595      }
1596    }
1597
1598    AllResults.push_back(Result(C->Completion, Priority, C->Kind));
1599  }
1600
1601  // If we did not add any cached completion results, just forward the
1602  // results we were given to the next consumer.
1603  if (!AddedResult) {
1604    Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
1605    return;
1606  }
1607
1608  Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
1609                                  AllResults.size());
1610}
1611
1612
1613
1614void ASTUnit::CodeComplete(llvm::StringRef File, unsigned Line, unsigned Column,
1615                           RemappedFile *RemappedFiles,
1616                           unsigned NumRemappedFiles,
1617                           bool IncludeMacros,
1618                           bool IncludeCodePatterns,
1619                           CodeCompleteConsumer &Consumer,
1620                           Diagnostic &Diag, LangOptions &LangOpts,
1621                           SourceManager &SourceMgr, FileManager &FileMgr,
1622                   llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics) {
1623  if (!Invocation.get())
1624    return;
1625
1626  llvm::Timer *CompletionTimer = 0;
1627  if (TimerGroup.get()) {
1628    llvm::SmallString<128> TimerName;
1629    llvm::raw_svector_ostream TimerNameOut(TimerName);
1630    TimerNameOut << "Code completion @ " << File << ":" << Line << ":"
1631                 << Column;
1632    CompletionTimer = new llvm::Timer(TimerNameOut.str(), *TimerGroup);
1633    CompletionTimer->startTimer();
1634    Timers.push_back(CompletionTimer);
1635  }
1636
1637  CompilerInvocation CCInvocation(*Invocation);
1638  FrontendOptions &FrontendOpts = CCInvocation.getFrontendOpts();
1639  PreprocessorOptions &PreprocessorOpts = CCInvocation.getPreprocessorOpts();
1640
1641  FrontendOpts.ShowMacrosInCodeCompletion
1642    = IncludeMacros && CachedCompletionResults.empty();
1643  FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
1644  FrontendOpts.ShowGlobalSymbolsInCodeCompletion
1645    = CachedCompletionResults.empty();
1646  FrontendOpts.CodeCompletionAt.FileName = File;
1647  FrontendOpts.CodeCompletionAt.Line = Line;
1648  FrontendOpts.CodeCompletionAt.Column = Column;
1649
1650  // Turn on spell-checking when performing code completion. It leads
1651  // to better results.
1652  unsigned SpellChecking = CCInvocation.getLangOpts().SpellChecking;
1653  CCInvocation.getLangOpts().SpellChecking = 1;
1654
1655  // Set the language options appropriately.
1656  LangOpts = CCInvocation.getLangOpts();
1657
1658  CompilerInstance Clang;
1659  Clang.setInvocation(&CCInvocation);
1660  OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1661
1662  // Set up diagnostics, capturing any diagnostics produced.
1663  Clang.setDiagnostics(&Diag);
1664  CaptureDroppedDiagnostics Capture(true,
1665                                    Clang.getDiagnostics(),
1666                                    StoredDiagnostics);
1667  Clang.setDiagnosticClient(Diag.getClient());
1668
1669  // Create the target instance.
1670  Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1671                                               Clang.getTargetOpts()));
1672  if (!Clang.hasTarget()) {
1673    Clang.takeDiagnosticClient();
1674    Clang.takeInvocation();
1675  }
1676
1677  // Inform the target of the language options.
1678  //
1679  // FIXME: We shouldn't need to do this, the target should be immutable once
1680  // created. This complexity should be lifted elsewhere.
1681  Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1682
1683  assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1684         "Invocation must have exactly one source file!");
1685  assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1686         "FIXME: AST inputs not yet supported here!");
1687  assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1688         "IR inputs not support here!");
1689
1690
1691  // Use the source and file managers that we were given.
1692  Clang.setFileManager(&FileMgr);
1693  Clang.setSourceManager(&SourceMgr);
1694
1695  // Remap files.
1696  PreprocessorOpts.clearRemappedFiles();
1697  PreprocessorOpts.RetainRemappedFileBuffers = true;
1698  for (unsigned I = 0; I != NumRemappedFiles; ++I)
1699    PreprocessorOpts.addRemappedFile(RemappedFiles[I].first,
1700                                     RemappedFiles[I].second);
1701
1702  // Use the code completion consumer we were given, but adding any cached
1703  // code-completion results.
1704  AugmentedCodeCompleteConsumer
1705  AugmentedConsumer(*this, Consumer, FrontendOpts.ShowMacrosInCodeCompletion,
1706                    FrontendOpts.ShowCodePatternsInCodeCompletion,
1707                    FrontendOpts.ShowGlobalSymbolsInCodeCompletion);
1708  Clang.setCodeCompletionConsumer(&AugmentedConsumer);
1709
1710  // If we have a precompiled preamble, try to use it. We only allow
1711  // the use of the precompiled preamble if we're if the completion
1712  // point is within the main file, after the end of the precompiled
1713  // preamble.
1714  llvm::MemoryBuffer *OverrideMainBuffer = 0;
1715  if (!PreambleFile.empty()) {
1716    using llvm::sys::FileStatus;
1717    llvm::sys::PathWithStatus CompleteFilePath(File);
1718    llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
1719    if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
1720      if (const FileStatus *MainStatus = MainPath.getFileStatus())
1721        if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID())
1722          OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(false,
1723                                                                    Line);
1724  }
1725
1726  // If the main file has been overridden due to the use of a preamble,
1727  // make that override happen and introduce the preamble.
1728  if (OverrideMainBuffer) {
1729    PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1730    PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1731    PreprocessorOpts.PrecompiledPreambleBytes.second
1732                                                    = PreambleEndsAtStartOfLine;
1733    PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
1734    PreprocessorOpts.DisablePCHValidation = true;
1735
1736    // The stored diagnostics have the old source manager. Copy them
1737    // to our output set of stored diagnostics, updating the source
1738    // manager to the one we were given.
1739    for (unsigned I = 0, N = this->StoredDiagnostics.size(); I != N; ++I) {
1740      StoredDiagnostics.push_back(this->StoredDiagnostics[I]);
1741      FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SourceMgr);
1742      StoredDiagnostics[I].setLocation(Loc);
1743    }
1744  }
1745
1746  llvm::OwningPtr<SyntaxOnlyAction> Act;
1747  Act.reset(new SyntaxOnlyAction);
1748  if (Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1749                           Clang.getFrontendOpts().Inputs[0].first)) {
1750    Act->Execute();
1751    Act->EndSourceFile();
1752  }
1753
1754  if (CompletionTimer)
1755    CompletionTimer->stopTimer();
1756
1757  // Steal back our resources.
1758  delete OverrideMainBuffer;
1759  Clang.takeFileManager();
1760  Clang.takeSourceManager();
1761  Clang.takeInvocation();
1762  Clang.takeDiagnosticClient();
1763  Clang.takeCodeCompletionConsumer();
1764  CCInvocation.getLangOpts().SpellChecking = SpellChecking;
1765}
1766
1767bool ASTUnit::Save(llvm::StringRef File) {
1768  if (getDiagnostics().hasErrorOccurred())
1769    return true;
1770
1771  // FIXME: Can we somehow regenerate the stat cache here, or do we need to
1772  // unconditionally create a stat cache when we parse the file?
1773  std::string ErrorInfo;
1774  llvm::raw_fd_ostream Out(File.str().c_str(), ErrorInfo,
1775                           llvm::raw_fd_ostream::F_Binary);
1776  if (!ErrorInfo.empty() || Out.has_error())
1777    return true;
1778
1779  std::vector<unsigned char> Buffer;
1780  llvm::BitstreamWriter Stream(Buffer);
1781  PCHWriter Writer(Stream);
1782  Writer.WritePCH(getSema(), 0, 0);
1783
1784  // Write the generated bitstream to "Out".
1785  Out.write((char *)&Buffer.front(), Buffer.size());
1786  Out.close();
1787  return Out.has_error();
1788}
1789