blob: dbebd136ba04eda303aea5f8559839a738bf4a8a [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-function state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
15#include "CodeGenModule.h"
Eli Friedman3f2af102008-05-22 01:40:10 +000016#include "CGDebugInfo.h"
John McCallf1549f62010-07-06 01:34:17 +000017#include "CGException.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000018#include "clang/Basic/TargetInfo.h"
Chris Lattner31a09842008-11-12 08:04:58 +000019#include "clang/AST/APValue.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000020#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000021#include "clang/AST/Decl.h"
Anders Carlsson2b77ba82009-04-04 20:47:02 +000022#include "clang/AST/DeclCXX.h"
Mike Stump6a1e0eb2009-12-04 23:26:17 +000023#include "clang/AST/StmtCXX.h"
Chris Lattner7255a2d2010-06-22 00:03:40 +000024#include "clang/Frontend/CodeGenOptions.h"
Mike Stump4e7a1f72009-02-21 20:00:35 +000025#include "llvm/Target/TargetData.h"
Chris Lattner7255a2d2010-06-22 00:03:40 +000026#include "llvm/Intrinsics.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027using namespace clang;
28using namespace CodeGen;
29
Mike Stump1eb44332009-09-09 15:08:12 +000030CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
Mike Stumpa4f668f2009-03-06 01:33:24 +000031 : BlockFunction(cgm, *this, Builder), CGM(cgm),
32 Target(CGM.getContext().Target),
Owen Andersonaac87052009-07-08 20:52:20 +000033 Builder(cgm.getModule().getContext()),
John McCallf1549f62010-07-06 01:34:17 +000034 ExceptionSlot(0), DebugInfo(0), IndirectBranch(0),
Chris Lattner3d00fdc2009-10-13 06:55:33 +000035 SwitchInsn(0), CaseRangeBlock(0), InvokeDest(0),
John McCallf1549f62010-07-06 01:34:17 +000036 DidCallStackSave(false), UnreachableBlock(0),
John McCall25049412010-02-16 22:04:33 +000037 CXXThisDecl(0), CXXThisValue(0), CXXVTTDecl(0), CXXVTTValue(0),
John McCallf1549f62010-07-06 01:34:17 +000038 ConditionalBranchLevel(0), TerminateLandingPad(0), TerminateHandler(0),
Chris Lattner83252dc2010-07-20 21:07:09 +000039 TrapBB(0) {
Chris Lattner77b89b82010-06-27 07:15:29 +000040
41 // Get some frequently used types.
Mike Stump4e7a1f72009-02-21 20:00:35 +000042 LLVMPointerWidth = Target.getPointerWidth(0);
Chris Lattner77b89b82010-06-27 07:15:29 +000043 llvm::LLVMContext &LLVMContext = CGM.getLLVMContext();
44 IntPtrTy = llvm::IntegerType::get(LLVMContext, LLVMPointerWidth);
45 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
46 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
47
Mike Stumpd88ea562009-12-09 03:35:49 +000048 Exceptions = getContext().getLangOptions().Exceptions;
Mike Stump9c276ae2009-12-12 01:27:46 +000049 CatchUndefined = getContext().getLangOptions().CatchUndefined;
Douglas Gregor35415f52010-05-25 17:04:15 +000050 CGM.getMangleContext().startNewFunction();
Chris Lattner41110242008-06-17 18:05:57 +000051}
Reid Spencer5f016e22007-07-11 17:01:13 +000052
53ASTContext &CodeGenFunction::getContext() const {
54 return CGM.getContext();
55}
56
57
Daniel Dunbar0096acf2009-02-25 19:24:29 +000058llvm::Value *CodeGenFunction::GetAddrOfLocalVar(const VarDecl *VD) {
59 llvm::Value *Res = LocalDeclMap[VD];
60 assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!");
61 return Res;
Lauro Ramos Venancio81373352008-02-26 21:41:45 +000062}
Reid Spencer5f016e22007-07-11 17:01:13 +000063
Daniel Dunbar0096acf2009-02-25 19:24:29 +000064llvm::Constant *
65CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) {
66 return cast<llvm::Constant>(GetAddrOfLocalVar(BVD));
Anders Carlssondde0a942008-09-11 09:15:33 +000067}
68
Daniel Dunbar8b1a3432009-02-03 23:03:55 +000069const llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
70 return CGM.getTypes().ConvertTypeForMem(T);
71}
72
Reid Spencer5f016e22007-07-11 17:01:13 +000073const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
74 return CGM.getTypes().ConvertType(T);
75}
76
77bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
Anders Carlssone9d34dc2009-09-29 02:09:01 +000078 return T->isRecordType() || T->isArrayType() || T->isAnyComplexType() ||
79 T->isMemberFunctionPointerType();
Reid Spencer5f016e22007-07-11 17:01:13 +000080}
81
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000082void CodeGenFunction::EmitReturnBlock() {
83 // For cleanliness, we try to avoid emitting the return block for
84 // simple cases.
85 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
86
87 if (CurBB) {
88 assert(!CurBB->getTerminator() && "Unexpected terminated block.");
89
Daniel Dunbar96e18b02009-07-19 08:24:34 +000090 // We have a valid insert point, reuse it if it is empty or there are no
91 // explicit jumps to the return block.
John McCallf1549f62010-07-06 01:34:17 +000092 if (CurBB->empty() || ReturnBlock.Block->use_empty()) {
93 ReturnBlock.Block->replaceAllUsesWith(CurBB);
94 delete ReturnBlock.Block;
Daniel Dunbar96e18b02009-07-19 08:24:34 +000095 } else
John McCallf1549f62010-07-06 01:34:17 +000096 EmitBlock(ReturnBlock.Block);
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000097 return;
98 }
99
100 // Otherwise, if the return block is the target of a single direct
101 // branch then we can just put the code in that block instead. This
102 // cleans up functions which started with a unified return block.
John McCallf1549f62010-07-06 01:34:17 +0000103 if (ReturnBlock.Block->hasOneUse()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000104 llvm::BranchInst *BI =
John McCallf1549f62010-07-06 01:34:17 +0000105 dyn_cast<llvm::BranchInst>(*ReturnBlock.Block->use_begin());
106 if (BI && BI->isUnconditional() &&
107 BI->getSuccessor(0) == ReturnBlock.Block) {
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000108 // Reset insertion point and delete the branch.
109 Builder.SetInsertPoint(BI->getParent());
110 BI->eraseFromParent();
John McCallf1549f62010-07-06 01:34:17 +0000111 delete ReturnBlock.Block;
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000112 return;
113 }
114 }
115
Mike Stumpf5408fe2009-05-16 07:57:57 +0000116 // FIXME: We are at an unreachable point, there is no reason to emit the block
117 // unless it has uses. However, we still need a place to put the debug
118 // region.end for now.
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000119
John McCallf1549f62010-07-06 01:34:17 +0000120 EmitBlock(ReturnBlock.Block);
121}
122
123static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
124 if (!BB) return;
125 if (!BB->use_empty())
126 return CGF.CurFn->getBasicBlockList().push_back(BB);
127 delete BB;
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000128}
129
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000130void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
Chris Lattnerda138702007-07-16 21:28:45 +0000131 assert(BreakContinueStack.empty() &&
132 "mismatched push/pop in break/continue stack!");
Mike Stump1eb44332009-09-09 15:08:12 +0000133
134 // Emit function epilog (to return).
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000135 EmitReturnBlock();
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000136
Chris Lattner7255a2d2010-06-22 00:03:40 +0000137 EmitFunctionInstrumentation("__cyg_profile_func_exit");
138
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000139 // Emit debug descriptor for function end.
Anders Carlssone896d982009-02-13 08:11:52 +0000140 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000141 DI->setLocation(EndLoc);
Devang Patel5a6fbcf2010-07-22 22:29:16 +0000142 DI->EmitFunctionEnd(Builder);
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000143 }
144
Chris Lattner35b21b82010-06-27 01:06:27 +0000145 EmitFunctionEpilog(*CurFnInfo);
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000146 EmitEndEHSpec(CurCodeDecl);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000147
John McCallf1549f62010-07-06 01:34:17 +0000148 assert(EHStack.empty() &&
149 "did not remove all scopes from cleanup stack!");
150
Chris Lattnerd9becd12009-10-28 23:59:40 +0000151 // If someone did an indirect goto, emit the indirect goto block at the end of
152 // the function.
153 if (IndirectBranch) {
154 EmitBlock(IndirectBranch->getParent());
155 Builder.ClearInsertionPoint();
156 }
157
Chris Lattner5a2fa142007-12-02 06:32:24 +0000158 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
Chris Lattner481769b2009-03-31 22:17:44 +0000159 llvm::Instruction *Ptr = AllocaInsertPt;
Chris Lattner5a2fa142007-12-02 06:32:24 +0000160 AllocaInsertPt = 0;
Chris Lattner481769b2009-03-31 22:17:44 +0000161 Ptr->eraseFromParent();
Chris Lattnerd9becd12009-10-28 23:59:40 +0000162
163 // If someone took the address of a label but never did an indirect goto, we
164 // made a zero entry PHI node, which is illegal, zap it now.
165 if (IndirectBranch) {
166 llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
167 if (PN->getNumIncomingValues() == 0) {
168 PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
169 PN->eraseFromParent();
170 }
171 }
John McCallf1549f62010-07-06 01:34:17 +0000172
173 EmitIfUsed(*this, TerminateLandingPad);
174 EmitIfUsed(*this, TerminateHandler);
175 EmitIfUsed(*this, UnreachableBlock);
John McCall744016d2010-07-06 23:57:41 +0000176
177 if (CGM.getCodeGenOpts().EmitDeclMetadata)
178 EmitDeclMetadata();
Reid Spencer5f016e22007-07-11 17:01:13 +0000179}
180
Chris Lattner7255a2d2010-06-22 00:03:40 +0000181/// ShouldInstrumentFunction - Return true if the current function should be
182/// instrumented with __cyg_profile_func_* calls
183bool CodeGenFunction::ShouldInstrumentFunction() {
184 if (!CGM.getCodeGenOpts().InstrumentFunctions)
185 return false;
186 if (CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
187 return false;
188 return true;
189}
190
191/// EmitFunctionInstrumentation - Emit LLVM code to call the specified
192/// instrumentation function with the current function and the call site, if
193/// function instrumentation is enabled.
194void CodeGenFunction::EmitFunctionInstrumentation(const char *Fn) {
195 if (!ShouldInstrumentFunction())
196 return;
197
Chris Lattner8dab6572010-06-23 05:21:28 +0000198 const llvm::PointerType *PointerTy;
Chris Lattner7255a2d2010-06-22 00:03:40 +0000199 const llvm::FunctionType *FunctionTy;
200 std::vector<const llvm::Type*> ProfileFuncArgs;
201
Chris Lattner8dab6572010-06-23 05:21:28 +0000202 // void __cyg_profile_func_{enter,exit} (void *this_fn, void *call_site);
203 PointerTy = llvm::Type::getInt8PtrTy(VMContext);
204 ProfileFuncArgs.push_back(PointerTy);
205 ProfileFuncArgs.push_back(PointerTy);
Chris Lattner7255a2d2010-06-22 00:03:40 +0000206 FunctionTy = llvm::FunctionType::get(
207 llvm::Type::getVoidTy(VMContext),
208 ProfileFuncArgs, false);
209
210 llvm::Constant *F = CGM.CreateRuntimeFunction(FunctionTy, Fn);
211 llvm::CallInst *CallSite = Builder.CreateCall(
212 CGM.getIntrinsic(llvm::Intrinsic::returnaddress, 0, 0),
Chris Lattner77b89b82010-06-27 07:15:29 +0000213 llvm::ConstantInt::get(Int32Ty, 0),
Chris Lattner7255a2d2010-06-22 00:03:40 +0000214 "callsite");
215
Chris Lattner8dab6572010-06-23 05:21:28 +0000216 Builder.CreateCall2(F,
217 llvm::ConstantExpr::getBitCast(CurFn, PointerTy),
218 CallSite);
Chris Lattner7255a2d2010-06-22 00:03:40 +0000219}
220
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000221void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
Daniel Dunbar7c086512008-09-09 23:14:03 +0000222 llvm::Function *Fn,
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000223 const FunctionArgList &Args,
224 SourceLocation StartLoc) {
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000225 const Decl *D = GD.getDecl();
226
Anders Carlsson4cc1a472009-02-09 20:20:56 +0000227 DidCallStackSave = false;
Chris Lattnerb5437d22009-04-23 05:30:27 +0000228 CurCodeDecl = CurFuncDecl = D;
Daniel Dunbar7c086512008-09-09 23:14:03 +0000229 FnRetTy = RetTy;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000230 CurFn = Fn;
Chris Lattner41110242008-06-17 18:05:57 +0000231 assert(CurFn->isDeclaration() && "Function already has body?");
232
Jakob Stoklund Olesena3fe2842010-02-09 00:10:00 +0000233 // Pass inline keyword to optimizer if it appears explicitly on any
234 // declaration.
235 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
236 for (FunctionDecl::redecl_iterator RI = FD->redecls_begin(),
237 RE = FD->redecls_end(); RI != RE; ++RI)
238 if (RI->isInlineSpecified()) {
239 Fn->addFnAttr(llvm::Attribute::InlineHint);
240 break;
241 }
242
Daniel Dunbar55e87422008-11-11 02:29:29 +0000243 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000244
Chris Lattner41110242008-06-17 18:05:57 +0000245 // Create a marker to make it easy to insert allocas into the entryblock
246 // later. Don't create this with the builder, because we don't want it
247 // folded.
Chris Lattner77b89b82010-06-27 07:15:29 +0000248 llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
249 AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "", EntryBB);
Chris Lattnerf1466842009-03-22 00:24:14 +0000250 if (Builder.isNamePreserving())
251 AllocaInsertPt->setName("allocapt");
Mike Stump1eb44332009-09-09 15:08:12 +0000252
John McCallf1549f62010-07-06 01:34:17 +0000253 ReturnBlock = getJumpDestInCurrentScope("return");
Mike Stump1eb44332009-09-09 15:08:12 +0000254
Chris Lattner41110242008-06-17 18:05:57 +0000255 Builder.SetInsertPoint(EntryBB);
Mike Stump1eb44332009-09-09 15:08:12 +0000256
Douglas Gregorce056bc2010-02-21 22:15:06 +0000257 QualType FnType = getContext().getFunctionType(RetTy, 0, 0, false, 0,
258 false, false, 0, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +0000259 /*FIXME?*/
260 FunctionType::ExtInfo());
Mike Stump91cc8152009-10-23 01:52:13 +0000261
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000262 // Emit subprogram debug descriptor.
Anders Carlssone896d982009-02-13 08:11:52 +0000263 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000264 DI->setLocation(StartLoc);
Devang Patel9c6c3a02010-01-14 00:36:21 +0000265 DI->EmitFunctionStart(GD, FnType, CurFn, Builder);
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000266 }
267
Chris Lattner7255a2d2010-06-22 00:03:40 +0000268 EmitFunctionInstrumentation("__cyg_profile_func_enter");
269
Daniel Dunbar88b53962009-02-02 22:03:45 +0000270 // FIXME: Leaked.
John McCall04a67a62010-02-05 21:31:56 +0000271 // CC info is ignored, hopefully?
272 CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args,
Rafael Espindola264ba482010-03-30 20:24:48 +0000273 FunctionType::ExtInfo());
Eli Friedmanb17daf92009-12-04 02:43:40 +0000274
275 if (RetTy->isVoidType()) {
276 // Void type; nothing to return.
277 ReturnValue = 0;
278 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
279 hasAggregateLLVMType(CurFnInfo->getReturnType())) {
280 // Indirect aggregate return; emit returned value directly into sret slot.
Daniel Dunbar647a1ec2010-02-16 19:45:20 +0000281 // This reduces code size, and affects correctness in C++.
Eli Friedmanb17daf92009-12-04 02:43:40 +0000282 ReturnValue = CurFn->arg_begin();
283 } else {
Daniel Dunbar647a1ec2010-02-16 19:45:20 +0000284 ReturnValue = CreateIRTemp(RetTy, "retval");
Eli Friedmanb17daf92009-12-04 02:43:40 +0000285 }
286
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000287 EmitStartEHSpec(CurCodeDecl);
Daniel Dunbar88b53962009-02-02 22:03:45 +0000288 EmitFunctionProlog(*CurFnInfo, CurFn, Args);
Mike Stump1eb44332009-09-09 15:08:12 +0000289
John McCall25049412010-02-16 22:04:33 +0000290 if (CXXThisDecl)
291 CXXThisValue = Builder.CreateLoad(LocalDeclMap[CXXThisDecl], "this");
292 if (CXXVTTDecl)
293 CXXVTTValue = Builder.CreateLoad(LocalDeclMap[CXXVTTDecl], "vtt");
294
Anders Carlsson751358f2008-12-20 21:28:43 +0000295 // If any of the arguments have a variably modified type, make sure to
296 // emit the type size.
297 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
298 i != e; ++i) {
299 QualType Ty = i->second;
300
301 if (Ty->isVariablyModifiedType())
302 EmitVLASize(Ty);
303 }
Daniel Dunbar7c086512008-09-09 23:14:03 +0000304}
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000305
John McCall9fc6a772010-02-19 09:25:03 +0000306void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args) {
307 const FunctionDecl *FD = cast<FunctionDecl>(CurGD.getDecl());
Douglas Gregor06a9f362010-05-01 20:49:11 +0000308 assert(FD->getBody());
309 EmitStmt(FD->getBody());
John McCalla355e072010-02-18 03:17:58 +0000310}
311
Anders Carlssonc997d422010-01-02 01:01:18 +0000312void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn) {
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000313 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
314
Anders Carlssone896d982009-02-13 08:11:52 +0000315 // Check if we should generate debug info for this function.
Mike Stump1feade82009-08-26 22:31:08 +0000316 if (CGM.getDebugInfo() && !FD->hasAttr<NoDebugAttr>())
Anders Carlssone896d982009-02-13 08:11:52 +0000317 DebugInfo = CGM.getDebugInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000318
Daniel Dunbar7c086512008-09-09 23:14:03 +0000319 FunctionArgList Args;
Mike Stump1eb44332009-09-09 15:08:12 +0000320
Mike Stump6a1e0eb2009-12-04 23:26:17 +0000321 CurGD = GD;
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000322 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
323 if (MD->isInstance()) {
324 // Create the implicit 'this' decl.
325 // FIXME: I'm not entirely sure I like using a fake decl just for code
326 // generation. Maybe we can come up with a better way?
John McCall25049412010-02-16 22:04:33 +0000327 CXXThisDecl = ImplicitParamDecl::Create(getContext(), 0,
328 FD->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +0000329 &getContext().Idents.get("this"),
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000330 MD->getThisType(getContext()));
331 Args.push_back(std::make_pair(CXXThisDecl, CXXThisDecl->getType()));
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000332
333 // Check if we need a VTT parameter as well.
Anders Carlssonaf440352010-03-23 04:11:45 +0000334 if (CodeGenVTables::needsVTTParameter(GD)) {
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000335 // FIXME: The comment about using a fake decl above applies here too.
336 QualType T = getContext().getPointerType(getContext().VoidPtrTy);
337 CXXVTTDecl =
John McCall25049412010-02-16 22:04:33 +0000338 ImplicitParamDecl::Create(getContext(), 0, FD->getLocation(),
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000339 &getContext().Idents.get("vtt"), T);
340 Args.push_back(std::make_pair(CXXVTTDecl, CXXVTTDecl->getType()));
341 }
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000342 }
343 }
Mike Stump1eb44332009-09-09 15:08:12 +0000344
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000345 if (FD->getNumParams()) {
John McCall183700f2009-09-21 23:43:11 +0000346 const FunctionProtoType* FProto = FD->getType()->getAs<FunctionProtoType>();
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000347 assert(FProto && "Function def must have prototype!");
Daniel Dunbar7c086512008-09-09 23:14:03 +0000348
349 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
Mike Stump1eb44332009-09-09 15:08:12 +0000350 Args.push_back(std::make_pair(FD->getParamDecl(i),
Daniel Dunbar7c086512008-09-09 23:14:03 +0000351 FProto->getArgType(i)));
Chris Lattner41110242008-06-17 18:05:57 +0000352 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000353
John McCalla355e072010-02-18 03:17:58 +0000354 SourceRange BodyRange;
355 if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange();
Anders Carlsson4365bba2009-11-06 02:55:43 +0000356
John McCalla355e072010-02-18 03:17:58 +0000357 // Emit the standard function prologue.
358 StartFunction(GD, FD->getResultType(), Fn, Args, BodyRange.getBegin());
Anders Carlsson4365bba2009-11-06 02:55:43 +0000359
John McCalla355e072010-02-18 03:17:58 +0000360 // Generate the body of the function.
John McCall9fc6a772010-02-19 09:25:03 +0000361 if (isa<CXXDestructorDecl>(FD))
362 EmitDestructorBody(Args);
363 else if (isa<CXXConstructorDecl>(FD))
364 EmitConstructorBody(Args);
365 else
366 EmitFunctionBody(Args);
Anders Carlsson1851a122010-02-07 19:45:40 +0000367
John McCalla355e072010-02-18 03:17:58 +0000368 // Emit the standard function epilogue.
369 FinishFunction(BodyRange.getEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000370
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000371 // Destroy the 'this' declaration.
372 if (CXXThisDecl)
373 CXXThisDecl->Destroy(getContext());
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000374
375 // Destroy the VTT declaration.
376 if (CXXVTTDecl)
377 CXXVTTDecl->Destroy(getContext());
Chris Lattner41110242008-06-17 18:05:57 +0000378}
379
Chris Lattner0946ccd2008-11-11 07:41:27 +0000380/// ContainsLabel - Return true if the statement contains a label in it. If
381/// this statement is not executed normally, it not containing a label means
382/// that we can just remove the code.
383bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
384 // Null statement, not a label!
385 if (S == 0) return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000386
Chris Lattner0946ccd2008-11-11 07:41:27 +0000387 // If this is a label, we have to emit the code, consider something like:
388 // if (0) { ... foo: bar(); } goto foo;
389 if (isa<LabelStmt>(S))
390 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000391
Chris Lattner0946ccd2008-11-11 07:41:27 +0000392 // If this is a case/default statement, and we haven't seen a switch, we have
393 // to emit the code.
394 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
395 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000396
Chris Lattner0946ccd2008-11-11 07:41:27 +0000397 // If this is a switch statement, we want to ignore cases below it.
398 if (isa<SwitchStmt>(S))
399 IgnoreCaseStmts = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000400
Chris Lattner0946ccd2008-11-11 07:41:27 +0000401 // Scan subexpressions for verboten labels.
402 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
403 I != E; ++I)
404 if (ContainsLabel(*I, IgnoreCaseStmts))
405 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000406
Chris Lattner0946ccd2008-11-11 07:41:27 +0000407 return false;
408}
409
Chris Lattner31a09842008-11-12 08:04:58 +0000410
411/// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
412/// a constant, or if it does but contains a label, return 0. If it constant
413/// folds to 'true' and does not contain a label, return 1, if it constant folds
414/// to 'false' and does not contain a label, return -1.
415int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
Daniel Dunbar36bc14c2008-11-12 22:37:10 +0000416 // FIXME: Rename and handle conversion of other evaluatable things
417 // to bool.
Anders Carlsson64712f12008-12-01 02:46:24 +0000418 Expr::EvalResult Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000419 if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
Anders Carlsson64712f12008-12-01 02:46:24 +0000420 Result.HasSideEffects)
Anders Carlssonef5a66d2008-11-22 22:32:07 +0000421 return 0; // Not foldable, not integer or not fully evaluatable.
Mike Stump1eb44332009-09-09 15:08:12 +0000422
Chris Lattner31a09842008-11-12 08:04:58 +0000423 if (CodeGenFunction::ContainsLabel(Cond))
424 return 0; // Contains a label.
Mike Stump1eb44332009-09-09 15:08:12 +0000425
Anders Carlsson64712f12008-12-01 02:46:24 +0000426 return Result.Val.getInt().getBoolValue() ? 1 : -1;
Chris Lattner31a09842008-11-12 08:04:58 +0000427}
428
429
430/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
431/// statement) to the specified blocks. Based on the condition, this might try
432/// to simplify the codegen of the conditional based on the branch.
433///
434void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
435 llvm::BasicBlock *TrueBlock,
436 llvm::BasicBlock *FalseBlock) {
437 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
438 return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000439
Chris Lattner31a09842008-11-12 08:04:58 +0000440 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
441 // Handle X && Y in a condition.
442 if (CondBOp->getOpcode() == BinaryOperator::LAnd) {
443 // If we have "1 && X", simplify the code. "0 && X" would have constant
444 // folded if the case was simple enough.
445 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
446 // br(1 && X) -> br(X).
447 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
448 }
Mike Stump1eb44332009-09-09 15:08:12 +0000449
Chris Lattner31a09842008-11-12 08:04:58 +0000450 // If we have "X && 1", simplify the code to use an uncond branch.
451 // "X && 0" would have been constant folded to 0.
452 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
453 // br(X && 1) -> br(X).
454 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
455 }
Mike Stump1eb44332009-09-09 15:08:12 +0000456
Chris Lattner31a09842008-11-12 08:04:58 +0000457 // Emit the LHS as a conditional. If the LHS conditional is false, we
458 // want to jump to the FalseBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000459 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
Chris Lattner31a09842008-11-12 08:04:58 +0000460 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
461 EmitBlock(LHSTrue);
Mike Stump1eb44332009-09-09 15:08:12 +0000462
Anders Carlsson08e9e452010-01-24 00:20:05 +0000463 // Any temporaries created here are conditional.
Anders Carlsson72119a82010-02-04 17:18:07 +0000464 BeginConditionalBranch();
Chris Lattner31a09842008-11-12 08:04:58 +0000465 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
Anders Carlsson72119a82010-02-04 17:18:07 +0000466 EndConditionalBranch();
Anders Carlsson08e9e452010-01-24 00:20:05 +0000467
Chris Lattner31a09842008-11-12 08:04:58 +0000468 return;
469 } else if (CondBOp->getOpcode() == BinaryOperator::LOr) {
470 // If we have "0 || X", simplify the code. "1 || X" would have constant
471 // folded if the case was simple enough.
472 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
473 // br(0 || X) -> br(X).
474 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
475 }
Mike Stump1eb44332009-09-09 15:08:12 +0000476
Chris Lattner31a09842008-11-12 08:04:58 +0000477 // If we have "X || 0", simplify the code to use an uncond branch.
478 // "X || 1" would have been constant folded to 1.
479 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
480 // br(X || 0) -> br(X).
481 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
482 }
Mike Stump1eb44332009-09-09 15:08:12 +0000483
Chris Lattner31a09842008-11-12 08:04:58 +0000484 // Emit the LHS as a conditional. If the LHS conditional is true, we
485 // want to jump to the TrueBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000486 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
Chris Lattner31a09842008-11-12 08:04:58 +0000487 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
488 EmitBlock(LHSFalse);
Mike Stump1eb44332009-09-09 15:08:12 +0000489
Anders Carlsson08e9e452010-01-24 00:20:05 +0000490 // Any temporaries created here are conditional.
Anders Carlsson72119a82010-02-04 17:18:07 +0000491 BeginConditionalBranch();
Chris Lattner31a09842008-11-12 08:04:58 +0000492 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
Anders Carlsson72119a82010-02-04 17:18:07 +0000493 EndConditionalBranch();
Anders Carlsson08e9e452010-01-24 00:20:05 +0000494
Chris Lattner31a09842008-11-12 08:04:58 +0000495 return;
496 }
Chris Lattner552f4c42008-11-12 08:13:36 +0000497 }
Mike Stump1eb44332009-09-09 15:08:12 +0000498
Chris Lattner552f4c42008-11-12 08:13:36 +0000499 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
500 // br(!x, t, f) -> br(x, f, t)
501 if (CondUOp->getOpcode() == UnaryOperator::LNot)
502 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
Chris Lattner31a09842008-11-12 08:04:58 +0000503 }
Mike Stump1eb44332009-09-09 15:08:12 +0000504
Daniel Dunbar09b14892008-11-12 10:30:32 +0000505 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
506 // Handle ?: operator.
507
508 // Just ignore GNU ?: extension.
509 if (CondOp->getLHS()) {
510 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
511 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
512 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
513 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
514 EmitBlock(LHSBlock);
515 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
516 EmitBlock(RHSBlock);
517 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
518 return;
519 }
520 }
521
Chris Lattner31a09842008-11-12 08:04:58 +0000522 // Emit the code with the fully general case.
523 llvm::Value *CondV = EvaluateExprAsBool(Cond);
524 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
525}
526
Daniel Dunbar488e9932008-08-16 00:56:44 +0000527/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000528/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000529void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
530 bool OmitOnError) {
531 CGM.ErrorUnsupported(S, Type, OmitOnError);
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000532}
533
Anders Carlsson1884eb02010-05-22 17:35:42 +0000534void
535CodeGenFunction::EmitNullInitialization(llvm::Value *DestPtr, QualType Ty) {
536 // If the type contains a pointer to data member we can't memset it to zero.
537 // Instead, create a null constant and copy it to the destination.
538 if (CGM.getTypes().ContainsPointerToDataMember(Ty)) {
539 llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
540
541 llvm::GlobalVariable *NullVariable =
542 new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
543 /*isConstant=*/true,
544 llvm::GlobalVariable::PrivateLinkage,
545 NullConstant, llvm::Twine());
546 EmitAggregateCopy(DestPtr, NullVariable, Ty, /*isVolatile=*/false);
547 return;
548 }
549
550
Anders Carlsson0d7c5832010-05-03 01:20:20 +0000551 // Ignore empty classes in C++.
552 if (getContext().getLangOptions().CPlusPlus) {
553 if (const RecordType *RT = Ty->getAs<RecordType>()) {
554 if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
555 return;
556 }
557 }
558
Anders Carlsson1884eb02010-05-22 17:35:42 +0000559 // Otherwise, just memset the whole thing to zero. This is legal
560 // because in LLVM, all default initializers (other than the ones we just
561 // handled above) are guaranteed to have a bit pattern of all zeros.
Chris Lattner36afd382009-10-13 06:02:42 +0000562 const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext);
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000563 if (DestPtr->getType() != BP)
564 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
565
566 // Get size and alignment info for this aggregate.
567 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
568
Chris Lattner88207c92009-04-21 17:59:23 +0000569 // Don't bother emitting a zero-byte memset.
570 if (TypeInfo.first == 0)
571 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000572
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000573 // FIXME: Handle variable sized types.
Chris Lattner77b89b82010-06-27 07:15:29 +0000574 Builder.CreateCall5(CGM.getMemSetFn(BP, IntPtrTy), DestPtr,
Owen Anderson0032b272009-08-13 21:57:51 +0000575 llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext)),
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000576 // TypeInfo.first describes size in bits.
Chris Lattner77b89b82010-06-27 07:15:29 +0000577 llvm::ConstantInt::get(IntPtrTy, TypeInfo.first/8),
578 llvm::ConstantInt::get(Int32Ty, TypeInfo.second/8),
Mon P Wang3ecd7852010-04-04 03:10:52 +0000579 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext),
580 0));
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000581}
582
Chris Lattnerd9becd12009-10-28 23:59:40 +0000583llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelStmt *L) {
584 // Make sure that there is a block for the indirect goto.
585 if (IndirectBranch == 0)
586 GetIndirectGotoBlock();
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000587
John McCallf1549f62010-07-06 01:34:17 +0000588 llvm::BasicBlock *BB = getJumpDestForLabel(L).Block;
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000589
Chris Lattnerd9becd12009-10-28 23:59:40 +0000590 // Make sure the indirect branch includes all of the address-taken blocks.
591 IndirectBranch->addDestination(BB);
592 return llvm::BlockAddress::get(CurFn, BB);
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000593}
594
595llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
Chris Lattnerd9becd12009-10-28 23:59:40 +0000596 // If we already made the indirect branch for indirect goto, return its block.
597 if (IndirectBranch) return IndirectBranch->getParent();
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000598
Chris Lattnerd9becd12009-10-28 23:59:40 +0000599 CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto"));
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000600
Chris Lattnerd9becd12009-10-28 23:59:40 +0000601 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
Chris Lattner85e74ac2009-10-28 20:36:47 +0000602
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000603 // Create the PHI node that indirect gotos will add entries to.
Chris Lattnerd9becd12009-10-28 23:59:40 +0000604 llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, "indirect.goto.dest");
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000605
Chris Lattnerd9becd12009-10-28 23:59:40 +0000606 // Create the indirect branch instruction.
607 IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
608 return IndirectBranch->getParent();
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000609}
Anders Carlssonddf7cac2008-11-04 05:30:00 +0000610
Daniel Dunbard286f052009-07-19 06:58:07 +0000611llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) {
Eli Friedmanbbed6b92009-08-15 02:50:32 +0000612 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
Mike Stump1eb44332009-09-09 15:08:12 +0000613
Anders Carlssonf666b772008-12-20 20:27:15 +0000614 assert(SizeEntry && "Did not emit size for type");
615 return SizeEntry;
616}
Anders Carlssondcc90d82008-12-12 07:19:02 +0000617
Daniel Dunbard286f052009-07-19 06:58:07 +0000618llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) {
Anders Carlsson60d35412008-12-20 20:46:34 +0000619 assert(Ty->isVariablyModifiedType() &&
620 "Must pass variably modified type to EmitVLASizes!");
Mike Stump1eb44332009-09-09 15:08:12 +0000621
Daniel Dunbard286f052009-07-19 06:58:07 +0000622 EnsureInsertPoint();
Mike Stump1eb44332009-09-09 15:08:12 +0000623
Anders Carlsson60d35412008-12-20 20:46:34 +0000624 if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
Eli Friedmanbbed6b92009-08-15 02:50:32 +0000625 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
Mike Stump1eb44332009-09-09 15:08:12 +0000626
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000627 if (!SizeEntry) {
Anders Carlsson96f21472009-02-05 19:43:10 +0000628 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
Mike Stump1eb44332009-09-09 15:08:12 +0000629
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000630 // Get the element size;
631 QualType ElemTy = VAT->getElementType();
632 llvm::Value *ElemSize;
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000633 if (ElemTy->isVariableArrayType())
634 ElemSize = EmitVLASize(ElemTy);
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000635 else
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000636 ElemSize = llvm::ConstantInt::get(SizeTy,
Ken Dyck199c3d62010-01-11 17:06:35 +0000637 getContext().getTypeSizeInChars(ElemTy).getQuantity());
Mike Stump1eb44332009-09-09 15:08:12 +0000638
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000639 llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
Anders Carlsson96f21472009-02-05 19:43:10 +0000640 NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
Mike Stump1eb44332009-09-09 15:08:12 +0000641
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000642 SizeEntry = Builder.CreateMul(ElemSize, NumElements);
Anders Carlsson60d35412008-12-20 20:46:34 +0000643 }
Mike Stump1eb44332009-09-09 15:08:12 +0000644
Anders Carlsson60d35412008-12-20 20:46:34 +0000645 return SizeEntry;
Anders Carlssondcc90d82008-12-12 07:19:02 +0000646 }
Mike Stump1eb44332009-09-09 15:08:12 +0000647
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000648 if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
649 EmitVLASize(AT->getElementType());
650 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000651 }
652
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000653 const PointerType *PT = Ty->getAs<PointerType>();
654 assert(PT && "unknown VM type!");
655 EmitVLASize(PT->getPointeeType());
Anders Carlsson60d35412008-12-20 20:46:34 +0000656 return 0;
Anders Carlssondcc90d82008-12-12 07:19:02 +0000657}
Eli Friedman4fd0aa52009-01-20 17:46:04 +0000658
659llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
Chris Lattnerfbe02ff2010-06-27 07:40:06 +0000660 if (CGM.getContext().getBuiltinVaListType()->isArrayType())
Eli Friedman4fd0aa52009-01-20 17:46:04 +0000661 return EmitScalarExpr(E);
Eli Friedman4fd0aa52009-01-20 17:46:04 +0000662 return EmitLValue(E).getAddress();
663}
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000664
John McCallf1549f62010-07-06 01:34:17 +0000665/// Pops cleanup blocks until the given savepoint is reached.
666void CodeGenFunction::PopCleanupBlocks(EHScopeStack::stable_iterator Old) {
667 assert(Old.isValid());
668
669 EHScopeStack::iterator E = EHStack.find(Old);
670 while (EHStack.begin() != E)
671 PopCleanupBlock();
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000672}
Anders Carlssonc71c8452009-02-07 23:50:39 +0000673
John McCallf1549f62010-07-06 01:34:17 +0000674/// Creates a switch instruction to thread branches out of the given
675/// block (which is the exit block of a cleanup).
676static void CreateCleanupSwitch(CodeGenFunction &CGF,
677 llvm::BasicBlock *Block) {
678 if (Block->getTerminator()) {
679 assert(isa<llvm::SwitchInst>(Block->getTerminator()) &&
680 "cleanup block already has a terminator, but it isn't a switch");
Mike Stump99533832009-12-02 07:41:41 +0000681 return;
682 }
683
John McCallf1549f62010-07-06 01:34:17 +0000684 llvm::Value *DestCodePtr
685 = CGF.CreateTempAlloca(CGF.Builder.getInt32Ty(), "cleanup.dst");
686 CGBuilderTy Builder(Block);
687 llvm::Value *DestCode = Builder.CreateLoad(DestCodePtr, "tmp");
Devang Patelcd9199e2010-04-13 00:08:43 +0000688
John McCallf1549f62010-07-06 01:34:17 +0000689 // Create a switch instruction to determine where to jump next.
690 Builder.CreateSwitch(DestCode, CGF.getUnreachableBlock());
Anders Carlssond66a9f92009-02-08 03:55:35 +0000691}
692
John McCallf1549f62010-07-06 01:34:17 +0000693/// Attempts to reduce a cleanup's entry block to a fallthrough. This
694/// is basically llvm::MergeBlockIntoPredecessor, except
695/// simplified/optimized for the tighter constraints on cleanup
696/// blocks.
697static void SimplifyCleanupEntry(CodeGenFunction &CGF,
698 llvm::BasicBlock *Entry) {
699 llvm::BasicBlock *Pred = Entry->getSinglePredecessor();
700 if (!Pred) return;
Mike Stump1eb44332009-09-09 15:08:12 +0000701
John McCallf1549f62010-07-06 01:34:17 +0000702 llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Pred->getTerminator());
703 if (!Br || Br->isConditional()) return;
704 assert(Br->getSuccessor(0) == Entry);
705
706 // If we were previously inserting at the end of the cleanup entry
707 // block, we'll need to continue inserting at the end of the
708 // predecessor.
709 bool WasInsertBlock = CGF.Builder.GetInsertBlock() == Entry;
710 assert(!WasInsertBlock || CGF.Builder.GetInsertPoint() == Entry->end());
711
712 // Kill the branch.
713 Br->eraseFromParent();
714
715 // Merge the blocks.
716 Pred->getInstList().splice(Pred->end(), Entry->getInstList());
717
718 // Kill the entry block.
719 Entry->eraseFromParent();
720
721 if (WasInsertBlock)
722 CGF.Builder.SetInsertPoint(Pred);
Anders Carlsson87eaf172009-02-08 00:50:42 +0000723}
724
John McCallf1549f62010-07-06 01:34:17 +0000725/// Attempts to reduce an cleanup's exit switch to an unconditional
726/// branch.
727static void SimplifyCleanupExit(llvm::BasicBlock *Exit) {
728 llvm::TerminatorInst *Terminator = Exit->getTerminator();
729 assert(Terminator && "completed cleanup exit has no terminator");
730
731 llvm::SwitchInst *Switch = dyn_cast<llvm::SwitchInst>(Terminator);
732 if (!Switch) return;
733 if (Switch->getNumCases() != 2) return; // default + 1
734
735 llvm::LoadInst *Cond = cast<llvm::LoadInst>(Switch->getCondition());
736 llvm::AllocaInst *CondVar = cast<llvm::AllocaInst>(Cond->getPointerOperand());
737
738 // Replace the switch instruction with an unconditional branch.
739 llvm::BasicBlock *Dest = Switch->getSuccessor(1); // default is 0
740 Switch->eraseFromParent();
741 llvm::BranchInst::Create(Dest, Exit);
742
743 // Delete all uses of the condition variable.
744 Cond->eraseFromParent();
745 while (!CondVar->use_empty())
746 cast<llvm::StoreInst>(*CondVar->use_begin())->eraseFromParent();
747
748 // Delete the condition variable itself.
749 CondVar->eraseFromParent();
750}
751
752/// Threads a branch fixup through a cleanup block.
753static void ThreadFixupThroughCleanup(CodeGenFunction &CGF,
754 BranchFixup &Fixup,
755 llvm::BasicBlock *Entry,
756 llvm::BasicBlock *Exit) {
757 if (!Exit->getTerminator())
758 CreateCleanupSwitch(CGF, Exit);
759
760 // Find the switch and its destination index alloca.
761 llvm::SwitchInst *Switch = cast<llvm::SwitchInst>(Exit->getTerminator());
762 llvm::Value *DestCodePtr =
763 cast<llvm::LoadInst>(Switch->getCondition())->getPointerOperand();
764
765 // Compute the index of the new case we're adding to the switch.
766 unsigned Index = Switch->getNumCases();
767
768 const llvm::IntegerType *i32 = llvm::Type::getInt32Ty(CGF.getLLVMContext());
769 llvm::ConstantInt *IndexV = llvm::ConstantInt::get(i32, Index);
770
771 // Set the index in the origin block.
772 new llvm::StoreInst(IndexV, DestCodePtr, Fixup.Origin);
773
774 // Add a case to the switch.
775 Switch->addCase(IndexV, Fixup.Destination);
776
777 // Change the last branch to point to the cleanup entry block.
778 Fixup.LatestBranch->setSuccessor(Fixup.LatestBranchIndex, Entry);
779
780 // And finally, update the fixup.
781 Fixup.LatestBranch = Switch;
782 Fixup.LatestBranchIndex = Index;
783}
784
785/// Try to simplify both the entry and exit edges of a cleanup.
786static void SimplifyCleanupEdges(CodeGenFunction &CGF,
787 llvm::BasicBlock *Entry,
788 llvm::BasicBlock *Exit) {
789
790 // Given their current implementations, it's important to run these
791 // in this order: SimplifyCleanupEntry will delete Entry if it can
792 // be merged into its predecessor, which will then break
793 // SimplifyCleanupExit if (as is common) Entry == Exit.
794
795 SimplifyCleanupExit(Exit);
796 SimplifyCleanupEntry(CGF, Entry);
797}
798
John McCall1f0fca52010-07-21 07:22:38 +0000799static void EmitCleanup(CodeGenFunction &CGF,
800 EHScopeStack::Cleanup *Fn,
801 bool ForEH) {
John McCallda65ea82010-07-13 20:32:21 +0000802 if (ForEH) CGF.EHStack.pushTerminate();
803 Fn->Emit(CGF, ForEH);
804 if (ForEH) CGF.EHStack.popTerminate();
805 assert(CGF.HaveInsertPoint() && "cleanup ended with no insertion point?");
806}
807
John McCall1f0fca52010-07-21 07:22:38 +0000808static void SplitAndEmitCleanup(CodeGenFunction &CGF,
809 EHScopeStack::Cleanup *Fn,
810 bool ForEH,
811 llvm::BasicBlock *Entry) {
John McCallda65ea82010-07-13 20:32:21 +0000812 assert(Entry && "no entry block for cleanup");
813
814 // Remove the switch and load from the end of the entry block.
815 llvm::Instruction *Switch = &Entry->getInstList().back();
816 Entry->getInstList().remove(Switch);
817 assert(isa<llvm::SwitchInst>(Switch));
818 llvm::Instruction *Load = &Entry->getInstList().back();
819 Entry->getInstList().remove(Load);
820 assert(isa<llvm::LoadInst>(Load));
821
822 assert(Entry->getInstList().empty() &&
823 "lazy cleanup block not empty after removing load/switch pair?");
824
825 // Emit the actual cleanup at the end of the entry block.
826 CGF.Builder.SetInsertPoint(Entry);
John McCall1f0fca52010-07-21 07:22:38 +0000827 EmitCleanup(CGF, Fn, ForEH);
John McCallda65ea82010-07-13 20:32:21 +0000828
829 // Put the load and switch at the end of the exit block.
830 llvm::BasicBlock *Exit = CGF.Builder.GetInsertBlock();
831 Exit->getInstList().push_back(Load);
832 Exit->getInstList().push_back(Switch);
833
834 // Clean up the edges if possible.
835 SimplifyCleanupEdges(CGF, Entry, Exit);
836
837 CGF.Builder.ClearInsertionPoint();
838}
839
John McCall1f0fca52010-07-21 07:22:38 +0000840/// Pops a cleanup block. If the block includes a normal cleanup, the
841/// current insertion point is threaded through the cleanup, as are
842/// any branch fixups on the cleanup.
843void CodeGenFunction::PopCleanupBlock() {
844 assert(!EHStack.empty() && "cleanup stack is empty!");
845 assert(isa<EHCleanupScope>(*EHStack.begin()) && "top not a cleanup!");
846 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.begin());
847 assert(Scope.getFixupDepth() <= EHStack.getNumBranchFixups());
John McCallda65ea82010-07-13 20:32:21 +0000848
849 // Check whether we need an EH cleanup. This is only true if we've
850 // generated a lazy EH cleanup block.
851 llvm::BasicBlock *EHEntry = Scope.getEHBlock();
852 bool RequiresEHCleanup = (EHEntry != 0);
853
854 // Check the three conditions which might require a normal cleanup:
855
856 // - whether there are branch fix-ups through this cleanup
857 unsigned FixupDepth = Scope.getFixupDepth();
John McCall1f0fca52010-07-21 07:22:38 +0000858 bool HasFixups = EHStack.getNumBranchFixups() != FixupDepth;
John McCallda65ea82010-07-13 20:32:21 +0000859
860 // - whether control has already been threaded through this cleanup
861 llvm::BasicBlock *NormalEntry = Scope.getNormalBlock();
862 bool HasExistingBranches = (NormalEntry != 0);
863
864 // - whether there's a fallthrough
John McCall1f0fca52010-07-21 07:22:38 +0000865 llvm::BasicBlock *FallthroughSource = Builder.GetInsertBlock();
John McCallda65ea82010-07-13 20:32:21 +0000866 bool HasFallthrough = (FallthroughSource != 0);
867
868 bool RequiresNormalCleanup = false;
869 if (Scope.isNormalCleanup() &&
870 (HasFixups || HasExistingBranches || HasFallthrough)) {
871 RequiresNormalCleanup = true;
872 }
873
874 // If we don't need the cleanup at all, we're done.
875 if (!RequiresNormalCleanup && !RequiresEHCleanup) {
John McCall1f0fca52010-07-21 07:22:38 +0000876 EHStack.popCleanup();
877 assert(EHStack.getNumBranchFixups() == 0 ||
878 EHStack.hasNormalCleanups());
John McCallda65ea82010-07-13 20:32:21 +0000879 return;
880 }
881
882 // Copy the cleanup emission data out. Note that SmallVector
883 // guarantees maximal alignment for its buffer regardless of its
884 // type parameter.
885 llvm::SmallVector<char, 8*sizeof(void*)> CleanupBuffer;
886 CleanupBuffer.reserve(Scope.getCleanupSize());
887 memcpy(CleanupBuffer.data(),
888 Scope.getCleanupBuffer(), Scope.getCleanupSize());
889 CleanupBuffer.set_size(Scope.getCleanupSize());
John McCall1f0fca52010-07-21 07:22:38 +0000890 EHScopeStack::Cleanup *Fn =
891 reinterpret_cast<EHScopeStack::Cleanup*>(CleanupBuffer.data());
John McCallda65ea82010-07-13 20:32:21 +0000892
893 // We're done with the scope; pop it off so we can emit the cleanups.
John McCall1f0fca52010-07-21 07:22:38 +0000894 EHStack.popCleanup();
John McCallda65ea82010-07-13 20:32:21 +0000895
896 if (RequiresNormalCleanup) {
897 // If we have a fallthrough and no other need for the cleanup,
898 // emit it directly.
899 if (HasFallthrough && !HasFixups && !HasExistingBranches) {
John McCall1f0fca52010-07-21 07:22:38 +0000900 EmitCleanup(*this, Fn, /*ForEH*/ false);
John McCallda65ea82010-07-13 20:32:21 +0000901
902 // Otherwise, the best approach is to thread everything through
903 // the cleanup block and then try to clean up after ourselves.
904 } else {
905 // Force the entry block to exist.
906 if (!HasExistingBranches) {
John McCall1f0fca52010-07-21 07:22:38 +0000907 NormalEntry = createBasicBlock("cleanup");
908 CreateCleanupSwitch(*this, NormalEntry);
John McCallda65ea82010-07-13 20:32:21 +0000909 }
910
John McCall1f0fca52010-07-21 07:22:38 +0000911 EmitBlock(NormalEntry);
John McCallda65ea82010-07-13 20:32:21 +0000912
913 // Thread the fallthrough edge through the (momentarily trivial)
914 // cleanup.
915 llvm::BasicBlock *FallthroughDestination = 0;
916 if (HasFallthrough) {
917 assert(isa<llvm::BranchInst>(FallthroughSource->getTerminator()));
John McCall1f0fca52010-07-21 07:22:38 +0000918 FallthroughDestination = createBasicBlock("cleanup.cont");
John McCallda65ea82010-07-13 20:32:21 +0000919
920 BranchFixup Fix;
921 Fix.Destination = FallthroughDestination;
922 Fix.LatestBranch = FallthroughSource->getTerminator();
923 Fix.LatestBranchIndex = 0;
924 Fix.Origin = Fix.LatestBranch;
925
926 // Restore fixup invariant. EmitBlock added a branch to the
927 // cleanup which we need to redirect to the destination.
928 cast<llvm::BranchInst>(Fix.LatestBranch)
929 ->setSuccessor(0, Fix.Destination);
930
John McCall1f0fca52010-07-21 07:22:38 +0000931 ThreadFixupThroughCleanup(*this, Fix, NormalEntry, NormalEntry);
John McCallda65ea82010-07-13 20:32:21 +0000932 }
933
934 // Thread any "real" fixups we need to thread.
John McCall1f0fca52010-07-21 07:22:38 +0000935 for (unsigned I = FixupDepth, E = EHStack.getNumBranchFixups();
John McCallda65ea82010-07-13 20:32:21 +0000936 I != E; ++I)
937 if (CGF.EHStack.getBranchFixup(I).Destination)
John McCall1f0fca52010-07-21 07:22:38 +0000938 ThreadFixupThroughCleanup(*this, EHStack.getBranchFixup(I),
John McCallda65ea82010-07-13 20:32:21 +0000939 NormalEntry, NormalEntry);
940
John McCall1f0fca52010-07-21 07:22:38 +0000941 SplitAndEmitCleanup(*this, Fn, /*ForEH*/ false, NormalEntry);
John McCallda65ea82010-07-13 20:32:21 +0000942
943 if (HasFallthrough)
John McCall1f0fca52010-07-21 07:22:38 +0000944 EmitBlock(FallthroughDestination);
John McCallda65ea82010-07-13 20:32:21 +0000945 }
946 }
947
948 // Emit the EH cleanup if required.
949 if (RequiresEHCleanup) {
John McCall1f0fca52010-07-21 07:22:38 +0000950 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
951 EmitBlock(EHEntry);
952 SplitAndEmitCleanup(*this, Fn, /*ForEH*/ true, EHEntry);
953 Builder.restoreIP(SavedIP);
John McCallda65ea82010-07-13 20:32:21 +0000954 }
955}
956
John McCallf1549f62010-07-06 01:34:17 +0000957void CodeGenFunction::EmitBranchThroughCleanup(JumpDest Dest) {
Anders Carlsson46831a92009-02-08 22:13:37 +0000958 if (!HaveInsertPoint())
959 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000960
John McCallf1549f62010-07-06 01:34:17 +0000961 // Create the branch.
962 llvm::BranchInst *BI = Builder.CreateBr(Dest.Block);
Mike Stump1eb44332009-09-09 15:08:12 +0000963
John McCallf1549f62010-07-06 01:34:17 +0000964 // If we're not in a cleanup scope, we don't need to worry about
965 // fixups.
966 if (!EHStack.hasNormalCleanups()) {
967 Builder.ClearInsertionPoint();
968 return;
969 }
970
971 // Initialize a fixup.
972 BranchFixup Fixup;
973 Fixup.Destination = Dest.Block;
974 Fixup.Origin = BI;
975 Fixup.LatestBranch = BI;
976 Fixup.LatestBranchIndex = 0;
977
978 // If we can't resolve the destination cleanup scope, just add this
979 // to the current cleanup scope.
980 if (!Dest.ScopeDepth.isValid()) {
981 EHStack.addBranchFixup() = Fixup;
982 Builder.ClearInsertionPoint();
983 return;
984 }
985
986 for (EHScopeStack::iterator I = EHStack.begin(),
987 E = EHStack.find(Dest.ScopeDepth); I != E; ++I) {
John McCall1f0fca52010-07-21 07:22:38 +0000988 if (isa<EHCleanupScope>(*I)) {
989 EHCleanupScope &Scope = cast<EHCleanupScope>(*I);
John McCallda65ea82010-07-13 20:32:21 +0000990 if (Scope.isNormalCleanup()) {
991 llvm::BasicBlock *Block = Scope.getNormalBlock();
992 if (!Block) {
993 Block = createBasicBlock("cleanup");
994 Scope.setNormalBlock(Block);
995 }
996 ThreadFixupThroughCleanup(*this, Fixup, Block, Block);
997 }
John McCallf1549f62010-07-06 01:34:17 +0000998 }
999 }
1000
Anders Carlsson46831a92009-02-08 22:13:37 +00001001 Builder.ClearInsertionPoint();
John McCallf1549f62010-07-06 01:34:17 +00001002}
Mike Stump1eb44332009-09-09 15:08:12 +00001003
John McCallf1549f62010-07-06 01:34:17 +00001004void CodeGenFunction::EmitBranchThroughEHCleanup(JumpDest Dest) {
1005 if (!HaveInsertPoint())
Anders Carlsson87eaf172009-02-08 00:50:42 +00001006 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001007
John McCallf1549f62010-07-06 01:34:17 +00001008 // Create the branch.
1009 llvm::BranchInst *BI = Builder.CreateBr(Dest.Block);
1010
1011 // If we're not in a cleanup scope, we don't need to worry about
1012 // fixups.
1013 if (!EHStack.hasEHCleanups()) {
1014 Builder.ClearInsertionPoint();
Anders Carlsson87eaf172009-02-08 00:50:42 +00001015 return;
1016 }
Mike Stump1eb44332009-09-09 15:08:12 +00001017
John McCallf1549f62010-07-06 01:34:17 +00001018 // Initialize a fixup.
1019 BranchFixup Fixup;
1020 Fixup.Destination = Dest.Block;
1021 Fixup.Origin = BI;
1022 Fixup.LatestBranch = BI;
1023 Fixup.LatestBranchIndex = 0;
1024
1025 // We should never get invalid scope depths for these: invalid scope
1026 // depths only arise for as-yet-unemitted labels, and we can't do an
1027 // EH-unwind to one of those.
1028 assert(Dest.ScopeDepth.isValid() && "invalid scope depth on EH dest?");
1029
1030 for (EHScopeStack::iterator I = EHStack.begin(),
1031 E = EHStack.find(Dest.ScopeDepth); I != E; ++I) {
John McCall1f0fca52010-07-21 07:22:38 +00001032 if (isa<EHCleanupScope>(*I)) {
1033 EHCleanupScope &Scope = cast<EHCleanupScope>(*I);
John McCallda65ea82010-07-13 20:32:21 +00001034 if (Scope.isEHCleanup()) {
1035 llvm::BasicBlock *Block = Scope.getEHBlock();
1036 if (!Block) {
1037 Block = createBasicBlock("eh.cleanup");
1038 Scope.setEHBlock(Block);
1039 }
1040 ThreadFixupThroughCleanup(*this, Fixup, Block, Block);
1041 }
John McCallf1549f62010-07-06 01:34:17 +00001042 }
Anders Carlsson87eaf172009-02-08 00:50:42 +00001043 }
John McCallf1549f62010-07-06 01:34:17 +00001044
1045 Builder.ClearInsertionPoint();
Anders Carlsson87eaf172009-02-08 00:50:42 +00001046}