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 pointer cast. 2069 if (auto *CI = dyn_cast<llvm::CallBase>(Src)) { 2070 if (CI->getMetadata("heapallocsite") && isa<ExplicitCastExpr>(CE)) { 2071 QualType PointeeType = DestTy->getPointeeType(); 2072 if (!PointeeType.isNull()) 2073 CGF.getDebugInfo()->addHeapAllocSiteMetadata(CI, PointeeType, 2074 CE->getExprLoc()); 2075 } 2076 } 2077 2078 return Builder.CreateBitCast(Src, DstTy); 2079 } 2080 case CK_AddressSpaceConversion: { 2081 Expr::EvalResult Result; 2082 if (E->EvaluateAsRValue(Result, CGF.getContext()) && 2083 Result.Val.isNullPointer()) { 2084 // If E has side effect, it is emitted even if its final result is a 2085 // null pointer. In that case, a DCE pass should be able to 2086 // eliminate the useless instructions emitted during translating E. 2087 if (Result.HasSideEffects) 2088 Visit(E); 2089 return CGF.CGM.getNullPointer(cast<llvm::PointerType>( 2090 ConvertType(DestTy)), DestTy); 2091 } 2092 // Since target may map different address spaces in AST to the same address 2093 // space, an address space conversion may end up as a bitcast. 2094 return CGF.CGM.getTargetCodeGenInfo().performAddrSpaceCast( 2095 CGF, Visit(E), E->getType()->getPointeeType().getAddressSpace(), 2096 DestTy->getPointeeType().getAddressSpace(), ConvertType(DestTy)); 2097 } 2098 case CK_AtomicToNonAtomic: 2099 case CK_NonAtomicToAtomic: 2100 case CK_NoOp: 2101 case CK_UserDefinedConversion: 2102 return Visit(const_cast<Expr*>(E)); 2103 2104 case CK_BaseToDerived: { 2105 const CXXRecordDecl *DerivedClassDecl = DestTy->getPointeeCXXRecordDecl(); 2106 assert(DerivedClassDecl && "BaseToDerived arg isn't a C++ object pointer!"); 2107 2108 Address Base = CGF.EmitPointerWithAlignment(E); 2109 Address Derived = 2110 CGF.GetAddressOfDerivedClass(Base, DerivedClassDecl, 2111 CE->path_begin(), CE->path_end(), 2112 CGF.ShouldNullCheckClassCastValue(CE)); 2113 2114 // C++11 [expr.static.cast]p11: Behavior is undefined if a downcast is 2115 // performed and the object is not of the derived type. 2116 if (CGF.sanitizePerformTypeCheck()) 2117 CGF.EmitTypeCheck(CodeGenFunction::TCK_DowncastPointer, CE->getExprLoc(), 2118 Derived.getPointer(), DestTy->getPointeeType()); 2119 2120 if (CGF.SanOpts.has(SanitizerKind::CFIDerivedCast)) 2121 CGF.EmitVTablePtrCheckForCast( 2122 DestTy->getPointeeType(), Derived.getPointer(), 2123 /*MayBeNull=*/true, CodeGenFunction::CFITCK_DerivedCast, 2124 CE->getBeginLoc()); 2125 2126 return Derived.getPointer(); 2127 } 2128 case CK_UncheckedDerivedToBase: 2129 case CK_DerivedToBase: { 2130 // The EmitPointerWithAlignment path does this fine; just discard 2131 // the alignment. 2132 return CGF.EmitPointerWithAlignment(CE).getPointer(); 2133 } 2134 2135 case CK_Dynamic: { 2136 Address V = CGF.EmitPointerWithAlignment(E); 2137 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE); 2138 return CGF.EmitDynamicCast(V, DCE); 2139 } 2140 2141 case CK_ArrayToPointerDecay: 2142 return CGF.EmitArrayToPointerDecay(E).getPointer(); 2143 case CK_FunctionToPointerDecay: 2144 return EmitLValue(E).getPointer(CGF); 2145 2146 case CK_NullToPointer: 2147 if (MustVisitNullValue(E)) 2148 CGF.EmitIgnoredExpr(E); 2149 2150 return CGF.CGM.getNullPointer(cast<llvm::PointerType>(ConvertType(DestTy)), 2151 DestTy); 2152 2153 case CK_NullToMemberPointer: { 2154 if (MustVisitNullValue(E)) 2155 CGF.EmitIgnoredExpr(E); 2156 2157 const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>(); 2158 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT); 2159 } 2160 2161 case CK_ReinterpretMemberPointer: 2162 case CK_BaseToDerivedMemberPointer: 2163 case CK_DerivedToBaseMemberPointer: { 2164 Value *Src = Visit(E); 2165 2166 // Note that the AST doesn't distinguish between checked and 2167 // unchecked member pointer conversions, so we always have to 2168 // implement checked conversions here. This is inefficient when 2169 // actual control flow may be required in order to perform the 2170 // check, which it is for data member pointers (but not member 2171 // function pointers on Itanium and ARM). 2172 return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src); 2173 } 2174 2175 case CK_ARCProduceObject: 2176 return CGF.EmitARCRetainScalarExpr(E); 2177 case CK_ARCConsumeObject: 2178 return CGF.EmitObjCConsumeObject(E->getType(), Visit(E)); 2179 case CK_ARCReclaimReturnedObject: 2180 return CGF.EmitARCReclaimReturnedObject(E, /*allowUnsafe*/ Ignored); 2181 case CK_ARCExtendBlockObject: 2182 return CGF.EmitARCExtendBlockObject(E); 2183 2184 case CK_CopyAndAutoreleaseBlockObject: 2185 return CGF.EmitBlockCopyAndAutorelease(Visit(E), E->getType()); 2186 2187 case CK_FloatingRealToComplex: 2188 case CK_FloatingComplexCast: 2189 case CK_IntegralRealToComplex: 2190 case CK_IntegralComplexCast: 2191 case CK_IntegralComplexToFloatingComplex: 2192 case CK_FloatingComplexToIntegralComplex: 2193 case CK_ConstructorConversion: 2194 case CK_ToUnion: 2195 llvm_unreachable("scalar cast to non-scalar value"); 2196 2197 case CK_LValueToRValue: 2198 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy)); 2199 assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!"); 2200 return Visit(const_cast<Expr*>(E)); 2201 2202 case CK_IntegralToPointer: { 2203 Value *Src = Visit(const_cast<Expr*>(E)); 2204 2205 // First, convert to the correct width so that we control the kind of 2206 // extension. 2207 auto DestLLVMTy = ConvertType(DestTy); 2208 llvm::Type *MiddleTy = CGF.CGM.getDataLayout().getIntPtrType(DestLLVMTy); 2209 bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType(); 2210 llvm::Value* IntResult = 2211 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv"); 2212 2213 auto *IntToPtr = Builder.CreateIntToPtr(IntResult, DestLLVMTy); 2214 2215 if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) { 2216 // Going from integer to pointer that could be dynamic requires reloading 2217 // dynamic information from invariant.group. 2218 if (DestTy.mayBeDynamicClass()) 2219 IntToPtr = Builder.CreateLaunderInvariantGroup(IntToPtr); 2220 } 2221 return IntToPtr; 2222 } 2223 case CK_PointerToIntegral: { 2224 assert(!DestTy->isBooleanType() && "bool should use PointerToBool"); 2225 auto *PtrExpr = Visit(E); 2226 2227 if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) { 2228 const QualType SrcType = E->getType(); 2229 2230 // Casting to integer requires stripping dynamic information as it does 2231 // not carries it. 2232 if (SrcType.mayBeDynamicClass()) 2233 PtrExpr = Builder.CreateStripInvariantGroup(PtrExpr); 2234 } 2235 2236 return Builder.CreatePtrToInt(PtrExpr, ConvertType(DestTy)); 2237 } 2238 case CK_ToVoid: { 2239 CGF.EmitIgnoredExpr(E); 2240 return nullptr; 2241 } 2242 case CK_VectorSplat: { 2243 llvm::Type *DstTy = ConvertType(DestTy); 2244 Value *Elt = Visit(const_cast<Expr*>(E)); 2245 // Splat the element across to all elements 2246 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements(); 2247 return Builder.CreateVectorSplat(NumElements, Elt, "splat"); 2248 } 2249 2250 case CK_FixedPointCast: 2251 return EmitScalarConversion(Visit(E), E->getType(), DestTy, 2252 CE->getExprLoc()); 2253 2254 case CK_FixedPointToBoolean: 2255 assert(E->getType()->isFixedPointType() && 2256 "Expected src type to be fixed point type"); 2257 assert(DestTy->isBooleanType() && "Expected dest type to be boolean type"); 2258 return EmitScalarConversion(Visit(E), E->getType(), DestTy, 2259 CE->getExprLoc()); 2260 2261 case CK_FixedPointToIntegral: 2262 assert(E->getType()->isFixedPointType() && 2263 "Expected src type to be fixed point type"); 2264 assert(DestTy->isIntegerType() && "Expected dest type to be an integer"); 2265 return EmitScalarConversion(Visit(E), E->getType(), DestTy, 2266 CE->getExprLoc()); 2267 2268 case CK_IntegralToFixedPoint: 2269 assert(E->getType()->isIntegerType() && 2270 "Expected src type to be an integer"); 2271 assert(DestTy->isFixedPointType() && 2272 "Expected dest type to be fixed point type"); 2273 return EmitScalarConversion(Visit(E), E->getType(), DestTy, 2274 CE->getExprLoc()); 2275 2276 case CK_IntegralCast: { 2277 ScalarConversionOpts Opts; 2278 if (auto *ICE = dyn_cast<ImplicitCastExpr>(CE)) { 2279 if (!ICE->isPartOfExplicitCast()) 2280 Opts = ScalarConversionOpts(CGF.SanOpts); 2281 } 2282 return EmitScalarConversion(Visit(E), E->getType(), DestTy, 2283 CE->getExprLoc(), Opts); 2284 } 2285 case CK_IntegralToFloating: 2286 case CK_FloatingToIntegral: 2287 case CK_FloatingCast: 2288 return EmitScalarConversion(Visit(E), E->getType(), DestTy, 2289 CE->getExprLoc()); 2290 case CK_BooleanToSignedIntegral: { 2291 ScalarConversionOpts Opts; 2292 Opts.TreatBooleanAsSigned = true; 2293 return EmitScalarConversion(Visit(E), E->getType(), DestTy, 2294 CE->getExprLoc(), Opts); 2295 } 2296 case CK_IntegralToBoolean: 2297 return EmitIntToBoolConversion(Visit(E)); 2298 case CK_PointerToBoolean: 2299 return EmitPointerToBoolConversion(Visit(E), E->getType()); 2300 case CK_FloatingToBoolean: 2301 return EmitFloatToBoolConversion(Visit(E)); 2302 case CK_MemberPointerToBoolean: { 2303 llvm::Value *MemPtr = Visit(E); 2304 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>(); 2305 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT); 2306 } 2307 2308 case CK_FloatingComplexToReal: 2309 case CK_IntegralComplexToReal: 2310 return CGF.EmitComplexExpr(E, false, true).first; 2311 2312 case CK_FloatingComplexToBoolean: 2313 case CK_IntegralComplexToBoolean: { 2314 CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E); 2315 2316 // TODO: kill this function off, inline appropriate case here 2317 return EmitComplexToScalarConversion(V, E->getType(), DestTy, 2318 CE->getExprLoc()); 2319 } 2320 2321 case CK_ZeroToOCLOpaqueType: { 2322 assert((DestTy->isEventT() || DestTy->isQueueT() || 2323 DestTy->isOCLIntelSubgroupAVCType()) && 2324 "CK_ZeroToOCLEvent cast on non-event type"); 2325 return llvm::Constant::getNullValue(ConvertType(DestTy)); 2326 } 2327 2328 case CK_IntToOCLSampler: 2329 return CGF.CGM.createOpenCLIntToSamplerConversion(E, CGF); 2330 2331 } // end of switch 2332 2333 llvm_unreachable("unknown scalar cast"); 2334 } 2335 2336 Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) { 2337 CodeGenFunction::StmtExprEvaluation eval(CGF); 2338 Address RetAlloca = CGF.EmitCompoundStmt(*E->getSubStmt(), 2339 !E->getType()->isVoidType()); 2340 if (!RetAlloca.isValid()) 2341 return nullptr; 2342 return CGF.EmitLoadOfScalar(CGF.MakeAddrLValue(RetAlloca, E->getType()), 2343 E->getExprLoc()); 2344 } 2345 2346 Value *ScalarExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) { 2347 CGF.enterFullExpression(E); 2348 CodeGenFunction::RunCleanupsScope Scope(CGF); 2349 Value *V = Visit(E->getSubExpr()); 2350 // Defend against dominance problems caused by jumps out of expression 2351 // evaluation through the shared cleanup block. 2352 Scope.ForceCleanup({&V}); 2353 return V; 2354 } 2355 2356 //===----------------------------------------------------------------------===// 2357 // Unary Operators 2358 //===----------------------------------------------------------------------===// 2359 2360 static BinOpInfo createBinOpInfoFromIncDec(const UnaryOperator *E, 2361 llvm::Value *InVal, bool IsInc, 2362 FPOptions FPFeatures) { 2363 BinOpInfo BinOp; 2364 BinOp.LHS = InVal; 2365 BinOp.RHS = llvm::ConstantInt::get(InVal->getType(), 1, false); 2366 BinOp.Ty = E->getType(); 2367 BinOp.Opcode = IsInc ? BO_Add : BO_Sub; 2368 BinOp.FPFeatures = FPFeatures; 2369 BinOp.E = E; 2370 return BinOp; 2371 } 2372 2373 llvm::Value *ScalarExprEmitter::EmitIncDecConsiderOverflowBehavior( 2374 const UnaryOperator *E, llvm::Value *InVal, bool IsInc) { 2375 llvm::Value *Amount = 2376 llvm::ConstantInt::get(InVal->getType(), IsInc ? 1 : -1, true); 2377 StringRef Name = IsInc ? "inc" : "dec"; 2378 switch (CGF.getLangOpts().getSignedOverflowBehavior()) { 2379 case LangOptions::SOB_Defined: 2380 return Builder.CreateAdd(InVal, Amount, Name); 2381 case LangOptions::SOB_Undefined: 2382 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) 2383 return Builder.CreateNSWAdd(InVal, Amount, Name); 2384 LLVM_FALLTHROUGH; 2385 case LangOptions::SOB_Trapping: 2386 if (!E->canOverflow()) 2387 return Builder.CreateNSWAdd(InVal, Amount, Name); 2388 return EmitOverflowCheckedBinOp(createBinOpInfoFromIncDec( 2389 E, InVal, IsInc, E->getFPFeatures(CGF.getLangOpts()))); 2390 } 2391 llvm_unreachable("Unknown SignedOverflowBehaviorTy"); 2392 } 2393 2394 namespace { 2395 /// Handles check and update for lastprivate conditional variables. 2396 class OMPLastprivateConditionalUpdateRAII { 2397 private: 2398 CodeGenFunction &CGF; 2399 const UnaryOperator *E; 2400 2401 public: 2402 OMPLastprivateConditionalUpdateRAII(CodeGenFunction &CGF, 2403 const UnaryOperator *E) 2404 : CGF(CGF), E(E) {} 2405 ~OMPLastprivateConditionalUpdateRAII() { 2406 if (CGF.getLangOpts().OpenMP) 2407 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional( 2408 CGF, E->getSubExpr()); 2409 } 2410 }; 2411 } // namespace 2412 2413 llvm::Value * 2414 ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, 2415 bool isInc, bool isPre) { 2416 OMPLastprivateConditionalUpdateRAII OMPRegion(CGF, E); 2417 QualType type = E->getSubExpr()->getType(); 2418 llvm::PHINode *atomicPHI = nullptr; 2419 llvm::Value *value; 2420 llvm::Value *input; 2421 2422 int amount = (isInc ? 1 : -1); 2423 bool isSubtraction = !isInc; 2424 2425 if (const AtomicType *atomicTy = type->getAs<AtomicType>()) { 2426 type = atomicTy->getValueType(); 2427 if (isInc && type->isBooleanType()) { 2428 llvm::Value *True = CGF.EmitToMemory(Builder.getTrue(), type); 2429 if (isPre) { 2430 Builder.CreateStore(True, LV.getAddress(CGF), LV.isVolatileQualified()) 2431 ->setAtomic(llvm::AtomicOrdering::SequentiallyConsistent); 2432 return Builder.getTrue(); 2433 } 2434 // For atomic bool increment, we just store true and return it for 2435 // preincrement, do an atomic swap with true for postincrement 2436 return Builder.CreateAtomicRMW( 2437 llvm::AtomicRMWInst::Xchg, LV.getPointer(CGF), True, 2438 llvm::AtomicOrdering::SequentiallyConsistent); 2439 } 2440 // Special case for atomic increment / decrement on integers, emit 2441 // atomicrmw instructions. We skip this if we want to be doing overflow 2442 // checking, and fall into the slow path with the atomic cmpxchg loop. 2443 if (!type->isBooleanType() && type->isIntegerType() && 2444 !(type->isUnsignedIntegerType() && 2445 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) && 2446 CGF.getLangOpts().getSignedOverflowBehavior() != 2447 LangOptions::SOB_Trapping) { 2448 llvm::AtomicRMWInst::BinOp aop = isInc ? llvm::AtomicRMWInst::Add : 2449 llvm::AtomicRMWInst::Sub; 2450 llvm::Instruction::BinaryOps op = isInc ? llvm::Instruction::Add : 2451 llvm::Instruction::Sub; 2452 llvm::Value *amt = CGF.EmitToMemory( 2453 llvm::ConstantInt::get(ConvertType(type), 1, true), type); 2454 llvm::Value *old = 2455 Builder.CreateAtomicRMW(aop, LV.getPointer(CGF), amt, 2456 llvm::AtomicOrdering::SequentiallyConsistent); 2457 return isPre ? Builder.CreateBinOp(op, old, amt) : old; 2458 } 2459 value = EmitLoadOfLValue(LV, E->getExprLoc()); 2460 input = value; 2461 // For every other atomic operation, we need to emit a load-op-cmpxchg loop 2462 llvm::BasicBlock *startBB = Builder.GetInsertBlock(); 2463 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn); 2464 value = CGF.EmitToMemory(value, type); 2465 Builder.CreateBr(opBB); 2466 Builder.SetInsertPoint(opBB); 2467 atomicPHI = Builder.CreatePHI(value->getType(), 2); 2468 atomicPHI->addIncoming(value, startBB); 2469 value = atomicPHI; 2470 } else { 2471 value = EmitLoadOfLValue(LV, E->getExprLoc()); 2472 input = value; 2473 } 2474 2475 // Special case of integer increment that we have to check first: bool++. 2476 // Due to promotion rules, we get: 2477 // bool++ -> bool = bool + 1 2478 // -> bool = (int)bool + 1 2479 // -> bool = ((int)bool + 1 != 0) 2480 // An interesting aspect of this is that increment is always true. 2481 // Decrement does not have this property. 2482 if (isInc && type->isBooleanType()) { 2483 value = Builder.getTrue(); 2484 2485 // Most common case by far: integer increment. 2486 } else if (type->isIntegerType()) { 2487 QualType promotedType; 2488 bool canPerformLossyDemotionCheck = false; 2489 if (type->isPromotableIntegerType()) { 2490 promotedType = CGF.getContext().getPromotedIntegerType(type); 2491 assert(promotedType != type && "Shouldn't promote to the same type."); 2492 canPerformLossyDemotionCheck = true; 2493 canPerformLossyDemotionCheck &= 2494 CGF.getContext().getCanonicalType(type) != 2495 CGF.getContext().getCanonicalType(promotedType); 2496 canPerformLossyDemotionCheck &= 2497 PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck( 2498 type, promotedType); 2499 assert((!canPerformLossyDemotionCheck || 2500 type->isSignedIntegerOrEnumerationType() || 2501 promotedType->isSignedIntegerOrEnumerationType() || 2502 ConvertType(type)->getScalarSizeInBits() == 2503 ConvertType(promotedType)->getScalarSizeInBits()) && 2504 "The following check expects that if we do promotion to different " 2505 "underlying canonical type, at least one of the types (either " 2506 "base or promoted) will be signed, or the bitwidths will match."); 2507 } 2508 if (CGF.SanOpts.hasOneOf( 2509 SanitizerKind::ImplicitIntegerArithmeticValueChange) && 2510 canPerformLossyDemotionCheck) { 2511 // While `x += 1` (for `x` with width less than int) is modeled as 2512 // promotion+arithmetics+demotion, and we can catch lossy demotion with 2513 // ease; inc/dec with width less than int can't overflow because of 2514 // promotion rules, so we omit promotion+demotion, which means that we can 2515 // not catch lossy "demotion". Because we still want to catch these cases 2516 // when the sanitizer is enabled, we perform the promotion, then perform 2517 // the increment/decrement in the wider type, and finally 2518 // perform the demotion. This will catch lossy demotions. 2519 2520 value = EmitScalarConversion(value, type, promotedType, E->getExprLoc()); 2521 Value *amt = llvm::ConstantInt::get(value->getType(), amount, true); 2522 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec"); 2523 // Do pass non-default ScalarConversionOpts so that sanitizer check is 2524 // emitted. 2525 value = EmitScalarConversion(value, promotedType, type, E->getExprLoc(), 2526 ScalarConversionOpts(CGF.SanOpts)); 2527 2528 // Note that signed integer inc/dec with width less than int can't 2529 // overflow because of promotion rules; we're just eliding a few steps 2530 // here. 2531 } else if (E->canOverflow() && type->isSignedIntegerOrEnumerationType()) { 2532 value = EmitIncDecConsiderOverflowBehavior(E, value, isInc); 2533 } else if (E->canOverflow() && type->isUnsignedIntegerType() && 2534 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) { 2535 value = EmitOverflowCheckedBinOp(createBinOpInfoFromIncDec( 2536 E, value, isInc, E->getFPFeatures(CGF.getLangOpts()))); 2537 } else { 2538 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount, true); 2539 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec"); 2540 } 2541 2542 // Next most common: pointer increment. 2543 } else if (const PointerType *ptr = type->getAs<PointerType>()) { 2544 QualType type = ptr->getPointeeType(); 2545 2546 // VLA types don't have constant size. 2547 if (const VariableArrayType *vla 2548 = CGF.getContext().getAsVariableArrayType(type)) { 2549 llvm::Value *numElts = CGF.getVLASize(vla).NumElts; 2550 if (!isInc) numElts = Builder.CreateNSWNeg(numElts, "vla.negsize"); 2551 if (CGF.getLangOpts().isSignedOverflowDefined()) 2552 value = Builder.CreateGEP(value, numElts, "vla.inc"); 2553 else 2554 value = CGF.EmitCheckedInBoundsGEP( 2555 value, numElts, /*SignedIndices=*/false, isSubtraction, 2556 E->getExprLoc(), "vla.inc"); 2557 2558 // Arithmetic on function pointers (!) is just +-1. 2559 } else if (type->isFunctionType()) { 2560 llvm::Value *amt = Builder.getInt32(amount); 2561 2562 value = CGF.EmitCastToVoidPtr(value); 2563 if (CGF.getLangOpts().isSignedOverflowDefined()) 2564 value = Builder.CreateGEP(value, amt, "incdec.funcptr"); 2565 else 2566 value = CGF.EmitCheckedInBoundsGEP(value, amt, /*SignedIndices=*/false, 2567 isSubtraction, E->getExprLoc(), 2568 "incdec.funcptr"); 2569 value = Builder.CreateBitCast(value, input->getType()); 2570 2571 // For everything else, we can just do a simple increment. 2572 } else { 2573 llvm::Value *amt = Builder.getInt32(amount); 2574 if (CGF.getLangOpts().isSignedOverflowDefined()) 2575 value = Builder.CreateGEP(value, amt, "incdec.ptr"); 2576 else 2577 value = CGF.EmitCheckedInBoundsGEP(value, amt, /*SignedIndices=*/false, 2578 isSubtraction, E->getExprLoc(), 2579 "incdec.ptr"); 2580 } 2581 2582 // Vector increment/decrement. 2583 } else if (type->isVectorType()) { 2584 if (type->hasIntegerRepresentation()) { 2585 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount); 2586 2587 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec"); 2588 } else { 2589 value = Builder.CreateFAdd( 2590 value, 2591 llvm::ConstantFP::get(value->getType(), amount), 2592 isInc ? "inc" : "dec"); 2593 } 2594 2595 // Floating point. 2596 } else if (type->isRealFloatingType()) { 2597 // Add the inc/dec to the real part. 2598 llvm::Value *amt; 2599 2600 if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) { 2601 // Another special case: half FP increment should be done via float 2602 if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) { 2603 value = Builder.CreateCall( 2604 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16, 2605 CGF.CGM.FloatTy), 2606 input, "incdec.conv"); 2607 } else { 2608 value = Builder.CreateFPExt(input, CGF.CGM.FloatTy, "incdec.conv"); 2609 } 2610 } 2611 2612 if (value->getType()->isFloatTy()) 2613 amt = llvm::ConstantFP::get(VMContext, 2614 llvm::APFloat(static_cast<float>(amount))); 2615 else if (value->getType()->isDoubleTy()) 2616 amt = llvm::ConstantFP::get(VMContext, 2617 llvm::APFloat(static_cast<double>(amount))); 2618 else { 2619 // Remaining types are Half, LongDouble or __float128. Convert from float. 2620 llvm::APFloat F(static_cast<float>(amount)); 2621 bool ignored; 2622 const llvm::fltSemantics *FS; 2623 // Don't use getFloatTypeSemantics because Half isn't 2624 // necessarily represented using the "half" LLVM type. 2625 if (value->getType()->isFP128Ty()) 2626 FS = &CGF.getTarget().getFloat128Format(); 2627 else if (value->getType()->isHalfTy()) 2628 FS = &CGF.getTarget().getHalfFormat(); 2629 else 2630 FS = &CGF.getTarget().getLongDoubleFormat(); 2631 F.convert(*FS, llvm::APFloat::rmTowardZero, &ignored); 2632 amt = llvm::ConstantFP::get(VMContext, F); 2633 } 2634 value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec"); 2635 2636 if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) { 2637 if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) { 2638 value = Builder.CreateCall( 2639 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16, 2640 CGF.CGM.FloatTy), 2641 value, "incdec.conv"); 2642 } else { 2643 value = Builder.CreateFPTrunc(value, input->getType(), "incdec.conv"); 2644 } 2645 } 2646 2647 // Fixed-point types. 2648 } else if (type->isFixedPointType()) { 2649 // Fixed-point types are tricky. In some cases, it isn't possible to 2650 // represent a 1 or a -1 in the type at all. Piggyback off of 2651 // EmitFixedPointBinOp to avoid having to reimplement saturation. 2652 BinOpInfo Info; 2653 Info.E = E; 2654 Info.Ty = E->getType(); 2655 Info.Opcode = isInc ? BO_Add : BO_Sub; 2656 Info.LHS = value; 2657 Info.RHS = llvm::ConstantInt::get(value->getType(), 1, false); 2658 // If the type is signed, it's better to represent this as +(-1) or -(-1), 2659 // since -1 is guaranteed to be representable. 2660 if (type->isSignedFixedPointType()) { 2661 Info.Opcode = isInc ? BO_Sub : BO_Add; 2662 Info.RHS = Builder.CreateNeg(Info.RHS); 2663 } 2664 // Now, convert from our invented integer literal to the type of the unary 2665 // op. This will upscale and saturate if necessary. This value can become 2666 // undef in some cases. 2667 FixedPointSemantics SrcSema = 2668 FixedPointSemantics::GetIntegerSemantics(value->getType() 2669 ->getScalarSizeInBits(), 2670 /*IsSigned=*/true); 2671 FixedPointSemantics DstSema = 2672 CGF.getContext().getFixedPointSemantics(Info.Ty); 2673 Info.RHS = EmitFixedPointConversion(Info.RHS, SrcSema, DstSema, 2674 E->getExprLoc()); 2675 value = EmitFixedPointBinOp(Info); 2676 2677 // Objective-C pointer types. 2678 } else { 2679 const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>(); 2680 value = CGF.EmitCastToVoidPtr(value); 2681 2682 CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType()); 2683 if (!isInc) size = -size; 2684 llvm::Value *sizeValue = 2685 llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity()); 2686 2687 if (CGF.getLangOpts().isSignedOverflowDefined()) 2688 value = Builder.CreateGEP(value, sizeValue, "incdec.objptr"); 2689 else 2690 value = CGF.EmitCheckedInBoundsGEP(value, sizeValue, 2691 /*SignedIndices=*/false, isSubtraction, 2692 E->getExprLoc(), "incdec.objptr"); 2693 value = Builder.CreateBitCast(value, input->getType()); 2694 } 2695 2696 if (atomicPHI) { 2697 llvm::BasicBlock *curBlock = Builder.GetInsertBlock(); 2698 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn); 2699 auto Pair = CGF.EmitAtomicCompareExchange( 2700 LV, RValue::get(atomicPHI), RValue::get(value), E->getExprLoc()); 2701 llvm::Value *old = CGF.EmitToMemory(Pair.first.getScalarVal(), type); 2702 llvm::Value *success = Pair.second; 2703 atomicPHI->addIncoming(old, curBlock); 2704 Builder.CreateCondBr(success, contBB, atomicPHI->getParent()); 2705 Builder.SetInsertPoint(contBB); 2706 return isPre ? value : input; 2707 } 2708 2709 // Store the updated result through the lvalue. 2710 if (LV.isBitField()) 2711 CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, &value); 2712 else 2713 CGF.EmitStoreThroughLValue(RValue::get(value), LV); 2714 2715 // If this is a postinc, return the value read from memory, otherwise use the 2716 // updated value. 2717 return isPre ? value : input; 2718 } 2719 2720 2721 2722 Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) { 2723 TestAndClearIgnoreResultAssign(); 2724 Value *Op = Visit(E->getSubExpr()); 2725 2726 // Generate a unary FNeg for FP ops. 2727 if (Op->getType()->isFPOrFPVectorTy()) 2728 return Builder.CreateFNeg(Op, "fneg"); 2729 2730 // Emit unary minus with EmitSub so we handle overflow cases etc. 2731 BinOpInfo BinOp; 2732 BinOp.RHS = Op; 2733 BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType()); 2734 BinOp.Ty = E->getType(); 2735 BinOp.Opcode = BO_Sub; 2736 BinOp.FPFeatures = E->getFPFeatures(CGF.getLangOpts()); 2737 BinOp.E = E; 2738 return EmitSub(BinOp); 2739 } 2740 2741 Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) { 2742 TestAndClearIgnoreResultAssign(); 2743 Value *Op = Visit(E->getSubExpr()); 2744 return Builder.CreateNot(Op, "neg"); 2745 } 2746 2747 Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) { 2748 // Perform vector logical not on comparison with zero vector. 2749 if (E->getType()->isExtVectorType()) { 2750 Value *Oper = Visit(E->getSubExpr()); 2751 Value *Zero = llvm::Constant::getNullValue(Oper->getType()); 2752 Value *Result; 2753 if (Oper->getType()->isFPOrFPVectorTy()) { 2754 llvm::IRBuilder<>::FastMathFlagGuard FMFG(Builder); 2755 setBuilderFlagsFromFPFeatures(Builder, CGF, 2756 E->getFPFeatures(CGF.getLangOpts())); 2757 Result = Builder.CreateFCmp(llvm::CmpInst::FCMP_OEQ, Oper, Zero, "cmp"); 2758 } else 2759 Result = Builder.CreateICmp(llvm::CmpInst::ICMP_EQ, Oper, Zero, "cmp"); 2760 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext"); 2761 } 2762 2763 // Compare operand to zero. 2764 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr()); 2765 2766 // Invert value. 2767 // TODO: Could dynamically modify easy computations here. For example, if 2768 // the operand is an icmp ne, turn into icmp eq. 2769 BoolVal = Builder.CreateNot(BoolVal, "lnot"); 2770 2771 // ZExt result to the expr type. 2772 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext"); 2773 } 2774 2775 Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) { 2776 // Try folding the offsetof to a constant. 2777 Expr::EvalResult EVResult; 2778 if (E->EvaluateAsInt(EVResult, CGF.getContext())) { 2779 llvm::APSInt Value = EVResult.Val.getInt(); 2780 return Builder.getInt(Value); 2781 } 2782 2783 // Loop over the components of the offsetof to compute the value. 2784 unsigned n = E->getNumComponents(); 2785 llvm::Type* ResultType = ConvertType(E->getType()); 2786 llvm::Value* Result = llvm::Constant::getNullValue(ResultType); 2787 QualType CurrentType = E->getTypeSourceInfo()->getType(); 2788 for (unsigned i = 0; i != n; ++i) { 2789 OffsetOfNode ON = E->getComponent(i); 2790 llvm::Value *Offset = nullptr; 2791 switch (ON.getKind()) { 2792 case OffsetOfNode::Array: { 2793 // Compute the index 2794 Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex()); 2795 llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr); 2796 bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType(); 2797 Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv"); 2798 2799 // Save the element type 2800 CurrentType = 2801 CGF.getContext().getAsArrayType(CurrentType)->getElementType(); 2802 2803 // Compute the element size 2804 llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType, 2805 CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity()); 2806 2807 // Multiply out to compute the result 2808 Offset = Builder.CreateMul(Idx, ElemSize); 2809 break; 2810 } 2811 2812 case OffsetOfNode::Field: { 2813 FieldDecl *MemberDecl = ON.getField(); 2814 RecordDecl *RD = CurrentType->castAs<RecordType>()->getDecl(); 2815 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD); 2816 2817 // Compute the index of the field in its parent. 2818 unsigned i = 0; 2819 // FIXME: It would be nice if we didn't have to loop here! 2820 for (RecordDecl::field_iterator Field = RD->field_begin(), 2821 FieldEnd = RD->field_end(); 2822 Field != FieldEnd; ++Field, ++i) { 2823 if (*Field == MemberDecl) 2824 break; 2825 } 2826 assert(i < RL.getFieldCount() && "offsetof field in wrong type"); 2827 2828 // Compute the offset to the field 2829 int64_t OffsetInt = RL.getFieldOffset(i) / 2830 CGF.getContext().getCharWidth(); 2831 Offset = llvm::ConstantInt::get(ResultType, OffsetInt); 2832 2833 // Save the element type. 2834 CurrentType = MemberDecl->getType(); 2835 break; 2836 } 2837 2838 case OffsetOfNode::Identifier: 2839 llvm_unreachable("dependent __builtin_offsetof"); 2840 2841 case OffsetOfNode::Base: { 2842 if (ON.getBase()->isVirtual()) { 2843 CGF.ErrorUnsupported(E, "virtual base in offsetof"); 2844 continue; 2845 } 2846 2847 RecordDecl *RD = CurrentType->castAs<RecordType>()->getDecl(); 2848 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD); 2849 2850 // Save the element type. 2851 CurrentType = ON.getBase()->getType(); 2852 2853 // Compute the offset to the base. 2854 const RecordType *BaseRT = CurrentType->getAs<RecordType>(); 2855 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl()); 2856 CharUnits OffsetInt = RL.getBaseClassOffset(BaseRD); 2857 Offset = llvm::ConstantInt::get(ResultType, OffsetInt.getQuantity()); 2858 break; 2859 } 2860 } 2861 Result = Builder.CreateAdd(Result, Offset); 2862 } 2863 return Result; 2864 } 2865 2866 /// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of 2867 /// argument of the sizeof expression as an integer. 2868 Value * 2869 ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr( 2870 const UnaryExprOrTypeTraitExpr *E) { 2871 QualType TypeToSize = E->getTypeOfArgument(); 2872 if (E->getKind() == UETT_SizeOf) { 2873 if (const VariableArrayType *VAT = 2874 CGF.getContext().getAsVariableArrayType(TypeToSize)) { 2875 if (E->isArgumentType()) { 2876 // sizeof(type) - make sure to emit the VLA size. 2877 CGF.EmitVariablyModifiedType(TypeToSize); 2878 } else { 2879 // C99 6.5.3.4p2: If the argument is an expression of type 2880 // VLA, it is evaluated. 2881 CGF.EmitIgnoredExpr(E->getArgumentExpr()); 2882 } 2883 2884 auto VlaSize = CGF.getVLASize(VAT); 2885 llvm::Value *size = VlaSize.NumElts; 2886 2887 // Scale the number of non-VLA elements by the non-VLA element size. 2888 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(VlaSize.Type); 2889 if (!eltSize.isOne()) 2890 size = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), size); 2891 2892 return size; 2893 } 2894 } else if (E->getKind() == UETT_OpenMPRequiredSimdAlign) { 2895 auto Alignment = 2896 CGF.getContext() 2897 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign( 2898 E->getTypeOfArgument()->getPointeeType())) 2899 .getQuantity(); 2900 return llvm::ConstantInt::get(CGF.SizeTy, Alignment); 2901 } 2902 2903 // If this isn't sizeof(vla), the result must be constant; use the constant 2904 // folding logic so we don't have to duplicate it here. 2905 return Builder.getInt(E->EvaluateKnownConstInt(CGF.getContext())); 2906 } 2907 2908 Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) { 2909 Expr *Op = E->getSubExpr(); 2910 if (Op->getType()->isAnyComplexType()) { 2911 // If it's an l-value, load through the appropriate subobject l-value. 2912 // Note that we have to ask E because Op might be an l-value that 2913 // this won't work for, e.g. an Obj-C property. 2914 if (E->isGLValue()) 2915 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E), 2916 E->getExprLoc()).getScalarVal(); 2917 2918 // Otherwise, calculate and project. 2919 return CGF.EmitComplexExpr(Op, false, true).first; 2920 } 2921 2922 return Visit(Op); 2923 } 2924 2925 Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) { 2926 Expr *Op = E->getSubExpr(); 2927 if (Op->getType()->isAnyComplexType()) { 2928 // If it's an l-value, load through the appropriate subobject l-value. 2929 // Note that we have to ask E because Op might be an l-value that 2930 // this won't work for, e.g. an Obj-C property. 2931 if (Op->isGLValue()) 2932 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E), 2933 E->getExprLoc()).getScalarVal(); 2934 2935 // Otherwise, calculate and project. 2936 return CGF.EmitComplexExpr(Op, true, false).second; 2937 } 2938 2939 // __imag on a scalar returns zero. Emit the subexpr to ensure side 2940 // effects are evaluated, but not the actual value. 2941 if (Op->isGLValue()) 2942 CGF.EmitLValue(Op); 2943 else 2944 CGF.EmitScalarExpr(Op, true); 2945 return llvm::Constant::getNullValue(ConvertType(E->getType())); 2946 } 2947 2948 //===----------------------------------------------------------------------===// 2949 // Binary Operators 2950 //===----------------------------------------------------------------------===// 2951 2952 BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) { 2953 TestAndClearIgnoreResultAssign(); 2954 BinOpInfo Result; 2955 Result.LHS = Visit(E->getLHS()); 2956 Result.RHS = Visit(E->getRHS()); 2957 Result.Ty = E->getType(); 2958 Result.Opcode = E->getOpcode(); 2959 Result.FPFeatures = E->getFPFeatures(CGF.getLangOpts()); 2960 Result.E = E; 2961 return Result; 2962 } 2963 2964 LValue ScalarExprEmitter::EmitCompoundAssignLValue( 2965 const CompoundAssignOperator *E, 2966 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &), 2967 Value *&Result) { 2968 QualType LHSTy = E->getLHS()->getType(); 2969 BinOpInfo OpInfo; 2970 2971 if (E->getComputationResultType()->isAnyComplexType()) 2972 return CGF.EmitScalarCompoundAssignWithComplex(E, Result); 2973 2974 // Emit the RHS first. __block variables need to have the rhs evaluated 2975 // first, plus this should improve codegen a little. 2976 OpInfo.RHS = Visit(E->getRHS()); 2977 OpInfo.Ty = E->getComputationResultType(); 2978 OpInfo.Opcode = E->getOpcode(); 2979 OpInfo.FPFeatures = E->getFPFeatures(CGF.getLangOpts()); 2980 OpInfo.E = E; 2981 // Load/convert the LHS. 2982 LValue LHSLV = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store); 2983 2984 llvm::PHINode *atomicPHI = nullptr; 2985 if (const AtomicType *atomicTy = LHSTy->getAs<AtomicType>()) { 2986 QualType type = atomicTy->getValueType(); 2987 if (!type->isBooleanType() && type->isIntegerType() && 2988 !(type->isUnsignedIntegerType() && 2989 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) && 2990 CGF.getLangOpts().getSignedOverflowBehavior() != 2991 LangOptions::SOB_Trapping) { 2992 llvm::AtomicRMWInst::BinOp AtomicOp = llvm::AtomicRMWInst::BAD_BINOP; 2993 llvm::Instruction::BinaryOps Op; 2994 switch (OpInfo.Opcode) { 2995 // We don't have atomicrmw operands for *, %, /, <<, >> 2996 case BO_MulAssign: case BO_DivAssign: 2997 case BO_RemAssign: 2998 case BO_ShlAssign: 2999 case BO_ShrAssign: 3000 break; 3001 case BO_AddAssign: 3002 AtomicOp = llvm::AtomicRMWInst::Add; 3003 Op = llvm::Instruction::Add; 3004 break; 3005 case BO_SubAssign: 3006 AtomicOp = llvm::AtomicRMWInst::Sub; 3007 Op = llvm::Instruction::Sub; 3008 break; 3009 case BO_AndAssign: 3010 AtomicOp = llvm::AtomicRMWInst::And; 3011 Op = llvm::Instruction::And; 3012 break; 3013 case BO_XorAssign: 3014 AtomicOp = llvm::AtomicRMWInst::Xor; 3015 Op = llvm::Instruction::Xor; 3016 break; 3017 case BO_OrAssign: 3018 AtomicOp = llvm::AtomicRMWInst::Or; 3019 Op = llvm::Instruction::Or; 3020 break; 3021 default: 3022 llvm_unreachable("Invalid compound assignment type"); 3023 } 3024 if (AtomicOp != llvm::AtomicRMWInst::BAD_BINOP) { 3025 llvm::Value *Amt = CGF.EmitToMemory( 3026 EmitScalarConversion(OpInfo.RHS, E->getRHS()->getType(), LHSTy, 3027 E->getExprLoc()), 3028 LHSTy); 3029 Value *OldVal = Builder.CreateAtomicRMW( 3030 AtomicOp, LHSLV.getPointer(CGF), Amt, 3031 llvm::AtomicOrdering::SequentiallyConsistent); 3032 3033 // Since operation is atomic, the result type is guaranteed to be the 3034 // same as the input in LLVM terms. 3035 Result = Builder.CreateBinOp(Op, OldVal, Amt); 3036 return LHSLV; 3037 } 3038 } 3039 // FIXME: For floating point types, we should be saving and restoring the 3040 // floating point environment in the loop. 3041 llvm::BasicBlock *startBB = Builder.GetInsertBlock(); 3042 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn); 3043 OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc()); 3044 OpInfo.LHS = CGF.EmitToMemory(OpInfo.LHS, type); 3045 Builder.CreateBr(opBB); 3046 Builder.SetInsertPoint(opBB); 3047 atomicPHI = Builder.CreatePHI(OpInfo.LHS->getType(), 2); 3048 atomicPHI->addIncoming(OpInfo.LHS, startBB); 3049 OpInfo.LHS = atomicPHI; 3050 } 3051 else 3052 OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc()); 3053 3054 SourceLocation Loc = E->getExprLoc(); 3055 OpInfo.LHS = 3056 EmitScalarConversion(OpInfo.LHS, LHSTy, E->getComputationLHSType(), Loc); 3057 3058 // Expand the binary operator. 3059 Result = (this->*Func)(OpInfo); 3060 3061 // Convert the result back to the LHS type, 3062 // potentially with Implicit Conversion sanitizer check. 3063 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy, 3064 Loc, ScalarConversionOpts(CGF.SanOpts)); 3065 3066 if (atomicPHI) { 3067 llvm::BasicBlock *curBlock = Builder.GetInsertBlock(); 3068 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn); 3069 auto Pair = CGF.EmitAtomicCompareExchange( 3070 LHSLV, RValue::get(atomicPHI), RValue::get(Result), E->getExprLoc()); 3071 llvm::Value *old = CGF.EmitToMemory(Pair.first.getScalarVal(), LHSTy); 3072 llvm::Value *success = Pair.second; 3073 atomicPHI->addIncoming(old, curBlock); 3074 Builder.CreateCondBr(success, contBB, atomicPHI->getParent()); 3075 Builder.SetInsertPoint(contBB); 3076 return LHSLV; 3077 } 3078 3079 // Store the result value into the LHS lvalue. Bit-fields are handled 3080 // specially because the result is altered by the store, i.e., [C99 6.5.16p1] 3081 // 'An assignment expression has the value of the left operand after the 3082 // assignment...'. 3083 if (LHSLV.isBitField()) 3084 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, &Result); 3085 else 3086 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV); 3087 3088 if (CGF.getLangOpts().OpenMP) 3089 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, 3090 E->getLHS()); 3091 return LHSLV; 3092 } 3093 3094 Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E, 3095 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) { 3096 bool Ignore = TestAndClearIgnoreResultAssign(); 3097 Value *RHS = nullptr; 3098 LValue LHS = EmitCompoundAssignLValue(E, Func, RHS); 3099 3100 // If the result is clearly ignored, return now. 3101 if (Ignore) 3102 return nullptr; 3103 3104 // The result of an assignment in C is the assigned r-value. 3105 if (!CGF.getLangOpts().CPlusPlus) 3106 return RHS; 3107 3108 // If the lvalue is non-volatile, return the computed value of the assignment. 3109 if (!LHS.isVolatileQualified()) 3110 return RHS; 3111 3112 // Otherwise, reload the value. 3113 return EmitLoadOfLValue(LHS, E->getExprLoc()); 3114 } 3115 3116 void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck( 3117 const BinOpInfo &Ops, llvm::Value *Zero, bool isDiv) { 3118 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 2> Checks; 3119 3120 if (CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero)) { 3121 Checks.push_back(std::make_pair(Builder.CreateICmpNE(Ops.RHS, Zero), 3122 SanitizerKind::IntegerDivideByZero)); 3123 } 3124 3125 const auto *BO = cast<BinaryOperator>(Ops.E); 3126 if (CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow) && 3127 Ops.Ty->hasSignedIntegerRepresentation() && 3128 !IsWidenedIntegerOp(CGF.getContext(), BO->getLHS()) && 3129 Ops.mayHaveIntegerOverflow()) { 3130 llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType()); 3131 3132 llvm::Value *IntMin = 3133 Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth())); 3134 llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL); 3135 3136 llvm::Value *LHSCmp = Builder.CreateICmpNE(Ops.LHS, IntMin); 3137 llvm::Value *RHSCmp = Builder.CreateICmpNE(Ops.RHS, NegOne); 3138 llvm::Value *NotOverflow = Builder.CreateOr(LHSCmp, RHSCmp, "or"); 3139 Checks.push_back( 3140 std::make_pair(NotOverflow, SanitizerKind::SignedIntegerOverflow)); 3141 } 3142 3143 if (Checks.size() > 0) 3144 EmitBinOpCheck(Checks, Ops); 3145 } 3146 3147 Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) { 3148 { 3149 CodeGenFunction::SanitizerScope SanScope(&CGF); 3150 if ((CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero) || 3151 CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) && 3152 Ops.Ty->isIntegerType() && 3153 (Ops.mayHaveIntegerDivisionByZero() || Ops.mayHaveIntegerOverflow())) { 3154 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty)); 3155 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true); 3156 } else if (CGF.SanOpts.has(SanitizerKind::FloatDivideByZero) && 3157 Ops.Ty->isRealFloatingType() && 3158 Ops.mayHaveFloatDivisionByZero()) { 3159 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty)); 3160 llvm::Value *NonZero = Builder.CreateFCmpUNE(Ops.RHS, Zero); 3161 EmitBinOpCheck(std::make_pair(NonZero, SanitizerKind::FloatDivideByZero), 3162 Ops); 3163 } 3164 } 3165 3166 if (Ops.LHS->getType()->isFPOrFPVectorTy()) { 3167 llvm::Value *Val; 3168 llvm::IRBuilder<>::FastMathFlagGuard FMFG(Builder); 3169 setBuilderFlagsFromFPFeatures(Builder, CGF, Ops.FPFeatures); 3170 Val = Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div"); 3171 if (CGF.getLangOpts().OpenCL && 3172 !CGF.CGM.getCodeGenOpts().CorrectlyRoundedDivSqrt) { 3173 // OpenCL v1.1 s7.4: minimum accuracy of single precision / is 2.5ulp 3174 // OpenCL v1.2 s5.6.4.2: The -cl-fp32-correctly-rounded-divide-sqrt 3175 // build option allows an application to specify that single precision 3176 // floating-point divide (x/y and 1/x) and sqrt used in the program 3177 // source are correctly rounded. 3178 llvm::Type *ValTy = Val->getType(); 3179 if (ValTy->isFloatTy() || 3180 (isa<llvm::VectorType>(ValTy) && 3181 cast<llvm::VectorType>(ValTy)->getElementType()->isFloatTy())) 3182 CGF.SetFPAccuracy(Val, 2.5); 3183 } 3184 return Val; 3185 } 3186 else if (Ops.isFixedPointOp()) 3187 return EmitFixedPointBinOp(Ops); 3188 else if (Ops.Ty->hasUnsignedIntegerRepresentation()) 3189 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div"); 3190 else 3191 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div"); 3192 } 3193 3194 Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) { 3195 // Rem in C can't be a floating point type: C99 6.5.5p2. 3196 if ((CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero) || 3197 CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) && 3198 Ops.Ty->isIntegerType() && 3199 (Ops.mayHaveIntegerDivisionByZero() || Ops.mayHaveIntegerOverflow())) { 3200 CodeGenFunction::SanitizerScope SanScope(&CGF); 3201 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty)); 3202 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false); 3203 } 3204 3205 if (Ops.Ty->hasUnsignedIntegerRepresentation()) 3206 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem"); 3207 else 3208 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem"); 3209 } 3210 3211 Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) { 3212 unsigned IID; 3213 unsigned OpID = 0; 3214 3215 bool isSigned = Ops.Ty->isSignedIntegerOrEnumerationType(); 3216 switch (Ops.Opcode) { 3217 case BO_Add: 3218 case BO_AddAssign: 3219 OpID = 1; 3220 IID = isSigned ? llvm::Intrinsic::sadd_with_overflow : 3221 llvm::Intrinsic::uadd_with_overflow; 3222 break; 3223 case BO_Sub: 3224 case BO_SubAssign: 3225 OpID = 2; 3226 IID = isSigned ? llvm::Intrinsic::ssub_with_overflow : 3227 llvm::Intrinsic::usub_with_overflow; 3228 break; 3229 case BO_Mul: 3230 case BO_MulAssign: 3231 OpID = 3; 3232 IID = isSigned ? llvm::Intrinsic::smul_with_overflow : 3233 llvm::Intrinsic::umul_with_overflow; 3234 break; 3235 default: 3236 llvm_unreachable("Unsupported operation for overflow detection"); 3237 } 3238 OpID <<= 1; 3239 if (isSigned) 3240 OpID |= 1; 3241 3242 CodeGenFunction::SanitizerScope SanScope(&CGF); 3243 llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty); 3244 3245 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy); 3246 3247 Value *resultAndOverflow = Builder.CreateCall(intrinsic, {Ops.LHS, Ops.RHS}); 3248 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0); 3249 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1); 3250 3251 // Handle overflow with llvm.trap if no custom handler has been specified. 3252 const std::string *handlerName = 3253 &CGF.getLangOpts().OverflowHandler; 3254 if (handlerName->empty()) { 3255 // If the signed-integer-overflow sanitizer is enabled, emit a call to its 3256 // runtime. Otherwise, this is a -ftrapv check, so just emit a trap. 3257 if (!isSigned || CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) { 3258 llvm::Value *NotOverflow = Builder.CreateNot(overflow); 3259 SanitizerMask Kind = isSigned ? SanitizerKind::SignedIntegerOverflow 3260 : SanitizerKind::UnsignedIntegerOverflow; 3261 EmitBinOpCheck(std::make_pair(NotOverflow, Kind), Ops); 3262 } else 3263 CGF.EmitTrapCheck(Builder.CreateNot(overflow)); 3264 return result; 3265 } 3266 3267 // Branch in case of overflow. 3268 llvm::BasicBlock *initialBB = Builder.GetInsertBlock(); 3269 llvm::BasicBlock *continueBB = 3270 CGF.createBasicBlock("nooverflow", CGF.CurFn, initialBB->getNextNode()); 3271 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn); 3272 3273 Builder.CreateCondBr(overflow, overflowBB, continueBB); 3274 3275 // If an overflow handler is set, then we want to call it and then use its 3276 // result, if it returns. 3277 Builder.SetInsertPoint(overflowBB); 3278 3279 // Get the overflow handler. 3280 llvm::Type *Int8Ty = CGF.Int8Ty; 3281 llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty }; 3282 llvm::FunctionType *handlerTy = 3283 llvm::FunctionType::get(CGF.Int64Ty, argTypes, true); 3284 llvm::FunctionCallee handler = 3285 CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName); 3286 3287 // Sign extend the args to 64-bit, so that we can use the same handler for 3288 // all types of overflow. 3289 llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty); 3290 llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty); 3291 3292 // Call the handler with the two arguments, the operation, and the size of 3293 // the result. 3294 llvm::Value *handlerArgs[] = { 3295 lhs, 3296 rhs, 3297 Builder.getInt8(OpID), 3298 Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth()) 3299 }; 3300 llvm::Value *handlerResult = 3301 CGF.EmitNounwindRuntimeCall(handler, handlerArgs); 3302 3303 // Truncate the result back to the desired size. 3304 handlerResult = Builder.CreateTrunc(handlerResult, opTy); 3305 Builder.CreateBr(continueBB); 3306 3307 Builder.SetInsertPoint(continueBB); 3308 llvm::PHINode *phi = Builder.CreatePHI(opTy, 2); 3309 phi->addIncoming(result, initialBB); 3310 phi->addIncoming(handlerResult, overflowBB); 3311 3312 return phi; 3313 } 3314 3315 /// Emit pointer + index arithmetic. 3316 static Value *emitPointerArithmetic(CodeGenFunction &CGF, 3317 const BinOpInfo &op, 3318 bool isSubtraction) { 3319 // Must have binary (not unary) expr here. Unary pointer 3320 // increment/decrement doesn't use this path. 3321 const BinaryOperator *expr = cast<BinaryOperator>(op.E); 3322 3323 Value *pointer = op.LHS; 3324 Expr *pointerOperand = expr->getLHS(); 3325 Value *index = op.RHS; 3326 Expr *indexOperand = expr->getRHS(); 3327 3328 // In a subtraction, the LHS is always the pointer. 3329 if (!isSubtraction && !pointer->getType()->isPointerTy()) { 3330 std::swap(pointer, index); 3331 std::swap(pointerOperand, indexOperand); 3332 } 3333 3334 bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType(); 3335 3336 unsigned width = cast<llvm::IntegerType>(index->getType())->getBitWidth(); 3337 auto &DL = CGF.CGM.getDataLayout(); 3338 auto PtrTy = cast<llvm::PointerType>(pointer->getType()); 3339 3340 // Some versions of glibc and gcc use idioms (particularly in their malloc 3341 // routines) that add a pointer-sized integer (known to be a pointer value) 3342 // to a null pointer in order to cast the value back to an integer or as 3343 // part of a pointer alignment algorithm. This is undefined behavior, but 3344 // we'd like to be able to compile programs that use it. 3345 // 3346 // Normally, we'd generate a GEP with a null-pointer base here in response 3347 // to that code, but it's also UB to dereference a pointer created that 3348 // way. Instead (as an acknowledged hack to tolerate the idiom) we will 3349 // generate a direct cast of the integer value to a pointer. 3350 // 3351 // The idiom (p = nullptr + N) is not met if any of the following are true: 3352 // 3353 // The operation is subtraction. 3354 // The index is not pointer-sized. 3355 // The pointer type is not byte-sized. 3356 // 3357 if (BinaryOperator::isNullPointerArithmeticExtension(CGF.getContext(), 3358 op.Opcode, 3359 expr->getLHS(), 3360 expr->getRHS())) 3361 return CGF.Builder.CreateIntToPtr(index, pointer->getType()); 3362 3363 if (width != DL.getIndexTypeSizeInBits(PtrTy)) { 3364 // Zero-extend or sign-extend the pointer value according to 3365 // whether the index is signed or not. 3366 index = CGF.Builder.CreateIntCast(index, DL.getIndexType(PtrTy), isSigned, 3367 "idx.ext"); 3368 } 3369 3370 // If this is subtraction, negate the index. 3371 if (isSubtraction) 3372 index = CGF.Builder.CreateNeg(index, "idx.neg"); 3373 3374 if (CGF.SanOpts.has(SanitizerKind::ArrayBounds)) 3375 CGF.EmitBoundsCheck(op.E, pointerOperand, index, indexOperand->getType(), 3376 /*Accessed*/ false); 3377 3378 const PointerType *pointerType 3379 = pointerOperand->getType()->getAs<PointerType>(); 3380 if (!pointerType) { 3381 QualType objectType = pointerOperand->getType() 3382 ->castAs<ObjCObjectPointerType>() 3383 ->getPointeeType(); 3384 llvm::Value *objectSize 3385 = CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(objectType)); 3386 3387 index = CGF.Builder.CreateMul(index, objectSize); 3388 3389 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy); 3390 result = CGF.Builder.CreateGEP(result, index, "add.ptr"); 3391 return CGF.Builder.CreateBitCast(result, pointer->getType()); 3392 } 3393 3394 QualType elementType = pointerType->getPointeeType(); 3395 if (const VariableArrayType *vla 3396 = CGF.getContext().getAsVariableArrayType(elementType)) { 3397 // The element count here is the total number of non-VLA elements. 3398 llvm::Value *numElements = CGF.getVLASize(vla).NumElts; 3399 3400 // Effectively, the multiply by the VLA size is part of the GEP. 3401 // GEP indexes are signed, and scaling an index isn't permitted to 3402 // signed-overflow, so we use the same semantics for our explicit 3403 // multiply. We suppress this if overflow is not undefined behavior. 3404 if (CGF.getLangOpts().isSignedOverflowDefined()) { 3405 index = CGF.Builder.CreateMul(index, numElements, "vla.index"); 3406 pointer = CGF.Builder.CreateGEP(pointer, index, "add.ptr"); 3407 } else { 3408 index = CGF.Builder.CreateNSWMul(index, numElements, "vla.index"); 3409 pointer = 3410 CGF.EmitCheckedInBoundsGEP(pointer, index, isSigned, isSubtraction, 3411 op.E->getExprLoc(), "add.ptr"); 3412 } 3413 return pointer; 3414 } 3415 3416 // Explicitly handle GNU void* and function pointer arithmetic extensions. The 3417 // GNU void* casts amount to no-ops since our void* type is i8*, but this is 3418 // future proof. 3419 if (elementType->isVoidType() || elementType->isFunctionType()) { 3420 Value *result = CGF.EmitCastToVoidPtr(pointer); 3421 result = CGF.Builder.CreateGEP(result, index, "add.ptr"); 3422 return CGF.Builder.CreateBitCast(result, pointer->getType()); 3423 } 3424 3425 if (CGF.getLangOpts().isSignedOverflowDefined()) 3426 return CGF.Builder.CreateGEP(pointer, index, "add.ptr"); 3427 3428 return CGF.EmitCheckedInBoundsGEP(pointer, index, isSigned, isSubtraction, 3429 op.E->getExprLoc(), "add.ptr"); 3430 } 3431 3432 // Construct an fmuladd intrinsic to represent a fused mul-add of MulOp and 3433 // Addend. Use negMul and negAdd to negate the first operand of the Mul or 3434 // the add operand respectively. This allows fmuladd to represent a*b-c, or 3435 // c-a*b. Patterns in LLVM should catch the negated forms and translate them to 3436 // efficient operations. 3437 static Value* buildFMulAdd(llvm::Instruction *MulOp, Value *Addend, 3438 const CodeGenFunction &CGF, CGBuilderTy &Builder, 3439 bool negMul, bool negAdd) { 3440 assert(!(negMul && negAdd) && "Only one of negMul and negAdd should be set."); 3441 3442 Value *MulOp0 = MulOp->getOperand(0); 3443 Value *MulOp1 = MulOp->getOperand(1); 3444 if (negMul) 3445 MulOp0 = Builder.CreateFNeg(MulOp0, "neg"); 3446 if (negAdd) 3447 Addend = Builder.CreateFNeg(Addend, "neg"); 3448 3449 Value *FMulAdd = nullptr; 3450 if (Builder.getIsFPConstrained()) { 3451 assert(isa<llvm::ConstrainedFPIntrinsic>(MulOp) && 3452 "Only constrained operation should be created when Builder is in FP " 3453 "constrained mode"); 3454 FMulAdd = Builder.CreateConstrainedFPCall( 3455 CGF.CGM.getIntrinsic(llvm::Intrinsic::experimental_constrained_fmuladd, 3456 Addend->getType()), 3457 {MulOp0, MulOp1, Addend}); 3458 } else { 3459 FMulAdd = Builder.CreateCall( 3460 CGF.CGM.getIntrinsic(llvm::Intrinsic::fmuladd, Addend->getType()), 3461 {MulOp0, MulOp1, Addend}); 3462 } 3463 MulOp->eraseFromParent(); 3464 3465 return FMulAdd; 3466 } 3467 3468 // Check whether it would be legal to emit an fmuladd intrinsic call to 3469 // represent op and if so, build the fmuladd. 3470 // 3471 // Checks that (a) the operation is fusable, and (b) -ffp-contract=on. 3472 // Does NOT check the type of the operation - it's assumed that this function 3473 // will be called from contexts where it's known that the type is contractable. 3474 static Value* tryEmitFMulAdd(const BinOpInfo &op, 3475 const CodeGenFunction &CGF, CGBuilderTy &Builder, 3476 bool isSub=false) { 3477 3478 assert((op.Opcode == BO_Add || op.Opcode == BO_AddAssign || 3479 op.Opcode == BO_Sub || op.Opcode == BO_SubAssign) && 3480 "Only fadd/fsub can be the root of an fmuladd."); 3481 3482 // Check whether this op is marked as fusable. 3483 if (!op.FPFeatures.allowFPContractWithinStatement()) 3484 return nullptr; 3485 3486 // We have a potentially fusable op. Look for a mul on one of the operands. 3487 // Also, make sure that the mul result isn't used directly. In that case, 3488 // there's no point creating a muladd operation. 3489 if (auto *LHSBinOp = dyn_cast<llvm::BinaryOperator>(op.LHS)) { 3490 if (LHSBinOp->getOpcode() == llvm::Instruction::FMul && 3491 LHSBinOp->use_empty()) 3492 return buildFMulAdd(LHSBinOp, op.RHS, CGF, Builder, false, isSub); 3493 } 3494 if (auto *RHSBinOp = dyn_cast<llvm::BinaryOperator>(op.RHS)) { 3495 if (RHSBinOp->getOpcode() == llvm::Instruction::FMul && 3496 RHSBinOp->use_empty()) 3497 return buildFMulAdd(RHSBinOp, op.LHS, CGF, Builder, isSub, false); 3498 } 3499 3500 if (auto *LHSBinOp = dyn_cast<llvm::CallBase>(op.LHS)) { 3501 if (LHSBinOp->getIntrinsicID() == 3502 llvm::Intrinsic::experimental_constrained_fmul && 3503 LHSBinOp->use_empty()) 3504 return buildFMulAdd(LHSBinOp, op.RHS, CGF, Builder, false, isSub); 3505 } 3506 if (auto *RHSBinOp = dyn_cast<llvm::CallBase>(op.RHS)) { 3507 if (RHSBinOp->getIntrinsicID() == 3508 llvm::Intrinsic::experimental_constrained_fmul && 3509 RHSBinOp->use_empty()) 3510 return buildFMulAdd(RHSBinOp, op.LHS, CGF, Builder, isSub, false); 3511 } 3512 3513 return nullptr; 3514 } 3515 3516 Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) { 3517 if (op.LHS->getType()->isPointerTy() || 3518 op.RHS->getType()->isPointerTy()) 3519 return emitPointerArithmetic(CGF, op, CodeGenFunction::NotSubtraction); 3520 3521 if (op.Ty->isSignedIntegerOrEnumerationType()) { 3522 switch (CGF.getLangOpts().getSignedOverflowBehavior()) { 3523 case LangOptions::SOB_Defined: 3524 return Builder.CreateAdd(op.LHS, op.RHS, "add"); 3525 case LangOptions::SOB_Undefined: 3526 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) 3527 return Builder.CreateNSWAdd(op.LHS, op.RHS, "add"); 3528 LLVM_FALLTHROUGH; 3529 case LangOptions::SOB_Trapping: 3530 if (CanElideOverflowCheck(CGF.getContext(), op)) 3531 return Builder.CreateNSWAdd(op.LHS, op.RHS, "add"); 3532 return EmitOverflowCheckedBinOp(op); 3533 } 3534 } 3535 3536 if (op.Ty->isConstantMatrixType()) { 3537 llvm::MatrixBuilder<CGBuilderTy> MB(Builder); 3538 return MB.CreateAdd(op.LHS, op.RHS); 3539 } 3540 3541 if (op.Ty->isUnsignedIntegerType() && 3542 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) && 3543 !CanElideOverflowCheck(CGF.getContext(), op)) 3544 return EmitOverflowCheckedBinOp(op); 3545 3546 if (op.LHS->getType()->isFPOrFPVectorTy()) { 3547 llvm::IRBuilder<>::FastMathFlagGuard FMFG(Builder); 3548 setBuilderFlagsFromFPFeatures(Builder, CGF, op.FPFeatures); 3549 // Try to form an fmuladd. 3550 if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder)) 3551 return FMulAdd; 3552 3553 return Builder.CreateFAdd(op.LHS, op.RHS, "add"); 3554 } 3555 3556 if (op.isFixedPointOp()) 3557 return EmitFixedPointBinOp(op); 3558 3559 return Builder.CreateAdd(op.LHS, op.RHS, "add"); 3560 } 3561 3562 /// The resulting value must be calculated with exact precision, so the operands 3563 /// may not be the same type. 3564 Value *ScalarExprEmitter::EmitFixedPointBinOp(const BinOpInfo &op) { 3565 using llvm::APSInt; 3566 using llvm::ConstantInt; 3567 3568 // This is either a binary operation where at least one of the operands is 3569 // a fixed-point type, or a unary operation where the operand is a fixed-point 3570 // type. The result type of a binary operation is determined by 3571 // Sema::handleFixedPointConversions(). 3572 QualType ResultTy = op.Ty; 3573 QualType LHSTy, RHSTy; 3574 if (const auto *BinOp = dyn_cast<BinaryOperator>(op.E)) { 3575 RHSTy = BinOp->getRHS()->getType(); 3576 if (const auto *CAO = dyn_cast<CompoundAssignOperator>(BinOp)) { 3577 // For compound assignment, the effective type of the LHS at this point 3578 // is the computation LHS type, not the actual LHS type, and the final 3579 // result type is not the type of the expression but rather the 3580 // computation result type. 3581 LHSTy = CAO->getComputationLHSType(); 3582 ResultTy = CAO->getComputationResultType(); 3583 } else 3584 LHSTy = BinOp->getLHS()->getType(); 3585 } else if (const auto *UnOp = dyn_cast<UnaryOperator>(op.E)) { 3586 LHSTy = UnOp->getSubExpr()->getType(); 3587 RHSTy = UnOp->getSubExpr()->getType(); 3588 } 3589 ASTContext &Ctx = CGF.getContext(); 3590 Value *LHS = op.LHS; 3591 Value *RHS = op.RHS; 3592 3593 auto LHSFixedSema = Ctx.getFixedPointSemantics(LHSTy); 3594 auto RHSFixedSema = Ctx.getFixedPointSemantics(RHSTy); 3595 auto ResultFixedSema = Ctx.getFixedPointSemantics(ResultTy); 3596 auto CommonFixedSema = LHSFixedSema.getCommonSemantics(RHSFixedSema); 3597 3598 // Convert the operands to the full precision type. 3599 Value *FullLHS = EmitFixedPointConversion(LHS, LHSFixedSema, CommonFixedSema, 3600 op.E->getExprLoc()); 3601 Value *FullRHS = EmitFixedPointConversion(RHS, RHSFixedSema, CommonFixedSema, 3602 op.E->getExprLoc()); 3603 3604 // Perform the actual operation. 3605 Value *Result; 3606 switch (op.Opcode) { 3607 case BO_AddAssign: 3608 case BO_Add: { 3609 if (ResultFixedSema.isSaturated()) { 3610 llvm::Intrinsic::ID IID = ResultFixedSema.isSigned() 3611 ? llvm::Intrinsic::sadd_sat 3612 : llvm::Intrinsic::uadd_sat; 3613 Result = Builder.CreateBinaryIntrinsic(IID, FullLHS, FullRHS); 3614 } else { 3615 Result = Builder.CreateAdd(FullLHS, FullRHS); 3616 } 3617 break; 3618 } 3619 case BO_SubAssign: 3620 case BO_Sub: { 3621 if (ResultFixedSema.isSaturated()) { 3622 llvm::Intrinsic::ID IID = ResultFixedSema.isSigned() 3623 ? llvm::Intrinsic::ssub_sat 3624 : llvm::Intrinsic::usub_sat; 3625 Result = Builder.CreateBinaryIntrinsic(IID, FullLHS, FullRHS); 3626 } else { 3627 Result = Builder.CreateSub(FullLHS, FullRHS); 3628 } 3629 break; 3630 } 3631 case BO_MulAssign: 3632 case BO_Mul: { 3633 llvm::Intrinsic::ID IID; 3634 if (ResultFixedSema.isSaturated()) 3635 IID = ResultFixedSema.isSigned() 3636 ? llvm::Intrinsic::smul_fix_sat 3637 : llvm::Intrinsic::umul_fix_sat; 3638 else 3639 IID = ResultFixedSema.isSigned() 3640 ? llvm::Intrinsic::smul_fix 3641 : llvm::Intrinsic::umul_fix; 3642 Result = Builder.CreateIntrinsic(IID, {FullLHS->getType()}, 3643 {FullLHS, FullRHS, Builder.getInt32(CommonFixedSema.getScale())}); 3644 break; 3645 } 3646 case BO_DivAssign: 3647 case BO_Div: { 3648 llvm::Intrinsic::ID IID; 3649 if (ResultFixedSema.isSaturated()) 3650 IID = ResultFixedSema.isSigned() ? llvm::Intrinsic::sdiv_fix_sat 3651 : llvm::Intrinsic::udiv_fix_sat; 3652 else 3653 IID = ResultFixedSema.isSigned() ? llvm::Intrinsic::sdiv_fix 3654 : llvm::Intrinsic::udiv_fix; 3655 Result = Builder.CreateIntrinsic(IID, {FullLHS->getType()}, 3656 {FullLHS, FullRHS, Builder.getInt32(CommonFixedSema.getScale())}); 3657 break; 3658 } 3659 case BO_LT: 3660 return CommonFixedSema.isSigned() ? Builder.CreateICmpSLT(FullLHS, FullRHS) 3661 : Builder.CreateICmpULT(FullLHS, FullRHS); 3662 case BO_GT: 3663 return CommonFixedSema.isSigned() ? Builder.CreateICmpSGT(FullLHS, FullRHS) 3664 : Builder.CreateICmpUGT(FullLHS, FullRHS); 3665 case BO_LE: 3666 return CommonFixedSema.isSigned() ? Builder.CreateICmpSLE(FullLHS, FullRHS) 3667 : Builder.CreateICmpULE(FullLHS, FullRHS); 3668 case BO_GE: 3669 return CommonFixedSema.isSigned() ? Builder.CreateICmpSGE(FullLHS, FullRHS) 3670 : Builder.CreateICmpUGE(FullLHS, FullRHS); 3671 case BO_EQ: 3672 // For equality operations, we assume any padding bits on unsigned types are 3673 // zero'd out. They could be overwritten through non-saturating operations 3674 // that cause overflow, but this leads to undefined behavior. 3675 return Builder.CreateICmpEQ(FullLHS, FullRHS); 3676 case BO_NE: 3677 return Builder.CreateICmpNE(FullLHS, FullRHS); 3678 case BO_Shl: 3679 case BO_Shr: 3680 case BO_Cmp: 3681 case BO_LAnd: 3682 case BO_LOr: 3683 case BO_ShlAssign: 3684 case BO_ShrAssign: 3685 llvm_unreachable("Found unimplemented fixed point binary operation"); 3686 case BO_PtrMemD: 3687 case BO_PtrMemI: 3688 case BO_Rem: 3689 case BO_Xor: 3690 case BO_And: 3691 case BO_Or: 3692 case BO_Assign: 3693 case BO_RemAssign: 3694 case BO_AndAssign: 3695 case BO_XorAssign: 3696 case BO_OrAssign: 3697 case BO_Comma: 3698 llvm_unreachable("Found unsupported binary operation for fixed point types."); 3699 } 3700 3701 // Convert to the result type. 3702 return EmitFixedPointConversion(Result, CommonFixedSema, ResultFixedSema, 3703 op.E->getExprLoc()); 3704 } 3705 3706 Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) { 3707 // The LHS is always a pointer if either side is. 3708 if (!op.LHS->getType()->isPointerTy()) { 3709 if (op.Ty->isSignedIntegerOrEnumerationType()) { 3710 switch (CGF.getLangOpts().getSignedOverflowBehavior()) { 3711 case LangOptions::SOB_Defined: 3712 return Builder.CreateSub(op.LHS, op.RHS, "sub"); 3713 case LangOptions::SOB_Undefined: 3714 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) 3715 return Builder.CreateNSWSub(op.LHS, op.RHS, "sub"); 3716 LLVM_FALLTHROUGH; 3717 case LangOptions::SOB_Trapping: 3718 if (CanElideOverflowCheck(CGF.getContext(), op)) 3719 return Builder.CreateNSWSub(op.LHS, op.RHS, "sub"); 3720 return EmitOverflowCheckedBinOp(op); 3721 } 3722 } 3723 3724 if (op.Ty->isConstantMatrixType()) { 3725 llvm::MatrixBuilder<CGBuilderTy> MB(Builder); 3726 return MB.CreateSub(op.LHS, op.RHS); 3727 } 3728 3729 if (op.Ty->isUnsignedIntegerType() && 3730 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) && 3731 !CanElideOverflowCheck(CGF.getContext(), op)) 3732 return EmitOverflowCheckedBinOp(op); 3733 3734 if (op.LHS->getType()->isFPOrFPVectorTy()) { 3735 llvm::IRBuilder<>::FastMathFlagGuard FMFG(Builder); 3736 setBuilderFlagsFromFPFeatures(Builder, CGF, op.FPFeatures); 3737 // Try to form an fmuladd. 3738 if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder, true)) 3739 return FMulAdd; 3740 return Builder.CreateFSub(op.LHS, op.RHS, "sub"); 3741 } 3742 3743 if (op.isFixedPointOp()) 3744 return EmitFixedPointBinOp(op); 3745 3746 return Builder.CreateSub(op.LHS, op.RHS, "sub"); 3747 } 3748 3749 // If the RHS is not a pointer, then we have normal pointer 3750 // arithmetic. 3751 if (!op.RHS->getType()->isPointerTy()) 3752 return emitPointerArithmetic(CGF, op, CodeGenFunction::IsSubtraction); 3753 3754 // Otherwise, this is a pointer subtraction. 3755 3756 // Do the raw subtraction part. 3757 llvm::Value *LHS 3758 = Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast"); 3759 llvm::Value *RHS 3760 = Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast"); 3761 Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub"); 3762 3763 // Okay, figure out the element size. 3764 const BinaryOperator *expr = cast<BinaryOperator>(op.E); 3765 QualType elementType = expr->getLHS()->getType()->getPointeeType(); 3766 3767 llvm::Value *divisor = nullptr; 3768 3769 // For a variable-length array, this is going to be non-constant. 3770 if (const VariableArrayType *vla 3771 = CGF.getContext().getAsVariableArrayType(elementType)) { 3772 auto VlaSize = CGF.getVLASize(vla); 3773 elementType = VlaSize.Type; 3774 divisor = VlaSize.NumElts; 3775 3776 // Scale the number of non-VLA elements by the non-VLA element size. 3777 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(elementType); 3778 if (!eltSize.isOne()) 3779 divisor = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), divisor); 3780 3781 // For everything elese, we can just compute it, safe in the 3782 // assumption that Sema won't let anything through that we can't 3783 // safely compute the size of. 3784 } else { 3785 CharUnits elementSize; 3786 // Handle GCC extension for pointer arithmetic on void* and 3787 // function pointer types. 3788 if (elementType->isVoidType() || elementType->isFunctionType()) 3789 elementSize = CharUnits::One(); 3790 else 3791 elementSize = CGF.getContext().getTypeSizeInChars(elementType); 3792 3793 // Don't even emit the divide for element size of 1. 3794 if (elementSize.isOne()) 3795 return diffInChars; 3796 3797 divisor = CGF.CGM.getSize(elementSize); 3798 } 3799 3800 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since 3801 // pointer difference in C is only defined in the case where both operands 3802 // are pointing to elements of an array. 3803 return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div"); 3804 } 3805 3806 Value *ScalarExprEmitter::GetWidthMinusOneValue(Value* LHS,Value* RHS) { 3807 llvm::IntegerType *Ty; 3808 if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(LHS->getType())) 3809 Ty = cast<llvm::IntegerType>(VT->getElementType()); 3810 else 3811 Ty = cast<llvm::IntegerType>(LHS->getType()); 3812 return llvm::ConstantInt::get(RHS->getType(), Ty->getBitWidth() - 1); 3813 } 3814 3815 Value *ScalarExprEmitter::ConstrainShiftValue(Value *LHS, Value *RHS, 3816 const Twine &Name) { 3817 llvm::IntegerType *Ty; 3818 if (auto *VT = dyn_cast<llvm::VectorType>(LHS->getType())) 3819 Ty = cast<llvm::IntegerType>(VT->getElementType()); 3820 else 3821 Ty = cast<llvm::IntegerType>(LHS->getType()); 3822 3823 if (llvm::isPowerOf2_64(Ty->getBitWidth())) 3824 return Builder.CreateAnd(RHS, GetWidthMinusOneValue(LHS, RHS), Name); 3825 3826 return Builder.CreateURem( 3827 RHS, llvm::ConstantInt::get(RHS->getType(), Ty->getBitWidth()), Name); 3828 } 3829 3830 Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) { 3831 // LLVM requires the LHS and RHS to be the same type: promote or truncate the 3832 // RHS to the same size as the LHS. 3833 Value *RHS = Ops.RHS; 3834 if (Ops.LHS->getType() != RHS->getType()) 3835 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom"); 3836 3837 bool SanitizeBase = CGF.SanOpts.has(SanitizerKind::ShiftBase) && 3838 Ops.Ty->hasSignedIntegerRepresentation() && 3839 !CGF.getLangOpts().isSignedOverflowDefined() && 3840 !CGF.getLangOpts().CPlusPlus20; 3841 bool SanitizeExponent = CGF.SanOpts.has(SanitizerKind::ShiftExponent); 3842 // OpenCL 6.3j: shift values are effectively % word size of LHS. 3843 if (CGF.getLangOpts().OpenCL) 3844 RHS = ConstrainShiftValue(Ops.LHS, RHS, "shl.mask"); 3845 else if ((SanitizeBase || SanitizeExponent) && 3846 isa<llvm::IntegerType>(Ops.LHS->getType())) { 3847 CodeGenFunction::SanitizerScope SanScope(&CGF); 3848 SmallVector<std::pair<Value *, SanitizerMask>, 2> Checks; 3849 llvm::Value *WidthMinusOne = GetWidthMinusOneValue(Ops.LHS, Ops.RHS); 3850 llvm::Value *ValidExponent = Builder.CreateICmpULE(Ops.RHS, WidthMinusOne); 3851 3852 if (SanitizeExponent) { 3853 Checks.push_back( 3854 std::make_pair(ValidExponent, SanitizerKind::ShiftExponent)); 3855 } 3856 3857 if (SanitizeBase) { 3858 // Check whether we are shifting any non-zero bits off the top of the 3859 // integer. We only emit this check if exponent is valid - otherwise 3860 // instructions below will have undefined behavior themselves. 3861 llvm::BasicBlock *Orig = Builder.GetInsertBlock(); 3862 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont"); 3863 llvm::BasicBlock *CheckShiftBase = CGF.createBasicBlock("check"); 3864 Builder.CreateCondBr(ValidExponent, CheckShiftBase, Cont); 3865 llvm::Value *PromotedWidthMinusOne = 3866 (RHS == Ops.RHS) ? WidthMinusOne 3867 : GetWidthMinusOneValue(Ops.LHS, RHS); 3868 CGF.EmitBlock(CheckShiftBase); 3869 llvm::Value *BitsShiftedOff = Builder.CreateLShr( 3870 Ops.LHS, Builder.CreateSub(PromotedWidthMinusOne, RHS, "shl.zeros", 3871 /*NUW*/ true, /*NSW*/ true), 3872 "shl.check"); 3873 if (CGF.getLangOpts().CPlusPlus) { 3874 // In C99, we are not permitted to shift a 1 bit into the sign bit. 3875 // Under C++11's rules, shifting a 1 bit into the sign bit is 3876 // OK, but shifting a 1 bit out of it is not. (C89 and C++03 don't 3877 // define signed left shifts, so we use the C99 and C++11 rules there). 3878 llvm::Value *One = llvm::ConstantInt::get(BitsShiftedOff->getType(), 1); 3879 BitsShiftedOff = Builder.CreateLShr(BitsShiftedOff, One); 3880 } 3881 llvm::Value *Zero = llvm::ConstantInt::get(BitsShiftedOff->getType(), 0); 3882 llvm::Value *ValidBase = Builder.CreateICmpEQ(BitsShiftedOff, Zero); 3883 CGF.EmitBlock(Cont); 3884 llvm::PHINode *BaseCheck = Builder.CreatePHI(ValidBase->getType(), 2); 3885 BaseCheck->addIncoming(Builder.getTrue(), Orig); 3886 BaseCheck->addIncoming(ValidBase, CheckShiftBase); 3887 Checks.push_back(std::make_pair(BaseCheck, SanitizerKind::ShiftBase)); 3888 } 3889 3890 assert(!Checks.empty()); 3891 EmitBinOpCheck(Checks, Ops); 3892 } 3893 3894 return Builder.CreateShl(Ops.LHS, RHS, "shl"); 3895 } 3896 3897 Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) { 3898 // LLVM requires the LHS and RHS to be the same type: promote or truncate the 3899 // RHS to the same size as the LHS. 3900 Value *RHS = Ops.RHS; 3901 if (Ops.LHS->getType() != RHS->getType()) 3902 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom"); 3903 3904 // OpenCL 6.3j: shift values are effectively % word size of LHS. 3905 if (CGF.getLangOpts().OpenCL) 3906 RHS = ConstrainShiftValue(Ops.LHS, RHS, "shr.mask"); 3907 else if (CGF.SanOpts.has(SanitizerKind::ShiftExponent) && 3908 isa<llvm::IntegerType>(Ops.LHS->getType())) { 3909 CodeGenFunction::SanitizerScope SanScope(&CGF); 3910 llvm::Value *Valid = 3911 Builder.CreateICmpULE(RHS, GetWidthMinusOneValue(Ops.LHS, RHS)); 3912 EmitBinOpCheck(std::make_pair(Valid, SanitizerKind::ShiftExponent), Ops); 3913 } 3914 3915 if (Ops.Ty->hasUnsignedIntegerRepresentation()) 3916 return Builder.CreateLShr(Ops.LHS, RHS, "shr"); 3917 return Builder.CreateAShr(Ops.LHS, RHS, "shr"); 3918 } 3919 3920 enum IntrinsicType { VCMPEQ, VCMPGT }; 3921 // return corresponding comparison intrinsic for given vector type 3922 static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT, 3923 BuiltinType::Kind ElemKind) { 3924 switch (ElemKind) { 3925 default: llvm_unreachable("unexpected element type"); 3926 case BuiltinType::Char_U: 3927 case BuiltinType::UChar: 3928 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p : 3929 llvm::Intrinsic::ppc_altivec_vcmpgtub_p; 3930 case BuiltinType::Char_S: 3931 case BuiltinType::SChar: 3932 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p : 3933 llvm::Intrinsic::ppc_altivec_vcmpgtsb_p; 3934 case BuiltinType::UShort: 3935 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p : 3936 llvm::Intrinsic::ppc_altivec_vcmpgtuh_p; 3937 case BuiltinType::Short: 3938 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p : 3939 llvm::Intrinsic::ppc_altivec_vcmpgtsh_p; 3940 case BuiltinType::UInt: 3941 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p : 3942 llvm::Intrinsic::ppc_altivec_vcmpgtuw_p; 3943 case BuiltinType::Int: 3944 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p : 3945 llvm::Intrinsic::ppc_altivec_vcmpgtsw_p; 3946 case BuiltinType::ULong: 3947 case BuiltinType::ULongLong: 3948 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequd_p : 3949 llvm::Intrinsic::ppc_altivec_vcmpgtud_p; 3950 case BuiltinType::Long: 3951 case BuiltinType::LongLong: 3952 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequd_p : 3953 llvm::Intrinsic::ppc_altivec_vcmpgtsd_p; 3954 case BuiltinType::Float: 3955 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p : 3956 llvm::Intrinsic::ppc_altivec_vcmpgtfp_p; 3957 case BuiltinType::Double: 3958 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_vsx_xvcmpeqdp_p : 3959 llvm::Intrinsic::ppc_vsx_xvcmpgtdp_p; 3960 } 3961 } 3962 3963 Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E, 3964 llvm::CmpInst::Predicate UICmpOpc, 3965 llvm::CmpInst::Predicate SICmpOpc, 3966 llvm::CmpInst::Predicate FCmpOpc, 3967 bool IsSignaling) { 3968 TestAndClearIgnoreResultAssign(); 3969 Value *Result; 3970 QualType LHSTy = E->getLHS()->getType(); 3971 QualType RHSTy = E->getRHS()->getType(); 3972 if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) { 3973 assert(E->getOpcode() == BO_EQ || 3974 E->getOpcode() == BO_NE); 3975 Value *LHS = CGF.EmitScalarExpr(E->getLHS()); 3976 Value *RHS = CGF.EmitScalarExpr(E->getRHS()); 3977 Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison( 3978 CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE); 3979 } else if (!LHSTy->isAnyComplexType() && !RHSTy->isAnyComplexType()) { 3980 BinOpInfo BOInfo = EmitBinOps(E); 3981 Value *LHS = BOInfo.LHS; 3982 Value *RHS = BOInfo.RHS; 3983 3984 // If AltiVec, the comparison results in a numeric type, so we use 3985 // intrinsics comparing vectors and giving 0 or 1 as a result 3986 if (LHSTy->isVectorType() && !E->getType()->isVectorType()) { 3987 // constants for mapping CR6 register bits to predicate result 3988 enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6; 3989 3990 llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic; 3991 3992 // in several cases vector arguments order will be reversed 3993 Value *FirstVecArg = LHS, 3994 *SecondVecArg = RHS; 3995 3996 QualType ElTy = LHSTy->castAs<VectorType>()->getElementType(); 3997 BuiltinType::Kind ElementKind = ElTy->castAs<BuiltinType>()->getKind(); 3998 3999 switch(E->getOpcode()) { 4000 default: llvm_unreachable("is not a comparison operation"); 4001 case BO_EQ: 4002 CR6 = CR6_LT; 4003 ID = GetIntrinsic(VCMPEQ, ElementKind); 4004 break; 4005 case BO_NE: 4006 CR6 = CR6_EQ; 4007 ID = GetIntrinsic(VCMPEQ, ElementKind); 4008 break; 4009 case BO_LT: 4010 CR6 = CR6_LT; 4011 ID = GetIntrinsic(VCMPGT, ElementKind); 4012 std::swap(FirstVecArg, SecondVecArg); 4013 break; 4014 case BO_GT: 4015 CR6 = CR6_LT; 4016 ID = GetIntrinsic(VCMPGT, ElementKind); 4017 break; 4018 case BO_LE: 4019 if (ElementKind == BuiltinType::Float) { 4020 CR6 = CR6_LT; 4021 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p; 4022 std::swap(FirstVecArg, SecondVecArg); 4023 } 4024 else { 4025 CR6 = CR6_EQ; 4026 ID = GetIntrinsic(VCMPGT, ElementKind); 4027 } 4028 break; 4029 case BO_GE: 4030 if (ElementKind == BuiltinType::Float) { 4031 CR6 = CR6_LT; 4032 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p; 4033 } 4034 else { 4035 CR6 = CR6_EQ; 4036 ID = GetIntrinsic(VCMPGT, ElementKind); 4037 std::swap(FirstVecArg, SecondVecArg); 4038 } 4039 break; 4040 } 4041 4042 Value *CR6Param = Builder.getInt32(CR6); 4043 llvm::Function *F = CGF.CGM.getIntrinsic(ID); 4044 Result = Builder.CreateCall(F, {CR6Param, FirstVecArg, SecondVecArg}); 4045 4046 // The result type of intrinsic may not be same as E->getType(). 4047 // If E->getType() is not BoolTy, EmitScalarConversion will do the 4048 // conversion work. If E->getType() is BoolTy, EmitScalarConversion will 4049 // do nothing, if ResultTy is not i1 at the same time, it will cause 4050 // crash later. 4051 llvm::IntegerType *ResultTy = cast<llvm::IntegerType>(Result->getType()); 4052 if (ResultTy->getBitWidth() > 1 && 4053 E->getType() == CGF.getContext().BoolTy) 4054 Result = Builder.CreateTrunc(Result, Builder.getInt1Ty()); 4055 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType(), 4056 E->getExprLoc()); 4057 } 4058 4059 if (BOInfo.isFixedPointOp()) { 4060 Result = EmitFixedPointBinOp(BOInfo); 4061 } else if (LHS->getType()->isFPOrFPVectorTy()) { 4062 llvm::IRBuilder<>::FastMathFlagGuard FMFG(Builder); 4063 setBuilderFlagsFromFPFeatures(Builder, CGF, BOInfo.FPFeatures); 4064 if (!IsSignaling) 4065 Result = Builder.CreateFCmp(FCmpOpc, LHS, RHS, "cmp"); 4066 else 4067 Result = Builder.CreateFCmpS(FCmpOpc, LHS, RHS, "cmp"); 4068 } else if (LHSTy->hasSignedIntegerRepresentation()) { 4069 Result = Builder.CreateICmp(SICmpOpc, LHS, RHS, "cmp"); 4070 } else { 4071 // Unsigned integers and pointers. 4072 4073 if (CGF.CGM.getCodeGenOpts().StrictVTablePointers && 4074 !isa<llvm::ConstantPointerNull>(LHS) && 4075 !isa<llvm::ConstantPointerNull>(RHS)) { 4076 4077 // Dynamic information is required to be stripped for comparisons, 4078 // because it could leak the dynamic information. Based on comparisons 4079 // of pointers to dynamic objects, the optimizer can replace one pointer 4080 // with another, which might be incorrect in presence of invariant 4081 // groups. Comparison with null is safe because null does not carry any 4082 // dynamic information. 4083 if (LHSTy.mayBeDynamicClass()) 4084 LHS = Builder.CreateStripInvariantGroup(LHS); 4085 if (RHSTy.mayBeDynamicClass()) 4086 RHS = Builder.CreateStripInvariantGroup(RHS); 4087 } 4088 4089 Result = Builder.CreateICmp(UICmpOpc, LHS, RHS, "cmp"); 4090 } 4091 4092 // If this is a vector comparison, sign extend the result to the appropriate 4093 // vector integer type and return it (don't convert to bool). 4094 if (LHSTy->isVectorType()) 4095 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext"); 4096 4097 } else { 4098 // Complex Comparison: can only be an equality comparison. 4099 CodeGenFunction::ComplexPairTy LHS, RHS; 4100 QualType CETy; 4101 if (auto *CTy = LHSTy->getAs<ComplexType>()) { 4102 LHS = CGF.EmitComplexExpr(E->getLHS()); 4103 CETy = CTy->getElementType(); 4104 } else { 4105 LHS.first = Visit(E->getLHS()); 4106 LHS.second = llvm::Constant::getNullValue(LHS.first->getType()); 4107 CETy = LHSTy; 4108 } 4109 if (auto *CTy = RHSTy->getAs<ComplexType>()) { 4110 RHS = CGF.EmitComplexExpr(E->getRHS()); 4111 assert(CGF.getContext().hasSameUnqualifiedType(CETy, 4112 CTy->getElementType()) && 4113 "The element types must always match."); 4114 (void)CTy; 4115 } else { 4116 RHS.first = Visit(E->getRHS()); 4117 RHS.second = llvm::Constant::getNullValue(RHS.first->getType()); 4118 assert(CGF.getContext().hasSameUnqualifiedType(CETy, RHSTy) && 4119 "The element types must always match."); 4120 } 4121 4122 Value *ResultR, *ResultI; 4123 if (CETy->isRealFloatingType()) { 4124 // As complex comparisons can only be equality comparisons, they 4125 // are never signaling comparisons. 4126 ResultR = Builder.CreateFCmp(FCmpOpc, LHS.first, RHS.first, "cmp.r"); 4127 ResultI = Builder.CreateFCmp(FCmpOpc, LHS.second, RHS.second, "cmp.i"); 4128 } else { 4129 // Complex comparisons can only be equality comparisons. As such, signed 4130 // and unsigned opcodes are the same. 4131 ResultR = Builder.CreateICmp(UICmpOpc, LHS.first, RHS.first, "cmp.r"); 4132 ResultI = Builder.CreateICmp(UICmpOpc, LHS.second, RHS.second, "cmp.i"); 4133 } 4134 4135 if (E->getOpcode() == BO_EQ) { 4136 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri"); 4137 } else { 4138 assert(E->getOpcode() == BO_NE && 4139 "Complex comparison other than == or != ?"); 4140 Result = Builder.CreateOr(ResultR, ResultI, "or.ri"); 4141 } 4142 } 4143 4144 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType(), 4145 E->getExprLoc()); 4146 } 4147 4148 Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) { 4149 bool Ignore = TestAndClearIgnoreResultAssign(); 4150 4151 Value *RHS; 4152 LValue LHS; 4153 4154 switch (E->getLHS()->getType().getObjCLifetime()) { 4155 case Qualifiers::OCL_Strong: 4156 std::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore); 4157 break; 4158 4159 case Qualifiers::OCL_Autoreleasing: 4160 std::tie(LHS, RHS) = CGF.EmitARCStoreAutoreleasing(E); 4161 break; 4162 4163 case Qualifiers::OCL_ExplicitNone: 4164 std::tie(LHS, RHS) = CGF.EmitARCStoreUnsafeUnretained(E, Ignore); 4165 break; 4166 4167 case Qualifiers::OCL_Weak: 4168 RHS = Visit(E->getRHS()); 4169 LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store); 4170 RHS = CGF.EmitARCStoreWeak(LHS.getAddress(CGF), RHS, Ignore); 4171 break; 4172 4173 case Qualifiers::OCL_None: 4174 // __block variables need to have the rhs evaluated first, plus 4175 // this should improve codegen just a little. 4176 RHS = Visit(E->getRHS()); 4177 LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store); 4178 4179 // Store the value into the LHS. Bit-fields are handled specially 4180 // because the result is altered by the store, i.e., [C99 6.5.16p1] 4181 // 'An assignment expression has the value of the left operand after 4182 // the assignment...'. 4183 if (LHS.isBitField()) { 4184 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, &RHS); 4185 } else { 4186 CGF.EmitNullabilityCheck(LHS, RHS, E->getExprLoc()); 4187 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS); 4188 } 4189 } 4190 4191 // If the result is clearly ignored, return now. 4192 if (Ignore) 4193 return nullptr; 4194 4195 // The result of an assignment in C is the assigned r-value. 4196 if (!CGF.getLangOpts().CPlusPlus) 4197 return RHS; 4198 4199 // If the lvalue is non-volatile, return the computed value of the assignment. 4200 if (!LHS.isVolatileQualified()) 4201 return RHS; 4202 4203 // Otherwise, reload the value. 4204 return EmitLoadOfLValue(LHS, E->getExprLoc()); 4205 } 4206 4207 Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) { 4208 // Perform vector logical and on comparisons with zero vectors. 4209 if (E->getType()->isVectorType()) { 4210 CGF.incrementProfileCounter(E); 4211 4212 Value *LHS = Visit(E->getLHS()); 4213 Value *RHS = Visit(E->getRHS()); 4214 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType()); 4215 if (LHS->getType()->isFPOrFPVectorTy()) { 4216 llvm::IRBuilder<>::FastMathFlagGuard FMFG(Builder); 4217 setBuilderFlagsFromFPFeatures(Builder, CGF, 4218 E->getFPFeatures(CGF.getLangOpts())); 4219 LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp"); 4220 RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp"); 4221 } else { 4222 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp"); 4223 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp"); 4224 } 4225 Value *And = Builder.CreateAnd(LHS, RHS); 4226 return Builder.CreateSExt(And, ConvertType(E->getType()), "sext"); 4227 } 4228 4229 llvm::Type *ResTy = ConvertType(E->getType()); 4230 4231 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0. 4232 // If we have 1 && X, just emit X without inserting the control flow. 4233 bool LHSCondVal; 4234 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) { 4235 if (LHSCondVal) { // If we have 1 && X, just emit X. 4236 CGF.incrementProfileCounter(E); 4237 4238 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 4239 // ZExt result to int or bool. 4240 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext"); 4241 } 4242 4243 // 0 && RHS: If it is safe, just elide the RHS, and return 0/false. 4244 if (!CGF.ContainsLabel(E->getRHS())) 4245 return llvm::Constant::getNullValue(ResTy); 4246 } 4247 4248 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end"); 4249 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs"); 4250 4251 CodeGenFunction::ConditionalEvaluation eval(CGF); 4252 4253 // Branch on the LHS first. If it is false, go to the failure (cont) block. 4254 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock, 4255 CGF.getProfileCount(E->getRHS())); 4256 4257 // Any edges into the ContBlock are now from an (indeterminate number of) 4258 // edges from this first condition. All of these values will be false. Start 4259 // setting up the PHI node in the Cont Block for this. 4260 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2, 4261 "", ContBlock); 4262 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock); 4263 PI != PE; ++PI) 4264 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI); 4265 4266 eval.begin(CGF); 4267 CGF.EmitBlock(RHSBlock); 4268 CGF.incrementProfileCounter(E); 4269 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 4270 eval.end(CGF); 4271 4272 // Reaquire the RHS block, as there may be subblocks inserted. 4273 RHSBlock = Builder.GetInsertBlock(); 4274 4275 // Emit an unconditional branch from this block to ContBlock. 4276 { 4277 // There is no need to emit line number for unconditional branch. 4278 auto NL = ApplyDebugLocation::CreateEmpty(CGF); 4279 CGF.EmitBlock(ContBlock); 4280 } 4281 // Insert an entry into the phi node for the edge with the value of RHSCond. 4282 PN->addIncoming(RHSCond, RHSBlock); 4283 4284 // Artificial location to preserve the scope information 4285 { 4286 auto NL = ApplyDebugLocation::CreateArtificial(CGF); 4287 PN->setDebugLoc(Builder.getCurrentDebugLocation()); 4288 } 4289 4290 // ZExt result to int. 4291 return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext"); 4292 } 4293 4294 Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) { 4295 // Perform vector logical or on comparisons with zero vectors. 4296 if (E->getType()->isVectorType()) { 4297 CGF.incrementProfileCounter(E); 4298 4299 Value *LHS = Visit(E->getLHS()); 4300 Value *RHS = Visit(E->getRHS()); 4301 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType()); 4302 if (LHS->getType()->isFPOrFPVectorTy()) { 4303 llvm::IRBuilder<>::FastMathFlagGuard FMFG(Builder); 4304 setBuilderFlagsFromFPFeatures(Builder, CGF, 4305 E->getFPFeatures(CGF.getLangOpts())); 4306 LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp"); 4307 RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp"); 4308 } else { 4309 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp"); 4310 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp"); 4311 } 4312 Value *Or = Builder.CreateOr(LHS, RHS); 4313 return Builder.CreateSExt(Or, ConvertType(E->getType()), "sext"); 4314 } 4315 4316 llvm::Type *ResTy = ConvertType(E->getType()); 4317 4318 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1. 4319 // If we have 0 || X, just emit X without inserting the control flow. 4320 bool LHSCondVal; 4321 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) { 4322 if (!LHSCondVal) { // If we have 0 || X, just emit X. 4323 CGF.incrementProfileCounter(E); 4324 4325 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 4326 // ZExt result to int or bool. 4327 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext"); 4328 } 4329 4330 // 1 || RHS: If it is safe, just elide the RHS, and return 1/true. 4331 if (!CGF.ContainsLabel(E->getRHS())) 4332 return llvm::ConstantInt::get(ResTy, 1); 4333 } 4334 4335 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end"); 4336 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs"); 4337 4338 CodeGenFunction::ConditionalEvaluation eval(CGF); 4339 4340 // Branch on the LHS first. If it is true, go to the success (cont) block. 4341 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock, 4342 CGF.getCurrentProfileCount() - 4343 CGF.getProfileCount(E->getRHS())); 4344 4345 // Any edges into the ContBlock are now from an (indeterminate number of) 4346 // edges from this first condition. All of these values will be true. Start 4347 // setting up the PHI node in the Cont Block for this. 4348 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2, 4349 "", ContBlock); 4350 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock); 4351 PI != PE; ++PI) 4352 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI); 4353 4354 eval.begin(CGF); 4355 4356 // Emit the RHS condition as a bool value. 4357 CGF.EmitBlock(RHSBlock); 4358 CGF.incrementProfileCounter(E); 4359 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 4360 4361 eval.end(CGF); 4362 4363 // Reaquire the RHS block, as there may be subblocks inserted. 4364 RHSBlock = Builder.GetInsertBlock(); 4365 4366 // Emit an unconditional branch from this block to ContBlock. Insert an entry 4367 // into the phi node for the edge with the value of RHSCond. 4368 CGF.EmitBlock(ContBlock); 4369 PN->addIncoming(RHSCond, RHSBlock); 4370 4371 // ZExt result to int. 4372 return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext"); 4373 } 4374 4375 Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) { 4376 CGF.EmitIgnoredExpr(E->getLHS()); 4377 CGF.EnsureInsertPoint(); 4378 return Visit(E->getRHS()); 4379 } 4380 4381 //===----------------------------------------------------------------------===// 4382 // Other Operators 4383 //===----------------------------------------------------------------------===// 4384 4385 /// isCheapEnoughToEvaluateUnconditionally - Return true if the specified 4386 /// expression is cheap enough and side-effect-free enough to evaluate 4387 /// unconditionally instead of conditionally. This is used to convert control 4388 /// flow into selects in some cases. 4389 static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E, 4390 CodeGenFunction &CGF) { 4391 // Anything that is an integer or floating point constant is fine. 4392 return E->IgnoreParens()->isEvaluatable(CGF.getContext()); 4393 4394 // Even non-volatile automatic variables can't be evaluated unconditionally. 4395 // Referencing a thread_local may cause non-trivial initialization work to 4396 // occur. If we're inside a lambda and one of the variables is from the scope 4397 // outside the lambda, that function may have returned already. Reading its 4398 // locals is a bad idea. Also, these reads may introduce races there didn't 4399 // exist in the source-level program. 4400 } 4401 4402 4403 Value *ScalarExprEmitter:: 4404 VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) { 4405 TestAndClearIgnoreResultAssign(); 4406 4407 // Bind the common expression if necessary. 4408 CodeGenFunction::OpaqueValueMapping binding(CGF, E); 4409 4410 Expr *condExpr = E->getCond(); 4411 Expr *lhsExpr = E->getTrueExpr(); 4412 Expr *rhsExpr = E->getFalseExpr(); 4413 4414 // If the condition constant folds and can be elided, try to avoid emitting 4415 // the condition and the dead arm. 4416 bool CondExprBool; 4417 if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) { 4418 Expr *live = lhsExpr, *dead = rhsExpr; 4419 if (!CondExprBool) std::swap(live, dead); 4420 4421 // If the dead side doesn't have labels we need, just emit the Live part. 4422 if (!CGF.ContainsLabel(dead)) { 4423 if (CondExprBool) 4424 CGF.incrementProfileCounter(E); 4425 Value *Result = Visit(live); 4426 4427 // If the live part is a throw expression, it acts like it has a void 4428 // type, so evaluating it returns a null Value*. However, a conditional 4429 // with non-void type must return a non-null Value*. 4430 if (!Result && !E->getType()->isVoidType()) 4431 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType())); 4432 4433 return Result; 4434 } 4435 } 4436 4437 // OpenCL: If the condition is a vector, we can treat this condition like 4438 // the select function. 4439 if ((CGF.getLangOpts().OpenCL && condExpr->getType()->isVectorType()) || 4440 condExpr->getType()->isExtVectorType()) { 4441 CGF.incrementProfileCounter(E); 4442 4443 llvm::Value *CondV = CGF.EmitScalarExpr(condExpr); 4444 llvm::Value *LHS = Visit(lhsExpr); 4445 llvm::Value *RHS = Visit(rhsExpr); 4446 4447 llvm::Type *condType = ConvertType(condExpr->getType()); 4448 llvm::VectorType *vecTy = cast<llvm::VectorType>(condType); 4449 4450 unsigned numElem = vecTy->getNumElements(); 4451 llvm::Type *elemType = vecTy->getElementType(); 4452 4453 llvm::Value *zeroVec = llvm::Constant::getNullValue(vecTy); 4454 llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec); 4455 llvm::Value *tmp = Builder.CreateSExt( 4456 TestMSB, llvm::FixedVectorType::get(elemType, numElem), "sext"); 4457 llvm::Value *tmp2 = Builder.CreateNot(tmp); 4458 4459 // Cast float to int to perform ANDs if necessary. 4460 llvm::Value *RHSTmp = RHS; 4461 llvm::Value *LHSTmp = LHS; 4462 bool wasCast = false; 4463 llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType()); 4464 if (rhsVTy->getElementType()->isFloatingPointTy()) { 4465 RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType()); 4466 LHSTmp = Builder.CreateBitCast(LHS, tmp->getType()); 4467 wasCast = true; 4468 } 4469 4470 llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2); 4471 llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp); 4472 llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond"); 4473 if (wasCast) 4474 tmp5 = Builder.CreateBitCast(tmp5, RHS->getType()); 4475 4476 return tmp5; 4477 } 4478 4479 if (condExpr->getType()->isVectorType()) { 4480 CGF.incrementProfileCounter(E); 4481 4482 llvm::Value *CondV = CGF.EmitScalarExpr(condExpr); 4483 llvm::Value *LHS = Visit(lhsExpr); 4484 llvm::Value *RHS = Visit(rhsExpr); 4485 4486 llvm::Type *CondType = ConvertType(condExpr->getType()); 4487 auto *VecTy = cast<llvm::VectorType>(CondType); 4488 llvm::Value *ZeroVec = llvm::Constant::getNullValue(VecTy); 4489 4490 CondV = Builder.CreateICmpNE(CondV, ZeroVec, "vector_cond"); 4491 return Builder.CreateSelect(CondV, LHS, RHS, "vector_select"); 4492 } 4493 4494 // If this is a really simple expression (like x ? 4 : 5), emit this as a 4495 // select instead of as control flow. We can only do this if it is cheap and 4496 // safe to evaluate the LHS and RHS unconditionally. 4497 if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) && 4498 isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) { 4499 llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr); 4500 llvm::Value *StepV = Builder.CreateZExtOrBitCast(CondV, CGF.Int64Ty); 4501 4502 CGF.incrementProfileCounter(E, StepV); 4503 4504 llvm::Value *LHS = Visit(lhsExpr); 4505 llvm::Value *RHS = Visit(rhsExpr); 4506 if (!LHS) { 4507 // If the conditional has void type, make sure we return a null Value*. 4508 assert(!RHS && "LHS and RHS types must match"); 4509 return nullptr; 4510 } 4511 return Builder.CreateSelect(CondV, LHS, RHS, "cond"); 4512 } 4513 4514 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true"); 4515 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false"); 4516 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end"); 4517 4518 CodeGenFunction::ConditionalEvaluation eval(CGF); 4519 CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock, 4520 CGF.getProfileCount(lhsExpr)); 4521 4522 CGF.EmitBlock(LHSBlock); 4523 CGF.incrementProfileCounter(E); 4524 eval.begin(CGF); 4525 Value *LHS = Visit(lhsExpr); 4526 eval.end(CGF); 4527 4528 LHSBlock = Builder.GetInsertBlock(); 4529 Builder.CreateBr(ContBlock); 4530 4531 CGF.EmitBlock(RHSBlock); 4532 eval.begin(CGF); 4533 Value *RHS = Visit(rhsExpr); 4534 eval.end(CGF); 4535 4536 RHSBlock = Builder.GetInsertBlock(); 4537 CGF.EmitBlock(ContBlock); 4538 4539 // If the LHS or RHS is a throw expression, it will be legitimately null. 4540 if (!LHS) 4541 return RHS; 4542 if (!RHS) 4543 return LHS; 4544 4545 // Create a PHI node for the real part. 4546 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond"); 4547 PN->addIncoming(LHS, LHSBlock); 4548 PN->addIncoming(RHS, RHSBlock); 4549 return PN; 4550 } 4551 4552 Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) { 4553 return Visit(E->getChosenSubExpr()); 4554 } 4555 4556 Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) { 4557 QualType Ty = VE->getType(); 4558 4559 if (Ty->isVariablyModifiedType()) 4560 CGF.EmitVariablyModifiedType(Ty); 4561 4562 Address ArgValue = Address::invalid(); 4563 Address ArgPtr = CGF.EmitVAArg(VE, ArgValue); 4564 4565 llvm::Type *ArgTy = ConvertType(VE->getType()); 4566 4567 // If EmitVAArg fails, emit an error. 4568 if (!ArgPtr.isValid()) { 4569 CGF.ErrorUnsupported(VE, "va_arg expression"); 4570 return llvm::UndefValue::get(ArgTy); 4571 } 4572 4573 // FIXME Volatility. 4574 llvm::Value *Val = Builder.CreateLoad(ArgPtr); 4575 4576 // If EmitVAArg promoted the type, we must truncate it. 4577 if (ArgTy != Val->getType()) { 4578 if (ArgTy->isPointerTy() && !Val->getType()->isPointerTy()) 4579 Val = Builder.CreateIntToPtr(Val, ArgTy); 4580 else 4581 Val = Builder.CreateTrunc(Val, ArgTy); 4582 } 4583 4584 return Val; 4585 } 4586 4587 Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) { 4588 return CGF.EmitBlockLiteral(block); 4589 } 4590 4591 // Convert a vec3 to vec4, or vice versa. 4592 static Value *ConvertVec3AndVec4(CGBuilderTy &Builder, CodeGenFunction &CGF, 4593 Value *Src, unsigned NumElementsDst) { 4594 llvm::Value *UnV = llvm::UndefValue::get(Src->getType()); 4595 static constexpr int Mask[] = {0, 1, 2, -1}; 4596 return Builder.CreateShuffleVector(Src, UnV, 4597 llvm::makeArrayRef(Mask, NumElementsDst)); 4598 } 4599 4600 // Create cast instructions for converting LLVM value \p Src to LLVM type \p 4601 // DstTy. \p Src has the same size as \p DstTy. Both are single value types 4602 // but could be scalar or vectors of different lengths, and either can be 4603 // pointer. 4604 // There are 4 cases: 4605 // 1. non-pointer -> non-pointer : needs 1 bitcast 4606 // 2. pointer -> pointer : needs 1 bitcast or addrspacecast 4607 // 3. pointer -> non-pointer 4608 // a) pointer -> intptr_t : needs 1 ptrtoint 4609 // b) pointer -> non-intptr_t : needs 1 ptrtoint then 1 bitcast 4610 // 4. non-pointer -> pointer 4611 // a) intptr_t -> pointer : needs 1 inttoptr 4612 // b) non-intptr_t -> pointer : needs 1 bitcast then 1 inttoptr 4613 // Note: for cases 3b and 4b two casts are required since LLVM casts do not 4614 // allow casting directly between pointer types and non-integer non-pointer 4615 // types. 4616 static Value *createCastsForTypeOfSameSize(CGBuilderTy &Builder, 4617 const llvm::DataLayout &DL, 4618 Value *Src, llvm::Type *DstTy, 4619 StringRef Name = "") { 4620 auto SrcTy = Src->getType(); 4621 4622 // Case 1. 4623 if (!SrcTy->isPointerTy() && !DstTy->isPointerTy()) 4624 return Builder.CreateBitCast(Src, DstTy, Name); 4625 4626 // Case 2. 4627 if (SrcTy->isPointerTy() && DstTy->isPointerTy()) 4628 return Builder.CreatePointerBitCastOrAddrSpaceCast(Src, DstTy, Name); 4629 4630 // Case 3. 4631 if (SrcTy->isPointerTy() && !DstTy->isPointerTy()) { 4632 // Case 3b. 4633 if (!DstTy->isIntegerTy()) 4634 Src = Builder.CreatePtrToInt(Src, DL.getIntPtrType(SrcTy)); 4635 // Cases 3a and 3b. 4636 return Builder.CreateBitOrPointerCast(Src, DstTy, Name); 4637 } 4638 4639 // Case 4b. 4640 if (!SrcTy->isIntegerTy()) 4641 Src = Builder.CreateBitCast(Src, DL.getIntPtrType(DstTy)); 4642 // Cases 4a and 4b. 4643 return Builder.CreateIntToPtr(Src, DstTy, Name); 4644 } 4645 4646 Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) { 4647 Value *Src = CGF.EmitScalarExpr(E->getSrcExpr()); 4648 llvm::Type *DstTy = ConvertType(E->getType()); 4649 4650 llvm::Type *SrcTy = Src->getType(); 4651 unsigned NumElementsSrc = isa<llvm::VectorType>(SrcTy) ? 4652 cast<llvm::VectorType>(SrcTy)->getNumElements() : 0; 4653 unsigned NumElementsDst = isa<llvm::VectorType>(DstTy) ? 4654 cast<llvm::VectorType>(DstTy)->getNumElements() : 0; 4655 4656 // Going from vec3 to non-vec3 is a special case and requires a shuffle 4657 // vector to get a vec4, then a bitcast if the target type is different. 4658 if (NumElementsSrc == 3 && NumElementsDst != 3) { 4659 Src = ConvertVec3AndVec4(Builder, CGF, Src, 4); 4660 4661 if (!CGF.CGM.getCodeGenOpts().PreserveVec3Type) { 4662 Src = createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(), Src, 4663 DstTy); 4664 } 4665 4666 Src->setName("astype"); 4667 return Src; 4668 } 4669 4670 // Going from non-vec3 to vec3 is a special case and requires a bitcast 4671 // to vec4 if the original type is not vec4, then a shuffle vector to 4672 // get a vec3. 4673 if (NumElementsSrc != 3 && NumElementsDst == 3) { 4674 if (!CGF.CGM.getCodeGenOpts().PreserveVec3Type) { 4675 auto *Vec4Ty = llvm::FixedVectorType::get( 4676 cast<llvm::VectorType>(DstTy)->getElementType(), 4); 4677 Src = createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(), Src, 4678 Vec4Ty); 4679 } 4680 4681 Src = ConvertVec3AndVec4(Builder, CGF, Src, 3); 4682 Src->setName("astype"); 4683 return Src; 4684 } 4685 4686 return createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(), 4687 Src, DstTy, "astype"); 4688 } 4689 4690 Value *ScalarExprEmitter::VisitAtomicExpr(AtomicExpr *E) { 4691 return CGF.EmitAtomicExpr(E).getScalarVal(); 4692 } 4693 4694 //===----------------------------------------------------------------------===// 4695 // Entry Point into this File 4696 //===----------------------------------------------------------------------===// 4697 4698 /// Emit the computation of the specified expression of scalar type, ignoring 4699 /// the result. 4700 Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) { 4701 assert(E && hasScalarEvaluationKind(E->getType()) && 4702 "Invalid scalar expression to emit"); 4703 4704 return ScalarExprEmitter(*this, IgnoreResultAssign) 4705 .Visit(const_cast<Expr *>(E)); 4706 } 4707 4708 /// Emit a conversion from the specified type to the specified destination type, 4709 /// both of which are LLVM scalar types. 4710 Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy, 4711 QualType DstTy, 4712 SourceLocation Loc) { 4713 assert(hasScalarEvaluationKind(SrcTy) && hasScalarEvaluationKind(DstTy) && 4714 "Invalid scalar expression to emit"); 4715 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy, Loc); 4716 } 4717 4718 /// Emit a conversion from the specified complex type to the specified 4719 /// destination type, where the destination type is an LLVM scalar type. 4720 Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src, 4721 QualType SrcTy, 4722 QualType DstTy, 4723 SourceLocation Loc) { 4724 assert(SrcTy->isAnyComplexType() && hasScalarEvaluationKind(DstTy) && 4725 "Invalid complex -> scalar conversion"); 4726 return ScalarExprEmitter(*this) 4727 .EmitComplexToScalarConversion(Src, SrcTy, DstTy, Loc); 4728 } 4729 4730 4731 llvm::Value *CodeGenFunction:: 4732 EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, 4733 bool isInc, bool isPre) { 4734 return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre); 4735 } 4736 4737 LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) { 4738 // object->isa or (*object).isa 4739 // Generate code as for: *(Class*)object 4740 4741 Expr *BaseExpr = E->getBase(); 4742 Address Addr = Address::invalid(); 4743 if (BaseExpr->isRValue()) { 4744 Addr = Address(EmitScalarExpr(BaseExpr), getPointerAlign()); 4745 } else { 4746 Addr = EmitLValue(BaseExpr).getAddress(*this); 4747 } 4748 4749 // Cast the address to Class*. 4750 Addr = Builder.CreateElementBitCast(Addr, ConvertType(E->getType())); 4751 return MakeAddrLValue(Addr, E->getType()); 4752 } 4753 4754 4755 LValue CodeGenFunction::EmitCompoundAssignmentLValue( 4756 const CompoundAssignOperator *E) { 4757 ScalarExprEmitter Scalar(*this); 4758 Value *Result = nullptr; 4759 switch (E->getOpcode()) { 4760 #define COMPOUND_OP(Op) \ 4761 case BO_##Op##Assign: \ 4762 return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \ 4763 Result) 4764 COMPOUND_OP(Mul); 4765 COMPOUND_OP(Div); 4766 COMPOUND_OP(Rem); 4767 COMPOUND_OP(Add); 4768 COMPOUND_OP(Sub); 4769 COMPOUND_OP(Shl); 4770 COMPOUND_OP(Shr); 4771 COMPOUND_OP(And); 4772 COMPOUND_OP(Xor); 4773 COMPOUND_OP(Or); 4774 #undef COMPOUND_OP 4775 4776 case BO_PtrMemD: 4777 case BO_PtrMemI: 4778 case BO_Mul: 4779 case BO_Div: 4780 case BO_Rem: 4781 case BO_Add: 4782 case BO_Sub: 4783 case BO_Shl: 4784 case BO_Shr: 4785 case BO_LT: 4786 case BO_GT: 4787 case BO_LE: 4788 case BO_GE: 4789 case BO_EQ: 4790 case BO_NE: 4791 case BO_Cmp: 4792 case BO_And: 4793 case BO_Xor: 4794 case BO_Or: 4795 case BO_LAnd: 4796 case BO_LOr: 4797 case BO_Assign: 4798 case BO_Comma: 4799 llvm_unreachable("Not valid compound assignment operators"); 4800 } 4801 4802 llvm_unreachable("Unhandled compound assignment operator"); 4803 } 4804 4805 struct GEPOffsetAndOverflow { 4806 // The total (signed) byte offset for the GEP. 4807 llvm::Value *TotalOffset; 4808 // The offset overflow flag - true if the total offset overflows. 4809 llvm::Value *OffsetOverflows; 4810 }; 4811 4812 /// Evaluate given GEPVal, which is either an inbounds GEP, or a constant, 4813 /// and compute the total offset it applies from it's base pointer BasePtr. 4814 /// Returns offset in bytes and a boolean flag whether an overflow happened 4815 /// during evaluation. 4816 static GEPOffsetAndOverflow EmitGEPOffsetInBytes(Value *BasePtr, Value *GEPVal, 4817 llvm::LLVMContext &VMContext, 4818 CodeGenModule &CGM, 4819 CGBuilderTy &Builder) { 4820 const auto &DL = CGM.getDataLayout(); 4821 4822 // The total (signed) byte offset for the GEP. 4823 llvm::Value *TotalOffset = nullptr; 4824 4825 // Was the GEP already reduced to a constant? 4826 if (isa<llvm::Constant>(GEPVal)) { 4827 // Compute the offset by casting both pointers to integers and subtracting: 4828 // GEPVal = BasePtr + ptr(Offset) <--> Offset = int(GEPVal) - int(BasePtr) 4829 Value *BasePtr_int = 4830 Builder.CreatePtrToInt(BasePtr, DL.getIntPtrType(BasePtr->getType())); 4831 Value *GEPVal_int = 4832 Builder.CreatePtrToInt(GEPVal, DL.getIntPtrType(GEPVal->getType())); 4833 TotalOffset = Builder.CreateSub(GEPVal_int, BasePtr_int); 4834 return {TotalOffset, /*OffsetOverflows=*/Builder.getFalse()}; 4835 } 4836 4837 auto *GEP = cast<llvm::GEPOperator>(GEPVal); 4838 assert(GEP->getPointerOperand() == BasePtr && 4839 "BasePtr must be the the base of the GEP."); 4840 assert(GEP->isInBounds() && "Expected inbounds GEP"); 4841 4842 auto *IntPtrTy = DL.getIntPtrType(GEP->getPointerOperandType()); 4843 4844 // Grab references to the signed add/mul overflow intrinsics for intptr_t. 4845 auto *Zero = llvm::ConstantInt::getNullValue(IntPtrTy); 4846 auto *SAddIntrinsic = 4847 CGM.getIntrinsic(llvm::Intrinsic::sadd_with_overflow, IntPtrTy); 4848 auto *SMulIntrinsic = 4849 CGM.getIntrinsic(llvm::Intrinsic::smul_with_overflow, IntPtrTy); 4850 4851 // The offset overflow flag - true if the total offset overflows. 4852 llvm::Value *OffsetOverflows = Builder.getFalse(); 4853 4854 /// Return the result of the given binary operation. 4855 auto eval = [&](BinaryOperator::Opcode Opcode, llvm::Value *LHS, 4856 llvm::Value *RHS) -> llvm::Value * { 4857 assert((Opcode == BO_Add || Opcode == BO_Mul) && "Can't eval binop"); 4858 4859 // If the operands are constants, return a constant result. 4860 if (auto *LHSCI = dyn_cast<llvm::ConstantInt>(LHS)) { 4861 if (auto *RHSCI = dyn_cast<llvm::ConstantInt>(RHS)) { 4862 llvm::APInt N; 4863 bool HasOverflow = mayHaveIntegerOverflow(LHSCI, RHSCI, Opcode, 4864 /*Signed=*/true, N); 4865 if (HasOverflow) 4866 OffsetOverflows = Builder.getTrue(); 4867 return llvm::ConstantInt::get(VMContext, N); 4868 } 4869 } 4870 4871 // Otherwise, compute the result with checked arithmetic. 4872 auto *ResultAndOverflow = Builder.CreateCall( 4873 (Opcode == BO_Add) ? SAddIntrinsic : SMulIntrinsic, {LHS, RHS}); 4874 OffsetOverflows = Builder.CreateOr( 4875 Builder.CreateExtractValue(ResultAndOverflow, 1), OffsetOverflows); 4876 return Builder.CreateExtractValue(ResultAndOverflow, 0); 4877 }; 4878 4879 // Determine the total byte offset by looking at each GEP operand. 4880 for (auto GTI = llvm::gep_type_begin(GEP), GTE = llvm::gep_type_end(GEP); 4881 GTI != GTE; ++GTI) { 4882 llvm::Value *LocalOffset; 4883 auto *Index = GTI.getOperand(); 4884 // Compute the local offset contributed by this indexing step: 4885 if (auto *STy = GTI.getStructTypeOrNull()) { 4886 // For struct indexing, the local offset is the byte position of the 4887 // specified field. 4888 unsigned FieldNo = cast<llvm::ConstantInt>(Index)->getZExtValue(); 4889 LocalOffset = llvm::ConstantInt::get( 4890 IntPtrTy, DL.getStructLayout(STy)->getElementOffset(FieldNo)); 4891 } else { 4892 // Otherwise this is array-like indexing. The local offset is the index 4893 // multiplied by the element size. 4894 auto *ElementSize = llvm::ConstantInt::get( 4895 IntPtrTy, DL.getTypeAllocSize(GTI.getIndexedType())); 4896 auto *IndexS = Builder.CreateIntCast(Index, IntPtrTy, /*isSigned=*/true); 4897 LocalOffset = eval(BO_Mul, ElementSize, IndexS); 4898 } 4899 4900 // If this is the first offset, set it as the total offset. Otherwise, add 4901 // the local offset into the running total. 4902 if (!TotalOffset || TotalOffset == Zero) 4903 TotalOffset = LocalOffset; 4904 else 4905 TotalOffset = eval(BO_Add, TotalOffset, LocalOffset); 4906 } 4907 4908 return {TotalOffset, OffsetOverflows}; 4909 } 4910 4911 Value * 4912 CodeGenFunction::EmitCheckedInBoundsGEP(Value *Ptr, ArrayRef<Value *> IdxList, 4913 bool SignedIndices, bool IsSubtraction, 4914 SourceLocation Loc, const Twine &Name) { 4915 Value *GEPVal = Builder.CreateInBoundsGEP(Ptr, IdxList, Name); 4916 4917 // If the pointer overflow sanitizer isn't enabled, do nothing. 4918 if (!SanOpts.has(SanitizerKind::PointerOverflow)) 4919 return GEPVal; 4920 4921 llvm::Type *PtrTy = Ptr->getType(); 4922 4923 // Perform nullptr-and-offset check unless the nullptr is defined. 4924 bool PerformNullCheck = !NullPointerIsDefined( 4925 Builder.GetInsertBlock()->getParent(), PtrTy->getPointerAddressSpace()); 4926 // Check for overflows unless the GEP got constant-folded, 4927 // and only in the default address space 4928 bool PerformOverflowCheck = 4929 !isa<llvm::Constant>(GEPVal) && PtrTy->getPointerAddressSpace() == 0; 4930 4931 if (!(PerformNullCheck || PerformOverflowCheck)) 4932 return GEPVal; 4933 4934 const auto &DL = CGM.getDataLayout(); 4935 4936 SanitizerScope SanScope(this); 4937 llvm::Type *IntPtrTy = DL.getIntPtrType(PtrTy); 4938 4939 GEPOffsetAndOverflow EvaluatedGEP = 4940 EmitGEPOffsetInBytes(Ptr, GEPVal, getLLVMContext(), CGM, Builder); 4941 4942 assert((!isa<llvm::Constant>(EvaluatedGEP.TotalOffset) || 4943 EvaluatedGEP.OffsetOverflows == Builder.getFalse()) && 4944 "If the offset got constant-folded, we don't expect that there was an " 4945 "overflow."); 4946 4947 auto *Zero = llvm::ConstantInt::getNullValue(IntPtrTy); 4948 4949 // Common case: if the total offset is zero, and we are using C++ semantics, 4950 // where nullptr+0 is defined, don't emit a check. 4951 if (EvaluatedGEP.TotalOffset == Zero && CGM.getLangOpts().CPlusPlus) 4952 return GEPVal; 4953 4954 // Now that we've computed the total offset, add it to the base pointer (with 4955 // wrapping semantics). 4956 auto *IntPtr = Builder.CreatePtrToInt(Ptr, IntPtrTy); 4957 auto *ComputedGEP = Builder.CreateAdd(IntPtr, EvaluatedGEP.TotalOffset); 4958 4959 llvm::SmallVector<std::pair<llvm::Value *, SanitizerMask>, 2> Checks; 4960 4961 if (PerformNullCheck) { 4962 // In C++, if the base pointer evaluates to a null pointer value, 4963 // the only valid pointer this inbounds GEP can produce is also 4964 // a null pointer, so the offset must also evaluate to zero. 4965 // Likewise, if we have non-zero base pointer, we can not get null pointer 4966 // as a result, so the offset can not be -intptr_t(BasePtr). 4967 // In other words, both pointers are either null, or both are non-null, 4968 // or the behaviour is undefined. 4969 // 4970 // C, however, is more strict in this regard, and gives more 4971 // optimization opportunities: in C, additionally, nullptr+0 is undefined. 4972 // So both the input to the 'gep inbounds' AND the output must not be null. 4973 auto *BaseIsNotNullptr = Builder.CreateIsNotNull(Ptr); 4974 auto *ResultIsNotNullptr = Builder.CreateIsNotNull(ComputedGEP); 4975 auto *Valid = 4976 CGM.getLangOpts().CPlusPlus 4977 ? Builder.CreateICmpEQ(BaseIsNotNullptr, ResultIsNotNullptr) 4978 : Builder.CreateAnd(BaseIsNotNullptr, ResultIsNotNullptr); 4979 Checks.emplace_back(Valid, SanitizerKind::PointerOverflow); 4980 } 4981 4982 if (PerformOverflowCheck) { 4983 // The GEP is valid if: 4984 // 1) The total offset doesn't overflow, and 4985 // 2) The sign of the difference between the computed address and the base 4986 // pointer matches the sign of the total offset. 4987 llvm::Value *ValidGEP; 4988 auto *NoOffsetOverflow = Builder.CreateNot(EvaluatedGEP.OffsetOverflows); 4989 if (SignedIndices) { 4990 // GEP is computed as `unsigned base + signed offset`, therefore: 4991 // * If offset was positive, then the computed pointer can not be 4992 // [unsigned] less than the base pointer, unless it overflowed. 4993 // * If offset was negative, then the computed pointer can not be 4994 // [unsigned] greater than the bas pointere, unless it overflowed. 4995 auto *PosOrZeroValid = Builder.CreateICmpUGE(ComputedGEP, IntPtr); 4996 auto *PosOrZeroOffset = 4997 Builder.CreateICmpSGE(EvaluatedGEP.TotalOffset, Zero); 4998 llvm::Value *NegValid = Builder.CreateICmpULT(ComputedGEP, IntPtr); 4999 ValidGEP = 5000 Builder.CreateSelect(PosOrZeroOffset, PosOrZeroValid, NegValid); 5001 } else if (!IsSubtraction) { 5002 // GEP is computed as `unsigned base + unsigned offset`, therefore the 5003 // computed pointer can not be [unsigned] less than base pointer, 5004 // unless there was an overflow. 5005 // Equivalent to `@llvm.uadd.with.overflow(%base, %offset)`. 5006 ValidGEP = Builder.CreateICmpUGE(ComputedGEP, IntPtr); 5007 } else { 5008 // GEP is computed as `unsigned base - unsigned offset`, therefore the 5009 // computed pointer can not be [unsigned] greater than base pointer, 5010 // unless there was an overflow. 5011 // Equivalent to `@llvm.usub.with.overflow(%base, sub(0, %offset))`. 5012 ValidGEP = Builder.CreateICmpULE(ComputedGEP, IntPtr); 5013 } 5014 ValidGEP = Builder.CreateAnd(ValidGEP, NoOffsetOverflow); 5015 Checks.emplace_back(ValidGEP, SanitizerKind::PointerOverflow); 5016 } 5017 5018 assert(!Checks.empty() && "Should have produced some checks."); 5019 5020 llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc)}; 5021 // Pass the computed GEP to the runtime to avoid emitting poisoned arguments. 5022 llvm::Value *DynamicArgs[] = {IntPtr, ComputedGEP}; 5023 EmitCheck(Checks, SanitizerHandler::PointerOverflow, StaticArgs, DynamicArgs); 5024 5025 return GEPVal; 5026 } 5027