blob: 5fb0b2babe1c9645bef35b944ef2bb0915320e5a [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"
Chris Lattner31a09842008-11-12 08:04:58 +000018#include "clang/AST/APValue.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000019#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000020#include "clang/AST/Decl.h"
Devang Pateld9363c32007-09-28 21:49:18 +000021#include "llvm/Support/CFG.h"
Mike Stump4e7a1f72009-02-21 20:00:35 +000022#include "llvm/Target/TargetData.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023using namespace clang;
24using namespace CodeGen;
25
26CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
Anders Carlssone896d982009-02-13 08:11:52 +000027 : CGM(cgm), Target(CGM.getContext().Target), DebugInfo(0), SwitchInsn(0),
Daniel Dunbar9834ffb2009-02-23 17:26:39 +000028 CaseRangeBlock(0), InvokeDest(0) {
Mike Stump4e7a1f72009-02-21 20:00:35 +000029 LLVMIntTy = ConvertType(getContext().IntTy);
30 LLVMPointerWidth = Target.getPointerWidth(0);
31
32 // FIXME: We need to rearrange the code for copy/dispose so we have this
33 // sooner, so we can calculate offsets correctly.
34 BlockHasCopyDispose = false;
35 if (!BlockHasCopyDispose)
36 BlockOffset = CGM.getTargetData()
37 .getTypeStoreSizeInBits(CGM.getGenericBlockLiteralType()) / 8;
38 else
39 BlockOffset = CGM.getTargetData()
40 .getTypeStoreSizeInBits(CGM.getGenericExtendedBlockLiteralType()) / 8;
Mike Stump8a2b4b12009-02-25 23:33:13 +000041 BlockAlign = getContext().getTypeAlign(getContext().VoidPtrTy) / 8;
Chris Lattner41110242008-06-17 18:05:57 +000042}
Reid Spencer5f016e22007-07-11 17:01:13 +000043
44ASTContext &CodeGenFunction::getContext() const {
45 return CGM.getContext();
46}
47
48
49llvm::BasicBlock *CodeGenFunction::getBasicBlockForLabel(const LabelStmt *S) {
50 llvm::BasicBlock *&BB = LabelMap[S];
51 if (BB) return BB;
52
53 // Create, but don't insert, the new block.
Daniel Dunbar55e87422008-11-11 02:29:29 +000054 return BB = createBasicBlock(S->getName());
Reid Spencer5f016e22007-07-11 17:01:13 +000055}
56
Daniel Dunbar0096acf2009-02-25 19:24:29 +000057llvm::Value *CodeGenFunction::GetAddrOfLocalVar(const VarDecl *VD) {
58 llvm::Value *Res = LocalDeclMap[VD];
59 assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!");
60 return Res;
Lauro Ramos Venancio81373352008-02-26 21:41:45 +000061}
Reid Spencer5f016e22007-07-11 17:01:13 +000062
Daniel Dunbar0096acf2009-02-25 19:24:29 +000063llvm::Constant *
64CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) {
65 return cast<llvm::Constant>(GetAddrOfLocalVar(BVD));
Anders Carlssondde0a942008-09-11 09:15:33 +000066}
67
Daniel Dunbar8b1a3432009-02-03 23:03:55 +000068const llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
69 return CGM.getTypes().ConvertTypeForMem(T);
70}
71
Reid Spencer5f016e22007-07-11 17:01:13 +000072const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
73 return CGM.getTypes().ConvertType(T);
74}
75
Chris Lattner41110242008-06-17 18:05:57 +000076bool CodeGenFunction::isObjCPointerType(QualType T) {
77 // All Objective-C types are pointers.
78 return T->isObjCInterfaceType() ||
79 T->isObjCQualifiedInterfaceType() || T->isObjCQualifiedIdType();
80}
81
Reid Spencer5f016e22007-07-11 17:01:13 +000082bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
Daniel Dunbara782ca72009-01-09 02:44:18 +000083 // FIXME: Use positive checks instead of negative ones to be more
84 // robust in the face of extension.
Chris Lattner41110242008-06-17 18:05:57 +000085 return !isObjCPointerType(T) &&!T->isRealType() && !T->isPointerLikeType() &&
Daniel Dunbara782ca72009-01-09 02:44:18 +000086 !T->isVoidType() && !T->isVectorType() && !T->isFunctionType() &&
87 !T->isBlockPointerType();
Reid Spencer5f016e22007-07-11 17:01:13 +000088}
89
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000090void CodeGenFunction::EmitReturnBlock() {
91 // For cleanliness, we try to avoid emitting the return block for
92 // simple cases.
93 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
94
95 if (CurBB) {
96 assert(!CurBB->getTerminator() && "Unexpected terminated block.");
97
98 // We have a valid insert point, reuse it if there are no explicit
99 // jumps to the return block.
100 if (ReturnBlock->use_empty())
101 delete ReturnBlock;
102 else
103 EmitBlock(ReturnBlock);
104 return;
105 }
106
107 // Otherwise, if the return block is the target of a single direct
108 // branch then we can just put the code in that block instead. This
109 // cleans up functions which started with a unified return block.
110 if (ReturnBlock->hasOneUse()) {
111 llvm::BranchInst *BI =
112 dyn_cast<llvm::BranchInst>(*ReturnBlock->use_begin());
113 if (BI && BI->isUnconditional() && BI->getSuccessor(0) == ReturnBlock) {
114 // Reset insertion point and delete the branch.
115 Builder.SetInsertPoint(BI->getParent());
116 BI->eraseFromParent();
117 delete ReturnBlock;
118 return;
119 }
120 }
121
122 // FIXME: We are at an unreachable point, there is no reason to emit
123 // the block unless it has uses. However, we still need a place to
124 // put the debug region.end for now.
125
126 EmitBlock(ReturnBlock);
127}
128
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000129void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000130 // Finish emission of indirect switches.
131 EmitIndirectSwitches();
132
Chris Lattnerda138702007-07-16 21:28:45 +0000133 assert(BreakContinueStack.empty() &&
134 "mismatched push/pop in break/continue stack!");
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000135 assert(BlockScopes.empty() &&
136 "did not remove all blocks from block scope map!");
137 assert(CleanupEntries.empty() &&
138 "mismatched push/pop in cleanup stack!");
139
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000140 // Emit function epilog (to return).
141 EmitReturnBlock();
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000142
143 // Emit debug descriptor for function end.
Anders Carlssone896d982009-02-13 08:11:52 +0000144 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000145 DI->setLocation(EndLoc);
146 DI->EmitRegionEnd(CurFn, Builder);
147 }
148
Daniel Dunbar88b53962009-02-02 22:03:45 +0000149 EmitFunctionEpilog(*CurFnInfo, ReturnValue);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000150
Chris Lattner5a2fa142007-12-02 06:32:24 +0000151 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
152 AllocaInsertPt->eraseFromParent();
153 AllocaInsertPt = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000154}
155
Daniel Dunbar7c086512008-09-09 23:14:03 +0000156void CodeGenFunction::StartFunction(const Decl *D, QualType RetTy,
157 llvm::Function *Fn,
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000158 const FunctionArgList &Args,
159 SourceLocation StartLoc) {
Anders Carlsson4cc1a472009-02-09 20:20:56 +0000160 DidCallStackSave = false;
Daniel Dunbar7c086512008-09-09 23:14:03 +0000161 CurFuncDecl = D;
162 FnRetTy = RetTy;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000163 CurFn = Fn;
Chris Lattner41110242008-06-17 18:05:57 +0000164 assert(CurFn->isDeclaration() && "Function already has body?");
165
Daniel Dunbar55e87422008-11-11 02:29:29 +0000166 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000167
Chris Lattner41110242008-06-17 18:05:57 +0000168 // Create a marker to make it easy to insert allocas into the entryblock
169 // later. Don't create this with the builder, because we don't want it
170 // folded.
171 llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::Int32Ty);
172 AllocaInsertPt = new llvm::BitCastInst(Undef, llvm::Type::Int32Ty, "allocapt",
173 EntryBB);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000174
Daniel Dunbar55e87422008-11-11 02:29:29 +0000175 ReturnBlock = createBasicBlock("return");
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000176 ReturnValue = 0;
Daniel Dunbar7c086512008-09-09 23:14:03 +0000177 if (!RetTy->isVoidType())
178 ReturnValue = CreateTempAlloca(ConvertType(RetTy), "retval");
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000179
Chris Lattner41110242008-06-17 18:05:57 +0000180 Builder.SetInsertPoint(EntryBB);
181
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000182 // Emit subprogram debug descriptor.
Daniel Dunbar7c086512008-09-09 23:14:03 +0000183 // FIXME: The cast here is a huge hack.
Anders Carlssone896d982009-02-13 08:11:52 +0000184 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000185 DI->setLocation(StartLoc);
186 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor6ec36682009-02-18 23:53:56 +0000187 DI->EmitFunctionStart(CGM.getMangledName(FD), RetTy, CurFn, Builder);
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000188 } else {
189 // Just use LLVM function name.
190 DI->EmitFunctionStart(Fn->getName().c_str(),
191 RetTy, CurFn, Builder);
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000192 }
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000193 }
194
Daniel Dunbar88b53962009-02-02 22:03:45 +0000195 // FIXME: Leaked.
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000196 CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args);
Daniel Dunbar88b53962009-02-02 22:03:45 +0000197 EmitFunctionProlog(*CurFnInfo, CurFn, Args);
Anders Carlsson751358f2008-12-20 21:28:43 +0000198
199 // If any of the arguments have a variably modified type, make sure to
200 // emit the type size.
201 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
202 i != e; ++i) {
203 QualType Ty = i->second;
204
205 if (Ty->isVariablyModifiedType())
206 EmitVLASize(Ty);
207 }
Daniel Dunbar7c086512008-09-09 23:14:03 +0000208}
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000209
Daniel Dunbar7c086512008-09-09 23:14:03 +0000210void CodeGenFunction::GenerateCode(const FunctionDecl *FD,
211 llvm::Function *Fn) {
Anders Carlssone896d982009-02-13 08:11:52 +0000212 // Check if we should generate debug info for this function.
213 if (CGM.getDebugInfo() && !FD->getAttr<NodebugAttr>())
214 DebugInfo = CGM.getDebugInfo();
215
Daniel Dunbar7c086512008-09-09 23:14:03 +0000216 FunctionArgList Args;
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000217 if (FD->getNumParams()) {
218 const FunctionTypeProto* FProto = FD->getType()->getAsFunctionTypeProto();
219 assert(FProto && "Function def must have prototype!");
Daniel Dunbar7c086512008-09-09 23:14:03 +0000220
221 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
222 Args.push_back(std::make_pair(FD->getParamDecl(i),
223 FProto->getArgType(i)));
Chris Lattner41110242008-06-17 18:05:57 +0000224 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000225
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000226 StartFunction(FD, FD->getResultType(), Fn, Args,
227 cast<CompoundStmt>(FD->getBody())->getLBracLoc());
Daniel Dunbar7c086512008-09-09 23:14:03 +0000228
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000229 EmitStmt(FD->getBody());
230
231 const CompoundStmt *S = dyn_cast<CompoundStmt>(FD->getBody());
232 if (S) {
233 FinishFunction(S->getRBracLoc());
234 } else {
235 FinishFunction();
236 }
Chris Lattner41110242008-06-17 18:05:57 +0000237}
238
Chris Lattner0946ccd2008-11-11 07:41:27 +0000239/// ContainsLabel - Return true if the statement contains a label in it. If
240/// this statement is not executed normally, it not containing a label means
241/// that we can just remove the code.
242bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
243 // Null statement, not a label!
244 if (S == 0) return false;
245
246 // If this is a label, we have to emit the code, consider something like:
247 // if (0) { ... foo: bar(); } goto foo;
248 if (isa<LabelStmt>(S))
249 return true;
250
251 // If this is a case/default statement, and we haven't seen a switch, we have
252 // to emit the code.
253 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
254 return true;
255
256 // If this is a switch statement, we want to ignore cases below it.
257 if (isa<SwitchStmt>(S))
258 IgnoreCaseStmts = true;
259
260 // Scan subexpressions for verboten labels.
261 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
262 I != E; ++I)
263 if (ContainsLabel(*I, IgnoreCaseStmts))
264 return true;
265
266 return false;
267}
268
Chris Lattner31a09842008-11-12 08:04:58 +0000269
270/// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
271/// a constant, or if it does but contains a label, return 0. If it constant
272/// folds to 'true' and does not contain a label, return 1, if it constant folds
273/// to 'false' and does not contain a label, return -1.
274int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
Daniel Dunbar36bc14c2008-11-12 22:37:10 +0000275 // FIXME: Rename and handle conversion of other evaluatable things
276 // to bool.
Anders Carlsson64712f12008-12-01 02:46:24 +0000277 Expr::EvalResult Result;
278 if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
279 Result.HasSideEffects)
Anders Carlssonef5a66d2008-11-22 22:32:07 +0000280 return 0; // Not foldable, not integer or not fully evaluatable.
Chris Lattner31a09842008-11-12 08:04:58 +0000281
282 if (CodeGenFunction::ContainsLabel(Cond))
283 return 0; // Contains a label.
284
Anders Carlsson64712f12008-12-01 02:46:24 +0000285 return Result.Val.getInt().getBoolValue() ? 1 : -1;
Chris Lattner31a09842008-11-12 08:04:58 +0000286}
287
288
289/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
290/// statement) to the specified blocks. Based on the condition, this might try
291/// to simplify the codegen of the conditional based on the branch.
292///
293void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
294 llvm::BasicBlock *TrueBlock,
295 llvm::BasicBlock *FalseBlock) {
296 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
297 return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
298
299 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
300 // Handle X && Y in a condition.
301 if (CondBOp->getOpcode() == BinaryOperator::LAnd) {
302 // If we have "1 && X", simplify the code. "0 && X" would have constant
303 // folded if the case was simple enough.
304 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
305 // br(1 && X) -> br(X).
306 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
307 }
308
309 // If we have "X && 1", simplify the code to use an uncond branch.
310 // "X && 0" would have been constant folded to 0.
311 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
312 // br(X && 1) -> br(X).
313 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
314 }
315
316 // Emit the LHS as a conditional. If the LHS conditional is false, we
317 // want to jump to the FalseBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000318 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
Chris Lattner31a09842008-11-12 08:04:58 +0000319 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
320 EmitBlock(LHSTrue);
321
322 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
323 return;
324 } else if (CondBOp->getOpcode() == BinaryOperator::LOr) {
325 // If we have "0 || X", simplify the code. "1 || X" would have constant
326 // folded if the case was simple enough.
327 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
328 // br(0 || X) -> br(X).
329 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
330 }
331
332 // If we have "X || 0", simplify the code to use an uncond branch.
333 // "X || 1" would have been constant folded to 1.
334 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
335 // br(X || 0) -> br(X).
336 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
337 }
338
339 // Emit the LHS as a conditional. If the LHS conditional is true, we
340 // want to jump to the TrueBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000341 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
Chris Lattner31a09842008-11-12 08:04:58 +0000342 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
343 EmitBlock(LHSFalse);
344
345 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
346 return;
347 }
Chris Lattner552f4c42008-11-12 08:13:36 +0000348 }
349
350 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
351 // br(!x, t, f) -> br(x, f, t)
352 if (CondUOp->getOpcode() == UnaryOperator::LNot)
353 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
Chris Lattner31a09842008-11-12 08:04:58 +0000354 }
355
Daniel Dunbar09b14892008-11-12 10:30:32 +0000356 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
357 // Handle ?: operator.
358
359 // Just ignore GNU ?: extension.
360 if (CondOp->getLHS()) {
361 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
362 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
363 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
364 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
365 EmitBlock(LHSBlock);
366 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
367 EmitBlock(RHSBlock);
368 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
369 return;
370 }
371 }
372
Chris Lattner31a09842008-11-12 08:04:58 +0000373 // Emit the code with the fully general case.
374 llvm::Value *CondV = EvaluateExprAsBool(Cond);
375 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
376}
377
Devang Patel88a981b2007-11-01 19:11:01 +0000378/// getCGRecordLayout - Return record layout info.
379const CGRecordLayout *CodeGenFunction::getCGRecordLayout(CodeGenTypes &CGT,
Chris Lattneraf319132008-02-05 06:55:31 +0000380 QualType Ty) {
381 const RecordType *RTy = Ty->getAsRecordType();
382 assert (RTy && "Unexpected type. RecordType expected here.");
Devang Patelb84a06e2007-10-23 02:10:49 +0000383
Chris Lattneraf319132008-02-05 06:55:31 +0000384 return CGT.getCGRecordLayout(RTy->getDecl());
Devang Patelb84a06e2007-10-23 02:10:49 +0000385}
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000386
Daniel Dunbar488e9932008-08-16 00:56:44 +0000387/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000388/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000389void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
390 bool OmitOnError) {
391 CGM.ErrorUnsupported(S, Type, OmitOnError);
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000392}
393
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000394unsigned CodeGenFunction::GetIDForAddrOfLabel(const LabelStmt *L) {
395 // Use LabelIDs.size() as the new ID if one hasn't been assigned.
396 return LabelIDs.insert(std::make_pair(L, LabelIDs.size())).first->second;
397}
398
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000399void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty)
400{
401 const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
402 if (DestPtr->getType() != BP)
403 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
404
405 // Get size and alignment info for this aggregate.
406 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
407
408 // FIXME: Handle variable sized types.
409 const llvm::Type *IntPtr = llvm::IntegerType::get(LLVMPointerWidth);
410
411 Builder.CreateCall4(CGM.getMemSetFn(), DestPtr,
412 llvm::ConstantInt::getNullValue(llvm::Type::Int8Ty),
413 // TypeInfo.first describes size in bits.
414 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
415 llvm::ConstantInt::get(llvm::Type::Int32Ty,
416 TypeInfo.second/8));
417}
418
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000419void CodeGenFunction::EmitIndirectSwitches() {
420 llvm::BasicBlock *Default;
421
Daniel Dunbar76526a52008-08-04 17:24:44 +0000422 if (IndirectSwitches.empty())
423 return;
424
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000425 if (!LabelIDs.empty()) {
426 Default = getBasicBlockForLabel(LabelIDs.begin()->first);
427 } else {
428 // No possible targets for indirect goto, just emit an infinite
429 // loop.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000430 Default = createBasicBlock("indirectgoto.loop", CurFn);
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000431 llvm::BranchInst::Create(Default, Default);
432 }
433
434 for (std::vector<llvm::SwitchInst*>::iterator i = IndirectSwitches.begin(),
435 e = IndirectSwitches.end(); i != e; ++i) {
436 llvm::SwitchInst *I = *i;
437
438 I->setSuccessor(0, Default);
439 for (std::map<const LabelStmt*,unsigned>::iterator LI = LabelIDs.begin(),
440 LE = LabelIDs.end(); LI != LE; ++LI) {
441 I->addCase(llvm::ConstantInt::get(llvm::Type::Int32Ty,
442 LI->second),
443 getBasicBlockForLabel(LI->first));
444 }
445 }
446}
Anders Carlssonddf7cac2008-11-04 05:30:00 +0000447
Anders Carlssondcc90d82008-12-12 07:19:02 +0000448llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT)
449{
450 llvm::Value *&SizeEntry = VLASizeMap[VAT];
Anders Carlssondcc90d82008-12-12 07:19:02 +0000451
Anders Carlssonf666b772008-12-20 20:27:15 +0000452 assert(SizeEntry && "Did not emit size for type");
453 return SizeEntry;
454}
Anders Carlssondcc90d82008-12-12 07:19:02 +0000455
Anders Carlsson60d35412008-12-20 20:46:34 +0000456llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty)
Anders Carlssonf666b772008-12-20 20:27:15 +0000457{
Anders Carlsson60d35412008-12-20 20:46:34 +0000458 assert(Ty->isVariablyModifiedType() &&
459 "Must pass variably modified type to EmitVLASizes!");
Anders Carlssonf666b772008-12-20 20:27:15 +0000460
Anders Carlsson60d35412008-12-20 20:46:34 +0000461 if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
462 llvm::Value *&SizeEntry = VLASizeMap[VAT];
463
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000464 if (!SizeEntry) {
465 // Get the element size;
466 llvm::Value *ElemSize;
Anders Carlsson60d35412008-12-20 20:46:34 +0000467
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000468 QualType ElemTy = VAT->getElementType();
Anders Carlsson96f21472009-02-05 19:43:10 +0000469
470 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
471
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000472 if (ElemTy->isVariableArrayType())
473 ElemSize = EmitVLASize(ElemTy);
474 else {
Anders Carlsson96f21472009-02-05 19:43:10 +0000475 ElemSize = llvm::ConstantInt::get(SizeTy,
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000476 getContext().getTypeSize(ElemTy) / 8);
477 }
Anders Carlsson60d35412008-12-20 20:46:34 +0000478
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000479 llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
Anders Carlsson96f21472009-02-05 19:43:10 +0000480 NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
481
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000482 SizeEntry = Builder.CreateMul(ElemSize, NumElements);
Anders Carlsson60d35412008-12-20 20:46:34 +0000483 }
484
Anders Carlsson60d35412008-12-20 20:46:34 +0000485 return SizeEntry;
486 } else if (const PointerType *PT = Ty->getAsPointerType())
487 EmitVLASize(PT->getPointeeType());
Anders Carlssonf666b772008-12-20 20:27:15 +0000488 else {
Anders Carlsson60d35412008-12-20 20:46:34 +0000489 assert(0 && "unknown VM type!");
Anders Carlssondcc90d82008-12-12 07:19:02 +0000490 }
Anders Carlsson60d35412008-12-20 20:46:34 +0000491
492 return 0;
Anders Carlssondcc90d82008-12-12 07:19:02 +0000493}
Eli Friedman4fd0aa52009-01-20 17:46:04 +0000494
495llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
496 if (CGM.getContext().getBuiltinVaListType()->isArrayType()) {
497 return EmitScalarExpr(E);
498 }
499 return EmitLValue(E).getAddress();
500}
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000501
Anders Carlsson6fc55912009-02-08 03:22:36 +0000502void CodeGenFunction::PushCleanupBlock(llvm::BasicBlock *CleanupBlock)
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000503{
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000504 CleanupEntries.push_back(CleanupEntry(CleanupBlock));
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000505}
Anders Carlssonc71c8452009-02-07 23:50:39 +0000506
507void CodeGenFunction::EmitCleanupBlocks(size_t OldCleanupStackSize)
508{
509 assert(CleanupEntries.size() >= OldCleanupStackSize &&
510 "Cleanup stack mismatch!");
511
512 while (CleanupEntries.size() > OldCleanupStackSize)
513 EmitCleanupBlock();
514}
515
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000516CodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock()
Anders Carlssonc71c8452009-02-07 23:50:39 +0000517{
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000518 CleanupEntry &CE = CleanupEntries.back();
519
520 llvm::BasicBlock *CleanupBlock = CE.CleanupBlock;
521
522 std::vector<llvm::BasicBlock *> Blocks;
523 std::swap(Blocks, CE.Blocks);
524
525 std::vector<llvm::BranchInst *> BranchFixups;
526 std::swap(BranchFixups, CE.BranchFixups);
527
528 CleanupEntries.pop_back();
529
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000530 // Check if any branch fixups pointed to the scope we just popped. If so,
531 // we can remove them.
532 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
533 llvm::BasicBlock *Dest = BranchFixups[i]->getSuccessor(0);
534 BlockScopeMap::iterator I = BlockScopes.find(Dest);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000535
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000536 if (I == BlockScopes.end())
537 continue;
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000538
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000539 assert(I->second <= CleanupEntries.size() && "Invalid branch fixup!");
Anders Carlssond66a9f92009-02-08 03:55:35 +0000540
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000541 if (I->second == CleanupEntries.size()) {
542 // We don't need to do this branch fixup.
543 BranchFixups[i] = BranchFixups.back();
544 BranchFixups.pop_back();
545 i--;
546 e--;
547 continue;
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000548 }
549 }
Anders Carlssond66a9f92009-02-08 03:55:35 +0000550
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000551 llvm::BasicBlock *SwitchBlock = 0;
552 llvm::BasicBlock *EndBlock = 0;
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000553 if (!BranchFixups.empty()) {
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000554 SwitchBlock = createBasicBlock("cleanup.switch");
555 EndBlock = createBasicBlock("cleanup.end");
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000556
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000557 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
558
559 Builder.SetInsertPoint(SwitchBlock);
560
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000561 llvm::Value *DestCodePtr = CreateTempAlloca(llvm::Type::Int32Ty,
562 "cleanup.dst");
563 llvm::Value *DestCode = Builder.CreateLoad(DestCodePtr, "tmp");
564
565 // Create a switch instruction to determine where to jump next.
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000566 llvm::SwitchInst *SI = Builder.CreateSwitch(DestCode, EndBlock,
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000567 BranchFixups.size());
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000568
Anders Carlsson46831a92009-02-08 22:13:37 +0000569 // Restore the current basic block (if any)
570 if (CurBB)
571 Builder.SetInsertPoint(CurBB);
572 else
573 Builder.ClearInsertionPoint();
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000574
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000575 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
576 llvm::BranchInst *BI = BranchFixups[i];
577 llvm::BasicBlock *Dest = BI->getSuccessor(0);
578
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000579 // Fixup the branch instruction to point to the cleanup block.
580 BI->setSuccessor(0, CleanupBlock);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000581
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000582 if (CleanupEntries.empty()) {
Anders Carlssoncc899202009-02-08 22:46:50 +0000583 llvm::ConstantInt *ID;
584
585 // Check if we already have a destination for this block.
586 if (Dest == SI->getDefaultDest())
587 ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
588 else {
589 ID = SI->findCaseDest(Dest);
590 if (!ID) {
591 // No code found, get a new unique one by using the number of
592 // switch successors.
593 ID = llvm::ConstantInt::get(llvm::Type::Int32Ty,
594 SI->getNumSuccessors());
595 SI->addCase(ID, Dest);
596 }
597 }
598
599 // Store the jump destination before the branch instruction.
600 new llvm::StoreInst(ID, DestCodePtr, BI);
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000601 } else {
602 // We need to jump through another cleanup block. Create a pad block
603 // with a branch instruction that jumps to the final destination and
604 // add it as a branch fixup to the current cleanup scope.
605
606 // Create the pad block.
607 llvm::BasicBlock *CleanupPad = createBasicBlock("cleanup.pad", CurFn);
Anders Carlssoncc899202009-02-08 22:46:50 +0000608
609 // Create a unique case ID.
610 llvm::ConstantInt *ID = llvm::ConstantInt::get(llvm::Type::Int32Ty,
611 SI->getNumSuccessors());
612
613 // Store the jump destination before the branch instruction.
614 new llvm::StoreInst(ID, DestCodePtr, BI);
615
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000616 // Add it as the destination.
Anders Carlssoncc899202009-02-08 22:46:50 +0000617 SI->addCase(ID, CleanupPad);
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000618
619 // Create the branch to the final destination.
620 llvm::BranchInst *BI = llvm::BranchInst::Create(Dest);
621 CleanupPad->getInstList().push_back(BI);
622
623 // And add it as a branch fixup.
624 CleanupEntries.back().BranchFixups.push_back(BI);
625 }
626 }
627 }
Anders Carlssond66a9f92009-02-08 03:55:35 +0000628
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000629 // Remove all blocks from the block scope map.
630 for (size_t i = 0, e = Blocks.size(); i != e; ++i) {
631 assert(BlockScopes.count(Blocks[i]) &&
632 "Did not find block in scope map!");
633
634 BlockScopes.erase(Blocks[i]);
635 }
Anders Carlssond66a9f92009-02-08 03:55:35 +0000636
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000637 return CleanupBlockInfo(CleanupBlock, SwitchBlock, EndBlock);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000638}
639
640void CodeGenFunction::EmitCleanupBlock()
641{
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000642 CleanupBlockInfo Info = PopCleanupBlock();
Anders Carlssond66a9f92009-02-08 03:55:35 +0000643
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000644 EmitBlock(Info.CleanupBlock);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000645
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000646 if (Info.SwitchBlock)
647 EmitBlock(Info.SwitchBlock);
648 if (Info.EndBlock)
649 EmitBlock(Info.EndBlock);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000650}
651
Anders Carlsson87eaf172009-02-08 00:50:42 +0000652void CodeGenFunction::AddBranchFixup(llvm::BranchInst *BI)
653{
654 assert(!CleanupEntries.empty() &&
655 "Trying to add branch fixup without cleanup block!");
656
657 // FIXME: We could be more clever here and check if there's already a
658 // branch fixup for this destination and recycle it.
659 CleanupEntries.back().BranchFixups.push_back(BI);
660}
661
662void CodeGenFunction::EmitBranchThroughCleanup(llvm::BasicBlock *Dest)
663{
Anders Carlsson46831a92009-02-08 22:13:37 +0000664 if (!HaveInsertPoint())
665 return;
666
Anders Carlsson87eaf172009-02-08 00:50:42 +0000667 llvm::BranchInst* BI = Builder.CreateBr(Dest);
668
Anders Carlsson46831a92009-02-08 22:13:37 +0000669 Builder.ClearInsertionPoint();
670
Anders Carlsson87eaf172009-02-08 00:50:42 +0000671 // The stack is empty, no need to do any cleanup.
672 if (CleanupEntries.empty())
673 return;
674
675 if (!Dest->getParent()) {
676 // We are trying to branch to a block that hasn't been inserted yet.
677 AddBranchFixup(BI);
678 return;
679 }
680
681 BlockScopeMap::iterator I = BlockScopes.find(Dest);
682 if (I == BlockScopes.end()) {
683 // We are trying to jump to a block that is outside of any cleanup scope.
684 AddBranchFixup(BI);
685 return;
686 }
687
688 assert(I->second < CleanupEntries.size() &&
689 "Trying to branch into cleanup region");
690
691 if (I->second == CleanupEntries.size() - 1) {
692 // We have a branch to a block in the same scope.
693 return;
694 }
695
696 AddBranchFixup(BI);
697}