1//===--- FrontendAction.cpp -----------------------------------------------===//
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#include "clang/Frontend/FrontendAction.h"
11#include "clang/AST/ASTConsumer.h"
12#include "clang/AST/ASTContext.h"
13#include "clang/AST/DeclGroup.h"
14#include "clang/Lex/HeaderSearch.h"
15#include "clang/Lex/Preprocessor.h"
16#include "clang/Frontend/ASTUnit.h"
17#include "clang/Frontend/ChainedIncludesSource.h"
18#include "clang/Frontend/CompilerInstance.h"
19#include "clang/Frontend/FrontendDiagnostic.h"
20#include "clang/Frontend/FrontendPluginRegistry.h"
21#include "clang/Frontend/LayoutOverrideSource.h"
22#include "clang/Frontend/MultiplexConsumer.h"
23#include "clang/Parse/ParseAST.h"
24#include "clang/Serialization/ASTDeserializationListener.h"
25#include "clang/Serialization/ASTReader.h"
26#include "llvm/Support/MemoryBuffer.h"
27#include "llvm/Support/Timer.h"
28#include "llvm/Support/ErrorHandling.h"
29#include "llvm/Support/raw_ostream.h"
30using namespace clang;
31
32namespace {
33
34class DelegatingDeserializationListener : public ASTDeserializationListener {
35  ASTDeserializationListener *Previous;
36
37public:
38  explicit DelegatingDeserializationListener(
39                                           ASTDeserializationListener *Previous)
40    : Previous(Previous) { }
41
42  virtual void ReaderInitialized(ASTReader *Reader) {
43    if (Previous)
44      Previous->ReaderInitialized(Reader);
45  }
46  virtual void IdentifierRead(serialization::IdentID ID,
47                              IdentifierInfo *II) {
48    if (Previous)
49      Previous->IdentifierRead(ID, II);
50  }
51  virtual void TypeRead(serialization::TypeIdx Idx, QualType T) {
52    if (Previous)
53      Previous->TypeRead(Idx, T);
54  }
55  virtual void DeclRead(serialization::DeclID ID, const Decl *D) {
56    if (Previous)
57      Previous->DeclRead(ID, D);
58  }
59  virtual void SelectorRead(serialization::SelectorID ID, Selector Sel) {
60    if (Previous)
61      Previous->SelectorRead(ID, Sel);
62  }
63  virtual void MacroDefinitionRead(serialization::PreprocessedEntityID PPID,
64                                   MacroDefinition *MD) {
65    if (Previous)
66      Previous->MacroDefinitionRead(PPID, MD);
67  }
68};
69
70/// \brief Dumps deserialized declarations.
71class DeserializedDeclsDumper : public DelegatingDeserializationListener {
72public:
73  explicit DeserializedDeclsDumper(ASTDeserializationListener *Previous)
74    : DelegatingDeserializationListener(Previous) { }
75
76  virtual void DeclRead(serialization::DeclID ID, const Decl *D) {
77    llvm::outs() << "PCH DECL: " << D->getDeclKindName();
78    if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
79      llvm::outs() << " - " << *ND;
80    llvm::outs() << "\n";
81
82    DelegatingDeserializationListener::DeclRead(ID, D);
83  }
84};
85
86/// \brief Checks deserialized declarations and emits error if a name
87/// matches one given in command-line using -error-on-deserialized-decl.
88class DeserializedDeclsChecker : public DelegatingDeserializationListener {
89  ASTContext &Ctx;
90  std::set<std::string> NamesToCheck;
91
92public:
93  DeserializedDeclsChecker(ASTContext &Ctx,
94                           const std::set<std::string> &NamesToCheck,
95                           ASTDeserializationListener *Previous)
96    : DelegatingDeserializationListener(Previous),
97      Ctx(Ctx), NamesToCheck(NamesToCheck) { }
98
99  virtual void DeclRead(serialization::DeclID ID, const Decl *D) {
100    if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
101      if (NamesToCheck.find(ND->getNameAsString()) != NamesToCheck.end()) {
102        unsigned DiagID
103          = Ctx.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error,
104                                                 "%0 was deserialized");
105        Ctx.getDiagnostics().Report(Ctx.getFullLoc(D->getLocation()), DiagID)
106            << ND->getNameAsString();
107      }
108
109    DelegatingDeserializationListener::DeclRead(ID, D);
110  }
111};
112
113} // end anonymous namespace
114
115FrontendAction::FrontendAction() : Instance(0) {}
116
117FrontendAction::~FrontendAction() {}
118
119void FrontendAction::setCurrentInput(const FrontendInputFile &CurrentInput,
120                                     ASTUnit *AST) {
121  this->CurrentInput = CurrentInput;
122  CurrentASTUnit.reset(AST);
123}
124
125ASTConsumer* FrontendAction::CreateWrappedASTConsumer(CompilerInstance &CI,
126                                                      StringRef InFile) {
127  ASTConsumer* Consumer = CreateASTConsumer(CI, InFile);
128  if (!Consumer)
129    return 0;
130
131  if (CI.getFrontendOpts().AddPluginActions.size() == 0)
132    return Consumer;
133
134  // Make sure the non-plugin consumer is first, so that plugins can't
135  // modifiy the AST.
136  std::vector<ASTConsumer*> Consumers(1, Consumer);
137
138  for (size_t i = 0, e = CI.getFrontendOpts().AddPluginActions.size();
139       i != e; ++i) {
140    // This is O(|plugins| * |add_plugins|), but since both numbers are
141    // way below 50 in practice, that's ok.
142    for (FrontendPluginRegistry::iterator
143        it = FrontendPluginRegistry::begin(),
144        ie = FrontendPluginRegistry::end();
145        it != ie; ++it) {
146      if (it->getName() == CI.getFrontendOpts().AddPluginActions[i]) {
147        OwningPtr<PluginASTAction> P(it->instantiate());
148        FrontendAction* c = P.get();
149        if (P->ParseArgs(CI, CI.getFrontendOpts().AddPluginArgs[i]))
150          Consumers.push_back(c->CreateASTConsumer(CI, InFile));
151      }
152    }
153  }
154
155  return new MultiplexConsumer(Consumers);
156}
157
158bool FrontendAction::BeginSourceFile(CompilerInstance &CI,
159                                     const FrontendInputFile &Input) {
160  assert(!Instance && "Already processing a source file!");
161  assert(!Input.File.empty() && "Unexpected empty filename!");
162  setCurrentInput(Input);
163  setCompilerInstance(&CI);
164
165  bool HasBegunSourceFile = false;
166  if (!BeginInvocation(CI))
167    goto failure;
168
169  // AST files follow a very different path, since they share objects via the
170  // AST unit.
171  if (Input.Kind == IK_AST) {
172    assert(!usesPreprocessorOnly() &&
173           "Attempt to pass AST file to preprocessor only action!");
174    assert(hasASTFileSupport() &&
175           "This action does not have AST file support!");
176
177    IntrusiveRefCntPtr<DiagnosticsEngine> Diags(&CI.getDiagnostics());
178    std::string Error;
179    ASTUnit *AST = ASTUnit::LoadFromASTFile(Input.File, Diags,
180                                            CI.getFileSystemOpts());
181    if (!AST)
182      goto failure;
183
184    setCurrentInput(Input, AST);
185
186    // Set the shared objects, these are reset when we finish processing the
187    // file, otherwise the CompilerInstance will happily destroy them.
188    CI.setFileManager(&AST->getFileManager());
189    CI.setSourceManager(&AST->getSourceManager());
190    CI.setPreprocessor(&AST->getPreprocessor());
191    CI.setASTContext(&AST->getASTContext());
192
193    // Initialize the action.
194    if (!BeginSourceFileAction(CI, Input.File))
195      goto failure;
196
197    /// Create the AST consumer.
198    CI.setASTConsumer(CreateWrappedASTConsumer(CI, Input.File));
199    if (!CI.hasASTConsumer())
200      goto failure;
201
202    return true;
203  }
204
205  // Set up the file and source managers, if needed.
206  if (!CI.hasFileManager())
207    CI.createFileManager();
208  if (!CI.hasSourceManager())
209    CI.createSourceManager(CI.getFileManager());
210
211  // IR files bypass the rest of initialization.
212  if (Input.Kind == IK_LLVM_IR) {
213    assert(hasIRSupport() &&
214           "This action does not have IR file support!");
215
216    // Inform the diagnostic client we are processing a source file.
217    CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), 0);
218    HasBegunSourceFile = true;
219
220    // Initialize the action.
221    if (!BeginSourceFileAction(CI, Input.File))
222      goto failure;
223
224    return true;
225  }
226
227  // Set up the preprocessor.
228  CI.createPreprocessor();
229
230  // Inform the diagnostic client we are processing a source file.
231  CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(),
232                                           &CI.getPreprocessor());
233  HasBegunSourceFile = true;
234
235  // Initialize the action.
236  if (!BeginSourceFileAction(CI, Input.File))
237    goto failure;
238
239  /// Create the AST context and consumer unless this is a preprocessor only
240  /// action.
241  if (!usesPreprocessorOnly()) {
242    CI.createASTContext();
243
244    OwningPtr<ASTConsumer> Consumer(
245                                   CreateWrappedASTConsumer(CI, Input.File));
246    if (!Consumer)
247      goto failure;
248
249    CI.getASTContext().setASTMutationListener(Consumer->GetASTMutationListener());
250
251    if (!CI.getPreprocessorOpts().ChainedIncludes.empty()) {
252      // Convert headers to PCH and chain them.
253      OwningPtr<ExternalASTSource> source;
254      source.reset(ChainedIncludesSource::create(CI));
255      if (!source)
256        goto failure;
257      CI.getASTContext().setExternalSource(source);
258
259    } else if (!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
260      // Use PCH.
261      assert(hasPCHSupport() && "This action does not have PCH support!");
262      ASTDeserializationListener *DeserialListener =
263          Consumer->GetASTDeserializationListener();
264      if (CI.getPreprocessorOpts().DumpDeserializedPCHDecls)
265        DeserialListener = new DeserializedDeclsDumper(DeserialListener);
266      if (!CI.getPreprocessorOpts().DeserializedPCHDeclsToErrorOn.empty())
267        DeserialListener = new DeserializedDeclsChecker(CI.getASTContext(),
268                         CI.getPreprocessorOpts().DeserializedPCHDeclsToErrorOn,
269                                                        DeserialListener);
270      CI.createPCHExternalASTSource(
271                                CI.getPreprocessorOpts().ImplicitPCHInclude,
272                                CI.getPreprocessorOpts().DisablePCHValidation,
273                                CI.getPreprocessorOpts().DisableStatCache,
274                            CI.getPreprocessorOpts().AllowPCHWithCompilerErrors,
275                                DeserialListener);
276      if (!CI.getASTContext().getExternalSource())
277        goto failure;
278    }
279
280    CI.setASTConsumer(Consumer.take());
281    if (!CI.hasASTConsumer())
282      goto failure;
283  }
284
285  // Initialize built-in info as long as we aren't using an external AST
286  // source.
287  if (!CI.hasASTContext() || !CI.getASTContext().getExternalSource()) {
288    Preprocessor &PP = CI.getPreprocessor();
289    PP.getBuiltinInfo().InitializeBuiltins(PP.getIdentifierTable(),
290                                           PP.getLangOpts());
291  }
292
293  // If there is a layout overrides file, attach an external AST source that
294  // provides the layouts from that file.
295  if (!CI.getFrontendOpts().OverrideRecordLayoutsFile.empty() &&
296      CI.hasASTContext() && !CI.getASTContext().getExternalSource()) {
297    OwningPtr<ExternalASTSource>
298      Override(new LayoutOverrideSource(
299                     CI.getFrontendOpts().OverrideRecordLayoutsFile));
300    CI.getASTContext().setExternalSource(Override);
301  }
302
303  return true;
304
305  // If we failed, reset state since the client will not end up calling the
306  // matching EndSourceFile().
307  failure:
308  if (isCurrentFileAST()) {
309    CI.setASTContext(0);
310    CI.setPreprocessor(0);
311    CI.setSourceManager(0);
312    CI.setFileManager(0);
313  }
314
315  if (HasBegunSourceFile)
316    CI.getDiagnosticClient().EndSourceFile();
317  setCurrentInput(FrontendInputFile());
318  setCompilerInstance(0);
319  return false;
320}
321
322bool FrontendAction::Execute() {
323  CompilerInstance &CI = getCompilerInstance();
324
325  // Initialize the main file entry. This needs to be delayed until after PCH
326  // has loaded.
327  if (!isCurrentFileAST()) {
328    if (!CI.InitializeSourceManager(getCurrentFile(),
329                                    getCurrentInput().IsSystem
330                                      ? SrcMgr::C_System
331                                      : SrcMgr::C_User))
332      return false;
333  }
334
335  if (CI.hasFrontendTimer()) {
336    llvm::TimeRegion Timer(CI.getFrontendTimer());
337    ExecuteAction();
338  }
339  else ExecuteAction();
340
341  return true;
342}
343
344void FrontendAction::EndSourceFile() {
345  CompilerInstance &CI = getCompilerInstance();
346
347  // Inform the diagnostic client we are done with this source file.
348  CI.getDiagnosticClient().EndSourceFile();
349
350  // Finalize the action.
351  EndSourceFileAction();
352
353  // Release the consumer and the AST, in that order since the consumer may
354  // perform actions in its destructor which require the context.
355  //
356  // FIXME: There is more per-file stuff we could just drop here?
357  if (CI.getFrontendOpts().DisableFree) {
358    CI.takeASTConsumer();
359    if (!isCurrentFileAST()) {
360      CI.takeSema();
361      CI.resetAndLeakASTContext();
362    }
363  } else {
364    if (!isCurrentFileAST()) {
365      CI.setSema(0);
366      CI.setASTContext(0);
367    }
368    CI.setASTConsumer(0);
369  }
370
371  // Inform the preprocessor we are done.
372  if (CI.hasPreprocessor())
373    CI.getPreprocessor().EndSourceFile();
374
375  if (CI.getFrontendOpts().ShowStats) {
376    llvm::errs() << "\nSTATISTICS FOR '" << getCurrentFile() << "':\n";
377    CI.getPreprocessor().PrintStats();
378    CI.getPreprocessor().getIdentifierTable().PrintStats();
379    CI.getPreprocessor().getHeaderSearchInfo().PrintStats();
380    CI.getSourceManager().PrintStats();
381    llvm::errs() << "\n";
382  }
383
384  // Cleanup the output streams, and erase the output files if we encountered
385  // an error.
386  CI.clearOutputFiles(/*EraseFiles=*/CI.getDiagnostics().hasErrorOccurred());
387
388  if (isCurrentFileAST()) {
389    CI.takeSema();
390    CI.resetAndLeakASTContext();
391    CI.resetAndLeakPreprocessor();
392    CI.resetAndLeakSourceManager();
393    CI.resetAndLeakFileManager();
394  }
395
396  setCompilerInstance(0);
397  setCurrentInput(FrontendInputFile());
398}
399
400//===----------------------------------------------------------------------===//
401// Utility Actions
402//===----------------------------------------------------------------------===//
403
404void ASTFrontendAction::ExecuteAction() {
405  CompilerInstance &CI = getCompilerInstance();
406
407  // FIXME: Move the truncation aspect of this into Sema, we delayed this till
408  // here so the source manager would be initialized.
409  if (hasCodeCompletionSupport() &&
410      !CI.getFrontendOpts().CodeCompletionAt.FileName.empty())
411    CI.createCodeCompletionConsumer();
412
413  // Use a code completion consumer?
414  CodeCompleteConsumer *CompletionConsumer = 0;
415  if (CI.hasCodeCompletionConsumer())
416    CompletionConsumer = &CI.getCodeCompletionConsumer();
417
418  if (!CI.hasSema())
419    CI.createSema(getTranslationUnitKind(), CompletionConsumer);
420
421  ParseAST(CI.getSema(), CI.getFrontendOpts().ShowStats,
422           CI.getFrontendOpts().SkipFunctionBodies);
423}
424
425void PluginASTAction::anchor() { }
426
427ASTConsumer *
428PreprocessorFrontendAction::CreateASTConsumer(CompilerInstance &CI,
429                                              StringRef InFile) {
430  llvm_unreachable("Invalid CreateASTConsumer on preprocessor action!");
431}
432
433ASTConsumer *WrapperFrontendAction::CreateASTConsumer(CompilerInstance &CI,
434                                                      StringRef InFile) {
435  return WrappedAction->CreateASTConsumer(CI, InFile);
436}
437bool WrapperFrontendAction::BeginInvocation(CompilerInstance &CI) {
438  return WrappedAction->BeginInvocation(CI);
439}
440bool WrapperFrontendAction::BeginSourceFileAction(CompilerInstance &CI,
441                                                  StringRef Filename) {
442  WrappedAction->setCurrentInput(getCurrentInput());
443  WrappedAction->setCompilerInstance(&CI);
444  return WrappedAction->BeginSourceFileAction(CI, Filename);
445}
446void WrapperFrontendAction::ExecuteAction() {
447  WrappedAction->ExecuteAction();
448}
449void WrapperFrontendAction::EndSourceFileAction() {
450  WrappedAction->EndSourceFileAction();
451}
452
453bool WrapperFrontendAction::usesPreprocessorOnly() const {
454  return WrappedAction->usesPreprocessorOnly();
455}
456TranslationUnitKind WrapperFrontendAction::getTranslationUnitKind() {
457  return WrappedAction->getTranslationUnitKind();
458}
459bool WrapperFrontendAction::hasPCHSupport() const {
460  return WrappedAction->hasPCHSupport();
461}
462bool WrapperFrontendAction::hasASTFileSupport() const {
463  return WrappedAction->hasASTFileSupport();
464}
465bool WrapperFrontendAction::hasIRSupport() const {
466  return WrappedAction->hasIRSupport();
467}
468bool WrapperFrontendAction::hasCodeCompletionSupport() const {
469  return WrappedAction->hasCodeCompletionSupport();
470}
471
472WrapperFrontendAction::WrapperFrontendAction(FrontendAction *WrappedAction)
473  : WrappedAction(WrappedAction) {}
474
475