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