CodeGenFunction.cpp revision 203955
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 "clang/AST/StmtCXX.h"
23#include "llvm/Target/TargetData.h"
24using namespace clang;
25using namespace CodeGen;
26
27CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
28  : BlockFunction(cgm, *this, Builder), CGM(cgm),
29    Target(CGM.getContext().Target),
30    Builder(cgm.getModule().getContext()),
31    DebugInfo(0), IndirectBranch(0),
32    SwitchInsn(0), CaseRangeBlock(0), InvokeDest(0),
33    CXXThisDecl(0), CXXVTTDecl(0),
34    ConditionalBranchLevel(0), TerminateHandler(0), TrapBB(0),
35    UniqueAggrDestructorCount(0) {
36  LLVMIntTy = ConvertType(getContext().IntTy);
37  LLVMPointerWidth = Target.getPointerWidth(0);
38  Exceptions = getContext().getLangOptions().Exceptions;
39  CatchUndefined = getContext().getLangOptions().CatchUndefined;
40}
41
42ASTContext &CodeGenFunction::getContext() const {
43  return CGM.getContext();
44}
45
46
47llvm::BasicBlock *CodeGenFunction::getBasicBlockForLabel(const LabelStmt *S) {
48  llvm::BasicBlock *&BB = LabelMap[S];
49  if (BB) return BB;
50
51  // Create, but don't insert, the new block.
52  return BB = createBasicBlock(S->getName());
53}
54
55llvm::Value *CodeGenFunction::GetAddrOfLocalVar(const VarDecl *VD) {
56  llvm::Value *Res = LocalDeclMap[VD];
57  assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!");
58  return Res;
59}
60
61llvm::Constant *
62CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) {
63  return cast<llvm::Constant>(GetAddrOfLocalVar(BVD));
64}
65
66const llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
67  return CGM.getTypes().ConvertTypeForMem(T);
68}
69
70const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
71  return CGM.getTypes().ConvertType(T);
72}
73
74bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
75  return T->isRecordType() || T->isArrayType() || T->isAnyComplexType() ||
76    T->isMemberFunctionPointerType();
77}
78
79void CodeGenFunction::EmitReturnBlock() {
80  // For cleanliness, we try to avoid emitting the return block for
81  // simple cases.
82  llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
83
84  if (CurBB) {
85    assert(!CurBB->getTerminator() && "Unexpected terminated block.");
86
87    // We have a valid insert point, reuse it if it is empty or there are no
88    // explicit jumps to the return block.
89    if (CurBB->empty() || ReturnBlock->use_empty()) {
90      ReturnBlock->replaceAllUsesWith(CurBB);
91      delete ReturnBlock;
92    } else
93      EmitBlock(ReturnBlock);
94    return;
95  }
96
97  // Otherwise, if the return block is the target of a single direct
98  // branch then we can just put the code in that block instead. This
99  // cleans up functions which started with a unified return block.
100  if (ReturnBlock->hasOneUse()) {
101    llvm::BranchInst *BI =
102      dyn_cast<llvm::BranchInst>(*ReturnBlock->use_begin());
103    if (BI && BI->isUnconditional() && BI->getSuccessor(0) == ReturnBlock) {
104      // Reset insertion point and delete the branch.
105      Builder.SetInsertPoint(BI->getParent());
106      BI->eraseFromParent();
107      delete ReturnBlock;
108      return;
109    }
110  }
111
112  // FIXME: We are at an unreachable point, there is no reason to emit the block
113  // unless it has uses. However, we still need a place to put the debug
114  // region.end for now.
115
116  EmitBlock(ReturnBlock);
117}
118
119void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
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  EmitEndEHSpec(CurCodeDecl);
138
139  // If someone did an indirect goto, emit the indirect goto block at the end of
140  // the function.
141  if (IndirectBranch) {
142    EmitBlock(IndirectBranch->getParent());
143    Builder.ClearInsertionPoint();
144  }
145
146  // Remove the AllocaInsertPt instruction, which is just a convenience for us.
147  llvm::Instruction *Ptr = AllocaInsertPt;
148  AllocaInsertPt = 0;
149  Ptr->eraseFromParent();
150
151  // If someone took the address of a label but never did an indirect goto, we
152  // made a zero entry PHI node, which is illegal, zap it now.
153  if (IndirectBranch) {
154    llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
155    if (PN->getNumIncomingValues() == 0) {
156      PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
157      PN->eraseFromParent();
158    }
159  }
160}
161
162void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
163                                    llvm::Function *Fn,
164                                    const FunctionArgList &Args,
165                                    SourceLocation StartLoc) {
166  const Decl *D = GD.getDecl();
167
168  DidCallStackSave = false;
169  CurCodeDecl = CurFuncDecl = D;
170  FnRetTy = RetTy;
171  CurFn = Fn;
172  assert(CurFn->isDeclaration() && "Function already has body?");
173
174  // Pass inline keyword to optimizer if it appears explicitly on any
175  // declaration.
176  if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
177    for (FunctionDecl::redecl_iterator RI = FD->redecls_begin(),
178           RE = FD->redecls_end(); RI != RE; ++RI)
179      if (RI->isInlineSpecified()) {
180        Fn->addFnAttr(llvm::Attribute::InlineHint);
181        break;
182      }
183
184  llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
185
186  // Create a marker to make it easy to insert allocas into the entryblock
187  // later.  Don't create this with the builder, because we don't want it
188  // folded.
189  llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::getInt32Ty(VMContext));
190  AllocaInsertPt = new llvm::BitCastInst(Undef,
191                                         llvm::Type::getInt32Ty(VMContext), "",
192                                         EntryBB);
193  if (Builder.isNamePreserving())
194    AllocaInsertPt->setName("allocapt");
195
196  ReturnBlock = createBasicBlock("return");
197
198  Builder.SetInsertPoint(EntryBB);
199
200  QualType FnType = getContext().getFunctionType(RetTy, 0, 0, false, 0);
201
202  // Emit subprogram debug descriptor.
203  if (CGDebugInfo *DI = getDebugInfo()) {
204    DI->setLocation(StartLoc);
205    DI->EmitFunctionStart(GD, FnType, CurFn, Builder);
206  }
207
208  // FIXME: Leaked.
209  // CC info is ignored, hopefully?
210  CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args,
211                                              CC_Default, false);
212
213  if (RetTy->isVoidType()) {
214    // Void type; nothing to return.
215    ReturnValue = 0;
216  } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
217             hasAggregateLLVMType(CurFnInfo->getReturnType())) {
218    // Indirect aggregate return; emit returned value directly into sret slot.
219    // This reduces code size, and is also affects correctness in C++.
220    ReturnValue = CurFn->arg_begin();
221  } else {
222    ReturnValue = CreateTempAlloca(ConvertType(RetTy), "retval");
223  }
224
225  EmitStartEHSpec(CurCodeDecl);
226  EmitFunctionProlog(*CurFnInfo, CurFn, Args);
227
228  // If any of the arguments have a variably modified type, make sure to
229  // emit the type size.
230  for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
231       i != e; ++i) {
232    QualType Ty = i->second;
233
234    if (Ty->isVariablyModifiedType())
235      EmitVLASize(Ty);
236  }
237}
238
239void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn) {
240  const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
241
242  // Check if we should generate debug info for this function.
243  if (CGM.getDebugInfo() && !FD->hasAttr<NoDebugAttr>())
244    DebugInfo = CGM.getDebugInfo();
245
246  FunctionArgList Args;
247
248  CurGD = GD;
249  OuterTryBlock = 0;
250  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
251    if (MD->isInstance()) {
252      // Create the implicit 'this' decl.
253      // FIXME: I'm not entirely sure I like using a fake decl just for code
254      // generation. Maybe we can come up with a better way?
255      CXXThisDecl = ImplicitParamDecl::Create(getContext(), 0, SourceLocation(),
256                                              &getContext().Idents.get("this"),
257                                              MD->getThisType(getContext()));
258      Args.push_back(std::make_pair(CXXThisDecl, CXXThisDecl->getType()));
259
260      // Check if we need a VTT parameter as well.
261      if (CGVtableInfo::needsVTTParameter(GD)) {
262        // FIXME: The comment about using a fake decl above applies here too.
263        QualType T = getContext().getPointerType(getContext().VoidPtrTy);
264        CXXVTTDecl =
265          ImplicitParamDecl::Create(getContext(), 0, SourceLocation(),
266                                    &getContext().Idents.get("vtt"), T);
267        Args.push_back(std::make_pair(CXXVTTDecl, CXXVTTDecl->getType()));
268      }
269    }
270  }
271
272  if (FD->getNumParams()) {
273    const FunctionProtoType* FProto = FD->getType()->getAs<FunctionProtoType>();
274    assert(FProto && "Function def must have prototype!");
275
276    for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
277      Args.push_back(std::make_pair(FD->getParamDecl(i),
278                                    FProto->getArgType(i)));
279  }
280
281  if (const CompoundStmt *S = FD->getCompoundBody()) {
282    StartFunction(GD, FD->getResultType(), Fn, Args, S->getLBracLoc());
283
284    if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
285      EmitCtorPrologue(CD, GD.getCtorType());
286      EmitStmt(S);
287
288      // If any of the member initializers are temporaries bound to references
289      // make sure to emit their destructors.
290      EmitCleanupBlocks(0);
291
292    } else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD)) {
293      llvm::BasicBlock *DtorEpilogue  = createBasicBlock("dtor.epilogue");
294      PushCleanupBlock(DtorEpilogue);
295
296      InitializeVtablePtrs(DD->getParent());
297
298      EmitStmt(S);
299
300      CleanupBlockInfo Info = PopCleanupBlock();
301
302      assert(Info.CleanupBlock == DtorEpilogue && "Block mismatch!");
303      EmitBlock(DtorEpilogue);
304      EmitDtorEpilogue(DD, GD.getDtorType());
305
306      if (Info.SwitchBlock)
307        EmitBlock(Info.SwitchBlock);
308      if (Info.EndBlock)
309        EmitBlock(Info.EndBlock);
310    } else {
311      // Just a regular function, emit its body.
312      EmitStmt(S);
313    }
314
315    FinishFunction(S->getRBracLoc());
316  } else if (FD->isImplicit()) {
317    const CXXRecordDecl *ClassDecl =
318      cast<CXXRecordDecl>(FD->getDeclContext());
319    (void) ClassDecl;
320    if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
321      // FIXME: For C++0x, we want to look for implicit *definitions* of
322      // these special member functions, rather than implicit *declarations*.
323      if (CD->isCopyConstructor()) {
324        assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
325               "Cannot synthesize a non-implicit copy constructor");
326        SynthesizeCXXCopyConstructor(CD, GD.getCtorType(), Fn, Args);
327      } else if (CD->isDefaultConstructor()) {
328        assert(!ClassDecl->hasUserDeclaredConstructor() &&
329               "Cannot synthesize a non-implicit default constructor.");
330        SynthesizeDefaultConstructor(CD, GD.getCtorType(), Fn, Args);
331      } else {
332        assert(false && "Implicit constructor cannot be synthesized");
333      }
334    } else if (const CXXDestructorDecl *CD = dyn_cast<CXXDestructorDecl>(FD)) {
335      assert(!ClassDecl->hasUserDeclaredDestructor() &&
336             "Cannot synthesize a non-implicit destructor");
337      SynthesizeDefaultDestructor(CD, GD.getDtorType(), Fn, Args);
338    } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
339      assert(MD->isCopyAssignment() &&
340             !ClassDecl->hasUserDeclaredCopyAssignment() &&
341             "Cannot synthesize a method that is not an implicit-defined "
342             "copy constructor");
343      SynthesizeCXXCopyAssignment(MD, Fn, Args);
344    } else {
345      assert(false && "Cannot synthesize unknown implicit function");
346    }
347  } else if (const Stmt *S = FD->getBody()) {
348    if (const CXXTryStmt *TS = dyn_cast<CXXTryStmt>(S)) {
349      OuterTryBlock = TS;
350      StartFunction(GD, FD->getResultType(), Fn, Args, TS->getTryLoc());
351      EmitStmt(TS);
352      FinishFunction(TS->getEndLoc());
353    }
354  }
355
356  // Destroy the 'this' declaration.
357  if (CXXThisDecl)
358    CXXThisDecl->Destroy(getContext());
359
360  // Destroy the VTT declaration.
361  if (CXXVTTDecl)
362    CXXVTTDecl->Destroy(getContext());
363}
364
365/// ContainsLabel - Return true if the statement contains a label in it.  If
366/// this statement is not executed normally, it not containing a label means
367/// that we can just remove the code.
368bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
369  // Null statement, not a label!
370  if (S == 0) return false;
371
372  // If this is a label, we have to emit the code, consider something like:
373  // if (0) {  ...  foo:  bar(); }  goto foo;
374  if (isa<LabelStmt>(S))
375    return true;
376
377  // If this is a case/default statement, and we haven't seen a switch, we have
378  // to emit the code.
379  if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
380    return true;
381
382  // If this is a switch statement, we want to ignore cases below it.
383  if (isa<SwitchStmt>(S))
384    IgnoreCaseStmts = true;
385
386  // Scan subexpressions for verboten labels.
387  for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
388       I != E; ++I)
389    if (ContainsLabel(*I, IgnoreCaseStmts))
390      return true;
391
392  return false;
393}
394
395
396/// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
397/// a constant, or if it does but contains a label, return 0.  If it constant
398/// folds to 'true' and does not contain a label, return 1, if it constant folds
399/// to 'false' and does not contain a label, return -1.
400int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
401  // FIXME: Rename and handle conversion of other evaluatable things
402  // to bool.
403  Expr::EvalResult Result;
404  if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
405      Result.HasSideEffects)
406    return 0;  // Not foldable, not integer or not fully evaluatable.
407
408  if (CodeGenFunction::ContainsLabel(Cond))
409    return 0;  // Contains a label.
410
411  return Result.Val.getInt().getBoolValue() ? 1 : -1;
412}
413
414
415/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
416/// statement) to the specified blocks.  Based on the condition, this might try
417/// to simplify the codegen of the conditional based on the branch.
418///
419void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
420                                           llvm::BasicBlock *TrueBlock,
421                                           llvm::BasicBlock *FalseBlock) {
422  if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
423    return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
424
425  if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
426    // Handle X && Y in a condition.
427    if (CondBOp->getOpcode() == BinaryOperator::LAnd) {
428      // If we have "1 && X", simplify the code.  "0 && X" would have constant
429      // folded if the case was simple enough.
430      if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
431        // br(1 && X) -> br(X).
432        return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
433      }
434
435      // If we have "X && 1", simplify the code to use an uncond branch.
436      // "X && 0" would have been constant folded to 0.
437      if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
438        // br(X && 1) -> br(X).
439        return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
440      }
441
442      // Emit the LHS as a conditional.  If the LHS conditional is false, we
443      // want to jump to the FalseBlock.
444      llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
445      EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
446      EmitBlock(LHSTrue);
447
448      // Any temporaries created here are conditional.
449      BeginConditionalBranch();
450      EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
451      EndConditionalBranch();
452
453      return;
454    } else if (CondBOp->getOpcode() == BinaryOperator::LOr) {
455      // If we have "0 || X", simplify the code.  "1 || X" would have constant
456      // folded if the case was simple enough.
457      if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
458        // br(0 || X) -> br(X).
459        return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
460      }
461
462      // If we have "X || 0", simplify the code to use an uncond branch.
463      // "X || 1" would have been constant folded to 1.
464      if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
465        // br(X || 0) -> br(X).
466        return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
467      }
468
469      // Emit the LHS as a conditional.  If the LHS conditional is true, we
470      // want to jump to the TrueBlock.
471      llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
472      EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
473      EmitBlock(LHSFalse);
474
475      // Any temporaries created here are conditional.
476      BeginConditionalBranch();
477      EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
478      EndConditionalBranch();
479
480      return;
481    }
482  }
483
484  if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
485    // br(!x, t, f) -> br(x, f, t)
486    if (CondUOp->getOpcode() == UnaryOperator::LNot)
487      return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
488  }
489
490  if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
491    // Handle ?: operator.
492
493    // Just ignore GNU ?: extension.
494    if (CondOp->getLHS()) {
495      // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
496      llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
497      llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
498      EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
499      EmitBlock(LHSBlock);
500      EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
501      EmitBlock(RHSBlock);
502      EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
503      return;
504    }
505  }
506
507  // Emit the code with the fully general case.
508  llvm::Value *CondV = EvaluateExprAsBool(Cond);
509  Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
510}
511
512/// ErrorUnsupported - Print out an error that codegen doesn't support the
513/// specified stmt yet.
514void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
515                                       bool OmitOnError) {
516  CGM.ErrorUnsupported(S, Type, OmitOnError);
517}
518
519void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty) {
520  const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext);
521  if (DestPtr->getType() != BP)
522    DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
523
524  // Get size and alignment info for this aggregate.
525  std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
526
527  // Don't bother emitting a zero-byte memset.
528  if (TypeInfo.first == 0)
529    return;
530
531  // FIXME: Handle variable sized types.
532  const llvm::Type *IntPtr = llvm::IntegerType::get(VMContext,
533                                                    LLVMPointerWidth);
534
535  Builder.CreateCall4(CGM.getMemSetFn(), DestPtr,
536                 llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext)),
537                      // TypeInfo.first describes size in bits.
538                      llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
539                      llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
540                                             TypeInfo.second/8));
541}
542
543llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelStmt *L) {
544  // Make sure that there is a block for the indirect goto.
545  if (IndirectBranch == 0)
546    GetIndirectGotoBlock();
547
548  llvm::BasicBlock *BB = getBasicBlockForLabel(L);
549
550  // Make sure the indirect branch includes all of the address-taken blocks.
551  IndirectBranch->addDestination(BB);
552  return llvm::BlockAddress::get(CurFn, BB);
553}
554
555llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
556  // If we already made the indirect branch for indirect goto, return its block.
557  if (IndirectBranch) return IndirectBranch->getParent();
558
559  CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto"));
560
561  const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
562
563  // Create the PHI node that indirect gotos will add entries to.
564  llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, "indirect.goto.dest");
565
566  // Create the indirect branch instruction.
567  IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
568  return IndirectBranch->getParent();
569}
570
571llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) {
572  llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
573
574  assert(SizeEntry && "Did not emit size for type");
575  return SizeEntry;
576}
577
578llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) {
579  assert(Ty->isVariablyModifiedType() &&
580         "Must pass variably modified type to EmitVLASizes!");
581
582  EnsureInsertPoint();
583
584  if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
585    llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
586
587    if (!SizeEntry) {
588      const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
589
590      // Get the element size;
591      QualType ElemTy = VAT->getElementType();
592      llvm::Value *ElemSize;
593      if (ElemTy->isVariableArrayType())
594        ElemSize = EmitVLASize(ElemTy);
595      else
596        ElemSize = llvm::ConstantInt::get(SizeTy,
597            getContext().getTypeSizeInChars(ElemTy).getQuantity());
598
599      llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
600      NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
601
602      SizeEntry = Builder.CreateMul(ElemSize, NumElements);
603    }
604
605    return SizeEntry;
606  }
607
608  if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
609    EmitVLASize(AT->getElementType());
610    return 0;
611  }
612
613  const PointerType *PT = Ty->getAs<PointerType>();
614  assert(PT && "unknown VM type!");
615  EmitVLASize(PT->getPointeeType());
616  return 0;
617}
618
619llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
620  if (CGM.getContext().getBuiltinVaListType()->isArrayType()) {
621    return EmitScalarExpr(E);
622  }
623  return EmitLValue(E).getAddress();
624}
625
626void CodeGenFunction::PushCleanupBlock(llvm::BasicBlock *CleanupEntryBlock,
627                                       llvm::BasicBlock *CleanupExitBlock,
628                                       llvm::BasicBlock *PreviousInvokeDest,
629                                       bool EHOnly) {
630  CleanupEntries.push_back(CleanupEntry(CleanupEntryBlock, CleanupExitBlock,
631                                        PreviousInvokeDest, EHOnly));
632}
633
634void CodeGenFunction::EmitCleanupBlocks(size_t OldCleanupStackSize) {
635  assert(CleanupEntries.size() >= OldCleanupStackSize &&
636         "Cleanup stack mismatch!");
637
638  while (CleanupEntries.size() > OldCleanupStackSize)
639    EmitCleanupBlock();
640}
641
642CodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock() {
643  CleanupEntry &CE = CleanupEntries.back();
644
645  llvm::BasicBlock *CleanupEntryBlock = CE.CleanupEntryBlock;
646
647  std::vector<llvm::BasicBlock *> Blocks;
648  std::swap(Blocks, CE.Blocks);
649
650  std::vector<llvm::BranchInst *> BranchFixups;
651  std::swap(BranchFixups, CE.BranchFixups);
652
653  bool EHOnly = CE.EHOnly;
654
655  setInvokeDest(CE.PreviousInvokeDest);
656
657  CleanupEntries.pop_back();
658
659  // Check if any branch fixups pointed to the scope we just popped. If so,
660  // we can remove them.
661  for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
662    llvm::BasicBlock *Dest = BranchFixups[i]->getSuccessor(0);
663    BlockScopeMap::iterator I = BlockScopes.find(Dest);
664
665    if (I == BlockScopes.end())
666      continue;
667
668    assert(I->second <= CleanupEntries.size() && "Invalid branch fixup!");
669
670    if (I->second == CleanupEntries.size()) {
671      // We don't need to do this branch fixup.
672      BranchFixups[i] = BranchFixups.back();
673      BranchFixups.pop_back();
674      i--;
675      e--;
676      continue;
677    }
678  }
679
680  llvm::BasicBlock *SwitchBlock = CE.CleanupExitBlock;
681  llvm::BasicBlock *EndBlock = 0;
682  if (!BranchFixups.empty()) {
683    if (!SwitchBlock)
684      SwitchBlock = createBasicBlock("cleanup.switch");
685    EndBlock = createBasicBlock("cleanup.end");
686
687    llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
688
689    Builder.SetInsertPoint(SwitchBlock);
690
691    llvm::Value *DestCodePtr
692      = CreateTempAlloca(llvm::Type::getInt32Ty(VMContext),
693                         "cleanup.dst");
694    llvm::Value *DestCode = Builder.CreateLoad(DestCodePtr, "tmp");
695
696    // Create a switch instruction to determine where to jump next.
697    llvm::SwitchInst *SI = Builder.CreateSwitch(DestCode, EndBlock,
698                                                BranchFixups.size());
699
700    // Restore the current basic block (if any)
701    if (CurBB) {
702      Builder.SetInsertPoint(CurBB);
703
704      // If we had a current basic block, we also need to emit an instruction
705      // to initialize the cleanup destination.
706      Builder.CreateStore(llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)),
707                          DestCodePtr);
708    } else
709      Builder.ClearInsertionPoint();
710
711    for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
712      llvm::BranchInst *BI = BranchFixups[i];
713      llvm::BasicBlock *Dest = BI->getSuccessor(0);
714
715      // Fixup the branch instruction to point to the cleanup block.
716      BI->setSuccessor(0, CleanupEntryBlock);
717
718      if (CleanupEntries.empty()) {
719        llvm::ConstantInt *ID;
720
721        // Check if we already have a destination for this block.
722        if (Dest == SI->getDefaultDest())
723          ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0);
724        else {
725          ID = SI->findCaseDest(Dest);
726          if (!ID) {
727            // No code found, get a new unique one by using the number of
728            // switch successors.
729            ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
730                                        SI->getNumSuccessors());
731            SI->addCase(ID, Dest);
732          }
733        }
734
735        // Store the jump destination before the branch instruction.
736        new llvm::StoreInst(ID, DestCodePtr, BI);
737      } else {
738        // We need to jump through another cleanup block. Create a pad block
739        // with a branch instruction that jumps to the final destination and add
740        // it as a branch fixup to the current cleanup scope.
741
742        // Create the pad block.
743        llvm::BasicBlock *CleanupPad = createBasicBlock("cleanup.pad", CurFn);
744
745        // Create a unique case ID.
746        llvm::ConstantInt *ID
747          = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
748                                   SI->getNumSuccessors());
749
750        // Store the jump destination before the branch instruction.
751        new llvm::StoreInst(ID, DestCodePtr, BI);
752
753        // Add it as the destination.
754        SI->addCase(ID, CleanupPad);
755
756        // Create the branch to the final destination.
757        llvm::BranchInst *BI = llvm::BranchInst::Create(Dest);
758        CleanupPad->getInstList().push_back(BI);
759
760        // And add it as a branch fixup.
761        CleanupEntries.back().BranchFixups.push_back(BI);
762      }
763    }
764  }
765
766  // Remove all blocks from the block scope map.
767  for (size_t i = 0, e = Blocks.size(); i != e; ++i) {
768    assert(BlockScopes.count(Blocks[i]) &&
769           "Did not find block in scope map!");
770
771    BlockScopes.erase(Blocks[i]);
772  }
773
774  return CleanupBlockInfo(CleanupEntryBlock, SwitchBlock, EndBlock, EHOnly);
775}
776
777void CodeGenFunction::EmitCleanupBlock() {
778  CleanupBlockInfo Info = PopCleanupBlock();
779
780  if (Info.EHOnly) {
781    // FIXME: Add this to the exceptional edge
782    if (Info.CleanupBlock->getNumUses() == 0)
783      delete Info.CleanupBlock;
784    return;
785  }
786
787  llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
788  if (CurBB && !CurBB->getTerminator() &&
789      Info.CleanupBlock->getNumUses() == 0) {
790    CurBB->getInstList().splice(CurBB->end(), Info.CleanupBlock->getInstList());
791    delete Info.CleanupBlock;
792  } else
793    EmitBlock(Info.CleanupBlock);
794
795  if (Info.SwitchBlock)
796    EmitBlock(Info.SwitchBlock);
797  if (Info.EndBlock)
798    EmitBlock(Info.EndBlock);
799}
800
801void CodeGenFunction::AddBranchFixup(llvm::BranchInst *BI) {
802  assert(!CleanupEntries.empty() &&
803         "Trying to add branch fixup without cleanup block!");
804
805  // FIXME: We could be more clever here and check if there's already a branch
806  // fixup for this destination and recycle it.
807  CleanupEntries.back().BranchFixups.push_back(BI);
808}
809
810void CodeGenFunction::EmitBranchThroughCleanup(llvm::BasicBlock *Dest) {
811  if (!HaveInsertPoint())
812    return;
813
814  llvm::BranchInst* BI = Builder.CreateBr(Dest);
815
816  Builder.ClearInsertionPoint();
817
818  // The stack is empty, no need to do any cleanup.
819  if (CleanupEntries.empty())
820    return;
821
822  if (!Dest->getParent()) {
823    // We are trying to branch to a block that hasn't been inserted yet.
824    AddBranchFixup(BI);
825    return;
826  }
827
828  BlockScopeMap::iterator I = BlockScopes.find(Dest);
829  if (I == BlockScopes.end()) {
830    // We are trying to jump to a block that is outside of any cleanup scope.
831    AddBranchFixup(BI);
832    return;
833  }
834
835  assert(I->second < CleanupEntries.size() &&
836         "Trying to branch into cleanup region");
837
838  if (I->second == CleanupEntries.size() - 1) {
839    // We have a branch to a block in the same scope.
840    return;
841  }
842
843  AddBranchFixup(BI);
844}
845