blob: 85758461622a49c83a3d5ea3b0478892aeb702e0 [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"
John McCall4c40d982010-08-31 07:33:07 +000016#include "CGCXXABI.h"
Eli Friedman3f2af102008-05-22 01:40:10 +000017#include "CGDebugInfo.h"
John McCallf1549f62010-07-06 01:34:17 +000018#include "CGException.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000019#include "clang/Basic/TargetInfo.h"
Chris Lattner31a09842008-11-12 08:04:58 +000020#include "clang/AST/APValue.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000021#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000022#include "clang/AST/Decl.h"
Anders Carlsson2b77ba82009-04-04 20:47:02 +000023#include "clang/AST/DeclCXX.h"
Mike Stump6a1e0eb2009-12-04 23:26:17 +000024#include "clang/AST/StmtCXX.h"
Chris Lattner7255a2d2010-06-22 00:03:40 +000025#include "clang/Frontend/CodeGenOptions.h"
Mike Stump4e7a1f72009-02-21 20:00:35 +000026#include "llvm/Target/TargetData.h"
Chris Lattner7255a2d2010-06-22 00:03:40 +000027#include "llvm/Intrinsics.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000028using namespace clang;
29using namespace CodeGen;
30
John McCall8abdbd82010-09-18 02:24:39 +000031static void ResolveAllBranchFixups(CodeGenFunction &CGF,
32 llvm::SwitchInst *Switch,
33 llvm::BasicBlock *CleanupEntry);
34
Mike Stump1eb44332009-09-09 15:08:12 +000035CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
Mike Stumpa4f668f2009-03-06 01:33:24 +000036 : BlockFunction(cgm, *this, Builder), CGM(cgm),
37 Target(CGM.getContext().Target),
Owen Andersonaac87052009-07-08 20:52:20 +000038 Builder(cgm.getModule().getContext()),
John McCallff8e1152010-07-23 21:56:41 +000039 NormalCleanupDest(0), EHCleanupDest(0), NextCleanupDestIndex(1),
John McCallf1549f62010-07-06 01:34:17 +000040 ExceptionSlot(0), DebugInfo(0), IndirectBranch(0),
John McCallff8e1152010-07-23 21:56:41 +000041 SwitchInsn(0), CaseRangeBlock(0),
John McCallf1549f62010-07-06 01:34:17 +000042 DidCallStackSave(false), UnreachableBlock(0),
John McCall25049412010-02-16 22:04:33 +000043 CXXThisDecl(0), CXXThisValue(0), CXXVTTDecl(0), CXXVTTValue(0),
John McCallf1549f62010-07-06 01:34:17 +000044 ConditionalBranchLevel(0), TerminateLandingPad(0), TerminateHandler(0),
Chris Lattner83252dc2010-07-20 21:07:09 +000045 TrapBB(0) {
Chris Lattner77b89b82010-06-27 07:15:29 +000046
47 // Get some frequently used types.
Mike Stump4e7a1f72009-02-21 20:00:35 +000048 LLVMPointerWidth = Target.getPointerWidth(0);
Chris Lattner77b89b82010-06-27 07:15:29 +000049 llvm::LLVMContext &LLVMContext = CGM.getLLVMContext();
50 IntPtrTy = llvm::IntegerType::get(LLVMContext, LLVMPointerWidth);
51 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
52 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
53
Mike Stumpd88ea562009-12-09 03:35:49 +000054 Exceptions = getContext().getLangOptions().Exceptions;
Mike Stump9c276ae2009-12-12 01:27:46 +000055 CatchUndefined = getContext().getLangOptions().CatchUndefined;
John McCall4c40d982010-08-31 07:33:07 +000056 CGM.getCXXABI().getMangleContext().startNewFunction();
Chris Lattner41110242008-06-17 18:05:57 +000057}
Reid Spencer5f016e22007-07-11 17:01:13 +000058
59ASTContext &CodeGenFunction::getContext() const {
60 return CGM.getContext();
61}
62
63
Daniel Dunbar8b1a3432009-02-03 23:03:55 +000064const llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
65 return CGM.getTypes().ConvertTypeForMem(T);
66}
67
Reid Spencer5f016e22007-07-11 17:01:13 +000068const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
69 return CGM.getTypes().ConvertType(T);
70}
71
72bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
Anders Carlssone9d34dc2009-09-29 02:09:01 +000073 return T->isRecordType() || T->isArrayType() || T->isAnyComplexType() ||
John McCalld608cdb2010-08-22 10:59:02 +000074 T->isObjCObjectType();
Reid Spencer5f016e22007-07-11 17:01:13 +000075}
76
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000077void CodeGenFunction::EmitReturnBlock() {
78 // For cleanliness, we try to avoid emitting the return block for
79 // simple cases.
80 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
81
82 if (CurBB) {
83 assert(!CurBB->getTerminator() && "Unexpected terminated block.");
84
Daniel Dunbar96e18b02009-07-19 08:24:34 +000085 // We have a valid insert point, reuse it if it is empty or there are no
86 // explicit jumps to the return block.
John McCallff8e1152010-07-23 21:56:41 +000087 if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) {
88 ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
89 delete ReturnBlock.getBlock();
Daniel Dunbar96e18b02009-07-19 08:24:34 +000090 } else
John McCallff8e1152010-07-23 21:56:41 +000091 EmitBlock(ReturnBlock.getBlock());
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000092 return;
93 }
94
95 // Otherwise, if the return block is the target of a single direct
96 // branch then we can just put the code in that block instead. This
97 // cleans up functions which started with a unified return block.
John McCallff8e1152010-07-23 21:56:41 +000098 if (ReturnBlock.getBlock()->hasOneUse()) {
Mike Stump1eb44332009-09-09 15:08:12 +000099 llvm::BranchInst *BI =
John McCallff8e1152010-07-23 21:56:41 +0000100 dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->use_begin());
John McCallf1549f62010-07-06 01:34:17 +0000101 if (BI && BI->isUnconditional() &&
John McCallff8e1152010-07-23 21:56:41 +0000102 BI->getSuccessor(0) == ReturnBlock.getBlock()) {
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000103 // Reset insertion point and delete the branch.
104 Builder.SetInsertPoint(BI->getParent());
105 BI->eraseFromParent();
John McCallff8e1152010-07-23 21:56:41 +0000106 delete ReturnBlock.getBlock();
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000107 return;
108 }
109 }
110
Mike Stumpf5408fe2009-05-16 07:57:57 +0000111 // FIXME: We are at an unreachable point, there is no reason to emit the block
112 // unless it has uses. However, we still need a place to put the debug
113 // region.end for now.
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000114
John McCallff8e1152010-07-23 21:56:41 +0000115 EmitBlock(ReturnBlock.getBlock());
John McCallf1549f62010-07-06 01:34:17 +0000116}
117
118static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
119 if (!BB) return;
120 if (!BB->use_empty())
121 return CGF.CurFn->getBasicBlockList().push_back(BB);
122 delete BB;
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000123}
124
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000125void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
Chris Lattnerda138702007-07-16 21:28:45 +0000126 assert(BreakContinueStack.empty() &&
127 "mismatched push/pop in break/continue stack!");
Mike Stump1eb44332009-09-09 15:08:12 +0000128
129 // Emit function epilog (to return).
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000130 EmitReturnBlock();
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000131
Chris Lattner7255a2d2010-06-22 00:03:40 +0000132 EmitFunctionInstrumentation("__cyg_profile_func_exit");
133
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000134 // Emit debug descriptor for function end.
Anders Carlssone896d982009-02-13 08:11:52 +0000135 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000136 DI->setLocation(EndLoc);
Devang Patel5a6fbcf2010-07-22 22:29:16 +0000137 DI->EmitFunctionEnd(Builder);
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000138 }
139
Chris Lattner35b21b82010-06-27 01:06:27 +0000140 EmitFunctionEpilog(*CurFnInfo);
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000141 EmitEndEHSpec(CurCodeDecl);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000142
John McCallf1549f62010-07-06 01:34:17 +0000143 assert(EHStack.empty() &&
144 "did not remove all scopes from cleanup stack!");
145
Chris Lattnerd9becd12009-10-28 23:59:40 +0000146 // If someone did an indirect goto, emit the indirect goto block at the end of
147 // the function.
148 if (IndirectBranch) {
149 EmitBlock(IndirectBranch->getParent());
150 Builder.ClearInsertionPoint();
151 }
152
Chris Lattner5a2fa142007-12-02 06:32:24 +0000153 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
Chris Lattner481769b2009-03-31 22:17:44 +0000154 llvm::Instruction *Ptr = AllocaInsertPt;
Chris Lattner5a2fa142007-12-02 06:32:24 +0000155 AllocaInsertPt = 0;
Chris Lattner481769b2009-03-31 22:17:44 +0000156 Ptr->eraseFromParent();
Chris Lattnerd9becd12009-10-28 23:59:40 +0000157
158 // If someone took the address of a label but never did an indirect goto, we
159 // made a zero entry PHI node, which is illegal, zap it now.
160 if (IndirectBranch) {
161 llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
162 if (PN->getNumIncomingValues() == 0) {
163 PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
164 PN->eraseFromParent();
165 }
166 }
John McCallf1549f62010-07-06 01:34:17 +0000167
John McCallff8e1152010-07-23 21:56:41 +0000168 EmitIfUsed(*this, RethrowBlock.getBlock());
John McCallf1549f62010-07-06 01:34:17 +0000169 EmitIfUsed(*this, TerminateLandingPad);
170 EmitIfUsed(*this, TerminateHandler);
171 EmitIfUsed(*this, UnreachableBlock);
John McCall744016d2010-07-06 23:57:41 +0000172
173 if (CGM.getCodeGenOpts().EmitDeclMetadata)
174 EmitDeclMetadata();
Reid Spencer5f016e22007-07-11 17:01:13 +0000175}
176
Chris Lattner7255a2d2010-06-22 00:03:40 +0000177/// ShouldInstrumentFunction - Return true if the current function should be
178/// instrumented with __cyg_profile_func_* calls
179bool CodeGenFunction::ShouldInstrumentFunction() {
180 if (!CGM.getCodeGenOpts().InstrumentFunctions)
181 return false;
182 if (CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
183 return false;
184 return true;
185}
186
187/// EmitFunctionInstrumentation - Emit LLVM code to call the specified
188/// instrumentation function with the current function and the call site, if
189/// function instrumentation is enabled.
190void CodeGenFunction::EmitFunctionInstrumentation(const char *Fn) {
191 if (!ShouldInstrumentFunction())
192 return;
193
Chris Lattner8dab6572010-06-23 05:21:28 +0000194 const llvm::PointerType *PointerTy;
Chris Lattner7255a2d2010-06-22 00:03:40 +0000195 const llvm::FunctionType *FunctionTy;
196 std::vector<const llvm::Type*> ProfileFuncArgs;
197
Chris Lattner8dab6572010-06-23 05:21:28 +0000198 // void __cyg_profile_func_{enter,exit} (void *this_fn, void *call_site);
199 PointerTy = llvm::Type::getInt8PtrTy(VMContext);
200 ProfileFuncArgs.push_back(PointerTy);
201 ProfileFuncArgs.push_back(PointerTy);
Chris Lattner7255a2d2010-06-22 00:03:40 +0000202 FunctionTy = llvm::FunctionType::get(
203 llvm::Type::getVoidTy(VMContext),
204 ProfileFuncArgs, false);
205
206 llvm::Constant *F = CGM.CreateRuntimeFunction(FunctionTy, Fn);
207 llvm::CallInst *CallSite = Builder.CreateCall(
208 CGM.getIntrinsic(llvm::Intrinsic::returnaddress, 0, 0),
Chris Lattner77b89b82010-06-27 07:15:29 +0000209 llvm::ConstantInt::get(Int32Ty, 0),
Chris Lattner7255a2d2010-06-22 00:03:40 +0000210 "callsite");
211
Chris Lattner8dab6572010-06-23 05:21:28 +0000212 Builder.CreateCall2(F,
213 llvm::ConstantExpr::getBitCast(CurFn, PointerTy),
214 CallSite);
Chris Lattner7255a2d2010-06-22 00:03:40 +0000215}
216
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000217void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
Daniel Dunbar7c086512008-09-09 23:14:03 +0000218 llvm::Function *Fn,
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000219 const FunctionArgList &Args,
220 SourceLocation StartLoc) {
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000221 const Decl *D = GD.getDecl();
222
Anders Carlsson4cc1a472009-02-09 20:20:56 +0000223 DidCallStackSave = false;
Chris Lattnerb5437d22009-04-23 05:30:27 +0000224 CurCodeDecl = CurFuncDecl = D;
Daniel Dunbar7c086512008-09-09 23:14:03 +0000225 FnRetTy = RetTy;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000226 CurFn = Fn;
Chris Lattner41110242008-06-17 18:05:57 +0000227 assert(CurFn->isDeclaration() && "Function already has body?");
228
Jakob Stoklund Olesena3fe2842010-02-09 00:10:00 +0000229 // Pass inline keyword to optimizer if it appears explicitly on any
230 // declaration.
231 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
232 for (FunctionDecl::redecl_iterator RI = FD->redecls_begin(),
233 RE = FD->redecls_end(); RI != RE; ++RI)
234 if (RI->isInlineSpecified()) {
235 Fn->addFnAttr(llvm::Attribute::InlineHint);
236 break;
237 }
238
Daniel Dunbar55e87422008-11-11 02:29:29 +0000239 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000240
Chris Lattner41110242008-06-17 18:05:57 +0000241 // Create a marker to make it easy to insert allocas into the entryblock
242 // later. Don't create this with the builder, because we don't want it
243 // folded.
Chris Lattner77b89b82010-06-27 07:15:29 +0000244 llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
245 AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "", EntryBB);
Chris Lattnerf1466842009-03-22 00:24:14 +0000246 if (Builder.isNamePreserving())
247 AllocaInsertPt->setName("allocapt");
Mike Stump1eb44332009-09-09 15:08:12 +0000248
John McCallf1549f62010-07-06 01:34:17 +0000249 ReturnBlock = getJumpDestInCurrentScope("return");
Mike Stump1eb44332009-09-09 15:08:12 +0000250
Chris Lattner41110242008-06-17 18:05:57 +0000251 Builder.SetInsertPoint(EntryBB);
Mike Stump1eb44332009-09-09 15:08:12 +0000252
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000253 // Emit subprogram debug descriptor.
Anders Carlssone896d982009-02-13 08:11:52 +0000254 if (CGDebugInfo *DI = getDebugInfo()) {
John McCalle23cf432010-12-14 08:05:40 +0000255 // FIXME: what is going on here and why does it ignore all these
256 // interesting type properties?
257 QualType FnType =
258 getContext().getFunctionType(RetTy, 0, 0,
259 FunctionProtoType::ExtProtoInfo());
260
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000261 DI->setLocation(StartLoc);
Devang Patel9c6c3a02010-01-14 00:36:21 +0000262 DI->EmitFunctionStart(GD, FnType, CurFn, Builder);
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000263 }
264
Chris Lattner7255a2d2010-06-22 00:03:40 +0000265 EmitFunctionInstrumentation("__cyg_profile_func_enter");
266
Daniel Dunbar88b53962009-02-02 22:03:45 +0000267 // FIXME: Leaked.
John McCall04a67a62010-02-05 21:31:56 +0000268 // CC info is ignored, hopefully?
269 CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args,
Rafael Espindola264ba482010-03-30 20:24:48 +0000270 FunctionType::ExtInfo());
Eli Friedmanb17daf92009-12-04 02:43:40 +0000271
272 if (RetTy->isVoidType()) {
273 // Void type; nothing to return.
274 ReturnValue = 0;
275 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
276 hasAggregateLLVMType(CurFnInfo->getReturnType())) {
277 // Indirect aggregate return; emit returned value directly into sret slot.
Daniel Dunbar647a1ec2010-02-16 19:45:20 +0000278 // This reduces code size, and affects correctness in C++.
Eli Friedmanb17daf92009-12-04 02:43:40 +0000279 ReturnValue = CurFn->arg_begin();
280 } else {
Daniel Dunbar647a1ec2010-02-16 19:45:20 +0000281 ReturnValue = CreateIRTemp(RetTy, "retval");
Eli Friedmanb17daf92009-12-04 02:43:40 +0000282 }
283
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000284 EmitStartEHSpec(CurCodeDecl);
Daniel Dunbar88b53962009-02-02 22:03:45 +0000285 EmitFunctionProlog(*CurFnInfo, CurFn, Args);
Mike Stump1eb44332009-09-09 15:08:12 +0000286
John McCall4c40d982010-08-31 07:33:07 +0000287 if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance())
288 CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
John McCall25049412010-02-16 22:04:33 +0000289
Anders Carlsson751358f2008-12-20 21:28:43 +0000290 // If any of the arguments have a variably modified type, make sure to
291 // emit the type size.
292 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
293 i != e; ++i) {
294 QualType Ty = i->second;
295
296 if (Ty->isVariablyModifiedType())
297 EmitVLASize(Ty);
298 }
Daniel Dunbar7c086512008-09-09 23:14:03 +0000299}
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000300
John McCall9fc6a772010-02-19 09:25:03 +0000301void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args) {
302 const FunctionDecl *FD = cast<FunctionDecl>(CurGD.getDecl());
Douglas Gregor06a9f362010-05-01 20:49:11 +0000303 assert(FD->getBody());
304 EmitStmt(FD->getBody());
John McCalla355e072010-02-18 03:17:58 +0000305}
306
John McCall39dad532010-08-03 22:46:07 +0000307/// Tries to mark the given function nounwind based on the
308/// non-existence of any throwing calls within it. We believe this is
309/// lightweight enough to do at -O0.
310static void TryMarkNoThrow(llvm::Function *F) {
John McCallb3a29f12010-08-11 22:38:33 +0000311 // LLVM treats 'nounwind' on a function as part of the type, so we
312 // can't do this on functions that can be overwritten.
313 if (F->mayBeOverridden()) return;
314
John McCall39dad532010-08-03 22:46:07 +0000315 for (llvm::Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI)
316 for (llvm::BasicBlock::iterator
317 BI = FI->begin(), BE = FI->end(); BI != BE; ++BI)
318 if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(&*BI))
319 if (!Call->doesNotThrow())
320 return;
321 F->setDoesNotThrow(true);
322}
323
Anders Carlssonc997d422010-01-02 01:01:18 +0000324void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn) {
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000325 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
326
Anders Carlssone896d982009-02-13 08:11:52 +0000327 // Check if we should generate debug info for this function.
Mike Stump1feade82009-08-26 22:31:08 +0000328 if (CGM.getDebugInfo() && !FD->hasAttr<NoDebugAttr>())
Anders Carlssone896d982009-02-13 08:11:52 +0000329 DebugInfo = CGM.getDebugInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000330
Daniel Dunbar7c086512008-09-09 23:14:03 +0000331 FunctionArgList Args;
John McCall4c40d982010-08-31 07:33:07 +0000332 QualType ResTy = FD->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +0000333
Mike Stump6a1e0eb2009-12-04 23:26:17 +0000334 CurGD = GD;
John McCall4c40d982010-08-31 07:33:07 +0000335 if (isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isInstance())
336 CGM.getCXXABI().BuildInstanceFunctionParams(*this, ResTy, Args);
Mike Stump1eb44332009-09-09 15:08:12 +0000337
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000338 if (FD->getNumParams()) {
John McCall183700f2009-09-21 23:43:11 +0000339 const FunctionProtoType* FProto = FD->getType()->getAs<FunctionProtoType>();
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000340 assert(FProto && "Function def must have prototype!");
Daniel Dunbar7c086512008-09-09 23:14:03 +0000341
342 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
Mike Stump1eb44332009-09-09 15:08:12 +0000343 Args.push_back(std::make_pair(FD->getParamDecl(i),
Daniel Dunbar7c086512008-09-09 23:14:03 +0000344 FProto->getArgType(i)));
Chris Lattner41110242008-06-17 18:05:57 +0000345 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000346
John McCalla355e072010-02-18 03:17:58 +0000347 SourceRange BodyRange;
348 if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange();
Anders Carlsson4365bba2009-11-06 02:55:43 +0000349
John McCalla355e072010-02-18 03:17:58 +0000350 // Emit the standard function prologue.
John McCall4c40d982010-08-31 07:33:07 +0000351 StartFunction(GD, ResTy, Fn, Args, BodyRange.getBegin());
Anders Carlsson4365bba2009-11-06 02:55:43 +0000352
John McCalla355e072010-02-18 03:17:58 +0000353 // Generate the body of the function.
John McCall9fc6a772010-02-19 09:25:03 +0000354 if (isa<CXXDestructorDecl>(FD))
355 EmitDestructorBody(Args);
356 else if (isa<CXXConstructorDecl>(FD))
357 EmitConstructorBody(Args);
358 else
359 EmitFunctionBody(Args);
Anders Carlsson1851a122010-02-07 19:45:40 +0000360
John McCalla355e072010-02-18 03:17:58 +0000361 // Emit the standard function epilogue.
362 FinishFunction(BodyRange.getEnd());
John McCall39dad532010-08-03 22:46:07 +0000363
364 // If we haven't marked the function nothrow through other means, do
365 // a quick pass now to see if we can.
366 if (!CurFn->doesNotThrow())
367 TryMarkNoThrow(CurFn);
Chris Lattner41110242008-06-17 18:05:57 +0000368}
369
Chris Lattner0946ccd2008-11-11 07:41:27 +0000370/// ContainsLabel - Return true if the statement contains a label in it. If
371/// this statement is not executed normally, it not containing a label means
372/// that we can just remove the code.
373bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
374 // Null statement, not a label!
375 if (S == 0) return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000376
Chris Lattner0946ccd2008-11-11 07:41:27 +0000377 // If this is a label, we have to emit the code, consider something like:
378 // if (0) { ... foo: bar(); } goto foo;
379 if (isa<LabelStmt>(S))
380 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000381
Chris Lattner0946ccd2008-11-11 07:41:27 +0000382 // If this is a case/default statement, and we haven't seen a switch, we have
383 // to emit the code.
384 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
385 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000386
Chris Lattner0946ccd2008-11-11 07:41:27 +0000387 // If this is a switch statement, we want to ignore cases below it.
388 if (isa<SwitchStmt>(S))
389 IgnoreCaseStmts = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000390
Chris Lattner0946ccd2008-11-11 07:41:27 +0000391 // Scan subexpressions for verboten labels.
392 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
393 I != E; ++I)
394 if (ContainsLabel(*I, IgnoreCaseStmts))
395 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000396
Chris Lattner0946ccd2008-11-11 07:41:27 +0000397 return false;
398}
399
Chris Lattner31a09842008-11-12 08:04:58 +0000400
401/// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
402/// a constant, or if it does but contains a label, return 0. If it constant
403/// folds to 'true' and does not contain a label, return 1, if it constant folds
404/// to 'false' and does not contain a label, return -1.
405int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
Daniel Dunbar36bc14c2008-11-12 22:37:10 +0000406 // FIXME: Rename and handle conversion of other evaluatable things
407 // to bool.
Anders Carlsson64712f12008-12-01 02:46:24 +0000408 Expr::EvalResult Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000409 if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
Anders Carlsson64712f12008-12-01 02:46:24 +0000410 Result.HasSideEffects)
Anders Carlssonef5a66d2008-11-22 22:32:07 +0000411 return 0; // Not foldable, not integer or not fully evaluatable.
Mike Stump1eb44332009-09-09 15:08:12 +0000412
Chris Lattner31a09842008-11-12 08:04:58 +0000413 if (CodeGenFunction::ContainsLabel(Cond))
414 return 0; // Contains a label.
Mike Stump1eb44332009-09-09 15:08:12 +0000415
Anders Carlsson64712f12008-12-01 02:46:24 +0000416 return Result.Val.getInt().getBoolValue() ? 1 : -1;
Chris Lattner31a09842008-11-12 08:04:58 +0000417}
418
419
420/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
421/// statement) to the specified blocks. Based on the condition, this might try
422/// to simplify the codegen of the conditional based on the branch.
423///
424void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
425 llvm::BasicBlock *TrueBlock,
426 llvm::BasicBlock *FalseBlock) {
427 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
428 return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000429
Chris Lattner31a09842008-11-12 08:04:58 +0000430 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
431 // Handle X && Y in a condition.
John McCall2de56d12010-08-25 11:45:40 +0000432 if (CondBOp->getOpcode() == BO_LAnd) {
Chris Lattner31a09842008-11-12 08:04:58 +0000433 // If we have "1 && X", simplify the code. "0 && X" would have constant
434 // folded if the case was simple enough.
435 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
436 // br(1 && X) -> br(X).
437 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
438 }
Mike Stump1eb44332009-09-09 15:08:12 +0000439
Chris Lattner31a09842008-11-12 08:04:58 +0000440 // If we have "X && 1", simplify the code to use an uncond branch.
441 // "X && 0" would have been constant folded to 0.
442 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
443 // br(X && 1) -> br(X).
444 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
445 }
Mike Stump1eb44332009-09-09 15:08:12 +0000446
Chris Lattner31a09842008-11-12 08:04:58 +0000447 // Emit the LHS as a conditional. If the LHS conditional is false, we
448 // want to jump to the FalseBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000449 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
Chris Lattner31a09842008-11-12 08:04:58 +0000450 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
451 EmitBlock(LHSTrue);
Mike Stump1eb44332009-09-09 15:08:12 +0000452
Anders Carlsson08e9e452010-01-24 00:20:05 +0000453 // Any temporaries created here are conditional.
Anders Carlsson72119a82010-02-04 17:18:07 +0000454 BeginConditionalBranch();
Chris Lattner31a09842008-11-12 08:04:58 +0000455 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
Anders Carlsson72119a82010-02-04 17:18:07 +0000456 EndConditionalBranch();
Anders Carlsson08e9e452010-01-24 00:20:05 +0000457
Chris Lattner31a09842008-11-12 08:04:58 +0000458 return;
John McCall2de56d12010-08-25 11:45:40 +0000459 } else if (CondBOp->getOpcode() == BO_LOr) {
Chris Lattner31a09842008-11-12 08:04:58 +0000460 // If we have "0 || X", simplify the code. "1 || X" would have constant
461 // folded if the case was simple enough.
462 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
463 // br(0 || X) -> br(X).
464 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
465 }
Mike Stump1eb44332009-09-09 15:08:12 +0000466
Chris Lattner31a09842008-11-12 08:04:58 +0000467 // If we have "X || 0", simplify the code to use an uncond branch.
468 // "X || 1" would have been constant folded to 1.
469 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
470 // br(X || 0) -> br(X).
471 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
472 }
Mike Stump1eb44332009-09-09 15:08:12 +0000473
Chris Lattner31a09842008-11-12 08:04:58 +0000474 // Emit the LHS as a conditional. If the LHS conditional is true, we
475 // want to jump to the TrueBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000476 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
Chris Lattner31a09842008-11-12 08:04:58 +0000477 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
478 EmitBlock(LHSFalse);
Mike Stump1eb44332009-09-09 15:08:12 +0000479
Anders Carlsson08e9e452010-01-24 00:20:05 +0000480 // Any temporaries created here are conditional.
Anders Carlsson72119a82010-02-04 17:18:07 +0000481 BeginConditionalBranch();
Chris Lattner31a09842008-11-12 08:04:58 +0000482 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
Anders Carlsson72119a82010-02-04 17:18:07 +0000483 EndConditionalBranch();
Anders Carlsson08e9e452010-01-24 00:20:05 +0000484
Chris Lattner31a09842008-11-12 08:04:58 +0000485 return;
486 }
Chris Lattner552f4c42008-11-12 08:13:36 +0000487 }
Mike Stump1eb44332009-09-09 15:08:12 +0000488
Chris Lattner552f4c42008-11-12 08:13:36 +0000489 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
490 // br(!x, t, f) -> br(x, f, t)
John McCall2de56d12010-08-25 11:45:40 +0000491 if (CondUOp->getOpcode() == UO_LNot)
Chris Lattner552f4c42008-11-12 08:13:36 +0000492 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
Chris Lattner31a09842008-11-12 08:04:58 +0000493 }
Mike Stump1eb44332009-09-09 15:08:12 +0000494
Daniel Dunbar09b14892008-11-12 10:30:32 +0000495 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
496 // Handle ?: operator.
497
498 // Just ignore GNU ?: extension.
499 if (CondOp->getLHS()) {
500 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
501 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
502 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
503 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
504 EmitBlock(LHSBlock);
505 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
506 EmitBlock(RHSBlock);
507 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
508 return;
509 }
510 }
511
Chris Lattner31a09842008-11-12 08:04:58 +0000512 // Emit the code with the fully general case.
513 llvm::Value *CondV = EvaluateExprAsBool(Cond);
514 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
515}
516
Daniel Dunbar488e9932008-08-16 00:56:44 +0000517/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000518/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000519void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
520 bool OmitOnError) {
521 CGM.ErrorUnsupported(S, Type, OmitOnError);
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000522}
523
Anders Carlsson1884eb02010-05-22 17:35:42 +0000524void
525CodeGenFunction::EmitNullInitialization(llvm::Value *DestPtr, QualType Ty) {
Anders Carlsson0d7c5832010-05-03 01:20:20 +0000526 // Ignore empty classes in C++.
527 if (getContext().getLangOptions().CPlusPlus) {
528 if (const RecordType *RT = Ty->getAs<RecordType>()) {
529 if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
530 return;
531 }
532 }
John McCall90217182010-08-07 08:21:30 +0000533
534 // Cast the dest ptr to the appropriate i8 pointer type.
535 unsigned DestAS =
536 cast<llvm::PointerType>(DestPtr->getType())->getAddressSpace();
Benjamin Kramer9f0c7cc2010-12-30 00:13:21 +0000537 const llvm::Type *BP = Builder.getInt8PtrTy(DestAS);
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000538 if (DestPtr->getType() != BP)
539 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
540
541 // Get size and alignment info for this aggregate.
542 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
Benjamin Kramer9f0c7cc2010-12-30 00:13:21 +0000543 uint64_t Size = TypeInfo.first / 8;
544 unsigned Align = TypeInfo.second / 8;
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000545
John McCall5576d9b2011-01-14 10:37:58 +0000546 llvm::Value *SizeVal;
547 bool vla;
Mike Stump1eb44332009-09-09 15:08:12 +0000548
John McCall5576d9b2011-01-14 10:37:58 +0000549 // Don't bother emitting a zero-byte memset.
550 if (Size == 0) {
551 // But note that getTypeInfo returns 0 for a VLA.
552 if (const VariableArrayType *vlaType =
553 dyn_cast_or_null<VariableArrayType>(
554 getContext().getAsArrayType(Ty))) {
555 SizeVal = GetVLASize(vlaType);
556 vla = true;
557 } else {
558 return;
559 }
560 } else {
561 SizeVal = llvm::ConstantInt::get(IntPtrTy, Size);
562 vla = false;
563 }
John McCall90217182010-08-07 08:21:30 +0000564
565 // If the type contains a pointer to data member we can't memset it to zero.
566 // Instead, create a null constant and copy it to the destination.
John McCallf16aa102010-08-22 21:01:12 +0000567 if (!CGM.getTypes().isZeroInitializable(Ty)) {
John McCall5576d9b2011-01-14 10:37:58 +0000568 // FIXME: variable-size types!
569 if (vla) return;
570
John McCall90217182010-08-07 08:21:30 +0000571 llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
572
573 llvm::GlobalVariable *NullVariable =
574 new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
575 /*isConstant=*/true,
576 llvm::GlobalVariable::PrivateLinkage,
577 NullConstant, llvm::Twine());
578 llvm::Value *SrcPtr =
579 Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy());
580
John McCall90217182010-08-07 08:21:30 +0000581 // Get and call the appropriate llvm.memcpy overload.
Benjamin Kramer9f0c7cc2010-12-30 00:13:21 +0000582 Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align, false);
John McCall90217182010-08-07 08:21:30 +0000583 return;
584 }
585
586 // Otherwise, just memset the whole thing to zero. This is legal
587 // because in LLVM, all default initializers (other than the ones we just
588 // handled above) are guaranteed to have a bit pattern of all zeros.
Benjamin Kramer9f0c7cc2010-12-30 00:13:21 +0000589 Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal, Align, false);
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000590}
591
Chris Lattnerd9becd12009-10-28 23:59:40 +0000592llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelStmt *L) {
593 // Make sure that there is a block for the indirect goto.
594 if (IndirectBranch == 0)
595 GetIndirectGotoBlock();
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000596
John McCallff8e1152010-07-23 21:56:41 +0000597 llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000598
Chris Lattnerd9becd12009-10-28 23:59:40 +0000599 // Make sure the indirect branch includes all of the address-taken blocks.
600 IndirectBranch->addDestination(BB);
601 return llvm::BlockAddress::get(CurFn, BB);
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000602}
603
604llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
Chris Lattnerd9becd12009-10-28 23:59:40 +0000605 // If we already made the indirect branch for indirect goto, return its block.
606 if (IndirectBranch) return IndirectBranch->getParent();
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000607
Chris Lattnerd9becd12009-10-28 23:59:40 +0000608 CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto"));
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000609
Chris Lattnerd9becd12009-10-28 23:59:40 +0000610 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
Chris Lattner85e74ac2009-10-28 20:36:47 +0000611
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000612 // Create the PHI node that indirect gotos will add entries to.
Chris Lattnerd9becd12009-10-28 23:59:40 +0000613 llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, "indirect.goto.dest");
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000614
Chris Lattnerd9becd12009-10-28 23:59:40 +0000615 // Create the indirect branch instruction.
616 IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
617 return IndirectBranch->getParent();
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000618}
Anders Carlssonddf7cac2008-11-04 05:30:00 +0000619
Daniel Dunbard286f052009-07-19 06:58:07 +0000620llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) {
Eli Friedmanbbed6b92009-08-15 02:50:32 +0000621 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
Mike Stump1eb44332009-09-09 15:08:12 +0000622
Anders Carlssonf666b772008-12-20 20:27:15 +0000623 assert(SizeEntry && "Did not emit size for type");
624 return SizeEntry;
625}
Anders Carlssondcc90d82008-12-12 07:19:02 +0000626
Daniel Dunbard286f052009-07-19 06:58:07 +0000627llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) {
Anders Carlsson60d35412008-12-20 20:46:34 +0000628 assert(Ty->isVariablyModifiedType() &&
629 "Must pass variably modified type to EmitVLASizes!");
Mike Stump1eb44332009-09-09 15:08:12 +0000630
Daniel Dunbard286f052009-07-19 06:58:07 +0000631 EnsureInsertPoint();
Mike Stump1eb44332009-09-09 15:08:12 +0000632
Anders Carlsson60d35412008-12-20 20:46:34 +0000633 if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000634 // unknown size indication requires no size computation.
635 if (!VAT->getSizeExpr())
636 return 0;
Eli Friedmanbbed6b92009-08-15 02:50:32 +0000637 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
Mike Stump1eb44332009-09-09 15:08:12 +0000638
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000639 if (!SizeEntry) {
Anders Carlsson96f21472009-02-05 19:43:10 +0000640 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
Mike Stump1eb44332009-09-09 15:08:12 +0000641
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000642 // Get the element size;
643 QualType ElemTy = VAT->getElementType();
644 llvm::Value *ElemSize;
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000645 if (ElemTy->isVariableArrayType())
646 ElemSize = EmitVLASize(ElemTy);
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000647 else
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000648 ElemSize = llvm::ConstantInt::get(SizeTy,
Ken Dyck199c3d62010-01-11 17:06:35 +0000649 getContext().getTypeSizeInChars(ElemTy).getQuantity());
Mike Stump1eb44332009-09-09 15:08:12 +0000650
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000651 llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
Anders Carlsson96f21472009-02-05 19:43:10 +0000652 NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
Mike Stump1eb44332009-09-09 15:08:12 +0000653
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000654 SizeEntry = Builder.CreateMul(ElemSize, NumElements);
Anders Carlsson60d35412008-12-20 20:46:34 +0000655 }
Mike Stump1eb44332009-09-09 15:08:12 +0000656
Anders Carlsson60d35412008-12-20 20:46:34 +0000657 return SizeEntry;
Anders Carlssondcc90d82008-12-12 07:19:02 +0000658 }
Mike Stump1eb44332009-09-09 15:08:12 +0000659
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000660 if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
661 EmitVLASize(AT->getElementType());
662 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000663 }
664
Abramo Bagnara075f8f12010-12-10 16:29:40 +0000665 if (const ParenType *PT = dyn_cast<ParenType>(Ty)) {
666 EmitVLASize(PT->getInnerType());
667 return 0;
668 }
669
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000670 const PointerType *PT = Ty->getAs<PointerType>();
671 assert(PT && "unknown VM type!");
672 EmitVLASize(PT->getPointeeType());
Anders Carlsson60d35412008-12-20 20:46:34 +0000673 return 0;
Anders Carlssondcc90d82008-12-12 07:19:02 +0000674}
Eli Friedman4fd0aa52009-01-20 17:46:04 +0000675
676llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
Dan Gohmanbc07a552010-10-29 22:47:07 +0000677 if (getContext().getBuiltinVaListType()->isArrayType())
Eli Friedman4fd0aa52009-01-20 17:46:04 +0000678 return EmitScalarExpr(E);
Eli Friedman4fd0aa52009-01-20 17:46:04 +0000679 return EmitLValue(E).getAddress();
680}
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000681
John McCallf1549f62010-07-06 01:34:17 +0000682/// Pops cleanup blocks until the given savepoint is reached.
683void CodeGenFunction::PopCleanupBlocks(EHScopeStack::stable_iterator Old) {
684 assert(Old.isValid());
685
John McCallff8e1152010-07-23 21:56:41 +0000686 while (EHStack.stable_begin() != Old) {
687 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.begin());
688
689 // As long as Old strictly encloses the scope's enclosing normal
690 // cleanup, we're going to emit another normal cleanup which
691 // fallthrough can propagate through.
692 bool FallThroughIsBranchThrough =
693 Old.strictlyEncloses(Scope.getEnclosingNormalCleanup());
694
695 PopCleanupBlock(FallThroughIsBranchThrough);
696 }
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000697}
Anders Carlssonc71c8452009-02-07 23:50:39 +0000698
John McCallff8e1152010-07-23 21:56:41 +0000699static llvm::BasicBlock *CreateNormalEntry(CodeGenFunction &CGF,
700 EHCleanupScope &Scope) {
701 assert(Scope.isNormalCleanup());
702 llvm::BasicBlock *Entry = Scope.getNormalBlock();
703 if (!Entry) {
704 Entry = CGF.createBasicBlock("cleanup");
705 Scope.setNormalBlock(Entry);
Mike Stump99533832009-12-02 07:41:41 +0000706 }
John McCallff8e1152010-07-23 21:56:41 +0000707 return Entry;
708}
Mike Stump99533832009-12-02 07:41:41 +0000709
John McCallff8e1152010-07-23 21:56:41 +0000710static llvm::BasicBlock *CreateEHEntry(CodeGenFunction &CGF,
711 EHCleanupScope &Scope) {
712 assert(Scope.isEHCleanup());
713 llvm::BasicBlock *Entry = Scope.getEHBlock();
714 if (!Entry) {
715 Entry = CGF.createBasicBlock("eh.cleanup");
716 Scope.setEHBlock(Entry);
717 }
718 return Entry;
719}
Devang Patelcd9199e2010-04-13 00:08:43 +0000720
John McCallff8e1152010-07-23 21:56:41 +0000721/// Transitions the terminator of the given exit-block of a cleanup to
722/// be a cleanup switch.
723static llvm::SwitchInst *TransitionToCleanupSwitch(CodeGenFunction &CGF,
724 llvm::BasicBlock *Block) {
725 // If it's a branch, turn it into a switch whose default
726 // destination is its original target.
727 llvm::TerminatorInst *Term = Block->getTerminator();
728 assert(Term && "can't transition block without terminator");
729
730 if (llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Term)) {
731 assert(Br->isUnconditional());
732 llvm::LoadInst *Load =
733 new llvm::LoadInst(CGF.getNormalCleanupDestSlot(), "cleanup.dest", Term);
734 llvm::SwitchInst *Switch =
735 llvm::SwitchInst::Create(Load, Br->getSuccessor(0), 4, Block);
736 Br->eraseFromParent();
737 return Switch;
738 } else {
739 return cast<llvm::SwitchInst>(Term);
740 }
Anders Carlssond66a9f92009-02-08 03:55:35 +0000741}
742
John McCallf1549f62010-07-06 01:34:17 +0000743/// Attempts to reduce a cleanup's entry block to a fallthrough. This
744/// is basically llvm::MergeBlockIntoPredecessor, except
John McCallff8e1152010-07-23 21:56:41 +0000745/// simplified/optimized for the tighter constraints on cleanup blocks.
746///
747/// Returns the new block, whatever it is.
748static llvm::BasicBlock *SimplifyCleanupEntry(CodeGenFunction &CGF,
749 llvm::BasicBlock *Entry) {
John McCallf1549f62010-07-06 01:34:17 +0000750 llvm::BasicBlock *Pred = Entry->getSinglePredecessor();
John McCallff8e1152010-07-23 21:56:41 +0000751 if (!Pred) return Entry;
Mike Stump1eb44332009-09-09 15:08:12 +0000752
John McCallf1549f62010-07-06 01:34:17 +0000753 llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Pred->getTerminator());
John McCallff8e1152010-07-23 21:56:41 +0000754 if (!Br || Br->isConditional()) return Entry;
John McCallf1549f62010-07-06 01:34:17 +0000755 assert(Br->getSuccessor(0) == Entry);
756
757 // If we were previously inserting at the end of the cleanup entry
758 // block, we'll need to continue inserting at the end of the
759 // predecessor.
760 bool WasInsertBlock = CGF.Builder.GetInsertBlock() == Entry;
761 assert(!WasInsertBlock || CGF.Builder.GetInsertPoint() == Entry->end());
762
763 // Kill the branch.
764 Br->eraseFromParent();
765
766 // Merge the blocks.
767 Pred->getInstList().splice(Pred->end(), Entry->getInstList());
768
John McCallb8424372011-01-14 10:35:38 +0000769 // Replace all uses of the entry with the predecessor, in case there
770 // are phis in the cleanup.
771 Entry->replaceAllUsesWith(Pred);
772
John McCallf1549f62010-07-06 01:34:17 +0000773 // Kill the entry block.
774 Entry->eraseFromParent();
775
776 if (WasInsertBlock)
777 CGF.Builder.SetInsertPoint(Pred);
Anders Carlsson87eaf172009-02-08 00:50:42 +0000778
John McCallff8e1152010-07-23 21:56:41 +0000779 return Pred;
John McCallf1549f62010-07-06 01:34:17 +0000780}
781
John McCall1f0fca52010-07-21 07:22:38 +0000782static void EmitCleanup(CodeGenFunction &CGF,
783 EHScopeStack::Cleanup *Fn,
John McCall7d8647f2010-09-14 07:57:04 +0000784 bool ForEH,
785 llvm::Value *ActiveFlag) {
786 // EH cleanups always occur within a terminate scope.
John McCallda65ea82010-07-13 20:32:21 +0000787 if (ForEH) CGF.EHStack.pushTerminate();
John McCall7d8647f2010-09-14 07:57:04 +0000788
789 // If there's an active flag, load it and skip the cleanup if it's
790 // false.
791 llvm::BasicBlock *ContBB = 0;
792 if (ActiveFlag) {
793 ContBB = CGF.createBasicBlock("cleanup.done");
794 llvm::BasicBlock *CleanupBB = CGF.createBasicBlock("cleanup.action");
795 llvm::Value *IsActive
796 = CGF.Builder.CreateLoad(ActiveFlag, "cleanup.is_active");
797 CGF.Builder.CreateCondBr(IsActive, CleanupBB, ContBB);
798 CGF.EmitBlock(CleanupBB);
799 }
800
801 // Ask the cleanup to emit itself.
John McCallda65ea82010-07-13 20:32:21 +0000802 Fn->Emit(CGF, ForEH);
John McCallda65ea82010-07-13 20:32:21 +0000803 assert(CGF.HaveInsertPoint() && "cleanup ended with no insertion point?");
John McCall7d8647f2010-09-14 07:57:04 +0000804
805 // Emit the continuation block if there was an active flag.
806 if (ActiveFlag)
807 CGF.EmitBlock(ContBB);
808
809 // Leave the terminate scope.
810 if (ForEH) CGF.EHStack.popTerminate();
811}
812
813static void ForwardPrebranchedFallthrough(llvm::BasicBlock *Exit,
814 llvm::BasicBlock *From,
815 llvm::BasicBlock *To) {
816 // Exit is the exit block of a cleanup, so it always terminates in
817 // an unconditional branch or a switch.
818 llvm::TerminatorInst *Term = Exit->getTerminator();
819
820 if (llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Term)) {
821 assert(Br->isUnconditional() && Br->getSuccessor(0) == From);
822 Br->setSuccessor(0, To);
823 } else {
824 llvm::SwitchInst *Switch = cast<llvm::SwitchInst>(Term);
825 for (unsigned I = 0, E = Switch->getNumSuccessors(); I != E; ++I)
826 if (Switch->getSuccessor(I) == From)
827 Switch->setSuccessor(I, To);
828 }
John McCallda65ea82010-07-13 20:32:21 +0000829}
830
John McCall1f0fca52010-07-21 07:22:38 +0000831/// Pops a cleanup block. If the block includes a normal cleanup, the
832/// current insertion point is threaded through the cleanup, as are
833/// any branch fixups on the cleanup.
John McCallff8e1152010-07-23 21:56:41 +0000834void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough) {
John McCall1f0fca52010-07-21 07:22:38 +0000835 assert(!EHStack.empty() && "cleanup stack is empty!");
836 assert(isa<EHCleanupScope>(*EHStack.begin()) && "top not a cleanup!");
837 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.begin());
838 assert(Scope.getFixupDepth() <= EHStack.getNumBranchFixups());
John McCall7d8647f2010-09-14 07:57:04 +0000839
840 // Remember activation information.
841 bool IsActive = Scope.isActive();
842 llvm::Value *NormalActiveFlag =
843 Scope.shouldTestFlagInNormalCleanup() ? Scope.getActiveFlag() : 0;
844 llvm::Value *EHActiveFlag =
845 Scope.shouldTestFlagInEHCleanup() ? Scope.getActiveFlag() : 0;
John McCallda65ea82010-07-13 20:32:21 +0000846
847 // Check whether we need an EH cleanup. This is only true if we've
848 // generated a lazy EH cleanup block.
John McCallff8e1152010-07-23 21:56:41 +0000849 bool RequiresEHCleanup = Scope.hasEHBranches();
John McCallda65ea82010-07-13 20:32:21 +0000850
851 // Check the three conditions which might require a normal cleanup:
852
853 // - whether there are branch fix-ups through this cleanup
854 unsigned FixupDepth = Scope.getFixupDepth();
John McCall1f0fca52010-07-21 07:22:38 +0000855 bool HasFixups = EHStack.getNumBranchFixups() != FixupDepth;
John McCallda65ea82010-07-13 20:32:21 +0000856
John McCallff8e1152010-07-23 21:56:41 +0000857 // - whether there are branch-throughs or branch-afters
858 bool HasExistingBranches = Scope.hasBranches();
John McCallda65ea82010-07-13 20:32:21 +0000859
860 // - whether there's a fallthrough
John McCall1f0fca52010-07-21 07:22:38 +0000861 llvm::BasicBlock *FallthroughSource = Builder.GetInsertBlock();
John McCall7d8647f2010-09-14 07:57:04 +0000862 bool HasFallthrough = (FallthroughSource != 0 && IsActive);
863
John McCalle71d60d2010-10-05 20:48:15 +0000864 // Branch-through fall-throughs leave the insertion point set to the
865 // end of the last cleanup, which points to the current scope. The
866 // rest of IR gen doesn't need to worry about this; it only happens
867 // during the execution of PopCleanupBlocks().
John McCall7d8647f2010-09-14 07:57:04 +0000868 bool HasPrebranchedFallthrough =
869 (FallthroughSource && FallthroughSource->getTerminator());
John McCallda65ea82010-07-13 20:32:21 +0000870
John McCalle71d60d2010-10-05 20:48:15 +0000871 // If this is a normal cleanup, then having a prebranched
872 // fallthrough implies that the fallthrough source unconditionally
873 // jumps here.
874 assert(!Scope.isNormalCleanup() || !HasPrebranchedFallthrough ||
875 (Scope.getNormalBlock() &&
876 FallthroughSource->getTerminator()->getSuccessor(0)
877 == Scope.getNormalBlock()));
878
John McCallda65ea82010-07-13 20:32:21 +0000879 bool RequiresNormalCleanup = false;
880 if (Scope.isNormalCleanup() &&
881 (HasFixups || HasExistingBranches || HasFallthrough)) {
882 RequiresNormalCleanup = true;
883 }
884
John McCall7d8647f2010-09-14 07:57:04 +0000885 // Even if we don't need the normal cleanup, we might still have
886 // prebranched fallthrough to worry about.
John McCalle71d60d2010-10-05 20:48:15 +0000887 if (Scope.isNormalCleanup() && !RequiresNormalCleanup &&
888 HasPrebranchedFallthrough) {
John McCall7d8647f2010-09-14 07:57:04 +0000889 assert(!IsActive);
890
891 llvm::BasicBlock *NormalEntry = Scope.getNormalBlock();
892
893 // If we're branching through this cleanup, just forward the
894 // prebranched fallthrough to the next cleanup, leaving the insert
895 // point in the old block.
896 if (FallthroughIsBranchThrough) {
897 EHScope &S = *EHStack.find(Scope.getEnclosingNormalCleanup());
898 llvm::BasicBlock *EnclosingEntry =
899 CreateNormalEntry(*this, cast<EHCleanupScope>(S));
900
901 ForwardPrebranchedFallthrough(FallthroughSource,
902 NormalEntry, EnclosingEntry);
903 assert(NormalEntry->use_empty() &&
904 "uses of entry remain after forwarding?");
905 delete NormalEntry;
906
907 // Otherwise, we're branching out; just emit the next block.
908 } else {
909 EmitBlock(NormalEntry);
910 SimplifyCleanupEntry(*this, NormalEntry);
911 }
912 }
913
John McCallda65ea82010-07-13 20:32:21 +0000914 // If we don't need the cleanup at all, we're done.
915 if (!RequiresNormalCleanup && !RequiresEHCleanup) {
John McCallff8e1152010-07-23 21:56:41 +0000916 EHStack.popCleanup(); // safe because there are no fixups
John McCall1f0fca52010-07-21 07:22:38 +0000917 assert(EHStack.getNumBranchFixups() == 0 ||
918 EHStack.hasNormalCleanups());
John McCallda65ea82010-07-13 20:32:21 +0000919 return;
920 }
921
922 // Copy the cleanup emission data out. Note that SmallVector
923 // guarantees maximal alignment for its buffer regardless of its
924 // type parameter.
925 llvm::SmallVector<char, 8*sizeof(void*)> CleanupBuffer;
926 CleanupBuffer.reserve(Scope.getCleanupSize());
927 memcpy(CleanupBuffer.data(),
928 Scope.getCleanupBuffer(), Scope.getCleanupSize());
929 CleanupBuffer.set_size(Scope.getCleanupSize());
John McCall1f0fca52010-07-21 07:22:38 +0000930 EHScopeStack::Cleanup *Fn =
931 reinterpret_cast<EHScopeStack::Cleanup*>(CleanupBuffer.data());
John McCallda65ea82010-07-13 20:32:21 +0000932
John McCallff8e1152010-07-23 21:56:41 +0000933 // We want to emit the EH cleanup after the normal cleanup, but go
934 // ahead and do the setup for the EH cleanup while the scope is still
935 // alive.
936 llvm::BasicBlock *EHEntry = 0;
937 llvm::SmallVector<llvm::Instruction*, 2> EHInstsToAppend;
938 if (RequiresEHCleanup) {
939 EHEntry = CreateEHEntry(*this, Scope);
John McCallda65ea82010-07-13 20:32:21 +0000940
John McCallff8e1152010-07-23 21:56:41 +0000941 // Figure out the branch-through dest if necessary.
942 llvm::BasicBlock *EHBranchThroughDest = 0;
943 if (Scope.hasEHBranchThroughs()) {
944 assert(Scope.getEnclosingEHCleanup() != EHStack.stable_end());
945 EHScope &S = *EHStack.find(Scope.getEnclosingEHCleanup());
946 EHBranchThroughDest = CreateEHEntry(*this, cast<EHCleanupScope>(S));
947 }
948
949 // If we have exactly one branch-after and no branch-throughs, we
950 // can dispatch it without a switch.
John McCall7cd4b062010-07-26 22:44:58 +0000951 if (!Scope.hasEHBranchThroughs() &&
John McCallff8e1152010-07-23 21:56:41 +0000952 Scope.getNumEHBranchAfters() == 1) {
953 assert(!EHBranchThroughDest);
954
955 // TODO: remove the spurious eh.cleanup.dest stores if this edge
956 // never went through any switches.
957 llvm::BasicBlock *BranchAfterDest = Scope.getEHBranchAfterBlock(0);
958 EHInstsToAppend.push_back(llvm::BranchInst::Create(BranchAfterDest));
959
960 // Otherwise, if we have any branch-afters, we need a switch.
961 } else if (Scope.getNumEHBranchAfters()) {
962 // The default of the switch belongs to the branch-throughs if
963 // they exist.
964 llvm::BasicBlock *Default =
965 (EHBranchThroughDest ? EHBranchThroughDest : getUnreachableBlock());
966
967 const unsigned SwitchCapacity = Scope.getNumEHBranchAfters();
968
969 llvm::LoadInst *Load =
970 new llvm::LoadInst(getEHCleanupDestSlot(), "cleanup.dest");
971 llvm::SwitchInst *Switch =
972 llvm::SwitchInst::Create(Load, Default, SwitchCapacity);
973
974 EHInstsToAppend.push_back(Load);
975 EHInstsToAppend.push_back(Switch);
976
977 for (unsigned I = 0, E = Scope.getNumEHBranchAfters(); I != E; ++I)
978 Switch->addCase(Scope.getEHBranchAfterIndex(I),
979 Scope.getEHBranchAfterBlock(I));
980
981 // Otherwise, we have only branch-throughs; jump to the next EH
982 // cleanup.
983 } else {
984 assert(EHBranchThroughDest);
985 EHInstsToAppend.push_back(llvm::BranchInst::Create(EHBranchThroughDest));
986 }
987 }
988
989 if (!RequiresNormalCleanup) {
990 EHStack.popCleanup();
991 } else {
John McCallda65ea82010-07-13 20:32:21 +0000992 // If we have a fallthrough and no other need for the cleanup,
993 // emit it directly.
John McCallff8e1152010-07-23 21:56:41 +0000994 if (HasFallthrough && !HasPrebranchedFallthrough &&
995 !HasFixups && !HasExistingBranches) {
996
997 // Fixups can cause us to optimistically create a normal block,
998 // only to later have no real uses for it. Just delete it in
999 // this case.
1000 // TODO: we can potentially simplify all the uses after this.
1001 if (Scope.getNormalBlock()) {
1002 Scope.getNormalBlock()->replaceAllUsesWith(getUnreachableBlock());
1003 delete Scope.getNormalBlock();
1004 }
1005
1006 EHStack.popCleanup();
1007
John McCall7d8647f2010-09-14 07:57:04 +00001008 EmitCleanup(*this, Fn, /*ForEH*/ false, NormalActiveFlag);
John McCallda65ea82010-07-13 20:32:21 +00001009
1010 // Otherwise, the best approach is to thread everything through
1011 // the cleanup block and then try to clean up after ourselves.
1012 } else {
1013 // Force the entry block to exist.
John McCallff8e1152010-07-23 21:56:41 +00001014 llvm::BasicBlock *NormalEntry = CreateNormalEntry(*this, Scope);
John McCallda65ea82010-07-13 20:32:21 +00001015
John McCall7d8647f2010-09-14 07:57:04 +00001016 // I. Set up the fallthrough edge in.
1017
John McCallff8e1152010-07-23 21:56:41 +00001018 // If there's a fallthrough, we need to store the cleanup
1019 // destination index. For fall-throughs this is always zero.
John McCall7d8647f2010-09-14 07:57:04 +00001020 if (HasFallthrough) {
1021 if (!HasPrebranchedFallthrough)
1022 Builder.CreateStore(Builder.getInt32(0), getNormalCleanupDestSlot());
John McCallff8e1152010-07-23 21:56:41 +00001023
John McCall7d8647f2010-09-14 07:57:04 +00001024 // Otherwise, clear the IP if we don't have fallthrough because
1025 // the cleanup is inactive. We don't need to save it because
1026 // it's still just FallthroughSource.
1027 } else if (FallthroughSource) {
1028 assert(!IsActive && "source without fallthrough for active cleanup");
1029 Builder.ClearInsertionPoint();
1030 }
1031
1032 // II. Emit the entry block. This implicitly branches to it if
1033 // we have fallthrough. All the fixups and existing branches
1034 // should already be branched to it.
John McCall1f0fca52010-07-21 07:22:38 +00001035 EmitBlock(NormalEntry);
John McCallda65ea82010-07-13 20:32:21 +00001036
John McCall7d8647f2010-09-14 07:57:04 +00001037 // III. Figure out where we're going and build the cleanup
1038 // epilogue.
1039
John McCallff8e1152010-07-23 21:56:41 +00001040 bool HasEnclosingCleanups =
1041 (Scope.getEnclosingNormalCleanup() != EHStack.stable_end());
John McCallda65ea82010-07-13 20:32:21 +00001042
John McCallff8e1152010-07-23 21:56:41 +00001043 // Compute the branch-through dest if we need it:
1044 // - if there are branch-throughs threaded through the scope
1045 // - if fall-through is a branch-through
1046 // - if there are fixups that will be optimistically forwarded
1047 // to the enclosing cleanup
1048 llvm::BasicBlock *BranchThroughDest = 0;
1049 if (Scope.hasBranchThroughs() ||
John McCall7d8647f2010-09-14 07:57:04 +00001050 (FallthroughSource && FallthroughIsBranchThrough) ||
John McCallff8e1152010-07-23 21:56:41 +00001051 (HasFixups && HasEnclosingCleanups)) {
1052 assert(HasEnclosingCleanups);
1053 EHScope &S = *EHStack.find(Scope.getEnclosingNormalCleanup());
1054 BranchThroughDest = CreateNormalEntry(*this, cast<EHCleanupScope>(S));
John McCallda65ea82010-07-13 20:32:21 +00001055 }
1056
John McCallff8e1152010-07-23 21:56:41 +00001057 llvm::BasicBlock *FallthroughDest = 0;
1058 llvm::SmallVector<llvm::Instruction*, 2> InstsToAppend;
1059
1060 // If there's exactly one branch-after and no other threads,
1061 // we can route it without a switch.
1062 if (!Scope.hasBranchThroughs() && !HasFixups && !HasFallthrough &&
1063 Scope.getNumBranchAfters() == 1) {
John McCall7d8647f2010-09-14 07:57:04 +00001064 assert(!BranchThroughDest || !IsActive);
John McCallff8e1152010-07-23 21:56:41 +00001065
1066 // TODO: clean up the possibly dead stores to the cleanup dest slot.
1067 llvm::BasicBlock *BranchAfter = Scope.getBranchAfterBlock(0);
1068 InstsToAppend.push_back(llvm::BranchInst::Create(BranchAfter));
1069
1070 // Build a switch-out if we need it:
1071 // - if there are branch-afters threaded through the scope
1072 // - if fall-through is a branch-after
1073 // - if there are fixups that have nowhere left to go and
1074 // so must be immediately resolved
1075 } else if (Scope.getNumBranchAfters() ||
1076 (HasFallthrough && !FallthroughIsBranchThrough) ||
1077 (HasFixups && !HasEnclosingCleanups)) {
1078
1079 llvm::BasicBlock *Default =
1080 (BranchThroughDest ? BranchThroughDest : getUnreachableBlock());
1081
1082 // TODO: base this on the number of branch-afters and fixups
1083 const unsigned SwitchCapacity = 10;
1084
1085 llvm::LoadInst *Load =
1086 new llvm::LoadInst(getNormalCleanupDestSlot(), "cleanup.dest");
1087 llvm::SwitchInst *Switch =
1088 llvm::SwitchInst::Create(Load, Default, SwitchCapacity);
1089
1090 InstsToAppend.push_back(Load);
1091 InstsToAppend.push_back(Switch);
1092
1093 // Branch-after fallthrough.
John McCall7d8647f2010-09-14 07:57:04 +00001094 if (FallthroughSource && !FallthroughIsBranchThrough) {
John McCallff8e1152010-07-23 21:56:41 +00001095 FallthroughDest = createBasicBlock("cleanup.cont");
John McCall7d8647f2010-09-14 07:57:04 +00001096 if (HasFallthrough)
1097 Switch->addCase(Builder.getInt32(0), FallthroughDest);
John McCallff8e1152010-07-23 21:56:41 +00001098 }
1099
1100 for (unsigned I = 0, E = Scope.getNumBranchAfters(); I != E; ++I) {
1101 Switch->addCase(Scope.getBranchAfterIndex(I),
1102 Scope.getBranchAfterBlock(I));
1103 }
1104
John McCall8abdbd82010-09-18 02:24:39 +00001105 // If there aren't any enclosing cleanups, we can resolve all
1106 // the fixups now.
John McCallff8e1152010-07-23 21:56:41 +00001107 if (HasFixups && !HasEnclosingCleanups)
John McCall8abdbd82010-09-18 02:24:39 +00001108 ResolveAllBranchFixups(*this, Switch, NormalEntry);
John McCallff8e1152010-07-23 21:56:41 +00001109 } else {
1110 // We should always have a branch-through destination in this case.
1111 assert(BranchThroughDest);
1112 InstsToAppend.push_back(llvm::BranchInst::Create(BranchThroughDest));
1113 }
1114
John McCall7d8647f2010-09-14 07:57:04 +00001115 // IV. Pop the cleanup and emit it.
John McCallff8e1152010-07-23 21:56:41 +00001116 EHStack.popCleanup();
1117 assert(EHStack.hasNormalCleanups() == HasEnclosingCleanups);
1118
John McCall7d8647f2010-09-14 07:57:04 +00001119 EmitCleanup(*this, Fn, /*ForEH*/ false, NormalActiveFlag);
John McCallff8e1152010-07-23 21:56:41 +00001120
1121 // Append the prepared cleanup prologue from above.
1122 llvm::BasicBlock *NormalExit = Builder.GetInsertBlock();
1123 for (unsigned I = 0, E = InstsToAppend.size(); I != E; ++I)
1124 NormalExit->getInstList().push_back(InstsToAppend[I]);
1125
1126 // Optimistically hope that any fixups will continue falling through.
John McCall1f0fca52010-07-21 07:22:38 +00001127 for (unsigned I = FixupDepth, E = EHStack.getNumBranchFixups();
John McCallff8e1152010-07-23 21:56:41 +00001128 I < E; ++I) {
1129 BranchFixup &Fixup = CGF.EHStack.getBranchFixup(I);
1130 if (!Fixup.Destination) continue;
1131 if (!Fixup.OptimisticBranchBlock) {
1132 new llvm::StoreInst(Builder.getInt32(Fixup.DestinationIndex),
1133 getNormalCleanupDestSlot(),
1134 Fixup.InitialBranch);
1135 Fixup.InitialBranch->setSuccessor(0, NormalEntry);
1136 }
1137 Fixup.OptimisticBranchBlock = NormalExit;
1138 }
John McCall7d8647f2010-09-14 07:57:04 +00001139
1140 // V. Set up the fallthrough edge out.
John McCallff8e1152010-07-23 21:56:41 +00001141
John McCall7d8647f2010-09-14 07:57:04 +00001142 // Case 1: a fallthrough source exists but shouldn't branch to
1143 // the cleanup because the cleanup is inactive.
1144 if (!HasFallthrough && FallthroughSource) {
1145 assert(!IsActive);
1146
1147 // If we have a prebranched fallthrough, that needs to be
1148 // forwarded to the right block.
1149 if (HasPrebranchedFallthrough) {
1150 llvm::BasicBlock *Next;
1151 if (FallthroughIsBranchThrough) {
1152 Next = BranchThroughDest;
1153 assert(!FallthroughDest);
1154 } else {
1155 Next = FallthroughDest;
1156 }
1157
1158 ForwardPrebranchedFallthrough(FallthroughSource, NormalEntry, Next);
1159 }
1160 Builder.SetInsertPoint(FallthroughSource);
1161
1162 // Case 2: a fallthrough source exists and should branch to the
1163 // cleanup, but we're not supposed to branch through to the next
1164 // cleanup.
1165 } else if (HasFallthrough && FallthroughDest) {
1166 assert(!FallthroughIsBranchThrough);
John McCallff8e1152010-07-23 21:56:41 +00001167 EmitBlock(FallthroughDest);
John McCall7d8647f2010-09-14 07:57:04 +00001168
1169 // Case 3: a fallthrough source exists and should branch to the
1170 // cleanup and then through to the next.
1171 } else if (HasFallthrough) {
1172 // Everything is already set up for this.
1173
1174 // Case 4: no fallthrough source exists.
1175 } else {
John McCallff8e1152010-07-23 21:56:41 +00001176 Builder.ClearInsertionPoint();
John McCall7d8647f2010-09-14 07:57:04 +00001177 }
1178
1179 // VI. Assorted cleaning.
John McCallda65ea82010-07-13 20:32:21 +00001180
John McCallff8e1152010-07-23 21:56:41 +00001181 // Check whether we can merge NormalEntry into a single predecessor.
1182 // This might invalidate (non-IR) pointers to NormalEntry.
1183 llvm::BasicBlock *NewNormalEntry =
1184 SimplifyCleanupEntry(*this, NormalEntry);
John McCallda65ea82010-07-13 20:32:21 +00001185
John McCallff8e1152010-07-23 21:56:41 +00001186 // If it did invalidate those pointers, and NormalEntry was the same
1187 // as NormalExit, go back and patch up the fixups.
1188 if (NewNormalEntry != NormalEntry && NormalEntry == NormalExit)
1189 for (unsigned I = FixupDepth, E = EHStack.getNumBranchFixups();
1190 I < E; ++I)
1191 CGF.EHStack.getBranchFixup(I).OptimisticBranchBlock = NewNormalEntry;
John McCallda65ea82010-07-13 20:32:21 +00001192 }
1193 }
1194
John McCallff8e1152010-07-23 21:56:41 +00001195 assert(EHStack.hasNormalCleanups() || EHStack.getNumBranchFixups() == 0);
1196
John McCallda65ea82010-07-13 20:32:21 +00001197 // Emit the EH cleanup if required.
1198 if (RequiresEHCleanup) {
John McCall1f0fca52010-07-21 07:22:38 +00001199 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
John McCallff8e1152010-07-23 21:56:41 +00001200
John McCall1f0fca52010-07-21 07:22:38 +00001201 EmitBlock(EHEntry);
John McCall7d8647f2010-09-14 07:57:04 +00001202 EmitCleanup(*this, Fn, /*ForEH*/ true, EHActiveFlag);
John McCallff8e1152010-07-23 21:56:41 +00001203
1204 // Append the prepared cleanup prologue from above.
1205 llvm::BasicBlock *EHExit = Builder.GetInsertBlock();
1206 for (unsigned I = 0, E = EHInstsToAppend.size(); I != E; ++I)
1207 EHExit->getInstList().push_back(EHInstsToAppend[I]);
1208
John McCall1f0fca52010-07-21 07:22:38 +00001209 Builder.restoreIP(SavedIP);
John McCallff8e1152010-07-23 21:56:41 +00001210
1211 SimplifyCleanupEntry(*this, EHEntry);
John McCallda65ea82010-07-13 20:32:21 +00001212 }
1213}
1214
John McCallff8e1152010-07-23 21:56:41 +00001215/// Terminate the current block by emitting a branch which might leave
1216/// the current cleanup-protected scope. The target scope may not yet
1217/// be known, in which case this will require a fixup.
1218///
1219/// As a side-effect, this method clears the insertion point.
John McCallf1549f62010-07-06 01:34:17 +00001220void CodeGenFunction::EmitBranchThroughCleanup(JumpDest Dest) {
John McCall413e6772010-07-28 01:07:35 +00001221 assert(Dest.getScopeDepth().encloses(EHStack.getInnermostNormalCleanup())
1222 && "stale jump destination");
1223
Anders Carlsson46831a92009-02-08 22:13:37 +00001224 if (!HaveInsertPoint())
1225 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001226
John McCallf1549f62010-07-06 01:34:17 +00001227 // Create the branch.
John McCallff8e1152010-07-23 21:56:41 +00001228 llvm::BranchInst *BI = Builder.CreateBr(Dest.getBlock());
Mike Stump1eb44332009-09-09 15:08:12 +00001229
John McCall838d7962010-08-14 07:46:19 +00001230 // Calculate the innermost active normal cleanup.
1231 EHScopeStack::stable_iterator
1232 TopCleanup = EHStack.getInnermostActiveNormalCleanup();
1233
1234 // If we're not in an active normal cleanup scope, or if the
1235 // destination scope is within the innermost active normal cleanup
1236 // scope, we don't need to worry about fixups.
1237 if (TopCleanup == EHStack.stable_end() ||
1238 TopCleanup.encloses(Dest.getScopeDepth())) { // works for invalid
John McCallf1549f62010-07-06 01:34:17 +00001239 Builder.ClearInsertionPoint();
1240 return;
1241 }
1242
John McCallf1549f62010-07-06 01:34:17 +00001243 // If we can't resolve the destination cleanup scope, just add this
John McCallff8e1152010-07-23 21:56:41 +00001244 // to the current cleanup scope as a branch fixup.
1245 if (!Dest.getScopeDepth().isValid()) {
1246 BranchFixup &Fixup = EHStack.addBranchFixup();
1247 Fixup.Destination = Dest.getBlock();
1248 Fixup.DestinationIndex = Dest.getDestIndex();
1249 Fixup.InitialBranch = BI;
1250 Fixup.OptimisticBranchBlock = 0;
1251
John McCallf1549f62010-07-06 01:34:17 +00001252 Builder.ClearInsertionPoint();
1253 return;
1254 }
1255
John McCallff8e1152010-07-23 21:56:41 +00001256 // Otherwise, thread through all the normal cleanups in scope.
1257
1258 // Store the index at the start.
1259 llvm::ConstantInt *Index = Builder.getInt32(Dest.getDestIndex());
1260 new llvm::StoreInst(Index, getNormalCleanupDestSlot(), BI);
1261
1262 // Adjust BI to point to the first cleanup block.
1263 {
1264 EHCleanupScope &Scope =
John McCall838d7962010-08-14 07:46:19 +00001265 cast<EHCleanupScope>(*EHStack.find(TopCleanup));
John McCallff8e1152010-07-23 21:56:41 +00001266 BI->setSuccessor(0, CreateNormalEntry(*this, Scope));
1267 }
1268
1269 // Add this destination to all the scopes involved.
John McCall838d7962010-08-14 07:46:19 +00001270 EHScopeStack::stable_iterator I = TopCleanup;
John McCallff8e1152010-07-23 21:56:41 +00001271 EHScopeStack::stable_iterator E = Dest.getScopeDepth();
1272 if (E.strictlyEncloses(I)) {
1273 while (true) {
1274 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(I));
1275 assert(Scope.isNormalCleanup());
1276 I = Scope.getEnclosingNormalCleanup();
1277
1278 // If this is the last cleanup we're propagating through, tell it
1279 // that there's a resolved jump moving through it.
1280 if (!E.strictlyEncloses(I)) {
1281 Scope.addBranchAfter(Index, Dest.getBlock());
1282 break;
John McCallda65ea82010-07-13 20:32:21 +00001283 }
John McCallff8e1152010-07-23 21:56:41 +00001284
1285 // Otherwise, tell the scope that there's a jump propoagating
1286 // through it. If this isn't new information, all the rest of
1287 // the work has been done before.
1288 if (!Scope.addBranchThrough(Dest.getBlock()))
1289 break;
John McCallf1549f62010-07-06 01:34:17 +00001290 }
1291 }
1292
Anders Carlsson46831a92009-02-08 22:13:37 +00001293 Builder.ClearInsertionPoint();
John McCallf1549f62010-07-06 01:34:17 +00001294}
Mike Stump1eb44332009-09-09 15:08:12 +00001295
John McCallff8e1152010-07-23 21:56:41 +00001296void CodeGenFunction::EmitBranchThroughEHCleanup(UnwindDest Dest) {
1297 // We should never get invalid scope depths for an UnwindDest; that
1298 // implies that the destination wasn't set up correctly.
1299 assert(Dest.getScopeDepth().isValid() && "invalid scope depth on EH dest?");
1300
John McCallf1549f62010-07-06 01:34:17 +00001301 if (!HaveInsertPoint())
Anders Carlsson87eaf172009-02-08 00:50:42 +00001302 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001303
John McCallf1549f62010-07-06 01:34:17 +00001304 // Create the branch.
John McCallff8e1152010-07-23 21:56:41 +00001305 llvm::BranchInst *BI = Builder.CreateBr(Dest.getBlock());
John McCallf1549f62010-07-06 01:34:17 +00001306
John McCall838d7962010-08-14 07:46:19 +00001307 // Calculate the innermost active cleanup.
1308 EHScopeStack::stable_iterator
1309 InnermostCleanup = EHStack.getInnermostActiveEHCleanup();
1310
John McCallff8e1152010-07-23 21:56:41 +00001311 // If the destination is in the same EH cleanup scope as us, we
1312 // don't need to thread through anything.
John McCall838d7962010-08-14 07:46:19 +00001313 if (InnermostCleanup.encloses(Dest.getScopeDepth())) {
John McCallf1549f62010-07-06 01:34:17 +00001314 Builder.ClearInsertionPoint();
Anders Carlsson87eaf172009-02-08 00:50:42 +00001315 return;
1316 }
John McCall838d7962010-08-14 07:46:19 +00001317 assert(InnermostCleanup != EHStack.stable_end());
Mike Stump1eb44332009-09-09 15:08:12 +00001318
John McCallff8e1152010-07-23 21:56:41 +00001319 // Store the index at the start.
1320 llvm::ConstantInt *Index = Builder.getInt32(Dest.getDestIndex());
1321 new llvm::StoreInst(Index, getEHCleanupDestSlot(), BI);
John McCallf1549f62010-07-06 01:34:17 +00001322
John McCallff8e1152010-07-23 21:56:41 +00001323 // Adjust BI to point to the first cleanup block.
1324 {
1325 EHCleanupScope &Scope =
John McCall838d7962010-08-14 07:46:19 +00001326 cast<EHCleanupScope>(*EHStack.find(InnermostCleanup));
John McCallff8e1152010-07-23 21:56:41 +00001327 BI->setSuccessor(0, CreateEHEntry(*this, Scope));
1328 }
1329
1330 // Add this destination to all the scopes involved.
1331 for (EHScopeStack::stable_iterator
John McCall838d7962010-08-14 07:46:19 +00001332 I = InnermostCleanup, E = Dest.getScopeDepth(); ; ) {
John McCallff8e1152010-07-23 21:56:41 +00001333 assert(E.strictlyEncloses(I));
1334 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(I));
1335 assert(Scope.isEHCleanup());
1336 I = Scope.getEnclosingEHCleanup();
John McCallf1549f62010-07-06 01:34:17 +00001337
John McCallff8e1152010-07-23 21:56:41 +00001338 // If this is the last cleanup we're propagating through, add this
1339 // as a branch-after.
1340 if (I == E) {
1341 Scope.addEHBranchAfter(Index, Dest.getBlock());
1342 break;
John McCallf1549f62010-07-06 01:34:17 +00001343 }
John McCallff8e1152010-07-23 21:56:41 +00001344
1345 // Otherwise, add it as a branch-through. If this isn't new
1346 // information, all the rest of the work has been done before.
1347 if (!Scope.addEHBranchThrough(Dest.getBlock()))
1348 break;
Anders Carlsson87eaf172009-02-08 00:50:42 +00001349 }
John McCallf1549f62010-07-06 01:34:17 +00001350
1351 Builder.ClearInsertionPoint();
Anders Carlsson87eaf172009-02-08 00:50:42 +00001352}
John McCallff8e1152010-07-23 21:56:41 +00001353
1354/// All the branch fixups on the EH stack have propagated out past the
1355/// outermost normal cleanup; resolve them all by adding cases to the
1356/// given switch instruction.
John McCall8abdbd82010-09-18 02:24:39 +00001357static void ResolveAllBranchFixups(CodeGenFunction &CGF,
1358 llvm::SwitchInst *Switch,
1359 llvm::BasicBlock *CleanupEntry) {
John McCallff8e1152010-07-23 21:56:41 +00001360 llvm::SmallPtrSet<llvm::BasicBlock*, 4> CasesAdded;
1361
John McCall8abdbd82010-09-18 02:24:39 +00001362 for (unsigned I = 0, E = CGF.EHStack.getNumBranchFixups(); I != E; ++I) {
John McCall0680e972010-10-05 02:33:56 +00001363 // Skip this fixup if its destination isn't set.
John McCall8abdbd82010-09-18 02:24:39 +00001364 BranchFixup &Fixup = CGF.EHStack.getBranchFixup(I);
John McCallff8e1152010-07-23 21:56:41 +00001365 if (Fixup.Destination == 0) continue;
John McCallff8e1152010-07-23 21:56:41 +00001366
John McCall8abdbd82010-09-18 02:24:39 +00001367 // If there isn't an OptimisticBranchBlock, then InitialBranch is
1368 // still pointing directly to its destination; forward it to the
1369 // appropriate cleanup entry. This is required in the specific
1370 // case of
1371 // { std::string s; goto lbl; }
1372 // lbl:
1373 // i.e. where there's an unresolved fixup inside a single cleanup
1374 // entry which we're currently popping.
1375 if (Fixup.OptimisticBranchBlock == 0) {
1376 new llvm::StoreInst(CGF.Builder.getInt32(Fixup.DestinationIndex),
1377 CGF.getNormalCleanupDestSlot(),
1378 Fixup.InitialBranch);
1379 Fixup.InitialBranch->setSuccessor(0, CleanupEntry);
1380 }
1381
John McCall0680e972010-10-05 02:33:56 +00001382 // Don't add this case to the switch statement twice.
1383 if (!CasesAdded.insert(Fixup.Destination)) continue;
1384
John McCall8abdbd82010-09-18 02:24:39 +00001385 Switch->addCase(CGF.Builder.getInt32(Fixup.DestinationIndex),
John McCallff8e1152010-07-23 21:56:41 +00001386 Fixup.Destination);
1387 }
1388
John McCall8abdbd82010-09-18 02:24:39 +00001389 CGF.EHStack.clearFixups();
John McCallff8e1152010-07-23 21:56:41 +00001390}
1391
1392void CodeGenFunction::ResolveBranchFixups(llvm::BasicBlock *Block) {
1393 assert(Block && "resolving a null target block");
1394 if (!EHStack.getNumBranchFixups()) return;
1395
1396 assert(EHStack.hasNormalCleanups() &&
1397 "branch fixups exist with no normal cleanups on stack");
1398
1399 llvm::SmallPtrSet<llvm::BasicBlock*, 4> ModifiedOptimisticBlocks;
1400 bool ResolvedAny = false;
1401
1402 for (unsigned I = 0, E = EHStack.getNumBranchFixups(); I != E; ++I) {
1403 // Skip this fixup if its destination doesn't match.
1404 BranchFixup &Fixup = EHStack.getBranchFixup(I);
1405 if (Fixup.Destination != Block) continue;
1406
1407 Fixup.Destination = 0;
1408 ResolvedAny = true;
1409
1410 // If it doesn't have an optimistic branch block, LatestBranch is
1411 // already pointing to the right place.
1412 llvm::BasicBlock *BranchBB = Fixup.OptimisticBranchBlock;
1413 if (!BranchBB)
1414 continue;
1415
1416 // Don't process the same optimistic branch block twice.
1417 if (!ModifiedOptimisticBlocks.insert(BranchBB))
1418 continue;
1419
1420 llvm::SwitchInst *Switch = TransitionToCleanupSwitch(*this, BranchBB);
1421
1422 // Add a case to the switch.
1423 Switch->addCase(Builder.getInt32(Fixup.DestinationIndex), Block);
1424 }
1425
1426 if (ResolvedAny)
1427 EHStack.popNullFixups();
1428}
1429
John McCall7d8647f2010-09-14 07:57:04 +00001430static bool IsUsedAsNormalCleanup(EHScopeStack &EHStack,
1431 EHScopeStack::stable_iterator C) {
1432 // If we needed a normal block for any reason, that counts.
1433 if (cast<EHCleanupScope>(*EHStack.find(C)).getNormalBlock())
1434 return true;
1435
1436 // Check whether any enclosed cleanups were needed.
1437 for (EHScopeStack::stable_iterator
1438 I = EHStack.getInnermostNormalCleanup();
1439 I != C; ) {
1440 assert(C.strictlyEncloses(I));
1441 EHCleanupScope &S = cast<EHCleanupScope>(*EHStack.find(I));
1442 if (S.getNormalBlock()) return true;
1443 I = S.getEnclosingNormalCleanup();
1444 }
1445
1446 return false;
1447}
1448
1449static bool IsUsedAsEHCleanup(EHScopeStack &EHStack,
1450 EHScopeStack::stable_iterator C) {
1451 // If we needed an EH block for any reason, that counts.
1452 if (cast<EHCleanupScope>(*EHStack.find(C)).getEHBlock())
1453 return true;
1454
1455 // Check whether any enclosed cleanups were needed.
1456 for (EHScopeStack::stable_iterator
1457 I = EHStack.getInnermostEHCleanup(); I != C; ) {
1458 assert(C.strictlyEncloses(I));
1459 EHCleanupScope &S = cast<EHCleanupScope>(*EHStack.find(I));
1460 if (S.getEHBlock()) return true;
1461 I = S.getEnclosingEHCleanup();
1462 }
1463
1464 return false;
1465}
1466
1467enum ForActivation_t {
1468 ForActivation,
1469 ForDeactivation
1470};
1471
1472/// The given cleanup block is changing activation state. Configure a
1473/// cleanup variable if necessary.
1474///
1475/// It would be good if we had some way of determining if there were
1476/// extra uses *after* the change-over point.
1477static void SetupCleanupBlockActivation(CodeGenFunction &CGF,
1478 EHScopeStack::stable_iterator C,
1479 ForActivation_t Kind) {
1480 EHCleanupScope &Scope = cast<EHCleanupScope>(*CGF.EHStack.find(C));
John McCall7d8647f2010-09-14 07:57:04 +00001481
John McCall3019c442010-09-17 00:50:28 +00001482 // We always need the flag if we're activating the cleanup, because
1483 // we have to assume that the current location doesn't necessarily
1484 // dominate all future uses of the cleanup.
1485 bool NeedFlag = (Kind == ForActivation);
John McCall7d8647f2010-09-14 07:57:04 +00001486
1487 // Calculate whether the cleanup was used:
1488
1489 // - as a normal cleanup
1490 if (Scope.isNormalCleanup() && IsUsedAsNormalCleanup(CGF.EHStack, C)) {
1491 Scope.setTestFlagInNormalCleanup();
1492 NeedFlag = true;
1493 }
1494
1495 // - as an EH cleanup
1496 if (Scope.isEHCleanup() && IsUsedAsEHCleanup(CGF.EHStack, C)) {
1497 Scope.setTestFlagInEHCleanup();
1498 NeedFlag = true;
1499 }
1500
1501 // If it hasn't yet been used as either, we're done.
1502 if (!NeedFlag) return;
1503
John McCall3019c442010-09-17 00:50:28 +00001504 llvm::AllocaInst *Var = Scope.getActiveFlag();
1505 if (!Var) {
1506 Var = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "cleanup.isactive");
1507 Scope.setActiveFlag(Var);
John McCall7d8647f2010-09-14 07:57:04 +00001508
John McCall3019c442010-09-17 00:50:28 +00001509 // Initialize to true or false depending on whether it was
1510 // active up to this point.
1511 CGF.InitTempAlloca(Var, CGF.Builder.getInt1(Kind == ForDeactivation));
John McCall7d8647f2010-09-14 07:57:04 +00001512 }
John McCall3019c442010-09-17 00:50:28 +00001513
1514 CGF.Builder.CreateStore(CGF.Builder.getInt1(Kind == ForActivation), Var);
John McCall7d8647f2010-09-14 07:57:04 +00001515}
1516
John McCallcd2d2b72010-08-13 21:20:51 +00001517/// Activate a cleanup that was created in an inactivated state.
John McCall7d8647f2010-09-14 07:57:04 +00001518void CodeGenFunction::ActivateCleanupBlock(EHScopeStack::stable_iterator C) {
John McCallcd2d2b72010-08-13 21:20:51 +00001519 assert(C != EHStack.stable_end() && "activating bottom of stack?");
1520 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(C));
1521 assert(!Scope.isActive() && "double activation");
1522
John McCall7d8647f2010-09-14 07:57:04 +00001523 SetupCleanupBlockActivation(*this, C, ForActivation);
John McCallcd2d2b72010-08-13 21:20:51 +00001524
John McCall7d8647f2010-09-14 07:57:04 +00001525 Scope.setActive(true);
1526}
John McCallcd2d2b72010-08-13 21:20:51 +00001527
John McCall7d8647f2010-09-14 07:57:04 +00001528/// Deactive a cleanup that was created in an active state.
1529void CodeGenFunction::DeactivateCleanupBlock(EHScopeStack::stable_iterator C) {
1530 assert(C != EHStack.stable_end() && "deactivating bottom of stack?");
1531 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(C));
John McCall3019c442010-09-17 00:50:28 +00001532 assert(Scope.isActive() && "double deactivation");
John McCall7d8647f2010-09-14 07:57:04 +00001533
1534 // If it's the top of the stack, just pop it.
1535 if (C == EHStack.stable_begin()) {
1536 // If it's a normal cleanup, we need to pretend that the
1537 // fallthrough is unreachable.
1538 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1539 PopCleanupBlock();
1540 Builder.restoreIP(SavedIP);
1541 return;
John McCallcd2d2b72010-08-13 21:20:51 +00001542 }
1543
John McCall7d8647f2010-09-14 07:57:04 +00001544 // Otherwise, follow the general case.
1545 SetupCleanupBlockActivation(*this, C, ForDeactivation);
John McCallcd2d2b72010-08-13 21:20:51 +00001546
John McCall7d8647f2010-09-14 07:57:04 +00001547 Scope.setActive(false);
John McCallcd2d2b72010-08-13 21:20:51 +00001548}
1549
John McCallff8e1152010-07-23 21:56:41 +00001550llvm::Value *CodeGenFunction::getNormalCleanupDestSlot() {
1551 if (!NormalCleanupDest)
1552 NormalCleanupDest =
1553 CreateTempAlloca(Builder.getInt32Ty(), "cleanup.dest.slot");
1554 return NormalCleanupDest;
1555}
1556
1557llvm::Value *CodeGenFunction::getEHCleanupDestSlot() {
1558 if (!EHCleanupDest)
1559 EHCleanupDest =
1560 CreateTempAlloca(Builder.getInt32Ty(), "eh.cleanup.dest.slot");
1561 return EHCleanupDest;
1562}
Devang Patel8d308382010-08-10 07:24:25 +00001563
1564void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
John McCall189d6ef2010-10-09 01:34:31 +00001565 llvm::Constant *Init) {
Devang Patel25c2c8f2010-08-10 17:53:33 +00001566 assert (Init && "Invalid DeclRefExpr initializer!");
1567 if (CGDebugInfo *Dbg = getDebugInfo())
Devang Pateld2829b72010-10-06 15:58:57 +00001568 Dbg->EmitGlobalVariable(E->getDecl(), Init);
Devang Patel8d308382010-08-10 07:24:25 +00001569}