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