blob: 7337590f570268ef7979cacf556c374aa7a36c1c [file] [log] [blame]
Chris Lattnerbed31442007-05-28 01:07:47 +00001//===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerbed31442007-05-28 01:07:47 +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 Friedman17630752008-05-22 01:40:10 +000016#include "CGDebugInfo.h"
Chris Lattnerd1af2d22007-05-29 23:17:50 +000017#include "clang/Basic/TargetInfo.h"
Chris Lattnercd439292008-11-12 08:04:58 +000018#include "clang/AST/APValue.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000019#include "clang/AST/ASTContext.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000020#include "clang/AST/Decl.h"
Anders Carlsson468fa632009-04-04 20:47:02 +000021#include "clang/AST/DeclCXX.h"
Mike Stumpbee78dd2009-12-04 23:26:17 +000022#include "clang/AST/StmtCXX.h"
Mike Stumpcb2fbcb2009-02-21 20:00:35 +000023#include "llvm/Target/TargetData.h"
Chris Lattnerbed31442007-05-28 01:07:47 +000024using namespace clang;
25using namespace CodeGen;
26
Mike Stump11289f42009-09-09 15:08:12 +000027CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
Mike Stump0c743272009-03-06 01:33:24 +000028 : BlockFunction(cgm, *this, Builder), CGM(cgm),
29 Target(CGM.getContext().Target),
Owen Andersonc9673d52009-07-08 20:52:20 +000030 Builder(cgm.getModule().getContext()),
Chris Lattner6c4d2552009-10-28 23:59:40 +000031 DebugInfo(0), IndirectBranch(0),
Chris Lattner2bb5cb42009-10-13 06:55:33 +000032 SwitchInsn(0), CaseRangeBlock(0), InvokeDest(0),
John McCall347132b2010-02-16 22:04:33 +000033 CXXThisDecl(0), CXXThisValue(0), CXXVTTDecl(0), CXXVTTValue(0),
Mike Stumpe8c3b3e2009-12-15 00:35:12 +000034 ConditionalBranchLevel(0), TerminateHandler(0), TrapBB(0),
Mike Stumpba6a0c42009-12-14 21:58:14 +000035 UniqueAggrDestructorCount(0) {
Mike Stumpcb2fbcb2009-02-21 20:00:35 +000036 LLVMIntTy = ConvertType(getContext().IntTy);
37 LLVMPointerWidth = Target.getPointerWidth(0);
Mike Stumpaff69af2009-12-09 03:35:49 +000038 Exceptions = getContext().getLangOptions().Exceptions;
Mike Stumpd9546382009-12-12 01:27:46 +000039 CatchUndefined = getContext().getLangOptions().CatchUndefined;
Chris Lattner5696e7b2008-06-17 18:05:57 +000040}
Chris Lattnerd1af2d22007-05-29 23:17:50 +000041
Chris Lattner6db1fb82007-06-02 22:49:07 +000042ASTContext &CodeGenFunction::getContext() const {
43 return CGM.getContext();
44}
45
Chris Lattnerd1af2d22007-05-29 23:17:50 +000046
Chris Lattnerac248202007-05-30 00:13:02 +000047llvm::BasicBlock *CodeGenFunction::getBasicBlockForLabel(const LabelStmt *S) {
Chris Lattner23b7eb62007-06-15 23:05:46 +000048 llvm::BasicBlock *&BB = LabelMap[S];
Chris Lattnerac248202007-05-30 00:13:02 +000049 if (BB) return BB;
Mike Stump11289f42009-09-09 15:08:12 +000050
Chris Lattnerac248202007-05-30 00:13:02 +000051 // Create, but don't insert, the new block.
Daniel Dunbar75283ff2008-11-11 02:29:29 +000052 return BB = createBasicBlock(S->getName());
Chris Lattnerac248202007-05-30 00:13:02 +000053}
54
Daniel Dunbar22a87f92009-02-25 19:24:29 +000055llvm::Value *CodeGenFunction::GetAddrOfLocalVar(const VarDecl *VD) {
56 llvm::Value *Res = LocalDeclMap[VD];
57 assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!");
58 return Res;
Lauro Ramos Venancio01a72ff2008-02-26 21:41:45 +000059}
Chris Lattnerac248202007-05-30 00:13:02 +000060
Daniel Dunbar22a87f92009-02-25 19:24:29 +000061llvm::Constant *
62CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) {
63 return cast<llvm::Constant>(GetAddrOfLocalVar(BVD));
Anders Carlsson9396a892008-09-11 09:15:33 +000064}
65
Daniel Dunbaree3da872009-02-03 23:03:55 +000066const llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
67 return CGM.getTypes().ConvertTypeForMem(T);
68}
69
Chris Lattnerf033c142007-06-22 19:05:19 +000070const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
71 return CGM.getTypes().ConvertType(T);
Chris Lattner45bb9142007-06-09 02:28:57 +000072}
Chris Lattnerd1af2d22007-05-29 23:17:50 +000073
Chris Lattner54fb19e2007-06-22 22:02:34 +000074bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
Anders Carlssonb05a3e52009-09-29 02:09:01 +000075 return T->isRecordType() || T->isArrayType() || T->isAnyComplexType() ||
76 T->isMemberFunctionPointerType();
Chris Lattner54fb19e2007-06-22 22:02:34 +000077}
78
Daniel Dunbarfd346a32009-01-26 23:27:52 +000079void CodeGenFunction::EmitReturnBlock() {
80 // For cleanliness, we try to avoid emitting the return block for
81 // simple cases.
82 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
83
84 if (CurBB) {
85 assert(!CurBB->getTerminator() && "Unexpected terminated block.");
86
Daniel Dunbarea3060a2009-07-19 08:24:34 +000087 // We have a valid insert point, reuse it if it is empty or there are no
88 // explicit jumps to the return block.
89 if (CurBB->empty() || ReturnBlock->use_empty()) {
90 ReturnBlock->replaceAllUsesWith(CurBB);
Daniel Dunbarfd346a32009-01-26 23:27:52 +000091 delete ReturnBlock;
Daniel Dunbarea3060a2009-07-19 08:24:34 +000092 } else
Daniel Dunbarfd346a32009-01-26 23:27:52 +000093 EmitBlock(ReturnBlock);
94 return;
95 }
96
97 // Otherwise, if the return block is the target of a single direct
98 // branch then we can just put the code in that block instead. This
99 // cleans up functions which started with a unified return block.
100 if (ReturnBlock->hasOneUse()) {
Mike Stump11289f42009-09-09 15:08:12 +0000101 llvm::BranchInst *BI =
Daniel Dunbarfd346a32009-01-26 23:27:52 +0000102 dyn_cast<llvm::BranchInst>(*ReturnBlock->use_begin());
103 if (BI && BI->isUnconditional() && BI->getSuccessor(0) == ReturnBlock) {
104 // Reset insertion point and delete the branch.
105 Builder.SetInsertPoint(BI->getParent());
106 BI->eraseFromParent();
107 delete ReturnBlock;
108 return;
109 }
110 }
111
Mike Stump18bb9282009-05-16 07:57:57 +0000112 // FIXME: We are at an unreachable point, there is no reason to emit the block
113 // unless it has uses. However, we still need a place to put the debug
114 // region.end for now.
Daniel Dunbarfd346a32009-01-26 23:27:52 +0000115
116 EmitBlock(ReturnBlock);
117}
118
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000119void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
Chris Lattnere73e4322007-07-16 21:28:45 +0000120 assert(BreakContinueStack.empty() &&
121 "mismatched push/pop in break/continue stack!");
Anders Carlssonfbfb5e62009-02-08 00:16:35 +0000122 assert(BlockScopes.empty() &&
123 "did not remove all blocks from block scope map!");
124 assert(CleanupEntries.empty() &&
125 "mismatched push/pop in cleanup stack!");
Mike Stump11289f42009-09-09 15:08:12 +0000126
127 // Emit function epilog (to return).
Daniel Dunbarfd346a32009-01-26 23:27:52 +0000128 EmitReturnBlock();
Daniel Dunbarfab3f932008-11-11 20:59:54 +0000129
130 // Emit debug descriptor for function end.
Anders Carlsson63784f42009-02-13 08:11:52 +0000131 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbarfab3f932008-11-11 20:59:54 +0000132 DI->setLocation(EndLoc);
133 DI->EmitRegionEnd(CurFn, Builder);
134 }
135
Daniel Dunbard931a872009-02-02 22:03:45 +0000136 EmitFunctionEpilog(*CurFnInfo, ReturnValue);
Mike Stump1d849212009-12-07 23:38:24 +0000137 EmitEndEHSpec(CurCodeDecl);
Daniel Dunbar54bb1932008-09-09 21:00:17 +0000138
Chris Lattner6c4d2552009-10-28 23:59:40 +0000139 // If someone did an indirect goto, emit the indirect goto block at the end of
140 // the function.
141 if (IndirectBranch) {
142 EmitBlock(IndirectBranch->getParent());
143 Builder.ClearInsertionPoint();
144 }
145
Chris Lattnerc48023b2007-12-02 06:32:24 +0000146 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
Chris Lattner2739d2b2009-03-31 22:17:44 +0000147 llvm::Instruction *Ptr = AllocaInsertPt;
Chris Lattnerc48023b2007-12-02 06:32:24 +0000148 AllocaInsertPt = 0;
Chris Lattner2739d2b2009-03-31 22:17:44 +0000149 Ptr->eraseFromParent();
Chris Lattner6c4d2552009-10-28 23:59:40 +0000150
151 // If someone took the address of a label but never did an indirect goto, we
152 // made a zero entry PHI node, which is illegal, zap it now.
153 if (IndirectBranch) {
154 llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
155 if (PN->getNumIncomingValues() == 0) {
156 PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
157 PN->eraseFromParent();
158 }
159 }
Chris Lattnerd1af2d22007-05-29 23:17:50 +0000160}
Chris Lattner308f4312007-05-29 23:50:05 +0000161
Anders Carlsson73fcc952009-09-11 00:07:24 +0000162void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000163 llvm::Function *Fn,
Daniel Dunbar354d2782008-10-18 18:22:23 +0000164 const FunctionArgList &Args,
165 SourceLocation StartLoc) {
Anders Carlsson73fcc952009-09-11 00:07:24 +0000166 const Decl *D = GD.getDecl();
167
Anders Carlssonf4478e92009-02-09 20:20:56 +0000168 DidCallStackSave = false;
Chris Lattner28ec0cf2009-04-23 05:30:27 +0000169 CurCodeDecl = CurFuncDecl = D;
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000170 FnRetTy = RetTy;
Daniel Dunbar9c426522008-07-29 23:18:29 +0000171 CurFn = Fn;
Chris Lattner5696e7b2008-06-17 18:05:57 +0000172 assert(CurFn->isDeclaration() && "Function already has body?");
173
Jakob Stoklund Olesen819e54b2010-02-09 00:10:00 +0000174 // Pass inline keyword to optimizer if it appears explicitly on any
175 // declaration.
176 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
177 for (FunctionDecl::redecl_iterator RI = FD->redecls_begin(),
178 RE = FD->redecls_end(); RI != RE; ++RI)
179 if (RI->isInlineSpecified()) {
180 Fn->addFnAttr(llvm::Attribute::InlineHint);
181 break;
182 }
183
Daniel Dunbar75283ff2008-11-11 02:29:29 +0000184 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
Daniel Dunbar54bb1932008-09-09 21:00:17 +0000185
Chris Lattner5696e7b2008-06-17 18:05:57 +0000186 // Create a marker to make it easy to insert allocas into the entryblock
187 // later. Don't create this with the builder, because we don't want it
188 // folded.
Owen Anderson41a75022009-08-13 21:57:51 +0000189 llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::getInt32Ty(VMContext));
Mike Stump1dbb8f72009-09-25 18:11:00 +0000190 AllocaInsertPt = new llvm::BitCastInst(Undef,
191 llvm::Type::getInt32Ty(VMContext), "",
Chris Lattner5696e7b2008-06-17 18:05:57 +0000192 EntryBB);
Chris Lattner47640222009-03-22 00:24:14 +0000193 if (Builder.isNamePreserving())
194 AllocaInsertPt->setName("allocapt");
Mike Stump11289f42009-09-09 15:08:12 +0000195
Daniel Dunbar75283ff2008-11-11 02:29:29 +0000196 ReturnBlock = createBasicBlock("return");
Mike Stump11289f42009-09-09 15:08:12 +0000197
Chris Lattner5696e7b2008-06-17 18:05:57 +0000198 Builder.SetInsertPoint(EntryBB);
Mike Stump11289f42009-09-09 15:08:12 +0000199
Mike Stumpae2559a2009-10-23 01:52:13 +0000200 QualType FnType = getContext().getFunctionType(RetTy, 0, 0, false, 0);
201
Sanjiv Gupta1e8b6082008-07-04 11:04:26 +0000202 // Emit subprogram debug descriptor.
Anders Carlsson63784f42009-02-13 08:11:52 +0000203 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar354d2782008-10-18 18:22:23 +0000204 DI->setLocation(StartLoc);
Devang Patel934661e2010-01-14 00:36:21 +0000205 DI->EmitFunctionStart(GD, FnType, CurFn, Builder);
Sanjiv Gupta1e8b6082008-07-04 11:04:26 +0000206 }
207
Daniel Dunbard931a872009-02-02 22:03:45 +0000208 // FIXME: Leaked.
John McCallab26cfa2010-02-05 21:31:56 +0000209 // CC info is ignored, hopefully?
210 CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args,
211 CC_Default, false);
Eli Friedman4b1942c2009-12-04 02:43:40 +0000212
213 if (RetTy->isVoidType()) {
214 // Void type; nothing to return.
215 ReturnValue = 0;
216 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
217 hasAggregateLLVMType(CurFnInfo->getReturnType())) {
218 // Indirect aggregate return; emit returned value directly into sret slot.
Daniel Dunbarfd09df72010-02-16 19:45:20 +0000219 // This reduces code size, and affects correctness in C++.
Eli Friedman4b1942c2009-12-04 02:43:40 +0000220 ReturnValue = CurFn->arg_begin();
221 } else {
Daniel Dunbarfd09df72010-02-16 19:45:20 +0000222 ReturnValue = CreateIRTemp(RetTy, "retval");
Eli Friedman4b1942c2009-12-04 02:43:40 +0000223 }
224
Mike Stump1d849212009-12-07 23:38:24 +0000225 EmitStartEHSpec(CurCodeDecl);
Daniel Dunbard931a872009-02-02 22:03:45 +0000226 EmitFunctionProlog(*CurFnInfo, CurFn, Args);
Mike Stump11289f42009-09-09 15:08:12 +0000227
John McCall347132b2010-02-16 22:04:33 +0000228 if (CXXThisDecl)
229 CXXThisValue = Builder.CreateLoad(LocalDeclMap[CXXThisDecl], "this");
230 if (CXXVTTDecl)
231 CXXVTTValue = Builder.CreateLoad(LocalDeclMap[CXXVTTDecl], "vtt");
232
Anders Carlssonc20879a2008-12-20 21:28:43 +0000233 // If any of the arguments have a variably modified type, make sure to
234 // emit the type size.
235 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
236 i != e; ++i) {
237 QualType Ty = i->second;
238
239 if (Ty->isVariablyModifiedType())
240 EmitVLASize(Ty);
241 }
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000242}
Eli Friedman3d421e12008-08-25 21:31:01 +0000243
John McCallb81884d2010-02-19 09:25:03 +0000244void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args) {
245 const FunctionDecl *FD = cast<FunctionDecl>(CurGD.getDecl());
John McCall89b12b32010-02-18 03:17:58 +0000246
247 Stmt *Body = FD->getBody();
John McCallb81884d2010-02-19 09:25:03 +0000248 if (Body)
John McCall89b12b32010-02-18 03:17:58 +0000249 EmitStmt(Body);
John McCallb81884d2010-02-19 09:25:03 +0000250 else {
251 assert(FD->isImplicit() && "non-implicit function def has no body");
252 assert(FD->isCopyAssignment() && "implicit function not copy assignment");
253 SynthesizeCXXCopyAssignment(Args);
John McCall89b12b32010-02-18 03:17:58 +0000254 }
255}
256
Anders Carlssone36a6b32010-01-02 01:01:18 +0000257void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn) {
Anders Carlsson73fcc952009-09-11 00:07:24 +0000258 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
259
Anders Carlsson63784f42009-02-13 08:11:52 +0000260 // Check if we should generate debug info for this function.
Mike Stump3722f582009-08-26 22:31:08 +0000261 if (CGM.getDebugInfo() && !FD->hasAttr<NoDebugAttr>())
Anders Carlsson63784f42009-02-13 08:11:52 +0000262 DebugInfo = CGM.getDebugInfo();
Mike Stump11289f42009-09-09 15:08:12 +0000263
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000264 FunctionArgList Args;
Mike Stump11289f42009-09-09 15:08:12 +0000265
Mike Stumpbee78dd2009-12-04 23:26:17 +0000266 CurGD = GD;
Anders Carlsson468fa632009-04-04 20:47:02 +0000267 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
268 if (MD->isInstance()) {
269 // Create the implicit 'this' decl.
270 // FIXME: I'm not entirely sure I like using a fake decl just for code
271 // generation. Maybe we can come up with a better way?
John McCall347132b2010-02-16 22:04:33 +0000272 CXXThisDecl = ImplicitParamDecl::Create(getContext(), 0,
273 FD->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +0000274 &getContext().Idents.get("this"),
Anders Carlsson468fa632009-04-04 20:47:02 +0000275 MD->getThisType(getContext()));
276 Args.push_back(std::make_pair(CXXThisDecl, CXXThisDecl->getType()));
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000277
278 // Check if we need a VTT parameter as well.
Anders Carlssone36a6b32010-01-02 01:01:18 +0000279 if (CGVtableInfo::needsVTTParameter(GD)) {
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000280 // FIXME: The comment about using a fake decl above applies here too.
281 QualType T = getContext().getPointerType(getContext().VoidPtrTy);
282 CXXVTTDecl =
John McCall347132b2010-02-16 22:04:33 +0000283 ImplicitParamDecl::Create(getContext(), 0, FD->getLocation(),
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000284 &getContext().Idents.get("vtt"), T);
285 Args.push_back(std::make_pair(CXXVTTDecl, CXXVTTDecl->getType()));
286 }
Anders Carlsson468fa632009-04-04 20:47:02 +0000287 }
288 }
Mike Stump11289f42009-09-09 15:08:12 +0000289
Eli Friedman3d421e12008-08-25 21:31:01 +0000290 if (FD->getNumParams()) {
John McCall9dd450b2009-09-21 23:43:11 +0000291 const FunctionProtoType* FProto = FD->getType()->getAs<FunctionProtoType>();
Eli Friedman3d421e12008-08-25 21:31:01 +0000292 assert(FProto && "Function def must have prototype!");
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000293
294 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
Mike Stump11289f42009-09-09 15:08:12 +0000295 Args.push_back(std::make_pair(FD->getParamDecl(i),
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000296 FProto->getArgType(i)));
Chris Lattner5696e7b2008-06-17 18:05:57 +0000297 }
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000298
John McCall89b12b32010-02-18 03:17:58 +0000299 SourceRange BodyRange;
300 if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange();
Anders Carlsson438cf922009-11-06 02:55:43 +0000301
John McCall89b12b32010-02-18 03:17:58 +0000302 // Emit the standard function prologue.
303 StartFunction(GD, FD->getResultType(), Fn, Args, BodyRange.getBegin());
Anders Carlsson438cf922009-11-06 02:55:43 +0000304
John McCall89b12b32010-02-18 03:17:58 +0000305 // Generate the body of the function.
John McCallb81884d2010-02-19 09:25:03 +0000306 if (isa<CXXDestructorDecl>(FD))
307 EmitDestructorBody(Args);
308 else if (isa<CXXConstructorDecl>(FD))
309 EmitConstructorBody(Args);
310 else
311 EmitFunctionBody(Args);
Anders Carlssonff8cce42010-02-07 19:45:40 +0000312
John McCall89b12b32010-02-18 03:17:58 +0000313 // Emit the standard function epilogue.
314 FinishFunction(BodyRange.getEnd());
Mike Stump11289f42009-09-09 15:08:12 +0000315
Anders Carlsson468fa632009-04-04 20:47:02 +0000316 // Destroy the 'this' declaration.
317 if (CXXThisDecl)
318 CXXThisDecl->Destroy(getContext());
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000319
320 // Destroy the VTT declaration.
321 if (CXXVTTDecl)
322 CXXVTTDecl->Destroy(getContext());
Chris Lattner5696e7b2008-06-17 18:05:57 +0000323}
324
Chris Lattner5b1964b2008-11-11 07:41:27 +0000325/// ContainsLabel - Return true if the statement contains a label in it. If
326/// this statement is not executed normally, it not containing a label means
327/// that we can just remove the code.
328bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
329 // Null statement, not a label!
330 if (S == 0) return false;
Mike Stump11289f42009-09-09 15:08:12 +0000331
Chris Lattner5b1964b2008-11-11 07:41:27 +0000332 // If this is a label, we have to emit the code, consider something like:
333 // if (0) { ... foo: bar(); } goto foo;
334 if (isa<LabelStmt>(S))
335 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000336
Chris Lattner5b1964b2008-11-11 07:41:27 +0000337 // If this is a case/default statement, and we haven't seen a switch, we have
338 // to emit the code.
339 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
340 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000341
Chris Lattner5b1964b2008-11-11 07:41:27 +0000342 // If this is a switch statement, we want to ignore cases below it.
343 if (isa<SwitchStmt>(S))
344 IgnoreCaseStmts = true;
Mike Stump11289f42009-09-09 15:08:12 +0000345
Chris Lattner5b1964b2008-11-11 07:41:27 +0000346 // Scan subexpressions for verboten labels.
347 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
348 I != E; ++I)
349 if (ContainsLabel(*I, IgnoreCaseStmts))
350 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000351
Chris Lattner5b1964b2008-11-11 07:41:27 +0000352 return false;
353}
354
Chris Lattnercd439292008-11-12 08:04:58 +0000355
356/// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
357/// a constant, or if it does but contains a label, return 0. If it constant
358/// folds to 'true' and does not contain a label, return 1, if it constant folds
359/// to 'false' and does not contain a label, return -1.
360int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
Daniel Dunbarf32443c2008-11-12 22:37:10 +0000361 // FIXME: Rename and handle conversion of other evaluatable things
362 // to bool.
Anders Carlsson86286452008-12-01 02:46:24 +0000363 Expr::EvalResult Result;
Mike Stump11289f42009-09-09 15:08:12 +0000364 if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
Anders Carlsson86286452008-12-01 02:46:24 +0000365 Result.HasSideEffects)
Anders Carlsson4046e652008-11-22 22:32:07 +0000366 return 0; // Not foldable, not integer or not fully evaluatable.
Mike Stump11289f42009-09-09 15:08:12 +0000367
Chris Lattnercd439292008-11-12 08:04:58 +0000368 if (CodeGenFunction::ContainsLabel(Cond))
369 return 0; // Contains a label.
Mike Stump11289f42009-09-09 15:08:12 +0000370
Anders Carlsson86286452008-12-01 02:46:24 +0000371 return Result.Val.getInt().getBoolValue() ? 1 : -1;
Chris Lattnercd439292008-11-12 08:04:58 +0000372}
373
374
375/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
376/// statement) to the specified blocks. Based on the condition, this might try
377/// to simplify the codegen of the conditional based on the branch.
378///
379void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
380 llvm::BasicBlock *TrueBlock,
381 llvm::BasicBlock *FalseBlock) {
382 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
383 return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
Mike Stump11289f42009-09-09 15:08:12 +0000384
Chris Lattnercd439292008-11-12 08:04:58 +0000385 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
386 // Handle X && Y in a condition.
387 if (CondBOp->getOpcode() == BinaryOperator::LAnd) {
388 // If we have "1 && X", simplify the code. "0 && X" would have constant
389 // folded if the case was simple enough.
390 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
391 // br(1 && X) -> br(X).
392 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
393 }
Mike Stump11289f42009-09-09 15:08:12 +0000394
Chris Lattnercd439292008-11-12 08:04:58 +0000395 // If we have "X && 1", simplify the code to use an uncond branch.
396 // "X && 0" would have been constant folded to 0.
397 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
398 // br(X && 1) -> br(X).
399 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
400 }
Mike Stump11289f42009-09-09 15:08:12 +0000401
Chris Lattnercd439292008-11-12 08:04:58 +0000402 // Emit the LHS as a conditional. If the LHS conditional is false, we
403 // want to jump to the FalseBlock.
Daniel Dunbara612e792008-11-13 01:38:36 +0000404 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
Chris Lattnercd439292008-11-12 08:04:58 +0000405 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
406 EmitBlock(LHSTrue);
Mike Stump11289f42009-09-09 15:08:12 +0000407
Anders Carlsson60ddba62010-01-24 00:20:05 +0000408 // Any temporaries created here are conditional.
Anders Carlssonae612d22010-02-04 17:18:07 +0000409 BeginConditionalBranch();
Chris Lattnercd439292008-11-12 08:04:58 +0000410 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
Anders Carlssonae612d22010-02-04 17:18:07 +0000411 EndConditionalBranch();
Anders Carlsson60ddba62010-01-24 00:20:05 +0000412
Chris Lattnercd439292008-11-12 08:04:58 +0000413 return;
414 } else if (CondBOp->getOpcode() == BinaryOperator::LOr) {
415 // If we have "0 || X", simplify the code. "1 || X" would have constant
416 // folded if the case was simple enough.
417 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
418 // br(0 || X) -> br(X).
419 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
420 }
Mike Stump11289f42009-09-09 15:08:12 +0000421
Chris Lattnercd439292008-11-12 08:04:58 +0000422 // If we have "X || 0", simplify the code to use an uncond branch.
423 // "X || 1" would have been constant folded to 1.
424 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
425 // br(X || 0) -> br(X).
426 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
427 }
Mike Stump11289f42009-09-09 15:08:12 +0000428
Chris Lattnercd439292008-11-12 08:04:58 +0000429 // Emit the LHS as a conditional. If the LHS conditional is true, we
430 // want to jump to the TrueBlock.
Daniel Dunbara612e792008-11-13 01:38:36 +0000431 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
Chris Lattnercd439292008-11-12 08:04:58 +0000432 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
433 EmitBlock(LHSFalse);
Mike Stump11289f42009-09-09 15:08:12 +0000434
Anders Carlsson60ddba62010-01-24 00:20:05 +0000435 // Any temporaries created here are conditional.
Anders Carlssonae612d22010-02-04 17:18:07 +0000436 BeginConditionalBranch();
Chris Lattnercd439292008-11-12 08:04:58 +0000437 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
Anders Carlssonae612d22010-02-04 17:18:07 +0000438 EndConditionalBranch();
Anders Carlsson60ddba62010-01-24 00:20:05 +0000439
Chris Lattnercd439292008-11-12 08:04:58 +0000440 return;
441 }
Chris Lattnerd9537732008-11-12 08:13:36 +0000442 }
Mike Stump11289f42009-09-09 15:08:12 +0000443
Chris Lattnerd9537732008-11-12 08:13:36 +0000444 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
445 // br(!x, t, f) -> br(x, f, t)
446 if (CondUOp->getOpcode() == UnaryOperator::LNot)
447 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
Chris Lattnercd439292008-11-12 08:04:58 +0000448 }
Mike Stump11289f42009-09-09 15:08:12 +0000449
Daniel Dunbarbf3c22e2008-11-12 10:30:32 +0000450 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
451 // Handle ?: operator.
452
453 // Just ignore GNU ?: extension.
454 if (CondOp->getLHS()) {
455 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
456 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
457 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
458 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
459 EmitBlock(LHSBlock);
460 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
461 EmitBlock(RHSBlock);
462 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
463 return;
464 }
465 }
466
Chris Lattnercd439292008-11-12 08:04:58 +0000467 // Emit the code with the fully general case.
468 llvm::Value *CondV = EvaluateExprAsBool(Cond);
469 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
470}
471
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000472/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerfc944342007-12-02 01:43:38 +0000473/// specified stmt yet.
Daniel Dunbarf2cf6d12008-09-04 03:43:08 +0000474void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
475 bool OmitOnError) {
476 CGM.ErrorUnsupported(S, Type, OmitOnError);
Chris Lattnerfc944342007-12-02 01:43:38 +0000477}
478
Chris Lattnerb534f6a2009-04-21 17:59:23 +0000479void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty) {
Chris Lattnerdd7eaad2009-10-13 06:02:42 +0000480 const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext);
Anders Carlsson2e744e82008-08-30 19:51:14 +0000481 if (DestPtr->getType() != BP)
482 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
483
484 // Get size and alignment info for this aggregate.
485 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
486
Chris Lattnerb534f6a2009-04-21 17:59:23 +0000487 // Don't bother emitting a zero-byte memset.
488 if (TypeInfo.first == 0)
489 return;
Mike Stump11289f42009-09-09 15:08:12 +0000490
Anders Carlsson2e744e82008-08-30 19:51:14 +0000491 // FIXME: Handle variable sized types.
Mike Stump11289f42009-09-09 15:08:12 +0000492 const llvm::Type *IntPtr = llvm::IntegerType::get(VMContext,
Owen Anderson41a75022009-08-13 21:57:51 +0000493 LLVMPointerWidth);
Anders Carlsson2e744e82008-08-30 19:51:14 +0000494
495 Builder.CreateCall4(CGM.getMemSetFn(), DestPtr,
Owen Anderson41a75022009-08-13 21:57:51 +0000496 llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext)),
Anders Carlsson2e744e82008-08-30 19:51:14 +0000497 // TypeInfo.first describes size in bits.
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000498 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
Mike Stump11289f42009-09-09 15:08:12 +0000499 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anders Carlsson2e744e82008-08-30 19:51:14 +0000500 TypeInfo.second/8));
501}
502
Chris Lattner6c4d2552009-10-28 23:59:40 +0000503llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelStmt *L) {
504 // Make sure that there is a block for the indirect goto.
505 if (IndirectBranch == 0)
506 GetIndirectGotoBlock();
Chris Lattner2bb5cb42009-10-13 06:55:33 +0000507
Chris Lattner6c4d2552009-10-28 23:59:40 +0000508 llvm::BasicBlock *BB = getBasicBlockForLabel(L);
Chris Lattner2bb5cb42009-10-13 06:55:33 +0000509
Chris Lattner6c4d2552009-10-28 23:59:40 +0000510 // Make sure the indirect branch includes all of the address-taken blocks.
511 IndirectBranch->addDestination(BB);
512 return llvm::BlockAddress::get(CurFn, BB);
Chris Lattner2bb5cb42009-10-13 06:55:33 +0000513}
514
515llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
Chris Lattner6c4d2552009-10-28 23:59:40 +0000516 // If we already made the indirect branch for indirect goto, return its block.
517 if (IndirectBranch) return IndirectBranch->getParent();
Chris Lattner2bb5cb42009-10-13 06:55:33 +0000518
Chris Lattner6c4d2552009-10-28 23:59:40 +0000519 CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto"));
Chris Lattner2bb5cb42009-10-13 06:55:33 +0000520
Chris Lattner6c4d2552009-10-28 23:59:40 +0000521 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
Chris Lattnera0c0d882009-10-28 20:36:47 +0000522
Chris Lattner2bb5cb42009-10-13 06:55:33 +0000523 // Create the PHI node that indirect gotos will add entries to.
Chris Lattner6c4d2552009-10-28 23:59:40 +0000524 llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, "indirect.goto.dest");
Chris Lattner2bb5cb42009-10-13 06:55:33 +0000525
Chris Lattner6c4d2552009-10-28 23:59:40 +0000526 // Create the indirect branch instruction.
527 IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
528 return IndirectBranch->getParent();
Daniel Dunbar88402ce2008-08-04 16:51:22 +0000529}
Anders Carlsson13abd7e2008-11-04 05:30:00 +0000530
Daniel Dunbarb6adc432009-07-19 06:58:07 +0000531llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) {
Eli Friedman04fddf02009-08-15 02:50:32 +0000532 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
Mike Stump11289f42009-09-09 15:08:12 +0000533
Anders Carlssone388a5b2008-12-20 20:27:15 +0000534 assert(SizeEntry && "Did not emit size for type");
535 return SizeEntry;
536}
Anders Carlssonccbe9202008-12-12 07:19:02 +0000537
Daniel Dunbarb6adc432009-07-19 06:58:07 +0000538llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) {
Anders Carlsson8a01b792008-12-20 20:46:34 +0000539 assert(Ty->isVariablyModifiedType() &&
540 "Must pass variably modified type to EmitVLASizes!");
Mike Stump11289f42009-09-09 15:08:12 +0000541
Daniel Dunbarb6adc432009-07-19 06:58:07 +0000542 EnsureInsertPoint();
Mike Stump11289f42009-09-09 15:08:12 +0000543
Anders Carlsson8a01b792008-12-20 20:46:34 +0000544 if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
Eli Friedman04fddf02009-08-15 02:50:32 +0000545 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
Mike Stump11289f42009-09-09 15:08:12 +0000546
Anders Carlsson5d985f52008-12-20 21:51:53 +0000547 if (!SizeEntry) {
Anders Carlsson31f86492009-02-05 19:43:10 +0000548 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
Mike Stump11289f42009-09-09 15:08:12 +0000549
Chris Lattner8dc76262009-08-15 00:03:43 +0000550 // Get the element size;
551 QualType ElemTy = VAT->getElementType();
552 llvm::Value *ElemSize;
Anders Carlsson5d985f52008-12-20 21:51:53 +0000553 if (ElemTy->isVariableArrayType())
554 ElemSize = EmitVLASize(ElemTy);
Chris Lattner8dc76262009-08-15 00:03:43 +0000555 else
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000556 ElemSize = llvm::ConstantInt::get(SizeTy,
Ken Dyck40775002010-01-11 17:06:35 +0000557 getContext().getTypeSizeInChars(ElemTy).getQuantity());
Mike Stump11289f42009-09-09 15:08:12 +0000558
Anders Carlsson5d985f52008-12-20 21:51:53 +0000559 llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
Anders Carlsson31f86492009-02-05 19:43:10 +0000560 NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
Mike Stump11289f42009-09-09 15:08:12 +0000561
Anders Carlsson5d985f52008-12-20 21:51:53 +0000562 SizeEntry = Builder.CreateMul(ElemSize, NumElements);
Anders Carlsson8a01b792008-12-20 20:46:34 +0000563 }
Mike Stump11289f42009-09-09 15:08:12 +0000564
Anders Carlsson8a01b792008-12-20 20:46:34 +0000565 return SizeEntry;
Anders Carlssonccbe9202008-12-12 07:19:02 +0000566 }
Mike Stump11289f42009-09-09 15:08:12 +0000567
Chris Lattner8dc76262009-08-15 00:03:43 +0000568 if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
569 EmitVLASize(AT->getElementType());
570 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000571 }
572
Chris Lattner8dc76262009-08-15 00:03:43 +0000573 const PointerType *PT = Ty->getAs<PointerType>();
574 assert(PT && "unknown VM type!");
575 EmitVLASize(PT->getPointeeType());
Anders Carlsson8a01b792008-12-20 20:46:34 +0000576 return 0;
Anders Carlssonccbe9202008-12-12 07:19:02 +0000577}
Eli Friedmanddea0ad2009-01-20 17:46:04 +0000578
579llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
580 if (CGM.getContext().getBuiltinVaListType()->isArrayType()) {
581 return EmitScalarExpr(E);
582 }
583 return EmitLValue(E).getAddress();
584}
Anders Carlsson15cb75a2009-02-07 22:53:43 +0000585
Fariborz Jahanian09cc10f2009-11-04 17:57:40 +0000586void CodeGenFunction::PushCleanupBlock(llvm::BasicBlock *CleanupEntryBlock,
Mike Stump33270212009-12-02 07:41:41 +0000587 llvm::BasicBlock *CleanupExitBlock,
Mike Stumpaff69af2009-12-09 03:35:49 +0000588 llvm::BasicBlock *PreviousInvokeDest,
Mike Stump33270212009-12-02 07:41:41 +0000589 bool EHOnly) {
590 CleanupEntries.push_back(CleanupEntry(CleanupEntryBlock, CleanupExitBlock,
Mike Stumpaff69af2009-12-09 03:35:49 +0000591 PreviousInvokeDest, EHOnly));
Anders Carlsson15cb75a2009-02-07 22:53:43 +0000592}
Anders Carlssonbe0f76a2009-02-07 23:50:39 +0000593
Mike Stump11289f42009-09-09 15:08:12 +0000594void CodeGenFunction::EmitCleanupBlocks(size_t OldCleanupStackSize) {
595 assert(CleanupEntries.size() >= OldCleanupStackSize &&
Anders Carlssonbe0f76a2009-02-07 23:50:39 +0000596 "Cleanup stack mismatch!");
Mike Stump11289f42009-09-09 15:08:12 +0000597
Anders Carlssonbe0f76a2009-02-07 23:50:39 +0000598 while (CleanupEntries.size() > OldCleanupStackSize)
599 EmitCleanupBlock();
600}
601
Mike Stump11289f42009-09-09 15:08:12 +0000602CodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock() {
Anders Carlsson66c384a2009-02-08 07:46:24 +0000603 CleanupEntry &CE = CleanupEntries.back();
Mike Stump11289f42009-09-09 15:08:12 +0000604
Fariborz Jahanian09cc10f2009-11-04 17:57:40 +0000605 llvm::BasicBlock *CleanupEntryBlock = CE.CleanupEntryBlock;
Mike Stump11289f42009-09-09 15:08:12 +0000606
Anders Carlsson66c384a2009-02-08 07:46:24 +0000607 std::vector<llvm::BasicBlock *> Blocks;
608 std::swap(Blocks, CE.Blocks);
Mike Stump11289f42009-09-09 15:08:12 +0000609
Anders Carlsson66c384a2009-02-08 07:46:24 +0000610 std::vector<llvm::BranchInst *> BranchFixups;
611 std::swap(BranchFixups, CE.BranchFixups);
Mike Stump11289f42009-09-09 15:08:12 +0000612
Mike Stump33270212009-12-02 07:41:41 +0000613 bool EHOnly = CE.EHOnly;
614
Mike Stumpaff69af2009-12-09 03:35:49 +0000615 setInvokeDest(CE.PreviousInvokeDest);
616
Anders Carlsson66c384a2009-02-08 07:46:24 +0000617 CleanupEntries.pop_back();
618
Anders Carlssonf57b9ee2009-02-08 22:45:15 +0000619 // Check if any branch fixups pointed to the scope we just popped. If so,
620 // we can remove them.
621 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
622 llvm::BasicBlock *Dest = BranchFixups[i]->getSuccessor(0);
623 BlockScopeMap::iterator I = BlockScopes.find(Dest);
Mike Stump11289f42009-09-09 15:08:12 +0000624
Anders Carlssonf57b9ee2009-02-08 22:45:15 +0000625 if (I == BlockScopes.end())
626 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000627
Anders Carlssonf57b9ee2009-02-08 22:45:15 +0000628 assert(I->second <= CleanupEntries.size() && "Invalid branch fixup!");
Mike Stump11289f42009-09-09 15:08:12 +0000629
Anders Carlssonf57b9ee2009-02-08 22:45:15 +0000630 if (I->second == CleanupEntries.size()) {
631 // We don't need to do this branch fixup.
632 BranchFixups[i] = BranchFixups.back();
633 BranchFixups.pop_back();
634 i--;
635 e--;
636 continue;
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000637 }
638 }
Mike Stump11289f42009-09-09 15:08:12 +0000639
Fariborz Jahanian09cc10f2009-11-04 17:57:40 +0000640 llvm::BasicBlock *SwitchBlock = CE.CleanupExitBlock;
Anders Carlsson66c384a2009-02-08 07:46:24 +0000641 llvm::BasicBlock *EndBlock = 0;
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000642 if (!BranchFixups.empty()) {
Fariborz Jahanian09cc10f2009-11-04 17:57:40 +0000643 if (!SwitchBlock)
644 SwitchBlock = createBasicBlock("cleanup.switch");
Anders Carlsson66c384a2009-02-08 07:46:24 +0000645 EndBlock = createBasicBlock("cleanup.end");
Mike Stump11289f42009-09-09 15:08:12 +0000646
Anders Carlsson66c384a2009-02-08 07:46:24 +0000647 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
Mike Stump11289f42009-09-09 15:08:12 +0000648
Anders Carlsson66c384a2009-02-08 07:46:24 +0000649 Builder.SetInsertPoint(SwitchBlock);
650
Mike Stump33270212009-12-02 07:41:41 +0000651 llvm::Value *DestCodePtr
652 = CreateTempAlloca(llvm::Type::getInt32Ty(VMContext),
653 "cleanup.dst");
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000654 llvm::Value *DestCode = Builder.CreateLoad(DestCodePtr, "tmp");
Mike Stump11289f42009-09-09 15:08:12 +0000655
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000656 // Create a switch instruction to determine where to jump next.
Mike Stump11289f42009-09-09 15:08:12 +0000657 llvm::SwitchInst *SI = Builder.CreateSwitch(DestCode, EndBlock,
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000658 BranchFixups.size());
Anders Carlsson66c384a2009-02-08 07:46:24 +0000659
Anders Carlsson76180ea2009-02-08 22:13:37 +0000660 // Restore the current basic block (if any)
Anders Carlssone73e3ec2009-03-17 05:53:35 +0000661 if (CurBB) {
Anders Carlsson76180ea2009-02-08 22:13:37 +0000662 Builder.SetInsertPoint(CurBB);
Mike Stump11289f42009-09-09 15:08:12 +0000663
Anders Carlssone73e3ec2009-03-17 05:53:35 +0000664 // If we had a current basic block, we also need to emit an instruction
665 // to initialize the cleanup destination.
Owen Anderson41a75022009-08-13 21:57:51 +0000666 Builder.CreateStore(llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)),
Anders Carlssone73e3ec2009-03-17 05:53:35 +0000667 DestCodePtr);
668 } else
Anders Carlsson76180ea2009-02-08 22:13:37 +0000669 Builder.ClearInsertionPoint();
Anders Carlsson66c384a2009-02-08 07:46:24 +0000670
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000671 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
672 llvm::BranchInst *BI = BranchFixups[i];
673 llvm::BasicBlock *Dest = BI->getSuccessor(0);
Mike Stump11289f42009-09-09 15:08:12 +0000674
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000675 // Fixup the branch instruction to point to the cleanup block.
Fariborz Jahanian09cc10f2009-11-04 17:57:40 +0000676 BI->setSuccessor(0, CleanupEntryBlock);
Mike Stump11289f42009-09-09 15:08:12 +0000677
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000678 if (CleanupEntries.empty()) {
Anders Carlsson9c964ac2009-02-08 22:46:50 +0000679 llvm::ConstantInt *ID;
Mike Stump11289f42009-09-09 15:08:12 +0000680
Anders Carlsson9c964ac2009-02-08 22:46:50 +0000681 // Check if we already have a destination for this block.
682 if (Dest == SI->getDefaultDest())
Owen Anderson41a75022009-08-13 21:57:51 +0000683 ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0);
Anders Carlsson9c964ac2009-02-08 22:46:50 +0000684 else {
685 ID = SI->findCaseDest(Dest);
686 if (!ID) {
687 // No code found, get a new unique one by using the number of
688 // switch successors.
Mike Stump11289f42009-09-09 15:08:12 +0000689 ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anders Carlsson9c964ac2009-02-08 22:46:50 +0000690 SI->getNumSuccessors());
691 SI->addCase(ID, Dest);
692 }
693 }
Mike Stump11289f42009-09-09 15:08:12 +0000694
Anders Carlsson9c964ac2009-02-08 22:46:50 +0000695 // Store the jump destination before the branch instruction.
696 new llvm::StoreInst(ID, DestCodePtr, BI);
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000697 } else {
698 // We need to jump through another cleanup block. Create a pad block
Mike Stump33270212009-12-02 07:41:41 +0000699 // with a branch instruction that jumps to the final destination and add
700 // it as a branch fixup to the current cleanup scope.
Mike Stump11289f42009-09-09 15:08:12 +0000701
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000702 // Create the pad block.
703 llvm::BasicBlock *CleanupPad = createBasicBlock("cleanup.pad", CurFn);
Anders Carlsson9c964ac2009-02-08 22:46:50 +0000704
705 // Create a unique case ID.
Mike Stump33270212009-12-02 07:41:41 +0000706 llvm::ConstantInt *ID
707 = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
708 SI->getNumSuccessors());
Anders Carlsson9c964ac2009-02-08 22:46:50 +0000709
710 // Store the jump destination before the branch instruction.
711 new llvm::StoreInst(ID, DestCodePtr, BI);
712
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000713 // Add it as the destination.
Anders Carlsson9c964ac2009-02-08 22:46:50 +0000714 SI->addCase(ID, CleanupPad);
Mike Stump11289f42009-09-09 15:08:12 +0000715
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000716 // Create the branch to the final destination.
717 llvm::BranchInst *BI = llvm::BranchInst::Create(Dest);
718 CleanupPad->getInstList().push_back(BI);
Mike Stump11289f42009-09-09 15:08:12 +0000719
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000720 // And add it as a branch fixup.
721 CleanupEntries.back().BranchFixups.push_back(BI);
722 }
723 }
724 }
Mike Stump11289f42009-09-09 15:08:12 +0000725
Anders Carlssonfbfb5e62009-02-08 00:16:35 +0000726 // Remove all blocks from the block scope map.
727 for (size_t i = 0, e = Blocks.size(); i != e; ++i) {
728 assert(BlockScopes.count(Blocks[i]) &&
729 "Did not find block in scope map!");
Mike Stump11289f42009-09-09 15:08:12 +0000730
Anders Carlssonfbfb5e62009-02-08 00:16:35 +0000731 BlockScopes.erase(Blocks[i]);
732 }
Mike Stump11289f42009-09-09 15:08:12 +0000733
Mike Stump33270212009-12-02 07:41:41 +0000734 return CleanupBlockInfo(CleanupEntryBlock, SwitchBlock, EndBlock, EHOnly);
Anders Carlssonae91d9b2009-02-08 03:55:35 +0000735}
736
Mike Stump11289f42009-09-09 15:08:12 +0000737void CodeGenFunction::EmitCleanupBlock() {
Anders Carlsson66c384a2009-02-08 07:46:24 +0000738 CleanupBlockInfo Info = PopCleanupBlock();
Mike Stump11289f42009-09-09 15:08:12 +0000739
Mike Stump33270212009-12-02 07:41:41 +0000740 if (Info.EHOnly) {
741 // FIXME: Add this to the exceptional edge
742 if (Info.CleanupBlock->getNumUses() == 0)
743 delete Info.CleanupBlock;
744 return;
745 }
746
Anders Carlssonf3f91ce2009-05-31 00:33:20 +0000747 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
Mike Stump11289f42009-09-09 15:08:12 +0000748 if (CurBB && !CurBB->getTerminator() &&
Anders Carlssonf3f91ce2009-05-31 00:33:20 +0000749 Info.CleanupBlock->getNumUses() == 0) {
750 CurBB->getInstList().splice(CurBB->end(), Info.CleanupBlock->getInstList());
751 delete Info.CleanupBlock;
Mike Stump11289f42009-09-09 15:08:12 +0000752 } else
Anders Carlssonf3f91ce2009-05-31 00:33:20 +0000753 EmitBlock(Info.CleanupBlock);
Mike Stump11289f42009-09-09 15:08:12 +0000754
Anders Carlsson66c384a2009-02-08 07:46:24 +0000755 if (Info.SwitchBlock)
756 EmitBlock(Info.SwitchBlock);
757 if (Info.EndBlock)
758 EmitBlock(Info.EndBlock);
Anders Carlssonae91d9b2009-02-08 03:55:35 +0000759}
760
Mike Stump11289f42009-09-09 15:08:12 +0000761void CodeGenFunction::AddBranchFixup(llvm::BranchInst *BI) {
762 assert(!CleanupEntries.empty() &&
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000763 "Trying to add branch fixup without cleanup block!");
Mike Stump11289f42009-09-09 15:08:12 +0000764
Mike Stump18bb9282009-05-16 07:57:57 +0000765 // FIXME: We could be more clever here and check if there's already a branch
766 // fixup for this destination and recycle it.
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000767 CleanupEntries.back().BranchFixups.push_back(BI);
768}
769
Mike Stump11289f42009-09-09 15:08:12 +0000770void CodeGenFunction::EmitBranchThroughCleanup(llvm::BasicBlock *Dest) {
Anders Carlsson76180ea2009-02-08 22:13:37 +0000771 if (!HaveInsertPoint())
772 return;
Mike Stump11289f42009-09-09 15:08:12 +0000773
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000774 llvm::BranchInst* BI = Builder.CreateBr(Dest);
Mike Stump11289f42009-09-09 15:08:12 +0000775
Anders Carlsson76180ea2009-02-08 22:13:37 +0000776 Builder.ClearInsertionPoint();
Mike Stump11289f42009-09-09 15:08:12 +0000777
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000778 // The stack is empty, no need to do any cleanup.
779 if (CleanupEntries.empty())
780 return;
Mike Stump11289f42009-09-09 15:08:12 +0000781
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000782 if (!Dest->getParent()) {
783 // We are trying to branch to a block that hasn't been inserted yet.
784 AddBranchFixup(BI);
785 return;
786 }
Mike Stump11289f42009-09-09 15:08:12 +0000787
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000788 BlockScopeMap::iterator I = BlockScopes.find(Dest);
789 if (I == BlockScopes.end()) {
790 // We are trying to jump to a block that is outside of any cleanup scope.
791 AddBranchFixup(BI);
792 return;
793 }
Mike Stump11289f42009-09-09 15:08:12 +0000794
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000795 assert(I->second < CleanupEntries.size() &&
796 "Trying to branch into cleanup region");
Mike Stump11289f42009-09-09 15:08:12 +0000797
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000798 if (I->second == CleanupEntries.size() - 1) {
799 // We have a branch to a block in the same scope.
800 return;
801 }
Mike Stump11289f42009-09-09 15:08:12 +0000802
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000803 AddBranchFixup(BI);
804}