CGExprScalar.cpp revision 206084
1321936Shselasky//===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===// 2321936Shselasky// 3321936Shselasky// The LLVM Compiler Infrastructure 4321936Shselasky// 5321936Shselasky// This file is distributed under the University of Illinois Open Source 6321936Shselasky// License. See LICENSE.TXT for details. 7321936Shselasky// 8321936Shselasky//===----------------------------------------------------------------------===// 9321936Shselasky// 10321936Shselasky// This contains code to emit Expr nodes with scalar LLVM types as LLVM code. 11321936Shselasky// 12321936Shselasky//===----------------------------------------------------------------------===// 13321936Shselasky 14321936Shselasky#include "CodeGenFunction.h" 15321936Shselasky#include "CGObjCRuntime.h" 16321936Shselasky#include "CodeGenModule.h" 17321936Shselasky#include "clang/AST/ASTContext.h" 18321936Shselasky#include "clang/AST/DeclObjC.h" 19321936Shselasky#include "clang/AST/RecordLayout.h" 20321936Shselasky#include "clang/AST/StmtVisitor.h" 21321936Shselasky#include "clang/Basic/TargetInfo.h" 22321936Shselasky#include "llvm/Constants.h" 23321936Shselasky#include "llvm/Function.h" 24321936Shselasky#include "llvm/GlobalVariable.h" 25321936Shselasky#include "llvm/Intrinsics.h" 26321936Shselasky#include "llvm/Module.h" 27321936Shselasky#include "llvm/Support/CFG.h" 28321936Shselasky#include "llvm/Target/TargetData.h" 29321936Shselasky#include <cstdarg> 30321936Shselasky 31321936Shselaskyusing namespace clang; 32321936Shselaskyusing namespace CodeGen; 33321936Shselaskyusing llvm::Value; 34321936Shselasky 35321936Shselasky//===----------------------------------------------------------------------===// 36321936Shselasky// Scalar Expression Emitter 37321936Shselasky//===----------------------------------------------------------------------===// 38321936Shselasky 39321936Shselaskystruct BinOpInfo { 40321936Shselasky Value *LHS; 41321936Shselasky Value *RHS; 42321936Shselasky QualType Ty; // Computation Type. 43321936Shselasky const BinaryOperator *E; 44321936Shselasky}; 45321936Shselasky 46321936Shselaskynamespace { 47321936Shselaskyclass ScalarExprEmitter 48321936Shselasky : public StmtVisitor<ScalarExprEmitter, Value*> { 49321936Shselasky CodeGenFunction &CGF; 50321936Shselasky CGBuilderTy &Builder; 51321936Shselasky bool IgnoreResultAssign; 52321936Shselasky llvm::LLVMContext &VMContext; 53321936Shselaskypublic: 54321936Shselasky 55321936Shselasky ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false) 56321936Shselasky : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira), 57321936Shselasky VMContext(cgf.getLLVMContext()) { 58321936Shselasky } 59321936Shselasky 60321936Shselasky //===--------------------------------------------------------------------===// 61321936Shselasky // Utilities 62321936Shselasky //===--------------------------------------------------------------------===// 63321936Shselasky 64321936Shselasky bool TestAndClearIgnoreResultAssign() { 65321936Shselasky bool I = IgnoreResultAssign; 66321936Shselasky IgnoreResultAssign = false; 67321936Shselasky return I; 68321936Shselasky } 69321936Shselasky 70321936Shselasky const llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); } 71321936Shselasky LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); } 72321936Shselasky LValue EmitCheckedLValue(const Expr *E) { return CGF.EmitCheckedLValue(E); } 73321936Shselasky 74321936Shselasky Value *EmitLoadOfLValue(LValue LV, QualType T) { 75321936Shselasky return CGF.EmitLoadOfLValue(LV, T).getScalarVal(); 76321936Shselasky } 77321936Shselasky 78321936Shselasky /// EmitLoadOfLValue - Given an expression with complex type that represents a 79321936Shselasky /// value l-value, this method emits the address of the l-value, then loads 80321936Shselasky /// and returns the result. 81321936Shselasky Value *EmitLoadOfLValue(const Expr *E) { 82321936Shselasky return EmitLoadOfLValue(EmitCheckedLValue(E), E->getType()); 83321936Shselasky } 84321936Shselasky 85321936Shselasky /// EmitConversionToBool - Convert the specified expression value to a 86321936Shselasky /// boolean (i1) truth value. This is equivalent to "Val != 0". 87321936Shselasky Value *EmitConversionToBool(Value *Src, QualType DstTy); 88321936Shselasky 89321936Shselasky /// EmitScalarConversion - Emit a conversion from the specified type to the 90321936Shselasky /// specified destination type, both of which are LLVM scalar types. 91321936Shselasky Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy); 92321936Shselasky 93321936Shselasky /// EmitComplexToScalarConversion - Emit a conversion from the specified 94321936Shselasky /// complex type to the specified destination type, where the destination type 95321936Shselasky /// is an LLVM scalar type. 96321936Shselasky Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src, 97321936Shselasky QualType SrcTy, QualType DstTy); 98321936Shselasky 99321936Shselasky //===--------------------------------------------------------------------===// 100321936Shselasky // Visitor Methods 101321936Shselasky //===--------------------------------------------------------------------===// 102321936Shselasky 103321936Shselasky Value *VisitStmt(Stmt *S) { 104321936Shselasky S->dump(CGF.getContext().getSourceManager()); 105321936Shselasky assert(0 && "Stmt can't have complex result type!"); 106321936Shselasky return 0; 107321936Shselasky } 108321936Shselasky Value *VisitExpr(Expr *S); 109321936Shselasky 110321936Shselasky Value *VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr()); } 111321936Shselasky 112321936Shselasky // Leaves. 113321936Shselasky Value *VisitIntegerLiteral(const IntegerLiteral *E) { 114321936Shselasky return llvm::ConstantInt::get(VMContext, E->getValue()); 115321936Shselasky } 116321936Shselasky Value *VisitFloatingLiteral(const FloatingLiteral *E) { 117321936Shselasky return llvm::ConstantFP::get(VMContext, E->getValue()); 118321936Shselasky } 119321936Shselasky Value *VisitCharacterLiteral(const CharacterLiteral *E) { 120321936Shselasky return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue()); 121321936Shselasky } 122321936Shselasky Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 123321936Shselasky return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue()); 124321936Shselasky } 125321936Shselasky Value *VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) { 126321936Shselasky return llvm::Constant::getNullValue(ConvertType(E->getType())); 127321936Shselasky } 128321936Shselasky Value *VisitGNUNullExpr(const GNUNullExpr *E) { 129321936Shselasky return llvm::Constant::getNullValue(ConvertType(E->getType())); 130321936Shselasky } 131321936Shselasky Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) { 132321936Shselasky return llvm::ConstantInt::get(ConvertType(E->getType()), 133321936Shselasky CGF.getContext().typesAreCompatible( 134321936Shselasky E->getArgType1(), E->getArgType2())); 135321936Shselasky } 136321936Shselasky Value *VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E); 137321936Shselasky Value *VisitAddrLabelExpr(const AddrLabelExpr *E) { 138321936Shselasky llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel()); 139321936Shselasky return Builder.CreateBitCast(V, ConvertType(E->getType())); 140321936Shselasky } 141321936Shselasky 142321936Shselasky // l-values. 143321936Shselasky Value *VisitDeclRefExpr(DeclRefExpr *E) { 144321936Shselasky Expr::EvalResult Result; 145321936Shselasky if (E->Evaluate(Result, CGF.getContext()) && Result.Val.isInt()) { 146321936Shselasky assert(!Result.HasSideEffects && "Constant declref with side-effect?!"); 147321936Shselasky return llvm::ConstantInt::get(VMContext, Result.Val.getInt()); 148321936Shselasky } 149321936Shselasky return EmitLoadOfLValue(E); 150321936Shselasky } 151321936Shselasky Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) { 152321936Shselasky return CGF.EmitObjCSelectorExpr(E); 153321936Shselasky } 154321936Shselasky Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) { 155321936Shselasky return CGF.EmitObjCProtocolExpr(E); 156321936Shselasky } 157321936Shselasky Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) { 158321936Shselasky return EmitLoadOfLValue(E); 159321936Shselasky } 160321936Shselasky Value *VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) { 161321936Shselasky return EmitLoadOfLValue(E); 162321936Shselasky } 163321936Shselasky Value *VisitObjCImplicitSetterGetterRefExpr( 164321936Shselasky ObjCImplicitSetterGetterRefExpr *E) { 165321936Shselasky return EmitLoadOfLValue(E); 166321936Shselasky } 167321936Shselasky Value *VisitObjCMessageExpr(ObjCMessageExpr *E) { 168321936Shselasky return CGF.EmitObjCMessageExpr(E).getScalarVal(); 169321936Shselasky } 170321936Shselasky 171321936Shselasky Value *VisitObjCIsaExpr(ObjCIsaExpr *E) { 172321936Shselasky LValue LV = CGF.EmitObjCIsaExpr(E); 173321936Shselasky Value *V = CGF.EmitLoadOfLValue(LV, E->getType()).getScalarVal(); 174321936Shselasky return V; 175321936Shselasky } 176321936Shselasky 177321936Shselasky Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E); 178321936Shselasky Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E); 179321936Shselasky Value *VisitMemberExpr(MemberExpr *E); 180321936Shselasky Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); } 181321936Shselasky Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { 182321936Shselasky return EmitLoadOfLValue(E); 183321936Shselasky } 184321936Shselasky 185321936Shselasky Value *VisitInitListExpr(InitListExpr *E); 186321936Shselasky 187321936Shselasky Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 188321936Shselasky return llvm::Constant::getNullValue(ConvertType(E->getType())); 189321936Shselasky } 190321936Shselasky Value *VisitCastExpr(CastExpr *E) { 191321936Shselasky // Make sure to evaluate VLA bounds now so that we have them for later. 192321936Shselasky if (E->getType()->isVariablyModifiedType()) 193321936Shselasky CGF.EmitVLASize(E->getType()); 194321936Shselasky 195321936Shselasky return EmitCastExpr(E); 196321936Shselasky } 197321936Shselasky Value *EmitCastExpr(CastExpr *E); 198321936Shselasky 199321936Shselasky Value *VisitCallExpr(const CallExpr *E) { 200321936Shselasky if (E->getCallReturnType()->isReferenceType()) 201321936Shselasky return EmitLoadOfLValue(E); 202321936Shselasky 203321936Shselasky return CGF.EmitCallExpr(E).getScalarVal(); 204321936Shselasky } 205321936Shselasky 206321936Shselasky Value *VisitStmtExpr(const StmtExpr *E); 207321936Shselasky 208321936Shselasky Value *VisitBlockDeclRefExpr(const BlockDeclRefExpr *E); 209321936Shselasky 210321936Shselasky // Unary Operators. 211321936Shselasky Value *VisitPrePostIncDec(const UnaryOperator *E, bool isInc, bool isPre) { 212321936Shselasky LValue LV = EmitLValue(E->getSubExpr()); 213321936Shselasky return CGF.EmitScalarPrePostIncDec(E, LV, isInc, isPre); 214321936Shselasky } 215321936Shselasky Value *VisitUnaryPostDec(const UnaryOperator *E) { 216321936Shselasky return VisitPrePostIncDec(E, false, false); 217321936Shselasky } 218321936Shselasky Value *VisitUnaryPostInc(const UnaryOperator *E) { 219321936Shselasky return VisitPrePostIncDec(E, true, false); 220321936Shselasky } 221321936Shselasky Value *VisitUnaryPreDec(const UnaryOperator *E) { 222321936Shselasky return VisitPrePostIncDec(E, false, true); 223321936Shselasky } 224321936Shselasky Value *VisitUnaryPreInc(const UnaryOperator *E) { 225321936Shselasky return VisitPrePostIncDec(E, true, true); 226321936Shselasky } 227321936Shselasky Value *VisitUnaryAddrOf(const UnaryOperator *E) { 228321936Shselasky return EmitLValue(E->getSubExpr()).getAddress(); 229321936Shselasky } 230321936Shselasky Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); } 231321936Shselasky Value *VisitUnaryPlus(const UnaryOperator *E) { 232321936Shselasky // This differs from gcc, though, most likely due to a bug in gcc. 233321936Shselasky TestAndClearIgnoreResultAssign(); 234321936Shselasky return Visit(E->getSubExpr()); 235321936Shselasky } 236321936Shselasky Value *VisitUnaryMinus (const UnaryOperator *E); 237321936Shselasky Value *VisitUnaryNot (const UnaryOperator *E); 238321936Shselasky Value *VisitUnaryLNot (const UnaryOperator *E); 239321936Shselasky Value *VisitUnaryReal (const UnaryOperator *E); 240321936Shselasky Value *VisitUnaryImag (const UnaryOperator *E); 241321936Shselasky Value *VisitUnaryExtension(const UnaryOperator *E) { 242321936Shselasky return Visit(E->getSubExpr()); 243321936Shselasky } 244321936Shselasky Value *VisitUnaryOffsetOf(const UnaryOperator *E); 245321936Shselasky 246321936Shselasky // C++ 247321936Shselasky Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) { 248321936Shselasky return Visit(DAE->getExpr()); 249321936Shselasky } 250321936Shselasky Value *VisitCXXThisExpr(CXXThisExpr *TE) { 251321936Shselasky return CGF.LoadCXXThis(); 252321936Shselasky } 253321936Shselasky 254321936Shselasky Value *VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E) { 255321936Shselasky return CGF.EmitCXXExprWithTemporaries(E).getScalarVal(); 256321936Shselasky } 257321936Shselasky Value *VisitCXXNewExpr(const CXXNewExpr *E) { 258321936Shselasky return CGF.EmitCXXNewExpr(E); 259321936Shselasky } 260321936Shselasky Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) { 261321936Shselasky CGF.EmitCXXDeleteExpr(E); 262321936Shselasky return 0; 263321936Shselasky } 264321936Shselasky Value *VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) { 265321936Shselasky return llvm::ConstantInt::get(Builder.getInt1Ty(), 266321936Shselasky E->EvaluateTrait(CGF.getContext())); 267321936Shselasky } 268321936Shselasky 269321936Shselasky Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) { 270321936Shselasky // C++ [expr.pseudo]p1: 271321936Shselasky // The result shall only be used as the operand for the function call 272321936Shselasky // operator (), and the result of such a call has type void. The only 273321936Shselasky // effect is the evaluation of the postfix-expression before the dot or 274321936Shselasky // arrow. 275321936Shselasky CGF.EmitScalarExpr(E->getBase()); 276321936Shselasky return 0; 277321936Shselasky } 278321936Shselasky 279321936Shselasky Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { 280321936Shselasky return llvm::Constant::getNullValue(ConvertType(E->getType())); 281321936Shselasky } 282321936Shselasky 283321936Shselasky Value *VisitCXXThrowExpr(const CXXThrowExpr *E) { 284321936Shselasky CGF.EmitCXXThrowExpr(E); 285321936Shselasky return 0; 286321936Shselasky } 287321936Shselasky 288321936Shselasky // Binary Operators. 289321936Shselasky Value *EmitMul(const BinOpInfo &Ops) { 290321936Shselasky if (CGF.getContext().getLangOptions().OverflowChecking 291321936Shselasky && Ops.Ty->isSignedIntegerType()) 292321936Shselasky return EmitOverflowCheckedBinOp(Ops); 293321936Shselasky if (Ops.LHS->getType()->isFPOrFPVectorTy()) 294321936Shselasky return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul"); 295321936Shselasky return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul"); 296321936Shselasky } 297321936Shselasky /// Create a binary op that checks for overflow. 298321936Shselasky /// Currently only supports +, - and *. 299321936Shselasky Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops); 300321936Shselasky Value *EmitDiv(const BinOpInfo &Ops); 301321936Shselasky Value *EmitRem(const BinOpInfo &Ops); 302321936Shselasky Value *EmitAdd(const BinOpInfo &Ops); 303321936Shselasky Value *EmitSub(const BinOpInfo &Ops); 304321936Shselasky Value *EmitShl(const BinOpInfo &Ops); 305321936Shselasky Value *EmitShr(const BinOpInfo &Ops); 306321936Shselasky Value *EmitAnd(const BinOpInfo &Ops) { 307321936Shselasky return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and"); 308321936Shselasky } 309321936Shselasky Value *EmitXor(const BinOpInfo &Ops) { 310321936Shselasky return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor"); 311321936Shselasky } 312321936Shselasky Value *EmitOr (const BinOpInfo &Ops) { 313321936Shselasky return Builder.CreateOr(Ops.LHS, Ops.RHS, "or"); 314321936Shselasky } 315321936Shselasky 316321936Shselasky BinOpInfo EmitBinOps(const BinaryOperator *E); 317321936Shselasky Value *EmitCompoundAssign(const CompoundAssignOperator *E, 318321936Shselasky Value *(ScalarExprEmitter::*F)(const BinOpInfo &)); 319321936Shselasky 320321936Shselasky // Binary operators and binary compound assignment operators. 321321936Shselasky#define HANDLEBINOP(OP) \ 322321936Shselasky Value *VisitBin ## OP(const BinaryOperator *E) { \ 323321936Shselasky return Emit ## OP(EmitBinOps(E)); \ 324321936Shselasky } \ 325321936Shselasky Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \ 326321936Shselasky return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \ 327321936Shselasky } 328321936Shselasky HANDLEBINOP(Mul) 329321936Shselasky HANDLEBINOP(Div) 330321936Shselasky HANDLEBINOP(Rem) 331321936Shselasky HANDLEBINOP(Add) 332321936Shselasky HANDLEBINOP(Sub) 333321936Shselasky HANDLEBINOP(Shl) 334321936Shselasky HANDLEBINOP(Shr) 335321936Shselasky HANDLEBINOP(And) 336321936Shselasky HANDLEBINOP(Xor) 337321936Shselasky HANDLEBINOP(Or) 338321936Shselasky#undef HANDLEBINOP 339321936Shselasky 340321936Shselasky // Comparisons. 341321936Shselasky Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc, 342321936Shselasky unsigned SICmpOpc, unsigned FCmpOpc); 343321936Shselasky#define VISITCOMP(CODE, UI, SI, FP) \ 344321936Shselasky Value *VisitBin##CODE(const BinaryOperator *E) { \ 345321936Shselasky return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \ 346321936Shselasky llvm::FCmpInst::FP); } 347321936Shselasky VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT) 348321936Shselasky VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT) 349321936Shselasky VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE) 350321936Shselasky VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE) 351321936Shselasky VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ) 352321936Shselasky VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE) 353321936Shselasky#undef VISITCOMP 354321936Shselasky 355321936Shselasky Value *VisitBinAssign (const BinaryOperator *E); 356321936Shselasky 357321936Shselasky Value *VisitBinLAnd (const BinaryOperator *E); 358321936Shselasky Value *VisitBinLOr (const BinaryOperator *E); 359321936Shselasky Value *VisitBinComma (const BinaryOperator *E); 360321936Shselasky 361321936Shselasky Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); } 362321936Shselasky Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); } 363321936Shselasky 364321936Shselasky // Other Operators. 365321936Shselasky Value *VisitBlockExpr(const BlockExpr *BE); 366321936Shselasky Value *VisitConditionalOperator(const ConditionalOperator *CO); 367321936Shselasky Value *VisitChooseExpr(ChooseExpr *CE); 368321936Shselasky Value *VisitVAArgExpr(VAArgExpr *VE); 369321936Shselasky Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) { 370321936Shselasky return CGF.EmitObjCStringLiteral(E); 371321936Shselasky } 372321936Shselasky}; 373321936Shselasky} // end anonymous namespace. 374321936Shselasky 375321936Shselasky//===----------------------------------------------------------------------===// 376321936Shselasky// Utilities 377321936Shselasky//===----------------------------------------------------------------------===// 378321936Shselasky 379321936Shselasky/// EmitConversionToBool - Convert the specified expression value to a 380321936Shselasky/// boolean (i1) truth value. This is equivalent to "Val != 0". 381321936ShselaskyValue *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) { 382321936Shselasky assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs"); 383321936Shselasky 384321936Shselasky if (SrcType->isRealFloatingType()) { 385321936Shselasky // Compare against 0.0 for fp scalars. 386321936Shselasky llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType()); 387321936Shselasky return Builder.CreateFCmpUNE(Src, Zero, "tobool"); 388321936Shselasky } 389321936Shselasky 390321936Shselasky if (SrcType->isMemberPointerType()) { 391321936Shselasky // Compare against -1. 392321936Shselasky llvm::Value *NegativeOne = llvm::Constant::getAllOnesValue(Src->getType()); 393321936Shselasky return Builder.CreateICmpNE(Src, NegativeOne, "tobool"); 394321936Shselasky } 395321936Shselasky 396321936Shselasky assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) && 397321936Shselasky "Unknown scalar type to convert"); 398321936Shselasky 399321936Shselasky // Because of the type rules of C, we often end up computing a logical value, 400321936Shselasky // then zero extending it to int, then wanting it as a logical value again. 401321936Shselasky // Optimize this common case. 402321936Shselasky if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) { 403321936Shselasky if (ZI->getOperand(0)->getType() == 404321936Shselasky llvm::Type::getInt1Ty(CGF.getLLVMContext())) { 405321936Shselasky Value *Result = ZI->getOperand(0); 406321936Shselasky // If there aren't any more uses, zap the instruction to save space. 407321936Shselasky // Note that there can be more uses, for example if this 408321936Shselasky // is the result of an assignment. 409321936Shselasky if (ZI->use_empty()) 410321936Shselasky ZI->eraseFromParent(); 411321936Shselasky return Result; 412321936Shselasky } 413321936Shselasky } 414321936Shselasky 415321936Shselasky // Compare against an integer or pointer null. 416321936Shselasky llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType()); 417321936Shselasky return Builder.CreateICmpNE(Src, Zero, "tobool"); 418321936Shselasky} 419321936Shselasky 420321936Shselasky/// EmitScalarConversion - Emit a conversion from the specified type to the 421321936Shselasky/// specified destination type, both of which are LLVM scalar types. 422321936ShselaskyValue *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType, 423321936Shselasky QualType DstType) { 424321936Shselasky SrcType = CGF.getContext().getCanonicalType(SrcType); 425321936Shselasky DstType = CGF.getContext().getCanonicalType(DstType); 426321936Shselasky if (SrcType == DstType) return Src; 427321936Shselasky 428321936Shselasky if (DstType->isVoidType()) return 0; 429321936Shselasky 430321936Shselasky llvm::LLVMContext &VMContext = CGF.getLLVMContext(); 431321936Shselasky 432321936Shselasky // Handle conversions to bool first, they are special: comparisons against 0. 433321936Shselasky if (DstType->isBooleanType()) 434321936Shselasky return EmitConversionToBool(Src, SrcType); 435321936Shselasky 436321936Shselasky const llvm::Type *DstTy = ConvertType(DstType); 437321936Shselasky 438321936Shselasky // Ignore conversions like int -> uint. 439321936Shselasky if (Src->getType() == DstTy) 440321936Shselasky return Src; 441321936Shselasky 442321936Shselasky // Handle pointer conversions next: pointers can only be converted to/from 443321936Shselasky // other pointers and integers. Check for pointer types in terms of LLVM, as 444321936Shselasky // some native types (like Obj-C id) may map to a pointer type. 445321936Shselasky if (isa<llvm::PointerType>(DstTy)) { 446321936Shselasky // The source value may be an integer, or a pointer. 447321936Shselasky if (isa<llvm::PointerType>(Src->getType())) 448321936Shselasky return Builder.CreateBitCast(Src, DstTy, "conv"); 449321936Shselasky 450321936Shselasky assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?"); 451321936Shselasky // First, convert to the correct width so that we control the kind of 452321936Shselasky // extension. 453321936Shselasky const llvm::Type *MiddleTy = 454321936Shselasky llvm::IntegerType::get(VMContext, CGF.LLVMPointerWidth); 455321936Shselasky bool InputSigned = SrcType->isSignedIntegerType(); 456321936Shselasky llvm::Value* IntResult = 457321936Shselasky Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv"); 458321936Shselasky // Then, cast to pointer. 459321936Shselasky return Builder.CreateIntToPtr(IntResult, DstTy, "conv"); 460321936Shselasky } 461321936Shselasky 462321936Shselasky if (isa<llvm::PointerType>(Src->getType())) { 463321936Shselasky // Must be an ptr to int cast. 464321936Shselasky assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?"); 465321936Shselasky return Builder.CreatePtrToInt(Src, DstTy, "conv"); 466321936Shselasky } 467321936Shselasky 468321936Shselasky // A scalar can be splatted to an extended vector of the same element type 469321936Shselasky if (DstType->isExtVectorType() && !SrcType->isVectorType()) { 470321936Shselasky // Cast the scalar to element type 471321936Shselasky QualType EltTy = DstType->getAs<ExtVectorType>()->getElementType(); 472321936Shselasky llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy); 473321936Shselasky 474321936Shselasky // Insert the element in element zero of an undef vector 475321936Shselasky llvm::Value *UnV = llvm::UndefValue::get(DstTy); 476321936Shselasky llvm::Value *Idx = 477321936Shselasky llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0); 478321936Shselasky UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp"); 479321936Shselasky 480321936Shselasky // Splat the element across to all elements 481321936Shselasky llvm::SmallVector<llvm::Constant*, 16> Args; 482321936Shselasky unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements(); 483321936Shselasky for (unsigned i = 0; i < NumElements; i++) 484321936Shselasky Args.push_back(llvm::ConstantInt::get( 485321936Shselasky llvm::Type::getInt32Ty(VMContext), 0)); 486321936Shselasky 487321936Shselasky llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements); 488321936Shselasky llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat"); 489321936Shselasky return Yay; 490321936Shselasky } 491321936Shselasky 492321936Shselasky // Allow bitcast from vector to integer/fp of the same size. 493321936Shselasky if (isa<llvm::VectorType>(Src->getType()) || 494321936Shselasky isa<llvm::VectorType>(DstTy)) 495341897Shselasky return Builder.CreateBitCast(Src, DstTy, "conv"); 496321936Shselasky 497321936Shselasky // Finally, we have the arithmetic types: real int/float. 498321936Shselasky if (isa<llvm::IntegerType>(Src->getType())) { 499321936Shselasky bool InputSigned = SrcType->isSignedIntegerType(); 500321936Shselasky if (isa<llvm::IntegerType>(DstTy)) 501321936Shselasky return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv"); 502321936Shselasky else if (InputSigned) 503321936Shselasky return Builder.CreateSIToFP(Src, DstTy, "conv"); 504321936Shselasky else 505321936Shselasky return Builder.CreateUIToFP(Src, DstTy, "conv"); 506321936Shselasky } 507321936Shselasky 508321936Shselasky assert(Src->getType()->isFloatingPointTy() && "Unknown real conversion"); 509321936Shselasky if (isa<llvm::IntegerType>(DstTy)) { 510321936Shselasky if (DstType->isSignedIntegerType()) 511321936Shselasky return Builder.CreateFPToSI(Src, DstTy, "conv"); 512321936Shselasky else 513321936Shselasky return Builder.CreateFPToUI(Src, DstTy, "conv"); 514321936Shselasky } 515321936Shselasky 516321936Shselasky assert(DstTy->isFloatingPointTy() && "Unknown real conversion"); 517321936Shselasky if (DstTy->getTypeID() < Src->getType()->getTypeID()) 518321936Shselasky return Builder.CreateFPTrunc(Src, DstTy, "conv"); 519321936Shselasky else 520321936Shselasky return Builder.CreateFPExt(Src, DstTy, "conv"); 521321936Shselasky} 522321936Shselasky 523321936Shselasky/// EmitComplexToScalarConversion - Emit a conversion from the specified complex 524321936Shselasky/// type to the specified destination type, where the destination type is an 525321936Shselasky/// LLVM scalar type. 526321936ShselaskyValue *ScalarExprEmitter:: 527321936ShselaskyEmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src, 528321936Shselasky QualType SrcTy, QualType DstTy) { 529321936Shselasky // Get the source element type. 530321936Shselasky SrcTy = SrcTy->getAs<ComplexType>()->getElementType(); 531321936Shselasky 532321936Shselasky // Handle conversions to bool first, they are special: comparisons against 0. 533321936Shselasky if (DstTy->isBooleanType()) { 534321936Shselasky // Complex != 0 -> (Real != 0) | (Imag != 0) 535321936Shselasky Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy); 536321936Shselasky Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy); 537321936Shselasky return Builder.CreateOr(Src.first, Src.second, "tobool"); 538321936Shselasky } 539321936Shselasky 540321936Shselasky // C99 6.3.1.7p2: "When a value of complex type is converted to a real type, 541321936Shselasky // the imaginary part of the complex value is discarded and the value of the 542321936Shselasky // real part is converted according to the conversion rules for the 543321936Shselasky // corresponding real type. 544321936Shselasky return EmitScalarConversion(Src.first, SrcTy, DstTy); 545321936Shselasky} 546321936Shselasky 547321936Shselasky 548321936Shselasky//===----------------------------------------------------------------------===// 549321936Shselasky// Visitor Methods 550321936Shselasky//===----------------------------------------------------------------------===// 551321936Shselasky 552321936ShselaskyValue *ScalarExprEmitter::VisitExpr(Expr *E) { 553321936Shselasky CGF.ErrorUnsupported(E, "scalar expression"); 554321936Shselasky if (E->getType()->isVoidType()) 555321936Shselasky return 0; 556321936Shselasky return llvm::UndefValue::get(CGF.ConvertType(E->getType())); 557321936Shselasky} 558321936Shselasky 559321936ShselaskyValue *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) { 560321936Shselasky llvm::SmallVector<llvm::Constant*, 32> indices; 561321936Shselasky for (unsigned i = 2; i < E->getNumSubExprs(); i++) { 562321936Shselasky indices.push_back(cast<llvm::Constant>(CGF.EmitScalarExpr(E->getExpr(i)))); 563321936Shselasky } 564321936Shselasky Value* V1 = CGF.EmitScalarExpr(E->getExpr(0)); 565321936Shselasky Value* V2 = CGF.EmitScalarExpr(E->getExpr(1)); 566321936Shselasky Value* SV = llvm::ConstantVector::get(indices.begin(), indices.size()); 567321936Shselasky return Builder.CreateShuffleVector(V1, V2, SV, "shuffle"); 568321936Shselasky} 569321936ShselaskyValue *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) { 570321936Shselasky Expr::EvalResult Result; 571321936Shselasky if (E->Evaluate(Result, CGF.getContext()) && Result.Val.isInt()) { 572321936Shselasky if (E->isArrow()) 573321936Shselasky CGF.EmitScalarExpr(E->getBase()); 574321936Shselasky else 575321936Shselasky EmitLValue(E->getBase()); 576321936Shselasky return llvm::ConstantInt::get(VMContext, Result.Val.getInt()); 577321936Shselasky } 578321936Shselasky return EmitLoadOfLValue(E); 579321936Shselasky} 580321936Shselasky 581321936ShselaskyValue *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) { 582321936Shselasky TestAndClearIgnoreResultAssign(); 583321936Shselasky 584321936Shselasky // Emit subscript expressions in rvalue context's. For most cases, this just 585321936Shselasky // loads the lvalue formed by the subscript expr. However, we have to be 586321936Shselasky // careful, because the base of a vector subscript is occasionally an rvalue, 587321936Shselasky // so we can't get it as an lvalue. 588321936Shselasky if (!E->getBase()->getType()->isVectorType()) 589321936Shselasky return EmitLoadOfLValue(E); 590321936Shselasky 591321936Shselasky // Handle the vector case. The base must be a vector, the index must be an 592321936Shselasky // integer value. 593321936Shselasky Value *Base = Visit(E->getBase()); 594321936Shselasky Value *Idx = Visit(E->getIdx()); 595321936Shselasky bool IdxSigned = E->getIdx()->getType()->isSignedIntegerType(); 596321936Shselasky Idx = Builder.CreateIntCast(Idx, 597321936Shselasky llvm::Type::getInt32Ty(CGF.getLLVMContext()), 598321936Shselasky IdxSigned, 599321936Shselasky "vecidxcast"); 600321936Shselasky return Builder.CreateExtractElement(Base, Idx, "vecext"); 601321936Shselasky} 602321936Shselasky 603321936Shselaskystatic llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx, 604321936Shselasky unsigned Off, const llvm::Type *I32Ty) { 605321936Shselasky int MV = SVI->getMaskValue(Idx); 606321936Shselasky if (MV == -1) 607321936Shselasky return llvm::UndefValue::get(I32Ty); 608321936Shselasky return llvm::ConstantInt::get(I32Ty, Off+MV); 609321936Shselasky} 610321936Shselasky 611321936ShselaskyValue *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) { 612321936Shselasky bool Ignore = TestAndClearIgnoreResultAssign(); 613321936Shselasky (void)Ignore; 614321936Shselasky assert (Ignore == false && "init list ignored"); 615321936Shselasky unsigned NumInitElements = E->getNumInits(); 616321936Shselasky 617321936Shselasky if (E->hadArrayRangeDesignator()) 618321936Shselasky CGF.ErrorUnsupported(E, "GNU array range designator extension"); 619321936Shselasky 620321936Shselasky const llvm::VectorType *VType = 621321936Shselasky dyn_cast<llvm::VectorType>(ConvertType(E->getType())); 622321936Shselasky 623321936Shselasky // We have a scalar in braces. Just use the first element. 624321936Shselasky if (!VType) 625321936Shselasky return Visit(E->getInit(0)); 626321936Shselasky 627321936Shselasky unsigned ResElts = VType->getNumElements(); 628321936Shselasky const llvm::Type *I32Ty = llvm::Type::getInt32Ty(CGF.getLLVMContext()); 629321936Shselasky 630321936Shselasky // Loop over initializers collecting the Value for each, and remembering 631321936Shselasky // whether the source was swizzle (ExtVectorElementExpr). This will allow 632321936Shselasky // us to fold the shuffle for the swizzle into the shuffle for the vector 633321936Shselasky // initializer, since LLVM optimizers generally do not want to touch 634321936Shselasky // shuffles. 635321936Shselasky unsigned CurIdx = 0; 636321936Shselasky bool VIsUndefShuffle = false; 637321936Shselasky llvm::Value *V = llvm::UndefValue::get(VType); 638321936Shselasky for (unsigned i = 0; i != NumInitElements; ++i) { 639321936Shselasky Expr *IE = E->getInit(i); 640321936Shselasky Value *Init = Visit(IE); 641321936Shselasky llvm::SmallVector<llvm::Constant*, 16> Args; 642321936Shselasky 643321936Shselasky const llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType()); 644321936Shselasky 645321936Shselasky // Handle scalar elements. If the scalar initializer is actually one 646321936Shselasky // element of a different vector of the same width, use shuffle instead of 647321936Shselasky // extract+insert. 648321936Shselasky if (!VVT) { 649321936Shselasky if (isa<ExtVectorElementExpr>(IE)) { 650321936Shselasky llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init); 651321936Shselasky 652321936Shselasky if (EI->getVectorOperandType()->getNumElements() == ResElts) { 653321936Shselasky llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand()); 654321936Shselasky Value *LHS = 0, *RHS = 0; 655321936Shselasky if (CurIdx == 0) { 656321936Shselasky // insert into undef -> shuffle (src, undef) 657321936Shselasky Args.push_back(C); 658321936Shselasky for (unsigned j = 1; j != ResElts; ++j) 659321936Shselasky Args.push_back(llvm::UndefValue::get(I32Ty)); 660321936Shselasky 661321936Shselasky LHS = EI->getVectorOperand(); 662321936Shselasky RHS = V; 663321936Shselasky VIsUndefShuffle = true; 664321936Shselasky } else if (VIsUndefShuffle) { 665321936Shselasky // insert into undefshuffle && size match -> shuffle (v, src) 666321936Shselasky llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V); 667321936Shselasky for (unsigned j = 0; j != CurIdx; ++j) 668321936Shselasky Args.push_back(getMaskElt(SVV, j, 0, I32Ty)); 669321936Shselasky Args.push_back(llvm::ConstantInt::get(I32Ty, 670321936Shselasky ResElts + C->getZExtValue())); 671321936Shselasky for (unsigned j = CurIdx + 1; j != ResElts; ++j) 672321936Shselasky Args.push_back(llvm::UndefValue::get(I32Ty)); 673321936Shselasky 674321936Shselasky LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0); 675321936Shselasky RHS = EI->getVectorOperand(); 676321936Shselasky VIsUndefShuffle = false; 677321936Shselasky } 678321936Shselasky if (!Args.empty()) { 679321936Shselasky llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], ResElts); 680321936Shselasky V = Builder.CreateShuffleVector(LHS, RHS, Mask); 681321936Shselasky ++CurIdx; 682321936Shselasky continue; 683321936Shselasky } 684321936Shselasky } 685321936Shselasky } 686321936Shselasky Value *Idx = llvm::ConstantInt::get(I32Ty, CurIdx); 687321936Shselasky V = Builder.CreateInsertElement(V, Init, Idx, "vecinit"); 688321936Shselasky VIsUndefShuffle = false; 689321936Shselasky ++CurIdx; 690321936Shselasky continue; 691321936Shselasky } 692321936Shselasky 693321936Shselasky unsigned InitElts = VVT->getNumElements(); 694321936Shselasky 695321936Shselasky // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's 696321936Shselasky // input is the same width as the vector being constructed, generate an 697321936Shselasky // optimized shuffle of the swizzle input into the result. 698321936Shselasky unsigned Offset = (CurIdx == 0) ? 0 : ResElts; 699321936Shselasky if (isa<ExtVectorElementExpr>(IE)) { 700321936Shselasky llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init); 701321936Shselasky Value *SVOp = SVI->getOperand(0); 702321936Shselasky const llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType()); 703321936Shselasky 704321936Shselasky if (OpTy->getNumElements() == ResElts) { 705321936Shselasky for (unsigned j = 0; j != CurIdx; ++j) { 706321936Shselasky // If the current vector initializer is a shuffle with undef, merge 707321936Shselasky // this shuffle directly into it. 708321936Shselasky if (VIsUndefShuffle) { 709321936Shselasky Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0, 710321936Shselasky I32Ty)); 711321936Shselasky } else { 712321936Shselasky Args.push_back(llvm::ConstantInt::get(I32Ty, j)); 713321936Shselasky } 714321936Shselasky } 715321936Shselasky for (unsigned j = 0, je = InitElts; j != je; ++j) 716321936Shselasky Args.push_back(getMaskElt(SVI, j, Offset, I32Ty)); 717321936Shselasky for (unsigned j = CurIdx + InitElts; j != ResElts; ++j) 718321936Shselasky Args.push_back(llvm::UndefValue::get(I32Ty)); 719321936Shselasky 720321936Shselasky if (VIsUndefShuffle) 721321936Shselasky V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0); 722321936Shselasky 723321936Shselasky Init = SVOp; 724321936Shselasky } 725321936Shselasky } 726321936Shselasky 727321936Shselasky // Extend init to result vector length, and then shuffle its contribution 728321936Shselasky // to the vector initializer into V. 729321936Shselasky if (Args.empty()) { 730321936Shselasky for (unsigned j = 0; j != InitElts; ++j) 731321936Shselasky Args.push_back(llvm::ConstantInt::get(I32Ty, j)); 732321936Shselasky for (unsigned j = InitElts; j != ResElts; ++j) 733321936Shselasky Args.push_back(llvm::UndefValue::get(I32Ty)); 734321936Shselasky llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], ResElts); 735321936Shselasky Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT), 736321936Shselasky Mask, "vext"); 737321936Shselasky 738321936Shselasky Args.clear(); 739321936Shselasky for (unsigned j = 0; j != CurIdx; ++j) 740321936Shselasky Args.push_back(llvm::ConstantInt::get(I32Ty, j)); 741321936Shselasky for (unsigned j = 0; j != InitElts; ++j) 742321936Shselasky Args.push_back(llvm::ConstantInt::get(I32Ty, j+Offset)); 743321936Shselasky for (unsigned j = CurIdx + InitElts; j != ResElts; ++j) 744321936Shselasky Args.push_back(llvm::UndefValue::get(I32Ty)); 745321936Shselasky } 746321936Shselasky 747321936Shselasky // If V is undef, make sure it ends up on the RHS of the shuffle to aid 748321936Shselasky // merging subsequent shuffles into this one. 749321936Shselasky if (CurIdx == 0) 750321936Shselasky std::swap(V, Init); 751321936Shselasky llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], ResElts); 752321936Shselasky V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit"); 753321936Shselasky VIsUndefShuffle = isa<llvm::UndefValue>(Init); 754321936Shselasky CurIdx += InitElts; 755321936Shselasky } 756321936Shselasky 757321936Shselasky // FIXME: evaluate codegen vs. shuffling against constant null vector. 758321936Shselasky // Emit remaining default initializers. 759321936Shselasky const llvm::Type *EltTy = VType->getElementType(); 760321936Shselasky 761321936Shselasky // Emit remaining default initializers 762321936Shselasky for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) { 763321936Shselasky Value *Idx = llvm::ConstantInt::get(I32Ty, CurIdx); 764321936Shselasky llvm::Value *Init = llvm::Constant::getNullValue(EltTy); 765321936Shselasky V = Builder.CreateInsertElement(V, Init, Idx, "vecinit"); 766321936Shselasky } 767321936Shselasky return V; 768321936Shselasky} 769321936Shselasky 770321936Shselaskystatic bool ShouldNullCheckClassCastValue(const CastExpr *CE) { 771321936Shselasky const Expr *E = CE->getSubExpr(); 772321936Shselasky 773321936Shselasky if (CE->getCastKind() == CastExpr::CK_UncheckedDerivedToBase) 774321936Shselasky return false; 775321936Shselasky 776321936Shselasky if (isa<CXXThisExpr>(E)) { 777321936Shselasky // We always assume that 'this' is never null. 778321936Shselasky return false; 779321936Shselasky } 780321936Shselasky 781321936Shselasky if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) { 782321936Shselasky // And that lvalue casts are never null. 783321936Shselasky if (ICE->isLvalueCast()) 784321936Shselasky return false; 785321936Shselasky } 786321936Shselasky 787321936Shselasky return true; 788321936Shselasky} 789321936Shselasky 790321936Shselasky// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts 791321936Shselasky// have to handle a more broad range of conversions than explicit casts, as they 792321936Shselasky// handle things like function to ptr-to-function decay etc. 793321936ShselaskyValue *ScalarExprEmitter::EmitCastExpr(CastExpr *CE) { 794321936Shselasky Expr *E = CE->getSubExpr(); 795321936Shselasky QualType DestTy = CE->getType(); 796321936Shselasky CastExpr::CastKind Kind = CE->getCastKind(); 797321936Shselasky 798321936Shselasky if (!DestTy->isVoidType()) 799321936Shselasky TestAndClearIgnoreResultAssign(); 800321936Shselasky 801321936Shselasky // Since almost all cast kinds apply to scalars, this switch doesn't have 802321936Shselasky // a default case, so the compiler will warn on a missing case. The cases 803321936Shselasky // are in the same order as in the CastKind enum. 804321936Shselasky switch (Kind) { 805321936Shselasky case CastExpr::CK_Unknown: 806321936Shselasky // FIXME: All casts should have a known kind! 807321936Shselasky //assert(0 && "Unknown cast kind!"); 808321936Shselasky break; 809321936Shselasky 810321936Shselasky case CastExpr::CK_AnyPointerToObjCPointerCast: 811321936Shselasky case CastExpr::CK_AnyPointerToBlockPointerCast: 812321936Shselasky case CastExpr::CK_BitCast: { 813321936Shselasky Value *Src = Visit(const_cast<Expr*>(E)); 814321936Shselasky return Builder.CreateBitCast(Src, ConvertType(DestTy)); 815321936Shselasky } 816321936Shselasky case CastExpr::CK_NoOp: 817321936Shselasky case CastExpr::CK_UserDefinedConversion: 818321936Shselasky return Visit(const_cast<Expr*>(E)); 819321936Shselasky 820321936Shselasky case CastExpr::CK_BaseToDerived: { 821321936Shselasky const CXXRecordDecl *BaseClassDecl = 822321936Shselasky E->getType()->getCXXRecordDeclForPointerType(); 823321936Shselasky const CXXRecordDecl *DerivedClassDecl = 824321936Shselasky DestTy->getCXXRecordDeclForPointerType(); 825321936Shselasky 826321936Shselasky Value *Src = Visit(const_cast<Expr*>(E)); 827321936Shselasky 828321936Shselasky bool NullCheckValue = ShouldNullCheckClassCastValue(CE); 829321936Shselasky return CGF.GetAddressOfDerivedClass(Src, BaseClassDecl, DerivedClassDecl, 830321936Shselasky NullCheckValue); 831321936Shselasky } 832321936Shselasky case CastExpr::CK_UncheckedDerivedToBase: 833321936Shselasky case CastExpr::CK_DerivedToBase: { 834321936Shselasky const RecordType *DerivedClassTy = 835321936Shselasky E->getType()->getAs<PointerType>()->getPointeeType()->getAs<RecordType>(); 836321936Shselasky CXXRecordDecl *DerivedClassDecl = 837321936Shselasky cast<CXXRecordDecl>(DerivedClassTy->getDecl()); 838321936Shselasky 839321936Shselasky const RecordType *BaseClassTy = 840321936Shselasky DestTy->getAs<PointerType>()->getPointeeType()->getAs<RecordType>(); 841321936Shselasky CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseClassTy->getDecl()); 842321936Shselasky 843321936Shselasky Value *Src = Visit(const_cast<Expr*>(E)); 844321936Shselasky 845321936Shselasky bool NullCheckValue = ShouldNullCheckClassCastValue(CE); 846321936Shselasky return CGF.GetAddressOfBaseClass(Src, DerivedClassDecl, BaseClassDecl, 847321936Shselasky NullCheckValue); 848321936Shselasky } 849321936Shselasky case CastExpr::CK_Dynamic: { 850321936Shselasky Value *V = Visit(const_cast<Expr*>(E)); 851321936Shselasky const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE); 852321936Shselasky return CGF.EmitDynamicCast(V, DCE); 853321936Shselasky } 854321936Shselasky case CastExpr::CK_ToUnion: 855321936Shselasky assert(0 && "Should be unreachable!"); 856321936Shselasky break; 857321936Shselasky 858321936Shselasky case CastExpr::CK_ArrayToPointerDecay: { 859321936Shselasky assert(E->getType()->isArrayType() && 860321936Shselasky "Array to pointer decay must have array source type!"); 861321936Shselasky 862321936Shselasky Value *V = EmitLValue(E).getAddress(); // Bitfields can't be arrays. 863321936Shselasky 864321936Shselasky // Note that VLA pointers are always decayed, so we don't need to do 865321936Shselasky // anything here. 866321936Shselasky if (!E->getType()->isVariableArrayType()) { 867321936Shselasky assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer"); 868321936Shselasky assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType()) 869321936Shselasky ->getElementType()) && 870321936Shselasky "Expected pointer to array"); 871321936Shselasky V = Builder.CreateStructGEP(V, 0, "arraydecay"); 872321936Shselasky } 873321936Shselasky 874321936Shselasky return V; 875321936Shselasky } 876321936Shselasky case CastExpr::CK_FunctionToPointerDecay: 877321936Shselasky return EmitLValue(E).getAddress(); 878321936Shselasky 879321936Shselasky case CastExpr::CK_NullToMemberPointer: 880321936Shselasky return CGF.CGM.EmitNullConstant(DestTy); 881321936Shselasky 882321936Shselasky case CastExpr::CK_BaseToDerivedMemberPointer: 883321936Shselasky case CastExpr::CK_DerivedToBaseMemberPointer: { 884321936Shselasky Value *Src = Visit(E); 885321936Shselasky 886321936Shselasky // See if we need to adjust the pointer. 887321936Shselasky const CXXRecordDecl *BaseDecl = 888321936Shselasky cast<CXXRecordDecl>(E->getType()->getAs<MemberPointerType>()-> 889321936Shselasky getClass()->getAs<RecordType>()->getDecl()); 890321936Shselasky const CXXRecordDecl *DerivedDecl = 891321936Shselasky cast<CXXRecordDecl>(CE->getType()->getAs<MemberPointerType>()-> 892321936Shselasky getClass()->getAs<RecordType>()->getDecl()); 893321936Shselasky if (CE->getCastKind() == CastExpr::CK_DerivedToBaseMemberPointer) 894321936Shselasky std::swap(DerivedDecl, BaseDecl); 895321936Shselasky 896321936Shselasky if (llvm::Constant *Adj = 897321936Shselasky CGF.CGM.GetNonVirtualBaseClassOffset(DerivedDecl, BaseDecl)) { 898321936Shselasky if (CE->getCastKind() == CastExpr::CK_DerivedToBaseMemberPointer) 899321936Shselasky Src = Builder.CreateSub(Src, Adj, "adj"); 900321936Shselasky else 901321936Shselasky Src = Builder.CreateAdd(Src, Adj, "adj"); 902321936Shselasky } 903321936Shselasky return Src; 904321936Shselasky } 905321936Shselasky 906321936Shselasky case CastExpr::CK_ConstructorConversion: 907321936Shselasky assert(0 && "Should be unreachable!"); 908321936Shselasky break; 909321936Shselasky 910321936Shselasky case CastExpr::CK_IntegralToPointer: { 911321936Shselasky Value *Src = Visit(const_cast<Expr*>(E)); 912321936Shselasky 913321936Shselasky // First, convert to the correct width so that we control the kind of 914321936Shselasky // extension. 915321936Shselasky const llvm::Type *MiddleTy = 916321936Shselasky llvm::IntegerType::get(VMContext, CGF.LLVMPointerWidth); 917321936Shselasky bool InputSigned = E->getType()->isSignedIntegerType(); 918321936Shselasky llvm::Value* IntResult = 919321936Shselasky Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv"); 920321936Shselasky 921321936Shselasky return Builder.CreateIntToPtr(IntResult, ConvertType(DestTy)); 922321936Shselasky } 923321936Shselasky case CastExpr::CK_PointerToIntegral: { 924321936Shselasky Value *Src = Visit(const_cast<Expr*>(E)); 925321936Shselasky return Builder.CreatePtrToInt(Src, ConvertType(DestTy)); 926321936Shselasky } 927321936Shselasky case CastExpr::CK_ToVoid: { 928321936Shselasky CGF.EmitAnyExpr(E, 0, false, true); 929321936Shselasky return 0; 930321936Shselasky } 931321936Shselasky case CastExpr::CK_VectorSplat: { 932321936Shselasky const llvm::Type *DstTy = ConvertType(DestTy); 933321936Shselasky Value *Elt = Visit(const_cast<Expr*>(E)); 934321936Shselasky 935321936Shselasky // Insert the element in element zero of an undef vector 936321936Shselasky llvm::Value *UnV = llvm::UndefValue::get(DstTy); 937321936Shselasky llvm::Value *Idx = 938321936Shselasky llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0); 939321936Shselasky UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp"); 940321936Shselasky 941321936Shselasky // Splat the element across to all elements 942321936Shselasky llvm::SmallVector<llvm::Constant*, 16> Args; 943321936Shselasky unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements(); 944321936Shselasky for (unsigned i = 0; i < NumElements; i++) 945321936Shselasky Args.push_back(llvm::ConstantInt::get( 946321936Shselasky llvm::Type::getInt32Ty(VMContext), 0)); 947321936Shselasky 948321936Shselasky llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements); 949321936Shselasky llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat"); 950321936Shselasky return Yay; 951321936Shselasky } 952321936Shselasky case CastExpr::CK_IntegralCast: 953321936Shselasky case CastExpr::CK_IntegralToFloating: 954321936Shselasky case CastExpr::CK_FloatingToIntegral: 955321936Shselasky case CastExpr::CK_FloatingCast: 956321936Shselasky return EmitScalarConversion(Visit(E), E->getType(), DestTy); 957321936Shselasky 958321936Shselasky case CastExpr::CK_MemberPointerToBoolean: 959321936Shselasky return CGF.EvaluateExprAsBool(E); 960321936Shselasky } 961321936Shselasky 962321936Shselasky // Handle cases where the source is an non-complex type. 963321936Shselasky 964321936Shselasky if (!CGF.hasAggregateLLVMType(E->getType())) { 965321936Shselasky Value *Src = Visit(const_cast<Expr*>(E)); 966321936Shselasky 967321936Shselasky // Use EmitScalarConversion to perform the conversion. 968321936Shselasky return EmitScalarConversion(Src, E->getType(), DestTy); 969321936Shselasky } 970321936Shselasky 971321936Shselasky if (E->getType()->isAnyComplexType()) { 972321936Shselasky // Handle cases where the source is a complex type. 973321936Shselasky bool IgnoreImag = true; 974321936Shselasky bool IgnoreImagAssign = true; 975321936Shselasky bool IgnoreReal = IgnoreResultAssign; 976321936Shselasky bool IgnoreRealAssign = IgnoreResultAssign; 977321936Shselasky if (DestTy->isBooleanType()) 978321936Shselasky IgnoreImagAssign = IgnoreImag = false; 979321936Shselasky else if (DestTy->isVoidType()) { 980321936Shselasky IgnoreReal = IgnoreImag = false; 981321936Shselasky IgnoreRealAssign = IgnoreImagAssign = true; 982321936Shselasky } 983321936Shselasky CodeGenFunction::ComplexPairTy V 984321936Shselasky = CGF.EmitComplexExpr(E, IgnoreReal, IgnoreImag, IgnoreRealAssign, 985321936Shselasky IgnoreImagAssign); 986321936Shselasky return EmitComplexToScalarConversion(V, E->getType(), DestTy); 987321936Shselasky } 988321936Shselasky 989321936Shselasky // Okay, this is a cast from an aggregate. It must be a cast to void. Just 990321936Shselasky // evaluate the result and return. 991321936Shselasky CGF.EmitAggExpr(E, 0, false, true); 992321936Shselasky return 0; 993321936Shselasky} 994321936Shselasky 995321936ShselaskyValue *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) { 996321936Shselasky return CGF.EmitCompoundStmt(*E->getSubStmt(), 997321936Shselasky !E->getType()->isVoidType()).getScalarVal(); 998321936Shselasky} 999321936Shselasky 1000321936ShselaskyValue *ScalarExprEmitter::VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) { 1001321936Shselasky llvm::Value *V = CGF.GetAddrOfBlockDecl(E); 1002321936Shselasky if (E->getType().isObjCGCWeak()) 1003321936Shselasky return CGF.CGM.getObjCRuntime().EmitObjCWeakRead(CGF, V); 1004321936Shselasky return Builder.CreateLoad(V, "tmp"); 1005321936Shselasky} 1006321936Shselasky 1007321936Shselasky//===----------------------------------------------------------------------===// 1008321936Shselasky// Unary Operators 1009321936Shselasky//===----------------------------------------------------------------------===// 1010321936Shselasky 1011321936ShselaskyValue *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) { 1012321936Shselasky TestAndClearIgnoreResultAssign(); 1013321936Shselasky Value *Op = Visit(E->getSubExpr()); 1014321936Shselasky if (Op->getType()->isFPOrFPVectorTy()) 1015321936Shselasky return Builder.CreateFNeg(Op, "neg"); 1016321936Shselasky return Builder.CreateNeg(Op, "neg"); 1017321936Shselasky} 1018321936Shselasky 1019321936ShselaskyValue *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) { 1020321936Shselasky TestAndClearIgnoreResultAssign(); 1021321936Shselasky Value *Op = Visit(E->getSubExpr()); 1022321936Shselasky return Builder.CreateNot(Op, "neg"); 1023321936Shselasky} 1024321936Shselasky 1025321936ShselaskyValue *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) { 1026321936Shselasky // Compare operand to zero. 1027321936Shselasky Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr()); 1028321936Shselasky 1029321936Shselasky // Invert value. 1030321936Shselasky // TODO: Could dynamically modify easy computations here. For example, if 1031321936Shselasky // the operand is an icmp ne, turn into icmp eq. 1032321936Shselasky BoolVal = Builder.CreateNot(BoolVal, "lnot"); 1033321936Shselasky 1034321936Shselasky // ZExt result to the expr type. 1035321936Shselasky return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext"); 1036321936Shselasky} 1037321936Shselasky 1038321936Shselasky/// VisitSizeOfAlignOfExpr - Return the size or alignment of the type of 1039321936Shselasky/// argument of the sizeof expression as an integer. 1040321936ShselaskyValue * 1041321936ShselaskyScalarExprEmitter::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) { 1042321936Shselasky QualType TypeToSize = E->getTypeOfArgument(); 1043321936Shselasky if (E->isSizeOf()) { 1044321936Shselasky if (const VariableArrayType *VAT = 1045321936Shselasky CGF.getContext().getAsVariableArrayType(TypeToSize)) { 1046321936Shselasky if (E->isArgumentType()) { 1047321936Shselasky // sizeof(type) - make sure to emit the VLA size. 1048321936Shselasky CGF.EmitVLASize(TypeToSize); 1049321936Shselasky } else { 1050321936Shselasky // C99 6.5.3.4p2: If the argument is an expression of type 1051321936Shselasky // VLA, it is evaluated. 1052321936Shselasky CGF.EmitAnyExpr(E->getArgumentExpr()); 1053321936Shselasky } 1054321936Shselasky 1055321936Shselasky return CGF.GetVLASize(VAT); 1056321936Shselasky } 1057321936Shselasky } 1058321936Shselasky 1059321936Shselasky // If this isn't sizeof(vla), the result must be constant; use the constant 1060321936Shselasky // folding logic so we don't have to duplicate it here. 1061321936Shselasky Expr::EvalResult Result; 1062321936Shselasky E->Evaluate(Result, CGF.getContext()); 1063321936Shselasky return llvm::ConstantInt::get(VMContext, Result.Val.getInt()); 1064321936Shselasky} 1065321936Shselasky 1066321936ShselaskyValue *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) { 1067321936Shselasky Expr *Op = E->getSubExpr(); 1068321936Shselasky if (Op->getType()->isAnyComplexType()) 1069321936Shselasky return CGF.EmitComplexExpr(Op, false, true, false, true).first; 1070321936Shselasky return Visit(Op); 1071321936Shselasky} 1072321936ShselaskyValue *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) { 1073321936Shselasky Expr *Op = E->getSubExpr(); 1074321936Shselasky if (Op->getType()->isAnyComplexType()) 1075321936Shselasky return CGF.EmitComplexExpr(Op, true, false, true, false).second; 1076321936Shselasky 1077321936Shselasky // __imag on a scalar returns zero. Emit the subexpr to ensure side 1078321936Shselasky // effects are evaluated, but not the actual value. 1079321936Shselasky if (E->isLvalue(CGF.getContext()) == Expr::LV_Valid) 1080321936Shselasky CGF.EmitLValue(Op); 1081321936Shselasky else 1082321936Shselasky CGF.EmitScalarExpr(Op, true); 1083321936Shselasky return llvm::Constant::getNullValue(ConvertType(E->getType())); 1084321936Shselasky} 1085321936Shselasky 1086321936ShselaskyValue *ScalarExprEmitter::VisitUnaryOffsetOf(const UnaryOperator *E) { 1087321936Shselasky Value* ResultAsPtr = EmitLValue(E->getSubExpr()).getAddress(); 1088321936Shselasky const llvm::Type* ResultType = ConvertType(E->getType()); 1089321936Shselasky return Builder.CreatePtrToInt(ResultAsPtr, ResultType, "offsetof"); 1090321936Shselasky} 1091321936Shselasky 1092321936Shselasky//===----------------------------------------------------------------------===// 1093321936Shselasky// Binary Operators 1094321936Shselasky//===----------------------------------------------------------------------===// 1095321936Shselasky 1096321936ShselaskyBinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) { 1097321936Shselasky TestAndClearIgnoreResultAssign(); 1098321936Shselasky BinOpInfo Result; 1099321936Shselasky Result.LHS = Visit(E->getLHS()); 1100321936Shselasky Result.RHS = Visit(E->getRHS()); 1101321936Shselasky Result.Ty = E->getType(); 1102321936Shselasky Result.E = E; 1103321936Shselasky return Result; 1104321936Shselasky} 1105321936Shselasky 1106321936ShselaskyValue *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E, 1107321936Shselasky Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) { 1108321936Shselasky bool Ignore = TestAndClearIgnoreResultAssign(); 1109321936Shselasky QualType LHSTy = E->getLHS()->getType(); 1110321936Shselasky 1111321936Shselasky BinOpInfo OpInfo; 1112321936Shselasky 1113321936Shselasky if (E->getComputationResultType()->isAnyComplexType()) { 1114321936Shselasky // This needs to go through the complex expression emitter, but it's a tad 1115321936Shselasky // complicated to do that... I'm leaving it out for now. (Note that we do 1116321936Shselasky // actually need the imaginary part of the RHS for multiplication and 1117321936Shselasky // division.) 1118321936Shselasky CGF.ErrorUnsupported(E, "complex compound assignment"); 1119321936Shselasky return llvm::UndefValue::get(CGF.ConvertType(E->getType())); 1120321936Shselasky } 1121321936Shselasky 1122321936Shselasky // Emit the RHS first. __block variables need to have the rhs evaluated 1123321936Shselasky // first, plus this should improve codegen a little. 1124321936Shselasky OpInfo.RHS = Visit(E->getRHS()); 1125321936Shselasky OpInfo.Ty = E->getComputationResultType(); 1126321936Shselasky OpInfo.E = E; 1127321936Shselasky // Load/convert the LHS. 1128321936Shselasky LValue LHSLV = EmitCheckedLValue(E->getLHS()); 1129321936Shselasky OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy); 1130321936Shselasky OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy, 1131321936Shselasky E->getComputationLHSType()); 1132321936Shselasky 1133321936Shselasky // Expand the binary operator. 1134321936Shselasky Value *Result = (this->*Func)(OpInfo); 1135321936Shselasky 1136321936Shselasky // Convert the result back to the LHS type. 1137321936Shselasky Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy); 1138321936Shselasky 1139321936Shselasky // Store the result value into the LHS lvalue. Bit-fields are handled 1140321936Shselasky // specially because the result is altered by the store, i.e., [C99 6.5.16p1] 1141321936Shselasky // 'An assignment expression has the value of the left operand after the 1142321936Shselasky // assignment...'. 1143321936Shselasky if (LHSLV.isBitfield()) { 1144321936Shselasky if (!LHSLV.isVolatileQualified()) { 1145321936Shselasky CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy, 1146321936Shselasky &Result); 1147321936Shselasky return Result; 1148321936Shselasky } else 1149321936Shselasky CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy); 1150321936Shselasky } else 1151321936Shselasky CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, LHSTy); 1152321936Shselasky if (Ignore) 1153321936Shselasky return 0; 1154321936Shselasky return EmitLoadOfLValue(LHSLV, E->getType()); 1155321936Shselasky} 1156321936Shselasky 1157321936Shselasky 1158321936ShselaskyValue *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) { 1159321936Shselasky if (Ops.LHS->getType()->isFPOrFPVectorTy()) 1160321936Shselasky return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div"); 1161321936Shselasky else if (Ops.Ty->isUnsignedIntegerType()) 1162321936Shselasky return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div"); 1163321936Shselasky else 1164321936Shselasky return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div"); 1165321936Shselasky} 1166321936Shselasky 1167321936ShselaskyValue *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) { 1168321936Shselasky // Rem in C can't be a floating point type: C99 6.5.5p2. 1169321936Shselasky if (Ops.Ty->isUnsignedIntegerType()) 1170321936Shselasky return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem"); 1171321936Shselasky else 1172321936Shselasky return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem"); 1173321936Shselasky} 1174321936Shselasky 1175321936ShselaskyValue *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) { 1176321936Shselasky unsigned IID; 1177321936Shselasky unsigned OpID = 0; 1178321936Shselasky 1179321936Shselasky switch (Ops.E->getOpcode()) { 1180321936Shselasky case BinaryOperator::Add: 1181321936Shselasky case BinaryOperator::AddAssign: 1182321936Shselasky OpID = 1; 1183321936Shselasky IID = llvm::Intrinsic::sadd_with_overflow; 1184321936Shselasky break; 1185321936Shselasky case BinaryOperator::Sub: 1186321936Shselasky case BinaryOperator::SubAssign: 1187321936Shselasky OpID = 2; 1188321936Shselasky IID = llvm::Intrinsic::ssub_with_overflow; 1189321936Shselasky break; 1190321936Shselasky case BinaryOperator::Mul: 1191321936Shselasky case BinaryOperator::MulAssign: 1192321936Shselasky OpID = 3; 1193321936Shselasky IID = llvm::Intrinsic::smul_with_overflow; 1194321936Shselasky break; 1195321936Shselasky default: 1196321936Shselasky assert(false && "Unsupported operation for overflow detection"); 1197321936Shselasky IID = 0; 1198321936Shselasky } 1199321936Shselasky OpID <<= 1; 1200321936Shselasky OpID |= 1; 1201321936Shselasky 1202321936Shselasky const llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty); 1203321936Shselasky 1204321936Shselasky llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, &opTy, 1); 1205321936Shselasky 1206321936Shselasky Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS); 1207321936Shselasky Value *result = Builder.CreateExtractValue(resultAndOverflow, 0); 1208321936Shselasky Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1); 1209321936Shselasky 1210321936Shselasky // Branch in case of overflow. 1211321936Shselasky llvm::BasicBlock *initialBB = Builder.GetInsertBlock(); 1212321936Shselasky llvm::BasicBlock *overflowBB = 1213321936Shselasky CGF.createBasicBlock("overflow", CGF.CurFn); 1214321936Shselasky llvm::BasicBlock *continueBB = 1215321936Shselasky CGF.createBasicBlock("overflow.continue", CGF.CurFn); 1216321936Shselasky 1217321936Shselasky Builder.CreateCondBr(overflow, overflowBB, continueBB); 1218321936Shselasky 1219321936Shselasky // Handle overflow 1220321936Shselasky 1221321936Shselasky Builder.SetInsertPoint(overflowBB); 1222321936Shselasky 1223321936Shselasky // Handler is: 1224321936Shselasky // long long *__overflow_handler)(long long a, long long b, char op, 1225321936Shselasky // char width) 1226321936Shselasky std::vector<const llvm::Type*> handerArgTypes; 1227321936Shselasky handerArgTypes.push_back(llvm::Type::getInt64Ty(VMContext)); 1228321936Shselasky handerArgTypes.push_back(llvm::Type::getInt64Ty(VMContext)); 1229321936Shselasky handerArgTypes.push_back(llvm::Type::getInt8Ty(VMContext)); 1230321936Shselasky handerArgTypes.push_back(llvm::Type::getInt8Ty(VMContext)); 1231321936Shselasky llvm::FunctionType *handlerTy = llvm::FunctionType::get( 1232321936Shselasky llvm::Type::getInt64Ty(VMContext), handerArgTypes, false); 1233321936Shselasky llvm::Value *handlerFunction = 1234321936Shselasky CGF.CGM.getModule().getOrInsertGlobal("__overflow_handler", 1235321936Shselasky llvm::PointerType::getUnqual(handlerTy)); 1236321936Shselasky handlerFunction = Builder.CreateLoad(handlerFunction); 1237321936Shselasky 1238321936Shselasky llvm::Value *handlerResult = Builder.CreateCall4(handlerFunction, 1239321936Shselasky Builder.CreateSExt(Ops.LHS, llvm::Type::getInt64Ty(VMContext)), 1240321936Shselasky Builder.CreateSExt(Ops.RHS, llvm::Type::getInt64Ty(VMContext)), 1241321936Shselasky llvm::ConstantInt::get(llvm::Type::getInt8Ty(VMContext), OpID), 1242321936Shselasky llvm::ConstantInt::get(llvm::Type::getInt8Ty(VMContext), 1243321936Shselasky cast<llvm::IntegerType>(opTy)->getBitWidth())); 1244321936Shselasky 1245321936Shselasky handlerResult = Builder.CreateTrunc(handlerResult, opTy); 1246321936Shselasky 1247321936Shselasky Builder.CreateBr(continueBB); 1248321936Shselasky 1249321936Shselasky // Set up the continuation 1250321936Shselasky Builder.SetInsertPoint(continueBB); 1251321936Shselasky // Get the correct result 1252321936Shselasky llvm::PHINode *phi = Builder.CreatePHI(opTy); 1253321936Shselasky phi->reserveOperandSpace(2); 1254321936Shselasky phi->addIncoming(result, initialBB); 1255321936Shselasky phi->addIncoming(handlerResult, overflowBB); 1256321936Shselasky 1257321936Shselasky return phi; 1258321936Shselasky} 1259321936Shselasky 1260321936ShselaskyValue *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) { 1261321936Shselasky if (!Ops.Ty->isAnyPointerType()) { 1262321936Shselasky if (CGF.getContext().getLangOptions().OverflowChecking && 1263321936Shselasky Ops.Ty->isSignedIntegerType()) 1264321936Shselasky return EmitOverflowCheckedBinOp(Ops); 1265321936Shselasky 1266321936Shselasky if (Ops.LHS->getType()->isFPOrFPVectorTy()) 1267 return Builder.CreateFAdd(Ops.LHS, Ops.RHS, "add"); 1268 1269 // Signed integer overflow is undefined behavior. 1270 if (Ops.Ty->isSignedIntegerType()) 1271 return Builder.CreateNSWAdd(Ops.LHS, Ops.RHS, "add"); 1272 1273 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add"); 1274 } 1275 1276 if (Ops.Ty->isPointerType() && 1277 Ops.Ty->getAs<PointerType>()->isVariableArrayType()) { 1278 // The amount of the addition needs to account for the VLA size 1279 CGF.ErrorUnsupported(Ops.E, "VLA pointer addition"); 1280 } 1281 Value *Ptr, *Idx; 1282 Expr *IdxExp; 1283 const PointerType *PT = Ops.E->getLHS()->getType()->getAs<PointerType>(); 1284 const ObjCObjectPointerType *OPT = 1285 Ops.E->getLHS()->getType()->getAs<ObjCObjectPointerType>(); 1286 if (PT || OPT) { 1287 Ptr = Ops.LHS; 1288 Idx = Ops.RHS; 1289 IdxExp = Ops.E->getRHS(); 1290 } else { // int + pointer 1291 PT = Ops.E->getRHS()->getType()->getAs<PointerType>(); 1292 OPT = Ops.E->getRHS()->getType()->getAs<ObjCObjectPointerType>(); 1293 assert((PT || OPT) && "Invalid add expr"); 1294 Ptr = Ops.RHS; 1295 Idx = Ops.LHS; 1296 IdxExp = Ops.E->getLHS(); 1297 } 1298 1299 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth(); 1300 if (Width < CGF.LLVMPointerWidth) { 1301 // Zero or sign extend the pointer value based on whether the index is 1302 // signed or not. 1303 const llvm::Type *IdxType = 1304 llvm::IntegerType::get(VMContext, CGF.LLVMPointerWidth); 1305 if (IdxExp->getType()->isSignedIntegerType()) 1306 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext"); 1307 else 1308 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext"); 1309 } 1310 const QualType ElementType = PT ? PT->getPointeeType() : OPT->getPointeeType(); 1311 // Handle interface types, which are not represented with a concrete type. 1312 if (const ObjCInterfaceType *OIT = dyn_cast<ObjCInterfaceType>(ElementType)) { 1313 llvm::Value *InterfaceSize = 1314 llvm::ConstantInt::get(Idx->getType(), 1315 CGF.getContext().getTypeSizeInChars(OIT).getQuantity()); 1316 Idx = Builder.CreateMul(Idx, InterfaceSize); 1317 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext); 1318 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty); 1319 Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr"); 1320 return Builder.CreateBitCast(Res, Ptr->getType()); 1321 } 1322 1323 // Explicitly handle GNU void* and function pointer arithmetic extensions. The 1324 // GNU void* casts amount to no-ops since our void* type is i8*, but this is 1325 // future proof. 1326 if (ElementType->isVoidType() || ElementType->isFunctionType()) { 1327 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext); 1328 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty); 1329 Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr"); 1330 return Builder.CreateBitCast(Res, Ptr->getType()); 1331 } 1332 1333 return Builder.CreateInBoundsGEP(Ptr, Idx, "add.ptr"); 1334} 1335 1336Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) { 1337 if (!isa<llvm::PointerType>(Ops.LHS->getType())) { 1338 if (CGF.getContext().getLangOptions().OverflowChecking 1339 && Ops.Ty->isSignedIntegerType()) 1340 return EmitOverflowCheckedBinOp(Ops); 1341 1342 if (Ops.LHS->getType()->isFPOrFPVectorTy()) 1343 return Builder.CreateFSub(Ops.LHS, Ops.RHS, "sub"); 1344 1345 // Signed integer overflow is undefined behavior. 1346 if (Ops.Ty->isSignedIntegerType()) 1347 return Builder.CreateNSWSub(Ops.LHS, Ops.RHS, "sub"); 1348 1349 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub"); 1350 } 1351 1352 if (Ops.E->getLHS()->getType()->isPointerType() && 1353 Ops.E->getLHS()->getType()->getAs<PointerType>()->isVariableArrayType()) { 1354 // The amount of the addition needs to account for the VLA size for 1355 // ptr-int 1356 // The amount of the division needs to account for the VLA size for 1357 // ptr-ptr. 1358 CGF.ErrorUnsupported(Ops.E, "VLA pointer subtraction"); 1359 } 1360 1361 const QualType LHSType = Ops.E->getLHS()->getType(); 1362 const QualType LHSElementType = LHSType->getPointeeType(); 1363 if (!isa<llvm::PointerType>(Ops.RHS->getType())) { 1364 // pointer - int 1365 Value *Idx = Ops.RHS; 1366 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth(); 1367 if (Width < CGF.LLVMPointerWidth) { 1368 // Zero or sign extend the pointer value based on whether the index is 1369 // signed or not. 1370 const llvm::Type *IdxType = 1371 llvm::IntegerType::get(VMContext, CGF.LLVMPointerWidth); 1372 if (Ops.E->getRHS()->getType()->isSignedIntegerType()) 1373 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext"); 1374 else 1375 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext"); 1376 } 1377 Idx = Builder.CreateNeg(Idx, "sub.ptr.neg"); 1378 1379 // Handle interface types, which are not represented with a concrete type. 1380 if (const ObjCInterfaceType *OIT = 1381 dyn_cast<ObjCInterfaceType>(LHSElementType)) { 1382 llvm::Value *InterfaceSize = 1383 llvm::ConstantInt::get(Idx->getType(), 1384 CGF.getContext(). 1385 getTypeSizeInChars(OIT).getQuantity()); 1386 Idx = Builder.CreateMul(Idx, InterfaceSize); 1387 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext); 1388 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty); 1389 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "add.ptr"); 1390 return Builder.CreateBitCast(Res, Ops.LHS->getType()); 1391 } 1392 1393 // Explicitly handle GNU void* and function pointer arithmetic 1394 // extensions. The GNU void* casts amount to no-ops since our void* type is 1395 // i8*, but this is future proof. 1396 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) { 1397 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext); 1398 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty); 1399 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "sub.ptr"); 1400 return Builder.CreateBitCast(Res, Ops.LHS->getType()); 1401 } 1402 1403 return Builder.CreateInBoundsGEP(Ops.LHS, Idx, "sub.ptr"); 1404 } else { 1405 // pointer - pointer 1406 Value *LHS = Ops.LHS; 1407 Value *RHS = Ops.RHS; 1408 1409 CharUnits ElementSize; 1410 1411 // Handle GCC extension for pointer arithmetic on void* and function pointer 1412 // types. 1413 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) { 1414 ElementSize = CharUnits::One(); 1415 } else { 1416 ElementSize = CGF.getContext().getTypeSizeInChars(LHSElementType); 1417 } 1418 1419 const llvm::Type *ResultType = ConvertType(Ops.Ty); 1420 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast"); 1421 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast"); 1422 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub"); 1423 1424 // Optimize out the shift for element size of 1. 1425 if (ElementSize.isOne()) 1426 return BytesBetween; 1427 1428 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since 1429 // pointer difference in C is only defined in the case where both operands 1430 // are pointing to elements of an array. 1431 Value *BytesPerElt = 1432 llvm::ConstantInt::get(ResultType, ElementSize.getQuantity()); 1433 return Builder.CreateExactSDiv(BytesBetween, BytesPerElt, "sub.ptr.div"); 1434 } 1435} 1436 1437Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) { 1438 // LLVM requires the LHS and RHS to be the same type: promote or truncate the 1439 // RHS to the same size as the LHS. 1440 Value *RHS = Ops.RHS; 1441 if (Ops.LHS->getType() != RHS->getType()) 1442 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom"); 1443 1444 if (CGF.CatchUndefined 1445 && isa<llvm::IntegerType>(Ops.LHS->getType())) { 1446 unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth(); 1447 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont"); 1448 CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS, 1449 llvm::ConstantInt::get(RHS->getType(), Width)), 1450 Cont, CGF.getTrapBB()); 1451 CGF.EmitBlock(Cont); 1452 } 1453 1454 return Builder.CreateShl(Ops.LHS, RHS, "shl"); 1455} 1456 1457Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) { 1458 // LLVM requires the LHS and RHS to be the same type: promote or truncate the 1459 // RHS to the same size as the LHS. 1460 Value *RHS = Ops.RHS; 1461 if (Ops.LHS->getType() != RHS->getType()) 1462 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom"); 1463 1464 if (CGF.CatchUndefined 1465 && isa<llvm::IntegerType>(Ops.LHS->getType())) { 1466 unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth(); 1467 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont"); 1468 CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS, 1469 llvm::ConstantInt::get(RHS->getType(), Width)), 1470 Cont, CGF.getTrapBB()); 1471 CGF.EmitBlock(Cont); 1472 } 1473 1474 if (Ops.Ty->isUnsignedIntegerType()) 1475 return Builder.CreateLShr(Ops.LHS, RHS, "shr"); 1476 return Builder.CreateAShr(Ops.LHS, RHS, "shr"); 1477} 1478 1479Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc, 1480 unsigned SICmpOpc, unsigned FCmpOpc) { 1481 TestAndClearIgnoreResultAssign(); 1482 Value *Result; 1483 QualType LHSTy = E->getLHS()->getType(); 1484 if (LHSTy->isMemberFunctionPointerType()) { 1485 Value *LHSPtr = CGF.EmitAnyExprToTemp(E->getLHS()).getAggregateAddr(); 1486 Value *RHSPtr = CGF.EmitAnyExprToTemp(E->getRHS()).getAggregateAddr(); 1487 llvm::Value *LHSFunc = Builder.CreateStructGEP(LHSPtr, 0); 1488 LHSFunc = Builder.CreateLoad(LHSFunc); 1489 llvm::Value *RHSFunc = Builder.CreateStructGEP(RHSPtr, 0); 1490 RHSFunc = Builder.CreateLoad(RHSFunc); 1491 Value *ResultF = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc, 1492 LHSFunc, RHSFunc, "cmp.func"); 1493 Value *NullPtr = llvm::Constant::getNullValue(LHSFunc->getType()); 1494 Value *ResultNull = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc, 1495 LHSFunc, NullPtr, "cmp.null"); 1496 llvm::Value *LHSAdj = Builder.CreateStructGEP(LHSPtr, 1); 1497 LHSAdj = Builder.CreateLoad(LHSAdj); 1498 llvm::Value *RHSAdj = Builder.CreateStructGEP(RHSPtr, 1); 1499 RHSAdj = Builder.CreateLoad(RHSAdj); 1500 Value *ResultA = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc, 1501 LHSAdj, RHSAdj, "cmp.adj"); 1502 if (E->getOpcode() == BinaryOperator::EQ) { 1503 Result = Builder.CreateOr(ResultNull, ResultA, "or.na"); 1504 Result = Builder.CreateAnd(Result, ResultF, "and.f"); 1505 } else { 1506 assert(E->getOpcode() == BinaryOperator::NE && 1507 "Member pointer comparison other than == or != ?"); 1508 Result = Builder.CreateAnd(ResultNull, ResultA, "and.na"); 1509 Result = Builder.CreateOr(Result, ResultF, "or.f"); 1510 } 1511 } else if (!LHSTy->isAnyComplexType()) { 1512 Value *LHS = Visit(E->getLHS()); 1513 Value *RHS = Visit(E->getRHS()); 1514 1515 if (LHS->getType()->isFPOrFPVectorTy()) { 1516 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc, 1517 LHS, RHS, "cmp"); 1518 } else if (LHSTy->isSignedIntegerType()) { 1519 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc, 1520 LHS, RHS, "cmp"); 1521 } else { 1522 // Unsigned integers and pointers. 1523 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc, 1524 LHS, RHS, "cmp"); 1525 } 1526 1527 // If this is a vector comparison, sign extend the result to the appropriate 1528 // vector integer type and return it (don't convert to bool). 1529 if (LHSTy->isVectorType()) 1530 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext"); 1531 1532 } else { 1533 // Complex Comparison: can only be an equality comparison. 1534 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS()); 1535 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS()); 1536 1537 QualType CETy = LHSTy->getAs<ComplexType>()->getElementType(); 1538 1539 Value *ResultR, *ResultI; 1540 if (CETy->isRealFloatingType()) { 1541 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc, 1542 LHS.first, RHS.first, "cmp.r"); 1543 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc, 1544 LHS.second, RHS.second, "cmp.i"); 1545 } else { 1546 // Complex comparisons can only be equality comparisons. As such, signed 1547 // and unsigned opcodes are the same. 1548 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc, 1549 LHS.first, RHS.first, "cmp.r"); 1550 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc, 1551 LHS.second, RHS.second, "cmp.i"); 1552 } 1553 1554 if (E->getOpcode() == BinaryOperator::EQ) { 1555 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri"); 1556 } else { 1557 assert(E->getOpcode() == BinaryOperator::NE && 1558 "Complex comparison other than == or != ?"); 1559 Result = Builder.CreateOr(ResultR, ResultI, "or.ri"); 1560 } 1561 } 1562 1563 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType()); 1564} 1565 1566Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) { 1567 bool Ignore = TestAndClearIgnoreResultAssign(); 1568 1569 // __block variables need to have the rhs evaluated first, plus this should 1570 // improve codegen just a little. 1571 Value *RHS = Visit(E->getRHS()); 1572 LValue LHS = EmitCheckedLValue(E->getLHS()); 1573 1574 // Store the value into the LHS. Bit-fields are handled specially 1575 // because the result is altered by the store, i.e., [C99 6.5.16p1] 1576 // 'An assignment expression has the value of the left operand after 1577 // the assignment...'. 1578 if (LHS.isBitfield()) { 1579 if (!LHS.isVolatileQualified()) { 1580 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType(), 1581 &RHS); 1582 return RHS; 1583 } else 1584 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType()); 1585 } else 1586 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType()); 1587 if (Ignore) 1588 return 0; 1589 return EmitLoadOfLValue(LHS, E->getType()); 1590} 1591 1592Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) { 1593 const llvm::Type *ResTy = ConvertType(E->getType()); 1594 1595 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0. 1596 // If we have 1 && X, just emit X without inserting the control flow. 1597 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) { 1598 if (Cond == 1) { // If we have 1 && X, just emit X. 1599 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 1600 // ZExt result to int or bool. 1601 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext"); 1602 } 1603 1604 // 0 && RHS: If it is safe, just elide the RHS, and return 0/false. 1605 if (!CGF.ContainsLabel(E->getRHS())) 1606 return llvm::Constant::getNullValue(ResTy); 1607 } 1608 1609 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end"); 1610 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs"); 1611 1612 // Branch on the LHS first. If it is false, go to the failure (cont) block. 1613 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock); 1614 1615 // Any edges into the ContBlock are now from an (indeterminate number of) 1616 // edges from this first condition. All of these values will be false. Start 1617 // setting up the PHI node in the Cont Block for this. 1618 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 1619 "", ContBlock); 1620 PN->reserveOperandSpace(2); // Normal case, two inputs. 1621 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock); 1622 PI != PE; ++PI) 1623 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI); 1624 1625 CGF.BeginConditionalBranch(); 1626 CGF.EmitBlock(RHSBlock); 1627 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 1628 CGF.EndConditionalBranch(); 1629 1630 // Reaquire the RHS block, as there may be subblocks inserted. 1631 RHSBlock = Builder.GetInsertBlock(); 1632 1633 // Emit an unconditional branch from this block to ContBlock. Insert an entry 1634 // into the phi node for the edge with the value of RHSCond. 1635 CGF.EmitBlock(ContBlock); 1636 PN->addIncoming(RHSCond, RHSBlock); 1637 1638 // ZExt result to int. 1639 return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext"); 1640} 1641 1642Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) { 1643 const llvm::Type *ResTy = ConvertType(E->getType()); 1644 1645 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1. 1646 // If we have 0 || X, just emit X without inserting the control flow. 1647 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) { 1648 if (Cond == -1) { // If we have 0 || X, just emit X. 1649 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 1650 // ZExt result to int or bool. 1651 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext"); 1652 } 1653 1654 // 1 || RHS: If it is safe, just elide the RHS, and return 1/true. 1655 if (!CGF.ContainsLabel(E->getRHS())) 1656 return llvm::ConstantInt::get(ResTy, 1); 1657 } 1658 1659 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end"); 1660 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs"); 1661 1662 // Branch on the LHS first. If it is true, go to the success (cont) block. 1663 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock); 1664 1665 // Any edges into the ContBlock are now from an (indeterminate number of) 1666 // edges from this first condition. All of these values will be true. Start 1667 // setting up the PHI node in the Cont Block for this. 1668 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 1669 "", ContBlock); 1670 PN->reserveOperandSpace(2); // Normal case, two inputs. 1671 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock); 1672 PI != PE; ++PI) 1673 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI); 1674 1675 CGF.BeginConditionalBranch(); 1676 1677 // Emit the RHS condition as a bool value. 1678 CGF.EmitBlock(RHSBlock); 1679 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 1680 1681 CGF.EndConditionalBranch(); 1682 1683 // Reaquire the RHS block, as there may be subblocks inserted. 1684 RHSBlock = Builder.GetInsertBlock(); 1685 1686 // Emit an unconditional branch from this block to ContBlock. Insert an entry 1687 // into the phi node for the edge with the value of RHSCond. 1688 CGF.EmitBlock(ContBlock); 1689 PN->addIncoming(RHSCond, RHSBlock); 1690 1691 // ZExt result to int. 1692 return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext"); 1693} 1694 1695Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) { 1696 CGF.EmitStmt(E->getLHS()); 1697 CGF.EnsureInsertPoint(); 1698 return Visit(E->getRHS()); 1699} 1700 1701//===----------------------------------------------------------------------===// 1702// Other Operators 1703//===----------------------------------------------------------------------===// 1704 1705/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified 1706/// expression is cheap enough and side-effect-free enough to evaluate 1707/// unconditionally instead of conditionally. This is used to convert control 1708/// flow into selects in some cases. 1709static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E, 1710 CodeGenFunction &CGF) { 1711 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 1712 return isCheapEnoughToEvaluateUnconditionally(PE->getSubExpr(), CGF); 1713 1714 // TODO: Allow anything we can constant fold to an integer or fp constant. 1715 if (isa<IntegerLiteral>(E) || isa<CharacterLiteral>(E) || 1716 isa<FloatingLiteral>(E)) 1717 return true; 1718 1719 // Non-volatile automatic variables too, to get "cond ? X : Y" where 1720 // X and Y are local variables. 1721 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 1722 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) 1723 if (VD->hasLocalStorage() && !(CGF.getContext() 1724 .getCanonicalType(VD->getType()) 1725 .isVolatileQualified())) 1726 return true; 1727 1728 return false; 1729} 1730 1731 1732Value *ScalarExprEmitter:: 1733VisitConditionalOperator(const ConditionalOperator *E) { 1734 TestAndClearIgnoreResultAssign(); 1735 // If the condition constant folds and can be elided, try to avoid emitting 1736 // the condition and the dead arm. 1737 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getCond())){ 1738 Expr *Live = E->getLHS(), *Dead = E->getRHS(); 1739 if (Cond == -1) 1740 std::swap(Live, Dead); 1741 1742 // If the dead side doesn't have labels we need, and if the Live side isn't 1743 // the gnu missing ?: extension (which we could handle, but don't bother 1744 // to), just emit the Live part. 1745 if ((!Dead || !CGF.ContainsLabel(Dead)) && // No labels in dead part 1746 Live) // Live part isn't missing. 1747 return Visit(Live); 1748 } 1749 1750 1751 // If this is a really simple expression (like x ? 4 : 5), emit this as a 1752 // select instead of as control flow. We can only do this if it is cheap and 1753 // safe to evaluate the LHS and RHS unconditionally. 1754 if (E->getLHS() && isCheapEnoughToEvaluateUnconditionally(E->getLHS(), 1755 CGF) && 1756 isCheapEnoughToEvaluateUnconditionally(E->getRHS(), CGF)) { 1757 llvm::Value *CondV = CGF.EvaluateExprAsBool(E->getCond()); 1758 llvm::Value *LHS = Visit(E->getLHS()); 1759 llvm::Value *RHS = Visit(E->getRHS()); 1760 return Builder.CreateSelect(CondV, LHS, RHS, "cond"); 1761 } 1762 1763 1764 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true"); 1765 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false"); 1766 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end"); 1767 Value *CondVal = 0; 1768 1769 // If we don't have the GNU missing condition extension, emit a branch on bool 1770 // the normal way. 1771 if (E->getLHS()) { 1772 // Otherwise, just use EmitBranchOnBoolExpr to get small and simple code for 1773 // the branch on bool. 1774 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock); 1775 } else { 1776 // Otherwise, for the ?: extension, evaluate the conditional and then 1777 // convert it to bool the hard way. We do this explicitly because we need 1778 // the unconverted value for the missing middle value of the ?:. 1779 CondVal = CGF.EmitScalarExpr(E->getCond()); 1780 1781 // In some cases, EmitScalarConversion will delete the "CondVal" expression 1782 // if there are no extra uses (an optimization). Inhibit this by making an 1783 // extra dead use, because we're going to add a use of CondVal later. We 1784 // don't use the builder for this, because we don't want it to get optimized 1785 // away. This leaves dead code, but the ?: extension isn't common. 1786 new llvm::BitCastInst(CondVal, CondVal->getType(), "dummy?:holder", 1787 Builder.GetInsertBlock()); 1788 1789 Value *CondBoolVal = 1790 CGF.EmitScalarConversion(CondVal, E->getCond()->getType(), 1791 CGF.getContext().BoolTy); 1792 Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock); 1793 } 1794 1795 CGF.BeginConditionalBranch(); 1796 CGF.EmitBlock(LHSBlock); 1797 1798 // Handle the GNU extension for missing LHS. 1799 Value *LHS; 1800 if (E->getLHS()) 1801 LHS = Visit(E->getLHS()); 1802 else // Perform promotions, to handle cases like "short ?: int" 1803 LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType()); 1804 1805 CGF.EndConditionalBranch(); 1806 LHSBlock = Builder.GetInsertBlock(); 1807 CGF.EmitBranch(ContBlock); 1808 1809 CGF.BeginConditionalBranch(); 1810 CGF.EmitBlock(RHSBlock); 1811 1812 Value *RHS = Visit(E->getRHS()); 1813 CGF.EndConditionalBranch(); 1814 RHSBlock = Builder.GetInsertBlock(); 1815 CGF.EmitBranch(ContBlock); 1816 1817 CGF.EmitBlock(ContBlock); 1818 1819 // If the LHS or RHS is a throw expression, it will be legitimately null. 1820 if (!LHS) 1821 return RHS; 1822 if (!RHS) 1823 return LHS; 1824 1825 // Create a PHI node for the real part. 1826 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond"); 1827 PN->reserveOperandSpace(2); 1828 PN->addIncoming(LHS, LHSBlock); 1829 PN->addIncoming(RHS, RHSBlock); 1830 return PN; 1831} 1832 1833Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) { 1834 return Visit(E->getChosenSubExpr(CGF.getContext())); 1835} 1836 1837Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) { 1838 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr()); 1839 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType()); 1840 1841 // If EmitVAArg fails, we fall back to the LLVM instruction. 1842 if (!ArgPtr) 1843 return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType())); 1844 1845 // FIXME Volatility. 1846 return Builder.CreateLoad(ArgPtr); 1847} 1848 1849Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *BE) { 1850 return CGF.BuildBlockLiteralTmp(BE); 1851} 1852 1853//===----------------------------------------------------------------------===// 1854// Entry Point into this File 1855//===----------------------------------------------------------------------===// 1856 1857/// EmitScalarExpr - Emit the computation of the specified expression of scalar 1858/// type, ignoring the result. 1859Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) { 1860 assert(E && !hasAggregateLLVMType(E->getType()) && 1861 "Invalid scalar expression to emit"); 1862 1863 return ScalarExprEmitter(*this, IgnoreResultAssign) 1864 .Visit(const_cast<Expr*>(E)); 1865} 1866 1867/// EmitScalarConversion - Emit a conversion from the specified type to the 1868/// specified destination type, both of which are LLVM scalar types. 1869Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy, 1870 QualType DstTy) { 1871 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) && 1872 "Invalid scalar expression to emit"); 1873 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy); 1874} 1875 1876/// EmitComplexToScalarConversion - Emit a conversion from the specified complex 1877/// type to the specified destination type, where the destination type is an 1878/// LLVM scalar type. 1879Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src, 1880 QualType SrcTy, 1881 QualType DstTy) { 1882 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) && 1883 "Invalid complex -> scalar conversion"); 1884 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy, 1885 DstTy); 1886} 1887 1888LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) { 1889 llvm::Value *V; 1890 // object->isa or (*object).isa 1891 // Generate code as for: *(Class*)object 1892 // build Class* type 1893 const llvm::Type *ClassPtrTy = ConvertType(E->getType()); 1894 1895 Expr *BaseExpr = E->getBase(); 1896 if (BaseExpr->isLvalue(getContext()) != Expr::LV_Valid) { 1897 V = CreateTempAlloca(ClassPtrTy, "resval"); 1898 llvm::Value *Src = EmitScalarExpr(BaseExpr); 1899 Builder.CreateStore(Src, V); 1900 LValue LV = LValue::MakeAddr(V, MakeQualifiers(E->getType())); 1901 V = ScalarExprEmitter(*this).EmitLoadOfLValue(LV, E->getType()); 1902 } 1903 else { 1904 if (E->isArrow()) 1905 V = ScalarExprEmitter(*this).EmitLoadOfLValue(BaseExpr); 1906 else 1907 V = EmitLValue(BaseExpr).getAddress(); 1908 } 1909 1910 // build Class* type 1911 ClassPtrTy = ClassPtrTy->getPointerTo(); 1912 V = Builder.CreateBitCast(V, ClassPtrTy); 1913 LValue LV = LValue::MakeAddr(V, MakeQualifiers(E->getType())); 1914 return LV; 1915} 1916 1917