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