1 //===--- FrontendAction.cpp -----------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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/CompilerInstance.h"
18 #include "clang/Frontend/FrontendDiagnostic.h"
19 #include "clang/Frontend/FrontendPluginRegistry.h"
20 #include "clang/Frontend/MultiplexConsumer.h"
21 #include "clang/Parse/ParseAST.h"
22 #include "clang/Serialization/ASTDeserializationListener.h"
23 #include "clang/Serialization/ChainedIncludesSource.h"
24 #include "llvm/Support/MemoryBuffer.h"
25 #include "llvm/Support/Timer.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/raw_ostream.h"
28 using namespace clang;
32 /// \brief Dumps deserialized declarations.
33 class DeserializedDeclsDumper : public ASTDeserializationListener {
34 ASTDeserializationListener *Previous;
37 DeserializedDeclsDumper(ASTDeserializationListener *Previous)
38 : Previous(Previous) { }
40 virtual void DeclRead(serialization::DeclID ID, const Decl *D) {
41 llvm::outs() << "PCH DECL: " << D->getDeclKindName();
42 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
43 llvm::outs() << " - " << ND->getNameAsString();
47 Previous->DeclRead(ID, D);
51 /// \brief Checks deserialized declarations and emits error if a name
52 /// matches one given in command-line using -error-on-deserialized-decl.
53 class DeserializedDeclsChecker : public ASTDeserializationListener {
55 std::set<std::string> NamesToCheck;
56 ASTDeserializationListener *Previous;
59 DeserializedDeclsChecker(ASTContext &Ctx,
60 const std::set<std::string> &NamesToCheck,
61 ASTDeserializationListener *Previous)
62 : Ctx(Ctx), NamesToCheck(NamesToCheck), Previous(Previous) { }
64 virtual void DeclRead(serialization::DeclID ID, const Decl *D) {
65 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
66 if (NamesToCheck.find(ND->getNameAsString()) != NamesToCheck.end()) {
68 = Ctx.getDiagnostics().getCustomDiagID(Diagnostic::Error,
69 "%0 was deserialized");
70 Ctx.getDiagnostics().Report(Ctx.getFullLoc(D->getLocation()), DiagID)
71 << ND->getNameAsString();
75 Previous->DeclRead(ID, D);
79 } // end anonymous namespace
81 FrontendAction::FrontendAction() : Instance(0) {}
83 FrontendAction::~FrontendAction() {}
85 void FrontendAction::setCurrentFile(llvm::StringRef Value, InputKind Kind,
88 CurrentFileKind = Kind;
89 CurrentASTUnit.reset(AST);
92 ASTConsumer* FrontendAction::CreateWrappedASTConsumer(CompilerInstance &CI,
93 llvm::StringRef InFile) {
94 ASTConsumer* Consumer = CreateASTConsumer(CI, InFile);
98 if (CI.getFrontendOpts().AddPluginActions.size() == 0)
101 // Make sure the non-plugin consumer is first, so that plugins can't
103 std::vector<ASTConsumer*> Consumers(1, Consumer);
105 for (size_t i = 0, e = CI.getFrontendOpts().AddPluginActions.size();
107 // This is O(|plugins| * |add_plugins|), but since both numbers are
108 // way below 50 in practice, that's ok.
109 for (FrontendPluginRegistry::iterator
110 it = FrontendPluginRegistry::begin(),
111 ie = FrontendPluginRegistry::end();
113 if (it->getName() == CI.getFrontendOpts().AddPluginActions[i]) {
114 llvm::OwningPtr<PluginASTAction> P(it->instantiate());
115 FrontendAction* c = P.get();
116 if (P->ParseArgs(CI, CI.getFrontendOpts().AddPluginArgs[i]))
117 Consumers.push_back(c->CreateASTConsumer(CI, InFile));
122 return new MultiplexConsumer(Consumers);
125 bool FrontendAction::BeginSourceFile(CompilerInstance &CI,
126 llvm::StringRef Filename,
127 InputKind InputKind) {
128 assert(!Instance && "Already processing a source file!");
129 assert(!Filename.empty() && "Unexpected empty filename!");
130 setCurrentFile(Filename, InputKind);
131 setCompilerInstance(&CI);
133 // AST files follow a very different path, since they share objects via the
135 if (InputKind == IK_AST) {
136 assert(!usesPreprocessorOnly() &&
137 "Attempt to pass AST file to preprocessor only action!");
138 assert(hasASTFileSupport() &&
139 "This action does not have AST file support!");
141 llvm::IntrusiveRefCntPtr<Diagnostic> Diags(&CI.getDiagnostics());
143 ASTUnit *AST = ASTUnit::LoadFromASTFile(Filename, Diags,
144 CI.getFileSystemOpts());
148 setCurrentFile(Filename, InputKind, AST);
150 // Set the shared objects, these are reset when we finish processing the
151 // file, otherwise the CompilerInstance will happily destroy them.
152 CI.setFileManager(&AST->getFileManager());
153 CI.setSourceManager(&AST->getSourceManager());
154 CI.setPreprocessor(&AST->getPreprocessor());
155 CI.setASTContext(&AST->getASTContext());
157 // Initialize the action.
158 if (!BeginSourceFileAction(CI, Filename))
161 /// Create the AST consumer.
162 CI.setASTConsumer(CreateWrappedASTConsumer(CI, Filename));
163 if (!CI.hasASTConsumer())
169 // Set up the file and source managers, if needed.
170 if (!CI.hasFileManager())
171 CI.createFileManager();
172 if (!CI.hasSourceManager())
173 CI.createSourceManager(CI.getFileManager());
175 // IR files bypass the rest of initialization.
176 if (InputKind == IK_LLVM_IR) {
177 assert(hasIRSupport() &&
178 "This action does not have IR file support!");
180 // Inform the diagnostic client we are processing a source file.
181 CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), 0);
183 // Initialize the action.
184 if (!BeginSourceFileAction(CI, Filename))
190 // Set up the preprocessor.
191 CI.createPreprocessor();
193 // Inform the diagnostic client we are processing a source file.
194 CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(),
195 &CI.getPreprocessor());
197 // Initialize the action.
198 if (!BeginSourceFileAction(CI, Filename))
201 /// Create the AST context and consumer unless this is a preprocessor only
203 if (!usesPreprocessorOnly()) {
204 CI.createASTContext();
206 llvm::OwningPtr<ASTConsumer> Consumer(
207 CreateWrappedASTConsumer(CI, Filename));
211 CI.getASTContext().setASTMutationListener(Consumer->GetASTMutationListener());
213 if (!CI.getPreprocessorOpts().ChainedIncludes.empty()) {
214 // Convert headers to PCH and chain them.
215 llvm::OwningPtr<ExternalASTSource> source;
216 source.reset(ChainedIncludesSource::create(CI));
219 CI.getASTContext().setExternalSource(source);
221 } else if (!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
223 assert(hasPCHSupport() && "This action does not have PCH support!");
224 ASTDeserializationListener *DeserialListener
225 = CI.getInvocation().getFrontendOpts().ChainedPCH ?
226 Consumer->GetASTDeserializationListener() : 0;
227 if (CI.getPreprocessorOpts().DumpDeserializedPCHDecls)
228 DeserialListener = new DeserializedDeclsDumper(DeserialListener);
229 if (!CI.getPreprocessorOpts().DeserializedPCHDeclsToErrorOn.empty())
230 DeserialListener = new DeserializedDeclsChecker(CI.getASTContext(),
231 CI.getPreprocessorOpts().DeserializedPCHDeclsToErrorOn,
233 CI.createPCHExternalASTSource(
234 CI.getPreprocessorOpts().ImplicitPCHInclude,
235 CI.getPreprocessorOpts().DisablePCHValidation,
236 CI.getPreprocessorOpts().DisableStatCache,
238 if (!CI.getASTContext().getExternalSource())
242 CI.setASTConsumer(Consumer.take());
243 if (!CI.hasASTConsumer())
247 // Initialize builtin info as long as we aren't using an external AST
249 if (!CI.hasASTContext() || !CI.getASTContext().getExternalSource()) {
250 Preprocessor &PP = CI.getPreprocessor();
251 PP.getBuiltinInfo().InitializeBuiltins(PP.getIdentifierTable(),
252 PP.getLangOptions());
257 // If we failed, reset state since the client will not end up calling the
258 // matching EndSourceFile().
260 if (isCurrentFileAST()) {
262 CI.setPreprocessor(0);
263 CI.setSourceManager(0);
264 CI.setFileManager(0);
267 CI.getDiagnosticClient().EndSourceFile();
268 setCurrentFile("", IK_None);
269 setCompilerInstance(0);
273 void FrontendAction::Execute() {
274 CompilerInstance &CI = getCompilerInstance();
276 // Initialize the main file entry. This needs to be delayed until after PCH
278 if (isCurrentFileAST()) {
279 // Set the main file ID to an empty file.
281 // FIXME: We probably shouldn't need this, but for now this is the
282 // simplest way to reuse the logic in ParseAST.
283 const char *EmptyStr = "";
284 llvm::MemoryBuffer *SB =
285 llvm::MemoryBuffer::getMemBuffer(EmptyStr, "<dummy input>");
286 CI.getSourceManager().createMainFileIDForMemBuffer(SB);
288 if (!CI.InitializeSourceManager(getCurrentFile()))
292 if (CI.hasFrontendTimer()) {
293 llvm::TimeRegion Timer(CI.getFrontendTimer());
296 else ExecuteAction();
299 void FrontendAction::EndSourceFile() {
300 CompilerInstance &CI = getCompilerInstance();
302 // Inform the diagnostic client we are done with this source file.
303 CI.getDiagnosticClient().EndSourceFile();
305 // Finalize the action.
306 EndSourceFileAction();
308 // Release the consumer and the AST, in that order since the consumer may
309 // perform actions in its destructor which require the context.
311 // FIXME: There is more per-file stuff we could just drop here?
312 if (CI.getFrontendOpts().DisableFree) {
313 CI.takeASTConsumer();
314 if (!isCurrentFileAST()) {
316 CI.resetAndLeakASTContext();
319 if (!isCurrentFileAST()) {
323 CI.setASTConsumer(0);
326 // Inform the preprocessor we are done.
327 if (CI.hasPreprocessor())
328 CI.getPreprocessor().EndSourceFile();
330 if (CI.getFrontendOpts().ShowStats) {
331 llvm::errs() << "\nSTATISTICS FOR '" << getCurrentFile() << "':\n";
332 CI.getPreprocessor().PrintStats();
333 CI.getPreprocessor().getIdentifierTable().PrintStats();
334 CI.getPreprocessor().getHeaderSearchInfo().PrintStats();
335 CI.getSourceManager().PrintStats();
336 llvm::errs() << "\n";
339 // Cleanup the output streams, and erase the output files if we encountered
341 CI.clearOutputFiles(/*EraseFiles=*/CI.getDiagnostics().hasErrorOccurred());
343 if (isCurrentFileAST()) {
345 CI.resetAndLeakASTContext();
346 CI.resetAndLeakPreprocessor();
347 CI.resetAndLeakSourceManager();
348 CI.resetAndLeakFileManager();
351 setCompilerInstance(0);
352 setCurrentFile("", IK_None);
355 //===----------------------------------------------------------------------===//
357 //===----------------------------------------------------------------------===//
359 void ASTFrontendAction::ExecuteAction() {
360 CompilerInstance &CI = getCompilerInstance();
362 // FIXME: Move the truncation aspect of this into Sema, we delayed this till
363 // here so the source manager would be initialized.
364 if (hasCodeCompletionSupport() &&
365 !CI.getFrontendOpts().CodeCompletionAt.FileName.empty())
366 CI.createCodeCompletionConsumer();
368 // Use a code completion consumer?
369 CodeCompleteConsumer *CompletionConsumer = 0;
370 if (CI.hasCodeCompletionConsumer())
371 CompletionConsumer = &CI.getCodeCompletionConsumer();
374 CI.createSema(usesCompleteTranslationUnit(), CompletionConsumer);
376 ParseAST(CI.getSema(), CI.getFrontendOpts().ShowStats);
380 PreprocessorFrontendAction::CreateASTConsumer(CompilerInstance &CI,
381 llvm::StringRef InFile) {
382 llvm_unreachable("Invalid CreateASTConsumer on preprocessor action!");