blob: d5e8c8a5881bcee5b8d9ebf159b0fde802331f3f [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"
Eli Friedman3f2af102008-05-22 01:40:10 +000016#include "CGDebugInfo.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000017#include "clang/Basic/TargetInfo.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000018#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000019#include "clang/AST/Decl.h"
Devang Pateld9363c32007-09-28 21:49:18 +000020#include "llvm/Support/CFG.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000021using namespace clang;
22using namespace CodeGen;
23
24CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
Devang Patelc049e4f2007-10-08 20:57:48 +000025 : CGM(cgm), Target(CGM.getContext().Target), SwitchInsn(NULL),
Chris Lattner41110242008-06-17 18:05:57 +000026 CaseRangeBlock(NULL) {
27 LLVMIntTy = ConvertType(getContext().IntTy);
28 LLVMPointerWidth = Target.getPointerWidth(0);
29}
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.
Daniel Dunbar55e87422008-11-11 02:29:29 +000041 return BB = createBasicBlock(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
Anders Carlssondde0a942008-09-11 09:15:33 +000049llvm::Value *CodeGenFunction::GetAddrOfLocalVar(const VarDecl *VD)
50{
51 return LocalDeclMap[VD];
52}
53
Reid Spencer5f016e22007-07-11 17:01:13 +000054const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
55 return CGM.getTypes().ConvertType(T);
56}
57
Chris Lattner41110242008-06-17 18:05:57 +000058bool CodeGenFunction::isObjCPointerType(QualType T) {
59 // All Objective-C types are pointers.
60 return T->isObjCInterfaceType() ||
61 T->isObjCQualifiedInterfaceType() || T->isObjCQualifiedIdType();
62}
63
Reid Spencer5f016e22007-07-11 17:01:13 +000064bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
Chris Lattner41110242008-06-17 18:05:57 +000065 return !isObjCPointerType(T) &&!T->isRealType() && !T->isPointerLikeType() &&
66 !T->isVoidType() && !T->isVectorType() && !T->isFunctionType();
Reid Spencer5f016e22007-07-11 17:01:13 +000067}
68
Daniel Dunbaraf05bb92008-08-26 08:29:31 +000069void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
Daniel Dunbar0ffb1252008-08-04 16:51:22 +000070 // Finish emission of indirect switches.
71 EmitIndirectSwitches();
72
Chris Lattnerda138702007-07-16 21:28:45 +000073 assert(BreakContinueStack.empty() &&
74 "mismatched push/pop in break/continue stack!");
Daniel Dunbar5ca20842008-09-09 21:00:17 +000075
Daniel Dunbarb01d1912008-09-27 07:15:59 +000076 // Emit function epilog (to return). This has the nice side effect
77 // of also automatically handling code that falls off the end.
78 EmitBlock(ReturnBlock);
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +000079
80 // Emit debug descriptor for function end.
81 if (CGDebugInfo *DI = CGM.getDebugInfo()) {
82 DI->setLocation(EndLoc);
83 DI->EmitRegionEnd(CurFn, Builder);
84 }
85
Daniel Dunbar17b708d2008-09-09 23:27:19 +000086 EmitFunctionEpilog(FnRetTy, ReturnValue);
Daniel Dunbar5ca20842008-09-09 21:00:17 +000087
Chris Lattner5a2fa142007-12-02 06:32:24 +000088 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
89 AllocaInsertPt->eraseFromParent();
90 AllocaInsertPt = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000091}
92
Daniel Dunbar7c086512008-09-09 23:14:03 +000093void CodeGenFunction::StartFunction(const Decl *D, QualType RetTy,
94 llvm::Function *Fn,
Daniel Dunbar2284ac92008-10-18 18:22:23 +000095 const FunctionArgList &Args,
96 SourceLocation StartLoc) {
Daniel Dunbar7c086512008-09-09 23:14:03 +000097 CurFuncDecl = D;
98 FnRetTy = RetTy;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +000099 CurFn = Fn;
Chris Lattner41110242008-06-17 18:05:57 +0000100 assert(CurFn->isDeclaration() && "Function already has body?");
101
Daniel Dunbar55e87422008-11-11 02:29:29 +0000102 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000103
Chris Lattner41110242008-06-17 18:05:57 +0000104 // Create a marker to make it easy to insert allocas into the entryblock
105 // later. Don't create this with the builder, because we don't want it
106 // folded.
107 llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::Int32Ty);
108 AllocaInsertPt = new llvm::BitCastInst(Undef, llvm::Type::Int32Ty, "allocapt",
109 EntryBB);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000110
Daniel Dunbar55e87422008-11-11 02:29:29 +0000111 ReturnBlock = createBasicBlock("return");
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000112 ReturnValue = 0;
Daniel Dunbar7c086512008-09-09 23:14:03 +0000113 if (!RetTy->isVoidType())
114 ReturnValue = CreateTempAlloca(ConvertType(RetTy), "retval");
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000115
Chris Lattner41110242008-06-17 18:05:57 +0000116 Builder.SetInsertPoint(EntryBB);
117
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000118 // Emit subprogram debug descriptor.
Daniel Dunbar7c086512008-09-09 23:14:03 +0000119 // FIXME: The cast here is a huge hack.
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000120 if (CGDebugInfo *DI = CGM.getDebugInfo()) {
121 DI->setLocation(StartLoc);
122 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
123 DI->EmitFunctionStart(FD->getName(), RetTy, CurFn, Builder);
124 } else {
125 // Just use LLVM function name.
126 DI->EmitFunctionStart(Fn->getName().c_str(),
127 RetTy, CurFn, Builder);
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000128 }
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000129 }
130
Daniel Dunbar17b708d2008-09-09 23:27:19 +0000131 EmitFunctionProlog(CurFn, FnRetTy, Args);
Daniel Dunbar7c086512008-09-09 23:14:03 +0000132}
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000133
Daniel Dunbar7c086512008-09-09 23:14:03 +0000134void CodeGenFunction::GenerateCode(const FunctionDecl *FD,
135 llvm::Function *Fn) {
136 FunctionArgList Args;
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000137 if (FD->getNumParams()) {
138 const FunctionTypeProto* FProto = FD->getType()->getAsFunctionTypeProto();
139 assert(FProto && "Function def must have prototype!");
Daniel Dunbar7c086512008-09-09 23:14:03 +0000140
141 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
142 Args.push_back(std::make_pair(FD->getParamDecl(i),
143 FProto->getArgType(i)));
Chris Lattner41110242008-06-17 18:05:57 +0000144 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000145
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000146 StartFunction(FD, FD->getResultType(), Fn, Args,
147 cast<CompoundStmt>(FD->getBody())->getLBracLoc());
Daniel Dunbar7c086512008-09-09 23:14:03 +0000148
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000149 EmitStmt(FD->getBody());
150
151 const CompoundStmt *S = dyn_cast<CompoundStmt>(FD->getBody());
152 if (S) {
153 FinishFunction(S->getRBracLoc());
154 } else {
155 FinishFunction();
156 }
Chris Lattner41110242008-06-17 18:05:57 +0000157}
158
Chris Lattner0946ccd2008-11-11 07:41:27 +0000159/// ContainsLabel - Return true if the statement contains a label in it. If
160/// this statement is not executed normally, it not containing a label means
161/// that we can just remove the code.
162bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
163 // Null statement, not a label!
164 if (S == 0) return false;
165
166 // If this is a label, we have to emit the code, consider something like:
167 // if (0) { ... foo: bar(); } goto foo;
168 if (isa<LabelStmt>(S))
169 return true;
170
171 // If this is a case/default statement, and we haven't seen a switch, we have
172 // to emit the code.
173 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
174 return true;
175
176 // If this is a switch statement, we want to ignore cases below it.
177 if (isa<SwitchStmt>(S))
178 IgnoreCaseStmts = true;
179
180 // Scan subexpressions for verboten labels.
181 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
182 I != E; ++I)
183 if (ContainsLabel(*I, IgnoreCaseStmts))
184 return true;
185
186 return false;
187}
188
Devang Patel88a981b2007-11-01 19:11:01 +0000189/// getCGRecordLayout - Return record layout info.
190const CGRecordLayout *CodeGenFunction::getCGRecordLayout(CodeGenTypes &CGT,
Chris Lattneraf319132008-02-05 06:55:31 +0000191 QualType Ty) {
192 const RecordType *RTy = Ty->getAsRecordType();
193 assert (RTy && "Unexpected type. RecordType expected here.");
Devang Patelb84a06e2007-10-23 02:10:49 +0000194
Chris Lattneraf319132008-02-05 06:55:31 +0000195 return CGT.getCGRecordLayout(RTy->getDecl());
Devang Patelb84a06e2007-10-23 02:10:49 +0000196}
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000197
Daniel Dunbar488e9932008-08-16 00:56:44 +0000198/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000199/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000200void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
201 bool OmitOnError) {
202 CGM.ErrorUnsupported(S, Type, OmitOnError);
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000203}
204
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000205unsigned CodeGenFunction::GetIDForAddrOfLabel(const LabelStmt *L) {
206 // Use LabelIDs.size() as the new ID if one hasn't been assigned.
207 return LabelIDs.insert(std::make_pair(L, LabelIDs.size())).first->second;
208}
209
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000210void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty)
211{
212 const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
213 if (DestPtr->getType() != BP)
214 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
215
216 // Get size and alignment info for this aggregate.
217 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
218
219 // FIXME: Handle variable sized types.
220 const llvm::Type *IntPtr = llvm::IntegerType::get(LLVMPointerWidth);
221
222 Builder.CreateCall4(CGM.getMemSetFn(), DestPtr,
223 llvm::ConstantInt::getNullValue(llvm::Type::Int8Ty),
224 // TypeInfo.first describes size in bits.
225 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
226 llvm::ConstantInt::get(llvm::Type::Int32Ty,
227 TypeInfo.second/8));
228}
229
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000230void CodeGenFunction::EmitIndirectSwitches() {
231 llvm::BasicBlock *Default;
232
Daniel Dunbar76526a52008-08-04 17:24:44 +0000233 if (IndirectSwitches.empty())
234 return;
235
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000236 if (!LabelIDs.empty()) {
237 Default = getBasicBlockForLabel(LabelIDs.begin()->first);
238 } else {
239 // No possible targets for indirect goto, just emit an infinite
240 // loop.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000241 Default = createBasicBlock("indirectgoto.loop", CurFn);
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000242 llvm::BranchInst::Create(Default, Default);
243 }
244
245 for (std::vector<llvm::SwitchInst*>::iterator i = IndirectSwitches.begin(),
246 e = IndirectSwitches.end(); i != e; ++i) {
247 llvm::SwitchInst *I = *i;
248
249 I->setSuccessor(0, Default);
250 for (std::map<const LabelStmt*,unsigned>::iterator LI = LabelIDs.begin(),
251 LE = LabelIDs.end(); LI != LE; ++LI) {
252 I->addCase(llvm::ConstantInt::get(llvm::Type::Int32Ty,
253 LI->second),
254 getBasicBlockForLabel(LI->first));
255 }
256 }
257}
Anders Carlssonddf7cac2008-11-04 05:30:00 +0000258
259llvm::Value *CodeGenFunction::EmitVAArg(llvm::Value *VAListAddr, QualType Ty)
260{
261 // FIXME: This entire method is hardcoded for 32-bit X86.
262
263 const char *TargetPrefix = getContext().Target.getTargetPrefix();
264
265 if (strcmp(TargetPrefix, "x86") != 0 ||
266 getContext().Target.getPointerWidth(0) != 32)
267 return 0;
268
269 const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
270 const llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
271
272 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
273 "ap");
274 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
275 llvm::Value *AddrTyped =
276 Builder.CreateBitCast(Addr,
277 llvm::PointerType::getUnqual(ConvertType(Ty)));
278
279 uint64_t SizeInBytes = getContext().getTypeSize(Ty) / 8;
280 const unsigned ArgumentSizeInBytes = 4;
281 if (SizeInBytes < ArgumentSizeInBytes)
282 SizeInBytes = ArgumentSizeInBytes;
283
284 llvm::Value *NextAddr =
285 Builder.CreateGEP(Addr,
286 llvm::ConstantInt::get(llvm::Type::Int32Ty, SizeInBytes),
287 "ap.next");
288 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
289
290 return AddrTyped;
291}
292