blob: a54f9bd235fc1b9198c8652ad2b0bdcd0c1f4d52 [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)
Mike Stumpa4f668f2009-03-06 01:33:24 +000027 : BlockFunction(cgm, *this, Builder), CGM(cgm),
28 Target(CGM.getContext().Target),
Mike Stump3947de52009-03-04 18:57:26 +000029 DebugInfo(0), SwitchInsn(0), CaseRangeBlock(0), InvokeDest(0) {
Mike Stump4e7a1f72009-02-21 20:00:35 +000030 LLVMIntTy = ConvertType(getContext().IntTy);
31 LLVMPointerWidth = Target.getPointerWidth(0);
32
33 // FIXME: We need to rearrange the code for copy/dispose so we have this
34 // sooner, so we can calculate offsets correctly.
Mike Stump4e7a1f72009-02-21 20:00:35 +000035 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
76bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
Daniel Dunbara782ca72009-01-09 02:44:18 +000077 // FIXME: Use positive checks instead of negative ones to be more
78 // robust in the face of extension.
Daniel Dunbar89588912009-02-26 20:52:22 +000079 return !T->hasPointerRepresentation() &&!T->isRealType() &&
80 !T->isVoidType() && !T->isVectorType() && !T->isFunctionType() &&
Daniel Dunbara782ca72009-01-09 02:44:18 +000081 !T->isBlockPointerType();
Reid Spencer5f016e22007-07-11 17:01:13 +000082}
83
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000084void CodeGenFunction::EmitReturnBlock() {
85 // For cleanliness, we try to avoid emitting the return block for
86 // simple cases.
87 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
88
89 if (CurBB) {
90 assert(!CurBB->getTerminator() && "Unexpected terminated block.");
91
92 // We have a valid insert point, reuse it if there are no explicit
93 // jumps to the return block.
94 if (ReturnBlock->use_empty())
95 delete ReturnBlock;
96 else
97 EmitBlock(ReturnBlock);
98 return;
99 }
100
101 // Otherwise, if the return block is the target of a single direct
102 // branch then we can just put the code in that block instead. This
103 // cleans up functions which started with a unified return block.
104 if (ReturnBlock->hasOneUse()) {
105 llvm::BranchInst *BI =
106 dyn_cast<llvm::BranchInst>(*ReturnBlock->use_begin());
107 if (BI && BI->isUnconditional() && BI->getSuccessor(0) == ReturnBlock) {
108 // Reset insertion point and delete the branch.
109 Builder.SetInsertPoint(BI->getParent());
110 BI->eraseFromParent();
111 delete ReturnBlock;
112 return;
113 }
114 }
115
116 // FIXME: We are at an unreachable point, there is no reason to emit
117 // the block unless it has uses. However, we still need a place to
118 // put the debug region.end for now.
119
120 EmitBlock(ReturnBlock);
121}
122
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000123void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000124 // Finish emission of indirect switches.
125 EmitIndirectSwitches();
126
Chris Lattnerda138702007-07-16 21:28:45 +0000127 assert(BreakContinueStack.empty() &&
128 "mismatched push/pop in break/continue stack!");
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000129 assert(BlockScopes.empty() &&
130 "did not remove all blocks from block scope map!");
131 assert(CleanupEntries.empty() &&
132 "mismatched push/pop in cleanup stack!");
133
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000134 // Emit function epilog (to return).
135 EmitReturnBlock();
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000136
137 // Emit debug descriptor for function end.
Anders Carlssone896d982009-02-13 08:11:52 +0000138 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000139 DI->setLocation(EndLoc);
140 DI->EmitRegionEnd(CurFn, Builder);
141 }
142
Daniel Dunbar88b53962009-02-02 22:03:45 +0000143 EmitFunctionEpilog(*CurFnInfo, ReturnValue);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000144
Chris Lattner5a2fa142007-12-02 06:32:24 +0000145 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
146 AllocaInsertPt->eraseFromParent();
147 AllocaInsertPt = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000148}
149
Daniel Dunbar7c086512008-09-09 23:14:03 +0000150void CodeGenFunction::StartFunction(const Decl *D, QualType RetTy,
151 llvm::Function *Fn,
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000152 const FunctionArgList &Args,
153 SourceLocation StartLoc) {
Anders Carlsson4cc1a472009-02-09 20:20:56 +0000154 DidCallStackSave = false;
Daniel Dunbar7c086512008-09-09 23:14:03 +0000155 CurFuncDecl = D;
156 FnRetTy = RetTy;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000157 CurFn = Fn;
Chris Lattner41110242008-06-17 18:05:57 +0000158 assert(CurFn->isDeclaration() && "Function already has body?");
159
Daniel Dunbar55e87422008-11-11 02:29:29 +0000160 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000161
Chris Lattner41110242008-06-17 18:05:57 +0000162 // Create a marker to make it easy to insert allocas into the entryblock
163 // later. Don't create this with the builder, because we don't want it
164 // folded.
165 llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::Int32Ty);
166 AllocaInsertPt = new llvm::BitCastInst(Undef, llvm::Type::Int32Ty, "allocapt",
167 EntryBB);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000168
Daniel Dunbar55e87422008-11-11 02:29:29 +0000169 ReturnBlock = createBasicBlock("return");
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000170 ReturnValue = 0;
Daniel Dunbar7c086512008-09-09 23:14:03 +0000171 if (!RetTy->isVoidType())
172 ReturnValue = CreateTempAlloca(ConvertType(RetTy), "retval");
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000173
Chris Lattner41110242008-06-17 18:05:57 +0000174 Builder.SetInsertPoint(EntryBB);
175
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000176 // Emit subprogram debug descriptor.
Daniel Dunbar7c086512008-09-09 23:14:03 +0000177 // FIXME: The cast here is a huge hack.
Anders Carlssone896d982009-02-13 08:11:52 +0000178 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000179 DI->setLocation(StartLoc);
180 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor6ec36682009-02-18 23:53:56 +0000181 DI->EmitFunctionStart(CGM.getMangledName(FD), RetTy, CurFn, Builder);
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000182 } else {
183 // Just use LLVM function name.
184 DI->EmitFunctionStart(Fn->getName().c_str(),
185 RetTy, CurFn, Builder);
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000186 }
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000187 }
188
Daniel Dunbar88b53962009-02-02 22:03:45 +0000189 // FIXME: Leaked.
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000190 CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args);
Daniel Dunbar88b53962009-02-02 22:03:45 +0000191 EmitFunctionProlog(*CurFnInfo, CurFn, Args);
Anders Carlsson751358f2008-12-20 21:28:43 +0000192
193 // If any of the arguments have a variably modified type, make sure to
194 // emit the type size.
195 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
196 i != e; ++i) {
197 QualType Ty = i->second;
198
199 if (Ty->isVariablyModifiedType())
200 EmitVLASize(Ty);
201 }
Daniel Dunbar7c086512008-09-09 23:14:03 +0000202}
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000203
Daniel Dunbar7c086512008-09-09 23:14:03 +0000204void CodeGenFunction::GenerateCode(const FunctionDecl *FD,
205 llvm::Function *Fn) {
Anders Carlssone896d982009-02-13 08:11:52 +0000206 // Check if we should generate debug info for this function.
207 if (CGM.getDebugInfo() && !FD->getAttr<NodebugAttr>())
208 DebugInfo = CGM.getDebugInfo();
209
Daniel Dunbar7c086512008-09-09 23:14:03 +0000210 FunctionArgList Args;
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000211 if (FD->getNumParams()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000212 const FunctionProtoType* FProto = FD->getType()->getAsFunctionProtoType();
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000213 assert(FProto && "Function def must have prototype!");
Daniel Dunbar7c086512008-09-09 23:14:03 +0000214
215 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
216 Args.push_back(std::make_pair(FD->getParamDecl(i),
217 FProto->getArgType(i)));
Chris Lattner41110242008-06-17 18:05:57 +0000218 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000219
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000220 StartFunction(FD, FD->getResultType(), Fn, Args,
221 cast<CompoundStmt>(FD->getBody())->getLBracLoc());
Daniel Dunbar7c086512008-09-09 23:14:03 +0000222
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000223 EmitStmt(FD->getBody());
224
225 const CompoundStmt *S = dyn_cast<CompoundStmt>(FD->getBody());
226 if (S) {
227 FinishFunction(S->getRBracLoc());
228 } else {
229 FinishFunction();
230 }
Chris Lattner41110242008-06-17 18:05:57 +0000231}
232
Chris Lattner0946ccd2008-11-11 07:41:27 +0000233/// ContainsLabel - Return true if the statement contains a label in it. If
234/// this statement is not executed normally, it not containing a label means
235/// that we can just remove the code.
236bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
237 // Null statement, not a label!
238 if (S == 0) return false;
239
240 // If this is a label, we have to emit the code, consider something like:
241 // if (0) { ... foo: bar(); } goto foo;
242 if (isa<LabelStmt>(S))
243 return true;
244
245 // If this is a case/default statement, and we haven't seen a switch, we have
246 // to emit the code.
247 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
248 return true;
249
250 // If this is a switch statement, we want to ignore cases below it.
251 if (isa<SwitchStmt>(S))
252 IgnoreCaseStmts = true;
253
254 // Scan subexpressions for verboten labels.
255 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
256 I != E; ++I)
257 if (ContainsLabel(*I, IgnoreCaseStmts))
258 return true;
259
260 return false;
261}
262
Chris Lattner31a09842008-11-12 08:04:58 +0000263
264/// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
265/// a constant, or if it does but contains a label, return 0. If it constant
266/// folds to 'true' and does not contain a label, return 1, if it constant folds
267/// to 'false' and does not contain a label, return -1.
268int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
Daniel Dunbar36bc14c2008-11-12 22:37:10 +0000269 // FIXME: Rename and handle conversion of other evaluatable things
270 // to bool.
Anders Carlsson64712f12008-12-01 02:46:24 +0000271 Expr::EvalResult Result;
272 if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
273 Result.HasSideEffects)
Anders Carlssonef5a66d2008-11-22 22:32:07 +0000274 return 0; // Not foldable, not integer or not fully evaluatable.
Chris Lattner31a09842008-11-12 08:04:58 +0000275
276 if (CodeGenFunction::ContainsLabel(Cond))
277 return 0; // Contains a label.
278
Anders Carlsson64712f12008-12-01 02:46:24 +0000279 return Result.Val.getInt().getBoolValue() ? 1 : -1;
Chris Lattner31a09842008-11-12 08:04:58 +0000280}
281
282
283/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
284/// statement) to the specified blocks. Based on the condition, this might try
285/// to simplify the codegen of the conditional based on the branch.
286///
287void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
288 llvm::BasicBlock *TrueBlock,
289 llvm::BasicBlock *FalseBlock) {
290 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
291 return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
292
293 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
294 // Handle X && Y in a condition.
295 if (CondBOp->getOpcode() == BinaryOperator::LAnd) {
296 // If we have "1 && X", simplify the code. "0 && X" would have constant
297 // folded if the case was simple enough.
298 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
299 // br(1 && X) -> br(X).
300 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
301 }
302
303 // If we have "X && 1", simplify the code to use an uncond branch.
304 // "X && 0" would have been constant folded to 0.
305 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
306 // br(X && 1) -> br(X).
307 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
308 }
309
310 // Emit the LHS as a conditional. If the LHS conditional is false, we
311 // want to jump to the FalseBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000312 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
Chris Lattner31a09842008-11-12 08:04:58 +0000313 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
314 EmitBlock(LHSTrue);
315
316 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
317 return;
318 } else if (CondBOp->getOpcode() == BinaryOperator::LOr) {
319 // If we have "0 || X", simplify the code. "1 || X" would have constant
320 // folded if the case was simple enough.
321 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
322 // br(0 || X) -> br(X).
323 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
324 }
325
326 // If we have "X || 0", simplify the code to use an uncond branch.
327 // "X || 1" would have been constant folded to 1.
328 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
329 // br(X || 0) -> br(X).
330 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
331 }
332
333 // Emit the LHS as a conditional. If the LHS conditional is true, we
334 // want to jump to the TrueBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000335 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
Chris Lattner31a09842008-11-12 08:04:58 +0000336 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
337 EmitBlock(LHSFalse);
338
339 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
340 return;
341 }
Chris Lattner552f4c42008-11-12 08:13:36 +0000342 }
343
344 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
345 // br(!x, t, f) -> br(x, f, t)
346 if (CondUOp->getOpcode() == UnaryOperator::LNot)
347 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
Chris Lattner31a09842008-11-12 08:04:58 +0000348 }
349
Daniel Dunbar09b14892008-11-12 10:30:32 +0000350 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
351 // Handle ?: operator.
352
353 // Just ignore GNU ?: extension.
354 if (CondOp->getLHS()) {
355 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
356 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
357 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
358 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
359 EmitBlock(LHSBlock);
360 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
361 EmitBlock(RHSBlock);
362 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
363 return;
364 }
365 }
366
Chris Lattner31a09842008-11-12 08:04:58 +0000367 // Emit the code with the fully general case.
368 llvm::Value *CondV = EvaluateExprAsBool(Cond);
369 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
370}
371
Devang Patel88a981b2007-11-01 19:11:01 +0000372/// getCGRecordLayout - Return record layout info.
373const CGRecordLayout *CodeGenFunction::getCGRecordLayout(CodeGenTypes &CGT,
Chris Lattneraf319132008-02-05 06:55:31 +0000374 QualType Ty) {
375 const RecordType *RTy = Ty->getAsRecordType();
376 assert (RTy && "Unexpected type. RecordType expected here.");
Devang Patelb84a06e2007-10-23 02:10:49 +0000377
Chris Lattneraf319132008-02-05 06:55:31 +0000378 return CGT.getCGRecordLayout(RTy->getDecl());
Devang Patelb84a06e2007-10-23 02:10:49 +0000379}
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000380
Daniel Dunbar488e9932008-08-16 00:56:44 +0000381/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000382/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000383void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
384 bool OmitOnError) {
385 CGM.ErrorUnsupported(S, Type, OmitOnError);
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000386}
387
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000388unsigned CodeGenFunction::GetIDForAddrOfLabel(const LabelStmt *L) {
389 // Use LabelIDs.size() as the new ID if one hasn't been assigned.
390 return LabelIDs.insert(std::make_pair(L, LabelIDs.size())).first->second;
391}
392
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000393void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty)
394{
395 const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
396 if (DestPtr->getType() != BP)
397 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
398
399 // Get size and alignment info for this aggregate.
400 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
401
402 // FIXME: Handle variable sized types.
403 const llvm::Type *IntPtr = llvm::IntegerType::get(LLVMPointerWidth);
404
405 Builder.CreateCall4(CGM.getMemSetFn(), DestPtr,
406 llvm::ConstantInt::getNullValue(llvm::Type::Int8Ty),
407 // TypeInfo.first describes size in bits.
408 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
409 llvm::ConstantInt::get(llvm::Type::Int32Ty,
410 TypeInfo.second/8));
411}
412
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000413void CodeGenFunction::EmitIndirectSwitches() {
414 llvm::BasicBlock *Default;
415
Daniel Dunbar76526a52008-08-04 17:24:44 +0000416 if (IndirectSwitches.empty())
417 return;
418
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000419 if (!LabelIDs.empty()) {
420 Default = getBasicBlockForLabel(LabelIDs.begin()->first);
421 } else {
422 // No possible targets for indirect goto, just emit an infinite
423 // loop.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000424 Default = createBasicBlock("indirectgoto.loop", CurFn);
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000425 llvm::BranchInst::Create(Default, Default);
426 }
427
428 for (std::vector<llvm::SwitchInst*>::iterator i = IndirectSwitches.begin(),
429 e = IndirectSwitches.end(); i != e; ++i) {
430 llvm::SwitchInst *I = *i;
431
432 I->setSuccessor(0, Default);
433 for (std::map<const LabelStmt*,unsigned>::iterator LI = LabelIDs.begin(),
434 LE = LabelIDs.end(); LI != LE; ++LI) {
435 I->addCase(llvm::ConstantInt::get(llvm::Type::Int32Ty,
436 LI->second),
437 getBasicBlockForLabel(LI->first));
438 }
439 }
440}
Anders Carlssonddf7cac2008-11-04 05:30:00 +0000441
Anders Carlssondcc90d82008-12-12 07:19:02 +0000442llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT)
443{
444 llvm::Value *&SizeEntry = VLASizeMap[VAT];
Anders Carlssondcc90d82008-12-12 07:19:02 +0000445
Anders Carlssonf666b772008-12-20 20:27:15 +0000446 assert(SizeEntry && "Did not emit size for type");
447 return SizeEntry;
448}
Anders Carlssondcc90d82008-12-12 07:19:02 +0000449
Anders Carlsson60d35412008-12-20 20:46:34 +0000450llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty)
Anders Carlssonf666b772008-12-20 20:27:15 +0000451{
Anders Carlsson60d35412008-12-20 20:46:34 +0000452 assert(Ty->isVariablyModifiedType() &&
453 "Must pass variably modified type to EmitVLASizes!");
Anders Carlssonf666b772008-12-20 20:27:15 +0000454
Anders Carlsson60d35412008-12-20 20:46:34 +0000455 if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
456 llvm::Value *&SizeEntry = VLASizeMap[VAT];
457
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000458 if (!SizeEntry) {
459 // Get the element size;
460 llvm::Value *ElemSize;
Anders Carlsson60d35412008-12-20 20:46:34 +0000461
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000462 QualType ElemTy = VAT->getElementType();
Anders Carlsson96f21472009-02-05 19:43:10 +0000463
464 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
465
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000466 if (ElemTy->isVariableArrayType())
467 ElemSize = EmitVLASize(ElemTy);
468 else {
Anders Carlsson96f21472009-02-05 19:43:10 +0000469 ElemSize = llvm::ConstantInt::get(SizeTy,
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000470 getContext().getTypeSize(ElemTy) / 8);
471 }
Anders Carlsson60d35412008-12-20 20:46:34 +0000472
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000473 llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
Anders Carlsson96f21472009-02-05 19:43:10 +0000474 NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
475
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000476 SizeEntry = Builder.CreateMul(ElemSize, NumElements);
Anders Carlsson60d35412008-12-20 20:46:34 +0000477 }
478
Anders Carlsson60d35412008-12-20 20:46:34 +0000479 return SizeEntry;
480 } else if (const PointerType *PT = Ty->getAsPointerType())
481 EmitVLASize(PT->getPointeeType());
Anders Carlssonf666b772008-12-20 20:27:15 +0000482 else {
Anders Carlsson60d35412008-12-20 20:46:34 +0000483 assert(0 && "unknown VM type!");
Anders Carlssondcc90d82008-12-12 07:19:02 +0000484 }
Anders Carlsson60d35412008-12-20 20:46:34 +0000485
486 return 0;
Anders Carlssondcc90d82008-12-12 07:19:02 +0000487}
Eli Friedman4fd0aa52009-01-20 17:46:04 +0000488
489llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
490 if (CGM.getContext().getBuiltinVaListType()->isArrayType()) {
491 return EmitScalarExpr(E);
492 }
493 return EmitLValue(E).getAddress();
494}
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000495
Anders Carlsson6fc55912009-02-08 03:22:36 +0000496void CodeGenFunction::PushCleanupBlock(llvm::BasicBlock *CleanupBlock)
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000497{
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000498 CleanupEntries.push_back(CleanupEntry(CleanupBlock));
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000499}
Anders Carlssonc71c8452009-02-07 23:50:39 +0000500
501void CodeGenFunction::EmitCleanupBlocks(size_t OldCleanupStackSize)
502{
503 assert(CleanupEntries.size() >= OldCleanupStackSize &&
504 "Cleanup stack mismatch!");
505
506 while (CleanupEntries.size() > OldCleanupStackSize)
507 EmitCleanupBlock();
508}
509
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000510CodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock()
Anders Carlssonc71c8452009-02-07 23:50:39 +0000511{
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000512 CleanupEntry &CE = CleanupEntries.back();
513
514 llvm::BasicBlock *CleanupBlock = CE.CleanupBlock;
515
516 std::vector<llvm::BasicBlock *> Blocks;
517 std::swap(Blocks, CE.Blocks);
518
519 std::vector<llvm::BranchInst *> BranchFixups;
520 std::swap(BranchFixups, CE.BranchFixups);
521
522 CleanupEntries.pop_back();
523
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000524 // Check if any branch fixups pointed to the scope we just popped. If so,
525 // we can remove them.
526 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
527 llvm::BasicBlock *Dest = BranchFixups[i]->getSuccessor(0);
528 BlockScopeMap::iterator I = BlockScopes.find(Dest);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000529
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000530 if (I == BlockScopes.end())
531 continue;
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000532
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000533 assert(I->second <= CleanupEntries.size() && "Invalid branch fixup!");
Anders Carlssond66a9f92009-02-08 03:55:35 +0000534
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000535 if (I->second == CleanupEntries.size()) {
536 // We don't need to do this branch fixup.
537 BranchFixups[i] = BranchFixups.back();
538 BranchFixups.pop_back();
539 i--;
540 e--;
541 continue;
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000542 }
543 }
Anders Carlssond66a9f92009-02-08 03:55:35 +0000544
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000545 llvm::BasicBlock *SwitchBlock = 0;
546 llvm::BasicBlock *EndBlock = 0;
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000547 if (!BranchFixups.empty()) {
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000548 SwitchBlock = createBasicBlock("cleanup.switch");
549 EndBlock = createBasicBlock("cleanup.end");
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000550
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000551 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
552
553 Builder.SetInsertPoint(SwitchBlock);
554
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000555 llvm::Value *DestCodePtr = CreateTempAlloca(llvm::Type::Int32Ty,
556 "cleanup.dst");
557 llvm::Value *DestCode = Builder.CreateLoad(DestCodePtr, "tmp");
558
559 // Create a switch instruction to determine where to jump next.
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000560 llvm::SwitchInst *SI = Builder.CreateSwitch(DestCode, EndBlock,
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000561 BranchFixups.size());
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000562
Anders Carlsson46831a92009-02-08 22:13:37 +0000563 // Restore the current basic block (if any)
564 if (CurBB)
565 Builder.SetInsertPoint(CurBB);
566 else
567 Builder.ClearInsertionPoint();
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000568
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000569 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
570 llvm::BranchInst *BI = BranchFixups[i];
571 llvm::BasicBlock *Dest = BI->getSuccessor(0);
572
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000573 // Fixup the branch instruction to point to the cleanup block.
574 BI->setSuccessor(0, CleanupBlock);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000575
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000576 if (CleanupEntries.empty()) {
Anders Carlssoncc899202009-02-08 22:46:50 +0000577 llvm::ConstantInt *ID;
578
579 // Check if we already have a destination for this block.
580 if (Dest == SI->getDefaultDest())
581 ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
582 else {
583 ID = SI->findCaseDest(Dest);
584 if (!ID) {
585 // No code found, get a new unique one by using the number of
586 // switch successors.
587 ID = llvm::ConstantInt::get(llvm::Type::Int32Ty,
588 SI->getNumSuccessors());
589 SI->addCase(ID, Dest);
590 }
591 }
592
593 // Store the jump destination before the branch instruction.
594 new llvm::StoreInst(ID, DestCodePtr, BI);
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000595 } else {
596 // We need to jump through another cleanup block. Create a pad block
597 // with a branch instruction that jumps to the final destination and
598 // add it as a branch fixup to the current cleanup scope.
599
600 // Create the pad block.
601 llvm::BasicBlock *CleanupPad = createBasicBlock("cleanup.pad", CurFn);
Anders Carlssoncc899202009-02-08 22:46:50 +0000602
603 // Create a unique case ID.
604 llvm::ConstantInt *ID = llvm::ConstantInt::get(llvm::Type::Int32Ty,
605 SI->getNumSuccessors());
606
607 // Store the jump destination before the branch instruction.
608 new llvm::StoreInst(ID, DestCodePtr, BI);
609
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000610 // Add it as the destination.
Anders Carlssoncc899202009-02-08 22:46:50 +0000611 SI->addCase(ID, CleanupPad);
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000612
613 // Create the branch to the final destination.
614 llvm::BranchInst *BI = llvm::BranchInst::Create(Dest);
615 CleanupPad->getInstList().push_back(BI);
616
617 // And add it as a branch fixup.
618 CleanupEntries.back().BranchFixups.push_back(BI);
619 }
620 }
621 }
Anders Carlssond66a9f92009-02-08 03:55:35 +0000622
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000623 // Remove all blocks from the block scope map.
624 for (size_t i = 0, e = Blocks.size(); i != e; ++i) {
625 assert(BlockScopes.count(Blocks[i]) &&
626 "Did not find block in scope map!");
627
628 BlockScopes.erase(Blocks[i]);
629 }
Anders Carlssond66a9f92009-02-08 03:55:35 +0000630
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000631 return CleanupBlockInfo(CleanupBlock, SwitchBlock, EndBlock);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000632}
633
634void CodeGenFunction::EmitCleanupBlock()
635{
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000636 CleanupBlockInfo Info = PopCleanupBlock();
Anders Carlssond66a9f92009-02-08 03:55:35 +0000637
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000638 EmitBlock(Info.CleanupBlock);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000639
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000640 if (Info.SwitchBlock)
641 EmitBlock(Info.SwitchBlock);
642 if (Info.EndBlock)
643 EmitBlock(Info.EndBlock);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000644}
645
Anders Carlsson87eaf172009-02-08 00:50:42 +0000646void CodeGenFunction::AddBranchFixup(llvm::BranchInst *BI)
647{
648 assert(!CleanupEntries.empty() &&
649 "Trying to add branch fixup without cleanup block!");
650
651 // FIXME: We could be more clever here and check if there's already a
652 // branch fixup for this destination and recycle it.
653 CleanupEntries.back().BranchFixups.push_back(BI);
654}
655
656void CodeGenFunction::EmitBranchThroughCleanup(llvm::BasicBlock *Dest)
657{
Anders Carlsson46831a92009-02-08 22:13:37 +0000658 if (!HaveInsertPoint())
659 return;
660
Anders Carlsson87eaf172009-02-08 00:50:42 +0000661 llvm::BranchInst* BI = Builder.CreateBr(Dest);
662
Anders Carlsson46831a92009-02-08 22:13:37 +0000663 Builder.ClearInsertionPoint();
664
Anders Carlsson87eaf172009-02-08 00:50:42 +0000665 // The stack is empty, no need to do any cleanup.
666 if (CleanupEntries.empty())
667 return;
668
669 if (!Dest->getParent()) {
670 // We are trying to branch to a block that hasn't been inserted yet.
671 AddBranchFixup(BI);
672 return;
673 }
674
675 BlockScopeMap::iterator I = BlockScopes.find(Dest);
676 if (I == BlockScopes.end()) {
677 // We are trying to jump to a block that is outside of any cleanup scope.
678 AddBranchFixup(BI);
679 return;
680 }
681
682 assert(I->second < CleanupEntries.size() &&
683 "Trying to branch into cleanup region");
684
685 if (I->second == CleanupEntries.size() - 1) {
686 // We have a branch to a block in the same scope.
687 return;
688 }
689
690 AddBranchFixup(BI);
691}