1 //===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This coordinates the per-function state used while generating code.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CodeGenFunction.h"
15 #include "CodeGenModule.h"
16 #include "CGDebugInfo.h"
17 #include "clang/Basic/TargetInfo.h"
18 #include "clang/AST/APValue.h"
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/Decl.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "llvm/Target/TargetData.h"
23 using namespace clang;
24 using namespace CodeGen;
25 
26 CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
27   : BlockFunction(cgm, *this, Builder), CGM(cgm),
28     Target(CGM.getContext().Target),
29     Builder(cgm.getModule().getContext()),
30     DebugInfo(0), SwitchInsn(0), CaseRangeBlock(0), InvokeDest(0),
31     CXXThisDecl(0) {
32   LLVMIntTy = ConvertType(getContext().IntTy);
33   LLVMPointerWidth = Target.getPointerWidth(0);
34 }
35 
36 ASTContext &CodeGenFunction::getContext() const {
37   return CGM.getContext();
38 }
39 
40 
41 llvm::BasicBlock *CodeGenFunction::getBasicBlockForLabel(const LabelStmt *S) {
42   llvm::BasicBlock *&BB = LabelMap[S];
43   if (BB) return BB;
44 
45   // Create, but don't insert, the new block.
46   return BB = createBasicBlock(S->getName());
47 }
48 
49 llvm::Value *CodeGenFunction::GetAddrOfLocalVar(const VarDecl *VD) {
50   llvm::Value *Res = LocalDeclMap[VD];
51   assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!");
52   return Res;
53 }
54 
55 llvm::Constant *
56 CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) {
57   return cast<llvm::Constant>(GetAddrOfLocalVar(BVD));
58 }
59 
60 const llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
61   return CGM.getTypes().ConvertTypeForMem(T);
62 }
63 
64 const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
65   return CGM.getTypes().ConvertType(T);
66 }
67 
68 bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
69   // FIXME: Use positive checks instead of negative ones to be more robust in
70   // the face of extension.
71   return !T->hasPointerRepresentation() &&!T->isRealType() &&
72     !T->isVoidType() && !T->isVectorType() && !T->isFunctionType() &&
73     !T->isBlockPointerType();
74 }
75 
76 void CodeGenFunction::EmitReturnBlock() {
77   // For cleanliness, we try to avoid emitting the return block for
78   // simple cases.
79   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
80 
81   if (CurBB) {
82     assert(!CurBB->getTerminator() && "Unexpected terminated block.");
83 
84     // We have a valid insert point, reuse it if it is empty or there are no
85     // explicit jumps to the return block.
86     if (CurBB->empty() || ReturnBlock->use_empty()) {
87       ReturnBlock->replaceAllUsesWith(CurBB);
88       delete ReturnBlock;
89     } else
90       EmitBlock(ReturnBlock);
91     return;
92   }
93 
94   // Otherwise, if the return block is the target of a single direct
95   // branch then we can just put the code in that block instead. This
96   // cleans up functions which started with a unified return block.
97   if (ReturnBlock->hasOneUse()) {
98     llvm::BranchInst *BI =
99       dyn_cast<llvm::BranchInst>(*ReturnBlock->use_begin());
100     if (BI && BI->isUnconditional() && BI->getSuccessor(0) == ReturnBlock) {
101       // Reset insertion point and delete the branch.
102       Builder.SetInsertPoint(BI->getParent());
103       BI->eraseFromParent();
104       delete ReturnBlock;
105       return;
106     }
107   }
108 
109   // FIXME: We are at an unreachable point, there is no reason to emit the block
110   // unless it has uses. However, we still need a place to put the debug
111   // region.end for now.
112 
113   EmitBlock(ReturnBlock);
114 }
115 
116 void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
117   // Finish emission of indirect switches.
118   EmitIndirectSwitches();
119 
120   assert(BreakContinueStack.empty() &&
121          "mismatched push/pop in break/continue stack!");
122   assert(BlockScopes.empty() &&
123          "did not remove all blocks from block scope map!");
124   assert(CleanupEntries.empty() &&
125          "mismatched push/pop in cleanup stack!");
126 
127   // Emit function epilog (to return).
128   EmitReturnBlock();
129 
130   // Emit debug descriptor for function end.
131   if (CGDebugInfo *DI = getDebugInfo()) {
132     DI->setLocation(EndLoc);
133     DI->EmitRegionEnd(CurFn, Builder);
134   }
135 
136   EmitFunctionEpilog(*CurFnInfo, ReturnValue);
137 
138   // Remove the AllocaInsertPt instruction, which is just a convenience for us.
139   llvm::Instruction *Ptr = AllocaInsertPt;
140   AllocaInsertPt = 0;
141   Ptr->eraseFromParent();
142 }
143 
144 void CodeGenFunction::StartFunction(const Decl *D, QualType RetTy,
145                                     llvm::Function *Fn,
146                                     const FunctionArgList &Args,
147                                     SourceLocation StartLoc) {
148   DidCallStackSave = false;
149   CurCodeDecl = CurFuncDecl = D;
150   FnRetTy = RetTy;
151   CurFn = Fn;
152   assert(CurFn->isDeclaration() && "Function already has body?");
153 
154   llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
155 
156   // Create a marker to make it easy to insert allocas into the entryblock
157   // later.  Don't create this with the builder, because we don't want it
158   // folded.
159   llvm::Value *Undef = VMContext.getUndef(llvm::Type::Int32Ty);
160   AllocaInsertPt = new llvm::BitCastInst(Undef, llvm::Type::Int32Ty, "",
161                                          EntryBB);
162   if (Builder.isNamePreserving())
163     AllocaInsertPt->setName("allocapt");
164 
165   ReturnBlock = createBasicBlock("return");
166   ReturnValue = 0;
167   if (!RetTy->isVoidType())
168     ReturnValue = CreateTempAlloca(ConvertType(RetTy), "retval");
169 
170   Builder.SetInsertPoint(EntryBB);
171 
172   // Emit subprogram debug descriptor.
173   // FIXME: The cast here is a huge hack.
174   if (CGDebugInfo *DI = getDebugInfo()) {
175     DI->setLocation(StartLoc);
176     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
177       DI->EmitFunctionStart(CGM.getMangledName(FD), RetTy, CurFn, Builder);
178     } else {
179       // Just use LLVM function name.
180       DI->EmitFunctionStart(Fn->getName().c_str(),
181                             RetTy, CurFn, Builder);
182     }
183   }
184 
185   // FIXME: Leaked.
186   CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args);
187   EmitFunctionProlog(*CurFnInfo, CurFn, Args);
188 
189   // If any of the arguments have a variably modified type, make sure to
190   // emit the type size.
191   for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
192        i != e; ++i) {
193     QualType Ty = i->second;
194 
195     if (Ty->isVariablyModifiedType())
196       EmitVLASize(Ty);
197   }
198 }
199 
200 void CodeGenFunction::GenerateCode(const FunctionDecl *FD,
201                                    llvm::Function *Fn) {
202   // Check if we should generate debug info for this function.
203   if (CGM.getDebugInfo() && !FD->hasAttr<NodebugAttr>())
204     DebugInfo = CGM.getDebugInfo();
205 
206   FunctionArgList Args;
207 
208   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
209     if (MD->isInstance()) {
210       // Create the implicit 'this' decl.
211       // FIXME: I'm not entirely sure I like using a fake decl just for code
212       // generation. Maybe we can come up with a better way?
213       CXXThisDecl = ImplicitParamDecl::Create(getContext(), 0, SourceLocation(),
214                                               &getContext().Idents.get("this"),
215                                               MD->getThisType(getContext()));
216       Args.push_back(std::make_pair(CXXThisDecl, CXXThisDecl->getType()));
217     }
218   }
219 
220   if (FD->getNumParams()) {
221     const FunctionProtoType* FProto = FD->getType()->getAsFunctionProtoType();
222     assert(FProto && "Function def must have prototype!");
223 
224     for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
225       Args.push_back(std::make_pair(FD->getParamDecl(i),
226                                     FProto->getArgType(i)));
227   }
228 
229   // FIXME: Support CXXTryStmt here, too.
230   if (const CompoundStmt *S = FD->getCompoundBody()) {
231     StartFunction(FD, FD->getResultType(), Fn, Args, S->getLBracLoc());
232     if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
233       EmitCtorPrologue(CD);
234     EmitStmt(S);
235     FinishFunction(S->getRBracLoc());
236   }
237 
238   // Destroy the 'this' declaration.
239   if (CXXThisDecl)
240     CXXThisDecl->Destroy(getContext());
241 }
242 
243 /// ContainsLabel - Return true if the statement contains a label in it.  If
244 /// this statement is not executed normally, it not containing a label means
245 /// that we can just remove the code.
246 bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
247   // Null statement, not a label!
248   if (S == 0) return false;
249 
250   // If this is a label, we have to emit the code, consider something like:
251   // if (0) {  ...  foo:  bar(); }  goto foo;
252   if (isa<LabelStmt>(S))
253     return true;
254 
255   // If this is a case/default statement, and we haven't seen a switch, we have
256   // to emit the code.
257   if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
258     return true;
259 
260   // If this is a switch statement, we want to ignore cases below it.
261   if (isa<SwitchStmt>(S))
262     IgnoreCaseStmts = true;
263 
264   // Scan subexpressions for verboten labels.
265   for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
266        I != E; ++I)
267     if (ContainsLabel(*I, IgnoreCaseStmts))
268       return true;
269 
270   return false;
271 }
272 
273 
274 /// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
275 /// a constant, or if it does but contains a label, return 0.  If it constant
276 /// folds to 'true' and does not contain a label, return 1, if it constant folds
277 /// to 'false' and does not contain a label, return -1.
278 int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
279   // FIXME: Rename and handle conversion of other evaluatable things
280   // to bool.
281   Expr::EvalResult Result;
282   if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
283       Result.HasSideEffects)
284     return 0;  // Not foldable, not integer or not fully evaluatable.
285 
286   if (CodeGenFunction::ContainsLabel(Cond))
287     return 0;  // Contains a label.
288 
289   return Result.Val.getInt().getBoolValue() ? 1 : -1;
290 }
291 
292 
293 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
294 /// statement) to the specified blocks.  Based on the condition, this might try
295 /// to simplify the codegen of the conditional based on the branch.
296 ///
297 void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
298                                            llvm::BasicBlock *TrueBlock,
299                                            llvm::BasicBlock *FalseBlock) {
300   if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
301     return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
302 
303   if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
304     // Handle X && Y in a condition.
305     if (CondBOp->getOpcode() == BinaryOperator::LAnd) {
306       // If we have "1 && X", simplify the code.  "0 && X" would have constant
307       // folded if the case was simple enough.
308       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
309         // br(1 && X) -> br(X).
310         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
311       }
312 
313       // If we have "X && 1", simplify the code to use an uncond branch.
314       // "X && 0" would have been constant folded to 0.
315       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
316         // br(X && 1) -> br(X).
317         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
318       }
319 
320       // Emit the LHS as a conditional.  If the LHS conditional is false, we
321       // want to jump to the FalseBlock.
322       llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
323       EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
324       EmitBlock(LHSTrue);
325 
326       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
327       return;
328     } else if (CondBOp->getOpcode() == BinaryOperator::LOr) {
329       // If we have "0 || X", simplify the code.  "1 || X" would have constant
330       // folded if the case was simple enough.
331       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
332         // br(0 || X) -> br(X).
333         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
334       }
335 
336       // If we have "X || 0", simplify the code to use an uncond branch.
337       // "X || 1" would have been constant folded to 1.
338       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
339         // br(X || 0) -> br(X).
340         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
341       }
342 
343       // Emit the LHS as a conditional.  If the LHS conditional is true, we
344       // want to jump to the TrueBlock.
345       llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
346       EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
347       EmitBlock(LHSFalse);
348 
349       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
350       return;
351     }
352   }
353 
354   if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
355     // br(!x, t, f) -> br(x, f, t)
356     if (CondUOp->getOpcode() == UnaryOperator::LNot)
357       return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
358   }
359 
360   if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
361     // Handle ?: operator.
362 
363     // Just ignore GNU ?: extension.
364     if (CondOp->getLHS()) {
365       // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
366       llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
367       llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
368       EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
369       EmitBlock(LHSBlock);
370       EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
371       EmitBlock(RHSBlock);
372       EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
373       return;
374     }
375   }
376 
377   // Emit the code with the fully general case.
378   llvm::Value *CondV = EvaluateExprAsBool(Cond);
379   Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
380 }
381 
382 /// getCGRecordLayout - Return record layout info.
383 const CGRecordLayout *CodeGenFunction::getCGRecordLayout(CodeGenTypes &CGT,
384                                                          QualType Ty) {
385   const RecordType *RTy = Ty->getAsRecordType();
386   assert (RTy && "Unexpected type. RecordType expected here.");
387 
388   return CGT.getCGRecordLayout(RTy->getDecl());
389 }
390 
391 /// ErrorUnsupported - Print out an error that codegen doesn't support the
392 /// specified stmt yet.
393 void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
394                                        bool OmitOnError) {
395   CGM.ErrorUnsupported(S, Type, OmitOnError);
396 }
397 
398 unsigned CodeGenFunction::GetIDForAddrOfLabel(const LabelStmt *L) {
399   // Use LabelIDs.size() as the new ID if one hasn't been assigned.
400   return LabelIDs.insert(std::make_pair(L, LabelIDs.size())).first->second;
401 }
402 
403 void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty) {
404   const llvm::Type *BP = VMContext.getPointerTypeUnqual(llvm::Type::Int8Ty);
405   if (DestPtr->getType() != BP)
406     DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
407 
408   // Get size and alignment info for this aggregate.
409   std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
410 
411   // Don't bother emitting a zero-byte memset.
412   if (TypeInfo.first == 0)
413     return;
414 
415   // FIXME: Handle variable sized types.
416   const llvm::Type *IntPtr = VMContext.getIntegerType(LLVMPointerWidth);
417 
418   Builder.CreateCall4(CGM.getMemSetFn(), DestPtr,
419                       getLLVMContext().getNullValue(llvm::Type::Int8Ty),
420                       // TypeInfo.first describes size in bits.
421                       VMContext.getConstantInt(IntPtr, TypeInfo.first/8),
422                       VMContext.getConstantInt(llvm::Type::Int32Ty,
423                                              TypeInfo.second/8));
424 }
425 
426 void CodeGenFunction::EmitIndirectSwitches() {
427   llvm::BasicBlock *Default;
428 
429   if (IndirectSwitches.empty())
430     return;
431 
432   if (!LabelIDs.empty()) {
433     Default = getBasicBlockForLabel(LabelIDs.begin()->first);
434   } else {
435     // No possible targets for indirect goto, just emit an infinite
436     // loop.
437     Default = createBasicBlock("indirectgoto.loop", CurFn);
438     llvm::BranchInst::Create(Default, Default);
439   }
440 
441   for (std::vector<llvm::SwitchInst*>::iterator i = IndirectSwitches.begin(),
442          e = IndirectSwitches.end(); i != e; ++i) {
443     llvm::SwitchInst *I = *i;
444 
445     I->setSuccessor(0, Default);
446     for (std::map<const LabelStmt*,unsigned>::iterator LI = LabelIDs.begin(),
447            LE = LabelIDs.end(); LI != LE; ++LI) {
448       I->addCase(VMContext.getConstantInt(llvm::Type::Int32Ty,
449                                         LI->second),
450                  getBasicBlockForLabel(LI->first));
451     }
452   }
453 }
454 
455 llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) {
456   llvm::Value *&SizeEntry = VLASizeMap[VAT];
457 
458   assert(SizeEntry && "Did not emit size for type");
459   return SizeEntry;
460 }
461 
462 llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) {
463   assert(Ty->isVariablyModifiedType() &&
464          "Must pass variably modified type to EmitVLASizes!");
465 
466   EnsureInsertPoint();
467 
468   if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
469     llvm::Value *&SizeEntry = VLASizeMap[VAT];
470 
471     if (!SizeEntry) {
472       // Get the element size;
473       llvm::Value *ElemSize;
474 
475       QualType ElemTy = VAT->getElementType();
476 
477       const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
478 
479       if (ElemTy->isVariableArrayType())
480         ElemSize = EmitVLASize(ElemTy);
481       else {
482         ElemSize = VMContext.getConstantInt(SizeTy,
483                                           getContext().getTypeSize(ElemTy) / 8);
484       }
485 
486       llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
487       NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
488 
489       SizeEntry = Builder.CreateMul(ElemSize, NumElements);
490     }
491 
492     return SizeEntry;
493   } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
494     EmitVLASize(AT->getElementType());
495   } else if (const PointerType *PT = Ty->getAsPointerType())
496     EmitVLASize(PT->getPointeeType());
497   else {
498     assert(0 && "unknown VM type!");
499   }
500 
501   return 0;
502 }
503 
504 llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
505   if (CGM.getContext().getBuiltinVaListType()->isArrayType()) {
506     return EmitScalarExpr(E);
507   }
508   return EmitLValue(E).getAddress();
509 }
510 
511 void CodeGenFunction::PushCleanupBlock(llvm::BasicBlock *CleanupBlock)
512 {
513   CleanupEntries.push_back(CleanupEntry(CleanupBlock));
514 }
515 
516 void CodeGenFunction::EmitCleanupBlocks(size_t OldCleanupStackSize)
517 {
518   assert(CleanupEntries.size() >= OldCleanupStackSize &&
519          "Cleanup stack mismatch!");
520 
521   while (CleanupEntries.size() > OldCleanupStackSize)
522     EmitCleanupBlock();
523 }
524 
525 CodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock()
526 {
527   CleanupEntry &CE = CleanupEntries.back();
528 
529   llvm::BasicBlock *CleanupBlock = CE.CleanupBlock;
530 
531   std::vector<llvm::BasicBlock *> Blocks;
532   std::swap(Blocks, CE.Blocks);
533 
534   std::vector<llvm::BranchInst *> BranchFixups;
535   std::swap(BranchFixups, CE.BranchFixups);
536 
537   CleanupEntries.pop_back();
538 
539   // Check if any branch fixups pointed to the scope we just popped. If so,
540   // we can remove them.
541   for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
542     llvm::BasicBlock *Dest = BranchFixups[i]->getSuccessor(0);
543     BlockScopeMap::iterator I = BlockScopes.find(Dest);
544 
545     if (I == BlockScopes.end())
546       continue;
547 
548     assert(I->second <= CleanupEntries.size() && "Invalid branch fixup!");
549 
550     if (I->second == CleanupEntries.size()) {
551       // We don't need to do this branch fixup.
552       BranchFixups[i] = BranchFixups.back();
553       BranchFixups.pop_back();
554       i--;
555       e--;
556       continue;
557     }
558   }
559 
560   llvm::BasicBlock *SwitchBlock = 0;
561   llvm::BasicBlock *EndBlock = 0;
562   if (!BranchFixups.empty()) {
563     SwitchBlock = createBasicBlock("cleanup.switch");
564     EndBlock = createBasicBlock("cleanup.end");
565 
566     llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
567 
568     Builder.SetInsertPoint(SwitchBlock);
569 
570     llvm::Value *DestCodePtr = CreateTempAlloca(llvm::Type::Int32Ty,
571                                                 "cleanup.dst");
572     llvm::Value *DestCode = Builder.CreateLoad(DestCodePtr, "tmp");
573 
574     // Create a switch instruction to determine where to jump next.
575     llvm::SwitchInst *SI = Builder.CreateSwitch(DestCode, EndBlock,
576                                                 BranchFixups.size());
577 
578     // Restore the current basic block (if any)
579     if (CurBB) {
580       Builder.SetInsertPoint(CurBB);
581 
582       // If we had a current basic block, we also need to emit an instruction
583       // to initialize the cleanup destination.
584       Builder.CreateStore(getLLVMContext().getNullValue(llvm::Type::Int32Ty),
585                           DestCodePtr);
586     } else
587       Builder.ClearInsertionPoint();
588 
589     for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
590       llvm::BranchInst *BI = BranchFixups[i];
591       llvm::BasicBlock *Dest = BI->getSuccessor(0);
592 
593       // Fixup the branch instruction to point to the cleanup block.
594       BI->setSuccessor(0, CleanupBlock);
595 
596       if (CleanupEntries.empty()) {
597         llvm::ConstantInt *ID;
598 
599         // Check if we already have a destination for this block.
600         if (Dest == SI->getDefaultDest())
601           ID = VMContext.getConstantInt(llvm::Type::Int32Ty, 0);
602         else {
603           ID = SI->findCaseDest(Dest);
604           if (!ID) {
605             // No code found, get a new unique one by using the number of
606             // switch successors.
607             ID = VMContext.getConstantInt(llvm::Type::Int32Ty,
608                                         SI->getNumSuccessors());
609             SI->addCase(ID, Dest);
610           }
611         }
612 
613         // Store the jump destination before the branch instruction.
614         new llvm::StoreInst(ID, DestCodePtr, BI);
615       } else {
616         // We need to jump through another cleanup block. Create a pad block
617         // with a branch instruction that jumps to the final destination and
618         // add it as a branch fixup to the current cleanup scope.
619 
620         // Create the pad block.
621         llvm::BasicBlock *CleanupPad = createBasicBlock("cleanup.pad", CurFn);
622 
623         // Create a unique case ID.
624         llvm::ConstantInt *ID = VMContext.getConstantInt(llvm::Type::Int32Ty,
625                                                        SI->getNumSuccessors());
626 
627         // Store the jump destination before the branch instruction.
628         new llvm::StoreInst(ID, DestCodePtr, BI);
629 
630         // Add it as the destination.
631         SI->addCase(ID, CleanupPad);
632 
633         // Create the branch to the final destination.
634         llvm::BranchInst *BI = llvm::BranchInst::Create(Dest);
635         CleanupPad->getInstList().push_back(BI);
636 
637         // And add it as a branch fixup.
638         CleanupEntries.back().BranchFixups.push_back(BI);
639       }
640     }
641   }
642 
643   // Remove all blocks from the block scope map.
644   for (size_t i = 0, e = Blocks.size(); i != e; ++i) {
645     assert(BlockScopes.count(Blocks[i]) &&
646            "Did not find block in scope map!");
647 
648     BlockScopes.erase(Blocks[i]);
649   }
650 
651   return CleanupBlockInfo(CleanupBlock, SwitchBlock, EndBlock);
652 }
653 
654 void CodeGenFunction::EmitCleanupBlock()
655 {
656   CleanupBlockInfo Info = PopCleanupBlock();
657 
658   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
659   if (CurBB && !CurBB->getTerminator() &&
660       Info.CleanupBlock->getNumUses() == 0) {
661     CurBB->getInstList().splice(CurBB->end(), Info.CleanupBlock->getInstList());
662     delete Info.CleanupBlock;
663   } else
664     EmitBlock(Info.CleanupBlock);
665 
666   if (Info.SwitchBlock)
667     EmitBlock(Info.SwitchBlock);
668   if (Info.EndBlock)
669     EmitBlock(Info.EndBlock);
670 }
671 
672 void CodeGenFunction::AddBranchFixup(llvm::BranchInst *BI)
673 {
674   assert(!CleanupEntries.empty() &&
675          "Trying to add branch fixup without cleanup block!");
676 
677   // FIXME: We could be more clever here and check if there's already a branch
678   // fixup for this destination and recycle it.
679   CleanupEntries.back().BranchFixups.push_back(BI);
680 }
681 
682 void CodeGenFunction::EmitBranchThroughCleanup(llvm::BasicBlock *Dest)
683 {
684   if (!HaveInsertPoint())
685     return;
686 
687   llvm::BranchInst* BI = Builder.CreateBr(Dest);
688 
689   Builder.ClearInsertionPoint();
690 
691   // The stack is empty, no need to do any cleanup.
692   if (CleanupEntries.empty())
693     return;
694 
695   if (!Dest->getParent()) {
696     // We are trying to branch to a block that hasn't been inserted yet.
697     AddBranchFixup(BI);
698     return;
699   }
700 
701   BlockScopeMap::iterator I = BlockScopes.find(Dest);
702   if (I == BlockScopes.end()) {
703     // We are trying to jump to a block that is outside of any cleanup scope.
704     AddBranchFixup(BI);
705     return;
706   }
707 
708   assert(I->second < CleanupEntries.size() &&
709          "Trying to branch into cleanup region");
710 
711   if (I->second == CleanupEntries.size() - 1) {
712     // We have a branch to a block in the same scope.
713     return;
714   }
715 
716   AddBranchFixup(BI);
717 }
718