blob: 1e952f9a7dbfd7d405d0e07bb330cd8a1761bef0 [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");
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000182 ReturnValue = 0;
Daniel Dunbar7c086512008-09-09 23:14:03 +0000183 if (!RetTy->isVoidType())
184 ReturnValue = CreateTempAlloca(ConvertType(RetTy), "retval");
Mike Stump1eb44332009-09-09 15:08:12 +0000185
Chris Lattner41110242008-06-17 18:05:57 +0000186 Builder.SetInsertPoint(EntryBB);
Mike Stump1eb44332009-09-09 15:08:12 +0000187
Mike Stump91cc8152009-10-23 01:52:13 +0000188 QualType FnType = getContext().getFunctionType(RetTy, 0, 0, false, 0);
189
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000190 // Emit subprogram debug descriptor.
Daniel Dunbar7c086512008-09-09 23:14:03 +0000191 // FIXME: The cast here is a huge hack.
Anders Carlssone896d982009-02-13 08:11:52 +0000192 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000193 DI->setLocation(StartLoc);
Anders Carlsson1860a312009-09-11 00:11:35 +0000194 if (isa<FunctionDecl>(D)) {
Mike Stump91cc8152009-10-23 01:52:13 +0000195 DI->EmitFunctionStart(CGM.getMangledName(GD), FnType, CurFn, Builder);
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000196 } else {
197 // Just use LLVM function name.
Mike Stump1eb44332009-09-09 15:08:12 +0000198
Daniel Dunbar42719fc2009-07-23 05:30:36 +0000199 // FIXME: Remove unnecessary conversion to std::string when API settles.
Mike Stump1eb44332009-09-09 15:08:12 +0000200 DI->EmitFunctionStart(std::string(Fn->getName()).c_str(),
Mike Stump91cc8152009-10-23 01:52:13 +0000201 FnType, CurFn, Builder);
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000202 }
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000203 }
204
Daniel Dunbar88b53962009-02-02 22:03:45 +0000205 // FIXME: Leaked.
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000206 CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args);
Daniel Dunbar88b53962009-02-02 22:03:45 +0000207 EmitFunctionProlog(*CurFnInfo, CurFn, Args);
Mike Stump1eb44332009-09-09 15:08:12 +0000208
Anders Carlsson751358f2008-12-20 21:28:43 +0000209 // If any of the arguments have a variably modified type, make sure to
210 // emit the type size.
211 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
212 i != e; ++i) {
213 QualType Ty = i->second;
214
215 if (Ty->isVariablyModifiedType())
216 EmitVLASize(Ty);
217 }
Daniel Dunbar7c086512008-09-09 23:14:03 +0000218}
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000219
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000220static bool NeedsVTTParameter(GlobalDecl GD) {
221 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
222
223 // We don't have any virtual bases, just return early.
224 if (!MD->getParent()->getNumVBases())
225 return false;
226
227 // Check if we have a base constructor.
228 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
229 return true;
230
231 // Check if we have a base destructor.
232 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
233 return true;
234
235 return false;
236}
237
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000238void CodeGenFunction::GenerateCode(GlobalDecl GD,
Daniel Dunbar7c086512008-09-09 23:14:03 +0000239 llvm::Function *Fn) {
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000240 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
241
Anders Carlssone896d982009-02-13 08:11:52 +0000242 // Check if we should generate debug info for this function.
Mike Stump1feade82009-08-26 22:31:08 +0000243 if (CGM.getDebugInfo() && !FD->hasAttr<NoDebugAttr>())
Anders Carlssone896d982009-02-13 08:11:52 +0000244 DebugInfo = CGM.getDebugInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000245
Daniel Dunbar7c086512008-09-09 23:14:03 +0000246 FunctionArgList Args;
Mike Stump1eb44332009-09-09 15:08:12 +0000247
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000248 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
249 if (MD->isInstance()) {
250 // Create the implicit 'this' decl.
251 // FIXME: I'm not entirely sure I like using a fake decl just for code
252 // generation. Maybe we can come up with a better way?
253 CXXThisDecl = ImplicitParamDecl::Create(getContext(), 0, SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +0000254 &getContext().Idents.get("this"),
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000255 MD->getThisType(getContext()));
256 Args.push_back(std::make_pair(CXXThisDecl, CXXThisDecl->getType()));
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000257
258 // Check if we need a VTT parameter as well.
259 if (NeedsVTTParameter(GD)) {
260 // FIXME: The comment about using a fake decl above applies here too.
261 QualType T = getContext().getPointerType(getContext().VoidPtrTy);
262 CXXVTTDecl =
263 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(),
264 &getContext().Idents.get("vtt"), T);
265 Args.push_back(std::make_pair(CXXVTTDecl, CXXVTTDecl->getType()));
266 }
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000267 }
268 }
Mike Stump1eb44332009-09-09 15:08:12 +0000269
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000270 if (FD->getNumParams()) {
John McCall183700f2009-09-21 23:43:11 +0000271 const FunctionProtoType* FProto = FD->getType()->getAs<FunctionProtoType>();
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000272 assert(FProto && "Function def must have prototype!");
Daniel Dunbar7c086512008-09-09 23:14:03 +0000273
274 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
Mike Stump1eb44332009-09-09 15:08:12 +0000275 Args.push_back(std::make_pair(FD->getParamDecl(i),
Daniel Dunbar7c086512008-09-09 23:14:03 +0000276 FProto->getArgType(i)));
Chris Lattner41110242008-06-17 18:05:57 +0000277 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000278
Sebastian Redld3a413d2009-04-26 20:35:05 +0000279 // FIXME: Support CXXTryStmt here, too.
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000280 if (const CompoundStmt *S = FD->getCompoundBody()) {
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000281 StartFunction(GD, FD->getResultType(), Fn, Args, S->getLBracLoc());
Anders Carlsson4365bba2009-11-06 02:55:43 +0000282
283 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlssonde1d26b2009-09-14 05:32:02 +0000284 EmitCtorPrologue(CD, GD.getCtorType());
Anders Carlsson4365bba2009-11-06 02:55:43 +0000285 EmitStmt(S);
Anders Carlsson5e1b9182009-11-06 04:19:02 +0000286
287 // If any of the member initializers are temporaries bound to references
288 // make sure to emit their destructors.
289 EmitCleanupBlocks(0);
290
Anders Carlsson4365bba2009-11-06 02:55:43 +0000291 } else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD)) {
292 llvm::BasicBlock *DtorEpilogue = createBasicBlock("dtor.epilogue");
293 PushCleanupBlock(DtorEpilogue);
294
295 EmitStmt(S);
Anders Carlssonc33e4ba2009-10-06 18:09:57 +0000296
Anders Carlssonc33e4ba2009-10-06 18:09:57 +0000297 CleanupBlockInfo Info = PopCleanupBlock();
298
299 assert(Info.CleanupBlock == DtorEpilogue && "Block mismatch!");
300 EmitBlock(DtorEpilogue);
Anders Carlssonde1d26b2009-09-14 05:32:02 +0000301 EmitDtorEpilogue(DD, GD.getDtorType());
Anders Carlssonc33e4ba2009-10-06 18:09:57 +0000302
303 if (Info.SwitchBlock)
304 EmitBlock(Info.SwitchBlock);
305 if (Info.EndBlock)
306 EmitBlock(Info.EndBlock);
Anders Carlsson4365bba2009-11-06 02:55:43 +0000307 } else {
308 // Just a regular function, emit its body.
309 EmitStmt(S);
Anders Carlssonc33e4ba2009-10-06 18:09:57 +0000310 }
Anders Carlsson4365bba2009-11-06 02:55:43 +0000311
Sebastian Redld3a413d2009-04-26 20:35:05 +0000312 FinishFunction(S->getRBracLoc());
Douglas Gregor45132722009-10-01 20:44:19 +0000313 } else if (FD->isImplicit()) {
314 const CXXRecordDecl *ClassDecl =
315 cast<CXXRecordDecl>(FD->getDeclContext());
316 (void) ClassDecl;
Fariborz Jahanianc7ff8e12009-07-30 23:22:00 +0000317 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
Douglas Gregor45132722009-10-01 20:44:19 +0000318 // FIXME: For C++0x, we want to look for implicit *definitions* of
319 // these special member functions, rather than implicit *declarations*.
Fariborz Jahanian98896522009-08-06 23:38:16 +0000320 if (CD->isCopyConstructor(getContext())) {
321 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
Douglas Gregor45132722009-10-01 20:44:19 +0000322 "Cannot synthesize a non-implicit copy constructor");
Anders Carlssonde1d26b2009-09-14 05:32:02 +0000323 SynthesizeCXXCopyConstructor(CD, GD.getCtorType(), Fn, Args);
Douglas Gregor45132722009-10-01 20:44:19 +0000324 } else if (CD->isDefaultConstructor()) {
Fariborz Jahanian98896522009-08-06 23:38:16 +0000325 assert(!ClassDecl->hasUserDeclaredConstructor() &&
Douglas Gregor45132722009-10-01 20:44:19 +0000326 "Cannot synthesize a non-implicit default constructor.");
Anders Carlssonde1d26b2009-09-14 05:32:02 +0000327 SynthesizeDefaultConstructor(CD, GD.getCtorType(), Fn, Args);
Douglas Gregor45132722009-10-01 20:44:19 +0000328 } else {
329 assert(false && "Implicit constructor cannot be synthesized");
Fariborz Jahanian98896522009-08-06 23:38:16 +0000330 }
Douglas Gregor45132722009-10-01 20:44:19 +0000331 } else if (const CXXDestructorDecl *CD = dyn_cast<CXXDestructorDecl>(FD)) {
332 assert(!ClassDecl->hasUserDeclaredDestructor() &&
333 "Cannot synthesize a non-implicit destructor");
334 SynthesizeDefaultDestructor(CD, GD.getDtorType(), Fn, Args);
335 } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
336 assert(MD->isCopyAssignment() &&
337 !ClassDecl->hasUserDeclaredCopyAssignment() &&
338 "Cannot synthesize a method that is not an implicit-defined "
339 "copy constructor");
Anders Carlssonde1d26b2009-09-14 05:32:02 +0000340 SynthesizeCXXCopyAssignment(MD, Fn, Args);
Douglas Gregor45132722009-10-01 20:44:19 +0000341 } else {
342 assert(false && "Cannot synthesize unknown implicit function");
343 }
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000344 }
Mike Stump1eb44332009-09-09 15:08:12 +0000345
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000346 // Destroy the 'this' declaration.
347 if (CXXThisDecl)
348 CXXThisDecl->Destroy(getContext());
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000349
350 // Destroy the VTT declaration.
351 if (CXXVTTDecl)
352 CXXVTTDecl->Destroy(getContext());
Chris Lattner41110242008-06-17 18:05:57 +0000353}
354
Chris Lattner0946ccd2008-11-11 07:41:27 +0000355/// ContainsLabel - Return true if the statement contains a label in it. If
356/// this statement is not executed normally, it not containing a label means
357/// that we can just remove the code.
358bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
359 // Null statement, not a label!
360 if (S == 0) return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000361
Chris Lattner0946ccd2008-11-11 07:41:27 +0000362 // If this is a label, we have to emit the code, consider something like:
363 // if (0) { ... foo: bar(); } goto foo;
364 if (isa<LabelStmt>(S))
365 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000366
Chris Lattner0946ccd2008-11-11 07:41:27 +0000367 // If this is a case/default statement, and we haven't seen a switch, we have
368 // to emit the code.
369 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
370 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000371
Chris Lattner0946ccd2008-11-11 07:41:27 +0000372 // If this is a switch statement, we want to ignore cases below it.
373 if (isa<SwitchStmt>(S))
374 IgnoreCaseStmts = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000375
Chris Lattner0946ccd2008-11-11 07:41:27 +0000376 // Scan subexpressions for verboten labels.
377 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
378 I != E; ++I)
379 if (ContainsLabel(*I, IgnoreCaseStmts))
380 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000381
Chris Lattner0946ccd2008-11-11 07:41:27 +0000382 return false;
383}
384
Chris Lattner31a09842008-11-12 08:04:58 +0000385
386/// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
387/// a constant, or if it does but contains a label, return 0. If it constant
388/// folds to 'true' and does not contain a label, return 1, if it constant folds
389/// to 'false' and does not contain a label, return -1.
390int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
Daniel Dunbar36bc14c2008-11-12 22:37:10 +0000391 // FIXME: Rename and handle conversion of other evaluatable things
392 // to bool.
Anders Carlsson64712f12008-12-01 02:46:24 +0000393 Expr::EvalResult Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000394 if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
Anders Carlsson64712f12008-12-01 02:46:24 +0000395 Result.HasSideEffects)
Anders Carlssonef5a66d2008-11-22 22:32:07 +0000396 return 0; // Not foldable, not integer or not fully evaluatable.
Mike Stump1eb44332009-09-09 15:08:12 +0000397
Chris Lattner31a09842008-11-12 08:04:58 +0000398 if (CodeGenFunction::ContainsLabel(Cond))
399 return 0; // Contains a label.
Mike Stump1eb44332009-09-09 15:08:12 +0000400
Anders Carlsson64712f12008-12-01 02:46:24 +0000401 return Result.Val.getInt().getBoolValue() ? 1 : -1;
Chris Lattner31a09842008-11-12 08:04:58 +0000402}
403
404
405/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
406/// statement) to the specified blocks. Based on the condition, this might try
407/// to simplify the codegen of the conditional based on the branch.
408///
409void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
410 llvm::BasicBlock *TrueBlock,
411 llvm::BasicBlock *FalseBlock) {
412 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
413 return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000414
Chris Lattner31a09842008-11-12 08:04:58 +0000415 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
416 // Handle X && Y in a condition.
417 if (CondBOp->getOpcode() == BinaryOperator::LAnd) {
418 // If we have "1 && X", simplify the code. "0 && X" would have constant
419 // folded if the case was simple enough.
420 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
421 // br(1 && X) -> br(X).
422 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
423 }
Mike Stump1eb44332009-09-09 15:08:12 +0000424
Chris Lattner31a09842008-11-12 08:04:58 +0000425 // If we have "X && 1", simplify the code to use an uncond branch.
426 // "X && 0" would have been constant folded to 0.
427 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
428 // br(X && 1) -> br(X).
429 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
430 }
Mike Stump1eb44332009-09-09 15:08:12 +0000431
Chris Lattner31a09842008-11-12 08:04:58 +0000432 // Emit the LHS as a conditional. If the LHS conditional is false, we
433 // want to jump to the FalseBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000434 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
Chris Lattner31a09842008-11-12 08:04:58 +0000435 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
436 EmitBlock(LHSTrue);
Mike Stump1eb44332009-09-09 15:08:12 +0000437
Chris Lattner31a09842008-11-12 08:04:58 +0000438 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
439 return;
440 } else if (CondBOp->getOpcode() == BinaryOperator::LOr) {
441 // If we have "0 || X", simplify the code. "1 || X" would have constant
442 // folded if the case was simple enough.
443 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
444 // br(0 || X) -> br(X).
445 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
446 }
Mike Stump1eb44332009-09-09 15:08:12 +0000447
Chris Lattner31a09842008-11-12 08:04:58 +0000448 // If we have "X || 0", simplify the code to use an uncond branch.
449 // "X || 1" would have been constant folded to 1.
450 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
451 // br(X || 0) -> br(X).
452 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
453 }
Mike Stump1eb44332009-09-09 15:08:12 +0000454
Chris Lattner31a09842008-11-12 08:04:58 +0000455 // Emit the LHS as a conditional. If the LHS conditional is true, we
456 // want to jump to the TrueBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000457 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
Chris Lattner31a09842008-11-12 08:04:58 +0000458 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
459 EmitBlock(LHSFalse);
Mike Stump1eb44332009-09-09 15:08:12 +0000460
Chris Lattner31a09842008-11-12 08:04:58 +0000461 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
462 return;
463 }
Chris Lattner552f4c42008-11-12 08:13:36 +0000464 }
Mike Stump1eb44332009-09-09 15:08:12 +0000465
Chris Lattner552f4c42008-11-12 08:13:36 +0000466 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
467 // br(!x, t, f) -> br(x, f, t)
468 if (CondUOp->getOpcode() == UnaryOperator::LNot)
469 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
Chris Lattner31a09842008-11-12 08:04:58 +0000470 }
Mike Stump1eb44332009-09-09 15:08:12 +0000471
Daniel Dunbar09b14892008-11-12 10:30:32 +0000472 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
473 // Handle ?: operator.
474
475 // Just ignore GNU ?: extension.
476 if (CondOp->getLHS()) {
477 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
478 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
479 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
480 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
481 EmitBlock(LHSBlock);
482 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
483 EmitBlock(RHSBlock);
484 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
485 return;
486 }
487 }
488
Chris Lattner31a09842008-11-12 08:04:58 +0000489 // Emit the code with the fully general case.
490 llvm::Value *CondV = EvaluateExprAsBool(Cond);
491 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
492}
493
Daniel Dunbar488e9932008-08-16 00:56:44 +0000494/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000495/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000496void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
497 bool OmitOnError) {
498 CGM.ErrorUnsupported(S, Type, OmitOnError);
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000499}
500
Chris Lattner88207c92009-04-21 17:59:23 +0000501void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty) {
Chris Lattner36afd382009-10-13 06:02:42 +0000502 const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext);
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000503 if (DestPtr->getType() != BP)
504 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
505
506 // Get size and alignment info for this aggregate.
507 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
508
Chris Lattner88207c92009-04-21 17:59:23 +0000509 // Don't bother emitting a zero-byte memset.
510 if (TypeInfo.first == 0)
511 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000512
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000513 // FIXME: Handle variable sized types.
Mike Stump1eb44332009-09-09 15:08:12 +0000514 const llvm::Type *IntPtr = llvm::IntegerType::get(VMContext,
Owen Anderson0032b272009-08-13 21:57:51 +0000515 LLVMPointerWidth);
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000516
517 Builder.CreateCall4(CGM.getMemSetFn(), DestPtr,
Owen Anderson0032b272009-08-13 21:57:51 +0000518 llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext)),
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000519 // TypeInfo.first describes size in bits.
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000520 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
Mike Stump1eb44332009-09-09 15:08:12 +0000521 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000522 TypeInfo.second/8));
523}
524
Chris Lattnerd9becd12009-10-28 23:59:40 +0000525llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelStmt *L) {
526 // Make sure that there is a block for the indirect goto.
527 if (IndirectBranch == 0)
528 GetIndirectGotoBlock();
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000529
Chris Lattnerd9becd12009-10-28 23:59:40 +0000530 llvm::BasicBlock *BB = getBasicBlockForLabel(L);
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000531
Chris Lattnerd9becd12009-10-28 23:59:40 +0000532 // Make sure the indirect branch includes all of the address-taken blocks.
533 IndirectBranch->addDestination(BB);
534 return llvm::BlockAddress::get(CurFn, BB);
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000535}
536
537llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
Chris Lattnerd9becd12009-10-28 23:59:40 +0000538 // If we already made the indirect branch for indirect goto, return its block.
539 if (IndirectBranch) return IndirectBranch->getParent();
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000540
Chris Lattnerd9becd12009-10-28 23:59:40 +0000541 CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto"));
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000542
Chris Lattnerd9becd12009-10-28 23:59:40 +0000543 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
Chris Lattner85e74ac2009-10-28 20:36:47 +0000544
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000545 // Create the PHI node that indirect gotos will add entries to.
Chris Lattnerd9becd12009-10-28 23:59:40 +0000546 llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, "indirect.goto.dest");
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000547
Chris Lattnerd9becd12009-10-28 23:59:40 +0000548 // Create the indirect branch instruction.
549 IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
550 return IndirectBranch->getParent();
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000551}
Anders Carlssonddf7cac2008-11-04 05:30:00 +0000552
Daniel Dunbard286f052009-07-19 06:58:07 +0000553llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) {
Eli Friedmanbbed6b92009-08-15 02:50:32 +0000554 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
Mike Stump1eb44332009-09-09 15:08:12 +0000555
Anders Carlssonf666b772008-12-20 20:27:15 +0000556 assert(SizeEntry && "Did not emit size for type");
557 return SizeEntry;
558}
Anders Carlssondcc90d82008-12-12 07:19:02 +0000559
Daniel Dunbard286f052009-07-19 06:58:07 +0000560llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) {
Anders Carlsson60d35412008-12-20 20:46:34 +0000561 assert(Ty->isVariablyModifiedType() &&
562 "Must pass variably modified type to EmitVLASizes!");
Mike Stump1eb44332009-09-09 15:08:12 +0000563
Daniel Dunbard286f052009-07-19 06:58:07 +0000564 EnsureInsertPoint();
Mike Stump1eb44332009-09-09 15:08:12 +0000565
Anders Carlsson60d35412008-12-20 20:46:34 +0000566 if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
Eli Friedmanbbed6b92009-08-15 02:50:32 +0000567 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
Mike Stump1eb44332009-09-09 15:08:12 +0000568
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000569 if (!SizeEntry) {
Anders Carlsson96f21472009-02-05 19:43:10 +0000570 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
Mike Stump1eb44332009-09-09 15:08:12 +0000571
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000572 // Get the element size;
573 QualType ElemTy = VAT->getElementType();
574 llvm::Value *ElemSize;
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000575 if (ElemTy->isVariableArrayType())
576 ElemSize = EmitVLASize(ElemTy);
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000577 else
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000578 ElemSize = llvm::ConstantInt::get(SizeTy,
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000579 getContext().getTypeSize(ElemTy) / 8);
Mike Stump1eb44332009-09-09 15:08:12 +0000580
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000581 llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
Anders Carlsson96f21472009-02-05 19:43:10 +0000582 NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
Mike Stump1eb44332009-09-09 15:08:12 +0000583
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000584 SizeEntry = Builder.CreateMul(ElemSize, NumElements);
Anders Carlsson60d35412008-12-20 20:46:34 +0000585 }
Mike Stump1eb44332009-09-09 15:08:12 +0000586
Anders Carlsson60d35412008-12-20 20:46:34 +0000587 return SizeEntry;
Anders Carlssondcc90d82008-12-12 07:19:02 +0000588 }
Mike Stump1eb44332009-09-09 15:08:12 +0000589
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000590 if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
591 EmitVLASize(AT->getElementType());
592 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000593 }
594
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000595 const PointerType *PT = Ty->getAs<PointerType>();
596 assert(PT && "unknown VM type!");
597 EmitVLASize(PT->getPointeeType());
Anders Carlsson60d35412008-12-20 20:46:34 +0000598 return 0;
Anders Carlssondcc90d82008-12-12 07:19:02 +0000599}
Eli Friedman4fd0aa52009-01-20 17:46:04 +0000600
601llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
602 if (CGM.getContext().getBuiltinVaListType()->isArrayType()) {
603 return EmitScalarExpr(E);
604 }
605 return EmitLValue(E).getAddress();
606}
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000607
Fariborz Jahanian77996212009-11-04 17:57:40 +0000608void CodeGenFunction::PushCleanupBlock(llvm::BasicBlock *CleanupEntryBlock,
Mike Stump99533832009-12-02 07:41:41 +0000609 llvm::BasicBlock *CleanupExitBlock,
610 bool EHOnly) {
611 CleanupEntries.push_back(CleanupEntry(CleanupEntryBlock, CleanupExitBlock,
612 EHOnly));
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000613}
Anders Carlssonc71c8452009-02-07 23:50:39 +0000614
Mike Stump1eb44332009-09-09 15:08:12 +0000615void CodeGenFunction::EmitCleanupBlocks(size_t OldCleanupStackSize) {
616 assert(CleanupEntries.size() >= OldCleanupStackSize &&
Anders Carlssonc71c8452009-02-07 23:50:39 +0000617 "Cleanup stack mismatch!");
Mike Stump1eb44332009-09-09 15:08:12 +0000618
Anders Carlssonc71c8452009-02-07 23:50:39 +0000619 while (CleanupEntries.size() > OldCleanupStackSize)
620 EmitCleanupBlock();
621}
622
Mike Stump1eb44332009-09-09 15:08:12 +0000623CodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock() {
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000624 CleanupEntry &CE = CleanupEntries.back();
Mike Stump1eb44332009-09-09 15:08:12 +0000625
Fariborz Jahanian77996212009-11-04 17:57:40 +0000626 llvm::BasicBlock *CleanupEntryBlock = CE.CleanupEntryBlock;
Mike Stump1eb44332009-09-09 15:08:12 +0000627
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000628 std::vector<llvm::BasicBlock *> Blocks;
629 std::swap(Blocks, CE.Blocks);
Mike Stump1eb44332009-09-09 15:08:12 +0000630
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000631 std::vector<llvm::BranchInst *> BranchFixups;
632 std::swap(BranchFixups, CE.BranchFixups);
Mike Stump1eb44332009-09-09 15:08:12 +0000633
Mike Stump99533832009-12-02 07:41:41 +0000634 bool EHOnly = CE.EHOnly;
635
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000636 CleanupEntries.pop_back();
637
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000638 // Check if any branch fixups pointed to the scope we just popped. If so,
639 // we can remove them.
640 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
641 llvm::BasicBlock *Dest = BranchFixups[i]->getSuccessor(0);
642 BlockScopeMap::iterator I = BlockScopes.find(Dest);
Mike Stump1eb44332009-09-09 15:08:12 +0000643
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000644 if (I == BlockScopes.end())
645 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000646
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000647 assert(I->second <= CleanupEntries.size() && "Invalid branch fixup!");
Mike Stump1eb44332009-09-09 15:08:12 +0000648
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000649 if (I->second == CleanupEntries.size()) {
650 // We don't need to do this branch fixup.
651 BranchFixups[i] = BranchFixups.back();
652 BranchFixups.pop_back();
653 i--;
654 e--;
655 continue;
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000656 }
657 }
Mike Stump1eb44332009-09-09 15:08:12 +0000658
Fariborz Jahanian77996212009-11-04 17:57:40 +0000659 llvm::BasicBlock *SwitchBlock = CE.CleanupExitBlock;
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000660 llvm::BasicBlock *EndBlock = 0;
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000661 if (!BranchFixups.empty()) {
Fariborz Jahanian77996212009-11-04 17:57:40 +0000662 if (!SwitchBlock)
663 SwitchBlock = createBasicBlock("cleanup.switch");
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000664 EndBlock = createBasicBlock("cleanup.end");
Mike Stump1eb44332009-09-09 15:08:12 +0000665
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000666 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
Mike Stump1eb44332009-09-09 15:08:12 +0000667
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000668 Builder.SetInsertPoint(SwitchBlock);
669
Mike Stump99533832009-12-02 07:41:41 +0000670 llvm::Value *DestCodePtr
671 = CreateTempAlloca(llvm::Type::getInt32Ty(VMContext),
672 "cleanup.dst");
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000673 llvm::Value *DestCode = Builder.CreateLoad(DestCodePtr, "tmp");
Mike Stump1eb44332009-09-09 15:08:12 +0000674
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000675 // Create a switch instruction to determine where to jump next.
Mike Stump1eb44332009-09-09 15:08:12 +0000676 llvm::SwitchInst *SI = Builder.CreateSwitch(DestCode, EndBlock,
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000677 BranchFixups.size());
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000678
Anders Carlsson46831a92009-02-08 22:13:37 +0000679 // Restore the current basic block (if any)
Anders Carlsson0ae7b2b2009-03-17 05:53:35 +0000680 if (CurBB) {
Anders Carlsson46831a92009-02-08 22:13:37 +0000681 Builder.SetInsertPoint(CurBB);
Mike Stump1eb44332009-09-09 15:08:12 +0000682
Anders Carlsson0ae7b2b2009-03-17 05:53:35 +0000683 // If we had a current basic block, we also need to emit an instruction
684 // to initialize the cleanup destination.
Owen Anderson0032b272009-08-13 21:57:51 +0000685 Builder.CreateStore(llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)),
Anders Carlsson0ae7b2b2009-03-17 05:53:35 +0000686 DestCodePtr);
687 } else
Anders Carlsson46831a92009-02-08 22:13:37 +0000688 Builder.ClearInsertionPoint();
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000689
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000690 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
691 llvm::BranchInst *BI = BranchFixups[i];
692 llvm::BasicBlock *Dest = BI->getSuccessor(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000693
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000694 // Fixup the branch instruction to point to the cleanup block.
Fariborz Jahanian77996212009-11-04 17:57:40 +0000695 BI->setSuccessor(0, CleanupEntryBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000696
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000697 if (CleanupEntries.empty()) {
Anders Carlssoncc899202009-02-08 22:46:50 +0000698 llvm::ConstantInt *ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000699
Anders Carlssoncc899202009-02-08 22:46:50 +0000700 // Check if we already have a destination for this block.
701 if (Dest == SI->getDefaultDest())
Owen Anderson0032b272009-08-13 21:57:51 +0000702 ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0);
Anders Carlssoncc899202009-02-08 22:46:50 +0000703 else {
704 ID = SI->findCaseDest(Dest);
705 if (!ID) {
706 // No code found, get a new unique one by using the number of
707 // switch successors.
Mike Stump1eb44332009-09-09 15:08:12 +0000708 ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anders Carlssoncc899202009-02-08 22:46:50 +0000709 SI->getNumSuccessors());
710 SI->addCase(ID, Dest);
711 }
712 }
Mike Stump1eb44332009-09-09 15:08:12 +0000713
Anders Carlssoncc899202009-02-08 22:46:50 +0000714 // Store the jump destination before the branch instruction.
715 new llvm::StoreInst(ID, DestCodePtr, BI);
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000716 } else {
717 // We need to jump through another cleanup block. Create a pad block
Mike Stump99533832009-12-02 07:41:41 +0000718 // with a branch instruction that jumps to the final destination and add
719 // it as a branch fixup to the current cleanup scope.
Mike Stump1eb44332009-09-09 15:08:12 +0000720
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000721 // Create the pad block.
722 llvm::BasicBlock *CleanupPad = createBasicBlock("cleanup.pad", CurFn);
Anders Carlssoncc899202009-02-08 22:46:50 +0000723
724 // Create a unique case ID.
Mike Stump99533832009-12-02 07:41:41 +0000725 llvm::ConstantInt *ID
726 = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
727 SI->getNumSuccessors());
Anders Carlssoncc899202009-02-08 22:46:50 +0000728
729 // Store the jump destination before the branch instruction.
730 new llvm::StoreInst(ID, DestCodePtr, BI);
731
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000732 // Add it as the destination.
Anders Carlssoncc899202009-02-08 22:46:50 +0000733 SI->addCase(ID, CleanupPad);
Mike Stump1eb44332009-09-09 15:08:12 +0000734
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000735 // Create the branch to the final destination.
736 llvm::BranchInst *BI = llvm::BranchInst::Create(Dest);
737 CleanupPad->getInstList().push_back(BI);
Mike Stump1eb44332009-09-09 15:08:12 +0000738
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000739 // And add it as a branch fixup.
740 CleanupEntries.back().BranchFixups.push_back(BI);
741 }
742 }
743 }
Mike Stump1eb44332009-09-09 15:08:12 +0000744
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000745 // Remove all blocks from the block scope map.
746 for (size_t i = 0, e = Blocks.size(); i != e; ++i) {
747 assert(BlockScopes.count(Blocks[i]) &&
748 "Did not find block in scope map!");
Mike Stump1eb44332009-09-09 15:08:12 +0000749
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000750 BlockScopes.erase(Blocks[i]);
751 }
Mike Stump1eb44332009-09-09 15:08:12 +0000752
Mike Stump99533832009-12-02 07:41:41 +0000753 return CleanupBlockInfo(CleanupEntryBlock, SwitchBlock, EndBlock, EHOnly);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000754}
755
Mike Stump1eb44332009-09-09 15:08:12 +0000756void CodeGenFunction::EmitCleanupBlock() {
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000757 CleanupBlockInfo Info = PopCleanupBlock();
Mike Stump1eb44332009-09-09 15:08:12 +0000758
Mike Stump99533832009-12-02 07:41:41 +0000759 if (Info.EHOnly) {
760 // FIXME: Add this to the exceptional edge
761 if (Info.CleanupBlock->getNumUses() == 0)
762 delete Info.CleanupBlock;
763 return;
764 }
765
Anders Carlssoneb6437a2009-05-31 00:33:20 +0000766 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
Mike Stump1eb44332009-09-09 15:08:12 +0000767 if (CurBB && !CurBB->getTerminator() &&
Anders Carlssoneb6437a2009-05-31 00:33:20 +0000768 Info.CleanupBlock->getNumUses() == 0) {
769 CurBB->getInstList().splice(CurBB->end(), Info.CleanupBlock->getInstList());
770 delete Info.CleanupBlock;
Mike Stump1eb44332009-09-09 15:08:12 +0000771 } else
Anders Carlssoneb6437a2009-05-31 00:33:20 +0000772 EmitBlock(Info.CleanupBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000773
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000774 if (Info.SwitchBlock)
775 EmitBlock(Info.SwitchBlock);
776 if (Info.EndBlock)
777 EmitBlock(Info.EndBlock);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000778}
779
Mike Stump1eb44332009-09-09 15:08:12 +0000780void CodeGenFunction::AddBranchFixup(llvm::BranchInst *BI) {
781 assert(!CleanupEntries.empty() &&
Anders Carlsson87eaf172009-02-08 00:50:42 +0000782 "Trying to add branch fixup without cleanup block!");
Mike Stump1eb44332009-09-09 15:08:12 +0000783
Mike Stumpf5408fe2009-05-16 07:57:57 +0000784 // FIXME: We could be more clever here and check if there's already a branch
785 // fixup for this destination and recycle it.
Anders Carlsson87eaf172009-02-08 00:50:42 +0000786 CleanupEntries.back().BranchFixups.push_back(BI);
787}
788
Mike Stump1eb44332009-09-09 15:08:12 +0000789void CodeGenFunction::EmitBranchThroughCleanup(llvm::BasicBlock *Dest) {
Anders Carlsson46831a92009-02-08 22:13:37 +0000790 if (!HaveInsertPoint())
791 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000792
Anders Carlsson87eaf172009-02-08 00:50:42 +0000793 llvm::BranchInst* BI = Builder.CreateBr(Dest);
Mike Stump1eb44332009-09-09 15:08:12 +0000794
Anders Carlsson46831a92009-02-08 22:13:37 +0000795 Builder.ClearInsertionPoint();
Mike Stump1eb44332009-09-09 15:08:12 +0000796
Anders Carlsson87eaf172009-02-08 00:50:42 +0000797 // The stack is empty, no need to do any cleanup.
798 if (CleanupEntries.empty())
799 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000800
Anders Carlsson87eaf172009-02-08 00:50:42 +0000801 if (!Dest->getParent()) {
802 // We are trying to branch to a block that hasn't been inserted yet.
803 AddBranchFixup(BI);
804 return;
805 }
Mike Stump1eb44332009-09-09 15:08:12 +0000806
Anders Carlsson87eaf172009-02-08 00:50:42 +0000807 BlockScopeMap::iterator I = BlockScopes.find(Dest);
808 if (I == BlockScopes.end()) {
809 // We are trying to jump to a block that is outside of any cleanup scope.
810 AddBranchFixup(BI);
811 return;
812 }
Mike Stump1eb44332009-09-09 15:08:12 +0000813
Anders Carlsson87eaf172009-02-08 00:50:42 +0000814 assert(I->second < CleanupEntries.size() &&
815 "Trying to branch into cleanup region");
Mike Stump1eb44332009-09-09 15:08:12 +0000816
Anders Carlsson87eaf172009-02-08 00:50:42 +0000817 if (I->second == CleanupEntries.size() - 1) {
818 // We have a branch to a block in the same scope.
819 return;
820 }
Mike Stump1eb44332009-09-09 15:08:12 +0000821
Anders Carlsson87eaf172009-02-08 00:50:42 +0000822 AddBranchFixup(BI);
823}