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