blob: 0dbc6120ed0b19f825ea804aaf6d910701cafb1f [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
Mike Stump1eb44332009-09-09 15:08:12 +000031CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
Mike Stumpa4f668f2009-03-06 01:33:24 +000032 : BlockFunction(cgm, *this, Builder), CGM(cgm),
33 Target(CGM.getContext().Target),
Owen Andersonaac87052009-07-08 20:52:20 +000034 Builder(cgm.getModule().getContext()),
John McCallff8e1152010-07-23 21:56:41 +000035 NormalCleanupDest(0), EHCleanupDest(0), NextCleanupDestIndex(1),
John McCallf1549f62010-07-06 01:34:17 +000036 ExceptionSlot(0), DebugInfo(0), IndirectBranch(0),
John McCallff8e1152010-07-23 21:56:41 +000037 SwitchInsn(0), CaseRangeBlock(0),
John McCallf1549f62010-07-06 01:34:17 +000038 DidCallStackSave(false), UnreachableBlock(0),
John McCall25049412010-02-16 22:04:33 +000039 CXXThisDecl(0), CXXThisValue(0), CXXVTTDecl(0), CXXVTTValue(0),
John McCallf1549f62010-07-06 01:34:17 +000040 ConditionalBranchLevel(0), TerminateLandingPad(0), TerminateHandler(0),
Chris Lattner83252dc2010-07-20 21:07:09 +000041 TrapBB(0) {
Chris Lattner77b89b82010-06-27 07:15:29 +000042
43 // Get some frequently used types.
Mike Stump4e7a1f72009-02-21 20:00:35 +000044 LLVMPointerWidth = Target.getPointerWidth(0);
Chris Lattner77b89b82010-06-27 07:15:29 +000045 llvm::LLVMContext &LLVMContext = CGM.getLLVMContext();
46 IntPtrTy = llvm::IntegerType::get(LLVMContext, LLVMPointerWidth);
47 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
48 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
49
Mike Stumpd88ea562009-12-09 03:35:49 +000050 Exceptions = getContext().getLangOptions().Exceptions;
Mike Stump9c276ae2009-12-12 01:27:46 +000051 CatchUndefined = getContext().getLangOptions().CatchUndefined;
John McCall4c40d982010-08-31 07:33:07 +000052 CGM.getCXXABI().getMangleContext().startNewFunction();
Chris Lattner41110242008-06-17 18:05:57 +000053}
Reid Spencer5f016e22007-07-11 17:01:13 +000054
55ASTContext &CodeGenFunction::getContext() const {
56 return CGM.getContext();
57}
58
59
Daniel Dunbar8b1a3432009-02-03 23:03:55 +000060const llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
61 return CGM.getTypes().ConvertTypeForMem(T);
62}
63
Reid Spencer5f016e22007-07-11 17:01:13 +000064const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
65 return CGM.getTypes().ConvertType(T);
66}
67
68bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
Anders Carlssone9d34dc2009-09-29 02:09:01 +000069 return T->isRecordType() || T->isArrayType() || T->isAnyComplexType() ||
John McCalld608cdb2010-08-22 10:59:02 +000070 T->isObjCObjectType();
Reid Spencer5f016e22007-07-11 17:01:13 +000071}
72
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000073void CodeGenFunction::EmitReturnBlock() {
74 // For cleanliness, we try to avoid emitting the return block for
75 // simple cases.
76 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
77
78 if (CurBB) {
79 assert(!CurBB->getTerminator() && "Unexpected terminated block.");
80
Daniel Dunbar96e18b02009-07-19 08:24:34 +000081 // We have a valid insert point, reuse it if it is empty or there are no
82 // explicit jumps to the return block.
John McCallff8e1152010-07-23 21:56:41 +000083 if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) {
84 ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
85 delete ReturnBlock.getBlock();
Daniel Dunbar96e18b02009-07-19 08:24:34 +000086 } else
John McCallff8e1152010-07-23 21:56:41 +000087 EmitBlock(ReturnBlock.getBlock());
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000088 return;
89 }
90
91 // Otherwise, if the return block is the target of a single direct
92 // branch then we can just put the code in that block instead. This
93 // cleans up functions which started with a unified return block.
John McCallff8e1152010-07-23 21:56:41 +000094 if (ReturnBlock.getBlock()->hasOneUse()) {
Mike Stump1eb44332009-09-09 15:08:12 +000095 llvm::BranchInst *BI =
John McCallff8e1152010-07-23 21:56:41 +000096 dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->use_begin());
John McCallf1549f62010-07-06 01:34:17 +000097 if (BI && BI->isUnconditional() &&
John McCallff8e1152010-07-23 21:56:41 +000098 BI->getSuccessor(0) == ReturnBlock.getBlock()) {
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000099 // Reset insertion point and delete the branch.
100 Builder.SetInsertPoint(BI->getParent());
101 BI->eraseFromParent();
John McCallff8e1152010-07-23 21:56:41 +0000102 delete ReturnBlock.getBlock();
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000103 return;
104 }
105 }
106
Mike Stumpf5408fe2009-05-16 07:57:57 +0000107 // FIXME: We are at an unreachable point, there is no reason to emit the block
108 // unless it has uses. However, we still need a place to put the debug
109 // region.end for now.
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000110
John McCallff8e1152010-07-23 21:56:41 +0000111 EmitBlock(ReturnBlock.getBlock());
John McCallf1549f62010-07-06 01:34:17 +0000112}
113
114static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
115 if (!BB) return;
116 if (!BB->use_empty())
117 return CGF.CurFn->getBasicBlockList().push_back(BB);
118 delete BB;
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000119}
120
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000121void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
Chris Lattnerda138702007-07-16 21:28:45 +0000122 assert(BreakContinueStack.empty() &&
123 "mismatched push/pop in break/continue stack!");
Mike Stump1eb44332009-09-09 15:08:12 +0000124
125 // Emit function epilog (to return).
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000126 EmitReturnBlock();
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000127
Chris Lattner7255a2d2010-06-22 00:03:40 +0000128 EmitFunctionInstrumentation("__cyg_profile_func_exit");
129
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000130 // Emit debug descriptor for function end.
Anders Carlssone896d982009-02-13 08:11:52 +0000131 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000132 DI->setLocation(EndLoc);
Devang Patel5a6fbcf2010-07-22 22:29:16 +0000133 DI->EmitFunctionEnd(Builder);
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000134 }
135
Chris Lattner35b21b82010-06-27 01:06:27 +0000136 EmitFunctionEpilog(*CurFnInfo);
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000137 EmitEndEHSpec(CurCodeDecl);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000138
John McCallf1549f62010-07-06 01:34:17 +0000139 assert(EHStack.empty() &&
140 "did not remove all scopes from cleanup stack!");
141
Chris Lattnerd9becd12009-10-28 23:59:40 +0000142 // If someone did an indirect goto, emit the indirect goto block at the end of
143 // the function.
144 if (IndirectBranch) {
145 EmitBlock(IndirectBranch->getParent());
146 Builder.ClearInsertionPoint();
147 }
148
Chris Lattner5a2fa142007-12-02 06:32:24 +0000149 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
Chris Lattner481769b2009-03-31 22:17:44 +0000150 llvm::Instruction *Ptr = AllocaInsertPt;
Chris Lattner5a2fa142007-12-02 06:32:24 +0000151 AllocaInsertPt = 0;
Chris Lattner481769b2009-03-31 22:17:44 +0000152 Ptr->eraseFromParent();
Chris Lattnerd9becd12009-10-28 23:59:40 +0000153
154 // If someone took the address of a label but never did an indirect goto, we
155 // made a zero entry PHI node, which is illegal, zap it now.
156 if (IndirectBranch) {
157 llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
158 if (PN->getNumIncomingValues() == 0) {
159 PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
160 PN->eraseFromParent();
161 }
162 }
John McCallf1549f62010-07-06 01:34:17 +0000163
John McCallff8e1152010-07-23 21:56:41 +0000164 EmitIfUsed(*this, RethrowBlock.getBlock());
John McCallf1549f62010-07-06 01:34:17 +0000165 EmitIfUsed(*this, TerminateLandingPad);
166 EmitIfUsed(*this, TerminateHandler);
167 EmitIfUsed(*this, UnreachableBlock);
John McCall744016d2010-07-06 23:57:41 +0000168
169 if (CGM.getCodeGenOpts().EmitDeclMetadata)
170 EmitDeclMetadata();
Reid Spencer5f016e22007-07-11 17:01:13 +0000171}
172
Chris Lattner7255a2d2010-06-22 00:03:40 +0000173/// ShouldInstrumentFunction - Return true if the current function should be
174/// instrumented with __cyg_profile_func_* calls
175bool CodeGenFunction::ShouldInstrumentFunction() {
176 if (!CGM.getCodeGenOpts().InstrumentFunctions)
177 return false;
178 if (CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
179 return false;
180 return true;
181}
182
183/// EmitFunctionInstrumentation - Emit LLVM code to call the specified
184/// instrumentation function with the current function and the call site, if
185/// function instrumentation is enabled.
186void CodeGenFunction::EmitFunctionInstrumentation(const char *Fn) {
187 if (!ShouldInstrumentFunction())
188 return;
189
Chris Lattner8dab6572010-06-23 05:21:28 +0000190 const llvm::PointerType *PointerTy;
Chris Lattner7255a2d2010-06-22 00:03:40 +0000191 const llvm::FunctionType *FunctionTy;
192 std::vector<const llvm::Type*> ProfileFuncArgs;
193
Chris Lattner8dab6572010-06-23 05:21:28 +0000194 // void __cyg_profile_func_{enter,exit} (void *this_fn, void *call_site);
195 PointerTy = llvm::Type::getInt8PtrTy(VMContext);
196 ProfileFuncArgs.push_back(PointerTy);
197 ProfileFuncArgs.push_back(PointerTy);
Chris Lattner7255a2d2010-06-22 00:03:40 +0000198 FunctionTy = llvm::FunctionType::get(
199 llvm::Type::getVoidTy(VMContext),
200 ProfileFuncArgs, false);
201
202 llvm::Constant *F = CGM.CreateRuntimeFunction(FunctionTy, Fn);
203 llvm::CallInst *CallSite = Builder.CreateCall(
204 CGM.getIntrinsic(llvm::Intrinsic::returnaddress, 0, 0),
Chris Lattner77b89b82010-06-27 07:15:29 +0000205 llvm::ConstantInt::get(Int32Ty, 0),
Chris Lattner7255a2d2010-06-22 00:03:40 +0000206 "callsite");
207
Chris Lattner8dab6572010-06-23 05:21:28 +0000208 Builder.CreateCall2(F,
209 llvm::ConstantExpr::getBitCast(CurFn, PointerTy),
210 CallSite);
Chris Lattner7255a2d2010-06-22 00:03:40 +0000211}
212
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000213void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
Daniel Dunbar7c086512008-09-09 23:14:03 +0000214 llvm::Function *Fn,
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000215 const FunctionArgList &Args,
216 SourceLocation StartLoc) {
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000217 const Decl *D = GD.getDecl();
218
Anders Carlsson4cc1a472009-02-09 20:20:56 +0000219 DidCallStackSave = false;
Chris Lattnerb5437d22009-04-23 05:30:27 +0000220 CurCodeDecl = CurFuncDecl = D;
Daniel Dunbar7c086512008-09-09 23:14:03 +0000221 FnRetTy = RetTy;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000222 CurFn = Fn;
Chris Lattner41110242008-06-17 18:05:57 +0000223 assert(CurFn->isDeclaration() && "Function already has body?");
224
Jakob Stoklund Olesena3fe2842010-02-09 00:10:00 +0000225 // Pass inline keyword to optimizer if it appears explicitly on any
226 // declaration.
227 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
228 for (FunctionDecl::redecl_iterator RI = FD->redecls_begin(),
229 RE = FD->redecls_end(); RI != RE; ++RI)
230 if (RI->isInlineSpecified()) {
231 Fn->addFnAttr(llvm::Attribute::InlineHint);
232 break;
233 }
234
Daniel Dunbar55e87422008-11-11 02:29:29 +0000235 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000236
Chris Lattner41110242008-06-17 18:05:57 +0000237 // Create a marker to make it easy to insert allocas into the entryblock
238 // later. Don't create this with the builder, because we don't want it
239 // folded.
Chris Lattner77b89b82010-06-27 07:15:29 +0000240 llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
241 AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "", EntryBB);
Chris Lattnerf1466842009-03-22 00:24:14 +0000242 if (Builder.isNamePreserving())
243 AllocaInsertPt->setName("allocapt");
Mike Stump1eb44332009-09-09 15:08:12 +0000244
John McCallf1549f62010-07-06 01:34:17 +0000245 ReturnBlock = getJumpDestInCurrentScope("return");
Mike Stump1eb44332009-09-09 15:08:12 +0000246
Chris Lattner41110242008-06-17 18:05:57 +0000247 Builder.SetInsertPoint(EntryBB);
Mike Stump1eb44332009-09-09 15:08:12 +0000248
Douglas Gregorce056bc2010-02-21 22:15:06 +0000249 QualType FnType = getContext().getFunctionType(RetTy, 0, 0, false, 0,
250 false, false, 0, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +0000251 /*FIXME?*/
252 FunctionType::ExtInfo());
Mike Stump91cc8152009-10-23 01:52:13 +0000253
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000254 // Emit subprogram debug descriptor.
Anders Carlssone896d982009-02-13 08:11:52 +0000255 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000256 DI->setLocation(StartLoc);
Devang Patel9c6c3a02010-01-14 00:36:21 +0000257 DI->EmitFunctionStart(GD, FnType, CurFn, Builder);
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000258 }
259
Chris Lattner7255a2d2010-06-22 00:03:40 +0000260 EmitFunctionInstrumentation("__cyg_profile_func_enter");
261
Daniel Dunbar88b53962009-02-02 22:03:45 +0000262 // FIXME: Leaked.
John McCall04a67a62010-02-05 21:31:56 +0000263 // CC info is ignored, hopefully?
264 CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args,
Rafael Espindola264ba482010-03-30 20:24:48 +0000265 FunctionType::ExtInfo());
Eli Friedmanb17daf92009-12-04 02:43:40 +0000266
267 if (RetTy->isVoidType()) {
268 // Void type; nothing to return.
269 ReturnValue = 0;
270 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
271 hasAggregateLLVMType(CurFnInfo->getReturnType())) {
272 // Indirect aggregate return; emit returned value directly into sret slot.
Daniel Dunbar647a1ec2010-02-16 19:45:20 +0000273 // This reduces code size, and affects correctness in C++.
Eli Friedmanb17daf92009-12-04 02:43:40 +0000274 ReturnValue = CurFn->arg_begin();
275 } else {
Daniel Dunbar647a1ec2010-02-16 19:45:20 +0000276 ReturnValue = CreateIRTemp(RetTy, "retval");
Eli Friedmanb17daf92009-12-04 02:43:40 +0000277 }
278
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000279 EmitStartEHSpec(CurCodeDecl);
Daniel Dunbar88b53962009-02-02 22:03:45 +0000280 EmitFunctionProlog(*CurFnInfo, CurFn, Args);
Mike Stump1eb44332009-09-09 15:08:12 +0000281
John McCall4c40d982010-08-31 07:33:07 +0000282 if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance())
283 CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
John McCall25049412010-02-16 22:04:33 +0000284
Anders Carlsson751358f2008-12-20 21:28:43 +0000285 // If any of the arguments have a variably modified type, make sure to
286 // emit the type size.
287 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
288 i != e; ++i) {
289 QualType Ty = i->second;
290
291 if (Ty->isVariablyModifiedType())
292 EmitVLASize(Ty);
293 }
Daniel Dunbar7c086512008-09-09 23:14:03 +0000294}
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000295
John McCall9fc6a772010-02-19 09:25:03 +0000296void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args) {
297 const FunctionDecl *FD = cast<FunctionDecl>(CurGD.getDecl());
Douglas Gregor06a9f362010-05-01 20:49:11 +0000298 assert(FD->getBody());
299 EmitStmt(FD->getBody());
John McCalla355e072010-02-18 03:17:58 +0000300}
301
John McCall39dad532010-08-03 22:46:07 +0000302/// Tries to mark the given function nounwind based on the
303/// non-existence of any throwing calls within it. We believe this is
304/// lightweight enough to do at -O0.
305static void TryMarkNoThrow(llvm::Function *F) {
John McCallb3a29f12010-08-11 22:38:33 +0000306 // LLVM treats 'nounwind' on a function as part of the type, so we
307 // can't do this on functions that can be overwritten.
308 if (F->mayBeOverridden()) return;
309
John McCall39dad532010-08-03 22:46:07 +0000310 for (llvm::Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI)
311 for (llvm::BasicBlock::iterator
312 BI = FI->begin(), BE = FI->end(); BI != BE; ++BI)
313 if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(&*BI))
314 if (!Call->doesNotThrow())
315 return;
316 F->setDoesNotThrow(true);
317}
318
Anders Carlssonc997d422010-01-02 01:01:18 +0000319void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn) {
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000320 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
321
Anders Carlssone896d982009-02-13 08:11:52 +0000322 // Check if we should generate debug info for this function.
Mike Stump1feade82009-08-26 22:31:08 +0000323 if (CGM.getDebugInfo() && !FD->hasAttr<NoDebugAttr>())
Anders Carlssone896d982009-02-13 08:11:52 +0000324 DebugInfo = CGM.getDebugInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000325
Daniel Dunbar7c086512008-09-09 23:14:03 +0000326 FunctionArgList Args;
John McCall4c40d982010-08-31 07:33:07 +0000327 QualType ResTy = FD->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +0000328
Mike Stump6a1e0eb2009-12-04 23:26:17 +0000329 CurGD = GD;
John McCall4c40d982010-08-31 07:33:07 +0000330 if (isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isInstance())
331 CGM.getCXXABI().BuildInstanceFunctionParams(*this, ResTy, Args);
Mike Stump1eb44332009-09-09 15:08:12 +0000332
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000333 if (FD->getNumParams()) {
John McCall183700f2009-09-21 23:43:11 +0000334 const FunctionProtoType* FProto = FD->getType()->getAs<FunctionProtoType>();
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000335 assert(FProto && "Function def must have prototype!");
Daniel Dunbar7c086512008-09-09 23:14:03 +0000336
337 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
Mike Stump1eb44332009-09-09 15:08:12 +0000338 Args.push_back(std::make_pair(FD->getParamDecl(i),
Daniel Dunbar7c086512008-09-09 23:14:03 +0000339 FProto->getArgType(i)));
Chris Lattner41110242008-06-17 18:05:57 +0000340 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000341
John McCalla355e072010-02-18 03:17:58 +0000342 SourceRange BodyRange;
343 if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange();
Anders Carlsson4365bba2009-11-06 02:55:43 +0000344
John McCalla355e072010-02-18 03:17:58 +0000345 // Emit the standard function prologue.
John McCall4c40d982010-08-31 07:33:07 +0000346 StartFunction(GD, ResTy, Fn, Args, BodyRange.getBegin());
Anders Carlsson4365bba2009-11-06 02:55:43 +0000347
John McCalla355e072010-02-18 03:17:58 +0000348 // Generate the body of the function.
John McCall9fc6a772010-02-19 09:25:03 +0000349 if (isa<CXXDestructorDecl>(FD))
350 EmitDestructorBody(Args);
351 else if (isa<CXXConstructorDecl>(FD))
352 EmitConstructorBody(Args);
353 else
354 EmitFunctionBody(Args);
Anders Carlsson1851a122010-02-07 19:45:40 +0000355
John McCalla355e072010-02-18 03:17:58 +0000356 // Emit the standard function epilogue.
357 FinishFunction(BodyRange.getEnd());
John McCall39dad532010-08-03 22:46:07 +0000358
359 // If we haven't marked the function nothrow through other means, do
360 // a quick pass now to see if we can.
361 if (!CurFn->doesNotThrow())
362 TryMarkNoThrow(CurFn);
Chris Lattner41110242008-06-17 18:05:57 +0000363}
364
Chris Lattner0946ccd2008-11-11 07:41:27 +0000365/// ContainsLabel - Return true if the statement contains a label in it. If
366/// this statement is not executed normally, it not containing a label means
367/// that we can just remove the code.
368bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
369 // Null statement, not a label!
370 if (S == 0) return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000371
Chris Lattner0946ccd2008-11-11 07:41:27 +0000372 // If this is a label, we have to emit the code, consider something like:
373 // if (0) { ... foo: bar(); } goto foo;
374 if (isa<LabelStmt>(S))
375 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000376
Chris Lattner0946ccd2008-11-11 07:41:27 +0000377 // If this is a case/default statement, and we haven't seen a switch, we have
378 // to emit the code.
379 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
380 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000381
Chris Lattner0946ccd2008-11-11 07:41:27 +0000382 // If this is a switch statement, we want to ignore cases below it.
383 if (isa<SwitchStmt>(S))
384 IgnoreCaseStmts = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000385
Chris Lattner0946ccd2008-11-11 07:41:27 +0000386 // Scan subexpressions for verboten labels.
387 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
388 I != E; ++I)
389 if (ContainsLabel(*I, IgnoreCaseStmts))
390 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000391
Chris Lattner0946ccd2008-11-11 07:41:27 +0000392 return false;
393}
394
Chris Lattner31a09842008-11-12 08:04:58 +0000395
396/// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
397/// a constant, or if it does but contains a label, return 0. If it constant
398/// folds to 'true' and does not contain a label, return 1, if it constant folds
399/// to 'false' and does not contain a label, return -1.
400int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
Daniel Dunbar36bc14c2008-11-12 22:37:10 +0000401 // FIXME: Rename and handle conversion of other evaluatable things
402 // to bool.
Anders Carlsson64712f12008-12-01 02:46:24 +0000403 Expr::EvalResult Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000404 if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
Anders Carlsson64712f12008-12-01 02:46:24 +0000405 Result.HasSideEffects)
Anders Carlssonef5a66d2008-11-22 22:32:07 +0000406 return 0; // Not foldable, not integer or not fully evaluatable.
Mike Stump1eb44332009-09-09 15:08:12 +0000407
Chris Lattner31a09842008-11-12 08:04:58 +0000408 if (CodeGenFunction::ContainsLabel(Cond))
409 return 0; // Contains a label.
Mike Stump1eb44332009-09-09 15:08:12 +0000410
Anders Carlsson64712f12008-12-01 02:46:24 +0000411 return Result.Val.getInt().getBoolValue() ? 1 : -1;
Chris Lattner31a09842008-11-12 08:04:58 +0000412}
413
414
415/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
416/// statement) to the specified blocks. Based on the condition, this might try
417/// to simplify the codegen of the conditional based on the branch.
418///
419void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
420 llvm::BasicBlock *TrueBlock,
421 llvm::BasicBlock *FalseBlock) {
422 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
423 return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000424
Chris Lattner31a09842008-11-12 08:04:58 +0000425 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
426 // Handle X && Y in a condition.
John McCall2de56d12010-08-25 11:45:40 +0000427 if (CondBOp->getOpcode() == BO_LAnd) {
Chris Lattner31a09842008-11-12 08:04:58 +0000428 // If we have "1 && X", simplify the code. "0 && X" would have constant
429 // folded if the case was simple enough.
430 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
431 // br(1 && X) -> br(X).
432 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
433 }
Mike Stump1eb44332009-09-09 15:08:12 +0000434
Chris Lattner31a09842008-11-12 08:04:58 +0000435 // If we have "X && 1", simplify the code to use an uncond branch.
436 // "X && 0" would have been constant folded to 0.
437 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
438 // br(X && 1) -> br(X).
439 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
440 }
Mike Stump1eb44332009-09-09 15:08:12 +0000441
Chris Lattner31a09842008-11-12 08:04:58 +0000442 // Emit the LHS as a conditional. If the LHS conditional is false, we
443 // want to jump to the FalseBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000444 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
Chris Lattner31a09842008-11-12 08:04:58 +0000445 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
446 EmitBlock(LHSTrue);
Mike Stump1eb44332009-09-09 15:08:12 +0000447
Anders Carlsson08e9e452010-01-24 00:20:05 +0000448 // Any temporaries created here are conditional.
Anders Carlsson72119a82010-02-04 17:18:07 +0000449 BeginConditionalBranch();
Chris Lattner31a09842008-11-12 08:04:58 +0000450 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
Anders Carlsson72119a82010-02-04 17:18:07 +0000451 EndConditionalBranch();
Anders Carlsson08e9e452010-01-24 00:20:05 +0000452
Chris Lattner31a09842008-11-12 08:04:58 +0000453 return;
John McCall2de56d12010-08-25 11:45:40 +0000454 } else if (CondBOp->getOpcode() == BO_LOr) {
Chris Lattner31a09842008-11-12 08:04:58 +0000455 // If we have "0 || X", simplify the code. "1 || X" would have constant
456 // folded if the case was simple enough.
457 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
458 // br(0 || X) -> br(X).
459 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
460 }
Mike Stump1eb44332009-09-09 15:08:12 +0000461
Chris Lattner31a09842008-11-12 08:04:58 +0000462 // If we have "X || 0", simplify the code to use an uncond branch.
463 // "X || 1" would have been constant folded to 1.
464 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
465 // br(X || 0) -> br(X).
466 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
467 }
Mike Stump1eb44332009-09-09 15:08:12 +0000468
Chris Lattner31a09842008-11-12 08:04:58 +0000469 // Emit the LHS as a conditional. If the LHS conditional is true, we
470 // want to jump to the TrueBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000471 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
Chris Lattner31a09842008-11-12 08:04:58 +0000472 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
473 EmitBlock(LHSFalse);
Mike Stump1eb44332009-09-09 15:08:12 +0000474
Anders Carlsson08e9e452010-01-24 00:20:05 +0000475 // Any temporaries created here are conditional.
Anders Carlsson72119a82010-02-04 17:18:07 +0000476 BeginConditionalBranch();
Chris Lattner31a09842008-11-12 08:04:58 +0000477 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
Anders Carlsson72119a82010-02-04 17:18:07 +0000478 EndConditionalBranch();
Anders Carlsson08e9e452010-01-24 00:20:05 +0000479
Chris Lattner31a09842008-11-12 08:04:58 +0000480 return;
481 }
Chris Lattner552f4c42008-11-12 08:13:36 +0000482 }
Mike Stump1eb44332009-09-09 15:08:12 +0000483
Chris Lattner552f4c42008-11-12 08:13:36 +0000484 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
485 // br(!x, t, f) -> br(x, f, t)
John McCall2de56d12010-08-25 11:45:40 +0000486 if (CondUOp->getOpcode() == UO_LNot)
Chris Lattner552f4c42008-11-12 08:13:36 +0000487 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
Chris Lattner31a09842008-11-12 08:04:58 +0000488 }
Mike Stump1eb44332009-09-09 15:08:12 +0000489
Daniel Dunbar09b14892008-11-12 10:30:32 +0000490 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
491 // Handle ?: operator.
492
493 // Just ignore GNU ?: extension.
494 if (CondOp->getLHS()) {
495 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
496 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
497 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
498 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
499 EmitBlock(LHSBlock);
500 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
501 EmitBlock(RHSBlock);
502 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
503 return;
504 }
505 }
506
Chris Lattner31a09842008-11-12 08:04:58 +0000507 // Emit the code with the fully general case.
508 llvm::Value *CondV = EvaluateExprAsBool(Cond);
509 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
510}
511
Daniel Dunbar488e9932008-08-16 00:56:44 +0000512/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000513/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000514void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
515 bool OmitOnError) {
516 CGM.ErrorUnsupported(S, Type, OmitOnError);
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000517}
518
Anders Carlsson1884eb02010-05-22 17:35:42 +0000519void
520CodeGenFunction::EmitNullInitialization(llvm::Value *DestPtr, QualType Ty) {
Anders Carlsson0d7c5832010-05-03 01:20:20 +0000521 // Ignore empty classes in C++.
522 if (getContext().getLangOptions().CPlusPlus) {
523 if (const RecordType *RT = Ty->getAs<RecordType>()) {
524 if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
525 return;
526 }
527 }
John McCall90217182010-08-07 08:21:30 +0000528
529 // Cast the dest ptr to the appropriate i8 pointer type.
530 unsigned DestAS =
531 cast<llvm::PointerType>(DestPtr->getType())->getAddressSpace();
532 const llvm::Type *BP =
533 llvm::Type::getInt8PtrTy(VMContext, DestAS);
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000534 if (DestPtr->getType() != BP)
535 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
536
537 // Get size and alignment info for this aggregate.
538 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
John McCall90217182010-08-07 08:21:30 +0000539 uint64_t Size = TypeInfo.first;
540 unsigned Align = TypeInfo.second;
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000541
Chris Lattner88207c92009-04-21 17:59:23 +0000542 // Don't bother emitting a zero-byte memset.
John McCall90217182010-08-07 08:21:30 +0000543 if (Size == 0)
Chris Lattner88207c92009-04-21 17:59:23 +0000544 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000545
John McCall90217182010-08-07 08:21:30 +0000546 llvm::ConstantInt *SizeVal = llvm::ConstantInt::get(IntPtrTy, Size / 8);
547 llvm::ConstantInt *AlignVal = Builder.getInt32(Align / 8);
548
549 // If the type contains a pointer to data member we can't memset it to zero.
550 // Instead, create a null constant and copy it to the destination.
John McCallf16aa102010-08-22 21:01:12 +0000551 if (!CGM.getTypes().isZeroInitializable(Ty)) {
John McCall90217182010-08-07 08:21:30 +0000552 llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
553
554 llvm::GlobalVariable *NullVariable =
555 new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
556 /*isConstant=*/true,
557 llvm::GlobalVariable::PrivateLinkage,
558 NullConstant, llvm::Twine());
559 llvm::Value *SrcPtr =
560 Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy());
561
562 // FIXME: variable-size types?
563
564 // Get and call the appropriate llvm.memcpy overload.
565 llvm::Constant *Memcpy =
566 CGM.getMemCpyFn(DestPtr->getType(), SrcPtr->getType(), IntPtrTy);
567 Builder.CreateCall5(Memcpy, DestPtr, SrcPtr, SizeVal, AlignVal,
568 /*volatile*/ Builder.getFalse());
569 return;
570 }
571
572 // Otherwise, just memset the whole thing to zero. This is legal
573 // because in LLVM, all default initializers (other than the ones we just
574 // handled above) are guaranteed to have a bit pattern of all zeros.
575
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000576 // FIXME: Handle variable sized types.
Chris Lattner77b89b82010-06-27 07:15:29 +0000577 Builder.CreateCall5(CGM.getMemSetFn(BP, IntPtrTy), DestPtr,
John McCall90217182010-08-07 08:21:30 +0000578 Builder.getInt8(0),
579 SizeVal, AlignVal, /*volatile*/ Builder.getFalse());
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000580}
581
Chris Lattnerd9becd12009-10-28 23:59:40 +0000582llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelStmt *L) {
583 // Make sure that there is a block for the indirect goto.
584 if (IndirectBranch == 0)
585 GetIndirectGotoBlock();
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000586
John McCallff8e1152010-07-23 21:56:41 +0000587 llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000588
Chris Lattnerd9becd12009-10-28 23:59:40 +0000589 // Make sure the indirect branch includes all of the address-taken blocks.
590 IndirectBranch->addDestination(BB);
591 return llvm::BlockAddress::get(CurFn, BB);
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000592}
593
594llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
Chris Lattnerd9becd12009-10-28 23:59:40 +0000595 // If we already made the indirect branch for indirect goto, return its block.
596 if (IndirectBranch) return IndirectBranch->getParent();
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000597
Chris Lattnerd9becd12009-10-28 23:59:40 +0000598 CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto"));
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000599
Chris Lattnerd9becd12009-10-28 23:59:40 +0000600 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
Chris Lattner85e74ac2009-10-28 20:36:47 +0000601
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000602 // Create the PHI node that indirect gotos will add entries to.
Chris Lattnerd9becd12009-10-28 23:59:40 +0000603 llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, "indirect.goto.dest");
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000604
Chris Lattnerd9becd12009-10-28 23:59:40 +0000605 // Create the indirect branch instruction.
606 IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
607 return IndirectBranch->getParent();
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000608}
Anders Carlssonddf7cac2008-11-04 05:30:00 +0000609
Daniel Dunbard286f052009-07-19 06:58:07 +0000610llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) {
Eli Friedmanbbed6b92009-08-15 02:50:32 +0000611 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
Mike Stump1eb44332009-09-09 15:08:12 +0000612
Anders Carlssonf666b772008-12-20 20:27:15 +0000613 assert(SizeEntry && "Did not emit size for type");
614 return SizeEntry;
615}
Anders Carlssondcc90d82008-12-12 07:19:02 +0000616
Daniel Dunbard286f052009-07-19 06:58:07 +0000617llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) {
Anders Carlsson60d35412008-12-20 20:46:34 +0000618 assert(Ty->isVariablyModifiedType() &&
619 "Must pass variably modified type to EmitVLASizes!");
Mike Stump1eb44332009-09-09 15:08:12 +0000620
Daniel Dunbard286f052009-07-19 06:58:07 +0000621 EnsureInsertPoint();
Mike Stump1eb44332009-09-09 15:08:12 +0000622
Anders Carlsson60d35412008-12-20 20:46:34 +0000623 if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
Eli Friedmanbbed6b92009-08-15 02:50:32 +0000624 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
Mike Stump1eb44332009-09-09 15:08:12 +0000625
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000626 if (!SizeEntry) {
Anders Carlsson96f21472009-02-05 19:43:10 +0000627 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
Mike Stump1eb44332009-09-09 15:08:12 +0000628
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000629 // Get the element size;
630 QualType ElemTy = VAT->getElementType();
631 llvm::Value *ElemSize;
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000632 if (ElemTy->isVariableArrayType())
633 ElemSize = EmitVLASize(ElemTy);
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000634 else
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000635 ElemSize = llvm::ConstantInt::get(SizeTy,
Ken Dyck199c3d62010-01-11 17:06:35 +0000636 getContext().getTypeSizeInChars(ElemTy).getQuantity());
Mike Stump1eb44332009-09-09 15:08:12 +0000637
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000638 llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
Anders Carlsson96f21472009-02-05 19:43:10 +0000639 NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
Mike Stump1eb44332009-09-09 15:08:12 +0000640
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000641 SizeEntry = Builder.CreateMul(ElemSize, NumElements);
Anders Carlsson60d35412008-12-20 20:46:34 +0000642 }
Mike Stump1eb44332009-09-09 15:08:12 +0000643
Anders Carlsson60d35412008-12-20 20:46:34 +0000644 return SizeEntry;
Anders Carlssondcc90d82008-12-12 07:19:02 +0000645 }
Mike Stump1eb44332009-09-09 15:08:12 +0000646
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000647 if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
648 EmitVLASize(AT->getElementType());
649 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000650 }
651
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000652 const PointerType *PT = Ty->getAs<PointerType>();
653 assert(PT && "unknown VM type!");
654 EmitVLASize(PT->getPointeeType());
Anders Carlsson60d35412008-12-20 20:46:34 +0000655 return 0;
Anders Carlssondcc90d82008-12-12 07:19:02 +0000656}
Eli Friedman4fd0aa52009-01-20 17:46:04 +0000657
658llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
Chris Lattnerfbe02ff2010-06-27 07:40:06 +0000659 if (CGM.getContext().getBuiltinVaListType()->isArrayType())
Eli Friedman4fd0aa52009-01-20 17:46:04 +0000660 return EmitScalarExpr(E);
Eli Friedman4fd0aa52009-01-20 17:46:04 +0000661 return EmitLValue(E).getAddress();
662}
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000663
John McCallf1549f62010-07-06 01:34:17 +0000664/// Pops cleanup blocks until the given savepoint is reached.
665void CodeGenFunction::PopCleanupBlocks(EHScopeStack::stable_iterator Old) {
666 assert(Old.isValid());
667
John McCallff8e1152010-07-23 21:56:41 +0000668 while (EHStack.stable_begin() != Old) {
669 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.begin());
670
671 // As long as Old strictly encloses the scope's enclosing normal
672 // cleanup, we're going to emit another normal cleanup which
673 // fallthrough can propagate through.
674 bool FallThroughIsBranchThrough =
675 Old.strictlyEncloses(Scope.getEnclosingNormalCleanup());
676
677 PopCleanupBlock(FallThroughIsBranchThrough);
678 }
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000679}
Anders Carlssonc71c8452009-02-07 23:50:39 +0000680
John McCallff8e1152010-07-23 21:56:41 +0000681static llvm::BasicBlock *CreateNormalEntry(CodeGenFunction &CGF,
682 EHCleanupScope &Scope) {
683 assert(Scope.isNormalCleanup());
684 llvm::BasicBlock *Entry = Scope.getNormalBlock();
685 if (!Entry) {
686 Entry = CGF.createBasicBlock("cleanup");
687 Scope.setNormalBlock(Entry);
Mike Stump99533832009-12-02 07:41:41 +0000688 }
John McCallff8e1152010-07-23 21:56:41 +0000689 return Entry;
690}
Mike Stump99533832009-12-02 07:41:41 +0000691
John McCallff8e1152010-07-23 21:56:41 +0000692static llvm::BasicBlock *CreateEHEntry(CodeGenFunction &CGF,
693 EHCleanupScope &Scope) {
694 assert(Scope.isEHCleanup());
695 llvm::BasicBlock *Entry = Scope.getEHBlock();
696 if (!Entry) {
697 Entry = CGF.createBasicBlock("eh.cleanup");
698 Scope.setEHBlock(Entry);
699 }
700 return Entry;
701}
Devang Patelcd9199e2010-04-13 00:08:43 +0000702
John McCallff8e1152010-07-23 21:56:41 +0000703/// Transitions the terminator of the given exit-block of a cleanup to
704/// be a cleanup switch.
705static llvm::SwitchInst *TransitionToCleanupSwitch(CodeGenFunction &CGF,
706 llvm::BasicBlock *Block) {
707 // If it's a branch, turn it into a switch whose default
708 // destination is its original target.
709 llvm::TerminatorInst *Term = Block->getTerminator();
710 assert(Term && "can't transition block without terminator");
711
712 if (llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Term)) {
713 assert(Br->isUnconditional());
714 llvm::LoadInst *Load =
715 new llvm::LoadInst(CGF.getNormalCleanupDestSlot(), "cleanup.dest", Term);
716 llvm::SwitchInst *Switch =
717 llvm::SwitchInst::Create(Load, Br->getSuccessor(0), 4, Block);
718 Br->eraseFromParent();
719 return Switch;
720 } else {
721 return cast<llvm::SwitchInst>(Term);
722 }
Anders Carlssond66a9f92009-02-08 03:55:35 +0000723}
724
John McCallf1549f62010-07-06 01:34:17 +0000725/// Attempts to reduce a cleanup's entry block to a fallthrough. This
726/// is basically llvm::MergeBlockIntoPredecessor, except
John McCallff8e1152010-07-23 21:56:41 +0000727/// simplified/optimized for the tighter constraints on cleanup blocks.
728///
729/// Returns the new block, whatever it is.
730static llvm::BasicBlock *SimplifyCleanupEntry(CodeGenFunction &CGF,
731 llvm::BasicBlock *Entry) {
John McCallf1549f62010-07-06 01:34:17 +0000732 llvm::BasicBlock *Pred = Entry->getSinglePredecessor();
John McCallff8e1152010-07-23 21:56:41 +0000733 if (!Pred) return Entry;
Mike Stump1eb44332009-09-09 15:08:12 +0000734
John McCallf1549f62010-07-06 01:34:17 +0000735 llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Pred->getTerminator());
John McCallff8e1152010-07-23 21:56:41 +0000736 if (!Br || Br->isConditional()) return Entry;
John McCallf1549f62010-07-06 01:34:17 +0000737 assert(Br->getSuccessor(0) == Entry);
738
739 // If we were previously inserting at the end of the cleanup entry
740 // block, we'll need to continue inserting at the end of the
741 // predecessor.
742 bool WasInsertBlock = CGF.Builder.GetInsertBlock() == Entry;
743 assert(!WasInsertBlock || CGF.Builder.GetInsertPoint() == Entry->end());
744
745 // Kill the branch.
746 Br->eraseFromParent();
747
748 // Merge the blocks.
749 Pred->getInstList().splice(Pred->end(), Entry->getInstList());
750
751 // Kill the entry block.
752 Entry->eraseFromParent();
753
754 if (WasInsertBlock)
755 CGF.Builder.SetInsertPoint(Pred);
Anders Carlsson87eaf172009-02-08 00:50:42 +0000756
John McCallff8e1152010-07-23 21:56:41 +0000757 return Pred;
John McCallf1549f62010-07-06 01:34:17 +0000758}
759
John McCall1f0fca52010-07-21 07:22:38 +0000760static void EmitCleanup(CodeGenFunction &CGF,
761 EHScopeStack::Cleanup *Fn,
John McCall7d8647f2010-09-14 07:57:04 +0000762 bool ForEH,
763 llvm::Value *ActiveFlag) {
764 // EH cleanups always occur within a terminate scope.
John McCallda65ea82010-07-13 20:32:21 +0000765 if (ForEH) CGF.EHStack.pushTerminate();
John McCall7d8647f2010-09-14 07:57:04 +0000766
767 // If there's an active flag, load it and skip the cleanup if it's
768 // false.
769 llvm::BasicBlock *ContBB = 0;
770 if (ActiveFlag) {
771 ContBB = CGF.createBasicBlock("cleanup.done");
772 llvm::BasicBlock *CleanupBB = CGF.createBasicBlock("cleanup.action");
773 llvm::Value *IsActive
774 = CGF.Builder.CreateLoad(ActiveFlag, "cleanup.is_active");
775 CGF.Builder.CreateCondBr(IsActive, CleanupBB, ContBB);
776 CGF.EmitBlock(CleanupBB);
777 }
778
779 // Ask the cleanup to emit itself.
John McCallda65ea82010-07-13 20:32:21 +0000780 Fn->Emit(CGF, ForEH);
John McCallda65ea82010-07-13 20:32:21 +0000781 assert(CGF.HaveInsertPoint() && "cleanup ended with no insertion point?");
John McCall7d8647f2010-09-14 07:57:04 +0000782
783 // Emit the continuation block if there was an active flag.
784 if (ActiveFlag)
785 CGF.EmitBlock(ContBB);
786
787 // Leave the terminate scope.
788 if (ForEH) CGF.EHStack.popTerminate();
789}
790
791static void ForwardPrebranchedFallthrough(llvm::BasicBlock *Exit,
792 llvm::BasicBlock *From,
793 llvm::BasicBlock *To) {
794 // Exit is the exit block of a cleanup, so it always terminates in
795 // an unconditional branch or a switch.
796 llvm::TerminatorInst *Term = Exit->getTerminator();
797
798 if (llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Term)) {
799 assert(Br->isUnconditional() && Br->getSuccessor(0) == From);
800 Br->setSuccessor(0, To);
801 } else {
802 llvm::SwitchInst *Switch = cast<llvm::SwitchInst>(Term);
803 for (unsigned I = 0, E = Switch->getNumSuccessors(); I != E; ++I)
804 if (Switch->getSuccessor(I) == From)
805 Switch->setSuccessor(I, To);
806 }
John McCallda65ea82010-07-13 20:32:21 +0000807}
808
John McCall1f0fca52010-07-21 07:22:38 +0000809/// Pops a cleanup block. If the block includes a normal cleanup, the
810/// current insertion point is threaded through the cleanup, as are
811/// any branch fixups on the cleanup.
John McCallff8e1152010-07-23 21:56:41 +0000812void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough) {
John McCall1f0fca52010-07-21 07:22:38 +0000813 assert(!EHStack.empty() && "cleanup stack is empty!");
814 assert(isa<EHCleanupScope>(*EHStack.begin()) && "top not a cleanup!");
815 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.begin());
816 assert(Scope.getFixupDepth() <= EHStack.getNumBranchFixups());
John McCall7d8647f2010-09-14 07:57:04 +0000817
818 // Remember activation information.
819 bool IsActive = Scope.isActive();
820 llvm::Value *NormalActiveFlag =
821 Scope.shouldTestFlagInNormalCleanup() ? Scope.getActiveFlag() : 0;
822 llvm::Value *EHActiveFlag =
823 Scope.shouldTestFlagInEHCleanup() ? Scope.getActiveFlag() : 0;
John McCallda65ea82010-07-13 20:32:21 +0000824
825 // Check whether we need an EH cleanup. This is only true if we've
826 // generated a lazy EH cleanup block.
John McCallff8e1152010-07-23 21:56:41 +0000827 bool RequiresEHCleanup = Scope.hasEHBranches();
John McCallda65ea82010-07-13 20:32:21 +0000828
829 // Check the three conditions which might require a normal cleanup:
830
831 // - whether there are branch fix-ups through this cleanup
832 unsigned FixupDepth = Scope.getFixupDepth();
John McCall1f0fca52010-07-21 07:22:38 +0000833 bool HasFixups = EHStack.getNumBranchFixups() != FixupDepth;
John McCallda65ea82010-07-13 20:32:21 +0000834
John McCallff8e1152010-07-23 21:56:41 +0000835 // - whether there are branch-throughs or branch-afters
836 bool HasExistingBranches = Scope.hasBranches();
John McCallda65ea82010-07-13 20:32:21 +0000837
838 // - whether there's a fallthrough
John McCall1f0fca52010-07-21 07:22:38 +0000839 llvm::BasicBlock *FallthroughSource = Builder.GetInsertBlock();
John McCall7d8647f2010-09-14 07:57:04 +0000840 bool HasFallthrough = (FallthroughSource != 0 && IsActive);
841
842 // As a kindof crazy internal case, branch-through fall-throughs
843 // leave the insertion point set to the end of the last cleanup.
844 bool HasPrebranchedFallthrough =
845 (FallthroughSource && FallthroughSource->getTerminator());
John McCallda65ea82010-07-13 20:32:21 +0000846
847 bool RequiresNormalCleanup = false;
848 if (Scope.isNormalCleanup() &&
849 (HasFixups || HasExistingBranches || HasFallthrough)) {
850 RequiresNormalCleanup = true;
851 }
852
John McCall7d8647f2010-09-14 07:57:04 +0000853 assert(!HasPrebranchedFallthrough || RequiresNormalCleanup || !IsActive);
854 assert(!HasPrebranchedFallthrough ||
855 (Scope.isNormalCleanup() && Scope.getNormalBlock() &&
856 FallthroughSource->getTerminator()->getSuccessor(0)
857 == Scope.getNormalBlock()));
858
859 // Even if we don't need the normal cleanup, we might still have
860 // prebranched fallthrough to worry about.
861 if (!RequiresNormalCleanup && HasPrebranchedFallthrough) {
862 assert(!IsActive);
863
864 llvm::BasicBlock *NormalEntry = Scope.getNormalBlock();
865
866 // If we're branching through this cleanup, just forward the
867 // prebranched fallthrough to the next cleanup, leaving the insert
868 // point in the old block.
869 if (FallthroughIsBranchThrough) {
870 EHScope &S = *EHStack.find(Scope.getEnclosingNormalCleanup());
871 llvm::BasicBlock *EnclosingEntry =
872 CreateNormalEntry(*this, cast<EHCleanupScope>(S));
873
874 ForwardPrebranchedFallthrough(FallthroughSource,
875 NormalEntry, EnclosingEntry);
876 assert(NormalEntry->use_empty() &&
877 "uses of entry remain after forwarding?");
878 delete NormalEntry;
879
880 // Otherwise, we're branching out; just emit the next block.
881 } else {
882 EmitBlock(NormalEntry);
883 SimplifyCleanupEntry(*this, NormalEntry);
884 }
885 }
886
John McCallda65ea82010-07-13 20:32:21 +0000887 // If we don't need the cleanup at all, we're done.
888 if (!RequiresNormalCleanup && !RequiresEHCleanup) {
John McCallff8e1152010-07-23 21:56:41 +0000889 EHStack.popCleanup(); // safe because there are no fixups
John McCall1f0fca52010-07-21 07:22:38 +0000890 assert(EHStack.getNumBranchFixups() == 0 ||
891 EHStack.hasNormalCleanups());
John McCallda65ea82010-07-13 20:32:21 +0000892 return;
893 }
894
895 // Copy the cleanup emission data out. Note that SmallVector
896 // guarantees maximal alignment for its buffer regardless of its
897 // type parameter.
898 llvm::SmallVector<char, 8*sizeof(void*)> CleanupBuffer;
899 CleanupBuffer.reserve(Scope.getCleanupSize());
900 memcpy(CleanupBuffer.data(),
901 Scope.getCleanupBuffer(), Scope.getCleanupSize());
902 CleanupBuffer.set_size(Scope.getCleanupSize());
John McCall1f0fca52010-07-21 07:22:38 +0000903 EHScopeStack::Cleanup *Fn =
904 reinterpret_cast<EHScopeStack::Cleanup*>(CleanupBuffer.data());
John McCallda65ea82010-07-13 20:32:21 +0000905
John McCallff8e1152010-07-23 21:56:41 +0000906 // We want to emit the EH cleanup after the normal cleanup, but go
907 // ahead and do the setup for the EH cleanup while the scope is still
908 // alive.
909 llvm::BasicBlock *EHEntry = 0;
910 llvm::SmallVector<llvm::Instruction*, 2> EHInstsToAppend;
911 if (RequiresEHCleanup) {
912 EHEntry = CreateEHEntry(*this, Scope);
John McCallda65ea82010-07-13 20:32:21 +0000913
John McCallff8e1152010-07-23 21:56:41 +0000914 // Figure out the branch-through dest if necessary.
915 llvm::BasicBlock *EHBranchThroughDest = 0;
916 if (Scope.hasEHBranchThroughs()) {
917 assert(Scope.getEnclosingEHCleanup() != EHStack.stable_end());
918 EHScope &S = *EHStack.find(Scope.getEnclosingEHCleanup());
919 EHBranchThroughDest = CreateEHEntry(*this, cast<EHCleanupScope>(S));
920 }
921
922 // If we have exactly one branch-after and no branch-throughs, we
923 // can dispatch it without a switch.
John McCall7cd4b062010-07-26 22:44:58 +0000924 if (!Scope.hasEHBranchThroughs() &&
John McCallff8e1152010-07-23 21:56:41 +0000925 Scope.getNumEHBranchAfters() == 1) {
926 assert(!EHBranchThroughDest);
927
928 // TODO: remove the spurious eh.cleanup.dest stores if this edge
929 // never went through any switches.
930 llvm::BasicBlock *BranchAfterDest = Scope.getEHBranchAfterBlock(0);
931 EHInstsToAppend.push_back(llvm::BranchInst::Create(BranchAfterDest));
932
933 // Otherwise, if we have any branch-afters, we need a switch.
934 } else if (Scope.getNumEHBranchAfters()) {
935 // The default of the switch belongs to the branch-throughs if
936 // they exist.
937 llvm::BasicBlock *Default =
938 (EHBranchThroughDest ? EHBranchThroughDest : getUnreachableBlock());
939
940 const unsigned SwitchCapacity = Scope.getNumEHBranchAfters();
941
942 llvm::LoadInst *Load =
943 new llvm::LoadInst(getEHCleanupDestSlot(), "cleanup.dest");
944 llvm::SwitchInst *Switch =
945 llvm::SwitchInst::Create(Load, Default, SwitchCapacity);
946
947 EHInstsToAppend.push_back(Load);
948 EHInstsToAppend.push_back(Switch);
949
950 for (unsigned I = 0, E = Scope.getNumEHBranchAfters(); I != E; ++I)
951 Switch->addCase(Scope.getEHBranchAfterIndex(I),
952 Scope.getEHBranchAfterBlock(I));
953
954 // Otherwise, we have only branch-throughs; jump to the next EH
955 // cleanup.
956 } else {
957 assert(EHBranchThroughDest);
958 EHInstsToAppend.push_back(llvm::BranchInst::Create(EHBranchThroughDest));
959 }
960 }
961
962 if (!RequiresNormalCleanup) {
963 EHStack.popCleanup();
964 } else {
John McCallda65ea82010-07-13 20:32:21 +0000965 // If we have a fallthrough and no other need for the cleanup,
966 // emit it directly.
John McCallff8e1152010-07-23 21:56:41 +0000967 if (HasFallthrough && !HasPrebranchedFallthrough &&
968 !HasFixups && !HasExistingBranches) {
969
970 // Fixups can cause us to optimistically create a normal block,
971 // only to later have no real uses for it. Just delete it in
972 // this case.
973 // TODO: we can potentially simplify all the uses after this.
974 if (Scope.getNormalBlock()) {
975 Scope.getNormalBlock()->replaceAllUsesWith(getUnreachableBlock());
976 delete Scope.getNormalBlock();
977 }
978
979 EHStack.popCleanup();
980
John McCall7d8647f2010-09-14 07:57:04 +0000981 EmitCleanup(*this, Fn, /*ForEH*/ false, NormalActiveFlag);
John McCallda65ea82010-07-13 20:32:21 +0000982
983 // Otherwise, the best approach is to thread everything through
984 // the cleanup block and then try to clean up after ourselves.
985 } else {
986 // Force the entry block to exist.
John McCallff8e1152010-07-23 21:56:41 +0000987 llvm::BasicBlock *NormalEntry = CreateNormalEntry(*this, Scope);
John McCallda65ea82010-07-13 20:32:21 +0000988
John McCall7d8647f2010-09-14 07:57:04 +0000989 // I. Set up the fallthrough edge in.
990
John McCallff8e1152010-07-23 21:56:41 +0000991 // If there's a fallthrough, we need to store the cleanup
992 // destination index. For fall-throughs this is always zero.
John McCall7d8647f2010-09-14 07:57:04 +0000993 if (HasFallthrough) {
994 if (!HasPrebranchedFallthrough)
995 Builder.CreateStore(Builder.getInt32(0), getNormalCleanupDestSlot());
John McCallff8e1152010-07-23 21:56:41 +0000996
John McCall7d8647f2010-09-14 07:57:04 +0000997 // Otherwise, clear the IP if we don't have fallthrough because
998 // the cleanup is inactive. We don't need to save it because
999 // it's still just FallthroughSource.
1000 } else if (FallthroughSource) {
1001 assert(!IsActive && "source without fallthrough for active cleanup");
1002 Builder.ClearInsertionPoint();
1003 }
1004
1005 // II. Emit the entry block. This implicitly branches to it if
1006 // we have fallthrough. All the fixups and existing branches
1007 // should already be branched to it.
John McCall1f0fca52010-07-21 07:22:38 +00001008 EmitBlock(NormalEntry);
John McCallda65ea82010-07-13 20:32:21 +00001009
John McCall7d8647f2010-09-14 07:57:04 +00001010 // III. Figure out where we're going and build the cleanup
1011 // epilogue.
1012
John McCallff8e1152010-07-23 21:56:41 +00001013 bool HasEnclosingCleanups =
1014 (Scope.getEnclosingNormalCleanup() != EHStack.stable_end());
John McCallda65ea82010-07-13 20:32:21 +00001015
John McCallff8e1152010-07-23 21:56:41 +00001016 // Compute the branch-through dest if we need it:
1017 // - if there are branch-throughs threaded through the scope
1018 // - if fall-through is a branch-through
1019 // - if there are fixups that will be optimistically forwarded
1020 // to the enclosing cleanup
1021 llvm::BasicBlock *BranchThroughDest = 0;
1022 if (Scope.hasBranchThroughs() ||
John McCall7d8647f2010-09-14 07:57:04 +00001023 (FallthroughSource && FallthroughIsBranchThrough) ||
John McCallff8e1152010-07-23 21:56:41 +00001024 (HasFixups && HasEnclosingCleanups)) {
1025 assert(HasEnclosingCleanups);
1026 EHScope &S = *EHStack.find(Scope.getEnclosingNormalCleanup());
1027 BranchThroughDest = CreateNormalEntry(*this, cast<EHCleanupScope>(S));
John McCallda65ea82010-07-13 20:32:21 +00001028 }
1029
John McCallff8e1152010-07-23 21:56:41 +00001030 llvm::BasicBlock *FallthroughDest = 0;
1031 llvm::SmallVector<llvm::Instruction*, 2> InstsToAppend;
1032
1033 // If there's exactly one branch-after and no other threads,
1034 // we can route it without a switch.
1035 if (!Scope.hasBranchThroughs() && !HasFixups && !HasFallthrough &&
1036 Scope.getNumBranchAfters() == 1) {
John McCall7d8647f2010-09-14 07:57:04 +00001037 assert(!BranchThroughDest || !IsActive);
John McCallff8e1152010-07-23 21:56:41 +00001038
1039 // TODO: clean up the possibly dead stores to the cleanup dest slot.
1040 llvm::BasicBlock *BranchAfter = Scope.getBranchAfterBlock(0);
1041 InstsToAppend.push_back(llvm::BranchInst::Create(BranchAfter));
1042
1043 // Build a switch-out if we need it:
1044 // - if there are branch-afters threaded through the scope
1045 // - if fall-through is a branch-after
1046 // - if there are fixups that have nowhere left to go and
1047 // so must be immediately resolved
1048 } else if (Scope.getNumBranchAfters() ||
1049 (HasFallthrough && !FallthroughIsBranchThrough) ||
1050 (HasFixups && !HasEnclosingCleanups)) {
1051
1052 llvm::BasicBlock *Default =
1053 (BranchThroughDest ? BranchThroughDest : getUnreachableBlock());
1054
1055 // TODO: base this on the number of branch-afters and fixups
1056 const unsigned SwitchCapacity = 10;
1057
1058 llvm::LoadInst *Load =
1059 new llvm::LoadInst(getNormalCleanupDestSlot(), "cleanup.dest");
1060 llvm::SwitchInst *Switch =
1061 llvm::SwitchInst::Create(Load, Default, SwitchCapacity);
1062
1063 InstsToAppend.push_back(Load);
1064 InstsToAppend.push_back(Switch);
1065
1066 // Branch-after fallthrough.
John McCall7d8647f2010-09-14 07:57:04 +00001067 if (FallthroughSource && !FallthroughIsBranchThrough) {
John McCallff8e1152010-07-23 21:56:41 +00001068 FallthroughDest = createBasicBlock("cleanup.cont");
John McCall7d8647f2010-09-14 07:57:04 +00001069 if (HasFallthrough)
1070 Switch->addCase(Builder.getInt32(0), FallthroughDest);
John McCallff8e1152010-07-23 21:56:41 +00001071 }
1072
1073 for (unsigned I = 0, E = Scope.getNumBranchAfters(); I != E; ++I) {
1074 Switch->addCase(Scope.getBranchAfterIndex(I),
1075 Scope.getBranchAfterBlock(I));
1076 }
1077
1078 if (HasFixups && !HasEnclosingCleanups)
1079 ResolveAllBranchFixups(Switch);
1080 } else {
1081 // We should always have a branch-through destination in this case.
1082 assert(BranchThroughDest);
1083 InstsToAppend.push_back(llvm::BranchInst::Create(BranchThroughDest));
1084 }
1085
John McCall7d8647f2010-09-14 07:57:04 +00001086 // IV. Pop the cleanup and emit it.
John McCallff8e1152010-07-23 21:56:41 +00001087 EHStack.popCleanup();
1088 assert(EHStack.hasNormalCleanups() == HasEnclosingCleanups);
1089
John McCall7d8647f2010-09-14 07:57:04 +00001090 EmitCleanup(*this, Fn, /*ForEH*/ false, NormalActiveFlag);
John McCallff8e1152010-07-23 21:56:41 +00001091
1092 // Append the prepared cleanup prologue from above.
1093 llvm::BasicBlock *NormalExit = Builder.GetInsertBlock();
1094 for (unsigned I = 0, E = InstsToAppend.size(); I != E; ++I)
1095 NormalExit->getInstList().push_back(InstsToAppend[I]);
1096
1097 // Optimistically hope that any fixups will continue falling through.
John McCall1f0fca52010-07-21 07:22:38 +00001098 for (unsigned I = FixupDepth, E = EHStack.getNumBranchFixups();
John McCallff8e1152010-07-23 21:56:41 +00001099 I < E; ++I) {
1100 BranchFixup &Fixup = CGF.EHStack.getBranchFixup(I);
1101 if (!Fixup.Destination) continue;
1102 if (!Fixup.OptimisticBranchBlock) {
1103 new llvm::StoreInst(Builder.getInt32(Fixup.DestinationIndex),
1104 getNormalCleanupDestSlot(),
1105 Fixup.InitialBranch);
1106 Fixup.InitialBranch->setSuccessor(0, NormalEntry);
1107 }
1108 Fixup.OptimisticBranchBlock = NormalExit;
1109 }
John McCall7d8647f2010-09-14 07:57:04 +00001110
1111 // V. Set up the fallthrough edge out.
John McCallff8e1152010-07-23 21:56:41 +00001112
John McCall7d8647f2010-09-14 07:57:04 +00001113 // Case 1: a fallthrough source exists but shouldn't branch to
1114 // the cleanup because the cleanup is inactive.
1115 if (!HasFallthrough && FallthroughSource) {
1116 assert(!IsActive);
1117
1118 // If we have a prebranched fallthrough, that needs to be
1119 // forwarded to the right block.
1120 if (HasPrebranchedFallthrough) {
1121 llvm::BasicBlock *Next;
1122 if (FallthroughIsBranchThrough) {
1123 Next = BranchThroughDest;
1124 assert(!FallthroughDest);
1125 } else {
1126 Next = FallthroughDest;
1127 }
1128
1129 ForwardPrebranchedFallthrough(FallthroughSource, NormalEntry, Next);
1130 }
1131 Builder.SetInsertPoint(FallthroughSource);
1132
1133 // Case 2: a fallthrough source exists and should branch to the
1134 // cleanup, but we're not supposed to branch through to the next
1135 // cleanup.
1136 } else if (HasFallthrough && FallthroughDest) {
1137 assert(!FallthroughIsBranchThrough);
John McCallff8e1152010-07-23 21:56:41 +00001138 EmitBlock(FallthroughDest);
John McCall7d8647f2010-09-14 07:57:04 +00001139
1140 // Case 3: a fallthrough source exists and should branch to the
1141 // cleanup and then through to the next.
1142 } else if (HasFallthrough) {
1143 // Everything is already set up for this.
1144
1145 // Case 4: no fallthrough source exists.
1146 } else {
John McCallff8e1152010-07-23 21:56:41 +00001147 Builder.ClearInsertionPoint();
John McCall7d8647f2010-09-14 07:57:04 +00001148 }
1149
1150 // VI. Assorted cleaning.
John McCallda65ea82010-07-13 20:32:21 +00001151
John McCallff8e1152010-07-23 21:56:41 +00001152 // Check whether we can merge NormalEntry into a single predecessor.
1153 // This might invalidate (non-IR) pointers to NormalEntry.
1154 llvm::BasicBlock *NewNormalEntry =
1155 SimplifyCleanupEntry(*this, NormalEntry);
John McCallda65ea82010-07-13 20:32:21 +00001156
John McCallff8e1152010-07-23 21:56:41 +00001157 // If it did invalidate those pointers, and NormalEntry was the same
1158 // as NormalExit, go back and patch up the fixups.
1159 if (NewNormalEntry != NormalEntry && NormalEntry == NormalExit)
1160 for (unsigned I = FixupDepth, E = EHStack.getNumBranchFixups();
1161 I < E; ++I)
1162 CGF.EHStack.getBranchFixup(I).OptimisticBranchBlock = NewNormalEntry;
John McCallda65ea82010-07-13 20:32:21 +00001163 }
1164 }
1165
John McCallff8e1152010-07-23 21:56:41 +00001166 assert(EHStack.hasNormalCleanups() || EHStack.getNumBranchFixups() == 0);
1167
John McCallda65ea82010-07-13 20:32:21 +00001168 // Emit the EH cleanup if required.
1169 if (RequiresEHCleanup) {
John McCall1f0fca52010-07-21 07:22:38 +00001170 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
John McCallff8e1152010-07-23 21:56:41 +00001171
John McCall1f0fca52010-07-21 07:22:38 +00001172 EmitBlock(EHEntry);
John McCall7d8647f2010-09-14 07:57:04 +00001173 EmitCleanup(*this, Fn, /*ForEH*/ true, EHActiveFlag);
John McCallff8e1152010-07-23 21:56:41 +00001174
1175 // Append the prepared cleanup prologue from above.
1176 llvm::BasicBlock *EHExit = Builder.GetInsertBlock();
1177 for (unsigned I = 0, E = EHInstsToAppend.size(); I != E; ++I)
1178 EHExit->getInstList().push_back(EHInstsToAppend[I]);
1179
John McCall1f0fca52010-07-21 07:22:38 +00001180 Builder.restoreIP(SavedIP);
John McCallff8e1152010-07-23 21:56:41 +00001181
1182 SimplifyCleanupEntry(*this, EHEntry);
John McCallda65ea82010-07-13 20:32:21 +00001183 }
1184}
1185
John McCallff8e1152010-07-23 21:56:41 +00001186/// Terminate the current block by emitting a branch which might leave
1187/// the current cleanup-protected scope. The target scope may not yet
1188/// be known, in which case this will require a fixup.
1189///
1190/// As a side-effect, this method clears the insertion point.
John McCallf1549f62010-07-06 01:34:17 +00001191void CodeGenFunction::EmitBranchThroughCleanup(JumpDest Dest) {
John McCall413e6772010-07-28 01:07:35 +00001192 assert(Dest.getScopeDepth().encloses(EHStack.getInnermostNormalCleanup())
1193 && "stale jump destination");
1194
Anders Carlsson46831a92009-02-08 22:13:37 +00001195 if (!HaveInsertPoint())
1196 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001197
John McCallf1549f62010-07-06 01:34:17 +00001198 // Create the branch.
John McCallff8e1152010-07-23 21:56:41 +00001199 llvm::BranchInst *BI = Builder.CreateBr(Dest.getBlock());
Mike Stump1eb44332009-09-09 15:08:12 +00001200
John McCall838d7962010-08-14 07:46:19 +00001201 // Calculate the innermost active normal cleanup.
1202 EHScopeStack::stable_iterator
1203 TopCleanup = EHStack.getInnermostActiveNormalCleanup();
1204
1205 // If we're not in an active normal cleanup scope, or if the
1206 // destination scope is within the innermost active normal cleanup
1207 // scope, we don't need to worry about fixups.
1208 if (TopCleanup == EHStack.stable_end() ||
1209 TopCleanup.encloses(Dest.getScopeDepth())) { // works for invalid
John McCallf1549f62010-07-06 01:34:17 +00001210 Builder.ClearInsertionPoint();
1211 return;
1212 }
1213
John McCallf1549f62010-07-06 01:34:17 +00001214 // If we can't resolve the destination cleanup scope, just add this
John McCallff8e1152010-07-23 21:56:41 +00001215 // to the current cleanup scope as a branch fixup.
1216 if (!Dest.getScopeDepth().isValid()) {
1217 BranchFixup &Fixup = EHStack.addBranchFixup();
1218 Fixup.Destination = Dest.getBlock();
1219 Fixup.DestinationIndex = Dest.getDestIndex();
1220 Fixup.InitialBranch = BI;
1221 Fixup.OptimisticBranchBlock = 0;
1222
John McCallf1549f62010-07-06 01:34:17 +00001223 Builder.ClearInsertionPoint();
1224 return;
1225 }
1226
John McCallff8e1152010-07-23 21:56:41 +00001227 // Otherwise, thread through all the normal cleanups in scope.
1228
1229 // Store the index at the start.
1230 llvm::ConstantInt *Index = Builder.getInt32(Dest.getDestIndex());
1231 new llvm::StoreInst(Index, getNormalCleanupDestSlot(), BI);
1232
1233 // Adjust BI to point to the first cleanup block.
1234 {
1235 EHCleanupScope &Scope =
John McCall838d7962010-08-14 07:46:19 +00001236 cast<EHCleanupScope>(*EHStack.find(TopCleanup));
John McCallff8e1152010-07-23 21:56:41 +00001237 BI->setSuccessor(0, CreateNormalEntry(*this, Scope));
1238 }
1239
1240 // Add this destination to all the scopes involved.
John McCall838d7962010-08-14 07:46:19 +00001241 EHScopeStack::stable_iterator I = TopCleanup;
John McCallff8e1152010-07-23 21:56:41 +00001242 EHScopeStack::stable_iterator E = Dest.getScopeDepth();
1243 if (E.strictlyEncloses(I)) {
1244 while (true) {
1245 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(I));
1246 assert(Scope.isNormalCleanup());
1247 I = Scope.getEnclosingNormalCleanup();
1248
1249 // If this is the last cleanup we're propagating through, tell it
1250 // that there's a resolved jump moving through it.
1251 if (!E.strictlyEncloses(I)) {
1252 Scope.addBranchAfter(Index, Dest.getBlock());
1253 break;
John McCallda65ea82010-07-13 20:32:21 +00001254 }
John McCallff8e1152010-07-23 21:56:41 +00001255
1256 // Otherwise, tell the scope that there's a jump propoagating
1257 // through it. If this isn't new information, all the rest of
1258 // the work has been done before.
1259 if (!Scope.addBranchThrough(Dest.getBlock()))
1260 break;
John McCallf1549f62010-07-06 01:34:17 +00001261 }
1262 }
1263
Anders Carlsson46831a92009-02-08 22:13:37 +00001264 Builder.ClearInsertionPoint();
John McCallf1549f62010-07-06 01:34:17 +00001265}
Mike Stump1eb44332009-09-09 15:08:12 +00001266
John McCallff8e1152010-07-23 21:56:41 +00001267void CodeGenFunction::EmitBranchThroughEHCleanup(UnwindDest Dest) {
1268 // We should never get invalid scope depths for an UnwindDest; that
1269 // implies that the destination wasn't set up correctly.
1270 assert(Dest.getScopeDepth().isValid() && "invalid scope depth on EH dest?");
1271
John McCallf1549f62010-07-06 01:34:17 +00001272 if (!HaveInsertPoint())
Anders Carlsson87eaf172009-02-08 00:50:42 +00001273 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001274
John McCallf1549f62010-07-06 01:34:17 +00001275 // Create the branch.
John McCallff8e1152010-07-23 21:56:41 +00001276 llvm::BranchInst *BI = Builder.CreateBr(Dest.getBlock());
John McCallf1549f62010-07-06 01:34:17 +00001277
John McCall838d7962010-08-14 07:46:19 +00001278 // Calculate the innermost active cleanup.
1279 EHScopeStack::stable_iterator
1280 InnermostCleanup = EHStack.getInnermostActiveEHCleanup();
1281
John McCallff8e1152010-07-23 21:56:41 +00001282 // If the destination is in the same EH cleanup scope as us, we
1283 // don't need to thread through anything.
John McCall838d7962010-08-14 07:46:19 +00001284 if (InnermostCleanup.encloses(Dest.getScopeDepth())) {
John McCallf1549f62010-07-06 01:34:17 +00001285 Builder.ClearInsertionPoint();
Anders Carlsson87eaf172009-02-08 00:50:42 +00001286 return;
1287 }
John McCall838d7962010-08-14 07:46:19 +00001288 assert(InnermostCleanup != EHStack.stable_end());
Mike Stump1eb44332009-09-09 15:08:12 +00001289
John McCallff8e1152010-07-23 21:56:41 +00001290 // Store the index at the start.
1291 llvm::ConstantInt *Index = Builder.getInt32(Dest.getDestIndex());
1292 new llvm::StoreInst(Index, getEHCleanupDestSlot(), BI);
John McCallf1549f62010-07-06 01:34:17 +00001293
John McCallff8e1152010-07-23 21:56:41 +00001294 // Adjust BI to point to the first cleanup block.
1295 {
1296 EHCleanupScope &Scope =
John McCall838d7962010-08-14 07:46:19 +00001297 cast<EHCleanupScope>(*EHStack.find(InnermostCleanup));
John McCallff8e1152010-07-23 21:56:41 +00001298 BI->setSuccessor(0, CreateEHEntry(*this, Scope));
1299 }
1300
1301 // Add this destination to all the scopes involved.
1302 for (EHScopeStack::stable_iterator
John McCall838d7962010-08-14 07:46:19 +00001303 I = InnermostCleanup, E = Dest.getScopeDepth(); ; ) {
John McCallff8e1152010-07-23 21:56:41 +00001304 assert(E.strictlyEncloses(I));
1305 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(I));
1306 assert(Scope.isEHCleanup());
1307 I = Scope.getEnclosingEHCleanup();
John McCallf1549f62010-07-06 01:34:17 +00001308
John McCallff8e1152010-07-23 21:56:41 +00001309 // If this is the last cleanup we're propagating through, add this
1310 // as a branch-after.
1311 if (I == E) {
1312 Scope.addEHBranchAfter(Index, Dest.getBlock());
1313 break;
John McCallf1549f62010-07-06 01:34:17 +00001314 }
John McCallff8e1152010-07-23 21:56:41 +00001315
1316 // Otherwise, add it as a branch-through. If this isn't new
1317 // information, all the rest of the work has been done before.
1318 if (!Scope.addEHBranchThrough(Dest.getBlock()))
1319 break;
Anders Carlsson87eaf172009-02-08 00:50:42 +00001320 }
John McCallf1549f62010-07-06 01:34:17 +00001321
1322 Builder.ClearInsertionPoint();
Anders Carlsson87eaf172009-02-08 00:50:42 +00001323}
John McCallff8e1152010-07-23 21:56:41 +00001324
1325/// All the branch fixups on the EH stack have propagated out past the
1326/// outermost normal cleanup; resolve them all by adding cases to the
1327/// given switch instruction.
1328void CodeGenFunction::ResolveAllBranchFixups(llvm::SwitchInst *Switch) {
1329 llvm::SmallPtrSet<llvm::BasicBlock*, 4> CasesAdded;
1330
1331 for (unsigned I = 0, E = EHStack.getNumBranchFixups(); I != E; ++I) {
1332 // Skip this fixup if its destination isn't set or if we've
1333 // already treated it.
1334 BranchFixup &Fixup = EHStack.getBranchFixup(I);
1335 if (Fixup.Destination == 0) continue;
1336 if (!CasesAdded.insert(Fixup.Destination)) continue;
1337
1338 Switch->addCase(Builder.getInt32(Fixup.DestinationIndex),
1339 Fixup.Destination);
1340 }
1341
1342 EHStack.clearFixups();
1343}
1344
1345void CodeGenFunction::ResolveBranchFixups(llvm::BasicBlock *Block) {
1346 assert(Block && "resolving a null target block");
1347 if (!EHStack.getNumBranchFixups()) return;
1348
1349 assert(EHStack.hasNormalCleanups() &&
1350 "branch fixups exist with no normal cleanups on stack");
1351
1352 llvm::SmallPtrSet<llvm::BasicBlock*, 4> ModifiedOptimisticBlocks;
1353 bool ResolvedAny = false;
1354
1355 for (unsigned I = 0, E = EHStack.getNumBranchFixups(); I != E; ++I) {
1356 // Skip this fixup if its destination doesn't match.
1357 BranchFixup &Fixup = EHStack.getBranchFixup(I);
1358 if (Fixup.Destination != Block) continue;
1359
1360 Fixup.Destination = 0;
1361 ResolvedAny = true;
1362
1363 // If it doesn't have an optimistic branch block, LatestBranch is
1364 // already pointing to the right place.
1365 llvm::BasicBlock *BranchBB = Fixup.OptimisticBranchBlock;
1366 if (!BranchBB)
1367 continue;
1368
1369 // Don't process the same optimistic branch block twice.
1370 if (!ModifiedOptimisticBlocks.insert(BranchBB))
1371 continue;
1372
1373 llvm::SwitchInst *Switch = TransitionToCleanupSwitch(*this, BranchBB);
1374
1375 // Add a case to the switch.
1376 Switch->addCase(Builder.getInt32(Fixup.DestinationIndex), Block);
1377 }
1378
1379 if (ResolvedAny)
1380 EHStack.popNullFixups();
1381}
1382
John McCall7d8647f2010-09-14 07:57:04 +00001383static bool IsUsedAsNormalCleanup(EHScopeStack &EHStack,
1384 EHScopeStack::stable_iterator C) {
1385 // If we needed a normal block for any reason, that counts.
1386 if (cast<EHCleanupScope>(*EHStack.find(C)).getNormalBlock())
1387 return true;
1388
1389 // Check whether any enclosed cleanups were needed.
1390 for (EHScopeStack::stable_iterator
1391 I = EHStack.getInnermostNormalCleanup();
1392 I != C; ) {
1393 assert(C.strictlyEncloses(I));
1394 EHCleanupScope &S = cast<EHCleanupScope>(*EHStack.find(I));
1395 if (S.getNormalBlock()) return true;
1396 I = S.getEnclosingNormalCleanup();
1397 }
1398
1399 return false;
1400}
1401
1402static bool IsUsedAsEHCleanup(EHScopeStack &EHStack,
1403 EHScopeStack::stable_iterator C) {
1404 // If we needed an EH block for any reason, that counts.
1405 if (cast<EHCleanupScope>(*EHStack.find(C)).getEHBlock())
1406 return true;
1407
1408 // Check whether any enclosed cleanups were needed.
1409 for (EHScopeStack::stable_iterator
1410 I = EHStack.getInnermostEHCleanup(); I != C; ) {
1411 assert(C.strictlyEncloses(I));
1412 EHCleanupScope &S = cast<EHCleanupScope>(*EHStack.find(I));
1413 if (S.getEHBlock()) return true;
1414 I = S.getEnclosingEHCleanup();
1415 }
1416
1417 return false;
1418}
1419
1420enum ForActivation_t {
1421 ForActivation,
1422 ForDeactivation
1423};
1424
1425/// The given cleanup block is changing activation state. Configure a
1426/// cleanup variable if necessary.
1427///
1428/// It would be good if we had some way of determining if there were
1429/// extra uses *after* the change-over point.
1430static void SetupCleanupBlockActivation(CodeGenFunction &CGF,
1431 EHScopeStack::stable_iterator C,
1432 ForActivation_t Kind) {
1433 EHCleanupScope &Scope = cast<EHCleanupScope>(*CGF.EHStack.find(C));
1434 assert(!Scope.getActiveFlag() && "scope already has activation flag");
1435
1436 bool NeedFlag = false;
1437
1438 // Calculate whether the cleanup was used:
1439
1440 // - as a normal cleanup
1441 if (Scope.isNormalCleanup() && IsUsedAsNormalCleanup(CGF.EHStack, C)) {
1442 Scope.setTestFlagInNormalCleanup();
1443 NeedFlag = true;
1444 }
1445
1446 // - as an EH cleanup
1447 if (Scope.isEHCleanup() && IsUsedAsEHCleanup(CGF.EHStack, C)) {
1448 Scope.setTestFlagInEHCleanup();
1449 NeedFlag = true;
1450 }
1451
1452 // If it hasn't yet been used as either, we're done.
1453 if (!NeedFlag) return;
1454
1455 llvm::AllocaInst *Var = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty());
1456 Scope.setActiveFlag(Var);
1457
1458 if (Kind == ForActivation) {
1459 CGF.InitTempAlloca(Var, CGF.Builder.getFalse());
1460 CGF.Builder.CreateStore(CGF.Builder.getTrue(), Var);
1461 } else {
1462 CGF.InitTempAlloca(Var, CGF.Builder.getTrue());
1463 CGF.Builder.CreateStore(CGF.Builder.getFalse(), Var);
1464 }
1465}
1466
John McCallcd2d2b72010-08-13 21:20:51 +00001467/// Activate a cleanup that was created in an inactivated state.
John McCall7d8647f2010-09-14 07:57:04 +00001468void CodeGenFunction::ActivateCleanupBlock(EHScopeStack::stable_iterator C) {
John McCallcd2d2b72010-08-13 21:20:51 +00001469 assert(C != EHStack.stable_end() && "activating bottom of stack?");
1470 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(C));
1471 assert(!Scope.isActive() && "double activation");
1472
John McCall7d8647f2010-09-14 07:57:04 +00001473 SetupCleanupBlockActivation(*this, C, ForActivation);
John McCallcd2d2b72010-08-13 21:20:51 +00001474
John McCall7d8647f2010-09-14 07:57:04 +00001475 Scope.setActive(true);
1476}
John McCallcd2d2b72010-08-13 21:20:51 +00001477
John McCall7d8647f2010-09-14 07:57:04 +00001478/// Deactive a cleanup that was created in an active state.
1479void CodeGenFunction::DeactivateCleanupBlock(EHScopeStack::stable_iterator C) {
1480 assert(C != EHStack.stable_end() && "deactivating bottom of stack?");
1481 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(C));
1482 assert(Scope.isActive() && "double activation");
1483
1484 // If it's the top of the stack, just pop it.
1485 if (C == EHStack.stable_begin()) {
1486 // If it's a normal cleanup, we need to pretend that the
1487 // fallthrough is unreachable.
1488 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1489 PopCleanupBlock();
1490 Builder.restoreIP(SavedIP);
1491 return;
John McCallcd2d2b72010-08-13 21:20:51 +00001492 }
1493
John McCall7d8647f2010-09-14 07:57:04 +00001494 // Otherwise, follow the general case.
1495 SetupCleanupBlockActivation(*this, C, ForDeactivation);
John McCallcd2d2b72010-08-13 21:20:51 +00001496
John McCall7d8647f2010-09-14 07:57:04 +00001497 Scope.setActive(false);
John McCallcd2d2b72010-08-13 21:20:51 +00001498}
1499
John McCallff8e1152010-07-23 21:56:41 +00001500llvm::Value *CodeGenFunction::getNormalCleanupDestSlot() {
1501 if (!NormalCleanupDest)
1502 NormalCleanupDest =
1503 CreateTempAlloca(Builder.getInt32Ty(), "cleanup.dest.slot");
1504 return NormalCleanupDest;
1505}
1506
1507llvm::Value *CodeGenFunction::getEHCleanupDestSlot() {
1508 if (!EHCleanupDest)
1509 EHCleanupDest =
1510 CreateTempAlloca(Builder.getInt32Ty(), "eh.cleanup.dest.slot");
1511 return EHCleanupDest;
1512}
Devang Patel8d308382010-08-10 07:24:25 +00001513
1514void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
Devang Patel25c2c8f2010-08-10 17:53:33 +00001515 llvm::ConstantInt *Init) {
1516 assert (Init && "Invalid DeclRefExpr initializer!");
1517 if (CGDebugInfo *Dbg = getDebugInfo())
1518 Dbg->EmitGlobalVariable(E->getDecl(), Init, Builder);
Devang Patel8d308382010-08-10 07:24:25 +00001519}