blob: 9c5c45de5e909c082717c12379bbc9fb11cfe8ee [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +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"
16#include "clang/Basic/TargetInfo.h"
17#include "clang/AST/AST.h"
Nate Begeman440b4562008-03-07 20:04:22 +000018#include "llvm/CallingConv.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000019#include "llvm/Constants.h"
20#include "llvm/DerivedTypes.h"
21#include "llvm/Function.h"
22#include "llvm/Analysis/Verifier.h"
Devang Pateld9363c32007-09-28 21:49:18 +000023#include "llvm/Support/CFG.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000024using namespace clang;
25using namespace CodeGen;
26
27CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
Devang Patelc049e4f2007-10-08 20:57:48 +000028 : CGM(cgm), Target(CGM.getContext().Target), SwitchInsn(NULL),
Chris Lattnerce5605e2008-03-30 23:25:33 +000029 CaseRangeBlock(NULL) {}
Reid Spencer5f016e22007-07-11 17:01:13 +000030
31ASTContext &CodeGenFunction::getContext() const {
32 return CGM.getContext();
33}
34
35
36llvm::BasicBlock *CodeGenFunction::getBasicBlockForLabel(const LabelStmt *S) {
37 llvm::BasicBlock *&BB = LabelMap[S];
38 if (BB) return BB;
39
40 // Create, but don't insert, the new block.
Gabor Greif984d0b42008-04-06 20:42:52 +000041 return BB = llvm::BasicBlock::Create(S->getName());
Reid Spencer5f016e22007-07-11 17:01:13 +000042}
43
Lauro Ramos Venancio81373352008-02-26 21:41:45 +000044llvm::Constant *
Steve Naroff248a7532008-04-15 22:42:06 +000045CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) {
Lauro Ramos Venancio81373352008-02-26 21:41:45 +000046 return cast<llvm::Constant>(LocalDeclMap[BVD]);
47}
Reid Spencer5f016e22007-07-11 17:01:13 +000048
49const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
50 return CGM.getTypes().ConvertType(T);
51}
52
53bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
Chris Lattner423a3c92008-04-02 17:45:06 +000054 return !T->isRealType() && !T->isPointerLikeType() &&
Anders Carlsson793680e2007-10-12 23:56:29 +000055 !T->isVoidType() && !T->isVectorType() && !T->isFunctionType();
Reid Spencer5f016e22007-07-11 17:01:13 +000056}
57
Chris Lattner391d77a2008-03-30 23:03:07 +000058/// Generate an Objective-C method. An Objective-C method is a C function with
59/// its pointer, name, and types registered in the class struture.
60// FIXME: This method contains a lot of code copied and pasted from
61// GenerateCode. This should be factored out.
62void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
63 llvm::SmallVector<const llvm::Type *, 16> ParamTypes;
64 for (unsigned i=0 ; i<OMD->param_size() ; i++) {
65 ParamTypes.push_back(ConvertType(OMD->getParamDecl(i)->getType()));
66 }
Chris Lattnerce5605e2008-03-30 23:25:33 +000067 CurFn =CGM.getObjCRuntime()->MethodPreamble(ConvertType(OMD->getResultType()),
68 llvm::PointerType::getUnqual(llvm::Type::Int32Ty),
69 ParamTypes.begin(),
70 OMD->param_size(),
71 OMD->isVariadic());
Gabor Greif984d0b42008-04-06 20:42:52 +000072 llvm::BasicBlock *EntryBB = llvm::BasicBlock::Create("entry", CurFn);
Chris Lattner391d77a2008-03-30 23:03:07 +000073
74 // Create a marker to make it easy to insert allocas into the entryblock
75 // later. Don't create this with the builder, because we don't want it
76 // folded.
77 llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::Int32Ty);
78 AllocaInsertPt = new llvm::BitCastInst(Undef, llvm::Type::Int32Ty, "allocapt",
79 EntryBB);
80
81 FnRetTy = OMD->getResultType();
82
83 Builder.SetInsertPoint(EntryBB);
84
85 // Emit allocs for param decls. Give the LLVM Argument nodes names.
86 llvm::Function::arg_iterator AI = CurFn->arg_begin();
87
88 // Name the struct return argument.
89 // FIXME: Probably should be in the runtime, or it will trample the other
90 // hidden arguments.
91 if (hasAggregateLLVMType(OMD->getResultType())) {
92 AI->setName("agg.result");
93 ++AI;
94 }
95
96 // Add implicit parameters to the decl map.
97 // TODO: Add something to AST to let the runtime specify the names and types
98 // of these.
99 llvm::Value *&DMEntry = LocalDeclMap[&(*OMD->getSelfDecl())];
Chris Lattnerc8aa5f12008-04-04 04:07:35 +0000100 const llvm::Type *SelfTy = AI->getType();
101 llvm::Value *DeclPtr = new llvm::AllocaInst(SelfTy, 0, "self.addr",
102 AllocaInsertPt);
103
104 // Store the initial value into the alloca.
105 Builder.CreateStore(AI, DeclPtr);
106 DMEntry = DeclPtr;
Chris Lattner391d77a2008-03-30 23:03:07 +0000107 ++AI; ++AI;
108
109
110 for (unsigned i = 0, e = OMD->getNumParams(); i != e; ++i, ++AI) {
111 assert(AI != CurFn->arg_end() && "Argument mismatch!");
112 EmitParmDecl(*OMD->getParamDecl(i), AI);
113 }
114
115 // Emit the function body.
116 EmitStmt(OMD->getBody());
117
118 // Emit a return for code that falls off the end. If insert point
119 // is a dummy block with no predecessors then remove the block itself.
120 llvm::BasicBlock *BB = Builder.GetInsertBlock();
121 if (isDummyBlock(BB))
122 BB->eraseFromParent();
123 else {
124 if (CurFn->getReturnType() == llvm::Type::VoidTy)
125 Builder.CreateRetVoid();
126 else
127 Builder.CreateRet(llvm::UndefValue::get(CurFn->getReturnType()));
128 }
129 assert(BreakContinueStack.empty() &&
130 "mismatched push/pop in break/continue stack!");
131
132 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
133 AllocaInsertPt->eraseFromParent();
134 AllocaInsertPt = 0;
135 // Verify that the function is well formed.
136 assert(!verifyFunction(*CurFn) && "Generated method is not well formed.");
137}
Reid Spencer5f016e22007-07-11 17:01:13 +0000138
Chris Lattnerc8aa5f12008-04-04 04:07:35 +0000139llvm::Value *CodeGenFunction::LoadObjCSelf(void)
140{
141 if(const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(CurFuncDecl)) {
142 llvm::Value *SelfPtr = LocalDeclMap[&(*OMD->getSelfDecl())];
143 return Builder.CreateLoad(SelfPtr, "self");
144 }
145 return NULL;
146}
147
Reid Spencer5f016e22007-07-11 17:01:13 +0000148void CodeGenFunction::GenerateCode(const FunctionDecl *FD) {
149 LLVMIntTy = ConvertType(getContext().IntTy);
Chris Lattner47f7dbf2007-09-04 02:34:27 +0000150 LLVMPointerWidth = static_cast<unsigned>(
Chris Lattner98be4942008-03-05 18:54:05 +0000151 getContext().getTypeSize(getContext().getPointerType(getContext().VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +0000152
Reid Spencer5f016e22007-07-11 17:01:13 +0000153 CurFuncDecl = FD;
Chris Lattnerc8aa5f12008-04-04 04:07:35 +0000154 FnRetTy = FD->getType()->getAsFunctionType()->getResultType();
Chris Lattner391d77a2008-03-30 23:03:07 +0000155
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000156 CurFn = cast<llvm::Function>(CGM.GetAddrOfFunctionDecl(FD, true));
Reid Spencer5f016e22007-07-11 17:01:13 +0000157 assert(CurFn->isDeclaration() && "Function already has body?");
158
Chris Lattner5c6a42a2007-11-27 06:46:51 +0000159 // TODO: Set up linkage and many other things. Note, this is a simple
160 // approximation of what we really want.
Chris Lattner8fabd782008-05-04 01:44:26 +0000161 if (FD->getStorageClass() == FunctionDecl::Static)
162 CurFn->setLinkage(llvm::Function::InternalLinkage);
163 else if (FD->getAttr<DLLImportAttr>())
Chris Lattnerddee4232008-03-03 03:28:21 +0000164 CurFn->setLinkage(llvm::Function::DLLImportLinkage);
165 else if (FD->getAttr<DLLExportAttr>())
166 CurFn->setLinkage(llvm::Function::DLLExportLinkage);
167 else if (FD->getAttr<WeakAttr>() || FD->isInline())
Chris Lattner5c6a42a2007-11-27 06:46:51 +0000168 CurFn->setLinkage(llvm::Function::WeakLinkage);
Chris Lattnerddee4232008-03-03 03:28:21 +0000169
Nate Begeman440b4562008-03-07 20:04:22 +0000170 if (FD->getAttr<FastCallAttr>())
171 CurFn->setCallingConv(llvm::CallingConv::Fast);
172
Chris Lattnerddee4232008-03-03 03:28:21 +0000173 if (const VisibilityAttr *attr = FD->getAttr<VisibilityAttr>())
174 CurFn->setVisibility(attr->getVisibility());
175 // FIXME: else handle -fvisibility
176
177
Chris Lattnerf89e88d2008-03-03 03:45:26 +0000178 unsigned FuncAttrs = 0;
Chris Lattnerddee4232008-03-03 03:28:21 +0000179 if (FD->getAttr<NoThrowAttr>())
Chris Lattnerf89e88d2008-03-03 03:45:26 +0000180 FuncAttrs |= llvm::ParamAttr::NoUnwind;
Chris Lattnerddee4232008-03-03 03:28:21 +0000181 if (FD->getAttr<NoReturnAttr>())
Chris Lattnerf89e88d2008-03-03 03:45:26 +0000182 FuncAttrs |= llvm::ParamAttr::NoReturn;
183
184 if (FuncAttrs) {
Chris Lattnere0e0c942008-03-12 17:46:07 +0000185 llvm::ParamAttrsWithIndex PAWI =
186 llvm::ParamAttrsWithIndex::get(0, FuncAttrs);
187 CurFn->setParamAttrs(llvm::PAListPtr::get(&PAWI, 1));
Chris Lattnerf89e88d2008-03-03 03:45:26 +0000188 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000189
Gabor Greif984d0b42008-04-06 20:42:52 +0000190 llvm::BasicBlock *EntryBB = llvm::BasicBlock::Create("entry", CurFn);
Reid Spencer5f016e22007-07-11 17:01:13 +0000191
Reid Spencer5f016e22007-07-11 17:01:13 +0000192 // Create a marker to make it easy to insert allocas into the entryblock
Chris Lattner55352a22007-12-17 20:50:59 +0000193 // later. Don't create this with the builder, because we don't want it
194 // folded.
Reid Spencer5f016e22007-07-11 17:01:13 +0000195 llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::Int32Ty);
Chris Lattner55352a22007-12-17 20:50:59 +0000196 AllocaInsertPt = new llvm::BitCastInst(Undef, llvm::Type::Int32Ty, "allocapt",
197 EntryBB);
198
199 Builder.SetInsertPoint(EntryBB);
Reid Spencer5f016e22007-07-11 17:01:13 +0000200
201 // Emit allocs for param decls. Give the LLVM Argument nodes names.
202 llvm::Function::arg_iterator AI = CurFn->arg_begin();
203
204 // Name the struct return argument.
205 if (hasAggregateLLVMType(FD->getResultType())) {
206 AI->setName("agg.result");
207 ++AI;
208 }
209
210 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i, ++AI) {
211 assert(AI != CurFn->arg_end() && "Argument mismatch!");
212 EmitParmDecl(*FD->getParamDecl(i), AI);
213 }
214
215 // Emit the function body.
216 EmitStmt(FD->getBody());
217
Devang Pateld9363c32007-09-28 21:49:18 +0000218 // Emit a return for code that falls off the end. If insert point
219 // is a dummy block with no predecessors then remove the block itself.
220 llvm::BasicBlock *BB = Builder.GetInsertBlock();
221 if (isDummyBlock(BB))
222 BB->eraseFromParent();
223 else {
224 // FIXME: if this is C++ main, this should return 0.
225 if (CurFn->getReturnType() == llvm::Type::VoidTy)
226 Builder.CreateRetVoid();
227 else
228 Builder.CreateRet(llvm::UndefValue::get(CurFn->getReturnType()));
229 }
Chris Lattnerda138702007-07-16 21:28:45 +0000230 assert(BreakContinueStack.empty() &&
231 "mismatched push/pop in break/continue stack!");
232
Chris Lattner5a2fa142007-12-02 06:32:24 +0000233 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
234 AllocaInsertPt->eraseFromParent();
235 AllocaInsertPt = 0;
236
Reid Spencer5f016e22007-07-11 17:01:13 +0000237 // Verify that the function is well formed.
Chris Lattner391d77a2008-03-30 23:03:07 +0000238 assert(!verifyFunction(*CurFn) && "Generated function is not well formed.");
Reid Spencer5f016e22007-07-11 17:01:13 +0000239}
240
Devang Pateld9363c32007-09-28 21:49:18 +0000241/// isDummyBlock - Return true if BB is an empty basic block
242/// with no predecessors.
243bool CodeGenFunction::isDummyBlock(const llvm::BasicBlock *BB) {
244 if (BB->empty() && pred_begin(BB) == pred_end(BB))
245 return true;
246 return false;
247}
248
Devang Patel51b09f22007-10-04 23:45:31 +0000249/// StartBlock - Start new block named N. If insert block is a dummy block
250/// then reuse it.
251void CodeGenFunction::StartBlock(const char *N) {
252 llvm::BasicBlock *BB = Builder.GetInsertBlock();
253 if (!isDummyBlock(BB))
Gabor Greif984d0b42008-04-06 20:42:52 +0000254 EmitBlock(llvm::BasicBlock::Create(N));
Devang Patel51b09f22007-10-04 23:45:31 +0000255 else
256 BB->setName(N);
257}
258
Devang Patel88a981b2007-11-01 19:11:01 +0000259/// getCGRecordLayout - Return record layout info.
260const CGRecordLayout *CodeGenFunction::getCGRecordLayout(CodeGenTypes &CGT,
Chris Lattneraf319132008-02-05 06:55:31 +0000261 QualType Ty) {
262 const RecordType *RTy = Ty->getAsRecordType();
263 assert (RTy && "Unexpected type. RecordType expected here.");
Devang Patelb84a06e2007-10-23 02:10:49 +0000264
Chris Lattneraf319132008-02-05 06:55:31 +0000265 return CGT.getCGRecordLayout(RTy->getDecl());
Devang Patelb84a06e2007-10-23 02:10:49 +0000266}
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000267
268/// WarnUnsupported - Print out a warning that codegen doesn't support the
269/// specified stmt yet.
Chris Lattnerdc4d2802007-12-02 01:49:16 +0000270void CodeGenFunction::WarnUnsupported(const Stmt *S, const char *Type) {
Chris Lattner2c8569d2007-12-02 07:19:18 +0000271 CGM.WarnUnsupported(S, Type);
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000272}
273