blob: d3bf1645a026f1fbd8739618f3e04c932e17142d [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"
Mike Stump6a1e0eb2009-12-04 23:26:17 +000022#include "clang/AST/StmtCXX.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
Mike Stump1eb44332009-09-09 15:08:12 +000027CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
Mike Stumpa4f668f2009-03-06 01:33:24 +000028 : BlockFunction(cgm, *this, Builder), CGM(cgm),
29 Target(CGM.getContext().Target),
Owen Andersonaac87052009-07-08 20:52:20 +000030 Builder(cgm.getModule().getContext()),
Chris Lattnerd9becd12009-10-28 23:59:40 +000031 DebugInfo(0), IndirectBranch(0),
Chris Lattner3d00fdc2009-10-13 06:55:33 +000032 SwitchInsn(0), CaseRangeBlock(0), InvokeDest(0),
John McCall25049412010-02-16 22:04:33 +000033 CXXThisDecl(0), CXXThisValue(0), CXXVTTDecl(0), CXXVTTValue(0),
Mike Stump15037ca2009-12-15 00:35:12 +000034 ConditionalBranchLevel(0), TerminateHandler(0), TrapBB(0),
Mike Stumpbe07f602009-12-14 21:58:14 +000035 UniqueAggrDestructorCount(0) {
Mike Stump4e7a1f72009-02-21 20:00:35 +000036 LLVMIntTy = ConvertType(getContext().IntTy);
37 LLVMPointerWidth = Target.getPointerWidth(0);
Mike Stumpd88ea562009-12-09 03:35:49 +000038 Exceptions = getContext().getLangOptions().Exceptions;
Mike Stump9c276ae2009-12-12 01:27:46 +000039 CatchUndefined = getContext().getLangOptions().CatchUndefined;
Chris Lattner41110242008-06-17 18:05:57 +000040}
Reid Spencer5f016e22007-07-11 17:01:13 +000041
42ASTContext &CodeGenFunction::getContext() const {
43 return CGM.getContext();
44}
45
46
47llvm::BasicBlock *CodeGenFunction::getBasicBlockForLabel(const LabelStmt *S) {
48 llvm::BasicBlock *&BB = LabelMap[S];
49 if (BB) return BB;
Mike Stump1eb44332009-09-09 15:08:12 +000050
Reid Spencer5f016e22007-07-11 17:01:13 +000051 // Create, but don't insert, the new block.
Daniel Dunbar55e87422008-11-11 02:29:29 +000052 return BB = createBasicBlock(S->getName());
Reid Spencer5f016e22007-07-11 17:01:13 +000053}
54
Daniel Dunbar0096acf2009-02-25 19:24:29 +000055llvm::Value *CodeGenFunction::GetAddrOfLocalVar(const VarDecl *VD) {
56 llvm::Value *Res = LocalDeclMap[VD];
57 assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!");
58 return Res;
Lauro Ramos Venancio81373352008-02-26 21:41:45 +000059}
Reid Spencer5f016e22007-07-11 17:01:13 +000060
Daniel Dunbar0096acf2009-02-25 19:24:29 +000061llvm::Constant *
62CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) {
63 return cast<llvm::Constant>(GetAddrOfLocalVar(BVD));
Anders Carlssondde0a942008-09-11 09:15:33 +000064}
65
Daniel Dunbar8b1a3432009-02-03 23:03:55 +000066const llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
67 return CGM.getTypes().ConvertTypeForMem(T);
68}
69
Reid Spencer5f016e22007-07-11 17:01:13 +000070const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
71 return CGM.getTypes().ConvertType(T);
72}
73
74bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
Anders Carlssone9d34dc2009-09-29 02:09:01 +000075 return T->isRecordType() || T->isArrayType() || T->isAnyComplexType() ||
76 T->isMemberFunctionPointerType();
Reid Spencer5f016e22007-07-11 17:01:13 +000077}
78
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000079void CodeGenFunction::EmitReturnBlock() {
80 // For cleanliness, we try to avoid emitting the return block for
81 // simple cases.
82 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
83
84 if (CurBB) {
85 assert(!CurBB->getTerminator() && "Unexpected terminated block.");
86
Daniel Dunbar96e18b02009-07-19 08:24:34 +000087 // We have a valid insert point, reuse it if it is empty or there are no
88 // explicit jumps to the return block.
89 if (CurBB->empty() || ReturnBlock->use_empty()) {
90 ReturnBlock->replaceAllUsesWith(CurBB);
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000091 delete ReturnBlock;
Daniel Dunbar96e18b02009-07-19 08:24:34 +000092 } else
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000093 EmitBlock(ReturnBlock);
94 return;
95 }
96
97 // Otherwise, if the return block is the target of a single direct
98 // branch then we can just put the code in that block instead. This
99 // cleans up functions which started with a unified return block.
100 if (ReturnBlock->hasOneUse()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000101 llvm::BranchInst *BI =
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000102 dyn_cast<llvm::BranchInst>(*ReturnBlock->use_begin());
103 if (BI && BI->isUnconditional() && BI->getSuccessor(0) == ReturnBlock) {
104 // Reset insertion point and delete the branch.
105 Builder.SetInsertPoint(BI->getParent());
106 BI->eraseFromParent();
107 delete ReturnBlock;
108 return;
109 }
110 }
111
Mike Stumpf5408fe2009-05-16 07:57:57 +0000112 // FIXME: We are at an unreachable point, there is no reason to emit the block
113 // unless it has uses. However, we still need a place to put the debug
114 // region.end for now.
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000115
116 EmitBlock(ReturnBlock);
117}
118
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000119void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
Chris Lattnerda138702007-07-16 21:28:45 +0000120 assert(BreakContinueStack.empty() &&
121 "mismatched push/pop in break/continue stack!");
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000122 assert(BlockScopes.empty() &&
123 "did not remove all blocks from block scope map!");
124 assert(CleanupEntries.empty() &&
125 "mismatched push/pop in cleanup stack!");
Mike Stump1eb44332009-09-09 15:08:12 +0000126
127 // Emit function epilog (to return).
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000128 EmitReturnBlock();
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000129
130 // Emit debug descriptor for function end.
Anders Carlssone896d982009-02-13 08:11:52 +0000131 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000132 DI->setLocation(EndLoc);
133 DI->EmitRegionEnd(CurFn, Builder);
134 }
135
Daniel Dunbar88b53962009-02-02 22:03:45 +0000136 EmitFunctionEpilog(*CurFnInfo, ReturnValue);
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000137 EmitEndEHSpec(CurCodeDecl);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000138
Chris Lattnerd9becd12009-10-28 23:59:40 +0000139 // If someone did an indirect goto, emit the indirect goto block at the end of
140 // the function.
141 if (IndirectBranch) {
142 EmitBlock(IndirectBranch->getParent());
143 Builder.ClearInsertionPoint();
144 }
145
Chris Lattner5a2fa142007-12-02 06:32:24 +0000146 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
Chris Lattner481769b2009-03-31 22:17:44 +0000147 llvm::Instruction *Ptr = AllocaInsertPt;
Chris Lattner5a2fa142007-12-02 06:32:24 +0000148 AllocaInsertPt = 0;
Chris Lattner481769b2009-03-31 22:17:44 +0000149 Ptr->eraseFromParent();
Chris Lattnerd9becd12009-10-28 23:59:40 +0000150
151 // If someone took the address of a label but never did an indirect goto, we
152 // made a zero entry PHI node, which is illegal, zap it now.
153 if (IndirectBranch) {
154 llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
155 if (PN->getNumIncomingValues() == 0) {
156 PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
157 PN->eraseFromParent();
158 }
159 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000160}
161
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000162void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
Daniel Dunbar7c086512008-09-09 23:14:03 +0000163 llvm::Function *Fn,
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000164 const FunctionArgList &Args,
165 SourceLocation StartLoc) {
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000166 const Decl *D = GD.getDecl();
167
Anders Carlsson4cc1a472009-02-09 20:20:56 +0000168 DidCallStackSave = false;
Chris Lattnerb5437d22009-04-23 05:30:27 +0000169 CurCodeDecl = CurFuncDecl = D;
Daniel Dunbar7c086512008-09-09 23:14:03 +0000170 FnRetTy = RetTy;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000171 CurFn = Fn;
Chris Lattner41110242008-06-17 18:05:57 +0000172 assert(CurFn->isDeclaration() && "Function already has body?");
173
Jakob Stoklund Olesena3fe2842010-02-09 00:10:00 +0000174 // Pass inline keyword to optimizer if it appears explicitly on any
175 // declaration.
176 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
177 for (FunctionDecl::redecl_iterator RI = FD->redecls_begin(),
178 RE = FD->redecls_end(); RI != RE; ++RI)
179 if (RI->isInlineSpecified()) {
180 Fn->addFnAttr(llvm::Attribute::InlineHint);
181 break;
182 }
183
Daniel Dunbar55e87422008-11-11 02:29:29 +0000184 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000185
Chris Lattner41110242008-06-17 18:05:57 +0000186 // Create a marker to make it easy to insert allocas into the entryblock
187 // later. Don't create this with the builder, because we don't want it
188 // folded.
Owen Anderson0032b272009-08-13 21:57:51 +0000189 llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::getInt32Ty(VMContext));
Mike Stumpbcdc0f02009-09-25 18:11:00 +0000190 AllocaInsertPt = new llvm::BitCastInst(Undef,
191 llvm::Type::getInt32Ty(VMContext), "",
Chris Lattner41110242008-06-17 18:05:57 +0000192 EntryBB);
Chris Lattnerf1466842009-03-22 00:24:14 +0000193 if (Builder.isNamePreserving())
194 AllocaInsertPt->setName("allocapt");
Mike Stump1eb44332009-09-09 15:08:12 +0000195
Daniel Dunbar55e87422008-11-11 02:29:29 +0000196 ReturnBlock = createBasicBlock("return");
Mike Stump1eb44332009-09-09 15:08:12 +0000197
Chris Lattner41110242008-06-17 18:05:57 +0000198 Builder.SetInsertPoint(EntryBB);
Mike Stump1eb44332009-09-09 15:08:12 +0000199
Douglas Gregorce056bc2010-02-21 22:15:06 +0000200 QualType FnType = getContext().getFunctionType(RetTy, 0, 0, false, 0,
201 false, false, 0, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +0000202 /*FIXME?*/
203 FunctionType::ExtInfo());
Mike Stump91cc8152009-10-23 01:52:13 +0000204
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000205 // Emit subprogram debug descriptor.
Anders Carlssone896d982009-02-13 08:11:52 +0000206 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000207 DI->setLocation(StartLoc);
Devang Patel9c6c3a02010-01-14 00:36:21 +0000208 DI->EmitFunctionStart(GD, FnType, CurFn, Builder);
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000209 }
210
Daniel Dunbar88b53962009-02-02 22:03:45 +0000211 // FIXME: Leaked.
John McCall04a67a62010-02-05 21:31:56 +0000212 // CC info is ignored, hopefully?
213 CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args,
Rafael Espindola264ba482010-03-30 20:24:48 +0000214 FunctionType::ExtInfo());
Eli Friedmanb17daf92009-12-04 02:43:40 +0000215
216 if (RetTy->isVoidType()) {
217 // Void type; nothing to return.
218 ReturnValue = 0;
219 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
220 hasAggregateLLVMType(CurFnInfo->getReturnType())) {
221 // Indirect aggregate return; emit returned value directly into sret slot.
Daniel Dunbar647a1ec2010-02-16 19:45:20 +0000222 // This reduces code size, and affects correctness in C++.
Eli Friedmanb17daf92009-12-04 02:43:40 +0000223 ReturnValue = CurFn->arg_begin();
224 } else {
Daniel Dunbar647a1ec2010-02-16 19:45:20 +0000225 ReturnValue = CreateIRTemp(RetTy, "retval");
Eli Friedmanb17daf92009-12-04 02:43:40 +0000226 }
227
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000228 EmitStartEHSpec(CurCodeDecl);
Daniel Dunbar88b53962009-02-02 22:03:45 +0000229 EmitFunctionProlog(*CurFnInfo, CurFn, Args);
Mike Stump1eb44332009-09-09 15:08:12 +0000230
John McCall25049412010-02-16 22:04:33 +0000231 if (CXXThisDecl)
232 CXXThisValue = Builder.CreateLoad(LocalDeclMap[CXXThisDecl], "this");
233 if (CXXVTTDecl)
234 CXXVTTValue = Builder.CreateLoad(LocalDeclMap[CXXVTTDecl], "vtt");
235
Anders Carlsson751358f2008-12-20 21:28:43 +0000236 // If any of the arguments have a variably modified type, make sure to
237 // emit the type size.
238 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
239 i != e; ++i) {
240 QualType Ty = i->second;
241
242 if (Ty->isVariablyModifiedType())
243 EmitVLASize(Ty);
244 }
Daniel Dunbar7c086512008-09-09 23:14:03 +0000245}
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000246
John McCall9fc6a772010-02-19 09:25:03 +0000247void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args) {
248 const FunctionDecl *FD = cast<FunctionDecl>(CurGD.getDecl());
Douglas Gregor06a9f362010-05-01 20:49:11 +0000249 assert(FD->getBody());
250 EmitStmt(FD->getBody());
John McCalla355e072010-02-18 03:17:58 +0000251}
252
Anders Carlssonc997d422010-01-02 01:01:18 +0000253void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn) {
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000254 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
255
Anders Carlssone896d982009-02-13 08:11:52 +0000256 // Check if we should generate debug info for this function.
Mike Stump1feade82009-08-26 22:31:08 +0000257 if (CGM.getDebugInfo() && !FD->hasAttr<NoDebugAttr>())
Anders Carlssone896d982009-02-13 08:11:52 +0000258 DebugInfo = CGM.getDebugInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000259
Daniel Dunbar7c086512008-09-09 23:14:03 +0000260 FunctionArgList Args;
Mike Stump1eb44332009-09-09 15:08:12 +0000261
Mike Stump6a1e0eb2009-12-04 23:26:17 +0000262 CurGD = GD;
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000263 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
264 if (MD->isInstance()) {
265 // Create the implicit 'this' decl.
266 // FIXME: I'm not entirely sure I like using a fake decl just for code
267 // generation. Maybe we can come up with a better way?
John McCall25049412010-02-16 22:04:33 +0000268 CXXThisDecl = ImplicitParamDecl::Create(getContext(), 0,
269 FD->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +0000270 &getContext().Idents.get("this"),
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000271 MD->getThisType(getContext()));
272 Args.push_back(std::make_pair(CXXThisDecl, CXXThisDecl->getType()));
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000273
274 // Check if we need a VTT parameter as well.
Anders Carlssonaf440352010-03-23 04:11:45 +0000275 if (CodeGenVTables::needsVTTParameter(GD)) {
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000276 // FIXME: The comment about using a fake decl above applies here too.
277 QualType T = getContext().getPointerType(getContext().VoidPtrTy);
278 CXXVTTDecl =
John McCall25049412010-02-16 22:04:33 +0000279 ImplicitParamDecl::Create(getContext(), 0, FD->getLocation(),
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000280 &getContext().Idents.get("vtt"), T);
281 Args.push_back(std::make_pair(CXXVTTDecl, CXXVTTDecl->getType()));
282 }
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000283 }
284 }
Mike Stump1eb44332009-09-09 15:08:12 +0000285
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000286 if (FD->getNumParams()) {
John McCall183700f2009-09-21 23:43:11 +0000287 const FunctionProtoType* FProto = FD->getType()->getAs<FunctionProtoType>();
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000288 assert(FProto && "Function def must have prototype!");
Daniel Dunbar7c086512008-09-09 23:14:03 +0000289
290 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
Mike Stump1eb44332009-09-09 15:08:12 +0000291 Args.push_back(std::make_pair(FD->getParamDecl(i),
Daniel Dunbar7c086512008-09-09 23:14:03 +0000292 FProto->getArgType(i)));
Chris Lattner41110242008-06-17 18:05:57 +0000293 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000294
John McCalla355e072010-02-18 03:17:58 +0000295 SourceRange BodyRange;
296 if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange();
Anders Carlsson4365bba2009-11-06 02:55:43 +0000297
John McCalla355e072010-02-18 03:17:58 +0000298 // Emit the standard function prologue.
299 StartFunction(GD, FD->getResultType(), Fn, Args, BodyRange.getBegin());
Anders Carlsson4365bba2009-11-06 02:55:43 +0000300
John McCalla355e072010-02-18 03:17:58 +0000301 // Generate the body of the function.
John McCall9fc6a772010-02-19 09:25:03 +0000302 if (isa<CXXDestructorDecl>(FD))
303 EmitDestructorBody(Args);
304 else if (isa<CXXConstructorDecl>(FD))
305 EmitConstructorBody(Args);
306 else
307 EmitFunctionBody(Args);
Anders Carlsson1851a122010-02-07 19:45:40 +0000308
John McCalla355e072010-02-18 03:17:58 +0000309 // Emit the standard function epilogue.
310 FinishFunction(BodyRange.getEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000311
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000312 // Destroy the 'this' declaration.
313 if (CXXThisDecl)
314 CXXThisDecl->Destroy(getContext());
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000315
316 // Destroy the VTT declaration.
317 if (CXXVTTDecl)
318 CXXVTTDecl->Destroy(getContext());
Chris Lattner41110242008-06-17 18:05:57 +0000319}
320
Chris Lattner0946ccd2008-11-11 07:41:27 +0000321/// ContainsLabel - Return true if the statement contains a label in it. If
322/// this statement is not executed normally, it not containing a label means
323/// that we can just remove the code.
324bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
325 // Null statement, not a label!
326 if (S == 0) return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000327
Chris Lattner0946ccd2008-11-11 07:41:27 +0000328 // If this is a label, we have to emit the code, consider something like:
329 // if (0) { ... foo: bar(); } goto foo;
330 if (isa<LabelStmt>(S))
331 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000332
Chris Lattner0946ccd2008-11-11 07:41:27 +0000333 // If this is a case/default statement, and we haven't seen a switch, we have
334 // to emit the code.
335 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
336 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000337
Chris Lattner0946ccd2008-11-11 07:41:27 +0000338 // If this is a switch statement, we want to ignore cases below it.
339 if (isa<SwitchStmt>(S))
340 IgnoreCaseStmts = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000341
Chris Lattner0946ccd2008-11-11 07:41:27 +0000342 // Scan subexpressions for verboten labels.
343 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
344 I != E; ++I)
345 if (ContainsLabel(*I, IgnoreCaseStmts))
346 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000347
Chris Lattner0946ccd2008-11-11 07:41:27 +0000348 return false;
349}
350
Chris Lattner31a09842008-11-12 08:04:58 +0000351
352/// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
353/// a constant, or if it does but contains a label, return 0. If it constant
354/// folds to 'true' and does not contain a label, return 1, if it constant folds
355/// to 'false' and does not contain a label, return -1.
356int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
Daniel Dunbar36bc14c2008-11-12 22:37:10 +0000357 // FIXME: Rename and handle conversion of other evaluatable things
358 // to bool.
Anders Carlsson64712f12008-12-01 02:46:24 +0000359 Expr::EvalResult Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000360 if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
Anders Carlsson64712f12008-12-01 02:46:24 +0000361 Result.HasSideEffects)
Anders Carlssonef5a66d2008-11-22 22:32:07 +0000362 return 0; // Not foldable, not integer or not fully evaluatable.
Mike Stump1eb44332009-09-09 15:08:12 +0000363
Chris Lattner31a09842008-11-12 08:04:58 +0000364 if (CodeGenFunction::ContainsLabel(Cond))
365 return 0; // Contains a label.
Mike Stump1eb44332009-09-09 15:08:12 +0000366
Anders Carlsson64712f12008-12-01 02:46:24 +0000367 return Result.Val.getInt().getBoolValue() ? 1 : -1;
Chris Lattner31a09842008-11-12 08:04:58 +0000368}
369
370
371/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
372/// statement) to the specified blocks. Based on the condition, this might try
373/// to simplify the codegen of the conditional based on the branch.
374///
375void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
376 llvm::BasicBlock *TrueBlock,
377 llvm::BasicBlock *FalseBlock) {
378 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
379 return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000380
Chris Lattner31a09842008-11-12 08:04:58 +0000381 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
382 // Handle X && Y in a condition.
383 if (CondBOp->getOpcode() == BinaryOperator::LAnd) {
384 // If we have "1 && X", simplify the code. "0 && X" would have constant
385 // folded if the case was simple enough.
386 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
387 // br(1 && X) -> br(X).
388 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
389 }
Mike Stump1eb44332009-09-09 15:08:12 +0000390
Chris Lattner31a09842008-11-12 08:04:58 +0000391 // If we have "X && 1", simplify the code to use an uncond branch.
392 // "X && 0" would have been constant folded to 0.
393 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
394 // br(X && 1) -> br(X).
395 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
396 }
Mike Stump1eb44332009-09-09 15:08:12 +0000397
Chris Lattner31a09842008-11-12 08:04:58 +0000398 // Emit the LHS as a conditional. If the LHS conditional is false, we
399 // want to jump to the FalseBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000400 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
Chris Lattner31a09842008-11-12 08:04:58 +0000401 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
402 EmitBlock(LHSTrue);
Mike Stump1eb44332009-09-09 15:08:12 +0000403
Anders Carlsson08e9e452010-01-24 00:20:05 +0000404 // Any temporaries created here are conditional.
Anders Carlsson72119a82010-02-04 17:18:07 +0000405 BeginConditionalBranch();
Chris Lattner31a09842008-11-12 08:04:58 +0000406 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
Anders Carlsson72119a82010-02-04 17:18:07 +0000407 EndConditionalBranch();
Anders Carlsson08e9e452010-01-24 00:20:05 +0000408
Chris Lattner31a09842008-11-12 08:04:58 +0000409 return;
410 } else if (CondBOp->getOpcode() == BinaryOperator::LOr) {
411 // If we have "0 || X", simplify the code. "1 || X" would have constant
412 // folded if the case was simple enough.
413 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
414 // br(0 || X) -> br(X).
415 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
416 }
Mike Stump1eb44332009-09-09 15:08:12 +0000417
Chris Lattner31a09842008-11-12 08:04:58 +0000418 // If we have "X || 0", simplify the code to use an uncond branch.
419 // "X || 1" would have been constant folded to 1.
420 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
421 // br(X || 0) -> br(X).
422 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
423 }
Mike Stump1eb44332009-09-09 15:08:12 +0000424
Chris Lattner31a09842008-11-12 08:04:58 +0000425 // Emit the LHS as a conditional. If the LHS conditional is true, we
426 // want to jump to the TrueBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000427 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
Chris Lattner31a09842008-11-12 08:04:58 +0000428 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
429 EmitBlock(LHSFalse);
Mike Stump1eb44332009-09-09 15:08:12 +0000430
Anders Carlsson08e9e452010-01-24 00:20:05 +0000431 // Any temporaries created here are conditional.
Anders Carlsson72119a82010-02-04 17:18:07 +0000432 BeginConditionalBranch();
Chris Lattner31a09842008-11-12 08:04:58 +0000433 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
Anders Carlsson72119a82010-02-04 17:18:07 +0000434 EndConditionalBranch();
Anders Carlsson08e9e452010-01-24 00:20:05 +0000435
Chris Lattner31a09842008-11-12 08:04:58 +0000436 return;
437 }
Chris Lattner552f4c42008-11-12 08:13:36 +0000438 }
Mike Stump1eb44332009-09-09 15:08:12 +0000439
Chris Lattner552f4c42008-11-12 08:13:36 +0000440 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
441 // br(!x, t, f) -> br(x, f, t)
442 if (CondUOp->getOpcode() == UnaryOperator::LNot)
443 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
Chris Lattner31a09842008-11-12 08:04:58 +0000444 }
Mike Stump1eb44332009-09-09 15:08:12 +0000445
Daniel Dunbar09b14892008-11-12 10:30:32 +0000446 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
447 // Handle ?: operator.
448
449 // Just ignore GNU ?: extension.
450 if (CondOp->getLHS()) {
451 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
452 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
453 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
454 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
455 EmitBlock(LHSBlock);
456 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
457 EmitBlock(RHSBlock);
458 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
459 return;
460 }
461 }
462
Chris Lattner31a09842008-11-12 08:04:58 +0000463 // Emit the code with the fully general case.
464 llvm::Value *CondV = EvaluateExprAsBool(Cond);
465 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
466}
467
Daniel Dunbar488e9932008-08-16 00:56:44 +0000468/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000469/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000470void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
471 bool OmitOnError) {
472 CGM.ErrorUnsupported(S, Type, OmitOnError);
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000473}
474
Chris Lattner88207c92009-04-21 17:59:23 +0000475void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty) {
Anders Carlsson0d7c5832010-05-03 01:20:20 +0000476 // Ignore empty classes in C++.
477 if (getContext().getLangOptions().CPlusPlus) {
478 if (const RecordType *RT = Ty->getAs<RecordType>()) {
479 if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
480 return;
481 }
482 }
483
Chris Lattner36afd382009-10-13 06:02:42 +0000484 const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext);
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000485 if (DestPtr->getType() != BP)
486 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
487
488 // Get size and alignment info for this aggregate.
489 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
490
Chris Lattner88207c92009-04-21 17:59:23 +0000491 // Don't bother emitting a zero-byte memset.
492 if (TypeInfo.first == 0)
493 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000494
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000495 // FIXME: Handle variable sized types.
Mike Stump1eb44332009-09-09 15:08:12 +0000496 const llvm::Type *IntPtr = llvm::IntegerType::get(VMContext,
Owen Anderson0032b272009-08-13 21:57:51 +0000497 LLVMPointerWidth);
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000498
Mon P Wang3ecd7852010-04-04 03:10:52 +0000499 Builder.CreateCall5(CGM.getMemSetFn(BP, IntPtr), DestPtr,
Owen Anderson0032b272009-08-13 21:57:51 +0000500 llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext)),
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000501 // TypeInfo.first describes size in bits.
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000502 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
Mike Stump1eb44332009-09-09 15:08:12 +0000503 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Mon P Wang3ecd7852010-04-04 03:10:52 +0000504 TypeInfo.second/8),
505 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext),
506 0));
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000507}
508
Chris Lattnerd9becd12009-10-28 23:59:40 +0000509llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelStmt *L) {
510 // Make sure that there is a block for the indirect goto.
511 if (IndirectBranch == 0)
512 GetIndirectGotoBlock();
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000513
Chris Lattnerd9becd12009-10-28 23:59:40 +0000514 llvm::BasicBlock *BB = getBasicBlockForLabel(L);
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000515
Chris Lattnerd9becd12009-10-28 23:59:40 +0000516 // Make sure the indirect branch includes all of the address-taken blocks.
517 IndirectBranch->addDestination(BB);
518 return llvm::BlockAddress::get(CurFn, BB);
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000519}
520
521llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
Chris Lattnerd9becd12009-10-28 23:59:40 +0000522 // If we already made the indirect branch for indirect goto, return its block.
523 if (IndirectBranch) return IndirectBranch->getParent();
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000524
Chris Lattnerd9becd12009-10-28 23:59:40 +0000525 CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto"));
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000526
Chris Lattnerd9becd12009-10-28 23:59:40 +0000527 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
Chris Lattner85e74ac2009-10-28 20:36:47 +0000528
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000529 // Create the PHI node that indirect gotos will add entries to.
Chris Lattnerd9becd12009-10-28 23:59:40 +0000530 llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, "indirect.goto.dest");
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000531
Chris Lattnerd9becd12009-10-28 23:59:40 +0000532 // Create the indirect branch instruction.
533 IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
534 return IndirectBranch->getParent();
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000535}
Anders Carlssonddf7cac2008-11-04 05:30:00 +0000536
Daniel Dunbard286f052009-07-19 06:58:07 +0000537llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) {
Eli Friedmanbbed6b92009-08-15 02:50:32 +0000538 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
Mike Stump1eb44332009-09-09 15:08:12 +0000539
Anders Carlssonf666b772008-12-20 20:27:15 +0000540 assert(SizeEntry && "Did not emit size for type");
541 return SizeEntry;
542}
Anders Carlssondcc90d82008-12-12 07:19:02 +0000543
Daniel Dunbard286f052009-07-19 06:58:07 +0000544llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) {
Anders Carlsson60d35412008-12-20 20:46:34 +0000545 assert(Ty->isVariablyModifiedType() &&
546 "Must pass variably modified type to EmitVLASizes!");
Mike Stump1eb44332009-09-09 15:08:12 +0000547
Daniel Dunbard286f052009-07-19 06:58:07 +0000548 EnsureInsertPoint();
Mike Stump1eb44332009-09-09 15:08:12 +0000549
Anders Carlsson60d35412008-12-20 20:46:34 +0000550 if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
Eli Friedmanbbed6b92009-08-15 02:50:32 +0000551 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
Mike Stump1eb44332009-09-09 15:08:12 +0000552
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000553 if (!SizeEntry) {
Anders Carlsson96f21472009-02-05 19:43:10 +0000554 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
Mike Stump1eb44332009-09-09 15:08:12 +0000555
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000556 // Get the element size;
557 QualType ElemTy = VAT->getElementType();
558 llvm::Value *ElemSize;
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000559 if (ElemTy->isVariableArrayType())
560 ElemSize = EmitVLASize(ElemTy);
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000561 else
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000562 ElemSize = llvm::ConstantInt::get(SizeTy,
Ken Dyck199c3d62010-01-11 17:06:35 +0000563 getContext().getTypeSizeInChars(ElemTy).getQuantity());
Mike Stump1eb44332009-09-09 15:08:12 +0000564
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000565 llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
Anders Carlsson96f21472009-02-05 19:43:10 +0000566 NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
Mike Stump1eb44332009-09-09 15:08:12 +0000567
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000568 SizeEntry = Builder.CreateMul(ElemSize, NumElements);
Anders Carlsson60d35412008-12-20 20:46:34 +0000569 }
Mike Stump1eb44332009-09-09 15:08:12 +0000570
Anders Carlsson60d35412008-12-20 20:46:34 +0000571 return SizeEntry;
Anders Carlssondcc90d82008-12-12 07:19:02 +0000572 }
Mike Stump1eb44332009-09-09 15:08:12 +0000573
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000574 if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
575 EmitVLASize(AT->getElementType());
576 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000577 }
578
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000579 const PointerType *PT = Ty->getAs<PointerType>();
580 assert(PT && "unknown VM type!");
581 EmitVLASize(PT->getPointeeType());
Anders Carlsson60d35412008-12-20 20:46:34 +0000582 return 0;
Anders Carlssondcc90d82008-12-12 07:19:02 +0000583}
Eli Friedman4fd0aa52009-01-20 17:46:04 +0000584
585llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
586 if (CGM.getContext().getBuiltinVaListType()->isArrayType()) {
587 return EmitScalarExpr(E);
588 }
589 return EmitLValue(E).getAddress();
590}
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000591
Fariborz Jahanian77996212009-11-04 17:57:40 +0000592void CodeGenFunction::PushCleanupBlock(llvm::BasicBlock *CleanupEntryBlock,
Mike Stump99533832009-12-02 07:41:41 +0000593 llvm::BasicBlock *CleanupExitBlock,
Mike Stumpd88ea562009-12-09 03:35:49 +0000594 llvm::BasicBlock *PreviousInvokeDest,
Mike Stump99533832009-12-02 07:41:41 +0000595 bool EHOnly) {
596 CleanupEntries.push_back(CleanupEntry(CleanupEntryBlock, CleanupExitBlock,
Mike Stumpd88ea562009-12-09 03:35:49 +0000597 PreviousInvokeDest, EHOnly));
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000598}
Anders Carlssonc71c8452009-02-07 23:50:39 +0000599
Mike Stump1eb44332009-09-09 15:08:12 +0000600void CodeGenFunction::EmitCleanupBlocks(size_t OldCleanupStackSize) {
601 assert(CleanupEntries.size() >= OldCleanupStackSize &&
Anders Carlssonc71c8452009-02-07 23:50:39 +0000602 "Cleanup stack mismatch!");
Mike Stump1eb44332009-09-09 15:08:12 +0000603
Anders Carlssonc71c8452009-02-07 23:50:39 +0000604 while (CleanupEntries.size() > OldCleanupStackSize)
605 EmitCleanupBlock();
606}
607
Mike Stump1eb44332009-09-09 15:08:12 +0000608CodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock() {
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000609 CleanupEntry &CE = CleanupEntries.back();
Mike Stump1eb44332009-09-09 15:08:12 +0000610
Fariborz Jahanian77996212009-11-04 17:57:40 +0000611 llvm::BasicBlock *CleanupEntryBlock = CE.CleanupEntryBlock;
Mike Stump1eb44332009-09-09 15:08:12 +0000612
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000613 std::vector<llvm::BasicBlock *> Blocks;
614 std::swap(Blocks, CE.Blocks);
Mike Stump1eb44332009-09-09 15:08:12 +0000615
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000616 std::vector<llvm::BranchInst *> BranchFixups;
617 std::swap(BranchFixups, CE.BranchFixups);
Mike Stump1eb44332009-09-09 15:08:12 +0000618
Mike Stump99533832009-12-02 07:41:41 +0000619 bool EHOnly = CE.EHOnly;
620
Mike Stumpd88ea562009-12-09 03:35:49 +0000621 setInvokeDest(CE.PreviousInvokeDest);
622
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000623 CleanupEntries.pop_back();
624
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000625 // Check if any branch fixups pointed to the scope we just popped. If so,
626 // we can remove them.
627 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
628 llvm::BasicBlock *Dest = BranchFixups[i]->getSuccessor(0);
629 BlockScopeMap::iterator I = BlockScopes.find(Dest);
Mike Stump1eb44332009-09-09 15:08:12 +0000630
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000631 if (I == BlockScopes.end())
632 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000633
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000634 assert(I->second <= CleanupEntries.size() && "Invalid branch fixup!");
Mike Stump1eb44332009-09-09 15:08:12 +0000635
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000636 if (I->second == CleanupEntries.size()) {
637 // We don't need to do this branch fixup.
638 BranchFixups[i] = BranchFixups.back();
639 BranchFixups.pop_back();
640 i--;
641 e--;
642 continue;
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000643 }
644 }
Mike Stump1eb44332009-09-09 15:08:12 +0000645
Fariborz Jahanian77996212009-11-04 17:57:40 +0000646 llvm::BasicBlock *SwitchBlock = CE.CleanupExitBlock;
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000647 llvm::BasicBlock *EndBlock = 0;
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000648 if (!BranchFixups.empty()) {
Fariborz Jahanian77996212009-11-04 17:57:40 +0000649 if (!SwitchBlock)
650 SwitchBlock = createBasicBlock("cleanup.switch");
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000651 EndBlock = createBasicBlock("cleanup.end");
Mike Stump1eb44332009-09-09 15:08:12 +0000652
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000653 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
Mike Stump1eb44332009-09-09 15:08:12 +0000654
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000655 Builder.SetInsertPoint(SwitchBlock);
656
Mike Stump99533832009-12-02 07:41:41 +0000657 llvm::Value *DestCodePtr
658 = CreateTempAlloca(llvm::Type::getInt32Ty(VMContext),
659 "cleanup.dst");
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000660 llvm::Value *DestCode = Builder.CreateLoad(DestCodePtr, "tmp");
Mike Stump1eb44332009-09-09 15:08:12 +0000661
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000662 // Create a switch instruction to determine where to jump next.
Mike Stump1eb44332009-09-09 15:08:12 +0000663 llvm::SwitchInst *SI = Builder.CreateSwitch(DestCode, EndBlock,
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000664 BranchFixups.size());
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000665
Anders Carlsson46831a92009-02-08 22:13:37 +0000666 // Restore the current basic block (if any)
Anders Carlsson0ae7b2b2009-03-17 05:53:35 +0000667 if (CurBB) {
Anders Carlsson46831a92009-02-08 22:13:37 +0000668 Builder.SetInsertPoint(CurBB);
Mike Stump1eb44332009-09-09 15:08:12 +0000669
Anders Carlsson0ae7b2b2009-03-17 05:53:35 +0000670 // If we had a current basic block, we also need to emit an instruction
671 // to initialize the cleanup destination.
Owen Anderson0032b272009-08-13 21:57:51 +0000672 Builder.CreateStore(llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)),
Anders Carlsson0ae7b2b2009-03-17 05:53:35 +0000673 DestCodePtr);
674 } else
Anders Carlsson46831a92009-02-08 22:13:37 +0000675 Builder.ClearInsertionPoint();
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000676
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000677 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
678 llvm::BranchInst *BI = BranchFixups[i];
679 llvm::BasicBlock *Dest = BI->getSuccessor(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000680
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000681 // Fixup the branch instruction to point to the cleanup block.
Fariborz Jahanian77996212009-11-04 17:57:40 +0000682 BI->setSuccessor(0, CleanupEntryBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000683
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000684 if (CleanupEntries.empty()) {
Anders Carlssoncc899202009-02-08 22:46:50 +0000685 llvm::ConstantInt *ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000686
Anders Carlssoncc899202009-02-08 22:46:50 +0000687 // Check if we already have a destination for this block.
688 if (Dest == SI->getDefaultDest())
Owen Anderson0032b272009-08-13 21:57:51 +0000689 ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0);
Anders Carlssoncc899202009-02-08 22:46:50 +0000690 else {
691 ID = SI->findCaseDest(Dest);
692 if (!ID) {
693 // No code found, get a new unique one by using the number of
694 // switch successors.
Mike Stump1eb44332009-09-09 15:08:12 +0000695 ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anders Carlssoncc899202009-02-08 22:46:50 +0000696 SI->getNumSuccessors());
697 SI->addCase(ID, Dest);
698 }
699 }
Mike Stump1eb44332009-09-09 15:08:12 +0000700
Anders Carlssoncc899202009-02-08 22:46:50 +0000701 // Store the jump destination before the branch instruction.
702 new llvm::StoreInst(ID, DestCodePtr, BI);
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000703 } else {
704 // We need to jump through another cleanup block. Create a pad block
Mike Stump99533832009-12-02 07:41:41 +0000705 // with a branch instruction that jumps to the final destination and add
706 // it as a branch fixup to the current cleanup scope.
Mike Stump1eb44332009-09-09 15:08:12 +0000707
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000708 // Create the pad block.
709 llvm::BasicBlock *CleanupPad = createBasicBlock("cleanup.pad", CurFn);
Anders Carlssoncc899202009-02-08 22:46:50 +0000710
711 // Create a unique case ID.
Mike Stump99533832009-12-02 07:41:41 +0000712 llvm::ConstantInt *ID
713 = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
714 SI->getNumSuccessors());
Anders Carlssoncc899202009-02-08 22:46:50 +0000715
716 // Store the jump destination before the branch instruction.
717 new llvm::StoreInst(ID, DestCodePtr, BI);
718
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000719 // Add it as the destination.
Anders Carlssoncc899202009-02-08 22:46:50 +0000720 SI->addCase(ID, CleanupPad);
Mike Stump1eb44332009-09-09 15:08:12 +0000721
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000722 // Create the branch to the final destination.
723 llvm::BranchInst *BI = llvm::BranchInst::Create(Dest);
724 CleanupPad->getInstList().push_back(BI);
Mike Stump1eb44332009-09-09 15:08:12 +0000725
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000726 // And add it as a branch fixup.
727 CleanupEntries.back().BranchFixups.push_back(BI);
728 }
729 }
730 }
Mike Stump1eb44332009-09-09 15:08:12 +0000731
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000732 // Remove all blocks from the block scope map.
733 for (size_t i = 0, e = Blocks.size(); i != e; ++i) {
734 assert(BlockScopes.count(Blocks[i]) &&
735 "Did not find block in scope map!");
Mike Stump1eb44332009-09-09 15:08:12 +0000736
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000737 BlockScopes.erase(Blocks[i]);
738 }
Mike Stump1eb44332009-09-09 15:08:12 +0000739
Mike Stump99533832009-12-02 07:41:41 +0000740 return CleanupBlockInfo(CleanupEntryBlock, SwitchBlock, EndBlock, EHOnly);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000741}
742
Mike Stump1eb44332009-09-09 15:08:12 +0000743void CodeGenFunction::EmitCleanupBlock() {
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000744 CleanupBlockInfo Info = PopCleanupBlock();
Mike Stump1eb44332009-09-09 15:08:12 +0000745
Mike Stump99533832009-12-02 07:41:41 +0000746 if (Info.EHOnly) {
747 // FIXME: Add this to the exceptional edge
748 if (Info.CleanupBlock->getNumUses() == 0)
749 delete Info.CleanupBlock;
750 return;
751 }
752
Devang Patelcd9199e2010-04-13 00:08:43 +0000753 // Scrub debug location info.
754 for (llvm::BasicBlock::iterator LBI = Info.CleanupBlock->begin(),
755 LBE = Info.CleanupBlock->end(); LBI != LBE; ++LBI)
756 Builder.SetInstDebugLocation(LBI);
757
Anders Carlssoneb6437a2009-05-31 00:33:20 +0000758 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
Mike Stump1eb44332009-09-09 15:08:12 +0000759 if (CurBB && !CurBB->getTerminator() &&
Anders Carlssoneb6437a2009-05-31 00:33:20 +0000760 Info.CleanupBlock->getNumUses() == 0) {
761 CurBB->getInstList().splice(CurBB->end(), Info.CleanupBlock->getInstList());
762 delete Info.CleanupBlock;
Mike Stump1eb44332009-09-09 15:08:12 +0000763 } else
Anders Carlssoneb6437a2009-05-31 00:33:20 +0000764 EmitBlock(Info.CleanupBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000765
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000766 if (Info.SwitchBlock)
767 EmitBlock(Info.SwitchBlock);
768 if (Info.EndBlock)
769 EmitBlock(Info.EndBlock);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000770}
771
Mike Stump1eb44332009-09-09 15:08:12 +0000772void CodeGenFunction::AddBranchFixup(llvm::BranchInst *BI) {
773 assert(!CleanupEntries.empty() &&
Anders Carlsson87eaf172009-02-08 00:50:42 +0000774 "Trying to add branch fixup without cleanup block!");
Mike Stump1eb44332009-09-09 15:08:12 +0000775
Mike Stumpf5408fe2009-05-16 07:57:57 +0000776 // FIXME: We could be more clever here and check if there's already a branch
777 // fixup for this destination and recycle it.
Anders Carlsson87eaf172009-02-08 00:50:42 +0000778 CleanupEntries.back().BranchFixups.push_back(BI);
779}
780
Mike Stump1eb44332009-09-09 15:08:12 +0000781void CodeGenFunction::EmitBranchThroughCleanup(llvm::BasicBlock *Dest) {
Anders Carlsson46831a92009-02-08 22:13:37 +0000782 if (!HaveInsertPoint())
783 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000784
Anders Carlsson87eaf172009-02-08 00:50:42 +0000785 llvm::BranchInst* BI = Builder.CreateBr(Dest);
Mike Stump1eb44332009-09-09 15:08:12 +0000786
Anders Carlsson46831a92009-02-08 22:13:37 +0000787 Builder.ClearInsertionPoint();
Mike Stump1eb44332009-09-09 15:08:12 +0000788
Anders Carlsson87eaf172009-02-08 00:50:42 +0000789 // The stack is empty, no need to do any cleanup.
790 if (CleanupEntries.empty())
791 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000792
Anders Carlsson87eaf172009-02-08 00:50:42 +0000793 if (!Dest->getParent()) {
794 // We are trying to branch to a block that hasn't been inserted yet.
795 AddBranchFixup(BI);
796 return;
797 }
Mike Stump1eb44332009-09-09 15:08:12 +0000798
Anders Carlsson87eaf172009-02-08 00:50:42 +0000799 BlockScopeMap::iterator I = BlockScopes.find(Dest);
800 if (I == BlockScopes.end()) {
801 // We are trying to jump to a block that is outside of any cleanup scope.
802 AddBranchFixup(BI);
803 return;
804 }
Mike Stump1eb44332009-09-09 15:08:12 +0000805
Anders Carlsson87eaf172009-02-08 00:50:42 +0000806 assert(I->second < CleanupEntries.size() &&
807 "Trying to branch into cleanup region");
Mike Stump1eb44332009-09-09 15:08:12 +0000808
Anders Carlsson87eaf172009-02-08 00:50:42 +0000809 if (I->second == CleanupEntries.size() - 1) {
810 // We have a branch to a block in the same scope.
811 return;
812 }
Mike Stump1eb44332009-09-09 15:08:12 +0000813
Anders Carlsson87eaf172009-02-08 00:50:42 +0000814 AddBranchFixup(BI);
815}