blob: 4ba4d600f864693a3659845641f3364648640820 [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"
Reid Spencer5f016e22007-07-11 17:01:13 +000022using namespace clang;
23using namespace CodeGen;
24
25CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
Devang Patelc049e4f2007-10-08 20:57:48 +000026 : CGM(cgm), Target(CGM.getContext().Target), SwitchInsn(NULL),
Mike Stump36a2ada2009-02-07 12:52:26 +000027 CaseRangeBlock(NULL), StackDepth(0) {
Chris Lattner41110242008-06-17 18:05:57 +000028 LLVMIntTy = ConvertType(getContext().IntTy);
29 LLVMPointerWidth = Target.getPointerWidth(0);
30}
Reid Spencer5f016e22007-07-11 17:01:13 +000031
32ASTContext &CodeGenFunction::getContext() const {
33 return CGM.getContext();
34}
35
36
37llvm::BasicBlock *CodeGenFunction::getBasicBlockForLabel(const LabelStmt *S) {
38 llvm::BasicBlock *&BB = LabelMap[S];
39 if (BB) return BB;
40
41 // Create, but don't insert, the new block.
Daniel Dunbar55e87422008-11-11 02:29:29 +000042 return BB = createBasicBlock(S->getName());
Reid Spencer5f016e22007-07-11 17:01:13 +000043}
44
Lauro Ramos Venancio81373352008-02-26 21:41:45 +000045llvm::Constant *
Steve Naroff248a7532008-04-15 22:42:06 +000046CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) {
Lauro Ramos Venancio81373352008-02-26 21:41:45 +000047 return cast<llvm::Constant>(LocalDeclMap[BVD]);
48}
Reid Spencer5f016e22007-07-11 17:01:13 +000049
Anders Carlssondde0a942008-09-11 09:15:33 +000050llvm::Value *CodeGenFunction::GetAddrOfLocalVar(const VarDecl *VD)
51{
52 return LocalDeclMap[VD];
53}
54
Daniel Dunbar8b1a3432009-02-03 23:03:55 +000055const llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
56 return CGM.getTypes().ConvertTypeForMem(T);
57}
58
Reid Spencer5f016e22007-07-11 17:01:13 +000059const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
60 return CGM.getTypes().ConvertType(T);
61}
62
Chris Lattner41110242008-06-17 18:05:57 +000063bool CodeGenFunction::isObjCPointerType(QualType T) {
64 // All Objective-C types are pointers.
65 return T->isObjCInterfaceType() ||
66 T->isObjCQualifiedInterfaceType() || T->isObjCQualifiedIdType();
67}
68
Reid Spencer5f016e22007-07-11 17:01:13 +000069bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
Daniel Dunbara782ca72009-01-09 02:44:18 +000070 // FIXME: Use positive checks instead of negative ones to be more
71 // robust in the face of extension.
Chris Lattner41110242008-06-17 18:05:57 +000072 return !isObjCPointerType(T) &&!T->isRealType() && !T->isPointerLikeType() &&
Daniel Dunbara782ca72009-01-09 02:44:18 +000073 !T->isVoidType() && !T->isVectorType() && !T->isFunctionType() &&
74 !T->isBlockPointerType();
Reid Spencer5f016e22007-07-11 17:01:13 +000075}
76
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000077void CodeGenFunction::EmitReturnBlock() {
78 // For cleanliness, we try to avoid emitting the return block for
79 // simple cases.
80 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
81
82 if (CurBB) {
83 assert(!CurBB->getTerminator() && "Unexpected terminated block.");
84
85 // We have a valid insert point, reuse it if there are no explicit
86 // jumps to the return block.
87 if (ReturnBlock->use_empty())
88 delete ReturnBlock;
89 else
90 EmitBlock(ReturnBlock);
91 return;
92 }
93
94 // Otherwise, if the return block is the target of a single direct
95 // branch then we can just put the code in that block instead. This
96 // cleans up functions which started with a unified return block.
97 if (ReturnBlock->hasOneUse()) {
98 llvm::BranchInst *BI =
99 dyn_cast<llvm::BranchInst>(*ReturnBlock->use_begin());
100 if (BI && BI->isUnconditional() && BI->getSuccessor(0) == ReturnBlock) {
101 // Reset insertion point and delete the branch.
102 Builder.SetInsertPoint(BI->getParent());
103 BI->eraseFromParent();
104 delete ReturnBlock;
105 return;
106 }
107 }
108
109 // FIXME: We are at an unreachable point, there is no reason to emit
110 // the block unless it has uses. However, we still need a place to
111 // put the debug region.end for now.
112
113 EmitBlock(ReturnBlock);
114}
115
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000116void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000117 // Finish emission of indirect switches.
118 EmitIndirectSwitches();
119
Chris Lattnerda138702007-07-16 21:28:45 +0000120 assert(BreakContinueStack.empty() &&
121 "mismatched push/pop in break/continue stack!");
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000122
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000123 // Emit function epilog (to return).
124 EmitReturnBlock();
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000125
126 // Emit debug descriptor for function end.
127 if (CGDebugInfo *DI = CGM.getDebugInfo()) {
128 DI->setLocation(EndLoc);
129 DI->EmitRegionEnd(CurFn, Builder);
130 }
131
Daniel Dunbar88b53962009-02-02 22:03:45 +0000132 EmitFunctionEpilog(*CurFnInfo, ReturnValue);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000133
Chris Lattner5a2fa142007-12-02 06:32:24 +0000134 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
135 AllocaInsertPt->eraseFromParent();
136 AllocaInsertPt = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000137}
138
Daniel Dunbar7c086512008-09-09 23:14:03 +0000139void CodeGenFunction::StartFunction(const Decl *D, QualType RetTy,
140 llvm::Function *Fn,
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000141 const FunctionArgList &Args,
142 SourceLocation StartLoc) {
Daniel Dunbar7c086512008-09-09 23:14:03 +0000143 CurFuncDecl = D;
144 FnRetTy = RetTy;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000145 CurFn = Fn;
Chris Lattner41110242008-06-17 18:05:57 +0000146 assert(CurFn->isDeclaration() && "Function already has body?");
147
Daniel Dunbar55e87422008-11-11 02:29:29 +0000148 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000149
Chris Lattner41110242008-06-17 18:05:57 +0000150 // Create a marker to make it easy to insert allocas into the entryblock
151 // later. Don't create this with the builder, because we don't want it
152 // folded.
153 llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::Int32Ty);
154 AllocaInsertPt = new llvm::BitCastInst(Undef, llvm::Type::Int32Ty, "allocapt",
155 EntryBB);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000156
Daniel Dunbar55e87422008-11-11 02:29:29 +0000157 ReturnBlock = createBasicBlock("return");
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000158 ReturnValue = 0;
Daniel Dunbar7c086512008-09-09 23:14:03 +0000159 if (!RetTy->isVoidType())
160 ReturnValue = CreateTempAlloca(ConvertType(RetTy), "retval");
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000161
Chris Lattner41110242008-06-17 18:05:57 +0000162 Builder.SetInsertPoint(EntryBB);
163
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000164 // Emit subprogram debug descriptor.
Daniel Dunbar7c086512008-09-09 23:14:03 +0000165 // FIXME: The cast here is a huge hack.
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000166 if (CGDebugInfo *DI = CGM.getDebugInfo()) {
167 DI->setLocation(StartLoc);
168 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Chris Lattner8ec03f52008-11-24 03:54:41 +0000169 DI->EmitFunctionStart(FD->getIdentifier()->getName(),
170 RetTy, CurFn, Builder);
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000171 } else {
172 // Just use LLVM function name.
173 DI->EmitFunctionStart(Fn->getName().c_str(),
174 RetTy, CurFn, Builder);
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000175 }
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000176 }
177
Daniel Dunbar88b53962009-02-02 22:03:45 +0000178 // FIXME: Leaked.
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000179 CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args);
Daniel Dunbar88b53962009-02-02 22:03:45 +0000180 EmitFunctionProlog(*CurFnInfo, CurFn, Args);
Anders Carlsson751358f2008-12-20 21:28:43 +0000181
182 // If any of the arguments have a variably modified type, make sure to
183 // emit the type size.
184 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
185 i != e; ++i) {
186 QualType Ty = i->second;
187
188 if (Ty->isVariablyModifiedType())
189 EmitVLASize(Ty);
190 }
Daniel Dunbar7c086512008-09-09 23:14:03 +0000191}
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000192
Daniel Dunbar7c086512008-09-09 23:14:03 +0000193void CodeGenFunction::GenerateCode(const FunctionDecl *FD,
194 llvm::Function *Fn) {
195 FunctionArgList Args;
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000196 if (FD->getNumParams()) {
197 const FunctionTypeProto* FProto = FD->getType()->getAsFunctionTypeProto();
198 assert(FProto && "Function def must have prototype!");
Daniel Dunbar7c086512008-09-09 23:14:03 +0000199
200 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
201 Args.push_back(std::make_pair(FD->getParamDecl(i),
202 FProto->getArgType(i)));
Chris Lattner41110242008-06-17 18:05:57 +0000203 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000204
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000205 StartFunction(FD, FD->getResultType(), Fn, Args,
206 cast<CompoundStmt>(FD->getBody())->getLBracLoc());
Daniel Dunbar7c086512008-09-09 23:14:03 +0000207
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000208 EmitStmt(FD->getBody());
209
210 const CompoundStmt *S = dyn_cast<CompoundStmt>(FD->getBody());
211 if (S) {
212 FinishFunction(S->getRBracLoc());
213 } else {
214 FinishFunction();
215 }
Chris Lattner41110242008-06-17 18:05:57 +0000216}
217
Chris Lattner0946ccd2008-11-11 07:41:27 +0000218/// ContainsLabel - Return true if the statement contains a label in it. If
219/// this statement is not executed normally, it not containing a label means
220/// that we can just remove the code.
221bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
222 // Null statement, not a label!
223 if (S == 0) return false;
224
225 // If this is a label, we have to emit the code, consider something like:
226 // if (0) { ... foo: bar(); } goto foo;
227 if (isa<LabelStmt>(S))
228 return true;
229
230 // If this is a case/default statement, and we haven't seen a switch, we have
231 // to emit the code.
232 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
233 return true;
234
235 // If this is a switch statement, we want to ignore cases below it.
236 if (isa<SwitchStmt>(S))
237 IgnoreCaseStmts = true;
238
239 // Scan subexpressions for verboten labels.
240 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
241 I != E; ++I)
242 if (ContainsLabel(*I, IgnoreCaseStmts))
243 return true;
244
245 return false;
246}
247
Chris Lattner31a09842008-11-12 08:04:58 +0000248
249/// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
250/// a constant, or if it does but contains a label, return 0. If it constant
251/// folds to 'true' and does not contain a label, return 1, if it constant folds
252/// to 'false' and does not contain a label, return -1.
253int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
Daniel Dunbar36bc14c2008-11-12 22:37:10 +0000254 // FIXME: Rename and handle conversion of other evaluatable things
255 // to bool.
Anders Carlsson64712f12008-12-01 02:46:24 +0000256 Expr::EvalResult Result;
257 if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
258 Result.HasSideEffects)
Anders Carlssonef5a66d2008-11-22 22:32:07 +0000259 return 0; // Not foldable, not integer or not fully evaluatable.
Chris Lattner31a09842008-11-12 08:04:58 +0000260
261 if (CodeGenFunction::ContainsLabel(Cond))
262 return 0; // Contains a label.
263
Anders Carlsson64712f12008-12-01 02:46:24 +0000264 return Result.Val.getInt().getBoolValue() ? 1 : -1;
Chris Lattner31a09842008-11-12 08:04:58 +0000265}
266
267
268/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
269/// statement) to the specified blocks. Based on the condition, this might try
270/// to simplify the codegen of the conditional based on the branch.
271///
272void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
273 llvm::BasicBlock *TrueBlock,
274 llvm::BasicBlock *FalseBlock) {
275 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
276 return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
277
278 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
279 // Handle X && Y in a condition.
280 if (CondBOp->getOpcode() == BinaryOperator::LAnd) {
281 // If we have "1 && X", simplify the code. "0 && X" would have constant
282 // folded if the case was simple enough.
283 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
284 // br(1 && X) -> br(X).
285 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
286 }
287
288 // If we have "X && 1", simplify the code to use an uncond branch.
289 // "X && 0" would have been constant folded to 0.
290 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
291 // br(X && 1) -> br(X).
292 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
293 }
294
295 // Emit the LHS as a conditional. If the LHS conditional is false, we
296 // want to jump to the FalseBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000297 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
Chris Lattner31a09842008-11-12 08:04:58 +0000298 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
299 EmitBlock(LHSTrue);
300
301 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
302 return;
303 } else if (CondBOp->getOpcode() == BinaryOperator::LOr) {
304 // If we have "0 || X", simplify the code. "1 || X" would have constant
305 // folded if the case was simple enough.
306 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
307 // br(0 || X) -> br(X).
308 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
309 }
310
311 // If we have "X || 0", simplify the code to use an uncond branch.
312 // "X || 1" would have been constant folded to 1.
313 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
314 // br(X || 0) -> br(X).
315 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
316 }
317
318 // Emit the LHS as a conditional. If the LHS conditional is true, we
319 // want to jump to the TrueBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000320 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
Chris Lattner31a09842008-11-12 08:04:58 +0000321 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
322 EmitBlock(LHSFalse);
323
324 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
325 return;
326 }
Chris Lattner552f4c42008-11-12 08:13:36 +0000327 }
328
329 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
330 // br(!x, t, f) -> br(x, f, t)
331 if (CondUOp->getOpcode() == UnaryOperator::LNot)
332 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
Chris Lattner31a09842008-11-12 08:04:58 +0000333 }
334
Daniel Dunbar09b14892008-11-12 10:30:32 +0000335 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
336 // Handle ?: operator.
337
338 // Just ignore GNU ?: extension.
339 if (CondOp->getLHS()) {
340 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
341 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
342 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
343 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
344 EmitBlock(LHSBlock);
345 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
346 EmitBlock(RHSBlock);
347 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
348 return;
349 }
350 }
351
Chris Lattner31a09842008-11-12 08:04:58 +0000352 // Emit the code with the fully general case.
353 llvm::Value *CondV = EvaluateExprAsBool(Cond);
354 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
355}
356
Devang Patel88a981b2007-11-01 19:11:01 +0000357/// getCGRecordLayout - Return record layout info.
358const CGRecordLayout *CodeGenFunction::getCGRecordLayout(CodeGenTypes &CGT,
Chris Lattneraf319132008-02-05 06:55:31 +0000359 QualType Ty) {
360 const RecordType *RTy = Ty->getAsRecordType();
361 assert (RTy && "Unexpected type. RecordType expected here.");
Devang Patelb84a06e2007-10-23 02:10:49 +0000362
Chris Lattneraf319132008-02-05 06:55:31 +0000363 return CGT.getCGRecordLayout(RTy->getDecl());
Devang Patelb84a06e2007-10-23 02:10:49 +0000364}
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000365
Daniel Dunbar488e9932008-08-16 00:56:44 +0000366/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000367/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000368void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
369 bool OmitOnError) {
370 CGM.ErrorUnsupported(S, Type, OmitOnError);
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000371}
372
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000373unsigned CodeGenFunction::GetIDForAddrOfLabel(const LabelStmt *L) {
374 // Use LabelIDs.size() as the new ID if one hasn't been assigned.
375 return LabelIDs.insert(std::make_pair(L, LabelIDs.size())).first->second;
376}
377
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000378void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty)
379{
380 const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
381 if (DestPtr->getType() != BP)
382 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
383
384 // Get size and alignment info for this aggregate.
385 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
386
387 // FIXME: Handle variable sized types.
388 const llvm::Type *IntPtr = llvm::IntegerType::get(LLVMPointerWidth);
389
390 Builder.CreateCall4(CGM.getMemSetFn(), DestPtr,
391 llvm::ConstantInt::getNullValue(llvm::Type::Int8Ty),
392 // TypeInfo.first describes size in bits.
393 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
394 llvm::ConstantInt::get(llvm::Type::Int32Ty,
395 TypeInfo.second/8));
396}
397
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000398void CodeGenFunction::EmitIndirectSwitches() {
399 llvm::BasicBlock *Default;
400
Daniel Dunbar76526a52008-08-04 17:24:44 +0000401 if (IndirectSwitches.empty())
402 return;
403
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000404 if (!LabelIDs.empty()) {
405 Default = getBasicBlockForLabel(LabelIDs.begin()->first);
406 } else {
407 // No possible targets for indirect goto, just emit an infinite
408 // loop.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000409 Default = createBasicBlock("indirectgoto.loop", CurFn);
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000410 llvm::BranchInst::Create(Default, Default);
411 }
412
413 for (std::vector<llvm::SwitchInst*>::iterator i = IndirectSwitches.begin(),
414 e = IndirectSwitches.end(); i != e; ++i) {
415 llvm::SwitchInst *I = *i;
416
417 I->setSuccessor(0, Default);
418 for (std::map<const LabelStmt*,unsigned>::iterator LI = LabelIDs.begin(),
419 LE = LabelIDs.end(); LI != LE; ++LI) {
420 I->addCase(llvm::ConstantInt::get(llvm::Type::Int32Ty,
421 LI->second),
422 getBasicBlockForLabel(LI->first));
423 }
424 }
425}
Anders Carlssonddf7cac2008-11-04 05:30:00 +0000426
427llvm::Value *CodeGenFunction::EmitVAArg(llvm::Value *VAListAddr, QualType Ty)
428{
429 // FIXME: This entire method is hardcoded for 32-bit X86.
430
431 const char *TargetPrefix = getContext().Target.getTargetPrefix();
432
433 if (strcmp(TargetPrefix, "x86") != 0 ||
434 getContext().Target.getPointerWidth(0) != 32)
435 return 0;
436
437 const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
438 const llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
439
440 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
441 "ap");
442 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
443 llvm::Value *AddrTyped =
444 Builder.CreateBitCast(Addr,
445 llvm::PointerType::getUnqual(ConvertType(Ty)));
446
447 uint64_t SizeInBytes = getContext().getTypeSize(Ty) / 8;
448 const unsigned ArgumentSizeInBytes = 4;
449 if (SizeInBytes < ArgumentSizeInBytes)
450 SizeInBytes = ArgumentSizeInBytes;
451
452 llvm::Value *NextAddr =
453 Builder.CreateGEP(Addr,
454 llvm::ConstantInt::get(llvm::Type::Int32Ty, SizeInBytes),
455 "ap.next");
456 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
457
458 return AddrTyped;
459}
460
Anders Carlssonf666b772008-12-20 20:27:15 +0000461
Anders Carlssondcc90d82008-12-12 07:19:02 +0000462llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT)
463{
464 llvm::Value *&SizeEntry = VLASizeMap[VAT];
Anders Carlssondcc90d82008-12-12 07:19:02 +0000465
Anders Carlssonf666b772008-12-20 20:27:15 +0000466 assert(SizeEntry && "Did not emit size for type");
467 return SizeEntry;
468}
Anders Carlssondcc90d82008-12-12 07:19:02 +0000469
Anders Carlsson60d35412008-12-20 20:46:34 +0000470llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty)
Anders Carlssonf666b772008-12-20 20:27:15 +0000471{
Anders Carlsson60d35412008-12-20 20:46:34 +0000472 assert(Ty->isVariablyModifiedType() &&
473 "Must pass variably modified type to EmitVLASizes!");
Anders Carlssonf666b772008-12-20 20:27:15 +0000474
Anders Carlsson60d35412008-12-20 20:46:34 +0000475 if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
476 llvm::Value *&SizeEntry = VLASizeMap[VAT];
477
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000478 if (!SizeEntry) {
479 // Get the element size;
480 llvm::Value *ElemSize;
Anders Carlsson60d35412008-12-20 20:46:34 +0000481
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000482 QualType ElemTy = VAT->getElementType();
Anders Carlsson96f21472009-02-05 19:43:10 +0000483
484 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
485
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000486 if (ElemTy->isVariableArrayType())
487 ElemSize = EmitVLASize(ElemTy);
488 else {
Anders Carlsson96f21472009-02-05 19:43:10 +0000489 ElemSize = llvm::ConstantInt::get(SizeTy,
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000490 getContext().getTypeSize(ElemTy) / 8);
491 }
Anders Carlsson60d35412008-12-20 20:46:34 +0000492
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000493 llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
Anders Carlsson96f21472009-02-05 19:43:10 +0000494 NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
495
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000496 SizeEntry = Builder.CreateMul(ElemSize, NumElements);
Anders Carlsson60d35412008-12-20 20:46:34 +0000497 }
498
Anders Carlsson60d35412008-12-20 20:46:34 +0000499 return SizeEntry;
500 } else if (const PointerType *PT = Ty->getAsPointerType())
501 EmitVLASize(PT->getPointeeType());
Anders Carlssonf666b772008-12-20 20:27:15 +0000502 else {
Anders Carlsson60d35412008-12-20 20:46:34 +0000503 assert(0 && "unknown VM type!");
Anders Carlssondcc90d82008-12-12 07:19:02 +0000504 }
Anders Carlsson60d35412008-12-20 20:46:34 +0000505
506 return 0;
Anders Carlssondcc90d82008-12-12 07:19:02 +0000507}
Eli Friedman4fd0aa52009-01-20 17:46:04 +0000508
509llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
510 if (CGM.getContext().getBuiltinVaListType()->isArrayType()) {
511 return EmitScalarExpr(E);
512 }
513 return EmitLValue(E).getAddress();
514}
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000515
516llvm::BasicBlock *CodeGenFunction::CreateCleanupBlock()
517{
518 llvm::BasicBlock *CleanupBlock = createBasicBlock("cleanup");
519
520 CleanupEntries.push_back(CleanupEntry(CleanupBlock));
521
522 return CleanupBlock;
523}