blob: adeb4ebfd4a60aa5f995f5b36c835518a914b195 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-function state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
15#include "CodeGenModule.h"
Eli Friedman9bc7c8d2008-05-22 01:40:10 +000016#include "CGDebugInfo.h"
Chris Lattner4b009652007-07-25 00:24:17 +000017#include "clang/Basic/TargetInfo.h"
Chris Lattner3d6606b2008-11-12 08:04:58 +000018#include "clang/AST/APValue.h"
Daniel Dunbareee5cd12008-08-11 05:00:27 +000019#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000020#include "clang/AST/Decl.h"
Devang Patel97299362007-09-28 21:49:18 +000021#include "llvm/Support/CFG.h"
Mike Stumpfca5da02009-02-21 20:00:35 +000022#include "llvm/Target/TargetData.h"
Chris Lattner4b009652007-07-25 00:24:17 +000023using namespace clang;
24using namespace CodeGen;
25
26CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
Mike Stumpecd79422009-03-06 01:33:24 +000027 : BlockFunction(cgm, *this, Builder), CGM(cgm),
28 Target(CGM.getContext().Target),
Mike Stumpa79696d2009-03-04 18:57:26 +000029 DebugInfo(0), SwitchInsn(0), CaseRangeBlock(0), InvokeDest(0) {
Mike Stumpfca5da02009-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.
35 BlockHasCopyDispose = false;
36 if (!BlockHasCopyDispose)
37 BlockOffset = CGM.getTargetData()
38 .getTypeStoreSizeInBits(CGM.getGenericBlockLiteralType()) / 8;
39 else
40 BlockOffset = CGM.getTargetData()
41 .getTypeStoreSizeInBits(CGM.getGenericExtendedBlockLiteralType()) / 8;
Mike Stumpf1711822009-02-25 23:33:13 +000042 BlockAlign = getContext().getTypeAlign(getContext().VoidPtrTy) / 8;
Chris Lattner8c7c6a12008-06-17 18:05:57 +000043}
Chris Lattner4b009652007-07-25 00:24:17 +000044
45ASTContext &CodeGenFunction::getContext() const {
46 return CGM.getContext();
47}
48
49
50llvm::BasicBlock *CodeGenFunction::getBasicBlockForLabel(const LabelStmt *S) {
51 llvm::BasicBlock *&BB = LabelMap[S];
52 if (BB) return BB;
53
54 // Create, but don't insert, the new block.
Daniel Dunbar72f96552008-11-11 02:29:29 +000055 return BB = createBasicBlock(S->getName());
Chris Lattner4b009652007-07-25 00:24:17 +000056}
57
Daniel Dunbardea59212009-02-25 19:24:29 +000058llvm::Value *CodeGenFunction::GetAddrOfLocalVar(const VarDecl *VD) {
59 llvm::Value *Res = LocalDeclMap[VD];
60 assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!");
61 return Res;
Lauro Ramos Venancio934fb022008-02-26 21:41:45 +000062}
Chris Lattner4b009652007-07-25 00:24:17 +000063
Daniel Dunbardea59212009-02-25 19:24:29 +000064llvm::Constant *
65CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) {
66 return cast<llvm::Constant>(GetAddrOfLocalVar(BVD));
Anders Carlsson75d86732008-09-11 09:15:33 +000067}
68
Daniel Dunbar706059f2009-02-03 23:03:55 +000069const llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
70 return CGM.getTypes().ConvertTypeForMem(T);
71}
72
Chris Lattner4b009652007-07-25 00:24:17 +000073const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
74 return CGM.getTypes().ConvertType(T);
75}
76
77bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
Daniel Dunbar96891242009-01-09 02:44:18 +000078 // FIXME: Use positive checks instead of negative ones to be more
79 // robust in the face of extension.
Daniel Dunbarfc096bf2009-02-26 20:52:22 +000080 return !T->hasPointerRepresentation() &&!T->isRealType() &&
81 !T->isVoidType() && !T->isVectorType() && !T->isFunctionType() &&
Daniel Dunbar96891242009-01-09 02:44:18 +000082 !T->isBlockPointerType();
Chris Lattner4b009652007-07-25 00:24:17 +000083}
84
Daniel Dunbar924f4ea2009-01-26 23:27:52 +000085void CodeGenFunction::EmitReturnBlock() {
86 // For cleanliness, we try to avoid emitting the return block for
87 // simple cases.
88 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
89
90 if (CurBB) {
91 assert(!CurBB->getTerminator() && "Unexpected terminated block.");
92
93 // We have a valid insert point, reuse it if there are no explicit
94 // jumps to the return block.
95 if (ReturnBlock->use_empty())
96 delete ReturnBlock;
97 else
98 EmitBlock(ReturnBlock);
99 return;
100 }
101
102 // Otherwise, if the return block is the target of a single direct
103 // branch then we can just put the code in that block instead. This
104 // cleans up functions which started with a unified return block.
105 if (ReturnBlock->hasOneUse()) {
106 llvm::BranchInst *BI =
107 dyn_cast<llvm::BranchInst>(*ReturnBlock->use_begin());
108 if (BI && BI->isUnconditional() && BI->getSuccessor(0) == ReturnBlock) {
109 // Reset insertion point and delete the branch.
110 Builder.SetInsertPoint(BI->getParent());
111 BI->eraseFromParent();
112 delete ReturnBlock;
113 return;
114 }
115 }
116
117 // FIXME: We are at an unreachable point, there is no reason to emit
118 // the block unless it has uses. However, we still need a place to
119 // put the debug region.end for now.
120
121 EmitBlock(ReturnBlock);
122}
123
Daniel Dunbar6b57d432008-08-26 08:29:31 +0000124void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
Daniel Dunbar879788d2008-08-04 16:51:22 +0000125 // Finish emission of indirect switches.
126 EmitIndirectSwitches();
127
Chris Lattner4b009652007-07-25 00:24:17 +0000128 assert(BreakContinueStack.empty() &&
129 "mismatched push/pop in break/continue stack!");
Anders Carlssone7de3522009-02-08 00:16:35 +0000130 assert(BlockScopes.empty() &&
131 "did not remove all blocks from block scope map!");
132 assert(CleanupEntries.empty() &&
133 "mismatched push/pop in cleanup stack!");
134
Daniel Dunbar924f4ea2009-01-26 23:27:52 +0000135 // Emit function epilog (to return).
136 EmitReturnBlock();
Daniel Dunbar03f7ae12008-11-11 20:59:54 +0000137
138 // Emit debug descriptor for function end.
Anders Carlsson73007792009-02-13 08:11:52 +0000139 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar03f7ae12008-11-11 20:59:54 +0000140 DI->setLocation(EndLoc);
141 DI->EmitRegionEnd(CurFn, Builder);
142 }
143
Daniel Dunbar6ee022b2009-02-02 22:03:45 +0000144 EmitFunctionEpilog(*CurFnInfo, ReturnValue);
Daniel Dunbar9fb751f2008-09-09 21:00:17 +0000145
Chris Lattnerca929812007-12-02 06:32:24 +0000146 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
147 AllocaInsertPt->eraseFromParent();
148 AllocaInsertPt = 0;
Chris Lattner4b009652007-07-25 00:24:17 +0000149}
150
Daniel Dunbar96816832008-09-09 23:14:03 +0000151void CodeGenFunction::StartFunction(const Decl *D, QualType RetTy,
152 llvm::Function *Fn,
Daniel Dunbar54968bf2008-10-18 18:22:23 +0000153 const FunctionArgList &Args,
154 SourceLocation StartLoc) {
Anders Carlsson60c4c402009-02-09 20:20:56 +0000155 DidCallStackSave = false;
Daniel Dunbar96816832008-09-09 23:14:03 +0000156 CurFuncDecl = D;
157 FnRetTy = RetTy;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000158 CurFn = Fn;
Chris Lattner8c7c6a12008-06-17 18:05:57 +0000159 assert(CurFn->isDeclaration() && "Function already has body?");
160
Daniel Dunbar72f96552008-11-11 02:29:29 +0000161 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
Daniel Dunbar9fb751f2008-09-09 21:00:17 +0000162
Chris Lattner8c7c6a12008-06-17 18:05:57 +0000163 // Create a marker to make it easy to insert allocas into the entryblock
164 // later. Don't create this with the builder, because we don't want it
165 // folded.
166 llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::Int32Ty);
167 AllocaInsertPt = new llvm::BitCastInst(Undef, llvm::Type::Int32Ty, "allocapt",
168 EntryBB);
Daniel Dunbar9fb751f2008-09-09 21:00:17 +0000169
Daniel Dunbar72f96552008-11-11 02:29:29 +0000170 ReturnBlock = createBasicBlock("return");
Daniel Dunbar9fb751f2008-09-09 21:00:17 +0000171 ReturnValue = 0;
Daniel Dunbar96816832008-09-09 23:14:03 +0000172 if (!RetTy->isVoidType())
173 ReturnValue = CreateTempAlloca(ConvertType(RetTy), "retval");
Daniel Dunbar9fb751f2008-09-09 21:00:17 +0000174
Chris Lattner8c7c6a12008-06-17 18:05:57 +0000175 Builder.SetInsertPoint(EntryBB);
176
Sanjiv Gupta1d340eb2008-07-04 11:04:26 +0000177 // Emit subprogram debug descriptor.
Daniel Dunbar96816832008-09-09 23:14:03 +0000178 // FIXME: The cast here is a huge hack.
Anders Carlsson73007792009-02-13 08:11:52 +0000179 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar54968bf2008-10-18 18:22:23 +0000180 DI->setLocation(StartLoc);
181 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3c3c4542009-02-18 23:53:56 +0000182 DI->EmitFunctionStart(CGM.getMangledName(FD), RetTy, CurFn, Builder);
Daniel Dunbar54968bf2008-10-18 18:22:23 +0000183 } else {
184 // Just use LLVM function name.
185 DI->EmitFunctionStart(Fn->getName().c_str(),
186 RetTy, CurFn, Builder);
Sanjiv Gupta1d340eb2008-07-04 11:04:26 +0000187 }
Sanjiv Gupta1d340eb2008-07-04 11:04:26 +0000188 }
189
Daniel Dunbar6ee022b2009-02-02 22:03:45 +0000190 // FIXME: Leaked.
Daniel Dunbar34bda882009-02-02 23:23:47 +0000191 CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args);
Daniel Dunbar6ee022b2009-02-02 22:03:45 +0000192 EmitFunctionProlog(*CurFnInfo, CurFn, Args);
Anders Carlsson21cecd42008-12-20 21:28:43 +0000193
194 // If any of the arguments have a variably modified type, make sure to
195 // emit the type size.
196 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
197 i != e; ++i) {
198 QualType Ty = i->second;
199
200 if (Ty->isVariablyModifiedType())
201 EmitVLASize(Ty);
202 }
Daniel Dunbar96816832008-09-09 23:14:03 +0000203}
Eli Friedman769e7302008-08-25 21:31:01 +0000204
Daniel Dunbar96816832008-09-09 23:14:03 +0000205void CodeGenFunction::GenerateCode(const FunctionDecl *FD,
206 llvm::Function *Fn) {
Anders Carlsson73007792009-02-13 08:11:52 +0000207 // Check if we should generate debug info for this function.
208 if (CGM.getDebugInfo() && !FD->getAttr<NodebugAttr>())
209 DebugInfo = CGM.getDebugInfo();
210
Daniel Dunbar96816832008-09-09 23:14:03 +0000211 FunctionArgList Args;
Eli Friedman769e7302008-08-25 21:31:01 +0000212 if (FD->getNumParams()) {
Douglas Gregor4fa58902009-02-26 23:50:07 +0000213 const FunctionProtoType* FProto = FD->getType()->getAsFunctionProtoType();
Eli Friedman769e7302008-08-25 21:31:01 +0000214 assert(FProto && "Function def must have prototype!");
Daniel Dunbar96816832008-09-09 23:14:03 +0000215
216 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
217 Args.push_back(std::make_pair(FD->getParamDecl(i),
218 FProto->getArgType(i)));
Chris Lattner8c7c6a12008-06-17 18:05:57 +0000219 }
Daniel Dunbar6b57d432008-08-26 08:29:31 +0000220
Daniel Dunbar54968bf2008-10-18 18:22:23 +0000221 StartFunction(FD, FD->getResultType(), Fn, Args,
222 cast<CompoundStmt>(FD->getBody())->getLBracLoc());
Daniel Dunbar96816832008-09-09 23:14:03 +0000223
Daniel Dunbar6b57d432008-08-26 08:29:31 +0000224 EmitStmt(FD->getBody());
225
226 const CompoundStmt *S = dyn_cast<CompoundStmt>(FD->getBody());
227 if (S) {
228 FinishFunction(S->getRBracLoc());
229 } else {
230 FinishFunction();
231 }
Chris Lattner8c7c6a12008-06-17 18:05:57 +0000232}
233
Chris Lattner3f73d0d2008-11-11 07:41:27 +0000234/// ContainsLabel - Return true if the statement contains a label in it. If
235/// this statement is not executed normally, it not containing a label means
236/// that we can just remove the code.
237bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
238 // Null statement, not a label!
239 if (S == 0) return false;
240
241 // If this is a label, we have to emit the code, consider something like:
242 // if (0) { ... foo: bar(); } goto foo;
243 if (isa<LabelStmt>(S))
244 return true;
245
246 // If this is a case/default statement, and we haven't seen a switch, we have
247 // to emit the code.
248 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
249 return true;
250
251 // If this is a switch statement, we want to ignore cases below it.
252 if (isa<SwitchStmt>(S))
253 IgnoreCaseStmts = true;
254
255 // Scan subexpressions for verboten labels.
256 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
257 I != E; ++I)
258 if (ContainsLabel(*I, IgnoreCaseStmts))
259 return true;
260
261 return false;
262}
263
Chris Lattner3d6606b2008-11-12 08:04:58 +0000264
265/// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
266/// a constant, or if it does but contains a label, return 0. If it constant
267/// folds to 'true' and does not contain a label, return 1, if it constant folds
268/// to 'false' and does not contain a label, return -1.
269int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
Daniel Dunbar14937022008-11-12 22:37:10 +0000270 // FIXME: Rename and handle conversion of other evaluatable things
271 // to bool.
Anders Carlsson90d85f32008-12-01 02:46:24 +0000272 Expr::EvalResult Result;
273 if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
274 Result.HasSideEffects)
Anders Carlssonea3c6ab2008-11-22 22:32:07 +0000275 return 0; // Not foldable, not integer or not fully evaluatable.
Chris Lattner3d6606b2008-11-12 08:04:58 +0000276
277 if (CodeGenFunction::ContainsLabel(Cond))
278 return 0; // Contains a label.
279
Anders Carlsson90d85f32008-12-01 02:46:24 +0000280 return Result.Val.getInt().getBoolValue() ? 1 : -1;
Chris Lattner3d6606b2008-11-12 08:04:58 +0000281}
282
283
284/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
285/// statement) to the specified blocks. Based on the condition, this might try
286/// to simplify the codegen of the conditional based on the branch.
287///
288void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
289 llvm::BasicBlock *TrueBlock,
290 llvm::BasicBlock *FalseBlock) {
291 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
292 return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
293
294 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
295 // Handle X && Y in a condition.
296 if (CondBOp->getOpcode() == BinaryOperator::LAnd) {
297 // If we have "1 && X", simplify the code. "0 && X" would have constant
298 // folded if the case was simple enough.
299 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
300 // br(1 && X) -> br(X).
301 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
302 }
303
304 // If we have "X && 1", simplify the code to use an uncond branch.
305 // "X && 0" would have been constant folded to 0.
306 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
307 // br(X && 1) -> br(X).
308 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
309 }
310
311 // Emit the LHS as a conditional. If the LHS conditional is false, we
312 // want to jump to the FalseBlock.
Daniel Dunbar6e3a10c2008-11-13 01:38:36 +0000313 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
Chris Lattner3d6606b2008-11-12 08:04:58 +0000314 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
315 EmitBlock(LHSTrue);
316
317 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
318 return;
319 } else if (CondBOp->getOpcode() == BinaryOperator::LOr) {
320 // If we have "0 || X", simplify the code. "1 || X" would have constant
321 // folded if the case was simple enough.
322 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
323 // br(0 || X) -> br(X).
324 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
325 }
326
327 // If we have "X || 0", simplify the code to use an uncond branch.
328 // "X || 1" would have been constant folded to 1.
329 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
330 // br(X || 0) -> br(X).
331 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
332 }
333
334 // Emit the LHS as a conditional. If the LHS conditional is true, we
335 // want to jump to the TrueBlock.
Daniel Dunbar6e3a10c2008-11-13 01:38:36 +0000336 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
Chris Lattner3d6606b2008-11-12 08:04:58 +0000337 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
338 EmitBlock(LHSFalse);
339
340 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
341 return;
342 }
Chris Lattnercfbfe912008-11-12 08:13:36 +0000343 }
344
345 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
346 // br(!x, t, f) -> br(x, f, t)
347 if (CondUOp->getOpcode() == UnaryOperator::LNot)
348 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
Chris Lattner3d6606b2008-11-12 08:04:58 +0000349 }
350
Daniel Dunbarab81c632008-11-12 10:30:32 +0000351 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
352 // Handle ?: operator.
353
354 // Just ignore GNU ?: extension.
355 if (CondOp->getLHS()) {
356 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
357 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
358 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
359 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
360 EmitBlock(LHSBlock);
361 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
362 EmitBlock(RHSBlock);
363 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
364 return;
365 }
366 }
367
Chris Lattner3d6606b2008-11-12 08:04:58 +0000368 // Emit the code with the fully general case.
369 llvm::Value *CondV = EvaluateExprAsBool(Cond);
370 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
371}
372
Devang Patel7a78e432007-11-01 19:11:01 +0000373/// getCGRecordLayout - Return record layout info.
374const CGRecordLayout *CodeGenFunction::getCGRecordLayout(CodeGenTypes &CGT,
Chris Lattner7b2543e2008-02-05 06:55:31 +0000375 QualType Ty) {
376 const RecordType *RTy = Ty->getAsRecordType();
377 assert (RTy && "Unexpected type. RecordType expected here.");
Devang Patelaebd83f2007-10-23 02:10:49 +0000378
Chris Lattner7b2543e2008-02-05 06:55:31 +0000379 return CGT.getCGRecordLayout(RTy->getDecl());
Devang Patelaebd83f2007-10-23 02:10:49 +0000380}
Chris Lattner9d4e6202007-12-02 01:43:38 +0000381
Daniel Dunbar9503b782008-08-16 00:56:44 +0000382/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner9d4e6202007-12-02 01:43:38 +0000383/// specified stmt yet.
Daniel Dunbar49bddf72008-09-04 03:43:08 +0000384void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
385 bool OmitOnError) {
386 CGM.ErrorUnsupported(S, Type, OmitOnError);
Chris Lattner9d4e6202007-12-02 01:43:38 +0000387}
388
Daniel Dunbar879788d2008-08-04 16:51:22 +0000389unsigned CodeGenFunction::GetIDForAddrOfLabel(const LabelStmt *L) {
390 // Use LabelIDs.size() as the new ID if one hasn't been assigned.
391 return LabelIDs.insert(std::make_pair(L, LabelIDs.size())).first->second;
392}
393
Anders Carlsson82b0d0c2008-08-30 19:51:14 +0000394void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty)
395{
396 const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
397 if (DestPtr->getType() != BP)
398 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
399
400 // Get size and alignment info for this aggregate.
401 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
402
403 // FIXME: Handle variable sized types.
404 const llvm::Type *IntPtr = llvm::IntegerType::get(LLVMPointerWidth);
405
406 Builder.CreateCall4(CGM.getMemSetFn(), DestPtr,
407 llvm::ConstantInt::getNullValue(llvm::Type::Int8Ty),
408 // TypeInfo.first describes size in bits.
409 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
410 llvm::ConstantInt::get(llvm::Type::Int32Ty,
411 TypeInfo.second/8));
412}
413
Daniel Dunbar879788d2008-08-04 16:51:22 +0000414void CodeGenFunction::EmitIndirectSwitches() {
415 llvm::BasicBlock *Default;
416
Daniel Dunbar8ccfa802008-08-04 17:24:44 +0000417 if (IndirectSwitches.empty())
418 return;
419
Daniel Dunbar879788d2008-08-04 16:51:22 +0000420 if (!LabelIDs.empty()) {
421 Default = getBasicBlockForLabel(LabelIDs.begin()->first);
422 } else {
423 // No possible targets for indirect goto, just emit an infinite
424 // loop.
Daniel Dunbar72f96552008-11-11 02:29:29 +0000425 Default = createBasicBlock("indirectgoto.loop", CurFn);
Daniel Dunbar879788d2008-08-04 16:51:22 +0000426 llvm::BranchInst::Create(Default, Default);
427 }
428
429 for (std::vector<llvm::SwitchInst*>::iterator i = IndirectSwitches.begin(),
430 e = IndirectSwitches.end(); i != e; ++i) {
431 llvm::SwitchInst *I = *i;
432
433 I->setSuccessor(0, Default);
434 for (std::map<const LabelStmt*,unsigned>::iterator LI = LabelIDs.begin(),
435 LE = LabelIDs.end(); LI != LE; ++LI) {
436 I->addCase(llvm::ConstantInt::get(llvm::Type::Int32Ty,
437 LI->second),
438 getBasicBlockForLabel(LI->first));
439 }
440 }
441}
Anders Carlsson285611e2008-11-04 05:30:00 +0000442
Anders Carlsson32aa0c22008-12-12 07:19:02 +0000443llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT)
444{
445 llvm::Value *&SizeEntry = VLASizeMap[VAT];
Anders Carlsson32aa0c22008-12-12 07:19:02 +0000446
Anders Carlssonf860e022008-12-20 20:27:15 +0000447 assert(SizeEntry && "Did not emit size for type");
448 return SizeEntry;
449}
Anders Carlsson32aa0c22008-12-12 07:19:02 +0000450
Anders Carlssond9767612008-12-20 20:46:34 +0000451llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty)
Anders Carlssonf860e022008-12-20 20:27:15 +0000452{
Anders Carlssond9767612008-12-20 20:46:34 +0000453 assert(Ty->isVariablyModifiedType() &&
454 "Must pass variably modified type to EmitVLASizes!");
Anders Carlssonf860e022008-12-20 20:27:15 +0000455
Anders Carlssond9767612008-12-20 20:46:34 +0000456 if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
457 llvm::Value *&SizeEntry = VLASizeMap[VAT];
458
Anders Carlssonef2f7df2008-12-20 21:51:53 +0000459 if (!SizeEntry) {
460 // Get the element size;
461 llvm::Value *ElemSize;
Anders Carlssond9767612008-12-20 20:46:34 +0000462
Anders Carlssonef2f7df2008-12-20 21:51:53 +0000463 QualType ElemTy = VAT->getElementType();
Anders Carlsson8f30de92009-02-05 19:43:10 +0000464
465 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
466
Anders Carlssonef2f7df2008-12-20 21:51:53 +0000467 if (ElemTy->isVariableArrayType())
468 ElemSize = EmitVLASize(ElemTy);
469 else {
Anders Carlsson8f30de92009-02-05 19:43:10 +0000470 ElemSize = llvm::ConstantInt::get(SizeTy,
Anders Carlssonef2f7df2008-12-20 21:51:53 +0000471 getContext().getTypeSize(ElemTy) / 8);
472 }
Anders Carlssond9767612008-12-20 20:46:34 +0000473
Anders Carlssonef2f7df2008-12-20 21:51:53 +0000474 llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
Anders Carlsson8f30de92009-02-05 19:43:10 +0000475 NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
476
Anders Carlssonef2f7df2008-12-20 21:51:53 +0000477 SizeEntry = Builder.CreateMul(ElemSize, NumElements);
Anders Carlssond9767612008-12-20 20:46:34 +0000478 }
479
Anders Carlssond9767612008-12-20 20:46:34 +0000480 return SizeEntry;
481 } else if (const PointerType *PT = Ty->getAsPointerType())
482 EmitVLASize(PT->getPointeeType());
Anders Carlssonf860e022008-12-20 20:27:15 +0000483 else {
Anders Carlssond9767612008-12-20 20:46:34 +0000484 assert(0 && "unknown VM type!");
Anders Carlsson32aa0c22008-12-12 07:19:02 +0000485 }
Anders Carlssond9767612008-12-20 20:46:34 +0000486
487 return 0;
Anders Carlsson32aa0c22008-12-12 07:19:02 +0000488}
Eli Friedman8f5e8782009-01-20 17:46:04 +0000489
490llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
491 if (CGM.getContext().getBuiltinVaListType()->isArrayType()) {
492 return EmitScalarExpr(E);
493 }
494 return EmitLValue(E).getAddress();
495}
Anders Carlsson9c5b2a42009-02-07 22:53:43 +0000496
Anders Carlsson459ee362009-02-08 03:22:36 +0000497void CodeGenFunction::PushCleanupBlock(llvm::BasicBlock *CleanupBlock)
Anders Carlsson9c5b2a42009-02-07 22:53:43 +0000498{
Anders Carlsson9c5b2a42009-02-07 22:53:43 +0000499 CleanupEntries.push_back(CleanupEntry(CleanupBlock));
Anders Carlsson9c5b2a42009-02-07 22:53:43 +0000500}
Anders Carlsson883fa552009-02-07 23:50:39 +0000501
502void CodeGenFunction::EmitCleanupBlocks(size_t OldCleanupStackSize)
503{
504 assert(CleanupEntries.size() >= OldCleanupStackSize &&
505 "Cleanup stack mismatch!");
506
507 while (CleanupEntries.size() > OldCleanupStackSize)
508 EmitCleanupBlock();
509}
510
Anders Carlssondf274192009-02-08 07:46:24 +0000511CodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock()
Anders Carlsson883fa552009-02-07 23:50:39 +0000512{
Anders Carlssondf274192009-02-08 07:46:24 +0000513 CleanupEntry &CE = CleanupEntries.back();
514
515 llvm::BasicBlock *CleanupBlock = CE.CleanupBlock;
516
517 std::vector<llvm::BasicBlock *> Blocks;
518 std::swap(Blocks, CE.Blocks);
519
520 std::vector<llvm::BranchInst *> BranchFixups;
521 std::swap(BranchFixups, CE.BranchFixups);
522
523 CleanupEntries.pop_back();
524
Anders Carlsson98720f02009-02-08 22:45:15 +0000525 // Check if any branch fixups pointed to the scope we just popped. If so,
526 // we can remove them.
527 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
528 llvm::BasicBlock *Dest = BranchFixups[i]->getSuccessor(0);
529 BlockScopeMap::iterator I = BlockScopes.find(Dest);
Anders Carlssone75ae4d2009-02-08 03:55:35 +0000530
Anders Carlsson98720f02009-02-08 22:45:15 +0000531 if (I == BlockScopes.end())
532 continue;
Anders Carlsson9b399792009-02-08 01:23:05 +0000533
Anders Carlsson98720f02009-02-08 22:45:15 +0000534 assert(I->second <= CleanupEntries.size() && "Invalid branch fixup!");
Anders Carlssone75ae4d2009-02-08 03:55:35 +0000535
Anders Carlsson98720f02009-02-08 22:45:15 +0000536 if (I->second == CleanupEntries.size()) {
537 // We don't need to do this branch fixup.
538 BranchFixups[i] = BranchFixups.back();
539 BranchFixups.pop_back();
540 i--;
541 e--;
542 continue;
Anders Carlsson9b399792009-02-08 01:23:05 +0000543 }
544 }
Anders Carlssone75ae4d2009-02-08 03:55:35 +0000545
Anders Carlssondf274192009-02-08 07:46:24 +0000546 llvm::BasicBlock *SwitchBlock = 0;
547 llvm::BasicBlock *EndBlock = 0;
Anders Carlsson9b399792009-02-08 01:23:05 +0000548 if (!BranchFixups.empty()) {
Anders Carlssondf274192009-02-08 07:46:24 +0000549 SwitchBlock = createBasicBlock("cleanup.switch");
550 EndBlock = createBasicBlock("cleanup.end");
Anders Carlsson9b399792009-02-08 01:23:05 +0000551
Anders Carlssondf274192009-02-08 07:46:24 +0000552 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
553
554 Builder.SetInsertPoint(SwitchBlock);
555
Anders Carlsson9b399792009-02-08 01:23:05 +0000556 llvm::Value *DestCodePtr = CreateTempAlloca(llvm::Type::Int32Ty,
557 "cleanup.dst");
558 llvm::Value *DestCode = Builder.CreateLoad(DestCodePtr, "tmp");
559
560 // Create a switch instruction to determine where to jump next.
Anders Carlssondf274192009-02-08 07:46:24 +0000561 llvm::SwitchInst *SI = Builder.CreateSwitch(DestCode, EndBlock,
Anders Carlsson9b399792009-02-08 01:23:05 +0000562 BranchFixups.size());
Anders Carlssondf274192009-02-08 07:46:24 +0000563
Anders Carlsson32fffb72009-02-08 22:13:37 +0000564 // Restore the current basic block (if any)
565 if (CurBB)
566 Builder.SetInsertPoint(CurBB);
567 else
568 Builder.ClearInsertionPoint();
Anders Carlssondf274192009-02-08 07:46:24 +0000569
Anders Carlsson9b399792009-02-08 01:23:05 +0000570 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
571 llvm::BranchInst *BI = BranchFixups[i];
572 llvm::BasicBlock *Dest = BI->getSuccessor(0);
573
Anders Carlsson9b399792009-02-08 01:23:05 +0000574 // Fixup the branch instruction to point to the cleanup block.
575 BI->setSuccessor(0, CleanupBlock);
Anders Carlssone75ae4d2009-02-08 03:55:35 +0000576
Anders Carlsson9b399792009-02-08 01:23:05 +0000577 if (CleanupEntries.empty()) {
Anders Carlsson8be63402009-02-08 22:46:50 +0000578 llvm::ConstantInt *ID;
579
580 // Check if we already have a destination for this block.
581 if (Dest == SI->getDefaultDest())
582 ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
583 else {
584 ID = SI->findCaseDest(Dest);
585 if (!ID) {
586 // No code found, get a new unique one by using the number of
587 // switch successors.
588 ID = llvm::ConstantInt::get(llvm::Type::Int32Ty,
589 SI->getNumSuccessors());
590 SI->addCase(ID, Dest);
591 }
592 }
593
594 // Store the jump destination before the branch instruction.
595 new llvm::StoreInst(ID, DestCodePtr, BI);
Anders Carlsson9b399792009-02-08 01:23:05 +0000596 } else {
597 // We need to jump through another cleanup block. Create a pad block
598 // with a branch instruction that jumps to the final destination and
599 // add it as a branch fixup to the current cleanup scope.
600
601 // Create the pad block.
602 llvm::BasicBlock *CleanupPad = createBasicBlock("cleanup.pad", CurFn);
Anders Carlsson8be63402009-02-08 22:46:50 +0000603
604 // Create a unique case ID.
605 llvm::ConstantInt *ID = llvm::ConstantInt::get(llvm::Type::Int32Ty,
606 SI->getNumSuccessors());
607
608 // Store the jump destination before the branch instruction.
609 new llvm::StoreInst(ID, DestCodePtr, BI);
610
Anders Carlsson9b399792009-02-08 01:23:05 +0000611 // Add it as the destination.
Anders Carlsson8be63402009-02-08 22:46:50 +0000612 SI->addCase(ID, CleanupPad);
Anders Carlsson9b399792009-02-08 01:23:05 +0000613
614 // Create the branch to the final destination.
615 llvm::BranchInst *BI = llvm::BranchInst::Create(Dest);
616 CleanupPad->getInstList().push_back(BI);
617
618 // And add it as a branch fixup.
619 CleanupEntries.back().BranchFixups.push_back(BI);
620 }
621 }
622 }
Anders Carlssone75ae4d2009-02-08 03:55:35 +0000623
Anders Carlssone7de3522009-02-08 00:16:35 +0000624 // Remove all blocks from the block scope map.
625 for (size_t i = 0, e = Blocks.size(); i != e; ++i) {
626 assert(BlockScopes.count(Blocks[i]) &&
627 "Did not find block in scope map!");
628
629 BlockScopes.erase(Blocks[i]);
630 }
Anders Carlssone75ae4d2009-02-08 03:55:35 +0000631
Anders Carlssondf274192009-02-08 07:46:24 +0000632 return CleanupBlockInfo(CleanupBlock, SwitchBlock, EndBlock);
Anders Carlssone75ae4d2009-02-08 03:55:35 +0000633}
634
635void CodeGenFunction::EmitCleanupBlock()
636{
Anders Carlssondf274192009-02-08 07:46:24 +0000637 CleanupBlockInfo Info = PopCleanupBlock();
Anders Carlssone75ae4d2009-02-08 03:55:35 +0000638
Anders Carlssondf274192009-02-08 07:46:24 +0000639 EmitBlock(Info.CleanupBlock);
Anders Carlssone75ae4d2009-02-08 03:55:35 +0000640
Anders Carlssondf274192009-02-08 07:46:24 +0000641 if (Info.SwitchBlock)
642 EmitBlock(Info.SwitchBlock);
643 if (Info.EndBlock)
644 EmitBlock(Info.EndBlock);
Anders Carlssone75ae4d2009-02-08 03:55:35 +0000645}
646
Anders Carlssoned536bc2009-02-08 00:50:42 +0000647void CodeGenFunction::AddBranchFixup(llvm::BranchInst *BI)
648{
649 assert(!CleanupEntries.empty() &&
650 "Trying to add branch fixup without cleanup block!");
651
652 // FIXME: We could be more clever here and check if there's already a
653 // branch fixup for this destination and recycle it.
654 CleanupEntries.back().BranchFixups.push_back(BI);
655}
656
657void CodeGenFunction::EmitBranchThroughCleanup(llvm::BasicBlock *Dest)
658{
Anders Carlsson32fffb72009-02-08 22:13:37 +0000659 if (!HaveInsertPoint())
660 return;
661
Anders Carlssoned536bc2009-02-08 00:50:42 +0000662 llvm::BranchInst* BI = Builder.CreateBr(Dest);
663
Anders Carlsson32fffb72009-02-08 22:13:37 +0000664 Builder.ClearInsertionPoint();
665
Anders Carlssoned536bc2009-02-08 00:50:42 +0000666 // The stack is empty, no need to do any cleanup.
667 if (CleanupEntries.empty())
668 return;
669
670 if (!Dest->getParent()) {
671 // We are trying to branch to a block that hasn't been inserted yet.
672 AddBranchFixup(BI);
673 return;
674 }
675
676 BlockScopeMap::iterator I = BlockScopes.find(Dest);
677 if (I == BlockScopes.end()) {
678 // We are trying to jump to a block that is outside of any cleanup scope.
679 AddBranchFixup(BI);
680 return;
681 }
682
683 assert(I->second < CleanupEntries.size() &&
684 "Trying to branch into cleanup region");
685
686 if (I->second == CleanupEntries.size() - 1) {
687 // We have a branch to a block in the same scope.
688 return;
689 }
690
691 AddBranchFixup(BI);
692}