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