blob: 04661fca471c96cb462aa6c0417bc9822a5bc6b6 [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"
Anders Carlsson2b77ba82009-04-04 20:47:02 +000021#include "clang/AST/DeclCXX.h"
Devang Pateld9363c32007-09-28 21:49:18 +000022#include "llvm/Support/CFG.h"
Mike Stump4e7a1f72009-02-21 20:00:35 +000023#include "llvm/Target/TargetData.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000024using namespace clang;
25using namespace CodeGen;
26
27CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
Mike Stumpa4f668f2009-03-06 01:33:24 +000028 : BlockFunction(cgm, *this, Builder), CGM(cgm),
29 Target(CGM.getContext().Target),
Anders Carlsson2b77ba82009-04-04 20:47:02 +000030 DebugInfo(0), SwitchInsn(0), CaseRangeBlock(0), InvokeDest(0),
31 CXXThisDecl(0) {
Mike Stump4e7a1f72009-02-21 20:00:35 +000032 LLVMIntTy = ConvertType(getContext().IntTy);
33 LLVMPointerWidth = Target.getPointerWidth(0);
Chris Lattner41110242008-06-17 18:05:57 +000034}
Reid Spencer5f016e22007-07-11 17:01:13 +000035
36ASTContext &CodeGenFunction::getContext() const {
37 return CGM.getContext();
38}
39
40
41llvm::BasicBlock *CodeGenFunction::getBasicBlockForLabel(const LabelStmt *S) {
42 llvm::BasicBlock *&BB = LabelMap[S];
43 if (BB) return BB;
44
45 // Create, but don't insert, the new block.
Daniel Dunbar55e87422008-11-11 02:29:29 +000046 return BB = createBasicBlock(S->getName());
Reid Spencer5f016e22007-07-11 17:01:13 +000047}
48
Daniel Dunbar0096acf2009-02-25 19:24:29 +000049llvm::Value *CodeGenFunction::GetAddrOfLocalVar(const VarDecl *VD) {
50 llvm::Value *Res = LocalDeclMap[VD];
51 assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!");
52 return Res;
Lauro Ramos Venancio81373352008-02-26 21:41:45 +000053}
Reid Spencer5f016e22007-07-11 17:01:13 +000054
Daniel Dunbar0096acf2009-02-25 19:24:29 +000055llvm::Constant *
56CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) {
57 return cast<llvm::Constant>(GetAddrOfLocalVar(BVD));
Anders Carlssondde0a942008-09-11 09:15:33 +000058}
59
Daniel Dunbar8b1a3432009-02-03 23:03:55 +000060const llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
61 return CGM.getTypes().ConvertTypeForMem(T);
62}
63
Reid Spencer5f016e22007-07-11 17:01:13 +000064const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
65 return CGM.getTypes().ConvertType(T);
66}
67
68bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
Mike Stumpf5408fe2009-05-16 07:57:57 +000069 // FIXME: Use positive checks instead of negative ones to be more robust in
70 // the face of extension.
Daniel Dunbar89588912009-02-26 20:52:22 +000071 return !T->hasPointerRepresentation() &&!T->isRealType() &&
72 !T->isVoidType() && !T->isVectorType() && !T->isFunctionType() &&
Daniel Dunbara782ca72009-01-09 02:44:18 +000073 !T->isBlockPointerType();
Reid Spencer5f016e22007-07-11 17:01:13 +000074}
75
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000076void CodeGenFunction::EmitReturnBlock() {
77 // For cleanliness, we try to avoid emitting the return block for
78 // simple cases.
79 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
80
81 if (CurBB) {
82 assert(!CurBB->getTerminator() && "Unexpected terminated block.");
83
84 // We have a valid insert point, reuse it if there are no explicit
85 // jumps to the return block.
86 if (ReturnBlock->use_empty())
87 delete ReturnBlock;
88 else
89 EmitBlock(ReturnBlock);
90 return;
91 }
92
93 // Otherwise, if the return block is the target of a single direct
94 // branch then we can just put the code in that block instead. This
95 // cleans up functions which started with a unified return block.
96 if (ReturnBlock->hasOneUse()) {
97 llvm::BranchInst *BI =
98 dyn_cast<llvm::BranchInst>(*ReturnBlock->use_begin());
99 if (BI && BI->isUnconditional() && BI->getSuccessor(0) == ReturnBlock) {
100 // Reset insertion point and delete the branch.
101 Builder.SetInsertPoint(BI->getParent());
102 BI->eraseFromParent();
103 delete ReturnBlock;
104 return;
105 }
106 }
107
Mike Stumpf5408fe2009-05-16 07:57:57 +0000108 // FIXME: We are at an unreachable point, there is no reason to emit the block
109 // unless it has uses. However, we still need a place to put the debug
110 // region.end for now.
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000111
112 EmitBlock(ReturnBlock);
113}
114
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000115void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000116 // Finish emission of indirect switches.
117 EmitIndirectSwitches();
118
Chris Lattnerda138702007-07-16 21:28:45 +0000119 assert(BreakContinueStack.empty() &&
120 "mismatched push/pop in break/continue stack!");
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000121 assert(BlockScopes.empty() &&
122 "did not remove all blocks from block scope map!");
123 assert(CleanupEntries.empty() &&
124 "mismatched push/pop in cleanup stack!");
125
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000126 // Emit function epilog (to return).
127 EmitReturnBlock();
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000128
129 // Emit debug descriptor for function end.
Anders Carlssone896d982009-02-13 08:11:52 +0000130 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000131 DI->setLocation(EndLoc);
132 DI->EmitRegionEnd(CurFn, Builder);
133 }
134
Daniel Dunbar88b53962009-02-02 22:03:45 +0000135 EmitFunctionEpilog(*CurFnInfo, ReturnValue);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000136
Chris Lattner5a2fa142007-12-02 06:32:24 +0000137 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
Chris Lattner481769b2009-03-31 22:17:44 +0000138 llvm::Instruction *Ptr = AllocaInsertPt;
Chris Lattner5a2fa142007-12-02 06:32:24 +0000139 AllocaInsertPt = 0;
Chris Lattner481769b2009-03-31 22:17:44 +0000140 Ptr->eraseFromParent();
Reid Spencer5f016e22007-07-11 17:01:13 +0000141}
142
Daniel Dunbar7c086512008-09-09 23:14:03 +0000143void CodeGenFunction::StartFunction(const Decl *D, QualType RetTy,
144 llvm::Function *Fn,
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000145 const FunctionArgList &Args,
146 SourceLocation StartLoc) {
Anders Carlsson4cc1a472009-02-09 20:20:56 +0000147 DidCallStackSave = false;
Chris Lattnerb5437d22009-04-23 05:30:27 +0000148 CurCodeDecl = CurFuncDecl = D;
Daniel Dunbar7c086512008-09-09 23:14:03 +0000149 FnRetTy = RetTy;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000150 CurFn = Fn;
Chris Lattner41110242008-06-17 18:05:57 +0000151 assert(CurFn->isDeclaration() && "Function already has body?");
152
Daniel Dunbar55e87422008-11-11 02:29:29 +0000153 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000154
Chris Lattner41110242008-06-17 18:05:57 +0000155 // Create a marker to make it easy to insert allocas into the entryblock
156 // later. Don't create this with the builder, because we don't want it
157 // folded.
158 llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::Int32Ty);
Chris Lattnerf1466842009-03-22 00:24:14 +0000159 AllocaInsertPt = new llvm::BitCastInst(Undef, llvm::Type::Int32Ty, "",
Chris Lattner41110242008-06-17 18:05:57 +0000160 EntryBB);
Chris Lattnerf1466842009-03-22 00:24:14 +0000161 if (Builder.isNamePreserving())
162 AllocaInsertPt->setName("allocapt");
163
Daniel Dunbar55e87422008-11-11 02:29:29 +0000164 ReturnBlock = createBasicBlock("return");
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000165 ReturnValue = 0;
Daniel Dunbar7c086512008-09-09 23:14:03 +0000166 if (!RetTy->isVoidType())
167 ReturnValue = CreateTempAlloca(ConvertType(RetTy), "retval");
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000168
Chris Lattner41110242008-06-17 18:05:57 +0000169 Builder.SetInsertPoint(EntryBB);
170
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000171 // Emit subprogram debug descriptor.
Daniel Dunbar7c086512008-09-09 23:14:03 +0000172 // FIXME: The cast here is a huge hack.
Anders Carlssone896d982009-02-13 08:11:52 +0000173 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000174 DI->setLocation(StartLoc);
175 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor6ec36682009-02-18 23:53:56 +0000176 DI->EmitFunctionStart(CGM.getMangledName(FD), RetTy, CurFn, Builder);
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000177 } else {
178 // Just use LLVM function name.
179 DI->EmitFunctionStart(Fn->getName().c_str(),
180 RetTy, CurFn, Builder);
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000181 }
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000182 }
183
Daniel Dunbar88b53962009-02-02 22:03:45 +0000184 // FIXME: Leaked.
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000185 CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args);
Daniel Dunbar88b53962009-02-02 22:03:45 +0000186 EmitFunctionProlog(*CurFnInfo, CurFn, Args);
Anders Carlsson751358f2008-12-20 21:28:43 +0000187
188 // If any of the arguments have a variably modified type, make sure to
189 // emit the type size.
190 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
191 i != e; ++i) {
192 QualType Ty = i->second;
193
194 if (Ty->isVariablyModifiedType())
195 EmitVLASize(Ty);
196 }
Daniel Dunbar7c086512008-09-09 23:14:03 +0000197}
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000198
Daniel Dunbar7c086512008-09-09 23:14:03 +0000199void CodeGenFunction::GenerateCode(const FunctionDecl *FD,
200 llvm::Function *Fn) {
Anders Carlssone896d982009-02-13 08:11:52 +0000201 // Check if we should generate debug info for this function.
Daniel Dunbarb11fa0d2009-04-13 21:08:27 +0000202 if (CGM.getDebugInfo() && !FD->hasAttr<NodebugAttr>())
Anders Carlssone896d982009-02-13 08:11:52 +0000203 DebugInfo = CGM.getDebugInfo();
204
Daniel Dunbar7c086512008-09-09 23:14:03 +0000205 FunctionArgList Args;
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000206
207 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
208 if (MD->isInstance()) {
209 // Create the implicit 'this' decl.
210 // FIXME: I'm not entirely sure I like using a fake decl just for code
211 // generation. Maybe we can come up with a better way?
212 CXXThisDecl = ImplicitParamDecl::Create(getContext(), 0, SourceLocation(),
213 &getContext().Idents.get("this"),
214 MD->getThisType(getContext()));
215 Args.push_back(std::make_pair(CXXThisDecl, CXXThisDecl->getType()));
216 }
217 }
218
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000219 if (FD->getNumParams()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000220 const FunctionProtoType* FProto = FD->getType()->getAsFunctionProtoType();
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000221 assert(FProto && "Function def must have prototype!");
Daniel Dunbar7c086512008-09-09 23:14:03 +0000222
223 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
224 Args.push_back(std::make_pair(FD->getParamDecl(i),
225 FProto->getArgType(i)));
Chris Lattner41110242008-06-17 18:05:57 +0000226 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000227
Sebastian Redld3a413d2009-04-26 20:35:05 +0000228 // FIXME: Support CXXTryStmt here, too.
229 if (const CompoundStmt *S = FD->getCompoundBody(getContext())) {
230 StartFunction(FD, FD->getResultType(), Fn, Args, S->getLBracLoc());
231 EmitStmt(S);
232 FinishFunction(S->getRBracLoc());
233 }
Daniel Dunbar7c086512008-09-09 23:14:03 +0000234
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000235 // Destroy the 'this' declaration.
236 if (CXXThisDecl)
237 CXXThisDecl->Destroy(getContext());
Chris Lattner41110242008-06-17 18:05:57 +0000238}
239
Chris Lattner0946ccd2008-11-11 07:41:27 +0000240/// ContainsLabel - Return true if the statement contains a label in it. If
241/// this statement is not executed normally, it not containing a label means
242/// that we can just remove the code.
243bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
244 // Null statement, not a label!
245 if (S == 0) return false;
246
247 // If this is a label, we have to emit the code, consider something like:
248 // if (0) { ... foo: bar(); } goto foo;
249 if (isa<LabelStmt>(S))
250 return true;
251
252 // If this is a case/default statement, and we haven't seen a switch, we have
253 // to emit the code.
254 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
255 return true;
256
257 // If this is a switch statement, we want to ignore cases below it.
258 if (isa<SwitchStmt>(S))
259 IgnoreCaseStmts = true;
260
261 // Scan subexpressions for verboten labels.
262 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
263 I != E; ++I)
264 if (ContainsLabel(*I, IgnoreCaseStmts))
265 return true;
266
267 return false;
268}
269
Chris Lattner31a09842008-11-12 08:04:58 +0000270
271/// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
272/// a constant, or if it does but contains a label, return 0. If it constant
273/// folds to 'true' and does not contain a label, return 1, if it constant folds
274/// to 'false' and does not contain a label, return -1.
275int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
Daniel Dunbar36bc14c2008-11-12 22:37:10 +0000276 // FIXME: Rename and handle conversion of other evaluatable things
277 // to bool.
Anders Carlsson64712f12008-12-01 02:46:24 +0000278 Expr::EvalResult Result;
279 if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
280 Result.HasSideEffects)
Anders Carlssonef5a66d2008-11-22 22:32:07 +0000281 return 0; // Not foldable, not integer or not fully evaluatable.
Chris Lattner31a09842008-11-12 08:04:58 +0000282
283 if (CodeGenFunction::ContainsLabel(Cond))
284 return 0; // Contains a label.
285
Anders Carlsson64712f12008-12-01 02:46:24 +0000286 return Result.Val.getInt().getBoolValue() ? 1 : -1;
Chris Lattner31a09842008-11-12 08:04:58 +0000287}
288
289
290/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
291/// statement) to the specified blocks. Based on the condition, this might try
292/// to simplify the codegen of the conditional based on the branch.
293///
294void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
295 llvm::BasicBlock *TrueBlock,
296 llvm::BasicBlock *FalseBlock) {
297 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
298 return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
299
300 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
301 // Handle X && Y in a condition.
302 if (CondBOp->getOpcode() == BinaryOperator::LAnd) {
303 // If we have "1 && X", simplify the code. "0 && X" would have constant
304 // folded if the case was simple enough.
305 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
306 // br(1 && X) -> br(X).
307 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
308 }
309
310 // If we have "X && 1", simplify the code to use an uncond branch.
311 // "X && 0" would have been constant folded to 0.
312 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
313 // br(X && 1) -> br(X).
314 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
315 }
316
317 // Emit the LHS as a conditional. If the LHS conditional is false, we
318 // want to jump to the FalseBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000319 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
Chris Lattner31a09842008-11-12 08:04:58 +0000320 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
321 EmitBlock(LHSTrue);
322
323 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
324 return;
325 } else if (CondBOp->getOpcode() == BinaryOperator::LOr) {
326 // If we have "0 || X", simplify the code. "1 || X" would have constant
327 // folded if the case was simple enough.
328 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
329 // br(0 || X) -> br(X).
330 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
331 }
332
333 // If we have "X || 0", simplify the code to use an uncond branch.
334 // "X || 1" would have been constant folded to 1.
335 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
336 // br(X || 0) -> br(X).
337 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
338 }
339
340 // Emit the LHS as a conditional. If the LHS conditional is true, we
341 // want to jump to the TrueBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000342 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
Chris Lattner31a09842008-11-12 08:04:58 +0000343 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
344 EmitBlock(LHSFalse);
345
346 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
347 return;
348 }
Chris Lattner552f4c42008-11-12 08:13:36 +0000349 }
350
351 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
352 // br(!x, t, f) -> br(x, f, t)
353 if (CondUOp->getOpcode() == UnaryOperator::LNot)
354 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
Chris Lattner31a09842008-11-12 08:04:58 +0000355 }
356
Daniel Dunbar09b14892008-11-12 10:30:32 +0000357 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
358 // Handle ?: operator.
359
360 // Just ignore GNU ?: extension.
361 if (CondOp->getLHS()) {
362 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
363 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
364 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
365 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
366 EmitBlock(LHSBlock);
367 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
368 EmitBlock(RHSBlock);
369 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
370 return;
371 }
372 }
373
Chris Lattner31a09842008-11-12 08:04:58 +0000374 // Emit the code with the fully general case.
375 llvm::Value *CondV = EvaluateExprAsBool(Cond);
376 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
377}
378
Devang Patel88a981b2007-11-01 19:11:01 +0000379/// getCGRecordLayout - Return record layout info.
380const CGRecordLayout *CodeGenFunction::getCGRecordLayout(CodeGenTypes &CGT,
Chris Lattneraf319132008-02-05 06:55:31 +0000381 QualType Ty) {
382 const RecordType *RTy = Ty->getAsRecordType();
383 assert (RTy && "Unexpected type. RecordType expected here.");
Devang Patelb84a06e2007-10-23 02:10:49 +0000384
Chris Lattneraf319132008-02-05 06:55:31 +0000385 return CGT.getCGRecordLayout(RTy->getDecl());
Devang Patelb84a06e2007-10-23 02:10:49 +0000386}
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000387
Daniel Dunbar488e9932008-08-16 00:56:44 +0000388/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000389/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000390void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
391 bool OmitOnError) {
392 CGM.ErrorUnsupported(S, Type, OmitOnError);
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000393}
394
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000395unsigned CodeGenFunction::GetIDForAddrOfLabel(const LabelStmt *L) {
396 // Use LabelIDs.size() as the new ID if one hasn't been assigned.
397 return LabelIDs.insert(std::make_pair(L, LabelIDs.size())).first->second;
398}
399
Chris Lattner88207c92009-04-21 17:59:23 +0000400void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty) {
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000401 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
Chris Lattner88207c92009-04-21 17:59:23 +0000408 // Don't bother emitting a zero-byte memset.
409 if (TypeInfo.first == 0)
410 return;
411
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000412 // FIXME: Handle variable sized types.
413 const llvm::Type *IntPtr = llvm::IntegerType::get(LLVMPointerWidth);
414
415 Builder.CreateCall4(CGM.getMemSetFn(), DestPtr,
416 llvm::ConstantInt::getNullValue(llvm::Type::Int8Ty),
417 // TypeInfo.first describes size in bits.
418 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
419 llvm::ConstantInt::get(llvm::Type::Int32Ty,
420 TypeInfo.second/8));
421}
422
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000423void CodeGenFunction::EmitIndirectSwitches() {
424 llvm::BasicBlock *Default;
425
Daniel Dunbar76526a52008-08-04 17:24:44 +0000426 if (IndirectSwitches.empty())
427 return;
428
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000429 if (!LabelIDs.empty()) {
430 Default = getBasicBlockForLabel(LabelIDs.begin()->first);
431 } else {
432 // No possible targets for indirect goto, just emit an infinite
433 // loop.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000434 Default = createBasicBlock("indirectgoto.loop", CurFn);
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000435 llvm::BranchInst::Create(Default, Default);
436 }
437
438 for (std::vector<llvm::SwitchInst*>::iterator i = IndirectSwitches.begin(),
439 e = IndirectSwitches.end(); i != e; ++i) {
440 llvm::SwitchInst *I = *i;
441
442 I->setSuccessor(0, Default);
443 for (std::map<const LabelStmt*,unsigned>::iterator LI = LabelIDs.begin(),
444 LE = LabelIDs.end(); LI != LE; ++LI) {
445 I->addCase(llvm::ConstantInt::get(llvm::Type::Int32Ty,
446 LI->second),
447 getBasicBlockForLabel(LI->first));
448 }
449 }
450}
Anders Carlssonddf7cac2008-11-04 05:30:00 +0000451
Anders Carlssondcc90d82008-12-12 07:19:02 +0000452llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT)
453{
454 llvm::Value *&SizeEntry = VLASizeMap[VAT];
Anders Carlssondcc90d82008-12-12 07:19:02 +0000455
Anders Carlssonf666b772008-12-20 20:27:15 +0000456 assert(SizeEntry && "Did not emit size for type");
457 return SizeEntry;
458}
Anders Carlssondcc90d82008-12-12 07:19:02 +0000459
Anders Carlsson60d35412008-12-20 20:46:34 +0000460llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty)
Anders Carlssonf666b772008-12-20 20:27:15 +0000461{
Anders Carlsson60d35412008-12-20 20:46:34 +0000462 assert(Ty->isVariablyModifiedType() &&
463 "Must pass variably modified type to EmitVLASizes!");
Anders Carlssonf666b772008-12-20 20:27:15 +0000464
Anders Carlsson60d35412008-12-20 20:46:34 +0000465 if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
466 llvm::Value *&SizeEntry = VLASizeMap[VAT];
467
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000468 if (!SizeEntry) {
469 // Get the element size;
470 llvm::Value *ElemSize;
Anders Carlsson60d35412008-12-20 20:46:34 +0000471
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000472 QualType ElemTy = VAT->getElementType();
Anders Carlsson96f21472009-02-05 19:43:10 +0000473
474 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
475
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000476 if (ElemTy->isVariableArrayType())
477 ElemSize = EmitVLASize(ElemTy);
478 else {
Anders Carlsson96f21472009-02-05 19:43:10 +0000479 ElemSize = llvm::ConstantInt::get(SizeTy,
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000480 getContext().getTypeSize(ElemTy) / 8);
481 }
Anders Carlsson60d35412008-12-20 20:46:34 +0000482
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000483 llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
Anders Carlsson96f21472009-02-05 19:43:10 +0000484 NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
485
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000486 SizeEntry = Builder.CreateMul(ElemSize, NumElements);
Anders Carlsson60d35412008-12-20 20:46:34 +0000487 }
488
Anders Carlsson60d35412008-12-20 20:46:34 +0000489 return SizeEntry;
490 } else if (const PointerType *PT = Ty->getAsPointerType())
491 EmitVLASize(PT->getPointeeType());
Anders Carlssonf666b772008-12-20 20:27:15 +0000492 else {
Anders Carlsson60d35412008-12-20 20:46:34 +0000493 assert(0 && "unknown VM type!");
Anders Carlssondcc90d82008-12-12 07:19:02 +0000494 }
Anders Carlsson60d35412008-12-20 20:46:34 +0000495
496 return 0;
Anders Carlssondcc90d82008-12-12 07:19:02 +0000497}
Eli Friedman4fd0aa52009-01-20 17:46:04 +0000498
499llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
500 if (CGM.getContext().getBuiltinVaListType()->isArrayType()) {
501 return EmitScalarExpr(E);
502 }
503 return EmitLValue(E).getAddress();
504}
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000505
Anders Carlsson6fc55912009-02-08 03:22:36 +0000506void CodeGenFunction::PushCleanupBlock(llvm::BasicBlock *CleanupBlock)
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000507{
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000508 CleanupEntries.push_back(CleanupEntry(CleanupBlock));
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000509}
Anders Carlssonc71c8452009-02-07 23:50:39 +0000510
511void CodeGenFunction::EmitCleanupBlocks(size_t OldCleanupStackSize)
512{
513 assert(CleanupEntries.size() >= OldCleanupStackSize &&
514 "Cleanup stack mismatch!");
515
516 while (CleanupEntries.size() > OldCleanupStackSize)
517 EmitCleanupBlock();
518}
519
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000520CodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock()
Anders Carlssonc71c8452009-02-07 23:50:39 +0000521{
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000522 CleanupEntry &CE = CleanupEntries.back();
523
524 llvm::BasicBlock *CleanupBlock = CE.CleanupBlock;
525
526 std::vector<llvm::BasicBlock *> Blocks;
527 std::swap(Blocks, CE.Blocks);
528
529 std::vector<llvm::BranchInst *> BranchFixups;
530 std::swap(BranchFixups, CE.BranchFixups);
531
532 CleanupEntries.pop_back();
533
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000534 // Check if any branch fixups pointed to the scope we just popped. If so,
535 // we can remove them.
536 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
537 llvm::BasicBlock *Dest = BranchFixups[i]->getSuccessor(0);
538 BlockScopeMap::iterator I = BlockScopes.find(Dest);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000539
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000540 if (I == BlockScopes.end())
541 continue;
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000542
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000543 assert(I->second <= CleanupEntries.size() && "Invalid branch fixup!");
Anders Carlssond66a9f92009-02-08 03:55:35 +0000544
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000545 if (I->second == CleanupEntries.size()) {
546 // We don't need to do this branch fixup.
547 BranchFixups[i] = BranchFixups.back();
548 BranchFixups.pop_back();
549 i--;
550 e--;
551 continue;
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000552 }
553 }
Anders Carlssond66a9f92009-02-08 03:55:35 +0000554
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000555 llvm::BasicBlock *SwitchBlock = 0;
556 llvm::BasicBlock *EndBlock = 0;
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000557 if (!BranchFixups.empty()) {
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000558 SwitchBlock = createBasicBlock("cleanup.switch");
559 EndBlock = createBasicBlock("cleanup.end");
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000560
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000561 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
Anders Carlsson0ae7b2b2009-03-17 05:53:35 +0000562
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000563 Builder.SetInsertPoint(SwitchBlock);
564
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000565 llvm::Value *DestCodePtr = CreateTempAlloca(llvm::Type::Int32Ty,
566 "cleanup.dst");
567 llvm::Value *DestCode = Builder.CreateLoad(DestCodePtr, "tmp");
568
569 // Create a switch instruction to determine where to jump next.
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000570 llvm::SwitchInst *SI = Builder.CreateSwitch(DestCode, EndBlock,
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000571 BranchFixups.size());
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000572
Anders Carlsson46831a92009-02-08 22:13:37 +0000573 // Restore the current basic block (if any)
Anders Carlsson0ae7b2b2009-03-17 05:53:35 +0000574 if (CurBB) {
Anders Carlsson46831a92009-02-08 22:13:37 +0000575 Builder.SetInsertPoint(CurBB);
Anders Carlsson0ae7b2b2009-03-17 05:53:35 +0000576
577 // If we had a current basic block, we also need to emit an instruction
578 // to initialize the cleanup destination.
579 Builder.CreateStore(llvm::Constant::getNullValue(llvm::Type::Int32Ty),
580 DestCodePtr);
581 } else
Anders Carlsson46831a92009-02-08 22:13:37 +0000582 Builder.ClearInsertionPoint();
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000583
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000584 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
585 llvm::BranchInst *BI = BranchFixups[i];
586 llvm::BasicBlock *Dest = BI->getSuccessor(0);
587
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000588 // Fixup the branch instruction to point to the cleanup block.
589 BI->setSuccessor(0, CleanupBlock);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000590
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000591 if (CleanupEntries.empty()) {
Anders Carlssoncc899202009-02-08 22:46:50 +0000592 llvm::ConstantInt *ID;
593
594 // Check if we already have a destination for this block.
595 if (Dest == SI->getDefaultDest())
596 ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
597 else {
598 ID = SI->findCaseDest(Dest);
599 if (!ID) {
600 // No code found, get a new unique one by using the number of
601 // switch successors.
602 ID = llvm::ConstantInt::get(llvm::Type::Int32Ty,
603 SI->getNumSuccessors());
604 SI->addCase(ID, Dest);
605 }
606 }
607
608 // Store the jump destination before the branch instruction.
609 new llvm::StoreInst(ID, DestCodePtr, BI);
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000610 } else {
611 // We need to jump through another cleanup block. Create a pad block
612 // with a branch instruction that jumps to the final destination and
613 // add it as a branch fixup to the current cleanup scope.
614
615 // Create the pad block.
616 llvm::BasicBlock *CleanupPad = createBasicBlock("cleanup.pad", CurFn);
Anders Carlssoncc899202009-02-08 22:46:50 +0000617
618 // Create a unique case ID.
619 llvm::ConstantInt *ID = llvm::ConstantInt::get(llvm::Type::Int32Ty,
620 SI->getNumSuccessors());
621
622 // Store the jump destination before the branch instruction.
623 new llvm::StoreInst(ID, DestCodePtr, BI);
624
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000625 // Add it as the destination.
Anders Carlssoncc899202009-02-08 22:46:50 +0000626 SI->addCase(ID, CleanupPad);
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000627
628 // Create the branch to the final destination.
629 llvm::BranchInst *BI = llvm::BranchInst::Create(Dest);
630 CleanupPad->getInstList().push_back(BI);
631
632 // And add it as a branch fixup.
633 CleanupEntries.back().BranchFixups.push_back(BI);
634 }
635 }
636 }
Anders Carlssond66a9f92009-02-08 03:55:35 +0000637
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000638 // Remove all blocks from the block scope map.
639 for (size_t i = 0, e = Blocks.size(); i != e; ++i) {
640 assert(BlockScopes.count(Blocks[i]) &&
641 "Did not find block in scope map!");
642
643 BlockScopes.erase(Blocks[i]);
644 }
Anders Carlssond66a9f92009-02-08 03:55:35 +0000645
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000646 return CleanupBlockInfo(CleanupBlock, SwitchBlock, EndBlock);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000647}
648
649void CodeGenFunction::EmitCleanupBlock()
650{
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000651 CleanupBlockInfo Info = PopCleanupBlock();
Anders Carlssond66a9f92009-02-08 03:55:35 +0000652
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000653 EmitBlock(Info.CleanupBlock);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000654
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000655 if (Info.SwitchBlock)
656 EmitBlock(Info.SwitchBlock);
657 if (Info.EndBlock)
658 EmitBlock(Info.EndBlock);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000659}
660
Anders Carlsson87eaf172009-02-08 00:50:42 +0000661void CodeGenFunction::AddBranchFixup(llvm::BranchInst *BI)
662{
663 assert(!CleanupEntries.empty() &&
664 "Trying to add branch fixup without cleanup block!");
665
Mike Stumpf5408fe2009-05-16 07:57:57 +0000666 // FIXME: We could be more clever here and check if there's already a branch
667 // fixup for this destination and recycle it.
Anders Carlsson87eaf172009-02-08 00:50:42 +0000668 CleanupEntries.back().BranchFixups.push_back(BI);
669}
670
671void CodeGenFunction::EmitBranchThroughCleanup(llvm::BasicBlock *Dest)
672{
Anders Carlsson46831a92009-02-08 22:13:37 +0000673 if (!HaveInsertPoint())
674 return;
675
Anders Carlsson87eaf172009-02-08 00:50:42 +0000676 llvm::BranchInst* BI = Builder.CreateBr(Dest);
677
Anders Carlsson46831a92009-02-08 22:13:37 +0000678 Builder.ClearInsertionPoint();
679
Anders Carlsson87eaf172009-02-08 00:50:42 +0000680 // The stack is empty, no need to do any cleanup.
681 if (CleanupEntries.empty())
682 return;
683
684 if (!Dest->getParent()) {
685 // We are trying to branch to a block that hasn't been inserted yet.
686 AddBranchFixup(BI);
687 return;
688 }
689
690 BlockScopeMap::iterator I = BlockScopes.find(Dest);
691 if (I == BlockScopes.end()) {
692 // We are trying to jump to a block that is outside of any cleanup scope.
693 AddBranchFixup(BI);
694 return;
695 }
696
697 assert(I->second < CleanupEntries.size() &&
698 "Trying to branch into cleanup region");
699
700 if (I->second == CleanupEntries.size() - 1) {
701 // We have a branch to a block in the same scope.
702 return;
703 }
704
705 AddBranchFixup(BI);
706}