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