CodeGenFunction.cpp revision 204643
129415Sjmg//===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
250723Scg//
339899Sluigi//                     The LLVM Compiler Infrastructure
429415Sjmg//
529415Sjmg// This file is distributed under the University of Illinois Open Source
629415Sjmg// License. See LICENSE.TXT for details.
729415Sjmg//
850723Scg//===----------------------------------------------------------------------===//
950723Scg//
1029415Sjmg// This coordinates the per-function state used while generating code.
1129415Sjmg//
1230869Sjmg//===----------------------------------------------------------------------===//
1330869Sjmg
1430869Sjmg#include "CodeGenFunction.h"
1530869Sjmg#include "CodeGenModule.h"
1650723Scg#include "CGDebugInfo.h"
1750723Scg#include "clang/Basic/TargetInfo.h"
1830869Sjmg#include "clang/AST/APValue.h"
1950723Scg#include "clang/AST/ASTContext.h"
2050723Scg#include "clang/AST/Decl.h"
2150723Scg#include "clang/AST/DeclCXX.h"
2250723Scg#include "clang/AST/StmtCXX.h"
2350723Scg#include "llvm/Target/TargetData.h"
2450723Scgusing namespace clang;
2550723Scgusing namespace CodeGen;
2650723Scg
2750723ScgCodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
2850723Scg  : BlockFunction(cgm, *this, Builder), CGM(cgm),
2950723Scg    Target(CGM.getContext().Target),
3029415Sjmg    Builder(cgm.getModule().getContext()),
3129415Sjmg    DebugInfo(0), IndirectBranch(0),
3253465Scg    SwitchInsn(0), CaseRangeBlock(0), InvokeDest(0),
3329415Sjmg    CXXThisDecl(0), CXXThisValue(0), CXXVTTDecl(0), CXXVTTValue(0),
3453465Scg    ConditionalBranchLevel(0), TerminateHandler(0), TrapBB(0),
3553553Stanimura    UniqueAggrDestructorCount(0) {
3629415Sjmg  LLVMIntTy = ConvertType(getContext().IntTy);
3770134Scg  LLVMPointerWidth = Target.getPointerWidth(0);
3870134Scg  Exceptions = getContext().getLangOptions().Exceptions;
3982180Scg  CatchUndefined = getContext().getLangOptions().CatchUndefined;
4082180Scg}
4167803Scg
4255706ScgASTContext &CodeGenFunction::getContext() const {
4355254Scg  return CGM.getContext();
4467803Scg}
4550723Scg
4650723Scg
4764881Scgllvm::BasicBlock *CodeGenFunction::getBasicBlockForLabel(const LabelStmt *S) {
4850723Scg  llvm::BasicBlock *&BB = LabelMap[S];
4974763Scg  if (BB) return BB;
5029415Sjmg
5167803Scg  // Create, but don't insert, the new block.
5264881Scg  return BB = createBasicBlock(S->getName());
5350723Scg}
5464881Scg
5550723Scgllvm::Value *CodeGenFunction::GetAddrOfLocalVar(const VarDecl *VD) {
5674763Scg  llvm::Value *Res = LocalDeclMap[VD];
5729415Sjmg  assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!");
5864881Scg  return Res;
5964881Scg}
6064881Scg
6164881Scgllvm::Constant *
6264881ScgCodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) {
6364881Scg  return cast<llvm::Constant>(GetAddrOfLocalVar(BVD));
6454462Scg}
6574763Scg
6654462Scgconst llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
6750723Scg  return CGM.getTypes().ConvertTypeForMem(T);
6829415Sjmg}
6950723Scg
7050723Scgconst llvm::Type *CodeGenFunction::ConvertType(QualType T) {
7174763Scg  return CGM.getTypes().ConvertType(T);
7274763Scg}
7367803Scg
7467803Scgbool CodeGenFunction::hasAggregateLLVMType(QualType T) {
7550723Scg  return T->isRecordType() || T->isArrayType() || T->isAnyComplexType() ||
7629415Sjmg    T->isMemberFunctionPointerType();
7750723Scg}
7850723Scg
7950723Scgvoid CodeGenFunction::EmitReturnBlock() {
8054462Scg  // For cleanliness, we try to avoid emitting the return block for
8154462Scg  // simple cases.
8265644Scg  llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
8355706Scg
8429415Sjmg  if (CurBB) {
8584111Scg    assert(!CurBB->getTerminator() && "Unexpected terminated block.");
8650723Scg
8750723Scg    // We have a valid insert point, reuse it if it is empty or there are no
8870291Scg    // explicit jumps to the return block.
8950723Scg    if (CurBB->empty() || ReturnBlock->use_empty()) {
9074763Scg      ReturnBlock->replaceAllUsesWith(CurBB);
9150723Scg      delete ReturnBlock;
9250723Scg    } else
9384111Scg      EmitBlock(ReturnBlock);
9474763Scg    return;
9574763Scg  }
9650723Scg
9750723Scg  // Otherwise, if the return block is the target of a single direct
9850723Scg  // branch then we can just put the code in that block instead. This
9967803Scg  // cleans up functions which started with a unified return block.
10050723Scg  if (ReturnBlock->hasOneUse()) {
10150723Scg    llvm::BranchInst *BI =
10250723Scg      dyn_cast<llvm::BranchInst>(*ReturnBlock->use_begin());
10350723Scg    if (BI && BI->isUnconditional() && BI->getSuccessor(0) == ReturnBlock) {
10454462Scg      // Reset insertion point and delete the branch.
10529415Sjmg      Builder.SetInsertPoint(BI->getParent());
10650723Scg      BI->eraseFromParent();
10784111Scg      delete ReturnBlock;
10850723Scg      return;
10929415Sjmg    }
11050723Scg  }
11129415Sjmg
11250723Scg  // FIXME: We are at an unreachable point, there is no reason to emit the block
11350723Scg  // unless it has uses. However, we still need a place to put the debug
11450723Scg  // region.end for now.
11550723Scg
11629415Sjmg  EmitBlock(ReturnBlock);
11729415Sjmg}
11884111Scg
11984111Scgvoid CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
12084111Scg  assert(BreakContinueStack.empty() &&
12184111Scg         "mismatched push/pop in break/continue stack!");
12284111Scg  assert(BlockScopes.empty() &&
12384111Scg         "did not remove all blocks from block scope map!");
12484111Scg  assert(CleanupEntries.empty() &&
12584111Scg         "mismatched push/pop in cleanup stack!");
12684111Scg
12784111Scg  // Emit function epilog (to return).
12884111Scg  EmitReturnBlock();
12984111Scg
13029415Sjmg  // Emit debug descriptor for function end.
13150723Scg  if (CGDebugInfo *DI = getDebugInfo()) {
13229415Sjmg    DI->setLocation(EndLoc);
13367803Scg    DI->EmitRegionEnd(CurFn, Builder);
13450723Scg  }
13529415Sjmg
13650723Scg  EmitFunctionEpilog(*CurFnInfo, ReturnValue);
13750723Scg  EmitEndEHSpec(CurCodeDecl);
13850723Scg
13967803Scg  // If someone did an indirect goto, emit the indirect goto block at the end of
14029415Sjmg  // the function.
14129415Sjmg  if (IndirectBranch) {
14229415Sjmg    EmitBlock(IndirectBranch->getParent());
14350723Scg    Builder.ClearInsertionPoint();
14429415Sjmg  }
14550723Scg
14650723Scg  // Remove the AllocaInsertPt instruction, which is just a convenience for us.
14729415Sjmg  llvm::Instruction *Ptr = AllocaInsertPt;
14850723Scg  AllocaInsertPt = 0;
14950723Scg  Ptr->eraseFromParent();
15050723Scg
15150723Scg  // If someone took the address of a label but never did an indirect goto, we
15229415Sjmg  // made a zero entry PHI node, which is illegal, zap it now.
15329415Sjmg  if (IndirectBranch) {
15450723Scg    llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
15550723Scg    if (PN->getNumIncomingValues() == 0) {
15629415Sjmg      PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
15750723Scg      PN->eraseFromParent();
15829415Sjmg    }
15950723Scg  }
16070134Scg}
16170134Scg
16270134Scgvoid CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
16370134Scg                                    llvm::Function *Fn,
16470134Scg                                    const FunctionArgList &Args,
16550723Scg                                    SourceLocation StartLoc) {
16650723Scg  const Decl *D = GD.getDecl();
16779116Sgreen
16883366Sjulian  DidCallStackSave = false;
16974797Scg  CurCodeDecl = CurFuncDecl = D;
17079090Sgreen  FnRetTy = RetTy;
17150723Scg  CurFn = Fn;
17250723Scg  assert(CurFn->isDeclaration() && "Function already has body?");
17329415Sjmg
17450723Scg  // Pass inline keyword to optimizer if it appears explicitly on any
17550723Scg  // declaration.
17650723Scg  if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
17750723Scg    for (FunctionDecl::redecl_iterator RI = FD->redecls_begin(),
17850723Scg           RE = FD->redecls_end(); RI != RE; ++RI)
17950723Scg      if (RI->isInlineSpecified()) {
18050723Scg        Fn->addFnAttr(llvm::Attribute::InlineHint);
18150723Scg        break;
18229415Sjmg      }
18367803Scg
18450723Scg  llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
18550723Scg
18650723Scg  // Create a marker to make it easy to insert allocas into the entryblock
18750723Scg  // later.  Don't create this with the builder, because we don't want it
18850723Scg  // folded.
18950723Scg  llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::getInt32Ty(VMContext));
19050723Scg  AllocaInsertPt = new llvm::BitCastInst(Undef,
19150723Scg                                         llvm::Type::getInt32Ty(VMContext), "",
19250723Scg                                         EntryBB);
19350723Scg  if (Builder.isNamePreserving())
19467803Scg    AllocaInsertPt->setName("allocapt");
19529415Sjmg
19650723Scg  ReturnBlock = createBasicBlock("return");
19750723Scg
19850723Scg  Builder.SetInsertPoint(EntryBB);
19984111Scg
20084111Scg  QualType FnType = getContext().getFunctionType(RetTy, 0, 0, false, 0,
20150723Scg                                                 false, false, 0, 0,
20250723Scg                                                 /*FIXME?*/false,
20350723Scg                                                 /*FIXME?*/CC_Default);
20484111Scg
20584111Scg  // Emit subprogram debug descriptor.
20650723Scg  if (CGDebugInfo *DI = getDebugInfo()) {
20784111Scg    DI->setLocation(StartLoc);
20884111Scg    DI->EmitFunctionStart(GD, FnType, CurFn, Builder);
20984111Scg  }
21084111Scg
21184111Scg  // FIXME: Leaked.
21284111Scg  // CC info is ignored, hopefully?
21384111Scg  CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args,
21484111Scg                                              CC_Default, false);
21584111Scg
21650723Scg  if (RetTy->isVoidType()) {
21729415Sjmg    // Void type; nothing to return.
21850723Scg    ReturnValue = 0;
21950723Scg  } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
22050723Scg             hasAggregateLLVMType(CurFnInfo->getReturnType())) {
22150723Scg    // Indirect aggregate return; emit returned value directly into sret slot.
22250723Scg    // This reduces code size, and affects correctness in C++.
22350723Scg    ReturnValue = CurFn->arg_begin();
22450723Scg  } else {
22574763Scg    ReturnValue = CreateIRTemp(RetTy, "retval");
22650723Scg  }
22750723Scg
22850723Scg  EmitStartEHSpec(CurCodeDecl);
22950723Scg  EmitFunctionProlog(*CurFnInfo, CurFn, Args);
23074763Scg
23150723Scg  if (CXXThisDecl)
23231361Sjmg    CXXThisValue = Builder.CreateLoad(LocalDeclMap[CXXThisDecl], "this");
23350723Scg  if (CXXVTTDecl)
23450723Scg    CXXVTTValue = Builder.CreateLoad(LocalDeclMap[CXXVTTDecl], "vtt");
23550723Scg
23650723Scg  // If any of the arguments have a variably modified type, make sure to
23729415Sjmg  // emit the type size.
23874763Scg  for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
23950723Scg       i != e; ++i) {
24050723Scg    QualType Ty = i->second;
24150723Scg
24250723Scg    if (Ty->isVariablyModifiedType())
24374763Scg      EmitVLASize(Ty);
24429415Sjmg  }
24550723Scg}
24650723Scg
24729415Sjmgvoid CodeGenFunction::EmitFunctionBody(FunctionArgList &Args) {
24850723Scg  const FunctionDecl *FD = cast<FunctionDecl>(CurGD.getDecl());
24950723Scg
25050723Scg  Stmt *Body = FD->getBody();
25150723Scg  if (Body)
25229415Sjmg    EmitStmt(Body);
25350723Scg  else {
25450723Scg    assert(FD->isImplicit() && "non-implicit function def has no body");
25550723Scg    assert(FD->isCopyAssignment() && "implicit function not copy assignment");
25650723Scg    SynthesizeCXXCopyAssignment(Args);
25750723Scg  }
25850723Scg}
25950723Scg
26050723Scgvoid CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn) {
26129415Sjmg  const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
26250723Scg
26350723Scg  // Check if we should generate debug info for this function.
26429415Sjmg  if (CGM.getDebugInfo() && !FD->hasAttr<NoDebugAttr>())
26574763Scg    DebugInfo = CGM.getDebugInfo();
26674763Scg
26774763Scg  FunctionArgList Args;
26850723Scg
26950723Scg  CurGD = GD;
27050723Scg  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
27174763Scg    if (MD->isInstance()) {
27274763Scg      // Create the implicit 'this' decl.
27374763Scg      // FIXME: I'm not entirely sure I like using a fake decl just for code
27450723Scg      // generation. Maybe we can come up with a better way?
27589774Sscottl      CXXThisDecl = ImplicitParamDecl::Create(getContext(), 0,
27650723Scg                                              FD->getLocation(),
27750723Scg                                              &getContext().Idents.get("this"),
27850723Scg                                              MD->getThisType(getContext()));
27929415Sjmg      Args.push_back(std::make_pair(CXXThisDecl, CXXThisDecl->getType()));
28029415Sjmg
28167803Scg      // Check if we need a VTT parameter as well.
28267803Scg      if (CGVtableInfo::needsVTTParameter(GD)) {
28367803Scg        // FIXME: The comment about using a fake decl above applies here too.
28467803Scg        QualType T = getContext().getPointerType(getContext().VoidPtrTy);
28567803Scg        CXXVTTDecl =
28667803Scg          ImplicitParamDecl::Create(getContext(), 0, FD->getLocation(),
28767803Scg                                    &getContext().Idents.get("vtt"), T);
28867803Scg        Args.push_back(std::make_pair(CXXVTTDecl, CXXVTTDecl->getType()));
28967803Scg      }
29067803Scg    }
29167803Scg  }
29267803Scg
29367803Scg  if (FD->getNumParams()) {
29467803Scg    const FunctionProtoType* FProto = FD->getType()->getAs<FunctionProtoType>();
29567803Scg    assert(FProto && "Function def must have prototype!");
29667803Scg
29767803Scg    for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
29867803Scg      Args.push_back(std::make_pair(FD->getParamDecl(i),
29967803Scg                                    FProto->getArgType(i)));
30067803Scg  }
30167803Scg
30267803Scg  SourceRange BodyRange;
30367803Scg  if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange();
30467803Scg
30574763Scg  // Emit the standard function prologue.
30667803Scg  StartFunction(GD, FD->getResultType(), Fn, Args, BodyRange.getBegin());
30767803Scg
30867803Scg  // Generate the body of the function.
30967803Scg  if (isa<CXXDestructorDecl>(FD))
31067803Scg    EmitDestructorBody(Args);
31167803Scg  else if (isa<CXXConstructorDecl>(FD))
31267803Scg    EmitConstructorBody(Args);
31367803Scg  else
31467803Scg    EmitFunctionBody(Args);
31567803Scg
31667803Scg  // Emit the standard function epilogue.
31767803Scg  FinishFunction(BodyRange.getEnd());
31867803Scg
31967803Scg  // Destroy the 'this' declaration.
32067803Scg  if (CXXThisDecl)
32167803Scg    CXXThisDecl->Destroy(getContext());
32267803Scg
32367803Scg  // Destroy the VTT declaration.
32467803Scg  if (CXXVTTDecl)
32567803Scg    CXXVTTDecl->Destroy(getContext());
32674763Scg}
32767803Scg
32867803Scg/// ContainsLabel - Return true if the statement contains a label in it.  If
32967803Scg/// this statement is not executed normally, it not containing a label means
33067803Scg/// that we can just remove the code.
33167803Scgbool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
33267803Scg  // Null statement, not a label!
33367803Scg  if (S == 0) return false;
33467803Scg
33567803Scg  // If this is a label, we have to emit the code, consider something like:
33667803Scg  // if (0) {  ...  foo:  bar(); }  goto foo;
33767803Scg  if (isa<LabelStmt>(S))
33867803Scg    return true;
33967803Scg
34068376Scg  // If this is a case/default statement, and we haven't seen a switch, we have
34167803Scg  // to emit the code.
34267803Scg  if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
34367803Scg    return true;
34467803Scg
34567803Scg  // If this is a switch statement, we want to ignore cases below it.
34667803Scg  if (isa<SwitchStmt>(S))
34767803Scg    IgnoreCaseStmts = true;
34867803Scg
34967803Scg  // Scan subexpressions for verboten labels.
35067803Scg  for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
35174763Scg       I != E; ++I)
35267803Scg    if (ContainsLabel(*I, IgnoreCaseStmts))
35367803Scg      return true;
35467803Scg
35567803Scg  return false;
35667803Scg}
35767803Scg
35867803Scg
35967803Scg/// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
36067803Scg/// a constant, or if it does but contains a label, return 0.  If it constant
36167803Scg/// folds to 'true' and does not contain a label, return 1, if it constant folds
36267803Scg/// to 'false' and does not contain a label, return -1.
36367803Scgint CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
36467803Scg  // FIXME: Rename and handle conversion of other evaluatable things
36567803Scg  // to bool.
36667803Scg  Expr::EvalResult Result;
36767803Scg  if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
36867803Scg      Result.HasSideEffects)
36967803Scg    return 0;  // Not foldable, not integer or not fully evaluatable.
37067803Scg
37167803Scg  if (CodeGenFunction::ContainsLabel(Cond))
37267803Scg    return 0;  // Contains a label.
37367803Scg
37467803Scg  return Result.Val.getInt().getBoolValue() ? 1 : -1;
37567803Scg}
37667803Scg
37767803Scg
37867803Scg/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
37967803Scg/// statement) to the specified blocks.  Based on the condition, this might try
38067803Scg/// to simplify the codegen of the conditional based on the branch.
38167803Scg///
38267803Scgvoid CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
38367803Scg                                           llvm::BasicBlock *TrueBlock,
38467803Scg                                           llvm::BasicBlock *FalseBlock) {
38570134Scg  if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
38670134Scg    return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
38770134Scg
38870134Scg  if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
38970134Scg    // Handle X && Y in a condition.
39070134Scg    if (CondBOp->getOpcode() == BinaryOperator::LAnd) {
39170134Scg      // If we have "1 && X", simplify the code.  "0 && X" would have constant
39270134Scg      // folded if the case was simple enough.
39367803Scg      if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
39467803Scg        // br(1 && X) -> br(X).
39529415Sjmg        return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
39667803Scg      }
39729415Sjmg
39850723Scg      // If we have "X && 1", simplify the code to use an uncond branch.
39965644Scg      // "X && 0" would have been constant folded to 0.
40065644Scg      if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
40165644Scg        // br(X && 1) -> br(X).
40250723Scg        return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
40350723Scg      }
40484111Scg
40584111Scg      // Emit the LHS as a conditional.  If the LHS conditional is false, we
40684111Scg      // want to jump to the FalseBlock.
40784111Scg      llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
40884111Scg      EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
40970291Scg      EmitBlock(LHSTrue);
41070291Scg
41170291Scg      // Any temporaries created here are conditional.
41274364Scg      BeginConditionalBranch();
41354462Scg      EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
41450723Scg      EndConditionalBranch();
41550723Scg
41670291Scg      return;
41754462Scg    } else if (CondBOp->getOpcode() == BinaryOperator::LOr) {
41850723Scg      // If we have "0 || X", simplify the code.  "1 || X" would have constant
41950723Scg      // folded if the case was simple enough.
42065644Scg      if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
42165644Scg        // br(0 || X) -> br(X).
42265644Scg        return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
42365644Scg      }
42465644Scg
42550723Scg      // If we have "X || 0", simplify the code to use an uncond branch.
42629415Sjmg      // "X || 1" would have been constant folded to 1.
42750723Scg      if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
42867803Scg        // br(X || 0) -> br(X).
42950723Scg        return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
43054462Scg      }
43154462Scg
43254462Scg      // Emit the LHS as a conditional.  If the LHS conditional is true, we
43350723Scg      // want to jump to the TrueBlock.
43467803Scg      llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
43567803Scg      EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
43654462Scg      EmitBlock(LHSFalse);
43750723Scg
43867803Scg      // Any temporaries created here are conditional.
43967803Scg      BeginConditionalBranch();
44054462Scg      EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
44150723Scg      EndConditionalBranch();
44267803Scg
44367803Scg      return;
44454462Scg    }
44558756Scg  }
44667803Scg
44729415Sjmg  if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
44850723Scg    // br(!x, t, f) -> br(x, f, t)
44954462Scg    if (CondUOp->getOpcode() == UnaryOperator::LNot)
45084111Scg      return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
45129415Sjmg  }
45250723Scg
45354462Scg  if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
45484111Scg    // Handle ?: operator.
45570291Scg
45670291Scg    // Just ignore GNU ?: extension.
45770291Scg    if (CondOp->getLHS()) {
45854462Scg      // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
45950723Scg      llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
46050723Scg      llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
46129415Sjmg      EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
46229415Sjmg      EmitBlock(LHSBlock);
46374763Scg      EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
46454462Scg      EmitBlock(RHSBlock);
46567803Scg      EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
46629415Sjmg      return;
46767803Scg    }
46867803Scg  }
46929415Sjmg
47067803Scg  // Emit the code with the fully general case.
47167803Scg  llvm::Value *CondV = EvaluateExprAsBool(Cond);
47267803Scg  Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
47367803Scg}
47429415Sjmg
47567803Scg/// ErrorUnsupported - Print out an error that codegen doesn't support the
47674763Scg/// specified stmt yet.
47767803Scgvoid CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
47874763Scg                                       bool OmitOnError) {
47974763Scg  CGM.ErrorUnsupported(S, Type, OmitOnError);
48041653Sbrian}
48174763Scg
48274763Scgvoid CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty) {
48374763Scg  const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext);
48474763Scg  if (DestPtr->getType() != BP)
48567803Scg    DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
48667803Scg
48767803Scg  // Get size and alignment info for this aggregate.
48867803Scg  std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
48929415Sjmg
49068414Scg  // Don't bother emitting a zero-byte memset.
49168414Scg  if (TypeInfo.first == 0)
49268414Scg    return;
49368414Scg
49468414Scg  // FIXME: Handle variable sized types.
49568414Scg  const llvm::Type *IntPtr = llvm::IntegerType::get(VMContext,
49668414Scg                                                    LLVMPointerWidth);
49768414Scg
49868414Scg  Builder.CreateCall4(CGM.getMemSetFn(), DestPtr,
49968414Scg                 llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext)),
50068414Scg                      // TypeInfo.first describes size in bits.
50168414Scg                      llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
50268414Scg                      llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
50368414Scg                                             TypeInfo.second/8));
50468414Scg}
50570291Scg
50668414Scgllvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelStmt *L) {
50770291Scg  // Make sure that there is a block for the indirect goto.
50868414Scg  if (IndirectBranch == 0)
50968414Scg    GetIndirectGotoBlock();
51068414Scg
51170291Scg  llvm::BasicBlock *BB = getBasicBlockForLabel(L);
51268414Scg
51370291Scg  // Make sure the indirect branch includes all of the address-taken blocks.
51468414Scg  IndirectBranch->addDestination(BB);
51568414Scg  return llvm::BlockAddress::get(CurFn, BB);
51668414Scg}
51750723Scg
51850723Scgllvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
51950723Scg  // If we already made the indirect branch for indirect goto, return its block.
52067803Scg  if (IndirectBranch) return IndirectBranch->getParent();
52150723Scg
52267803Scg  CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto"));
52367803Scg
52450723Scg  const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
52550723Scg
52631361Sjmg  // Create the PHI node that indirect gotos will add entries to.
52750723Scg  llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, "indirect.goto.dest");
52867803Scg
52950723Scg  // Create the indirect branch instruction.
53067803Scg  IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
53167803Scg  return IndirectBranch->getParent();
53267803Scg}
53329415Sjmg
53474763Scgllvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) {
53567803Scg  llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
53670291Scg
53767803Scg  assert(SizeEntry && "Did not emit size for type");
53870291Scg  return SizeEntry;
53967803Scg}
54029415Sjmg
54167803Scgllvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) {
54229415Sjmg  assert(Ty->isVariablyModifiedType() &&
54367803Scg         "Must pass variably modified type to EmitVLASizes!");
54468414Scg
54570291Scg  EnsureInsertPoint();
54670291Scg
54770291Scg  if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
54870291Scg    llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
54967803Scg
55067803Scg    if (!SizeEntry) {
55167803Scg      const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
55270291Scg
55370291Scg      // Get the element size;
55470291Scg      QualType ElemTy = VAT->getElementType();
55570291Scg      llvm::Value *ElemSize;
55667803Scg      if (ElemTy->isVariableArrayType())
55767803Scg        ElemSize = EmitVLASize(ElemTy);
55870291Scg      else
55970291Scg        ElemSize = llvm::ConstantInt::get(SizeTy,
56070291Scg            getContext().getTypeSizeInChars(ElemTy).getQuantity());
56170291Scg
56267803Scg      llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
56370291Scg      NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
56470291Scg
56570291Scg      SizeEntry = Builder.CreateMul(ElemSize, NumElements);
56670291Scg    }
56767803Scg
56850723Scg    return SizeEntry;
56967803Scg  }
57029415Sjmg
57170291Scg  if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
57270291Scg    EmitVLASize(AT->getElementType());
57329415Sjmg    return 0;
57467803Scg  }
57568414Scg
57668414Scg  const PointerType *PT = Ty->getAs<PointerType>();
57767803Scg  assert(PT && "unknown VM type!");
57855706Scg  EmitVLASize(PT->getPointeeType());
57967803Scg  return 0;
58067803Scg}
58167803Scg
58267803Scgllvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
58367803Scg  if (CGM.getContext().getBuiltinVaListType()->isArrayType()) {
58467803Scg    return EmitScalarExpr(E);
58555706Scg  }
58667803Scg  return EmitLValue(E).getAddress();
58767803Scg}
58867803Scg
58967803Scgvoid CodeGenFunction::PushCleanupBlock(llvm::BasicBlock *CleanupEntryBlock,
59067803Scg                                       llvm::BasicBlock *CleanupExitBlock,
59167803Scg                                       llvm::BasicBlock *PreviousInvokeDest,
59267803Scg                                       bool EHOnly) {
59367803Scg  CleanupEntries.push_back(CleanupEntry(CleanupEntryBlock, CleanupExitBlock,
59467803Scg                                        PreviousInvokeDest, EHOnly));
59567803Scg}
59667803Scg
59767803Scgvoid CodeGenFunction::EmitCleanupBlocks(size_t OldCleanupStackSize) {
59867803Scg  assert(CleanupEntries.size() >= OldCleanupStackSize &&
59967803Scg         "Cleanup stack mismatch!");
60070291Scg
60167803Scg  while (CleanupEntries.size() > OldCleanupStackSize)
60250723Scg    EmitCleanupBlock();
60350723Scg}
60467803Scg
60567803ScgCodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock() {
60667803Scg  CleanupEntry &CE = CleanupEntries.back();
60767803Scg
60867803Scg  llvm::BasicBlock *CleanupEntryBlock = CE.CleanupEntryBlock;
60967803Scg
61029415Sjmg  std::vector<llvm::BasicBlock *> Blocks;
61167803Scg  std::swap(Blocks, CE.Blocks);
61267803Scg
61367803Scg  std::vector<llvm::BranchInst *> BranchFixups;
61467803Scg  std::swap(BranchFixups, CE.BranchFixups);
61567803Scg
61667803Scg  bool EHOnly = CE.EHOnly;
61767803Scg
61867803Scg  setInvokeDest(CE.PreviousInvokeDest);
61967803Scg
62067803Scg  CleanupEntries.pop_back();
62167803Scg
62267803Scg  // Check if any branch fixups pointed to the scope we just popped. If so,
62367803Scg  // we can remove them.
62467803Scg  for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
62570291Scg    llvm::BasicBlock *Dest = BranchFixups[i]->getSuccessor(0);
62667803Scg    BlockScopeMap::iterator I = BlockScopes.find(Dest);
62729415Sjmg
62874763Scg    if (I == BlockScopes.end())
62967803Scg      continue;
63067803Scg
63150723Scg    assert(I->second <= CleanupEntries.size() && "Invalid branch fixup!");
63229415Sjmg
63355706Scg    if (I->second == CleanupEntries.size()) {
63455706Scg      // We don't need to do this branch fixup.
63574763Scg      BranchFixups[i] = BranchFixups.back();
63655706Scg      BranchFixups.pop_back();
63755706Scg      i--;
63855706Scg      e--;
63955706Scg      continue;
64055706Scg    }
64155706Scg  }
64255706Scg
64367803Scg  llvm::BasicBlock *SwitchBlock = CE.CleanupExitBlock;
64467803Scg  llvm::BasicBlock *EndBlock = 0;
64584111Scg  if (!BranchFixups.empty()) {
64655706Scg    if (!SwitchBlock)
64767803Scg      SwitchBlock = createBasicBlock("cleanup.switch");
64855706Scg    EndBlock = createBasicBlock("cleanup.end");
64955706Scg
65055706Scg    llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
65155706Scg
65270134Scg    Builder.SetInsertPoint(SwitchBlock);
65355706Scg
65455706Scg    llvm::Value *DestCodePtr
65567803Scg      = CreateTempAlloca(llvm::Type::getInt32Ty(VMContext),
65655706Scg                         "cleanup.dst");
65767803Scg    llvm::Value *DestCode = Builder.CreateLoad(DestCodePtr, "tmp");
65867803Scg
65967803Scg    // Create a switch instruction to determine where to jump next.
66067803Scg    llvm::SwitchInst *SI = Builder.CreateSwitch(DestCode, EndBlock,
66155706Scg                                                BranchFixups.size());
66255706Scg
66355706Scg    // Restore the current basic block (if any)
66455706Scg    if (CurBB) {
66570134Scg      Builder.SetInsertPoint(CurBB);
66655706Scg
66755706Scg      // If we had a current basic block, we also need to emit an instruction
66855706Scg      // to initialize the cleanup destination.
66967803Scg      Builder.CreateStore(llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)),
67067803Scg                          DestCodePtr);
67155706Scg    } else
67255706Scg      Builder.ClearInsertionPoint();
67355706Scg
67470134Scg    for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
67555706Scg      llvm::BranchInst *BI = BranchFixups[i];
67655706Scg      llvm::BasicBlock *Dest = BI->getSuccessor(0);
67755706Scg
67867803Scg      // Fixup the branch instruction to point to the cleanup block.
67970291Scg      BI->setSuccessor(0, CleanupEntryBlock);
68055706Scg
68155706Scg      if (CleanupEntries.empty()) {
68255706Scg        llvm::ConstantInt *ID;
68370134Scg
68455706Scg        // Check if we already have a destination for this block.
68555706Scg        if (Dest == SI->getDefaultDest())
68667803Scg          ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0);
68755706Scg        else {
68860958Scg          ID = SI->findCaseDest(Dest);
68955706Scg          if (!ID) {
69055706Scg            // No code found, get a new unique one by using the number of
69155706Scg            // switch successors.
69267803Scg            ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
69355706Scg                                        SI->getNumSuccessors());
69467803Scg            SI->addCase(ID, Dest);
69568376Scg          }
69667803Scg        }
69767803Scg
69855706Scg        // Store the jump destination before the branch instruction.
69955706Scg        new llvm::StoreInst(ID, DestCodePtr, BI);
70055706Scg      } else {
70155706Scg        // We need to jump through another cleanup block. Create a pad block
70270134Scg        // with a branch instruction that jumps to the final destination and add
70355706Scg        // it as a branch fixup to the current cleanup scope.
70455706Scg
70555706Scg        // Create the pad block.
70670291Scg        llvm::BasicBlock *CleanupPad = createBasicBlock("cleanup.pad", CurFn);
70755706Scg
70855706Scg        // Create a unique case ID.
70974763Scg        llvm::ConstantInt *ID
71070134Scg          = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
71155706Scg                                   SI->getNumSuccessors());
71255706Scg
71367803Scg        // Store the jump destination before the branch instruction.
71455706Scg        new llvm::StoreInst(ID, DestCodePtr, BI);
71567803Scg
71655706Scg        // Add it as the destination.
71755706Scg        SI->addCase(ID, CleanupPad);
71867803Scg
71955706Scg        // Create the branch to the final destination.
72055706Scg        llvm::BranchInst *BI = llvm::BranchInst::Create(Dest);
72129415Sjmg        CleanupPad->getInstList().push_back(BI);
72270134Scg
72329415Sjmg        // And add it as a branch fixup.
72467803Scg        CleanupEntries.back().BranchFixups.push_back(BI);
72567803Scg      }
72631361Sjmg    }
72767803Scg  }
72829415Sjmg
72967803Scg  // Remove all blocks from the block scope map.
73029415Sjmg  for (size_t i = 0, e = Blocks.size(); i != e; ++i) {
73129415Sjmg    assert(BlockScopes.count(Blocks[i]) &&
73270134Scg           "Did not find block in scope map!");
73370134Scg
73470134Scg    BlockScopes.erase(Blocks[i]);
73570134Scg  }
73670134Scg
73770134Scg  return CleanupBlockInfo(CleanupEntryBlock, SwitchBlock, EndBlock, EHOnly);
73870134Scg}
73970134Scg
74070134Scgvoid CodeGenFunction::EmitCleanupBlock() {
74170134Scg  CleanupBlockInfo Info = PopCleanupBlock();
74270134Scg
74370134Scg  if (Info.EHOnly) {
74470134Scg    // FIXME: Add this to the exceptional edge
74567803Scg    if (Info.CleanupBlock->getNumUses() == 0)
74629415Sjmg      delete Info.CleanupBlock;
74729415Sjmg    return;
74867803Scg  }
74953553Stanimura
75054462Scg  llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
75155092Sdfr  if (CurBB && !CurBB->getTerminator() &&
75253553Stanimura      Info.CleanupBlock->getNumUses() == 0) {
75353553Stanimura    CurBB->getInstList().splice(CurBB->end(), Info.CleanupBlock->getInstList());
75454462Scg    delete Info.CleanupBlock;
75554462Scg  } else
75653553Stanimura    EmitBlock(Info.CleanupBlock);
75753553Stanimura
75854462Scg  if (Info.SwitchBlock)
75954791Scg    EmitBlock(Info.SwitchBlock);
76054462Scg  if (Info.EndBlock)
76167803Scg    EmitBlock(Info.EndBlock);
76267803Scg}
76367803Scg
76467803Scgvoid CodeGenFunction::AddBranchFixup(llvm::BranchInst *BI) {
76567803Scg  assert(!CleanupEntries.empty() &&
76667803Scg         "Trying to add branch fixup without cleanup block!");
76758756Scg
76853553Stanimura  // FIXME: We could be more clever here and check if there's already a branch
76953553Stanimura  // fixup for this destination and recycle it.
77053553Stanimura  CleanupEntries.back().BranchFixups.push_back(BI);
77167803Scg}
77253553Stanimura
77353553Stanimuravoid CodeGenFunction::EmitBranchThroughCleanup(llvm::BasicBlock *Dest) {
77455092Sdfr  if (!HaveInsertPoint())
77584111Scg    return;
77653553Stanimura
77778564Sgreid  llvm::BranchInst* BI = Builder.CreateBr(Dest);
77855706Scg
77955706Scg  Builder.ClearInsertionPoint();
78053553Stanimura
78174763Scg  // The stack is empty, no need to do any cleanup.
78274763Scg  if (CleanupEntries.empty())
78354462Scg    return;
78454462Scg
78584111Scg  if (!Dest->getParent()) {
78654462Scg    // We are trying to branch to a block that hasn't been inserted yet.
78767803Scg    AddBranchFixup(BI);
78867803Scg    return;
78967803Scg  }
79067803Scg
79170134Scg  BlockScopeMap::iterator I = BlockScopes.find(Dest);
79267803Scg  if (I == BlockScopes.end()) {
79374763Scg    // We are trying to jump to a block that is outside of any cleanup scope.
79467803Scg    AddBranchFixup(BI);
79567803Scg    return;
79670291Scg  }
79767803Scg
79867803Scg  assert(I->second < CleanupEntries.size() &&
79967803Scg         "Trying to branch into cleanup region");
80067803Scg
80167803Scg  if (I->second == CleanupEntries.size() - 1) {
80267803Scg    // We have a branch to a block in the same scope.
80367803Scg    return;
80467803Scg  }
80584111Scg
80667803Scg  AddBranchFixup(BI);
80767803Scg}
80867803Scg