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