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