ASTUnit.cpp revision 01a429a1029dd650ed11cc35160451664f664df3
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 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_ObjCInterfaceName - 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  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(StringRef Triple) {
400    TargetTriple = Triple;
401    return false;
402  }
403
404  virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
405                                    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  SmallVectorImpl<StoredDiagnostic> &StoredDiags;
426
427public:
428  explicit StoredDiagnosticClient(
429                          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                          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(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 = 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                                         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                             StringRef isysroot, 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                                         StringRef InFile) {
832    std::string Sysroot;
833    std::string OutputFile;
834    raw_ostream *OS = 0;
835    bool Chaining;
836    if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
837                                                       OutputFile,
838                                                       OS, Chaining))
839      return 0;
840
841    if (!CI.getFrontendOpts().RelocatablePCH)
842      Sysroot.clear();
843
844    CI.getPreprocessor().addPPCallbacks(
845     new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
846    return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Chaining,
847                                          Sysroot, OS);
848  }
849
850  virtual bool hasCodeCompletionSupport() const { return false; }
851  virtual bool hasASTFileSupport() const { return false; }
852  virtual bool usesCompleteTranslationUnit() { return false; }
853};
854
855}
856
857/// Parse the source file into a translation unit using the given compiler
858/// invocation, replacing the current translation unit.
859///
860/// \returns True if a failure occurred that causes the ASTUnit not to
861/// contain any translation-unit information, false otherwise.
862bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
863  delete SavedMainFileBuffer;
864  SavedMainFileBuffer = 0;
865
866  if (!Invocation) {
867    delete OverrideMainBuffer;
868    return true;
869  }
870
871  // Create the compiler instance to use for building the AST.
872  llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
873
874  // Recover resources if we crash before exiting this method.
875  llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
876    CICleanup(Clang.get());
877
878  Clang->setInvocation(&*Invocation);
879  OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
880
881  // Set up diagnostics, capturing any diagnostics that would
882  // otherwise be dropped.
883  Clang->setDiagnostics(&getDiagnostics());
884
885  // Create the target instance.
886  Clang->getTargetOpts().Features = TargetFeatures;
887  Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
888                   Clang->getTargetOpts()));
889  if (!Clang->hasTarget()) {
890    delete OverrideMainBuffer;
891    return true;
892  }
893
894  // Inform the target of the language options.
895  //
896  // FIXME: We shouldn't need to do this, the target should be immutable once
897  // created. This complexity should be lifted elsewhere.
898  Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
899
900  assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
901         "Invocation must have exactly one source file!");
902  assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
903         "FIXME: AST inputs not yet supported here!");
904  assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
905         "IR inputs not support here!");
906
907  // Configure the various subsystems.
908  // FIXME: Should we retain the previous file manager?
909  FileSystemOpts = Clang->getFileSystemOpts();
910  FileMgr = new FileManager(FileSystemOpts);
911  SourceMgr = new SourceManager(getDiagnostics(), *FileMgr);
912  TheSema.reset();
913  Ctx = 0;
914  PP = 0;
915
916  // Clear out old caches and data.
917  TopLevelDecls.clear();
918  PreprocessedEntities.clear();
919  CleanTemporaryFiles();
920  PreprocessedEntitiesByFile.clear();
921
922  if (!OverrideMainBuffer) {
923    StoredDiagnostics.erase(
924                    StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
925                            StoredDiagnostics.end());
926    TopLevelDeclsInPreamble.clear();
927    PreprocessedEntitiesInPreamble.clear();
928  }
929
930  // Create a file manager object to provide access to and cache the filesystem.
931  Clang->setFileManager(&getFileManager());
932
933  // Create the source manager.
934  Clang->setSourceManager(&getSourceManager());
935
936  // If the main file has been overridden due to the use of a preamble,
937  // make that override happen and introduce the preamble.
938  PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
939  PreprocessorOpts.DetailedRecordIncludesNestedMacroExpansions
940    = NestedMacroExpansions;
941  std::string PriorImplicitPCHInclude;
942  if (OverrideMainBuffer) {
943    PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
944    PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
945    PreprocessorOpts.PrecompiledPreambleBytes.second
946                                                    = PreambleEndsAtStartOfLine;
947    PriorImplicitPCHInclude = PreprocessorOpts.ImplicitPCHInclude;
948    PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
949    PreprocessorOpts.DisablePCHValidation = true;
950
951    // The stored diagnostic has the old source manager in it; update
952    // the locations to refer into the new source manager. Since we've
953    // been careful to make sure that the source manager's state
954    // before and after are identical, so that we can reuse the source
955    // location itself.
956    for (unsigned I = NumStoredDiagnosticsFromDriver,
957                  N = StoredDiagnostics.size();
958         I < N; ++I) {
959      FullSourceLoc Loc(StoredDiagnostics[I].getLocation(),
960                        getSourceManager());
961      StoredDiagnostics[I].setLocation(Loc);
962    }
963
964    // Keep track of the override buffer;
965    SavedMainFileBuffer = OverrideMainBuffer;
966  } else {
967    PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
968    PreprocessorOpts.PrecompiledPreambleBytes.second = false;
969  }
970
971  llvm::OwningPtr<TopLevelDeclTrackerAction> Act(
972    new TopLevelDeclTrackerAction(*this));
973
974  // Recover resources if we crash before exiting this method.
975  llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
976    ActCleanup(Act.get());
977
978  if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
979                            Clang->getFrontendOpts().Inputs[0].first))
980    goto error;
981
982  if (OverrideMainBuffer) {
983    std::string ModName = PreambleFile;
984    TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
985                               getSourceManager(), PreambleDiagnostics,
986                               StoredDiagnostics);
987  }
988
989  Act->Execute();
990
991  // Steal the created target, context, and preprocessor.
992  TheSema.reset(Clang->takeSema());
993  Consumer.reset(Clang->takeASTConsumer());
994  Ctx = &Clang->getASTContext();
995  PP = &Clang->getPreprocessor();
996  Clang->setSourceManager(0);
997  Clang->setFileManager(0);
998  Target = &Clang->getTarget();
999
1000  Act->EndSourceFile();
1001
1002  // Remove the overridden buffer we used for the preamble.
1003  if (OverrideMainBuffer) {
1004    PreprocessorOpts.eraseRemappedFile(
1005                               PreprocessorOpts.remapped_file_buffer_end() - 1);
1006    PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
1007  }
1008
1009  return false;
1010
1011error:
1012  // Remove the overridden buffer we used for the preamble.
1013  if (OverrideMainBuffer) {
1014    PreprocessorOpts.eraseRemappedFile(
1015                               PreprocessorOpts.remapped_file_buffer_end() - 1);
1016    PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
1017    delete OverrideMainBuffer;
1018    SavedMainFileBuffer = 0;
1019  }
1020
1021  StoredDiagnostics.clear();
1022  return true;
1023}
1024
1025/// \brief Simple function to retrieve a path for a preamble precompiled header.
1026static std::string GetPreamblePCHPath() {
1027  // FIXME: This is lame; sys::Path should provide this function (in particular,
1028  // it should know how to find the temporary files dir).
1029  // FIXME: This is really lame. I copied this code from the Driver!
1030  // FIXME: This is a hack so that we can override the preamble file during
1031  // crash-recovery testing, which is the only case where the preamble files
1032  // are not necessarily cleaned up.
1033  const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1034  if (TmpFile)
1035    return TmpFile;
1036
1037  std::string Error;
1038  const char *TmpDir = ::getenv("TMPDIR");
1039  if (!TmpDir)
1040    TmpDir = ::getenv("TEMP");
1041  if (!TmpDir)
1042    TmpDir = ::getenv("TMP");
1043#ifdef LLVM_ON_WIN32
1044  if (!TmpDir)
1045    TmpDir = ::getenv("USERPROFILE");
1046#endif
1047  if (!TmpDir)
1048    TmpDir = "/tmp";
1049  llvm::sys::Path P(TmpDir);
1050  P.createDirectoryOnDisk(true);
1051  P.appendComponent("preamble");
1052  P.appendSuffix("pch");
1053  if (P.makeUnique(/*reuse_current=*/false, /*ErrMsg*/0))
1054    return std::string();
1055
1056  return P.str();
1057}
1058
1059/// \brief Compute the preamble for the main file, providing the source buffer
1060/// that corresponds to the main file along with a pair (bytes, start-of-line)
1061/// that describes the preamble.
1062std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
1063ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
1064                         unsigned MaxLines, bool &CreatedBuffer) {
1065  FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
1066  PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
1067  CreatedBuffer = false;
1068
1069  // Try to determine if the main file has been remapped, either from the
1070  // command line (to another file) or directly through the compiler invocation
1071  // (to a memory buffer).
1072  llvm::MemoryBuffer *Buffer = 0;
1073  llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
1074  if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
1075    // Check whether there is a file-file remapping of the main file
1076    for (PreprocessorOptions::remapped_file_iterator
1077          M = PreprocessorOpts.remapped_file_begin(),
1078          E = PreprocessorOpts.remapped_file_end();
1079         M != E;
1080         ++M) {
1081      llvm::sys::PathWithStatus MPath(M->first);
1082      if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1083        if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1084          // We found a remapping. Try to load the resulting, remapped source.
1085          if (CreatedBuffer) {
1086            delete Buffer;
1087            CreatedBuffer = false;
1088          }
1089
1090          Buffer = getBufferForFile(M->second);
1091          if (!Buffer)
1092            return std::make_pair((llvm::MemoryBuffer*)0,
1093                                  std::make_pair(0, true));
1094          CreatedBuffer = true;
1095        }
1096      }
1097    }
1098
1099    // Check whether there is a file-buffer remapping. It supercedes the
1100    // file-file remapping.
1101    for (PreprocessorOptions::remapped_file_buffer_iterator
1102           M = PreprocessorOpts.remapped_file_buffer_begin(),
1103           E = PreprocessorOpts.remapped_file_buffer_end();
1104         M != E;
1105         ++M) {
1106      llvm::sys::PathWithStatus MPath(M->first);
1107      if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1108        if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1109          // We found a remapping.
1110          if (CreatedBuffer) {
1111            delete Buffer;
1112            CreatedBuffer = false;
1113          }
1114
1115          Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
1116        }
1117      }
1118    }
1119  }
1120
1121  // If the main source file was not remapped, load it now.
1122  if (!Buffer) {
1123    Buffer = getBufferForFile(FrontendOpts.Inputs[0].second);
1124    if (!Buffer)
1125      return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
1126
1127    CreatedBuffer = true;
1128  }
1129
1130  return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer, MaxLines));
1131}
1132
1133static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
1134                                                      unsigned NewSize,
1135                                                      StringRef NewName) {
1136  llvm::MemoryBuffer *Result
1137    = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
1138  memcpy(const_cast<char*>(Result->getBufferStart()),
1139         Old->getBufferStart(), Old->getBufferSize());
1140  memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
1141         ' ', NewSize - Old->getBufferSize() - 1);
1142  const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
1143
1144  return Result;
1145}
1146
1147/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1148/// the source file.
1149///
1150/// This routine will compute the preamble of the main source file. If a
1151/// non-trivial preamble is found, it will precompile that preamble into a
1152/// precompiled header so that the precompiled preamble can be used to reduce
1153/// reparsing time. If a precompiled preamble has already been constructed,
1154/// this routine will determine if it is still valid and, if so, avoid
1155/// rebuilding the precompiled preamble.
1156///
1157/// \param AllowRebuild When true (the default), this routine is
1158/// allowed to rebuild the precompiled preamble if it is found to be
1159/// out-of-date.
1160///
1161/// \param MaxLines When non-zero, the maximum number of lines that
1162/// can occur within the preamble.
1163///
1164/// \returns If the precompiled preamble can be used, returns a newly-allocated
1165/// buffer that should be used in place of the main file when doing so.
1166/// Otherwise, returns a NULL pointer.
1167llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
1168                              const CompilerInvocation &PreambleInvocationIn,
1169                                                           bool AllowRebuild,
1170                                                           unsigned MaxLines) {
1171
1172  llvm::IntrusiveRefCntPtr<CompilerInvocation>
1173    PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1174  FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
1175  PreprocessorOptions &PreprocessorOpts
1176    = PreambleInvocation->getPreprocessorOpts();
1177
1178  bool CreatedPreambleBuffer = false;
1179  std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
1180    = ComputePreamble(*PreambleInvocation, MaxLines, CreatedPreambleBuffer);
1181
1182  // If ComputePreamble() Take ownership of the preamble buffer.
1183  llvm::OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
1184  if (CreatedPreambleBuffer)
1185    OwnedPreambleBuffer.reset(NewPreamble.first);
1186
1187  if (!NewPreamble.second.first) {
1188    // We couldn't find a preamble in the main source. Clear out the current
1189    // preamble, if we have one. It's obviously no good any more.
1190    Preamble.clear();
1191    if (!PreambleFile.empty()) {
1192      llvm::sys::Path(PreambleFile).eraseFromDisk();
1193      PreambleFile.clear();
1194    }
1195
1196    // The next time we actually see a preamble, precompile it.
1197    PreambleRebuildCounter = 1;
1198    return 0;
1199  }
1200
1201  if (!Preamble.empty()) {
1202    // We've previously computed a preamble. Check whether we have the same
1203    // preamble now that we did before, and that there's enough space in
1204    // the main-file buffer within the precompiled preamble to fit the
1205    // new main file.
1206    if (Preamble.size() == NewPreamble.second.first &&
1207        PreambleEndsAtStartOfLine == NewPreamble.second.second &&
1208        NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
1209        memcmp(&Preamble[0], NewPreamble.first->getBufferStart(),
1210               NewPreamble.second.first) == 0) {
1211      // The preamble has not changed. We may be able to re-use the precompiled
1212      // preamble.
1213
1214      // Check that none of the files used by the preamble have changed.
1215      bool AnyFileChanged = false;
1216
1217      // First, make a record of those files that have been overridden via
1218      // remapping or unsaved_files.
1219      llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1220      for (PreprocessorOptions::remapped_file_iterator
1221                R = PreprocessorOpts.remapped_file_begin(),
1222             REnd = PreprocessorOpts.remapped_file_end();
1223           !AnyFileChanged && R != REnd;
1224           ++R) {
1225        struct stat StatBuf;
1226        if (FileMgr->getNoncachedStatValue(R->second, StatBuf)) {
1227          // If we can't stat the file we're remapping to, assume that something
1228          // horrible happened.
1229          AnyFileChanged = true;
1230          break;
1231        }
1232
1233        OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1234                                                   StatBuf.st_mtime);
1235      }
1236      for (PreprocessorOptions::remapped_file_buffer_iterator
1237                R = PreprocessorOpts.remapped_file_buffer_begin(),
1238             REnd = PreprocessorOpts.remapped_file_buffer_end();
1239           !AnyFileChanged && R != REnd;
1240           ++R) {
1241        // FIXME: Should we actually compare the contents of file->buffer
1242        // remappings?
1243        OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1244                                                   0);
1245      }
1246
1247      // Check whether anything has changed.
1248      for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1249             F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1250           !AnyFileChanged && F != FEnd;
1251           ++F) {
1252        llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1253          = OverriddenFiles.find(F->first());
1254        if (Overridden != OverriddenFiles.end()) {
1255          // This file was remapped; check whether the newly-mapped file
1256          // matches up with the previous mapping.
1257          if (Overridden->second != F->second)
1258            AnyFileChanged = true;
1259          continue;
1260        }
1261
1262        // The file was not remapped; check whether it has changed on disk.
1263        struct stat StatBuf;
1264        if (FileMgr->getNoncachedStatValue(F->first(), StatBuf)) {
1265          // If we can't stat the file, assume that something horrible happened.
1266          AnyFileChanged = true;
1267        } else if (StatBuf.st_size != F->second.first ||
1268                   StatBuf.st_mtime != F->second.second)
1269          AnyFileChanged = true;
1270      }
1271
1272      if (!AnyFileChanged) {
1273        // Okay! We can re-use the precompiled preamble.
1274
1275        // Set the state of the diagnostic object to mimic its state
1276        // after parsing the preamble.
1277        // FIXME: This won't catch any #pragma push warning changes that
1278        // have occurred in the preamble.
1279        getDiagnostics().Reset();
1280        ProcessWarningOptions(getDiagnostics(),
1281                              PreambleInvocation->getDiagnosticOpts());
1282        getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1283
1284        // Create a version of the main file buffer that is padded to
1285        // buffer size we reserved when creating the preamble.
1286        return CreatePaddedMainFileBuffer(NewPreamble.first,
1287                                          PreambleReservedSize,
1288                                          FrontendOpts.Inputs[0].second);
1289      }
1290    }
1291
1292    // If we aren't allowed to rebuild the precompiled preamble, just
1293    // return now.
1294    if (!AllowRebuild)
1295      return 0;
1296
1297    // We can't reuse the previously-computed preamble. Build a new one.
1298    Preamble.clear();
1299    PreambleDiagnostics.clear();
1300    llvm::sys::Path(PreambleFile).eraseFromDisk();
1301    PreambleRebuildCounter = 1;
1302  } else if (!AllowRebuild) {
1303    // We aren't allowed to rebuild the precompiled preamble; just
1304    // return now.
1305    return 0;
1306  }
1307
1308  // If the preamble rebuild counter > 1, it's because we previously
1309  // failed to build a preamble and we're not yet ready to try
1310  // again. Decrement the counter and return a failure.
1311  if (PreambleRebuildCounter > 1) {
1312    --PreambleRebuildCounter;
1313    return 0;
1314  }
1315
1316  // Create a temporary file for the precompiled preamble. In rare
1317  // circumstances, this can fail.
1318  std::string PreamblePCHPath = GetPreamblePCHPath();
1319  if (PreamblePCHPath.empty()) {
1320    // Try again next time.
1321    PreambleRebuildCounter = 1;
1322    return 0;
1323  }
1324
1325  // We did not previously compute a preamble, or it can't be reused anyway.
1326  SimpleTimer PreambleTimer(WantTiming);
1327  PreambleTimer.setOutput("Precompiling preamble");
1328
1329  // Create a new buffer that stores the preamble. The buffer also contains
1330  // extra space for the original contents of the file (which will be present
1331  // when we actually parse the file) along with more room in case the file
1332  // grows.
1333  PreambleReservedSize = NewPreamble.first->getBufferSize();
1334  if (PreambleReservedSize < 4096)
1335    PreambleReservedSize = 8191;
1336  else
1337    PreambleReservedSize *= 2;
1338
1339  // Save the preamble text for later; we'll need to compare against it for
1340  // subsequent reparses.
1341  Preamble.assign(NewPreamble.first->getBufferStart(),
1342                  NewPreamble.first->getBufferStart()
1343                                                  + NewPreamble.second.first);
1344  PreambleEndsAtStartOfLine = NewPreamble.second.second;
1345
1346  delete PreambleBuffer;
1347  PreambleBuffer
1348    = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
1349                                                FrontendOpts.Inputs[0].second);
1350  memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
1351         NewPreamble.first->getBufferStart(), Preamble.size());
1352  memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
1353         ' ', PreambleReservedSize - Preamble.size() - 1);
1354  const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
1355
1356  // Remap the main source file to the preamble buffer.
1357  llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
1358  PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1359
1360  // Tell the compiler invocation to generate a temporary precompiled header.
1361  FrontendOpts.ProgramAction = frontend::GeneratePCH;
1362  FrontendOpts.ChainedPCH = true;
1363  // FIXME: Generate the precompiled header into memory?
1364  FrontendOpts.OutputFile = PreamblePCHPath;
1365  PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1366  PreprocessorOpts.PrecompiledPreambleBytes.second = false;
1367
1368  // Create the compiler instance to use for building the precompiled preamble.
1369  llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
1370
1371  // Recover resources if we crash before exiting this method.
1372  llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1373    CICleanup(Clang.get());
1374
1375  Clang->setInvocation(&*PreambleInvocation);
1376  OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
1377
1378  // Set up diagnostics, capturing all of the diagnostics produced.
1379  Clang->setDiagnostics(&getDiagnostics());
1380
1381  // Create the target instance.
1382  Clang->getTargetOpts().Features = TargetFeatures;
1383  Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1384                                               Clang->getTargetOpts()));
1385  if (!Clang->hasTarget()) {
1386    llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1387    Preamble.clear();
1388    PreambleRebuildCounter = DefaultPreambleRebuildInterval;
1389    PreprocessorOpts.eraseRemappedFile(
1390                               PreprocessorOpts.remapped_file_buffer_end() - 1);
1391    return 0;
1392  }
1393
1394  // Inform the target of the language options.
1395  //
1396  // FIXME: We shouldn't need to do this, the target should be immutable once
1397  // created. This complexity should be lifted elsewhere.
1398  Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
1399
1400  assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1401         "Invocation must have exactly one source file!");
1402  assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
1403         "FIXME: AST inputs not yet supported here!");
1404  assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1405         "IR inputs not support here!");
1406
1407  // Clear out old caches and data.
1408  getDiagnostics().Reset();
1409  ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
1410  StoredDiagnostics.erase(
1411                    StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
1412                          StoredDiagnostics.end());
1413  TopLevelDecls.clear();
1414  TopLevelDeclsInPreamble.clear();
1415  PreprocessedEntities.clear();
1416  PreprocessedEntitiesInPreamble.clear();
1417
1418  // Create a file manager object to provide access to and cache the filesystem.
1419  Clang->setFileManager(new FileManager(Clang->getFileSystemOpts()));
1420
1421  // Create the source manager.
1422  Clang->setSourceManager(new SourceManager(getDiagnostics(),
1423                                            Clang->getFileManager()));
1424
1425  llvm::OwningPtr<PrecompilePreambleAction> Act;
1426  Act.reset(new PrecompilePreambleAction(*this));
1427  if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
1428                            Clang->getFrontendOpts().Inputs[0].first)) {
1429    llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1430    Preamble.clear();
1431    PreambleRebuildCounter = DefaultPreambleRebuildInterval;
1432    PreprocessorOpts.eraseRemappedFile(
1433                               PreprocessorOpts.remapped_file_buffer_end() - 1);
1434    return 0;
1435  }
1436
1437  Act->Execute();
1438  Act->EndSourceFile();
1439
1440  if (Diagnostics->hasErrorOccurred()) {
1441    // There were errors parsing the preamble, so no precompiled header was
1442    // generated. Forget that we even tried.
1443    // FIXME: Should we leave a note for ourselves to try again?
1444    llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1445    Preamble.clear();
1446    TopLevelDeclsInPreamble.clear();
1447    PreprocessedEntities.clear();
1448    PreprocessedEntitiesInPreamble.clear();
1449    PreambleRebuildCounter = DefaultPreambleRebuildInterval;
1450    PreprocessorOpts.eraseRemappedFile(
1451                               PreprocessorOpts.remapped_file_buffer_end() - 1);
1452    return 0;
1453  }
1454
1455  // Transfer any diagnostics generated when parsing the preamble into the set
1456  // of preamble diagnostics.
1457  PreambleDiagnostics.clear();
1458  PreambleDiagnostics.insert(PreambleDiagnostics.end(),
1459                   StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
1460                             StoredDiagnostics.end());
1461  StoredDiagnostics.erase(
1462                    StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
1463                          StoredDiagnostics.end());
1464
1465  // Keep track of the preamble we precompiled.
1466  PreambleFile = FrontendOpts.OutputFile;
1467  NumWarningsInPreamble = getDiagnostics().getNumWarnings();
1468
1469  // Keep track of all of the files that the source manager knows about,
1470  // so we can verify whether they have changed or not.
1471  FilesInPreamble.clear();
1472  SourceManager &SourceMgr = Clang->getSourceManager();
1473  const llvm::MemoryBuffer *MainFileBuffer
1474    = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1475  for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1476                                     FEnd = SourceMgr.fileinfo_end();
1477       F != FEnd;
1478       ++F) {
1479    const FileEntry *File = F->second->OrigEntry;
1480    if (!File || F->second->getRawBuffer() == MainFileBuffer)
1481      continue;
1482
1483    FilesInPreamble[File->getName()]
1484      = std::make_pair(F->second->getSize(), File->getModificationTime());
1485  }
1486
1487  PreambleRebuildCounter = 1;
1488  PreprocessorOpts.eraseRemappedFile(
1489                               PreprocessorOpts.remapped_file_buffer_end() - 1);
1490
1491  // If the hash of top-level entities differs from the hash of the top-level
1492  // entities the last time we rebuilt the preamble, clear out the completion
1493  // cache.
1494  if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1495    CompletionCacheTopLevelHashValue = 0;
1496    PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1497  }
1498
1499  return CreatePaddedMainFileBuffer(NewPreamble.first,
1500                                    PreambleReservedSize,
1501                                    FrontendOpts.Inputs[0].second);
1502}
1503
1504void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1505  std::vector<Decl *> Resolved;
1506  Resolved.reserve(TopLevelDeclsInPreamble.size());
1507  ExternalASTSource &Source = *getASTContext().getExternalSource();
1508  for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1509    // Resolve the declaration ID to an actual declaration, possibly
1510    // deserializing the declaration in the process.
1511    Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1512    if (D)
1513      Resolved.push_back(D);
1514  }
1515  TopLevelDeclsInPreamble.clear();
1516  TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1517}
1518
1519void ASTUnit::RealizePreprocessedEntitiesFromPreamble() {
1520  if (!PP)
1521    return;
1522
1523  PreprocessingRecord *PPRec = PP->getPreprocessingRecord();
1524  if (!PPRec)
1525    return;
1526
1527  ExternalPreprocessingRecordSource *External = PPRec->getExternalSource();
1528  if (!External)
1529    return;
1530
1531  for (unsigned I = 0, N = PreprocessedEntitiesInPreamble.size(); I != N; ++I) {
1532    if (PreprocessedEntity *PE
1533          = External->ReadPreprocessedEntityAtOffset(
1534                                            PreprocessedEntitiesInPreamble[I]))
1535      PreprocessedEntities.push_back(PE);
1536  }
1537
1538  if (PreprocessedEntities.empty())
1539    return;
1540
1541  PreprocessedEntities.insert(PreprocessedEntities.end(),
1542                              PPRec->begin(true), PPRec->end(true));
1543}
1544
1545ASTUnit::pp_entity_iterator ASTUnit::pp_entity_begin() {
1546  if (!PreprocessedEntitiesInPreamble.empty() &&
1547      PreprocessedEntities.empty())
1548    RealizePreprocessedEntitiesFromPreamble();
1549
1550  return PreprocessedEntities.begin();
1551}
1552
1553ASTUnit::pp_entity_iterator ASTUnit::pp_entity_end() {
1554  if (!PreprocessedEntitiesInPreamble.empty() &&
1555      PreprocessedEntities.empty())
1556    RealizePreprocessedEntitiesFromPreamble();
1557
1558  return PreprocessedEntities.end();
1559}
1560
1561unsigned ASTUnit::getMaxPCHLevel() const {
1562  if (!getOnlyLocalDecls())
1563    return Decl::MaxPCHLevel;
1564
1565  return 0;
1566}
1567
1568StringRef ASTUnit::getMainFileName() const {
1569  return Invocation->getFrontendOpts().Inputs[0].second;
1570}
1571
1572ASTUnit *ASTUnit::create(CompilerInvocation *CI,
1573                         llvm::IntrusiveRefCntPtr<Diagnostic> Diags) {
1574  llvm::OwningPtr<ASTUnit> AST;
1575  AST.reset(new ASTUnit(false));
1576  ConfigureDiags(Diags, 0, 0, *AST, /*CaptureDiagnostics=*/false);
1577  AST->Diagnostics = Diags;
1578  AST->Invocation = CI;
1579  AST->FileSystemOpts = CI->getFileSystemOpts();
1580  AST->FileMgr = new FileManager(AST->FileSystemOpts);
1581  AST->SourceMgr = new SourceManager(*Diags, *AST->FileMgr);
1582
1583  return AST.take();
1584}
1585
1586ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(CompilerInvocation *CI,
1587                                   llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
1588                                             ASTFrontendAction *Action) {
1589  assert(CI && "A CompilerInvocation is required");
1590
1591  // Create the AST unit.
1592  llvm::OwningPtr<ASTUnit> AST;
1593  AST.reset(new ASTUnit(false));
1594  ConfigureDiags(Diags, 0, 0, *AST, /*CaptureDiagnostics*/false);
1595  AST->Diagnostics = Diags;
1596  AST->OnlyLocalDecls = false;
1597  AST->CaptureDiagnostics = false;
1598  AST->CompleteTranslationUnit = Action ? Action->usesCompleteTranslationUnit()
1599                                        : true;
1600  AST->ShouldCacheCodeCompletionResults = false;
1601  AST->Invocation = CI;
1602
1603  // Recover resources if we crash before exiting this method.
1604  llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1605    ASTUnitCleanup(AST.get());
1606  llvm::CrashRecoveryContextCleanupRegistrar<Diagnostic,
1607    llvm::CrashRecoveryContextReleaseRefCleanup<Diagnostic> >
1608    DiagCleanup(Diags.getPtr());
1609
1610  // We'll manage file buffers ourselves.
1611  CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1612  CI->getFrontendOpts().DisableFree = false;
1613  ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1614
1615  // Save the target features.
1616  AST->TargetFeatures = CI->getTargetOpts().Features;
1617
1618  // Create the compiler instance to use for building the AST.
1619  llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
1620
1621  // Recover resources if we crash before exiting this method.
1622  llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1623    CICleanup(Clang.get());
1624
1625  Clang->setInvocation(CI);
1626  AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
1627
1628  // Set up diagnostics, capturing any diagnostics that would
1629  // otherwise be dropped.
1630  Clang->setDiagnostics(&AST->getDiagnostics());
1631
1632  // Create the target instance.
1633  Clang->getTargetOpts().Features = AST->TargetFeatures;
1634  Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1635                   Clang->getTargetOpts()));
1636  if (!Clang->hasTarget())
1637    return 0;
1638
1639  // Inform the target of the language options.
1640  //
1641  // FIXME: We shouldn't need to do this, the target should be immutable once
1642  // created. This complexity should be lifted elsewhere.
1643  Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
1644
1645  assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1646         "Invocation must have exactly one source file!");
1647  assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
1648         "FIXME: AST inputs not yet supported here!");
1649  assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1650         "IR inputs not supported here!");
1651
1652  // Configure the various subsystems.
1653  AST->FileSystemOpts = Clang->getFileSystemOpts();
1654  AST->FileMgr = new FileManager(AST->FileSystemOpts);
1655  AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr);
1656  AST->TheSema.reset();
1657  AST->Ctx = 0;
1658  AST->PP = 0;
1659
1660  // Create a file manager object to provide access to and cache the filesystem.
1661  Clang->setFileManager(&AST->getFileManager());
1662
1663  // Create the source manager.
1664  Clang->setSourceManager(&AST->getSourceManager());
1665
1666  ASTFrontendAction *Act = Action;
1667
1668  llvm::OwningPtr<TopLevelDeclTrackerAction> TrackerAct;
1669  if (!Act) {
1670    TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1671    Act = TrackerAct.get();
1672  }
1673
1674  // Recover resources if we crash before exiting this method.
1675  llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1676    ActCleanup(TrackerAct.get());
1677
1678  if (!Act->BeginSourceFile(*Clang.get(),
1679                            Clang->getFrontendOpts().Inputs[0].second,
1680                            Clang->getFrontendOpts().Inputs[0].first))
1681    return 0;
1682
1683  Act->Execute();
1684
1685  // Steal the created target, context, and preprocessor.
1686  AST->TheSema.reset(Clang->takeSema());
1687  AST->Consumer.reset(Clang->takeASTConsumer());
1688  AST->Ctx = &Clang->getASTContext();
1689  AST->PP = &Clang->getPreprocessor();
1690  Clang->setSourceManager(0);
1691  Clang->setFileManager(0);
1692  AST->Target = &Clang->getTarget();
1693
1694  Act->EndSourceFile();
1695
1696  return AST.take();
1697}
1698
1699bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1700  if (!Invocation)
1701    return true;
1702
1703  // We'll manage file buffers ourselves.
1704  Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1705  Invocation->getFrontendOpts().DisableFree = false;
1706  ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1707
1708  // Save the target features.
1709  TargetFeatures = Invocation->getTargetOpts().Features;
1710
1711  llvm::MemoryBuffer *OverrideMainBuffer = 0;
1712  if (PrecompilePreamble) {
1713    PreambleRebuildCounter = 2;
1714    OverrideMainBuffer
1715      = getMainBufferWithPrecompiledPreamble(*Invocation);
1716  }
1717
1718  SimpleTimer ParsingTimer(WantTiming);
1719  ParsingTimer.setOutput("Parsing " + getMainFileName());
1720
1721  // Recover resources if we crash before exiting this method.
1722  llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1723    MemBufferCleanup(OverrideMainBuffer);
1724
1725  return Parse(OverrideMainBuffer);
1726}
1727
1728ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
1729                                   llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
1730                                             bool OnlyLocalDecls,
1731                                             bool CaptureDiagnostics,
1732                                             bool PrecompilePreamble,
1733                                             bool CompleteTranslationUnit,
1734                                             bool CacheCodeCompletionResults,
1735                                             bool NestedMacroExpansions) {
1736  // Create the AST unit.
1737  llvm::OwningPtr<ASTUnit> AST;
1738  AST.reset(new ASTUnit(false));
1739  ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
1740  AST->Diagnostics = Diags;
1741  AST->OnlyLocalDecls = OnlyLocalDecls;
1742  AST->CaptureDiagnostics = CaptureDiagnostics;
1743  AST->CompleteTranslationUnit = CompleteTranslationUnit;
1744  AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1745  AST->Invocation = CI;
1746  AST->NestedMacroExpansions = NestedMacroExpansions;
1747
1748  // Recover resources if we crash before exiting this method.
1749  llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1750    ASTUnitCleanup(AST.get());
1751  llvm::CrashRecoveryContextCleanupRegistrar<Diagnostic,
1752    llvm::CrashRecoveryContextReleaseRefCleanup<Diagnostic> >
1753    DiagCleanup(Diags.getPtr());
1754
1755  return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
1756}
1757
1758ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1759                                      const char **ArgEnd,
1760                                    llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
1761                                      StringRef ResourceFilesPath,
1762                                      bool OnlyLocalDecls,
1763                                      bool CaptureDiagnostics,
1764                                      RemappedFile *RemappedFiles,
1765                                      unsigned NumRemappedFiles,
1766                                      bool RemappedFilesKeepOriginalName,
1767                                      bool PrecompilePreamble,
1768                                      bool CompleteTranslationUnit,
1769                                      bool CacheCodeCompletionResults,
1770                                      bool CXXPrecompilePreamble,
1771                                      bool CXXChainedPCH,
1772                                      bool NestedMacroExpansions) {
1773  if (!Diags.getPtr()) {
1774    // No diagnostics engine was provided, so create our own diagnostics object
1775    // with the default options.
1776    DiagnosticOptions DiagOpts;
1777    Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd - ArgBegin,
1778                                                ArgBegin);
1779  }
1780
1781  SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
1782
1783  llvm::IntrusiveRefCntPtr<CompilerInvocation> CI;
1784
1785  {
1786
1787    CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
1788                                      StoredDiagnostics);
1789
1790    CI = clang::createInvocationFromCommandLine(
1791                                           llvm::makeArrayRef(ArgBegin, ArgEnd),
1792                                           Diags);
1793    if (!CI)
1794      return 0;
1795  }
1796
1797  // Override any files that need remapping
1798  for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1799    FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1800    if (const llvm::MemoryBuffer *
1801            memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1802      CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, memBuf);
1803    } else {
1804      const char *fname = fileOrBuf.get<const char *>();
1805      CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, fname);
1806    }
1807  }
1808  CI->getPreprocessorOpts().RemappedFilesKeepOriginalName =
1809                                                  RemappedFilesKeepOriginalName;
1810
1811  // Override the resources path.
1812  CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1813
1814  // Check whether we should precompile the preamble and/or use chained PCH.
1815  // FIXME: This is a temporary hack while we debug C++ chained PCH.
1816  if (CI->getLangOpts().CPlusPlus) {
1817    PrecompilePreamble = PrecompilePreamble && CXXPrecompilePreamble;
1818
1819    if (PrecompilePreamble && !CXXChainedPCH &&
1820        !CI->getPreprocessorOpts().ImplicitPCHInclude.empty())
1821      PrecompilePreamble = false;
1822  }
1823
1824  // Create the AST unit.
1825  llvm::OwningPtr<ASTUnit> AST;
1826  AST.reset(new ASTUnit(false));
1827  ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
1828  AST->Diagnostics = Diags;
1829
1830  AST->FileSystemOpts = CI->getFileSystemOpts();
1831  AST->FileMgr = new FileManager(AST->FileSystemOpts);
1832  AST->OnlyLocalDecls = OnlyLocalDecls;
1833  AST->CaptureDiagnostics = CaptureDiagnostics;
1834  AST->CompleteTranslationUnit = CompleteTranslationUnit;
1835  AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1836  AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
1837  AST->StoredDiagnostics.swap(StoredDiagnostics);
1838  AST->Invocation = CI;
1839  AST->NestedMacroExpansions = NestedMacroExpansions;
1840
1841  // Recover resources if we crash before exiting this method.
1842  llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1843    ASTUnitCleanup(AST.get());
1844  llvm::CrashRecoveryContextCleanupRegistrar<CompilerInvocation,
1845    llvm::CrashRecoveryContextReleaseRefCleanup<CompilerInvocation> >
1846    CICleanup(CI.getPtr());
1847  llvm::CrashRecoveryContextCleanupRegistrar<Diagnostic,
1848    llvm::CrashRecoveryContextReleaseRefCleanup<Diagnostic> >
1849    DiagCleanup(Diags.getPtr());
1850
1851  return AST->LoadFromCompilerInvocation(PrecompilePreamble) ? 0 : AST.take();
1852}
1853
1854bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
1855  if (!Invocation)
1856    return true;
1857
1858  SimpleTimer ParsingTimer(WantTiming);
1859  ParsingTimer.setOutput("Reparsing " + getMainFileName());
1860
1861  // Remap files.
1862  PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
1863  PPOpts.DisableStatCache = true;
1864  for (PreprocessorOptions::remapped_file_buffer_iterator
1865         R = PPOpts.remapped_file_buffer_begin(),
1866         REnd = PPOpts.remapped_file_buffer_end();
1867       R != REnd;
1868       ++R) {
1869    delete R->second;
1870  }
1871  Invocation->getPreprocessorOpts().clearRemappedFiles();
1872  for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1873    FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1874    if (const llvm::MemoryBuffer *
1875            memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1876      Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1877                                                        memBuf);
1878    } else {
1879      const char *fname = fileOrBuf.get<const char *>();
1880      Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1881                                                        fname);
1882    }
1883  }
1884
1885  // If we have a preamble file lying around, or if we might try to
1886  // build a precompiled preamble, do so now.
1887  llvm::MemoryBuffer *OverrideMainBuffer = 0;
1888  if (!PreambleFile.empty() || PreambleRebuildCounter > 0)
1889    OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
1890
1891  // Clear out the diagnostics state.
1892  if (!OverrideMainBuffer) {
1893    getDiagnostics().Reset();
1894    ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1895  }
1896
1897  // Parse the sources
1898  bool Result = Parse(OverrideMainBuffer);
1899
1900  // If we're caching global code-completion results, and the top-level
1901  // declarations have changed, clear out the code-completion cache.
1902  if (!Result && ShouldCacheCodeCompletionResults &&
1903      CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
1904    CacheCodeCompletionResults();
1905
1906  // We now need to clear out the completion allocator for
1907  // clang_getCursorCompletionString; it'll be recreated if necessary.
1908  CursorCompletionAllocator = 0;
1909
1910  return Result;
1911}
1912
1913//----------------------------------------------------------------------------//
1914// Code completion
1915//----------------------------------------------------------------------------//
1916
1917namespace {
1918  /// \brief Code completion consumer that combines the cached code-completion
1919  /// results from an ASTUnit with the code-completion results provided to it,
1920  /// then passes the result on to
1921  class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
1922    unsigned long long NormalContexts;
1923    ASTUnit &AST;
1924    CodeCompleteConsumer &Next;
1925
1926  public:
1927    AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
1928                                  bool IncludeMacros, bool IncludeCodePatterns,
1929                                  bool IncludeGlobals)
1930      : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
1931                             Next.isOutputBinary()), AST(AST), Next(Next)
1932    {
1933      // Compute the set of contexts in which we will look when we don't have
1934      // any information about the specific context.
1935      NormalContexts
1936        = (1LL << (CodeCompletionContext::CCC_TopLevel - 1))
1937        | (1LL << (CodeCompletionContext::CCC_ObjCInterface - 1))
1938        | (1LL << (CodeCompletionContext::CCC_ObjCImplementation - 1))
1939        | (1LL << (CodeCompletionContext::CCC_ObjCIvarList - 1))
1940        | (1LL << (CodeCompletionContext::CCC_Statement - 1))
1941        | (1LL << (CodeCompletionContext::CCC_Expression - 1))
1942        | (1LL << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
1943        | (1LL << (CodeCompletionContext::CCC_DotMemberAccess - 1))
1944        | (1LL << (CodeCompletionContext::CCC_ArrowMemberAccess - 1))
1945        | (1LL << (CodeCompletionContext::CCC_ObjCPropertyAccess - 1))
1946        | (1LL << (CodeCompletionContext::CCC_ObjCProtocolName - 1))
1947        | (1LL << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
1948        | (1LL << (CodeCompletionContext::CCC_Recovery - 1));
1949
1950      if (AST.getASTContext().getLangOptions().CPlusPlus)
1951        NormalContexts |= (1LL << (CodeCompletionContext::CCC_EnumTag - 1))
1952                   | (1LL << (CodeCompletionContext::CCC_UnionTag - 1))
1953                   | (1LL << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
1954    }
1955
1956    virtual void ProcessCodeCompleteResults(Sema &S,
1957                                            CodeCompletionContext Context,
1958                                            CodeCompletionResult *Results,
1959                                            unsigned NumResults);
1960
1961    virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1962                                           OverloadCandidate *Candidates,
1963                                           unsigned NumCandidates) {
1964      Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
1965    }
1966
1967    virtual CodeCompletionAllocator &getAllocator() {
1968      return Next.getAllocator();
1969    }
1970  };
1971}
1972
1973/// \brief Helper function that computes which global names are hidden by the
1974/// local code-completion results.
1975static void CalculateHiddenNames(const CodeCompletionContext &Context,
1976                                 CodeCompletionResult *Results,
1977                                 unsigned NumResults,
1978                                 ASTContext &Ctx,
1979                          llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
1980  bool OnlyTagNames = false;
1981  switch (Context.getKind()) {
1982  case CodeCompletionContext::CCC_Recovery:
1983  case CodeCompletionContext::CCC_TopLevel:
1984  case CodeCompletionContext::CCC_ObjCInterface:
1985  case CodeCompletionContext::CCC_ObjCImplementation:
1986  case CodeCompletionContext::CCC_ObjCIvarList:
1987  case CodeCompletionContext::CCC_ClassStructUnion:
1988  case CodeCompletionContext::CCC_Statement:
1989  case CodeCompletionContext::CCC_Expression:
1990  case CodeCompletionContext::CCC_ObjCMessageReceiver:
1991  case CodeCompletionContext::CCC_DotMemberAccess:
1992  case CodeCompletionContext::CCC_ArrowMemberAccess:
1993  case CodeCompletionContext::CCC_ObjCPropertyAccess:
1994  case CodeCompletionContext::CCC_Namespace:
1995  case CodeCompletionContext::CCC_Type:
1996  case CodeCompletionContext::CCC_Name:
1997  case CodeCompletionContext::CCC_PotentiallyQualifiedName:
1998  case CodeCompletionContext::CCC_ParenthesizedExpression:
1999  case CodeCompletionContext::CCC_ObjCInterfaceName:
2000    break;
2001
2002  case CodeCompletionContext::CCC_EnumTag:
2003  case CodeCompletionContext::CCC_UnionTag:
2004  case CodeCompletionContext::CCC_ClassOrStructTag:
2005    OnlyTagNames = true;
2006    break;
2007
2008  case CodeCompletionContext::CCC_ObjCProtocolName:
2009  case CodeCompletionContext::CCC_MacroName:
2010  case CodeCompletionContext::CCC_MacroNameUse:
2011  case CodeCompletionContext::CCC_PreprocessorExpression:
2012  case CodeCompletionContext::CCC_PreprocessorDirective:
2013  case CodeCompletionContext::CCC_NaturalLanguage:
2014  case CodeCompletionContext::CCC_SelectorName:
2015  case CodeCompletionContext::CCC_TypeQualifiers:
2016  case CodeCompletionContext::CCC_Other:
2017  case CodeCompletionContext::CCC_OtherWithMacros:
2018  case CodeCompletionContext::CCC_ObjCInstanceMessage:
2019  case CodeCompletionContext::CCC_ObjCClassMessage:
2020  case CodeCompletionContext::CCC_ObjCCategoryName:
2021    // We're looking for nothing, or we're looking for names that cannot
2022    // be hidden.
2023    return;
2024  }
2025
2026  typedef CodeCompletionResult Result;
2027  for (unsigned I = 0; I != NumResults; ++I) {
2028    if (Results[I].Kind != Result::RK_Declaration)
2029      continue;
2030
2031    unsigned IDNS
2032      = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2033
2034    bool Hiding = false;
2035    if (OnlyTagNames)
2036      Hiding = (IDNS & Decl::IDNS_Tag);
2037    else {
2038      unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
2039                             Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2040                             Decl::IDNS_NonMemberOperator);
2041      if (Ctx.getLangOptions().CPlusPlus)
2042        HiddenIDNS |= Decl::IDNS_Tag;
2043      Hiding = (IDNS & HiddenIDNS);
2044    }
2045
2046    if (!Hiding)
2047      continue;
2048
2049    DeclarationName Name = Results[I].Declaration->getDeclName();
2050    if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2051      HiddenNames.insert(Identifier->getName());
2052    else
2053      HiddenNames.insert(Name.getAsString());
2054  }
2055}
2056
2057
2058void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2059                                            CodeCompletionContext Context,
2060                                            CodeCompletionResult *Results,
2061                                            unsigned NumResults) {
2062  // Merge the results we were given with the results we cached.
2063  bool AddedResult = false;
2064  unsigned InContexts
2065    = (Context.getKind() == CodeCompletionContext::CCC_Recovery? NormalContexts
2066                                        : (1ULL << (Context.getKind() - 1)));
2067  // Contains the set of names that are hidden by "local" completion results.
2068  llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
2069  typedef CodeCompletionResult Result;
2070  SmallVector<Result, 8> AllResults;
2071  for (ASTUnit::cached_completion_iterator
2072            C = AST.cached_completion_begin(),
2073         CEnd = AST.cached_completion_end();
2074       C != CEnd; ++C) {
2075    // If the context we are in matches any of the contexts we are
2076    // interested in, we'll add this result.
2077    if ((C->ShowInContexts & InContexts) == 0)
2078      continue;
2079
2080    // If we haven't added any results previously, do so now.
2081    if (!AddedResult) {
2082      CalculateHiddenNames(Context, Results, NumResults, S.Context,
2083                           HiddenNames);
2084      AllResults.insert(AllResults.end(), Results, Results + NumResults);
2085      AddedResult = true;
2086    }
2087
2088    // Determine whether this global completion result is hidden by a local
2089    // completion result. If so, skip it.
2090    if (C->Kind != CXCursor_MacroDefinition &&
2091        HiddenNames.count(C->Completion->getTypedText()))
2092      continue;
2093
2094    // Adjust priority based on similar type classes.
2095    unsigned Priority = C->Priority;
2096    CXCursorKind CursorKind = C->Kind;
2097    CodeCompletionString *Completion = C->Completion;
2098    if (!Context.getPreferredType().isNull()) {
2099      if (C->Kind == CXCursor_MacroDefinition) {
2100        Priority = getMacroUsagePriority(C->Completion->getTypedText(),
2101                                         S.getLangOptions(),
2102                               Context.getPreferredType()->isAnyPointerType());
2103      } else if (C->Type) {
2104        CanQualType Expected
2105          = S.Context.getCanonicalType(
2106                               Context.getPreferredType().getUnqualifiedType());
2107        SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2108        if (ExpectedSTC == C->TypeClass) {
2109          // We know this type is similar; check for an exact match.
2110          llvm::StringMap<unsigned> &CachedCompletionTypes
2111            = AST.getCachedCompletionTypes();
2112          llvm::StringMap<unsigned>::iterator Pos
2113            = CachedCompletionTypes.find(QualType(Expected).getAsString());
2114          if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2115            Priority /= CCF_ExactTypeMatch;
2116          else
2117            Priority /= CCF_SimilarTypeMatch;
2118        }
2119      }
2120    }
2121
2122    // Adjust the completion string, if required.
2123    if (C->Kind == CXCursor_MacroDefinition &&
2124        Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2125      // Create a new code-completion string that just contains the
2126      // macro name, without its arguments.
2127      CodeCompletionBuilder Builder(getAllocator(), CCP_CodePattern,
2128                                    C->Availability);
2129      Builder.AddTypedTextChunk(C->Completion->getTypedText());
2130      CursorKind = CXCursor_NotImplemented;
2131      Priority = CCP_CodePattern;
2132      Completion = Builder.TakeString();
2133    }
2134
2135    AllResults.push_back(Result(Completion, Priority, CursorKind,
2136                                C->Availability));
2137  }
2138
2139  // If we did not add any cached completion results, just forward the
2140  // results we were given to the next consumer.
2141  if (!AddedResult) {
2142    Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2143    return;
2144  }
2145
2146  Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2147                                  AllResults.size());
2148}
2149
2150
2151
2152void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
2153                           RemappedFile *RemappedFiles,
2154                           unsigned NumRemappedFiles,
2155                           bool IncludeMacros,
2156                           bool IncludeCodePatterns,
2157                           CodeCompleteConsumer &Consumer,
2158                           Diagnostic &Diag, LangOptions &LangOpts,
2159                           SourceManager &SourceMgr, FileManager &FileMgr,
2160                   SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2161             SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
2162  if (!Invocation)
2163    return;
2164
2165  SimpleTimer CompletionTimer(WantTiming);
2166  CompletionTimer.setOutput("Code completion @ " + File + ":" +
2167                            Twine(Line) + ":" + Twine(Column));
2168
2169  llvm::IntrusiveRefCntPtr<CompilerInvocation>
2170    CCInvocation(new CompilerInvocation(*Invocation));
2171
2172  FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
2173  PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
2174
2175  FrontendOpts.ShowMacrosInCodeCompletion
2176    = IncludeMacros && CachedCompletionResults.empty();
2177  FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
2178  FrontendOpts.ShowGlobalSymbolsInCodeCompletion
2179    = CachedCompletionResults.empty();
2180  FrontendOpts.CodeCompletionAt.FileName = File;
2181  FrontendOpts.CodeCompletionAt.Line = Line;
2182  FrontendOpts.CodeCompletionAt.Column = Column;
2183
2184  // Set the language options appropriately.
2185  LangOpts = CCInvocation->getLangOpts();
2186
2187  llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
2188
2189  // Recover resources if we crash before exiting this method.
2190  llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2191    CICleanup(Clang.get());
2192
2193  Clang->setInvocation(&*CCInvocation);
2194  OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
2195
2196  // Set up diagnostics, capturing any diagnostics produced.
2197  Clang->setDiagnostics(&Diag);
2198  ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
2199  CaptureDroppedDiagnostics Capture(true,
2200                                    Clang->getDiagnostics(),
2201                                    StoredDiagnostics);
2202
2203  // Create the target instance.
2204  Clang->getTargetOpts().Features = TargetFeatures;
2205  Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
2206                                               Clang->getTargetOpts()));
2207  if (!Clang->hasTarget()) {
2208    Clang->setInvocation(0);
2209    return;
2210  }
2211
2212  // Inform the target of the language options.
2213  //
2214  // FIXME: We shouldn't need to do this, the target should be immutable once
2215  // created. This complexity should be lifted elsewhere.
2216  Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
2217
2218  assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
2219         "Invocation must have exactly one source file!");
2220  assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
2221         "FIXME: AST inputs not yet supported here!");
2222  assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
2223         "IR inputs not support here!");
2224
2225
2226  // Use the source and file managers that we were given.
2227  Clang->setFileManager(&FileMgr);
2228  Clang->setSourceManager(&SourceMgr);
2229
2230  // Remap files.
2231  PreprocessorOpts.clearRemappedFiles();
2232  PreprocessorOpts.RetainRemappedFileBuffers = true;
2233  for (unsigned I = 0; I != NumRemappedFiles; ++I) {
2234    FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2235    if (const llvm::MemoryBuffer *
2236            memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2237      PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, memBuf);
2238      OwnedBuffers.push_back(memBuf);
2239    } else {
2240      const char *fname = fileOrBuf.get<const char *>();
2241      PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, fname);
2242    }
2243  }
2244
2245  // Use the code completion consumer we were given, but adding any cached
2246  // code-completion results.
2247  AugmentedCodeCompleteConsumer *AugmentedConsumer
2248    = new AugmentedCodeCompleteConsumer(*this, Consumer,
2249                                        FrontendOpts.ShowMacrosInCodeCompletion,
2250                                FrontendOpts.ShowCodePatternsInCodeCompletion,
2251                                FrontendOpts.ShowGlobalSymbolsInCodeCompletion);
2252  Clang->setCodeCompletionConsumer(AugmentedConsumer);
2253
2254  // If we have a precompiled preamble, try to use it. We only allow
2255  // the use of the precompiled preamble if we're if the completion
2256  // point is within the main file, after the end of the precompiled
2257  // preamble.
2258  llvm::MemoryBuffer *OverrideMainBuffer = 0;
2259  if (!PreambleFile.empty()) {
2260    using llvm::sys::FileStatus;
2261    llvm::sys::PathWithStatus CompleteFilePath(File);
2262    llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
2263    if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
2264      if (const FileStatus *MainStatus = MainPath.getFileStatus())
2265        if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID())
2266          OverrideMainBuffer
2267            = getMainBufferWithPrecompiledPreamble(*CCInvocation, false,
2268                                                   Line - 1);
2269  }
2270
2271  // If the main file has been overridden due to the use of a preamble,
2272  // make that override happen and introduce the preamble.
2273  PreprocessorOpts.DisableStatCache = true;
2274  StoredDiagnostics.insert(StoredDiagnostics.end(),
2275                           this->StoredDiagnostics.begin(),
2276             this->StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver);
2277  if (OverrideMainBuffer) {
2278    PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
2279    PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2280    PreprocessorOpts.PrecompiledPreambleBytes.second
2281                                                    = PreambleEndsAtStartOfLine;
2282    PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
2283    PreprocessorOpts.DisablePCHValidation = true;
2284
2285    OwnedBuffers.push_back(OverrideMainBuffer);
2286  } else {
2287    PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2288    PreprocessorOpts.PrecompiledPreambleBytes.second = false;
2289  }
2290
2291  // Disable the preprocessing record
2292  PreprocessorOpts.DetailedRecord = false;
2293
2294  llvm::OwningPtr<SyntaxOnlyAction> Act;
2295  Act.reset(new SyntaxOnlyAction);
2296  if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
2297                           Clang->getFrontendOpts().Inputs[0].first)) {
2298    if (OverrideMainBuffer) {
2299      std::string ModName = PreambleFile;
2300      TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
2301                                 getSourceManager(), PreambleDiagnostics,
2302                                 StoredDiagnostics);
2303    }
2304    Act->Execute();
2305    Act->EndSourceFile();
2306  }
2307}
2308
2309CXSaveError ASTUnit::Save(StringRef File) {
2310  if (getDiagnostics().hasUnrecoverableErrorOccurred())
2311    return CXSaveError_TranslationErrors;
2312
2313  // Write to a temporary file and later rename it to the actual file, to avoid
2314  // possible race conditions.
2315  llvm::SmallString<128> TempPath;
2316  TempPath = File;
2317  TempPath += "-%%%%%%%%";
2318  int fd;
2319  if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
2320                                 /*makeAbsolute=*/false))
2321    return CXSaveError_Unknown;
2322
2323  // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2324  // unconditionally create a stat cache when we parse the file?
2325  llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
2326
2327  serialize(Out);
2328  Out.close();
2329  if (Out.has_error())
2330    return CXSaveError_Unknown;
2331
2332  if (llvm::error_code ec = llvm::sys::fs::rename(TempPath.str(), File)) {
2333    bool exists;
2334    llvm::sys::fs::remove(TempPath.str(), exists);
2335    return CXSaveError_Unknown;
2336  }
2337
2338  return CXSaveError_None;
2339}
2340
2341bool ASTUnit::serialize(raw_ostream &OS) {
2342  if (getDiagnostics().hasErrorOccurred())
2343    return true;
2344
2345  std::vector<unsigned char> Buffer;
2346  llvm::BitstreamWriter Stream(Buffer);
2347  ASTWriter Writer(Stream);
2348  Writer.WriteAST(getSema(), 0, std::string(), "");
2349
2350  // Write the generated bitstream to "Out".
2351  if (!Buffer.empty())
2352    OS.write((char *)&Buffer.front(), Buffer.size());
2353
2354  return false;
2355}
2356
2357typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2358
2359static void TranslateSLoc(SourceLocation &L, SLocRemap &Remap) {
2360  unsigned Raw = L.getRawEncoding();
2361  const unsigned MacroBit = 1U << 31;
2362  L = SourceLocation::getFromRawEncoding((Raw & MacroBit) |
2363      ((Raw & ~MacroBit) + Remap.find(Raw & ~MacroBit)->second));
2364}
2365
2366void ASTUnit::TranslateStoredDiagnostics(
2367                          ASTReader *MMan,
2368                          StringRef ModName,
2369                          SourceManager &SrcMgr,
2370                          const SmallVectorImpl<StoredDiagnostic> &Diags,
2371                          SmallVectorImpl<StoredDiagnostic> &Out) {
2372  // The stored diagnostic has the old source manager in it; update
2373  // the locations to refer into the new source manager. We also need to remap
2374  // all the locations to the new view. This includes the diag location, any
2375  // associated source ranges, and the source ranges of associated fix-its.
2376  // FIXME: There should be a cleaner way to do this.
2377
2378  SmallVector<StoredDiagnostic, 4> Result;
2379  Result.reserve(Diags.size());
2380  assert(MMan && "Don't have a module manager");
2381  serialization::Module *Mod = MMan->ModuleMgr.lookup(ModName);
2382  assert(Mod && "Don't have preamble module");
2383  SLocRemap &Remap = Mod->SLocRemap;
2384  for (unsigned I = 0, N = Diags.size(); I != N; ++I) {
2385    // Rebuild the StoredDiagnostic.
2386    const StoredDiagnostic &SD = Diags[I];
2387    SourceLocation L = SD.getLocation();
2388    TranslateSLoc(L, Remap);
2389    FullSourceLoc Loc(L, SrcMgr);
2390
2391    SmallVector<CharSourceRange, 4> Ranges;
2392    Ranges.reserve(SD.range_size());
2393    for (StoredDiagnostic::range_iterator I = SD.range_begin(),
2394                                          E = SD.range_end();
2395         I != E; ++I) {
2396      SourceLocation BL = I->getBegin();
2397      TranslateSLoc(BL, Remap);
2398      SourceLocation EL = I->getEnd();
2399      TranslateSLoc(EL, Remap);
2400      Ranges.push_back(CharSourceRange(SourceRange(BL, EL), I->isTokenRange()));
2401    }
2402
2403    SmallVector<FixItHint, 2> FixIts;
2404    FixIts.reserve(SD.fixit_size());
2405    for (StoredDiagnostic::fixit_iterator I = SD.fixit_begin(),
2406                                          E = SD.fixit_end();
2407         I != E; ++I) {
2408      FixIts.push_back(FixItHint());
2409      FixItHint &FH = FixIts.back();
2410      FH.CodeToInsert = I->CodeToInsert;
2411      SourceLocation BL = I->RemoveRange.getBegin();
2412      TranslateSLoc(BL, Remap);
2413      SourceLocation EL = I->RemoveRange.getEnd();
2414      TranslateSLoc(EL, Remap);
2415      FH.RemoveRange = CharSourceRange(SourceRange(BL, EL),
2416                                       I->RemoveRange.isTokenRange());
2417    }
2418
2419    Result.push_back(StoredDiagnostic(SD.getLevel(), SD.getID(),
2420                                      SD.getMessage(), Loc, Ranges, FixIts));
2421  }
2422  Result.swap(Out);
2423}
2424