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