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