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