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