blob: c6111fac19747bace328ddc69cd7418b7b23fd87 [file] [log] [blame]
Chris Lattnerbed31442007-05-28 01:07:47 +00001//===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerbed31442007-05-28 01:07:47 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-function state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
15#include "CodeGenModule.h"
Eli Friedman17630752008-05-22 01:40:10 +000016#include "CGDebugInfo.h"
Chris Lattnerd1af2d22007-05-29 23:17:50 +000017#include "clang/Basic/TargetInfo.h"
Chris Lattnercd439292008-11-12 08:04:58 +000018#include "clang/AST/APValue.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000019#include "clang/AST/ASTContext.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000020#include "clang/AST/Decl.h"
Anders Carlsson468fa632009-04-04 20:47:02 +000021#include "clang/AST/DeclCXX.h"
Mike Stumpcb2fbcb2009-02-21 20:00:35 +000022#include "llvm/Target/TargetData.h"
Chris Lattnerbed31442007-05-28 01:07:47 +000023using namespace clang;
24using namespace CodeGen;
25
Mike Stump11289f42009-09-09 15:08:12 +000026CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
Mike Stump0c743272009-03-06 01:33:24 +000027 : BlockFunction(cgm, *this, Builder), CGM(cgm),
28 Target(CGM.getContext().Target),
Owen Andersonc9673d52009-07-08 20:52:20 +000029 Builder(cgm.getModule().getContext()),
Chris Lattner2bb5cb42009-10-13 06:55:33 +000030 DebugInfo(0), IndirectGotoSwitch(0),
31 SwitchInsn(0), CaseRangeBlock(0), InvokeDest(0),
Anders Carlsson468fa632009-04-04 20:47:02 +000032 CXXThisDecl(0) {
Mike Stumpcb2fbcb2009-02-21 20:00:35 +000033 LLVMIntTy = ConvertType(getContext().IntTy);
34 LLVMPointerWidth = Target.getPointerWidth(0);
Chris Lattner5696e7b2008-06-17 18:05:57 +000035}
Chris Lattnerd1af2d22007-05-29 23:17:50 +000036
Chris Lattner6db1fb82007-06-02 22:49:07 +000037ASTContext &CodeGenFunction::getContext() const {
38 return CGM.getContext();
39}
40
Chris Lattnerd1af2d22007-05-29 23:17:50 +000041
Chris Lattnerac248202007-05-30 00:13:02 +000042llvm::BasicBlock *CodeGenFunction::getBasicBlockForLabel(const LabelStmt *S) {
Chris Lattner23b7eb62007-06-15 23:05:46 +000043 llvm::BasicBlock *&BB = LabelMap[S];
Chris Lattnerac248202007-05-30 00:13:02 +000044 if (BB) return BB;
Mike Stump11289f42009-09-09 15:08:12 +000045
Chris Lattnerac248202007-05-30 00:13:02 +000046 // Create, but don't insert, the new block.
Daniel Dunbar75283ff2008-11-11 02:29:29 +000047 return BB = createBasicBlock(S->getName());
Chris Lattnerac248202007-05-30 00:13:02 +000048}
49
Daniel Dunbar22a87f92009-02-25 19:24:29 +000050llvm::Value *CodeGenFunction::GetAddrOfLocalVar(const VarDecl *VD) {
51 llvm::Value *Res = LocalDeclMap[VD];
52 assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!");
53 return Res;
Lauro Ramos Venancio01a72ff2008-02-26 21:41:45 +000054}
Chris Lattnerac248202007-05-30 00:13:02 +000055
Daniel Dunbar22a87f92009-02-25 19:24:29 +000056llvm::Constant *
57CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) {
58 return cast<llvm::Constant>(GetAddrOfLocalVar(BVD));
Anders Carlsson9396a892008-09-11 09:15:33 +000059}
60
Daniel Dunbaree3da872009-02-03 23:03:55 +000061const llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
62 return CGM.getTypes().ConvertTypeForMem(T);
63}
64
Chris Lattnerf033c142007-06-22 19:05:19 +000065const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
66 return CGM.getTypes().ConvertType(T);
Chris Lattner45bb9142007-06-09 02:28:57 +000067}
Chris Lattnerd1af2d22007-05-29 23:17:50 +000068
Chris Lattner54fb19e2007-06-22 22:02:34 +000069bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
Anders Carlssonb05a3e52009-09-29 02:09:01 +000070 return T->isRecordType() || T->isArrayType() || T->isAnyComplexType() ||
71 T->isMemberFunctionPointerType();
Chris Lattner54fb19e2007-06-22 22:02:34 +000072}
73
Daniel Dunbarfd346a32009-01-26 23:27:52 +000074void CodeGenFunction::EmitReturnBlock() {
75 // For cleanliness, we try to avoid emitting the return block for
76 // simple cases.
77 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
78
79 if (CurBB) {
80 assert(!CurBB->getTerminator() && "Unexpected terminated block.");
81
Daniel Dunbarea3060a2009-07-19 08:24:34 +000082 // We have a valid insert point, reuse it if it is empty or there are no
83 // explicit jumps to the return block.
84 if (CurBB->empty() || ReturnBlock->use_empty()) {
85 ReturnBlock->replaceAllUsesWith(CurBB);
Daniel Dunbarfd346a32009-01-26 23:27:52 +000086 delete ReturnBlock;
Daniel Dunbarea3060a2009-07-19 08:24:34 +000087 } else
Daniel Dunbarfd346a32009-01-26 23:27:52 +000088 EmitBlock(ReturnBlock);
89 return;
90 }
91
92 // Otherwise, if the return block is the target of a single direct
93 // branch then we can just put the code in that block instead. This
94 // cleans up functions which started with a unified return block.
95 if (ReturnBlock->hasOneUse()) {
Mike Stump11289f42009-09-09 15:08:12 +000096 llvm::BranchInst *BI =
Daniel Dunbarfd346a32009-01-26 23:27:52 +000097 dyn_cast<llvm::BranchInst>(*ReturnBlock->use_begin());
98 if (BI && BI->isUnconditional() && BI->getSuccessor(0) == ReturnBlock) {
99 // Reset insertion point and delete the branch.
100 Builder.SetInsertPoint(BI->getParent());
101 BI->eraseFromParent();
102 delete ReturnBlock;
103 return;
104 }
105 }
106
Mike Stump18bb9282009-05-16 07:57:57 +0000107 // FIXME: We are at an unreachable point, there is no reason to emit the block
108 // unless it has uses. However, we still need a place to put the debug
109 // region.end for now.
Daniel Dunbarfd346a32009-01-26 23:27:52 +0000110
111 EmitBlock(ReturnBlock);
112}
113
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000114void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
Chris Lattnere73e4322007-07-16 21:28:45 +0000115 assert(BreakContinueStack.empty() &&
116 "mismatched push/pop in break/continue stack!");
Anders Carlssonfbfb5e62009-02-08 00:16:35 +0000117 assert(BlockScopes.empty() &&
118 "did not remove all blocks from block scope map!");
119 assert(CleanupEntries.empty() &&
120 "mismatched push/pop in cleanup stack!");
Mike Stump11289f42009-09-09 15:08:12 +0000121
122 // Emit function epilog (to return).
Daniel Dunbarfd346a32009-01-26 23:27:52 +0000123 EmitReturnBlock();
Daniel Dunbarfab3f932008-11-11 20:59:54 +0000124
125 // Emit debug descriptor for function end.
Anders Carlsson63784f42009-02-13 08:11:52 +0000126 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbarfab3f932008-11-11 20:59:54 +0000127 DI->setLocation(EndLoc);
128 DI->EmitRegionEnd(CurFn, Builder);
129 }
130
Daniel Dunbard931a872009-02-02 22:03:45 +0000131 EmitFunctionEpilog(*CurFnInfo, ReturnValue);
Daniel Dunbar54bb1932008-09-09 21:00:17 +0000132
Chris Lattnerc48023b2007-12-02 06:32:24 +0000133 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
Chris Lattner2739d2b2009-03-31 22:17:44 +0000134 llvm::Instruction *Ptr = AllocaInsertPt;
Chris Lattnerc48023b2007-12-02 06:32:24 +0000135 AllocaInsertPt = 0;
Chris Lattner2739d2b2009-03-31 22:17:44 +0000136 Ptr->eraseFromParent();
Chris Lattnerd1af2d22007-05-29 23:17:50 +0000137}
Chris Lattner308f4312007-05-29 23:50:05 +0000138
Anders Carlsson73fcc952009-09-11 00:07:24 +0000139void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000140 llvm::Function *Fn,
Daniel Dunbar354d2782008-10-18 18:22:23 +0000141 const FunctionArgList &Args,
142 SourceLocation StartLoc) {
Anders Carlsson73fcc952009-09-11 00:07:24 +0000143 const Decl *D = GD.getDecl();
144
Anders Carlssonf4478e92009-02-09 20:20:56 +0000145 DidCallStackSave = false;
Chris Lattner28ec0cf2009-04-23 05:30:27 +0000146 CurCodeDecl = CurFuncDecl = D;
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000147 FnRetTy = RetTy;
Daniel Dunbar9c426522008-07-29 23:18:29 +0000148 CurFn = Fn;
Chris Lattner5696e7b2008-06-17 18:05:57 +0000149 assert(CurFn->isDeclaration() && "Function already has body?");
150
Daniel Dunbar75283ff2008-11-11 02:29:29 +0000151 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
Daniel Dunbar54bb1932008-09-09 21:00:17 +0000152
Chris Lattner5696e7b2008-06-17 18:05:57 +0000153 // Create a marker to make it easy to insert allocas into the entryblock
154 // later. Don't create this with the builder, because we don't want it
155 // folded.
Owen Anderson41a75022009-08-13 21:57:51 +0000156 llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::getInt32Ty(VMContext));
Mike Stump1dbb8f72009-09-25 18:11:00 +0000157 AllocaInsertPt = new llvm::BitCastInst(Undef,
158 llvm::Type::getInt32Ty(VMContext), "",
Chris Lattner5696e7b2008-06-17 18:05:57 +0000159 EntryBB);
Chris Lattner47640222009-03-22 00:24:14 +0000160 if (Builder.isNamePreserving())
161 AllocaInsertPt->setName("allocapt");
Mike Stump11289f42009-09-09 15:08:12 +0000162
Daniel Dunbar75283ff2008-11-11 02:29:29 +0000163 ReturnBlock = createBasicBlock("return");
Daniel Dunbar54bb1932008-09-09 21:00:17 +0000164 ReturnValue = 0;
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000165 if (!RetTy->isVoidType())
166 ReturnValue = CreateTempAlloca(ConvertType(RetTy), "retval");
Mike Stump11289f42009-09-09 15:08:12 +0000167
Chris Lattner5696e7b2008-06-17 18:05:57 +0000168 Builder.SetInsertPoint(EntryBB);
Mike Stump11289f42009-09-09 15:08:12 +0000169
Mike Stumpae2559a2009-10-23 01:52:13 +0000170 QualType FnType = getContext().getFunctionType(RetTy, 0, 0, false, 0);
171
Sanjiv Gupta1e8b6082008-07-04 11:04:26 +0000172 // Emit subprogram debug descriptor.
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000173 // FIXME: The cast here is a huge hack.
Anders Carlsson63784f42009-02-13 08:11:52 +0000174 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar354d2782008-10-18 18:22:23 +0000175 DI->setLocation(StartLoc);
Anders Carlssonfd384d82009-09-11 00:11:35 +0000176 if (isa<FunctionDecl>(D)) {
Mike Stumpae2559a2009-10-23 01:52:13 +0000177 DI->EmitFunctionStart(CGM.getMangledName(GD), FnType, CurFn, Builder);
Daniel Dunbar354d2782008-10-18 18:22:23 +0000178 } else {
179 // Just use LLVM function name.
Mike Stump11289f42009-09-09 15:08:12 +0000180
Daniel Dunbar7c02cf62009-07-23 05:30:36 +0000181 // FIXME: Remove unnecessary conversion to std::string when API settles.
Mike Stump11289f42009-09-09 15:08:12 +0000182 DI->EmitFunctionStart(std::string(Fn->getName()).c_str(),
Mike Stumpae2559a2009-10-23 01:52:13 +0000183 FnType, CurFn, Builder);
Sanjiv Gupta1e8b6082008-07-04 11:04:26 +0000184 }
Sanjiv Gupta1e8b6082008-07-04 11:04:26 +0000185 }
186
Daniel Dunbard931a872009-02-02 22:03:45 +0000187 // FIXME: Leaked.
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000188 CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args);
Daniel Dunbard931a872009-02-02 22:03:45 +0000189 EmitFunctionProlog(*CurFnInfo, CurFn, Args);
Mike Stump11289f42009-09-09 15:08:12 +0000190
Anders Carlssonc20879a2008-12-20 21:28:43 +0000191 // If any of the arguments have a variably modified type, make sure to
192 // emit the type size.
193 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
194 i != e; ++i) {
195 QualType Ty = i->second;
196
197 if (Ty->isVariablyModifiedType())
198 EmitVLASize(Ty);
199 }
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000200}
Eli Friedman3d421e12008-08-25 21:31:01 +0000201
Anders Carlsson73fcc952009-09-11 00:07:24 +0000202void CodeGenFunction::GenerateCode(GlobalDecl GD,
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000203 llvm::Function *Fn) {
Anders Carlsson73fcc952009-09-11 00:07:24 +0000204 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
205
Anders Carlsson63784f42009-02-13 08:11:52 +0000206 // Check if we should generate debug info for this function.
Mike Stump3722f582009-08-26 22:31:08 +0000207 if (CGM.getDebugInfo() && !FD->hasAttr<NoDebugAttr>())
Anders Carlsson63784f42009-02-13 08:11:52 +0000208 DebugInfo = CGM.getDebugInfo();
Mike Stump11289f42009-09-09 15:08:12 +0000209
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000210 FunctionArgList Args;
Mike Stump11289f42009-09-09 15:08:12 +0000211
Anders Carlsson468fa632009-04-04 20:47:02 +0000212 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
213 if (MD->isInstance()) {
214 // Create the implicit 'this' decl.
215 // FIXME: I'm not entirely sure I like using a fake decl just for code
216 // generation. Maybe we can come up with a better way?
217 CXXThisDecl = ImplicitParamDecl::Create(getContext(), 0, SourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +0000218 &getContext().Idents.get("this"),
Anders Carlsson468fa632009-04-04 20:47:02 +0000219 MD->getThisType(getContext()));
220 Args.push_back(std::make_pair(CXXThisDecl, CXXThisDecl->getType()));
221 }
222 }
Mike Stump11289f42009-09-09 15:08:12 +0000223
Eli Friedman3d421e12008-08-25 21:31:01 +0000224 if (FD->getNumParams()) {
John McCall9dd450b2009-09-21 23:43:11 +0000225 const FunctionProtoType* FProto = FD->getType()->getAs<FunctionProtoType>();
Eli Friedman3d421e12008-08-25 21:31:01 +0000226 assert(FProto && "Function def must have prototype!");
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000227
228 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
Mike Stump11289f42009-09-09 15:08:12 +0000229 Args.push_back(std::make_pair(FD->getParamDecl(i),
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000230 FProto->getArgType(i)));
Chris Lattner5696e7b2008-06-17 18:05:57 +0000231 }
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000232
Sebastian Redla7b98a72009-04-26 20:35:05 +0000233 // FIXME: Support CXXTryStmt here, too.
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +0000234 if (const CompoundStmt *S = FD->getCompoundBody()) {
Anders Carlsson73fcc952009-09-11 00:07:24 +0000235 StartFunction(GD, FD->getResultType(), Fn, Args, S->getLBracLoc());
Anders Carlsson6b7378b2009-10-06 18:09:57 +0000236 const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD);
237 llvm::BasicBlock *DtorEpilogue = 0;
238 if (DD) {
239 DtorEpilogue = createBasicBlock("dtor.epilogue");
240
241 PushCleanupBlock(DtorEpilogue);
242 }
243
Fariborz Jahanian127059c2009-07-20 22:35:22 +0000244 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Anders Carlssonddf57d32009-09-14 05:32:02 +0000245 EmitCtorPrologue(CD, GD.getCtorType());
Sebastian Redla7b98a72009-04-26 20:35:05 +0000246 EmitStmt(S);
Anders Carlsson6b7378b2009-10-06 18:09:57 +0000247
248 if (DD) {
249 CleanupBlockInfo Info = PopCleanupBlock();
250
251 assert(Info.CleanupBlock == DtorEpilogue && "Block mismatch!");
252 EmitBlock(DtorEpilogue);
Anders Carlssonddf57d32009-09-14 05:32:02 +0000253 EmitDtorEpilogue(DD, GD.getDtorType());
Anders Carlsson6b7378b2009-10-06 18:09:57 +0000254
255 if (Info.SwitchBlock)
256 EmitBlock(Info.SwitchBlock);
257 if (Info.EndBlock)
258 EmitBlock(Info.EndBlock);
259 }
Sebastian Redla7b98a72009-04-26 20:35:05 +0000260 FinishFunction(S->getRBracLoc());
Douglas Gregor369acf92009-10-01 20:44:19 +0000261 } else if (FD->isImplicit()) {
262 const CXXRecordDecl *ClassDecl =
263 cast<CXXRecordDecl>(FD->getDeclContext());
264 (void) ClassDecl;
Fariborz Jahanian6f14c732009-07-30 23:22:00 +0000265 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
Douglas Gregor369acf92009-10-01 20:44:19 +0000266 // FIXME: For C++0x, we want to look for implicit *definitions* of
267 // these special member functions, rather than implicit *declarations*.
Fariborz Jahanian9301b242009-08-06 23:38:16 +0000268 if (CD->isCopyConstructor(getContext())) {
269 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
Douglas Gregor369acf92009-10-01 20:44:19 +0000270 "Cannot synthesize a non-implicit copy constructor");
Anders Carlssonddf57d32009-09-14 05:32:02 +0000271 SynthesizeCXXCopyConstructor(CD, GD.getCtorType(), Fn, Args);
Douglas Gregor369acf92009-10-01 20:44:19 +0000272 } else if (CD->isDefaultConstructor()) {
Fariborz Jahanian9301b242009-08-06 23:38:16 +0000273 assert(!ClassDecl->hasUserDeclaredConstructor() &&
Douglas Gregor369acf92009-10-01 20:44:19 +0000274 "Cannot synthesize a non-implicit default constructor.");
Anders Carlssonddf57d32009-09-14 05:32:02 +0000275 SynthesizeDefaultConstructor(CD, GD.getCtorType(), Fn, Args);
Douglas Gregor369acf92009-10-01 20:44:19 +0000276 } else {
277 assert(false && "Implicit constructor cannot be synthesized");
Fariborz Jahanian9301b242009-08-06 23:38:16 +0000278 }
Douglas Gregor369acf92009-10-01 20:44:19 +0000279 } else if (const CXXDestructorDecl *CD = dyn_cast<CXXDestructorDecl>(FD)) {
280 assert(!ClassDecl->hasUserDeclaredDestructor() &&
281 "Cannot synthesize a non-implicit destructor");
282 SynthesizeDefaultDestructor(CD, GD.getDtorType(), Fn, Args);
283 } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
284 assert(MD->isCopyAssignment() &&
285 !ClassDecl->hasUserDeclaredCopyAssignment() &&
286 "Cannot synthesize a method that is not an implicit-defined "
287 "copy constructor");
Anders Carlssonddf57d32009-09-14 05:32:02 +0000288 SynthesizeCXXCopyAssignment(MD, Fn, Args);
Douglas Gregor369acf92009-10-01 20:44:19 +0000289 } else {
290 assert(false && "Cannot synthesize unknown implicit function");
291 }
Anders Carlsson73fcc952009-09-11 00:07:24 +0000292 }
Mike Stump11289f42009-09-09 15:08:12 +0000293
Anders Carlsson468fa632009-04-04 20:47:02 +0000294 // Destroy the 'this' declaration.
295 if (CXXThisDecl)
296 CXXThisDecl->Destroy(getContext());
Chris Lattner5696e7b2008-06-17 18:05:57 +0000297}
298
Chris Lattner5b1964b2008-11-11 07:41:27 +0000299/// ContainsLabel - Return true if the statement contains a label in it. If
300/// this statement is not executed normally, it not containing a label means
301/// that we can just remove the code.
302bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
303 // Null statement, not a label!
304 if (S == 0) return false;
Mike Stump11289f42009-09-09 15:08:12 +0000305
Chris Lattner5b1964b2008-11-11 07:41:27 +0000306 // If this is a label, we have to emit the code, consider something like:
307 // if (0) { ... foo: bar(); } goto foo;
308 if (isa<LabelStmt>(S))
309 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000310
Chris Lattner5b1964b2008-11-11 07:41:27 +0000311 // If this is a case/default statement, and we haven't seen a switch, we have
312 // to emit the code.
313 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
314 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000315
Chris Lattner5b1964b2008-11-11 07:41:27 +0000316 // If this is a switch statement, we want to ignore cases below it.
317 if (isa<SwitchStmt>(S))
318 IgnoreCaseStmts = true;
Mike Stump11289f42009-09-09 15:08:12 +0000319
Chris Lattner5b1964b2008-11-11 07:41:27 +0000320 // Scan subexpressions for verboten labels.
321 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
322 I != E; ++I)
323 if (ContainsLabel(*I, IgnoreCaseStmts))
324 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000325
Chris Lattner5b1964b2008-11-11 07:41:27 +0000326 return false;
327}
328
Chris Lattnercd439292008-11-12 08:04:58 +0000329
330/// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
331/// a constant, or if it does but contains a label, return 0. If it constant
332/// folds to 'true' and does not contain a label, return 1, if it constant folds
333/// to 'false' and does not contain a label, return -1.
334int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
Daniel Dunbarf32443c2008-11-12 22:37:10 +0000335 // FIXME: Rename and handle conversion of other evaluatable things
336 // to bool.
Anders Carlsson86286452008-12-01 02:46:24 +0000337 Expr::EvalResult Result;
Mike Stump11289f42009-09-09 15:08:12 +0000338 if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
Anders Carlsson86286452008-12-01 02:46:24 +0000339 Result.HasSideEffects)
Anders Carlsson4046e652008-11-22 22:32:07 +0000340 return 0; // Not foldable, not integer or not fully evaluatable.
Mike Stump11289f42009-09-09 15:08:12 +0000341
Chris Lattnercd439292008-11-12 08:04:58 +0000342 if (CodeGenFunction::ContainsLabel(Cond))
343 return 0; // Contains a label.
Mike Stump11289f42009-09-09 15:08:12 +0000344
Anders Carlsson86286452008-12-01 02:46:24 +0000345 return Result.Val.getInt().getBoolValue() ? 1 : -1;
Chris Lattnercd439292008-11-12 08:04:58 +0000346}
347
348
349/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
350/// statement) to the specified blocks. Based on the condition, this might try
351/// to simplify the codegen of the conditional based on the branch.
352///
353void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
354 llvm::BasicBlock *TrueBlock,
355 llvm::BasicBlock *FalseBlock) {
356 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
357 return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
Mike Stump11289f42009-09-09 15:08:12 +0000358
Chris Lattnercd439292008-11-12 08:04:58 +0000359 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
360 // Handle X && Y in a condition.
361 if (CondBOp->getOpcode() == BinaryOperator::LAnd) {
362 // If we have "1 && X", simplify the code. "0 && X" would have constant
363 // folded if the case was simple enough.
364 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
365 // br(1 && X) -> br(X).
366 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
367 }
Mike Stump11289f42009-09-09 15:08:12 +0000368
Chris Lattnercd439292008-11-12 08:04:58 +0000369 // If we have "X && 1", simplify the code to use an uncond branch.
370 // "X && 0" would have been constant folded to 0.
371 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
372 // br(X && 1) -> br(X).
373 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
374 }
Mike Stump11289f42009-09-09 15:08:12 +0000375
Chris Lattnercd439292008-11-12 08:04:58 +0000376 // Emit the LHS as a conditional. If the LHS conditional is false, we
377 // want to jump to the FalseBlock.
Daniel Dunbara612e792008-11-13 01:38:36 +0000378 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
Chris Lattnercd439292008-11-12 08:04:58 +0000379 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
380 EmitBlock(LHSTrue);
Mike Stump11289f42009-09-09 15:08:12 +0000381
Chris Lattnercd439292008-11-12 08:04:58 +0000382 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
383 return;
384 } else if (CondBOp->getOpcode() == BinaryOperator::LOr) {
385 // If we have "0 || X", simplify the code. "1 || X" would have constant
386 // folded if the case was simple enough.
387 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
388 // br(0 || X) -> br(X).
389 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
390 }
Mike Stump11289f42009-09-09 15:08:12 +0000391
Chris Lattnercd439292008-11-12 08:04:58 +0000392 // If we have "X || 0", simplify the code to use an uncond branch.
393 // "X || 1" would have been constant folded to 1.
394 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
395 // br(X || 0) -> br(X).
396 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
397 }
Mike Stump11289f42009-09-09 15:08:12 +0000398
Chris Lattnercd439292008-11-12 08:04:58 +0000399 // Emit the LHS as a conditional. If the LHS conditional is true, we
400 // want to jump to the TrueBlock.
Daniel Dunbara612e792008-11-13 01:38:36 +0000401 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
Chris Lattnercd439292008-11-12 08:04:58 +0000402 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
403 EmitBlock(LHSFalse);
Mike Stump11289f42009-09-09 15:08:12 +0000404
Chris Lattnercd439292008-11-12 08:04:58 +0000405 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
406 return;
407 }
Chris Lattnerd9537732008-11-12 08:13:36 +0000408 }
Mike Stump11289f42009-09-09 15:08:12 +0000409
Chris Lattnerd9537732008-11-12 08:13:36 +0000410 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
411 // br(!x, t, f) -> br(x, f, t)
412 if (CondUOp->getOpcode() == UnaryOperator::LNot)
413 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
Chris Lattnercd439292008-11-12 08:04:58 +0000414 }
Mike Stump11289f42009-09-09 15:08:12 +0000415
Daniel Dunbarbf3c22e2008-11-12 10:30:32 +0000416 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
417 // Handle ?: operator.
418
419 // Just ignore GNU ?: extension.
420 if (CondOp->getLHS()) {
421 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
422 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
423 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
424 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
425 EmitBlock(LHSBlock);
426 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
427 EmitBlock(RHSBlock);
428 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
429 return;
430 }
431 }
432
Chris Lattnercd439292008-11-12 08:04:58 +0000433 // Emit the code with the fully general case.
434 llvm::Value *CondV = EvaluateExprAsBool(Cond);
435 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
436}
437
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000438/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerfc944342007-12-02 01:43:38 +0000439/// specified stmt yet.
Daniel Dunbarf2cf6d12008-09-04 03:43:08 +0000440void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
441 bool OmitOnError) {
442 CGM.ErrorUnsupported(S, Type, OmitOnError);
Chris Lattnerfc944342007-12-02 01:43:38 +0000443}
444
Chris Lattnerb534f6a2009-04-21 17:59:23 +0000445void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty) {
Chris Lattnerdd7eaad2009-10-13 06:02:42 +0000446 const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext);
Anders Carlsson2e744e82008-08-30 19:51:14 +0000447 if (DestPtr->getType() != BP)
448 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
449
450 // Get size and alignment info for this aggregate.
451 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
452
Chris Lattnerb534f6a2009-04-21 17:59:23 +0000453 // Don't bother emitting a zero-byte memset.
454 if (TypeInfo.first == 0)
455 return;
Mike Stump11289f42009-09-09 15:08:12 +0000456
Anders Carlsson2e744e82008-08-30 19:51:14 +0000457 // FIXME: Handle variable sized types.
Mike Stump11289f42009-09-09 15:08:12 +0000458 const llvm::Type *IntPtr = llvm::IntegerType::get(VMContext,
Owen Anderson41a75022009-08-13 21:57:51 +0000459 LLVMPointerWidth);
Anders Carlsson2e744e82008-08-30 19:51:14 +0000460
461 Builder.CreateCall4(CGM.getMemSetFn(), DestPtr,
Owen Anderson41a75022009-08-13 21:57:51 +0000462 llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext)),
Anders Carlsson2e744e82008-08-30 19:51:14 +0000463 // TypeInfo.first describes size in bits.
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000464 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
Mike Stump11289f42009-09-09 15:08:12 +0000465 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anders Carlsson2e744e82008-08-30 19:51:14 +0000466 TypeInfo.second/8));
467}
468
Chris Lattner2bb5cb42009-10-13 06:55:33 +0000469unsigned CodeGenFunction::GetIDForAddrOfLabel(const LabelStmt *L) {
470 // Use LabelIDs.size()+1 as the new ID if one hasn't been assigned.
471 unsigned &Entry = LabelIDs[L];
472 if (Entry) return Entry;
473
474 Entry = LabelIDs.size();
475
476 // If this is the first "address taken" of a label and the indirect goto has
477 // already been seen, add this to it.
478 if (IndirectGotoSwitch) {
479 // If this is the first address-taken label, set it as the default dest.
480 if (Entry == 1)
481 IndirectGotoSwitch->setSuccessor(0, getBasicBlockForLabel(L));
482 else {
483 // Otherwise add it to the switch as a new dest.
484 const llvm::IntegerType *Int32Ty = llvm::Type::getInt32Ty(VMContext);
485 IndirectGotoSwitch->addCase(llvm::ConstantInt::get(Int32Ty, Entry),
486 getBasicBlockForLabel(L));
Daniel Dunbar88402ce2008-08-04 16:51:22 +0000487 }
Mike Stump11289f42009-09-09 15:08:12 +0000488 }
Chris Lattner2bb5cb42009-10-13 06:55:33 +0000489
490 return Entry;
491}
492
493llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
494 // If we already made the switch stmt for indirect goto, return its block.
495 if (IndirectGotoSwitch) return IndirectGotoSwitch->getParent();
496
497 EmitBlock(createBasicBlock("indirectgoto"));
498
Chris Lattnera0c0d882009-10-28 20:36:47 +0000499 const llvm::IntegerType *Int32Ty = llvm::Type::getInt32Ty(VMContext);
500
Chris Lattner2bb5cb42009-10-13 06:55:33 +0000501 // Create the PHI node that indirect gotos will add entries to.
Chris Lattnera0c0d882009-10-28 20:36:47 +0000502 llvm::Value *DestVal = Builder.CreatePHI(Int32Ty, "indirect.goto.dest");
Chris Lattner2bb5cb42009-10-13 06:55:33 +0000503
504 // Create the switch instruction. For now, set the insert block to this block
505 // which will be fixed as labels are added.
506 IndirectGotoSwitch = Builder.CreateSwitch(DestVal, Builder.GetInsertBlock());
507
508 // Clear the insertion point to indicate we are in unreachable code.
509 Builder.ClearInsertionPoint();
510
511 // If we already have labels created, add them.
512 if (!LabelIDs.empty()) {
513 // Invert LabelID's so that the order is determinstic.
514 std::vector<const LabelStmt*> AddrTakenLabelsByID;
515 AddrTakenLabelsByID.resize(LabelIDs.size());
516
517 for (std::map<const LabelStmt*,unsigned>::iterator
518 LI = LabelIDs.begin(), LE = LabelIDs.end(); LI != LE; ++LI) {
519 assert(LI->second-1 < AddrTakenLabelsByID.size() &&
520 "Numbering inconsistent");
521 AddrTakenLabelsByID[LI->second-1] = LI->first;
522 }
523
524 // Set the default entry as the first block.
525 IndirectGotoSwitch->setSuccessor(0,
526 getBasicBlockForLabel(AddrTakenLabelsByID[0]));
527
Chris Lattner2bb5cb42009-10-13 06:55:33 +0000528 // FIXME: The iteration order of this is nondeterminstic!
529 for (unsigned i = 1, e = AddrTakenLabelsByID.size(); i != e; ++i)
530 IndirectGotoSwitch->addCase(llvm::ConstantInt::get(Int32Ty, i+1),
531 getBasicBlockForLabel(AddrTakenLabelsByID[i]));
532 } else {
533 // Otherwise, create a dead block and set it as the default dest. This will
534 // be removed by the optimizers after the indirect goto is set up.
535 llvm::BasicBlock *Dummy = createBasicBlock("indgoto.dummy");
536 EmitBlock(Dummy);
537 IndirectGotoSwitch->setSuccessor(0, Dummy);
538 Builder.CreateUnreachable();
539 Builder.ClearInsertionPoint();
540 }
541
542 return IndirectGotoSwitch->getParent();
Daniel Dunbar88402ce2008-08-04 16:51:22 +0000543}
Anders Carlsson13abd7e2008-11-04 05:30:00 +0000544
Daniel Dunbarb6adc432009-07-19 06:58:07 +0000545llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) {
Eli Friedman04fddf02009-08-15 02:50:32 +0000546 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
Mike Stump11289f42009-09-09 15:08:12 +0000547
Anders Carlssone388a5b2008-12-20 20:27:15 +0000548 assert(SizeEntry && "Did not emit size for type");
549 return SizeEntry;
550}
Anders Carlssonccbe9202008-12-12 07:19:02 +0000551
Daniel Dunbarb6adc432009-07-19 06:58:07 +0000552llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) {
Anders Carlsson8a01b792008-12-20 20:46:34 +0000553 assert(Ty->isVariablyModifiedType() &&
554 "Must pass variably modified type to EmitVLASizes!");
Mike Stump11289f42009-09-09 15:08:12 +0000555
Daniel Dunbarb6adc432009-07-19 06:58:07 +0000556 EnsureInsertPoint();
Mike Stump11289f42009-09-09 15:08:12 +0000557
Anders Carlsson8a01b792008-12-20 20:46:34 +0000558 if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
Eli Friedman04fddf02009-08-15 02:50:32 +0000559 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
Mike Stump11289f42009-09-09 15:08:12 +0000560
Anders Carlsson5d985f52008-12-20 21:51:53 +0000561 if (!SizeEntry) {
Anders Carlsson31f86492009-02-05 19:43:10 +0000562 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
Mike Stump11289f42009-09-09 15:08:12 +0000563
Chris Lattner8dc76262009-08-15 00:03:43 +0000564 // Get the element size;
565 QualType ElemTy = VAT->getElementType();
566 llvm::Value *ElemSize;
Anders Carlsson5d985f52008-12-20 21:51:53 +0000567 if (ElemTy->isVariableArrayType())
568 ElemSize = EmitVLASize(ElemTy);
Chris Lattner8dc76262009-08-15 00:03:43 +0000569 else
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000570 ElemSize = llvm::ConstantInt::get(SizeTy,
Anders Carlsson5d985f52008-12-20 21:51:53 +0000571 getContext().getTypeSize(ElemTy) / 8);
Mike Stump11289f42009-09-09 15:08:12 +0000572
Anders Carlsson5d985f52008-12-20 21:51:53 +0000573 llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
Anders Carlsson31f86492009-02-05 19:43:10 +0000574 NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
Mike Stump11289f42009-09-09 15:08:12 +0000575
Anders Carlsson5d985f52008-12-20 21:51:53 +0000576 SizeEntry = Builder.CreateMul(ElemSize, NumElements);
Anders Carlsson8a01b792008-12-20 20:46:34 +0000577 }
Mike Stump11289f42009-09-09 15:08:12 +0000578
Anders Carlsson8a01b792008-12-20 20:46:34 +0000579 return SizeEntry;
Anders Carlssonccbe9202008-12-12 07:19:02 +0000580 }
Mike Stump11289f42009-09-09 15:08:12 +0000581
Chris Lattner8dc76262009-08-15 00:03:43 +0000582 if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
583 EmitVLASize(AT->getElementType());
584 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000585 }
586
Chris Lattner8dc76262009-08-15 00:03:43 +0000587 const PointerType *PT = Ty->getAs<PointerType>();
588 assert(PT && "unknown VM type!");
589 EmitVLASize(PT->getPointeeType());
Anders Carlsson8a01b792008-12-20 20:46:34 +0000590 return 0;
Anders Carlssonccbe9202008-12-12 07:19:02 +0000591}
Eli Friedmanddea0ad2009-01-20 17:46:04 +0000592
593llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
594 if (CGM.getContext().getBuiltinVaListType()->isArrayType()) {
595 return EmitScalarExpr(E);
596 }
597 return EmitLValue(E).getAddress();
598}
Anders Carlsson15cb75a2009-02-07 22:53:43 +0000599
Mike Stump11289f42009-09-09 15:08:12 +0000600void CodeGenFunction::PushCleanupBlock(llvm::BasicBlock *CleanupBlock) {
Anders Carlsson15cb75a2009-02-07 22:53:43 +0000601 CleanupEntries.push_back(CleanupEntry(CleanupBlock));
Anders Carlsson15cb75a2009-02-07 22:53:43 +0000602}
Anders Carlssonbe0f76a2009-02-07 23:50:39 +0000603
Mike Stump11289f42009-09-09 15:08:12 +0000604void CodeGenFunction::EmitCleanupBlocks(size_t OldCleanupStackSize) {
605 assert(CleanupEntries.size() >= OldCleanupStackSize &&
Anders Carlssonbe0f76a2009-02-07 23:50:39 +0000606 "Cleanup stack mismatch!");
Mike Stump11289f42009-09-09 15:08:12 +0000607
Anders Carlssonbe0f76a2009-02-07 23:50:39 +0000608 while (CleanupEntries.size() > OldCleanupStackSize)
609 EmitCleanupBlock();
610}
611
Mike Stump11289f42009-09-09 15:08:12 +0000612CodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock() {
Anders Carlsson66c384a2009-02-08 07:46:24 +0000613 CleanupEntry &CE = CleanupEntries.back();
Mike Stump11289f42009-09-09 15:08:12 +0000614
Anders Carlsson66c384a2009-02-08 07:46:24 +0000615 llvm::BasicBlock *CleanupBlock = CE.CleanupBlock;
Mike Stump11289f42009-09-09 15:08:12 +0000616
Anders Carlsson66c384a2009-02-08 07:46:24 +0000617 std::vector<llvm::BasicBlock *> Blocks;
618 std::swap(Blocks, CE.Blocks);
Mike Stump11289f42009-09-09 15:08:12 +0000619
Anders Carlsson66c384a2009-02-08 07:46:24 +0000620 std::vector<llvm::BranchInst *> BranchFixups;
621 std::swap(BranchFixups, CE.BranchFixups);
Mike Stump11289f42009-09-09 15:08:12 +0000622
Anders Carlsson66c384a2009-02-08 07:46:24 +0000623 CleanupEntries.pop_back();
624
Anders Carlssonf57b9ee2009-02-08 22:45:15 +0000625 // Check if any branch fixups pointed to the scope we just popped. If so,
626 // we can remove them.
627 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
628 llvm::BasicBlock *Dest = BranchFixups[i]->getSuccessor(0);
629 BlockScopeMap::iterator I = BlockScopes.find(Dest);
Mike Stump11289f42009-09-09 15:08:12 +0000630
Anders Carlssonf57b9ee2009-02-08 22:45:15 +0000631 if (I == BlockScopes.end())
632 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000633
Anders Carlssonf57b9ee2009-02-08 22:45:15 +0000634 assert(I->second <= CleanupEntries.size() && "Invalid branch fixup!");
Mike Stump11289f42009-09-09 15:08:12 +0000635
Anders Carlssonf57b9ee2009-02-08 22:45:15 +0000636 if (I->second == CleanupEntries.size()) {
637 // We don't need to do this branch fixup.
638 BranchFixups[i] = BranchFixups.back();
639 BranchFixups.pop_back();
640 i--;
641 e--;
642 continue;
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000643 }
644 }
Mike Stump11289f42009-09-09 15:08:12 +0000645
Anders Carlsson66c384a2009-02-08 07:46:24 +0000646 llvm::BasicBlock *SwitchBlock = 0;
647 llvm::BasicBlock *EndBlock = 0;
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000648 if (!BranchFixups.empty()) {
Anders Carlsson66c384a2009-02-08 07:46:24 +0000649 SwitchBlock = createBasicBlock("cleanup.switch");
650 EndBlock = createBasicBlock("cleanup.end");
Mike Stump11289f42009-09-09 15:08:12 +0000651
Anders Carlsson66c384a2009-02-08 07:46:24 +0000652 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
Mike Stump11289f42009-09-09 15:08:12 +0000653
Anders Carlsson66c384a2009-02-08 07:46:24 +0000654 Builder.SetInsertPoint(SwitchBlock);
655
Mike Stump11289f42009-09-09 15:08:12 +0000656 llvm::Value *DestCodePtr = CreateTempAlloca(llvm::Type::getInt32Ty(VMContext),
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000657 "cleanup.dst");
658 llvm::Value *DestCode = Builder.CreateLoad(DestCodePtr, "tmp");
Mike Stump11289f42009-09-09 15:08:12 +0000659
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000660 // Create a switch instruction to determine where to jump next.
Mike Stump11289f42009-09-09 15:08:12 +0000661 llvm::SwitchInst *SI = Builder.CreateSwitch(DestCode, EndBlock,
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000662 BranchFixups.size());
Anders Carlsson66c384a2009-02-08 07:46:24 +0000663
Anders Carlsson76180ea2009-02-08 22:13:37 +0000664 // Restore the current basic block (if any)
Anders Carlssone73e3ec2009-03-17 05:53:35 +0000665 if (CurBB) {
Anders Carlsson76180ea2009-02-08 22:13:37 +0000666 Builder.SetInsertPoint(CurBB);
Mike Stump11289f42009-09-09 15:08:12 +0000667
Anders Carlssone73e3ec2009-03-17 05:53:35 +0000668 // If we had a current basic block, we also need to emit an instruction
669 // to initialize the cleanup destination.
Owen Anderson41a75022009-08-13 21:57:51 +0000670 Builder.CreateStore(llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)),
Anders Carlssone73e3ec2009-03-17 05:53:35 +0000671 DestCodePtr);
672 } else
Anders Carlsson76180ea2009-02-08 22:13:37 +0000673 Builder.ClearInsertionPoint();
Anders Carlsson66c384a2009-02-08 07:46:24 +0000674
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000675 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
676 llvm::BranchInst *BI = BranchFixups[i];
677 llvm::BasicBlock *Dest = BI->getSuccessor(0);
Mike Stump11289f42009-09-09 15:08:12 +0000678
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000679 // Fixup the branch instruction to point to the cleanup block.
680 BI->setSuccessor(0, CleanupBlock);
Mike Stump11289f42009-09-09 15:08:12 +0000681
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000682 if (CleanupEntries.empty()) {
Anders Carlsson9c964ac2009-02-08 22:46:50 +0000683 llvm::ConstantInt *ID;
Mike Stump11289f42009-09-09 15:08:12 +0000684
Anders Carlsson9c964ac2009-02-08 22:46:50 +0000685 // Check if we already have a destination for this block.
686 if (Dest == SI->getDefaultDest())
Owen Anderson41a75022009-08-13 21:57:51 +0000687 ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0);
Anders Carlsson9c964ac2009-02-08 22:46:50 +0000688 else {
689 ID = SI->findCaseDest(Dest);
690 if (!ID) {
691 // No code found, get a new unique one by using the number of
692 // switch successors.
Mike Stump11289f42009-09-09 15:08:12 +0000693 ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anders Carlsson9c964ac2009-02-08 22:46:50 +0000694 SI->getNumSuccessors());
695 SI->addCase(ID, Dest);
696 }
697 }
Mike Stump11289f42009-09-09 15:08:12 +0000698
Anders Carlsson9c964ac2009-02-08 22:46:50 +0000699 // Store the jump destination before the branch instruction.
700 new llvm::StoreInst(ID, DestCodePtr, BI);
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000701 } else {
702 // We need to jump through another cleanup block. Create a pad block
703 // with a branch instruction that jumps to the final destination and
704 // add it as a branch fixup to the current cleanup scope.
Mike Stump11289f42009-09-09 15:08:12 +0000705
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000706 // Create the pad block.
707 llvm::BasicBlock *CleanupPad = createBasicBlock("cleanup.pad", CurFn);
Anders Carlsson9c964ac2009-02-08 22:46:50 +0000708
709 // Create a unique case ID.
Mike Stump11289f42009-09-09 15:08:12 +0000710 llvm::ConstantInt *ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anders Carlsson9c964ac2009-02-08 22:46:50 +0000711 SI->getNumSuccessors());
712
713 // Store the jump destination before the branch instruction.
714 new llvm::StoreInst(ID, DestCodePtr, BI);
715
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000716 // Add it as the destination.
Anders Carlsson9c964ac2009-02-08 22:46:50 +0000717 SI->addCase(ID, CleanupPad);
Mike Stump11289f42009-09-09 15:08:12 +0000718
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000719 // Create the branch to the final destination.
720 llvm::BranchInst *BI = llvm::BranchInst::Create(Dest);
721 CleanupPad->getInstList().push_back(BI);
Mike Stump11289f42009-09-09 15:08:12 +0000722
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000723 // And add it as a branch fixup.
724 CleanupEntries.back().BranchFixups.push_back(BI);
725 }
726 }
727 }
Mike Stump11289f42009-09-09 15:08:12 +0000728
Anders Carlssonfbfb5e62009-02-08 00:16:35 +0000729 // Remove all blocks from the block scope map.
730 for (size_t i = 0, e = Blocks.size(); i != e; ++i) {
731 assert(BlockScopes.count(Blocks[i]) &&
732 "Did not find block in scope map!");
Mike Stump11289f42009-09-09 15:08:12 +0000733
Anders Carlssonfbfb5e62009-02-08 00:16:35 +0000734 BlockScopes.erase(Blocks[i]);
735 }
Mike Stump11289f42009-09-09 15:08:12 +0000736
Anders Carlsson66c384a2009-02-08 07:46:24 +0000737 return CleanupBlockInfo(CleanupBlock, SwitchBlock, EndBlock);
Anders Carlssonae91d9b2009-02-08 03:55:35 +0000738}
739
Mike Stump11289f42009-09-09 15:08:12 +0000740void CodeGenFunction::EmitCleanupBlock() {
Anders Carlsson66c384a2009-02-08 07:46:24 +0000741 CleanupBlockInfo Info = PopCleanupBlock();
Mike Stump11289f42009-09-09 15:08:12 +0000742
Anders Carlssonf3f91ce2009-05-31 00:33:20 +0000743 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
Mike Stump11289f42009-09-09 15:08:12 +0000744 if (CurBB && !CurBB->getTerminator() &&
Anders Carlssonf3f91ce2009-05-31 00:33:20 +0000745 Info.CleanupBlock->getNumUses() == 0) {
746 CurBB->getInstList().splice(CurBB->end(), Info.CleanupBlock->getInstList());
747 delete Info.CleanupBlock;
Mike Stump11289f42009-09-09 15:08:12 +0000748 } else
Anders Carlssonf3f91ce2009-05-31 00:33:20 +0000749 EmitBlock(Info.CleanupBlock);
Mike Stump11289f42009-09-09 15:08:12 +0000750
Anders Carlsson66c384a2009-02-08 07:46:24 +0000751 if (Info.SwitchBlock)
752 EmitBlock(Info.SwitchBlock);
753 if (Info.EndBlock)
754 EmitBlock(Info.EndBlock);
Anders Carlssonae91d9b2009-02-08 03:55:35 +0000755}
756
Mike Stump11289f42009-09-09 15:08:12 +0000757void CodeGenFunction::AddBranchFixup(llvm::BranchInst *BI) {
758 assert(!CleanupEntries.empty() &&
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000759 "Trying to add branch fixup without cleanup block!");
Mike Stump11289f42009-09-09 15:08:12 +0000760
Mike Stump18bb9282009-05-16 07:57:57 +0000761 // FIXME: We could be more clever here and check if there's already a branch
762 // fixup for this destination and recycle it.
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000763 CleanupEntries.back().BranchFixups.push_back(BI);
764}
765
Mike Stump11289f42009-09-09 15:08:12 +0000766void CodeGenFunction::EmitBranchThroughCleanup(llvm::BasicBlock *Dest) {
Anders Carlsson76180ea2009-02-08 22:13:37 +0000767 if (!HaveInsertPoint())
768 return;
Mike Stump11289f42009-09-09 15:08:12 +0000769
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000770 llvm::BranchInst* BI = Builder.CreateBr(Dest);
Mike Stump11289f42009-09-09 15:08:12 +0000771
Anders Carlsson76180ea2009-02-08 22:13:37 +0000772 Builder.ClearInsertionPoint();
Mike Stump11289f42009-09-09 15:08:12 +0000773
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000774 // The stack is empty, no need to do any cleanup.
775 if (CleanupEntries.empty())
776 return;
Mike Stump11289f42009-09-09 15:08:12 +0000777
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000778 if (!Dest->getParent()) {
779 // We are trying to branch to a block that hasn't been inserted yet.
780 AddBranchFixup(BI);
781 return;
782 }
Mike Stump11289f42009-09-09 15:08:12 +0000783
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000784 BlockScopeMap::iterator I = BlockScopes.find(Dest);
785 if (I == BlockScopes.end()) {
786 // We are trying to jump to a block that is outside of any cleanup scope.
787 AddBranchFixup(BI);
788 return;
789 }
Mike Stump11289f42009-09-09 15:08:12 +0000790
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000791 assert(I->second < CleanupEntries.size() &&
792 "Trying to branch into cleanup region");
Mike Stump11289f42009-09-09 15:08:12 +0000793
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000794 if (I->second == CleanupEntries.size() - 1) {
795 // We have a branch to a block in the same scope.
796 return;
797 }
Mike Stump11289f42009-09-09 15:08:12 +0000798
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000799 AddBranchFixup(BI);
800}