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