blob: 22b3bd416d8cdad31119a3a418f2f5110780bbdb [file] [log] [blame]
Daniel Dunbarcea0c702010-02-25 04:37:45 +00001//===--- CodeGenAction.cpp - LLVM Code Generation Frontend Action ---------===//
Daniel Dunbarc13935e2008-10-21 23:49:24 +00002//
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
Daniel Dunbarcea0c702010-02-25 04:37:45 +000010#include "clang/Frontend/CodeGenAction.h"
Chris Lattner5ec32e72010-04-06 18:38:50 +000011#include "clang/Basic/SourceManager.h"
12#include "clang/Basic/TargetInfo.h"
Chris Lattner5bbb3c82009-03-29 16:50:03 +000013#include "clang/AST/ASTConsumer.h"
Daniel Dunbarb9bbd542009-11-15 06:48:46 +000014#include "clang/AST/ASTContext.h"
Chris Lattner5bbb3c82009-03-29 16:50:03 +000015#include "clang/AST/DeclGroup.h"
Daniel Dunbarb9bbd542009-11-15 06:48:46 +000016#include "clang/CodeGen/ModuleBuilder.h"
Daniel Dunbarcea0c702010-02-25 04:37:45 +000017#include "clang/Frontend/ASTConsumers.h"
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000018#include "clang/Frontend/BackendUtil.h"
Daniel Dunbarcea0c702010-02-25 04:37:45 +000019#include "clang/Frontend/CompilerInstance.h"
Daniel Dunbaracadc552009-12-03 09:12:54 +000020#include "clang/Frontend/FrontendDiagnostic.h"
Chris Lattner6d672132010-04-06 17:52:14 +000021#include "llvm/LLVMContext.h"
Daniel Dunbarc13935e2008-10-21 23:49:24 +000022#include "llvm/Module.h"
Daniel Dunbar3e111522010-06-07 23:21:04 +000023#include "llvm/Pass.h"
Daniel Dunbarc13935e2008-10-21 23:49:24 +000024#include "llvm/ADT/OwningPtr.h"
Daniel Dunbar6f8362c2010-06-07 23:27:59 +000025#include "llvm/Support/IRReader.h"
Chris Lattner5ec32e72010-04-06 18:38:50 +000026#include "llvm/Support/MemoryBuffer.h"
27#include "llvm/Support/SourceMgr.h"
Chris Lattner263d64c2009-02-18 01:37:30 +000028#include "llvm/Support/Timer.h"
Daniel Dunbarc13935e2008-10-21 23:49:24 +000029using namespace clang;
30using namespace llvm;
31
32namespace {
Benjamin Kramer16634c22009-11-28 10:07:24 +000033 class BackendConsumer : public ASTConsumer {
Daniel Dunbar20c13162009-12-04 08:17:40 +000034 Diagnostic &Diags;
Daniel Dunbarc13935e2008-10-21 23:49:24 +000035 BackendAction Action;
Daniel Dunbarde182242009-11-30 08:39:32 +000036 const CodeGenOptions &CodeGenOpts;
Daniel Dunbarde182242009-11-30 08:39:32 +000037 const TargetOptions &TargetOpts;
Eli Friedman94cf21e2009-05-18 22:20:00 +000038 llvm::raw_ostream *AsmOutStream;
Chris Lattnereae6cb62009-03-05 08:00:35 +000039 ASTContext *Context;
Daniel Dunbarb3a36cf2008-10-29 08:50:02 +000040
Chris Lattner263d64c2009-02-18 01:37:30 +000041 Timer LLVMIRGeneration;
Mike Stump11289f42009-09-09 15:08:12 +000042
Daniel Dunbarc13935e2008-10-21 23:49:24 +000043 llvm::OwningPtr<CodeGenerator> Gen;
Mike Stump11289f42009-09-09 15:08:12 +000044
Daniel Dunbar400a6932010-02-25 04:37:50 +000045 llvm::OwningPtr<llvm::Module> TheModule;
Daniel Dunbarc13935e2008-10-21 23:49:24 +000046
Mike Stump11289f42009-09-09 15:08:12 +000047 public:
Daniel Dunbaracadc552009-12-03 09:12:54 +000048 BackendConsumer(BackendAction action, Diagnostic &_Diags,
Daniel Dunbar6d5824f2010-06-07 23:19:17 +000049 const CodeGenOptions &compopts,
Daniel Dunbar8e705052009-11-30 08:39:52 +000050 const TargetOptions &targetopts, bool TimePasses,
51 const std::string &infile, llvm::raw_ostream *OS,
Chris Lattner6d672132010-04-06 17:52:14 +000052 LLVMContext &C) :
Daniel Dunbaracadc552009-12-03 09:12:54 +000053 Diags(_Diags),
Mike Stump11289f42009-09-09 15:08:12 +000054 Action(action),
Chandler Carruthbc55fe22009-11-12 17:24:48 +000055 CodeGenOpts(compopts),
Daniel Dunbarb9bbd542009-11-15 06:48:46 +000056 TargetOpts(targetopts),
Chris Lattner15681772009-07-14 20:39:15 +000057 AsmOutStream(OS),
Chris Lattner263d64c2009-02-18 01:37:30 +000058 LLVMIRGeneration("LLVM IR Generation Time"),
Daniel Dunbar3e111522010-06-07 23:21:04 +000059 Gen(CreateLLVMCodeGen(Diags, infile, compopts, C)) {
Daniel Dunbar8e705052009-11-30 08:39:52 +000060 llvm::TimePassesIsEnabled = TimePasses;
Chris Lattnerdeffa132009-02-18 01:23:44 +000061 }
Daniel Dunbarc13935e2008-10-21 23:49:24 +000062
Daniel Dunbar400a6932010-02-25 04:37:50 +000063 llvm::Module *takeModule() { return TheModule.take(); }
64
Chris Lattner5cf49fe2009-03-28 02:18:25 +000065 virtual void Initialize(ASTContext &Ctx) {
66 Context = &Ctx;
Mike Stump11289f42009-09-09 15:08:12 +000067
Daniel Dunbar8e705052009-11-30 08:39:52 +000068 if (llvm::TimePassesIsEnabled)
Chris Lattner263d64c2009-02-18 01:37:30 +000069 LLVMIRGeneration.startTimer();
Mike Stump11289f42009-09-09 15:08:12 +000070
Chris Lattner5cf49fe2009-03-28 02:18:25 +000071 Gen->Initialize(Ctx);
Daniel Dunbarc13935e2008-10-21 23:49:24 +000072
Daniel Dunbar400a6932010-02-25 04:37:50 +000073 TheModule.reset(Gen->GetModule());
Mike Stump11289f42009-09-09 15:08:12 +000074
Daniel Dunbar8e705052009-11-30 08:39:52 +000075 if (llvm::TimePassesIsEnabled)
Chris Lattner263d64c2009-02-18 01:37:30 +000076 LLVMIRGeneration.stopTimer();
Daniel Dunbarc13935e2008-10-21 23:49:24 +000077 }
Mike Stump11289f42009-09-09 15:08:12 +000078
Chris Lattner5bbb3c82009-03-29 16:50:03 +000079 virtual void HandleTopLevelDecl(DeclGroupRef D) {
80 PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
Chris Lattnereae6cb62009-03-05 08:00:35 +000081 Context->getSourceManager(),
82 "LLVM IR generation of declaration");
Mike Stump11289f42009-09-09 15:08:12 +000083
Daniel Dunbar8e705052009-11-30 08:39:52 +000084 if (llvm::TimePassesIsEnabled)
Chris Lattner263d64c2009-02-18 01:37:30 +000085 LLVMIRGeneration.startTimer();
Chris Lattner5bbb3c82009-03-29 16:50:03 +000086
Daniel Dunbarc13935e2008-10-21 23:49:24 +000087 Gen->HandleTopLevelDecl(D);
Chris Lattner263d64c2009-02-18 01:37:30 +000088
Daniel Dunbar8e705052009-11-30 08:39:52 +000089 if (llvm::TimePassesIsEnabled)
Chris Lattner263d64c2009-02-18 01:37:30 +000090 LLVMIRGeneration.stopTimer();
Daniel Dunbarc13935e2008-10-21 23:49:24 +000091 }
Mike Stump11289f42009-09-09 15:08:12 +000092
Chris Lattnercf169832009-03-28 04:11:33 +000093 virtual void HandleTranslationUnit(ASTContext &C) {
Chris Lattnereae6cb62009-03-05 08:00:35 +000094 {
Chris Lattnere46de752009-03-06 06:46:31 +000095 PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
Daniel Dunbar8e705052009-11-30 08:39:52 +000096 if (llvm::TimePassesIsEnabled)
Chris Lattnereae6cb62009-03-05 08:00:35 +000097 LLVMIRGeneration.startTimer();
Chris Lattner263d64c2009-02-18 01:37:30 +000098
Chris Lattnercf169832009-03-28 04:11:33 +000099 Gen->HandleTranslationUnit(C);
Daniel Dunbara94d8732008-11-11 06:35:39 +0000100
Daniel Dunbar8e705052009-11-30 08:39:52 +0000101 if (llvm::TimePassesIsEnabled)
Chris Lattnereae6cb62009-03-05 08:00:35 +0000102 LLVMIRGeneration.stopTimer();
103 }
Chris Lattner263d64c2009-02-18 01:37:30 +0000104
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000105 // Silently ignore if we weren't initialized for some reason.
Daniel Dunbar3e111522010-06-07 23:21:04 +0000106 if (!TheModule)
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000107 return;
Mike Stump11289f42009-09-09 15:08:12 +0000108
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000109 // Make sure IR generation is happy with the module. This is released by
110 // the module provider.
111 Module *M = Gen->ReleaseModule();
112 if (!M) {
113 // The module has been released by IR gen on failures, do not double
114 // free.
115 TheModule.take();
116 return;
117 }
118
119 assert(TheModule.get() == M &&
120 "Unexpected module change during IR generation");
121
122 // Install an inline asm handler so that diagnostics get printed through
123 // our diagnostics hooks.
124 LLVMContext &Ctx = TheModule->getContext();
125 void *OldHandler = Ctx.getInlineAsmDiagnosticHandler();
126 void *OldContext = Ctx.getInlineAsmDiagnosticContext();
127 Ctx.setInlineAsmDiagnosticHandler((void*)(intptr_t)InlineAsmDiagHandler,
128 this);
129
130 EmitBackendOutput(Diags, CodeGenOpts, TargetOpts,
Daniel Dunbar3e111522010-06-07 23:21:04 +0000131 TheModule.get(), Action, AsmOutStream);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000132
133 Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000134 }
Mike Stump11289f42009-09-09 15:08:12 +0000135
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000136 virtual void HandleTagDeclDefinition(TagDecl *D) {
Chris Lattnereae6cb62009-03-05 08:00:35 +0000137 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
138 Context->getSourceManager(),
139 "LLVM IR generation of declaration");
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000140 Gen->HandleTagDeclDefinition(D);
141 }
Douglas Gregorbeecd582009-04-21 17:11:58 +0000142
143 virtual void CompleteTentativeDefinition(VarDecl *D) {
144 Gen->CompleteTentativeDefinition(D);
145 }
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000146
Douglas Gregor88d292c2010-05-13 16:44:06 +0000147 virtual void HandleVTable(CXXRecordDecl *RD, bool DefinitionRequired) {
148 Gen->HandleVTable(RD, DefinitionRequired);
149 }
150
Chris Lattner5ec32e72010-04-06 18:38:50 +0000151 static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context,
152 unsigned LocCookie) {
153 SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie);
154 ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
155 }
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000156
Chris Lattner5ec32e72010-04-06 18:38:50 +0000157 void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
158 SourceLocation LocCookie);
Mike Stump11289f42009-09-09 15:08:12 +0000159 };
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000160}
161
Chris Lattner79f67a72010-04-08 00:23:06 +0000162/// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
163/// buffer to be a valid FullSourceLoc.
164static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
165 SourceManager &CSM) {
166 // Get both the clang and llvm source managers. The location is relative to
167 // a memory buffer that the LLVM Source Manager is handling, we need to add
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000168 // a copy to the Clang source manager.
Chris Lattner79f67a72010-04-08 00:23:06 +0000169 const llvm::SourceMgr &LSM = *D.getSourceMgr();
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000170
Chris Lattner79f67a72010-04-08 00:23:06 +0000171 // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
172 // already owns its one and clang::SourceManager wants to own its one.
173 const MemoryBuffer *LBuf =
174 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000175
Chris Lattner79f67a72010-04-08 00:23:06 +0000176 // Create the copy and transfer ownership to clang::SourceManager.
177 llvm::MemoryBuffer *CBuf =
178 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
179 LBuf->getBufferIdentifier());
180 FileID FID = CSM.createFileIDForMemBuffer(CBuf);
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000181
Chris Lattner79f67a72010-04-08 00:23:06 +0000182 // Translate the offset into the file.
183 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000184 SourceLocation NewLoc =
Chris Lattner79f67a72010-04-08 00:23:06 +0000185 CSM.getLocForStartOfFile(FID).getFileLocWithOffset(Offset);
186 return FullSourceLoc(NewLoc, CSM);
187}
188
Chris Lattner6d672132010-04-06 17:52:14 +0000189
Chris Lattner5ec32e72010-04-06 18:38:50 +0000190/// InlineAsmDiagHandler2 - This function is invoked when the backend hits an
191/// error parsing inline asm. The SMDiagnostic indicates the error relative to
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000192/// the temporary memory buffer that the inline asm parser has set up.
Chris Lattner5ec32e72010-04-06 18:38:50 +0000193void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D,
194 SourceLocation LocCookie) {
195 // There are a couple of different kinds of errors we could get here. First,
196 // we re-format the SMDiagnostic in terms of a clang diagnostic.
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000197
Chris Lattner5ec32e72010-04-06 18:38:50 +0000198 // Strip "error: " off the start of the message string.
199 llvm::StringRef Message = D.getMessage();
200 if (Message.startswith("error: "))
201 Message = Message.substr(7);
202
203 // There are two cases: the SMDiagnostic could have a inline asm source
204 // location or it might not. If it does, translate the location.
205 FullSourceLoc Loc;
Chris Lattner79f67a72010-04-08 00:23:06 +0000206 if (D.getLoc() != SMLoc())
207 Loc = ConvertBackendLocation(D, Context->getSourceManager());
Chris Lattner5ec32e72010-04-06 18:38:50 +0000208 Diags.Report(Loc, diag::err_fe_inline_asm).AddString(Message);
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000209
Chris Lattner5ec32e72010-04-06 18:38:50 +0000210 // This could be a problem with no clang-level source location information.
211 // In this case, LocCookie is invalid. If there is source level information,
212 // print an "generated from" note.
213 if (LocCookie.isValid())
214 Diags.Report(FullSourceLoc(LocCookie, Context->getSourceManager()),
215 diag::note_fe_inline_asm_here);
216}
217
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000218//
219
220CodeGenAction::CodeGenAction(unsigned _Act) : Act(_Act) {}
221
Daniel Dunbare8ecf9a2010-02-25 20:37:44 +0000222CodeGenAction::~CodeGenAction() {}
223
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000224bool CodeGenAction::hasIRSupport() const { return true; }
225
Daniel Dunbar400a6932010-02-25 04:37:50 +0000226void CodeGenAction::EndSourceFileAction() {
227 // If the consumer creation failed, do nothing.
228 if (!getCompilerInstance().hasASTConsumer())
229 return;
230
231 // Steal the module from the consumer.
232 BackendConsumer *Consumer = static_cast<BackendConsumer*>(
233 &getCompilerInstance().getASTConsumer());
234
235 TheModule.reset(Consumer->takeModule());
236}
237
238llvm::Module *CodeGenAction::takeModule() {
239 return TheModule.take();
240}
241
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000242static raw_ostream *GetOutputStream(CompilerInstance &CI,
243 llvm::StringRef InFile,
244 BackendAction Action) {
245 switch (Action) {
246 case Backend_EmitAssembly:
247 return CI.createDefaultOutputFile(false, InFile, "s");
248 case Backend_EmitLL:
249 return CI.createDefaultOutputFile(false, InFile, "ll");
250 case Backend_EmitBC:
251 return CI.createDefaultOutputFile(true, InFile, "bc");
252 case Backend_EmitNothing:
253 return 0;
254 case Backend_EmitMCNull:
255 case Backend_EmitObj:
256 return CI.createDefaultOutputFile(true, InFile, "o");
257 }
258
259 assert(0 && "Invalid action!");
260 return 0;
261}
262
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000263ASTConsumer *CodeGenAction::CreateASTConsumer(CompilerInstance &CI,
264 llvm::StringRef InFile) {
265 BackendAction BA = static_cast<BackendAction>(Act);
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000266 llvm::OwningPtr<llvm::raw_ostream> OS(GetOutputStream(CI, InFile, BA));
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000267 if (BA != Backend_EmitNothing && !OS)
268 return 0;
269
Daniel Dunbar6d5824f2010-06-07 23:19:17 +0000270 return new BackendConsumer(BA, CI.getDiagnostics(),
John McCall731be662010-03-04 04:29:44 +0000271 CI.getCodeGenOpts(), CI.getTargetOpts(),
272 CI.getFrontendOpts().ShowTimers, InFile, OS.take(),
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000273 CI.getLLVMContext());
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000274}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000275
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000276void CodeGenAction::ExecuteAction() {
277 // If this is an IR file, we have to treat it specially.
278 if (getCurrentFileKind() == IK_LLVM_IR) {
279 BackendAction BA = static_cast<BackendAction>(Act);
280 CompilerInstance &CI = getCompilerInstance();
281 raw_ostream *OS = GetOutputStream(CI, getCurrentFile(), BA);
282 if (BA != Backend_EmitNothing && !OS)
283 return;
284
285 bool Invalid;
286 SourceManager &SM = CI.getSourceManager();
287 const llvm::MemoryBuffer *MainFile = SM.getBuffer(SM.getMainFileID(),
288 &Invalid);
289 if (Invalid)
290 return;
291
292 // FIXME: This is stupid, IRReader shouldn't take ownership.
293 llvm::MemoryBuffer *MainFileCopy =
294 llvm::MemoryBuffer::getMemBufferCopy(MainFile->getBuffer(),
295 getCurrentFile().c_str());
296
297 llvm::SMDiagnostic Err;
298 TheModule.reset(ParseIR(MainFileCopy, Err, CI.getLLVMContext()));
299 if (!TheModule) {
300 // Translate from the diagnostic info to the SourceManager location.
301 SourceLocation Loc = SM.getLocation(
302 SM.getFileEntryForID(SM.getMainFileID()), Err.getLineNo(),
303 Err.getColumnNo() + 1);
304
305 // Get a custom diagnostic for the error. We strip off a leading
306 // diagnostic code if there is one.
307 llvm::StringRef Msg = Err.getMessage();
308 if (Msg.startswith("error: "))
309 Msg = Msg.substr(7);
310 unsigned DiagID = CI.getDiagnostics().getCustomDiagID(Diagnostic::Error,
311 Msg);
312
313 CI.getDiagnostics().Report(FullSourceLoc(Loc, SM), DiagID);
314 return;
315 }
316
317 EmitBackendOutput(CI.getDiagnostics(), CI.getCodeGenOpts(),
318 CI.getTargetOpts(), TheModule.get(),
319 BA, OS);
320 return;
321 }
322
323 // Otherwise follow the normal AST path.
324 this->ASTFrontendAction::ExecuteAction();
325}
326
327//
328
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000329EmitAssemblyAction::EmitAssemblyAction()
330 : CodeGenAction(Backend_EmitAssembly) {}
331
332EmitBCAction::EmitBCAction() : CodeGenAction(Backend_EmitBC) {}
333
334EmitLLVMAction::EmitLLVMAction() : CodeGenAction(Backend_EmitLL) {}
335
336EmitLLVMOnlyAction::EmitLLVMOnlyAction() : CodeGenAction(Backend_EmitNothing) {}
337
Daniel Dunbar4c77a642010-05-25 18:41:01 +0000338EmitCodeGenOnlyAction::EmitCodeGenOnlyAction() : CodeGenAction(Backend_EmitMCNull) {}
339
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000340EmitObjAction::EmitObjAction() : CodeGenAction(Backend_EmitObj) {}