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