blob: 704de3531c81a764d71483da46803e5d56776316 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-function state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
15#include "CodeGenModule.h"
Eli Friedman3f2af102008-05-22 01:40:10 +000016#include "CGDebugInfo.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000017#include "clang/Basic/TargetInfo.h"
Chris Lattner31a09842008-11-12 08:04:58 +000018#include "clang/AST/APValue.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000019#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000020#include "clang/AST/Decl.h"
Anders Carlsson2b77ba82009-04-04 20:47:02 +000021#include "clang/AST/DeclCXX.h"
Mike Stump6a1e0eb2009-12-04 23:26:17 +000022#include "clang/AST/StmtCXX.h"
Chris Lattner7255a2d2010-06-22 00:03:40 +000023#include "clang/Frontend/CodeGenOptions.h"
Mike Stump4e7a1f72009-02-21 20:00:35 +000024#include "llvm/Target/TargetData.h"
Chris Lattner7255a2d2010-06-22 00:03:40 +000025#include "llvm/Intrinsics.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000026using namespace clang;
27using namespace CodeGen;
28
Mike Stump1eb44332009-09-09 15:08:12 +000029CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
Mike Stumpa4f668f2009-03-06 01:33:24 +000030 : BlockFunction(cgm, *this, Builder), CGM(cgm),
31 Target(CGM.getContext().Target),
Owen Andersonaac87052009-07-08 20:52:20 +000032 Builder(cgm.getModule().getContext()),
Chris Lattnerd9becd12009-10-28 23:59:40 +000033 DebugInfo(0), IndirectBranch(0),
Chris Lattner3d00fdc2009-10-13 06:55:33 +000034 SwitchInsn(0), CaseRangeBlock(0), InvokeDest(0),
John McCall25049412010-02-16 22:04:33 +000035 CXXThisDecl(0), CXXThisValue(0), CXXVTTDecl(0), CXXVTTValue(0),
Anders Carlsson5687a5c2010-06-08 22:30:17 +000036 ConditionalBranchLevel(0), TerminateHandler(0), TrapBB(0) {
Mike Stump4e7a1f72009-02-21 20:00:35 +000037 LLVMIntTy = ConvertType(getContext().IntTy);
38 LLVMPointerWidth = Target.getPointerWidth(0);
Mike Stumpd88ea562009-12-09 03:35:49 +000039 Exceptions = getContext().getLangOptions().Exceptions;
Mike Stump9c276ae2009-12-12 01:27:46 +000040 CatchUndefined = getContext().getLangOptions().CatchUndefined;
Douglas Gregor35415f52010-05-25 17:04:15 +000041 CGM.getMangleContext().startNewFunction();
Chris Lattner41110242008-06-17 18:05:57 +000042}
Reid Spencer5f016e22007-07-11 17:01:13 +000043
44ASTContext &CodeGenFunction::getContext() const {
45 return CGM.getContext();
46}
47
48
49llvm::BasicBlock *CodeGenFunction::getBasicBlockForLabel(const LabelStmt *S) {
50 llvm::BasicBlock *&BB = LabelMap[S];
51 if (BB) return BB;
Mike Stump1eb44332009-09-09 15:08:12 +000052
Reid Spencer5f016e22007-07-11 17:01:13 +000053 // Create, but don't insert, the new block.
Daniel Dunbar55e87422008-11-11 02:29:29 +000054 return BB = createBasicBlock(S->getName());
Reid Spencer5f016e22007-07-11 17:01:13 +000055}
56
Daniel Dunbar0096acf2009-02-25 19:24:29 +000057llvm::Value *CodeGenFunction::GetAddrOfLocalVar(const VarDecl *VD) {
58 llvm::Value *Res = LocalDeclMap[VD];
59 assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!");
60 return Res;
Lauro Ramos Venancio81373352008-02-26 21:41:45 +000061}
Reid Spencer5f016e22007-07-11 17:01:13 +000062
Daniel Dunbar0096acf2009-02-25 19:24:29 +000063llvm::Constant *
64CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) {
65 return cast<llvm::Constant>(GetAddrOfLocalVar(BVD));
Anders Carlssondde0a942008-09-11 09:15:33 +000066}
67
Daniel Dunbar8b1a3432009-02-03 23:03:55 +000068const llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
69 return CGM.getTypes().ConvertTypeForMem(T);
70}
71
Reid Spencer5f016e22007-07-11 17:01:13 +000072const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
73 return CGM.getTypes().ConvertType(T);
74}
75
76bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
Anders Carlssone9d34dc2009-09-29 02:09:01 +000077 return T->isRecordType() || T->isArrayType() || T->isAnyComplexType() ||
78 T->isMemberFunctionPointerType();
Reid Spencer5f016e22007-07-11 17:01:13 +000079}
80
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000081void CodeGenFunction::EmitReturnBlock() {
82 // For cleanliness, we try to avoid emitting the return block for
83 // simple cases.
84 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
85
86 if (CurBB) {
87 assert(!CurBB->getTerminator() && "Unexpected terminated block.");
88
Daniel Dunbar96e18b02009-07-19 08:24:34 +000089 // We have a valid insert point, reuse it if it is empty or there are no
90 // explicit jumps to the return block.
91 if (CurBB->empty() || ReturnBlock->use_empty()) {
92 ReturnBlock->replaceAllUsesWith(CurBB);
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000093 delete ReturnBlock;
Daniel Dunbar96e18b02009-07-19 08:24:34 +000094 } else
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000095 EmitBlock(ReturnBlock);
96 return;
97 }
98
99 // Otherwise, if the return block is the target of a single direct
100 // branch then we can just put the code in that block instead. This
101 // cleans up functions which started with a unified return block.
102 if (ReturnBlock->hasOneUse()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000103 llvm::BranchInst *BI =
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000104 dyn_cast<llvm::BranchInst>(*ReturnBlock->use_begin());
105 if (BI && BI->isUnconditional() && BI->getSuccessor(0) == ReturnBlock) {
106 // Reset insertion point and delete the branch.
107 Builder.SetInsertPoint(BI->getParent());
108 BI->eraseFromParent();
109 delete ReturnBlock;
110 return;
111 }
112 }
113
Mike Stumpf5408fe2009-05-16 07:57:57 +0000114 // FIXME: We are at an unreachable point, there is no reason to emit the block
115 // unless it has uses. However, we still need a place to put the debug
116 // region.end for now.
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000117
118 EmitBlock(ReturnBlock);
119}
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!");
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000124 assert(BlockScopes.empty() &&
125 "did not remove all blocks from block scope map!");
126 assert(CleanupEntries.empty() &&
127 "mismatched push/pop in cleanup stack!");
Mike Stump1eb44332009-09-09 15:08:12 +0000128
129 // Emit function epilog (to return).
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000130 EmitReturnBlock();
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000131
Chris Lattner7255a2d2010-06-22 00:03:40 +0000132 EmitFunctionInstrumentation("__cyg_profile_func_exit");
133
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000134 // Emit debug descriptor for function end.
Anders Carlssone896d982009-02-13 08:11:52 +0000135 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000136 DI->setLocation(EndLoc);
137 DI->EmitRegionEnd(CurFn, Builder);
138 }
139
Daniel Dunbar88b53962009-02-02 22:03:45 +0000140 EmitFunctionEpilog(*CurFnInfo, ReturnValue);
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000141 EmitEndEHSpec(CurCodeDecl);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000142
Chris Lattnerd9becd12009-10-28 23:59:40 +0000143 // If someone did an indirect goto, emit the indirect goto block at the end of
144 // the function.
145 if (IndirectBranch) {
146 EmitBlock(IndirectBranch->getParent());
147 Builder.ClearInsertionPoint();
148 }
149
Chris Lattner5a2fa142007-12-02 06:32:24 +0000150 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
Chris Lattner481769b2009-03-31 22:17:44 +0000151 llvm::Instruction *Ptr = AllocaInsertPt;
Chris Lattner5a2fa142007-12-02 06:32:24 +0000152 AllocaInsertPt = 0;
Chris Lattner481769b2009-03-31 22:17:44 +0000153 Ptr->eraseFromParent();
Chris Lattnerd9becd12009-10-28 23:59:40 +0000154
155 // If someone took the address of a label but never did an indirect goto, we
156 // made a zero entry PHI node, which is illegal, zap it now.
157 if (IndirectBranch) {
158 llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
159 if (PN->getNumIncomingValues() == 0) {
160 PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
161 PN->eraseFromParent();
162 }
163 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000164}
165
Chris Lattner7255a2d2010-06-22 00:03:40 +0000166/// ShouldInstrumentFunction - Return true if the current function should be
167/// instrumented with __cyg_profile_func_* calls
168bool CodeGenFunction::ShouldInstrumentFunction() {
169 if (!CGM.getCodeGenOpts().InstrumentFunctions)
170 return false;
171 if (CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
172 return false;
173 return true;
174}
175
176/// EmitFunctionInstrumentation - Emit LLVM code to call the specified
177/// instrumentation function with the current function and the call site, if
178/// function instrumentation is enabled.
179void CodeGenFunction::EmitFunctionInstrumentation(const char *Fn) {
180 if (!ShouldInstrumentFunction())
181 return;
182
Chris Lattner8dab6572010-06-23 05:21:28 +0000183 const llvm::PointerType *PointerTy;
Chris Lattner7255a2d2010-06-22 00:03:40 +0000184 const llvm::FunctionType *FunctionTy;
185 std::vector<const llvm::Type*> ProfileFuncArgs;
186
Chris Lattner8dab6572010-06-23 05:21:28 +0000187 // void __cyg_profile_func_{enter,exit} (void *this_fn, void *call_site);
188 PointerTy = llvm::Type::getInt8PtrTy(VMContext);
189 ProfileFuncArgs.push_back(PointerTy);
190 ProfileFuncArgs.push_back(PointerTy);
Chris Lattner7255a2d2010-06-22 00:03:40 +0000191 FunctionTy = llvm::FunctionType::get(
192 llvm::Type::getVoidTy(VMContext),
193 ProfileFuncArgs, false);
194
195 llvm::Constant *F = CGM.CreateRuntimeFunction(FunctionTy, Fn);
196 llvm::CallInst *CallSite = Builder.CreateCall(
197 CGM.getIntrinsic(llvm::Intrinsic::returnaddress, 0, 0),
198 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0),
199 "callsite");
200
Chris Lattner8dab6572010-06-23 05:21:28 +0000201 Builder.CreateCall2(F,
202 llvm::ConstantExpr::getBitCast(CurFn, PointerTy),
203 CallSite);
Chris Lattner7255a2d2010-06-22 00:03:40 +0000204}
205
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000206void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
Daniel Dunbar7c086512008-09-09 23:14:03 +0000207 llvm::Function *Fn,
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000208 const FunctionArgList &Args,
209 SourceLocation StartLoc) {
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000210 const Decl *D = GD.getDecl();
211
Anders Carlsson4cc1a472009-02-09 20:20:56 +0000212 DidCallStackSave = false;
Chris Lattnerb5437d22009-04-23 05:30:27 +0000213 CurCodeDecl = CurFuncDecl = D;
Daniel Dunbar7c086512008-09-09 23:14:03 +0000214 FnRetTy = RetTy;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000215 CurFn = Fn;
Chris Lattner41110242008-06-17 18:05:57 +0000216 assert(CurFn->isDeclaration() && "Function already has body?");
217
Jakob Stoklund Olesena3fe2842010-02-09 00:10:00 +0000218 // Pass inline keyword to optimizer if it appears explicitly on any
219 // declaration.
220 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
221 for (FunctionDecl::redecl_iterator RI = FD->redecls_begin(),
222 RE = FD->redecls_end(); RI != RE; ++RI)
223 if (RI->isInlineSpecified()) {
224 Fn->addFnAttr(llvm::Attribute::InlineHint);
225 break;
226 }
227
Daniel Dunbar55e87422008-11-11 02:29:29 +0000228 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000229
Chris Lattner41110242008-06-17 18:05:57 +0000230 // Create a marker to make it easy to insert allocas into the entryblock
231 // later. Don't create this with the builder, because we don't want it
232 // folded.
Owen Anderson0032b272009-08-13 21:57:51 +0000233 llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::getInt32Ty(VMContext));
Mike Stumpbcdc0f02009-09-25 18:11:00 +0000234 AllocaInsertPt = new llvm::BitCastInst(Undef,
235 llvm::Type::getInt32Ty(VMContext), "",
Chris Lattner41110242008-06-17 18:05:57 +0000236 EntryBB);
Chris Lattnerf1466842009-03-22 00:24:14 +0000237 if (Builder.isNamePreserving())
238 AllocaInsertPt->setName("allocapt");
Mike Stump1eb44332009-09-09 15:08:12 +0000239
Daniel Dunbar55e87422008-11-11 02:29:29 +0000240 ReturnBlock = createBasicBlock("return");
Mike Stump1eb44332009-09-09 15:08:12 +0000241
Chris Lattner41110242008-06-17 18:05:57 +0000242 Builder.SetInsertPoint(EntryBB);
Mike Stump1eb44332009-09-09 15:08:12 +0000243
Douglas Gregorce056bc2010-02-21 22:15:06 +0000244 QualType FnType = getContext().getFunctionType(RetTy, 0, 0, false, 0,
245 false, false, 0, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +0000246 /*FIXME?*/
247 FunctionType::ExtInfo());
Mike Stump91cc8152009-10-23 01:52:13 +0000248
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000249 // Emit subprogram debug descriptor.
Anders Carlssone896d982009-02-13 08:11:52 +0000250 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000251 DI->setLocation(StartLoc);
Devang Patel9c6c3a02010-01-14 00:36:21 +0000252 DI->EmitFunctionStart(GD, FnType, CurFn, Builder);
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000253 }
254
Chris Lattner7255a2d2010-06-22 00:03:40 +0000255 EmitFunctionInstrumentation("__cyg_profile_func_enter");
256
Daniel Dunbar88b53962009-02-02 22:03:45 +0000257 // FIXME: Leaked.
John McCall04a67a62010-02-05 21:31:56 +0000258 // CC info is ignored, hopefully?
259 CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args,
Rafael Espindola264ba482010-03-30 20:24:48 +0000260 FunctionType::ExtInfo());
Eli Friedmanb17daf92009-12-04 02:43:40 +0000261
262 if (RetTy->isVoidType()) {
263 // Void type; nothing to return.
264 ReturnValue = 0;
265 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
266 hasAggregateLLVMType(CurFnInfo->getReturnType())) {
267 // Indirect aggregate return; emit returned value directly into sret slot.
Daniel Dunbar647a1ec2010-02-16 19:45:20 +0000268 // This reduces code size, and affects correctness in C++.
Eli Friedmanb17daf92009-12-04 02:43:40 +0000269 ReturnValue = CurFn->arg_begin();
270 } else {
Daniel Dunbar647a1ec2010-02-16 19:45:20 +0000271 ReturnValue = CreateIRTemp(RetTy, "retval");
Eli Friedmanb17daf92009-12-04 02:43:40 +0000272 }
273
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000274 EmitStartEHSpec(CurCodeDecl);
Daniel Dunbar88b53962009-02-02 22:03:45 +0000275 EmitFunctionProlog(*CurFnInfo, CurFn, Args);
Mike Stump1eb44332009-09-09 15:08:12 +0000276
John McCall25049412010-02-16 22:04:33 +0000277 if (CXXThisDecl)
278 CXXThisValue = Builder.CreateLoad(LocalDeclMap[CXXThisDecl], "this");
279 if (CXXVTTDecl)
280 CXXVTTValue = Builder.CreateLoad(LocalDeclMap[CXXVTTDecl], "vtt");
281
Anders Carlsson751358f2008-12-20 21:28:43 +0000282 // If any of the arguments have a variably modified type, make sure to
283 // emit the type size.
284 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
285 i != e; ++i) {
286 QualType Ty = i->second;
287
288 if (Ty->isVariablyModifiedType())
289 EmitVLASize(Ty);
290 }
Daniel Dunbar7c086512008-09-09 23:14:03 +0000291}
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000292
John McCall9fc6a772010-02-19 09:25:03 +0000293void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args) {
294 const FunctionDecl *FD = cast<FunctionDecl>(CurGD.getDecl());
Douglas Gregor06a9f362010-05-01 20:49:11 +0000295 assert(FD->getBody());
296 EmitStmt(FD->getBody());
John McCalla355e072010-02-18 03:17:58 +0000297}
298
Anders Carlssonc997d422010-01-02 01:01:18 +0000299void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn) {
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000300 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
301
Anders Carlssone896d982009-02-13 08:11:52 +0000302 // Check if we should generate debug info for this function.
Mike Stump1feade82009-08-26 22:31:08 +0000303 if (CGM.getDebugInfo() && !FD->hasAttr<NoDebugAttr>())
Anders Carlssone896d982009-02-13 08:11:52 +0000304 DebugInfo = CGM.getDebugInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000305
Daniel Dunbar7c086512008-09-09 23:14:03 +0000306 FunctionArgList Args;
Mike Stump1eb44332009-09-09 15:08:12 +0000307
Mike Stump6a1e0eb2009-12-04 23:26:17 +0000308 CurGD = GD;
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000309 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
310 if (MD->isInstance()) {
311 // Create the implicit 'this' decl.
312 // FIXME: I'm not entirely sure I like using a fake decl just for code
313 // generation. Maybe we can come up with a better way?
John McCall25049412010-02-16 22:04:33 +0000314 CXXThisDecl = ImplicitParamDecl::Create(getContext(), 0,
315 FD->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +0000316 &getContext().Idents.get("this"),
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000317 MD->getThisType(getContext()));
318 Args.push_back(std::make_pair(CXXThisDecl, CXXThisDecl->getType()));
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000319
320 // Check if we need a VTT parameter as well.
Anders Carlssonaf440352010-03-23 04:11:45 +0000321 if (CodeGenVTables::needsVTTParameter(GD)) {
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000322 // FIXME: The comment about using a fake decl above applies here too.
323 QualType T = getContext().getPointerType(getContext().VoidPtrTy);
324 CXXVTTDecl =
John McCall25049412010-02-16 22:04:33 +0000325 ImplicitParamDecl::Create(getContext(), 0, FD->getLocation(),
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000326 &getContext().Idents.get("vtt"), T);
327 Args.push_back(std::make_pair(CXXVTTDecl, CXXVTTDecl->getType()));
328 }
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000329 }
330 }
Mike Stump1eb44332009-09-09 15:08:12 +0000331
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000332 if (FD->getNumParams()) {
John McCall183700f2009-09-21 23:43:11 +0000333 const FunctionProtoType* FProto = FD->getType()->getAs<FunctionProtoType>();
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000334 assert(FProto && "Function def must have prototype!");
Daniel Dunbar7c086512008-09-09 23:14:03 +0000335
336 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
Mike Stump1eb44332009-09-09 15:08:12 +0000337 Args.push_back(std::make_pair(FD->getParamDecl(i),
Daniel Dunbar7c086512008-09-09 23:14:03 +0000338 FProto->getArgType(i)));
Chris Lattner41110242008-06-17 18:05:57 +0000339 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000340
John McCalla355e072010-02-18 03:17:58 +0000341 SourceRange BodyRange;
342 if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange();
Anders Carlsson4365bba2009-11-06 02:55:43 +0000343
John McCalla355e072010-02-18 03:17:58 +0000344 // Emit the standard function prologue.
345 StartFunction(GD, FD->getResultType(), Fn, Args, BodyRange.getBegin());
Anders Carlsson4365bba2009-11-06 02:55:43 +0000346
John McCalla355e072010-02-18 03:17:58 +0000347 // Generate the body of the function.
John McCall9fc6a772010-02-19 09:25:03 +0000348 if (isa<CXXDestructorDecl>(FD))
349 EmitDestructorBody(Args);
350 else if (isa<CXXConstructorDecl>(FD))
351 EmitConstructorBody(Args);
352 else
353 EmitFunctionBody(Args);
Anders Carlsson1851a122010-02-07 19:45:40 +0000354
John McCalla355e072010-02-18 03:17:58 +0000355 // Emit the standard function epilogue.
356 FinishFunction(BodyRange.getEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000357
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000358 // Destroy the 'this' declaration.
359 if (CXXThisDecl)
360 CXXThisDecl->Destroy(getContext());
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000361
362 // Destroy the VTT declaration.
363 if (CXXVTTDecl)
364 CXXVTTDecl->Destroy(getContext());
Chris Lattner41110242008-06-17 18:05:57 +0000365}
366
Chris Lattner0946ccd2008-11-11 07:41:27 +0000367/// ContainsLabel - Return true if the statement contains a label in it. If
368/// this statement is not executed normally, it not containing a label means
369/// that we can just remove the code.
370bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
371 // Null statement, not a label!
372 if (S == 0) return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000373
Chris Lattner0946ccd2008-11-11 07:41:27 +0000374 // If this is a label, we have to emit the code, consider something like:
375 // if (0) { ... foo: bar(); } goto foo;
376 if (isa<LabelStmt>(S))
377 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000378
Chris Lattner0946ccd2008-11-11 07:41:27 +0000379 // If this is a case/default statement, and we haven't seen a switch, we have
380 // to emit the code.
381 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
382 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000383
Chris Lattner0946ccd2008-11-11 07:41:27 +0000384 // If this is a switch statement, we want to ignore cases below it.
385 if (isa<SwitchStmt>(S))
386 IgnoreCaseStmts = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000387
Chris Lattner0946ccd2008-11-11 07:41:27 +0000388 // Scan subexpressions for verboten labels.
389 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
390 I != E; ++I)
391 if (ContainsLabel(*I, IgnoreCaseStmts))
392 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000393
Chris Lattner0946ccd2008-11-11 07:41:27 +0000394 return false;
395}
396
Chris Lattner31a09842008-11-12 08:04:58 +0000397
398/// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
399/// a constant, or if it does but contains a label, return 0. If it constant
400/// folds to 'true' and does not contain a label, return 1, if it constant folds
401/// to 'false' and does not contain a label, return -1.
402int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
Daniel Dunbar36bc14c2008-11-12 22:37:10 +0000403 // FIXME: Rename and handle conversion of other evaluatable things
404 // to bool.
Anders Carlsson64712f12008-12-01 02:46:24 +0000405 Expr::EvalResult Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000406 if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
Anders Carlsson64712f12008-12-01 02:46:24 +0000407 Result.HasSideEffects)
Anders Carlssonef5a66d2008-11-22 22:32:07 +0000408 return 0; // Not foldable, not integer or not fully evaluatable.
Mike Stump1eb44332009-09-09 15:08:12 +0000409
Chris Lattner31a09842008-11-12 08:04:58 +0000410 if (CodeGenFunction::ContainsLabel(Cond))
411 return 0; // Contains a label.
Mike Stump1eb44332009-09-09 15:08:12 +0000412
Anders Carlsson64712f12008-12-01 02:46:24 +0000413 return Result.Val.getInt().getBoolValue() ? 1 : -1;
Chris Lattner31a09842008-11-12 08:04:58 +0000414}
415
416
417/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
418/// statement) to the specified blocks. Based on the condition, this might try
419/// to simplify the codegen of the conditional based on the branch.
420///
421void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
422 llvm::BasicBlock *TrueBlock,
423 llvm::BasicBlock *FalseBlock) {
424 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
425 return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000426
Chris Lattner31a09842008-11-12 08:04:58 +0000427 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
428 // Handle X && Y in a condition.
429 if (CondBOp->getOpcode() == BinaryOperator::LAnd) {
430 // If we have "1 && X", simplify the code. "0 && X" would have constant
431 // folded if the case was simple enough.
432 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
433 // br(1 && X) -> br(X).
434 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
435 }
Mike Stump1eb44332009-09-09 15:08:12 +0000436
Chris Lattner31a09842008-11-12 08:04:58 +0000437 // If we have "X && 1", simplify the code to use an uncond branch.
438 // "X && 0" would have been constant folded to 0.
439 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
440 // br(X && 1) -> br(X).
441 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
442 }
Mike Stump1eb44332009-09-09 15:08:12 +0000443
Chris Lattner31a09842008-11-12 08:04:58 +0000444 // Emit the LHS as a conditional. If the LHS conditional is false, we
445 // want to jump to the FalseBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000446 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
Chris Lattner31a09842008-11-12 08:04:58 +0000447 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
448 EmitBlock(LHSTrue);
Mike Stump1eb44332009-09-09 15:08:12 +0000449
Anders Carlsson08e9e452010-01-24 00:20:05 +0000450 // Any temporaries created here are conditional.
Anders Carlsson72119a82010-02-04 17:18:07 +0000451 BeginConditionalBranch();
Chris Lattner31a09842008-11-12 08:04:58 +0000452 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
Anders Carlsson72119a82010-02-04 17:18:07 +0000453 EndConditionalBranch();
Anders Carlsson08e9e452010-01-24 00:20:05 +0000454
Chris Lattner31a09842008-11-12 08:04:58 +0000455 return;
456 } else if (CondBOp->getOpcode() == BinaryOperator::LOr) {
457 // If we have "0 || X", simplify the code. "1 || X" would have constant
458 // folded if the case was simple enough.
459 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
460 // br(0 || X) -> br(X).
461 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
462 }
Mike Stump1eb44332009-09-09 15:08:12 +0000463
Chris Lattner31a09842008-11-12 08:04:58 +0000464 // If we have "X || 0", simplify the code to use an uncond branch.
465 // "X || 1" would have been constant folded to 1.
466 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
467 // br(X || 0) -> br(X).
468 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
469 }
Mike Stump1eb44332009-09-09 15:08:12 +0000470
Chris Lattner31a09842008-11-12 08:04:58 +0000471 // Emit the LHS as a conditional. If the LHS conditional is true, we
472 // want to jump to the TrueBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000473 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
Chris Lattner31a09842008-11-12 08:04:58 +0000474 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
475 EmitBlock(LHSFalse);
Mike Stump1eb44332009-09-09 15:08:12 +0000476
Anders Carlsson08e9e452010-01-24 00:20:05 +0000477 // Any temporaries created here are conditional.
Anders Carlsson72119a82010-02-04 17:18:07 +0000478 BeginConditionalBranch();
Chris Lattner31a09842008-11-12 08:04:58 +0000479 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
Anders Carlsson72119a82010-02-04 17:18:07 +0000480 EndConditionalBranch();
Anders Carlsson08e9e452010-01-24 00:20:05 +0000481
Chris Lattner31a09842008-11-12 08:04:58 +0000482 return;
483 }
Chris Lattner552f4c42008-11-12 08:13:36 +0000484 }
Mike Stump1eb44332009-09-09 15:08:12 +0000485
Chris Lattner552f4c42008-11-12 08:13:36 +0000486 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
487 // br(!x, t, f) -> br(x, f, t)
488 if (CondUOp->getOpcode() == UnaryOperator::LNot)
489 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
Chris Lattner31a09842008-11-12 08:04:58 +0000490 }
Mike Stump1eb44332009-09-09 15:08:12 +0000491
Daniel Dunbar09b14892008-11-12 10:30:32 +0000492 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
493 // Handle ?: operator.
494
495 // Just ignore GNU ?: extension.
496 if (CondOp->getLHS()) {
497 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
498 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
499 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
500 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
501 EmitBlock(LHSBlock);
502 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
503 EmitBlock(RHSBlock);
504 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
505 return;
506 }
507 }
508
Chris Lattner31a09842008-11-12 08:04:58 +0000509 // Emit the code with the fully general case.
510 llvm::Value *CondV = EvaluateExprAsBool(Cond);
511 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
512}
513
Daniel Dunbar488e9932008-08-16 00:56:44 +0000514/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000515/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000516void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
517 bool OmitOnError) {
518 CGM.ErrorUnsupported(S, Type, OmitOnError);
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000519}
520
Anders Carlsson1884eb02010-05-22 17:35:42 +0000521void
522CodeGenFunction::EmitNullInitialization(llvm::Value *DestPtr, QualType Ty) {
523 // If the type contains a pointer to data member we can't memset it to zero.
524 // Instead, create a null constant and copy it to the destination.
525 if (CGM.getTypes().ContainsPointerToDataMember(Ty)) {
526 llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
527
528 llvm::GlobalVariable *NullVariable =
529 new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
530 /*isConstant=*/true,
531 llvm::GlobalVariable::PrivateLinkage,
532 NullConstant, llvm::Twine());
533 EmitAggregateCopy(DestPtr, NullVariable, Ty, /*isVolatile=*/false);
534 return;
535 }
536
537
Anders Carlsson0d7c5832010-05-03 01:20:20 +0000538 // Ignore empty classes in C++.
539 if (getContext().getLangOptions().CPlusPlus) {
540 if (const RecordType *RT = Ty->getAs<RecordType>()) {
541 if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
542 return;
543 }
544 }
545
Anders Carlsson1884eb02010-05-22 17:35:42 +0000546 // Otherwise, just memset the whole thing to zero. This is legal
547 // because in LLVM, all default initializers (other than the ones we just
548 // handled above) are guaranteed to have a bit pattern of all zeros.
Chris Lattner36afd382009-10-13 06:02:42 +0000549 const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext);
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000550 if (DestPtr->getType() != BP)
551 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
552
553 // Get size and alignment info for this aggregate.
554 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
555
Chris Lattner88207c92009-04-21 17:59:23 +0000556 // Don't bother emitting a zero-byte memset.
557 if (TypeInfo.first == 0)
558 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000559
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000560 // FIXME: Handle variable sized types.
Mike Stump1eb44332009-09-09 15:08:12 +0000561 const llvm::Type *IntPtr = llvm::IntegerType::get(VMContext,
Owen Anderson0032b272009-08-13 21:57:51 +0000562 LLVMPointerWidth);
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000563
Mon P Wang3ecd7852010-04-04 03:10:52 +0000564 Builder.CreateCall5(CGM.getMemSetFn(BP, IntPtr), DestPtr,
Owen Anderson0032b272009-08-13 21:57:51 +0000565 llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext)),
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000566 // TypeInfo.first describes size in bits.
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000567 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
Mike Stump1eb44332009-09-09 15:08:12 +0000568 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Mon P Wang3ecd7852010-04-04 03:10:52 +0000569 TypeInfo.second/8),
570 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext),
571 0));
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000572}
573
Chris Lattnerd9becd12009-10-28 23:59:40 +0000574llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelStmt *L) {
575 // Make sure that there is a block for the indirect goto.
576 if (IndirectBranch == 0)
577 GetIndirectGotoBlock();
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000578
Chris Lattnerd9becd12009-10-28 23:59:40 +0000579 llvm::BasicBlock *BB = getBasicBlockForLabel(L);
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000580
Chris Lattnerd9becd12009-10-28 23:59:40 +0000581 // Make sure the indirect branch includes all of the address-taken blocks.
582 IndirectBranch->addDestination(BB);
583 return llvm::BlockAddress::get(CurFn, BB);
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000584}
585
586llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
Chris Lattnerd9becd12009-10-28 23:59:40 +0000587 // If we already made the indirect branch for indirect goto, return its block.
588 if (IndirectBranch) return IndirectBranch->getParent();
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000589
Chris Lattnerd9becd12009-10-28 23:59:40 +0000590 CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto"));
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000591
Chris Lattnerd9becd12009-10-28 23:59:40 +0000592 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
Chris Lattner85e74ac2009-10-28 20:36:47 +0000593
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000594 // Create the PHI node that indirect gotos will add entries to.
Chris Lattnerd9becd12009-10-28 23:59:40 +0000595 llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, "indirect.goto.dest");
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000596
Chris Lattnerd9becd12009-10-28 23:59:40 +0000597 // Create the indirect branch instruction.
598 IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
599 return IndirectBranch->getParent();
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000600}
Anders Carlssonddf7cac2008-11-04 05:30:00 +0000601
Daniel Dunbard286f052009-07-19 06:58:07 +0000602llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) {
Eli Friedmanbbed6b92009-08-15 02:50:32 +0000603 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
Mike Stump1eb44332009-09-09 15:08:12 +0000604
Anders Carlssonf666b772008-12-20 20:27:15 +0000605 assert(SizeEntry && "Did not emit size for type");
606 return SizeEntry;
607}
Anders Carlssondcc90d82008-12-12 07:19:02 +0000608
Daniel Dunbard286f052009-07-19 06:58:07 +0000609llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) {
Anders Carlsson60d35412008-12-20 20:46:34 +0000610 assert(Ty->isVariablyModifiedType() &&
611 "Must pass variably modified type to EmitVLASizes!");
Mike Stump1eb44332009-09-09 15:08:12 +0000612
Daniel Dunbard286f052009-07-19 06:58:07 +0000613 EnsureInsertPoint();
Mike Stump1eb44332009-09-09 15:08:12 +0000614
Anders Carlsson60d35412008-12-20 20:46:34 +0000615 if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
Eli Friedmanbbed6b92009-08-15 02:50:32 +0000616 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
Mike Stump1eb44332009-09-09 15:08:12 +0000617
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000618 if (!SizeEntry) {
Anders Carlsson96f21472009-02-05 19:43:10 +0000619 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
Mike Stump1eb44332009-09-09 15:08:12 +0000620
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000621 // Get the element size;
622 QualType ElemTy = VAT->getElementType();
623 llvm::Value *ElemSize;
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000624 if (ElemTy->isVariableArrayType())
625 ElemSize = EmitVLASize(ElemTy);
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000626 else
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000627 ElemSize = llvm::ConstantInt::get(SizeTy,
Ken Dyck199c3d62010-01-11 17:06:35 +0000628 getContext().getTypeSizeInChars(ElemTy).getQuantity());
Mike Stump1eb44332009-09-09 15:08:12 +0000629
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000630 llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
Anders Carlsson96f21472009-02-05 19:43:10 +0000631 NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
Mike Stump1eb44332009-09-09 15:08:12 +0000632
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000633 SizeEntry = Builder.CreateMul(ElemSize, NumElements);
Anders Carlsson60d35412008-12-20 20:46:34 +0000634 }
Mike Stump1eb44332009-09-09 15:08:12 +0000635
Anders Carlsson60d35412008-12-20 20:46:34 +0000636 return SizeEntry;
Anders Carlssondcc90d82008-12-12 07:19:02 +0000637 }
Mike Stump1eb44332009-09-09 15:08:12 +0000638
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000639 if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
640 EmitVLASize(AT->getElementType());
641 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000642 }
643
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000644 const PointerType *PT = Ty->getAs<PointerType>();
645 assert(PT && "unknown VM type!");
646 EmitVLASize(PT->getPointeeType());
Anders Carlsson60d35412008-12-20 20:46:34 +0000647 return 0;
Anders Carlssondcc90d82008-12-12 07:19:02 +0000648}
Eli Friedman4fd0aa52009-01-20 17:46:04 +0000649
650llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
651 if (CGM.getContext().getBuiltinVaListType()->isArrayType()) {
652 return EmitScalarExpr(E);
653 }
654 return EmitLValue(E).getAddress();
655}
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000656
Fariborz Jahanian77996212009-11-04 17:57:40 +0000657void CodeGenFunction::PushCleanupBlock(llvm::BasicBlock *CleanupEntryBlock,
Mike Stump99533832009-12-02 07:41:41 +0000658 llvm::BasicBlock *CleanupExitBlock,
Mike Stumpd88ea562009-12-09 03:35:49 +0000659 llvm::BasicBlock *PreviousInvokeDest,
Mike Stump99533832009-12-02 07:41:41 +0000660 bool EHOnly) {
661 CleanupEntries.push_back(CleanupEntry(CleanupEntryBlock, CleanupExitBlock,
Mike Stumpd88ea562009-12-09 03:35:49 +0000662 PreviousInvokeDest, EHOnly));
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000663}
Anders Carlssonc71c8452009-02-07 23:50:39 +0000664
Mike Stump1eb44332009-09-09 15:08:12 +0000665void CodeGenFunction::EmitCleanupBlocks(size_t OldCleanupStackSize) {
666 assert(CleanupEntries.size() >= OldCleanupStackSize &&
Anders Carlssonc71c8452009-02-07 23:50:39 +0000667 "Cleanup stack mismatch!");
Mike Stump1eb44332009-09-09 15:08:12 +0000668
Anders Carlssonc71c8452009-02-07 23:50:39 +0000669 while (CleanupEntries.size() > OldCleanupStackSize)
670 EmitCleanupBlock();
671}
672
Mike Stump1eb44332009-09-09 15:08:12 +0000673CodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock() {
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000674 CleanupEntry &CE = CleanupEntries.back();
Mike Stump1eb44332009-09-09 15:08:12 +0000675
Fariborz Jahanian77996212009-11-04 17:57:40 +0000676 llvm::BasicBlock *CleanupEntryBlock = CE.CleanupEntryBlock;
Mike Stump1eb44332009-09-09 15:08:12 +0000677
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000678 std::vector<llvm::BasicBlock *> Blocks;
679 std::swap(Blocks, CE.Blocks);
Mike Stump1eb44332009-09-09 15:08:12 +0000680
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000681 std::vector<llvm::BranchInst *> BranchFixups;
682 std::swap(BranchFixups, CE.BranchFixups);
Mike Stump1eb44332009-09-09 15:08:12 +0000683
Mike Stump99533832009-12-02 07:41:41 +0000684 bool EHOnly = CE.EHOnly;
685
Mike Stumpd88ea562009-12-09 03:35:49 +0000686 setInvokeDest(CE.PreviousInvokeDest);
687
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000688 CleanupEntries.pop_back();
689
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000690 // Check if any branch fixups pointed to the scope we just popped. If so,
691 // we can remove them.
692 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
693 llvm::BasicBlock *Dest = BranchFixups[i]->getSuccessor(0);
694 BlockScopeMap::iterator I = BlockScopes.find(Dest);
Mike Stump1eb44332009-09-09 15:08:12 +0000695
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000696 if (I == BlockScopes.end())
697 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000698
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000699 assert(I->second <= CleanupEntries.size() && "Invalid branch fixup!");
Mike Stump1eb44332009-09-09 15:08:12 +0000700
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000701 if (I->second == CleanupEntries.size()) {
702 // We don't need to do this branch fixup.
703 BranchFixups[i] = BranchFixups.back();
704 BranchFixups.pop_back();
705 i--;
706 e--;
707 continue;
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000708 }
709 }
Mike Stump1eb44332009-09-09 15:08:12 +0000710
Fariborz Jahanian77996212009-11-04 17:57:40 +0000711 llvm::BasicBlock *SwitchBlock = CE.CleanupExitBlock;
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000712 llvm::BasicBlock *EndBlock = 0;
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000713 if (!BranchFixups.empty()) {
Fariborz Jahanian77996212009-11-04 17:57:40 +0000714 if (!SwitchBlock)
715 SwitchBlock = createBasicBlock("cleanup.switch");
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000716 EndBlock = createBasicBlock("cleanup.end");
Mike Stump1eb44332009-09-09 15:08:12 +0000717
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000718 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
Mike Stump1eb44332009-09-09 15:08:12 +0000719
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000720 Builder.SetInsertPoint(SwitchBlock);
721
Mike Stump99533832009-12-02 07:41:41 +0000722 llvm::Value *DestCodePtr
723 = CreateTempAlloca(llvm::Type::getInt32Ty(VMContext),
724 "cleanup.dst");
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000725 llvm::Value *DestCode = Builder.CreateLoad(DestCodePtr, "tmp");
Mike Stump1eb44332009-09-09 15:08:12 +0000726
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000727 // Create a switch instruction to determine where to jump next.
Mike Stump1eb44332009-09-09 15:08:12 +0000728 llvm::SwitchInst *SI = Builder.CreateSwitch(DestCode, EndBlock,
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000729 BranchFixups.size());
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000730
Anders Carlsson46831a92009-02-08 22:13:37 +0000731 // Restore the current basic block (if any)
Anders Carlsson0ae7b2b2009-03-17 05:53:35 +0000732 if (CurBB) {
Anders Carlsson46831a92009-02-08 22:13:37 +0000733 Builder.SetInsertPoint(CurBB);
Mike Stump1eb44332009-09-09 15:08:12 +0000734
Anders Carlsson0ae7b2b2009-03-17 05:53:35 +0000735 // If we had a current basic block, we also need to emit an instruction
736 // to initialize the cleanup destination.
Owen Anderson0032b272009-08-13 21:57:51 +0000737 Builder.CreateStore(llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)),
Anders Carlsson0ae7b2b2009-03-17 05:53:35 +0000738 DestCodePtr);
739 } else
Anders Carlsson46831a92009-02-08 22:13:37 +0000740 Builder.ClearInsertionPoint();
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000741
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000742 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
743 llvm::BranchInst *BI = BranchFixups[i];
744 llvm::BasicBlock *Dest = BI->getSuccessor(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000745
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000746 // Fixup the branch instruction to point to the cleanup block.
Fariborz Jahanian77996212009-11-04 17:57:40 +0000747 BI->setSuccessor(0, CleanupEntryBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000748
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000749 if (CleanupEntries.empty()) {
Anders Carlssoncc899202009-02-08 22:46:50 +0000750 llvm::ConstantInt *ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000751
Anders Carlssoncc899202009-02-08 22:46:50 +0000752 // Check if we already have a destination for this block.
753 if (Dest == SI->getDefaultDest())
Owen Anderson0032b272009-08-13 21:57:51 +0000754 ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0);
Anders Carlssoncc899202009-02-08 22:46:50 +0000755 else {
756 ID = SI->findCaseDest(Dest);
757 if (!ID) {
758 // No code found, get a new unique one by using the number of
759 // switch successors.
Mike Stump1eb44332009-09-09 15:08:12 +0000760 ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anders Carlssoncc899202009-02-08 22:46:50 +0000761 SI->getNumSuccessors());
762 SI->addCase(ID, Dest);
763 }
764 }
Mike Stump1eb44332009-09-09 15:08:12 +0000765
Anders Carlssoncc899202009-02-08 22:46:50 +0000766 // Store the jump destination before the branch instruction.
767 new llvm::StoreInst(ID, DestCodePtr, BI);
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000768 } else {
769 // We need to jump through another cleanup block. Create a pad block
Mike Stump99533832009-12-02 07:41:41 +0000770 // with a branch instruction that jumps to the final destination and add
771 // it as a branch fixup to the current cleanup scope.
Mike Stump1eb44332009-09-09 15:08:12 +0000772
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000773 // Create the pad block.
774 llvm::BasicBlock *CleanupPad = createBasicBlock("cleanup.pad", CurFn);
Anders Carlssoncc899202009-02-08 22:46:50 +0000775
776 // Create a unique case ID.
Mike Stump99533832009-12-02 07:41:41 +0000777 llvm::ConstantInt *ID
778 = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
779 SI->getNumSuccessors());
Anders Carlssoncc899202009-02-08 22:46:50 +0000780
781 // Store the jump destination before the branch instruction.
782 new llvm::StoreInst(ID, DestCodePtr, BI);
783
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000784 // Add it as the destination.
Anders Carlssoncc899202009-02-08 22:46:50 +0000785 SI->addCase(ID, CleanupPad);
Mike Stump1eb44332009-09-09 15:08:12 +0000786
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000787 // Create the branch to the final destination.
788 llvm::BranchInst *BI = llvm::BranchInst::Create(Dest);
789 CleanupPad->getInstList().push_back(BI);
Mike Stump1eb44332009-09-09 15:08:12 +0000790
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000791 // And add it as a branch fixup.
792 CleanupEntries.back().BranchFixups.push_back(BI);
793 }
794 }
795 }
Mike Stump1eb44332009-09-09 15:08:12 +0000796
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000797 // Remove all blocks from the block scope map.
798 for (size_t i = 0, e = Blocks.size(); i != e; ++i) {
799 assert(BlockScopes.count(Blocks[i]) &&
800 "Did not find block in scope map!");
Mike Stump1eb44332009-09-09 15:08:12 +0000801
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000802 BlockScopes.erase(Blocks[i]);
803 }
Mike Stump1eb44332009-09-09 15:08:12 +0000804
Mike Stump99533832009-12-02 07:41:41 +0000805 return CleanupBlockInfo(CleanupEntryBlock, SwitchBlock, EndBlock, EHOnly);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000806}
807
Mike Stump1eb44332009-09-09 15:08:12 +0000808void CodeGenFunction::EmitCleanupBlock() {
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000809 CleanupBlockInfo Info = PopCleanupBlock();
Mike Stump1eb44332009-09-09 15:08:12 +0000810
Mike Stump99533832009-12-02 07:41:41 +0000811 if (Info.EHOnly) {
812 // FIXME: Add this to the exceptional edge
813 if (Info.CleanupBlock->getNumUses() == 0)
814 delete Info.CleanupBlock;
815 return;
816 }
817
Devang Patelcd9199e2010-04-13 00:08:43 +0000818 // Scrub debug location info.
819 for (llvm::BasicBlock::iterator LBI = Info.CleanupBlock->begin(),
820 LBE = Info.CleanupBlock->end(); LBI != LBE; ++LBI)
821 Builder.SetInstDebugLocation(LBI);
822
Anders Carlssoneb6437a2009-05-31 00:33:20 +0000823 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
Mike Stump1eb44332009-09-09 15:08:12 +0000824 if (CurBB && !CurBB->getTerminator() &&
Anders Carlssoneb6437a2009-05-31 00:33:20 +0000825 Info.CleanupBlock->getNumUses() == 0) {
826 CurBB->getInstList().splice(CurBB->end(), Info.CleanupBlock->getInstList());
827 delete Info.CleanupBlock;
Mike Stump1eb44332009-09-09 15:08:12 +0000828 } else
Anders Carlssoneb6437a2009-05-31 00:33:20 +0000829 EmitBlock(Info.CleanupBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000830
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000831 if (Info.SwitchBlock)
832 EmitBlock(Info.SwitchBlock);
833 if (Info.EndBlock)
834 EmitBlock(Info.EndBlock);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000835}
836
Mike Stump1eb44332009-09-09 15:08:12 +0000837void CodeGenFunction::AddBranchFixup(llvm::BranchInst *BI) {
838 assert(!CleanupEntries.empty() &&
Anders Carlsson87eaf172009-02-08 00:50:42 +0000839 "Trying to add branch fixup without cleanup block!");
Mike Stump1eb44332009-09-09 15:08:12 +0000840
Mike Stumpf5408fe2009-05-16 07:57:57 +0000841 // FIXME: We could be more clever here and check if there's already a branch
842 // fixup for this destination and recycle it.
Anders Carlsson87eaf172009-02-08 00:50:42 +0000843 CleanupEntries.back().BranchFixups.push_back(BI);
844}
845
Mike Stump1eb44332009-09-09 15:08:12 +0000846void CodeGenFunction::EmitBranchThroughCleanup(llvm::BasicBlock *Dest) {
Anders Carlsson46831a92009-02-08 22:13:37 +0000847 if (!HaveInsertPoint())
848 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000849
Anders Carlsson87eaf172009-02-08 00:50:42 +0000850 llvm::BranchInst* BI = Builder.CreateBr(Dest);
Mike Stump1eb44332009-09-09 15:08:12 +0000851
Anders Carlsson46831a92009-02-08 22:13:37 +0000852 Builder.ClearInsertionPoint();
Mike Stump1eb44332009-09-09 15:08:12 +0000853
Anders Carlsson87eaf172009-02-08 00:50:42 +0000854 // The stack is empty, no need to do any cleanup.
855 if (CleanupEntries.empty())
856 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000857
Anders Carlsson87eaf172009-02-08 00:50:42 +0000858 if (!Dest->getParent()) {
859 // We are trying to branch to a block that hasn't been inserted yet.
860 AddBranchFixup(BI);
861 return;
862 }
Mike Stump1eb44332009-09-09 15:08:12 +0000863
Anders Carlsson87eaf172009-02-08 00:50:42 +0000864 BlockScopeMap::iterator I = BlockScopes.find(Dest);
865 if (I == BlockScopes.end()) {
866 // We are trying to jump to a block that is outside of any cleanup scope.
867 AddBranchFixup(BI);
868 return;
869 }
Mike Stump1eb44332009-09-09 15:08:12 +0000870
Anders Carlsson87eaf172009-02-08 00:50:42 +0000871 assert(I->second < CleanupEntries.size() &&
872 "Trying to branch into cleanup region");
Mike Stump1eb44332009-09-09 15:08:12 +0000873
Anders Carlsson87eaf172009-02-08 00:50:42 +0000874 if (I->second == CleanupEntries.size() - 1) {
875 // We have a branch to a block in the same scope.
876 return;
877 }
Mike Stump1eb44332009-09-09 15:08:12 +0000878
Anders Carlsson87eaf172009-02-08 00:50:42 +0000879 AddBranchFixup(BI);
880}