1 //===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This contains code to emit Expr nodes with scalar LLVM types as LLVM code. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "CGCXXABI.h" 14 #include "CGCleanup.h" 15 #include "CGDebugInfo.h" 16 #include "CGObjCRuntime.h" 17 #include "CGOpenMPRuntime.h" 18 #include "CodeGenFunction.h" 19 #include "CodeGenModule.h" 20 #include "ConstantEmitter.h" 21 #include "TargetInfo.h" 22 #include "clang/AST/ASTContext.h" 23 #include "clang/AST/Attr.h" 24 #include "clang/AST/DeclObjC.h" 25 #include "clang/AST/Expr.h" 26 #include "clang/AST/RecordLayout.h" 27 #include "clang/AST/StmtVisitor.h" 28 #include "clang/Basic/CodeGenOptions.h" 29 #include "clang/Basic/FixedPoint.h" 30 #include "clang/Basic/TargetInfo.h" 31 #include "llvm/ADT/Optional.h" 32 #include "llvm/IR/CFG.h" 33 #include "llvm/IR/Constants.h" 34 #include "llvm/IR/DataLayout.h" 35 #include "llvm/IR/Function.h" 36 #include "llvm/IR/GetElementPtrTypeIterator.h" 37 #include "llvm/IR/GlobalVariable.h" 38 #include "llvm/IR/Intrinsics.h" 39 #include "llvm/IR/IntrinsicsPowerPC.h" 40 #include "llvm/IR/MatrixBuilder.h" 41 #include "llvm/IR/Module.h" 42 #include <cstdarg> 43 44 using namespace clang; 45 using namespace CodeGen; 46 using llvm::Value; 47 48 //===----------------------------------------------------------------------===// 49 // Scalar Expression Emitter 50 //===----------------------------------------------------------------------===// 51 52 namespace { 53 54 /// Determine whether the given binary operation may overflow. 55 /// Sets \p Result to the value of the operation for BO_Add, BO_Sub, BO_Mul, 56 /// and signed BO_{Div,Rem}. For these opcodes, and for unsigned BO_{Div,Rem}, 57 /// the returned overflow check is precise. The returned value is 'true' for 58 /// all other opcodes, to be conservative. 59 bool mayHaveIntegerOverflow(llvm::ConstantInt *LHS, llvm::ConstantInt *RHS, 60 BinaryOperator::Opcode Opcode, bool Signed, 61 llvm::APInt &Result) { 62 // Assume overflow is possible, unless we can prove otherwise. 63 bool Overflow = true; 64 const auto &LHSAP = LHS->getValue(); 65 const auto &RHSAP = RHS->getValue(); 66 if (Opcode == BO_Add) { 67 if (Signed) 68 Result = LHSAP.sadd_ov(RHSAP, Overflow); 69 else 70 Result = LHSAP.uadd_ov(RHSAP, Overflow); 71 } else if (Opcode == BO_Sub) { 72 if (Signed) 73 Result = LHSAP.ssub_ov(RHSAP, Overflow); 74 else 75 Result = LHSAP.usub_ov(RHSAP, Overflow); 76 } else if (Opcode == BO_Mul) { 77 if (Signed) 78 Result = LHSAP.smul_ov(RHSAP, Overflow); 79 else 80 Result = LHSAP.umul_ov(RHSAP, Overflow); 81 } else if (Opcode == BO_Div || Opcode == BO_Rem) { 82 if (Signed && !RHS->isZero()) 83 Result = LHSAP.sdiv_ov(RHSAP, Overflow); 84 else 85 return false; 86 } 87 return Overflow; 88 } 89 90 struct BinOpInfo { 91 Value *LHS; 92 Value *RHS; 93 QualType Ty; // Computation Type. 94 BinaryOperator::Opcode Opcode; // Opcode of BinOp to perform 95 FPOptions FPFeatures; 96 const Expr *E; // Entire expr, for error unsupported. May not be binop. 97 98 /// Check if the binop can result in integer overflow. 99 bool mayHaveIntegerOverflow() const { 100 // Without constant input, we can't rule out overflow. 101 auto *LHSCI = dyn_cast<llvm::ConstantInt>(LHS); 102 auto *RHSCI = dyn_cast<llvm::ConstantInt>(RHS); 103 if (!LHSCI || !RHSCI) 104 return true; 105 106 llvm::APInt Result; 107 return ::mayHaveIntegerOverflow( 108 LHSCI, RHSCI, Opcode, Ty->hasSignedIntegerRepresentation(), Result); 109 } 110 111 /// Check if the binop computes a division or a remainder. 112 bool isDivremOp() const { 113 return Opcode == BO_Div || Opcode == BO_Rem || Opcode == BO_DivAssign || 114 Opcode == BO_RemAssign; 115 } 116 117 /// Check if the binop can result in an integer division by zero. 118 bool mayHaveIntegerDivisionByZero() const { 119 if (isDivremOp()) 120 if (auto *CI = dyn_cast<llvm::ConstantInt>(RHS)) 121 return CI->isZero(); 122 return true; 123 } 124 125 /// Check if the binop can result in a float division by zero. 126 bool mayHaveFloatDivisionByZero() const { 127 if (isDivremOp()) 128 if (auto *CFP = dyn_cast<llvm::ConstantFP>(RHS)) 129 return CFP->isZero(); 130 return true; 131 } 132 133 /// Check if at least one operand is a fixed point type. In such cases, this 134 /// operation did not follow usual arithmetic conversion and both operands 135 /// might not be of the same type. 136 bool isFixedPointOp() const { 137 // We cannot simply check the result type since comparison operations return 138 // an int. 139 if (const auto *BinOp = dyn_cast<BinaryOperator>(E)) { 140 QualType LHSType = BinOp->getLHS()->getType(); 141 QualType RHSType = BinOp->getRHS()->getType(); 142 return LHSType->isFixedPointType() || RHSType->isFixedPointType(); 143 } 144 if (const auto *UnOp = dyn_cast<UnaryOperator>(E)) 145 return UnOp->getSubExpr()->getType()->isFixedPointType(); 146 return false; 147 } 148 }; 149 150 static bool MustVisitNullValue(const Expr *E) { 151 // If a null pointer expression's type is the C++0x nullptr_t, then 152 // it's not necessarily a simple constant and it must be evaluated 153 // for its potential side effects. 154 return E->getType()->isNullPtrType(); 155 } 156 157 /// If \p E is a widened promoted integer, get its base (unpromoted) type. 158 static llvm::Optional<QualType> getUnwidenedIntegerType(const ASTContext &Ctx, 159 const Expr *E) { 160 const Expr *Base = E->IgnoreImpCasts(); 161 if (E == Base) 162 return llvm::None; 163 164 QualType BaseTy = Base->getType(); 165 if (!BaseTy->isPromotableIntegerType() || 166 Ctx.getTypeSize(BaseTy) >= Ctx.getTypeSize(E->getType())) 167 return llvm::None; 168 169 return BaseTy; 170 } 171 172 /// Check if \p E is a widened promoted integer. 173 static bool IsWidenedIntegerOp(const ASTContext &Ctx, const Expr *E) { 174 return getUnwidenedIntegerType(Ctx, E).hasValue(); 175 } 176 177 /// Check if we can skip the overflow check for \p Op. 178 static bool CanElideOverflowCheck(const ASTContext &Ctx, const BinOpInfo &Op) { 179 assert((isa<UnaryOperator>(Op.E) || isa<BinaryOperator>(Op.E)) && 180 "Expected a unary or binary operator"); 181 182 // If the binop has constant inputs and we can prove there is no overflow, 183 // we can elide the overflow check. 184 if (!Op.mayHaveIntegerOverflow()) 185 return true; 186 187 // If a unary op has a widened operand, the op cannot overflow. 188 if (const auto *UO = dyn_cast<UnaryOperator>(Op.E)) 189 return !UO->canOverflow(); 190 191 // We usually don't need overflow checks for binops with widened operands. 192 // Multiplication with promoted unsigned operands is a special case. 193 const auto *BO = cast<BinaryOperator>(Op.E); 194 auto OptionalLHSTy = getUnwidenedIntegerType(Ctx, BO->getLHS()); 195 if (!OptionalLHSTy) 196 return false; 197 198 auto OptionalRHSTy = getUnwidenedIntegerType(Ctx, BO->getRHS()); 199 if (!OptionalRHSTy) 200 return false; 201 202 QualType LHSTy = *OptionalLHSTy; 203 QualType RHSTy = *OptionalRHSTy; 204 205 // This is the simple case: binops without unsigned multiplication, and with 206 // widened operands. No overflow check is needed here. 207 if ((Op.Opcode != BO_Mul && Op.Opcode != BO_MulAssign) || 208 !LHSTy->isUnsignedIntegerType() || !RHSTy->isUnsignedIntegerType()) 209 return true; 210 211 // For unsigned multiplication the overflow check can be elided if either one 212 // of the unpromoted types are less than half the size of the promoted type. 213 unsigned PromotedSize = Ctx.getTypeSize(Op.E->getType()); 214 return (2 * Ctx.getTypeSize(LHSTy)) < PromotedSize || 215 (2 * Ctx.getTypeSize(RHSTy)) < PromotedSize; 216 } 217 218 class ScalarExprEmitter 219 : public StmtVisitor<ScalarExprEmitter, Value*> { 220 CodeGenFunction &CGF; 221 CGBuilderTy &Builder; 222 bool IgnoreResultAssign; 223 llvm::LLVMContext &VMContext; 224 public: 225 226 ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false) 227 : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira), 228 VMContext(cgf.getLLVMContext()) { 229 } 230 231 //===--------------------------------------------------------------------===// 232 // Utilities 233 //===--------------------------------------------------------------------===// 234 235 bool TestAndClearIgnoreResultAssign() { 236 bool I = IgnoreResultAssign; 237 IgnoreResultAssign = false; 238 return I; 239 } 240 241 llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); } 242 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); } 243 LValue EmitCheckedLValue(const Expr *E, CodeGenFunction::TypeCheckKind TCK) { 244 return CGF.EmitCheckedLValue(E, TCK); 245 } 246 247 void EmitBinOpCheck(ArrayRef<std::pair<Value *, SanitizerMask>> Checks, 248 const BinOpInfo &Info); 249 250 Value *EmitLoadOfLValue(LValue LV, SourceLocation Loc) { 251 return CGF.EmitLoadOfLValue(LV, Loc).getScalarVal(); 252 } 253 254 void EmitLValueAlignmentAssumption(const Expr *E, Value *V) { 255 const AlignValueAttr *AVAttr = nullptr; 256 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) { 257 const ValueDecl *VD = DRE->getDecl(); 258 259 if (VD->getType()->isReferenceType()) { 260 if (const auto *TTy = 261 dyn_cast<TypedefType>(VD->getType().getNonReferenceType())) 262 AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>(); 263 } else { 264 // Assumptions for function parameters are emitted at the start of the 265 // function, so there is no need to repeat that here, 266 // unless the alignment-assumption sanitizer is enabled, 267 // then we prefer the assumption over alignment attribute 268 // on IR function param. 269 if (isa<ParmVarDecl>(VD) && !CGF.SanOpts.has(SanitizerKind::Alignment)) 270 return; 271 272 AVAttr = VD->getAttr<AlignValueAttr>(); 273 } 274 } 275 276 if (!AVAttr) 277 if (const auto *TTy = 278 dyn_cast<TypedefType>(E->getType())) 279 AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>(); 280 281 if (!AVAttr) 282 return; 283 284 Value *AlignmentValue = CGF.EmitScalarExpr(AVAttr->getAlignment()); 285 llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(AlignmentValue); 286 CGF.emitAlignmentAssumption(V, E, AVAttr->getLocation(), AlignmentCI); 287 } 288 289 /// EmitLoadOfLValue - Given an expression with complex type that represents a 290 /// value l-value, this method emits the address of the l-value, then loads 291 /// and returns the result. 292 Value *EmitLoadOfLValue(const Expr *E) { 293 Value *V = EmitLoadOfLValue(EmitCheckedLValue(E, CodeGenFunction::TCK_Load), 294 E->getExprLoc()); 295 296 EmitLValueAlignmentAssumption(E, V); 297 return V; 298 } 299 300 /// EmitConversionToBool - Convert the specified expression value to a 301 /// boolean (i1) truth value. This is equivalent to "Val != 0". 302 Value *EmitConversionToBool(Value *Src, QualType DstTy); 303 304 /// Emit a check that a conversion from a floating-point type does not 305 /// overflow. 306 void EmitFloatConversionCheck(Value *OrigSrc, QualType OrigSrcType, 307 Value *Src, QualType SrcType, QualType DstType, 308 llvm::Type *DstTy, SourceLocation Loc); 309 310 /// Known implicit conversion check kinds. 311 /// Keep in sync with the enum of the same name in ubsan_handlers.h 312 enum ImplicitConversionCheckKind : unsigned char { 313 ICCK_IntegerTruncation = 0, // Legacy, was only used by clang 7. 314 ICCK_UnsignedIntegerTruncation = 1, 315 ICCK_SignedIntegerTruncation = 2, 316 ICCK_IntegerSignChange = 3, 317 ICCK_SignedIntegerTruncationOrSignChange = 4, 318 }; 319 320 /// Emit a check that an [implicit] truncation of an integer does not 321 /// discard any bits. It is not UB, so we use the value after truncation. 322 void EmitIntegerTruncationCheck(Value *Src, QualType SrcType, Value *Dst, 323 QualType DstType, SourceLocation Loc); 324 325 /// Emit a check that an [implicit] conversion of an integer does not change 326 /// the sign of the value. It is not UB, so we use the value after conversion. 327 /// NOTE: Src and Dst may be the exact same value! (point to the same thing) 328 void EmitIntegerSignChangeCheck(Value *Src, QualType SrcType, Value *Dst, 329 QualType DstType, SourceLocation Loc); 330 331 /// Emit a conversion from the specified type to the specified destination 332 /// type, both of which are LLVM scalar types. 333 struct ScalarConversionOpts { 334 bool TreatBooleanAsSigned; 335 bool EmitImplicitIntegerTruncationChecks; 336 bool EmitImplicitIntegerSignChangeChecks; 337 338 ScalarConversionOpts() 339 : TreatBooleanAsSigned(false), 340 EmitImplicitIntegerTruncationChecks(false), 341 EmitImplicitIntegerSignChangeChecks(false) {} 342 343 ScalarConversionOpts(clang::SanitizerSet SanOpts) 344 : TreatBooleanAsSigned(false), 345 EmitImplicitIntegerTruncationChecks( 346 SanOpts.hasOneOf(SanitizerKind::ImplicitIntegerTruncation)), 347 EmitImplicitIntegerSignChangeChecks( 348 SanOpts.has(SanitizerKind::ImplicitIntegerSignChange)) {} 349 }; 350 Value * 351 EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy, 352 SourceLocation Loc, 353 ScalarConversionOpts Opts = ScalarConversionOpts()); 354 355 /// Convert between either a fixed point and other fixed point or fixed point 356 /// and an integer. 357 Value *EmitFixedPointConversion(Value *Src, QualType SrcTy, QualType DstTy, 358 SourceLocation Loc); 359 Value *EmitFixedPointConversion(Value *Src, FixedPointSemantics &SrcFixedSema, 360 FixedPointSemantics &DstFixedSema, 361 SourceLocation Loc, 362 bool DstIsInteger = false); 363 364 /// Emit a conversion from the specified complex type to the specified 365 /// destination type, where the destination type is an LLVM scalar type. 366 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src, 367 QualType SrcTy, QualType DstTy, 368 SourceLocation Loc); 369 370 /// EmitNullValue - Emit a value that corresponds to null for the given type. 371 Value *EmitNullValue(QualType Ty); 372 373 /// EmitFloatToBoolConversion - Perform an FP to boolean conversion. 374 Value *EmitFloatToBoolConversion(Value *V) { 375 // Compare against 0.0 for fp scalars. 376 llvm::Value *Zero = llvm::Constant::getNullValue(V->getType()); 377 return Builder.CreateFCmpUNE(V, Zero, "tobool"); 378 } 379 380 /// EmitPointerToBoolConversion - Perform a pointer to boolean conversion. 381 Value *EmitPointerToBoolConversion(Value *V, QualType QT) { 382 Value *Zero = CGF.CGM.getNullPointer(cast<llvm::PointerType>(V->getType()), QT); 383 384 return Builder.CreateICmpNE(V, Zero, "tobool"); 385 } 386 387 Value *EmitIntToBoolConversion(Value *V) { 388 // Because of the type rules of C, we often end up computing a 389 // logical value, then zero extending it to int, then wanting it 390 // as a logical value again. Optimize this common case. 391 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(V)) { 392 if (ZI->getOperand(0)->getType() == Builder.getInt1Ty()) { 393 Value *Result = ZI->getOperand(0); 394 // If there aren't any more uses, zap the instruction to save space. 395 // Note that there can be more uses, for example if this 396 // is the result of an assignment. 397 if (ZI->use_empty()) 398 ZI->eraseFromParent(); 399 return Result; 400 } 401 } 402 403 return Builder.CreateIsNotNull(V, "tobool"); 404 } 405 406 //===--------------------------------------------------------------------===// 407 // Visitor Methods 408 //===--------------------------------------------------------------------===// 409 410 Value *Visit(Expr *E) { 411 ApplyDebugLocation DL(CGF, E); 412 return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E); 413 } 414 415 Value *VisitStmt(Stmt *S) { 416 S->dump(CGF.getContext().getSourceManager()); 417 llvm_unreachable("Stmt can't have complex result type!"); 418 } 419 Value *VisitExpr(Expr *S); 420 421 Value *VisitConstantExpr(ConstantExpr *E) { 422 return Visit(E->getSubExpr()); 423 } 424 Value *VisitParenExpr(ParenExpr *PE) { 425 return Visit(PE->getSubExpr()); 426 } 427 Value *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) { 428 return Visit(E->getReplacement()); 429 } 430 Value *VisitGenericSelectionExpr(GenericSelectionExpr *GE) { 431 return Visit(GE->getResultExpr()); 432 } 433 Value *VisitCoawaitExpr(CoawaitExpr *S) { 434 return CGF.EmitCoawaitExpr(*S).getScalarVal(); 435 } 436 Value *VisitCoyieldExpr(CoyieldExpr *S) { 437 return CGF.EmitCoyieldExpr(*S).getScalarVal(); 438 } 439 Value *VisitUnaryCoawait(const UnaryOperator *E) { 440 return Visit(E->getSubExpr()); 441 } 442 443 // Leaves. 444 Value *VisitIntegerLiteral(const IntegerLiteral *E) { 445 return Builder.getInt(E->getValue()); 446 } 447 Value *VisitFixedPointLiteral(const FixedPointLiteral *E) { 448 return Builder.getInt(E->getValue()); 449 } 450 Value *VisitFloatingLiteral(const FloatingLiteral *E) { 451 return llvm::ConstantFP::get(VMContext, E->getValue()); 452 } 453 Value *VisitCharacterLiteral(const CharacterLiteral *E) { 454 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue()); 455 } 456 Value *VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) { 457 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue()); 458 } 459 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 460 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue()); 461 } 462 Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { 463 return EmitNullValue(E->getType()); 464 } 465 Value *VisitGNUNullExpr(const GNUNullExpr *E) { 466 return EmitNullValue(E->getType()); 467 } 468 Value *VisitOffsetOfExpr(OffsetOfExpr *E); 469 Value *VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); 470 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) { 471 llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel()); 472 return Builder.CreateBitCast(V, ConvertType(E->getType())); 473 } 474 475 Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) { 476 return llvm::ConstantInt::get(ConvertType(E->getType()),E->getPackLength()); 477 } 478 479 Value *VisitPseudoObjectExpr(PseudoObjectExpr *E) { 480 return CGF.EmitPseudoObjectRValue(E).getScalarVal(); 481 } 482 483 Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) { 484 if (E->isGLValue()) 485 return EmitLoadOfLValue(CGF.getOrCreateOpaqueLValueMapping(E), 486 E->getExprLoc()); 487 488 // Otherwise, assume the mapping is the scalar directly. 489 return CGF.getOrCreateOpaqueRValueMapping(E).getScalarVal(); 490 } 491 492 // l-values. 493 Value *VisitDeclRefExpr(DeclRefExpr *E) { 494 if (CodeGenFunction::ConstantEmission Constant = CGF.tryEmitAsConstant(E)) 495 return CGF.emitScalarConstant(Constant, E); 496 return EmitLoadOfLValue(E); 497 } 498 499 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) { 500 return CGF.EmitObjCSelectorExpr(E); 501 } 502 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) { 503 return CGF.EmitObjCProtocolExpr(E); 504 } 505 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) { 506 return EmitLoadOfLValue(E); 507 } 508 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) { 509 if (E->getMethodDecl() && 510 E->getMethodDecl()->getReturnType()->isReferenceType()) 511 return EmitLoadOfLValue(E); 512 return CGF.EmitObjCMessageExpr(E).getScalarVal(); 513 } 514 515 Value *VisitObjCIsaExpr(ObjCIsaExpr *E) { 516 LValue LV = CGF.EmitObjCIsaExpr(E); 517 Value *V = CGF.EmitLoadOfLValue(LV, E->getExprLoc()).getScalarVal(); 518 return V; 519 } 520 521 Value *VisitObjCAvailabilityCheckExpr(ObjCAvailabilityCheckExpr *E) { 522 VersionTuple Version = E->getVersion(); 523 524 // If we're checking for a platform older than our minimum deployment 525 // target, we can fold the check away. 526 if (Version <= CGF.CGM.getTarget().getPlatformMinVersion()) 527 return llvm::ConstantInt::get(Builder.getInt1Ty(), 1); 528 529 Optional<unsigned> Min = Version.getMinor(), SMin = Version.getSubminor(); 530 llvm::Value *Args[] = { 531 llvm::ConstantInt::get(CGF.CGM.Int32Ty, Version.getMajor()), 532 llvm::ConstantInt::get(CGF.CGM.Int32Ty, Min ? *Min : 0), 533 llvm::ConstantInt::get(CGF.CGM.Int32Ty, SMin ? *SMin : 0), 534 }; 535 536 return CGF.EmitBuiltinAvailable(Args); 537 } 538 539 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E); 540 Value *VisitMatrixSubscriptExpr(MatrixSubscriptExpr *E); 541 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E); 542 Value *VisitConvertVectorExpr(ConvertVectorExpr *E); 543 Value *VisitMemberExpr(MemberExpr *E); 544 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); } 545 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { 546 // Strictly speaking, we shouldn't be calling EmitLoadOfLValue, which 547 // transitively calls EmitCompoundLiteralLValue, here in C++ since compound 548 // literals aren't l-values in C++. We do so simply because that's the 549 // cleanest way to handle compound literals in C++. 550 // See the discussion here: https://reviews.llvm.org/D64464 551 return EmitLoadOfLValue(E); 552 } 553 554 Value *VisitInitListExpr(InitListExpr *E); 555 556 Value *VisitArrayInitIndexExpr(ArrayInitIndexExpr *E) { 557 assert(CGF.getArrayInitIndex() && 558 "ArrayInitIndexExpr not inside an ArrayInitLoopExpr?"); 559 return CGF.getArrayInitIndex(); 560 } 561 562 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 563 return EmitNullValue(E->getType()); 564 } 565 Value *VisitExplicitCastExpr(ExplicitCastExpr *E) { 566 CGF.CGM.EmitExplicitCastExprType(E, &CGF); 567 return VisitCastExpr(E); 568 } 569 Value *VisitCastExpr(CastExpr *E); 570 571 Value *VisitCallExpr(const CallExpr *E) { 572 if (E->getCallReturnType(CGF.getContext())->isReferenceType()) 573 return EmitLoadOfLValue(E); 574 575 Value *V = CGF.EmitCallExpr(E).getScalarVal(); 576 577 EmitLValueAlignmentAssumption(E, V); 578 return V; 579 } 580 581 Value *VisitStmtExpr(const StmtExpr *E); 582 583 // Unary Operators. 584 Value *VisitUnaryPostDec(const UnaryOperator *E) { 585 LValue LV = EmitLValue(E->getSubExpr()); 586 return EmitScalarPrePostIncDec(E, LV, false, false); 587 } 588 Value *VisitUnaryPostInc(const UnaryOperator *E) { 589 LValue LV = EmitLValue(E->getSubExpr()); 590 return EmitScalarPrePostIncDec(E, LV, true, false); 591 } 592 Value *VisitUnaryPreDec(const UnaryOperator *E) { 593 LValue LV = EmitLValue(E->getSubExpr()); 594 return EmitScalarPrePostIncDec(E, LV, false, true); 595 } 596 Value *VisitUnaryPreInc(const UnaryOperator *E) { 597 LValue LV = EmitLValue(E->getSubExpr()); 598 return EmitScalarPrePostIncDec(E, LV, true, true); 599 } 600 601 llvm::Value *EmitIncDecConsiderOverflowBehavior(const UnaryOperator *E, 602 llvm::Value *InVal, 603 bool IsInc); 604 605 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, 606 bool isInc, bool isPre); 607 608 609 Value *VisitUnaryAddrOf(const UnaryOperator *E) { 610 if (isa<MemberPointerType>(E->getType())) // never sugared 611 return CGF.CGM.getMemberPointerConstant(E); 612 613 return EmitLValue(E->getSubExpr()).getPointer(CGF); 614 } 615 Value *VisitUnaryDeref(const UnaryOperator *E) { 616 if (E->getType()->isVoidType()) 617 return Visit(E->getSubExpr()); // the actual value should be unused 618 return EmitLoadOfLValue(E); 619 } 620 Value *VisitUnaryPlus(const UnaryOperator *E) { 621 // This differs from gcc, though, most likely due to a bug in gcc. 622 TestAndClearIgnoreResultAssign(); 623 return Visit(E->getSubExpr()); 624 } 625 Value *VisitUnaryMinus (const UnaryOperator *E); 626 Value *VisitUnaryNot (const UnaryOperator *E); 627 Value *VisitUnaryLNot (const UnaryOperator *E); 628 Value *VisitUnaryReal (const UnaryOperator *E); 629 Value *VisitUnaryImag (const UnaryOperator *E); 630 Value *VisitUnaryExtension(const UnaryOperator *E) { 631 return Visit(E->getSubExpr()); 632 } 633 634 // C++ 635 Value *VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E) { 636 return EmitLoadOfLValue(E); 637 } 638 Value *VisitSourceLocExpr(SourceLocExpr *SLE) { 639 auto &Ctx = CGF.getContext(); 640 APValue Evaluated = 641 SLE->EvaluateInContext(Ctx, CGF.CurSourceLocExprScope.getDefaultExpr()); 642 return ConstantEmitter(CGF).emitAbstract(SLE->getLocation(), Evaluated, 643 SLE->getType()); 644 } 645 646 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) { 647 CodeGenFunction::CXXDefaultArgExprScope Scope(CGF, DAE); 648 return Visit(DAE->getExpr()); 649 } 650 Value *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) { 651 CodeGenFunction::CXXDefaultInitExprScope Scope(CGF, DIE); 652 return Visit(DIE->getExpr()); 653 } 654 Value *VisitCXXThisExpr(CXXThisExpr *TE) { 655 return CGF.LoadCXXThis(); 656 } 657 658 Value *VisitExprWithCleanups(ExprWithCleanups *E); 659 Value *VisitCXXNewExpr(const CXXNewExpr *E) { 660 return CGF.EmitCXXNewExpr(E); 661 } 662 Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) { 663 CGF.EmitCXXDeleteExpr(E); 664 return nullptr; 665 } 666 667 Value *VisitTypeTraitExpr(const TypeTraitExpr *E) { 668 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue()); 669 } 670 671 Value *VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E) { 672 return Builder.getInt1(E->isSatisfied()); 673 } 674 675 Value *VisitRequiresExpr(const RequiresExpr *E) { 676 return Builder.getInt1(E->isSatisfied()); 677 } 678 679 Value *VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 680 return llvm::ConstantInt::get(Builder.getInt32Ty(), E->getValue()); 681 } 682 683 Value *VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 684 return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue()); 685 } 686 687 Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) { 688 // C++ [expr.pseudo]p1: 689 // The result shall only be used as the operand for the function call 690 // operator (), and the result of such a call has type void. The only 691 // effect is the evaluation of the postfix-expression before the dot or 692 // arrow. 693 CGF.EmitScalarExpr(E->getBase()); 694 return nullptr; 695 } 696 697 Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { 698 return EmitNullValue(E->getType()); 699 } 700 701 Value *VisitCXXThrowExpr(const CXXThrowExpr *E) { 702 CGF.EmitCXXThrowExpr(E); 703 return nullptr; 704 } 705 706 Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { 707 return Builder.getInt1(E->getValue()); 708 } 709 710 // Binary Operators. 711 Value *EmitMul(const BinOpInfo &Ops) { 712 if (Ops.Ty->isSignedIntegerOrEnumerationType()) { 713 switch (CGF.getLangOpts().getSignedOverflowBehavior()) { 714 case LangOptions::SOB_Defined: 715 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul"); 716 case LangOptions::SOB_Undefined: 717 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) 718 return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul"); 719 LLVM_FALLTHROUGH; 720 case LangOptions::SOB_Trapping: 721 if (CanElideOverflowCheck(CGF.getContext(), Ops)) 722 return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul"); 723 return EmitOverflowCheckedBinOp(Ops); 724 } 725 } 726 727 if (Ops.Ty->isConstantMatrixType()) { 728 llvm::MatrixBuilder<CGBuilderTy> MB(Builder); 729 // We need to check the types of the operands of the operator to get the 730 // correct matrix dimensions. 731 auto *BO = cast<BinaryOperator>(Ops.E); 732 auto *LHSMatTy = dyn_cast<ConstantMatrixType>( 733 BO->getLHS()->getType().getCanonicalType()); 734 auto *RHSMatTy = dyn_cast<ConstantMatrixType>( 735 BO->getRHS()->getType().getCanonicalType()); 736 if (LHSMatTy && RHSMatTy) 737 return MB.CreateMatrixMultiply(Ops.LHS, Ops.RHS, LHSMatTy->getNumRows(), 738 LHSMatTy->getNumColumns(), 739 RHSMatTy->getNumColumns()); 740 return MB.CreateScalarMultiply(Ops.LHS, Ops.RHS); 741 } 742 743 if (Ops.Ty->isUnsignedIntegerType() && 744 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) && 745 !CanElideOverflowCheck(CGF.getContext(), Ops)) 746 return EmitOverflowCheckedBinOp(Ops); 747 748 if (Ops.LHS->getType()->isFPOrFPVectorTy()) { 749 // Preserve the old values 750 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Ops.FPFeatures); 751 return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul"); 752 } 753 if (Ops.isFixedPointOp()) 754 return EmitFixedPointBinOp(Ops); 755 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul"); 756 } 757 /// Create a binary op that checks for overflow. 758 /// Currently only supports +, - and *. 759 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops); 760 761 // Check for undefined division and modulus behaviors. 762 void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops, 763 llvm::Value *Zero,bool isDiv); 764 // Common helper for getting how wide LHS of shift is. 765 static Value *GetWidthMinusOneValue(Value* LHS,Value* RHS); 766 767 // Used for shifting constraints for OpenCL, do mask for powers of 2, URem for 768 // non powers of two. 769 Value *ConstrainShiftValue(Value *LHS, Value *RHS, const Twine &Name); 770 771 Value *EmitDiv(const BinOpInfo &Ops); 772 Value *EmitRem(const BinOpInfo &Ops); 773 Value *EmitAdd(const BinOpInfo &Ops); 774 Value *EmitSub(const BinOpInfo &Ops); 775 Value *EmitShl(const BinOpInfo &Ops); 776 Value *EmitShr(const BinOpInfo &Ops); 777 Value *EmitAnd(const BinOpInfo &Ops) { 778 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and"); 779 } 780 Value *EmitXor(const BinOpInfo &Ops) { 781 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor"); 782 } 783 Value *EmitOr (const BinOpInfo &Ops) { 784 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or"); 785 } 786 787 // Helper functions for fixed point binary operations. 788 Value *EmitFixedPointBinOp(const BinOpInfo &Ops); 789 790 BinOpInfo EmitBinOps(const BinaryOperator *E); 791 LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E, 792 Value *(ScalarExprEmitter::*F)(const BinOpInfo &), 793 Value *&Result); 794 795 Value *EmitCompoundAssign(const CompoundAssignOperator *E, 796 Value *(ScalarExprEmitter::*F)(const BinOpInfo &)); 797 798 // Binary operators and binary compound assignment operators. 799 #define HANDLEBINOP(OP) \ 800 Value *VisitBin ## OP(const BinaryOperator *E) { \ 801 return Emit ## OP(EmitBinOps(E)); \ 802 } \ 803 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \ 804 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \ 805 } 806 HANDLEBINOP(Mul) 807 HANDLEBINOP(Div) 808 HANDLEBINOP(Rem) 809 HANDLEBINOP(Add) 810 HANDLEBINOP(Sub) 811 HANDLEBINOP(Shl) 812 HANDLEBINOP(Shr) 813 HANDLEBINOP(And) 814 HANDLEBINOP(Xor) 815 HANDLEBINOP(Or) 816 #undef HANDLEBINOP 817 818 // Comparisons. 819 Value *EmitCompare(const BinaryOperator *E, llvm::CmpInst::Predicate UICmpOpc, 820 llvm::CmpInst::Predicate SICmpOpc, 821 llvm::CmpInst::Predicate FCmpOpc, bool IsSignaling); 822 #define VISITCOMP(CODE, UI, SI, FP, SIG) \ 823 Value *VisitBin##CODE(const BinaryOperator *E) { \ 824 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \ 825 llvm::FCmpInst::FP, SIG); } 826 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT, true) 827 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT, true) 828 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE, true) 829 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE, true) 830 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ, false) 831 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE, false) 832 #undef VISITCOMP 833 834 Value *VisitBinAssign (const BinaryOperator *E); 835 836 Value *VisitBinLAnd (const BinaryOperator *E); 837 Value *VisitBinLOr (const BinaryOperator *E); 838 Value *VisitBinComma (const BinaryOperator *E); 839 840 Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); } 841 Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); } 842 843 Value *VisitCXXRewrittenBinaryOperator(CXXRewrittenBinaryOperator *E) { 844 return Visit(E->getSemanticForm()); 845 } 846 847 // Other Operators. 848 Value *VisitBlockExpr(const BlockExpr *BE); 849 Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *); 850 Value *VisitChooseExpr(ChooseExpr *CE); 851 Value *VisitVAArgExpr(VAArgExpr *VE); 852 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) { 853 return CGF.EmitObjCStringLiteral(E); 854 } 855 Value *VisitObjCBoxedExpr(ObjCBoxedExpr *E) { 856 return CGF.EmitObjCBoxedExpr(E); 857 } 858 Value *VisitObjCArrayLiteral(ObjCArrayLiteral *E) { 859 return CGF.EmitObjCArrayLiteral(E); 860 } 861 Value *VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) { 862 return CGF.EmitObjCDictionaryLiteral(E); 863 } 864 Value *VisitAsTypeExpr(AsTypeExpr *CE); 865 Value *VisitAtomicExpr(AtomicExpr *AE); 866 }; 867 } // end anonymous namespace. 868 869 //===----------------------------------------------------------------------===// 870 // Utilities 871 //===----------------------------------------------------------------------===// 872 873 /// EmitConversionToBool - Convert the specified expression value to a 874 /// boolean (i1) truth value. This is equivalent to "Val != 0". 875 Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) { 876 assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs"); 877 878 if (SrcType->isRealFloatingType()) 879 return EmitFloatToBoolConversion(Src); 880 881 if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType)) 882 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT); 883 884 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) && 885 "Unknown scalar type to convert"); 886 887 if (isa<llvm::IntegerType>(Src->getType())) 888 return EmitIntToBoolConversion(Src); 889 890 assert(isa<llvm::PointerType>(Src->getType())); 891 return EmitPointerToBoolConversion(Src, SrcType); 892 } 893 894 void ScalarExprEmitter::EmitFloatConversionCheck( 895 Value *OrigSrc, QualType OrigSrcType, Value *Src, QualType SrcType, 896 QualType DstType, llvm::Type *DstTy, SourceLocation Loc) { 897 assert(SrcType->isFloatingType() && "not a conversion from floating point"); 898 if (!isa<llvm::IntegerType>(DstTy)) 899 return; 900 901 CodeGenFunction::SanitizerScope SanScope(&CGF); 902 using llvm::APFloat; 903 using llvm::APSInt; 904 905 llvm::Value *Check = nullptr; 906 const llvm::fltSemantics &SrcSema = 907 CGF.getContext().getFloatTypeSemantics(OrigSrcType); 908 909 // Floating-point to integer. This has undefined behavior if the source is 910 // +-Inf, NaN, or doesn't fit into the destination type (after truncation 911 // to an integer). 912 unsigned Width = CGF.getContext().getIntWidth(DstType); 913 bool Unsigned = DstType->isUnsignedIntegerOrEnumerationType(); 914 915 APSInt Min = APSInt::getMinValue(Width, Unsigned); 916 APFloat MinSrc(SrcSema, APFloat::uninitialized); 917 if (MinSrc.convertFromAPInt(Min, !Unsigned, APFloat::rmTowardZero) & 918 APFloat::opOverflow) 919 // Don't need an overflow check for lower bound. Just check for 920 // -Inf/NaN. 921 MinSrc = APFloat::getInf(SrcSema, true); 922 else 923 // Find the largest value which is too small to represent (before 924 // truncation toward zero). 925 MinSrc.subtract(APFloat(SrcSema, 1), APFloat::rmTowardNegative); 926 927 APSInt Max = APSInt::getMaxValue(Width, Unsigned); 928 APFloat MaxSrc(SrcSema, APFloat::uninitialized); 929 if (MaxSrc.convertFromAPInt(Max, !Unsigned, APFloat::rmTowardZero) & 930 APFloat::opOverflow) 931 // Don't need an overflow check for upper bound. Just check for 932 // +Inf/NaN. 933 MaxSrc = APFloat::getInf(SrcSema, false); 934 else 935 // Find the smallest value which is too large to represent (before 936 // truncation toward zero). 937 MaxSrc.add(APFloat(SrcSema, 1), APFloat::rmTowardPositive); 938 939 // If we're converting from __half, convert the range to float to match 940 // the type of src. 941 if (OrigSrcType->isHalfType()) { 942 const llvm::fltSemantics &Sema = 943 CGF.getContext().getFloatTypeSemantics(SrcType); 944 bool IsInexact; 945 MinSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact); 946 MaxSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact); 947 } 948 949 llvm::Value *GE = 950 Builder.CreateFCmpOGT(Src, llvm::ConstantFP::get(VMContext, MinSrc)); 951 llvm::Value *LE = 952 Builder.CreateFCmpOLT(Src, llvm::ConstantFP::get(VMContext, MaxSrc)); 953 Check = Builder.CreateAnd(GE, LE); 954 955 llvm::Constant *StaticArgs[] = {CGF.EmitCheckSourceLocation(Loc), 956 CGF.EmitCheckTypeDescriptor(OrigSrcType), 957 CGF.EmitCheckTypeDescriptor(DstType)}; 958 CGF.EmitCheck(std::make_pair(Check, SanitizerKind::FloatCastOverflow), 959 SanitizerHandler::FloatCastOverflow, StaticArgs, OrigSrc); 960 } 961 962 // Should be called within CodeGenFunction::SanitizerScope RAII scope. 963 // Returns 'i1 false' when the truncation Src -> Dst was lossy. 964 static std::pair<ScalarExprEmitter::ImplicitConversionCheckKind, 965 std::pair<llvm::Value *, SanitizerMask>> 966 EmitIntegerTruncationCheckHelper(Value *Src, QualType SrcType, Value *Dst, 967 QualType DstType, CGBuilderTy &Builder) { 968 llvm::Type *SrcTy = Src->getType(); 969 llvm::Type *DstTy = Dst->getType(); 970 (void)DstTy; // Only used in assert() 971 972 // This should be truncation of integral types. 973 assert(Src != Dst); 974 assert(SrcTy->getScalarSizeInBits() > Dst->getType()->getScalarSizeInBits()); 975 assert(isa<llvm::IntegerType>(SrcTy) && isa<llvm::IntegerType>(DstTy) && 976 "non-integer llvm type"); 977 978 bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType(); 979 bool DstSigned = DstType->isSignedIntegerOrEnumerationType(); 980 981 // If both (src and dst) types are unsigned, then it's an unsigned truncation. 982 // Else, it is a signed truncation. 983 ScalarExprEmitter::ImplicitConversionCheckKind Kind; 984 SanitizerMask Mask; 985 if (!SrcSigned && !DstSigned) { 986 Kind = ScalarExprEmitter::ICCK_UnsignedIntegerTruncation; 987 Mask = SanitizerKind::ImplicitUnsignedIntegerTruncation; 988 } else { 989 Kind = ScalarExprEmitter::ICCK_SignedIntegerTruncation; 990 Mask = SanitizerKind::ImplicitSignedIntegerTruncation; 991 } 992 993 llvm::Value *Check = nullptr; 994 // 1. Extend the truncated value back to the same width as the Src. 995 Check = Builder.CreateIntCast(Dst, SrcTy, DstSigned, "anyext"); 996 // 2. Equality-compare with the original source value 997 Check = Builder.CreateICmpEQ(Check, Src, "truncheck"); 998 // If the comparison result is 'i1 false', then the truncation was lossy. 999 return std::make_pair(Kind, std::make_pair(Check, Mask)); 1000 } 1001 1002 static bool PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck( 1003 QualType SrcType, QualType DstType) { 1004 return SrcType->isIntegerType() && DstType->isIntegerType(); 1005 } 1006 1007 void ScalarExprEmitter::EmitIntegerTruncationCheck(Value *Src, QualType SrcType, 1008 Value *Dst, QualType DstType, 1009 SourceLocation Loc) { 1010 if (!CGF.SanOpts.hasOneOf(SanitizerKind::ImplicitIntegerTruncation)) 1011 return; 1012 1013 // We only care about int->int conversions here. 1014 // We ignore conversions to/from pointer and/or bool. 1015 if (!PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(SrcType, 1016 DstType)) 1017 return; 1018 1019 unsigned SrcBits = Src->getType()->getScalarSizeInBits(); 1020 unsigned DstBits = Dst->getType()->getScalarSizeInBits(); 1021 // This must be truncation. Else we do not care. 1022 if (SrcBits <= DstBits) 1023 return; 1024 1025 assert(!DstType->isBooleanType() && "we should not get here with booleans."); 1026 1027 // If the integer sign change sanitizer is enabled, 1028 // and we are truncating from larger unsigned type to smaller signed type, 1029 // let that next sanitizer deal with it. 1030 bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType(); 1031 bool DstSigned = DstType->isSignedIntegerOrEnumerationType(); 1032 if (CGF.SanOpts.has(SanitizerKind::ImplicitIntegerSignChange) && 1033 (!SrcSigned && DstSigned)) 1034 return; 1035 1036 CodeGenFunction::SanitizerScope SanScope(&CGF); 1037 1038 std::pair<ScalarExprEmitter::ImplicitConversionCheckKind, 1039 std::pair<llvm::Value *, SanitizerMask>> 1040 Check = 1041 EmitIntegerTruncationCheckHelper(Src, SrcType, Dst, DstType, Builder); 1042 // If the comparison result is 'i1 false', then the truncation was lossy. 1043 1044 // Do we care about this type of truncation? 1045 if (!CGF.SanOpts.has(Check.second.second)) 1046 return; 1047 1048 llvm::Constant *StaticArgs[] = { 1049 CGF.EmitCheckSourceLocation(Loc), CGF.EmitCheckTypeDescriptor(SrcType), 1050 CGF.EmitCheckTypeDescriptor(DstType), 1051 llvm::ConstantInt::get(Builder.getInt8Ty(), Check.first)}; 1052 CGF.EmitCheck(Check.second, SanitizerHandler::ImplicitConversion, StaticArgs, 1053 {Src, Dst}); 1054 } 1055 1056 // Should be called within CodeGenFunction::SanitizerScope RAII scope. 1057 // Returns 'i1 false' when the conversion Src -> Dst changed the sign. 1058 static std::pair<ScalarExprEmitter::ImplicitConversionCheckKind, 1059 std::pair<llvm::Value *, SanitizerMask>> 1060 EmitIntegerSignChangeCheckHelper(Value *Src, QualType SrcType, Value *Dst, 1061 QualType DstType, CGBuilderTy &Builder) { 1062 llvm::Type *SrcTy = Src->getType(); 1063 llvm::Type *DstTy = Dst->getType(); 1064 1065 assert(isa<llvm::IntegerType>(SrcTy) && isa<llvm::IntegerType>(DstTy) && 1066 "non-integer llvm type"); 1067 1068 bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType(); 1069 bool DstSigned = DstType->isSignedIntegerOrEnumerationType(); 1070 (void)SrcSigned; // Only used in assert() 1071 (void)DstSigned; // Only used in assert() 1072 unsigned SrcBits = SrcTy->getScalarSizeInBits(); 1073 unsigned DstBits = DstTy->getScalarSizeInBits(); 1074 (void)SrcBits; // Only used in assert() 1075 (void)DstBits; // Only used in assert() 1076 1077 assert(((SrcBits != DstBits) || (SrcSigned != DstSigned)) && 1078 "either the widths should be different, or the signednesses."); 1079 1080 // NOTE: zero value is considered to be non-negative. 1081 auto EmitIsNegativeTest = [&Builder](Value *V, QualType VType, 1082 const char *Name) -> Value * { 1083 // Is this value a signed type? 1084 bool VSigned = VType->isSignedIntegerOrEnumerationType(); 1085 llvm::Type *VTy = V->getType(); 1086 if (!VSigned) { 1087 // If the value is unsigned, then it is never negative. 1088 // FIXME: can we encounter non-scalar VTy here? 1089 return llvm::ConstantInt::getFalse(VTy->getContext()); 1090 } 1091 // Get the zero of the same type with which we will be comparing. 1092 llvm::Constant *Zero = llvm::ConstantInt::get(VTy, 0); 1093 // %V.isnegative = icmp slt %V, 0 1094 // I.e is %V *strictly* less than zero, does it have negative value? 1095 return Builder.CreateICmp(llvm::ICmpInst::ICMP_SLT, V, Zero, 1096 llvm::Twine(Name) + "." + V->getName() + 1097 ".negativitycheck"); 1098 }; 1099 1100 // 1. Was the old Value negative? 1101 llvm::Value *SrcIsNegative = EmitIsNegativeTest(Src, SrcType, "src"); 1102 // 2. Is the new Value negative? 1103 llvm::Value *DstIsNegative = EmitIsNegativeTest(Dst, DstType, "dst"); 1104 // 3. Now, was the 'negativity status' preserved during the conversion? 1105 // NOTE: conversion from negative to zero is considered to change the sign. 1106 // (We want to get 'false' when the conversion changed the sign) 1107 // So we should just equality-compare the negativity statuses. 1108 llvm::Value *Check = nullptr; 1109 Check = Builder.CreateICmpEQ(SrcIsNegative, DstIsNegative, "signchangecheck"); 1110 // If the comparison result is 'false', then the conversion changed the sign. 1111 return std::make_pair( 1112 ScalarExprEmitter::ICCK_IntegerSignChange, 1113 std::make_pair(Check, SanitizerKind::ImplicitIntegerSignChange)); 1114 } 1115 1116 void ScalarExprEmitter::EmitIntegerSignChangeCheck(Value *Src, QualType SrcType, 1117 Value *Dst, QualType DstType, 1118 SourceLocation Loc) { 1119 if (!CGF.SanOpts.has(SanitizerKind::ImplicitIntegerSignChange)) 1120 return; 1121 1122 llvm::Type *SrcTy = Src->getType(); 1123 llvm::Type *DstTy = Dst->getType(); 1124 1125 // We only care about int->int conversions here. 1126 // We ignore conversions to/from pointer and/or bool. 1127 if (!PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(SrcType, 1128 DstType)) 1129 return; 1130 1131 bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType(); 1132 bool DstSigned = DstType->isSignedIntegerOrEnumerationType(); 1133 unsigned SrcBits = SrcTy->getScalarSizeInBits(); 1134 unsigned DstBits = DstTy->getScalarSizeInBits(); 1135 1136 // Now, we do not need to emit the check in *all* of the cases. 1137 // We can avoid emitting it in some obvious cases where it would have been 1138 // dropped by the opt passes (instcombine) always anyways. 1139 // If it's a cast between effectively the same type, no check. 1140 // NOTE: this is *not* equivalent to checking the canonical types. 1141 if (SrcSigned == DstSigned && SrcBits == DstBits) 1142 return; 1143 // At least one of the values needs to have signed type. 1144 // If both are unsigned, then obviously, neither of them can be negative. 1145 if (!SrcSigned && !DstSigned) 1146 return; 1147 // If the conversion is to *larger* *signed* type, then no check is needed. 1148 // Because either sign-extension happens (so the sign will remain), 1149 // or zero-extension will happen (the sign bit will be zero.) 1150 if ((DstBits > SrcBits) && DstSigned) 1151 return; 1152 if (CGF.SanOpts.has(SanitizerKind::ImplicitSignedIntegerTruncation) && 1153 (SrcBits > DstBits) && SrcSigned) { 1154 // If the signed integer truncation sanitizer is enabled, 1155 // and this is a truncation from signed type, then no check is needed. 1156 // Because here sign change check is interchangeable with truncation check. 1157 return; 1158 } 1159 // That's it. We can't rule out any more cases with the data we have. 1160 1161 CodeGenFunction::SanitizerScope SanScope(&CGF); 1162 1163 std::pair<ScalarExprEmitter::ImplicitConversionCheckKind, 1164 std::pair<llvm::Value *, SanitizerMask>> 1165 Check; 1166 1167 // Each of these checks needs to return 'false' when an issue was detected. 1168 ImplicitConversionCheckKind CheckKind; 1169 llvm::SmallVector<std::pair<llvm::Value *, SanitizerMask>, 2> Checks; 1170 // So we can 'and' all the checks together, and still get 'false', 1171 // if at least one of the checks detected an issue. 1172 1173 Check = EmitIntegerSignChangeCheckHelper(Src, SrcType, Dst, DstType, Builder); 1174 CheckKind = Check.first; 1175 Checks.emplace_back(Check.second); 1176 1177 if (CGF.SanOpts.has(SanitizerKind::ImplicitSignedIntegerTruncation) && 1178 (SrcBits > DstBits) && !SrcSigned && DstSigned) { 1179 // If the signed integer truncation sanitizer was enabled, 1180 // and we are truncating from larger unsigned type to smaller signed type, 1181 // let's handle the case we skipped in that check. 1182 Check = 1183 EmitIntegerTruncationCheckHelper(Src, SrcType, Dst, DstType, Builder); 1184 CheckKind = ICCK_SignedIntegerTruncationOrSignChange; 1185 Checks.emplace_back(Check.second); 1186 // If the comparison result is 'i1 false', then the truncation was lossy. 1187 } 1188 1189 llvm::Constant *StaticArgs[] = { 1190 CGF.EmitCheckSourceLocation(Loc), CGF.EmitCheckTypeDescriptor(SrcType), 1191 CGF.EmitCheckTypeDescriptor(DstType), 1192 llvm::ConstantInt::get(Builder.getInt8Ty(), CheckKind)}; 1193 // EmitCheck() will 'and' all the checks together. 1194 CGF.EmitCheck(Checks, SanitizerHandler::ImplicitConversion, StaticArgs, 1195 {Src, Dst}); 1196 } 1197 1198 /// Emit a conversion from the specified type to the specified destination type, 1199 /// both of which are LLVM scalar types. 1200 Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType, 1201 QualType DstType, 1202 SourceLocation Loc, 1203 ScalarConversionOpts Opts) { 1204 // All conversions involving fixed point types should be handled by the 1205 // EmitFixedPoint family functions. This is done to prevent bloating up this 1206 // function more, and although fixed point numbers are represented by 1207 // integers, we do not want to follow any logic that assumes they should be 1208 // treated as integers. 1209 // TODO(leonardchan): When necessary, add another if statement checking for 1210 // conversions to fixed point types from other types. 1211 if (SrcType->isFixedPointType()) { 1212 if (DstType->isBooleanType()) 1213 // It is important that we check this before checking if the dest type is 1214 // an integer because booleans are technically integer types. 1215 // We do not need to check the padding bit on unsigned types if unsigned 1216 // padding is enabled because overflow into this bit is undefined 1217 // behavior. 1218 return Builder.CreateIsNotNull(Src, "tobool"); 1219 if (DstType->isFixedPointType() || DstType->isIntegerType()) 1220 return EmitFixedPointConversion(Src, SrcType, DstType, Loc); 1221 1222 llvm_unreachable( 1223 "Unhandled scalar conversion from a fixed point type to another type."); 1224 } else if (DstType->isFixedPointType()) { 1225 if (SrcType->isIntegerType()) 1226 // This also includes converting booleans and enums to fixed point types. 1227 return EmitFixedPointConversion(Src, SrcType, DstType, Loc); 1228 1229 llvm_unreachable( 1230 "Unhandled scalar conversion to a fixed point type from another type."); 1231 } 1232 1233 QualType NoncanonicalSrcType = SrcType; 1234 QualType NoncanonicalDstType = DstType; 1235 1236 SrcType = CGF.getContext().getCanonicalType(SrcType); 1237 DstType = CGF.getContext().getCanonicalType(DstType); 1238 if (SrcType == DstType) return Src; 1239 1240 if (DstType->isVoidType()) return nullptr; 1241 1242 llvm::Value *OrigSrc = Src; 1243 QualType OrigSrcType = SrcType; 1244 llvm::Type *SrcTy = Src->getType(); 1245 1246 // Handle conversions to bool first, they are special: comparisons against 0. 1247 if (DstType->isBooleanType()) 1248 return EmitConversionToBool(Src, SrcType); 1249 1250 llvm::Type *DstTy = ConvertType(DstType); 1251 1252 // Cast from half through float if half isn't a native type. 1253 if (SrcType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) { 1254 // Cast to FP using the intrinsic if the half type itself isn't supported. 1255 if (DstTy->isFloatingPointTy()) { 1256 if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) 1257 return Builder.CreateCall( 1258 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16, DstTy), 1259 Src); 1260 } else { 1261 // Cast to other types through float, using either the intrinsic or FPExt, 1262 // depending on whether the half type itself is supported 1263 // (as opposed to operations on half, available with NativeHalfType). 1264 if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) { 1265 Src = Builder.CreateCall( 1266 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16, 1267 CGF.CGM.FloatTy), 1268 Src); 1269 } else { 1270 Src = Builder.CreateFPExt(Src, CGF.CGM.FloatTy, "conv"); 1271 } 1272 SrcType = CGF.getContext().FloatTy; 1273 SrcTy = CGF.FloatTy; 1274 } 1275 } 1276 1277 // Ignore conversions like int -> uint. 1278 if (SrcTy == DstTy) { 1279 if (Opts.EmitImplicitIntegerSignChangeChecks) 1280 EmitIntegerSignChangeCheck(Src, NoncanonicalSrcType, Src, 1281 NoncanonicalDstType, Loc); 1282 1283 return Src; 1284 } 1285 1286 // Handle pointer conversions next: pointers can only be converted to/from 1287 // other pointers and integers. Check for pointer types in terms of LLVM, as 1288 // some native types (like Obj-C id) may map to a pointer type. 1289 if (auto DstPT = dyn_cast<llvm::PointerType>(DstTy)) { 1290 // The source value may be an integer, or a pointer. 1291 if (isa<llvm::PointerType>(SrcTy)) 1292 return Builder.CreateBitCast(Src, DstTy, "conv"); 1293 1294 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?"); 1295 // First, convert to the correct width so that we control the kind of 1296 // extension. 1297 llvm::Type *MiddleTy = CGF.CGM.getDataLayout().getIntPtrType(DstPT); 1298 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType(); 1299 llvm::Value* IntResult = 1300 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv"); 1301 // Then, cast to pointer. 1302 return Builder.CreateIntToPtr(IntResult, DstTy, "conv"); 1303 } 1304 1305 if (isa<llvm::PointerType>(SrcTy)) { 1306 // Must be an ptr to int cast. 1307 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?"); 1308 return Builder.CreatePtrToInt(Src, DstTy, "conv"); 1309 } 1310 1311 // A scalar can be splatted to an extended vector of the same element type 1312 if (DstType->isExtVectorType() && !SrcType->isVectorType()) { 1313 // Sema should add casts to make sure that the source expression's type is 1314 // the same as the vector's element type (sans qualifiers) 1315 assert(DstType->castAs<ExtVectorType>()->getElementType().getTypePtr() == 1316 SrcType.getTypePtr() && 1317 "Splatted expr doesn't match with vector element type?"); 1318 1319 // Splat the element across to all elements 1320 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements(); 1321 return Builder.CreateVectorSplat(NumElements, Src, "splat"); 1322 } 1323 1324 if (isa<llvm::VectorType>(SrcTy) || isa<llvm::VectorType>(DstTy)) { 1325 // Allow bitcast from vector to integer/fp of the same size. 1326 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits(); 1327 unsigned DstSize = DstTy->getPrimitiveSizeInBits(); 1328 if (SrcSize == DstSize) 1329 return Builder.CreateBitCast(Src, DstTy, "conv"); 1330 1331 // Conversions between vectors of different sizes are not allowed except 1332 // when vectors of half are involved. Operations on storage-only half 1333 // vectors require promoting half vector operands to float vectors and 1334 // truncating the result, which is either an int or float vector, to a 1335 // short or half vector. 1336 1337 // Source and destination are both expected to be vectors. 1338 llvm::Type *SrcElementTy = cast<llvm::VectorType>(SrcTy)->getElementType(); 1339 llvm::Type *DstElementTy = cast<llvm::VectorType>(DstTy)->getElementType(); 1340 (void)DstElementTy; 1341 1342 assert(((SrcElementTy->isIntegerTy() && 1343 DstElementTy->isIntegerTy()) || 1344 (SrcElementTy->isFloatingPointTy() && 1345 DstElementTy->isFloatingPointTy())) && 1346 "unexpected conversion between a floating-point vector and an " 1347 "integer vector"); 1348 1349 // Truncate an i32 vector to an i16 vector. 1350 if (SrcElementTy->isIntegerTy()) 1351 return Builder.CreateIntCast(Src, DstTy, false, "conv"); 1352 1353 // Truncate a float vector to a half vector. 1354 if (SrcSize > DstSize) 1355 return Builder.CreateFPTrunc(Src, DstTy, "conv"); 1356 1357 // Promote a half vector to a float vector. 1358 return Builder.CreateFPExt(Src, DstTy, "conv"); 1359 } 1360 1361 // Finally, we have the arithmetic types: real int/float. 1362 Value *Res = nullptr; 1363 llvm::Type *ResTy = DstTy; 1364 1365 // An overflowing conversion has undefined behavior if either the source type 1366 // or the destination type is a floating-point type. However, we consider the 1367 // range of representable values for all floating-point types to be 1368 // [-inf,+inf], so no overflow can ever happen when the destination type is a 1369 // floating-point type. 1370 if (CGF.SanOpts.has(SanitizerKind::FloatCastOverflow) && 1371 OrigSrcType->isFloatingType()) 1372 EmitFloatConversionCheck(OrigSrc, OrigSrcType, Src, SrcType, DstType, DstTy, 1373 Loc); 1374 1375 // Cast to half through float if half isn't a native type. 1376 if (DstType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) { 1377 // Make sure we cast in a single step if from another FP type. 1378 if (SrcTy->isFloatingPointTy()) { 1379 // Use the intrinsic if the half type itself isn't supported 1380 // (as opposed to operations on half, available with NativeHalfType). 1381 if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) 1382 return Builder.CreateCall( 1383 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16, SrcTy), Src); 1384 // If the half type is supported, just use an fptrunc. 1385 return Builder.CreateFPTrunc(Src, DstTy); 1386 } 1387 DstTy = CGF.FloatTy; 1388 } 1389 1390 if (isa<llvm::IntegerType>(SrcTy)) { 1391 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType(); 1392 if (SrcType->isBooleanType() && Opts.TreatBooleanAsSigned) { 1393 InputSigned = true; 1394 } 1395 if (isa<llvm::IntegerType>(DstTy)) 1396 Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv"); 1397 else if (InputSigned) 1398 Res = Builder.CreateSIToFP(Src, DstTy, "conv"); 1399 else 1400 Res = Builder.CreateUIToFP(Src, DstTy, "conv"); 1401 } else if (isa<llvm::IntegerType>(DstTy)) { 1402 assert(SrcTy->isFloatingPointTy() && "Unknown real conversion"); 1403 if (DstType->isSignedIntegerOrEnumerationType()) 1404 Res = Builder.CreateFPToSI(Src, DstTy, "conv"); 1405 else 1406 Res = Builder.CreateFPToUI(Src, DstTy, "conv"); 1407 } else { 1408 assert(SrcTy->isFloatingPointTy() && DstTy->isFloatingPointTy() && 1409 "Unknown real conversion"); 1410 if (DstTy->getTypeID() < SrcTy->getTypeID()) 1411 Res = Builder.CreateFPTrunc(Src, DstTy, "conv"); 1412 else 1413 Res = Builder.CreateFPExt(Src, DstTy, "conv"); 1414 } 1415 1416 if (DstTy != ResTy) { 1417 if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) { 1418 assert(ResTy->isIntegerTy(16) && "Only half FP requires extra conversion"); 1419 Res = Builder.CreateCall( 1420 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16, CGF.CGM.FloatTy), 1421 Res); 1422 } else { 1423 Res = Builder.CreateFPTrunc(Res, ResTy, "conv"); 1424 } 1425 } 1426 1427 if (Opts.EmitImplicitIntegerTruncationChecks) 1428 EmitIntegerTruncationCheck(Src, NoncanonicalSrcType, Res, 1429 NoncanonicalDstType, Loc); 1430 1431 if (Opts.EmitImplicitIntegerSignChangeChecks) 1432 EmitIntegerSignChangeCheck(Src, NoncanonicalSrcType, Res, 1433 NoncanonicalDstType, Loc); 1434 1435 return Res; 1436 } 1437 1438 Value *ScalarExprEmitter::EmitFixedPointConversion(Value *Src, QualType SrcTy, 1439 QualType DstTy, 1440 SourceLocation Loc) { 1441 FixedPointSemantics SrcFPSema = 1442 CGF.getContext().getFixedPointSemantics(SrcTy); 1443 FixedPointSemantics DstFPSema = 1444 CGF.getContext().getFixedPointSemantics(DstTy); 1445 return EmitFixedPointConversion(Src, SrcFPSema, DstFPSema, Loc, 1446 DstTy->isIntegerType()); 1447 } 1448 1449 Value *ScalarExprEmitter::EmitFixedPointConversion( 1450 Value *Src, FixedPointSemantics &SrcFPSema, FixedPointSemantics &DstFPSema, 1451 SourceLocation Loc, bool DstIsInteger) { 1452 using llvm::APInt; 1453 using llvm::ConstantInt; 1454 using llvm::Value; 1455 1456 unsigned SrcWidth = SrcFPSema.getWidth(); 1457 unsigned DstWidth = DstFPSema.getWidth(); 1458 unsigned SrcScale = SrcFPSema.getScale(); 1459 unsigned DstScale = DstFPSema.getScale(); 1460 bool SrcIsSigned = SrcFPSema.isSigned(); 1461 bool DstIsSigned = DstFPSema.isSigned(); 1462 1463 llvm::Type *DstIntTy = Builder.getIntNTy(DstWidth); 1464 1465 Value *Result = Src; 1466 unsigned ResultWidth = SrcWidth; 1467 1468 // Downscale. 1469 if (DstScale < SrcScale) { 1470 // When converting to integers, we round towards zero. For negative numbers, 1471 // right shifting rounds towards negative infinity. In this case, we can 1472 // just round up before shifting. 1473 if (DstIsInteger && SrcIsSigned) { 1474 Value *Zero = llvm::Constant::getNullValue(Result->getType()); 1475 Value *IsNegative = Builder.CreateICmpSLT(Result, Zero); 1476 Value *LowBits = ConstantInt::get( 1477 CGF.getLLVMContext(), APInt::getLowBitsSet(ResultWidth, SrcScale)); 1478 Value *Rounded = Builder.CreateAdd(Result, LowBits); 1479 Result = Builder.CreateSelect(IsNegative, Rounded, Result); 1480 } 1481 1482 Result = SrcIsSigned 1483 ? Builder.CreateAShr(Result, SrcScale - DstScale, "downscale") 1484 : Builder.CreateLShr(Result, SrcScale - DstScale, "downscale"); 1485 } 1486 1487 if (!DstFPSema.isSaturated()) { 1488 // Resize. 1489 Result = Builder.CreateIntCast(Result, DstIntTy, SrcIsSigned, "resize"); 1490 1491 // Upscale. 1492 if (DstScale > SrcScale) 1493 Result = Builder.CreateShl(Result, DstScale - SrcScale, "upscale"); 1494 } else { 1495 // Adjust the number of fractional bits. 1496 if (DstScale > SrcScale) { 1497 // Compare to DstWidth to prevent resizing twice. 1498 ResultWidth = std::max(SrcWidth + DstScale - SrcScale, DstWidth); 1499 llvm::Type *UpscaledTy = Builder.getIntNTy(ResultWidth); 1500 Result = Builder.CreateIntCast(Result, UpscaledTy, SrcIsSigned, "resize"); 1501 Result = Builder.CreateShl(Result, DstScale - SrcScale, "upscale"); 1502 } 1503 1504 // Handle saturation. 1505 bool LessIntBits = DstFPSema.getIntegralBits() < SrcFPSema.getIntegralBits(); 1506 if (LessIntBits) { 1507 Value *Max = ConstantInt::get( 1508 CGF.getLLVMContext(), 1509 APFixedPoint::getMax(DstFPSema).getValue().extOrTrunc(ResultWidth)); 1510 Value *TooHigh = SrcIsSigned ? Builder.CreateICmpSGT(Result, Max) 1511 : Builder.CreateICmpUGT(Result, Max); 1512 Result = Builder.CreateSelect(TooHigh, Max, Result, "satmax"); 1513 } 1514 // Cannot overflow min to dest type if src is unsigned since all fixed 1515 // point types can cover the unsigned min of 0. 1516 if (SrcIsSigned && (LessIntBits || !DstIsSigned)) { 1517 Value *Min = ConstantInt::get( 1518 CGF.getLLVMContext(), 1519 APFixedPoint::getMin(DstFPSema).getValue().extOrTrunc(ResultWidth)); 1520 Value *TooLow = Builder.CreateICmpSLT(Result, Min); 1521 Result = Builder.CreateSelect(TooLow, Min, Result, "satmin"); 1522 } 1523 1524 // Resize the integer part to get the final destination size. 1525 if (ResultWidth != DstWidth) 1526 Result = Builder.CreateIntCast(Result, DstIntTy, SrcIsSigned, "resize"); 1527 } 1528 return Result; 1529 } 1530 1531 /// Emit a conversion from the specified complex type to the specified 1532 /// destination type, where the destination type is an LLVM scalar type. 1533 Value *ScalarExprEmitter::EmitComplexToScalarConversion( 1534 CodeGenFunction::ComplexPairTy Src, QualType SrcTy, QualType DstTy, 1535 SourceLocation Loc) { 1536 // Get the source element type. 1537 SrcTy = SrcTy->castAs<ComplexType>()->getElementType(); 1538 1539 // Handle conversions to bool first, they are special: comparisons against 0. 1540 if (DstTy->isBooleanType()) { 1541 // Complex != 0 -> (Real != 0) | (Imag != 0) 1542 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy, Loc); 1543 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy, Loc); 1544 return Builder.CreateOr(Src.first, Src.second, "tobool"); 1545 } 1546 1547 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type, 1548 // the imaginary part of the complex value is discarded and the value of the 1549 // real part is converted according to the conversion rules for the 1550 // corresponding real type. 1551 return EmitScalarConversion(Src.first, SrcTy, DstTy, Loc); 1552 } 1553 1554 Value *ScalarExprEmitter::EmitNullValue(QualType Ty) { 1555 return CGF.EmitFromMemory(CGF.CGM.EmitNullConstant(Ty), Ty); 1556 } 1557 1558 /// Emit a sanitization check for the given "binary" operation (which 1559 /// might actually be a unary increment which has been lowered to a binary 1560 /// operation). The check passes if all values in \p Checks (which are \c i1), 1561 /// are \c true. 1562 void ScalarExprEmitter::EmitBinOpCheck( 1563 ArrayRef<std::pair<Value *, SanitizerMask>> Checks, const BinOpInfo &Info) { 1564 assert(CGF.IsSanitizerScope); 1565 SanitizerHandler Check; 1566 SmallVector<llvm::Constant *, 4> StaticData; 1567 SmallVector<llvm::Value *, 2> DynamicData; 1568 1569 BinaryOperatorKind Opcode = Info.Opcode; 1570 if (BinaryOperator::isCompoundAssignmentOp(Opcode)) 1571 Opcode = BinaryOperator::getOpForCompoundAssignment(Opcode); 1572 1573 StaticData.push_back(CGF.EmitCheckSourceLocation(Info.E->getExprLoc())); 1574 const UnaryOperator *UO = dyn_cast<UnaryOperator>(Info.E); 1575 if (UO && UO->getOpcode() == UO_Minus) { 1576 Check = SanitizerHandler::NegateOverflow; 1577 StaticData.push_back(CGF.EmitCheckTypeDescriptor(UO->getType())); 1578 DynamicData.push_back(Info.RHS); 1579 } else { 1580 if (BinaryOperator::isShiftOp(Opcode)) { 1581 // Shift LHS negative or too large, or RHS out of bounds. 1582 Check = SanitizerHandler::ShiftOutOfBounds; 1583 const BinaryOperator *BO = cast<BinaryOperator>(Info.E); 1584 StaticData.push_back( 1585 CGF.EmitCheckTypeDescriptor(BO->getLHS()->getType())); 1586 StaticData.push_back( 1587 CGF.EmitCheckTypeDescriptor(BO->getRHS()->getType())); 1588 } else if (Opcode == BO_Div || Opcode == BO_Rem) { 1589 // Divide or modulo by zero, or signed overflow (eg INT_MAX / -1). 1590 Check = SanitizerHandler::DivremOverflow; 1591 StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.Ty)); 1592 } else { 1593 // Arithmetic overflow (+, -, *). 1594 switch (Opcode) { 1595 case BO_Add: Check = SanitizerHandler::AddOverflow; break; 1596 case BO_Sub: Check = SanitizerHandler::SubOverflow; break; 1597 case BO_Mul: Check = SanitizerHandler::MulOverflow; break; 1598 default: llvm_unreachable("unexpected opcode for bin op check"); 1599 } 1600 StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.Ty)); 1601 } 1602 DynamicData.push_back(Info.LHS); 1603 DynamicData.push_back(Info.RHS); 1604 } 1605 1606 CGF.EmitCheck(Checks, Check, StaticData, DynamicData); 1607 } 1608 1609 //===----------------------------------------------------------------------===// 1610 // Visitor Methods 1611 //===----------------------------------------------------------------------===// 1612 1613 Value *ScalarExprEmitter::VisitExpr(Expr *E) { 1614 CGF.ErrorUnsupported(E, "scalar expression"); 1615 if (E->getType()->isVoidType()) 1616 return nullptr; 1617 return llvm::UndefValue::get(CGF.ConvertType(E->getType())); 1618 } 1619 1620 Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) { 1621 // Vector Mask Case 1622 if (E->getNumSubExprs() == 2) { 1623 Value *LHS = CGF.EmitScalarExpr(E->getExpr(0)); 1624 Value *RHS = CGF.EmitScalarExpr(E->getExpr(1)); 1625 Value *Mask; 1626 1627 llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType()); 1628 unsigned LHSElts = LTy->getNumElements(); 1629 1630 Mask = RHS; 1631 1632 llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType()); 1633 1634 // Mask off the high bits of each shuffle index. 1635 Value *MaskBits = 1636 llvm::ConstantInt::get(MTy, llvm::NextPowerOf2(LHSElts - 1) - 1); 1637 Mask = Builder.CreateAnd(Mask, MaskBits, "mask"); 1638 1639 // newv = undef 1640 // mask = mask & maskbits 1641 // for each elt 1642 // n = extract mask i 1643 // x = extract val n 1644 // newv = insert newv, x, i 1645 auto *RTy = llvm::FixedVectorType::get(LTy->getElementType(), 1646 MTy->getNumElements()); 1647 Value* NewV = llvm::UndefValue::get(RTy); 1648 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) { 1649 Value *IIndx = llvm::ConstantInt::get(CGF.SizeTy, i); 1650 Value *Indx = Builder.CreateExtractElement(Mask, IIndx, "shuf_idx"); 1651 1652 Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt"); 1653 NewV = Builder.CreateInsertElement(NewV, VExt, IIndx, "shuf_ins"); 1654 } 1655 return NewV; 1656 } 1657 1658 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0)); 1659 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1)); 1660 1661 SmallVector<int, 32> Indices; 1662 for (unsigned i = 2; i < E->getNumSubExprs(); ++i) { 1663 llvm::APSInt Idx = E->getShuffleMaskIdx(CGF.getContext(), i-2); 1664 // Check for -1 and output it as undef in the IR. 1665 if (Idx.isSigned() && Idx.isAllOnesValue()) 1666 Indices.push_back(-1); 1667 else 1668 Indices.push_back(Idx.getZExtValue()); 1669 } 1670 1671 return Builder.CreateShuffleVector(V1, V2, Indices, "shuffle"); 1672 } 1673 1674 Value *ScalarExprEmitter::VisitConvertVectorExpr(ConvertVectorExpr *E) { 1675 QualType SrcType = E->getSrcExpr()->getType(), 1676 DstType = E->getType(); 1677 1678 Value *Src = CGF.EmitScalarExpr(E->getSrcExpr()); 1679 1680 SrcType = CGF.getContext().getCanonicalType(SrcType); 1681 DstType = CGF.getContext().getCanonicalType(DstType); 1682 if (SrcType == DstType) return Src; 1683 1684 assert(SrcType->isVectorType() && 1685 "ConvertVector source type must be a vector"); 1686 assert(DstType->isVectorType() && 1687 "ConvertVector destination type must be a vector"); 1688 1689 llvm::Type *SrcTy = Src->getType(); 1690 llvm::Type *DstTy = ConvertType(DstType); 1691 1692 // Ignore conversions like int -> uint. 1693 if (SrcTy == DstTy) 1694 return Src; 1695 1696 QualType SrcEltType = SrcType->castAs<VectorType>()->getElementType(), 1697 DstEltType = DstType->castAs<VectorType>()->getElementType(); 1698 1699 assert(SrcTy->isVectorTy() && 1700 "ConvertVector source IR type must be a vector"); 1701 assert(DstTy->isVectorTy() && 1702 "ConvertVector destination IR type must be a vector"); 1703 1704 llvm::Type *SrcEltTy = cast<llvm::VectorType>(SrcTy)->getElementType(), 1705 *DstEltTy = cast<llvm::VectorType>(DstTy)->getElementType(); 1706 1707 if (DstEltType->isBooleanType()) { 1708 assert((SrcEltTy->isFloatingPointTy() || 1709 isa<llvm::IntegerType>(SrcEltTy)) && "Unknown boolean conversion"); 1710 1711 llvm::Value *Zero = llvm::Constant::getNullValue(SrcTy); 1712 if (SrcEltTy->isFloatingPointTy()) { 1713 return Builder.CreateFCmpUNE(Src, Zero, "tobool"); 1714 } else { 1715 return Builder.CreateICmpNE(Src, Zero, "tobool"); 1716 } 1717 } 1718 1719 // We have the arithmetic types: real int/float. 1720 Value *Res = nullptr; 1721 1722 if (isa<llvm::IntegerType>(SrcEltTy)) { 1723 bool InputSigned = SrcEltType->isSignedIntegerOrEnumerationType(); 1724 if (isa<llvm::IntegerType>(DstEltTy)) 1725 Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv"); 1726 else if (InputSigned) 1727 Res = Builder.CreateSIToFP(Src, DstTy, "conv"); 1728 else 1729 Res = Builder.CreateUIToFP(Src, DstTy, "conv"); 1730 } else if (isa<llvm::IntegerType>(DstEltTy)) { 1731 assert(SrcEltTy->isFloatingPointTy() && "Unknown real conversion"); 1732 if (DstEltType->isSignedIntegerOrEnumerationType()) 1733 Res = Builder.CreateFPToSI(Src, DstTy, "conv"); 1734 else 1735 Res = Builder.CreateFPToUI(Src, DstTy, "conv"); 1736 } else { 1737 assert(SrcEltTy->isFloatingPointTy() && DstEltTy->isFloatingPointTy() && 1738 "Unknown real conversion"); 1739 if (DstEltTy->getTypeID() < SrcEltTy->getTypeID()) 1740 Res = Builder.CreateFPTrunc(Src, DstTy, "conv"); 1741 else 1742 Res = Builder.CreateFPExt(Src, DstTy, "conv"); 1743 } 1744 1745 return Res; 1746 } 1747 1748 Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) { 1749 if (CodeGenFunction::ConstantEmission Constant = CGF.tryEmitAsConstant(E)) { 1750 CGF.EmitIgnoredExpr(E->getBase()); 1751 return CGF.emitScalarConstant(Constant, E); 1752 } else { 1753 Expr::EvalResult Result; 1754 if (E->EvaluateAsInt(Result, CGF.getContext(), Expr::SE_AllowSideEffects)) { 1755 llvm::APSInt Value = Result.Val.getInt(); 1756 CGF.EmitIgnoredExpr(E->getBase()); 1757 return Builder.getInt(Value); 1758 } 1759 } 1760 1761 return EmitLoadOfLValue(E); 1762 } 1763 1764 Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) { 1765 TestAndClearIgnoreResultAssign(); 1766 1767 // Emit subscript expressions in rvalue context's. For most cases, this just 1768 // loads the lvalue formed by the subscript expr. However, we have to be 1769 // careful, because the base of a vector subscript is occasionally an rvalue, 1770 // so we can't get it as an lvalue. 1771 if (!E->getBase()->getType()->isVectorType()) 1772 return EmitLoadOfLValue(E); 1773 1774 // Handle the vector case. The base must be a vector, the index must be an 1775 // integer value. 1776 Value *Base = Visit(E->getBase()); 1777 Value *Idx = Visit(E->getIdx()); 1778 QualType IdxTy = E->getIdx()->getType(); 1779 1780 if (CGF.SanOpts.has(SanitizerKind::ArrayBounds)) 1781 CGF.EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, /*Accessed*/true); 1782 1783 return Builder.CreateExtractElement(Base, Idx, "vecext"); 1784 } 1785 1786 Value *ScalarExprEmitter::VisitMatrixSubscriptExpr(MatrixSubscriptExpr *E) { 1787 TestAndClearIgnoreResultAssign(); 1788 1789 // Handle the vector case. The base must be a vector, the index must be an 1790 // integer value. 1791 Value *RowIdx = Visit(E->getRowIdx()); 1792 Value *ColumnIdx = Visit(E->getColumnIdx()); 1793 Value *Matrix = Visit(E->getBase()); 1794 1795 // TODO: Should we emit bounds checks with SanitizerKind::ArrayBounds? 1796 llvm::MatrixBuilder<CGBuilderTy> MB(Builder); 1797 return MB.CreateExtractElement( 1798 Matrix, RowIdx, ColumnIdx, 1799 E->getBase()->getType()->getAs<ConstantMatrixType>()->getNumRows()); 1800 } 1801 1802 static int getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx, 1803 unsigned Off) { 1804 int MV = SVI->getMaskValue(Idx); 1805 if (MV == -1) 1806 return -1; 1807 return Off + MV; 1808 } 1809 1810 static int getAsInt32(llvm::ConstantInt *C, llvm::Type *I32Ty) { 1811 assert(llvm::ConstantInt::isValueValidForType(I32Ty, C->getZExtValue()) && 1812 "Index operand too large for shufflevector mask!"); 1813 return C->getZExtValue(); 1814 } 1815 1816 Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) { 1817 bool Ignore = TestAndClearIgnoreResultAssign(); 1818 (void)Ignore; 1819 assert (Ignore == false && "init list ignored"); 1820 unsigned NumInitElements = E->getNumInits(); 1821 1822 if (E->hadArrayRangeDesignator()) 1823 CGF.ErrorUnsupported(E, "GNU array range designator extension"); 1824 1825 llvm::VectorType *VType = 1826 dyn_cast<llvm::VectorType>(ConvertType(E->getType())); 1827 1828 if (!VType) { 1829 if (NumInitElements == 0) { 1830 // C++11 value-initialization for the scalar. 1831 return EmitNullValue(E->getType()); 1832 } 1833 // We have a scalar in braces. Just use the first element. 1834 return Visit(E->getInit(0)); 1835 } 1836 1837 unsigned ResElts = VType->getNumElements(); 1838 1839 // Loop over initializers collecting the Value for each, and remembering 1840 // whether the source was swizzle (ExtVectorElementExpr). This will allow 1841 // us to fold the shuffle for the swizzle into the shuffle for the vector 1842 // initializer, since LLVM optimizers generally do not want to touch 1843 // shuffles. 1844 unsigned CurIdx = 0; 1845 bool VIsUndefShuffle = false; 1846 llvm::Value *V = llvm::UndefValue::get(VType); 1847 for (unsigned i = 0; i != NumInitElements; ++i) { 1848 Expr *IE = E->getInit(i); 1849 Value *Init = Visit(IE); 1850 SmallVector<int, 16> Args; 1851 1852 llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType()); 1853 1854 // Handle scalar elements. If the scalar initializer is actually one 1855 // element of a different vector of the same width, use shuffle instead of 1856 // extract+insert. 1857 if (!VVT) { 1858 if (isa<ExtVectorElementExpr>(IE)) { 1859 llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init); 1860 1861 if (EI->getVectorOperandType()->getNumElements() == ResElts) { 1862 llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand()); 1863 Value *LHS = nullptr, *RHS = nullptr; 1864 if (CurIdx == 0) { 1865 // insert into undef -> shuffle (src, undef) 1866 // shufflemask must use an i32 1867 Args.push_back(getAsInt32(C, CGF.Int32Ty)); 1868 Args.resize(ResElts, -1); 1869 1870 LHS = EI->getVectorOperand(); 1871 RHS = V; 1872 VIsUndefShuffle = true; 1873 } else if (VIsUndefShuffle) { 1874 // insert into undefshuffle && size match -> shuffle (v, src) 1875 llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V); 1876 for (unsigned j = 0; j != CurIdx; ++j) 1877 Args.push_back(getMaskElt(SVV, j, 0)); 1878 Args.push_back(ResElts + C->getZExtValue()); 1879 Args.resize(ResElts, -1); 1880 1881 LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0); 1882 RHS = EI->getVectorOperand(); 1883 VIsUndefShuffle = false; 1884 } 1885 if (!Args.empty()) { 1886 V = Builder.CreateShuffleVector(LHS, RHS, Args); 1887 ++CurIdx; 1888 continue; 1889 } 1890 } 1891 } 1892 V = Builder.CreateInsertElement(V, Init, Builder.getInt32(CurIdx), 1893 "vecinit"); 1894 VIsUndefShuffle = false; 1895 ++CurIdx; 1896 continue; 1897 } 1898 1899 unsigned InitElts = VVT->getNumElements(); 1900 1901 // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's 1902 // input is the same width as the vector being constructed, generate an 1903 // optimized shuffle of the swizzle input into the result. 1904 unsigned Offset = (CurIdx == 0) ? 0 : ResElts; 1905 if (isa<ExtVectorElementExpr>(IE)) { 1906 llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init); 1907 Value *SVOp = SVI->getOperand(0); 1908 llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType()); 1909 1910 if (OpTy->getNumElements() == ResElts) { 1911 for (unsigned j = 0; j != CurIdx; ++j) { 1912 // If the current vector initializer is a shuffle with undef, merge 1913 // this shuffle directly into it. 1914 if (VIsUndefShuffle) { 1915 Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0)); 1916 } else { 1917 Args.push_back(j); 1918 } 1919 } 1920 for (unsigned j = 0, je = InitElts; j != je; ++j) 1921 Args.push_back(getMaskElt(SVI, j, Offset)); 1922 Args.resize(ResElts, -1); 1923 1924 if (VIsUndefShuffle) 1925 V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0); 1926 1927 Init = SVOp; 1928 } 1929 } 1930 1931 // Extend init to result vector length, and then shuffle its contribution 1932 // to the vector initializer into V. 1933 if (Args.empty()) { 1934 for (unsigned j = 0; j != InitElts; ++j) 1935 Args.push_back(j); 1936 Args.resize(ResElts, -1); 1937 Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT), Args, 1938 "vext"); 1939 1940 Args.clear(); 1941 for (unsigned j = 0; j != CurIdx; ++j) 1942 Args.push_back(j); 1943 for (unsigned j = 0; j != InitElts; ++j) 1944 Args.push_back(j + Offset); 1945 Args.resize(ResElts, -1); 1946 } 1947 1948 // If V is undef, make sure it ends up on the RHS of the shuffle to aid 1949 // merging subsequent shuffles into this one. 1950 if (CurIdx == 0) 1951 std::swap(V, Init); 1952 V = Builder.CreateShuffleVector(V, Init, Args, "vecinit"); 1953 VIsUndefShuffle = isa<llvm::UndefValue>(Init); 1954 CurIdx += InitElts; 1955 } 1956 1957 // FIXME: evaluate codegen vs. shuffling against constant null vector. 1958 // Emit remaining default initializers. 1959 llvm::Type *EltTy = VType->getElementType(); 1960 1961 // Emit remaining default initializers 1962 for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) { 1963 Value *Idx = Builder.getInt32(CurIdx); 1964 llvm::Value *Init = llvm::Constant::getNullValue(EltTy); 1965 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit"); 1966 } 1967 return V; 1968 } 1969 1970 bool CodeGenFunction::ShouldNullCheckClassCastValue(const CastExpr *CE) { 1971 const Expr *E = CE->getSubExpr(); 1972 1973 if (CE->getCastKind() == CK_UncheckedDerivedToBase) 1974 return false; 1975 1976 if (isa<CXXThisExpr>(E->IgnoreParens())) { 1977 // We always assume that 'this' is never null. 1978 return false; 1979 } 1980 1981 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) { 1982 // And that glvalue casts are never null. 1983 if (ICE->getValueKind() != VK_RValue) 1984 return false; 1985 } 1986 1987 return true; 1988 } 1989 1990 // VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts 1991 // have to handle a more broad range of conversions than explicit casts, as they 1992 // handle things like function to ptr-to-function decay etc. 1993 Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) { 1994 Expr *E = CE->getSubExpr(); 1995 QualType DestTy = CE->getType(); 1996 CastKind Kind = CE->getCastKind(); 1997 1998 // These cases are generally not written to ignore the result of 1999 // evaluating their sub-expressions, so we clear this now. 2000 bool Ignored = TestAndClearIgnoreResultAssign(); 2001 2002 // Since almost all cast kinds apply to scalars, this switch doesn't have 2003 // a default case, so the compiler will warn on a missing case. The cases 2004 // are in the same order as in the CastKind enum. 2005 switch (Kind) { 2006 case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!"); 2007 case CK_BuiltinFnToFnPtr: 2008 llvm_unreachable("builtin functions are handled elsewhere"); 2009 2010 case CK_LValueBitCast: 2011 case CK_ObjCObjectLValueCast: { 2012 Address Addr = EmitLValue(E).getAddress(CGF); 2013 Addr = Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(DestTy)); 2014 LValue LV = CGF.MakeAddrLValue(Addr, DestTy); 2015 return EmitLoadOfLValue(LV, CE->getExprLoc()); 2016 } 2017 2018 case CK_LValueToRValueBitCast: { 2019 LValue SourceLVal = CGF.EmitLValue(E); 2020 Address Addr = Builder.CreateElementBitCast(SourceLVal.getAddress(CGF), 2021 CGF.ConvertTypeForMem(DestTy)); 2022 LValue DestLV = CGF.MakeAddrLValue(Addr, DestTy); 2023 DestLV.setTBAAInfo(TBAAAccessInfo::getMayAliasInfo()); 2024 return EmitLoadOfLValue(DestLV, CE->getExprLoc()); 2025 } 2026 2027 case CK_CPointerToObjCPointerCast: 2028 case CK_BlockPointerToObjCPointerCast: 2029 case CK_AnyPointerToBlockPointerCast: 2030 case CK_BitCast: { 2031 Value *Src = Visit(const_cast<Expr*>(E)); 2032 llvm::Type *SrcTy = Src->getType(); 2033 llvm::Type *DstTy = ConvertType(DestTy); 2034 if (SrcTy->isPtrOrPtrVectorTy() && DstTy->isPtrOrPtrVectorTy() && 2035 SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace()) { 2036 llvm_unreachable("wrong cast for pointers in different address spaces" 2037 "(must be an address space cast)!"); 2038 } 2039 2040 if (CGF.SanOpts.has(SanitizerKind::CFIUnrelatedCast)) { 2041 if (auto PT = DestTy->getAs<PointerType>()) 2042 CGF.EmitVTablePtrCheckForCast(PT->getPointeeType(), Src, 2043 /*MayBeNull=*/true, 2044 CodeGenFunction::CFITCK_UnrelatedCast, 2045 CE->getBeginLoc()); 2046 } 2047 2048 if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) { 2049 const QualType SrcType = E->getType(); 2050 2051 if (SrcType.mayBeNotDynamicClass() && DestTy.mayBeDynamicClass()) { 2052 // Casting to pointer that could carry dynamic information (provided by 2053 // invariant.group) requires launder. 2054 Src = Builder.CreateLaunderInvariantGroup(Src); 2055 } else if (SrcType.mayBeDynamicClass() && DestTy.mayBeNotDynamicClass()) { 2056 // Casting to pointer that does not carry dynamic information (provided 2057 // by invariant.group) requires stripping it. Note that we don't do it 2058 // if the source could not be dynamic type and destination could be 2059 // dynamic because dynamic information is already laundered. It is 2060 // because launder(strip(src)) == launder(src), so there is no need to 2061 // add extra strip before launder. 2062 Src = Builder.CreateStripInvariantGroup(Src); 2063 } 2064 } 2065 2066 // Update heapallocsite metadata when there is an explicit pointer cast. 2067 if (auto *CI = dyn_cast<llvm::CallBase>(Src)) { 2068 if (CI->getMetadata("heapallocsite") && isa<ExplicitCastExpr>(CE)) { 2069 QualType PointeeType = DestTy->getPointeeType(); 2070 if (!PointeeType.isNull()) 2071 CGF.getDebugInfo()->addHeapAllocSiteMetadata(CI, PointeeType, 2072 CE->getExprLoc()); 2073 } 2074 } 2075 2076 return Builder.CreateBitCast(Src, DstTy); 2077 } 2078 case CK_AddressSpaceConversion: { 2079 Expr::EvalResult Result; 2080 if (E->EvaluateAsRValue(Result, CGF.getContext()) && 2081 Result.Val.isNullPointer()) { 2082 // If E has side effect, it is emitted even if its final result is a 2083 // null pointer. In that case, a DCE pass should be able to 2084 // eliminate the useless instructions emitted during translating E. 2085 if (Result.HasSideEffects) 2086 Visit(E); 2087 return CGF.CGM.getNullPointer(cast<llvm::PointerType>( 2088 ConvertType(DestTy)), DestTy); 2089 } 2090 // Since target may map different address spaces in AST to the same address 2091 // space, an address space conversion may end up as a bitcast. 2092 return CGF.CGM.getTargetCodeGenInfo().performAddrSpaceCast( 2093 CGF, Visit(E), E->getType()->getPointeeType().getAddressSpace(), 2094 DestTy->getPointeeType().getAddressSpace(), ConvertType(DestTy)); 2095 } 2096 case CK_AtomicToNonAtomic: 2097 case CK_NonAtomicToAtomic: 2098 case CK_NoOp: 2099 case CK_UserDefinedConversion: 2100 return Visit(const_cast<Expr*>(E)); 2101 2102 case CK_BaseToDerived: { 2103 const CXXRecordDecl *DerivedClassDecl = DestTy->getPointeeCXXRecordDecl(); 2104 assert(DerivedClassDecl && "BaseToDerived arg isn't a C++ object pointer!"); 2105 2106 Address Base = CGF.EmitPointerWithAlignment(E); 2107 Address Derived = 2108 CGF.GetAddressOfDerivedClass(Base, DerivedClassDecl, 2109 CE->path_begin(), CE->path_end(), 2110 CGF.ShouldNullCheckClassCastValue(CE)); 2111 2112 // C++11 [expr.static.cast]p11: Behavior is undefined if a downcast is 2113 // performed and the object is not of the derived type. 2114 if (CGF.sanitizePerformTypeCheck()) 2115 CGF.EmitTypeCheck(CodeGenFunction::TCK_DowncastPointer, CE->getExprLoc(), 2116 Derived.getPointer(), DestTy->getPointeeType()); 2117 2118 if (CGF.SanOpts.has(SanitizerKind::CFIDerivedCast)) 2119 CGF.EmitVTablePtrCheckForCast( 2120 DestTy->getPointeeType(), Derived.getPointer(), 2121 /*MayBeNull=*/true, CodeGenFunction::CFITCK_DerivedCast, 2122 CE->getBeginLoc()); 2123 2124 return Derived.getPointer(); 2125 } 2126 case CK_UncheckedDerivedToBase: 2127 case CK_DerivedToBase: { 2128 // The EmitPointerWithAlignment path does this fine; just discard 2129 // the alignment. 2130 return CGF.EmitPointerWithAlignment(CE).getPointer(); 2131 } 2132 2133 case CK_Dynamic: { 2134 Address V = CGF.EmitPointerWithAlignment(E); 2135 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE); 2136 return CGF.EmitDynamicCast(V, DCE); 2137 } 2138 2139 case CK_ArrayToPointerDecay: 2140 return CGF.EmitArrayToPointerDecay(E).getPointer(); 2141 case CK_FunctionToPointerDecay: 2142 return EmitLValue(E).getPointer(CGF); 2143 2144 case CK_NullToPointer: 2145 if (MustVisitNullValue(E)) 2146 CGF.EmitIgnoredExpr(E); 2147 2148 return CGF.CGM.getNullPointer(cast<llvm::PointerType>(ConvertType(DestTy)), 2149 DestTy); 2150 2151 case CK_NullToMemberPointer: { 2152 if (MustVisitNullValue(E)) 2153 CGF.EmitIgnoredExpr(E); 2154 2155 const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>(); 2156 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT); 2157 } 2158 2159 case CK_ReinterpretMemberPointer: 2160 case CK_BaseToDerivedMemberPointer: 2161 case CK_DerivedToBaseMemberPointer: { 2162 Value *Src = Visit(E); 2163 2164 // Note that the AST doesn't distinguish between checked and 2165 // unchecked member pointer conversions, so we always have to 2166 // implement checked conversions here. This is inefficient when 2167 // actual control flow may be required in order to perform the 2168 // check, which it is for data member pointers (but not member 2169 // function pointers on Itanium and ARM). 2170 return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src); 2171 } 2172 2173 case CK_ARCProduceObject: 2174 return CGF.EmitARCRetainScalarExpr(E); 2175 case CK_ARCConsumeObject: 2176 return CGF.EmitObjCConsumeObject(E->getType(), Visit(E)); 2177 case CK_ARCReclaimReturnedObject: 2178 return CGF.EmitARCReclaimReturnedObject(E, /*allowUnsafe*/ Ignored); 2179 case CK_ARCExtendBlockObject: 2180 return CGF.EmitARCExtendBlockObject(E); 2181 2182 case CK_CopyAndAutoreleaseBlockObject: 2183 return CGF.EmitBlockCopyAndAutorelease(Visit(E), E->getType()); 2184 2185 case CK_FloatingRealToComplex: 2186 case CK_FloatingComplexCast: 2187 case CK_IntegralRealToComplex: 2188 case CK_IntegralComplexCast: 2189 case CK_IntegralComplexToFloatingComplex: 2190 case CK_FloatingComplexToIntegralComplex: 2191 case CK_ConstructorConversion: 2192 case CK_ToUnion: 2193 llvm_unreachable("scalar cast to non-scalar value"); 2194 2195 case CK_LValueToRValue: 2196 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy)); 2197 assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!"); 2198 return Visit(const_cast<Expr*>(E)); 2199 2200 case CK_IntegralToPointer: { 2201 Value *Src = Visit(const_cast<Expr*>(E)); 2202 2203 // First, convert to the correct width so that we control the kind of 2204 // extension. 2205 auto DestLLVMTy = ConvertType(DestTy); 2206 llvm::Type *MiddleTy = CGF.CGM.getDataLayout().getIntPtrType(DestLLVMTy); 2207 bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType(); 2208 llvm::Value* IntResult = 2209 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv"); 2210 2211 auto *IntToPtr = Builder.CreateIntToPtr(IntResult, DestLLVMTy); 2212 2213 if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) { 2214 // Going from integer to pointer that could be dynamic requires reloading 2215 // dynamic information from invariant.group. 2216 if (DestTy.mayBeDynamicClass()) 2217 IntToPtr = Builder.CreateLaunderInvariantGroup(IntToPtr); 2218 } 2219 return IntToPtr; 2220 } 2221 case CK_PointerToIntegral: { 2222 assert(!DestTy->isBooleanType() && "bool should use PointerToBool"); 2223 auto *PtrExpr = Visit(E); 2224 2225 if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) { 2226 const QualType SrcType = E->getType(); 2227 2228 // Casting to integer requires stripping dynamic information as it does 2229 // not carries it. 2230 if (SrcType.mayBeDynamicClass()) 2231 PtrExpr = Builder.CreateStripInvariantGroup(PtrExpr); 2232 } 2233 2234 return Builder.CreatePtrToInt(PtrExpr, ConvertType(DestTy)); 2235 } 2236 case CK_ToVoid: { 2237 CGF.EmitIgnoredExpr(E); 2238 return nullptr; 2239 } 2240 case CK_VectorSplat: { 2241 llvm::Type *DstTy = ConvertType(DestTy); 2242 Value *Elt = Visit(const_cast<Expr*>(E)); 2243 // Splat the element across to all elements 2244 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements(); 2245 return Builder.CreateVectorSplat(NumElements, Elt, "splat"); 2246 } 2247 2248 case CK_FixedPointCast: 2249 return EmitScalarConversion(Visit(E), E->getType(), DestTy, 2250 CE->getExprLoc()); 2251 2252 case CK_FixedPointToBoolean: 2253 assert(E->getType()->isFixedPointType() && 2254 "Expected src type to be fixed point type"); 2255 assert(DestTy->isBooleanType() && "Expected dest type to be boolean type"); 2256 return EmitScalarConversion(Visit(E), E->getType(), DestTy, 2257 CE->getExprLoc()); 2258 2259 case CK_FixedPointToIntegral: 2260 assert(E->getType()->isFixedPointType() && 2261 "Expected src type to be fixed point type"); 2262 assert(DestTy->isIntegerType() && "Expected dest type to be an integer"); 2263 return EmitScalarConversion(Visit(E), E->getType(), DestTy, 2264 CE->getExprLoc()); 2265 2266 case CK_IntegralToFixedPoint: 2267 assert(E->getType()->isIntegerType() && 2268 "Expected src type to be an integer"); 2269 assert(DestTy->isFixedPointType() && 2270 "Expected dest type to be fixed point type"); 2271 return EmitScalarConversion(Visit(E), E->getType(), DestTy, 2272 CE->getExprLoc()); 2273 2274 case CK_IntegralCast: { 2275 ScalarConversionOpts Opts; 2276 if (auto *ICE = dyn_cast<ImplicitCastExpr>(CE)) { 2277 if (!ICE->isPartOfExplicitCast()) 2278 Opts = ScalarConversionOpts(CGF.SanOpts); 2279 } 2280 return EmitScalarConversion(Visit(E), E->getType(), DestTy, 2281 CE->getExprLoc(), Opts); 2282 } 2283 case CK_IntegralToFloating: 2284 case CK_FloatingToIntegral: 2285 case CK_FloatingCast: 2286 return EmitScalarConversion(Visit(E), E->getType(), DestTy, 2287 CE->getExprLoc()); 2288 case CK_BooleanToSignedIntegral: { 2289 ScalarConversionOpts Opts; 2290 Opts.TreatBooleanAsSigned = true; 2291 return EmitScalarConversion(Visit(E), E->getType(), DestTy, 2292 CE->getExprLoc(), Opts); 2293 } 2294 case CK_IntegralToBoolean: 2295 return EmitIntToBoolConversion(Visit(E)); 2296 case CK_PointerToBoolean: 2297 return EmitPointerToBoolConversion(Visit(E), E->getType()); 2298 case CK_FloatingToBoolean: 2299 return EmitFloatToBoolConversion(Visit(E)); 2300 case CK_MemberPointerToBoolean: { 2301 llvm::Value *MemPtr = Visit(E); 2302 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>(); 2303 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT); 2304 } 2305 2306 case CK_FloatingComplexToReal: 2307 case CK_IntegralComplexToReal: 2308 return CGF.EmitComplexExpr(E, false, true).first; 2309 2310 case CK_FloatingComplexToBoolean: 2311 case CK_IntegralComplexToBoolean: { 2312 CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E); 2313 2314 // TODO: kill this function off, inline appropriate case here 2315 return EmitComplexToScalarConversion(V, E->getType(), DestTy, 2316 CE->getExprLoc()); 2317 } 2318 2319 case CK_ZeroToOCLOpaqueType: { 2320 assert((DestTy->isEventT() || DestTy->isQueueT() || 2321 DestTy->isOCLIntelSubgroupAVCType()) && 2322 "CK_ZeroToOCLEvent cast on non-event type"); 2323 return llvm::Constant::getNullValue(ConvertType(DestTy)); 2324 } 2325 2326 case CK_IntToOCLSampler: 2327 return CGF.CGM.createOpenCLIntToSamplerConversion(E, CGF); 2328 2329 } // end of switch 2330 2331 llvm_unreachable("unknown scalar cast"); 2332 } 2333 2334 Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) { 2335 CodeGenFunction::StmtExprEvaluation eval(CGF); 2336 Address RetAlloca = CGF.EmitCompoundStmt(*E->getSubStmt(), 2337 !E->getType()->isVoidType()); 2338 if (!RetAlloca.isValid()) 2339 return nullptr; 2340 return CGF.EmitLoadOfScalar(CGF.MakeAddrLValue(RetAlloca, E->getType()), 2341 E->getExprLoc()); 2342 } 2343 2344 Value *ScalarExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) { 2345 CodeGenFunction::RunCleanupsScope Scope(CGF); 2346 Value *V = Visit(E->getSubExpr()); 2347 // Defend against dominance problems caused by jumps out of expression 2348 // evaluation through the shared cleanup block. 2349 Scope.ForceCleanup({&V}); 2350 return V; 2351 } 2352 2353 //===----------------------------------------------------------------------===// 2354 // Unary Operators 2355 //===----------------------------------------------------------------------===// 2356 2357 static BinOpInfo createBinOpInfoFromIncDec(const UnaryOperator *E, 2358 llvm::Value *InVal, bool IsInc, 2359 FPOptions FPFeatures) { 2360 BinOpInfo BinOp; 2361 BinOp.LHS = InVal; 2362 BinOp.RHS = llvm::ConstantInt::get(InVal->getType(), 1, false); 2363 BinOp.Ty = E->getType(); 2364 BinOp.Opcode = IsInc ? BO_Add : BO_Sub; 2365 BinOp.FPFeatures = FPFeatures; 2366 BinOp.E = E; 2367 return BinOp; 2368 } 2369 2370 llvm::Value *ScalarExprEmitter::EmitIncDecConsiderOverflowBehavior( 2371 const UnaryOperator *E, llvm::Value *InVal, bool IsInc) { 2372 llvm::Value *Amount = 2373 llvm::ConstantInt::get(InVal->getType(), IsInc ? 1 : -1, true); 2374 StringRef Name = IsInc ? "inc" : "dec"; 2375 switch (CGF.getLangOpts().getSignedOverflowBehavior()) { 2376 case LangOptions::SOB_Defined: 2377 return Builder.CreateAdd(InVal, Amount, Name); 2378 case LangOptions::SOB_Undefined: 2379 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) 2380 return Builder.CreateNSWAdd(InVal, Amount, Name); 2381 LLVM_FALLTHROUGH; 2382 case LangOptions::SOB_Trapping: 2383 if (!E->canOverflow()) 2384 return Builder.CreateNSWAdd(InVal, Amount, Name); 2385 return EmitOverflowCheckedBinOp(createBinOpInfoFromIncDec( 2386 E, InVal, IsInc, E->getFPFeatures(CGF.getLangOpts()))); 2387 } 2388 llvm_unreachable("Unknown SignedOverflowBehaviorTy"); 2389 } 2390 2391 namespace { 2392 /// Handles check and update for lastprivate conditional variables. 2393 class OMPLastprivateConditionalUpdateRAII { 2394 private: 2395 CodeGenFunction &CGF; 2396 const UnaryOperator *E; 2397 2398 public: 2399 OMPLastprivateConditionalUpdateRAII(CodeGenFunction &CGF, 2400 const UnaryOperator *E) 2401 : CGF(CGF), E(E) {} 2402 ~OMPLastprivateConditionalUpdateRAII() { 2403 if (CGF.getLangOpts().OpenMP) 2404 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional( 2405 CGF, E->getSubExpr()); 2406 } 2407 }; 2408 } // namespace 2409 2410 llvm::Value * 2411 ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, 2412 bool isInc, bool isPre) { 2413 OMPLastprivateConditionalUpdateRAII OMPRegion(CGF, E); 2414 QualType type = E->getSubExpr()->getType(); 2415 llvm::PHINode *atomicPHI = nullptr; 2416 llvm::Value *value; 2417 llvm::Value *input; 2418 2419 int amount = (isInc ? 1 : -1); 2420 bool isSubtraction = !isInc; 2421 2422 if (const AtomicType *atomicTy = type->getAs<AtomicType>()) { 2423 type = atomicTy->getValueType(); 2424 if (isInc && type->isBooleanType()) { 2425 llvm::Value *True = CGF.EmitToMemory(Builder.getTrue(), type); 2426 if (isPre) { 2427 Builder.CreateStore(True, LV.getAddress(CGF), LV.isVolatileQualified()) 2428 ->setAtomic(llvm::AtomicOrdering::SequentiallyConsistent); 2429 return Builder.getTrue(); 2430 } 2431 // For atomic bool increment, we just store true and return it for 2432 // preincrement, do an atomic swap with true for postincrement 2433 return Builder.CreateAtomicRMW( 2434 llvm::AtomicRMWInst::Xchg, LV.getPointer(CGF), True, 2435 llvm::AtomicOrdering::SequentiallyConsistent); 2436 } 2437 // Special case for atomic increment / decrement on integers, emit 2438 // atomicrmw instructions. We skip this if we want to be doing overflow 2439 // checking, and fall into the slow path with the atomic cmpxchg loop. 2440 if (!type->isBooleanType() && type->isIntegerType() && 2441 !(type->isUnsignedIntegerType() && 2442 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) && 2443 CGF.getLangOpts().getSignedOverflowBehavior() != 2444 LangOptions::SOB_Trapping) { 2445 llvm::AtomicRMWInst::BinOp aop = isInc ? llvm::AtomicRMWInst::Add : 2446 llvm::AtomicRMWInst::Sub; 2447 llvm::Instruction::BinaryOps op = isInc ? llvm::Instruction::Add : 2448 llvm::Instruction::Sub; 2449 llvm::Value *amt = CGF.EmitToMemory( 2450 llvm::ConstantInt::get(ConvertType(type), 1, true), type); 2451 llvm::Value *old = 2452 Builder.CreateAtomicRMW(aop, LV.getPointer(CGF), amt, 2453 llvm::AtomicOrdering::SequentiallyConsistent); 2454 return isPre ? Builder.CreateBinOp(op, old, amt) : old; 2455 } 2456 value = EmitLoadOfLValue(LV, E->getExprLoc()); 2457 input = value; 2458 // For every other atomic operation, we need to emit a load-op-cmpxchg loop 2459 llvm::BasicBlock *startBB = Builder.GetInsertBlock(); 2460 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn); 2461 value = CGF.EmitToMemory(value, type); 2462 Builder.CreateBr(opBB); 2463 Builder.SetInsertPoint(opBB); 2464 atomicPHI = Builder.CreatePHI(value->getType(), 2); 2465 atomicPHI->addIncoming(value, startBB); 2466 value = atomicPHI; 2467 } else { 2468 value = EmitLoadOfLValue(LV, E->getExprLoc()); 2469 input = value; 2470 } 2471 2472 // Special case of integer increment that we have to check first: bool++. 2473 // Due to promotion rules, we get: 2474 // bool++ -> bool = bool + 1 2475 // -> bool = (int)bool + 1 2476 // -> bool = ((int)bool + 1 != 0) 2477 // An interesting aspect of this is that increment is always true. 2478 // Decrement does not have this property. 2479 if (isInc && type->isBooleanType()) { 2480 value = Builder.getTrue(); 2481 2482 // Most common case by far: integer increment. 2483 } else if (type->isIntegerType()) { 2484 QualType promotedType; 2485 bool canPerformLossyDemotionCheck = false; 2486 if (type->isPromotableIntegerType()) { 2487 promotedType = CGF.getContext().getPromotedIntegerType(type); 2488 assert(promotedType != type && "Shouldn't promote to the same type."); 2489 canPerformLossyDemotionCheck = true; 2490 canPerformLossyDemotionCheck &= 2491 CGF.getContext().getCanonicalType(type) != 2492 CGF.getContext().getCanonicalType(promotedType); 2493 canPerformLossyDemotionCheck &= 2494 PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck( 2495 type, promotedType); 2496 assert((!canPerformLossyDemotionCheck || 2497 type->isSignedIntegerOrEnumerationType() || 2498 promotedType->isSignedIntegerOrEnumerationType() || 2499 ConvertType(type)->getScalarSizeInBits() == 2500 ConvertType(promotedType)->getScalarSizeInBits()) && 2501 "The following check expects that if we do promotion to different " 2502 "underlying canonical type, at least one of the types (either " 2503 "base or promoted) will be signed, or the bitwidths will match."); 2504 } 2505 if (CGF.SanOpts.hasOneOf( 2506 SanitizerKind::ImplicitIntegerArithmeticValueChange) && 2507 canPerformLossyDemotionCheck) { 2508 // While `x += 1` (for `x` with width less than int) is modeled as 2509 // promotion+arithmetics+demotion, and we can catch lossy demotion with 2510 // ease; inc/dec with width less than int can't overflow because of 2511 // promotion rules, so we omit promotion+demotion, which means that we can 2512 // not catch lossy "demotion". Because we still want to catch these cases 2513 // when the sanitizer is enabled, we perform the promotion, then perform 2514 // the increment/decrement in the wider type, and finally 2515 // perform the demotion. This will catch lossy demotions. 2516 2517 value = EmitScalarConversion(value, type, promotedType, E->getExprLoc()); 2518 Value *amt = llvm::ConstantInt::get(value->getType(), amount, true); 2519 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec"); 2520 // Do pass non-default ScalarConversionOpts so that sanitizer check is 2521 // emitted. 2522 value = EmitScalarConversion(value, promotedType, type, E->getExprLoc(), 2523 ScalarConversionOpts(CGF.SanOpts)); 2524 2525 // Note that signed integer inc/dec with width less than int can't 2526 // overflow because of promotion rules; we're just eliding a few steps 2527 // here. 2528 } else if (E->canOverflow() && type->isSignedIntegerOrEnumerationType()) { 2529 value = EmitIncDecConsiderOverflowBehavior(E, value, isInc); 2530 } else if (E->canOverflow() && type->isUnsignedIntegerType() && 2531 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) { 2532 value = EmitOverflowCheckedBinOp(createBinOpInfoFromIncDec( 2533 E, value, isInc, E->getFPFeatures(CGF.getLangOpts()))); 2534 } else { 2535 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount, true); 2536 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec"); 2537 } 2538 2539 // Next most common: pointer increment. 2540 } else if (const PointerType *ptr = type->getAs<PointerType>()) { 2541 QualType type = ptr->getPointeeType(); 2542 2543 // VLA types don't have constant size. 2544 if (const VariableArrayType *vla 2545 = CGF.getContext().getAsVariableArrayType(type)) { 2546 llvm::Value *numElts = CGF.getVLASize(vla).NumElts; 2547 if (!isInc) numElts = Builder.CreateNSWNeg(numElts, "vla.negsize"); 2548 if (CGF.getLangOpts().isSignedOverflowDefined()) 2549 value = Builder.CreateGEP(value, numElts, "vla.inc"); 2550 else 2551 value = CGF.EmitCheckedInBoundsGEP( 2552 value, numElts, /*SignedIndices=*/false, isSubtraction, 2553 E->getExprLoc(), "vla.inc"); 2554 2555 // Arithmetic on function pointers (!) is just +-1. 2556 } else if (type->isFunctionType()) { 2557 llvm::Value *amt = Builder.getInt32(amount); 2558 2559 value = CGF.EmitCastToVoidPtr(value); 2560 if (CGF.getLangOpts().isSignedOverflowDefined()) 2561 value = Builder.CreateGEP(value, amt, "incdec.funcptr"); 2562 else 2563 value = CGF.EmitCheckedInBoundsGEP(value, amt, /*SignedIndices=*/false, 2564 isSubtraction, E->getExprLoc(), 2565 "incdec.funcptr"); 2566 value = Builder.CreateBitCast(value, input->getType()); 2567 2568 // For everything else, we can just do a simple increment. 2569 } else { 2570 llvm::Value *amt = Builder.getInt32(amount); 2571 if (CGF.getLangOpts().isSignedOverflowDefined()) 2572 value = Builder.CreateGEP(value, amt, "incdec.ptr"); 2573 else 2574 value = CGF.EmitCheckedInBoundsGEP(value, amt, /*SignedIndices=*/false, 2575 isSubtraction, E->getExprLoc(), 2576 "incdec.ptr"); 2577 } 2578 2579 // Vector increment/decrement. 2580 } else if (type->isVectorType()) { 2581 if (type->hasIntegerRepresentation()) { 2582 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount); 2583 2584 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec"); 2585 } else { 2586 value = Builder.CreateFAdd( 2587 value, 2588 llvm::ConstantFP::get(value->getType(), amount), 2589 isInc ? "inc" : "dec"); 2590 } 2591 2592 // Floating point. 2593 } else if (type->isRealFloatingType()) { 2594 // Add the inc/dec to the real part. 2595 llvm::Value *amt; 2596 2597 if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) { 2598 // Another special case: half FP increment should be done via float 2599 if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) { 2600 value = Builder.CreateCall( 2601 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16, 2602 CGF.CGM.FloatTy), 2603 input, "incdec.conv"); 2604 } else { 2605 value = Builder.CreateFPExt(input, CGF.CGM.FloatTy, "incdec.conv"); 2606 } 2607 } 2608 2609 if (value->getType()->isFloatTy()) 2610 amt = llvm::ConstantFP::get(VMContext, 2611 llvm::APFloat(static_cast<float>(amount))); 2612 else if (value->getType()->isDoubleTy()) 2613 amt = llvm::ConstantFP::get(VMContext, 2614 llvm::APFloat(static_cast<double>(amount))); 2615 else { 2616 // Remaining types are Half, LongDouble or __float128. Convert from float. 2617 llvm::APFloat F(static_cast<float>(amount)); 2618 bool ignored; 2619 const llvm::fltSemantics *FS; 2620 // Don't use getFloatTypeSemantics because Half isn't 2621 // necessarily represented using the "half" LLVM type. 2622 if (value->getType()->isFP128Ty()) 2623 FS = &CGF.getTarget().getFloat128Format(); 2624 else if (value->getType()->isHalfTy()) 2625 FS = &CGF.getTarget().getHalfFormat(); 2626 else 2627 FS = &CGF.getTarget().getLongDoubleFormat(); 2628 F.convert(*FS, llvm::APFloat::rmTowardZero, &ignored); 2629 amt = llvm::ConstantFP::get(VMContext, F); 2630 } 2631 value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec"); 2632 2633 if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) { 2634 if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) { 2635 value = Builder.CreateCall( 2636 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16, 2637 CGF.CGM.FloatTy), 2638 value, "incdec.conv"); 2639 } else { 2640 value = Builder.CreateFPTrunc(value, input->getType(), "incdec.conv"); 2641 } 2642 } 2643 2644 // Fixed-point types. 2645 } else if (type->isFixedPointType()) { 2646 // Fixed-point types are tricky. In some cases, it isn't possible to 2647 // represent a 1 or a -1 in the type at all. Piggyback off of 2648 // EmitFixedPointBinOp to avoid having to reimplement saturation. 2649 BinOpInfo Info; 2650 Info.E = E; 2651 Info.Ty = E->getType(); 2652 Info.Opcode = isInc ? BO_Add : BO_Sub; 2653 Info.LHS = value; 2654 Info.RHS = llvm::ConstantInt::get(value->getType(), 1, false); 2655 // If the type is signed, it's better to represent this as +(-1) or -(-1), 2656 // since -1 is guaranteed to be representable. 2657 if (type->isSignedFixedPointType()) { 2658 Info.Opcode = isInc ? BO_Sub : BO_Add; 2659 Info.RHS = Builder.CreateNeg(Info.RHS); 2660 } 2661 // Now, convert from our invented integer literal to the type of the unary 2662 // op. This will upscale and saturate if necessary. This value can become 2663 // undef in some cases. 2664 FixedPointSemantics SrcSema = 2665 FixedPointSemantics::GetIntegerSemantics(value->getType() 2666 ->getScalarSizeInBits(), 2667 /*IsSigned=*/true); 2668 FixedPointSemantics DstSema = 2669 CGF.getContext().getFixedPointSemantics(Info.Ty); 2670 Info.RHS = EmitFixedPointConversion(Info.RHS, SrcSema, DstSema, 2671 E->getExprLoc()); 2672 value = EmitFixedPointBinOp(Info); 2673 2674 // Objective-C pointer types. 2675 } else { 2676 const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>(); 2677 value = CGF.EmitCastToVoidPtr(value); 2678 2679 CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType()); 2680 if (!isInc) size = -size; 2681 llvm::Value *sizeValue = 2682 llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity()); 2683 2684 if (CGF.getLangOpts().isSignedOverflowDefined()) 2685 value = Builder.CreateGEP(value, sizeValue, "incdec.objptr"); 2686 else 2687 value = CGF.EmitCheckedInBoundsGEP(value, sizeValue, 2688 /*SignedIndices=*/false, isSubtraction, 2689 E->getExprLoc(), "incdec.objptr"); 2690 value = Builder.CreateBitCast(value, input->getType()); 2691 } 2692 2693 if (atomicPHI) { 2694 llvm::BasicBlock *curBlock = Builder.GetInsertBlock(); 2695 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn); 2696 auto Pair = CGF.EmitAtomicCompareExchange( 2697 LV, RValue::get(atomicPHI), RValue::get(value), E->getExprLoc()); 2698 llvm::Value *old = CGF.EmitToMemory(Pair.first.getScalarVal(), type); 2699 llvm::Value *success = Pair.second; 2700 atomicPHI->addIncoming(old, curBlock); 2701 Builder.CreateCondBr(success, contBB, atomicPHI->getParent()); 2702 Builder.SetInsertPoint(contBB); 2703 return isPre ? value : input; 2704 } 2705 2706 // Store the updated result through the lvalue. 2707 if (LV.isBitField()) 2708 CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, &value); 2709 else 2710 CGF.EmitStoreThroughLValue(RValue::get(value), LV); 2711 2712 // If this is a postinc, return the value read from memory, otherwise use the 2713 // updated value. 2714 return isPre ? value : input; 2715 } 2716 2717 2718 2719 Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) { 2720 TestAndClearIgnoreResultAssign(); 2721 Value *Op = Visit(E->getSubExpr()); 2722 2723 // Generate a unary FNeg for FP ops. 2724 if (Op->getType()->isFPOrFPVectorTy()) 2725 return Builder.CreateFNeg(Op, "fneg"); 2726 2727 // Emit unary minus with EmitSub so we handle overflow cases etc. 2728 BinOpInfo BinOp; 2729 BinOp.RHS = Op; 2730 BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType()); 2731 BinOp.Ty = E->getType(); 2732 BinOp.Opcode = BO_Sub; 2733 BinOp.FPFeatures = E->getFPFeatures(CGF.getLangOpts()); 2734 BinOp.E = E; 2735 return EmitSub(BinOp); 2736 } 2737 2738 Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) { 2739 TestAndClearIgnoreResultAssign(); 2740 Value *Op = Visit(E->getSubExpr()); 2741 return Builder.CreateNot(Op, "neg"); 2742 } 2743 2744 Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) { 2745 // Perform vector logical not on comparison with zero vector. 2746 if (E->getType()->isVectorType() && 2747 E->getType()->castAs<VectorType>()->getVectorKind() == 2748 VectorType::GenericVector) { 2749 Value *Oper = Visit(E->getSubExpr()); 2750 Value *Zero = llvm::Constant::getNullValue(Oper->getType()); 2751 Value *Result; 2752 if (Oper->getType()->isFPOrFPVectorTy()) { 2753 CodeGenFunction::CGFPOptionsRAII FPOptsRAII( 2754 CGF, E->getFPFeatures(CGF.getLangOpts())); 2755 Result = Builder.CreateFCmp(llvm::CmpInst::FCMP_OEQ, Oper, Zero, "cmp"); 2756 } else 2757 Result = Builder.CreateICmp(llvm::CmpInst::ICMP_EQ, Oper, Zero, "cmp"); 2758 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext"); 2759 } 2760 2761 // Compare operand to zero. 2762 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr()); 2763 2764 // Invert value. 2765 // TODO: Could dynamically modify easy computations here. For example, if 2766 // the operand is an icmp ne, turn into icmp eq. 2767 BoolVal = Builder.CreateNot(BoolVal, "lnot"); 2768 2769 // ZExt result to the expr type. 2770 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext"); 2771 } 2772 2773 Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) { 2774 // Try folding the offsetof to a constant. 2775 Expr::EvalResult EVResult; 2776 if (E->EvaluateAsInt(EVResult, CGF.getContext())) { 2777 llvm::APSInt Value = EVResult.Val.getInt(); 2778 return Builder.getInt(Value); 2779 } 2780 2781 // Loop over the components of the offsetof to compute the value. 2782 unsigned n = E->getNumComponents(); 2783 llvm::Type* ResultType = ConvertType(E->getType()); 2784 llvm::Value* Result = llvm::Constant::getNullValue(ResultType); 2785 QualType CurrentType = E->getTypeSourceInfo()->getType(); 2786 for (unsigned i = 0; i != n; ++i) { 2787 OffsetOfNode ON = E->getComponent(i); 2788 llvm::Value *Offset = nullptr; 2789 switch (ON.getKind()) { 2790 case OffsetOfNode::Array: { 2791 // Compute the index 2792 Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex()); 2793 llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr); 2794 bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType(); 2795 Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv"); 2796 2797 // Save the element type 2798 CurrentType = 2799 CGF.getContext().getAsArrayType(CurrentType)->getElementType(); 2800 2801 // Compute the element size 2802 llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType, 2803 CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity()); 2804 2805 // Multiply out to compute the result 2806 Offset = Builder.CreateMul(Idx, ElemSize); 2807 break; 2808 } 2809 2810 case OffsetOfNode::Field: { 2811 FieldDecl *MemberDecl = ON.getField(); 2812 RecordDecl *RD = CurrentType->castAs<RecordType>()->getDecl(); 2813 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD); 2814 2815 // Compute the index of the field in its parent. 2816 unsigned i = 0; 2817 // FIXME: It would be nice if we didn't have to loop here! 2818 for (RecordDecl::field_iterator Field = RD->field_begin(), 2819 FieldEnd = RD->field_end(); 2820 Field != FieldEnd; ++Field, ++i) { 2821 if (*Field == MemberDecl) 2822 break; 2823 } 2824 assert(i < RL.getFieldCount() && "offsetof field in wrong type"); 2825 2826 // Compute the offset to the field 2827 int64_t OffsetInt = RL.getFieldOffset(i) / 2828 CGF.getContext().getCharWidth(); 2829 Offset = llvm::ConstantInt::get(ResultType, OffsetInt); 2830 2831 // Save the element type. 2832 CurrentType = MemberDecl->getType(); 2833 break; 2834 } 2835 2836 case OffsetOfNode::Identifier: 2837 llvm_unreachable("dependent __builtin_offsetof"); 2838 2839 case OffsetOfNode::Base: { 2840 if (ON.getBase()->isVirtual()) { 2841 CGF.ErrorUnsupported(E, "virtual base in offsetof"); 2842 continue; 2843 } 2844 2845 RecordDecl *RD = CurrentType->castAs<RecordType>()->getDecl(); 2846 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD); 2847 2848 // Save the element type. 2849 CurrentType = ON.getBase()->getType(); 2850 2851 // Compute the offset to the base. 2852 const RecordType *BaseRT = CurrentType->getAs<RecordType>(); 2853 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl()); 2854 CharUnits OffsetInt = RL.getBaseClassOffset(BaseRD); 2855 Offset = llvm::ConstantInt::get(ResultType, OffsetInt.getQuantity()); 2856 break; 2857 } 2858 } 2859 Result = Builder.CreateAdd(Result, Offset); 2860 } 2861 return Result; 2862 } 2863 2864 /// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of 2865 /// argument of the sizeof expression as an integer. 2866 Value * 2867 ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr( 2868 const UnaryExprOrTypeTraitExpr *E) { 2869 QualType TypeToSize = E->getTypeOfArgument(); 2870 if (E->getKind() == UETT_SizeOf) { 2871 if (const VariableArrayType *VAT = 2872 CGF.getContext().getAsVariableArrayType(TypeToSize)) { 2873 if (E->isArgumentType()) { 2874 // sizeof(type) - make sure to emit the VLA size. 2875 CGF.EmitVariablyModifiedType(TypeToSize); 2876 } else { 2877 // C99 6.5.3.4p2: If the argument is an expression of type 2878 // VLA, it is evaluated. 2879 CGF.EmitIgnoredExpr(E->getArgumentExpr()); 2880 } 2881 2882 auto VlaSize = CGF.getVLASize(VAT); 2883 llvm::Value *size = VlaSize.NumElts; 2884 2885 // Scale the number of non-VLA elements by the non-VLA element size. 2886 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(VlaSize.Type); 2887 if (!eltSize.isOne()) 2888 size = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), size); 2889 2890 return size; 2891 } 2892 } else if (E->getKind() == UETT_OpenMPRequiredSimdAlign) { 2893 auto Alignment = 2894 CGF.getContext() 2895 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign( 2896 E->getTypeOfArgument()->getPointeeType())) 2897 .getQuantity(); 2898 return llvm::ConstantInt::get(CGF.SizeTy, Alignment); 2899 } 2900 2901 // If this isn't sizeof(vla), the result must be constant; use the constant 2902 // folding logic so we don't have to duplicate it here. 2903 return Builder.getInt(E->EvaluateKnownConstInt(CGF.getContext())); 2904 } 2905 2906 Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) { 2907 Expr *Op = E->getSubExpr(); 2908 if (Op->getType()->isAnyComplexType()) { 2909 // If it's an l-value, load through the appropriate subobject l-value. 2910 // Note that we have to ask E because Op might be an l-value that 2911 // this won't work for, e.g. an Obj-C property. 2912 if (E->isGLValue()) 2913 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E), 2914 E->getExprLoc()).getScalarVal(); 2915 2916 // Otherwise, calculate and project. 2917 return CGF.EmitComplexExpr(Op, false, true).first; 2918 } 2919 2920 return Visit(Op); 2921 } 2922 2923 Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) { 2924 Expr *Op = E->getSubExpr(); 2925 if (Op->getType()->isAnyComplexType()) { 2926 // If it's an l-value, load through the appropriate subobject l-value. 2927 // Note that we have to ask E because Op might be an l-value that 2928 // this won't work for, e.g. an Obj-C property. 2929 if (Op->isGLValue()) 2930 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E), 2931 E->getExprLoc()).getScalarVal(); 2932 2933 // Otherwise, calculate and project. 2934 return CGF.EmitComplexExpr(Op, true, false).second; 2935 } 2936 2937 // __imag on a scalar returns zero. Emit the subexpr to ensure side 2938 // effects are evaluated, but not the actual value. 2939 if (Op->isGLValue()) 2940 CGF.EmitLValue(Op); 2941 else 2942 CGF.EmitScalarExpr(Op, true); 2943 return llvm::Constant::getNullValue(ConvertType(E->getType())); 2944 } 2945 2946 //===----------------------------------------------------------------------===// 2947 // Binary Operators 2948 //===----------------------------------------------------------------------===// 2949 2950 BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) { 2951 TestAndClearIgnoreResultAssign(); 2952 BinOpInfo Result; 2953 Result.LHS = Visit(E->getLHS()); 2954 Result.RHS = Visit(E->getRHS()); 2955 Result.Ty = E->getType(); 2956 Result.Opcode = E->getOpcode(); 2957 Result.FPFeatures = E->getFPFeatures(CGF.getLangOpts()); 2958 Result.E = E; 2959 return Result; 2960 } 2961 2962 LValue ScalarExprEmitter::EmitCompoundAssignLValue( 2963 const CompoundAssignOperator *E, 2964 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &), 2965 Value *&Result) { 2966 QualType LHSTy = E->getLHS()->getType(); 2967 BinOpInfo OpInfo; 2968 2969 if (E->getComputationResultType()->isAnyComplexType()) 2970 return CGF.EmitScalarCompoundAssignWithComplex(E, Result); 2971 2972 // Emit the RHS first. __block variables need to have the rhs evaluated 2973 // first, plus this should improve codegen a little. 2974 OpInfo.RHS = Visit(E->getRHS()); 2975 OpInfo.Ty = E->getComputationResultType(); 2976 OpInfo.Opcode = E->getOpcode(); 2977 OpInfo.FPFeatures = E->getFPFeatures(CGF.getLangOpts()); 2978 OpInfo.E = E; 2979 // Load/convert the LHS. 2980 LValue LHSLV = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store); 2981 2982 llvm::PHINode *atomicPHI = nullptr; 2983 if (const AtomicType *atomicTy = LHSTy->getAs<AtomicType>()) { 2984 QualType type = atomicTy->getValueType(); 2985 if (!type->isBooleanType() && type->isIntegerType() && 2986 !(type->isUnsignedIntegerType() && 2987 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) && 2988 CGF.getLangOpts().getSignedOverflowBehavior() != 2989 LangOptions::SOB_Trapping) { 2990 llvm::AtomicRMWInst::BinOp AtomicOp = llvm::AtomicRMWInst::BAD_BINOP; 2991 llvm::Instruction::BinaryOps Op; 2992 switch (OpInfo.Opcode) { 2993 // We don't have atomicrmw operands for *, %, /, <<, >> 2994 case BO_MulAssign: case BO_DivAssign: 2995 case BO_RemAssign: 2996 case BO_ShlAssign: 2997 case BO_ShrAssign: 2998 break; 2999 case BO_AddAssign: 3000 AtomicOp = llvm::AtomicRMWInst::Add; 3001 Op = llvm::Instruction::Add; 3002 break; 3003 case BO_SubAssign: 3004 AtomicOp = llvm::AtomicRMWInst::Sub; 3005 Op = llvm::Instruction::Sub; 3006 break; 3007 case BO_AndAssign: 3008 AtomicOp = llvm::AtomicRMWInst::And; 3009 Op = llvm::Instruction::And; 3010 break; 3011 case BO_XorAssign: 3012 AtomicOp = llvm::AtomicRMWInst::Xor; 3013 Op = llvm::Instruction::Xor; 3014 break; 3015 case BO_OrAssign: 3016 AtomicOp = llvm::AtomicRMWInst::Or; 3017 Op = llvm::Instruction::Or; 3018 break; 3019 default: 3020 llvm_unreachable("Invalid compound assignment type"); 3021 } 3022 if (AtomicOp != llvm::AtomicRMWInst::BAD_BINOP) { 3023 llvm::Value *Amt = CGF.EmitToMemory( 3024 EmitScalarConversion(OpInfo.RHS, E->getRHS()->getType(), LHSTy, 3025 E->getExprLoc()), 3026 LHSTy); 3027 Value *OldVal = Builder.CreateAtomicRMW( 3028 AtomicOp, LHSLV.getPointer(CGF), Amt, 3029 llvm::AtomicOrdering::SequentiallyConsistent); 3030 3031 // Since operation is atomic, the result type is guaranteed to be the 3032 // same as the input in LLVM terms. 3033 Result = Builder.CreateBinOp(Op, OldVal, Amt); 3034 return LHSLV; 3035 } 3036 } 3037 // FIXME: For floating point types, we should be saving and restoring the 3038 // floating point environment in the loop. 3039 llvm::BasicBlock *startBB = Builder.GetInsertBlock(); 3040 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn); 3041 OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc()); 3042 OpInfo.LHS = CGF.EmitToMemory(OpInfo.LHS, type); 3043 Builder.CreateBr(opBB); 3044 Builder.SetInsertPoint(opBB); 3045 atomicPHI = Builder.CreatePHI(OpInfo.LHS->getType(), 2); 3046 atomicPHI->addIncoming(OpInfo.LHS, startBB); 3047 OpInfo.LHS = atomicPHI; 3048 } 3049 else 3050 OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc()); 3051 3052 SourceLocation Loc = E->getExprLoc(); 3053 OpInfo.LHS = 3054 EmitScalarConversion(OpInfo.LHS, LHSTy, E->getComputationLHSType(), Loc); 3055 3056 // Expand the binary operator. 3057 Result = (this->*Func)(OpInfo); 3058 3059 // Convert the result back to the LHS type, 3060 // potentially with Implicit Conversion sanitizer check. 3061 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy, 3062 Loc, ScalarConversionOpts(CGF.SanOpts)); 3063 3064 if (atomicPHI) { 3065 llvm::BasicBlock *curBlock = Builder.GetInsertBlock(); 3066 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn); 3067 auto Pair = CGF.EmitAtomicCompareExchange( 3068 LHSLV, RValue::get(atomicPHI), RValue::get(Result), E->getExprLoc()); 3069 llvm::Value *old = CGF.EmitToMemory(Pair.first.getScalarVal(), LHSTy); 3070 llvm::Value *success = Pair.second; 3071 atomicPHI->addIncoming(old, curBlock); 3072 Builder.CreateCondBr(success, contBB, atomicPHI->getParent()); 3073 Builder.SetInsertPoint(contBB); 3074 return LHSLV; 3075 } 3076 3077 // Store the result value into the LHS lvalue. Bit-fields are handled 3078 // specially because the result is altered by the store, i.e., [C99 6.5.16p1] 3079 // 'An assignment expression has the value of the left operand after the 3080 // assignment...'. 3081 if (LHSLV.isBitField()) 3082 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, &Result); 3083 else 3084 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV); 3085 3086 if (CGF.getLangOpts().OpenMP) 3087 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, 3088 E->getLHS()); 3089 return LHSLV; 3090 } 3091 3092 Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E, 3093 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) { 3094 bool Ignore = TestAndClearIgnoreResultAssign(); 3095 Value *RHS = nullptr; 3096 LValue LHS = EmitCompoundAssignLValue(E, Func, RHS); 3097 3098 // If the result is clearly ignored, return now. 3099 if (Ignore) 3100 return nullptr; 3101 3102 // The result of an assignment in C is the assigned r-value. 3103 if (!CGF.getLangOpts().CPlusPlus) 3104 return RHS; 3105 3106 // If the lvalue is non-volatile, return the computed value of the assignment. 3107 if (!LHS.isVolatileQualified()) 3108 return RHS; 3109 3110 // Otherwise, reload the value. 3111 return EmitLoadOfLValue(LHS, E->getExprLoc()); 3112 } 3113 3114 void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck( 3115 const BinOpInfo &Ops, llvm::Value *Zero, bool isDiv) { 3116 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 2> Checks; 3117 3118 if (CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero)) { 3119 Checks.push_back(std::make_pair(Builder.CreateICmpNE(Ops.RHS, Zero), 3120 SanitizerKind::IntegerDivideByZero)); 3121 } 3122 3123 const auto *BO = cast<BinaryOperator>(Ops.E); 3124 if (CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow) && 3125 Ops.Ty->hasSignedIntegerRepresentation() && 3126 !IsWidenedIntegerOp(CGF.getContext(), BO->getLHS()) && 3127 Ops.mayHaveIntegerOverflow()) { 3128 llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType()); 3129 3130 llvm::Value *IntMin = 3131 Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth())); 3132 llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL); 3133 3134 llvm::Value *LHSCmp = Builder.CreateICmpNE(Ops.LHS, IntMin); 3135 llvm::Value *RHSCmp = Builder.CreateICmpNE(Ops.RHS, NegOne); 3136 llvm::Value *NotOverflow = Builder.CreateOr(LHSCmp, RHSCmp, "or"); 3137 Checks.push_back( 3138 std::make_pair(NotOverflow, SanitizerKind::SignedIntegerOverflow)); 3139 } 3140 3141 if (Checks.size() > 0) 3142 EmitBinOpCheck(Checks, Ops); 3143 } 3144 3145 Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) { 3146 { 3147 CodeGenFunction::SanitizerScope SanScope(&CGF); 3148 if ((CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero) || 3149 CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) && 3150 Ops.Ty->isIntegerType() && 3151 (Ops.mayHaveIntegerDivisionByZero() || Ops.mayHaveIntegerOverflow())) { 3152 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty)); 3153 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true); 3154 } else if (CGF.SanOpts.has(SanitizerKind::FloatDivideByZero) && 3155 Ops.Ty->isRealFloatingType() && 3156 Ops.mayHaveFloatDivisionByZero()) { 3157 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty)); 3158 llvm::Value *NonZero = Builder.CreateFCmpUNE(Ops.RHS, Zero); 3159 EmitBinOpCheck(std::make_pair(NonZero, SanitizerKind::FloatDivideByZero), 3160 Ops); 3161 } 3162 } 3163 3164 if (Ops.LHS->getType()->isFPOrFPVectorTy()) { 3165 llvm::Value *Val; 3166 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Ops.FPFeatures); 3167 Val = Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div"); 3168 if (CGF.getLangOpts().OpenCL && 3169 !CGF.CGM.getCodeGenOpts().CorrectlyRoundedDivSqrt) { 3170 // OpenCL v1.1 s7.4: minimum accuracy of single precision / is 2.5ulp 3171 // OpenCL v1.2 s5.6.4.2: The -cl-fp32-correctly-rounded-divide-sqrt 3172 // build option allows an application to specify that single precision 3173 // floating-point divide (x/y and 1/x) and sqrt used in the program 3174 // source are correctly rounded. 3175 llvm::Type *ValTy = Val->getType(); 3176 if (ValTy->isFloatTy() || 3177 (isa<llvm::VectorType>(ValTy) && 3178 cast<llvm::VectorType>(ValTy)->getElementType()->isFloatTy())) 3179 CGF.SetFPAccuracy(Val, 2.5); 3180 } 3181 return Val; 3182 } 3183 else if (Ops.isFixedPointOp()) 3184 return EmitFixedPointBinOp(Ops); 3185 else if (Ops.Ty->hasUnsignedIntegerRepresentation()) 3186 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div"); 3187 else 3188 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div"); 3189 } 3190 3191 Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) { 3192 // Rem in C can't be a floating point type: C99 6.5.5p2. 3193 if ((CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero) || 3194 CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) && 3195 Ops.Ty->isIntegerType() && 3196 (Ops.mayHaveIntegerDivisionByZero() || Ops.mayHaveIntegerOverflow())) { 3197 CodeGenFunction::SanitizerScope SanScope(&CGF); 3198 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty)); 3199 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false); 3200 } 3201 3202 if (Ops.Ty->hasUnsignedIntegerRepresentation()) 3203 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem"); 3204 else 3205 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem"); 3206 } 3207 3208 Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) { 3209 unsigned IID; 3210 unsigned OpID = 0; 3211 3212 bool isSigned = Ops.Ty->isSignedIntegerOrEnumerationType(); 3213 switch (Ops.Opcode) { 3214 case BO_Add: 3215 case BO_AddAssign: 3216 OpID = 1; 3217 IID = isSigned ? llvm::Intrinsic::sadd_with_overflow : 3218 llvm::Intrinsic::uadd_with_overflow; 3219 break; 3220 case BO_Sub: 3221 case BO_SubAssign: 3222 OpID = 2; 3223 IID = isSigned ? llvm::Intrinsic::ssub_with_overflow : 3224 llvm::Intrinsic::usub_with_overflow; 3225 break; 3226 case BO_Mul: 3227 case BO_MulAssign: 3228 OpID = 3; 3229 IID = isSigned ? llvm::Intrinsic::smul_with_overflow : 3230 llvm::Intrinsic::umul_with_overflow; 3231 break; 3232 default: 3233 llvm_unreachable("Unsupported operation for overflow detection"); 3234 } 3235 OpID <<= 1; 3236 if (isSigned) 3237 OpID |= 1; 3238 3239 CodeGenFunction::SanitizerScope SanScope(&CGF); 3240 llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty); 3241 3242 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy); 3243 3244 Value *resultAndOverflow = Builder.CreateCall(intrinsic, {Ops.LHS, Ops.RHS}); 3245 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0); 3246 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1); 3247 3248 // Handle overflow with llvm.trap if no custom handler has been specified. 3249 const std::string *handlerName = 3250 &CGF.getLangOpts().OverflowHandler; 3251 if (handlerName->empty()) { 3252 // If the signed-integer-overflow sanitizer is enabled, emit a call to its 3253 // runtime. Otherwise, this is a -ftrapv check, so just emit a trap. 3254 if (!isSigned || CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) { 3255 llvm::Value *NotOverflow = Builder.CreateNot(overflow); 3256 SanitizerMask Kind = isSigned ? SanitizerKind::SignedIntegerOverflow 3257 : SanitizerKind::UnsignedIntegerOverflow; 3258 EmitBinOpCheck(std::make_pair(NotOverflow, Kind), Ops); 3259 } else 3260 CGF.EmitTrapCheck(Builder.CreateNot(overflow)); 3261 return result; 3262 } 3263 3264 // Branch in case of overflow. 3265 llvm::BasicBlock *initialBB = Builder.GetInsertBlock(); 3266 llvm::BasicBlock *continueBB = 3267 CGF.createBasicBlock("nooverflow", CGF.CurFn, initialBB->getNextNode()); 3268 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn); 3269 3270 Builder.CreateCondBr(overflow, overflowBB, continueBB); 3271 3272 // If an overflow handler is set, then we want to call it and then use its 3273 // result, if it returns. 3274 Builder.SetInsertPoint(overflowBB); 3275 3276 // Get the overflow handler. 3277 llvm::Type *Int8Ty = CGF.Int8Ty; 3278 llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty }; 3279 llvm::FunctionType *handlerTy = 3280 llvm::FunctionType::get(CGF.Int64Ty, argTypes, true); 3281 llvm::FunctionCallee handler = 3282 CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName); 3283 3284 // Sign extend the args to 64-bit, so that we can use the same handler for 3285 // all types of overflow. 3286 llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty); 3287 llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty); 3288 3289 // Call the handler with the two arguments, the operation, and the size of 3290 // the result. 3291 llvm::Value *handlerArgs[] = { 3292 lhs, 3293 rhs, 3294 Builder.getInt8(OpID), 3295 Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth()) 3296 }; 3297 llvm::Value *handlerResult = 3298 CGF.EmitNounwindRuntimeCall(handler, handlerArgs); 3299 3300 // Truncate the result back to the desired size. 3301 handlerResult = Builder.CreateTrunc(handlerResult, opTy); 3302 Builder.CreateBr(continueBB); 3303 3304 Builder.SetInsertPoint(continueBB); 3305 llvm::PHINode *phi = Builder.CreatePHI(opTy, 2); 3306 phi->addIncoming(result, initialBB); 3307 phi->addIncoming(handlerResult, overflowBB); 3308 3309 return phi; 3310 } 3311 3312 /// Emit pointer + index arithmetic. 3313 static Value *emitPointerArithmetic(CodeGenFunction &CGF, 3314 const BinOpInfo &op, 3315 bool isSubtraction) { 3316 // Must have binary (not unary) expr here. Unary pointer 3317 // increment/decrement doesn't use this path. 3318 const BinaryOperator *expr = cast<BinaryOperator>(op.E); 3319 3320 Value *pointer = op.LHS; 3321 Expr *pointerOperand = expr->getLHS(); 3322 Value *index = op.RHS; 3323 Expr *indexOperand = expr->getRHS(); 3324 3325 // In a subtraction, the LHS is always the pointer. 3326 if (!isSubtraction && !pointer->getType()->isPointerTy()) { 3327 std::swap(pointer, index); 3328 std::swap(pointerOperand, indexOperand); 3329 } 3330 3331 bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType(); 3332 3333 unsigned width = cast<llvm::IntegerType>(index->getType())->getBitWidth(); 3334 auto &DL = CGF.CGM.getDataLayout(); 3335 auto PtrTy = cast<llvm::PointerType>(pointer->getType()); 3336 3337 // Some versions of glibc and gcc use idioms (particularly in their malloc 3338 // routines) that add a pointer-sized integer (known to be a pointer value) 3339 // to a null pointer in order to cast the value back to an integer or as 3340 // part of a pointer alignment algorithm. This is undefined behavior, but 3341 // we'd like to be able to compile programs that use it. 3342 // 3343 // Normally, we'd generate a GEP with a null-pointer base here in response 3344 // to that code, but it's also UB to dereference a pointer created that 3345 // way. Instead (as an acknowledged hack to tolerate the idiom) we will 3346 // generate a direct cast of the integer value to a pointer. 3347 // 3348 // The idiom (p = nullptr + N) is not met if any of the following are true: 3349 // 3350 // The operation is subtraction. 3351 // The index is not pointer-sized. 3352 // The pointer type is not byte-sized. 3353 // 3354 if (BinaryOperator::isNullPointerArithmeticExtension(CGF.getContext(), 3355 op.Opcode, 3356 expr->getLHS(), 3357 expr->getRHS())) 3358 return CGF.Builder.CreateIntToPtr(index, pointer->getType()); 3359 3360 if (width != DL.getIndexTypeSizeInBits(PtrTy)) { 3361 // Zero-extend or sign-extend the pointer value according to 3362 // whether the index is signed or not. 3363 index = CGF.Builder.CreateIntCast(index, DL.getIndexType(PtrTy), isSigned, 3364 "idx.ext"); 3365 } 3366 3367 // If this is subtraction, negate the index. 3368 if (isSubtraction) 3369 index = CGF.Builder.CreateNeg(index, "idx.neg"); 3370 3371 if (CGF.SanOpts.has(SanitizerKind::ArrayBounds)) 3372 CGF.EmitBoundsCheck(op.E, pointerOperand, index, indexOperand->getType(), 3373 /*Accessed*/ false); 3374 3375 const PointerType *pointerType 3376 = pointerOperand->getType()->getAs<PointerType>(); 3377 if (!pointerType) { 3378 QualType objectType = pointerOperand->getType() 3379 ->castAs<ObjCObjectPointerType>() 3380 ->getPointeeType(); 3381 llvm::Value *objectSize 3382 = CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(objectType)); 3383 3384 index = CGF.Builder.CreateMul(index, objectSize); 3385 3386 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy); 3387 result = CGF.Builder.CreateGEP(result, index, "add.ptr"); 3388 return CGF.Builder.CreateBitCast(result, pointer->getType()); 3389 } 3390 3391 QualType elementType = pointerType->getPointeeType(); 3392 if (const VariableArrayType *vla 3393 = CGF.getContext().getAsVariableArrayType(elementType)) { 3394 // The element count here is the total number of non-VLA elements. 3395 llvm::Value *numElements = CGF.getVLASize(vla).NumElts; 3396 3397 // Effectively, the multiply by the VLA size is part of the GEP. 3398 // GEP indexes are signed, and scaling an index isn't permitted to 3399 // signed-overflow, so we use the same semantics for our explicit 3400 // multiply. We suppress this if overflow is not undefined behavior. 3401 if (CGF.getLangOpts().isSignedOverflowDefined()) { 3402 index = CGF.Builder.CreateMul(index, numElements, "vla.index"); 3403 pointer = CGF.Builder.CreateGEP(pointer, index, "add.ptr"); 3404 } else { 3405 index = CGF.Builder.CreateNSWMul(index, numElements, "vla.index"); 3406 pointer = 3407 CGF.EmitCheckedInBoundsGEP(pointer, index, isSigned, isSubtraction, 3408 op.E->getExprLoc(), "add.ptr"); 3409 } 3410 return pointer; 3411 } 3412 3413 // Explicitly handle GNU void* and function pointer arithmetic extensions. The 3414 // GNU void* casts amount to no-ops since our void* type is i8*, but this is 3415 // future proof. 3416 if (elementType->isVoidType() || elementType->isFunctionType()) { 3417 Value *result = CGF.EmitCastToVoidPtr(pointer); 3418 result = CGF.Builder.CreateGEP(result, index, "add.ptr"); 3419 return CGF.Builder.CreateBitCast(result, pointer->getType()); 3420 } 3421 3422 if (CGF.getLangOpts().isSignedOverflowDefined()) 3423 return CGF.Builder.CreateGEP(pointer, index, "add.ptr"); 3424 3425 return CGF.EmitCheckedInBoundsGEP(pointer, index, isSigned, isSubtraction, 3426 op.E->getExprLoc(), "add.ptr"); 3427 } 3428 3429 // Construct an fmuladd intrinsic to represent a fused mul-add of MulOp and 3430 // Addend. Use negMul and negAdd to negate the first operand of the Mul or 3431 // the add operand respectively. This allows fmuladd to represent a*b-c, or 3432 // c-a*b. Patterns in LLVM should catch the negated forms and translate them to 3433 // efficient operations. 3434 static Value* buildFMulAdd(llvm::Instruction *MulOp, Value *Addend, 3435 const CodeGenFunction &CGF, CGBuilderTy &Builder, 3436 bool negMul, bool negAdd) { 3437 assert(!(negMul && negAdd) && "Only one of negMul and negAdd should be set."); 3438 3439 Value *MulOp0 = MulOp->getOperand(0); 3440 Value *MulOp1 = MulOp->getOperand(1); 3441 if (negMul) 3442 MulOp0 = Builder.CreateFNeg(MulOp0, "neg"); 3443 if (negAdd) 3444 Addend = Builder.CreateFNeg(Addend, "neg"); 3445 3446 Value *FMulAdd = nullptr; 3447 if (Builder.getIsFPConstrained()) { 3448 assert(isa<llvm::ConstrainedFPIntrinsic>(MulOp) && 3449 "Only constrained operation should be created when Builder is in FP " 3450 "constrained mode"); 3451 FMulAdd = Builder.CreateConstrainedFPCall( 3452 CGF.CGM.getIntrinsic(llvm::Intrinsic::experimental_constrained_fmuladd, 3453 Addend->getType()), 3454 {MulOp0, MulOp1, Addend}); 3455 } else { 3456 FMulAdd = Builder.CreateCall( 3457 CGF.CGM.getIntrinsic(llvm::Intrinsic::fmuladd, Addend->getType()), 3458 {MulOp0, MulOp1, Addend}); 3459 } 3460 MulOp->eraseFromParent(); 3461 3462 return FMulAdd; 3463 } 3464 3465 // Check whether it would be legal to emit an fmuladd intrinsic call to 3466 // represent op and if so, build the fmuladd. 3467 // 3468 // Checks that (a) the operation is fusable, and (b) -ffp-contract=on. 3469 // Does NOT check the type of the operation - it's assumed that this function 3470 // will be called from contexts where it's known that the type is contractable. 3471 static Value* tryEmitFMulAdd(const BinOpInfo &op, 3472 const CodeGenFunction &CGF, CGBuilderTy &Builder, 3473 bool isSub=false) { 3474 3475 assert((op.Opcode == BO_Add || op.Opcode == BO_AddAssign || 3476 op.Opcode == BO_Sub || op.Opcode == BO_SubAssign) && 3477 "Only fadd/fsub can be the root of an fmuladd."); 3478 3479 // Check whether this op is marked as fusable. 3480 if (!op.FPFeatures.allowFPContractWithinStatement()) 3481 return nullptr; 3482 3483 // We have a potentially fusable op. Look for a mul on one of the operands. 3484 // Also, make sure that the mul result isn't used directly. In that case, 3485 // there's no point creating a muladd operation. 3486 if (auto *LHSBinOp = dyn_cast<llvm::BinaryOperator>(op.LHS)) { 3487 if (LHSBinOp->getOpcode() == llvm::Instruction::FMul && 3488 LHSBinOp->use_empty()) 3489 return buildFMulAdd(LHSBinOp, op.RHS, CGF, Builder, false, isSub); 3490 } 3491 if (auto *RHSBinOp = dyn_cast<llvm::BinaryOperator>(op.RHS)) { 3492 if (RHSBinOp->getOpcode() == llvm::Instruction::FMul && 3493 RHSBinOp->use_empty()) 3494 return buildFMulAdd(RHSBinOp, op.LHS, CGF, Builder, isSub, false); 3495 } 3496 3497 if (auto *LHSBinOp = dyn_cast<llvm::CallBase>(op.LHS)) { 3498 if (LHSBinOp->getIntrinsicID() == 3499 llvm::Intrinsic::experimental_constrained_fmul && 3500 LHSBinOp->use_empty()) 3501 return buildFMulAdd(LHSBinOp, op.RHS, CGF, Builder, false, isSub); 3502 } 3503 if (auto *RHSBinOp = dyn_cast<llvm::CallBase>(op.RHS)) { 3504 if (RHSBinOp->getIntrinsicID() == 3505 llvm::Intrinsic::experimental_constrained_fmul && 3506 RHSBinOp->use_empty()) 3507 return buildFMulAdd(RHSBinOp, op.LHS, CGF, Builder, isSub, false); 3508 } 3509 3510 return nullptr; 3511 } 3512 3513 Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) { 3514 if (op.LHS->getType()->isPointerTy() || 3515 op.RHS->getType()->isPointerTy()) 3516 return emitPointerArithmetic(CGF, op, CodeGenFunction::NotSubtraction); 3517 3518 if (op.Ty->isSignedIntegerOrEnumerationType()) { 3519 switch (CGF.getLangOpts().getSignedOverflowBehavior()) { 3520 case LangOptions::SOB_Defined: 3521 return Builder.CreateAdd(op.LHS, op.RHS, "add"); 3522 case LangOptions::SOB_Undefined: 3523 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) 3524 return Builder.CreateNSWAdd(op.LHS, op.RHS, "add"); 3525 LLVM_FALLTHROUGH; 3526 case LangOptions::SOB_Trapping: 3527 if (CanElideOverflowCheck(CGF.getContext(), op)) 3528 return Builder.CreateNSWAdd(op.LHS, op.RHS, "add"); 3529 return EmitOverflowCheckedBinOp(op); 3530 } 3531 } 3532 3533 if (op.Ty->isConstantMatrixType()) { 3534 llvm::MatrixBuilder<CGBuilderTy> MB(Builder); 3535 return MB.CreateAdd(op.LHS, op.RHS); 3536 } 3537 3538 if (op.Ty->isUnsignedIntegerType() && 3539 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) && 3540 !CanElideOverflowCheck(CGF.getContext(), op)) 3541 return EmitOverflowCheckedBinOp(op); 3542 3543 if (op.LHS->getType()->isFPOrFPVectorTy()) { 3544 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures); 3545 // Try to form an fmuladd. 3546 if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder)) 3547 return FMulAdd; 3548 3549 return Builder.CreateFAdd(op.LHS, op.RHS, "add"); 3550 } 3551 3552 if (op.isFixedPointOp()) 3553 return EmitFixedPointBinOp(op); 3554 3555 return Builder.CreateAdd(op.LHS, op.RHS, "add"); 3556 } 3557 3558 /// The resulting value must be calculated with exact precision, so the operands 3559 /// may not be the same type. 3560 Value *ScalarExprEmitter::EmitFixedPointBinOp(const BinOpInfo &op) { 3561 using llvm::APSInt; 3562 using llvm::ConstantInt; 3563 3564 // This is either a binary operation where at least one of the operands is 3565 // a fixed-point type, or a unary operation where the operand is a fixed-point 3566 // type. The result type of a binary operation is determined by 3567 // Sema::handleFixedPointConversions(). 3568 QualType ResultTy = op.Ty; 3569 QualType LHSTy, RHSTy; 3570 if (const auto *BinOp = dyn_cast<BinaryOperator>(op.E)) { 3571 RHSTy = BinOp->getRHS()->getType(); 3572 if (const auto *CAO = dyn_cast<CompoundAssignOperator>(BinOp)) { 3573 // For compound assignment, the effective type of the LHS at this point 3574 // is the computation LHS type, not the actual LHS type, and the final 3575 // result type is not the type of the expression but rather the 3576 // computation result type. 3577 LHSTy = CAO->getComputationLHSType(); 3578 ResultTy = CAO->getComputationResultType(); 3579 } else 3580 LHSTy = BinOp->getLHS()->getType(); 3581 } else if (const auto *UnOp = dyn_cast<UnaryOperator>(op.E)) { 3582 LHSTy = UnOp->getSubExpr()->getType(); 3583 RHSTy = UnOp->getSubExpr()->getType(); 3584 } 3585 ASTContext &Ctx = CGF.getContext(); 3586 Value *LHS = op.LHS; 3587 Value *RHS = op.RHS; 3588 3589 auto LHSFixedSema = Ctx.getFixedPointSemantics(LHSTy); 3590 auto RHSFixedSema = Ctx.getFixedPointSemantics(RHSTy); 3591 auto ResultFixedSema = Ctx.getFixedPointSemantics(ResultTy); 3592 auto CommonFixedSema = LHSFixedSema.getCommonSemantics(RHSFixedSema); 3593 3594 // Convert the operands to the full precision type. 3595 Value *FullLHS = EmitFixedPointConversion(LHS, LHSFixedSema, CommonFixedSema, 3596 op.E->getExprLoc()); 3597 Value *FullRHS = EmitFixedPointConversion(RHS, RHSFixedSema, CommonFixedSema, 3598 op.E->getExprLoc()); 3599 3600 // Perform the actual operation. 3601 Value *Result; 3602 switch (op.Opcode) { 3603 case BO_AddAssign: 3604 case BO_Add: { 3605 if (ResultFixedSema.isSaturated()) { 3606 llvm::Intrinsic::ID IID = ResultFixedSema.isSigned() 3607 ? llvm::Intrinsic::sadd_sat 3608 : llvm::Intrinsic::uadd_sat; 3609 Result = Builder.CreateBinaryIntrinsic(IID, FullLHS, FullRHS); 3610 } else { 3611 Result = Builder.CreateAdd(FullLHS, FullRHS); 3612 } 3613 break; 3614 } 3615 case BO_SubAssign: 3616 case BO_Sub: { 3617 if (ResultFixedSema.isSaturated()) { 3618 llvm::Intrinsic::ID IID = ResultFixedSema.isSigned() 3619 ? llvm::Intrinsic::ssub_sat 3620 : llvm::Intrinsic::usub_sat; 3621 Result = Builder.CreateBinaryIntrinsic(IID, FullLHS, FullRHS); 3622 } else { 3623 Result = Builder.CreateSub(FullLHS, FullRHS); 3624 } 3625 break; 3626 } 3627 case BO_MulAssign: 3628 case BO_Mul: { 3629 llvm::Intrinsic::ID IID; 3630 if (ResultFixedSema.isSaturated()) 3631 IID = ResultFixedSema.isSigned() 3632 ? llvm::Intrinsic::smul_fix_sat 3633 : llvm::Intrinsic::umul_fix_sat; 3634 else 3635 IID = ResultFixedSema.isSigned() 3636 ? llvm::Intrinsic::smul_fix 3637 : llvm::Intrinsic::umul_fix; 3638 Result = Builder.CreateIntrinsic(IID, {FullLHS->getType()}, 3639 {FullLHS, FullRHS, Builder.getInt32(CommonFixedSema.getScale())}); 3640 break; 3641 } 3642 case BO_DivAssign: 3643 case BO_Div: { 3644 llvm::Intrinsic::ID IID; 3645 if (ResultFixedSema.isSaturated()) 3646 IID = ResultFixedSema.isSigned() ? llvm::Intrinsic::sdiv_fix_sat 3647 : llvm::Intrinsic::udiv_fix_sat; 3648 else 3649 IID = ResultFixedSema.isSigned() ? llvm::Intrinsic::sdiv_fix 3650 : llvm::Intrinsic::udiv_fix; 3651 Result = Builder.CreateIntrinsic(IID, {FullLHS->getType()}, 3652 {FullLHS, FullRHS, Builder.getInt32(CommonFixedSema.getScale())}); 3653 break; 3654 } 3655 case BO_LT: 3656 return CommonFixedSema.isSigned() ? Builder.CreateICmpSLT(FullLHS, FullRHS) 3657 : Builder.CreateICmpULT(FullLHS, FullRHS); 3658 case BO_GT: 3659 return CommonFixedSema.isSigned() ? Builder.CreateICmpSGT(FullLHS, FullRHS) 3660 : Builder.CreateICmpUGT(FullLHS, FullRHS); 3661 case BO_LE: 3662 return CommonFixedSema.isSigned() ? Builder.CreateICmpSLE(FullLHS, FullRHS) 3663 : Builder.CreateICmpULE(FullLHS, FullRHS); 3664 case BO_GE: 3665 return CommonFixedSema.isSigned() ? Builder.CreateICmpSGE(FullLHS, FullRHS) 3666 : Builder.CreateICmpUGE(FullLHS, FullRHS); 3667 case BO_EQ: 3668 // For equality operations, we assume any padding bits on unsigned types are 3669 // zero'd out. They could be overwritten through non-saturating operations 3670 // that cause overflow, but this leads to undefined behavior. 3671 return Builder.CreateICmpEQ(FullLHS, FullRHS); 3672 case BO_NE: 3673 return Builder.CreateICmpNE(FullLHS, FullRHS); 3674 case BO_Shl: 3675 case BO_Shr: 3676 case BO_Cmp: 3677 case BO_LAnd: 3678 case BO_LOr: 3679 case BO_ShlAssign: 3680 case BO_ShrAssign: 3681 llvm_unreachable("Found unimplemented fixed point binary operation"); 3682 case BO_PtrMemD: 3683 case BO_PtrMemI: 3684 case BO_Rem: 3685 case BO_Xor: 3686 case BO_And: 3687 case BO_Or: 3688 case BO_Assign: 3689 case BO_RemAssign: 3690 case BO_AndAssign: 3691 case BO_XorAssign: 3692 case BO_OrAssign: 3693 case BO_Comma: 3694 llvm_unreachable("Found unsupported binary operation for fixed point types."); 3695 } 3696 3697 // Convert to the result type. 3698 return EmitFixedPointConversion(Result, CommonFixedSema, ResultFixedSema, 3699 op.E->getExprLoc()); 3700 } 3701 3702 Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) { 3703 // The LHS is always a pointer if either side is. 3704 if (!op.LHS->getType()->isPointerTy()) { 3705 if (op.Ty->isSignedIntegerOrEnumerationType()) { 3706 switch (CGF.getLangOpts().getSignedOverflowBehavior()) { 3707 case LangOptions::SOB_Defined: 3708 return Builder.CreateSub(op.LHS, op.RHS, "sub"); 3709 case LangOptions::SOB_Undefined: 3710 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) 3711 return Builder.CreateNSWSub(op.LHS, op.RHS, "sub"); 3712 LLVM_FALLTHROUGH; 3713 case LangOptions::SOB_Trapping: 3714 if (CanElideOverflowCheck(CGF.getContext(), op)) 3715 return Builder.CreateNSWSub(op.LHS, op.RHS, "sub"); 3716 return EmitOverflowCheckedBinOp(op); 3717 } 3718 } 3719 3720 if (op.Ty->isConstantMatrixType()) { 3721 llvm::MatrixBuilder<CGBuilderTy> MB(Builder); 3722 return MB.CreateSub(op.LHS, op.RHS); 3723 } 3724 3725 if (op.Ty->isUnsignedIntegerType() && 3726 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) && 3727 !CanElideOverflowCheck(CGF.getContext(), op)) 3728 return EmitOverflowCheckedBinOp(op); 3729 3730 if (op.LHS->getType()->isFPOrFPVectorTy()) { 3731 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures); 3732 // Try to form an fmuladd. 3733 if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder, true)) 3734 return FMulAdd; 3735 return Builder.CreateFSub(op.LHS, op.RHS, "sub"); 3736 } 3737 3738 if (op.isFixedPointOp()) 3739 return EmitFixedPointBinOp(op); 3740 3741 return Builder.CreateSub(op.LHS, op.RHS, "sub"); 3742 } 3743 3744 // If the RHS is not a pointer, then we have normal pointer 3745 // arithmetic. 3746 if (!op.RHS->getType()->isPointerTy()) 3747 return emitPointerArithmetic(CGF, op, CodeGenFunction::IsSubtraction); 3748 3749 // Otherwise, this is a pointer subtraction. 3750 3751 // Do the raw subtraction part. 3752 llvm::Value *LHS 3753 = Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast"); 3754 llvm::Value *RHS 3755 = Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast"); 3756 Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub"); 3757 3758 // Okay, figure out the element size. 3759 const BinaryOperator *expr = cast<BinaryOperator>(op.E); 3760 QualType elementType = expr->getLHS()->getType()->getPointeeType(); 3761 3762 llvm::Value *divisor = nullptr; 3763 3764 // For a variable-length array, this is going to be non-constant. 3765 if (const VariableArrayType *vla 3766 = CGF.getContext().getAsVariableArrayType(elementType)) { 3767 auto VlaSize = CGF.getVLASize(vla); 3768 elementType = VlaSize.Type; 3769 divisor = VlaSize.NumElts; 3770 3771 // Scale the number of non-VLA elements by the non-VLA element size. 3772 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(elementType); 3773 if (!eltSize.isOne()) 3774 divisor = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), divisor); 3775 3776 // For everything elese, we can just compute it, safe in the 3777 // assumption that Sema won't let anything through that we can't 3778 // safely compute the size of. 3779 } else { 3780 CharUnits elementSize; 3781 // Handle GCC extension for pointer arithmetic on void* and 3782 // function pointer types. 3783 if (elementType->isVoidType() || elementType->isFunctionType()) 3784 elementSize = CharUnits::One(); 3785 else 3786 elementSize = CGF.getContext().getTypeSizeInChars(elementType); 3787 3788 // Don't even emit the divide for element size of 1. 3789 if (elementSize.isOne()) 3790 return diffInChars; 3791 3792 divisor = CGF.CGM.getSize(elementSize); 3793 } 3794 3795 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since 3796 // pointer difference in C is only defined in the case where both operands 3797 // are pointing to elements of an array. 3798 return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div"); 3799 } 3800 3801 Value *ScalarExprEmitter::GetWidthMinusOneValue(Value* LHS,Value* RHS) { 3802 llvm::IntegerType *Ty; 3803 if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(LHS->getType())) 3804 Ty = cast<llvm::IntegerType>(VT->getElementType()); 3805 else 3806 Ty = cast<llvm::IntegerType>(LHS->getType()); 3807 return llvm::ConstantInt::get(RHS->getType(), Ty->getBitWidth() - 1); 3808 } 3809 3810 Value *ScalarExprEmitter::ConstrainShiftValue(Value *LHS, Value *RHS, 3811 const Twine &Name) { 3812 llvm::IntegerType *Ty; 3813 if (auto *VT = dyn_cast<llvm::VectorType>(LHS->getType())) 3814 Ty = cast<llvm::IntegerType>(VT->getElementType()); 3815 else 3816 Ty = cast<llvm::IntegerType>(LHS->getType()); 3817 3818 if (llvm::isPowerOf2_64(Ty->getBitWidth())) 3819 return Builder.CreateAnd(RHS, GetWidthMinusOneValue(LHS, RHS), Name); 3820 3821 return Builder.CreateURem( 3822 RHS, llvm::ConstantInt::get(RHS->getType(), Ty->getBitWidth()), Name); 3823 } 3824 3825 Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) { 3826 // LLVM requires the LHS and RHS to be the same type: promote or truncate the 3827 // RHS to the same size as the LHS. 3828 Value *RHS = Ops.RHS; 3829 if (Ops.LHS->getType() != RHS->getType()) 3830 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom"); 3831 3832 bool SanitizeBase = CGF.SanOpts.has(SanitizerKind::ShiftBase) && 3833 Ops.Ty->hasSignedIntegerRepresentation() && 3834 !CGF.getLangOpts().isSignedOverflowDefined() && 3835 !CGF.getLangOpts().CPlusPlus20; 3836 bool SanitizeExponent = CGF.SanOpts.has(SanitizerKind::ShiftExponent); 3837 // OpenCL 6.3j: shift values are effectively % word size of LHS. 3838 if (CGF.getLangOpts().OpenCL) 3839 RHS = ConstrainShiftValue(Ops.LHS, RHS, "shl.mask"); 3840 else if ((SanitizeBase || SanitizeExponent) && 3841 isa<llvm::IntegerType>(Ops.LHS->getType())) { 3842 CodeGenFunction::SanitizerScope SanScope(&CGF); 3843 SmallVector<std::pair<Value *, SanitizerMask>, 2> Checks; 3844 llvm::Value *WidthMinusOne = GetWidthMinusOneValue(Ops.LHS, Ops.RHS); 3845 llvm::Value *ValidExponent = Builder.CreateICmpULE(Ops.RHS, WidthMinusOne); 3846 3847 if (SanitizeExponent) { 3848 Checks.push_back( 3849 std::make_pair(ValidExponent, SanitizerKind::ShiftExponent)); 3850 } 3851 3852 if (SanitizeBase) { 3853 // Check whether we are shifting any non-zero bits off the top of the 3854 // integer. We only emit this check if exponent is valid - otherwise 3855 // instructions below will have undefined behavior themselves. 3856 llvm::BasicBlock *Orig = Builder.GetInsertBlock(); 3857 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont"); 3858 llvm::BasicBlock *CheckShiftBase = CGF.createBasicBlock("check"); 3859 Builder.CreateCondBr(ValidExponent, CheckShiftBase, Cont); 3860 llvm::Value *PromotedWidthMinusOne = 3861 (RHS == Ops.RHS) ? WidthMinusOne 3862 : GetWidthMinusOneValue(Ops.LHS, RHS); 3863 CGF.EmitBlock(CheckShiftBase); 3864 llvm::Value *BitsShiftedOff = Builder.CreateLShr( 3865 Ops.LHS, Builder.CreateSub(PromotedWidthMinusOne, RHS, "shl.zeros", 3866 /*NUW*/ true, /*NSW*/ true), 3867 "shl.check"); 3868 if (CGF.getLangOpts().CPlusPlus) { 3869 // In C99, we are not permitted to shift a 1 bit into the sign bit. 3870 // Under C++11's rules, shifting a 1 bit into the sign bit is 3871 // OK, but shifting a 1 bit out of it is not. (C89 and C++03 don't 3872 // define signed left shifts, so we use the C99 and C++11 rules there). 3873 llvm::Value *One = llvm::ConstantInt::get(BitsShiftedOff->getType(), 1); 3874 BitsShiftedOff = Builder.CreateLShr(BitsShiftedOff, One); 3875 } 3876 llvm::Value *Zero = llvm::ConstantInt::get(BitsShiftedOff->getType(), 0); 3877 llvm::Value *ValidBase = Builder.CreateICmpEQ(BitsShiftedOff, Zero); 3878 CGF.EmitBlock(Cont); 3879 llvm::PHINode *BaseCheck = Builder.CreatePHI(ValidBase->getType(), 2); 3880 BaseCheck->addIncoming(Builder.getTrue(), Orig); 3881 BaseCheck->addIncoming(ValidBase, CheckShiftBase); 3882 Checks.push_back(std::make_pair(BaseCheck, SanitizerKind::ShiftBase)); 3883 } 3884 3885 assert(!Checks.empty()); 3886 EmitBinOpCheck(Checks, Ops); 3887 } 3888 3889 return Builder.CreateShl(Ops.LHS, RHS, "shl"); 3890 } 3891 3892 Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) { 3893 // LLVM requires the LHS and RHS to be the same type: promote or truncate the 3894 // RHS to the same size as the LHS. 3895 Value *RHS = Ops.RHS; 3896 if (Ops.LHS->getType() != RHS->getType()) 3897 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom"); 3898 3899 // OpenCL 6.3j: shift values are effectively % word size of LHS. 3900 if (CGF.getLangOpts().OpenCL) 3901 RHS = ConstrainShiftValue(Ops.LHS, RHS, "shr.mask"); 3902 else if (CGF.SanOpts.has(SanitizerKind::ShiftExponent) && 3903 isa<llvm::IntegerType>(Ops.LHS->getType())) { 3904 CodeGenFunction::SanitizerScope SanScope(&CGF); 3905 llvm::Value *Valid = 3906 Builder.CreateICmpULE(RHS, GetWidthMinusOneValue(Ops.LHS, RHS)); 3907 EmitBinOpCheck(std::make_pair(Valid, SanitizerKind::ShiftExponent), Ops); 3908 } 3909 3910 if (Ops.Ty->hasUnsignedIntegerRepresentation()) 3911 return Builder.CreateLShr(Ops.LHS, RHS, "shr"); 3912 return Builder.CreateAShr(Ops.LHS, RHS, "shr"); 3913 } 3914 3915 enum IntrinsicType { VCMPEQ, VCMPGT }; 3916 // return corresponding comparison intrinsic for given vector type 3917 static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT, 3918 BuiltinType::Kind ElemKind) { 3919 switch (ElemKind) { 3920 default: llvm_unreachable("unexpected element type"); 3921 case BuiltinType::Char_U: 3922 case BuiltinType::UChar: 3923 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p : 3924 llvm::Intrinsic::ppc_altivec_vcmpgtub_p; 3925 case BuiltinType::Char_S: 3926 case BuiltinType::SChar: 3927 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p : 3928 llvm::Intrinsic::ppc_altivec_vcmpgtsb_p; 3929 case BuiltinType::UShort: 3930 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p : 3931 llvm::Intrinsic::ppc_altivec_vcmpgtuh_p; 3932 case BuiltinType::Short: 3933 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p : 3934 llvm::Intrinsic::ppc_altivec_vcmpgtsh_p; 3935 case BuiltinType::UInt: 3936 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p : 3937 llvm::Intrinsic::ppc_altivec_vcmpgtuw_p; 3938 case BuiltinType::Int: 3939 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p : 3940 llvm::Intrinsic::ppc_altivec_vcmpgtsw_p; 3941 case BuiltinType::ULong: 3942 case BuiltinType::ULongLong: 3943 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequd_p : 3944 llvm::Intrinsic::ppc_altivec_vcmpgtud_p; 3945 case BuiltinType::Long: 3946 case BuiltinType::LongLong: 3947 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequd_p : 3948 llvm::Intrinsic::ppc_altivec_vcmpgtsd_p; 3949 case BuiltinType::Float: 3950 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p : 3951 llvm::Intrinsic::ppc_altivec_vcmpgtfp_p; 3952 case BuiltinType::Double: 3953 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_vsx_xvcmpeqdp_p : 3954 llvm::Intrinsic::ppc_vsx_xvcmpgtdp_p; 3955 } 3956 } 3957 3958 Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E, 3959 llvm::CmpInst::Predicate UICmpOpc, 3960 llvm::CmpInst::Predicate SICmpOpc, 3961 llvm::CmpInst::Predicate FCmpOpc, 3962 bool IsSignaling) { 3963 TestAndClearIgnoreResultAssign(); 3964 Value *Result; 3965 QualType LHSTy = E->getLHS()->getType(); 3966 QualType RHSTy = E->getRHS()->getType(); 3967 if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) { 3968 assert(E->getOpcode() == BO_EQ || 3969 E->getOpcode() == BO_NE); 3970 Value *LHS = CGF.EmitScalarExpr(E->getLHS()); 3971 Value *RHS = CGF.EmitScalarExpr(E->getRHS()); 3972 Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison( 3973 CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE); 3974 } else if (!LHSTy->isAnyComplexType() && !RHSTy->isAnyComplexType()) { 3975 BinOpInfo BOInfo = EmitBinOps(E); 3976 Value *LHS = BOInfo.LHS; 3977 Value *RHS = BOInfo.RHS; 3978 3979 // If AltiVec, the comparison results in a numeric type, so we use 3980 // intrinsics comparing vectors and giving 0 or 1 as a result 3981 if (LHSTy->isVectorType() && !E->getType()->isVectorType()) { 3982 // constants for mapping CR6 register bits to predicate result 3983 enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6; 3984 3985 llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic; 3986 3987 // in several cases vector arguments order will be reversed 3988 Value *FirstVecArg = LHS, 3989 *SecondVecArg = RHS; 3990 3991 QualType ElTy = LHSTy->castAs<VectorType>()->getElementType(); 3992 BuiltinType::Kind ElementKind = ElTy->castAs<BuiltinType>()->getKind(); 3993 3994 switch(E->getOpcode()) { 3995 default: llvm_unreachable("is not a comparison operation"); 3996 case BO_EQ: 3997 CR6 = CR6_LT; 3998 ID = GetIntrinsic(VCMPEQ, ElementKind); 3999 break; 4000 case BO_NE: 4001 CR6 = CR6_EQ; 4002 ID = GetIntrinsic(VCMPEQ, ElementKind); 4003 break; 4004 case BO_LT: 4005 CR6 = CR6_LT; 4006 ID = GetIntrinsic(VCMPGT, ElementKind); 4007 std::swap(FirstVecArg, SecondVecArg); 4008 break; 4009 case BO_GT: 4010 CR6 = CR6_LT; 4011 ID = GetIntrinsic(VCMPGT, ElementKind); 4012 break; 4013 case BO_LE: 4014 if (ElementKind == BuiltinType::Float) { 4015 CR6 = CR6_LT; 4016 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p; 4017 std::swap(FirstVecArg, SecondVecArg); 4018 } 4019 else { 4020 CR6 = CR6_EQ; 4021 ID = GetIntrinsic(VCMPGT, ElementKind); 4022 } 4023 break; 4024 case BO_GE: 4025 if (ElementKind == BuiltinType::Float) { 4026 CR6 = CR6_LT; 4027 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p; 4028 } 4029 else { 4030 CR6 = CR6_EQ; 4031 ID = GetIntrinsic(VCMPGT, ElementKind); 4032 std::swap(FirstVecArg, SecondVecArg); 4033 } 4034 break; 4035 } 4036 4037 Value *CR6Param = Builder.getInt32(CR6); 4038 llvm::Function *F = CGF.CGM.getIntrinsic(ID); 4039 Result = Builder.CreateCall(F, {CR6Param, FirstVecArg, SecondVecArg}); 4040 4041 // The result type of intrinsic may not be same as E->getType(). 4042 // If E->getType() is not BoolTy, EmitScalarConversion will do the 4043 // conversion work. If E->getType() is BoolTy, EmitScalarConversion will 4044 // do nothing, if ResultTy is not i1 at the same time, it will cause 4045 // crash later. 4046 llvm::IntegerType *ResultTy = cast<llvm::IntegerType>(Result->getType()); 4047 if (ResultTy->getBitWidth() > 1 && 4048 E->getType() == CGF.getContext().BoolTy) 4049 Result = Builder.CreateTrunc(Result, Builder.getInt1Ty()); 4050 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType(), 4051 E->getExprLoc()); 4052 } 4053 4054 if (BOInfo.isFixedPointOp()) { 4055 Result = EmitFixedPointBinOp(BOInfo); 4056 } else if (LHS->getType()->isFPOrFPVectorTy()) { 4057 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, BOInfo.FPFeatures); 4058 if (!IsSignaling) 4059 Result = Builder.CreateFCmp(FCmpOpc, LHS, RHS, "cmp"); 4060 else 4061 Result = Builder.CreateFCmpS(FCmpOpc, LHS, RHS, "cmp"); 4062 } else if (LHSTy->hasSignedIntegerRepresentation()) { 4063 Result = Builder.CreateICmp(SICmpOpc, LHS, RHS, "cmp"); 4064 } else { 4065 // Unsigned integers and pointers. 4066 4067 if (CGF.CGM.getCodeGenOpts().StrictVTablePointers && 4068 !isa<llvm::ConstantPointerNull>(LHS) && 4069 !isa<llvm::ConstantPointerNull>(RHS)) { 4070 4071 // Dynamic information is required to be stripped for comparisons, 4072 // because it could leak the dynamic information. Based on comparisons 4073 // of pointers to dynamic objects, the optimizer can replace one pointer 4074 // with another, which might be incorrect in presence of invariant 4075 // groups. Comparison with null is safe because null does not carry any 4076 // dynamic information. 4077 if (LHSTy.mayBeDynamicClass()) 4078 LHS = Builder.CreateStripInvariantGroup(LHS); 4079 if (RHSTy.mayBeDynamicClass()) 4080 RHS = Builder.CreateStripInvariantGroup(RHS); 4081 } 4082 4083 Result = Builder.CreateICmp(UICmpOpc, LHS, RHS, "cmp"); 4084 } 4085 4086 // If this is a vector comparison, sign extend the result to the appropriate 4087 // vector integer type and return it (don't convert to bool). 4088 if (LHSTy->isVectorType()) 4089 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext"); 4090 4091 } else { 4092 // Complex Comparison: can only be an equality comparison. 4093 CodeGenFunction::ComplexPairTy LHS, RHS; 4094 QualType CETy; 4095 if (auto *CTy = LHSTy->getAs<ComplexType>()) { 4096 LHS = CGF.EmitComplexExpr(E->getLHS()); 4097 CETy = CTy->getElementType(); 4098 } else { 4099 LHS.first = Visit(E->getLHS()); 4100 LHS.second = llvm::Constant::getNullValue(LHS.first->getType()); 4101 CETy = LHSTy; 4102 } 4103 if (auto *CTy = RHSTy->getAs<ComplexType>()) { 4104 RHS = CGF.EmitComplexExpr(E->getRHS()); 4105 assert(CGF.getContext().hasSameUnqualifiedType(CETy, 4106 CTy->getElementType()) && 4107 "The element types must always match."); 4108 (void)CTy; 4109 } else { 4110 RHS.first = Visit(E->getRHS()); 4111 RHS.second = llvm::Constant::getNullValue(RHS.first->getType()); 4112 assert(CGF.getContext().hasSameUnqualifiedType(CETy, RHSTy) && 4113 "The element types must always match."); 4114 } 4115 4116 Value *ResultR, *ResultI; 4117 if (CETy->isRealFloatingType()) { 4118 // As complex comparisons can only be equality comparisons, they 4119 // are never signaling comparisons. 4120 ResultR = Builder.CreateFCmp(FCmpOpc, LHS.first, RHS.first, "cmp.r"); 4121 ResultI = Builder.CreateFCmp(FCmpOpc, LHS.second, RHS.second, "cmp.i"); 4122 } else { 4123 // Complex comparisons can only be equality comparisons. As such, signed 4124 // and unsigned opcodes are the same. 4125 ResultR = Builder.CreateICmp(UICmpOpc, LHS.first, RHS.first, "cmp.r"); 4126 ResultI = Builder.CreateICmp(UICmpOpc, LHS.second, RHS.second, "cmp.i"); 4127 } 4128 4129 if (E->getOpcode() == BO_EQ) { 4130 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri"); 4131 } else { 4132 assert(E->getOpcode() == BO_NE && 4133 "Complex comparison other than == or != ?"); 4134 Result = Builder.CreateOr(ResultR, ResultI, "or.ri"); 4135 } 4136 } 4137 4138 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType(), 4139 E->getExprLoc()); 4140 } 4141 4142 Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) { 4143 bool Ignore = TestAndClearIgnoreResultAssign(); 4144 4145 Value *RHS; 4146 LValue LHS; 4147 4148 switch (E->getLHS()->getType().getObjCLifetime()) { 4149 case Qualifiers::OCL_Strong: 4150 std::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore); 4151 break; 4152 4153 case Qualifiers::OCL_Autoreleasing: 4154 std::tie(LHS, RHS) = CGF.EmitARCStoreAutoreleasing(E); 4155 break; 4156 4157 case Qualifiers::OCL_ExplicitNone: 4158 std::tie(LHS, RHS) = CGF.EmitARCStoreUnsafeUnretained(E, Ignore); 4159 break; 4160 4161 case Qualifiers::OCL_Weak: 4162 RHS = Visit(E->getRHS()); 4163 LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store); 4164 RHS = CGF.EmitARCStoreWeak(LHS.getAddress(CGF), RHS, Ignore); 4165 break; 4166 4167 case Qualifiers::OCL_None: 4168 // __block variables need to have the rhs evaluated first, plus 4169 // this should improve codegen just a little. 4170 RHS = Visit(E->getRHS()); 4171 LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store); 4172 4173 // Store the value into the LHS. Bit-fields are handled specially 4174 // because the result is altered by the store, i.e., [C99 6.5.16p1] 4175 // 'An assignment expression has the value of the left operand after 4176 // the assignment...'. 4177 if (LHS.isBitField()) { 4178 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, &RHS); 4179 } else { 4180 CGF.EmitNullabilityCheck(LHS, RHS, E->getExprLoc()); 4181 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS); 4182 } 4183 } 4184 4185 // If the result is clearly ignored, return now. 4186 if (Ignore) 4187 return nullptr; 4188 4189 // The result of an assignment in C is the assigned r-value. 4190 if (!CGF.getLangOpts().CPlusPlus) 4191 return RHS; 4192 4193 // If the lvalue is non-volatile, return the computed value of the assignment. 4194 if (!LHS.isVolatileQualified()) 4195 return RHS; 4196 4197 // Otherwise, reload the value. 4198 return EmitLoadOfLValue(LHS, E->getExprLoc()); 4199 } 4200 4201 Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) { 4202 // Perform vector logical and on comparisons with zero vectors. 4203 if (E->getType()->isVectorType()) { 4204 CGF.incrementProfileCounter(E); 4205 4206 Value *LHS = Visit(E->getLHS()); 4207 Value *RHS = Visit(E->getRHS()); 4208 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType()); 4209 if (LHS->getType()->isFPOrFPVectorTy()) { 4210 CodeGenFunction::CGFPOptionsRAII FPOptsRAII( 4211 CGF, E->getFPFeatures(CGF.getLangOpts())); 4212 LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp"); 4213 RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp"); 4214 } else { 4215 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp"); 4216 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp"); 4217 } 4218 Value *And = Builder.CreateAnd(LHS, RHS); 4219 return Builder.CreateSExt(And, ConvertType(E->getType()), "sext"); 4220 } 4221 4222 llvm::Type *ResTy = ConvertType(E->getType()); 4223 4224 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0. 4225 // If we have 1 && X, just emit X without inserting the control flow. 4226 bool LHSCondVal; 4227 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) { 4228 if (LHSCondVal) { // If we have 1 && X, just emit X. 4229 CGF.incrementProfileCounter(E); 4230 4231 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 4232 // ZExt result to int or bool. 4233 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext"); 4234 } 4235 4236 // 0 && RHS: If it is safe, just elide the RHS, and return 0/false. 4237 if (!CGF.ContainsLabel(E->getRHS())) 4238 return llvm::Constant::getNullValue(ResTy); 4239 } 4240 4241 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end"); 4242 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs"); 4243 4244 CodeGenFunction::ConditionalEvaluation eval(CGF); 4245 4246 // Branch on the LHS first. If it is false, go to the failure (cont) block. 4247 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock, 4248 CGF.getProfileCount(E->getRHS())); 4249 4250 // Any edges into the ContBlock are now from an (indeterminate number of) 4251 // edges from this first condition. All of these values will be false. Start 4252 // setting up the PHI node in the Cont Block for this. 4253 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2, 4254 "", ContBlock); 4255 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock); 4256 PI != PE; ++PI) 4257 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI); 4258 4259 eval.begin(CGF); 4260 CGF.EmitBlock(RHSBlock); 4261 CGF.incrementProfileCounter(E); 4262 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 4263 eval.end(CGF); 4264 4265 // Reaquire the RHS block, as there may be subblocks inserted. 4266 RHSBlock = Builder.GetInsertBlock(); 4267 4268 // Emit an unconditional branch from this block to ContBlock. 4269 { 4270 // There is no need to emit line number for unconditional branch. 4271 auto NL = ApplyDebugLocation::CreateEmpty(CGF); 4272 CGF.EmitBlock(ContBlock); 4273 } 4274 // Insert an entry into the phi node for the edge with the value of RHSCond. 4275 PN->addIncoming(RHSCond, RHSBlock); 4276 4277 // Artificial location to preserve the scope information 4278 { 4279 auto NL = ApplyDebugLocation::CreateArtificial(CGF); 4280 PN->setDebugLoc(Builder.getCurrentDebugLocation()); 4281 } 4282 4283 // ZExt result to int. 4284 return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext"); 4285 } 4286 4287 Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) { 4288 // Perform vector logical or on comparisons with zero vectors. 4289 if (E->getType()->isVectorType()) { 4290 CGF.incrementProfileCounter(E); 4291 4292 Value *LHS = Visit(E->getLHS()); 4293 Value *RHS = Visit(E->getRHS()); 4294 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType()); 4295 if (LHS->getType()->isFPOrFPVectorTy()) { 4296 CodeGenFunction::CGFPOptionsRAII FPOptsRAII( 4297 CGF, E->getFPFeatures(CGF.getLangOpts())); 4298 LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp"); 4299 RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp"); 4300 } else { 4301 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp"); 4302 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp"); 4303 } 4304 Value *Or = Builder.CreateOr(LHS, RHS); 4305 return Builder.CreateSExt(Or, ConvertType(E->getType()), "sext"); 4306 } 4307 4308 llvm::Type *ResTy = ConvertType(E->getType()); 4309 4310 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1. 4311 // If we have 0 || X, just emit X without inserting the control flow. 4312 bool LHSCondVal; 4313 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) { 4314 if (!LHSCondVal) { // If we have 0 || X, just emit X. 4315 CGF.incrementProfileCounter(E); 4316 4317 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 4318 // ZExt result to int or bool. 4319 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext"); 4320 } 4321 4322 // 1 || RHS: If it is safe, just elide the RHS, and return 1/true. 4323 if (!CGF.ContainsLabel(E->getRHS())) 4324 return llvm::ConstantInt::get(ResTy, 1); 4325 } 4326 4327 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end"); 4328 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs"); 4329 4330 CodeGenFunction::ConditionalEvaluation eval(CGF); 4331 4332 // Branch on the LHS first. If it is true, go to the success (cont) block. 4333 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock, 4334 CGF.getCurrentProfileCount() - 4335 CGF.getProfileCount(E->getRHS())); 4336 4337 // Any edges into the ContBlock are now from an (indeterminate number of) 4338 // edges from this first condition. All of these values will be true. Start 4339 // setting up the PHI node in the Cont Block for this. 4340 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2, 4341 "", ContBlock); 4342 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock); 4343 PI != PE; ++PI) 4344 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI); 4345 4346 eval.begin(CGF); 4347 4348 // Emit the RHS condition as a bool value. 4349 CGF.EmitBlock(RHSBlock); 4350 CGF.incrementProfileCounter(E); 4351 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 4352 4353 eval.end(CGF); 4354 4355 // Reaquire the RHS block, as there may be subblocks inserted. 4356 RHSBlock = Builder.GetInsertBlock(); 4357 4358 // Emit an unconditional branch from this block to ContBlock. Insert an entry 4359 // into the phi node for the edge with the value of RHSCond. 4360 CGF.EmitBlock(ContBlock); 4361 PN->addIncoming(RHSCond, RHSBlock); 4362 4363 // ZExt result to int. 4364 return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext"); 4365 } 4366 4367 Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) { 4368 CGF.EmitIgnoredExpr(E->getLHS()); 4369 CGF.EnsureInsertPoint(); 4370 return Visit(E->getRHS()); 4371 } 4372 4373 //===----------------------------------------------------------------------===// 4374 // Other Operators 4375 //===----------------------------------------------------------------------===// 4376 4377 /// isCheapEnoughToEvaluateUnconditionally - Return true if the specified 4378 /// expression is cheap enough and side-effect-free enough to evaluate 4379 /// unconditionally instead of conditionally. This is used to convert control 4380 /// flow into selects in some cases. 4381 static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E, 4382 CodeGenFunction &CGF) { 4383 // Anything that is an integer or floating point constant is fine. 4384 return E->IgnoreParens()->isEvaluatable(CGF.getContext()); 4385 4386 // Even non-volatile automatic variables can't be evaluated unconditionally. 4387 // Referencing a thread_local may cause non-trivial initialization work to 4388 // occur. If we're inside a lambda and one of the variables is from the scope 4389 // outside the lambda, that function may have returned already. Reading its 4390 // locals is a bad idea. Also, these reads may introduce races there didn't 4391 // exist in the source-level program. 4392 } 4393 4394 4395 Value *ScalarExprEmitter:: 4396 VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) { 4397 TestAndClearIgnoreResultAssign(); 4398 4399 // Bind the common expression if necessary. 4400 CodeGenFunction::OpaqueValueMapping binding(CGF, E); 4401 4402 Expr *condExpr = E->getCond(); 4403 Expr *lhsExpr = E->getTrueExpr(); 4404 Expr *rhsExpr = E->getFalseExpr(); 4405 4406 // If the condition constant folds and can be elided, try to avoid emitting 4407 // the condition and the dead arm. 4408 bool CondExprBool; 4409 if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) { 4410 Expr *live = lhsExpr, *dead = rhsExpr; 4411 if (!CondExprBool) std::swap(live, dead); 4412 4413 // If the dead side doesn't have labels we need, just emit the Live part. 4414 if (!CGF.ContainsLabel(dead)) { 4415 if (CondExprBool) 4416 CGF.incrementProfileCounter(E); 4417 Value *Result = Visit(live); 4418 4419 // If the live part is a throw expression, it acts like it has a void 4420 // type, so evaluating it returns a null Value*. However, a conditional 4421 // with non-void type must return a non-null Value*. 4422 if (!Result && !E->getType()->isVoidType()) 4423 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType())); 4424 4425 return Result; 4426 } 4427 } 4428 4429 // OpenCL: If the condition is a vector, we can treat this condition like 4430 // the select function. 4431 if ((CGF.getLangOpts().OpenCL && condExpr->getType()->isVectorType()) || 4432 condExpr->getType()->isExtVectorType()) { 4433 CGF.incrementProfileCounter(E); 4434 4435 llvm::Value *CondV = CGF.EmitScalarExpr(condExpr); 4436 llvm::Value *LHS = Visit(lhsExpr); 4437 llvm::Value *RHS = Visit(rhsExpr); 4438 4439 llvm::Type *condType = ConvertType(condExpr->getType()); 4440 llvm::VectorType *vecTy = cast<llvm::VectorType>(condType); 4441 4442 unsigned numElem = vecTy->getNumElements(); 4443 llvm::Type *elemType = vecTy->getElementType(); 4444 4445 llvm::Value *zeroVec = llvm::Constant::getNullValue(vecTy); 4446 llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec); 4447 llvm::Value *tmp = Builder.CreateSExt( 4448 TestMSB, llvm::FixedVectorType::get(elemType, numElem), "sext"); 4449 llvm::Value *tmp2 = Builder.CreateNot(tmp); 4450 4451 // Cast float to int to perform ANDs if necessary. 4452 llvm::Value *RHSTmp = RHS; 4453 llvm::Value *LHSTmp = LHS; 4454 bool wasCast = false; 4455 llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType()); 4456 if (rhsVTy->getElementType()->isFloatingPointTy()) { 4457 RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType()); 4458 LHSTmp = Builder.CreateBitCast(LHS, tmp->getType()); 4459 wasCast = true; 4460 } 4461 4462 llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2); 4463 llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp); 4464 llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond"); 4465 if (wasCast) 4466 tmp5 = Builder.CreateBitCast(tmp5, RHS->getType()); 4467 4468 return tmp5; 4469 } 4470 4471 if (condExpr->getType()->isVectorType()) { 4472 CGF.incrementProfileCounter(E); 4473 4474 llvm::Value *CondV = CGF.EmitScalarExpr(condExpr); 4475 llvm::Value *LHS = Visit(lhsExpr); 4476 llvm::Value *RHS = Visit(rhsExpr); 4477 4478 llvm::Type *CondType = ConvertType(condExpr->getType()); 4479 auto *VecTy = cast<llvm::VectorType>(CondType); 4480 llvm::Value *ZeroVec = llvm::Constant::getNullValue(VecTy); 4481 4482 CondV = Builder.CreateICmpNE(CondV, ZeroVec, "vector_cond"); 4483 return Builder.CreateSelect(CondV, LHS, RHS, "vector_select"); 4484 } 4485 4486 // If this is a really simple expression (like x ? 4 : 5), emit this as a 4487 // select instead of as control flow. We can only do this if it is cheap and 4488 // safe to evaluate the LHS and RHS unconditionally. 4489 if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) && 4490 isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) { 4491 llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr); 4492 llvm::Value *StepV = Builder.CreateZExtOrBitCast(CondV, CGF.Int64Ty); 4493 4494 CGF.incrementProfileCounter(E, StepV); 4495 4496 llvm::Value *LHS = Visit(lhsExpr); 4497 llvm::Value *RHS = Visit(rhsExpr); 4498 if (!LHS) { 4499 // If the conditional has void type, make sure we return a null Value*. 4500 assert(!RHS && "LHS and RHS types must match"); 4501 return nullptr; 4502 } 4503 return Builder.CreateSelect(CondV, LHS, RHS, "cond"); 4504 } 4505 4506 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true"); 4507 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false"); 4508 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end"); 4509 4510 CodeGenFunction::ConditionalEvaluation eval(CGF); 4511 CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock, 4512 CGF.getProfileCount(lhsExpr)); 4513 4514 CGF.EmitBlock(LHSBlock); 4515 CGF.incrementProfileCounter(E); 4516 eval.begin(CGF); 4517 Value *LHS = Visit(lhsExpr); 4518 eval.end(CGF); 4519 4520 LHSBlock = Builder.GetInsertBlock(); 4521 Builder.CreateBr(ContBlock); 4522 4523 CGF.EmitBlock(RHSBlock); 4524 eval.begin(CGF); 4525 Value *RHS = Visit(rhsExpr); 4526 eval.end(CGF); 4527 4528 RHSBlock = Builder.GetInsertBlock(); 4529 CGF.EmitBlock(ContBlock); 4530 4531 // If the LHS or RHS is a throw expression, it will be legitimately null. 4532 if (!LHS) 4533 return RHS; 4534 if (!RHS) 4535 return LHS; 4536 4537 // Create a PHI node for the real part. 4538 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond"); 4539 PN->addIncoming(LHS, LHSBlock); 4540 PN->addIncoming(RHS, RHSBlock); 4541 return PN; 4542 } 4543 4544 Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) { 4545 return Visit(E->getChosenSubExpr()); 4546 } 4547 4548 Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) { 4549 QualType Ty = VE->getType(); 4550 4551 if (Ty->isVariablyModifiedType()) 4552 CGF.EmitVariablyModifiedType(Ty); 4553 4554 Address ArgValue = Address::invalid(); 4555 Address ArgPtr = CGF.EmitVAArg(VE, ArgValue); 4556 4557 llvm::Type *ArgTy = ConvertType(VE->getType()); 4558 4559 // If EmitVAArg fails, emit an error. 4560 if (!ArgPtr.isValid()) { 4561 CGF.ErrorUnsupported(VE, "va_arg expression"); 4562 return llvm::UndefValue::get(ArgTy); 4563 } 4564 4565 // FIXME Volatility. 4566 llvm::Value *Val = Builder.CreateLoad(ArgPtr); 4567 4568 // If EmitVAArg promoted the type, we must truncate it. 4569 if (ArgTy != Val->getType()) { 4570 if (ArgTy->isPointerTy() && !Val->getType()->isPointerTy()) 4571 Val = Builder.CreateIntToPtr(Val, ArgTy); 4572 else 4573 Val = Builder.CreateTrunc(Val, ArgTy); 4574 } 4575 4576 return Val; 4577 } 4578 4579 Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) { 4580 return CGF.EmitBlockLiteral(block); 4581 } 4582 4583 // Convert a vec3 to vec4, or vice versa. 4584 static Value *ConvertVec3AndVec4(CGBuilderTy &Builder, CodeGenFunction &CGF, 4585 Value *Src, unsigned NumElementsDst) { 4586 llvm::Value *UnV = llvm::UndefValue::get(Src->getType()); 4587 static constexpr int Mask[] = {0, 1, 2, -1}; 4588 return Builder.CreateShuffleVector(Src, UnV, 4589 llvm::makeArrayRef(Mask, NumElementsDst)); 4590 } 4591 4592 // Create cast instructions for converting LLVM value \p Src to LLVM type \p 4593 // DstTy. \p Src has the same size as \p DstTy. Both are single value types 4594 // but could be scalar or vectors of different lengths, and either can be 4595 // pointer. 4596 // There are 4 cases: 4597 // 1. non-pointer -> non-pointer : needs 1 bitcast 4598 // 2. pointer -> pointer : needs 1 bitcast or addrspacecast 4599 // 3. pointer -> non-pointer 4600 // a) pointer -> intptr_t : needs 1 ptrtoint 4601 // b) pointer -> non-intptr_t : needs 1 ptrtoint then 1 bitcast 4602 // 4. non-pointer -> pointer 4603 // a) intptr_t -> pointer : needs 1 inttoptr 4604 // b) non-intptr_t -> pointer : needs 1 bitcast then 1 inttoptr 4605 // Note: for cases 3b and 4b two casts are required since LLVM casts do not 4606 // allow casting directly between pointer types and non-integer non-pointer 4607 // types. 4608 static Value *createCastsForTypeOfSameSize(CGBuilderTy &Builder, 4609 const llvm::DataLayout &DL, 4610 Value *Src, llvm::Type *DstTy, 4611 StringRef Name = "") { 4612 auto SrcTy = Src->getType(); 4613 4614 // Case 1. 4615 if (!SrcTy->isPointerTy() && !DstTy->isPointerTy()) 4616 return Builder.CreateBitCast(Src, DstTy, Name); 4617 4618 // Case 2. 4619 if (SrcTy->isPointerTy() && DstTy->isPointerTy()) 4620 return Builder.CreatePointerBitCastOrAddrSpaceCast(Src, DstTy, Name); 4621 4622 // Case 3. 4623 if (SrcTy->isPointerTy() && !DstTy->isPointerTy()) { 4624 // Case 3b. 4625 if (!DstTy->isIntegerTy()) 4626 Src = Builder.CreatePtrToInt(Src, DL.getIntPtrType(SrcTy)); 4627 // Cases 3a and 3b. 4628 return Builder.CreateBitOrPointerCast(Src, DstTy, Name); 4629 } 4630 4631 // Case 4b. 4632 if (!SrcTy->isIntegerTy()) 4633 Src = Builder.CreateBitCast(Src, DL.getIntPtrType(DstTy)); 4634 // Cases 4a and 4b. 4635 return Builder.CreateIntToPtr(Src, DstTy, Name); 4636 } 4637 4638 Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) { 4639 Value *Src = CGF.EmitScalarExpr(E->getSrcExpr()); 4640 llvm::Type *DstTy = ConvertType(E->getType()); 4641 4642 llvm::Type *SrcTy = Src->getType(); 4643 unsigned NumElementsSrc = isa<llvm::VectorType>(SrcTy) ? 4644 cast<llvm::VectorType>(SrcTy)->getNumElements() : 0; 4645 unsigned NumElementsDst = isa<llvm::VectorType>(DstTy) ? 4646 cast<llvm::VectorType>(DstTy)->getNumElements() : 0; 4647 4648 // Going from vec3 to non-vec3 is a special case and requires a shuffle 4649 // vector to get a vec4, then a bitcast if the target type is different. 4650 if (NumElementsSrc == 3 && NumElementsDst != 3) { 4651 Src = ConvertVec3AndVec4(Builder, CGF, Src, 4); 4652 4653 if (!CGF.CGM.getCodeGenOpts().PreserveVec3Type) { 4654 Src = createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(), Src, 4655 DstTy); 4656 } 4657 4658 Src->setName("astype"); 4659 return Src; 4660 } 4661 4662 // Going from non-vec3 to vec3 is a special case and requires a bitcast 4663 // to vec4 if the original type is not vec4, then a shuffle vector to 4664 // get a vec3. 4665 if (NumElementsSrc != 3 && NumElementsDst == 3) { 4666 if (!CGF.CGM.getCodeGenOpts().PreserveVec3Type) { 4667 auto *Vec4Ty = llvm::FixedVectorType::get( 4668 cast<llvm::VectorType>(DstTy)->getElementType(), 4); 4669 Src = createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(), Src, 4670 Vec4Ty); 4671 } 4672 4673 Src = ConvertVec3AndVec4(Builder, CGF, Src, 3); 4674 Src->setName("astype"); 4675 return Src; 4676 } 4677 4678 return createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(), 4679 Src, DstTy, "astype"); 4680 } 4681 4682 Value *ScalarExprEmitter::VisitAtomicExpr(AtomicExpr *E) { 4683 return CGF.EmitAtomicExpr(E).getScalarVal(); 4684 } 4685 4686 //===----------------------------------------------------------------------===// 4687 // Entry Point into this File 4688 //===----------------------------------------------------------------------===// 4689 4690 /// Emit the computation of the specified expression of scalar type, ignoring 4691 /// the result. 4692 Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) { 4693 assert(E && hasScalarEvaluationKind(E->getType()) && 4694 "Invalid scalar expression to emit"); 4695 4696 return ScalarExprEmitter(*this, IgnoreResultAssign) 4697 .Visit(const_cast<Expr *>(E)); 4698 } 4699 4700 /// Emit a conversion from the specified type to the specified destination type, 4701 /// both of which are LLVM scalar types. 4702 Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy, 4703 QualType DstTy, 4704 SourceLocation Loc) { 4705 assert(hasScalarEvaluationKind(SrcTy) && hasScalarEvaluationKind(DstTy) && 4706 "Invalid scalar expression to emit"); 4707 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy, Loc); 4708 } 4709 4710 /// Emit a conversion from the specified complex type to the specified 4711 /// destination type, where the destination type is an LLVM scalar type. 4712 Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src, 4713 QualType SrcTy, 4714 QualType DstTy, 4715 SourceLocation Loc) { 4716 assert(SrcTy->isAnyComplexType() && hasScalarEvaluationKind(DstTy) && 4717 "Invalid complex -> scalar conversion"); 4718 return ScalarExprEmitter(*this) 4719 .EmitComplexToScalarConversion(Src, SrcTy, DstTy, Loc); 4720 } 4721 4722 4723 llvm::Value *CodeGenFunction:: 4724 EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, 4725 bool isInc, bool isPre) { 4726 return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre); 4727 } 4728 4729 LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) { 4730 // object->isa or (*object).isa 4731 // Generate code as for: *(Class*)object 4732 4733 Expr *BaseExpr = E->getBase(); 4734 Address Addr = Address::invalid(); 4735 if (BaseExpr->isRValue()) { 4736 Addr = Address(EmitScalarExpr(BaseExpr), getPointerAlign()); 4737 } else { 4738 Addr = EmitLValue(BaseExpr).getAddress(*this); 4739 } 4740 4741 // Cast the address to Class*. 4742 Addr = Builder.CreateElementBitCast(Addr, ConvertType(E->getType())); 4743 return MakeAddrLValue(Addr, E->getType()); 4744 } 4745 4746 4747 LValue CodeGenFunction::EmitCompoundAssignmentLValue( 4748 const CompoundAssignOperator *E) { 4749 ScalarExprEmitter Scalar(*this); 4750 Value *Result = nullptr; 4751 switch (E->getOpcode()) { 4752 #define COMPOUND_OP(Op) \ 4753 case BO_##Op##Assign: \ 4754 return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \ 4755 Result) 4756 COMPOUND_OP(Mul); 4757 COMPOUND_OP(Div); 4758 COMPOUND_OP(Rem); 4759 COMPOUND_OP(Add); 4760 COMPOUND_OP(Sub); 4761 COMPOUND_OP(Shl); 4762 COMPOUND_OP(Shr); 4763 COMPOUND_OP(And); 4764 COMPOUND_OP(Xor); 4765 COMPOUND_OP(Or); 4766 #undef COMPOUND_OP 4767 4768 case BO_PtrMemD: 4769 case BO_PtrMemI: 4770 case BO_Mul: 4771 case BO_Div: 4772 case BO_Rem: 4773 case BO_Add: 4774 case BO_Sub: 4775 case BO_Shl: 4776 case BO_Shr: 4777 case BO_LT: 4778 case BO_GT: 4779 case BO_LE: 4780 case BO_GE: 4781 case BO_EQ: 4782 case BO_NE: 4783 case BO_Cmp: 4784 case BO_And: 4785 case BO_Xor: 4786 case BO_Or: 4787 case BO_LAnd: 4788 case BO_LOr: 4789 case BO_Assign: 4790 case BO_Comma: 4791 llvm_unreachable("Not valid compound assignment operators"); 4792 } 4793 4794 llvm_unreachable("Unhandled compound assignment operator"); 4795 } 4796 4797 struct GEPOffsetAndOverflow { 4798 // The total (signed) byte offset for the GEP. 4799 llvm::Value *TotalOffset; 4800 // The offset overflow flag - true if the total offset overflows. 4801 llvm::Value *OffsetOverflows; 4802 }; 4803 4804 /// Evaluate given GEPVal, which is either an inbounds GEP, or a constant, 4805 /// and compute the total offset it applies from it's base pointer BasePtr. 4806 /// Returns offset in bytes and a boolean flag whether an overflow happened 4807 /// during evaluation. 4808 static GEPOffsetAndOverflow EmitGEPOffsetInBytes(Value *BasePtr, Value *GEPVal, 4809 llvm::LLVMContext &VMContext, 4810 CodeGenModule &CGM, 4811 CGBuilderTy &Builder) { 4812 const auto &DL = CGM.getDataLayout(); 4813 4814 // The total (signed) byte offset for the GEP. 4815 llvm::Value *TotalOffset = nullptr; 4816 4817 // Was the GEP already reduced to a constant? 4818 if (isa<llvm::Constant>(GEPVal)) { 4819 // Compute the offset by casting both pointers to integers and subtracting: 4820 // GEPVal = BasePtr + ptr(Offset) <--> Offset = int(GEPVal) - int(BasePtr) 4821 Value *BasePtr_int = 4822 Builder.CreatePtrToInt(BasePtr, DL.getIntPtrType(BasePtr->getType())); 4823 Value *GEPVal_int = 4824 Builder.CreatePtrToInt(GEPVal, DL.getIntPtrType(GEPVal->getType())); 4825 TotalOffset = Builder.CreateSub(GEPVal_int, BasePtr_int); 4826 return {TotalOffset, /*OffsetOverflows=*/Builder.getFalse()}; 4827 } 4828 4829 auto *GEP = cast<llvm::GEPOperator>(GEPVal); 4830 assert(GEP->getPointerOperand() == BasePtr && 4831 "BasePtr must be the the base of the GEP."); 4832 assert(GEP->isInBounds() && "Expected inbounds GEP"); 4833 4834 auto *IntPtrTy = DL.getIntPtrType(GEP->getPointerOperandType()); 4835 4836 // Grab references to the signed add/mul overflow intrinsics for intptr_t. 4837 auto *Zero = llvm::ConstantInt::getNullValue(IntPtrTy); 4838 auto *SAddIntrinsic = 4839 CGM.getIntrinsic(llvm::Intrinsic::sadd_with_overflow, IntPtrTy); 4840 auto *SMulIntrinsic = 4841 CGM.getIntrinsic(llvm::Intrinsic::smul_with_overflow, IntPtrTy); 4842 4843 // The offset overflow flag - true if the total offset overflows. 4844 llvm::Value *OffsetOverflows = Builder.getFalse(); 4845 4846 /// Return the result of the given binary operation. 4847 auto eval = [&](BinaryOperator::Opcode Opcode, llvm::Value *LHS, 4848 llvm::Value *RHS) -> llvm::Value * { 4849 assert((Opcode == BO_Add || Opcode == BO_Mul) && "Can't eval binop"); 4850 4851 // If the operands are constants, return a constant result. 4852 if (auto *LHSCI = dyn_cast<llvm::ConstantInt>(LHS)) { 4853 if (auto *RHSCI = dyn_cast<llvm::ConstantInt>(RHS)) { 4854 llvm::APInt N; 4855 bool HasOverflow = mayHaveIntegerOverflow(LHSCI, RHSCI, Opcode, 4856 /*Signed=*/true, N); 4857 if (HasOverflow) 4858 OffsetOverflows = Builder.getTrue(); 4859 return llvm::ConstantInt::get(VMContext, N); 4860 } 4861 } 4862 4863 // Otherwise, compute the result with checked arithmetic. 4864 auto *ResultAndOverflow = Builder.CreateCall( 4865 (Opcode == BO_Add) ? SAddIntrinsic : SMulIntrinsic, {LHS, RHS}); 4866 OffsetOverflows = Builder.CreateOr( 4867 Builder.CreateExtractValue(ResultAndOverflow, 1), OffsetOverflows); 4868 return Builder.CreateExtractValue(ResultAndOverflow, 0); 4869 }; 4870 4871 // Determine the total byte offset by looking at each GEP operand. 4872 for (auto GTI = llvm::gep_type_begin(GEP), GTE = llvm::gep_type_end(GEP); 4873 GTI != GTE; ++GTI) { 4874 llvm::Value *LocalOffset; 4875 auto *Index = GTI.getOperand(); 4876 // Compute the local offset contributed by this indexing step: 4877 if (auto *STy = GTI.getStructTypeOrNull()) { 4878 // For struct indexing, the local offset is the byte position of the 4879 // specified field. 4880 unsigned FieldNo = cast<llvm::ConstantInt>(Index)->getZExtValue(); 4881 LocalOffset = llvm::ConstantInt::get( 4882 IntPtrTy, DL.getStructLayout(STy)->getElementOffset(FieldNo)); 4883 } else { 4884 // Otherwise this is array-like indexing. The local offset is the index 4885 // multiplied by the element size. 4886 auto *ElementSize = llvm::ConstantInt::get( 4887 IntPtrTy, DL.getTypeAllocSize(GTI.getIndexedType())); 4888 auto *IndexS = Builder.CreateIntCast(Index, IntPtrTy, /*isSigned=*/true); 4889 LocalOffset = eval(BO_Mul, ElementSize, IndexS); 4890 } 4891 4892 // If this is the first offset, set it as the total offset. Otherwise, add 4893 // the local offset into the running total. 4894 if (!TotalOffset || TotalOffset == Zero) 4895 TotalOffset = LocalOffset; 4896 else 4897 TotalOffset = eval(BO_Add, TotalOffset, LocalOffset); 4898 } 4899 4900 return {TotalOffset, OffsetOverflows}; 4901 } 4902 4903 Value * 4904 CodeGenFunction::EmitCheckedInBoundsGEP(Value *Ptr, ArrayRef<Value *> IdxList, 4905 bool SignedIndices, bool IsSubtraction, 4906 SourceLocation Loc, const Twine &Name) { 4907 Value *GEPVal = Builder.CreateInBoundsGEP(Ptr, IdxList, Name); 4908 4909 // If the pointer overflow sanitizer isn't enabled, do nothing. 4910 if (!SanOpts.has(SanitizerKind::PointerOverflow)) 4911 return GEPVal; 4912 4913 llvm::Type *PtrTy = Ptr->getType(); 4914 4915 // Perform nullptr-and-offset check unless the nullptr is defined. 4916 bool PerformNullCheck = !NullPointerIsDefined( 4917 Builder.GetInsertBlock()->getParent(), PtrTy->getPointerAddressSpace()); 4918 // Check for overflows unless the GEP got constant-folded, 4919 // and only in the default address space 4920 bool PerformOverflowCheck = 4921 !isa<llvm::Constant>(GEPVal) && PtrTy->getPointerAddressSpace() == 0; 4922 4923 if (!(PerformNullCheck || PerformOverflowCheck)) 4924 return GEPVal; 4925 4926 const auto &DL = CGM.getDataLayout(); 4927 4928 SanitizerScope SanScope(this); 4929 llvm::Type *IntPtrTy = DL.getIntPtrType(PtrTy); 4930 4931 GEPOffsetAndOverflow EvaluatedGEP = 4932 EmitGEPOffsetInBytes(Ptr, GEPVal, getLLVMContext(), CGM, Builder); 4933 4934 assert((!isa<llvm::Constant>(EvaluatedGEP.TotalOffset) || 4935 EvaluatedGEP.OffsetOverflows == Builder.getFalse()) && 4936 "If the offset got constant-folded, we don't expect that there was an " 4937 "overflow."); 4938 4939 auto *Zero = llvm::ConstantInt::getNullValue(IntPtrTy); 4940 4941 // Common case: if the total offset is zero, and we are using C++ semantics, 4942 // where nullptr+0 is defined, don't emit a check. 4943 if (EvaluatedGEP.TotalOffset == Zero && CGM.getLangOpts().CPlusPlus) 4944 return GEPVal; 4945 4946 // Now that we've computed the total offset, add it to the base pointer (with 4947 // wrapping semantics). 4948 auto *IntPtr = Builder.CreatePtrToInt(Ptr, IntPtrTy); 4949 auto *ComputedGEP = Builder.CreateAdd(IntPtr, EvaluatedGEP.TotalOffset); 4950 4951 llvm::SmallVector<std::pair<llvm::Value *, SanitizerMask>, 2> Checks; 4952 4953 if (PerformNullCheck) { 4954 // In C++, if the base pointer evaluates to a null pointer value, 4955 // the only valid pointer this inbounds GEP can produce is also 4956 // a null pointer, so the offset must also evaluate to zero. 4957 // Likewise, if we have non-zero base pointer, we can not get null pointer 4958 // as a result, so the offset can not be -intptr_t(BasePtr). 4959 // In other words, both pointers are either null, or both are non-null, 4960 // or the behaviour is undefined. 4961 // 4962 // C, however, is more strict in this regard, and gives more 4963 // optimization opportunities: in C, additionally, nullptr+0 is undefined. 4964 // So both the input to the 'gep inbounds' AND the output must not be null. 4965 auto *BaseIsNotNullptr = Builder.CreateIsNotNull(Ptr); 4966 auto *ResultIsNotNullptr = Builder.CreateIsNotNull(ComputedGEP); 4967 auto *Valid = 4968 CGM.getLangOpts().CPlusPlus 4969 ? Builder.CreateICmpEQ(BaseIsNotNullptr, ResultIsNotNullptr) 4970 : Builder.CreateAnd(BaseIsNotNullptr, ResultIsNotNullptr); 4971 Checks.emplace_back(Valid, SanitizerKind::PointerOverflow); 4972 } 4973 4974 if (PerformOverflowCheck) { 4975 // The GEP is valid if: 4976 // 1) The total offset doesn't overflow, and 4977 // 2) The sign of the difference between the computed address and the base 4978 // pointer matches the sign of the total offset. 4979 llvm::Value *ValidGEP; 4980 auto *NoOffsetOverflow = Builder.CreateNot(EvaluatedGEP.OffsetOverflows); 4981 if (SignedIndices) { 4982 // GEP is computed as `unsigned base + signed offset`, therefore: 4983 // * If offset was positive, then the computed pointer can not be 4984 // [unsigned] less than the base pointer, unless it overflowed. 4985 // * If offset was negative, then the computed pointer can not be 4986 // [unsigned] greater than the bas pointere, unless it overflowed. 4987 auto *PosOrZeroValid = Builder.CreateICmpUGE(ComputedGEP, IntPtr); 4988 auto *PosOrZeroOffset = 4989 Builder.CreateICmpSGE(EvaluatedGEP.TotalOffset, Zero); 4990 llvm::Value *NegValid = Builder.CreateICmpULT(ComputedGEP, IntPtr); 4991 ValidGEP = 4992 Builder.CreateSelect(PosOrZeroOffset, PosOrZeroValid, NegValid); 4993 } else if (!IsSubtraction) { 4994 // GEP is computed as `unsigned base + unsigned offset`, therefore the 4995 // computed pointer can not be [unsigned] less than base pointer, 4996 // unless there was an overflow. 4997 // Equivalent to `@llvm.uadd.with.overflow(%base, %offset)`. 4998 ValidGEP = Builder.CreateICmpUGE(ComputedGEP, IntPtr); 4999 } else { 5000 // GEP is computed as `unsigned base - unsigned offset`, therefore the 5001 // computed pointer can not be [unsigned] greater than base pointer, 5002 // unless there was an overflow. 5003 // Equivalent to `@llvm.usub.with.overflow(%base, sub(0, %offset))`. 5004 ValidGEP = Builder.CreateICmpULE(ComputedGEP, IntPtr); 5005 } 5006 ValidGEP = Builder.CreateAnd(ValidGEP, NoOffsetOverflow); 5007 Checks.emplace_back(ValidGEP, SanitizerKind::PointerOverflow); 5008 } 5009 5010 assert(!Checks.empty() && "Should have produced some checks."); 5011 5012 llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc)}; 5013 // Pass the computed GEP to the runtime to avoid emitting poisoned arguments. 5014 llvm::Value *DynamicArgs[] = {IntPtr, ComputedGEP}; 5015 EmitCheck(Checks, SanitizerHandler::PointerOverflow, StaticArgs, DynamicArgs); 5016 5017 return GEPVal; 5018 } 5019