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 
181       // FIXME: Remove unnecessary conversion to std::string when API settles.
182       DI->EmitFunctionStart(std::string(Fn->getName()).c_str(),
183                             RetTy, CurFn, Builder);
184     }
185   }
186 
187   // FIXME: Leaked.
188   CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args);
189   EmitFunctionProlog(*CurFnInfo, CurFn, Args);
190 
191   // 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   }
200 }
201 
202 void CodeGenFunction::GenerateCode(const FunctionDecl *FD,
203                                    llvm::Function *Fn) {
204   // Check if we should generate debug info for this function.
205   if (CGM.getDebugInfo() && !FD->hasAttr<NodebugAttr>())
206     DebugInfo = CGM.getDebugInfo();
207 
208   FunctionArgList Args;
209 
210   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
211     if (MD->isInstance()) {
212       // Create the implicit 'this' decl.
213       // FIXME: I'm not entirely sure I like using a fake decl just for code
214       // generation. Maybe we can come up with a better way?
215       CXXThisDecl = ImplicitParamDecl::Create(getContext(), 0, SourceLocation(),
216                                               &getContext().Idents.get("this"),
217                                               MD->getThisType(getContext()));
218       Args.push_back(std::make_pair(CXXThisDecl, CXXThisDecl->getType()));
219     }
220   }
221 
222   if (FD->getNumParams()) {
223     const FunctionProtoType* FProto = FD->getType()->getAsFunctionProtoType();
224     assert(FProto && "Function def must have prototype!");
225 
226     for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
227       Args.push_back(std::make_pair(FD->getParamDecl(i),
228                                     FProto->getArgType(i)));
229   }
230 
231   // FIXME: Support CXXTryStmt here, too.
232   if (const CompoundStmt *S = FD->getCompoundBody()) {
233     StartFunction(FD, FD->getResultType(), Fn, Args, S->getLBracLoc());
234     if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
235       EmitCtorPrologue(CD);
236     EmitStmt(S);
237     FinishFunction(S->getRBracLoc());
238   }
239 
240   // Destroy the 'this' declaration.
241   if (CXXThisDecl)
242     CXXThisDecl->Destroy(getContext());
243 }
244 
245 /// ContainsLabel - Return true if the statement contains a label in it.  If
246 /// this statement is not executed normally, it not containing a label means
247 /// that we can just remove the code.
248 bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
249   // Null statement, not a label!
250   if (S == 0) return false;
251 
252   // If this is a label, we have to emit the code, consider something like:
253   // if (0) {  ...  foo:  bar(); }  goto foo;
254   if (isa<LabelStmt>(S))
255     return true;
256 
257   // If this is a case/default statement, and we haven't seen a switch, we have
258   // to emit the code.
259   if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
260     return true;
261 
262   // If this is a switch statement, we want to ignore cases below it.
263   if (isa<SwitchStmt>(S))
264     IgnoreCaseStmts = true;
265 
266   // Scan subexpressions for verboten labels.
267   for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
268        I != E; ++I)
269     if (ContainsLabel(*I, IgnoreCaseStmts))
270       return true;
271 
272   return false;
273 }
274 
275 
276 /// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
277 /// a constant, or if it does but contains a label, return 0.  If it constant
278 /// folds to 'true' and does not contain a label, return 1, if it constant folds
279 /// to 'false' and does not contain a label, return -1.
280 int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
281   // FIXME: Rename and handle conversion of other evaluatable things
282   // to bool.
283   Expr::EvalResult Result;
284   if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
285       Result.HasSideEffects)
286     return 0;  // Not foldable, not integer or not fully evaluatable.
287 
288   if (CodeGenFunction::ContainsLabel(Cond))
289     return 0;  // Contains a label.
290 
291   return Result.Val.getInt().getBoolValue() ? 1 : -1;
292 }
293 
294 
295 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
296 /// statement) to the specified blocks.  Based on the condition, this might try
297 /// to simplify the codegen of the conditional based on the branch.
298 ///
299 void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
300                                            llvm::BasicBlock *TrueBlock,
301                                            llvm::BasicBlock *FalseBlock) {
302   if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
303     return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
304 
305   if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
306     // Handle X && Y in a condition.
307     if (CondBOp->getOpcode() == BinaryOperator::LAnd) {
308       // If we have "1 && X", simplify the code.  "0 && X" would have constant
309       // folded if the case was simple enough.
310       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
311         // br(1 && X) -> br(X).
312         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
313       }
314 
315       // If we have "X && 1", simplify the code to use an uncond branch.
316       // "X && 0" would have been constant folded to 0.
317       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
318         // br(X && 1) -> br(X).
319         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
320       }
321 
322       // Emit the LHS as a conditional.  If the LHS conditional is false, we
323       // want to jump to the FalseBlock.
324       llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
325       EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
326       EmitBlock(LHSTrue);
327 
328       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
329       return;
330     } else if (CondBOp->getOpcode() == BinaryOperator::LOr) {
331       // If we have "0 || X", simplify the code.  "1 || X" would have constant
332       // folded if the case was simple enough.
333       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
334         // br(0 || X) -> br(X).
335         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
336       }
337 
338       // If we have "X || 0", simplify the code to use an uncond branch.
339       // "X || 1" would have been constant folded to 1.
340       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
341         // br(X || 0) -> br(X).
342         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
343       }
344 
345       // Emit the LHS as a conditional.  If the LHS conditional is true, we
346       // want to jump to the TrueBlock.
347       llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
348       EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
349       EmitBlock(LHSFalse);
350 
351       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
352       return;
353     }
354   }
355 
356   if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
357     // br(!x, t, f) -> br(x, f, t)
358     if (CondUOp->getOpcode() == UnaryOperator::LNot)
359       return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
360   }
361 
362   if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
363     // Handle ?: operator.
364 
365     // Just ignore GNU ?: extension.
366     if (CondOp->getLHS()) {
367       // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
368       llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
369       llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
370       EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
371       EmitBlock(LHSBlock);
372       EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
373       EmitBlock(RHSBlock);
374       EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
375       return;
376     }
377   }
378 
379   // Emit the code with the fully general case.
380   llvm::Value *CondV = EvaluateExprAsBool(Cond);
381   Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
382 }
383 
384 /// getCGRecordLayout - Return record layout info.
385 const CGRecordLayout *CodeGenFunction::getCGRecordLayout(CodeGenTypes &CGT,
386                                                          QualType Ty) {
387   const RecordType *RTy = Ty->getAsRecordType();
388   assert (RTy && "Unexpected type. RecordType expected here.");
389 
390   return CGT.getCGRecordLayout(RTy->getDecl());
391 }
392 
393 /// ErrorUnsupported - Print out an error that codegen doesn't support the
394 /// specified stmt yet.
395 void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
396                                        bool OmitOnError) {
397   CGM.ErrorUnsupported(S, Type, OmitOnError);
398 }
399 
400 unsigned CodeGenFunction::GetIDForAddrOfLabel(const LabelStmt *L) {
401   // Use LabelIDs.size() as the new ID if one hasn't been assigned.
402   return LabelIDs.insert(std::make_pair(L, LabelIDs.size())).first->second;
403 }
404 
405 void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty) {
406   const llvm::Type *BP = VMContext.getPointerTypeUnqual(llvm::Type::Int8Ty);
407   if (DestPtr->getType() != BP)
408     DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
409 
410   // Get size and alignment info for this aggregate.
411   std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
412 
413   // Don't bother emitting a zero-byte memset.
414   if (TypeInfo.first == 0)
415     return;
416 
417   // FIXME: Handle variable sized types.
418   const llvm::Type *IntPtr = VMContext.getIntegerType(LLVMPointerWidth);
419 
420   Builder.CreateCall4(CGM.getMemSetFn(), DestPtr,
421                       getLLVMContext().getNullValue(llvm::Type::Int8Ty),
422                       // TypeInfo.first describes size in bits.
423                       llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
424                       llvm::ConstantInt::get(llvm::Type::Int32Ty,
425                                              TypeInfo.second/8));
426 }
427 
428 void CodeGenFunction::EmitIndirectSwitches() {
429   llvm::BasicBlock *Default;
430 
431   if (IndirectSwitches.empty())
432     return;
433 
434   if (!LabelIDs.empty()) {
435     Default = getBasicBlockForLabel(LabelIDs.begin()->first);
436   } else {
437     // No possible targets for indirect goto, just emit an infinite
438     // loop.
439     Default = createBasicBlock("indirectgoto.loop", CurFn);
440     llvm::BranchInst::Create(Default, Default);
441   }
442 
443   for (std::vector<llvm::SwitchInst*>::iterator i = IndirectSwitches.begin(),
444          e = IndirectSwitches.end(); i != e; ++i) {
445     llvm::SwitchInst *I = *i;
446 
447     I->setSuccessor(0, Default);
448     for (std::map<const LabelStmt*,unsigned>::iterator LI = LabelIDs.begin(),
449            LE = LabelIDs.end(); LI != LE; ++LI) {
450       I->addCase(llvm::ConstantInt::get(llvm::Type::Int32Ty,
451                                         LI->second),
452                  getBasicBlockForLabel(LI->first));
453     }
454   }
455 }
456 
457 llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) {
458   llvm::Value *&SizeEntry = VLASizeMap[VAT];
459 
460   assert(SizeEntry && "Did not emit size for type");
461   return SizeEntry;
462 }
463 
464 llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) {
465   assert(Ty->isVariablyModifiedType() &&
466          "Must pass variably modified type to EmitVLASizes!");
467 
468   EnsureInsertPoint();
469 
470   if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
471     llvm::Value *&SizeEntry = VLASizeMap[VAT];
472 
473     if (!SizeEntry) {
474       // Get the element size;
475       llvm::Value *ElemSize;
476 
477       QualType ElemTy = VAT->getElementType();
478 
479       const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
480 
481       if (ElemTy->isVariableArrayType())
482         ElemSize = EmitVLASize(ElemTy);
483       else {
484         ElemSize = llvm::ConstantInt::get(SizeTy,
485                                           getContext().getTypeSize(ElemTy) / 8);
486       }
487 
488       llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
489       NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
490 
491       SizeEntry = Builder.CreateMul(ElemSize, NumElements);
492     }
493 
494     return SizeEntry;
495   } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
496     EmitVLASize(AT->getElementType());
497   } else if (const PointerType *PT = Ty->getAsPointerType())
498     EmitVLASize(PT->getPointeeType());
499   else {
500     assert(0 && "unknown VM type!");
501   }
502 
503   return 0;
504 }
505 
506 llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
507   if (CGM.getContext().getBuiltinVaListType()->isArrayType()) {
508     return EmitScalarExpr(E);
509   }
510   return EmitLValue(E).getAddress();
511 }
512 
513 void CodeGenFunction::PushCleanupBlock(llvm::BasicBlock *CleanupBlock)
514 {
515   CleanupEntries.push_back(CleanupEntry(CleanupBlock));
516 }
517 
518 void CodeGenFunction::EmitCleanupBlocks(size_t OldCleanupStackSize)
519 {
520   assert(CleanupEntries.size() >= OldCleanupStackSize &&
521          "Cleanup stack mismatch!");
522 
523   while (CleanupEntries.size() > OldCleanupStackSize)
524     EmitCleanupBlock();
525 }
526 
527 CodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock()
528 {
529   CleanupEntry &CE = CleanupEntries.back();
530 
531   llvm::BasicBlock *CleanupBlock = CE.CleanupBlock;
532 
533   std::vector<llvm::BasicBlock *> Blocks;
534   std::swap(Blocks, CE.Blocks);
535 
536   std::vector<llvm::BranchInst *> BranchFixups;
537   std::swap(BranchFixups, CE.BranchFixups);
538 
539   CleanupEntries.pop_back();
540 
541   // Check if any branch fixups pointed to the scope we just popped. If so,
542   // we can remove them.
543   for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
544     llvm::BasicBlock *Dest = BranchFixups[i]->getSuccessor(0);
545     BlockScopeMap::iterator I = BlockScopes.find(Dest);
546 
547     if (I == BlockScopes.end())
548       continue;
549 
550     assert(I->second <= CleanupEntries.size() && "Invalid branch fixup!");
551 
552     if (I->second == CleanupEntries.size()) {
553       // We don't need to do this branch fixup.
554       BranchFixups[i] = BranchFixups.back();
555       BranchFixups.pop_back();
556       i--;
557       e--;
558       continue;
559     }
560   }
561 
562   llvm::BasicBlock *SwitchBlock = 0;
563   llvm::BasicBlock *EndBlock = 0;
564   if (!BranchFixups.empty()) {
565     SwitchBlock = createBasicBlock("cleanup.switch");
566     EndBlock = createBasicBlock("cleanup.end");
567 
568     llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
569 
570     Builder.SetInsertPoint(SwitchBlock);
571 
572     llvm::Value *DestCodePtr = CreateTempAlloca(llvm::Type::Int32Ty,
573                                                 "cleanup.dst");
574     llvm::Value *DestCode = Builder.CreateLoad(DestCodePtr, "tmp");
575 
576     // Create a switch instruction to determine where to jump next.
577     llvm::SwitchInst *SI = Builder.CreateSwitch(DestCode, EndBlock,
578                                                 BranchFixups.size());
579 
580     // Restore the current basic block (if any)
581     if (CurBB) {
582       Builder.SetInsertPoint(CurBB);
583 
584       // If we had a current basic block, we also need to emit an instruction
585       // to initialize the cleanup destination.
586       Builder.CreateStore(getLLVMContext().getNullValue(llvm::Type::Int32Ty),
587                           DestCodePtr);
588     } else
589       Builder.ClearInsertionPoint();
590 
591     for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
592       llvm::BranchInst *BI = BranchFixups[i];
593       llvm::BasicBlock *Dest = BI->getSuccessor(0);
594 
595       // Fixup the branch instruction to point to the cleanup block.
596       BI->setSuccessor(0, CleanupBlock);
597 
598       if (CleanupEntries.empty()) {
599         llvm::ConstantInt *ID;
600 
601         // Check if we already have a destination for this block.
602         if (Dest == SI->getDefaultDest())
603           ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
604         else {
605           ID = SI->findCaseDest(Dest);
606           if (!ID) {
607             // No code found, get a new unique one by using the number of
608             // switch successors.
609             ID = llvm::ConstantInt::get(llvm::Type::Int32Ty,
610                                         SI->getNumSuccessors());
611             SI->addCase(ID, Dest);
612           }
613         }
614 
615         // Store the jump destination before the branch instruction.
616         new llvm::StoreInst(ID, DestCodePtr, BI);
617       } else {
618         // We need to jump through another cleanup block. Create a pad block
619         // with a branch instruction that jumps to the final destination and
620         // add it as a branch fixup to the current cleanup scope.
621 
622         // Create the pad block.
623         llvm::BasicBlock *CleanupPad = createBasicBlock("cleanup.pad", CurFn);
624 
625         // Create a unique case ID.
626         llvm::ConstantInt *ID = llvm::ConstantInt::get(llvm::Type::Int32Ty,
627                                                        SI->getNumSuccessors());
628 
629         // Store the jump destination before the branch instruction.
630         new llvm::StoreInst(ID, DestCodePtr, BI);
631 
632         // Add it as the destination.
633         SI->addCase(ID, CleanupPad);
634 
635         // Create the branch to the final destination.
636         llvm::BranchInst *BI = llvm::BranchInst::Create(Dest);
637         CleanupPad->getInstList().push_back(BI);
638 
639         // And add it as a branch fixup.
640         CleanupEntries.back().BranchFixups.push_back(BI);
641       }
642     }
643   }
644 
645   // Remove all blocks from the block scope map.
646   for (size_t i = 0, e = Blocks.size(); i != e; ++i) {
647     assert(BlockScopes.count(Blocks[i]) &&
648            "Did not find block in scope map!");
649 
650     BlockScopes.erase(Blocks[i]);
651   }
652 
653   return CleanupBlockInfo(CleanupBlock, SwitchBlock, EndBlock);
654 }
655 
656 void CodeGenFunction::EmitCleanupBlock()
657 {
658   CleanupBlockInfo Info = PopCleanupBlock();
659 
660   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
661   if (CurBB && !CurBB->getTerminator() &&
662       Info.CleanupBlock->getNumUses() == 0) {
663     CurBB->getInstList().splice(CurBB->end(), Info.CleanupBlock->getInstList());
664     delete Info.CleanupBlock;
665   } else
666     EmitBlock(Info.CleanupBlock);
667 
668   if (Info.SwitchBlock)
669     EmitBlock(Info.SwitchBlock);
670   if (Info.EndBlock)
671     EmitBlock(Info.EndBlock);
672 }
673 
674 void CodeGenFunction::AddBranchFixup(llvm::BranchInst *BI)
675 {
676   assert(!CleanupEntries.empty() &&
677          "Trying to add branch fixup without cleanup block!");
678 
679   // FIXME: We could be more clever here and check if there's already a branch
680   // fixup for this destination and recycle it.
681   CleanupEntries.back().BranchFixups.push_back(BI);
682 }
683 
684 void CodeGenFunction::EmitBranchThroughCleanup(llvm::BasicBlock *Dest)
685 {
686   if (!HaveInsertPoint())
687     return;
688 
689   llvm::BranchInst* BI = Builder.CreateBr(Dest);
690 
691   Builder.ClearInsertionPoint();
692 
693   // The stack is empty, no need to do any cleanup.
694   if (CleanupEntries.empty())
695     return;
696 
697   if (!Dest->getParent()) {
698     // We are trying to branch to a block that hasn't been inserted yet.
699     AddBranchFixup(BI);
700     return;
701   }
702 
703   BlockScopeMap::iterator I = BlockScopes.find(Dest);
704   if (I == BlockScopes.end()) {
705     // We are trying to jump to a block that is outside of any cleanup scope.
706     AddBranchFixup(BI);
707     return;
708   }
709 
710   assert(I->second < CleanupEntries.size() &&
711          "Trying to branch into cleanup region");
712 
713   if (I->second == CleanupEntries.size() - 1) {
714     // We have a branch to a block in the same scope.
715     return;
716   }
717 
718   AddBranchFixup(BI);
719 }
720