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