blob: 26a0cfbafbbac8187fe9426b4a820b5c3a43e072 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-function state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
15#include "CodeGenModule.h"
Eli Friedman9bc7c8d2008-05-22 01:40:10 +000016#include "CGDebugInfo.h"
Chris Lattner4b009652007-07-25 00:24:17 +000017#include "clang/Basic/TargetInfo.h"
18#include "clang/AST/AST.h"
Nate Begemand75d28b2008-03-07 20:04:22 +000019#include "llvm/CallingConv.h"
Chris Lattner4b009652007-07-25 00:24:17 +000020#include "llvm/Constants.h"
21#include "llvm/DerivedTypes.h"
22#include "llvm/Function.h"
23#include "llvm/Analysis/Verifier.h"
Devang Patel97299362007-09-28 21:49:18 +000024#include "llvm/Support/CFG.h"
Chris Lattner4b009652007-07-25 00:24:17 +000025using namespace clang;
26using namespace CodeGen;
27
28CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
Devang Patel347ca322007-10-08 20:57:48 +000029 : CGM(cgm), Target(CGM.getContext().Target), SwitchInsn(NULL),
Chris Lattnerc61e9f82008-03-30 23:25:33 +000030 CaseRangeBlock(NULL) {}
Chris Lattner4b009652007-07-25 00:24:17 +000031
32ASTContext &CodeGenFunction::getContext() const {
33 return CGM.getContext();
34}
35
36
37llvm::BasicBlock *CodeGenFunction::getBasicBlockForLabel(const LabelStmt *S) {
38 llvm::BasicBlock *&BB = LabelMap[S];
39 if (BB) return BB;
40
41 // Create, but don't insert, the new block.
Gabor Greif815e2c12008-04-06 20:42:52 +000042 return BB = llvm::BasicBlock::Create(S->getName());
Chris Lattner4b009652007-07-25 00:24:17 +000043}
44
Lauro Ramos Venancio934fb022008-02-26 21:41:45 +000045llvm::Constant *
Steve Naroff72a6ebc2008-04-15 22:42:06 +000046CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) {
Lauro Ramos Venancio934fb022008-02-26 21:41:45 +000047 return cast<llvm::Constant>(LocalDeclMap[BVD]);
48}
Chris Lattner4b009652007-07-25 00:24:17 +000049
50const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
51 return CGM.getTypes().ConvertType(T);
52}
53
54bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
Chris Lattnera05f7d22008-04-02 17:45:06 +000055 return !T->isRealType() && !T->isPointerLikeType() &&
Anders Carlssoncebb8d62007-10-12 23:56:29 +000056 !T->isVoidType() && !T->isVectorType() && !T->isFunctionType();
Chris Lattner4b009652007-07-25 00:24:17 +000057}
58
Chris Lattnerb326b172008-03-30 23:03:07 +000059/// Generate an Objective-C method. An Objective-C method is a C function with
60/// its pointer, name, and types registered in the class struture.
61// FIXME: This method contains a lot of code copied and pasted from
62// GenerateCode. This should be factored out.
63void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
64 llvm::SmallVector<const llvm::Type *, 16> ParamTypes;
65 for (unsigned i=0 ; i<OMD->param_size() ; i++) {
66 ParamTypes.push_back(ConvertType(OMD->getParamDecl(i)->getType()));
67 }
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000068 std::string CategoryName = "";
69 if (ObjCCategoryImplDecl *OCD =
70 dyn_cast<ObjCCategoryImplDecl>(OMD->getMethodContext())) {
71 CategoryName = OCD->getName();
72 }
73
74 CurFn =CGM.getObjCRuntime()->MethodPreamble(
75 OMD->getClassInterface()->getName(),
76 CategoryName,
77 OMD->getSelector().getName(),
78 ConvertType(OMD->getResultType()),
79 llvm::PointerType::getUnqual(llvm::Type::Int32Ty),
80 ParamTypes.begin(),
81 OMD->param_size(),
82 !OMD->isInstance(),
83 OMD->isVariadic());
Gabor Greif815e2c12008-04-06 20:42:52 +000084 llvm::BasicBlock *EntryBB = llvm::BasicBlock::Create("entry", CurFn);
Chris Lattnerb326b172008-03-30 23:03:07 +000085
86 // Create a marker to make it easy to insert allocas into the entryblock
87 // later. Don't create this with the builder, because we don't want it
88 // folded.
89 llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::Int32Ty);
90 AllocaInsertPt = new llvm::BitCastInst(Undef, llvm::Type::Int32Ty, "allocapt",
91 EntryBB);
92
93 FnRetTy = OMD->getResultType();
94
95 Builder.SetInsertPoint(EntryBB);
96
97 // Emit allocs for param decls. Give the LLVM Argument nodes names.
98 llvm::Function::arg_iterator AI = CurFn->arg_begin();
99
100 // Name the struct return argument.
101 // FIXME: Probably should be in the runtime, or it will trample the other
102 // hidden arguments.
103 if (hasAggregateLLVMType(OMD->getResultType())) {
104 AI->setName("agg.result");
105 ++AI;
106 }
107
108 // Add implicit parameters to the decl map.
109 // TODO: Add something to AST to let the runtime specify the names and types
110 // of these.
111 llvm::Value *&DMEntry = LocalDeclMap[&(*OMD->getSelfDecl())];
Chris Lattner6e6a5972008-04-04 04:07:35 +0000112 const llvm::Type *SelfTy = AI->getType();
113 llvm::Value *DeclPtr = new llvm::AllocaInst(SelfTy, 0, "self.addr",
114 AllocaInsertPt);
115
116 // Store the initial value into the alloca.
117 Builder.CreateStore(AI, DeclPtr);
118 DMEntry = DeclPtr;
Chris Lattnerb326b172008-03-30 23:03:07 +0000119 ++AI; ++AI;
120
121
122 for (unsigned i = 0, e = OMD->getNumParams(); i != e; ++i, ++AI) {
123 assert(AI != CurFn->arg_end() && "Argument mismatch!");
124 EmitParmDecl(*OMD->getParamDecl(i), AI);
125 }
126
127 // Emit the function body.
128 EmitStmt(OMD->getBody());
129
130 // Emit a return for code that falls off the end. If insert point
131 // is a dummy block with no predecessors then remove the block itself.
132 llvm::BasicBlock *BB = Builder.GetInsertBlock();
133 if (isDummyBlock(BB))
134 BB->eraseFromParent();
135 else {
136 if (CurFn->getReturnType() == llvm::Type::VoidTy)
137 Builder.CreateRetVoid();
138 else
139 Builder.CreateRet(llvm::UndefValue::get(CurFn->getReturnType()));
140 }
141 assert(BreakContinueStack.empty() &&
142 "mismatched push/pop in break/continue stack!");
143
144 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
145 AllocaInsertPt->eraseFromParent();
146 AllocaInsertPt = 0;
147 // Verify that the function is well formed.
148 assert(!verifyFunction(*CurFn) && "Generated method is not well formed.");
149}
Chris Lattner4b009652007-07-25 00:24:17 +0000150
Chris Lattner6e6a5972008-04-04 04:07:35 +0000151llvm::Value *CodeGenFunction::LoadObjCSelf(void)
152{
153 if(const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(CurFuncDecl)) {
154 llvm::Value *SelfPtr = LocalDeclMap[&(*OMD->getSelfDecl())];
155 return Builder.CreateLoad(SelfPtr, "self");
156 }
157 return NULL;
158}
159
Chris Lattner4b009652007-07-25 00:24:17 +0000160void CodeGenFunction::GenerateCode(const FunctionDecl *FD) {
161 LLVMIntTy = ConvertType(getContext().IntTy);
Chris Lattnera96e0d82007-09-04 02:34:27 +0000162 LLVMPointerWidth = static_cast<unsigned>(
Chris Lattner8cd0e932008-03-05 18:54:05 +0000163 getContext().getTypeSize(getContext().getPointerType(getContext().VoidTy)));
Chris Lattner4b009652007-07-25 00:24:17 +0000164
Chris Lattner4b009652007-07-25 00:24:17 +0000165 CurFuncDecl = FD;
Chris Lattner6e6a5972008-04-04 04:07:35 +0000166 FnRetTy = FD->getType()->getAsFunctionType()->getResultType();
Chris Lattnerb326b172008-03-30 23:03:07 +0000167
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000168 CurFn = cast<llvm::Function>(CGM.GetAddrOfFunctionDecl(FD, true));
Chris Lattner4b009652007-07-25 00:24:17 +0000169 assert(CurFn->isDeclaration() && "Function already has body?");
170
Chris Lattner23d9e712007-11-27 06:46:51 +0000171 // TODO: Set up linkage and many other things. Note, this is a simple
172 // approximation of what we really want.
Chris Lattner25094a42008-05-04 01:44:26 +0000173 if (FD->getStorageClass() == FunctionDecl::Static)
174 CurFn->setLinkage(llvm::Function::InternalLinkage);
175 else if (FD->getAttr<DLLImportAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000176 CurFn->setLinkage(llvm::Function::DLLImportLinkage);
177 else if (FD->getAttr<DLLExportAttr>())
178 CurFn->setLinkage(llvm::Function::DLLExportLinkage);
179 else if (FD->getAttr<WeakAttr>() || FD->isInline())
Chris Lattner23d9e712007-11-27 06:46:51 +0000180 CurFn->setLinkage(llvm::Function::WeakLinkage);
Chris Lattner402b3372008-03-03 03:28:21 +0000181
Nate Begemand75d28b2008-03-07 20:04:22 +0000182 if (FD->getAttr<FastCallAttr>())
183 CurFn->setCallingConv(llvm::CallingConv::Fast);
184
Chris Lattner402b3372008-03-03 03:28:21 +0000185 if (const VisibilityAttr *attr = FD->getAttr<VisibilityAttr>())
Dan Gohman4751a3a2008-05-22 00:50:06 +0000186 CodeGenModule::setVisibility(CurFn, attr->getVisibility());
Chris Lattner402b3372008-03-03 03:28:21 +0000187 // FIXME: else handle -fvisibility
188
189
Chris Lattner0b3357e2008-03-03 03:45:26 +0000190 unsigned FuncAttrs = 0;
Chris Lattner402b3372008-03-03 03:28:21 +0000191 if (FD->getAttr<NoThrowAttr>())
Chris Lattner0b3357e2008-03-03 03:45:26 +0000192 FuncAttrs |= llvm::ParamAttr::NoUnwind;
Chris Lattner402b3372008-03-03 03:28:21 +0000193 if (FD->getAttr<NoReturnAttr>())
Chris Lattner0b3357e2008-03-03 03:45:26 +0000194 FuncAttrs |= llvm::ParamAttr::NoReturn;
195
196 if (FuncAttrs) {
Chris Lattner8c83f082008-03-12 17:46:07 +0000197 llvm::ParamAttrsWithIndex PAWI =
198 llvm::ParamAttrsWithIndex::get(0, FuncAttrs);
199 CurFn->setParamAttrs(llvm::PAListPtr::get(&PAWI, 1));
Chris Lattner0b3357e2008-03-03 03:45:26 +0000200 }
Chris Lattner402b3372008-03-03 03:28:21 +0000201
Gabor Greif815e2c12008-04-06 20:42:52 +0000202 llvm::BasicBlock *EntryBB = llvm::BasicBlock::Create("entry", CurFn);
Chris Lattner4b009652007-07-25 00:24:17 +0000203
Chris Lattner4b009652007-07-25 00:24:17 +0000204 // Create a marker to make it easy to insert allocas into the entryblock
Chris Lattner40715f02007-12-17 20:50:59 +0000205 // later. Don't create this with the builder, because we don't want it
206 // folded.
Chris Lattner4b009652007-07-25 00:24:17 +0000207 llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::Int32Ty);
Chris Lattner40715f02007-12-17 20:50:59 +0000208 AllocaInsertPt = new llvm::BitCastInst(Undef, llvm::Type::Int32Ty, "allocapt",
209 EntryBB);
210
211 Builder.SetInsertPoint(EntryBB);
Eli Friedman9bc7c8d2008-05-22 01:40:10 +0000212
213 CGDebugInfo *DI = CGM.getDebugInfo();
214 if (DI) {
215 CompoundStmt* body = cast<CompoundStmt>(CurFuncDecl->getBody());
216 if (body->getLBracLoc().isValid()) {
217 DI->setLocation(body->getLBracLoc());
218 }
Sanjiv Gupta93eb8252008-05-25 05:15:42 +0000219 DI->EmitFunctionStart(FD, CurFn, Builder);
Eli Friedman9bc7c8d2008-05-22 01:40:10 +0000220 }
221
Chris Lattner4b009652007-07-25 00:24:17 +0000222 // Emit allocs for param decls. Give the LLVM Argument nodes names.
223 llvm::Function::arg_iterator AI = CurFn->arg_begin();
224
225 // Name the struct return argument.
226 if (hasAggregateLLVMType(FD->getResultType())) {
227 AI->setName("agg.result");
228 ++AI;
229 }
230
231 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i, ++AI) {
232 assert(AI != CurFn->arg_end() && "Argument mismatch!");
233 EmitParmDecl(*FD->getParamDecl(i), AI);
234 }
235
236 // Emit the function body.
237 EmitStmt(FD->getBody());
238
Sanjiv Gupta93eb8252008-05-25 05:15:42 +0000239 if (DI) {
240 CompoundStmt* body = cast<CompoundStmt>(CurFuncDecl->getBody());
241 if (body->getRBracLoc().isValid()) {
242 DI->setLocation(body->getRBracLoc());
243 }
244 DI->EmitRegionEnd(CurFn, Builder);
245 }
246
Devang Patel97299362007-09-28 21:49:18 +0000247 // Emit a return for code that falls off the end. If insert point
248 // is a dummy block with no predecessors then remove the block itself.
249 llvm::BasicBlock *BB = Builder.GetInsertBlock();
250 if (isDummyBlock(BB))
251 BB->eraseFromParent();
252 else {
253 // FIXME: if this is C++ main, this should return 0.
254 if (CurFn->getReturnType() == llvm::Type::VoidTy)
255 Builder.CreateRetVoid();
256 else
257 Builder.CreateRet(llvm::UndefValue::get(CurFn->getReturnType()));
258 }
Chris Lattner4b009652007-07-25 00:24:17 +0000259 assert(BreakContinueStack.empty() &&
260 "mismatched push/pop in break/continue stack!");
261
Chris Lattnerca929812007-12-02 06:32:24 +0000262 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
263 AllocaInsertPt->eraseFromParent();
264 AllocaInsertPt = 0;
265
Chris Lattner4b009652007-07-25 00:24:17 +0000266 // Verify that the function is well formed.
Chris Lattnerb326b172008-03-30 23:03:07 +0000267 assert(!verifyFunction(*CurFn) && "Generated function is not well formed.");
Chris Lattner4b009652007-07-25 00:24:17 +0000268}
269
Devang Patel97299362007-09-28 21:49:18 +0000270/// isDummyBlock - Return true if BB is an empty basic block
271/// with no predecessors.
272bool CodeGenFunction::isDummyBlock(const llvm::BasicBlock *BB) {
273 if (BB->empty() && pred_begin(BB) == pred_end(BB))
274 return true;
275 return false;
276}
277
Devang Patele58e0802007-10-04 23:45:31 +0000278/// StartBlock - Start new block named N. If insert block is a dummy block
279/// then reuse it.
280void CodeGenFunction::StartBlock(const char *N) {
281 llvm::BasicBlock *BB = Builder.GetInsertBlock();
282 if (!isDummyBlock(BB))
Gabor Greif815e2c12008-04-06 20:42:52 +0000283 EmitBlock(llvm::BasicBlock::Create(N));
Devang Patele58e0802007-10-04 23:45:31 +0000284 else
285 BB->setName(N);
286}
287
Devang Patel7a78e432007-11-01 19:11:01 +0000288/// getCGRecordLayout - Return record layout info.
289const CGRecordLayout *CodeGenFunction::getCGRecordLayout(CodeGenTypes &CGT,
Chris Lattner7b2543e2008-02-05 06:55:31 +0000290 QualType Ty) {
291 const RecordType *RTy = Ty->getAsRecordType();
292 assert (RTy && "Unexpected type. RecordType expected here.");
Devang Patelaebd83f2007-10-23 02:10:49 +0000293
Chris Lattner7b2543e2008-02-05 06:55:31 +0000294 return CGT.getCGRecordLayout(RTy->getDecl());
Devang Patelaebd83f2007-10-23 02:10:49 +0000295}
Chris Lattner9d4e6202007-12-02 01:43:38 +0000296
297/// WarnUnsupported - Print out a warning that codegen doesn't support the
298/// specified stmt yet.
Chris Lattnere8f49632007-12-02 01:49:16 +0000299void CodeGenFunction::WarnUnsupported(const Stmt *S, const char *Type) {
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000300 CGM.WarnUnsupported(S, Type);
Chris Lattner9d4e6202007-12-02 01:43:38 +0000301}
302