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