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