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