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