blob: 88f02a9738cfb640b66a390331b7ab286de133ef [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 Stump4e7a1f72009-02-21 20:00:35 +000022#include "llvm/Target/TargetData.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023using namespace clang;
24using namespace CodeGen;
25
Mike Stump1eb44332009-09-09 15:08:12 +000026CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
Mike Stumpa4f668f2009-03-06 01:33:24 +000027 : BlockFunction(cgm, *this, Builder), CGM(cgm),
28 Target(CGM.getContext().Target),
Owen Andersonaac87052009-07-08 20:52:20 +000029 Builder(cgm.getModule().getContext()),
Chris Lattnerd9becd12009-10-28 23:59:40 +000030 DebugInfo(0), IndirectBranch(0),
Chris Lattner3d00fdc2009-10-13 06:55:33 +000031 SwitchInsn(0), CaseRangeBlock(0), InvokeDest(0),
Anders Carlssonf6c56e22009-11-25 03:15:49 +000032 CXXThisDecl(0), CXXVTTDecl(0),
Anders Carlssona36bf8f2009-11-20 17:27:56 +000033 ConditionalBranchLevel(0) {
Mike Stump4e7a1f72009-02-21 20:00:35 +000034 LLVMIntTy = ConvertType(getContext().IntTy);
35 LLVMPointerWidth = Target.getPointerWidth(0);
Chris Lattner41110242008-06-17 18:05:57 +000036}
Reid Spencer5f016e22007-07-11 17:01:13 +000037
38ASTContext &CodeGenFunction::getContext() const {
39 return CGM.getContext();
40}
41
42
43llvm::BasicBlock *CodeGenFunction::getBasicBlockForLabel(const LabelStmt *S) {
44 llvm::BasicBlock *&BB = LabelMap[S];
45 if (BB) return BB;
Mike Stump1eb44332009-09-09 15:08:12 +000046
Reid Spencer5f016e22007-07-11 17:01:13 +000047 // Create, but don't insert, the new block.
Daniel Dunbar55e87422008-11-11 02:29:29 +000048 return BB = createBasicBlock(S->getName());
Reid Spencer5f016e22007-07-11 17:01:13 +000049}
50
Daniel Dunbar0096acf2009-02-25 19:24:29 +000051llvm::Value *CodeGenFunction::GetAddrOfLocalVar(const VarDecl *VD) {
52 llvm::Value *Res = LocalDeclMap[VD];
53 assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!");
54 return Res;
Lauro Ramos Venancio81373352008-02-26 21:41:45 +000055}
Reid Spencer5f016e22007-07-11 17:01:13 +000056
Daniel Dunbar0096acf2009-02-25 19:24:29 +000057llvm::Constant *
58CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) {
59 return cast<llvm::Constant>(GetAddrOfLocalVar(BVD));
Anders Carlssondde0a942008-09-11 09:15:33 +000060}
61
Daniel Dunbar8b1a3432009-02-03 23:03:55 +000062const llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
63 return CGM.getTypes().ConvertTypeForMem(T);
64}
65
Reid Spencer5f016e22007-07-11 17:01:13 +000066const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
67 return CGM.getTypes().ConvertType(T);
68}
69
70bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
Anders Carlssone9d34dc2009-09-29 02:09:01 +000071 return T->isRecordType() || T->isArrayType() || T->isAnyComplexType() ||
72 T->isMemberFunctionPointerType();
Reid Spencer5f016e22007-07-11 17:01:13 +000073}
74
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000075void CodeGenFunction::EmitReturnBlock() {
76 // For cleanliness, we try to avoid emitting the return block for
77 // simple cases.
78 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
79
80 if (CurBB) {
81 assert(!CurBB->getTerminator() && "Unexpected terminated block.");
82
Daniel Dunbar96e18b02009-07-19 08:24:34 +000083 // We have a valid insert point, reuse it if it is empty or there are no
84 // explicit jumps to the return block.
85 if (CurBB->empty() || ReturnBlock->use_empty()) {
86 ReturnBlock->replaceAllUsesWith(CurBB);
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000087 delete ReturnBlock;
Daniel Dunbar96e18b02009-07-19 08:24:34 +000088 } else
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000089 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()) {
Mike Stump1eb44332009-09-09 15:08:12 +000097 llvm::BranchInst *BI =
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000098 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) {
Chris Lattnerda138702007-07-16 21:28:45 +0000116 assert(BreakContinueStack.empty() &&
117 "mismatched push/pop in break/continue stack!");
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000118 assert(BlockScopes.empty() &&
119 "did not remove all blocks from block scope map!");
120 assert(CleanupEntries.empty() &&
121 "mismatched push/pop in cleanup stack!");
Mike Stump1eb44332009-09-09 15:08:12 +0000122
123 // Emit function epilog (to return).
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000124 EmitReturnBlock();
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000125
126 // Emit debug descriptor for function end.
Anders Carlssone896d982009-02-13 08:11:52 +0000127 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000128 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 Lattnerd9becd12009-10-28 23:59:40 +0000134 // If someone did an indirect goto, emit the indirect goto block at the end of
135 // the function.
136 if (IndirectBranch) {
137 EmitBlock(IndirectBranch->getParent());
138 Builder.ClearInsertionPoint();
139 }
140
Chris Lattner5a2fa142007-12-02 06:32:24 +0000141 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
Chris Lattner481769b2009-03-31 22:17:44 +0000142 llvm::Instruction *Ptr = AllocaInsertPt;
Chris Lattner5a2fa142007-12-02 06:32:24 +0000143 AllocaInsertPt = 0;
Chris Lattner481769b2009-03-31 22:17:44 +0000144 Ptr->eraseFromParent();
Chris Lattnerd9becd12009-10-28 23:59:40 +0000145
146 // If someone took the address of a label but never did an indirect goto, we
147 // made a zero entry PHI node, which is illegal, zap it now.
148 if (IndirectBranch) {
149 llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
150 if (PN->getNumIncomingValues() == 0) {
151 PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
152 PN->eraseFromParent();
153 }
154 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000155}
156
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000157void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
Daniel Dunbar7c086512008-09-09 23:14:03 +0000158 llvm::Function *Fn,
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000159 const FunctionArgList &Args,
160 SourceLocation StartLoc) {
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000161 const Decl *D = GD.getDecl();
162
Anders Carlsson4cc1a472009-02-09 20:20:56 +0000163 DidCallStackSave = false;
Chris Lattnerb5437d22009-04-23 05:30:27 +0000164 CurCodeDecl = CurFuncDecl = D;
Daniel Dunbar7c086512008-09-09 23:14:03 +0000165 FnRetTy = RetTy;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000166 CurFn = Fn;
Chris Lattner41110242008-06-17 18:05:57 +0000167 assert(CurFn->isDeclaration() && "Function already has body?");
168
Daniel Dunbar55e87422008-11-11 02:29:29 +0000169 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000170
Chris Lattner41110242008-06-17 18:05:57 +0000171 // Create a marker to make it easy to insert allocas into the entryblock
172 // later. Don't create this with the builder, because we don't want it
173 // folded.
Owen Anderson0032b272009-08-13 21:57:51 +0000174 llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::getInt32Ty(VMContext));
Mike Stumpbcdc0f02009-09-25 18:11:00 +0000175 AllocaInsertPt = new llvm::BitCastInst(Undef,
176 llvm::Type::getInt32Ty(VMContext), "",
Chris Lattner41110242008-06-17 18:05:57 +0000177 EntryBB);
Chris Lattnerf1466842009-03-22 00:24:14 +0000178 if (Builder.isNamePreserving())
179 AllocaInsertPt->setName("allocapt");
Mike Stump1eb44332009-09-09 15:08:12 +0000180
Daniel Dunbar55e87422008-11-11 02:29:29 +0000181 ReturnBlock = createBasicBlock("return");
Mike Stump1eb44332009-09-09 15:08:12 +0000182
Chris Lattner41110242008-06-17 18:05:57 +0000183 Builder.SetInsertPoint(EntryBB);
Mike Stump1eb44332009-09-09 15:08:12 +0000184
Mike Stump91cc8152009-10-23 01:52:13 +0000185 QualType FnType = getContext().getFunctionType(RetTy, 0, 0, false, 0);
186
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000187 // Emit subprogram debug descriptor.
Daniel Dunbar7c086512008-09-09 23:14:03 +0000188 // FIXME: The cast here is a huge hack.
Anders Carlssone896d982009-02-13 08:11:52 +0000189 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000190 DI->setLocation(StartLoc);
Anders Carlsson1860a312009-09-11 00:11:35 +0000191 if (isa<FunctionDecl>(D)) {
Mike Stump91cc8152009-10-23 01:52:13 +0000192 DI->EmitFunctionStart(CGM.getMangledName(GD), FnType, CurFn, Builder);
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000193 } else {
194 // Just use LLVM function name.
Mike Stump1eb44332009-09-09 15:08:12 +0000195
Daniel Dunbar42719fc2009-07-23 05:30:36 +0000196 // FIXME: Remove unnecessary conversion to std::string when API settles.
Mike Stump1eb44332009-09-09 15:08:12 +0000197 DI->EmitFunctionStart(std::string(Fn->getName()).c_str(),
Mike Stump91cc8152009-10-23 01:52:13 +0000198 FnType, CurFn, Builder);
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000199 }
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000200 }
201
Daniel Dunbar88b53962009-02-02 22:03:45 +0000202 // FIXME: Leaked.
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000203 CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args);
Eli Friedmanb17daf92009-12-04 02:43:40 +0000204
205 if (RetTy->isVoidType()) {
206 // Void type; nothing to return.
207 ReturnValue = 0;
208 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
209 hasAggregateLLVMType(CurFnInfo->getReturnType())) {
210 // Indirect aggregate return; emit returned value directly into sret slot.
211 // This reduces code size, and is also affects correctness in C++.
212 ReturnValue = CurFn->arg_begin();
213 } else {
214 ReturnValue = CreateTempAlloca(ConvertType(RetTy), "retval");
215 }
216
Daniel Dunbar88b53962009-02-02 22:03:45 +0000217 EmitFunctionProlog(*CurFnInfo, CurFn, Args);
Mike Stump1eb44332009-09-09 15:08:12 +0000218
Anders Carlsson751358f2008-12-20 21:28:43 +0000219 // If any of the arguments have a variably modified type, make sure to
220 // emit the type size.
221 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
222 i != e; ++i) {
223 QualType Ty = i->second;
224
225 if (Ty->isVariablyModifiedType())
226 EmitVLASize(Ty);
227 }
Daniel Dunbar7c086512008-09-09 23:14:03 +0000228}
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000229
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000230static bool NeedsVTTParameter(GlobalDecl GD) {
231 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
232
233 // We don't have any virtual bases, just return early.
234 if (!MD->getParent()->getNumVBases())
235 return false;
236
237 // Check if we have a base constructor.
238 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
239 return true;
240
241 // Check if we have a base destructor.
242 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
243 return true;
244
245 return false;
246}
247
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000248void CodeGenFunction::GenerateCode(GlobalDecl GD,
Daniel Dunbar7c086512008-09-09 23:14:03 +0000249 llvm::Function *Fn) {
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000250 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
251
Anders Carlssone896d982009-02-13 08:11:52 +0000252 // Check if we should generate debug info for this function.
Mike Stump1feade82009-08-26 22:31:08 +0000253 if (CGM.getDebugInfo() && !FD->hasAttr<NoDebugAttr>())
Anders Carlssone896d982009-02-13 08:11:52 +0000254 DebugInfo = CGM.getDebugInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000255
Daniel Dunbar7c086512008-09-09 23:14:03 +0000256 FunctionArgList Args;
Mike Stump1eb44332009-09-09 15:08:12 +0000257
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000258 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
259 if (MD->isInstance()) {
260 // Create the implicit 'this' decl.
261 // FIXME: I'm not entirely sure I like using a fake decl just for code
262 // generation. Maybe we can come up with a better way?
263 CXXThisDecl = ImplicitParamDecl::Create(getContext(), 0, SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +0000264 &getContext().Idents.get("this"),
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000265 MD->getThisType(getContext()));
266 Args.push_back(std::make_pair(CXXThisDecl, CXXThisDecl->getType()));
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000267
268 // Check if we need a VTT parameter as well.
269 if (NeedsVTTParameter(GD)) {
270 // FIXME: The comment about using a fake decl above applies here too.
271 QualType T = getContext().getPointerType(getContext().VoidPtrTy);
272 CXXVTTDecl =
273 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(),
274 &getContext().Idents.get("vtt"), T);
275 Args.push_back(std::make_pair(CXXVTTDecl, CXXVTTDecl->getType()));
276 }
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000277 }
278 }
Mike Stump1eb44332009-09-09 15:08:12 +0000279
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000280 if (FD->getNumParams()) {
John McCall183700f2009-09-21 23:43:11 +0000281 const FunctionProtoType* FProto = FD->getType()->getAs<FunctionProtoType>();
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000282 assert(FProto && "Function def must have prototype!");
Daniel Dunbar7c086512008-09-09 23:14:03 +0000283
284 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
Mike Stump1eb44332009-09-09 15:08:12 +0000285 Args.push_back(std::make_pair(FD->getParamDecl(i),
Daniel Dunbar7c086512008-09-09 23:14:03 +0000286 FProto->getArgType(i)));
Chris Lattner41110242008-06-17 18:05:57 +0000287 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000288
Sebastian Redld3a413d2009-04-26 20:35:05 +0000289 // FIXME: Support CXXTryStmt here, too.
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000290 if (const CompoundStmt *S = FD->getCompoundBody()) {
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000291 StartFunction(GD, FD->getResultType(), Fn, Args, S->getLBracLoc());
Anders Carlsson4365bba2009-11-06 02:55:43 +0000292
293 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlssonde1d26b2009-09-14 05:32:02 +0000294 EmitCtorPrologue(CD, GD.getCtorType());
Anders Carlsson4365bba2009-11-06 02:55:43 +0000295 EmitStmt(S);
Anders Carlsson5e1b9182009-11-06 04:19:02 +0000296
297 // If any of the member initializers are temporaries bound to references
298 // make sure to emit their destructors.
299 EmitCleanupBlocks(0);
300
Anders Carlsson4365bba2009-11-06 02:55:43 +0000301 } else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD)) {
302 llvm::BasicBlock *DtorEpilogue = createBasicBlock("dtor.epilogue");
303 PushCleanupBlock(DtorEpilogue);
304
305 EmitStmt(S);
Anders Carlssonc33e4ba2009-10-06 18:09:57 +0000306
Anders Carlssonc33e4ba2009-10-06 18:09:57 +0000307 CleanupBlockInfo Info = PopCleanupBlock();
308
309 assert(Info.CleanupBlock == DtorEpilogue && "Block mismatch!");
310 EmitBlock(DtorEpilogue);
Anders Carlssonde1d26b2009-09-14 05:32:02 +0000311 EmitDtorEpilogue(DD, GD.getDtorType());
Anders Carlssonc33e4ba2009-10-06 18:09:57 +0000312
313 if (Info.SwitchBlock)
314 EmitBlock(Info.SwitchBlock);
315 if (Info.EndBlock)
316 EmitBlock(Info.EndBlock);
Anders Carlsson4365bba2009-11-06 02:55:43 +0000317 } else {
318 // Just a regular function, emit its body.
319 EmitStmt(S);
Anders Carlssonc33e4ba2009-10-06 18:09:57 +0000320 }
Anders Carlsson4365bba2009-11-06 02:55:43 +0000321
Sebastian Redld3a413d2009-04-26 20:35:05 +0000322 FinishFunction(S->getRBracLoc());
Douglas Gregor45132722009-10-01 20:44:19 +0000323 } else if (FD->isImplicit()) {
324 const CXXRecordDecl *ClassDecl =
325 cast<CXXRecordDecl>(FD->getDeclContext());
326 (void) ClassDecl;
Fariborz Jahanianc7ff8e12009-07-30 23:22:00 +0000327 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
Douglas Gregor45132722009-10-01 20:44:19 +0000328 // FIXME: For C++0x, we want to look for implicit *definitions* of
329 // these special member functions, rather than implicit *declarations*.
Fariborz Jahanian98896522009-08-06 23:38:16 +0000330 if (CD->isCopyConstructor(getContext())) {
331 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
Douglas Gregor45132722009-10-01 20:44:19 +0000332 "Cannot synthesize a non-implicit copy constructor");
Anders Carlssonde1d26b2009-09-14 05:32:02 +0000333 SynthesizeCXXCopyConstructor(CD, GD.getCtorType(), Fn, Args);
Douglas Gregor45132722009-10-01 20:44:19 +0000334 } else if (CD->isDefaultConstructor()) {
Fariborz Jahanian98896522009-08-06 23:38:16 +0000335 assert(!ClassDecl->hasUserDeclaredConstructor() &&
Douglas Gregor45132722009-10-01 20:44:19 +0000336 "Cannot synthesize a non-implicit default constructor.");
Anders Carlssonde1d26b2009-09-14 05:32:02 +0000337 SynthesizeDefaultConstructor(CD, GD.getCtorType(), Fn, Args);
Douglas Gregor45132722009-10-01 20:44:19 +0000338 } else {
339 assert(false && "Implicit constructor cannot be synthesized");
Fariborz Jahanian98896522009-08-06 23:38:16 +0000340 }
Douglas Gregor45132722009-10-01 20:44:19 +0000341 } else if (const CXXDestructorDecl *CD = dyn_cast<CXXDestructorDecl>(FD)) {
342 assert(!ClassDecl->hasUserDeclaredDestructor() &&
343 "Cannot synthesize a non-implicit destructor");
344 SynthesizeDefaultDestructor(CD, GD.getDtorType(), Fn, Args);
345 } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
346 assert(MD->isCopyAssignment() &&
347 !ClassDecl->hasUserDeclaredCopyAssignment() &&
348 "Cannot synthesize a method that is not an implicit-defined "
349 "copy constructor");
Anders Carlssonde1d26b2009-09-14 05:32:02 +0000350 SynthesizeCXXCopyAssignment(MD, Fn, Args);
Douglas Gregor45132722009-10-01 20:44:19 +0000351 } else {
352 assert(false && "Cannot synthesize unknown implicit function");
353 }
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000354 }
Mike Stump1eb44332009-09-09 15:08:12 +0000355
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000356 // Destroy the 'this' declaration.
357 if (CXXThisDecl)
358 CXXThisDecl->Destroy(getContext());
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000359
360 // Destroy the VTT declaration.
361 if (CXXVTTDecl)
362 CXXVTTDecl->Destroy(getContext());
Chris Lattner41110242008-06-17 18:05:57 +0000363}
364
Chris Lattner0946ccd2008-11-11 07:41:27 +0000365/// ContainsLabel - Return true if the statement contains a label in it. If
366/// this statement is not executed normally, it not containing a label means
367/// that we can just remove the code.
368bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
369 // Null statement, not a label!
370 if (S == 0) return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000371
Chris Lattner0946ccd2008-11-11 07:41:27 +0000372 // If this is a label, we have to emit the code, consider something like:
373 // if (0) { ... foo: bar(); } goto foo;
374 if (isa<LabelStmt>(S))
375 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000376
Chris Lattner0946ccd2008-11-11 07:41:27 +0000377 // If this is a case/default statement, and we haven't seen a switch, we have
378 // to emit the code.
379 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
380 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000381
Chris Lattner0946ccd2008-11-11 07:41:27 +0000382 // If this is a switch statement, we want to ignore cases below it.
383 if (isa<SwitchStmt>(S))
384 IgnoreCaseStmts = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000385
Chris Lattner0946ccd2008-11-11 07:41:27 +0000386 // Scan subexpressions for verboten labels.
387 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
388 I != E; ++I)
389 if (ContainsLabel(*I, IgnoreCaseStmts))
390 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000391
Chris Lattner0946ccd2008-11-11 07:41:27 +0000392 return false;
393}
394
Chris Lattner31a09842008-11-12 08:04:58 +0000395
396/// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
397/// a constant, or if it does but contains a label, return 0. If it constant
398/// folds to 'true' and does not contain a label, return 1, if it constant folds
399/// to 'false' and does not contain a label, return -1.
400int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
Daniel Dunbar36bc14c2008-11-12 22:37:10 +0000401 // FIXME: Rename and handle conversion of other evaluatable things
402 // to bool.
Anders Carlsson64712f12008-12-01 02:46:24 +0000403 Expr::EvalResult Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000404 if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
Anders Carlsson64712f12008-12-01 02:46:24 +0000405 Result.HasSideEffects)
Anders Carlssonef5a66d2008-11-22 22:32:07 +0000406 return 0; // Not foldable, not integer or not fully evaluatable.
Mike Stump1eb44332009-09-09 15:08:12 +0000407
Chris Lattner31a09842008-11-12 08:04:58 +0000408 if (CodeGenFunction::ContainsLabel(Cond))
409 return 0; // Contains a label.
Mike Stump1eb44332009-09-09 15:08:12 +0000410
Anders Carlsson64712f12008-12-01 02:46:24 +0000411 return Result.Val.getInt().getBoolValue() ? 1 : -1;
Chris Lattner31a09842008-11-12 08:04:58 +0000412}
413
414
415/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
416/// statement) to the specified blocks. Based on the condition, this might try
417/// to simplify the codegen of the conditional based on the branch.
418///
419void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
420 llvm::BasicBlock *TrueBlock,
421 llvm::BasicBlock *FalseBlock) {
422 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
423 return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000424
Chris Lattner31a09842008-11-12 08:04:58 +0000425 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
426 // Handle X && Y in a condition.
427 if (CondBOp->getOpcode() == BinaryOperator::LAnd) {
428 // If we have "1 && X", simplify the code. "0 && X" would have constant
429 // folded if the case was simple enough.
430 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
431 // br(1 && X) -> br(X).
432 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
433 }
Mike Stump1eb44332009-09-09 15:08:12 +0000434
Chris Lattner31a09842008-11-12 08:04:58 +0000435 // If we have "X && 1", simplify the code to use an uncond branch.
436 // "X && 0" would have been constant folded to 0.
437 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
438 // br(X && 1) -> br(X).
439 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
440 }
Mike Stump1eb44332009-09-09 15:08:12 +0000441
Chris Lattner31a09842008-11-12 08:04:58 +0000442 // Emit the LHS as a conditional. If the LHS conditional is false, we
443 // want to jump to the FalseBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000444 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
Chris Lattner31a09842008-11-12 08:04:58 +0000445 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
446 EmitBlock(LHSTrue);
Mike Stump1eb44332009-09-09 15:08:12 +0000447
Chris Lattner31a09842008-11-12 08:04:58 +0000448 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
449 return;
450 } else if (CondBOp->getOpcode() == BinaryOperator::LOr) {
451 // If we have "0 || X", simplify the code. "1 || X" would have constant
452 // folded if the case was simple enough.
453 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
454 // br(0 || X) -> br(X).
455 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
456 }
Mike Stump1eb44332009-09-09 15:08:12 +0000457
Chris Lattner31a09842008-11-12 08:04:58 +0000458 // If we have "X || 0", simplify the code to use an uncond branch.
459 // "X || 1" would have been constant folded to 1.
460 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
461 // br(X || 0) -> br(X).
462 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
463 }
Mike Stump1eb44332009-09-09 15:08:12 +0000464
Chris Lattner31a09842008-11-12 08:04:58 +0000465 // Emit the LHS as a conditional. If the LHS conditional is true, we
466 // want to jump to the TrueBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000467 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
Chris Lattner31a09842008-11-12 08:04:58 +0000468 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
469 EmitBlock(LHSFalse);
Mike Stump1eb44332009-09-09 15:08:12 +0000470
Chris Lattner31a09842008-11-12 08:04:58 +0000471 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
472 return;
473 }
Chris Lattner552f4c42008-11-12 08:13:36 +0000474 }
Mike Stump1eb44332009-09-09 15:08:12 +0000475
Chris Lattner552f4c42008-11-12 08:13:36 +0000476 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
477 // br(!x, t, f) -> br(x, f, t)
478 if (CondUOp->getOpcode() == UnaryOperator::LNot)
479 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
Chris Lattner31a09842008-11-12 08:04:58 +0000480 }
Mike Stump1eb44332009-09-09 15:08:12 +0000481
Daniel Dunbar09b14892008-11-12 10:30:32 +0000482 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
483 // Handle ?: operator.
484
485 // Just ignore GNU ?: extension.
486 if (CondOp->getLHS()) {
487 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
488 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
489 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
490 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
491 EmitBlock(LHSBlock);
492 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
493 EmitBlock(RHSBlock);
494 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
495 return;
496 }
497 }
498
Chris Lattner31a09842008-11-12 08:04:58 +0000499 // Emit the code with the fully general case.
500 llvm::Value *CondV = EvaluateExprAsBool(Cond);
501 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
502}
503
Daniel Dunbar488e9932008-08-16 00:56:44 +0000504/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000505/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000506void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
507 bool OmitOnError) {
508 CGM.ErrorUnsupported(S, Type, OmitOnError);
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000509}
510
Chris Lattner88207c92009-04-21 17:59:23 +0000511void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty) {
Chris Lattner36afd382009-10-13 06:02:42 +0000512 const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext);
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000513 if (DestPtr->getType() != BP)
514 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
515
516 // Get size and alignment info for this aggregate.
517 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
518
Chris Lattner88207c92009-04-21 17:59:23 +0000519 // Don't bother emitting a zero-byte memset.
520 if (TypeInfo.first == 0)
521 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000522
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000523 // FIXME: Handle variable sized types.
Mike Stump1eb44332009-09-09 15:08:12 +0000524 const llvm::Type *IntPtr = llvm::IntegerType::get(VMContext,
Owen Anderson0032b272009-08-13 21:57:51 +0000525 LLVMPointerWidth);
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000526
527 Builder.CreateCall4(CGM.getMemSetFn(), DestPtr,
Owen Anderson0032b272009-08-13 21:57:51 +0000528 llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext)),
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000529 // TypeInfo.first describes size in bits.
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000530 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
Mike Stump1eb44332009-09-09 15:08:12 +0000531 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000532 TypeInfo.second/8));
533}
534
Chris Lattnerd9becd12009-10-28 23:59:40 +0000535llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelStmt *L) {
536 // Make sure that there is a block for the indirect goto.
537 if (IndirectBranch == 0)
538 GetIndirectGotoBlock();
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000539
Chris Lattnerd9becd12009-10-28 23:59:40 +0000540 llvm::BasicBlock *BB = getBasicBlockForLabel(L);
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000541
Chris Lattnerd9becd12009-10-28 23:59:40 +0000542 // Make sure the indirect branch includes all of the address-taken blocks.
543 IndirectBranch->addDestination(BB);
544 return llvm::BlockAddress::get(CurFn, BB);
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000545}
546
547llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
Chris Lattnerd9becd12009-10-28 23:59:40 +0000548 // If we already made the indirect branch for indirect goto, return its block.
549 if (IndirectBranch) return IndirectBranch->getParent();
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000550
Chris Lattnerd9becd12009-10-28 23:59:40 +0000551 CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto"));
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000552
Chris Lattnerd9becd12009-10-28 23:59:40 +0000553 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
Chris Lattner85e74ac2009-10-28 20:36:47 +0000554
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000555 // Create the PHI node that indirect gotos will add entries to.
Chris Lattnerd9becd12009-10-28 23:59:40 +0000556 llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, "indirect.goto.dest");
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000557
Chris Lattnerd9becd12009-10-28 23:59:40 +0000558 // Create the indirect branch instruction.
559 IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
560 return IndirectBranch->getParent();
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000561}
Anders Carlssonddf7cac2008-11-04 05:30:00 +0000562
Daniel Dunbard286f052009-07-19 06:58:07 +0000563llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) {
Eli Friedmanbbed6b92009-08-15 02:50:32 +0000564 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
Mike Stump1eb44332009-09-09 15:08:12 +0000565
Anders Carlssonf666b772008-12-20 20:27:15 +0000566 assert(SizeEntry && "Did not emit size for type");
567 return SizeEntry;
568}
Anders Carlssondcc90d82008-12-12 07:19:02 +0000569
Daniel Dunbard286f052009-07-19 06:58:07 +0000570llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) {
Anders Carlsson60d35412008-12-20 20:46:34 +0000571 assert(Ty->isVariablyModifiedType() &&
572 "Must pass variably modified type to EmitVLASizes!");
Mike Stump1eb44332009-09-09 15:08:12 +0000573
Daniel Dunbard286f052009-07-19 06:58:07 +0000574 EnsureInsertPoint();
Mike Stump1eb44332009-09-09 15:08:12 +0000575
Anders Carlsson60d35412008-12-20 20:46:34 +0000576 if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
Eli Friedmanbbed6b92009-08-15 02:50:32 +0000577 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
Mike Stump1eb44332009-09-09 15:08:12 +0000578
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000579 if (!SizeEntry) {
Anders Carlsson96f21472009-02-05 19:43:10 +0000580 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
Mike Stump1eb44332009-09-09 15:08:12 +0000581
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000582 // Get the element size;
583 QualType ElemTy = VAT->getElementType();
584 llvm::Value *ElemSize;
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000585 if (ElemTy->isVariableArrayType())
586 ElemSize = EmitVLASize(ElemTy);
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000587 else
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000588 ElemSize = llvm::ConstantInt::get(SizeTy,
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000589 getContext().getTypeSize(ElemTy) / 8);
Mike Stump1eb44332009-09-09 15:08:12 +0000590
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000591 llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
Anders Carlsson96f21472009-02-05 19:43:10 +0000592 NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
Mike Stump1eb44332009-09-09 15:08:12 +0000593
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000594 SizeEntry = Builder.CreateMul(ElemSize, NumElements);
Anders Carlsson60d35412008-12-20 20:46:34 +0000595 }
Mike Stump1eb44332009-09-09 15:08:12 +0000596
Anders Carlsson60d35412008-12-20 20:46:34 +0000597 return SizeEntry;
Anders Carlssondcc90d82008-12-12 07:19:02 +0000598 }
Mike Stump1eb44332009-09-09 15:08:12 +0000599
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000600 if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
601 EmitVLASize(AT->getElementType());
602 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000603 }
604
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000605 const PointerType *PT = Ty->getAs<PointerType>();
606 assert(PT && "unknown VM type!");
607 EmitVLASize(PT->getPointeeType());
Anders Carlsson60d35412008-12-20 20:46:34 +0000608 return 0;
Anders Carlssondcc90d82008-12-12 07:19:02 +0000609}
Eli Friedman4fd0aa52009-01-20 17:46:04 +0000610
611llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
612 if (CGM.getContext().getBuiltinVaListType()->isArrayType()) {
613 return EmitScalarExpr(E);
614 }
615 return EmitLValue(E).getAddress();
616}
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000617
Fariborz Jahanian77996212009-11-04 17:57:40 +0000618void CodeGenFunction::PushCleanupBlock(llvm::BasicBlock *CleanupEntryBlock,
Mike Stump99533832009-12-02 07:41:41 +0000619 llvm::BasicBlock *CleanupExitBlock,
620 bool EHOnly) {
621 CleanupEntries.push_back(CleanupEntry(CleanupEntryBlock, CleanupExitBlock,
622 EHOnly));
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000623}
Anders Carlssonc71c8452009-02-07 23:50:39 +0000624
Mike Stump1eb44332009-09-09 15:08:12 +0000625void CodeGenFunction::EmitCleanupBlocks(size_t OldCleanupStackSize) {
626 assert(CleanupEntries.size() >= OldCleanupStackSize &&
Anders Carlssonc71c8452009-02-07 23:50:39 +0000627 "Cleanup stack mismatch!");
Mike Stump1eb44332009-09-09 15:08:12 +0000628
Anders Carlssonc71c8452009-02-07 23:50:39 +0000629 while (CleanupEntries.size() > OldCleanupStackSize)
630 EmitCleanupBlock();
631}
632
Mike Stump1eb44332009-09-09 15:08:12 +0000633CodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock() {
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000634 CleanupEntry &CE = CleanupEntries.back();
Mike Stump1eb44332009-09-09 15:08:12 +0000635
Fariborz Jahanian77996212009-11-04 17:57:40 +0000636 llvm::BasicBlock *CleanupEntryBlock = CE.CleanupEntryBlock;
Mike Stump1eb44332009-09-09 15:08:12 +0000637
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000638 std::vector<llvm::BasicBlock *> Blocks;
639 std::swap(Blocks, CE.Blocks);
Mike Stump1eb44332009-09-09 15:08:12 +0000640
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000641 std::vector<llvm::BranchInst *> BranchFixups;
642 std::swap(BranchFixups, CE.BranchFixups);
Mike Stump1eb44332009-09-09 15:08:12 +0000643
Mike Stump99533832009-12-02 07:41:41 +0000644 bool EHOnly = CE.EHOnly;
645
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000646 CleanupEntries.pop_back();
647
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000648 // Check if any branch fixups pointed to the scope we just popped. If so,
649 // we can remove them.
650 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
651 llvm::BasicBlock *Dest = BranchFixups[i]->getSuccessor(0);
652 BlockScopeMap::iterator I = BlockScopes.find(Dest);
Mike Stump1eb44332009-09-09 15:08:12 +0000653
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000654 if (I == BlockScopes.end())
655 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000656
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000657 assert(I->second <= CleanupEntries.size() && "Invalid branch fixup!");
Mike Stump1eb44332009-09-09 15:08:12 +0000658
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000659 if (I->second == CleanupEntries.size()) {
660 // We don't need to do this branch fixup.
661 BranchFixups[i] = BranchFixups.back();
662 BranchFixups.pop_back();
663 i--;
664 e--;
665 continue;
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000666 }
667 }
Mike Stump1eb44332009-09-09 15:08:12 +0000668
Fariborz Jahanian77996212009-11-04 17:57:40 +0000669 llvm::BasicBlock *SwitchBlock = CE.CleanupExitBlock;
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000670 llvm::BasicBlock *EndBlock = 0;
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000671 if (!BranchFixups.empty()) {
Fariborz Jahanian77996212009-11-04 17:57:40 +0000672 if (!SwitchBlock)
673 SwitchBlock = createBasicBlock("cleanup.switch");
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000674 EndBlock = createBasicBlock("cleanup.end");
Mike Stump1eb44332009-09-09 15:08:12 +0000675
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000676 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
Mike Stump1eb44332009-09-09 15:08:12 +0000677
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000678 Builder.SetInsertPoint(SwitchBlock);
679
Mike Stump99533832009-12-02 07:41:41 +0000680 llvm::Value *DestCodePtr
681 = CreateTempAlloca(llvm::Type::getInt32Ty(VMContext),
682 "cleanup.dst");
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000683 llvm::Value *DestCode = Builder.CreateLoad(DestCodePtr, "tmp");
Mike Stump1eb44332009-09-09 15:08:12 +0000684
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000685 // Create a switch instruction to determine where to jump next.
Mike Stump1eb44332009-09-09 15:08:12 +0000686 llvm::SwitchInst *SI = Builder.CreateSwitch(DestCode, EndBlock,
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000687 BranchFixups.size());
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000688
Anders Carlsson46831a92009-02-08 22:13:37 +0000689 // Restore the current basic block (if any)
Anders Carlsson0ae7b2b2009-03-17 05:53:35 +0000690 if (CurBB) {
Anders Carlsson46831a92009-02-08 22:13:37 +0000691 Builder.SetInsertPoint(CurBB);
Mike Stump1eb44332009-09-09 15:08:12 +0000692
Anders Carlsson0ae7b2b2009-03-17 05:53:35 +0000693 // If we had a current basic block, we also need to emit an instruction
694 // to initialize the cleanup destination.
Owen Anderson0032b272009-08-13 21:57:51 +0000695 Builder.CreateStore(llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)),
Anders Carlsson0ae7b2b2009-03-17 05:53:35 +0000696 DestCodePtr);
697 } else
Anders Carlsson46831a92009-02-08 22:13:37 +0000698 Builder.ClearInsertionPoint();
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000699
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000700 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
701 llvm::BranchInst *BI = BranchFixups[i];
702 llvm::BasicBlock *Dest = BI->getSuccessor(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000703
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000704 // Fixup the branch instruction to point to the cleanup block.
Fariborz Jahanian77996212009-11-04 17:57:40 +0000705 BI->setSuccessor(0, CleanupEntryBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000706
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000707 if (CleanupEntries.empty()) {
Anders Carlssoncc899202009-02-08 22:46:50 +0000708 llvm::ConstantInt *ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000709
Anders Carlssoncc899202009-02-08 22:46:50 +0000710 // Check if we already have a destination for this block.
711 if (Dest == SI->getDefaultDest())
Owen Anderson0032b272009-08-13 21:57:51 +0000712 ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0);
Anders Carlssoncc899202009-02-08 22:46:50 +0000713 else {
714 ID = SI->findCaseDest(Dest);
715 if (!ID) {
716 // No code found, get a new unique one by using the number of
717 // switch successors.
Mike Stump1eb44332009-09-09 15:08:12 +0000718 ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anders Carlssoncc899202009-02-08 22:46:50 +0000719 SI->getNumSuccessors());
720 SI->addCase(ID, Dest);
721 }
722 }
Mike Stump1eb44332009-09-09 15:08:12 +0000723
Anders Carlssoncc899202009-02-08 22:46:50 +0000724 // Store the jump destination before the branch instruction.
725 new llvm::StoreInst(ID, DestCodePtr, BI);
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000726 } else {
727 // We need to jump through another cleanup block. Create a pad block
Mike Stump99533832009-12-02 07:41:41 +0000728 // with a branch instruction that jumps to the final destination and add
729 // it as a branch fixup to the current cleanup scope.
Mike Stump1eb44332009-09-09 15:08:12 +0000730
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000731 // Create the pad block.
732 llvm::BasicBlock *CleanupPad = createBasicBlock("cleanup.pad", CurFn);
Anders Carlssoncc899202009-02-08 22:46:50 +0000733
734 // Create a unique case ID.
Mike Stump99533832009-12-02 07:41:41 +0000735 llvm::ConstantInt *ID
736 = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
737 SI->getNumSuccessors());
Anders Carlssoncc899202009-02-08 22:46:50 +0000738
739 // Store the jump destination before the branch instruction.
740 new llvm::StoreInst(ID, DestCodePtr, BI);
741
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000742 // Add it as the destination.
Anders Carlssoncc899202009-02-08 22:46:50 +0000743 SI->addCase(ID, CleanupPad);
Mike Stump1eb44332009-09-09 15:08:12 +0000744
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000745 // Create the branch to the final destination.
746 llvm::BranchInst *BI = llvm::BranchInst::Create(Dest);
747 CleanupPad->getInstList().push_back(BI);
Mike Stump1eb44332009-09-09 15:08:12 +0000748
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000749 // And add it as a branch fixup.
750 CleanupEntries.back().BranchFixups.push_back(BI);
751 }
752 }
753 }
Mike Stump1eb44332009-09-09 15:08:12 +0000754
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000755 // Remove all blocks from the block scope map.
756 for (size_t i = 0, e = Blocks.size(); i != e; ++i) {
757 assert(BlockScopes.count(Blocks[i]) &&
758 "Did not find block in scope map!");
Mike Stump1eb44332009-09-09 15:08:12 +0000759
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000760 BlockScopes.erase(Blocks[i]);
761 }
Mike Stump1eb44332009-09-09 15:08:12 +0000762
Mike Stump99533832009-12-02 07:41:41 +0000763 return CleanupBlockInfo(CleanupEntryBlock, SwitchBlock, EndBlock, EHOnly);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000764}
765
Mike Stump1eb44332009-09-09 15:08:12 +0000766void CodeGenFunction::EmitCleanupBlock() {
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000767 CleanupBlockInfo Info = PopCleanupBlock();
Mike Stump1eb44332009-09-09 15:08:12 +0000768
Mike Stump99533832009-12-02 07:41:41 +0000769 if (Info.EHOnly) {
770 // FIXME: Add this to the exceptional edge
771 if (Info.CleanupBlock->getNumUses() == 0)
772 delete Info.CleanupBlock;
773 return;
774 }
775
Anders Carlssoneb6437a2009-05-31 00:33:20 +0000776 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
Mike Stump1eb44332009-09-09 15:08:12 +0000777 if (CurBB && !CurBB->getTerminator() &&
Anders Carlssoneb6437a2009-05-31 00:33:20 +0000778 Info.CleanupBlock->getNumUses() == 0) {
779 CurBB->getInstList().splice(CurBB->end(), Info.CleanupBlock->getInstList());
780 delete Info.CleanupBlock;
Mike Stump1eb44332009-09-09 15:08:12 +0000781 } else
Anders Carlssoneb6437a2009-05-31 00:33:20 +0000782 EmitBlock(Info.CleanupBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000783
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000784 if (Info.SwitchBlock)
785 EmitBlock(Info.SwitchBlock);
786 if (Info.EndBlock)
787 EmitBlock(Info.EndBlock);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000788}
789
Mike Stump1eb44332009-09-09 15:08:12 +0000790void CodeGenFunction::AddBranchFixup(llvm::BranchInst *BI) {
791 assert(!CleanupEntries.empty() &&
Anders Carlsson87eaf172009-02-08 00:50:42 +0000792 "Trying to add branch fixup without cleanup block!");
Mike Stump1eb44332009-09-09 15:08:12 +0000793
Mike Stumpf5408fe2009-05-16 07:57:57 +0000794 // FIXME: We could be more clever here and check if there's already a branch
795 // fixup for this destination and recycle it.
Anders Carlsson87eaf172009-02-08 00:50:42 +0000796 CleanupEntries.back().BranchFixups.push_back(BI);
797}
798
Mike Stump1eb44332009-09-09 15:08:12 +0000799void CodeGenFunction::EmitBranchThroughCleanup(llvm::BasicBlock *Dest) {
Anders Carlsson46831a92009-02-08 22:13:37 +0000800 if (!HaveInsertPoint())
801 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000802
Anders Carlsson87eaf172009-02-08 00:50:42 +0000803 llvm::BranchInst* BI = Builder.CreateBr(Dest);
Mike Stump1eb44332009-09-09 15:08:12 +0000804
Anders Carlsson46831a92009-02-08 22:13:37 +0000805 Builder.ClearInsertionPoint();
Mike Stump1eb44332009-09-09 15:08:12 +0000806
Anders Carlsson87eaf172009-02-08 00:50:42 +0000807 // The stack is empty, no need to do any cleanup.
808 if (CleanupEntries.empty())
809 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000810
Anders Carlsson87eaf172009-02-08 00:50:42 +0000811 if (!Dest->getParent()) {
812 // We are trying to branch to a block that hasn't been inserted yet.
813 AddBranchFixup(BI);
814 return;
815 }
Mike Stump1eb44332009-09-09 15:08:12 +0000816
Anders Carlsson87eaf172009-02-08 00:50:42 +0000817 BlockScopeMap::iterator I = BlockScopes.find(Dest);
818 if (I == BlockScopes.end()) {
819 // We are trying to jump to a block that is outside of any cleanup scope.
820 AddBranchFixup(BI);
821 return;
822 }
Mike Stump1eb44332009-09-09 15:08:12 +0000823
Anders Carlsson87eaf172009-02-08 00:50:42 +0000824 assert(I->second < CleanupEntries.size() &&
825 "Trying to branch into cleanup region");
Mike Stump1eb44332009-09-09 15:08:12 +0000826
Anders Carlsson87eaf172009-02-08 00:50:42 +0000827 if (I->second == CleanupEntries.size() - 1) {
828 // We have a branch to a block in the same scope.
829 return;
830 }
Mike Stump1eb44332009-09-09 15:08:12 +0000831
Anders Carlsson87eaf172009-02-08 00:50:42 +0000832 AddBranchFixup(BI);
833}