xref: /llvm-project/clang/lib/CodeGen/CodeGenFunction.cpp (revision 468fa6366be872e9cbb687e1963a6bd4b9ce89ed)
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->getAttr<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   StartFunction(FD, FD->getResultType(), Fn, Args,
229                 cast<CompoundStmt>(FD->getBody())->getLBracLoc());
230 
231   EmitStmt(FD->getBody());
232 
233   const CompoundStmt *S = dyn_cast<CompoundStmt>(FD->getBody());
234   if (S) {
235     FinishFunction(S->getRBracLoc());
236   } else {
237     FinishFunction();
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 {
407   const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
408   if (DestPtr->getType() != BP)
409     DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
410 
411   // Get size and alignment info for this aggregate.
412   std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
413 
414   // FIXME: Handle variable sized types.
415   const llvm::Type *IntPtr = llvm::IntegerType::get(LLVMPointerWidth);
416 
417   Builder.CreateCall4(CGM.getMemSetFn(), DestPtr,
418                       llvm::ConstantInt::getNullValue(llvm::Type::Int8Ty),
419                       // TypeInfo.first describes size in bits.
420                       llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
421                       llvm::ConstantInt::get(llvm::Type::Int32Ty,
422                                              TypeInfo.second/8));
423 }
424 
425 void CodeGenFunction::EmitIndirectSwitches() {
426   llvm::BasicBlock *Default;
427 
428   if (IndirectSwitches.empty())
429     return;
430 
431   if (!LabelIDs.empty()) {
432     Default = getBasicBlockForLabel(LabelIDs.begin()->first);
433   } else {
434     // No possible targets for indirect goto, just emit an infinite
435     // loop.
436     Default = createBasicBlock("indirectgoto.loop", CurFn);
437     llvm::BranchInst::Create(Default, Default);
438   }
439 
440   for (std::vector<llvm::SwitchInst*>::iterator i = IndirectSwitches.begin(),
441          e = IndirectSwitches.end(); i != e; ++i) {
442     llvm::SwitchInst *I = *i;
443 
444     I->setSuccessor(0, Default);
445     for (std::map<const LabelStmt*,unsigned>::iterator LI = LabelIDs.begin(),
446            LE = LabelIDs.end(); LI != LE; ++LI) {
447       I->addCase(llvm::ConstantInt::get(llvm::Type::Int32Ty,
448                                         LI->second),
449                  getBasicBlockForLabel(LI->first));
450     }
451   }
452 }
453 
454 llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT)
455 {
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 {
464   assert(Ty->isVariablyModifiedType() &&
465          "Must pass variably modified type to EmitVLASizes!");
466 
467   if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
468     llvm::Value *&SizeEntry = VLASizeMap[VAT];
469 
470     if (!SizeEntry) {
471       // Get the element size;
472       llvm::Value *ElemSize;
473 
474       QualType ElemTy = VAT->getElementType();
475 
476       const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
477 
478       if (ElemTy->isVariableArrayType())
479         ElemSize = EmitVLASize(ElemTy);
480       else {
481         ElemSize = llvm::ConstantInt::get(SizeTy,
482                                           getContext().getTypeSize(ElemTy) / 8);
483       }
484 
485       llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
486       NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
487 
488       SizeEntry = Builder.CreateMul(ElemSize, NumElements);
489     }
490 
491     return SizeEntry;
492   } else if (const PointerType *PT = Ty->getAsPointerType())
493     EmitVLASize(PT->getPointeeType());
494   else {
495     assert(0 && "unknown VM type!");
496   }
497 
498   return 0;
499 }
500 
501 llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
502   if (CGM.getContext().getBuiltinVaListType()->isArrayType()) {
503     return EmitScalarExpr(E);
504   }
505   return EmitLValue(E).getAddress();
506 }
507 
508 void CodeGenFunction::PushCleanupBlock(llvm::BasicBlock *CleanupBlock)
509 {
510   CleanupEntries.push_back(CleanupEntry(CleanupBlock));
511 }
512 
513 void CodeGenFunction::EmitCleanupBlocks(size_t OldCleanupStackSize)
514 {
515   assert(CleanupEntries.size() >= OldCleanupStackSize &&
516          "Cleanup stack mismatch!");
517 
518   while (CleanupEntries.size() > OldCleanupStackSize)
519     EmitCleanupBlock();
520 }
521 
522 CodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock()
523 {
524   CleanupEntry &CE = CleanupEntries.back();
525 
526   llvm::BasicBlock *CleanupBlock = CE.CleanupBlock;
527 
528   std::vector<llvm::BasicBlock *> Blocks;
529   std::swap(Blocks, CE.Blocks);
530 
531   std::vector<llvm::BranchInst *> BranchFixups;
532   std::swap(BranchFixups, CE.BranchFixups);
533 
534   CleanupEntries.pop_back();
535 
536   // Check if any branch fixups pointed to the scope we just popped. If so,
537   // we can remove them.
538   for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
539     llvm::BasicBlock *Dest = BranchFixups[i]->getSuccessor(0);
540     BlockScopeMap::iterator I = BlockScopes.find(Dest);
541 
542     if (I == BlockScopes.end())
543       continue;
544 
545     assert(I->second <= CleanupEntries.size() && "Invalid branch fixup!");
546 
547     if (I->second == CleanupEntries.size()) {
548       // We don't need to do this branch fixup.
549       BranchFixups[i] = BranchFixups.back();
550       BranchFixups.pop_back();
551       i--;
552       e--;
553       continue;
554     }
555   }
556 
557   llvm::BasicBlock *SwitchBlock = 0;
558   llvm::BasicBlock *EndBlock = 0;
559   if (!BranchFixups.empty()) {
560     SwitchBlock = createBasicBlock("cleanup.switch");
561     EndBlock = createBasicBlock("cleanup.end");
562 
563     llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
564 
565     Builder.SetInsertPoint(SwitchBlock);
566 
567     llvm::Value *DestCodePtr = CreateTempAlloca(llvm::Type::Int32Ty,
568                                                 "cleanup.dst");
569     llvm::Value *DestCode = Builder.CreateLoad(DestCodePtr, "tmp");
570 
571     // Create a switch instruction to determine where to jump next.
572     llvm::SwitchInst *SI = Builder.CreateSwitch(DestCode, EndBlock,
573                                                 BranchFixups.size());
574 
575     // Restore the current basic block (if any)
576     if (CurBB) {
577       Builder.SetInsertPoint(CurBB);
578 
579       // If we had a current basic block, we also need to emit an instruction
580       // to initialize the cleanup destination.
581       Builder.CreateStore(llvm::Constant::getNullValue(llvm::Type::Int32Ty),
582                           DestCodePtr);
583     } else
584       Builder.ClearInsertionPoint();
585 
586     for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
587       llvm::BranchInst *BI = BranchFixups[i];
588       llvm::BasicBlock *Dest = BI->getSuccessor(0);
589 
590       // Fixup the branch instruction to point to the cleanup block.
591       BI->setSuccessor(0, CleanupBlock);
592 
593       if (CleanupEntries.empty()) {
594         llvm::ConstantInt *ID;
595 
596         // Check if we already have a destination for this block.
597         if (Dest == SI->getDefaultDest())
598           ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
599         else {
600           ID = SI->findCaseDest(Dest);
601           if (!ID) {
602             // No code found, get a new unique one by using the number of
603             // switch successors.
604             ID = llvm::ConstantInt::get(llvm::Type::Int32Ty,
605                                         SI->getNumSuccessors());
606             SI->addCase(ID, Dest);
607           }
608         }
609 
610         // Store the jump destination before the branch instruction.
611         new llvm::StoreInst(ID, DestCodePtr, BI);
612       } else {
613         // We need to jump through another cleanup block. Create a pad block
614         // with a branch instruction that jumps to the final destination and
615         // add it as a branch fixup to the current cleanup scope.
616 
617         // Create the pad block.
618         llvm::BasicBlock *CleanupPad = createBasicBlock("cleanup.pad", CurFn);
619 
620         // Create a unique case ID.
621         llvm::ConstantInt *ID = llvm::ConstantInt::get(llvm::Type::Int32Ty,
622                                                        SI->getNumSuccessors());
623 
624         // Store the jump destination before the branch instruction.
625         new llvm::StoreInst(ID, DestCodePtr, BI);
626 
627         // Add it as the destination.
628         SI->addCase(ID, CleanupPad);
629 
630         // Create the branch to the final destination.
631         llvm::BranchInst *BI = llvm::BranchInst::Create(Dest);
632         CleanupPad->getInstList().push_back(BI);
633 
634         // And add it as a branch fixup.
635         CleanupEntries.back().BranchFixups.push_back(BI);
636       }
637     }
638   }
639 
640   // Remove all blocks from the block scope map.
641   for (size_t i = 0, e = Blocks.size(); i != e; ++i) {
642     assert(BlockScopes.count(Blocks[i]) &&
643            "Did not find block in scope map!");
644 
645     BlockScopes.erase(Blocks[i]);
646   }
647 
648   return CleanupBlockInfo(CleanupBlock, SwitchBlock, EndBlock);
649 }
650 
651 void CodeGenFunction::EmitCleanupBlock()
652 {
653   CleanupBlockInfo Info = PopCleanupBlock();
654 
655   EmitBlock(Info.CleanupBlock);
656 
657   if (Info.SwitchBlock)
658     EmitBlock(Info.SwitchBlock);
659   if (Info.EndBlock)
660     EmitBlock(Info.EndBlock);
661 }
662 
663 void CodeGenFunction::AddBranchFixup(llvm::BranchInst *BI)
664 {
665   assert(!CleanupEntries.empty() &&
666          "Trying to add branch fixup without cleanup block!");
667 
668   // FIXME: We could be more clever here and check if there's already a
669   // branch fixup for this destination and recycle it.
670   CleanupEntries.back().BranchFixups.push_back(BI);
671 }
672 
673 void CodeGenFunction::EmitBranchThroughCleanup(llvm::BasicBlock *Dest)
674 {
675   if (!HaveInsertPoint())
676     return;
677 
678   llvm::BranchInst* BI = Builder.CreateBr(Dest);
679 
680   Builder.ClearInsertionPoint();
681 
682   // The stack is empty, no need to do any cleanup.
683   if (CleanupEntries.empty())
684     return;
685 
686   if (!Dest->getParent()) {
687     // We are trying to branch to a block that hasn't been inserted yet.
688     AddBranchFixup(BI);
689     return;
690   }
691 
692   BlockScopeMap::iterator I = BlockScopes.find(Dest);
693   if (I == BlockScopes.end()) {
694     // We are trying to jump to a block that is outside of any cleanup scope.
695     AddBranchFixup(BI);
696     return;
697   }
698 
699   assert(I->second < CleanupEntries.size() &&
700          "Trying to branch into cleanup region");
701 
702   if (I->second == CleanupEntries.size() - 1) {
703     // We have a branch to a block in the same scope.
704     return;
705   }
706 
707   AddBranchFixup(BI);
708 }
709