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