blob: 1a5c0422477ab3f365977cff847d850336a2f5f8 [file] [log] [blame]
Daniel Dunbar4ee24092009-11-14 10:42:35 +00001//===--- 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"
Sebastian Redlffaab3e2010-07-30 00:29:29 +000011#include "clang/AST/ASTConsumer.h"
Daniel Dunbar4ee24092009-11-14 10:42:35 +000012#include "clang/AST/ASTContext.h"
Nico Weber5aa74af2011-01-25 20:34:14 +000013#include "clang/AST/DeclGroup.h"
Daniel Dunbar4ee24092009-11-14 10:42:35 +000014#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"
Nico Weber5aa74af2011-01-25 20:34:14 +000019#include "clang/Frontend/FrontendPluginRegistry.h"
20#include "clang/Frontend/MultiplexConsumer.h"
John McCall19510852010-08-20 18:27:03 +000021#include "clang/Parse/ParseAST.h"
Argyrios Kyrtzidisb9728582010-10-14 20:14:18 +000022#include "clang/Serialization/ASTDeserializationListener.h"
Daniel Dunbar4ee24092009-11-14 10:42:35 +000023#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/Timer.h"
25#include "llvm/Support/ErrorHandling.h"
26#include "llvm/Support/raw_ostream.h"
27using namespace clang;
28
Argyrios Kyrtzidisb9728582010-10-14 20:14:18 +000029namespace {
30
31/// \brief Dumps deserialized declarations.
32class DeserializedDeclsDumper : public ASTDeserializationListener {
33 ASTDeserializationListener *Previous;
34
35public:
36 DeserializedDeclsDumper(ASTDeserializationListener *Previous)
37 : Previous(Previous) { }
38
39 virtual void DeclRead(serialization::DeclID ID, const Decl *D) {
40 llvm::outs() << "PCH DECL: " << D->getDeclKindName();
41 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
42 llvm::outs() << " - " << ND->getNameAsString();
43 llvm::outs() << "\n";
44
45 if (Previous)
46 Previous->DeclRead(ID, D);
47 }
Argyrios Kyrtzidisb9728582010-10-14 20:14:18 +000048};
49
Argyrios Kyrtzidis3e785932010-10-14 20:14:25 +000050 /// \brief Checks deserialized declarations and emits error if a name
51 /// matches one given in command-line using -error-on-deserialized-decl.
52 class DeserializedDeclsChecker : public ASTDeserializationListener {
53 ASTContext &Ctx;
54 std::set<std::string> NamesToCheck;
55 ASTDeserializationListener *Previous;
56
57 public:
58 DeserializedDeclsChecker(ASTContext &Ctx,
59 const std::set<std::string> &NamesToCheck,
60 ASTDeserializationListener *Previous)
61 : Ctx(Ctx), NamesToCheck(NamesToCheck), Previous(Previous) { }
62
63 virtual void DeclRead(serialization::DeclID ID, const Decl *D) {
64 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
65 if (NamesToCheck.find(ND->getNameAsString()) != NamesToCheck.end()) {
66 unsigned DiagID
67 = Ctx.getDiagnostics().getCustomDiagID(Diagnostic::Error,
68 "%0 was deserialized");
69 Ctx.getDiagnostics().Report(Ctx.getFullLoc(D->getLocation()), DiagID)
70 << ND->getNameAsString();
71 }
72
73 if (Previous)
74 Previous->DeclRead(ID, D);
75 }
Argyrios Kyrtzidis3e785932010-10-14 20:14:25 +000076};
77
Argyrios Kyrtzidisb9728582010-10-14 20:14:18 +000078} // end anonymous namespace
79
Kovarththanan Rajaratnamf79bafa2009-11-29 09:57:35 +000080FrontendAction::FrontendAction() : Instance(0) {}
Daniel Dunbar4ee24092009-11-14 10:42:35 +000081
82FrontendAction::~FrontendAction() {}
83
Daniel Dunbar685ac662010-06-07 23:25:49 +000084void FrontendAction::setCurrentFile(llvm::StringRef Value, InputKind Kind,
85 ASTUnit *AST) {
Daniel Dunbar4ee24092009-11-14 10:42:35 +000086 CurrentFile = Value;
Daniel Dunbar685ac662010-06-07 23:25:49 +000087 CurrentFileKind = Kind;
Daniel Dunbar4ee24092009-11-14 10:42:35 +000088 CurrentASTUnit.reset(AST);
89}
90
Nico Weber5aa74af2011-01-25 20:34:14 +000091ASTConsumer* FrontendAction::CreateWrappedASTConsumer(CompilerInstance &CI,
92 llvm::StringRef InFile) {
93 ASTConsumer* Consumer = CreateASTConsumer(CI, InFile);
94 if (!Consumer)
95 return 0;
96
97 if (CI.getFrontendOpts().AddPluginActions.size() == 0)
98 return Consumer;
99
100 // Make sure the non-plugin consumer is first, so that plugins can't
101 // modifiy the AST.
102 std::vector<ASTConsumer*> Consumers(1, Consumer);
103
104 for (size_t i = 0, e = CI.getFrontendOpts().AddPluginActions.size();
105 i != e; ++i) {
106 // This is O(|plugins| * |add_plugins|), but since both numbers are
107 // way below 50 in practice, that's ok.
108 for (FrontendPluginRegistry::iterator
109 it = FrontendPluginRegistry::begin(),
110 ie = FrontendPluginRegistry::end();
111 it != ie; ++it) {
112 if (it->getName() == CI.getFrontendOpts().AddPluginActions[i]) {
113 llvm::OwningPtr<PluginASTAction> P(it->instantiate());
114 FrontendAction* c = P.get();
115 if (P->ParseArgs(CI, CI.getFrontendOpts().PluginArgs))
116 Consumers.push_back(c->CreateASTConsumer(CI, InFile));
117 }
118 }
119 }
120
121 return new MultiplexConsumer(Consumers);
122}
123
Daniel Dunbar4ee24092009-11-14 10:42:35 +0000124bool FrontendAction::BeginSourceFile(CompilerInstance &CI,
125 llvm::StringRef Filename,
Daniel Dunbard3598a62010-06-07 23:23:06 +0000126 InputKind InputKind) {
Daniel Dunbar4ee24092009-11-14 10:42:35 +0000127 assert(!Instance && "Already processing a source file!");
128 assert(!Filename.empty() && "Unexpected empty filename!");
Daniel Dunbar685ac662010-06-07 23:25:49 +0000129 setCurrentFile(Filename, InputKind);
Daniel Dunbar4ee24092009-11-14 10:42:35 +0000130 setCompilerInstance(&CI);
131
132 // AST files follow a very different path, since they share objects via the
133 // AST unit.
Daniel Dunbar20560482010-06-07 23:23:50 +0000134 if (InputKind == IK_AST) {
Daniel Dunbar4ee24092009-11-14 10:42:35 +0000135 assert(!usesPreprocessorOnly() &&
136 "Attempt to pass AST file to preprocessor only action!");
Daniel Dunbareb58d832010-06-07 23:24:43 +0000137 assert(hasASTFileSupport() &&
138 "This action does not have AST file support!");
Daniel Dunbar4ee24092009-11-14 10:42:35 +0000139
Douglas Gregor28019772010-04-05 23:52:57 +0000140 llvm::IntrusiveRefCntPtr<Diagnostic> Diags(&CI.getDiagnostics());
Daniel Dunbar4ee24092009-11-14 10:42:35 +0000141 std::string Error;
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000142 ASTUnit *AST = ASTUnit::LoadFromASTFile(Filename, Diags,
143 CI.getFileSystemOpts());
Daniel Dunbar5262fda2009-12-03 01:45:44 +0000144 if (!AST)
Daniel Dunbar4ee24092009-11-14 10:42:35 +0000145 goto failure;
Daniel Dunbar4ee24092009-11-14 10:42:35 +0000146
Daniel Dunbar685ac662010-06-07 23:25:49 +0000147 setCurrentFile(Filename, InputKind, AST);
Daniel Dunbar4ee24092009-11-14 10:42:35 +0000148
149 // Set the shared objects, these are reset when we finish processing the
150 // file, otherwise the CompilerInstance will happily destroy them.
151 CI.setFileManager(&AST->getFileManager());
152 CI.setSourceManager(&AST->getSourceManager());
153 CI.setPreprocessor(&AST->getPreprocessor());
154 CI.setASTContext(&AST->getASTContext());
155
156 // Initialize the action.
157 if (!BeginSourceFileAction(CI, Filename))
158 goto failure;
159
160 /// Create the AST consumer.
Nico Weber5aa74af2011-01-25 20:34:14 +0000161 CI.setASTConsumer(CreateWrappedASTConsumer(CI, Filename));
Daniel Dunbar4ee24092009-11-14 10:42:35 +0000162 if (!CI.hasASTConsumer())
163 goto failure;
164
165 return true;
166 }
167
Daniel Dunbarfaddc3e2010-06-07 23:26:47 +0000168 // Set up the file and source managers, if needed.
Daniel Dunbar20560482010-06-07 23:23:50 +0000169 if (!CI.hasFileManager())
170 CI.createFileManager();
171 if (!CI.hasSourceManager())
Chris Lattner39b49bc2010-11-23 08:35:12 +0000172 CI.createSourceManager(CI.getFileManager());
Daniel Dunbarfaddc3e2010-06-07 23:26:47 +0000173
174 // IR files bypass the rest of initialization.
175 if (InputKind == IK_LLVM_IR) {
176 assert(hasIRSupport() &&
177 "This action does not have IR file support!");
178
179 // Inform the diagnostic client we are processing a source file.
180 CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), 0);
181
182 // Initialize the action.
183 if (!BeginSourceFileAction(CI, Filename))
184 goto failure;
185
186 return true;
187 }
188
189 // Set up the preprocessor.
Daniel Dunbar20560482010-06-07 23:23:50 +0000190 CI.createPreprocessor();
191
Daniel Dunbar4ee24092009-11-14 10:42:35 +0000192 // Inform the diagnostic client we are processing a source file.
193 CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(),
194 &CI.getPreprocessor());
195
196 // Initialize the action.
197 if (!BeginSourceFileAction(CI, Filename))
198 goto failure;
199
200 /// Create the AST context and consumer unless this is a preprocessor only
201 /// action.
202 if (!usesPreprocessorOnly()) {
203 CI.createASTContext();
Daniel Dunbar4ee24092009-11-14 10:42:35 +0000204
Nico Weber5aa74af2011-01-25 20:34:14 +0000205 llvm::OwningPtr<ASTConsumer> Consumer(
206 CreateWrappedASTConsumer(CI, Filename));
Fariborz Jahaniand3057192010-10-29 19:49:13 +0000207 if (!Consumer)
208 goto failure;
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000209
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +0000210 CI.getASTContext().setASTMutationListener(Consumer->GetASTMutationListener());
211
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000212 /// Use PCH?
Daniel Dunbar049d3a02009-11-17 05:52:41 +0000213 if (!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
Daniel Dunbar4ee24092009-11-14 10:42:35 +0000214 assert(hasPCHSupport() && "This action does not have PCH support!");
Argyrios Kyrtzidisb9728582010-10-14 20:14:18 +0000215 ASTDeserializationListener *DeserialListener
216 = CI.getInvocation().getFrontendOpts().ChainedPCH ?
217 Consumer->GetASTDeserializationListener() : 0;
218 if (CI.getPreprocessorOpts().DumpDeserializedPCHDecls)
219 DeserialListener = new DeserializedDeclsDumper(DeserialListener);
Argyrios Kyrtzidis3e785932010-10-14 20:14:25 +0000220 if (!CI.getPreprocessorOpts().DeserializedPCHDeclsToErrorOn.empty())
221 DeserialListener = new DeserializedDeclsChecker(CI.getASTContext(),
222 CI.getPreprocessorOpts().DeserializedPCHDeclsToErrorOn,
223 DeserialListener);
Daniel Dunbar4ee24092009-11-14 10:42:35 +0000224 CI.createPCHExternalASTSource(
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000225 CI.getPreprocessorOpts().ImplicitPCHInclude,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000226 CI.getPreprocessorOpts().DisablePCHValidation,
Argyrios Kyrtzidisb9728582010-10-14 20:14:18 +0000227 DeserialListener);
Daniel Dunbar4ee24092009-11-14 10:42:35 +0000228 if (!CI.getASTContext().getExternalSource())
229 goto failure;
230 }
Sebastian Redl77f46032010-07-09 21:00:24 +0000231
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000232 CI.setASTConsumer(Consumer.take());
Sebastian Redl77f46032010-07-09 21:00:24 +0000233 if (!CI.hasASTConsumer())
234 goto failure;
Daniel Dunbar4ee24092009-11-14 10:42:35 +0000235 }
236
237 // Initialize builtin info as long as we aren't using an external AST
238 // source.
239 if (!CI.hasASTContext() || !CI.getASTContext().getExternalSource()) {
240 Preprocessor &PP = CI.getPreprocessor();
241 PP.getBuiltinInfo().InitializeBuiltins(PP.getIdentifierTable(),
Fariborz Jahanian67aba812010-11-30 17:35:24 +0000242 PP.getLangOptions());
Daniel Dunbar4ee24092009-11-14 10:42:35 +0000243 }
244
245 return true;
246
247 // If we failed, reset state since the client will not end up calling the
248 // matching EndSourceFile().
249 failure:
250 if (isCurrentFileAST()) {
251 CI.takeASTContext();
252 CI.takePreprocessor();
253 CI.takeSourceManager();
254 CI.takeFileManager();
255 }
256
257 CI.getDiagnosticClient().EndSourceFile();
Daniel Dunbar685ac662010-06-07 23:25:49 +0000258 setCurrentFile("", IK_None);
Daniel Dunbar4ee24092009-11-14 10:42:35 +0000259 setCompilerInstance(0);
260 return false;
261}
262
263void FrontendAction::Execute() {
264 CompilerInstance &CI = getCompilerInstance();
265
266 // Initialize the main file entry. This needs to be delayed until after PCH
267 // has loaded.
268 if (isCurrentFileAST()) {
269 // Set the main file ID to an empty file.
270 //
271 // FIXME: We probably shouldn't need this, but for now this is the
272 // simplest way to reuse the logic in ParseAST.
273 const char *EmptyStr = "";
274 llvm::MemoryBuffer *SB =
Chris Lattnera0a270c2010-04-05 22:42:27 +0000275 llvm::MemoryBuffer::getMemBuffer(EmptyStr, "<dummy input>");
Daniel Dunbar4ee24092009-11-14 10:42:35 +0000276 CI.getSourceManager().createMainFileIDForMemBuffer(SB);
277 } else {
278 if (!CI.InitializeSourceManager(getCurrentFile()))
279 return;
280 }
281
Kovarththanan Rajaratnamf79bafa2009-11-29 09:57:35 +0000282 if (CI.hasFrontendTimer()) {
283 llvm::TimeRegion Timer(CI.getFrontendTimer());
284 ExecuteAction();
285 }
286 else ExecuteAction();
Daniel Dunbar4ee24092009-11-14 10:42:35 +0000287}
288
289void FrontendAction::EndSourceFile() {
290 CompilerInstance &CI = getCompilerInstance();
291
292 // Finalize the action.
293 EndSourceFileAction();
294
295 // Release the consumer and the AST, in that order since the consumer may
296 // perform actions in its destructor which require the context.
297 //
298 // FIXME: There is more per-file stuff we could just drop here?
299 if (CI.getFrontendOpts().DisableFree) {
300 CI.takeASTConsumer();
Douglas Gregorf18d0d82010-08-12 23:31:19 +0000301 if (!isCurrentFileAST()) {
302 CI.takeSema();
Daniel Dunbar4ee24092009-11-14 10:42:35 +0000303 CI.takeASTContext();
Douglas Gregorf18d0d82010-08-12 23:31:19 +0000304 }
Daniel Dunbar4ee24092009-11-14 10:42:35 +0000305 } else {
Douglas Gregorf18d0d82010-08-12 23:31:19 +0000306 if (!isCurrentFileAST()) {
307 CI.setSema(0);
Daniel Dunbar4ee24092009-11-14 10:42:35 +0000308 CI.setASTContext(0);
Douglas Gregorf18d0d82010-08-12 23:31:19 +0000309 }
310 CI.setASTConsumer(0);
Daniel Dunbar4ee24092009-11-14 10:42:35 +0000311 }
312
Daniel Dunbardbd82092010-03-23 05:09:10 +0000313 // Inform the preprocessor we are done.
314 if (CI.hasPreprocessor())
315 CI.getPreprocessor().EndSourceFile();
316
Daniel Dunbar4ee24092009-11-14 10:42:35 +0000317 if (CI.getFrontendOpts().ShowStats) {
318 llvm::errs() << "\nSTATISTICS FOR '" << getCurrentFile() << "':\n";
319 CI.getPreprocessor().PrintStats();
320 CI.getPreprocessor().getIdentifierTable().PrintStats();
321 CI.getPreprocessor().getHeaderSearchInfo().PrintStats();
322 CI.getSourceManager().PrintStats();
323 llvm::errs() << "\n";
324 }
325
326 // Cleanup the output streams, and erase the output files if we encountered
327 // an error.
Argyrios Kyrtzidisbe3aab62010-11-18 21:47:07 +0000328 CI.clearOutputFiles(/*EraseFiles=*/CI.getDiagnostics().hasErrorOccurred());
Daniel Dunbar4ee24092009-11-14 10:42:35 +0000329
330 // Inform the diagnostic client we are done with this source file.
331 CI.getDiagnosticClient().EndSourceFile();
332
333 if (isCurrentFileAST()) {
Douglas Gregorf18d0d82010-08-12 23:31:19 +0000334 CI.takeSema();
Daniel Dunbar4ee24092009-11-14 10:42:35 +0000335 CI.takeASTContext();
336 CI.takePreprocessor();
337 CI.takeSourceManager();
338 CI.takeFileManager();
339 }
340
341 setCompilerInstance(0);
Daniel Dunbar685ac662010-06-07 23:25:49 +0000342 setCurrentFile("", IK_None);
Daniel Dunbar4ee24092009-11-14 10:42:35 +0000343}
344
345//===----------------------------------------------------------------------===//
346// Utility Actions
347//===----------------------------------------------------------------------===//
348
349void ASTFrontendAction::ExecuteAction() {
350 CompilerInstance &CI = getCompilerInstance();
351
352 // FIXME: Move the truncation aspect of this into Sema, we delayed this till
353 // here so the source manager would be initialized.
354 if (hasCodeCompletionSupport() &&
355 !CI.getFrontendOpts().CodeCompletionAt.FileName.empty())
356 CI.createCodeCompletionConsumer();
357
358 // Use a code completion consumer?
359 CodeCompleteConsumer *CompletionConsumer = 0;
360 if (CI.hasCodeCompletionConsumer())
361 CompletionConsumer = &CI.getCodeCompletionConsumer();
362
Douglas Gregorf18d0d82010-08-12 23:31:19 +0000363 if (!CI.hasSema())
364 CI.createSema(usesCompleteTranslationUnit(), CompletionConsumer);
365
366 ParseAST(CI.getSema(), CI.getFrontendOpts().ShowStats);
Daniel Dunbar4ee24092009-11-14 10:42:35 +0000367}
368
369ASTConsumer *
370PreprocessorFrontendAction::CreateASTConsumer(CompilerInstance &CI,
371 llvm::StringRef InFile) {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +0000372 llvm_unreachable("Invalid CreateASTConsumer on preprocessor action!");
Daniel Dunbar4ee24092009-11-14 10:42:35 +0000373}