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