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