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