CGExprScalar.cpp revision 578faa837b552403e2002b97fdfbfde14f2448e5
1//===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This contains code to emit Expr nodes with scalar LLVM types as LLVM code. 11// 12//===----------------------------------------------------------------------===// 13 14#include "clang/Frontend/CodeGenOptions.h" 15#include "CodeGenFunction.h" 16#include "CGCXXABI.h" 17#include "CGObjCRuntime.h" 18#include "CodeGenModule.h" 19#include "CGDebugInfo.h" 20#include "clang/AST/ASTContext.h" 21#include "clang/AST/DeclObjC.h" 22#include "clang/AST/RecordLayout.h" 23#include "clang/AST/StmtVisitor.h" 24#include "clang/Basic/TargetInfo.h" 25#include "llvm/Constants.h" 26#include "llvm/Function.h" 27#include "llvm/GlobalVariable.h" 28#include "llvm/Intrinsics.h" 29#include "llvm/Module.h" 30#include "llvm/Support/CFG.h" 31#include "llvm/Target/TargetData.h" 32#include <cstdarg> 33 34using namespace clang; 35using namespace CodeGen; 36using llvm::Value; 37 38//===----------------------------------------------------------------------===// 39// Scalar Expression Emitter 40//===----------------------------------------------------------------------===// 41 42namespace { 43struct BinOpInfo { 44 Value *LHS; 45 Value *RHS; 46 QualType Ty; // Computation Type. 47 BinaryOperator::Opcode Opcode; // Opcode of BinOp to perform 48 const Expr *E; // Entire expr, for error unsupported. May not be binop. 49}; 50 51static bool MustVisitNullValue(const Expr *E) { 52 // If a null pointer expression's type is the C++0x nullptr_t, then 53 // it's not necessarily a simple constant and it must be evaluated 54 // for its potential side effects. 55 return E->getType()->isNullPtrType(); 56} 57 58class ScalarExprEmitter 59 : public StmtVisitor<ScalarExprEmitter, Value*> { 60 CodeGenFunction &CGF; 61 CGBuilderTy &Builder; 62 bool IgnoreResultAssign; 63 llvm::LLVMContext &VMContext; 64public: 65 66 ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false) 67 : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira), 68 VMContext(cgf.getLLVMContext()) { 69 } 70 71 //===--------------------------------------------------------------------===// 72 // Utilities 73 //===--------------------------------------------------------------------===// 74 75 bool TestAndClearIgnoreResultAssign() { 76 bool I = IgnoreResultAssign; 77 IgnoreResultAssign = false; 78 return I; 79 } 80 81 llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); } 82 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); } 83 LValue EmitCheckedLValue(const Expr *E) { return CGF.EmitCheckedLValue(E); } 84 85 Value *EmitLoadOfLValue(LValue LV) { 86 return CGF.EmitLoadOfLValue(LV).getScalarVal(); 87 } 88 89 /// EmitLoadOfLValue - Given an expression with complex type that represents a 90 /// value l-value, this method emits the address of the l-value, then loads 91 /// and returns the result. 92 Value *EmitLoadOfLValue(const Expr *E) { 93 return EmitLoadOfLValue(EmitCheckedLValue(E)); 94 } 95 96 /// EmitConversionToBool - Convert the specified expression value to a 97 /// boolean (i1) truth value. This is equivalent to "Val != 0". 98 Value *EmitConversionToBool(Value *Src, QualType DstTy); 99 100 /// EmitScalarConversion - Emit a conversion from the specified type to the 101 /// specified destination type, both of which are LLVM scalar types. 102 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy); 103 104 /// EmitComplexToScalarConversion - Emit a conversion from the specified 105 /// complex type to the specified destination type, where the destination type 106 /// is an LLVM scalar type. 107 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src, 108 QualType SrcTy, QualType DstTy); 109 110 /// EmitNullValue - Emit a value that corresponds to null for the given type. 111 Value *EmitNullValue(QualType Ty); 112 113 /// EmitFloatToBoolConversion - Perform an FP to boolean conversion. 114 Value *EmitFloatToBoolConversion(Value *V) { 115 // Compare against 0.0 for fp scalars. 116 llvm::Value *Zero = llvm::Constant::getNullValue(V->getType()); 117 return Builder.CreateFCmpUNE(V, Zero, "tobool"); 118 } 119 120 /// EmitPointerToBoolConversion - Perform a pointer to boolean conversion. 121 Value *EmitPointerToBoolConversion(Value *V) { 122 Value *Zero = llvm::ConstantPointerNull::get( 123 cast<llvm::PointerType>(V->getType())); 124 return Builder.CreateICmpNE(V, Zero, "tobool"); 125 } 126 127 Value *EmitIntToBoolConversion(Value *V) { 128 // Because of the type rules of C, we often end up computing a 129 // logical value, then zero extending it to int, then wanting it 130 // as a logical value again. Optimize this common case. 131 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(V)) { 132 if (ZI->getOperand(0)->getType() == Builder.getInt1Ty()) { 133 Value *Result = ZI->getOperand(0); 134 // If there aren't any more uses, zap the instruction to save space. 135 // Note that there can be more uses, for example if this 136 // is the result of an assignment. 137 if (ZI->use_empty()) 138 ZI->eraseFromParent(); 139 return Result; 140 } 141 } 142 143 return Builder.CreateIsNotNull(V, "tobool"); 144 } 145 146 //===--------------------------------------------------------------------===// 147 // Visitor Methods 148 //===--------------------------------------------------------------------===// 149 150 Value *Visit(Expr *E) { 151 return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E); 152 } 153 154 Value *VisitStmt(Stmt *S) { 155 S->dump(CGF.getContext().getSourceManager()); 156 llvm_unreachable("Stmt can't have complex result type!"); 157 } 158 Value *VisitExpr(Expr *S); 159 160 Value *VisitParenExpr(ParenExpr *PE) { 161 return Visit(PE->getSubExpr()); 162 } 163 Value *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) { 164 return Visit(E->getReplacement()); 165 } 166 Value *VisitGenericSelectionExpr(GenericSelectionExpr *GE) { 167 return Visit(GE->getResultExpr()); 168 } 169 170 // Leaves. 171 Value *VisitIntegerLiteral(const IntegerLiteral *E) { 172 return Builder.getInt(E->getValue()); 173 } 174 Value *VisitFloatingLiteral(const FloatingLiteral *E) { 175 return llvm::ConstantFP::get(VMContext, E->getValue()); 176 } 177 Value *VisitCharacterLiteral(const CharacterLiteral *E) { 178 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue()); 179 } 180 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 181 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue()); 182 } 183 Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { 184 return EmitNullValue(E->getType()); 185 } 186 Value *VisitGNUNullExpr(const GNUNullExpr *E) { 187 return EmitNullValue(E->getType()); 188 } 189 Value *VisitOffsetOfExpr(OffsetOfExpr *E); 190 Value *VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); 191 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) { 192 llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel()); 193 return Builder.CreateBitCast(V, ConvertType(E->getType())); 194 } 195 196 Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) { 197 return llvm::ConstantInt::get(ConvertType(E->getType()),E->getPackLength()); 198 } 199 200 Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) { 201 if (E->isGLValue()) 202 return EmitLoadOfLValue(CGF.getOpaqueLValueMapping(E)); 203 204 // Otherwise, assume the mapping is the scalar directly. 205 return CGF.getOpaqueRValueMapping(E).getScalarVal(); 206 } 207 208 // l-values. 209 Value *VisitDeclRefExpr(DeclRefExpr *E) { 210 Expr::EvalResult Result; 211 if (!E->Evaluate(Result, CGF.getContext())) 212 return EmitLoadOfLValue(E); 213 214 assert(!Result.HasSideEffects && "Constant declref with side-effect?!"); 215 216 llvm::Constant *C; 217 if (Result.Val.isInt()) 218 C = Builder.getInt(Result.Val.getInt()); 219 else if (Result.Val.isFloat()) 220 C = llvm::ConstantFP::get(VMContext, Result.Val.getFloat()); 221 else 222 return EmitLoadOfLValue(E); 223 224 // Make sure we emit a debug reference to the global variable. 225 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) { 226 if (!CGF.getContext().DeclMustBeEmitted(VD)) 227 CGF.EmitDeclRefExprDbgValue(E, C); 228 } else if (isa<EnumConstantDecl>(E->getDecl())) { 229 CGF.EmitDeclRefExprDbgValue(E, C); 230 } 231 232 return C; 233 } 234 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) { 235 return CGF.EmitObjCSelectorExpr(E); 236 } 237 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) { 238 return CGF.EmitObjCProtocolExpr(E); 239 } 240 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) { 241 return EmitLoadOfLValue(E); 242 } 243 Value *VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) { 244 assert(E->getObjectKind() == OK_Ordinary && 245 "reached property reference without lvalue-to-rvalue"); 246 return EmitLoadOfLValue(E); 247 } 248 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) { 249 if (E->getMethodDecl() && 250 E->getMethodDecl()->getResultType()->isReferenceType()) 251 return EmitLoadOfLValue(E); 252 return CGF.EmitObjCMessageExpr(E).getScalarVal(); 253 } 254 255 Value *VisitObjCIsaExpr(ObjCIsaExpr *E) { 256 LValue LV = CGF.EmitObjCIsaExpr(E); 257 Value *V = CGF.EmitLoadOfLValue(LV).getScalarVal(); 258 return V; 259 } 260 261 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E); 262 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E); 263 Value *VisitMemberExpr(MemberExpr *E); 264 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); } 265 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { 266 return EmitLoadOfLValue(E); 267 } 268 269 Value *VisitInitListExpr(InitListExpr *E); 270 271 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 272 return CGF.CGM.EmitNullConstant(E->getType()); 273 } 274 Value *VisitExplicitCastExpr(ExplicitCastExpr *E) { 275 if (E->getType()->isVariablyModifiedType()) 276 CGF.EmitVariablyModifiedType(E->getType()); 277 return VisitCastExpr(E); 278 } 279 Value *VisitCastExpr(CastExpr *E); 280 281 Value *VisitCallExpr(const CallExpr *E) { 282 if (E->getCallReturnType()->isReferenceType()) 283 return EmitLoadOfLValue(E); 284 285 return CGF.EmitCallExpr(E).getScalarVal(); 286 } 287 288 Value *VisitStmtExpr(const StmtExpr *E); 289 290 Value *VisitBlockDeclRefExpr(const BlockDeclRefExpr *E); 291 292 // Unary Operators. 293 Value *VisitUnaryPostDec(const UnaryOperator *E) { 294 LValue LV = EmitLValue(E->getSubExpr()); 295 return EmitScalarPrePostIncDec(E, LV, false, false); 296 } 297 Value *VisitUnaryPostInc(const UnaryOperator *E) { 298 LValue LV = EmitLValue(E->getSubExpr()); 299 return EmitScalarPrePostIncDec(E, LV, true, false); 300 } 301 Value *VisitUnaryPreDec(const UnaryOperator *E) { 302 LValue LV = EmitLValue(E->getSubExpr()); 303 return EmitScalarPrePostIncDec(E, LV, false, true); 304 } 305 Value *VisitUnaryPreInc(const UnaryOperator *E) { 306 LValue LV = EmitLValue(E->getSubExpr()); 307 return EmitScalarPrePostIncDec(E, LV, true, true); 308 } 309 310 llvm::Value *EmitAddConsiderOverflowBehavior(const UnaryOperator *E, 311 llvm::Value *InVal, 312 llvm::Value *NextVal, 313 bool IsInc); 314 315 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, 316 bool isInc, bool isPre); 317 318 319 Value *VisitUnaryAddrOf(const UnaryOperator *E) { 320 if (isa<MemberPointerType>(E->getType())) // never sugared 321 return CGF.CGM.getMemberPointerConstant(E); 322 323 return EmitLValue(E->getSubExpr()).getAddress(); 324 } 325 Value *VisitUnaryDeref(const UnaryOperator *E) { 326 if (E->getType()->isVoidType()) 327 return Visit(E->getSubExpr()); // the actual value should be unused 328 return EmitLoadOfLValue(E); 329 } 330 Value *VisitUnaryPlus(const UnaryOperator *E) { 331 // This differs from gcc, though, most likely due to a bug in gcc. 332 TestAndClearIgnoreResultAssign(); 333 return Visit(E->getSubExpr()); 334 } 335 Value *VisitUnaryMinus (const UnaryOperator *E); 336 Value *VisitUnaryNot (const UnaryOperator *E); 337 Value *VisitUnaryLNot (const UnaryOperator *E); 338 Value *VisitUnaryReal (const UnaryOperator *E); 339 Value *VisitUnaryImag (const UnaryOperator *E); 340 Value *VisitUnaryExtension(const UnaryOperator *E) { 341 return Visit(E->getSubExpr()); 342 } 343 344 // C++ 345 Value *VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E) { 346 return EmitLoadOfLValue(E); 347 } 348 349 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) { 350 return Visit(DAE->getExpr()); 351 } 352 Value *VisitCXXThisExpr(CXXThisExpr *TE) { 353 return CGF.LoadCXXThis(); 354 } 355 356 Value *VisitExprWithCleanups(ExprWithCleanups *E) { 357 return CGF.EmitExprWithCleanups(E).getScalarVal(); 358 } 359 Value *VisitCXXNewExpr(const CXXNewExpr *E) { 360 return CGF.EmitCXXNewExpr(E); 361 } 362 Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) { 363 CGF.EmitCXXDeleteExpr(E); 364 return 0; 365 } 366 Value *VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) { 367 return Builder.getInt1(E->getValue()); 368 } 369 370 Value *VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) { 371 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue()); 372 } 373 374 Value *VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 375 return llvm::ConstantInt::get(Builder.getInt32Ty(), E->getValue()); 376 } 377 378 Value *VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 379 return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue()); 380 } 381 382 Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) { 383 // C++ [expr.pseudo]p1: 384 // The result shall only be used as the operand for the function call 385 // operator (), and the result of such a call has type void. The only 386 // effect is the evaluation of the postfix-expression before the dot or 387 // arrow. 388 CGF.EmitScalarExpr(E->getBase()); 389 return 0; 390 } 391 392 Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { 393 return EmitNullValue(E->getType()); 394 } 395 396 Value *VisitCXXThrowExpr(const CXXThrowExpr *E) { 397 CGF.EmitCXXThrowExpr(E); 398 return 0; 399 } 400 401 Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { 402 return Builder.getInt1(E->getValue()); 403 } 404 405 // Binary Operators. 406 Value *EmitMul(const BinOpInfo &Ops) { 407 if (Ops.Ty->isSignedIntegerOrEnumerationType()) { 408 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) { 409 case LangOptions::SOB_Undefined: 410 return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul"); 411 case LangOptions::SOB_Defined: 412 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul"); 413 case LangOptions::SOB_Trapping: 414 return EmitOverflowCheckedBinOp(Ops); 415 } 416 } 417 418 if (Ops.LHS->getType()->isFPOrFPVectorTy()) 419 return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul"); 420 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul"); 421 } 422 bool isTrapvOverflowBehavior() { 423 return CGF.getContext().getLangOptions().getSignedOverflowBehavior() 424 == LangOptions::SOB_Trapping; 425 } 426 /// Create a binary op that checks for overflow. 427 /// Currently only supports +, - and *. 428 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops); 429 // Emit the overflow BB when -ftrapv option is activated. 430 void EmitOverflowBB(llvm::BasicBlock *overflowBB) { 431 Builder.SetInsertPoint(overflowBB); 432 llvm::Function *Trap = CGF.CGM.getIntrinsic(llvm::Intrinsic::trap); 433 Builder.CreateCall(Trap); 434 Builder.CreateUnreachable(); 435 } 436 // Check for undefined division and modulus behaviors. 437 void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops, 438 llvm::Value *Zero,bool isDiv); 439 Value *EmitDiv(const BinOpInfo &Ops); 440 Value *EmitRem(const BinOpInfo &Ops); 441 Value *EmitAdd(const BinOpInfo &Ops); 442 Value *EmitSub(const BinOpInfo &Ops); 443 Value *EmitShl(const BinOpInfo &Ops); 444 Value *EmitShr(const BinOpInfo &Ops); 445 Value *EmitAnd(const BinOpInfo &Ops) { 446 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and"); 447 } 448 Value *EmitXor(const BinOpInfo &Ops) { 449 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor"); 450 } 451 Value *EmitOr (const BinOpInfo &Ops) { 452 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or"); 453 } 454 455 BinOpInfo EmitBinOps(const BinaryOperator *E); 456 LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E, 457 Value *(ScalarExprEmitter::*F)(const BinOpInfo &), 458 Value *&Result); 459 460 Value *EmitCompoundAssign(const CompoundAssignOperator *E, 461 Value *(ScalarExprEmitter::*F)(const BinOpInfo &)); 462 463 // Binary operators and binary compound assignment operators. 464#define HANDLEBINOP(OP) \ 465 Value *VisitBin ## OP(const BinaryOperator *E) { \ 466 return Emit ## OP(EmitBinOps(E)); \ 467 } \ 468 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \ 469 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \ 470 } 471 HANDLEBINOP(Mul) 472 HANDLEBINOP(Div) 473 HANDLEBINOP(Rem) 474 HANDLEBINOP(Add) 475 HANDLEBINOP(Sub) 476 HANDLEBINOP(Shl) 477 HANDLEBINOP(Shr) 478 HANDLEBINOP(And) 479 HANDLEBINOP(Xor) 480 HANDLEBINOP(Or) 481#undef HANDLEBINOP 482 483 // Comparisons. 484 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc, 485 unsigned SICmpOpc, unsigned FCmpOpc); 486#define VISITCOMP(CODE, UI, SI, FP) \ 487 Value *VisitBin##CODE(const BinaryOperator *E) { \ 488 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \ 489 llvm::FCmpInst::FP); } 490 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT) 491 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT) 492 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE) 493 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE) 494 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ) 495 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE) 496#undef VISITCOMP 497 498 Value *VisitBinAssign (const BinaryOperator *E); 499 500 Value *VisitBinLAnd (const BinaryOperator *E); 501 Value *VisitBinLOr (const BinaryOperator *E); 502 Value *VisitBinComma (const BinaryOperator *E); 503 504 Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); } 505 Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); } 506 507 // Other Operators. 508 Value *VisitBlockExpr(const BlockExpr *BE); 509 Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *); 510 Value *VisitChooseExpr(ChooseExpr *CE); 511 Value *VisitVAArgExpr(VAArgExpr *VE); 512 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) { 513 return CGF.EmitObjCStringLiteral(E); 514 } 515 Value *VisitAsTypeExpr(AsTypeExpr *CE); 516}; 517} // end anonymous namespace. 518 519//===----------------------------------------------------------------------===// 520// Utilities 521//===----------------------------------------------------------------------===// 522 523/// EmitConversionToBool - Convert the specified expression value to a 524/// boolean (i1) truth value. This is equivalent to "Val != 0". 525Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) { 526 assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs"); 527 528 if (SrcType->isRealFloatingType()) 529 return EmitFloatToBoolConversion(Src); 530 531 if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType)) 532 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT); 533 534 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) && 535 "Unknown scalar type to convert"); 536 537 if (isa<llvm::IntegerType>(Src->getType())) 538 return EmitIntToBoolConversion(Src); 539 540 assert(isa<llvm::PointerType>(Src->getType())); 541 return EmitPointerToBoolConversion(Src); 542} 543 544/// EmitScalarConversion - Emit a conversion from the specified type to the 545/// specified destination type, both of which are LLVM scalar types. 546Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType, 547 QualType DstType) { 548 SrcType = CGF.getContext().getCanonicalType(SrcType); 549 DstType = CGF.getContext().getCanonicalType(DstType); 550 if (SrcType == DstType) return Src; 551 552 if (DstType->isVoidType()) return 0; 553 554 // Handle conversions to bool first, they are special: comparisons against 0. 555 if (DstType->isBooleanType()) 556 return EmitConversionToBool(Src, SrcType); 557 558 llvm::Type *DstTy = ConvertType(DstType); 559 560 // Ignore conversions like int -> uint. 561 if (Src->getType() == DstTy) 562 return Src; 563 564 // Handle pointer conversions next: pointers can only be converted to/from 565 // other pointers and integers. Check for pointer types in terms of LLVM, as 566 // some native types (like Obj-C id) may map to a pointer type. 567 if (isa<llvm::PointerType>(DstTy)) { 568 // The source value may be an integer, or a pointer. 569 if (isa<llvm::PointerType>(Src->getType())) 570 return Builder.CreateBitCast(Src, DstTy, "conv"); 571 572 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?"); 573 // First, convert to the correct width so that we control the kind of 574 // extension. 575 llvm::Type *MiddleTy = CGF.IntPtrTy; 576 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType(); 577 llvm::Value* IntResult = 578 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv"); 579 // Then, cast to pointer. 580 return Builder.CreateIntToPtr(IntResult, DstTy, "conv"); 581 } 582 583 if (isa<llvm::PointerType>(Src->getType())) { 584 // Must be an ptr to int cast. 585 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?"); 586 return Builder.CreatePtrToInt(Src, DstTy, "conv"); 587 } 588 589 // A scalar can be splatted to an extended vector of the same element type 590 if (DstType->isExtVectorType() && !SrcType->isVectorType()) { 591 // Cast the scalar to element type 592 QualType EltTy = DstType->getAs<ExtVectorType>()->getElementType(); 593 llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy); 594 595 // Insert the element in element zero of an undef vector 596 llvm::Value *UnV = llvm::UndefValue::get(DstTy); 597 llvm::Value *Idx = Builder.getInt32(0); 598 UnV = Builder.CreateInsertElement(UnV, Elt, Idx); 599 600 // Splat the element across to all elements 601 SmallVector<llvm::Constant*, 16> Args; 602 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements(); 603 for (unsigned i = 0; i != NumElements; ++i) 604 Args.push_back(Builder.getInt32(0)); 605 606 llvm::Constant *Mask = llvm::ConstantVector::get(Args); 607 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat"); 608 return Yay; 609 } 610 611 // Allow bitcast from vector to integer/fp of the same size. 612 if (isa<llvm::VectorType>(Src->getType()) || 613 isa<llvm::VectorType>(DstTy)) 614 return Builder.CreateBitCast(Src, DstTy, "conv"); 615 616 // Finally, we have the arithmetic types: real int/float. 617 if (isa<llvm::IntegerType>(Src->getType())) { 618 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType(); 619 if (isa<llvm::IntegerType>(DstTy)) 620 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv"); 621 else if (InputSigned) 622 return Builder.CreateSIToFP(Src, DstTy, "conv"); 623 else 624 return Builder.CreateUIToFP(Src, DstTy, "conv"); 625 } 626 627 assert(Src->getType()->isFloatingPointTy() && "Unknown real conversion"); 628 if (isa<llvm::IntegerType>(DstTy)) { 629 if (DstType->isSignedIntegerOrEnumerationType()) 630 return Builder.CreateFPToSI(Src, DstTy, "conv"); 631 else 632 return Builder.CreateFPToUI(Src, DstTy, "conv"); 633 } 634 635 assert(DstTy->isFloatingPointTy() && "Unknown real conversion"); 636 if (DstTy->getTypeID() < Src->getType()->getTypeID()) 637 return Builder.CreateFPTrunc(Src, DstTy, "conv"); 638 else 639 return Builder.CreateFPExt(Src, DstTy, "conv"); 640} 641 642/// EmitComplexToScalarConversion - Emit a conversion from the specified complex 643/// type to the specified destination type, where the destination type is an 644/// LLVM scalar type. 645Value *ScalarExprEmitter:: 646EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src, 647 QualType SrcTy, QualType DstTy) { 648 // Get the source element type. 649 SrcTy = SrcTy->getAs<ComplexType>()->getElementType(); 650 651 // Handle conversions to bool first, they are special: comparisons against 0. 652 if (DstTy->isBooleanType()) { 653 // Complex != 0 -> (Real != 0) | (Imag != 0) 654 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy); 655 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy); 656 return Builder.CreateOr(Src.first, Src.second, "tobool"); 657 } 658 659 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type, 660 // the imaginary part of the complex value is discarded and the value of the 661 // real part is converted according to the conversion rules for the 662 // corresponding real type. 663 return EmitScalarConversion(Src.first, SrcTy, DstTy); 664} 665 666Value *ScalarExprEmitter::EmitNullValue(QualType Ty) { 667 if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>()) 668 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT); 669 670 return llvm::Constant::getNullValue(ConvertType(Ty)); 671} 672 673//===----------------------------------------------------------------------===// 674// Visitor Methods 675//===----------------------------------------------------------------------===// 676 677Value *ScalarExprEmitter::VisitExpr(Expr *E) { 678 CGF.ErrorUnsupported(E, "scalar expression"); 679 if (E->getType()->isVoidType()) 680 return 0; 681 return llvm::UndefValue::get(CGF.ConvertType(E->getType())); 682} 683 684Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) { 685 // Vector Mask Case 686 if (E->getNumSubExprs() == 2 || 687 (E->getNumSubExprs() == 3 && E->getExpr(2)->getType()->isVectorType())) { 688 Value *LHS = CGF.EmitScalarExpr(E->getExpr(0)); 689 Value *RHS = CGF.EmitScalarExpr(E->getExpr(1)); 690 Value *Mask; 691 692 llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType()); 693 unsigned LHSElts = LTy->getNumElements(); 694 695 if (E->getNumSubExprs() == 3) { 696 Mask = CGF.EmitScalarExpr(E->getExpr(2)); 697 698 // Shuffle LHS & RHS into one input vector. 699 SmallVector<llvm::Constant*, 32> concat; 700 for (unsigned i = 0; i != LHSElts; ++i) { 701 concat.push_back(Builder.getInt32(2*i)); 702 concat.push_back(Builder.getInt32(2*i+1)); 703 } 704 705 Value* CV = llvm::ConstantVector::get(concat); 706 LHS = Builder.CreateShuffleVector(LHS, RHS, CV, "concat"); 707 LHSElts *= 2; 708 } else { 709 Mask = RHS; 710 } 711 712 llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType()); 713 llvm::Constant* EltMask; 714 715 // Treat vec3 like vec4. 716 if ((LHSElts == 6) && (E->getNumSubExprs() == 3)) 717 EltMask = llvm::ConstantInt::get(MTy->getElementType(), 718 (1 << llvm::Log2_32(LHSElts+2))-1); 719 else if ((LHSElts == 3) && (E->getNumSubExprs() == 2)) 720 EltMask = llvm::ConstantInt::get(MTy->getElementType(), 721 (1 << llvm::Log2_32(LHSElts+1))-1); 722 else 723 EltMask = llvm::ConstantInt::get(MTy->getElementType(), 724 (1 << llvm::Log2_32(LHSElts))-1); 725 726 // Mask off the high bits of each shuffle index. 727 SmallVector<llvm::Constant *, 32> MaskV; 728 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) 729 MaskV.push_back(EltMask); 730 731 Value* MaskBits = llvm::ConstantVector::get(MaskV); 732 Mask = Builder.CreateAnd(Mask, MaskBits, "mask"); 733 734 // newv = undef 735 // mask = mask & maskbits 736 // for each elt 737 // n = extract mask i 738 // x = extract val n 739 // newv = insert newv, x, i 740 llvm::VectorType *RTy = llvm::VectorType::get(LTy->getElementType(), 741 MTy->getNumElements()); 742 Value* NewV = llvm::UndefValue::get(RTy); 743 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) { 744 Value *Indx = Builder.getInt32(i); 745 Indx = Builder.CreateExtractElement(Mask, Indx, "shuf_idx"); 746 Indx = Builder.CreateZExt(Indx, CGF.Int32Ty, "idx_zext"); 747 748 // Handle vec3 special since the index will be off by one for the RHS. 749 if ((LHSElts == 6) && (E->getNumSubExprs() == 3)) { 750 Value *cmpIndx, *newIndx; 751 cmpIndx = Builder.CreateICmpUGT(Indx, Builder.getInt32(3), 752 "cmp_shuf_idx"); 753 newIndx = Builder.CreateSub(Indx, Builder.getInt32(1), "shuf_idx_adj"); 754 Indx = Builder.CreateSelect(cmpIndx, newIndx, Indx, "sel_shuf_idx"); 755 } 756 Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt"); 757 NewV = Builder.CreateInsertElement(NewV, VExt, Indx, "shuf_ins"); 758 } 759 return NewV; 760 } 761 762 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0)); 763 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1)); 764 765 // Handle vec3 special since the index will be off by one for the RHS. 766 llvm::VectorType *VTy = cast<llvm::VectorType>(V1->getType()); 767 SmallVector<llvm::Constant*, 32> indices; 768 for (unsigned i = 2; i < E->getNumSubExprs(); i++) { 769 unsigned Idx = E->getShuffleMaskIdx(CGF.getContext(), i-2); 770 if (VTy->getNumElements() == 3 && Idx > 3) 771 Idx -= 1; 772 indices.push_back(Builder.getInt32(Idx)); 773 } 774 775 Value *SV = llvm::ConstantVector::get(indices); 776 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle"); 777} 778Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) { 779 Expr::EvalResult Result; 780 if (E->Evaluate(Result, CGF.getContext()) && Result.Val.isInt()) { 781 if (E->isArrow()) 782 CGF.EmitScalarExpr(E->getBase()); 783 else 784 EmitLValue(E->getBase()); 785 return Builder.getInt(Result.Val.getInt()); 786 } 787 788 // Emit debug info for aggregate now, if it was delayed to reduce 789 // debug info size. 790 CGDebugInfo *DI = CGF.getDebugInfo(); 791 if (DI && CGF.CGM.getCodeGenOpts().LimitDebugInfo) { 792 QualType PQTy = E->getBase()->IgnoreParenImpCasts()->getType(); 793 if (const PointerType * PTy = dyn_cast<PointerType>(PQTy)) 794 if (FieldDecl *M = dyn_cast<FieldDecl>(E->getMemberDecl())) 795 DI->getOrCreateRecordType(PTy->getPointeeType(), 796 M->getParent()->getLocation()); 797 } 798 return EmitLoadOfLValue(E); 799} 800 801Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) { 802 TestAndClearIgnoreResultAssign(); 803 804 // Emit subscript expressions in rvalue context's. For most cases, this just 805 // loads the lvalue formed by the subscript expr. However, we have to be 806 // careful, because the base of a vector subscript is occasionally an rvalue, 807 // so we can't get it as an lvalue. 808 if (!E->getBase()->getType()->isVectorType()) 809 return EmitLoadOfLValue(E); 810 811 // Handle the vector case. The base must be a vector, the index must be an 812 // integer value. 813 Value *Base = Visit(E->getBase()); 814 Value *Idx = Visit(E->getIdx()); 815 bool IdxSigned = E->getIdx()->getType()->isSignedIntegerOrEnumerationType(); 816 Idx = Builder.CreateIntCast(Idx, CGF.Int32Ty, IdxSigned, "vecidxcast"); 817 return Builder.CreateExtractElement(Base, Idx, "vecext"); 818} 819 820static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx, 821 unsigned Off, llvm::Type *I32Ty) { 822 int MV = SVI->getMaskValue(Idx); 823 if (MV == -1) 824 return llvm::UndefValue::get(I32Ty); 825 return llvm::ConstantInt::get(I32Ty, Off+MV); 826} 827 828Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) { 829 bool Ignore = TestAndClearIgnoreResultAssign(); 830 (void)Ignore; 831 assert (Ignore == false && "init list ignored"); 832 unsigned NumInitElements = E->getNumInits(); 833 834 if (E->hadArrayRangeDesignator()) 835 CGF.ErrorUnsupported(E, "GNU array range designator extension"); 836 837 llvm::VectorType *VType = 838 dyn_cast<llvm::VectorType>(ConvertType(E->getType())); 839 840 if (!VType) { 841 if (NumInitElements == 0) { 842 // C++11 value-initialization for the scalar. 843 return EmitNullValue(E->getType()); 844 } 845 // We have a scalar in braces. Just use the first element. 846 return Visit(E->getInit(0)); 847 } 848 849 unsigned ResElts = VType->getNumElements(); 850 851 // Loop over initializers collecting the Value for each, and remembering 852 // whether the source was swizzle (ExtVectorElementExpr). This will allow 853 // us to fold the shuffle for the swizzle into the shuffle for the vector 854 // initializer, since LLVM optimizers generally do not want to touch 855 // shuffles. 856 unsigned CurIdx = 0; 857 bool VIsUndefShuffle = false; 858 llvm::Value *V = llvm::UndefValue::get(VType); 859 for (unsigned i = 0; i != NumInitElements; ++i) { 860 Expr *IE = E->getInit(i); 861 Value *Init = Visit(IE); 862 SmallVector<llvm::Constant*, 16> Args; 863 864 llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType()); 865 866 // Handle scalar elements. If the scalar initializer is actually one 867 // element of a different vector of the same width, use shuffle instead of 868 // extract+insert. 869 if (!VVT) { 870 if (isa<ExtVectorElementExpr>(IE)) { 871 llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init); 872 873 if (EI->getVectorOperandType()->getNumElements() == ResElts) { 874 llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand()); 875 Value *LHS = 0, *RHS = 0; 876 if (CurIdx == 0) { 877 // insert into undef -> shuffle (src, undef) 878 Args.push_back(C); 879 for (unsigned j = 1; j != ResElts; ++j) 880 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty)); 881 882 LHS = EI->getVectorOperand(); 883 RHS = V; 884 VIsUndefShuffle = true; 885 } else if (VIsUndefShuffle) { 886 // insert into undefshuffle && size match -> shuffle (v, src) 887 llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V); 888 for (unsigned j = 0; j != CurIdx; ++j) 889 Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty)); 890 Args.push_back(Builder.getInt32(ResElts + C->getZExtValue())); 891 for (unsigned j = CurIdx + 1; j != ResElts; ++j) 892 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty)); 893 894 LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0); 895 RHS = EI->getVectorOperand(); 896 VIsUndefShuffle = false; 897 } 898 if (!Args.empty()) { 899 llvm::Constant *Mask = llvm::ConstantVector::get(Args); 900 V = Builder.CreateShuffleVector(LHS, RHS, Mask); 901 ++CurIdx; 902 continue; 903 } 904 } 905 } 906 V = Builder.CreateInsertElement(V, Init, Builder.getInt32(CurIdx), 907 "vecinit"); 908 VIsUndefShuffle = false; 909 ++CurIdx; 910 continue; 911 } 912 913 unsigned InitElts = VVT->getNumElements(); 914 915 // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's 916 // input is the same width as the vector being constructed, generate an 917 // optimized shuffle of the swizzle input into the result. 918 unsigned Offset = (CurIdx == 0) ? 0 : ResElts; 919 if (isa<ExtVectorElementExpr>(IE)) { 920 llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init); 921 Value *SVOp = SVI->getOperand(0); 922 llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType()); 923 924 if (OpTy->getNumElements() == ResElts) { 925 for (unsigned j = 0; j != CurIdx; ++j) { 926 // If the current vector initializer is a shuffle with undef, merge 927 // this shuffle directly into it. 928 if (VIsUndefShuffle) { 929 Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0, 930 CGF.Int32Ty)); 931 } else { 932 Args.push_back(Builder.getInt32(j)); 933 } 934 } 935 for (unsigned j = 0, je = InitElts; j != je; ++j) 936 Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty)); 937 for (unsigned j = CurIdx + InitElts; j != ResElts; ++j) 938 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty)); 939 940 if (VIsUndefShuffle) 941 V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0); 942 943 Init = SVOp; 944 } 945 } 946 947 // Extend init to result vector length, and then shuffle its contribution 948 // to the vector initializer into V. 949 if (Args.empty()) { 950 for (unsigned j = 0; j != InitElts; ++j) 951 Args.push_back(Builder.getInt32(j)); 952 for (unsigned j = InitElts; j != ResElts; ++j) 953 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty)); 954 llvm::Constant *Mask = llvm::ConstantVector::get(Args); 955 Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT), 956 Mask, "vext"); 957 958 Args.clear(); 959 for (unsigned j = 0; j != CurIdx; ++j) 960 Args.push_back(Builder.getInt32(j)); 961 for (unsigned j = 0; j != InitElts; ++j) 962 Args.push_back(Builder.getInt32(j+Offset)); 963 for (unsigned j = CurIdx + InitElts; j != ResElts; ++j) 964 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty)); 965 } 966 967 // If V is undef, make sure it ends up on the RHS of the shuffle to aid 968 // merging subsequent shuffles into this one. 969 if (CurIdx == 0) 970 std::swap(V, Init); 971 llvm::Constant *Mask = llvm::ConstantVector::get(Args); 972 V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit"); 973 VIsUndefShuffle = isa<llvm::UndefValue>(Init); 974 CurIdx += InitElts; 975 } 976 977 // FIXME: evaluate codegen vs. shuffling against constant null vector. 978 // Emit remaining default initializers. 979 llvm::Type *EltTy = VType->getElementType(); 980 981 // Emit remaining default initializers 982 for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) { 983 Value *Idx = Builder.getInt32(CurIdx); 984 llvm::Value *Init = llvm::Constant::getNullValue(EltTy); 985 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit"); 986 } 987 return V; 988} 989 990static bool ShouldNullCheckClassCastValue(const CastExpr *CE) { 991 const Expr *E = CE->getSubExpr(); 992 993 if (CE->getCastKind() == CK_UncheckedDerivedToBase) 994 return false; 995 996 if (isa<CXXThisExpr>(E)) { 997 // We always assume that 'this' is never null. 998 return false; 999 } 1000 1001 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) { 1002 // And that glvalue casts are never null. 1003 if (ICE->getValueKind() != VK_RValue) 1004 return false; 1005 } 1006 1007 return true; 1008} 1009 1010// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts 1011// have to handle a more broad range of conversions than explicit casts, as they 1012// handle things like function to ptr-to-function decay etc. 1013Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) { 1014 Expr *E = CE->getSubExpr(); 1015 QualType DestTy = CE->getType(); 1016 CastKind Kind = CE->getCastKind(); 1017 1018 if (!DestTy->isVoidType()) 1019 TestAndClearIgnoreResultAssign(); 1020 1021 // Since almost all cast kinds apply to scalars, this switch doesn't have 1022 // a default case, so the compiler will warn on a missing case. The cases 1023 // are in the same order as in the CastKind enum. 1024 switch (Kind) { 1025 case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!"); 1026 1027 case CK_LValueBitCast: 1028 case CK_ObjCObjectLValueCast: { 1029 Value *V = EmitLValue(E).getAddress(); 1030 V = Builder.CreateBitCast(V, 1031 ConvertType(CGF.getContext().getPointerType(DestTy))); 1032 return EmitLoadOfLValue(CGF.MakeAddrLValue(V, DestTy)); 1033 } 1034 1035 case CK_CPointerToObjCPointerCast: 1036 case CK_BlockPointerToObjCPointerCast: 1037 case CK_AnyPointerToBlockPointerCast: 1038 case CK_BitCast: { 1039 Value *Src = Visit(const_cast<Expr*>(E)); 1040 return Builder.CreateBitCast(Src, ConvertType(DestTy)); 1041 } 1042 case CK_NoOp: 1043 case CK_UserDefinedConversion: 1044 return Visit(const_cast<Expr*>(E)); 1045 1046 case CK_BaseToDerived: { 1047 const CXXRecordDecl *DerivedClassDecl = 1048 DestTy->getCXXRecordDeclForPointerType(); 1049 1050 return CGF.GetAddressOfDerivedClass(Visit(E), DerivedClassDecl, 1051 CE->path_begin(), CE->path_end(), 1052 ShouldNullCheckClassCastValue(CE)); 1053 } 1054 case CK_UncheckedDerivedToBase: 1055 case CK_DerivedToBase: { 1056 const RecordType *DerivedClassTy = 1057 E->getType()->getAs<PointerType>()->getPointeeType()->getAs<RecordType>(); 1058 CXXRecordDecl *DerivedClassDecl = 1059 cast<CXXRecordDecl>(DerivedClassTy->getDecl()); 1060 1061 return CGF.GetAddressOfBaseClass(Visit(E), DerivedClassDecl, 1062 CE->path_begin(), CE->path_end(), 1063 ShouldNullCheckClassCastValue(CE)); 1064 } 1065 case CK_Dynamic: { 1066 Value *V = Visit(const_cast<Expr*>(E)); 1067 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE); 1068 return CGF.EmitDynamicCast(V, DCE); 1069 } 1070 1071 case CK_ArrayToPointerDecay: { 1072 assert(E->getType()->isArrayType() && 1073 "Array to pointer decay must have array source type!"); 1074 1075 Value *V = EmitLValue(E).getAddress(); // Bitfields can't be arrays. 1076 1077 // Note that VLA pointers are always decayed, so we don't need to do 1078 // anything here. 1079 if (!E->getType()->isVariableArrayType()) { 1080 assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer"); 1081 assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType()) 1082 ->getElementType()) && 1083 "Expected pointer to array"); 1084 V = Builder.CreateStructGEP(V, 0, "arraydecay"); 1085 } 1086 1087 // Make sure the array decay ends up being the right type. This matters if 1088 // the array type was of an incomplete type. 1089 return CGF.Builder.CreateBitCast(V, ConvertType(CE->getType())); 1090 } 1091 case CK_FunctionToPointerDecay: 1092 return EmitLValue(E).getAddress(); 1093 1094 case CK_NullToPointer: 1095 if (MustVisitNullValue(E)) 1096 (void) Visit(E); 1097 1098 return llvm::ConstantPointerNull::get( 1099 cast<llvm::PointerType>(ConvertType(DestTy))); 1100 1101 case CK_NullToMemberPointer: { 1102 if (MustVisitNullValue(E)) 1103 (void) Visit(E); 1104 1105 const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>(); 1106 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT); 1107 } 1108 1109 case CK_BaseToDerivedMemberPointer: 1110 case CK_DerivedToBaseMemberPointer: { 1111 Value *Src = Visit(E); 1112 1113 // Note that the AST doesn't distinguish between checked and 1114 // unchecked member pointer conversions, so we always have to 1115 // implement checked conversions here. This is inefficient when 1116 // actual control flow may be required in order to perform the 1117 // check, which it is for data member pointers (but not member 1118 // function pointers on Itanium and ARM). 1119 return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src); 1120 } 1121 1122 case CK_ARCProduceObject: 1123 return CGF.EmitARCRetainScalarExpr(E); 1124 case CK_ARCConsumeObject: 1125 return CGF.EmitObjCConsumeObject(E->getType(), Visit(E)); 1126 case CK_ARCReclaimReturnedObject: { 1127 llvm::Value *value = Visit(E); 1128 value = CGF.EmitARCRetainAutoreleasedReturnValue(value); 1129 return CGF.EmitObjCConsumeObject(E->getType(), value); 1130 } 1131 case CK_ARCExtendBlockObject: { 1132 llvm::Value *value = CGF.EmitARCRetainScalarExpr(E); 1133 return CGF.EmitObjCConsumeObject(E->getType(), value); 1134 } 1135 1136 case CK_FloatingRealToComplex: 1137 case CK_FloatingComplexCast: 1138 case CK_IntegralRealToComplex: 1139 case CK_IntegralComplexCast: 1140 case CK_IntegralComplexToFloatingComplex: 1141 case CK_FloatingComplexToIntegralComplex: 1142 case CK_ConstructorConversion: 1143 case CK_ToUnion: 1144 llvm_unreachable("scalar cast to non-scalar value"); 1145 break; 1146 1147 case CK_GetObjCProperty: { 1148 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy)); 1149 assert(E->isGLValue() && E->getObjectKind() == OK_ObjCProperty && 1150 "CK_GetObjCProperty for non-lvalue or non-ObjCProperty"); 1151 RValue RV = CGF.EmitLoadOfLValue(CGF.EmitLValue(E)); 1152 return RV.getScalarVal(); 1153 } 1154 1155 case CK_LValueToRValue: 1156 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy)); 1157 assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!"); 1158 return Visit(const_cast<Expr*>(E)); 1159 1160 case CK_IntegralToPointer: { 1161 Value *Src = Visit(const_cast<Expr*>(E)); 1162 1163 // First, convert to the correct width so that we control the kind of 1164 // extension. 1165 llvm::Type *MiddleTy = CGF.IntPtrTy; 1166 bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType(); 1167 llvm::Value* IntResult = 1168 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv"); 1169 1170 return Builder.CreateIntToPtr(IntResult, ConvertType(DestTy)); 1171 } 1172 case CK_PointerToIntegral: 1173 assert(!DestTy->isBooleanType() && "bool should use PointerToBool"); 1174 return Builder.CreatePtrToInt(Visit(E), ConvertType(DestTy)); 1175 1176 case CK_ToVoid: { 1177 CGF.EmitIgnoredExpr(E); 1178 return 0; 1179 } 1180 case CK_VectorSplat: { 1181 llvm::Type *DstTy = ConvertType(DestTy); 1182 Value *Elt = Visit(const_cast<Expr*>(E)); 1183 1184 // Insert the element in element zero of an undef vector 1185 llvm::Value *UnV = llvm::UndefValue::get(DstTy); 1186 llvm::Value *Idx = Builder.getInt32(0); 1187 UnV = Builder.CreateInsertElement(UnV, Elt, Idx); 1188 1189 // Splat the element across to all elements 1190 SmallVector<llvm::Constant*, 16> Args; 1191 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements(); 1192 llvm::Constant *Zero = Builder.getInt32(0); 1193 for (unsigned i = 0; i < NumElements; i++) 1194 Args.push_back(Zero); 1195 1196 llvm::Constant *Mask = llvm::ConstantVector::get(Args); 1197 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat"); 1198 return Yay; 1199 } 1200 1201 case CK_IntegralCast: 1202 case CK_IntegralToFloating: 1203 case CK_FloatingToIntegral: 1204 case CK_FloatingCast: 1205 return EmitScalarConversion(Visit(E), E->getType(), DestTy); 1206 1207 case CK_IntegralToBoolean: 1208 return EmitIntToBoolConversion(Visit(E)); 1209 case CK_PointerToBoolean: 1210 return EmitPointerToBoolConversion(Visit(E)); 1211 case CK_FloatingToBoolean: 1212 return EmitFloatToBoolConversion(Visit(E)); 1213 case CK_MemberPointerToBoolean: { 1214 llvm::Value *MemPtr = Visit(E); 1215 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>(); 1216 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT); 1217 } 1218 1219 case CK_FloatingComplexToReal: 1220 case CK_IntegralComplexToReal: 1221 return CGF.EmitComplexExpr(E, false, true).first; 1222 1223 case CK_FloatingComplexToBoolean: 1224 case CK_IntegralComplexToBoolean: { 1225 CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E); 1226 1227 // TODO: kill this function off, inline appropriate case here 1228 return EmitComplexToScalarConversion(V, E->getType(), DestTy); 1229 } 1230 1231 } 1232 1233 llvm_unreachable("unknown scalar cast"); 1234 return 0; 1235} 1236 1237Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) { 1238 CodeGenFunction::StmtExprEvaluation eval(CGF); 1239 return CGF.EmitCompoundStmt(*E->getSubStmt(), !E->getType()->isVoidType()) 1240 .getScalarVal(); 1241} 1242 1243Value *ScalarExprEmitter::VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) { 1244 LValue LV = CGF.EmitBlockDeclRefLValue(E); 1245 return CGF.EmitLoadOfLValue(LV).getScalarVal(); 1246} 1247 1248//===----------------------------------------------------------------------===// 1249// Unary Operators 1250//===----------------------------------------------------------------------===// 1251 1252llvm::Value *ScalarExprEmitter:: 1253EmitAddConsiderOverflowBehavior(const UnaryOperator *E, 1254 llvm::Value *InVal, 1255 llvm::Value *NextVal, bool IsInc) { 1256 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) { 1257 case LangOptions::SOB_Undefined: 1258 return Builder.CreateNSWAdd(InVal, NextVal, IsInc ? "inc" : "dec"); 1259 break; 1260 case LangOptions::SOB_Defined: 1261 return Builder.CreateAdd(InVal, NextVal, IsInc ? "inc" : "dec"); 1262 break; 1263 case LangOptions::SOB_Trapping: 1264 BinOpInfo BinOp; 1265 BinOp.LHS = InVal; 1266 BinOp.RHS = NextVal; 1267 BinOp.Ty = E->getType(); 1268 BinOp.Opcode = BO_Add; 1269 BinOp.E = E; 1270 return EmitOverflowCheckedBinOp(BinOp); 1271 } 1272 llvm_unreachable("Unknown SignedOverflowBehaviorTy"); 1273} 1274 1275llvm::Value * 1276ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, 1277 bool isInc, bool isPre) { 1278 1279 QualType type = E->getSubExpr()->getType(); 1280 llvm::Value *value = EmitLoadOfLValue(LV); 1281 llvm::Value *input = value; 1282 1283 int amount = (isInc ? 1 : -1); 1284 1285 // Special case of integer increment that we have to check first: bool++. 1286 // Due to promotion rules, we get: 1287 // bool++ -> bool = bool + 1 1288 // -> bool = (int)bool + 1 1289 // -> bool = ((int)bool + 1 != 0) 1290 // An interesting aspect of this is that increment is always true. 1291 // Decrement does not have this property. 1292 if (isInc && type->isBooleanType()) { 1293 value = Builder.getTrue(); 1294 1295 // Most common case by far: integer increment. 1296 } else if (type->isIntegerType()) { 1297 1298 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount); 1299 1300 // Note that signed integer inc/dec with width less than int can't 1301 // overflow because of promotion rules; we're just eliding a few steps here. 1302 if (type->isSignedIntegerOrEnumerationType() && 1303 value->getType()->getPrimitiveSizeInBits() >= 1304 CGF.IntTy->getBitWidth()) 1305 value = EmitAddConsiderOverflowBehavior(E, value, amt, isInc); 1306 else 1307 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec"); 1308 1309 // Next most common: pointer increment. 1310 } else if (const PointerType *ptr = type->getAs<PointerType>()) { 1311 QualType type = ptr->getPointeeType(); 1312 1313 // VLA types don't have constant size. 1314 if (const VariableArrayType *vla 1315 = CGF.getContext().getAsVariableArrayType(type)) { 1316 llvm::Value *numElts = CGF.getVLASize(vla).first; 1317 if (!isInc) numElts = Builder.CreateNSWNeg(numElts, "vla.negsize"); 1318 if (CGF.getContext().getLangOptions().isSignedOverflowDefined()) 1319 value = Builder.CreateGEP(value, numElts, "vla.inc"); 1320 else 1321 value = Builder.CreateInBoundsGEP(value, numElts, "vla.inc"); 1322 1323 // Arithmetic on function pointers (!) is just +-1. 1324 } else if (type->isFunctionType()) { 1325 llvm::Value *amt = Builder.getInt32(amount); 1326 1327 value = CGF.EmitCastToVoidPtr(value); 1328 if (CGF.getContext().getLangOptions().isSignedOverflowDefined()) 1329 value = Builder.CreateGEP(value, amt, "incdec.funcptr"); 1330 else 1331 value = Builder.CreateInBoundsGEP(value, amt, "incdec.funcptr"); 1332 value = Builder.CreateBitCast(value, input->getType()); 1333 1334 // For everything else, we can just do a simple increment. 1335 } else { 1336 llvm::Value *amt = Builder.getInt32(amount); 1337 if (CGF.getContext().getLangOptions().isSignedOverflowDefined()) 1338 value = Builder.CreateGEP(value, amt, "incdec.ptr"); 1339 else 1340 value = Builder.CreateInBoundsGEP(value, amt, "incdec.ptr"); 1341 } 1342 1343 // Vector increment/decrement. 1344 } else if (type->isVectorType()) { 1345 if (type->hasIntegerRepresentation()) { 1346 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount); 1347 1348 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec"); 1349 } else { 1350 value = Builder.CreateFAdd( 1351 value, 1352 llvm::ConstantFP::get(value->getType(), amount), 1353 isInc ? "inc" : "dec"); 1354 } 1355 1356 // Floating point. 1357 } else if (type->isRealFloatingType()) { 1358 // Add the inc/dec to the real part. 1359 llvm::Value *amt; 1360 if (value->getType()->isFloatTy()) 1361 amt = llvm::ConstantFP::get(VMContext, 1362 llvm::APFloat(static_cast<float>(amount))); 1363 else if (value->getType()->isDoubleTy()) 1364 amt = llvm::ConstantFP::get(VMContext, 1365 llvm::APFloat(static_cast<double>(amount))); 1366 else { 1367 llvm::APFloat F(static_cast<float>(amount)); 1368 bool ignored; 1369 F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero, 1370 &ignored); 1371 amt = llvm::ConstantFP::get(VMContext, F); 1372 } 1373 value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec"); 1374 1375 // Objective-C pointer types. 1376 } else { 1377 const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>(); 1378 value = CGF.EmitCastToVoidPtr(value); 1379 1380 CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType()); 1381 if (!isInc) size = -size; 1382 llvm::Value *sizeValue = 1383 llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity()); 1384 1385 if (CGF.getContext().getLangOptions().isSignedOverflowDefined()) 1386 value = Builder.CreateGEP(value, sizeValue, "incdec.objptr"); 1387 else 1388 value = Builder.CreateInBoundsGEP(value, sizeValue, "incdec.objptr"); 1389 value = Builder.CreateBitCast(value, input->getType()); 1390 } 1391 1392 // Store the updated result through the lvalue. 1393 if (LV.isBitField()) 1394 CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, &value); 1395 else 1396 CGF.EmitStoreThroughLValue(RValue::get(value), LV); 1397 1398 // If this is a postinc, return the value read from memory, otherwise use the 1399 // updated value. 1400 return isPre ? value : input; 1401} 1402 1403 1404 1405Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) { 1406 TestAndClearIgnoreResultAssign(); 1407 // Emit unary minus with EmitSub so we handle overflow cases etc. 1408 BinOpInfo BinOp; 1409 BinOp.RHS = Visit(E->getSubExpr()); 1410 1411 if (BinOp.RHS->getType()->isFPOrFPVectorTy()) 1412 BinOp.LHS = llvm::ConstantFP::getZeroValueForNegation(BinOp.RHS->getType()); 1413 else 1414 BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType()); 1415 BinOp.Ty = E->getType(); 1416 BinOp.Opcode = BO_Sub; 1417 BinOp.E = E; 1418 return EmitSub(BinOp); 1419} 1420 1421Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) { 1422 TestAndClearIgnoreResultAssign(); 1423 Value *Op = Visit(E->getSubExpr()); 1424 return Builder.CreateNot(Op, "neg"); 1425} 1426 1427Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) { 1428 // Compare operand to zero. 1429 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr()); 1430 1431 // Invert value. 1432 // TODO: Could dynamically modify easy computations here. For example, if 1433 // the operand is an icmp ne, turn into icmp eq. 1434 BoolVal = Builder.CreateNot(BoolVal, "lnot"); 1435 1436 // ZExt result to the expr type. 1437 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext"); 1438} 1439 1440Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) { 1441 // Try folding the offsetof to a constant. 1442 Expr::EvalResult EvalResult; 1443 if (E->Evaluate(EvalResult, CGF.getContext())) 1444 return Builder.getInt(EvalResult.Val.getInt()); 1445 1446 // Loop over the components of the offsetof to compute the value. 1447 unsigned n = E->getNumComponents(); 1448 llvm::Type* ResultType = ConvertType(E->getType()); 1449 llvm::Value* Result = llvm::Constant::getNullValue(ResultType); 1450 QualType CurrentType = E->getTypeSourceInfo()->getType(); 1451 for (unsigned i = 0; i != n; ++i) { 1452 OffsetOfExpr::OffsetOfNode ON = E->getComponent(i); 1453 llvm::Value *Offset = 0; 1454 switch (ON.getKind()) { 1455 case OffsetOfExpr::OffsetOfNode::Array: { 1456 // Compute the index 1457 Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex()); 1458 llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr); 1459 bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType(); 1460 Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv"); 1461 1462 // Save the element type 1463 CurrentType = 1464 CGF.getContext().getAsArrayType(CurrentType)->getElementType(); 1465 1466 // Compute the element size 1467 llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType, 1468 CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity()); 1469 1470 // Multiply out to compute the result 1471 Offset = Builder.CreateMul(Idx, ElemSize); 1472 break; 1473 } 1474 1475 case OffsetOfExpr::OffsetOfNode::Field: { 1476 FieldDecl *MemberDecl = ON.getField(); 1477 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl(); 1478 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD); 1479 1480 // Compute the index of the field in its parent. 1481 unsigned i = 0; 1482 // FIXME: It would be nice if we didn't have to loop here! 1483 for (RecordDecl::field_iterator Field = RD->field_begin(), 1484 FieldEnd = RD->field_end(); 1485 Field != FieldEnd; (void)++Field, ++i) { 1486 if (*Field == MemberDecl) 1487 break; 1488 } 1489 assert(i < RL.getFieldCount() && "offsetof field in wrong type"); 1490 1491 // Compute the offset to the field 1492 int64_t OffsetInt = RL.getFieldOffset(i) / 1493 CGF.getContext().getCharWidth(); 1494 Offset = llvm::ConstantInt::get(ResultType, OffsetInt); 1495 1496 // Save the element type. 1497 CurrentType = MemberDecl->getType(); 1498 break; 1499 } 1500 1501 case OffsetOfExpr::OffsetOfNode::Identifier: 1502 llvm_unreachable("dependent __builtin_offsetof"); 1503 1504 case OffsetOfExpr::OffsetOfNode::Base: { 1505 if (ON.getBase()->isVirtual()) { 1506 CGF.ErrorUnsupported(E, "virtual base in offsetof"); 1507 continue; 1508 } 1509 1510 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl(); 1511 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD); 1512 1513 // Save the element type. 1514 CurrentType = ON.getBase()->getType(); 1515 1516 // Compute the offset to the base. 1517 const RecordType *BaseRT = CurrentType->getAs<RecordType>(); 1518 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl()); 1519 int64_t OffsetInt = RL.getBaseClassOffsetInBits(BaseRD) / 1520 CGF.getContext().getCharWidth(); 1521 Offset = llvm::ConstantInt::get(ResultType, OffsetInt); 1522 break; 1523 } 1524 } 1525 Result = Builder.CreateAdd(Result, Offset); 1526 } 1527 return Result; 1528} 1529 1530/// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of 1531/// argument of the sizeof expression as an integer. 1532Value * 1533ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr( 1534 const UnaryExprOrTypeTraitExpr *E) { 1535 QualType TypeToSize = E->getTypeOfArgument(); 1536 if (E->getKind() == UETT_SizeOf) { 1537 if (const VariableArrayType *VAT = 1538 CGF.getContext().getAsVariableArrayType(TypeToSize)) { 1539 if (E->isArgumentType()) { 1540 // sizeof(type) - make sure to emit the VLA size. 1541 CGF.EmitVariablyModifiedType(TypeToSize); 1542 } else { 1543 // C99 6.5.3.4p2: If the argument is an expression of type 1544 // VLA, it is evaluated. 1545 CGF.EmitIgnoredExpr(E->getArgumentExpr()); 1546 } 1547 1548 QualType eltType; 1549 llvm::Value *numElts; 1550 llvm::tie(numElts, eltType) = CGF.getVLASize(VAT); 1551 1552 llvm::Value *size = numElts; 1553 1554 // Scale the number of non-VLA elements by the non-VLA element size. 1555 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType); 1556 if (!eltSize.isOne()) 1557 size = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), numElts); 1558 1559 return size; 1560 } 1561 } 1562 1563 // If this isn't sizeof(vla), the result must be constant; use the constant 1564 // folding logic so we don't have to duplicate it here. 1565 Expr::EvalResult Result; 1566 E->Evaluate(Result, CGF.getContext()); 1567 return Builder.getInt(Result.Val.getInt()); 1568} 1569 1570Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) { 1571 Expr *Op = E->getSubExpr(); 1572 if (Op->getType()->isAnyComplexType()) { 1573 // If it's an l-value, load through the appropriate subobject l-value. 1574 // Note that we have to ask E because Op might be an l-value that 1575 // this won't work for, e.g. an Obj-C property. 1576 if (E->isGLValue()) 1577 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E)).getScalarVal(); 1578 1579 // Otherwise, calculate and project. 1580 return CGF.EmitComplexExpr(Op, false, true).first; 1581 } 1582 1583 return Visit(Op); 1584} 1585 1586Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) { 1587 Expr *Op = E->getSubExpr(); 1588 if (Op->getType()->isAnyComplexType()) { 1589 // If it's an l-value, load through the appropriate subobject l-value. 1590 // Note that we have to ask E because Op might be an l-value that 1591 // this won't work for, e.g. an Obj-C property. 1592 if (Op->isGLValue()) 1593 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E)).getScalarVal(); 1594 1595 // Otherwise, calculate and project. 1596 return CGF.EmitComplexExpr(Op, true, false).second; 1597 } 1598 1599 // __imag on a scalar returns zero. Emit the subexpr to ensure side 1600 // effects are evaluated, but not the actual value. 1601 CGF.EmitScalarExpr(Op, true); 1602 return llvm::Constant::getNullValue(ConvertType(E->getType())); 1603} 1604 1605//===----------------------------------------------------------------------===// 1606// Binary Operators 1607//===----------------------------------------------------------------------===// 1608 1609BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) { 1610 TestAndClearIgnoreResultAssign(); 1611 BinOpInfo Result; 1612 Result.LHS = Visit(E->getLHS()); 1613 Result.RHS = Visit(E->getRHS()); 1614 Result.Ty = E->getType(); 1615 Result.Opcode = E->getOpcode(); 1616 Result.E = E; 1617 return Result; 1618} 1619 1620LValue ScalarExprEmitter::EmitCompoundAssignLValue( 1621 const CompoundAssignOperator *E, 1622 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &), 1623 Value *&Result) { 1624 QualType LHSTy = E->getLHS()->getType(); 1625 BinOpInfo OpInfo; 1626 1627 if (E->getComputationResultType()->isAnyComplexType()) { 1628 // This needs to go through the complex expression emitter, but it's a tad 1629 // complicated to do that... I'm leaving it out for now. (Note that we do 1630 // actually need the imaginary part of the RHS for multiplication and 1631 // division.) 1632 CGF.ErrorUnsupported(E, "complex compound assignment"); 1633 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType())); 1634 return LValue(); 1635 } 1636 1637 // Emit the RHS first. __block variables need to have the rhs evaluated 1638 // first, plus this should improve codegen a little. 1639 OpInfo.RHS = Visit(E->getRHS()); 1640 OpInfo.Ty = E->getComputationResultType(); 1641 OpInfo.Opcode = E->getOpcode(); 1642 OpInfo.E = E; 1643 // Load/convert the LHS. 1644 LValue LHSLV = EmitCheckedLValue(E->getLHS()); 1645 OpInfo.LHS = EmitLoadOfLValue(LHSLV); 1646 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy, 1647 E->getComputationLHSType()); 1648 1649 // Expand the binary operator. 1650 Result = (this->*Func)(OpInfo); 1651 1652 // Convert the result back to the LHS type. 1653 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy); 1654 1655 // Store the result value into the LHS lvalue. Bit-fields are handled 1656 // specially because the result is altered by the store, i.e., [C99 6.5.16p1] 1657 // 'An assignment expression has the value of the left operand after the 1658 // assignment...'. 1659 if (LHSLV.isBitField()) 1660 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, &Result); 1661 else 1662 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV); 1663 1664 return LHSLV; 1665} 1666 1667Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E, 1668 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) { 1669 bool Ignore = TestAndClearIgnoreResultAssign(); 1670 Value *RHS; 1671 LValue LHS = EmitCompoundAssignLValue(E, Func, RHS); 1672 1673 // If the result is clearly ignored, return now. 1674 if (Ignore) 1675 return 0; 1676 1677 // The result of an assignment in C is the assigned r-value. 1678 if (!CGF.getContext().getLangOptions().CPlusPlus) 1679 return RHS; 1680 1681 // Objective-C property assignment never reloads the value following a store. 1682 if (LHS.isPropertyRef()) 1683 return RHS; 1684 1685 // If the lvalue is non-volatile, return the computed value of the assignment. 1686 if (!LHS.isVolatileQualified()) 1687 return RHS; 1688 1689 // Otherwise, reload the value. 1690 return EmitLoadOfLValue(LHS); 1691} 1692 1693void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck( 1694 const BinOpInfo &Ops, 1695 llvm::Value *Zero, bool isDiv) { 1696 llvm::Function::iterator insertPt = Builder.GetInsertBlock(); 1697 llvm::BasicBlock *contBB = 1698 CGF.createBasicBlock(isDiv ? "div.cont" : "rem.cont", CGF.CurFn, 1699 llvm::next(insertPt)); 1700 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn); 1701 1702 llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType()); 1703 1704 if (Ops.Ty->hasSignedIntegerRepresentation()) { 1705 llvm::Value *IntMin = 1706 Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth())); 1707 llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL); 1708 1709 llvm::Value *Cond1 = Builder.CreateICmpEQ(Ops.RHS, Zero); 1710 llvm::Value *LHSCmp = Builder.CreateICmpEQ(Ops.LHS, IntMin); 1711 llvm::Value *RHSCmp = Builder.CreateICmpEQ(Ops.RHS, NegOne); 1712 llvm::Value *Cond2 = Builder.CreateAnd(LHSCmp, RHSCmp, "and"); 1713 Builder.CreateCondBr(Builder.CreateOr(Cond1, Cond2, "or"), 1714 overflowBB, contBB); 1715 } else { 1716 CGF.Builder.CreateCondBr(Builder.CreateICmpEQ(Ops.RHS, Zero), 1717 overflowBB, contBB); 1718 } 1719 EmitOverflowBB(overflowBB); 1720 Builder.SetInsertPoint(contBB); 1721} 1722 1723Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) { 1724 if (isTrapvOverflowBehavior()) { 1725 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty)); 1726 1727 if (Ops.Ty->isIntegerType()) 1728 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true); 1729 else if (Ops.Ty->isRealFloatingType()) { 1730 llvm::Function::iterator insertPt = Builder.GetInsertBlock(); 1731 llvm::BasicBlock *DivCont = CGF.createBasicBlock("div.cont", CGF.CurFn, 1732 llvm::next(insertPt)); 1733 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", 1734 CGF.CurFn); 1735 CGF.Builder.CreateCondBr(Builder.CreateFCmpOEQ(Ops.RHS, Zero), 1736 overflowBB, DivCont); 1737 EmitOverflowBB(overflowBB); 1738 Builder.SetInsertPoint(DivCont); 1739 } 1740 } 1741 if (Ops.LHS->getType()->isFPOrFPVectorTy()) 1742 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div"); 1743 else if (Ops.Ty->hasUnsignedIntegerRepresentation()) 1744 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div"); 1745 else 1746 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div"); 1747} 1748 1749Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) { 1750 // Rem in C can't be a floating point type: C99 6.5.5p2. 1751 if (isTrapvOverflowBehavior()) { 1752 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty)); 1753 1754 if (Ops.Ty->isIntegerType()) 1755 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false); 1756 } 1757 1758 if (Ops.Ty->hasUnsignedIntegerRepresentation()) 1759 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem"); 1760 else 1761 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem"); 1762} 1763 1764Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) { 1765 unsigned IID; 1766 unsigned OpID = 0; 1767 1768 switch (Ops.Opcode) { 1769 case BO_Add: 1770 case BO_AddAssign: 1771 OpID = 1; 1772 IID = llvm::Intrinsic::sadd_with_overflow; 1773 break; 1774 case BO_Sub: 1775 case BO_SubAssign: 1776 OpID = 2; 1777 IID = llvm::Intrinsic::ssub_with_overflow; 1778 break; 1779 case BO_Mul: 1780 case BO_MulAssign: 1781 OpID = 3; 1782 IID = llvm::Intrinsic::smul_with_overflow; 1783 break; 1784 default: 1785 llvm_unreachable("Unsupported operation for overflow detection"); 1786 IID = 0; 1787 } 1788 OpID <<= 1; 1789 OpID |= 1; 1790 1791 llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty); 1792 1793 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy); 1794 1795 Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS); 1796 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0); 1797 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1); 1798 1799 // Branch in case of overflow. 1800 llvm::BasicBlock *initialBB = Builder.GetInsertBlock(); 1801 llvm::Function::iterator insertPt = initialBB; 1802 llvm::BasicBlock *continueBB = CGF.createBasicBlock("nooverflow", CGF.CurFn, 1803 llvm::next(insertPt)); 1804 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn); 1805 1806 Builder.CreateCondBr(overflow, overflowBB, continueBB); 1807 1808 // Handle overflow with llvm.trap. 1809 const std::string *handlerName = 1810 &CGF.getContext().getLangOptions().OverflowHandler; 1811 if (handlerName->empty()) { 1812 EmitOverflowBB(overflowBB); 1813 Builder.SetInsertPoint(continueBB); 1814 return result; 1815 } 1816 1817 // If an overflow handler is set, then we want to call it and then use its 1818 // result, if it returns. 1819 Builder.SetInsertPoint(overflowBB); 1820 1821 // Get the overflow handler. 1822 llvm::Type *Int8Ty = llvm::Type::getInt8Ty(VMContext); 1823 llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty }; 1824 llvm::FunctionType *handlerTy = 1825 llvm::FunctionType::get(CGF.Int64Ty, argTypes, true); 1826 llvm::Value *handler = CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName); 1827 1828 // Sign extend the args to 64-bit, so that we can use the same handler for 1829 // all types of overflow. 1830 llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty); 1831 llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty); 1832 1833 // Call the handler with the two arguments, the operation, and the size of 1834 // the result. 1835 llvm::Value *handlerResult = Builder.CreateCall4(handler, lhs, rhs, 1836 Builder.getInt8(OpID), 1837 Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth())); 1838 1839 // Truncate the result back to the desired size. 1840 handlerResult = Builder.CreateTrunc(handlerResult, opTy); 1841 Builder.CreateBr(continueBB); 1842 1843 Builder.SetInsertPoint(continueBB); 1844 llvm::PHINode *phi = Builder.CreatePHI(opTy, 2); 1845 phi->addIncoming(result, initialBB); 1846 phi->addIncoming(handlerResult, overflowBB); 1847 1848 return phi; 1849} 1850 1851/// Emit pointer + index arithmetic. 1852static Value *emitPointerArithmetic(CodeGenFunction &CGF, 1853 const BinOpInfo &op, 1854 bool isSubtraction) { 1855 // Must have binary (not unary) expr here. Unary pointer 1856 // increment/decrement doesn't use this path. 1857 const BinaryOperator *expr = cast<BinaryOperator>(op.E); 1858 1859 Value *pointer = op.LHS; 1860 Expr *pointerOperand = expr->getLHS(); 1861 Value *index = op.RHS; 1862 Expr *indexOperand = expr->getRHS(); 1863 1864 // In a subtraction, the LHS is always the pointer. 1865 if (!isSubtraction && !pointer->getType()->isPointerTy()) { 1866 std::swap(pointer, index); 1867 std::swap(pointerOperand, indexOperand); 1868 } 1869 1870 unsigned width = cast<llvm::IntegerType>(index->getType())->getBitWidth(); 1871 if (width != CGF.PointerWidthInBits) { 1872 // Zero-extend or sign-extend the pointer value according to 1873 // whether the index is signed or not. 1874 bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType(); 1875 index = CGF.Builder.CreateIntCast(index, CGF.PtrDiffTy, isSigned, 1876 "idx.ext"); 1877 } 1878 1879 // If this is subtraction, negate the index. 1880 if (isSubtraction) 1881 index = CGF.Builder.CreateNeg(index, "idx.neg"); 1882 1883 const PointerType *pointerType 1884 = pointerOperand->getType()->getAs<PointerType>(); 1885 if (!pointerType) { 1886 QualType objectType = pointerOperand->getType() 1887 ->castAs<ObjCObjectPointerType>() 1888 ->getPointeeType(); 1889 llvm::Value *objectSize 1890 = CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(objectType)); 1891 1892 index = CGF.Builder.CreateMul(index, objectSize); 1893 1894 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy); 1895 result = CGF.Builder.CreateGEP(result, index, "add.ptr"); 1896 return CGF.Builder.CreateBitCast(result, pointer->getType()); 1897 } 1898 1899 QualType elementType = pointerType->getPointeeType(); 1900 if (const VariableArrayType *vla 1901 = CGF.getContext().getAsVariableArrayType(elementType)) { 1902 // The element count here is the total number of non-VLA elements. 1903 llvm::Value *numElements = CGF.getVLASize(vla).first; 1904 1905 // Effectively, the multiply by the VLA size is part of the GEP. 1906 // GEP indexes are signed, and scaling an index isn't permitted to 1907 // signed-overflow, so we use the same semantics for our explicit 1908 // multiply. We suppress this if overflow is not undefined behavior. 1909 if (CGF.getLangOptions().isSignedOverflowDefined()) { 1910 index = CGF.Builder.CreateMul(index, numElements, "vla.index"); 1911 pointer = CGF.Builder.CreateGEP(pointer, index, "add.ptr"); 1912 } else { 1913 index = CGF.Builder.CreateNSWMul(index, numElements, "vla.index"); 1914 pointer = CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr"); 1915 } 1916 return pointer; 1917 } 1918 1919 // Explicitly handle GNU void* and function pointer arithmetic extensions. The 1920 // GNU void* casts amount to no-ops since our void* type is i8*, but this is 1921 // future proof. 1922 if (elementType->isVoidType() || elementType->isFunctionType()) { 1923 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy); 1924 result = CGF.Builder.CreateGEP(result, index, "add.ptr"); 1925 return CGF.Builder.CreateBitCast(result, pointer->getType()); 1926 } 1927 1928 if (CGF.getLangOptions().isSignedOverflowDefined()) 1929 return CGF.Builder.CreateGEP(pointer, index, "add.ptr"); 1930 1931 return CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr"); 1932} 1933 1934Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) { 1935 if (op.LHS->getType()->isPointerTy() || 1936 op.RHS->getType()->isPointerTy()) 1937 return emitPointerArithmetic(CGF, op, /*subtraction*/ false); 1938 1939 if (op.Ty->isSignedIntegerOrEnumerationType()) { 1940 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) { 1941 case LangOptions::SOB_Undefined: 1942 return Builder.CreateNSWAdd(op.LHS, op.RHS, "add"); 1943 case LangOptions::SOB_Defined: 1944 return Builder.CreateAdd(op.LHS, op.RHS, "add"); 1945 case LangOptions::SOB_Trapping: 1946 return EmitOverflowCheckedBinOp(op); 1947 } 1948 } 1949 1950 if (op.LHS->getType()->isFPOrFPVectorTy()) 1951 return Builder.CreateFAdd(op.LHS, op.RHS, "add"); 1952 1953 return Builder.CreateAdd(op.LHS, op.RHS, "add"); 1954} 1955 1956Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) { 1957 // The LHS is always a pointer if either side is. 1958 if (!op.LHS->getType()->isPointerTy()) { 1959 if (op.Ty->isSignedIntegerOrEnumerationType()) { 1960 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) { 1961 case LangOptions::SOB_Undefined: 1962 return Builder.CreateNSWSub(op.LHS, op.RHS, "sub"); 1963 case LangOptions::SOB_Defined: 1964 return Builder.CreateSub(op.LHS, op.RHS, "sub"); 1965 case LangOptions::SOB_Trapping: 1966 return EmitOverflowCheckedBinOp(op); 1967 } 1968 } 1969 1970 if (op.LHS->getType()->isFPOrFPVectorTy()) 1971 return Builder.CreateFSub(op.LHS, op.RHS, "sub"); 1972 1973 return Builder.CreateSub(op.LHS, op.RHS, "sub"); 1974 } 1975 1976 // If the RHS is not a pointer, then we have normal pointer 1977 // arithmetic. 1978 if (!op.RHS->getType()->isPointerTy()) 1979 return emitPointerArithmetic(CGF, op, /*subtraction*/ true); 1980 1981 // Otherwise, this is a pointer subtraction. 1982 1983 // Do the raw subtraction part. 1984 llvm::Value *LHS 1985 = Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast"); 1986 llvm::Value *RHS 1987 = Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast"); 1988 Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub"); 1989 1990 // Okay, figure out the element size. 1991 const BinaryOperator *expr = cast<BinaryOperator>(op.E); 1992 QualType elementType = expr->getLHS()->getType()->getPointeeType(); 1993 1994 llvm::Value *divisor = 0; 1995 1996 // For a variable-length array, this is going to be non-constant. 1997 if (const VariableArrayType *vla 1998 = CGF.getContext().getAsVariableArrayType(elementType)) { 1999 llvm::Value *numElements; 2000 llvm::tie(numElements, elementType) = CGF.getVLASize(vla); 2001 2002 divisor = numElements; 2003 2004 // Scale the number of non-VLA elements by the non-VLA element size. 2005 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(elementType); 2006 if (!eltSize.isOne()) 2007 divisor = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), divisor); 2008 2009 // For everything elese, we can just compute it, safe in the 2010 // assumption that Sema won't let anything through that we can't 2011 // safely compute the size of. 2012 } else { 2013 CharUnits elementSize; 2014 // Handle GCC extension for pointer arithmetic on void* and 2015 // function pointer types. 2016 if (elementType->isVoidType() || elementType->isFunctionType()) 2017 elementSize = CharUnits::One(); 2018 else 2019 elementSize = CGF.getContext().getTypeSizeInChars(elementType); 2020 2021 // Don't even emit the divide for element size of 1. 2022 if (elementSize.isOne()) 2023 return diffInChars; 2024 2025 divisor = CGF.CGM.getSize(elementSize); 2026 } 2027 2028 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since 2029 // pointer difference in C is only defined in the case where both operands 2030 // are pointing to elements of an array. 2031 return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div"); 2032} 2033 2034Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) { 2035 // LLVM requires the LHS and RHS to be the same type: promote or truncate the 2036 // RHS to the same size as the LHS. 2037 Value *RHS = Ops.RHS; 2038 if (Ops.LHS->getType() != RHS->getType()) 2039 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom"); 2040 2041 if (CGF.CatchUndefined 2042 && isa<llvm::IntegerType>(Ops.LHS->getType())) { 2043 unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth(); 2044 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont"); 2045 CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS, 2046 llvm::ConstantInt::get(RHS->getType(), Width)), 2047 Cont, CGF.getTrapBB()); 2048 CGF.EmitBlock(Cont); 2049 } 2050 2051 return Builder.CreateShl(Ops.LHS, RHS, "shl"); 2052} 2053 2054Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) { 2055 // LLVM requires the LHS and RHS to be the same type: promote or truncate the 2056 // RHS to the same size as the LHS. 2057 Value *RHS = Ops.RHS; 2058 if (Ops.LHS->getType() != RHS->getType()) 2059 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom"); 2060 2061 if (CGF.CatchUndefined 2062 && isa<llvm::IntegerType>(Ops.LHS->getType())) { 2063 unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth(); 2064 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont"); 2065 CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS, 2066 llvm::ConstantInt::get(RHS->getType(), Width)), 2067 Cont, CGF.getTrapBB()); 2068 CGF.EmitBlock(Cont); 2069 } 2070 2071 if (Ops.Ty->hasUnsignedIntegerRepresentation()) 2072 return Builder.CreateLShr(Ops.LHS, RHS, "shr"); 2073 return Builder.CreateAShr(Ops.LHS, RHS, "shr"); 2074} 2075 2076enum IntrinsicType { VCMPEQ, VCMPGT }; 2077// return corresponding comparison intrinsic for given vector type 2078static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT, 2079 BuiltinType::Kind ElemKind) { 2080 switch (ElemKind) { 2081 default: llvm_unreachable("unexpected element type"); 2082 case BuiltinType::Char_U: 2083 case BuiltinType::UChar: 2084 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p : 2085 llvm::Intrinsic::ppc_altivec_vcmpgtub_p; 2086 break; 2087 case BuiltinType::Char_S: 2088 case BuiltinType::SChar: 2089 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p : 2090 llvm::Intrinsic::ppc_altivec_vcmpgtsb_p; 2091 break; 2092 case BuiltinType::UShort: 2093 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p : 2094 llvm::Intrinsic::ppc_altivec_vcmpgtuh_p; 2095 break; 2096 case BuiltinType::Short: 2097 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p : 2098 llvm::Intrinsic::ppc_altivec_vcmpgtsh_p; 2099 break; 2100 case BuiltinType::UInt: 2101 case BuiltinType::ULong: 2102 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p : 2103 llvm::Intrinsic::ppc_altivec_vcmpgtuw_p; 2104 break; 2105 case BuiltinType::Int: 2106 case BuiltinType::Long: 2107 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p : 2108 llvm::Intrinsic::ppc_altivec_vcmpgtsw_p; 2109 break; 2110 case BuiltinType::Float: 2111 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p : 2112 llvm::Intrinsic::ppc_altivec_vcmpgtfp_p; 2113 break; 2114 } 2115 return llvm::Intrinsic::not_intrinsic; 2116} 2117 2118Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc, 2119 unsigned SICmpOpc, unsigned FCmpOpc) { 2120 TestAndClearIgnoreResultAssign(); 2121 Value *Result; 2122 QualType LHSTy = E->getLHS()->getType(); 2123 if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) { 2124 assert(E->getOpcode() == BO_EQ || 2125 E->getOpcode() == BO_NE); 2126 Value *LHS = CGF.EmitScalarExpr(E->getLHS()); 2127 Value *RHS = CGF.EmitScalarExpr(E->getRHS()); 2128 Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison( 2129 CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE); 2130 } else if (!LHSTy->isAnyComplexType()) { 2131 Value *LHS = Visit(E->getLHS()); 2132 Value *RHS = Visit(E->getRHS()); 2133 2134 // If AltiVec, the comparison results in a numeric type, so we use 2135 // intrinsics comparing vectors and giving 0 or 1 as a result 2136 if (LHSTy->isVectorType() && !E->getType()->isVectorType()) { 2137 // constants for mapping CR6 register bits to predicate result 2138 enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6; 2139 2140 llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic; 2141 2142 // in several cases vector arguments order will be reversed 2143 Value *FirstVecArg = LHS, 2144 *SecondVecArg = RHS; 2145 2146 QualType ElTy = LHSTy->getAs<VectorType>()->getElementType(); 2147 const BuiltinType *BTy = ElTy->getAs<BuiltinType>(); 2148 BuiltinType::Kind ElementKind = BTy->getKind(); 2149 2150 switch(E->getOpcode()) { 2151 default: llvm_unreachable("is not a comparison operation"); 2152 case BO_EQ: 2153 CR6 = CR6_LT; 2154 ID = GetIntrinsic(VCMPEQ, ElementKind); 2155 break; 2156 case BO_NE: 2157 CR6 = CR6_EQ; 2158 ID = GetIntrinsic(VCMPEQ, ElementKind); 2159 break; 2160 case BO_LT: 2161 CR6 = CR6_LT; 2162 ID = GetIntrinsic(VCMPGT, ElementKind); 2163 std::swap(FirstVecArg, SecondVecArg); 2164 break; 2165 case BO_GT: 2166 CR6 = CR6_LT; 2167 ID = GetIntrinsic(VCMPGT, ElementKind); 2168 break; 2169 case BO_LE: 2170 if (ElementKind == BuiltinType::Float) { 2171 CR6 = CR6_LT; 2172 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p; 2173 std::swap(FirstVecArg, SecondVecArg); 2174 } 2175 else { 2176 CR6 = CR6_EQ; 2177 ID = GetIntrinsic(VCMPGT, ElementKind); 2178 } 2179 break; 2180 case BO_GE: 2181 if (ElementKind == BuiltinType::Float) { 2182 CR6 = CR6_LT; 2183 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p; 2184 } 2185 else { 2186 CR6 = CR6_EQ; 2187 ID = GetIntrinsic(VCMPGT, ElementKind); 2188 std::swap(FirstVecArg, SecondVecArg); 2189 } 2190 break; 2191 } 2192 2193 Value *CR6Param = Builder.getInt32(CR6); 2194 llvm::Function *F = CGF.CGM.getIntrinsic(ID); 2195 Result = Builder.CreateCall3(F, CR6Param, FirstVecArg, SecondVecArg, ""); 2196 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType()); 2197 } 2198 2199 if (LHS->getType()->isFPOrFPVectorTy()) { 2200 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc, 2201 LHS, RHS, "cmp"); 2202 } else if (LHSTy->hasSignedIntegerRepresentation()) { 2203 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc, 2204 LHS, RHS, "cmp"); 2205 } else { 2206 // Unsigned integers and pointers. 2207 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc, 2208 LHS, RHS, "cmp"); 2209 } 2210 2211 // If this is a vector comparison, sign extend the result to the appropriate 2212 // vector integer type and return it (don't convert to bool). 2213 if (LHSTy->isVectorType()) 2214 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext"); 2215 2216 } else { 2217 // Complex Comparison: can only be an equality comparison. 2218 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS()); 2219 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS()); 2220 2221 QualType CETy = LHSTy->getAs<ComplexType>()->getElementType(); 2222 2223 Value *ResultR, *ResultI; 2224 if (CETy->isRealFloatingType()) { 2225 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc, 2226 LHS.first, RHS.first, "cmp.r"); 2227 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc, 2228 LHS.second, RHS.second, "cmp.i"); 2229 } else { 2230 // Complex comparisons can only be equality comparisons. As such, signed 2231 // and unsigned opcodes are the same. 2232 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc, 2233 LHS.first, RHS.first, "cmp.r"); 2234 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc, 2235 LHS.second, RHS.second, "cmp.i"); 2236 } 2237 2238 if (E->getOpcode() == BO_EQ) { 2239 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri"); 2240 } else { 2241 assert(E->getOpcode() == BO_NE && 2242 "Complex comparison other than == or != ?"); 2243 Result = Builder.CreateOr(ResultR, ResultI, "or.ri"); 2244 } 2245 } 2246 2247 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType()); 2248} 2249 2250Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) { 2251 bool Ignore = TestAndClearIgnoreResultAssign(); 2252 2253 Value *RHS; 2254 LValue LHS; 2255 2256 switch (E->getLHS()->getType().getObjCLifetime()) { 2257 case Qualifiers::OCL_Strong: 2258 llvm::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore); 2259 break; 2260 2261 case Qualifiers::OCL_Autoreleasing: 2262 llvm::tie(LHS,RHS) = CGF.EmitARCStoreAutoreleasing(E); 2263 break; 2264 2265 case Qualifiers::OCL_Weak: 2266 RHS = Visit(E->getRHS()); 2267 LHS = EmitCheckedLValue(E->getLHS()); 2268 RHS = CGF.EmitARCStoreWeak(LHS.getAddress(), RHS, Ignore); 2269 break; 2270 2271 // No reason to do any of these differently. 2272 case Qualifiers::OCL_None: 2273 case Qualifiers::OCL_ExplicitNone: 2274 // __block variables need to have the rhs evaluated first, plus 2275 // this should improve codegen just a little. 2276 RHS = Visit(E->getRHS()); 2277 LHS = EmitCheckedLValue(E->getLHS()); 2278 2279 // Store the value into the LHS. Bit-fields are handled specially 2280 // because the result is altered by the store, i.e., [C99 6.5.16p1] 2281 // 'An assignment expression has the value of the left operand after 2282 // the assignment...'. 2283 if (LHS.isBitField()) 2284 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, &RHS); 2285 else 2286 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS); 2287 } 2288 2289 // If the result is clearly ignored, return now. 2290 if (Ignore) 2291 return 0; 2292 2293 // The result of an assignment in C is the assigned r-value. 2294 if (!CGF.getContext().getLangOptions().CPlusPlus) 2295 return RHS; 2296 2297 // Objective-C property assignment never reloads the value following a store. 2298 if (LHS.isPropertyRef()) 2299 return RHS; 2300 2301 // If the lvalue is non-volatile, return the computed value of the assignment. 2302 if (!LHS.isVolatileQualified()) 2303 return RHS; 2304 2305 // Otherwise, reload the value. 2306 return EmitLoadOfLValue(LHS); 2307} 2308 2309Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) { 2310 llvm::Type *ResTy = ConvertType(E->getType()); 2311 2312 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0. 2313 // If we have 1 && X, just emit X without inserting the control flow. 2314 bool LHSCondVal; 2315 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) { 2316 if (LHSCondVal) { // If we have 1 && X, just emit X. 2317 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 2318 // ZExt result to int or bool. 2319 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext"); 2320 } 2321 2322 // 0 && RHS: If it is safe, just elide the RHS, and return 0/false. 2323 if (!CGF.ContainsLabel(E->getRHS())) 2324 return llvm::Constant::getNullValue(ResTy); 2325 } 2326 2327 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end"); 2328 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs"); 2329 2330 CodeGenFunction::ConditionalEvaluation eval(CGF); 2331 2332 // Branch on the LHS first. If it is false, go to the failure (cont) block. 2333 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock); 2334 2335 // Any edges into the ContBlock are now from an (indeterminate number of) 2336 // edges from this first condition. All of these values will be false. Start 2337 // setting up the PHI node in the Cont Block for this. 2338 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2, 2339 "", ContBlock); 2340 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock); 2341 PI != PE; ++PI) 2342 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI); 2343 2344 eval.begin(CGF); 2345 CGF.EmitBlock(RHSBlock); 2346 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 2347 eval.end(CGF); 2348 2349 // Reaquire the RHS block, as there may be subblocks inserted. 2350 RHSBlock = Builder.GetInsertBlock(); 2351 2352 // Emit an unconditional branch from this block to ContBlock. Insert an entry 2353 // into the phi node for the edge with the value of RHSCond. 2354 if (CGF.getDebugInfo()) 2355 // There is no need to emit line number for unconditional branch. 2356 Builder.SetCurrentDebugLocation(llvm::DebugLoc()); 2357 CGF.EmitBlock(ContBlock); 2358 PN->addIncoming(RHSCond, RHSBlock); 2359 2360 // ZExt result to int. 2361 return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext"); 2362} 2363 2364Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) { 2365 llvm::Type *ResTy = ConvertType(E->getType()); 2366 2367 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1. 2368 // If we have 0 || X, just emit X without inserting the control flow. 2369 bool LHSCondVal; 2370 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) { 2371 if (!LHSCondVal) { // If we have 0 || X, just emit X. 2372 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 2373 // ZExt result to int or bool. 2374 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext"); 2375 } 2376 2377 // 1 || RHS: If it is safe, just elide the RHS, and return 1/true. 2378 if (!CGF.ContainsLabel(E->getRHS())) 2379 return llvm::ConstantInt::get(ResTy, 1); 2380 } 2381 2382 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end"); 2383 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs"); 2384 2385 CodeGenFunction::ConditionalEvaluation eval(CGF); 2386 2387 // Branch on the LHS first. If it is true, go to the success (cont) block. 2388 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock); 2389 2390 // Any edges into the ContBlock are now from an (indeterminate number of) 2391 // edges from this first condition. All of these values will be true. Start 2392 // setting up the PHI node in the Cont Block for this. 2393 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2, 2394 "", ContBlock); 2395 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock); 2396 PI != PE; ++PI) 2397 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI); 2398 2399 eval.begin(CGF); 2400 2401 // Emit the RHS condition as a bool value. 2402 CGF.EmitBlock(RHSBlock); 2403 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 2404 2405 eval.end(CGF); 2406 2407 // Reaquire the RHS block, as there may be subblocks inserted. 2408 RHSBlock = Builder.GetInsertBlock(); 2409 2410 // Emit an unconditional branch from this block to ContBlock. Insert an entry 2411 // into the phi node for the edge with the value of RHSCond. 2412 CGF.EmitBlock(ContBlock); 2413 PN->addIncoming(RHSCond, RHSBlock); 2414 2415 // ZExt result to int. 2416 return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext"); 2417} 2418 2419Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) { 2420 CGF.EmitIgnoredExpr(E->getLHS()); 2421 CGF.EnsureInsertPoint(); 2422 return Visit(E->getRHS()); 2423} 2424 2425//===----------------------------------------------------------------------===// 2426// Other Operators 2427//===----------------------------------------------------------------------===// 2428 2429/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified 2430/// expression is cheap enough and side-effect-free enough to evaluate 2431/// unconditionally instead of conditionally. This is used to convert control 2432/// flow into selects in some cases. 2433static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E, 2434 CodeGenFunction &CGF) { 2435 E = E->IgnoreParens(); 2436 2437 // Anything that is an integer or floating point constant is fine. 2438 if (E->isConstantInitializer(CGF.getContext(), false)) 2439 return true; 2440 2441 // Non-volatile automatic variables too, to get "cond ? X : Y" where 2442 // X and Y are local variables. 2443 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 2444 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) 2445 if (VD->hasLocalStorage() && !(CGF.getContext() 2446 .getCanonicalType(VD->getType()) 2447 .isVolatileQualified())) 2448 return true; 2449 2450 return false; 2451} 2452 2453 2454Value *ScalarExprEmitter:: 2455VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) { 2456 TestAndClearIgnoreResultAssign(); 2457 2458 // Bind the common expression if necessary. 2459 CodeGenFunction::OpaqueValueMapping binding(CGF, E); 2460 2461 Expr *condExpr = E->getCond(); 2462 Expr *lhsExpr = E->getTrueExpr(); 2463 Expr *rhsExpr = E->getFalseExpr(); 2464 2465 // If the condition constant folds and can be elided, try to avoid emitting 2466 // the condition and the dead arm. 2467 bool CondExprBool; 2468 if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) { 2469 Expr *live = lhsExpr, *dead = rhsExpr; 2470 if (!CondExprBool) std::swap(live, dead); 2471 2472 // If the dead side doesn't have labels we need, and if the Live side isn't 2473 // the gnu missing ?: extension (which we could handle, but don't bother 2474 // to), just emit the Live part. 2475 if (!CGF.ContainsLabel(dead)) 2476 return Visit(live); 2477 } 2478 2479 // OpenCL: If the condition is a vector, we can treat this condition like 2480 // the select function. 2481 if (CGF.getContext().getLangOptions().OpenCL 2482 && condExpr->getType()->isVectorType()) { 2483 llvm::Value *CondV = CGF.EmitScalarExpr(condExpr); 2484 llvm::Value *LHS = Visit(lhsExpr); 2485 llvm::Value *RHS = Visit(rhsExpr); 2486 2487 llvm::Type *condType = ConvertType(condExpr->getType()); 2488 llvm::VectorType *vecTy = cast<llvm::VectorType>(condType); 2489 2490 unsigned numElem = vecTy->getNumElements(); 2491 llvm::Type *elemType = vecTy->getElementType(); 2492 2493 std::vector<llvm::Constant*> Zvals; 2494 for (unsigned i = 0; i < numElem; ++i) 2495 Zvals.push_back(llvm::ConstantInt::get(elemType, 0)); 2496 2497 llvm::Value *zeroVec = llvm::ConstantVector::get(Zvals); 2498 llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec); 2499 llvm::Value *tmp = Builder.CreateSExt(TestMSB, 2500 llvm::VectorType::get(elemType, 2501 numElem), 2502 "sext"); 2503 llvm::Value *tmp2 = Builder.CreateNot(tmp); 2504 2505 // Cast float to int to perform ANDs if necessary. 2506 llvm::Value *RHSTmp = RHS; 2507 llvm::Value *LHSTmp = LHS; 2508 bool wasCast = false; 2509 llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType()); 2510 if (rhsVTy->getElementType()->isFloatTy()) { 2511 RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType()); 2512 LHSTmp = Builder.CreateBitCast(LHS, tmp->getType()); 2513 wasCast = true; 2514 } 2515 2516 llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2); 2517 llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp); 2518 llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond"); 2519 if (wasCast) 2520 tmp5 = Builder.CreateBitCast(tmp5, RHS->getType()); 2521 2522 return tmp5; 2523 } 2524 2525 // If this is a really simple expression (like x ? 4 : 5), emit this as a 2526 // select instead of as control flow. We can only do this if it is cheap and 2527 // safe to evaluate the LHS and RHS unconditionally. 2528 if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) && 2529 isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) { 2530 llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr); 2531 llvm::Value *LHS = Visit(lhsExpr); 2532 llvm::Value *RHS = Visit(rhsExpr); 2533 return Builder.CreateSelect(CondV, LHS, RHS, "cond"); 2534 } 2535 2536 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true"); 2537 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false"); 2538 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end"); 2539 2540 CodeGenFunction::ConditionalEvaluation eval(CGF); 2541 CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock); 2542 2543 CGF.EmitBlock(LHSBlock); 2544 eval.begin(CGF); 2545 Value *LHS = Visit(lhsExpr); 2546 eval.end(CGF); 2547 2548 LHSBlock = Builder.GetInsertBlock(); 2549 Builder.CreateBr(ContBlock); 2550 2551 CGF.EmitBlock(RHSBlock); 2552 eval.begin(CGF); 2553 Value *RHS = Visit(rhsExpr); 2554 eval.end(CGF); 2555 2556 RHSBlock = Builder.GetInsertBlock(); 2557 CGF.EmitBlock(ContBlock); 2558 2559 // If the LHS or RHS is a throw expression, it will be legitimately null. 2560 if (!LHS) 2561 return RHS; 2562 if (!RHS) 2563 return LHS; 2564 2565 // Create a PHI node for the real part. 2566 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond"); 2567 PN->addIncoming(LHS, LHSBlock); 2568 PN->addIncoming(RHS, RHSBlock); 2569 return PN; 2570} 2571 2572Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) { 2573 return Visit(E->getChosenSubExpr(CGF.getContext())); 2574} 2575 2576Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) { 2577 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr()); 2578 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType()); 2579 2580 // If EmitVAArg fails, we fall back to the LLVM instruction. 2581 if (!ArgPtr) 2582 return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType())); 2583 2584 // FIXME Volatility. 2585 return Builder.CreateLoad(ArgPtr); 2586} 2587 2588Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) { 2589 return CGF.EmitBlockLiteral(block); 2590} 2591 2592Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) { 2593 Value *Src = CGF.EmitScalarExpr(E->getSrcExpr()); 2594 llvm::Type *DstTy = ConvertType(E->getType()); 2595 2596 // Going from vec4->vec3 or vec3->vec4 is a special case and requires 2597 // a shuffle vector instead of a bitcast. 2598 llvm::Type *SrcTy = Src->getType(); 2599 if (isa<llvm::VectorType>(DstTy) && isa<llvm::VectorType>(SrcTy)) { 2600 unsigned numElementsDst = cast<llvm::VectorType>(DstTy)->getNumElements(); 2601 unsigned numElementsSrc = cast<llvm::VectorType>(SrcTy)->getNumElements(); 2602 if ((numElementsDst == 3 && numElementsSrc == 4) 2603 || (numElementsDst == 4 && numElementsSrc == 3)) { 2604 2605 2606 // In the case of going from int4->float3, a bitcast is needed before 2607 // doing a shuffle. 2608 llvm::Type *srcElemTy = 2609 cast<llvm::VectorType>(SrcTy)->getElementType(); 2610 llvm::Type *dstElemTy = 2611 cast<llvm::VectorType>(DstTy)->getElementType(); 2612 2613 if ((srcElemTy->isIntegerTy() && dstElemTy->isFloatTy()) 2614 || (srcElemTy->isFloatTy() && dstElemTy->isIntegerTy())) { 2615 // Create a float type of the same size as the source or destination. 2616 llvm::VectorType *newSrcTy = llvm::VectorType::get(dstElemTy, 2617 numElementsSrc); 2618 2619 Src = Builder.CreateBitCast(Src, newSrcTy, "astypeCast"); 2620 } 2621 2622 llvm::Value *UnV = llvm::UndefValue::get(Src->getType()); 2623 2624 SmallVector<llvm::Constant*, 3> Args; 2625 Args.push_back(Builder.getInt32(0)); 2626 Args.push_back(Builder.getInt32(1)); 2627 Args.push_back(Builder.getInt32(2)); 2628 2629 if (numElementsDst == 4) 2630 Args.push_back(llvm::UndefValue::get( 2631 llvm::Type::getInt32Ty(CGF.getLLVMContext()))); 2632 2633 llvm::Constant *Mask = llvm::ConstantVector::get(Args); 2634 2635 return Builder.CreateShuffleVector(Src, UnV, Mask, "astype"); 2636 } 2637 } 2638 2639 return Builder.CreateBitCast(Src, DstTy, "astype"); 2640} 2641 2642//===----------------------------------------------------------------------===// 2643// Entry Point into this File 2644//===----------------------------------------------------------------------===// 2645 2646/// EmitScalarExpr - Emit the computation of the specified expression of scalar 2647/// type, ignoring the result. 2648Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) { 2649 assert(E && !hasAggregateLLVMType(E->getType()) && 2650 "Invalid scalar expression to emit"); 2651 2652 if (isa<CXXDefaultArgExpr>(E)) 2653 disableDebugInfo(); 2654 Value *V = ScalarExprEmitter(*this, IgnoreResultAssign) 2655 .Visit(const_cast<Expr*>(E)); 2656 if (isa<CXXDefaultArgExpr>(E)) 2657 enableDebugInfo(); 2658 return V; 2659} 2660 2661/// EmitScalarConversion - Emit a conversion from the specified type to the 2662/// specified destination type, both of which are LLVM scalar types. 2663Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy, 2664 QualType DstTy) { 2665 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) && 2666 "Invalid scalar expression to emit"); 2667 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy); 2668} 2669 2670/// EmitComplexToScalarConversion - Emit a conversion from the specified complex 2671/// type to the specified destination type, where the destination type is an 2672/// LLVM scalar type. 2673Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src, 2674 QualType SrcTy, 2675 QualType DstTy) { 2676 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) && 2677 "Invalid complex -> scalar conversion"); 2678 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy, 2679 DstTy); 2680} 2681 2682 2683llvm::Value *CodeGenFunction:: 2684EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, 2685 bool isInc, bool isPre) { 2686 return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre); 2687} 2688 2689LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) { 2690 llvm::Value *V; 2691 // object->isa or (*object).isa 2692 // Generate code as for: *(Class*)object 2693 // build Class* type 2694 llvm::Type *ClassPtrTy = ConvertType(E->getType()); 2695 2696 Expr *BaseExpr = E->getBase(); 2697 if (BaseExpr->isRValue()) { 2698 V = CreateTempAlloca(ClassPtrTy, "resval"); 2699 llvm::Value *Src = EmitScalarExpr(BaseExpr); 2700 Builder.CreateStore(Src, V); 2701 V = ScalarExprEmitter(*this).EmitLoadOfLValue( 2702 MakeAddrLValue(V, E->getType())); 2703 } else { 2704 if (E->isArrow()) 2705 V = ScalarExprEmitter(*this).EmitLoadOfLValue(BaseExpr); 2706 else 2707 V = EmitLValue(BaseExpr).getAddress(); 2708 } 2709 2710 // build Class* type 2711 ClassPtrTy = ClassPtrTy->getPointerTo(); 2712 V = Builder.CreateBitCast(V, ClassPtrTy); 2713 return MakeAddrLValue(V, E->getType()); 2714} 2715 2716 2717LValue CodeGenFunction::EmitCompoundAssignmentLValue( 2718 const CompoundAssignOperator *E) { 2719 ScalarExprEmitter Scalar(*this); 2720 Value *Result = 0; 2721 switch (E->getOpcode()) { 2722#define COMPOUND_OP(Op) \ 2723 case BO_##Op##Assign: \ 2724 return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \ 2725 Result) 2726 COMPOUND_OP(Mul); 2727 COMPOUND_OP(Div); 2728 COMPOUND_OP(Rem); 2729 COMPOUND_OP(Add); 2730 COMPOUND_OP(Sub); 2731 COMPOUND_OP(Shl); 2732 COMPOUND_OP(Shr); 2733 COMPOUND_OP(And); 2734 COMPOUND_OP(Xor); 2735 COMPOUND_OP(Or); 2736#undef COMPOUND_OP 2737 2738 case BO_PtrMemD: 2739 case BO_PtrMemI: 2740 case BO_Mul: 2741 case BO_Div: 2742 case BO_Rem: 2743 case BO_Add: 2744 case BO_Sub: 2745 case BO_Shl: 2746 case BO_Shr: 2747 case BO_LT: 2748 case BO_GT: 2749 case BO_LE: 2750 case BO_GE: 2751 case BO_EQ: 2752 case BO_NE: 2753 case BO_And: 2754 case BO_Xor: 2755 case BO_Or: 2756 case BO_LAnd: 2757 case BO_LOr: 2758 case BO_Assign: 2759 case BO_Comma: 2760 llvm_unreachable("Not valid compound assignment operators"); 2761 } 2762 2763 llvm_unreachable("Unhandled compound assignment operator"); 2764} 2765