1 //===- InstCombineCalls.cpp -----------------------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the visitCall and visitInvoke functions. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "InstCombineInternal.h" 15 #include "llvm/ADT/APFloat.h" 16 #include "llvm/ADT/APInt.h" 17 #include "llvm/ADT/ArrayRef.h" 18 #include "llvm/ADT/None.h" 19 #include "llvm/ADT/Optional.h" 20 #include "llvm/ADT/STLExtras.h" 21 #include "llvm/ADT/SmallVector.h" 22 #include "llvm/ADT/Statistic.h" 23 #include "llvm/ADT/Twine.h" 24 #include "llvm/Analysis/AssumptionCache.h" 25 #include "llvm/Analysis/InstructionSimplify.h" 26 #include "llvm/Analysis/MemoryBuiltins.h" 27 #include "llvm/Transforms/Utils/Local.h" 28 #include "llvm/Analysis/ValueTracking.h" 29 #include "llvm/IR/Attributes.h" 30 #include "llvm/IR/BasicBlock.h" 31 #include "llvm/IR/CallSite.h" 32 #include "llvm/IR/Constant.h" 33 #include "llvm/IR/Constants.h" 34 #include "llvm/IR/DataLayout.h" 35 #include "llvm/IR/DerivedTypes.h" 36 #include "llvm/IR/Function.h" 37 #include "llvm/IR/GlobalVariable.h" 38 #include "llvm/IR/InstrTypes.h" 39 #include "llvm/IR/Instruction.h" 40 #include "llvm/IR/Instructions.h" 41 #include "llvm/IR/IntrinsicInst.h" 42 #include "llvm/IR/Intrinsics.h" 43 #include "llvm/IR/LLVMContext.h" 44 #include "llvm/IR/Metadata.h" 45 #include "llvm/IR/PatternMatch.h" 46 #include "llvm/IR/Statepoint.h" 47 #include "llvm/IR/Type.h" 48 #include "llvm/IR/User.h" 49 #include "llvm/IR/Value.h" 50 #include "llvm/IR/ValueHandle.h" 51 #include "llvm/Support/AtomicOrdering.h" 52 #include "llvm/Support/Casting.h" 53 #include "llvm/Support/CommandLine.h" 54 #include "llvm/Support/Compiler.h" 55 #include "llvm/Support/Debug.h" 56 #include "llvm/Support/ErrorHandling.h" 57 #include "llvm/Support/KnownBits.h" 58 #include "llvm/Support/MathExtras.h" 59 #include "llvm/Support/raw_ostream.h" 60 #include "llvm/Transforms/InstCombine/InstCombineWorklist.h" 61 #include "llvm/Transforms/Utils/SimplifyLibCalls.h" 62 #include <algorithm> 63 #include <cassert> 64 #include <cstdint> 65 #include <cstring> 66 #include <utility> 67 #include <vector> 68 69 using namespace llvm; 70 using namespace PatternMatch; 71 72 #define DEBUG_TYPE "instcombine" 73 74 STATISTIC(NumSimplified, "Number of library calls simplified"); 75 76 static cl::opt<unsigned> GuardWideningWindow( 77 "instcombine-guard-widening-window", 78 cl::init(3), 79 cl::desc("How wide an instruction window to bypass looking for " 80 "another guard")); 81 82 /// Return the specified type promoted as it would be to pass though a va_arg 83 /// area. 84 static Type *getPromotedType(Type *Ty) { 85 if (IntegerType* ITy = dyn_cast<IntegerType>(Ty)) { 86 if (ITy->getBitWidth() < 32) 87 return Type::getInt32Ty(Ty->getContext()); 88 } 89 return Ty; 90 } 91 92 /// Return a constant boolean vector that has true elements in all positions 93 /// where the input constant data vector has an element with the sign bit set. 94 static Constant *getNegativeIsTrueBoolVec(ConstantDataVector *V) { 95 SmallVector<Constant *, 32> BoolVec; 96 IntegerType *BoolTy = Type::getInt1Ty(V->getContext()); 97 for (unsigned I = 0, E = V->getNumElements(); I != E; ++I) { 98 Constant *Elt = V->getElementAsConstant(I); 99 assert((isa<ConstantInt>(Elt) || isa<ConstantFP>(Elt)) && 100 "Unexpected constant data vector element type"); 101 bool Sign = V->getElementType()->isIntegerTy() 102 ? cast<ConstantInt>(Elt)->isNegative() 103 : cast<ConstantFP>(Elt)->isNegative(); 104 BoolVec.push_back(ConstantInt::get(BoolTy, Sign)); 105 } 106 return ConstantVector::get(BoolVec); 107 } 108 109 Instruction *InstCombiner::SimplifyAnyMemTransfer(AnyMemTransferInst *MI) { 110 unsigned DstAlign = getKnownAlignment(MI->getRawDest(), DL, MI, &AC, &DT); 111 unsigned CopyDstAlign = MI->getDestAlignment(); 112 if (CopyDstAlign < DstAlign){ 113 MI->setDestAlignment(DstAlign); 114 return MI; 115 } 116 117 unsigned SrcAlign = getKnownAlignment(MI->getRawSource(), DL, MI, &AC, &DT); 118 unsigned CopySrcAlign = MI->getSourceAlignment(); 119 if (CopySrcAlign < SrcAlign) { 120 MI->setSourceAlignment(SrcAlign); 121 return MI; 122 } 123 124 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with 125 // load/store. 126 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getLength()); 127 if (!MemOpLength) return nullptr; 128 129 // Source and destination pointer types are always "i8*" for intrinsic. See 130 // if the size is something we can handle with a single primitive load/store. 131 // A single load+store correctly handles overlapping memory in the memmove 132 // case. 133 uint64_t Size = MemOpLength->getLimitedValue(); 134 assert(Size && "0-sized memory transferring should be removed already."); 135 136 if (Size > 8 || (Size&(Size-1))) 137 return nullptr; // If not 1/2/4/8 bytes, exit. 138 139 // Use an integer load+store unless we can find something better. 140 unsigned SrcAddrSp = 141 cast<PointerType>(MI->getArgOperand(1)->getType())->getAddressSpace(); 142 unsigned DstAddrSp = 143 cast<PointerType>(MI->getArgOperand(0)->getType())->getAddressSpace(); 144 145 IntegerType* IntType = IntegerType::get(MI->getContext(), Size<<3); 146 Type *NewSrcPtrTy = PointerType::get(IntType, SrcAddrSp); 147 Type *NewDstPtrTy = PointerType::get(IntType, DstAddrSp); 148 149 // If the memcpy has metadata describing the members, see if we can get the 150 // TBAA tag describing our copy. 151 MDNode *CopyMD = nullptr; 152 if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa)) { 153 CopyMD = M; 154 } else if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa_struct)) { 155 if (M->getNumOperands() == 3 && M->getOperand(0) && 156 mdconst::hasa<ConstantInt>(M->getOperand(0)) && 157 mdconst::extract<ConstantInt>(M->getOperand(0))->isZero() && 158 M->getOperand(1) && 159 mdconst::hasa<ConstantInt>(M->getOperand(1)) && 160 mdconst::extract<ConstantInt>(M->getOperand(1))->getValue() == 161 Size && 162 M->getOperand(2) && isa<MDNode>(M->getOperand(2))) 163 CopyMD = cast<MDNode>(M->getOperand(2)); 164 } 165 166 Value *Src = Builder.CreateBitCast(MI->getArgOperand(1), NewSrcPtrTy); 167 Value *Dest = Builder.CreateBitCast(MI->getArgOperand(0), NewDstPtrTy); 168 LoadInst *L = Builder.CreateLoad(Src); 169 // Alignment from the mem intrinsic will be better, so use it. 170 L->setAlignment(CopySrcAlign); 171 if (CopyMD) 172 L->setMetadata(LLVMContext::MD_tbaa, CopyMD); 173 MDNode *LoopMemParallelMD = 174 MI->getMetadata(LLVMContext::MD_mem_parallel_loop_access); 175 if (LoopMemParallelMD) 176 L->setMetadata(LLVMContext::MD_mem_parallel_loop_access, LoopMemParallelMD); 177 MDNode *AccessGroupMD = MI->getMetadata(LLVMContext::MD_access_group); 178 if (AccessGroupMD) 179 L->setMetadata(LLVMContext::MD_access_group, AccessGroupMD); 180 181 StoreInst *S = Builder.CreateStore(L, Dest); 182 // Alignment from the mem intrinsic will be better, so use it. 183 S->setAlignment(CopyDstAlign); 184 if (CopyMD) 185 S->setMetadata(LLVMContext::MD_tbaa, CopyMD); 186 if (LoopMemParallelMD) 187 S->setMetadata(LLVMContext::MD_mem_parallel_loop_access, LoopMemParallelMD); 188 if (AccessGroupMD) 189 S->setMetadata(LLVMContext::MD_access_group, AccessGroupMD); 190 191 if (auto *MT = dyn_cast<MemTransferInst>(MI)) { 192 // non-atomics can be volatile 193 L->setVolatile(MT->isVolatile()); 194 S->setVolatile(MT->isVolatile()); 195 } 196 if (isa<AtomicMemTransferInst>(MI)) { 197 // atomics have to be unordered 198 L->setOrdering(AtomicOrdering::Unordered); 199 S->setOrdering(AtomicOrdering::Unordered); 200 } 201 202 // Set the size of the copy to 0, it will be deleted on the next iteration. 203 MI->setLength(Constant::getNullValue(MemOpLength->getType())); 204 return MI; 205 } 206 207 Instruction *InstCombiner::SimplifyAnyMemSet(AnyMemSetInst *MI) { 208 unsigned Alignment = getKnownAlignment(MI->getDest(), DL, MI, &AC, &DT); 209 if (MI->getDestAlignment() < Alignment) { 210 MI->setDestAlignment(Alignment); 211 return MI; 212 } 213 214 // Extract the length and alignment and fill if they are constant. 215 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength()); 216 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue()); 217 if (!LenC || !FillC || !FillC->getType()->isIntegerTy(8)) 218 return nullptr; 219 uint64_t Len = LenC->getLimitedValue(); 220 Alignment = MI->getDestAlignment(); 221 assert(Len && "0-sized memory setting should be removed already."); 222 223 // memset(s,c,n) -> store s, c (for n=1,2,4,8) 224 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) { 225 Type *ITy = IntegerType::get(MI->getContext(), Len*8); // n=1 -> i8. 226 227 Value *Dest = MI->getDest(); 228 unsigned DstAddrSp = cast<PointerType>(Dest->getType())->getAddressSpace(); 229 Type *NewDstPtrTy = PointerType::get(ITy, DstAddrSp); 230 Dest = Builder.CreateBitCast(Dest, NewDstPtrTy); 231 232 // Alignment 0 is identity for alignment 1 for memset, but not store. 233 if (Alignment == 0) Alignment = 1; 234 235 // Extract the fill value and store. 236 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL; 237 StoreInst *S = Builder.CreateStore(ConstantInt::get(ITy, Fill), Dest, 238 MI->isVolatile()); 239 S->setAlignment(Alignment); 240 if (isa<AtomicMemSetInst>(MI)) 241 S->setOrdering(AtomicOrdering::Unordered); 242 243 // Set the size of the copy to 0, it will be deleted on the next iteration. 244 MI->setLength(Constant::getNullValue(LenC->getType())); 245 return MI; 246 } 247 248 return nullptr; 249 } 250 251 static Value *simplifyX86immShift(const IntrinsicInst &II, 252 InstCombiner::BuilderTy &Builder) { 253 bool LogicalShift = false; 254 bool ShiftLeft = false; 255 256 switch (II.getIntrinsicID()) { 257 default: llvm_unreachable("Unexpected intrinsic!"); 258 case Intrinsic::x86_sse2_psra_d: 259 case Intrinsic::x86_sse2_psra_w: 260 case Intrinsic::x86_sse2_psrai_d: 261 case Intrinsic::x86_sse2_psrai_w: 262 case Intrinsic::x86_avx2_psra_d: 263 case Intrinsic::x86_avx2_psra_w: 264 case Intrinsic::x86_avx2_psrai_d: 265 case Intrinsic::x86_avx2_psrai_w: 266 case Intrinsic::x86_avx512_psra_q_128: 267 case Intrinsic::x86_avx512_psrai_q_128: 268 case Intrinsic::x86_avx512_psra_q_256: 269 case Intrinsic::x86_avx512_psrai_q_256: 270 case Intrinsic::x86_avx512_psra_d_512: 271 case Intrinsic::x86_avx512_psra_q_512: 272 case Intrinsic::x86_avx512_psra_w_512: 273 case Intrinsic::x86_avx512_psrai_d_512: 274 case Intrinsic::x86_avx512_psrai_q_512: 275 case Intrinsic::x86_avx512_psrai_w_512: 276 LogicalShift = false; ShiftLeft = false; 277 break; 278 case Intrinsic::x86_sse2_psrl_d: 279 case Intrinsic::x86_sse2_psrl_q: 280 case Intrinsic::x86_sse2_psrl_w: 281 case Intrinsic::x86_sse2_psrli_d: 282 case Intrinsic::x86_sse2_psrli_q: 283 case Intrinsic::x86_sse2_psrli_w: 284 case Intrinsic::x86_avx2_psrl_d: 285 case Intrinsic::x86_avx2_psrl_q: 286 case Intrinsic::x86_avx2_psrl_w: 287 case Intrinsic::x86_avx2_psrli_d: 288 case Intrinsic::x86_avx2_psrli_q: 289 case Intrinsic::x86_avx2_psrli_w: 290 case Intrinsic::x86_avx512_psrl_d_512: 291 case Intrinsic::x86_avx512_psrl_q_512: 292 case Intrinsic::x86_avx512_psrl_w_512: 293 case Intrinsic::x86_avx512_psrli_d_512: 294 case Intrinsic::x86_avx512_psrli_q_512: 295 case Intrinsic::x86_avx512_psrli_w_512: 296 LogicalShift = true; ShiftLeft = false; 297 break; 298 case Intrinsic::x86_sse2_psll_d: 299 case Intrinsic::x86_sse2_psll_q: 300 case Intrinsic::x86_sse2_psll_w: 301 case Intrinsic::x86_sse2_pslli_d: 302 case Intrinsic::x86_sse2_pslli_q: 303 case Intrinsic::x86_sse2_pslli_w: 304 case Intrinsic::x86_avx2_psll_d: 305 case Intrinsic::x86_avx2_psll_q: 306 case Intrinsic::x86_avx2_psll_w: 307 case Intrinsic::x86_avx2_pslli_d: 308 case Intrinsic::x86_avx2_pslli_q: 309 case Intrinsic::x86_avx2_pslli_w: 310 case Intrinsic::x86_avx512_psll_d_512: 311 case Intrinsic::x86_avx512_psll_q_512: 312 case Intrinsic::x86_avx512_psll_w_512: 313 case Intrinsic::x86_avx512_pslli_d_512: 314 case Intrinsic::x86_avx512_pslli_q_512: 315 case Intrinsic::x86_avx512_pslli_w_512: 316 LogicalShift = true; ShiftLeft = true; 317 break; 318 } 319 assert((LogicalShift || !ShiftLeft) && "Only logical shifts can shift left"); 320 321 // Simplify if count is constant. 322 auto Arg1 = II.getArgOperand(1); 323 auto CAZ = dyn_cast<ConstantAggregateZero>(Arg1); 324 auto CDV = dyn_cast<ConstantDataVector>(Arg1); 325 auto CInt = dyn_cast<ConstantInt>(Arg1); 326 if (!CAZ && !CDV && !CInt) 327 return nullptr; 328 329 APInt Count(64, 0); 330 if (CDV) { 331 // SSE2/AVX2 uses all the first 64-bits of the 128-bit vector 332 // operand to compute the shift amount. 333 auto VT = cast<VectorType>(CDV->getType()); 334 unsigned BitWidth = VT->getElementType()->getPrimitiveSizeInBits(); 335 assert((64 % BitWidth) == 0 && "Unexpected packed shift size"); 336 unsigned NumSubElts = 64 / BitWidth; 337 338 // Concatenate the sub-elements to create the 64-bit value. 339 for (unsigned i = 0; i != NumSubElts; ++i) { 340 unsigned SubEltIdx = (NumSubElts - 1) - i; 341 auto SubElt = cast<ConstantInt>(CDV->getElementAsConstant(SubEltIdx)); 342 Count <<= BitWidth; 343 Count |= SubElt->getValue().zextOrTrunc(64); 344 } 345 } 346 else if (CInt) 347 Count = CInt->getValue(); 348 349 auto Vec = II.getArgOperand(0); 350 auto VT = cast<VectorType>(Vec->getType()); 351 auto SVT = VT->getElementType(); 352 unsigned VWidth = VT->getNumElements(); 353 unsigned BitWidth = SVT->getPrimitiveSizeInBits(); 354 355 // If shift-by-zero then just return the original value. 356 if (Count.isNullValue()) 357 return Vec; 358 359 // Handle cases when Shift >= BitWidth. 360 if (Count.uge(BitWidth)) { 361 // If LogicalShift - just return zero. 362 if (LogicalShift) 363 return ConstantAggregateZero::get(VT); 364 365 // If ArithmeticShift - clamp Shift to (BitWidth - 1). 366 Count = APInt(64, BitWidth - 1); 367 } 368 369 // Get a constant vector of the same type as the first operand. 370 auto ShiftAmt = ConstantInt::get(SVT, Count.zextOrTrunc(BitWidth)); 371 auto ShiftVec = Builder.CreateVectorSplat(VWidth, ShiftAmt); 372 373 if (ShiftLeft) 374 return Builder.CreateShl(Vec, ShiftVec); 375 376 if (LogicalShift) 377 return Builder.CreateLShr(Vec, ShiftVec); 378 379 return Builder.CreateAShr(Vec, ShiftVec); 380 } 381 382 // Attempt to simplify AVX2 per-element shift intrinsics to a generic IR shift. 383 // Unlike the generic IR shifts, the intrinsics have defined behaviour for out 384 // of range shift amounts (logical - set to zero, arithmetic - splat sign bit). 385 static Value *simplifyX86varShift(const IntrinsicInst &II, 386 InstCombiner::BuilderTy &Builder) { 387 bool LogicalShift = false; 388 bool ShiftLeft = false; 389 390 switch (II.getIntrinsicID()) { 391 default: llvm_unreachable("Unexpected intrinsic!"); 392 case Intrinsic::x86_avx2_psrav_d: 393 case Intrinsic::x86_avx2_psrav_d_256: 394 case Intrinsic::x86_avx512_psrav_q_128: 395 case Intrinsic::x86_avx512_psrav_q_256: 396 case Intrinsic::x86_avx512_psrav_d_512: 397 case Intrinsic::x86_avx512_psrav_q_512: 398 case Intrinsic::x86_avx512_psrav_w_128: 399 case Intrinsic::x86_avx512_psrav_w_256: 400 case Intrinsic::x86_avx512_psrav_w_512: 401 LogicalShift = false; 402 ShiftLeft = false; 403 break; 404 case Intrinsic::x86_avx2_psrlv_d: 405 case Intrinsic::x86_avx2_psrlv_d_256: 406 case Intrinsic::x86_avx2_psrlv_q: 407 case Intrinsic::x86_avx2_psrlv_q_256: 408 case Intrinsic::x86_avx512_psrlv_d_512: 409 case Intrinsic::x86_avx512_psrlv_q_512: 410 case Intrinsic::x86_avx512_psrlv_w_128: 411 case Intrinsic::x86_avx512_psrlv_w_256: 412 case Intrinsic::x86_avx512_psrlv_w_512: 413 LogicalShift = true; 414 ShiftLeft = false; 415 break; 416 case Intrinsic::x86_avx2_psllv_d: 417 case Intrinsic::x86_avx2_psllv_d_256: 418 case Intrinsic::x86_avx2_psllv_q: 419 case Intrinsic::x86_avx2_psllv_q_256: 420 case Intrinsic::x86_avx512_psllv_d_512: 421 case Intrinsic::x86_avx512_psllv_q_512: 422 case Intrinsic::x86_avx512_psllv_w_128: 423 case Intrinsic::x86_avx512_psllv_w_256: 424 case Intrinsic::x86_avx512_psllv_w_512: 425 LogicalShift = true; 426 ShiftLeft = true; 427 break; 428 } 429 assert((LogicalShift || !ShiftLeft) && "Only logical shifts can shift left"); 430 431 // Simplify if all shift amounts are constant/undef. 432 auto *CShift = dyn_cast<Constant>(II.getArgOperand(1)); 433 if (!CShift) 434 return nullptr; 435 436 auto Vec = II.getArgOperand(0); 437 auto VT = cast<VectorType>(II.getType()); 438 auto SVT = VT->getVectorElementType(); 439 int NumElts = VT->getNumElements(); 440 int BitWidth = SVT->getIntegerBitWidth(); 441 442 // Collect each element's shift amount. 443 // We also collect special cases: UNDEF = -1, OUT-OF-RANGE = BitWidth. 444 bool AnyOutOfRange = false; 445 SmallVector<int, 8> ShiftAmts; 446 for (int I = 0; I < NumElts; ++I) { 447 auto *CElt = CShift->getAggregateElement(I); 448 if (CElt && isa<UndefValue>(CElt)) { 449 ShiftAmts.push_back(-1); 450 continue; 451 } 452 453 auto *COp = dyn_cast_or_null<ConstantInt>(CElt); 454 if (!COp) 455 return nullptr; 456 457 // Handle out of range shifts. 458 // If LogicalShift - set to BitWidth (special case). 459 // If ArithmeticShift - set to (BitWidth - 1) (sign splat). 460 APInt ShiftVal = COp->getValue(); 461 if (ShiftVal.uge(BitWidth)) { 462 AnyOutOfRange = LogicalShift; 463 ShiftAmts.push_back(LogicalShift ? BitWidth : BitWidth - 1); 464 continue; 465 } 466 467 ShiftAmts.push_back((int)ShiftVal.getZExtValue()); 468 } 469 470 // If all elements out of range or UNDEF, return vector of zeros/undefs. 471 // ArithmeticShift should only hit this if they are all UNDEF. 472 auto OutOfRange = [&](int Idx) { return (Idx < 0) || (BitWidth <= Idx); }; 473 if (llvm::all_of(ShiftAmts, OutOfRange)) { 474 SmallVector<Constant *, 8> ConstantVec; 475 for (int Idx : ShiftAmts) { 476 if (Idx < 0) { 477 ConstantVec.push_back(UndefValue::get(SVT)); 478 } else { 479 assert(LogicalShift && "Logical shift expected"); 480 ConstantVec.push_back(ConstantInt::getNullValue(SVT)); 481 } 482 } 483 return ConstantVector::get(ConstantVec); 484 } 485 486 // We can't handle only some out of range values with generic logical shifts. 487 if (AnyOutOfRange) 488 return nullptr; 489 490 // Build the shift amount constant vector. 491 SmallVector<Constant *, 8> ShiftVecAmts; 492 for (int Idx : ShiftAmts) { 493 if (Idx < 0) 494 ShiftVecAmts.push_back(UndefValue::get(SVT)); 495 else 496 ShiftVecAmts.push_back(ConstantInt::get(SVT, Idx)); 497 } 498 auto ShiftVec = ConstantVector::get(ShiftVecAmts); 499 500 if (ShiftLeft) 501 return Builder.CreateShl(Vec, ShiftVec); 502 503 if (LogicalShift) 504 return Builder.CreateLShr(Vec, ShiftVec); 505 506 return Builder.CreateAShr(Vec, ShiftVec); 507 } 508 509 static Value *simplifyX86pack(IntrinsicInst &II, bool IsSigned) { 510 Value *Arg0 = II.getArgOperand(0); 511 Value *Arg1 = II.getArgOperand(1); 512 Type *ResTy = II.getType(); 513 514 // Fast all undef handling. 515 if (isa<UndefValue>(Arg0) && isa<UndefValue>(Arg1)) 516 return UndefValue::get(ResTy); 517 518 Type *ArgTy = Arg0->getType(); 519 unsigned NumLanes = ResTy->getPrimitiveSizeInBits() / 128; 520 unsigned NumDstElts = ResTy->getVectorNumElements(); 521 unsigned NumSrcElts = ArgTy->getVectorNumElements(); 522 assert(NumDstElts == (2 * NumSrcElts) && "Unexpected packing types"); 523 524 unsigned NumDstEltsPerLane = NumDstElts / NumLanes; 525 unsigned NumSrcEltsPerLane = NumSrcElts / NumLanes; 526 unsigned DstScalarSizeInBits = ResTy->getScalarSizeInBits(); 527 assert(ArgTy->getScalarSizeInBits() == (2 * DstScalarSizeInBits) && 528 "Unexpected packing types"); 529 530 // Constant folding. 531 auto *Cst0 = dyn_cast<Constant>(Arg0); 532 auto *Cst1 = dyn_cast<Constant>(Arg1); 533 if (!Cst0 || !Cst1) 534 return nullptr; 535 536 SmallVector<Constant *, 32> Vals; 537 for (unsigned Lane = 0; Lane != NumLanes; ++Lane) { 538 for (unsigned Elt = 0; Elt != NumDstEltsPerLane; ++Elt) { 539 unsigned SrcIdx = Lane * NumSrcEltsPerLane + Elt % NumSrcEltsPerLane; 540 auto *Cst = (Elt >= NumSrcEltsPerLane) ? Cst1 : Cst0; 541 auto *COp = Cst->getAggregateElement(SrcIdx); 542 if (COp && isa<UndefValue>(COp)) { 543 Vals.push_back(UndefValue::get(ResTy->getScalarType())); 544 continue; 545 } 546 547 auto *CInt = dyn_cast_or_null<ConstantInt>(COp); 548 if (!CInt) 549 return nullptr; 550 551 APInt Val = CInt->getValue(); 552 assert(Val.getBitWidth() == ArgTy->getScalarSizeInBits() && 553 "Unexpected constant bitwidth"); 554 555 if (IsSigned) { 556 // PACKSS: Truncate signed value with signed saturation. 557 // Source values less than dst minint are saturated to minint. 558 // Source values greater than dst maxint are saturated to maxint. 559 if (Val.isSignedIntN(DstScalarSizeInBits)) 560 Val = Val.trunc(DstScalarSizeInBits); 561 else if (Val.isNegative()) 562 Val = APInt::getSignedMinValue(DstScalarSizeInBits); 563 else 564 Val = APInt::getSignedMaxValue(DstScalarSizeInBits); 565 } else { 566 // PACKUS: Truncate signed value with unsigned saturation. 567 // Source values less than zero are saturated to zero. 568 // Source values greater than dst maxuint are saturated to maxuint. 569 if (Val.isIntN(DstScalarSizeInBits)) 570 Val = Val.trunc(DstScalarSizeInBits); 571 else if (Val.isNegative()) 572 Val = APInt::getNullValue(DstScalarSizeInBits); 573 else 574 Val = APInt::getAllOnesValue(DstScalarSizeInBits); 575 } 576 577 Vals.push_back(ConstantInt::get(ResTy->getScalarType(), Val)); 578 } 579 } 580 581 return ConstantVector::get(Vals); 582 } 583 584 // Replace X86-specific intrinsics with generic floor-ceil where applicable. 585 static Value *simplifyX86round(IntrinsicInst &II, 586 InstCombiner::BuilderTy &Builder) { 587 ConstantInt *Arg = nullptr; 588 Intrinsic::ID IntrinsicID = II.getIntrinsicID(); 589 590 if (IntrinsicID == Intrinsic::x86_sse41_round_ss || 591 IntrinsicID == Intrinsic::x86_sse41_round_sd) 592 Arg = dyn_cast<ConstantInt>(II.getArgOperand(2)); 593 else if (IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ss || 594 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_sd) 595 Arg = dyn_cast<ConstantInt>(II.getArgOperand(4)); 596 else 597 Arg = dyn_cast<ConstantInt>(II.getArgOperand(1)); 598 if (!Arg) 599 return nullptr; 600 unsigned RoundControl = Arg->getZExtValue(); 601 602 Arg = nullptr; 603 unsigned SAE = 0; 604 if (IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ps_512 || 605 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_pd_512) 606 Arg = dyn_cast<ConstantInt>(II.getArgOperand(4)); 607 else if (IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ss || 608 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_sd) 609 Arg = dyn_cast<ConstantInt>(II.getArgOperand(5)); 610 else 611 SAE = 4; 612 if (!SAE) { 613 if (!Arg) 614 return nullptr; 615 SAE = Arg->getZExtValue(); 616 } 617 618 if (SAE != 4 || (RoundControl != 2 /*ceil*/ && RoundControl != 1 /*floor*/)) 619 return nullptr; 620 621 Value *Src, *Dst, *Mask; 622 bool IsScalar = false; 623 if (IntrinsicID == Intrinsic::x86_sse41_round_ss || 624 IntrinsicID == Intrinsic::x86_sse41_round_sd || 625 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ss || 626 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_sd) { 627 IsScalar = true; 628 if (IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ss || 629 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_sd) { 630 Mask = II.getArgOperand(3); 631 Value *Zero = Constant::getNullValue(Mask->getType()); 632 Mask = Builder.CreateAnd(Mask, 1); 633 Mask = Builder.CreateICmp(ICmpInst::ICMP_NE, Mask, Zero); 634 Dst = II.getArgOperand(2); 635 } else 636 Dst = II.getArgOperand(0); 637 Src = Builder.CreateExtractElement(II.getArgOperand(1), (uint64_t)0); 638 } else { 639 Src = II.getArgOperand(0); 640 if (IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ps_128 || 641 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ps_256 || 642 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ps_512 || 643 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_pd_128 || 644 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_pd_256 || 645 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_pd_512) { 646 Dst = II.getArgOperand(2); 647 Mask = II.getArgOperand(3); 648 } else { 649 Dst = Src; 650 Mask = ConstantInt::getAllOnesValue( 651 Builder.getIntNTy(Src->getType()->getVectorNumElements())); 652 } 653 } 654 655 Intrinsic::ID ID = (RoundControl == 2) ? Intrinsic::ceil : Intrinsic::floor; 656 Value *Res = Builder.CreateUnaryIntrinsic(ID, Src, &II); 657 if (!IsScalar) { 658 if (auto *C = dyn_cast<Constant>(Mask)) 659 if (C->isAllOnesValue()) 660 return Res; 661 auto *MaskTy = VectorType::get( 662 Builder.getInt1Ty(), cast<IntegerType>(Mask->getType())->getBitWidth()); 663 Mask = Builder.CreateBitCast(Mask, MaskTy); 664 unsigned Width = Src->getType()->getVectorNumElements(); 665 if (MaskTy->getVectorNumElements() > Width) { 666 uint32_t Indices[4]; 667 for (unsigned i = 0; i != Width; ++i) 668 Indices[i] = i; 669 Mask = Builder.CreateShuffleVector(Mask, Mask, 670 makeArrayRef(Indices, Width)); 671 } 672 return Builder.CreateSelect(Mask, Res, Dst); 673 } 674 if (IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ss || 675 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_sd) { 676 Dst = Builder.CreateExtractElement(Dst, (uint64_t)0); 677 Res = Builder.CreateSelect(Mask, Res, Dst); 678 Dst = II.getArgOperand(0); 679 } 680 return Builder.CreateInsertElement(Dst, Res, (uint64_t)0); 681 } 682 683 static Value *simplifyX86movmsk(const IntrinsicInst &II, 684 InstCombiner::BuilderTy &Builder) { 685 Value *Arg = II.getArgOperand(0); 686 Type *ResTy = II.getType(); 687 Type *ArgTy = Arg->getType(); 688 689 // movmsk(undef) -> zero as we must ensure the upper bits are zero. 690 if (isa<UndefValue>(Arg)) 691 return Constant::getNullValue(ResTy); 692 693 // We can't easily peek through x86_mmx types. 694 if (!ArgTy->isVectorTy()) 695 return nullptr; 696 697 if (auto *C = dyn_cast<Constant>(Arg)) { 698 // Extract signbits of the vector input and pack into integer result. 699 APInt Result(ResTy->getPrimitiveSizeInBits(), 0); 700 for (unsigned I = 0, E = ArgTy->getVectorNumElements(); I != E; ++I) { 701 auto *COp = C->getAggregateElement(I); 702 if (!COp) 703 return nullptr; 704 if (isa<UndefValue>(COp)) 705 continue; 706 707 auto *CInt = dyn_cast<ConstantInt>(COp); 708 auto *CFp = dyn_cast<ConstantFP>(COp); 709 if (!CInt && !CFp) 710 return nullptr; 711 712 if ((CInt && CInt->isNegative()) || (CFp && CFp->isNegative())) 713 Result.setBit(I); 714 } 715 return Constant::getIntegerValue(ResTy, Result); 716 } 717 718 // Look for a sign-extended boolean source vector as the argument to this 719 // movmsk. If the argument is bitcast, look through that, but make sure the 720 // source of that bitcast is still a vector with the same number of elements. 721 // TODO: We can also convert a bitcast with wider elements, but that requires 722 // duplicating the bool source sign bits to match the number of elements 723 // expected by the movmsk call. 724 Arg = peekThroughBitcast(Arg); 725 Value *X; 726 if (Arg->getType()->isVectorTy() && 727 Arg->getType()->getVectorNumElements() == ArgTy->getVectorNumElements() && 728 match(Arg, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) { 729 // call iM movmsk(sext <N x i1> X) --> zext (bitcast <N x i1> X to iN) to iM 730 unsigned NumElts = X->getType()->getVectorNumElements(); 731 Type *ScalarTy = Type::getIntNTy(Arg->getContext(), NumElts); 732 Value *BC = Builder.CreateBitCast(X, ScalarTy); 733 return Builder.CreateZExtOrTrunc(BC, ResTy); 734 } 735 736 return nullptr; 737 } 738 739 static Value *simplifyX86insertps(const IntrinsicInst &II, 740 InstCombiner::BuilderTy &Builder) { 741 auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2)); 742 if (!CInt) 743 return nullptr; 744 745 VectorType *VecTy = cast<VectorType>(II.getType()); 746 assert(VecTy->getNumElements() == 4 && "insertps with wrong vector type"); 747 748 // The immediate permute control byte looks like this: 749 // [3:0] - zero mask for each 32-bit lane 750 // [5:4] - select one 32-bit destination lane 751 // [7:6] - select one 32-bit source lane 752 753 uint8_t Imm = CInt->getZExtValue(); 754 uint8_t ZMask = Imm & 0xf; 755 uint8_t DestLane = (Imm >> 4) & 0x3; 756 uint8_t SourceLane = (Imm >> 6) & 0x3; 757 758 ConstantAggregateZero *ZeroVector = ConstantAggregateZero::get(VecTy); 759 760 // If all zero mask bits are set, this was just a weird way to 761 // generate a zero vector. 762 if (ZMask == 0xf) 763 return ZeroVector; 764 765 // Initialize by passing all of the first source bits through. 766 uint32_t ShuffleMask[4] = { 0, 1, 2, 3 }; 767 768 // We may replace the second operand with the zero vector. 769 Value *V1 = II.getArgOperand(1); 770 771 if (ZMask) { 772 // If the zero mask is being used with a single input or the zero mask 773 // overrides the destination lane, this is a shuffle with the zero vector. 774 if ((II.getArgOperand(0) == II.getArgOperand(1)) || 775 (ZMask & (1 << DestLane))) { 776 V1 = ZeroVector; 777 // We may still move 32-bits of the first source vector from one lane 778 // to another. 779 ShuffleMask[DestLane] = SourceLane; 780 // The zero mask may override the previous insert operation. 781 for (unsigned i = 0; i < 4; ++i) 782 if ((ZMask >> i) & 0x1) 783 ShuffleMask[i] = i + 4; 784 } else { 785 // TODO: Model this case as 2 shuffles or a 'logical and' plus shuffle? 786 return nullptr; 787 } 788 } else { 789 // Replace the selected destination lane with the selected source lane. 790 ShuffleMask[DestLane] = SourceLane + 4; 791 } 792 793 return Builder.CreateShuffleVector(II.getArgOperand(0), V1, ShuffleMask); 794 } 795 796 /// Attempt to simplify SSE4A EXTRQ/EXTRQI instructions using constant folding 797 /// or conversion to a shuffle vector. 798 static Value *simplifyX86extrq(IntrinsicInst &II, Value *Op0, 799 ConstantInt *CILength, ConstantInt *CIIndex, 800 InstCombiner::BuilderTy &Builder) { 801 auto LowConstantHighUndef = [&](uint64_t Val) { 802 Type *IntTy64 = Type::getInt64Ty(II.getContext()); 803 Constant *Args[] = {ConstantInt::get(IntTy64, Val), 804 UndefValue::get(IntTy64)}; 805 return ConstantVector::get(Args); 806 }; 807 808 // See if we're dealing with constant values. 809 Constant *C0 = dyn_cast<Constant>(Op0); 810 ConstantInt *CI0 = 811 C0 ? dyn_cast_or_null<ConstantInt>(C0->getAggregateElement((unsigned)0)) 812 : nullptr; 813 814 // Attempt to constant fold. 815 if (CILength && CIIndex) { 816 // From AMD documentation: "The bit index and field length are each six 817 // bits in length other bits of the field are ignored." 818 APInt APIndex = CIIndex->getValue().zextOrTrunc(6); 819 APInt APLength = CILength->getValue().zextOrTrunc(6); 820 821 unsigned Index = APIndex.getZExtValue(); 822 823 // From AMD documentation: "a value of zero in the field length is 824 // defined as length of 64". 825 unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue(); 826 827 // From AMD documentation: "If the sum of the bit index + length field 828 // is greater than 64, the results are undefined". 829 unsigned End = Index + Length; 830 831 // Note that both field index and field length are 8-bit quantities. 832 // Since variables 'Index' and 'Length' are unsigned values 833 // obtained from zero-extending field index and field length 834 // respectively, their sum should never wrap around. 835 if (End > 64) 836 return UndefValue::get(II.getType()); 837 838 // If we are inserting whole bytes, we can convert this to a shuffle. 839 // Lowering can recognize EXTRQI shuffle masks. 840 if ((Length % 8) == 0 && (Index % 8) == 0) { 841 // Convert bit indices to byte indices. 842 Length /= 8; 843 Index /= 8; 844 845 Type *IntTy8 = Type::getInt8Ty(II.getContext()); 846 Type *IntTy32 = Type::getInt32Ty(II.getContext()); 847 VectorType *ShufTy = VectorType::get(IntTy8, 16); 848 849 SmallVector<Constant *, 16> ShuffleMask; 850 for (int i = 0; i != (int)Length; ++i) 851 ShuffleMask.push_back( 852 Constant::getIntegerValue(IntTy32, APInt(32, i + Index))); 853 for (int i = Length; i != 8; ++i) 854 ShuffleMask.push_back( 855 Constant::getIntegerValue(IntTy32, APInt(32, i + 16))); 856 for (int i = 8; i != 16; ++i) 857 ShuffleMask.push_back(UndefValue::get(IntTy32)); 858 859 Value *SV = Builder.CreateShuffleVector( 860 Builder.CreateBitCast(Op0, ShufTy), 861 ConstantAggregateZero::get(ShufTy), ConstantVector::get(ShuffleMask)); 862 return Builder.CreateBitCast(SV, II.getType()); 863 } 864 865 // Constant Fold - shift Index'th bit to lowest position and mask off 866 // Length bits. 867 if (CI0) { 868 APInt Elt = CI0->getValue(); 869 Elt.lshrInPlace(Index); 870 Elt = Elt.zextOrTrunc(Length); 871 return LowConstantHighUndef(Elt.getZExtValue()); 872 } 873 874 // If we were an EXTRQ call, we'll save registers if we convert to EXTRQI. 875 if (II.getIntrinsicID() == Intrinsic::x86_sse4a_extrq) { 876 Value *Args[] = {Op0, CILength, CIIndex}; 877 Module *M = II.getModule(); 878 Value *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_extrqi); 879 return Builder.CreateCall(F, Args); 880 } 881 } 882 883 // Constant Fold - extraction from zero is always {zero, undef}. 884 if (CI0 && CI0->isZero()) 885 return LowConstantHighUndef(0); 886 887 return nullptr; 888 } 889 890 /// Attempt to simplify SSE4A INSERTQ/INSERTQI instructions using constant 891 /// folding or conversion to a shuffle vector. 892 static Value *simplifyX86insertq(IntrinsicInst &II, Value *Op0, Value *Op1, 893 APInt APLength, APInt APIndex, 894 InstCombiner::BuilderTy &Builder) { 895 // From AMD documentation: "The bit index and field length are each six bits 896 // in length other bits of the field are ignored." 897 APIndex = APIndex.zextOrTrunc(6); 898 APLength = APLength.zextOrTrunc(6); 899 900 // Attempt to constant fold. 901 unsigned Index = APIndex.getZExtValue(); 902 903 // From AMD documentation: "a value of zero in the field length is 904 // defined as length of 64". 905 unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue(); 906 907 // From AMD documentation: "If the sum of the bit index + length field 908 // is greater than 64, the results are undefined". 909 unsigned End = Index + Length; 910 911 // Note that both field index and field length are 8-bit quantities. 912 // Since variables 'Index' and 'Length' are unsigned values 913 // obtained from zero-extending field index and field length 914 // respectively, their sum should never wrap around. 915 if (End > 64) 916 return UndefValue::get(II.getType()); 917 918 // If we are inserting whole bytes, we can convert this to a shuffle. 919 // Lowering can recognize INSERTQI shuffle masks. 920 if ((Length % 8) == 0 && (Index % 8) == 0) { 921 // Convert bit indices to byte indices. 922 Length /= 8; 923 Index /= 8; 924 925 Type *IntTy8 = Type::getInt8Ty(II.getContext()); 926 Type *IntTy32 = Type::getInt32Ty(II.getContext()); 927 VectorType *ShufTy = VectorType::get(IntTy8, 16); 928 929 SmallVector<Constant *, 16> ShuffleMask; 930 for (int i = 0; i != (int)Index; ++i) 931 ShuffleMask.push_back(Constant::getIntegerValue(IntTy32, APInt(32, i))); 932 for (int i = 0; i != (int)Length; ++i) 933 ShuffleMask.push_back( 934 Constant::getIntegerValue(IntTy32, APInt(32, i + 16))); 935 for (int i = Index + Length; i != 8; ++i) 936 ShuffleMask.push_back(Constant::getIntegerValue(IntTy32, APInt(32, i))); 937 for (int i = 8; i != 16; ++i) 938 ShuffleMask.push_back(UndefValue::get(IntTy32)); 939 940 Value *SV = Builder.CreateShuffleVector(Builder.CreateBitCast(Op0, ShufTy), 941 Builder.CreateBitCast(Op1, ShufTy), 942 ConstantVector::get(ShuffleMask)); 943 return Builder.CreateBitCast(SV, II.getType()); 944 } 945 946 // See if we're dealing with constant values. 947 Constant *C0 = dyn_cast<Constant>(Op0); 948 Constant *C1 = dyn_cast<Constant>(Op1); 949 ConstantInt *CI00 = 950 C0 ? dyn_cast_or_null<ConstantInt>(C0->getAggregateElement((unsigned)0)) 951 : nullptr; 952 ConstantInt *CI10 = 953 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)0)) 954 : nullptr; 955 956 // Constant Fold - insert bottom Length bits starting at the Index'th bit. 957 if (CI00 && CI10) { 958 APInt V00 = CI00->getValue(); 959 APInt V10 = CI10->getValue(); 960 APInt Mask = APInt::getLowBitsSet(64, Length).shl(Index); 961 V00 = V00 & ~Mask; 962 V10 = V10.zextOrTrunc(Length).zextOrTrunc(64).shl(Index); 963 APInt Val = V00 | V10; 964 Type *IntTy64 = Type::getInt64Ty(II.getContext()); 965 Constant *Args[] = {ConstantInt::get(IntTy64, Val.getZExtValue()), 966 UndefValue::get(IntTy64)}; 967 return ConstantVector::get(Args); 968 } 969 970 // If we were an INSERTQ call, we'll save demanded elements if we convert to 971 // INSERTQI. 972 if (II.getIntrinsicID() == Intrinsic::x86_sse4a_insertq) { 973 Type *IntTy8 = Type::getInt8Ty(II.getContext()); 974 Constant *CILength = ConstantInt::get(IntTy8, Length, false); 975 Constant *CIIndex = ConstantInt::get(IntTy8, Index, false); 976 977 Value *Args[] = {Op0, Op1, CILength, CIIndex}; 978 Module *M = II.getModule(); 979 Value *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_insertqi); 980 return Builder.CreateCall(F, Args); 981 } 982 983 return nullptr; 984 } 985 986 /// Attempt to convert pshufb* to shufflevector if the mask is constant. 987 static Value *simplifyX86pshufb(const IntrinsicInst &II, 988 InstCombiner::BuilderTy &Builder) { 989 Constant *V = dyn_cast<Constant>(II.getArgOperand(1)); 990 if (!V) 991 return nullptr; 992 993 auto *VecTy = cast<VectorType>(II.getType()); 994 auto *MaskEltTy = Type::getInt32Ty(II.getContext()); 995 unsigned NumElts = VecTy->getNumElements(); 996 assert((NumElts == 16 || NumElts == 32 || NumElts == 64) && 997 "Unexpected number of elements in shuffle mask!"); 998 999 // Construct a shuffle mask from constant integers or UNDEFs. 1000 Constant *Indexes[64] = {nullptr}; 1001 1002 // Each byte in the shuffle control mask forms an index to permute the 1003 // corresponding byte in the destination operand. 1004 for (unsigned I = 0; I < NumElts; ++I) { 1005 Constant *COp = V->getAggregateElement(I); 1006 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp))) 1007 return nullptr; 1008 1009 if (isa<UndefValue>(COp)) { 1010 Indexes[I] = UndefValue::get(MaskEltTy); 1011 continue; 1012 } 1013 1014 int8_t Index = cast<ConstantInt>(COp)->getValue().getZExtValue(); 1015 1016 // If the most significant bit (bit[7]) of each byte of the shuffle 1017 // control mask is set, then zero is written in the result byte. 1018 // The zero vector is in the right-hand side of the resulting 1019 // shufflevector. 1020 1021 // The value of each index for the high 128-bit lane is the least 1022 // significant 4 bits of the respective shuffle control byte. 1023 Index = ((Index < 0) ? NumElts : Index & 0x0F) + (I & 0xF0); 1024 Indexes[I] = ConstantInt::get(MaskEltTy, Index); 1025 } 1026 1027 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, NumElts)); 1028 auto V1 = II.getArgOperand(0); 1029 auto V2 = Constant::getNullValue(VecTy); 1030 return Builder.CreateShuffleVector(V1, V2, ShuffleMask); 1031 } 1032 1033 /// Attempt to convert vpermilvar* to shufflevector if the mask is constant. 1034 static Value *simplifyX86vpermilvar(const IntrinsicInst &II, 1035 InstCombiner::BuilderTy &Builder) { 1036 Constant *V = dyn_cast<Constant>(II.getArgOperand(1)); 1037 if (!V) 1038 return nullptr; 1039 1040 auto *VecTy = cast<VectorType>(II.getType()); 1041 auto *MaskEltTy = Type::getInt32Ty(II.getContext()); 1042 unsigned NumElts = VecTy->getVectorNumElements(); 1043 bool IsPD = VecTy->getScalarType()->isDoubleTy(); 1044 unsigned NumLaneElts = IsPD ? 2 : 4; 1045 assert(NumElts == 16 || NumElts == 8 || NumElts == 4 || NumElts == 2); 1046 1047 // Construct a shuffle mask from constant integers or UNDEFs. 1048 Constant *Indexes[16] = {nullptr}; 1049 1050 // The intrinsics only read one or two bits, clear the rest. 1051 for (unsigned I = 0; I < NumElts; ++I) { 1052 Constant *COp = V->getAggregateElement(I); 1053 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp))) 1054 return nullptr; 1055 1056 if (isa<UndefValue>(COp)) { 1057 Indexes[I] = UndefValue::get(MaskEltTy); 1058 continue; 1059 } 1060 1061 APInt Index = cast<ConstantInt>(COp)->getValue(); 1062 Index = Index.zextOrTrunc(32).getLoBits(2); 1063 1064 // The PD variants uses bit 1 to select per-lane element index, so 1065 // shift down to convert to generic shuffle mask index. 1066 if (IsPD) 1067 Index.lshrInPlace(1); 1068 1069 // The _256 variants are a bit trickier since the mask bits always index 1070 // into the corresponding 128 half. In order to convert to a generic 1071 // shuffle, we have to make that explicit. 1072 Index += APInt(32, (I / NumLaneElts) * NumLaneElts); 1073 1074 Indexes[I] = ConstantInt::get(MaskEltTy, Index); 1075 } 1076 1077 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, NumElts)); 1078 auto V1 = II.getArgOperand(0); 1079 auto V2 = UndefValue::get(V1->getType()); 1080 return Builder.CreateShuffleVector(V1, V2, ShuffleMask); 1081 } 1082 1083 /// Attempt to convert vpermd/vpermps to shufflevector if the mask is constant. 1084 static Value *simplifyX86vpermv(const IntrinsicInst &II, 1085 InstCombiner::BuilderTy &Builder) { 1086 auto *V = dyn_cast<Constant>(II.getArgOperand(1)); 1087 if (!V) 1088 return nullptr; 1089 1090 auto *VecTy = cast<VectorType>(II.getType()); 1091 auto *MaskEltTy = Type::getInt32Ty(II.getContext()); 1092 unsigned Size = VecTy->getNumElements(); 1093 assert((Size == 4 || Size == 8 || Size == 16 || Size == 32 || Size == 64) && 1094 "Unexpected shuffle mask size"); 1095 1096 // Construct a shuffle mask from constant integers or UNDEFs. 1097 Constant *Indexes[64] = {nullptr}; 1098 1099 for (unsigned I = 0; I < Size; ++I) { 1100 Constant *COp = V->getAggregateElement(I); 1101 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp))) 1102 return nullptr; 1103 1104 if (isa<UndefValue>(COp)) { 1105 Indexes[I] = UndefValue::get(MaskEltTy); 1106 continue; 1107 } 1108 1109 uint32_t Index = cast<ConstantInt>(COp)->getZExtValue(); 1110 Index &= Size - 1; 1111 Indexes[I] = ConstantInt::get(MaskEltTy, Index); 1112 } 1113 1114 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, Size)); 1115 auto V1 = II.getArgOperand(0); 1116 auto V2 = UndefValue::get(VecTy); 1117 return Builder.CreateShuffleVector(V1, V2, ShuffleMask); 1118 } 1119 1120 /// Decode XOP integer vector comparison intrinsics. 1121 static Value *simplifyX86vpcom(const IntrinsicInst &II, 1122 InstCombiner::BuilderTy &Builder, 1123 bool IsSigned) { 1124 if (auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2))) { 1125 uint64_t Imm = CInt->getZExtValue() & 0x7; 1126 VectorType *VecTy = cast<VectorType>(II.getType()); 1127 CmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; 1128 1129 switch (Imm) { 1130 case 0x0: 1131 Pred = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; 1132 break; 1133 case 0x1: 1134 Pred = IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 1135 break; 1136 case 0x2: 1137 Pred = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 1138 break; 1139 case 0x3: 1140 Pred = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 1141 break; 1142 case 0x4: 1143 Pred = ICmpInst::ICMP_EQ; break; 1144 case 0x5: 1145 Pred = ICmpInst::ICMP_NE; break; 1146 case 0x6: 1147 return ConstantInt::getSigned(VecTy, 0); // FALSE 1148 case 0x7: 1149 return ConstantInt::getSigned(VecTy, -1); // TRUE 1150 } 1151 1152 if (Value *Cmp = Builder.CreateICmp(Pred, II.getArgOperand(0), 1153 II.getArgOperand(1))) 1154 return Builder.CreateSExtOrTrunc(Cmp, VecTy); 1155 } 1156 return nullptr; 1157 } 1158 1159 static bool maskIsAllOneOrUndef(Value *Mask) { 1160 auto *ConstMask = dyn_cast<Constant>(Mask); 1161 if (!ConstMask) 1162 return false; 1163 if (ConstMask->isAllOnesValue() || isa<UndefValue>(ConstMask)) 1164 return true; 1165 for (unsigned I = 0, E = ConstMask->getType()->getVectorNumElements(); I != E; 1166 ++I) { 1167 if (auto *MaskElt = ConstMask->getAggregateElement(I)) 1168 if (MaskElt->isAllOnesValue() || isa<UndefValue>(MaskElt)) 1169 continue; 1170 return false; 1171 } 1172 return true; 1173 } 1174 1175 static Value *simplifyMaskedLoad(const IntrinsicInst &II, 1176 InstCombiner::BuilderTy &Builder) { 1177 // If the mask is all ones or undefs, this is a plain vector load of the 1st 1178 // argument. 1179 if (maskIsAllOneOrUndef(II.getArgOperand(2))) { 1180 Value *LoadPtr = II.getArgOperand(0); 1181 unsigned Alignment = cast<ConstantInt>(II.getArgOperand(1))->getZExtValue(); 1182 return Builder.CreateAlignedLoad(LoadPtr, Alignment, "unmaskedload"); 1183 } 1184 1185 return nullptr; 1186 } 1187 1188 static Instruction *simplifyMaskedStore(IntrinsicInst &II, InstCombiner &IC) { 1189 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3)); 1190 if (!ConstMask) 1191 return nullptr; 1192 1193 // If the mask is all zeros, this instruction does nothing. 1194 if (ConstMask->isNullValue()) 1195 return IC.eraseInstFromFunction(II); 1196 1197 // If the mask is all ones, this is a plain vector store of the 1st argument. 1198 if (ConstMask->isAllOnesValue()) { 1199 Value *StorePtr = II.getArgOperand(1); 1200 unsigned Alignment = cast<ConstantInt>(II.getArgOperand(2))->getZExtValue(); 1201 return new StoreInst(II.getArgOperand(0), StorePtr, false, Alignment); 1202 } 1203 1204 return nullptr; 1205 } 1206 1207 static Instruction *simplifyMaskedGather(IntrinsicInst &II, InstCombiner &IC) { 1208 // If the mask is all zeros, return the "passthru" argument of the gather. 1209 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(2)); 1210 if (ConstMask && ConstMask->isNullValue()) 1211 return IC.replaceInstUsesWith(II, II.getArgOperand(3)); 1212 1213 return nullptr; 1214 } 1215 1216 /// This function transforms launder.invariant.group and strip.invariant.group 1217 /// like: 1218 /// launder(launder(%x)) -> launder(%x) (the result is not the argument) 1219 /// launder(strip(%x)) -> launder(%x) 1220 /// strip(strip(%x)) -> strip(%x) (the result is not the argument) 1221 /// strip(launder(%x)) -> strip(%x) 1222 /// This is legal because it preserves the most recent information about 1223 /// the presence or absence of invariant.group. 1224 static Instruction *simplifyInvariantGroupIntrinsic(IntrinsicInst &II, 1225 InstCombiner &IC) { 1226 auto *Arg = II.getArgOperand(0); 1227 auto *StrippedArg = Arg->stripPointerCasts(); 1228 auto *StrippedInvariantGroupsArg = Arg->stripPointerCastsAndInvariantGroups(); 1229 if (StrippedArg == StrippedInvariantGroupsArg) 1230 return nullptr; // No launders/strips to remove. 1231 1232 Value *Result = nullptr; 1233 1234 if (II.getIntrinsicID() == Intrinsic::launder_invariant_group) 1235 Result = IC.Builder.CreateLaunderInvariantGroup(StrippedInvariantGroupsArg); 1236 else if (II.getIntrinsicID() == Intrinsic::strip_invariant_group) 1237 Result = IC.Builder.CreateStripInvariantGroup(StrippedInvariantGroupsArg); 1238 else 1239 llvm_unreachable( 1240 "simplifyInvariantGroupIntrinsic only handles launder and strip"); 1241 if (Result->getType()->getPointerAddressSpace() != 1242 II.getType()->getPointerAddressSpace()) 1243 Result = IC.Builder.CreateAddrSpaceCast(Result, II.getType()); 1244 if (Result->getType() != II.getType()) 1245 Result = IC.Builder.CreateBitCast(Result, II.getType()); 1246 1247 return cast<Instruction>(Result); 1248 } 1249 1250 static Instruction *simplifyMaskedScatter(IntrinsicInst &II, InstCombiner &IC) { 1251 // If the mask is all zeros, a scatter does nothing. 1252 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3)); 1253 if (ConstMask && ConstMask->isNullValue()) 1254 return IC.eraseInstFromFunction(II); 1255 1256 return nullptr; 1257 } 1258 1259 static Instruction *foldCttzCtlz(IntrinsicInst &II, InstCombiner &IC) { 1260 assert((II.getIntrinsicID() == Intrinsic::cttz || 1261 II.getIntrinsicID() == Intrinsic::ctlz) && 1262 "Expected cttz or ctlz intrinsic"); 1263 Value *Op0 = II.getArgOperand(0); 1264 1265 KnownBits Known = IC.computeKnownBits(Op0, 0, &II); 1266 1267 // Create a mask for bits above (ctlz) or below (cttz) the first known one. 1268 bool IsTZ = II.getIntrinsicID() == Intrinsic::cttz; 1269 unsigned PossibleZeros = IsTZ ? Known.countMaxTrailingZeros() 1270 : Known.countMaxLeadingZeros(); 1271 unsigned DefiniteZeros = IsTZ ? Known.countMinTrailingZeros() 1272 : Known.countMinLeadingZeros(); 1273 1274 // If all bits above (ctlz) or below (cttz) the first known one are known 1275 // zero, this value is constant. 1276 // FIXME: This should be in InstSimplify because we're replacing an 1277 // instruction with a constant. 1278 if (PossibleZeros == DefiniteZeros) { 1279 auto *C = ConstantInt::get(Op0->getType(), DefiniteZeros); 1280 return IC.replaceInstUsesWith(II, C); 1281 } 1282 1283 // If the input to cttz/ctlz is known to be non-zero, 1284 // then change the 'ZeroIsUndef' parameter to 'true' 1285 // because we know the zero behavior can't affect the result. 1286 if (!Known.One.isNullValue() || 1287 isKnownNonZero(Op0, IC.getDataLayout(), 0, &IC.getAssumptionCache(), &II, 1288 &IC.getDominatorTree())) { 1289 if (!match(II.getArgOperand(1), m_One())) { 1290 II.setOperand(1, IC.Builder.getTrue()); 1291 return &II; 1292 } 1293 } 1294 1295 // Add range metadata since known bits can't completely reflect what we know. 1296 // TODO: Handle splat vectors. 1297 auto *IT = dyn_cast<IntegerType>(Op0->getType()); 1298 if (IT && IT->getBitWidth() != 1 && !II.getMetadata(LLVMContext::MD_range)) { 1299 Metadata *LowAndHigh[] = { 1300 ConstantAsMetadata::get(ConstantInt::get(IT, DefiniteZeros)), 1301 ConstantAsMetadata::get(ConstantInt::get(IT, PossibleZeros + 1))}; 1302 II.setMetadata(LLVMContext::MD_range, 1303 MDNode::get(II.getContext(), LowAndHigh)); 1304 return &II; 1305 } 1306 1307 return nullptr; 1308 } 1309 1310 static Instruction *foldCtpop(IntrinsicInst &II, InstCombiner &IC) { 1311 assert(II.getIntrinsicID() == Intrinsic::ctpop && 1312 "Expected ctpop intrinsic"); 1313 Value *Op0 = II.getArgOperand(0); 1314 // FIXME: Try to simplify vectors of integers. 1315 auto *IT = dyn_cast<IntegerType>(Op0->getType()); 1316 if (!IT) 1317 return nullptr; 1318 1319 unsigned BitWidth = IT->getBitWidth(); 1320 KnownBits Known(BitWidth); 1321 IC.computeKnownBits(Op0, Known, 0, &II); 1322 1323 unsigned MinCount = Known.countMinPopulation(); 1324 unsigned MaxCount = Known.countMaxPopulation(); 1325 1326 // Add range metadata since known bits can't completely reflect what we know. 1327 if (IT->getBitWidth() != 1 && !II.getMetadata(LLVMContext::MD_range)) { 1328 Metadata *LowAndHigh[] = { 1329 ConstantAsMetadata::get(ConstantInt::get(IT, MinCount)), 1330 ConstantAsMetadata::get(ConstantInt::get(IT, MaxCount + 1))}; 1331 II.setMetadata(LLVMContext::MD_range, 1332 MDNode::get(II.getContext(), LowAndHigh)); 1333 return &II; 1334 } 1335 1336 return nullptr; 1337 } 1338 1339 // TODO: If the x86 backend knew how to convert a bool vector mask back to an 1340 // XMM register mask efficiently, we could transform all x86 masked intrinsics 1341 // to LLVM masked intrinsics and remove the x86 masked intrinsic defs. 1342 static Instruction *simplifyX86MaskedLoad(IntrinsicInst &II, InstCombiner &IC) { 1343 Value *Ptr = II.getOperand(0); 1344 Value *Mask = II.getOperand(1); 1345 Constant *ZeroVec = Constant::getNullValue(II.getType()); 1346 1347 // Special case a zero mask since that's not a ConstantDataVector. 1348 // This masked load instruction creates a zero vector. 1349 if (isa<ConstantAggregateZero>(Mask)) 1350 return IC.replaceInstUsesWith(II, ZeroVec); 1351 1352 auto *ConstMask = dyn_cast<ConstantDataVector>(Mask); 1353 if (!ConstMask) 1354 return nullptr; 1355 1356 // The mask is constant. Convert this x86 intrinsic to the LLVM instrinsic 1357 // to allow target-independent optimizations. 1358 1359 // First, cast the x86 intrinsic scalar pointer to a vector pointer to match 1360 // the LLVM intrinsic definition for the pointer argument. 1361 unsigned AddrSpace = cast<PointerType>(Ptr->getType())->getAddressSpace(); 1362 PointerType *VecPtrTy = PointerType::get(II.getType(), AddrSpace); 1363 Value *PtrCast = IC.Builder.CreateBitCast(Ptr, VecPtrTy, "castvec"); 1364 1365 // Second, convert the x86 XMM integer vector mask to a vector of bools based 1366 // on each element's most significant bit (the sign bit). 1367 Constant *BoolMask = getNegativeIsTrueBoolVec(ConstMask); 1368 1369 // The pass-through vector for an x86 masked load is a zero vector. 1370 CallInst *NewMaskedLoad = 1371 IC.Builder.CreateMaskedLoad(PtrCast, 1, BoolMask, ZeroVec); 1372 return IC.replaceInstUsesWith(II, NewMaskedLoad); 1373 } 1374 1375 // TODO: If the x86 backend knew how to convert a bool vector mask back to an 1376 // XMM register mask efficiently, we could transform all x86 masked intrinsics 1377 // to LLVM masked intrinsics and remove the x86 masked intrinsic defs. 1378 static bool simplifyX86MaskedStore(IntrinsicInst &II, InstCombiner &IC) { 1379 Value *Ptr = II.getOperand(0); 1380 Value *Mask = II.getOperand(1); 1381 Value *Vec = II.getOperand(2); 1382 1383 // Special case a zero mask since that's not a ConstantDataVector: 1384 // this masked store instruction does nothing. 1385 if (isa<ConstantAggregateZero>(Mask)) { 1386 IC.eraseInstFromFunction(II); 1387 return true; 1388 } 1389 1390 // The SSE2 version is too weird (eg, unaligned but non-temporal) to do 1391 // anything else at this level. 1392 if (II.getIntrinsicID() == Intrinsic::x86_sse2_maskmov_dqu) 1393 return false; 1394 1395 auto *ConstMask = dyn_cast<ConstantDataVector>(Mask); 1396 if (!ConstMask) 1397 return false; 1398 1399 // The mask is constant. Convert this x86 intrinsic to the LLVM instrinsic 1400 // to allow target-independent optimizations. 1401 1402 // First, cast the x86 intrinsic scalar pointer to a vector pointer to match 1403 // the LLVM intrinsic definition for the pointer argument. 1404 unsigned AddrSpace = cast<PointerType>(Ptr->getType())->getAddressSpace(); 1405 PointerType *VecPtrTy = PointerType::get(Vec->getType(), AddrSpace); 1406 Value *PtrCast = IC.Builder.CreateBitCast(Ptr, VecPtrTy, "castvec"); 1407 1408 // Second, convert the x86 XMM integer vector mask to a vector of bools based 1409 // on each element's most significant bit (the sign bit). 1410 Constant *BoolMask = getNegativeIsTrueBoolVec(ConstMask); 1411 1412 IC.Builder.CreateMaskedStore(Vec, PtrCast, 1, BoolMask); 1413 1414 // 'Replace uses' doesn't work for stores. Erase the original masked store. 1415 IC.eraseInstFromFunction(II); 1416 return true; 1417 } 1418 1419 // Constant fold llvm.amdgcn.fmed3 intrinsics for standard inputs. 1420 // 1421 // A single NaN input is folded to minnum, so we rely on that folding for 1422 // handling NaNs. 1423 static APFloat fmed3AMDGCN(const APFloat &Src0, const APFloat &Src1, 1424 const APFloat &Src2) { 1425 APFloat Max3 = maxnum(maxnum(Src0, Src1), Src2); 1426 1427 APFloat::cmpResult Cmp0 = Max3.compare(Src0); 1428 assert(Cmp0 != APFloat::cmpUnordered && "nans handled separately"); 1429 if (Cmp0 == APFloat::cmpEqual) 1430 return maxnum(Src1, Src2); 1431 1432 APFloat::cmpResult Cmp1 = Max3.compare(Src1); 1433 assert(Cmp1 != APFloat::cmpUnordered && "nans handled separately"); 1434 if (Cmp1 == APFloat::cmpEqual) 1435 return maxnum(Src0, Src2); 1436 1437 return maxnum(Src0, Src1); 1438 } 1439 1440 /// Convert a table lookup to shufflevector if the mask is constant. 1441 /// This could benefit tbl1 if the mask is { 7,6,5,4,3,2,1,0 }, in 1442 /// which case we could lower the shufflevector with rev64 instructions 1443 /// as it's actually a byte reverse. 1444 static Value *simplifyNeonTbl1(const IntrinsicInst &II, 1445 InstCombiner::BuilderTy &Builder) { 1446 // Bail out if the mask is not a constant. 1447 auto *C = dyn_cast<Constant>(II.getArgOperand(1)); 1448 if (!C) 1449 return nullptr; 1450 1451 auto *VecTy = cast<VectorType>(II.getType()); 1452 unsigned NumElts = VecTy->getNumElements(); 1453 1454 // Only perform this transformation for <8 x i8> vector types. 1455 if (!VecTy->getElementType()->isIntegerTy(8) || NumElts != 8) 1456 return nullptr; 1457 1458 uint32_t Indexes[8]; 1459 1460 for (unsigned I = 0; I < NumElts; ++I) { 1461 Constant *COp = C->getAggregateElement(I); 1462 1463 if (!COp || !isa<ConstantInt>(COp)) 1464 return nullptr; 1465 1466 Indexes[I] = cast<ConstantInt>(COp)->getLimitedValue(); 1467 1468 // Make sure the mask indices are in range. 1469 if (Indexes[I] >= NumElts) 1470 return nullptr; 1471 } 1472 1473 auto *ShuffleMask = ConstantDataVector::get(II.getContext(), 1474 makeArrayRef(Indexes)); 1475 auto *V1 = II.getArgOperand(0); 1476 auto *V2 = Constant::getNullValue(V1->getType()); 1477 return Builder.CreateShuffleVector(V1, V2, ShuffleMask); 1478 } 1479 1480 /// Convert a vector load intrinsic into a simple llvm load instruction. 1481 /// This is beneficial when the underlying object being addressed comes 1482 /// from a constant, since we get constant-folding for free. 1483 static Value *simplifyNeonVld1(const IntrinsicInst &II, 1484 unsigned MemAlign, 1485 InstCombiner::BuilderTy &Builder) { 1486 auto *IntrAlign = dyn_cast<ConstantInt>(II.getArgOperand(1)); 1487 1488 if (!IntrAlign) 1489 return nullptr; 1490 1491 unsigned Alignment = IntrAlign->getLimitedValue() < MemAlign ? 1492 MemAlign : IntrAlign->getLimitedValue(); 1493 1494 if (!isPowerOf2_32(Alignment)) 1495 return nullptr; 1496 1497 auto *BCastInst = Builder.CreateBitCast(II.getArgOperand(0), 1498 PointerType::get(II.getType(), 0)); 1499 return Builder.CreateAlignedLoad(BCastInst, Alignment); 1500 } 1501 1502 // Returns true iff the 2 intrinsics have the same operands, limiting the 1503 // comparison to the first NumOperands. 1504 static bool haveSameOperands(const IntrinsicInst &I, const IntrinsicInst &E, 1505 unsigned NumOperands) { 1506 assert(I.getNumArgOperands() >= NumOperands && "Not enough operands"); 1507 assert(E.getNumArgOperands() >= NumOperands && "Not enough operands"); 1508 for (unsigned i = 0; i < NumOperands; i++) 1509 if (I.getArgOperand(i) != E.getArgOperand(i)) 1510 return false; 1511 return true; 1512 } 1513 1514 // Remove trivially empty start/end intrinsic ranges, i.e. a start 1515 // immediately followed by an end (ignoring debuginfo or other 1516 // start/end intrinsics in between). As this handles only the most trivial 1517 // cases, tracking the nesting level is not needed: 1518 // 1519 // call @llvm.foo.start(i1 0) ; &I 1520 // call @llvm.foo.start(i1 0) 1521 // call @llvm.foo.end(i1 0) ; This one will not be skipped: it will be removed 1522 // call @llvm.foo.end(i1 0) 1523 static bool removeTriviallyEmptyRange(IntrinsicInst &I, unsigned StartID, 1524 unsigned EndID, InstCombiner &IC) { 1525 assert(I.getIntrinsicID() == StartID && 1526 "Start intrinsic does not have expected ID"); 1527 BasicBlock::iterator BI(I), BE(I.getParent()->end()); 1528 for (++BI; BI != BE; ++BI) { 1529 if (auto *E = dyn_cast<IntrinsicInst>(BI)) { 1530 if (isa<DbgInfoIntrinsic>(E) || E->getIntrinsicID() == StartID) 1531 continue; 1532 if (E->getIntrinsicID() == EndID && 1533 haveSameOperands(I, *E, E->getNumArgOperands())) { 1534 IC.eraseInstFromFunction(*E); 1535 IC.eraseInstFromFunction(I); 1536 return true; 1537 } 1538 } 1539 break; 1540 } 1541 1542 return false; 1543 } 1544 1545 // Convert NVVM intrinsics to target-generic LLVM code where possible. 1546 static Instruction *SimplifyNVVMIntrinsic(IntrinsicInst *II, InstCombiner &IC) { 1547 // Each NVVM intrinsic we can simplify can be replaced with one of: 1548 // 1549 // * an LLVM intrinsic, 1550 // * an LLVM cast operation, 1551 // * an LLVM binary operation, or 1552 // * ad-hoc LLVM IR for the particular operation. 1553 1554 // Some transformations are only valid when the module's 1555 // flush-denormals-to-zero (ftz) setting is true/false, whereas other 1556 // transformations are valid regardless of the module's ftz setting. 1557 enum FtzRequirementTy { 1558 FTZ_Any, // Any ftz setting is ok. 1559 FTZ_MustBeOn, // Transformation is valid only if ftz is on. 1560 FTZ_MustBeOff, // Transformation is valid only if ftz is off. 1561 }; 1562 // Classes of NVVM intrinsics that can't be replaced one-to-one with a 1563 // target-generic intrinsic, cast op, or binary op but that we can nonetheless 1564 // simplify. 1565 enum SpecialCase { 1566 SPC_Reciprocal, 1567 }; 1568 1569 // SimplifyAction is a poor-man's variant (plus an additional flag) that 1570 // represents how to replace an NVVM intrinsic with target-generic LLVM IR. 1571 struct SimplifyAction { 1572 // Invariant: At most one of these Optionals has a value. 1573 Optional<Intrinsic::ID> IID; 1574 Optional<Instruction::CastOps> CastOp; 1575 Optional<Instruction::BinaryOps> BinaryOp; 1576 Optional<SpecialCase> Special; 1577 1578 FtzRequirementTy FtzRequirement = FTZ_Any; 1579 1580 SimplifyAction() = default; 1581 1582 SimplifyAction(Intrinsic::ID IID, FtzRequirementTy FtzReq) 1583 : IID(IID), FtzRequirement(FtzReq) {} 1584 1585 // Cast operations don't have anything to do with FTZ, so we skip that 1586 // argument. 1587 SimplifyAction(Instruction::CastOps CastOp) : CastOp(CastOp) {} 1588 1589 SimplifyAction(Instruction::BinaryOps BinaryOp, FtzRequirementTy FtzReq) 1590 : BinaryOp(BinaryOp), FtzRequirement(FtzReq) {} 1591 1592 SimplifyAction(SpecialCase Special, FtzRequirementTy FtzReq) 1593 : Special(Special), FtzRequirement(FtzReq) {} 1594 }; 1595 1596 // Try to generate a SimplifyAction describing how to replace our 1597 // IntrinsicInstr with target-generic LLVM IR. 1598 const SimplifyAction Action = [II]() -> SimplifyAction { 1599 switch (II->getIntrinsicID()) { 1600 // NVVM intrinsics that map directly to LLVM intrinsics. 1601 case Intrinsic::nvvm_ceil_d: 1602 return {Intrinsic::ceil, FTZ_Any}; 1603 case Intrinsic::nvvm_ceil_f: 1604 return {Intrinsic::ceil, FTZ_MustBeOff}; 1605 case Intrinsic::nvvm_ceil_ftz_f: 1606 return {Intrinsic::ceil, FTZ_MustBeOn}; 1607 case Intrinsic::nvvm_fabs_d: 1608 return {Intrinsic::fabs, FTZ_Any}; 1609 case Intrinsic::nvvm_fabs_f: 1610 return {Intrinsic::fabs, FTZ_MustBeOff}; 1611 case Intrinsic::nvvm_fabs_ftz_f: 1612 return {Intrinsic::fabs, FTZ_MustBeOn}; 1613 case Intrinsic::nvvm_floor_d: 1614 return {Intrinsic::floor, FTZ_Any}; 1615 case Intrinsic::nvvm_floor_f: 1616 return {Intrinsic::floor, FTZ_MustBeOff}; 1617 case Intrinsic::nvvm_floor_ftz_f: 1618 return {Intrinsic::floor, FTZ_MustBeOn}; 1619 case Intrinsic::nvvm_fma_rn_d: 1620 return {Intrinsic::fma, FTZ_Any}; 1621 case Intrinsic::nvvm_fma_rn_f: 1622 return {Intrinsic::fma, FTZ_MustBeOff}; 1623 case Intrinsic::nvvm_fma_rn_ftz_f: 1624 return {Intrinsic::fma, FTZ_MustBeOn}; 1625 case Intrinsic::nvvm_fmax_d: 1626 return {Intrinsic::maxnum, FTZ_Any}; 1627 case Intrinsic::nvvm_fmax_f: 1628 return {Intrinsic::maxnum, FTZ_MustBeOff}; 1629 case Intrinsic::nvvm_fmax_ftz_f: 1630 return {Intrinsic::maxnum, FTZ_MustBeOn}; 1631 case Intrinsic::nvvm_fmin_d: 1632 return {Intrinsic::minnum, FTZ_Any}; 1633 case Intrinsic::nvvm_fmin_f: 1634 return {Intrinsic::minnum, FTZ_MustBeOff}; 1635 case Intrinsic::nvvm_fmin_ftz_f: 1636 return {Intrinsic::minnum, FTZ_MustBeOn}; 1637 case Intrinsic::nvvm_round_d: 1638 return {Intrinsic::round, FTZ_Any}; 1639 case Intrinsic::nvvm_round_f: 1640 return {Intrinsic::round, FTZ_MustBeOff}; 1641 case Intrinsic::nvvm_round_ftz_f: 1642 return {Intrinsic::round, FTZ_MustBeOn}; 1643 case Intrinsic::nvvm_sqrt_rn_d: 1644 return {Intrinsic::sqrt, FTZ_Any}; 1645 case Intrinsic::nvvm_sqrt_f: 1646 // nvvm_sqrt_f is a special case. For most intrinsics, foo_ftz_f is the 1647 // ftz version, and foo_f is the non-ftz version. But nvvm_sqrt_f adopts 1648 // the ftz-ness of the surrounding code. sqrt_rn_f and sqrt_rn_ftz_f are 1649 // the versions with explicit ftz-ness. 1650 return {Intrinsic::sqrt, FTZ_Any}; 1651 case Intrinsic::nvvm_sqrt_rn_f: 1652 return {Intrinsic::sqrt, FTZ_MustBeOff}; 1653 case Intrinsic::nvvm_sqrt_rn_ftz_f: 1654 return {Intrinsic::sqrt, FTZ_MustBeOn}; 1655 case Intrinsic::nvvm_trunc_d: 1656 return {Intrinsic::trunc, FTZ_Any}; 1657 case Intrinsic::nvvm_trunc_f: 1658 return {Intrinsic::trunc, FTZ_MustBeOff}; 1659 case Intrinsic::nvvm_trunc_ftz_f: 1660 return {Intrinsic::trunc, FTZ_MustBeOn}; 1661 1662 // NVVM intrinsics that map to LLVM cast operations. 1663 // 1664 // Note that llvm's target-generic conversion operators correspond to the rz 1665 // (round to zero) versions of the nvvm conversion intrinsics, even though 1666 // most everything else here uses the rn (round to nearest even) nvvm ops. 1667 case Intrinsic::nvvm_d2i_rz: 1668 case Intrinsic::nvvm_f2i_rz: 1669 case Intrinsic::nvvm_d2ll_rz: 1670 case Intrinsic::nvvm_f2ll_rz: 1671 return {Instruction::FPToSI}; 1672 case Intrinsic::nvvm_d2ui_rz: 1673 case Intrinsic::nvvm_f2ui_rz: 1674 case Intrinsic::nvvm_d2ull_rz: 1675 case Intrinsic::nvvm_f2ull_rz: 1676 return {Instruction::FPToUI}; 1677 case Intrinsic::nvvm_i2d_rz: 1678 case Intrinsic::nvvm_i2f_rz: 1679 case Intrinsic::nvvm_ll2d_rz: 1680 case Intrinsic::nvvm_ll2f_rz: 1681 return {Instruction::SIToFP}; 1682 case Intrinsic::nvvm_ui2d_rz: 1683 case Intrinsic::nvvm_ui2f_rz: 1684 case Intrinsic::nvvm_ull2d_rz: 1685 case Intrinsic::nvvm_ull2f_rz: 1686 return {Instruction::UIToFP}; 1687 1688 // NVVM intrinsics that map to LLVM binary ops. 1689 case Intrinsic::nvvm_add_rn_d: 1690 return {Instruction::FAdd, FTZ_Any}; 1691 case Intrinsic::nvvm_add_rn_f: 1692 return {Instruction::FAdd, FTZ_MustBeOff}; 1693 case Intrinsic::nvvm_add_rn_ftz_f: 1694 return {Instruction::FAdd, FTZ_MustBeOn}; 1695 case Intrinsic::nvvm_mul_rn_d: 1696 return {Instruction::FMul, FTZ_Any}; 1697 case Intrinsic::nvvm_mul_rn_f: 1698 return {Instruction::FMul, FTZ_MustBeOff}; 1699 case Intrinsic::nvvm_mul_rn_ftz_f: 1700 return {Instruction::FMul, FTZ_MustBeOn}; 1701 case Intrinsic::nvvm_div_rn_d: 1702 return {Instruction::FDiv, FTZ_Any}; 1703 case Intrinsic::nvvm_div_rn_f: 1704 return {Instruction::FDiv, FTZ_MustBeOff}; 1705 case Intrinsic::nvvm_div_rn_ftz_f: 1706 return {Instruction::FDiv, FTZ_MustBeOn}; 1707 1708 // The remainder of cases are NVVM intrinsics that map to LLVM idioms, but 1709 // need special handling. 1710 // 1711 // We seem to be missing intrinsics for rcp.approx.{ftz.}f32, which is just 1712 // as well. 1713 case Intrinsic::nvvm_rcp_rn_d: 1714 return {SPC_Reciprocal, FTZ_Any}; 1715 case Intrinsic::nvvm_rcp_rn_f: 1716 return {SPC_Reciprocal, FTZ_MustBeOff}; 1717 case Intrinsic::nvvm_rcp_rn_ftz_f: 1718 return {SPC_Reciprocal, FTZ_MustBeOn}; 1719 1720 // We do not currently simplify intrinsics that give an approximate answer. 1721 // These include: 1722 // 1723 // - nvvm_cos_approx_{f,ftz_f} 1724 // - nvvm_ex2_approx_{d,f,ftz_f} 1725 // - nvvm_lg2_approx_{d,f,ftz_f} 1726 // - nvvm_sin_approx_{f,ftz_f} 1727 // - nvvm_sqrt_approx_{f,ftz_f} 1728 // - nvvm_rsqrt_approx_{d,f,ftz_f} 1729 // - nvvm_div_approx_{ftz_d,ftz_f,f} 1730 // - nvvm_rcp_approx_ftz_d 1731 // 1732 // Ideally we'd encode them as e.g. "fast call @llvm.cos", where "fast" 1733 // means that fastmath is enabled in the intrinsic. Unfortunately only 1734 // binary operators (currently) have a fastmath bit in SelectionDAG, so this 1735 // information gets lost and we can't select on it. 1736 // 1737 // TODO: div and rcp are lowered to a binary op, so these we could in theory 1738 // lower them to "fast fdiv". 1739 1740 default: 1741 return {}; 1742 } 1743 }(); 1744 1745 // If Action.FtzRequirementTy is not satisfied by the module's ftz state, we 1746 // can bail out now. (Notice that in the case that IID is not an NVVM 1747 // intrinsic, we don't have to look up any module metadata, as 1748 // FtzRequirementTy will be FTZ_Any.) 1749 if (Action.FtzRequirement != FTZ_Any) { 1750 bool FtzEnabled = 1751 II->getFunction()->getFnAttribute("nvptx-f32ftz").getValueAsString() == 1752 "true"; 1753 1754 if (FtzEnabled != (Action.FtzRequirement == FTZ_MustBeOn)) 1755 return nullptr; 1756 } 1757 1758 // Simplify to target-generic intrinsic. 1759 if (Action.IID) { 1760 SmallVector<Value *, 4> Args(II->arg_operands()); 1761 // All the target-generic intrinsics currently of interest to us have one 1762 // type argument, equal to that of the nvvm intrinsic's argument. 1763 Type *Tys[] = {II->getArgOperand(0)->getType()}; 1764 return CallInst::Create( 1765 Intrinsic::getDeclaration(II->getModule(), *Action.IID, Tys), Args); 1766 } 1767 1768 // Simplify to target-generic binary op. 1769 if (Action.BinaryOp) 1770 return BinaryOperator::Create(*Action.BinaryOp, II->getArgOperand(0), 1771 II->getArgOperand(1), II->getName()); 1772 1773 // Simplify to target-generic cast op. 1774 if (Action.CastOp) 1775 return CastInst::Create(*Action.CastOp, II->getArgOperand(0), II->getType(), 1776 II->getName()); 1777 1778 // All that's left are the special cases. 1779 if (!Action.Special) 1780 return nullptr; 1781 1782 switch (*Action.Special) { 1783 case SPC_Reciprocal: 1784 // Simplify reciprocal. 1785 return BinaryOperator::Create( 1786 Instruction::FDiv, ConstantFP::get(II->getArgOperand(0)->getType(), 1), 1787 II->getArgOperand(0), II->getName()); 1788 } 1789 llvm_unreachable("All SpecialCase enumerators should be handled in switch."); 1790 } 1791 1792 Instruction *InstCombiner::visitVAStartInst(VAStartInst &I) { 1793 removeTriviallyEmptyRange(I, Intrinsic::vastart, Intrinsic::vaend, *this); 1794 return nullptr; 1795 } 1796 1797 Instruction *InstCombiner::visitVACopyInst(VACopyInst &I) { 1798 removeTriviallyEmptyRange(I, Intrinsic::vacopy, Intrinsic::vaend, *this); 1799 return nullptr; 1800 } 1801 1802 static Instruction *canonicalizeConstantArg0ToArg1(CallInst &Call) { 1803 assert(Call.getNumArgOperands() > 1 && "Need at least 2 args to swap"); 1804 Value *Arg0 = Call.getArgOperand(0), *Arg1 = Call.getArgOperand(1); 1805 if (isa<Constant>(Arg0) && !isa<Constant>(Arg1)) { 1806 Call.setArgOperand(0, Arg1); 1807 Call.setArgOperand(1, Arg0); 1808 return &Call; 1809 } 1810 return nullptr; 1811 } 1812 1813 /// CallInst simplification. This mostly only handles folding of intrinsic 1814 /// instructions. For normal calls, it allows visitCallSite to do the heavy 1815 /// lifting. 1816 Instruction *InstCombiner::visitCallInst(CallInst &CI) { 1817 if (Value *V = SimplifyCall(&CI, SQ.getWithInstruction(&CI))) 1818 return replaceInstUsesWith(CI, V); 1819 1820 if (isFreeCall(&CI, &TLI)) 1821 return visitFree(CI); 1822 1823 // If the caller function is nounwind, mark the call as nounwind, even if the 1824 // callee isn't. 1825 if (CI.getFunction()->doesNotThrow() && !CI.doesNotThrow()) { 1826 CI.setDoesNotThrow(); 1827 return &CI; 1828 } 1829 1830 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI); 1831 if (!II) return visitCallSite(&CI); 1832 1833 // Intrinsics cannot occur in an invoke, so handle them here instead of in 1834 // visitCallSite. 1835 if (auto *MI = dyn_cast<AnyMemIntrinsic>(II)) { 1836 bool Changed = false; 1837 1838 // memmove/cpy/set of zero bytes is a noop. 1839 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) { 1840 if (NumBytes->isNullValue()) 1841 return eraseInstFromFunction(CI); 1842 1843 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes)) 1844 if (CI->getZExtValue() == 1) { 1845 // Replace the instruction with just byte operations. We would 1846 // transform other cases to loads/stores, but we don't know if 1847 // alignment is sufficient. 1848 } 1849 } 1850 1851 // No other transformations apply to volatile transfers. 1852 if (auto *M = dyn_cast<MemIntrinsic>(MI)) 1853 if (M->isVolatile()) 1854 return nullptr; 1855 1856 // If we have a memmove and the source operation is a constant global, 1857 // then the source and dest pointers can't alias, so we can change this 1858 // into a call to memcpy. 1859 if (auto *MMI = dyn_cast<AnyMemMoveInst>(MI)) { 1860 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource())) 1861 if (GVSrc->isConstant()) { 1862 Module *M = CI.getModule(); 1863 Intrinsic::ID MemCpyID = 1864 isa<AtomicMemMoveInst>(MMI) 1865 ? Intrinsic::memcpy_element_unordered_atomic 1866 : Intrinsic::memcpy; 1867 Type *Tys[3] = { CI.getArgOperand(0)->getType(), 1868 CI.getArgOperand(1)->getType(), 1869 CI.getArgOperand(2)->getType() }; 1870 CI.setCalledFunction(Intrinsic::getDeclaration(M, MemCpyID, Tys)); 1871 Changed = true; 1872 } 1873 } 1874 1875 if (AnyMemTransferInst *MTI = dyn_cast<AnyMemTransferInst>(MI)) { 1876 // memmove(x,x,size) -> noop. 1877 if (MTI->getSource() == MTI->getDest()) 1878 return eraseInstFromFunction(CI); 1879 } 1880 1881 // If we can determine a pointer alignment that is bigger than currently 1882 // set, update the alignment. 1883 if (auto *MTI = dyn_cast<AnyMemTransferInst>(MI)) { 1884 if (Instruction *I = SimplifyAnyMemTransfer(MTI)) 1885 return I; 1886 } else if (auto *MSI = dyn_cast<AnyMemSetInst>(MI)) { 1887 if (Instruction *I = SimplifyAnyMemSet(MSI)) 1888 return I; 1889 } 1890 1891 if (Changed) return II; 1892 } 1893 1894 if (Instruction *I = SimplifyNVVMIntrinsic(II, *this)) 1895 return I; 1896 1897 auto SimplifyDemandedVectorEltsLow = [this](Value *Op, unsigned Width, 1898 unsigned DemandedWidth) { 1899 APInt UndefElts(Width, 0); 1900 APInt DemandedElts = APInt::getLowBitsSet(Width, DemandedWidth); 1901 return SimplifyDemandedVectorElts(Op, DemandedElts, UndefElts); 1902 }; 1903 1904 switch (II->getIntrinsicID()) { 1905 default: break; 1906 case Intrinsic::objectsize: 1907 if (ConstantInt *N = 1908 lowerObjectSizeCall(II, DL, &TLI, /*MustSucceed=*/false)) 1909 return replaceInstUsesWith(CI, N); 1910 return nullptr; 1911 case Intrinsic::bswap: { 1912 Value *IIOperand = II->getArgOperand(0); 1913 Value *X = nullptr; 1914 1915 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c)) 1916 if (match(IIOperand, m_Trunc(m_BSwap(m_Value(X))))) { 1917 unsigned C = X->getType()->getPrimitiveSizeInBits() - 1918 IIOperand->getType()->getPrimitiveSizeInBits(); 1919 Value *CV = ConstantInt::get(X->getType(), C); 1920 Value *V = Builder.CreateLShr(X, CV); 1921 return new TruncInst(V, IIOperand->getType()); 1922 } 1923 break; 1924 } 1925 case Intrinsic::masked_load: 1926 if (Value *SimplifiedMaskedOp = simplifyMaskedLoad(*II, Builder)) 1927 return replaceInstUsesWith(CI, SimplifiedMaskedOp); 1928 break; 1929 case Intrinsic::masked_store: 1930 return simplifyMaskedStore(*II, *this); 1931 case Intrinsic::masked_gather: 1932 return simplifyMaskedGather(*II, *this); 1933 case Intrinsic::masked_scatter: 1934 return simplifyMaskedScatter(*II, *this); 1935 case Intrinsic::launder_invariant_group: 1936 case Intrinsic::strip_invariant_group: 1937 if (auto *SkippedBarrier = simplifyInvariantGroupIntrinsic(*II, *this)) 1938 return replaceInstUsesWith(*II, SkippedBarrier); 1939 break; 1940 case Intrinsic::powi: 1941 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) { 1942 // 0 and 1 are handled in instsimplify 1943 1944 // powi(x, -1) -> 1/x 1945 if (Power->isMinusOne()) 1946 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0), 1947 II->getArgOperand(0)); 1948 // powi(x, 2) -> x*x 1949 if (Power->equalsInt(2)) 1950 return BinaryOperator::CreateFMul(II->getArgOperand(0), 1951 II->getArgOperand(0)); 1952 } 1953 break; 1954 1955 case Intrinsic::cttz: 1956 case Intrinsic::ctlz: 1957 if (auto *I = foldCttzCtlz(*II, *this)) 1958 return I; 1959 break; 1960 1961 case Intrinsic::ctpop: 1962 if (auto *I = foldCtpop(*II, *this)) 1963 return I; 1964 break; 1965 1966 case Intrinsic::fshl: 1967 case Intrinsic::fshr: { 1968 const APInt *SA; 1969 if (match(II->getArgOperand(2), m_APInt(SA))) { 1970 Value *Op0 = II->getArgOperand(0), *Op1 = II->getArgOperand(1); 1971 unsigned BitWidth = SA->getBitWidth(); 1972 uint64_t ShiftAmt = SA->urem(BitWidth); 1973 assert(ShiftAmt != 0 && "SimplifyCall should have handled zero shift"); 1974 // Normalize to funnel shift left. 1975 if (II->getIntrinsicID() == Intrinsic::fshr) 1976 ShiftAmt = BitWidth - ShiftAmt; 1977 1978 // fshl(X, 0, C) -> shl X, C 1979 // fshl(X, undef, C) -> shl X, C 1980 if (match(Op1, m_Zero()) || match(Op1, m_Undef())) 1981 return BinaryOperator::CreateShl( 1982 Op0, ConstantInt::get(II->getType(), ShiftAmt)); 1983 1984 // fshl(0, X, C) -> lshr X, (BW-C) 1985 // fshl(undef, X, C) -> lshr X, (BW-C) 1986 if (match(Op0, m_Zero()) || match(Op0, m_Undef())) 1987 return BinaryOperator::CreateLShr( 1988 Op1, ConstantInt::get(II->getType(), BitWidth - ShiftAmt)); 1989 } 1990 1991 // The shift amount (operand 2) of a funnel shift is modulo the bitwidth, 1992 // so only the low bits of the shift amount are demanded if the bitwidth is 1993 // a power-of-2. 1994 unsigned BitWidth = II->getType()->getScalarSizeInBits(); 1995 if (!isPowerOf2_32(BitWidth)) 1996 break; 1997 APInt Op2Demanded = APInt::getLowBitsSet(BitWidth, Log2_32_Ceil(BitWidth)); 1998 KnownBits Op2Known(BitWidth); 1999 if (SimplifyDemandedBits(II, 2, Op2Demanded, Op2Known)) 2000 return &CI; 2001 break; 2002 } 2003 case Intrinsic::uadd_with_overflow: 2004 case Intrinsic::sadd_with_overflow: 2005 case Intrinsic::umul_with_overflow: 2006 case Intrinsic::smul_with_overflow: 2007 if (Instruction *I = canonicalizeConstantArg0ToArg1(CI)) 2008 return I; 2009 LLVM_FALLTHROUGH; 2010 2011 case Intrinsic::usub_with_overflow: 2012 case Intrinsic::ssub_with_overflow: { 2013 OverflowCheckFlavor OCF = 2014 IntrinsicIDToOverflowCheckFlavor(II->getIntrinsicID()); 2015 assert(OCF != OCF_INVALID && "unexpected!"); 2016 2017 Value *OperationResult = nullptr; 2018 Constant *OverflowResult = nullptr; 2019 if (OptimizeOverflowCheck(OCF, II->getArgOperand(0), II->getArgOperand(1), 2020 *II, OperationResult, OverflowResult)) 2021 return CreateOverflowTuple(II, OperationResult, OverflowResult); 2022 2023 break; 2024 } 2025 2026 case Intrinsic::uadd_sat: 2027 case Intrinsic::sadd_sat: 2028 if (Instruction *I = canonicalizeConstantArg0ToArg1(CI)) 2029 return I; 2030 LLVM_FALLTHROUGH; 2031 case Intrinsic::usub_sat: 2032 case Intrinsic::ssub_sat: { 2033 Value *Arg0 = II->getArgOperand(0); 2034 Value *Arg1 = II->getArgOperand(1); 2035 Intrinsic::ID IID = II->getIntrinsicID(); 2036 2037 // Make use of known overflow information. 2038 OverflowResult OR; 2039 switch (IID) { 2040 default: 2041 llvm_unreachable("Unexpected intrinsic!"); 2042 case Intrinsic::uadd_sat: 2043 OR = computeOverflowForUnsignedAdd(Arg0, Arg1, II); 2044 if (OR == OverflowResult::NeverOverflows) 2045 return BinaryOperator::CreateNUWAdd(Arg0, Arg1); 2046 if (OR == OverflowResult::AlwaysOverflows) 2047 return replaceInstUsesWith(*II, 2048 ConstantInt::getAllOnesValue(II->getType())); 2049 break; 2050 case Intrinsic::usub_sat: 2051 OR = computeOverflowForUnsignedSub(Arg0, Arg1, II); 2052 if (OR == OverflowResult::NeverOverflows) 2053 return BinaryOperator::CreateNUWSub(Arg0, Arg1); 2054 if (OR == OverflowResult::AlwaysOverflows) 2055 return replaceInstUsesWith(*II, 2056 ConstantInt::getNullValue(II->getType())); 2057 break; 2058 case Intrinsic::sadd_sat: 2059 if (willNotOverflowSignedAdd(Arg0, Arg1, *II)) 2060 return BinaryOperator::CreateNSWAdd(Arg0, Arg1); 2061 break; 2062 case Intrinsic::ssub_sat: 2063 if (willNotOverflowSignedSub(Arg0, Arg1, *II)) 2064 return BinaryOperator::CreateNSWSub(Arg0, Arg1); 2065 break; 2066 } 2067 2068 // ssub.sat(X, C) -> sadd.sat(X, -C) if C != MIN 2069 Constant *C; 2070 if (IID == Intrinsic::ssub_sat && match(Arg1, m_Constant(C)) && 2071 C->isNotMinSignedValue()) { 2072 Value *NegVal = ConstantExpr::getNeg(C); 2073 return replaceInstUsesWith( 2074 *II, Builder.CreateBinaryIntrinsic( 2075 Intrinsic::sadd_sat, Arg0, NegVal)); 2076 } 2077 2078 // sat(sat(X + Val2) + Val) -> sat(X + (Val+Val2)) 2079 // sat(sat(X - Val2) - Val) -> sat(X - (Val+Val2)) 2080 // if Val and Val2 have the same sign 2081 if (auto *Other = dyn_cast<IntrinsicInst>(Arg0)) { 2082 Value *X; 2083 const APInt *Val, *Val2; 2084 APInt NewVal; 2085 bool IsUnsigned = 2086 IID == Intrinsic::uadd_sat || IID == Intrinsic::usub_sat; 2087 if (Other->getIntrinsicID() == II->getIntrinsicID() && 2088 match(Arg1, m_APInt(Val)) && 2089 match(Other->getArgOperand(0), m_Value(X)) && 2090 match(Other->getArgOperand(1), m_APInt(Val2))) { 2091 if (IsUnsigned) 2092 NewVal = Val->uadd_sat(*Val2); 2093 else if (Val->isNonNegative() == Val2->isNonNegative()) { 2094 bool Overflow; 2095 NewVal = Val->sadd_ov(*Val2, Overflow); 2096 if (Overflow) { 2097 // Both adds together may add more than SignedMaxValue 2098 // without saturating the final result. 2099 break; 2100 } 2101 } else { 2102 // Cannot fold saturated addition with different signs. 2103 break; 2104 } 2105 2106 return replaceInstUsesWith( 2107 *II, Builder.CreateBinaryIntrinsic( 2108 IID, X, ConstantInt::get(II->getType(), NewVal))); 2109 } 2110 } 2111 break; 2112 } 2113 2114 case Intrinsic::minnum: 2115 case Intrinsic::maxnum: 2116 case Intrinsic::minimum: 2117 case Intrinsic::maximum: { 2118 if (Instruction *I = canonicalizeConstantArg0ToArg1(CI)) 2119 return I; 2120 Value *Arg0 = II->getArgOperand(0); 2121 Value *Arg1 = II->getArgOperand(1); 2122 Intrinsic::ID IID = II->getIntrinsicID(); 2123 Value *X, *Y; 2124 if (match(Arg0, m_FNeg(m_Value(X))) && match(Arg1, m_FNeg(m_Value(Y))) && 2125 (Arg0->hasOneUse() || Arg1->hasOneUse())) { 2126 // If both operands are negated, invert the call and negate the result: 2127 // min(-X, -Y) --> -(max(X, Y)) 2128 // max(-X, -Y) --> -(min(X, Y)) 2129 Intrinsic::ID NewIID; 2130 switch (IID) { 2131 case Intrinsic::maxnum: 2132 NewIID = Intrinsic::minnum; 2133 break; 2134 case Intrinsic::minnum: 2135 NewIID = Intrinsic::maxnum; 2136 break; 2137 case Intrinsic::maximum: 2138 NewIID = Intrinsic::minimum; 2139 break; 2140 case Intrinsic::minimum: 2141 NewIID = Intrinsic::maximum; 2142 break; 2143 default: 2144 llvm_unreachable("unexpected intrinsic ID"); 2145 } 2146 Value *NewCall = Builder.CreateBinaryIntrinsic(NewIID, X, Y, II); 2147 Instruction *FNeg = BinaryOperator::CreateFNeg(NewCall); 2148 FNeg->copyIRFlags(II); 2149 return FNeg; 2150 } 2151 2152 // m(m(X, C2), C1) -> m(X, C) 2153 const APFloat *C1, *C2; 2154 if (auto *M = dyn_cast<IntrinsicInst>(Arg0)) { 2155 if (M->getIntrinsicID() == IID && match(Arg1, m_APFloat(C1)) && 2156 ((match(M->getArgOperand(0), m_Value(X)) && 2157 match(M->getArgOperand(1), m_APFloat(C2))) || 2158 (match(M->getArgOperand(1), m_Value(X)) && 2159 match(M->getArgOperand(0), m_APFloat(C2))))) { 2160 APFloat Res(0.0); 2161 switch (IID) { 2162 case Intrinsic::maxnum: 2163 Res = maxnum(*C1, *C2); 2164 break; 2165 case Intrinsic::minnum: 2166 Res = minnum(*C1, *C2); 2167 break; 2168 case Intrinsic::maximum: 2169 Res = maximum(*C1, *C2); 2170 break; 2171 case Intrinsic::minimum: 2172 Res = minimum(*C1, *C2); 2173 break; 2174 default: 2175 llvm_unreachable("unexpected intrinsic ID"); 2176 } 2177 Instruction *NewCall = Builder.CreateBinaryIntrinsic( 2178 IID, X, ConstantFP::get(Arg0->getType(), Res)); 2179 NewCall->copyIRFlags(II); 2180 return replaceInstUsesWith(*II, NewCall); 2181 } 2182 } 2183 2184 break; 2185 } 2186 case Intrinsic::fmuladd: { 2187 // Canonicalize fast fmuladd to the separate fmul + fadd. 2188 if (II->isFast()) { 2189 BuilderTy::FastMathFlagGuard Guard(Builder); 2190 Builder.setFastMathFlags(II->getFastMathFlags()); 2191 Value *Mul = Builder.CreateFMul(II->getArgOperand(0), 2192 II->getArgOperand(1)); 2193 Value *Add = Builder.CreateFAdd(Mul, II->getArgOperand(2)); 2194 Add->takeName(II); 2195 return replaceInstUsesWith(*II, Add); 2196 } 2197 2198 LLVM_FALLTHROUGH; 2199 } 2200 case Intrinsic::fma: { 2201 if (Instruction *I = canonicalizeConstantArg0ToArg1(CI)) 2202 return I; 2203 2204 // fma fneg(x), fneg(y), z -> fma x, y, z 2205 Value *Src0 = II->getArgOperand(0); 2206 Value *Src1 = II->getArgOperand(1); 2207 Value *X, *Y; 2208 if (match(Src0, m_FNeg(m_Value(X))) && match(Src1, m_FNeg(m_Value(Y)))) { 2209 II->setArgOperand(0, X); 2210 II->setArgOperand(1, Y); 2211 return II; 2212 } 2213 2214 // fma fabs(x), fabs(x), z -> fma x, x, z 2215 if (match(Src0, m_FAbs(m_Value(X))) && 2216 match(Src1, m_FAbs(m_Specific(X)))) { 2217 II->setArgOperand(0, X); 2218 II->setArgOperand(1, X); 2219 return II; 2220 } 2221 2222 // fma x, 1, z -> fadd x, z 2223 if (match(Src1, m_FPOne())) { 2224 auto *FAdd = BinaryOperator::CreateFAdd(Src0, II->getArgOperand(2)); 2225 FAdd->copyFastMathFlags(II); 2226 return FAdd; 2227 } 2228 2229 break; 2230 } 2231 case Intrinsic::fabs: { 2232 Value *Cond; 2233 Constant *LHS, *RHS; 2234 if (match(II->getArgOperand(0), 2235 m_Select(m_Value(Cond), m_Constant(LHS), m_Constant(RHS)))) { 2236 CallInst *Call0 = Builder.CreateCall(II->getCalledFunction(), {LHS}); 2237 CallInst *Call1 = Builder.CreateCall(II->getCalledFunction(), {RHS}); 2238 return SelectInst::Create(Cond, Call0, Call1); 2239 } 2240 2241 LLVM_FALLTHROUGH; 2242 } 2243 case Intrinsic::ceil: 2244 case Intrinsic::floor: 2245 case Intrinsic::round: 2246 case Intrinsic::nearbyint: 2247 case Intrinsic::rint: 2248 case Intrinsic::trunc: { 2249 Value *ExtSrc; 2250 if (match(II->getArgOperand(0), m_OneUse(m_FPExt(m_Value(ExtSrc))))) { 2251 // Narrow the call: intrinsic (fpext x) -> fpext (intrinsic x) 2252 Value *NarrowII = 2253 Builder.CreateUnaryIntrinsic(II->getIntrinsicID(), ExtSrc, II); 2254 return new FPExtInst(NarrowII, II->getType()); 2255 } 2256 break; 2257 } 2258 case Intrinsic::cos: 2259 case Intrinsic::amdgcn_cos: { 2260 Value *X; 2261 Value *Src = II->getArgOperand(0); 2262 if (match(Src, m_FNeg(m_Value(X))) || match(Src, m_FAbs(m_Value(X)))) { 2263 // cos(-x) -> cos(x) 2264 // cos(fabs(x)) -> cos(x) 2265 II->setArgOperand(0, X); 2266 return II; 2267 } 2268 break; 2269 } 2270 case Intrinsic::sin: { 2271 Value *X; 2272 if (match(II->getArgOperand(0), m_OneUse(m_FNeg(m_Value(X))))) { 2273 // sin(-x) --> -sin(x) 2274 Value *NewSin = Builder.CreateUnaryIntrinsic(Intrinsic::sin, X, II); 2275 Instruction *FNeg = BinaryOperator::CreateFNeg(NewSin); 2276 FNeg->copyFastMathFlags(II); 2277 return FNeg; 2278 } 2279 break; 2280 } 2281 case Intrinsic::ppc_altivec_lvx: 2282 case Intrinsic::ppc_altivec_lvxl: 2283 // Turn PPC lvx -> load if the pointer is known aligned. 2284 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, &AC, 2285 &DT) >= 16) { 2286 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(0), 2287 PointerType::getUnqual(II->getType())); 2288 return new LoadInst(Ptr); 2289 } 2290 break; 2291 case Intrinsic::ppc_vsx_lxvw4x: 2292 case Intrinsic::ppc_vsx_lxvd2x: { 2293 // Turn PPC VSX loads into normal loads. 2294 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(0), 2295 PointerType::getUnqual(II->getType())); 2296 return new LoadInst(Ptr, Twine(""), false, 1); 2297 } 2298 case Intrinsic::ppc_altivec_stvx: 2299 case Intrinsic::ppc_altivec_stvxl: 2300 // Turn stvx -> store if the pointer is known aligned. 2301 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, &AC, 2302 &DT) >= 16) { 2303 Type *OpPtrTy = 2304 PointerType::getUnqual(II->getArgOperand(0)->getType()); 2305 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(1), OpPtrTy); 2306 return new StoreInst(II->getArgOperand(0), Ptr); 2307 } 2308 break; 2309 case Intrinsic::ppc_vsx_stxvw4x: 2310 case Intrinsic::ppc_vsx_stxvd2x: { 2311 // Turn PPC VSX stores into normal stores. 2312 Type *OpPtrTy = PointerType::getUnqual(II->getArgOperand(0)->getType()); 2313 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(1), OpPtrTy); 2314 return new StoreInst(II->getArgOperand(0), Ptr, false, 1); 2315 } 2316 case Intrinsic::ppc_qpx_qvlfs: 2317 // Turn PPC QPX qvlfs -> load if the pointer is known aligned. 2318 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, &AC, 2319 &DT) >= 16) { 2320 Type *VTy = VectorType::get(Builder.getFloatTy(), 2321 II->getType()->getVectorNumElements()); 2322 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(0), 2323 PointerType::getUnqual(VTy)); 2324 Value *Load = Builder.CreateLoad(Ptr); 2325 return new FPExtInst(Load, II->getType()); 2326 } 2327 break; 2328 case Intrinsic::ppc_qpx_qvlfd: 2329 // Turn PPC QPX qvlfd -> load if the pointer is known aligned. 2330 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 32, DL, II, &AC, 2331 &DT) >= 32) { 2332 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(0), 2333 PointerType::getUnqual(II->getType())); 2334 return new LoadInst(Ptr); 2335 } 2336 break; 2337 case Intrinsic::ppc_qpx_qvstfs: 2338 // Turn PPC QPX qvstfs -> store if the pointer is known aligned. 2339 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, &AC, 2340 &DT) >= 16) { 2341 Type *VTy = VectorType::get(Builder.getFloatTy(), 2342 II->getArgOperand(0)->getType()->getVectorNumElements()); 2343 Value *TOp = Builder.CreateFPTrunc(II->getArgOperand(0), VTy); 2344 Type *OpPtrTy = PointerType::getUnqual(VTy); 2345 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(1), OpPtrTy); 2346 return new StoreInst(TOp, Ptr); 2347 } 2348 break; 2349 case Intrinsic::ppc_qpx_qvstfd: 2350 // Turn PPC QPX qvstfd -> store if the pointer is known aligned. 2351 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 32, DL, II, &AC, 2352 &DT) >= 32) { 2353 Type *OpPtrTy = 2354 PointerType::getUnqual(II->getArgOperand(0)->getType()); 2355 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(1), OpPtrTy); 2356 return new StoreInst(II->getArgOperand(0), Ptr); 2357 } 2358 break; 2359 2360 case Intrinsic::x86_bmi_bextr_32: 2361 case Intrinsic::x86_bmi_bextr_64: 2362 case Intrinsic::x86_tbm_bextri_u32: 2363 case Intrinsic::x86_tbm_bextri_u64: 2364 // If the RHS is a constant we can try some simplifications. 2365 if (auto *C = dyn_cast<ConstantInt>(II->getArgOperand(1))) { 2366 uint64_t Shift = C->getZExtValue(); 2367 uint64_t Length = (Shift >> 8) & 0xff; 2368 Shift &= 0xff; 2369 unsigned BitWidth = II->getType()->getIntegerBitWidth(); 2370 // If the length is 0 or the shift is out of range, replace with zero. 2371 if (Length == 0 || Shift >= BitWidth) 2372 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), 0)); 2373 // If the LHS is also a constant, we can completely constant fold this. 2374 if (auto *InC = dyn_cast<ConstantInt>(II->getArgOperand(0))) { 2375 uint64_t Result = InC->getZExtValue() >> Shift; 2376 if (Length > BitWidth) 2377 Length = BitWidth; 2378 Result &= maskTrailingOnes<uint64_t>(Length); 2379 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), Result)); 2380 } 2381 // TODO should we turn this into 'and' if shift is 0? Or 'shl' if we 2382 // are only masking bits that a shift already cleared? 2383 } 2384 break; 2385 2386 case Intrinsic::x86_bmi_bzhi_32: 2387 case Intrinsic::x86_bmi_bzhi_64: 2388 // If the RHS is a constant we can try some simplifications. 2389 if (auto *C = dyn_cast<ConstantInt>(II->getArgOperand(1))) { 2390 uint64_t Index = C->getZExtValue() & 0xff; 2391 unsigned BitWidth = II->getType()->getIntegerBitWidth(); 2392 if (Index >= BitWidth) 2393 return replaceInstUsesWith(CI, II->getArgOperand(0)); 2394 if (Index == 0) 2395 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), 0)); 2396 // If the LHS is also a constant, we can completely constant fold this. 2397 if (auto *InC = dyn_cast<ConstantInt>(II->getArgOperand(0))) { 2398 uint64_t Result = InC->getZExtValue(); 2399 Result &= maskTrailingOnes<uint64_t>(Index); 2400 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), Result)); 2401 } 2402 // TODO should we convert this to an AND if the RHS is constant? 2403 } 2404 break; 2405 2406 case Intrinsic::x86_vcvtph2ps_128: 2407 case Intrinsic::x86_vcvtph2ps_256: { 2408 auto Arg = II->getArgOperand(0); 2409 auto ArgType = cast<VectorType>(Arg->getType()); 2410 auto RetType = cast<VectorType>(II->getType()); 2411 unsigned ArgWidth = ArgType->getNumElements(); 2412 unsigned RetWidth = RetType->getNumElements(); 2413 assert(RetWidth <= ArgWidth && "Unexpected input/return vector widths"); 2414 assert(ArgType->isIntOrIntVectorTy() && 2415 ArgType->getScalarSizeInBits() == 16 && 2416 "CVTPH2PS input type should be 16-bit integer vector"); 2417 assert(RetType->getScalarType()->isFloatTy() && 2418 "CVTPH2PS output type should be 32-bit float vector"); 2419 2420 // Constant folding: Convert to generic half to single conversion. 2421 if (isa<ConstantAggregateZero>(Arg)) 2422 return replaceInstUsesWith(*II, ConstantAggregateZero::get(RetType)); 2423 2424 if (isa<ConstantDataVector>(Arg)) { 2425 auto VectorHalfAsShorts = Arg; 2426 if (RetWidth < ArgWidth) { 2427 SmallVector<uint32_t, 8> SubVecMask; 2428 for (unsigned i = 0; i != RetWidth; ++i) 2429 SubVecMask.push_back((int)i); 2430 VectorHalfAsShorts = Builder.CreateShuffleVector( 2431 Arg, UndefValue::get(ArgType), SubVecMask); 2432 } 2433 2434 auto VectorHalfType = 2435 VectorType::get(Type::getHalfTy(II->getContext()), RetWidth); 2436 auto VectorHalfs = 2437 Builder.CreateBitCast(VectorHalfAsShorts, VectorHalfType); 2438 auto VectorFloats = Builder.CreateFPExt(VectorHalfs, RetType); 2439 return replaceInstUsesWith(*II, VectorFloats); 2440 } 2441 2442 // We only use the lowest lanes of the argument. 2443 if (Value *V = SimplifyDemandedVectorEltsLow(Arg, ArgWidth, RetWidth)) { 2444 II->setArgOperand(0, V); 2445 return II; 2446 } 2447 break; 2448 } 2449 2450 case Intrinsic::x86_sse_cvtss2si: 2451 case Intrinsic::x86_sse_cvtss2si64: 2452 case Intrinsic::x86_sse_cvttss2si: 2453 case Intrinsic::x86_sse_cvttss2si64: 2454 case Intrinsic::x86_sse2_cvtsd2si: 2455 case Intrinsic::x86_sse2_cvtsd2si64: 2456 case Intrinsic::x86_sse2_cvttsd2si: 2457 case Intrinsic::x86_sse2_cvttsd2si64: 2458 case Intrinsic::x86_avx512_vcvtss2si32: 2459 case Intrinsic::x86_avx512_vcvtss2si64: 2460 case Intrinsic::x86_avx512_vcvtss2usi32: 2461 case Intrinsic::x86_avx512_vcvtss2usi64: 2462 case Intrinsic::x86_avx512_vcvtsd2si32: 2463 case Intrinsic::x86_avx512_vcvtsd2si64: 2464 case Intrinsic::x86_avx512_vcvtsd2usi32: 2465 case Intrinsic::x86_avx512_vcvtsd2usi64: 2466 case Intrinsic::x86_avx512_cvttss2si: 2467 case Intrinsic::x86_avx512_cvttss2si64: 2468 case Intrinsic::x86_avx512_cvttss2usi: 2469 case Intrinsic::x86_avx512_cvttss2usi64: 2470 case Intrinsic::x86_avx512_cvttsd2si: 2471 case Intrinsic::x86_avx512_cvttsd2si64: 2472 case Intrinsic::x86_avx512_cvttsd2usi: 2473 case Intrinsic::x86_avx512_cvttsd2usi64: { 2474 // These intrinsics only demand the 0th element of their input vectors. If 2475 // we can simplify the input based on that, do so now. 2476 Value *Arg = II->getArgOperand(0); 2477 unsigned VWidth = Arg->getType()->getVectorNumElements(); 2478 if (Value *V = SimplifyDemandedVectorEltsLow(Arg, VWidth, 1)) { 2479 II->setArgOperand(0, V); 2480 return II; 2481 } 2482 break; 2483 } 2484 2485 case Intrinsic::x86_sse41_round_ps: 2486 case Intrinsic::x86_sse41_round_pd: 2487 case Intrinsic::x86_avx_round_ps_256: 2488 case Intrinsic::x86_avx_round_pd_256: 2489 case Intrinsic::x86_avx512_mask_rndscale_ps_128: 2490 case Intrinsic::x86_avx512_mask_rndscale_ps_256: 2491 case Intrinsic::x86_avx512_mask_rndscale_ps_512: 2492 case Intrinsic::x86_avx512_mask_rndscale_pd_128: 2493 case Intrinsic::x86_avx512_mask_rndscale_pd_256: 2494 case Intrinsic::x86_avx512_mask_rndscale_pd_512: 2495 case Intrinsic::x86_avx512_mask_rndscale_ss: 2496 case Intrinsic::x86_avx512_mask_rndscale_sd: 2497 if (Value *V = simplifyX86round(*II, Builder)) 2498 return replaceInstUsesWith(*II, V); 2499 break; 2500 2501 case Intrinsic::x86_mmx_pmovmskb: 2502 case Intrinsic::x86_sse_movmsk_ps: 2503 case Intrinsic::x86_sse2_movmsk_pd: 2504 case Intrinsic::x86_sse2_pmovmskb_128: 2505 case Intrinsic::x86_avx_movmsk_pd_256: 2506 case Intrinsic::x86_avx_movmsk_ps_256: 2507 case Intrinsic::x86_avx2_pmovmskb: 2508 if (Value *V = simplifyX86movmsk(*II, Builder)) 2509 return replaceInstUsesWith(*II, V); 2510 break; 2511 2512 case Intrinsic::x86_sse_comieq_ss: 2513 case Intrinsic::x86_sse_comige_ss: 2514 case Intrinsic::x86_sse_comigt_ss: 2515 case Intrinsic::x86_sse_comile_ss: 2516 case Intrinsic::x86_sse_comilt_ss: 2517 case Intrinsic::x86_sse_comineq_ss: 2518 case Intrinsic::x86_sse_ucomieq_ss: 2519 case Intrinsic::x86_sse_ucomige_ss: 2520 case Intrinsic::x86_sse_ucomigt_ss: 2521 case Intrinsic::x86_sse_ucomile_ss: 2522 case Intrinsic::x86_sse_ucomilt_ss: 2523 case Intrinsic::x86_sse_ucomineq_ss: 2524 case Intrinsic::x86_sse2_comieq_sd: 2525 case Intrinsic::x86_sse2_comige_sd: 2526 case Intrinsic::x86_sse2_comigt_sd: 2527 case Intrinsic::x86_sse2_comile_sd: 2528 case Intrinsic::x86_sse2_comilt_sd: 2529 case Intrinsic::x86_sse2_comineq_sd: 2530 case Intrinsic::x86_sse2_ucomieq_sd: 2531 case Intrinsic::x86_sse2_ucomige_sd: 2532 case Intrinsic::x86_sse2_ucomigt_sd: 2533 case Intrinsic::x86_sse2_ucomile_sd: 2534 case Intrinsic::x86_sse2_ucomilt_sd: 2535 case Intrinsic::x86_sse2_ucomineq_sd: 2536 case Intrinsic::x86_avx512_vcomi_ss: 2537 case Intrinsic::x86_avx512_vcomi_sd: 2538 case Intrinsic::x86_avx512_mask_cmp_ss: 2539 case Intrinsic::x86_avx512_mask_cmp_sd: { 2540 // These intrinsics only demand the 0th element of their input vectors. If 2541 // we can simplify the input based on that, do so now. 2542 bool MadeChange = false; 2543 Value *Arg0 = II->getArgOperand(0); 2544 Value *Arg1 = II->getArgOperand(1); 2545 unsigned VWidth = Arg0->getType()->getVectorNumElements(); 2546 if (Value *V = SimplifyDemandedVectorEltsLow(Arg0, VWidth, 1)) { 2547 II->setArgOperand(0, V); 2548 MadeChange = true; 2549 } 2550 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, 1)) { 2551 II->setArgOperand(1, V); 2552 MadeChange = true; 2553 } 2554 if (MadeChange) 2555 return II; 2556 break; 2557 } 2558 case Intrinsic::x86_avx512_cmp_pd_128: 2559 case Intrinsic::x86_avx512_cmp_pd_256: 2560 case Intrinsic::x86_avx512_cmp_pd_512: 2561 case Intrinsic::x86_avx512_cmp_ps_128: 2562 case Intrinsic::x86_avx512_cmp_ps_256: 2563 case Intrinsic::x86_avx512_cmp_ps_512: { 2564 // Folding cmp(sub(a,b),0) -> cmp(a,b) and cmp(0,sub(a,b)) -> cmp(b,a) 2565 Value *Arg0 = II->getArgOperand(0); 2566 Value *Arg1 = II->getArgOperand(1); 2567 bool Arg0IsZero = match(Arg0, m_PosZeroFP()); 2568 if (Arg0IsZero) 2569 std::swap(Arg0, Arg1); 2570 Value *A, *B; 2571 // This fold requires only the NINF(not +/- inf) since inf minus 2572 // inf is nan. 2573 // NSZ(No Signed Zeros) is not needed because zeros of any sign are 2574 // equal for both compares. 2575 // NNAN is not needed because nans compare the same for both compares. 2576 // The compare intrinsic uses the above assumptions and therefore 2577 // doesn't require additional flags. 2578 if ((match(Arg0, m_OneUse(m_FSub(m_Value(A), m_Value(B)))) && 2579 match(Arg1, m_PosZeroFP()) && isa<Instruction>(Arg0) && 2580 cast<Instruction>(Arg0)->getFastMathFlags().noInfs())) { 2581 if (Arg0IsZero) 2582 std::swap(A, B); 2583 II->setArgOperand(0, A); 2584 II->setArgOperand(1, B); 2585 return II; 2586 } 2587 break; 2588 } 2589 2590 case Intrinsic::x86_avx512_add_ps_512: 2591 case Intrinsic::x86_avx512_div_ps_512: 2592 case Intrinsic::x86_avx512_mul_ps_512: 2593 case Intrinsic::x86_avx512_sub_ps_512: 2594 case Intrinsic::x86_avx512_add_pd_512: 2595 case Intrinsic::x86_avx512_div_pd_512: 2596 case Intrinsic::x86_avx512_mul_pd_512: 2597 case Intrinsic::x86_avx512_sub_pd_512: 2598 // If the rounding mode is CUR_DIRECTION(4) we can turn these into regular 2599 // IR operations. 2600 if (auto *R = dyn_cast<ConstantInt>(II->getArgOperand(2))) { 2601 if (R->getValue() == 4) { 2602 Value *Arg0 = II->getArgOperand(0); 2603 Value *Arg1 = II->getArgOperand(1); 2604 2605 Value *V; 2606 switch (II->getIntrinsicID()) { 2607 default: llvm_unreachable("Case stmts out of sync!"); 2608 case Intrinsic::x86_avx512_add_ps_512: 2609 case Intrinsic::x86_avx512_add_pd_512: 2610 V = Builder.CreateFAdd(Arg0, Arg1); 2611 break; 2612 case Intrinsic::x86_avx512_sub_ps_512: 2613 case Intrinsic::x86_avx512_sub_pd_512: 2614 V = Builder.CreateFSub(Arg0, Arg1); 2615 break; 2616 case Intrinsic::x86_avx512_mul_ps_512: 2617 case Intrinsic::x86_avx512_mul_pd_512: 2618 V = Builder.CreateFMul(Arg0, Arg1); 2619 break; 2620 case Intrinsic::x86_avx512_div_ps_512: 2621 case Intrinsic::x86_avx512_div_pd_512: 2622 V = Builder.CreateFDiv(Arg0, Arg1); 2623 break; 2624 } 2625 2626 return replaceInstUsesWith(*II, V); 2627 } 2628 } 2629 break; 2630 2631 case Intrinsic::x86_avx512_mask_add_ss_round: 2632 case Intrinsic::x86_avx512_mask_div_ss_round: 2633 case Intrinsic::x86_avx512_mask_mul_ss_round: 2634 case Intrinsic::x86_avx512_mask_sub_ss_round: 2635 case Intrinsic::x86_avx512_mask_add_sd_round: 2636 case Intrinsic::x86_avx512_mask_div_sd_round: 2637 case Intrinsic::x86_avx512_mask_mul_sd_round: 2638 case Intrinsic::x86_avx512_mask_sub_sd_round: 2639 // If the rounding mode is CUR_DIRECTION(4) we can turn these into regular 2640 // IR operations. 2641 if (auto *R = dyn_cast<ConstantInt>(II->getArgOperand(4))) { 2642 if (R->getValue() == 4) { 2643 // Extract the element as scalars. 2644 Value *Arg0 = II->getArgOperand(0); 2645 Value *Arg1 = II->getArgOperand(1); 2646 Value *LHS = Builder.CreateExtractElement(Arg0, (uint64_t)0); 2647 Value *RHS = Builder.CreateExtractElement(Arg1, (uint64_t)0); 2648 2649 Value *V; 2650 switch (II->getIntrinsicID()) { 2651 default: llvm_unreachable("Case stmts out of sync!"); 2652 case Intrinsic::x86_avx512_mask_add_ss_round: 2653 case Intrinsic::x86_avx512_mask_add_sd_round: 2654 V = Builder.CreateFAdd(LHS, RHS); 2655 break; 2656 case Intrinsic::x86_avx512_mask_sub_ss_round: 2657 case Intrinsic::x86_avx512_mask_sub_sd_round: 2658 V = Builder.CreateFSub(LHS, RHS); 2659 break; 2660 case Intrinsic::x86_avx512_mask_mul_ss_round: 2661 case Intrinsic::x86_avx512_mask_mul_sd_round: 2662 V = Builder.CreateFMul(LHS, RHS); 2663 break; 2664 case Intrinsic::x86_avx512_mask_div_ss_round: 2665 case Intrinsic::x86_avx512_mask_div_sd_round: 2666 V = Builder.CreateFDiv(LHS, RHS); 2667 break; 2668 } 2669 2670 // Handle the masking aspect of the intrinsic. 2671 Value *Mask = II->getArgOperand(3); 2672 auto *C = dyn_cast<ConstantInt>(Mask); 2673 // We don't need a select if we know the mask bit is a 1. 2674 if (!C || !C->getValue()[0]) { 2675 // Cast the mask to an i1 vector and then extract the lowest element. 2676 auto *MaskTy = VectorType::get(Builder.getInt1Ty(), 2677 cast<IntegerType>(Mask->getType())->getBitWidth()); 2678 Mask = Builder.CreateBitCast(Mask, MaskTy); 2679 Mask = Builder.CreateExtractElement(Mask, (uint64_t)0); 2680 // Extract the lowest element from the passthru operand. 2681 Value *Passthru = Builder.CreateExtractElement(II->getArgOperand(2), 2682 (uint64_t)0); 2683 V = Builder.CreateSelect(Mask, V, Passthru); 2684 } 2685 2686 // Insert the result back into the original argument 0. 2687 V = Builder.CreateInsertElement(Arg0, V, (uint64_t)0); 2688 2689 return replaceInstUsesWith(*II, V); 2690 } 2691 } 2692 LLVM_FALLTHROUGH; 2693 2694 // X86 scalar intrinsics simplified with SimplifyDemandedVectorElts. 2695 case Intrinsic::x86_avx512_mask_max_ss_round: 2696 case Intrinsic::x86_avx512_mask_min_ss_round: 2697 case Intrinsic::x86_avx512_mask_max_sd_round: 2698 case Intrinsic::x86_avx512_mask_min_sd_round: 2699 case Intrinsic::x86_sse_cmp_ss: 2700 case Intrinsic::x86_sse_min_ss: 2701 case Intrinsic::x86_sse_max_ss: 2702 case Intrinsic::x86_sse2_cmp_sd: 2703 case Intrinsic::x86_sse2_min_sd: 2704 case Intrinsic::x86_sse2_max_sd: 2705 case Intrinsic::x86_xop_vfrcz_ss: 2706 case Intrinsic::x86_xop_vfrcz_sd: { 2707 unsigned VWidth = II->getType()->getVectorNumElements(); 2708 APInt UndefElts(VWidth, 0); 2709 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth)); 2710 if (Value *V = SimplifyDemandedVectorElts(II, AllOnesEltMask, UndefElts)) { 2711 if (V != II) 2712 return replaceInstUsesWith(*II, V); 2713 return II; 2714 } 2715 break; 2716 } 2717 case Intrinsic::x86_sse41_round_ss: 2718 case Intrinsic::x86_sse41_round_sd: { 2719 unsigned VWidth = II->getType()->getVectorNumElements(); 2720 APInt UndefElts(VWidth, 0); 2721 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth)); 2722 if (Value *V = SimplifyDemandedVectorElts(II, AllOnesEltMask, UndefElts)) { 2723 if (V != II) 2724 return replaceInstUsesWith(*II, V); 2725 return II; 2726 } else if (Value *V = simplifyX86round(*II, Builder)) 2727 return replaceInstUsesWith(*II, V); 2728 break; 2729 } 2730 2731 // Constant fold ashr( <A x Bi>, Ci ). 2732 // Constant fold lshr( <A x Bi>, Ci ). 2733 // Constant fold shl( <A x Bi>, Ci ). 2734 case Intrinsic::x86_sse2_psrai_d: 2735 case Intrinsic::x86_sse2_psrai_w: 2736 case Intrinsic::x86_avx2_psrai_d: 2737 case Intrinsic::x86_avx2_psrai_w: 2738 case Intrinsic::x86_avx512_psrai_q_128: 2739 case Intrinsic::x86_avx512_psrai_q_256: 2740 case Intrinsic::x86_avx512_psrai_d_512: 2741 case Intrinsic::x86_avx512_psrai_q_512: 2742 case Intrinsic::x86_avx512_psrai_w_512: 2743 case Intrinsic::x86_sse2_psrli_d: 2744 case Intrinsic::x86_sse2_psrli_q: 2745 case Intrinsic::x86_sse2_psrli_w: 2746 case Intrinsic::x86_avx2_psrli_d: 2747 case Intrinsic::x86_avx2_psrli_q: 2748 case Intrinsic::x86_avx2_psrli_w: 2749 case Intrinsic::x86_avx512_psrli_d_512: 2750 case Intrinsic::x86_avx512_psrli_q_512: 2751 case Intrinsic::x86_avx512_psrli_w_512: 2752 case Intrinsic::x86_sse2_pslli_d: 2753 case Intrinsic::x86_sse2_pslli_q: 2754 case Intrinsic::x86_sse2_pslli_w: 2755 case Intrinsic::x86_avx2_pslli_d: 2756 case Intrinsic::x86_avx2_pslli_q: 2757 case Intrinsic::x86_avx2_pslli_w: 2758 case Intrinsic::x86_avx512_pslli_d_512: 2759 case Intrinsic::x86_avx512_pslli_q_512: 2760 case Intrinsic::x86_avx512_pslli_w_512: 2761 if (Value *V = simplifyX86immShift(*II, Builder)) 2762 return replaceInstUsesWith(*II, V); 2763 break; 2764 2765 case Intrinsic::x86_sse2_psra_d: 2766 case Intrinsic::x86_sse2_psra_w: 2767 case Intrinsic::x86_avx2_psra_d: 2768 case Intrinsic::x86_avx2_psra_w: 2769 case Intrinsic::x86_avx512_psra_q_128: 2770 case Intrinsic::x86_avx512_psra_q_256: 2771 case Intrinsic::x86_avx512_psra_d_512: 2772 case Intrinsic::x86_avx512_psra_q_512: 2773 case Intrinsic::x86_avx512_psra_w_512: 2774 case Intrinsic::x86_sse2_psrl_d: 2775 case Intrinsic::x86_sse2_psrl_q: 2776 case Intrinsic::x86_sse2_psrl_w: 2777 case Intrinsic::x86_avx2_psrl_d: 2778 case Intrinsic::x86_avx2_psrl_q: 2779 case Intrinsic::x86_avx2_psrl_w: 2780 case Intrinsic::x86_avx512_psrl_d_512: 2781 case Intrinsic::x86_avx512_psrl_q_512: 2782 case Intrinsic::x86_avx512_psrl_w_512: 2783 case Intrinsic::x86_sse2_psll_d: 2784 case Intrinsic::x86_sse2_psll_q: 2785 case Intrinsic::x86_sse2_psll_w: 2786 case Intrinsic::x86_avx2_psll_d: 2787 case Intrinsic::x86_avx2_psll_q: 2788 case Intrinsic::x86_avx2_psll_w: 2789 case Intrinsic::x86_avx512_psll_d_512: 2790 case Intrinsic::x86_avx512_psll_q_512: 2791 case Intrinsic::x86_avx512_psll_w_512: { 2792 if (Value *V = simplifyX86immShift(*II, Builder)) 2793 return replaceInstUsesWith(*II, V); 2794 2795 // SSE2/AVX2 uses only the first 64-bits of the 128-bit vector 2796 // operand to compute the shift amount. 2797 Value *Arg1 = II->getArgOperand(1); 2798 assert(Arg1->getType()->getPrimitiveSizeInBits() == 128 && 2799 "Unexpected packed shift size"); 2800 unsigned VWidth = Arg1->getType()->getVectorNumElements(); 2801 2802 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, VWidth / 2)) { 2803 II->setArgOperand(1, V); 2804 return II; 2805 } 2806 break; 2807 } 2808 2809 case Intrinsic::x86_avx2_psllv_d: 2810 case Intrinsic::x86_avx2_psllv_d_256: 2811 case Intrinsic::x86_avx2_psllv_q: 2812 case Intrinsic::x86_avx2_psllv_q_256: 2813 case Intrinsic::x86_avx512_psllv_d_512: 2814 case Intrinsic::x86_avx512_psllv_q_512: 2815 case Intrinsic::x86_avx512_psllv_w_128: 2816 case Intrinsic::x86_avx512_psllv_w_256: 2817 case Intrinsic::x86_avx512_psllv_w_512: 2818 case Intrinsic::x86_avx2_psrav_d: 2819 case Intrinsic::x86_avx2_psrav_d_256: 2820 case Intrinsic::x86_avx512_psrav_q_128: 2821 case Intrinsic::x86_avx512_psrav_q_256: 2822 case Intrinsic::x86_avx512_psrav_d_512: 2823 case Intrinsic::x86_avx512_psrav_q_512: 2824 case Intrinsic::x86_avx512_psrav_w_128: 2825 case Intrinsic::x86_avx512_psrav_w_256: 2826 case Intrinsic::x86_avx512_psrav_w_512: 2827 case Intrinsic::x86_avx2_psrlv_d: 2828 case Intrinsic::x86_avx2_psrlv_d_256: 2829 case Intrinsic::x86_avx2_psrlv_q: 2830 case Intrinsic::x86_avx2_psrlv_q_256: 2831 case Intrinsic::x86_avx512_psrlv_d_512: 2832 case Intrinsic::x86_avx512_psrlv_q_512: 2833 case Intrinsic::x86_avx512_psrlv_w_128: 2834 case Intrinsic::x86_avx512_psrlv_w_256: 2835 case Intrinsic::x86_avx512_psrlv_w_512: 2836 if (Value *V = simplifyX86varShift(*II, Builder)) 2837 return replaceInstUsesWith(*II, V); 2838 break; 2839 2840 case Intrinsic::x86_sse2_packssdw_128: 2841 case Intrinsic::x86_sse2_packsswb_128: 2842 case Intrinsic::x86_avx2_packssdw: 2843 case Intrinsic::x86_avx2_packsswb: 2844 case Intrinsic::x86_avx512_packssdw_512: 2845 case Intrinsic::x86_avx512_packsswb_512: 2846 if (Value *V = simplifyX86pack(*II, true)) 2847 return replaceInstUsesWith(*II, V); 2848 break; 2849 2850 case Intrinsic::x86_sse2_packuswb_128: 2851 case Intrinsic::x86_sse41_packusdw: 2852 case Intrinsic::x86_avx2_packusdw: 2853 case Intrinsic::x86_avx2_packuswb: 2854 case Intrinsic::x86_avx512_packusdw_512: 2855 case Intrinsic::x86_avx512_packuswb_512: 2856 if (Value *V = simplifyX86pack(*II, false)) 2857 return replaceInstUsesWith(*II, V); 2858 break; 2859 2860 case Intrinsic::x86_pclmulqdq: 2861 case Intrinsic::x86_pclmulqdq_256: 2862 case Intrinsic::x86_pclmulqdq_512: { 2863 if (auto *C = dyn_cast<ConstantInt>(II->getArgOperand(2))) { 2864 unsigned Imm = C->getZExtValue(); 2865 2866 bool MadeChange = false; 2867 Value *Arg0 = II->getArgOperand(0); 2868 Value *Arg1 = II->getArgOperand(1); 2869 unsigned VWidth = Arg0->getType()->getVectorNumElements(); 2870 2871 APInt UndefElts1(VWidth, 0); 2872 APInt DemandedElts1 = APInt::getSplat(VWidth, 2873 APInt(2, (Imm & 0x01) ? 2 : 1)); 2874 if (Value *V = SimplifyDemandedVectorElts(Arg0, DemandedElts1, 2875 UndefElts1)) { 2876 II->setArgOperand(0, V); 2877 MadeChange = true; 2878 } 2879 2880 APInt UndefElts2(VWidth, 0); 2881 APInt DemandedElts2 = APInt::getSplat(VWidth, 2882 APInt(2, (Imm & 0x10) ? 2 : 1)); 2883 if (Value *V = SimplifyDemandedVectorElts(Arg1, DemandedElts2, 2884 UndefElts2)) { 2885 II->setArgOperand(1, V); 2886 MadeChange = true; 2887 } 2888 2889 // If either input elements are undef, the result is zero. 2890 if (DemandedElts1.isSubsetOf(UndefElts1) || 2891 DemandedElts2.isSubsetOf(UndefElts2)) 2892 return replaceInstUsesWith(*II, 2893 ConstantAggregateZero::get(II->getType())); 2894 2895 if (MadeChange) 2896 return II; 2897 } 2898 break; 2899 } 2900 2901 case Intrinsic::x86_sse41_insertps: 2902 if (Value *V = simplifyX86insertps(*II, Builder)) 2903 return replaceInstUsesWith(*II, V); 2904 break; 2905 2906 case Intrinsic::x86_sse4a_extrq: { 2907 Value *Op0 = II->getArgOperand(0); 2908 Value *Op1 = II->getArgOperand(1); 2909 unsigned VWidth0 = Op0->getType()->getVectorNumElements(); 2910 unsigned VWidth1 = Op1->getType()->getVectorNumElements(); 2911 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 && 2912 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 && 2913 VWidth1 == 16 && "Unexpected operand sizes"); 2914 2915 // See if we're dealing with constant values. 2916 Constant *C1 = dyn_cast<Constant>(Op1); 2917 ConstantInt *CILength = 2918 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)0)) 2919 : nullptr; 2920 ConstantInt *CIIndex = 2921 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)1)) 2922 : nullptr; 2923 2924 // Attempt to simplify to a constant, shuffle vector or EXTRQI call. 2925 if (Value *V = simplifyX86extrq(*II, Op0, CILength, CIIndex, Builder)) 2926 return replaceInstUsesWith(*II, V); 2927 2928 // EXTRQ only uses the lowest 64-bits of the first 128-bit vector 2929 // operands and the lowest 16-bits of the second. 2930 bool MadeChange = false; 2931 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) { 2932 II->setArgOperand(0, V); 2933 MadeChange = true; 2934 } 2935 if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 2)) { 2936 II->setArgOperand(1, V); 2937 MadeChange = true; 2938 } 2939 if (MadeChange) 2940 return II; 2941 break; 2942 } 2943 2944 case Intrinsic::x86_sse4a_extrqi: { 2945 // EXTRQI: Extract Length bits starting from Index. Zero pad the remaining 2946 // bits of the lower 64-bits. The upper 64-bits are undefined. 2947 Value *Op0 = II->getArgOperand(0); 2948 unsigned VWidth = Op0->getType()->getVectorNumElements(); 2949 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 && 2950 "Unexpected operand size"); 2951 2952 // See if we're dealing with constant values. 2953 ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(1)); 2954 ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(2)); 2955 2956 // Attempt to simplify to a constant or shuffle vector. 2957 if (Value *V = simplifyX86extrq(*II, Op0, CILength, CIIndex, Builder)) 2958 return replaceInstUsesWith(*II, V); 2959 2960 // EXTRQI only uses the lowest 64-bits of the first 128-bit vector 2961 // operand. 2962 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) { 2963 II->setArgOperand(0, V); 2964 return II; 2965 } 2966 break; 2967 } 2968 2969 case Intrinsic::x86_sse4a_insertq: { 2970 Value *Op0 = II->getArgOperand(0); 2971 Value *Op1 = II->getArgOperand(1); 2972 unsigned VWidth = Op0->getType()->getVectorNumElements(); 2973 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 && 2974 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 && 2975 Op1->getType()->getVectorNumElements() == 2 && 2976 "Unexpected operand size"); 2977 2978 // See if we're dealing with constant values. 2979 Constant *C1 = dyn_cast<Constant>(Op1); 2980 ConstantInt *CI11 = 2981 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)1)) 2982 : nullptr; 2983 2984 // Attempt to simplify to a constant, shuffle vector or INSERTQI call. 2985 if (CI11) { 2986 const APInt &V11 = CI11->getValue(); 2987 APInt Len = V11.zextOrTrunc(6); 2988 APInt Idx = V11.lshr(8).zextOrTrunc(6); 2989 if (Value *V = simplifyX86insertq(*II, Op0, Op1, Len, Idx, Builder)) 2990 return replaceInstUsesWith(*II, V); 2991 } 2992 2993 // INSERTQ only uses the lowest 64-bits of the first 128-bit vector 2994 // operand. 2995 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) { 2996 II->setArgOperand(0, V); 2997 return II; 2998 } 2999 break; 3000 } 3001 3002 case Intrinsic::x86_sse4a_insertqi: { 3003 // INSERTQI: Extract lowest Length bits from lower half of second source and 3004 // insert over first source starting at Index bit. The upper 64-bits are 3005 // undefined. 3006 Value *Op0 = II->getArgOperand(0); 3007 Value *Op1 = II->getArgOperand(1); 3008 unsigned VWidth0 = Op0->getType()->getVectorNumElements(); 3009 unsigned VWidth1 = Op1->getType()->getVectorNumElements(); 3010 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 && 3011 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 && 3012 VWidth1 == 2 && "Unexpected operand sizes"); 3013 3014 // See if we're dealing with constant values. 3015 ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(2)); 3016 ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(3)); 3017 3018 // Attempt to simplify to a constant or shuffle vector. 3019 if (CILength && CIIndex) { 3020 APInt Len = CILength->getValue().zextOrTrunc(6); 3021 APInt Idx = CIIndex->getValue().zextOrTrunc(6); 3022 if (Value *V = simplifyX86insertq(*II, Op0, Op1, Len, Idx, Builder)) 3023 return replaceInstUsesWith(*II, V); 3024 } 3025 3026 // INSERTQI only uses the lowest 64-bits of the first two 128-bit vector 3027 // operands. 3028 bool MadeChange = false; 3029 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) { 3030 II->setArgOperand(0, V); 3031 MadeChange = true; 3032 } 3033 if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 1)) { 3034 II->setArgOperand(1, V); 3035 MadeChange = true; 3036 } 3037 if (MadeChange) 3038 return II; 3039 break; 3040 } 3041 3042 case Intrinsic::x86_sse41_pblendvb: 3043 case Intrinsic::x86_sse41_blendvps: 3044 case Intrinsic::x86_sse41_blendvpd: 3045 case Intrinsic::x86_avx_blendv_ps_256: 3046 case Intrinsic::x86_avx_blendv_pd_256: 3047 case Intrinsic::x86_avx2_pblendvb: { 3048 // fold (blend A, A, Mask) -> A 3049 Value *Op0 = II->getArgOperand(0); 3050 Value *Op1 = II->getArgOperand(1); 3051 Value *Mask = II->getArgOperand(2); 3052 if (Op0 == Op1) 3053 return replaceInstUsesWith(CI, Op0); 3054 3055 // Zero Mask - select 1st argument. 3056 if (isa<ConstantAggregateZero>(Mask)) 3057 return replaceInstUsesWith(CI, Op0); 3058 3059 // Constant Mask - select 1st/2nd argument lane based on top bit of mask. 3060 if (auto *ConstantMask = dyn_cast<ConstantDataVector>(Mask)) { 3061 Constant *NewSelector = getNegativeIsTrueBoolVec(ConstantMask); 3062 return SelectInst::Create(NewSelector, Op1, Op0, "blendv"); 3063 } 3064 3065 // Convert to a vector select if we can bypass casts and find a boolean 3066 // vector condition value. 3067 Value *BoolVec; 3068 Mask = peekThroughBitcast(Mask); 3069 if (match(Mask, m_SExt(m_Value(BoolVec))) && 3070 BoolVec->getType()->isVectorTy() && 3071 BoolVec->getType()->getScalarSizeInBits() == 1) { 3072 assert(Mask->getType()->getPrimitiveSizeInBits() == 3073 II->getType()->getPrimitiveSizeInBits() && 3074 "Not expecting mask and operands with different sizes"); 3075 3076 unsigned NumMaskElts = Mask->getType()->getVectorNumElements(); 3077 unsigned NumOperandElts = II->getType()->getVectorNumElements(); 3078 if (NumMaskElts == NumOperandElts) 3079 return SelectInst::Create(BoolVec, Op1, Op0); 3080 3081 // If the mask has less elements than the operands, each mask bit maps to 3082 // multiple elements of the operands. Bitcast back and forth. 3083 if (NumMaskElts < NumOperandElts) { 3084 Value *CastOp0 = Builder.CreateBitCast(Op0, Mask->getType()); 3085 Value *CastOp1 = Builder.CreateBitCast(Op1, Mask->getType()); 3086 Value *Sel = Builder.CreateSelect(BoolVec, CastOp1, CastOp0); 3087 return new BitCastInst(Sel, II->getType()); 3088 } 3089 } 3090 3091 break; 3092 } 3093 3094 case Intrinsic::x86_ssse3_pshuf_b_128: 3095 case Intrinsic::x86_avx2_pshuf_b: 3096 case Intrinsic::x86_avx512_pshuf_b_512: 3097 if (Value *V = simplifyX86pshufb(*II, Builder)) 3098 return replaceInstUsesWith(*II, V); 3099 break; 3100 3101 case Intrinsic::x86_avx_vpermilvar_ps: 3102 case Intrinsic::x86_avx_vpermilvar_ps_256: 3103 case Intrinsic::x86_avx512_vpermilvar_ps_512: 3104 case Intrinsic::x86_avx_vpermilvar_pd: 3105 case Intrinsic::x86_avx_vpermilvar_pd_256: 3106 case Intrinsic::x86_avx512_vpermilvar_pd_512: 3107 if (Value *V = simplifyX86vpermilvar(*II, Builder)) 3108 return replaceInstUsesWith(*II, V); 3109 break; 3110 3111 case Intrinsic::x86_avx2_permd: 3112 case Intrinsic::x86_avx2_permps: 3113 case Intrinsic::x86_avx512_permvar_df_256: 3114 case Intrinsic::x86_avx512_permvar_df_512: 3115 case Intrinsic::x86_avx512_permvar_di_256: 3116 case Intrinsic::x86_avx512_permvar_di_512: 3117 case Intrinsic::x86_avx512_permvar_hi_128: 3118 case Intrinsic::x86_avx512_permvar_hi_256: 3119 case Intrinsic::x86_avx512_permvar_hi_512: 3120 case Intrinsic::x86_avx512_permvar_qi_128: 3121 case Intrinsic::x86_avx512_permvar_qi_256: 3122 case Intrinsic::x86_avx512_permvar_qi_512: 3123 case Intrinsic::x86_avx512_permvar_sf_512: 3124 case Intrinsic::x86_avx512_permvar_si_512: 3125 if (Value *V = simplifyX86vpermv(*II, Builder)) 3126 return replaceInstUsesWith(*II, V); 3127 break; 3128 3129 case Intrinsic::x86_avx_maskload_ps: 3130 case Intrinsic::x86_avx_maskload_pd: 3131 case Intrinsic::x86_avx_maskload_ps_256: 3132 case Intrinsic::x86_avx_maskload_pd_256: 3133 case Intrinsic::x86_avx2_maskload_d: 3134 case Intrinsic::x86_avx2_maskload_q: 3135 case Intrinsic::x86_avx2_maskload_d_256: 3136 case Intrinsic::x86_avx2_maskload_q_256: 3137 if (Instruction *I = simplifyX86MaskedLoad(*II, *this)) 3138 return I; 3139 break; 3140 3141 case Intrinsic::x86_sse2_maskmov_dqu: 3142 case Intrinsic::x86_avx_maskstore_ps: 3143 case Intrinsic::x86_avx_maskstore_pd: 3144 case Intrinsic::x86_avx_maskstore_ps_256: 3145 case Intrinsic::x86_avx_maskstore_pd_256: 3146 case Intrinsic::x86_avx2_maskstore_d: 3147 case Intrinsic::x86_avx2_maskstore_q: 3148 case Intrinsic::x86_avx2_maskstore_d_256: 3149 case Intrinsic::x86_avx2_maskstore_q_256: 3150 if (simplifyX86MaskedStore(*II, *this)) 3151 return nullptr; 3152 break; 3153 3154 case Intrinsic::x86_xop_vpcomb: 3155 case Intrinsic::x86_xop_vpcomd: 3156 case Intrinsic::x86_xop_vpcomq: 3157 case Intrinsic::x86_xop_vpcomw: 3158 if (Value *V = simplifyX86vpcom(*II, Builder, true)) 3159 return replaceInstUsesWith(*II, V); 3160 break; 3161 3162 case Intrinsic::x86_xop_vpcomub: 3163 case Intrinsic::x86_xop_vpcomud: 3164 case Intrinsic::x86_xop_vpcomuq: 3165 case Intrinsic::x86_xop_vpcomuw: 3166 if (Value *V = simplifyX86vpcom(*II, Builder, false)) 3167 return replaceInstUsesWith(*II, V); 3168 break; 3169 3170 case Intrinsic::ppc_altivec_vperm: 3171 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant. 3172 // Note that ppc_altivec_vperm has a big-endian bias, so when creating 3173 // a vectorshuffle for little endian, we must undo the transformation 3174 // performed on vec_perm in altivec.h. That is, we must complement 3175 // the permutation mask with respect to 31 and reverse the order of 3176 // V1 and V2. 3177 if (Constant *Mask = dyn_cast<Constant>(II->getArgOperand(2))) { 3178 assert(Mask->getType()->getVectorNumElements() == 16 && 3179 "Bad type for intrinsic!"); 3180 3181 // Check that all of the elements are integer constants or undefs. 3182 bool AllEltsOk = true; 3183 for (unsigned i = 0; i != 16; ++i) { 3184 Constant *Elt = Mask->getAggregateElement(i); 3185 if (!Elt || !(isa<ConstantInt>(Elt) || isa<UndefValue>(Elt))) { 3186 AllEltsOk = false; 3187 break; 3188 } 3189 } 3190 3191 if (AllEltsOk) { 3192 // Cast the input vectors to byte vectors. 3193 Value *Op0 = Builder.CreateBitCast(II->getArgOperand(0), 3194 Mask->getType()); 3195 Value *Op1 = Builder.CreateBitCast(II->getArgOperand(1), 3196 Mask->getType()); 3197 Value *Result = UndefValue::get(Op0->getType()); 3198 3199 // Only extract each element once. 3200 Value *ExtractedElts[32]; 3201 memset(ExtractedElts, 0, sizeof(ExtractedElts)); 3202 3203 for (unsigned i = 0; i != 16; ++i) { 3204 if (isa<UndefValue>(Mask->getAggregateElement(i))) 3205 continue; 3206 unsigned Idx = 3207 cast<ConstantInt>(Mask->getAggregateElement(i))->getZExtValue(); 3208 Idx &= 31; // Match the hardware behavior. 3209 if (DL.isLittleEndian()) 3210 Idx = 31 - Idx; 3211 3212 if (!ExtractedElts[Idx]) { 3213 Value *Op0ToUse = (DL.isLittleEndian()) ? Op1 : Op0; 3214 Value *Op1ToUse = (DL.isLittleEndian()) ? Op0 : Op1; 3215 ExtractedElts[Idx] = 3216 Builder.CreateExtractElement(Idx < 16 ? Op0ToUse : Op1ToUse, 3217 Builder.getInt32(Idx&15)); 3218 } 3219 3220 // Insert this value into the result vector. 3221 Result = Builder.CreateInsertElement(Result, ExtractedElts[Idx], 3222 Builder.getInt32(i)); 3223 } 3224 return CastInst::Create(Instruction::BitCast, Result, CI.getType()); 3225 } 3226 } 3227 break; 3228 3229 case Intrinsic::arm_neon_vld1: { 3230 unsigned MemAlign = getKnownAlignment(II->getArgOperand(0), 3231 DL, II, &AC, &DT); 3232 if (Value *V = simplifyNeonVld1(*II, MemAlign, Builder)) 3233 return replaceInstUsesWith(*II, V); 3234 break; 3235 } 3236 3237 case Intrinsic::arm_neon_vld2: 3238 case Intrinsic::arm_neon_vld3: 3239 case Intrinsic::arm_neon_vld4: 3240 case Intrinsic::arm_neon_vld2lane: 3241 case Intrinsic::arm_neon_vld3lane: 3242 case Intrinsic::arm_neon_vld4lane: 3243 case Intrinsic::arm_neon_vst1: 3244 case Intrinsic::arm_neon_vst2: 3245 case Intrinsic::arm_neon_vst3: 3246 case Intrinsic::arm_neon_vst4: 3247 case Intrinsic::arm_neon_vst2lane: 3248 case Intrinsic::arm_neon_vst3lane: 3249 case Intrinsic::arm_neon_vst4lane: { 3250 unsigned MemAlign = 3251 getKnownAlignment(II->getArgOperand(0), DL, II, &AC, &DT); 3252 unsigned AlignArg = II->getNumArgOperands() - 1; 3253 ConstantInt *IntrAlign = dyn_cast<ConstantInt>(II->getArgOperand(AlignArg)); 3254 if (IntrAlign && IntrAlign->getZExtValue() < MemAlign) { 3255 II->setArgOperand(AlignArg, 3256 ConstantInt::get(Type::getInt32Ty(II->getContext()), 3257 MemAlign, false)); 3258 return II; 3259 } 3260 break; 3261 } 3262 3263 case Intrinsic::arm_neon_vtbl1: 3264 case Intrinsic::aarch64_neon_tbl1: 3265 if (Value *V = simplifyNeonTbl1(*II, Builder)) 3266 return replaceInstUsesWith(*II, V); 3267 break; 3268 3269 case Intrinsic::arm_neon_vmulls: 3270 case Intrinsic::arm_neon_vmullu: 3271 case Intrinsic::aarch64_neon_smull: 3272 case Intrinsic::aarch64_neon_umull: { 3273 Value *Arg0 = II->getArgOperand(0); 3274 Value *Arg1 = II->getArgOperand(1); 3275 3276 // Handle mul by zero first: 3277 if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) { 3278 return replaceInstUsesWith(CI, ConstantAggregateZero::get(II->getType())); 3279 } 3280 3281 // Check for constant LHS & RHS - in this case we just simplify. 3282 bool Zext = (II->getIntrinsicID() == Intrinsic::arm_neon_vmullu || 3283 II->getIntrinsicID() == Intrinsic::aarch64_neon_umull); 3284 VectorType *NewVT = cast<VectorType>(II->getType()); 3285 if (Constant *CV0 = dyn_cast<Constant>(Arg0)) { 3286 if (Constant *CV1 = dyn_cast<Constant>(Arg1)) { 3287 CV0 = ConstantExpr::getIntegerCast(CV0, NewVT, /*isSigned=*/!Zext); 3288 CV1 = ConstantExpr::getIntegerCast(CV1, NewVT, /*isSigned=*/!Zext); 3289 3290 return replaceInstUsesWith(CI, ConstantExpr::getMul(CV0, CV1)); 3291 } 3292 3293 // Couldn't simplify - canonicalize constant to the RHS. 3294 std::swap(Arg0, Arg1); 3295 } 3296 3297 // Handle mul by one: 3298 if (Constant *CV1 = dyn_cast<Constant>(Arg1)) 3299 if (ConstantInt *Splat = 3300 dyn_cast_or_null<ConstantInt>(CV1->getSplatValue())) 3301 if (Splat->isOne()) 3302 return CastInst::CreateIntegerCast(Arg0, II->getType(), 3303 /*isSigned=*/!Zext); 3304 3305 break; 3306 } 3307 case Intrinsic::arm_neon_aesd: 3308 case Intrinsic::arm_neon_aese: 3309 case Intrinsic::aarch64_crypto_aesd: 3310 case Intrinsic::aarch64_crypto_aese: { 3311 Value *DataArg = II->getArgOperand(0); 3312 Value *KeyArg = II->getArgOperand(1); 3313 3314 // Try to use the builtin XOR in AESE and AESD to eliminate a prior XOR 3315 Value *Data, *Key; 3316 if (match(KeyArg, m_ZeroInt()) && 3317 match(DataArg, m_Xor(m_Value(Data), m_Value(Key)))) { 3318 II->setArgOperand(0, Data); 3319 II->setArgOperand(1, Key); 3320 return II; 3321 } 3322 break; 3323 } 3324 case Intrinsic::amdgcn_rcp: { 3325 Value *Src = II->getArgOperand(0); 3326 3327 // TODO: Move to ConstantFolding/InstSimplify? 3328 if (isa<UndefValue>(Src)) 3329 return replaceInstUsesWith(CI, Src); 3330 3331 if (const ConstantFP *C = dyn_cast<ConstantFP>(Src)) { 3332 const APFloat &ArgVal = C->getValueAPF(); 3333 APFloat Val(ArgVal.getSemantics(), 1.0); 3334 APFloat::opStatus Status = Val.divide(ArgVal, 3335 APFloat::rmNearestTiesToEven); 3336 // Only do this if it was exact and therefore not dependent on the 3337 // rounding mode. 3338 if (Status == APFloat::opOK) 3339 return replaceInstUsesWith(CI, ConstantFP::get(II->getContext(), Val)); 3340 } 3341 3342 break; 3343 } 3344 case Intrinsic::amdgcn_rsq: { 3345 Value *Src = II->getArgOperand(0); 3346 3347 // TODO: Move to ConstantFolding/InstSimplify? 3348 if (isa<UndefValue>(Src)) 3349 return replaceInstUsesWith(CI, Src); 3350 break; 3351 } 3352 case Intrinsic::amdgcn_frexp_mant: 3353 case Intrinsic::amdgcn_frexp_exp: { 3354 Value *Src = II->getArgOperand(0); 3355 if (const ConstantFP *C = dyn_cast<ConstantFP>(Src)) { 3356 int Exp; 3357 APFloat Significand = frexp(C->getValueAPF(), Exp, 3358 APFloat::rmNearestTiesToEven); 3359 3360 if (II->getIntrinsicID() == Intrinsic::amdgcn_frexp_mant) { 3361 return replaceInstUsesWith(CI, ConstantFP::get(II->getContext(), 3362 Significand)); 3363 } 3364 3365 // Match instruction special case behavior. 3366 if (Exp == APFloat::IEK_NaN || Exp == APFloat::IEK_Inf) 3367 Exp = 0; 3368 3369 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), Exp)); 3370 } 3371 3372 if (isa<UndefValue>(Src)) 3373 return replaceInstUsesWith(CI, UndefValue::get(II->getType())); 3374 3375 break; 3376 } 3377 case Intrinsic::amdgcn_class: { 3378 enum { 3379 S_NAN = 1 << 0, // Signaling NaN 3380 Q_NAN = 1 << 1, // Quiet NaN 3381 N_INFINITY = 1 << 2, // Negative infinity 3382 N_NORMAL = 1 << 3, // Negative normal 3383 N_SUBNORMAL = 1 << 4, // Negative subnormal 3384 N_ZERO = 1 << 5, // Negative zero 3385 P_ZERO = 1 << 6, // Positive zero 3386 P_SUBNORMAL = 1 << 7, // Positive subnormal 3387 P_NORMAL = 1 << 8, // Positive normal 3388 P_INFINITY = 1 << 9 // Positive infinity 3389 }; 3390 3391 const uint32_t FullMask = S_NAN | Q_NAN | N_INFINITY | N_NORMAL | 3392 N_SUBNORMAL | N_ZERO | P_ZERO | P_SUBNORMAL | P_NORMAL | P_INFINITY; 3393 3394 Value *Src0 = II->getArgOperand(0); 3395 Value *Src1 = II->getArgOperand(1); 3396 const ConstantInt *CMask = dyn_cast<ConstantInt>(Src1); 3397 if (!CMask) { 3398 if (isa<UndefValue>(Src0)) 3399 return replaceInstUsesWith(*II, UndefValue::get(II->getType())); 3400 3401 if (isa<UndefValue>(Src1)) 3402 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), false)); 3403 break; 3404 } 3405 3406 uint32_t Mask = CMask->getZExtValue(); 3407 3408 // If all tests are made, it doesn't matter what the value is. 3409 if ((Mask & FullMask) == FullMask) 3410 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), true)); 3411 3412 if ((Mask & FullMask) == 0) 3413 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), false)); 3414 3415 if (Mask == (S_NAN | Q_NAN)) { 3416 // Equivalent of isnan. Replace with standard fcmp. 3417 Value *FCmp = Builder.CreateFCmpUNO(Src0, Src0); 3418 FCmp->takeName(II); 3419 return replaceInstUsesWith(*II, FCmp); 3420 } 3421 3422 if (Mask == (N_ZERO | P_ZERO)) { 3423 // Equivalent of == 0. 3424 Value *FCmp = Builder.CreateFCmpOEQ( 3425 Src0, ConstantFP::get(Src0->getType(), 0.0)); 3426 3427 FCmp->takeName(II); 3428 return replaceInstUsesWith(*II, FCmp); 3429 } 3430 3431 // fp_class (nnan x), qnan|snan|other -> fp_class (nnan x), other 3432 if (((Mask & S_NAN) || (Mask & Q_NAN)) && isKnownNeverNaN(Src0, &TLI)) { 3433 II->setArgOperand(1, ConstantInt::get(Src1->getType(), 3434 Mask & ~(S_NAN | Q_NAN))); 3435 return II; 3436 } 3437 3438 const ConstantFP *CVal = dyn_cast<ConstantFP>(Src0); 3439 if (!CVal) { 3440 if (isa<UndefValue>(Src0)) 3441 return replaceInstUsesWith(*II, UndefValue::get(II->getType())); 3442 3443 // Clamp mask to used bits 3444 if ((Mask & FullMask) != Mask) { 3445 CallInst *NewCall = Builder.CreateCall(II->getCalledFunction(), 3446 { Src0, ConstantInt::get(Src1->getType(), Mask & FullMask) } 3447 ); 3448 3449 NewCall->takeName(II); 3450 return replaceInstUsesWith(*II, NewCall); 3451 } 3452 3453 break; 3454 } 3455 3456 const APFloat &Val = CVal->getValueAPF(); 3457 3458 bool Result = 3459 ((Mask & S_NAN) && Val.isNaN() && Val.isSignaling()) || 3460 ((Mask & Q_NAN) && Val.isNaN() && !Val.isSignaling()) || 3461 ((Mask & N_INFINITY) && Val.isInfinity() && Val.isNegative()) || 3462 ((Mask & N_NORMAL) && Val.isNormal() && Val.isNegative()) || 3463 ((Mask & N_SUBNORMAL) && Val.isDenormal() && Val.isNegative()) || 3464 ((Mask & N_ZERO) && Val.isZero() && Val.isNegative()) || 3465 ((Mask & P_ZERO) && Val.isZero() && !Val.isNegative()) || 3466 ((Mask & P_SUBNORMAL) && Val.isDenormal() && !Val.isNegative()) || 3467 ((Mask & P_NORMAL) && Val.isNormal() && !Val.isNegative()) || 3468 ((Mask & P_INFINITY) && Val.isInfinity() && !Val.isNegative()); 3469 3470 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), Result)); 3471 } 3472 case Intrinsic::amdgcn_cvt_pkrtz: { 3473 Value *Src0 = II->getArgOperand(0); 3474 Value *Src1 = II->getArgOperand(1); 3475 if (const ConstantFP *C0 = dyn_cast<ConstantFP>(Src0)) { 3476 if (const ConstantFP *C1 = dyn_cast<ConstantFP>(Src1)) { 3477 const fltSemantics &HalfSem 3478 = II->getType()->getScalarType()->getFltSemantics(); 3479 bool LosesInfo; 3480 APFloat Val0 = C0->getValueAPF(); 3481 APFloat Val1 = C1->getValueAPF(); 3482 Val0.convert(HalfSem, APFloat::rmTowardZero, &LosesInfo); 3483 Val1.convert(HalfSem, APFloat::rmTowardZero, &LosesInfo); 3484 3485 Constant *Folded = ConstantVector::get({ 3486 ConstantFP::get(II->getContext(), Val0), 3487 ConstantFP::get(II->getContext(), Val1) }); 3488 return replaceInstUsesWith(*II, Folded); 3489 } 3490 } 3491 3492 if (isa<UndefValue>(Src0) && isa<UndefValue>(Src1)) 3493 return replaceInstUsesWith(*II, UndefValue::get(II->getType())); 3494 3495 break; 3496 } 3497 case Intrinsic::amdgcn_cvt_pknorm_i16: 3498 case Intrinsic::amdgcn_cvt_pknorm_u16: 3499 case Intrinsic::amdgcn_cvt_pk_i16: 3500 case Intrinsic::amdgcn_cvt_pk_u16: { 3501 Value *Src0 = II->getArgOperand(0); 3502 Value *Src1 = II->getArgOperand(1); 3503 3504 if (isa<UndefValue>(Src0) && isa<UndefValue>(Src1)) 3505 return replaceInstUsesWith(*II, UndefValue::get(II->getType())); 3506 3507 break; 3508 } 3509 case Intrinsic::amdgcn_ubfe: 3510 case Intrinsic::amdgcn_sbfe: { 3511 // Decompose simple cases into standard shifts. 3512 Value *Src = II->getArgOperand(0); 3513 if (isa<UndefValue>(Src)) 3514 return replaceInstUsesWith(*II, Src); 3515 3516 unsigned Width; 3517 Type *Ty = II->getType(); 3518 unsigned IntSize = Ty->getIntegerBitWidth(); 3519 3520 ConstantInt *CWidth = dyn_cast<ConstantInt>(II->getArgOperand(2)); 3521 if (CWidth) { 3522 Width = CWidth->getZExtValue(); 3523 if ((Width & (IntSize - 1)) == 0) 3524 return replaceInstUsesWith(*II, ConstantInt::getNullValue(Ty)); 3525 3526 if (Width >= IntSize) { 3527 // Hardware ignores high bits, so remove those. 3528 II->setArgOperand(2, ConstantInt::get(CWidth->getType(), 3529 Width & (IntSize - 1))); 3530 return II; 3531 } 3532 } 3533 3534 unsigned Offset; 3535 ConstantInt *COffset = dyn_cast<ConstantInt>(II->getArgOperand(1)); 3536 if (COffset) { 3537 Offset = COffset->getZExtValue(); 3538 if (Offset >= IntSize) { 3539 II->setArgOperand(1, ConstantInt::get(COffset->getType(), 3540 Offset & (IntSize - 1))); 3541 return II; 3542 } 3543 } 3544 3545 bool Signed = II->getIntrinsicID() == Intrinsic::amdgcn_sbfe; 3546 3547 if (!CWidth || !COffset) 3548 break; 3549 3550 // The case of Width == 0 is handled above, which makes this tranformation 3551 // safe. If Width == 0, then the ashr and lshr instructions become poison 3552 // value since the shift amount would be equal to the bit size. 3553 assert(Width != 0); 3554 3555 // TODO: This allows folding to undef when the hardware has specific 3556 // behavior? 3557 if (Offset + Width < IntSize) { 3558 Value *Shl = Builder.CreateShl(Src, IntSize - Offset - Width); 3559 Value *RightShift = Signed ? Builder.CreateAShr(Shl, IntSize - Width) 3560 : Builder.CreateLShr(Shl, IntSize - Width); 3561 RightShift->takeName(II); 3562 return replaceInstUsesWith(*II, RightShift); 3563 } 3564 3565 Value *RightShift = Signed ? Builder.CreateAShr(Src, Offset) 3566 : Builder.CreateLShr(Src, Offset); 3567 3568 RightShift->takeName(II); 3569 return replaceInstUsesWith(*II, RightShift); 3570 } 3571 case Intrinsic::amdgcn_exp: 3572 case Intrinsic::amdgcn_exp_compr: { 3573 ConstantInt *En = dyn_cast<ConstantInt>(II->getArgOperand(1)); 3574 if (!En) // Illegal. 3575 break; 3576 3577 unsigned EnBits = En->getZExtValue(); 3578 if (EnBits == 0xf) 3579 break; // All inputs enabled. 3580 3581 bool IsCompr = II->getIntrinsicID() == Intrinsic::amdgcn_exp_compr; 3582 bool Changed = false; 3583 for (int I = 0; I < (IsCompr ? 2 : 4); ++I) { 3584 if ((!IsCompr && (EnBits & (1 << I)) == 0) || 3585 (IsCompr && ((EnBits & (0x3 << (2 * I))) == 0))) { 3586 Value *Src = II->getArgOperand(I + 2); 3587 if (!isa<UndefValue>(Src)) { 3588 II->setArgOperand(I + 2, UndefValue::get(Src->getType())); 3589 Changed = true; 3590 } 3591 } 3592 } 3593 3594 if (Changed) 3595 return II; 3596 3597 break; 3598 } 3599 case Intrinsic::amdgcn_fmed3: { 3600 // Note this does not preserve proper sNaN behavior if IEEE-mode is enabled 3601 // for the shader. 3602 3603 Value *Src0 = II->getArgOperand(0); 3604 Value *Src1 = II->getArgOperand(1); 3605 Value *Src2 = II->getArgOperand(2); 3606 3607 // Checking for NaN before canonicalization provides better fidelity when 3608 // mapping other operations onto fmed3 since the order of operands is 3609 // unchanged. 3610 CallInst *NewCall = nullptr; 3611 if (match(Src0, m_NaN()) || isa<UndefValue>(Src0)) { 3612 NewCall = Builder.CreateMinNum(Src1, Src2); 3613 } else if (match(Src1, m_NaN()) || isa<UndefValue>(Src1)) { 3614 NewCall = Builder.CreateMinNum(Src0, Src2); 3615 } else if (match(Src2, m_NaN()) || isa<UndefValue>(Src2)) { 3616 NewCall = Builder.CreateMaxNum(Src0, Src1); 3617 } 3618 3619 if (NewCall) { 3620 NewCall->copyFastMathFlags(II); 3621 NewCall->takeName(II); 3622 return replaceInstUsesWith(*II, NewCall); 3623 } 3624 3625 bool Swap = false; 3626 // Canonicalize constants to RHS operands. 3627 // 3628 // fmed3(c0, x, c1) -> fmed3(x, c0, c1) 3629 if (isa<Constant>(Src0) && !isa<Constant>(Src1)) { 3630 std::swap(Src0, Src1); 3631 Swap = true; 3632 } 3633 3634 if (isa<Constant>(Src1) && !isa<Constant>(Src2)) { 3635 std::swap(Src1, Src2); 3636 Swap = true; 3637 } 3638 3639 if (isa<Constant>(Src0) && !isa<Constant>(Src1)) { 3640 std::swap(Src0, Src1); 3641 Swap = true; 3642 } 3643 3644 if (Swap) { 3645 II->setArgOperand(0, Src0); 3646 II->setArgOperand(1, Src1); 3647 II->setArgOperand(2, Src2); 3648 return II; 3649 } 3650 3651 if (const ConstantFP *C0 = dyn_cast<ConstantFP>(Src0)) { 3652 if (const ConstantFP *C1 = dyn_cast<ConstantFP>(Src1)) { 3653 if (const ConstantFP *C2 = dyn_cast<ConstantFP>(Src2)) { 3654 APFloat Result = fmed3AMDGCN(C0->getValueAPF(), C1->getValueAPF(), 3655 C2->getValueAPF()); 3656 return replaceInstUsesWith(*II, 3657 ConstantFP::get(Builder.getContext(), Result)); 3658 } 3659 } 3660 } 3661 3662 break; 3663 } 3664 case Intrinsic::amdgcn_icmp: 3665 case Intrinsic::amdgcn_fcmp: { 3666 const ConstantInt *CC = dyn_cast<ConstantInt>(II->getArgOperand(2)); 3667 if (!CC) 3668 break; 3669 3670 // Guard against invalid arguments. 3671 int64_t CCVal = CC->getZExtValue(); 3672 bool IsInteger = II->getIntrinsicID() == Intrinsic::amdgcn_icmp; 3673 if ((IsInteger && (CCVal < CmpInst::FIRST_ICMP_PREDICATE || 3674 CCVal > CmpInst::LAST_ICMP_PREDICATE)) || 3675 (!IsInteger && (CCVal < CmpInst::FIRST_FCMP_PREDICATE || 3676 CCVal > CmpInst::LAST_FCMP_PREDICATE))) 3677 break; 3678 3679 Value *Src0 = II->getArgOperand(0); 3680 Value *Src1 = II->getArgOperand(1); 3681 3682 if (auto *CSrc0 = dyn_cast<Constant>(Src0)) { 3683 if (auto *CSrc1 = dyn_cast<Constant>(Src1)) { 3684 Constant *CCmp = ConstantExpr::getCompare(CCVal, CSrc0, CSrc1); 3685 if (CCmp->isNullValue()) { 3686 return replaceInstUsesWith( 3687 *II, ConstantExpr::getSExt(CCmp, II->getType())); 3688 } 3689 3690 // The result of V_ICMP/V_FCMP assembly instructions (which this 3691 // intrinsic exposes) is one bit per thread, masked with the EXEC 3692 // register (which contains the bitmask of live threads). So a 3693 // comparison that always returns true is the same as a read of the 3694 // EXEC register. 3695 Value *NewF = Intrinsic::getDeclaration( 3696 II->getModule(), Intrinsic::read_register, II->getType()); 3697 Metadata *MDArgs[] = {MDString::get(II->getContext(), "exec")}; 3698 MDNode *MD = MDNode::get(II->getContext(), MDArgs); 3699 Value *Args[] = {MetadataAsValue::get(II->getContext(), MD)}; 3700 CallInst *NewCall = Builder.CreateCall(NewF, Args); 3701 NewCall->addAttribute(AttributeList::FunctionIndex, 3702 Attribute::Convergent); 3703 NewCall->takeName(II); 3704 return replaceInstUsesWith(*II, NewCall); 3705 } 3706 3707 // Canonicalize constants to RHS. 3708 CmpInst::Predicate SwapPred 3709 = CmpInst::getSwappedPredicate(static_cast<CmpInst::Predicate>(CCVal)); 3710 II->setArgOperand(0, Src1); 3711 II->setArgOperand(1, Src0); 3712 II->setArgOperand(2, ConstantInt::get(CC->getType(), 3713 static_cast<int>(SwapPred))); 3714 return II; 3715 } 3716 3717 if (CCVal != CmpInst::ICMP_EQ && CCVal != CmpInst::ICMP_NE) 3718 break; 3719 3720 // Canonicalize compare eq with true value to compare != 0 3721 // llvm.amdgcn.icmp(zext (i1 x), 1, eq) 3722 // -> llvm.amdgcn.icmp(zext (i1 x), 0, ne) 3723 // llvm.amdgcn.icmp(sext (i1 x), -1, eq) 3724 // -> llvm.amdgcn.icmp(sext (i1 x), 0, ne) 3725 Value *ExtSrc; 3726 if (CCVal == CmpInst::ICMP_EQ && 3727 ((match(Src1, m_One()) && match(Src0, m_ZExt(m_Value(ExtSrc)))) || 3728 (match(Src1, m_AllOnes()) && match(Src0, m_SExt(m_Value(ExtSrc))))) && 3729 ExtSrc->getType()->isIntegerTy(1)) { 3730 II->setArgOperand(1, ConstantInt::getNullValue(Src1->getType())); 3731 II->setArgOperand(2, ConstantInt::get(CC->getType(), CmpInst::ICMP_NE)); 3732 return II; 3733 } 3734 3735 CmpInst::Predicate SrcPred; 3736 Value *SrcLHS; 3737 Value *SrcRHS; 3738 3739 // Fold compare eq/ne with 0 from a compare result as the predicate to the 3740 // intrinsic. The typical use is a wave vote function in the library, which 3741 // will be fed from a user code condition compared with 0. Fold in the 3742 // redundant compare. 3743 3744 // llvm.amdgcn.icmp([sz]ext ([if]cmp pred a, b), 0, ne) 3745 // -> llvm.amdgcn.[if]cmp(a, b, pred) 3746 // 3747 // llvm.amdgcn.icmp([sz]ext ([if]cmp pred a, b), 0, eq) 3748 // -> llvm.amdgcn.[if]cmp(a, b, inv pred) 3749 if (match(Src1, m_Zero()) && 3750 match(Src0, 3751 m_ZExtOrSExt(m_Cmp(SrcPred, m_Value(SrcLHS), m_Value(SrcRHS))))) { 3752 if (CCVal == CmpInst::ICMP_EQ) 3753 SrcPred = CmpInst::getInversePredicate(SrcPred); 3754 3755 Intrinsic::ID NewIID = CmpInst::isFPPredicate(SrcPred) ? 3756 Intrinsic::amdgcn_fcmp : Intrinsic::amdgcn_icmp; 3757 3758 Type *Ty = SrcLHS->getType(); 3759 if (auto *CmpType = dyn_cast<IntegerType>(Ty)) { 3760 // Promote to next legal integer type. 3761 unsigned Width = CmpType->getBitWidth(); 3762 unsigned NewWidth = Width; 3763 if (Width <= 16) 3764 NewWidth = 16; 3765 else if (Width <= 32) 3766 NewWidth = 32; 3767 else if (Width <= 64) 3768 NewWidth = 64; 3769 else if (Width > 64) 3770 break; // Can't handle this. 3771 3772 if (Width != NewWidth) { 3773 IntegerType *CmpTy = Builder.getIntNTy(NewWidth); 3774 if (CmpInst::isSigned(SrcPred)) { 3775 SrcLHS = Builder.CreateSExt(SrcLHS, CmpTy); 3776 SrcRHS = Builder.CreateSExt(SrcRHS, CmpTy); 3777 } else { 3778 SrcLHS = Builder.CreateZExt(SrcLHS, CmpTy); 3779 SrcRHS = Builder.CreateZExt(SrcRHS, CmpTy); 3780 } 3781 } 3782 } else if (!Ty->isFloatTy() && !Ty->isDoubleTy() && !Ty->isHalfTy()) 3783 break; 3784 3785 Value *NewF = Intrinsic::getDeclaration(II->getModule(), NewIID, 3786 SrcLHS->getType()); 3787 Value *Args[] = { SrcLHS, SrcRHS, 3788 ConstantInt::get(CC->getType(), SrcPred) }; 3789 CallInst *NewCall = Builder.CreateCall(NewF, Args); 3790 NewCall->takeName(II); 3791 return replaceInstUsesWith(*II, NewCall); 3792 } 3793 3794 break; 3795 } 3796 case Intrinsic::amdgcn_wqm_vote: { 3797 // wqm_vote is identity when the argument is constant. 3798 if (!isa<Constant>(II->getArgOperand(0))) 3799 break; 3800 3801 return replaceInstUsesWith(*II, II->getArgOperand(0)); 3802 } 3803 case Intrinsic::amdgcn_kill: { 3804 const ConstantInt *C = dyn_cast<ConstantInt>(II->getArgOperand(0)); 3805 if (!C || !C->getZExtValue()) 3806 break; 3807 3808 // amdgcn.kill(i1 1) is a no-op 3809 return eraseInstFromFunction(CI); 3810 } 3811 case Intrinsic::amdgcn_update_dpp: { 3812 Value *Old = II->getArgOperand(0); 3813 3814 auto BC = dyn_cast<ConstantInt>(II->getArgOperand(5)); 3815 auto RM = dyn_cast<ConstantInt>(II->getArgOperand(3)); 3816 auto BM = dyn_cast<ConstantInt>(II->getArgOperand(4)); 3817 if (!BC || !RM || !BM || 3818 BC->isZeroValue() || 3819 RM->getZExtValue() != 0xF || 3820 BM->getZExtValue() != 0xF || 3821 isa<UndefValue>(Old)) 3822 break; 3823 3824 // If bound_ctrl = 1, row mask = bank mask = 0xf we can omit old value. 3825 II->setOperand(0, UndefValue::get(Old->getType())); 3826 return II; 3827 } 3828 case Intrinsic::stackrestore: { 3829 // If the save is right next to the restore, remove the restore. This can 3830 // happen when variable allocas are DCE'd. 3831 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) { 3832 if (SS->getIntrinsicID() == Intrinsic::stacksave) { 3833 // Skip over debug info. 3834 if (SS->getNextNonDebugInstruction() == II) { 3835 return eraseInstFromFunction(CI); 3836 } 3837 } 3838 } 3839 3840 // Scan down this block to see if there is another stack restore in the 3841 // same block without an intervening call/alloca. 3842 BasicBlock::iterator BI(II); 3843 Instruction *TI = II->getParent()->getTerminator(); 3844 bool CannotRemove = false; 3845 for (++BI; &*BI != TI; ++BI) { 3846 if (isa<AllocaInst>(BI)) { 3847 CannotRemove = true; 3848 break; 3849 } 3850 if (CallInst *BCI = dyn_cast<CallInst>(BI)) { 3851 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) { 3852 // If there is a stackrestore below this one, remove this one. 3853 if (II->getIntrinsicID() == Intrinsic::stackrestore) 3854 return eraseInstFromFunction(CI); 3855 3856 // Bail if we cross over an intrinsic with side effects, such as 3857 // llvm.stacksave, llvm.read_register, or llvm.setjmp. 3858 if (II->mayHaveSideEffects()) { 3859 CannotRemove = true; 3860 break; 3861 } 3862 } else { 3863 // If we found a non-intrinsic call, we can't remove the stack 3864 // restore. 3865 CannotRemove = true; 3866 break; 3867 } 3868 } 3869 } 3870 3871 // If the stack restore is in a return, resume, or unwind block and if there 3872 // are no allocas or calls between the restore and the return, nuke the 3873 // restore. 3874 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI))) 3875 return eraseInstFromFunction(CI); 3876 break; 3877 } 3878 case Intrinsic::lifetime_start: 3879 // Asan needs to poison memory to detect invalid access which is possible 3880 // even for empty lifetime range. 3881 if (II->getFunction()->hasFnAttribute(Attribute::SanitizeAddress) || 3882 II->getFunction()->hasFnAttribute(Attribute::SanitizeHWAddress)) 3883 break; 3884 3885 if (removeTriviallyEmptyRange(*II, Intrinsic::lifetime_start, 3886 Intrinsic::lifetime_end, *this)) 3887 return nullptr; 3888 break; 3889 case Intrinsic::assume: { 3890 Value *IIOperand = II->getArgOperand(0); 3891 // Remove an assume if it is followed by an identical assume. 3892 // TODO: Do we need this? Unless there are conflicting assumptions, the 3893 // computeKnownBits(IIOperand) below here eliminates redundant assumes. 3894 Instruction *Next = II->getNextNonDebugInstruction(); 3895 if (match(Next, m_Intrinsic<Intrinsic::assume>(m_Specific(IIOperand)))) 3896 return eraseInstFromFunction(CI); 3897 3898 // Canonicalize assume(a && b) -> assume(a); assume(b); 3899 // Note: New assumption intrinsics created here are registered by 3900 // the InstCombineIRInserter object. 3901 Value *AssumeIntrinsic = II->getCalledValue(), *A, *B; 3902 if (match(IIOperand, m_And(m_Value(A), m_Value(B)))) { 3903 Builder.CreateCall(AssumeIntrinsic, A, II->getName()); 3904 Builder.CreateCall(AssumeIntrinsic, B, II->getName()); 3905 return eraseInstFromFunction(*II); 3906 } 3907 // assume(!(a || b)) -> assume(!a); assume(!b); 3908 if (match(IIOperand, m_Not(m_Or(m_Value(A), m_Value(B))))) { 3909 Builder.CreateCall(AssumeIntrinsic, Builder.CreateNot(A), II->getName()); 3910 Builder.CreateCall(AssumeIntrinsic, Builder.CreateNot(B), II->getName()); 3911 return eraseInstFromFunction(*II); 3912 } 3913 3914 // assume( (load addr) != null ) -> add 'nonnull' metadata to load 3915 // (if assume is valid at the load) 3916 CmpInst::Predicate Pred; 3917 Instruction *LHS; 3918 if (match(IIOperand, m_ICmp(Pred, m_Instruction(LHS), m_Zero())) && 3919 Pred == ICmpInst::ICMP_NE && LHS->getOpcode() == Instruction::Load && 3920 LHS->getType()->isPointerTy() && 3921 isValidAssumeForContext(II, LHS, &DT)) { 3922 MDNode *MD = MDNode::get(II->getContext(), None); 3923 LHS->setMetadata(LLVMContext::MD_nonnull, MD); 3924 return eraseInstFromFunction(*II); 3925 3926 // TODO: apply nonnull return attributes to calls and invokes 3927 // TODO: apply range metadata for range check patterns? 3928 } 3929 3930 // If there is a dominating assume with the same condition as this one, 3931 // then this one is redundant, and should be removed. 3932 KnownBits Known(1); 3933 computeKnownBits(IIOperand, Known, 0, II); 3934 if (Known.isAllOnes()) 3935 return eraseInstFromFunction(*II); 3936 3937 // Update the cache of affected values for this assumption (we might be 3938 // here because we just simplified the condition). 3939 AC.updateAffectedValues(II); 3940 break; 3941 } 3942 case Intrinsic::experimental_gc_relocate: { 3943 // Translate facts known about a pointer before relocating into 3944 // facts about the relocate value, while being careful to 3945 // preserve relocation semantics. 3946 Value *DerivedPtr = cast<GCRelocateInst>(II)->getDerivedPtr(); 3947 3948 // Remove the relocation if unused, note that this check is required 3949 // to prevent the cases below from looping forever. 3950 if (II->use_empty()) 3951 return eraseInstFromFunction(*II); 3952 3953 // Undef is undef, even after relocation. 3954 // TODO: provide a hook for this in GCStrategy. This is clearly legal for 3955 // most practical collectors, but there was discussion in the review thread 3956 // about whether it was legal for all possible collectors. 3957 if (isa<UndefValue>(DerivedPtr)) 3958 // Use undef of gc_relocate's type to replace it. 3959 return replaceInstUsesWith(*II, UndefValue::get(II->getType())); 3960 3961 if (auto *PT = dyn_cast<PointerType>(II->getType())) { 3962 // The relocation of null will be null for most any collector. 3963 // TODO: provide a hook for this in GCStrategy. There might be some 3964 // weird collector this property does not hold for. 3965 if (isa<ConstantPointerNull>(DerivedPtr)) 3966 // Use null-pointer of gc_relocate's type to replace it. 3967 return replaceInstUsesWith(*II, ConstantPointerNull::get(PT)); 3968 3969 // isKnownNonNull -> nonnull attribute 3970 if (!II->hasRetAttr(Attribute::NonNull) && 3971 isKnownNonZero(DerivedPtr, DL, 0, &AC, II, &DT)) { 3972 II->addAttribute(AttributeList::ReturnIndex, Attribute::NonNull); 3973 return II; 3974 } 3975 } 3976 3977 // TODO: bitcast(relocate(p)) -> relocate(bitcast(p)) 3978 // Canonicalize on the type from the uses to the defs 3979 3980 // TODO: relocate((gep p, C, C2, ...)) -> gep(relocate(p), C, C2, ...) 3981 break; 3982 } 3983 3984 case Intrinsic::experimental_guard: { 3985 // Is this guard followed by another guard? We scan forward over a small 3986 // fixed window of instructions to handle common cases with conditions 3987 // computed between guards. 3988 Instruction *NextInst = II->getNextNode(); 3989 for (unsigned i = 0; i < GuardWideningWindow; i++) { 3990 // Note: Using context-free form to avoid compile time blow up 3991 if (!isSafeToSpeculativelyExecute(NextInst)) 3992 break; 3993 NextInst = NextInst->getNextNode(); 3994 } 3995 Value *NextCond = nullptr; 3996 if (match(NextInst, 3997 m_Intrinsic<Intrinsic::experimental_guard>(m_Value(NextCond)))) { 3998 Value *CurrCond = II->getArgOperand(0); 3999 4000 // Remove a guard that it is immediately preceded by an identical guard. 4001 if (CurrCond == NextCond) 4002 return eraseInstFromFunction(*NextInst); 4003 4004 // Otherwise canonicalize guard(a); guard(b) -> guard(a & b). 4005 Instruction* MoveI = II->getNextNode(); 4006 while (MoveI != NextInst) { 4007 auto *Temp = MoveI; 4008 MoveI = MoveI->getNextNode(); 4009 Temp->moveBefore(II); 4010 } 4011 II->setArgOperand(0, Builder.CreateAnd(CurrCond, NextCond)); 4012 return eraseInstFromFunction(*NextInst); 4013 } 4014 break; 4015 } 4016 } 4017 return visitCallSite(II); 4018 } 4019 4020 // Fence instruction simplification 4021 Instruction *InstCombiner::visitFenceInst(FenceInst &FI) { 4022 // Remove identical consecutive fences. 4023 Instruction *Next = FI.getNextNonDebugInstruction(); 4024 if (auto *NFI = dyn_cast<FenceInst>(Next)) 4025 if (FI.isIdenticalTo(NFI)) 4026 return eraseInstFromFunction(FI); 4027 return nullptr; 4028 } 4029 4030 // InvokeInst simplification 4031 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) { 4032 return visitCallSite(&II); 4033 } 4034 4035 /// If this cast does not affect the value passed through the varargs area, we 4036 /// can eliminate the use of the cast. 4037 static bool isSafeToEliminateVarargsCast(const CallSite CS, 4038 const DataLayout &DL, 4039 const CastInst *const CI, 4040 const int ix) { 4041 if (!CI->isLosslessCast()) 4042 return false; 4043 4044 // If this is a GC intrinsic, avoid munging types. We need types for 4045 // statepoint reconstruction in SelectionDAG. 4046 // TODO: This is probably something which should be expanded to all 4047 // intrinsics since the entire point of intrinsics is that 4048 // they are understandable by the optimizer. 4049 if (isStatepoint(CS) || isGCRelocate(CS) || isGCResult(CS)) 4050 return false; 4051 4052 // The size of ByVal or InAlloca arguments is derived from the type, so we 4053 // can't change to a type with a different size. If the size were 4054 // passed explicitly we could avoid this check. 4055 if (!CS.isByValOrInAllocaArgument(ix)) 4056 return true; 4057 4058 Type* SrcTy = 4059 cast<PointerType>(CI->getOperand(0)->getType())->getElementType(); 4060 Type* DstTy = cast<PointerType>(CI->getType())->getElementType(); 4061 if (!SrcTy->isSized() || !DstTy->isSized()) 4062 return false; 4063 if (DL.getTypeAllocSize(SrcTy) != DL.getTypeAllocSize(DstTy)) 4064 return false; 4065 return true; 4066 } 4067 4068 Instruction *InstCombiner::tryOptimizeCall(CallInst *CI) { 4069 if (!CI->getCalledFunction()) return nullptr; 4070 4071 auto InstCombineRAUW = [this](Instruction *From, Value *With) { 4072 replaceInstUsesWith(*From, With); 4073 }; 4074 auto InstCombineErase = [this](Instruction *I) { 4075 eraseInstFromFunction(*I); 4076 }; 4077 LibCallSimplifier Simplifier(DL, &TLI, ORE, InstCombineRAUW, 4078 InstCombineErase); 4079 if (Value *With = Simplifier.optimizeCall(CI)) { 4080 ++NumSimplified; 4081 return CI->use_empty() ? CI : replaceInstUsesWith(*CI, With); 4082 } 4083 4084 return nullptr; 4085 } 4086 4087 static IntrinsicInst *findInitTrampolineFromAlloca(Value *TrampMem) { 4088 // Strip off at most one level of pointer casts, looking for an alloca. This 4089 // is good enough in practice and simpler than handling any number of casts. 4090 Value *Underlying = TrampMem->stripPointerCasts(); 4091 if (Underlying != TrampMem && 4092 (!Underlying->hasOneUse() || Underlying->user_back() != TrampMem)) 4093 return nullptr; 4094 if (!isa<AllocaInst>(Underlying)) 4095 return nullptr; 4096 4097 IntrinsicInst *InitTrampoline = nullptr; 4098 for (User *U : TrampMem->users()) { 4099 IntrinsicInst *II = dyn_cast<IntrinsicInst>(U); 4100 if (!II) 4101 return nullptr; 4102 if (II->getIntrinsicID() == Intrinsic::init_trampoline) { 4103 if (InitTrampoline) 4104 // More than one init_trampoline writes to this value. Give up. 4105 return nullptr; 4106 InitTrampoline = II; 4107 continue; 4108 } 4109 if (II->getIntrinsicID() == Intrinsic::adjust_trampoline) 4110 // Allow any number of calls to adjust.trampoline. 4111 continue; 4112 return nullptr; 4113 } 4114 4115 // No call to init.trampoline found. 4116 if (!InitTrampoline) 4117 return nullptr; 4118 4119 // Check that the alloca is being used in the expected way. 4120 if (InitTrampoline->getOperand(0) != TrampMem) 4121 return nullptr; 4122 4123 return InitTrampoline; 4124 } 4125 4126 static IntrinsicInst *findInitTrampolineFromBB(IntrinsicInst *AdjustTramp, 4127 Value *TrampMem) { 4128 // Visit all the previous instructions in the basic block, and try to find a 4129 // init.trampoline which has a direct path to the adjust.trampoline. 4130 for (BasicBlock::iterator I = AdjustTramp->getIterator(), 4131 E = AdjustTramp->getParent()->begin(); 4132 I != E;) { 4133 Instruction *Inst = &*--I; 4134 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) 4135 if (II->getIntrinsicID() == Intrinsic::init_trampoline && 4136 II->getOperand(0) == TrampMem) 4137 return II; 4138 if (Inst->mayWriteToMemory()) 4139 return nullptr; 4140 } 4141 return nullptr; 4142 } 4143 4144 // Given a call to llvm.adjust.trampoline, find and return the corresponding 4145 // call to llvm.init.trampoline if the call to the trampoline can be optimized 4146 // to a direct call to a function. Otherwise return NULL. 4147 static IntrinsicInst *findInitTrampoline(Value *Callee) { 4148 Callee = Callee->stripPointerCasts(); 4149 IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee); 4150 if (!AdjustTramp || 4151 AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline) 4152 return nullptr; 4153 4154 Value *TrampMem = AdjustTramp->getOperand(0); 4155 4156 if (IntrinsicInst *IT = findInitTrampolineFromAlloca(TrampMem)) 4157 return IT; 4158 if (IntrinsicInst *IT = findInitTrampolineFromBB(AdjustTramp, TrampMem)) 4159 return IT; 4160 return nullptr; 4161 } 4162 4163 /// Improvements for call and invoke instructions. 4164 Instruction *InstCombiner::visitCallSite(CallSite CS) { 4165 if (isAllocLikeFn(CS.getInstruction(), &TLI)) 4166 return visitAllocSite(*CS.getInstruction()); 4167 4168 bool Changed = false; 4169 4170 // Mark any parameters that are known to be non-null with the nonnull 4171 // attribute. This is helpful for inlining calls to functions with null 4172 // checks on their arguments. 4173 SmallVector<unsigned, 4> ArgNos; 4174 unsigned ArgNo = 0; 4175 4176 for (Value *V : CS.args()) { 4177 if (V->getType()->isPointerTy() && 4178 !CS.paramHasAttr(ArgNo, Attribute::NonNull) && 4179 isKnownNonZero(V, DL, 0, &AC, CS.getInstruction(), &DT)) 4180 ArgNos.push_back(ArgNo); 4181 ArgNo++; 4182 } 4183 4184 assert(ArgNo == CS.arg_size() && "sanity check"); 4185 4186 if (!ArgNos.empty()) { 4187 AttributeList AS = CS.getAttributes(); 4188 LLVMContext &Ctx = CS.getInstruction()->getContext(); 4189 AS = AS.addParamAttribute(Ctx, ArgNos, 4190 Attribute::get(Ctx, Attribute::NonNull)); 4191 CS.setAttributes(AS); 4192 Changed = true; 4193 } 4194 4195 // If the callee is a pointer to a function, attempt to move any casts to the 4196 // arguments of the call/invoke. 4197 Value *Callee = CS.getCalledValue(); 4198 if (!isa<Function>(Callee) && transformConstExprCastCall(CS)) 4199 return nullptr; 4200 4201 if (Function *CalleeF = dyn_cast<Function>(Callee)) { 4202 // Remove the convergent attr on calls when the callee is not convergent. 4203 if (CS.isConvergent() && !CalleeF->isConvergent() && 4204 !CalleeF->isIntrinsic()) { 4205 LLVM_DEBUG(dbgs() << "Removing convergent attr from instr " 4206 << CS.getInstruction() << "\n"); 4207 CS.setNotConvergent(); 4208 return CS.getInstruction(); 4209 } 4210 4211 // If the call and callee calling conventions don't match, this call must 4212 // be unreachable, as the call is undefined. 4213 if (CalleeF->getCallingConv() != CS.getCallingConv() && 4214 // Only do this for calls to a function with a body. A prototype may 4215 // not actually end up matching the implementation's calling conv for a 4216 // variety of reasons (e.g. it may be written in assembly). 4217 !CalleeF->isDeclaration()) { 4218 Instruction *OldCall = CS.getInstruction(); 4219 new StoreInst(ConstantInt::getTrue(Callee->getContext()), 4220 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())), 4221 OldCall); 4222 // If OldCall does not return void then replaceAllUsesWith undef. 4223 // This allows ValueHandlers and custom metadata to adjust itself. 4224 if (!OldCall->getType()->isVoidTy()) 4225 replaceInstUsesWith(*OldCall, UndefValue::get(OldCall->getType())); 4226 if (isa<CallInst>(OldCall)) 4227 return eraseInstFromFunction(*OldCall); 4228 4229 // We cannot remove an invoke, because it would change the CFG, just 4230 // change the callee to a null pointer. 4231 cast<InvokeInst>(OldCall)->setCalledFunction( 4232 Constant::getNullValue(CalleeF->getType())); 4233 return nullptr; 4234 } 4235 } 4236 4237 if ((isa<ConstantPointerNull>(Callee) && 4238 !NullPointerIsDefined(CS.getInstruction()->getFunction())) || 4239 isa<UndefValue>(Callee)) { 4240 // If CS does not return void then replaceAllUsesWith undef. 4241 // This allows ValueHandlers and custom metadata to adjust itself. 4242 if (!CS.getInstruction()->getType()->isVoidTy()) 4243 replaceInstUsesWith(*CS.getInstruction(), 4244 UndefValue::get(CS.getInstruction()->getType())); 4245 4246 if (isa<InvokeInst>(CS.getInstruction())) { 4247 // Can't remove an invoke because we cannot change the CFG. 4248 return nullptr; 4249 } 4250 4251 // This instruction is not reachable, just remove it. We insert a store to 4252 // undef so that we know that this code is not reachable, despite the fact 4253 // that we can't modify the CFG here. 4254 new StoreInst(ConstantInt::getTrue(Callee->getContext()), 4255 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())), 4256 CS.getInstruction()); 4257 4258 return eraseInstFromFunction(*CS.getInstruction()); 4259 } 4260 4261 if (IntrinsicInst *II = findInitTrampoline(Callee)) 4262 return transformCallThroughTrampoline(CS, II); 4263 4264 PointerType *PTy = cast<PointerType>(Callee->getType()); 4265 FunctionType *FTy = cast<FunctionType>(PTy->getElementType()); 4266 if (FTy->isVarArg()) { 4267 int ix = FTy->getNumParams(); 4268 // See if we can optimize any arguments passed through the varargs area of 4269 // the call. 4270 for (CallSite::arg_iterator I = CS.arg_begin() + FTy->getNumParams(), 4271 E = CS.arg_end(); I != E; ++I, ++ix) { 4272 CastInst *CI = dyn_cast<CastInst>(*I); 4273 if (CI && isSafeToEliminateVarargsCast(CS, DL, CI, ix)) { 4274 *I = CI->getOperand(0); 4275 Changed = true; 4276 } 4277 } 4278 } 4279 4280 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) { 4281 // Inline asm calls cannot throw - mark them 'nounwind'. 4282 CS.setDoesNotThrow(); 4283 Changed = true; 4284 } 4285 4286 // Try to optimize the call if possible, we require DataLayout for most of 4287 // this. None of these calls are seen as possibly dead so go ahead and 4288 // delete the instruction now. 4289 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) { 4290 Instruction *I = tryOptimizeCall(CI); 4291 // If we changed something return the result, etc. Otherwise let 4292 // the fallthrough check. 4293 if (I) return eraseInstFromFunction(*I); 4294 } 4295 4296 return Changed ? CS.getInstruction() : nullptr; 4297 } 4298 4299 /// If the callee is a constexpr cast of a function, attempt to move the cast to 4300 /// the arguments of the call/invoke. 4301 bool InstCombiner::transformConstExprCastCall(CallSite CS) { 4302 auto *Callee = dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts()); 4303 if (!Callee) 4304 return false; 4305 4306 // If this is a call to a thunk function, don't remove the cast. Thunks are 4307 // used to transparently forward all incoming parameters and outgoing return 4308 // values, so it's important to leave the cast in place. 4309 if (Callee->hasFnAttribute("thunk")) 4310 return false; 4311 4312 // If this is a musttail call, the callee's prototype must match the caller's 4313 // prototype with the exception of pointee types. The code below doesn't 4314 // implement that, so we can't do this transform. 4315 // TODO: Do the transform if it only requires adding pointer casts. 4316 if (CS.isMustTailCall()) 4317 return false; 4318 4319 Instruction *Caller = CS.getInstruction(); 4320 const AttributeList &CallerPAL = CS.getAttributes(); 4321 4322 // Okay, this is a cast from a function to a different type. Unless doing so 4323 // would cause a type conversion of one of our arguments, change this call to 4324 // be a direct call with arguments casted to the appropriate types. 4325 FunctionType *FT = Callee->getFunctionType(); 4326 Type *OldRetTy = Caller->getType(); 4327 Type *NewRetTy = FT->getReturnType(); 4328 4329 // Check to see if we are changing the return type... 4330 if (OldRetTy != NewRetTy) { 4331 4332 if (NewRetTy->isStructTy()) 4333 return false; // TODO: Handle multiple return values. 4334 4335 if (!CastInst::isBitOrNoopPointerCastable(NewRetTy, OldRetTy, DL)) { 4336 if (Callee->isDeclaration()) 4337 return false; // Cannot transform this return value. 4338 4339 if (!Caller->use_empty() && 4340 // void -> non-void is handled specially 4341 !NewRetTy->isVoidTy()) 4342 return false; // Cannot transform this return value. 4343 } 4344 4345 if (!CallerPAL.isEmpty() && !Caller->use_empty()) { 4346 AttrBuilder RAttrs(CallerPAL, AttributeList::ReturnIndex); 4347 if (RAttrs.overlaps(AttributeFuncs::typeIncompatible(NewRetTy))) 4348 return false; // Attribute not compatible with transformed value. 4349 } 4350 4351 // If the callsite is an invoke instruction, and the return value is used by 4352 // a PHI node in a successor, we cannot change the return type of the call 4353 // because there is no place to put the cast instruction (without breaking 4354 // the critical edge). Bail out in this case. 4355 if (!Caller->use_empty()) 4356 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) 4357 for (User *U : II->users()) 4358 if (PHINode *PN = dyn_cast<PHINode>(U)) 4359 if (PN->getParent() == II->getNormalDest() || 4360 PN->getParent() == II->getUnwindDest()) 4361 return false; 4362 } 4363 4364 unsigned NumActualArgs = CS.arg_size(); 4365 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs); 4366 4367 // Prevent us turning: 4368 // declare void @takes_i32_inalloca(i32* inalloca) 4369 // call void bitcast (void (i32*)* @takes_i32_inalloca to void (i32)*)(i32 0) 4370 // 4371 // into: 4372 // call void @takes_i32_inalloca(i32* null) 4373 // 4374 // Similarly, avoid folding away bitcasts of byval calls. 4375 if (Callee->getAttributes().hasAttrSomewhere(Attribute::InAlloca) || 4376 Callee->getAttributes().hasAttrSomewhere(Attribute::ByVal)) 4377 return false; 4378 4379 CallSite::arg_iterator AI = CS.arg_begin(); 4380 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) { 4381 Type *ParamTy = FT->getParamType(i); 4382 Type *ActTy = (*AI)->getType(); 4383 4384 if (!CastInst::isBitOrNoopPointerCastable(ActTy, ParamTy, DL)) 4385 return false; // Cannot transform this parameter value. 4386 4387 if (AttrBuilder(CallerPAL.getParamAttributes(i)) 4388 .overlaps(AttributeFuncs::typeIncompatible(ParamTy))) 4389 return false; // Attribute not compatible with transformed value. 4390 4391 if (CS.isInAllocaArgument(i)) 4392 return false; // Cannot transform to and from inalloca. 4393 4394 // If the parameter is passed as a byval argument, then we have to have a 4395 // sized type and the sized type has to have the same size as the old type. 4396 if (ParamTy != ActTy && CallerPAL.hasParamAttribute(i, Attribute::ByVal)) { 4397 PointerType *ParamPTy = dyn_cast<PointerType>(ParamTy); 4398 if (!ParamPTy || !ParamPTy->getElementType()->isSized()) 4399 return false; 4400 4401 Type *CurElTy = ActTy->getPointerElementType(); 4402 if (DL.getTypeAllocSize(CurElTy) != 4403 DL.getTypeAllocSize(ParamPTy->getElementType())) 4404 return false; 4405 } 4406 } 4407 4408 if (Callee->isDeclaration()) { 4409 // Do not delete arguments unless we have a function body. 4410 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg()) 4411 return false; 4412 4413 // If the callee is just a declaration, don't change the varargsness of the 4414 // call. We don't want to introduce a varargs call where one doesn't 4415 // already exist. 4416 PointerType *APTy = cast<PointerType>(CS.getCalledValue()->getType()); 4417 if (FT->isVarArg()!=cast<FunctionType>(APTy->getElementType())->isVarArg()) 4418 return false; 4419 4420 // If both the callee and the cast type are varargs, we still have to make 4421 // sure the number of fixed parameters are the same or we have the same 4422 // ABI issues as if we introduce a varargs call. 4423 if (FT->isVarArg() && 4424 cast<FunctionType>(APTy->getElementType())->isVarArg() && 4425 FT->getNumParams() != 4426 cast<FunctionType>(APTy->getElementType())->getNumParams()) 4427 return false; 4428 } 4429 4430 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() && 4431 !CallerPAL.isEmpty()) { 4432 // In this case we have more arguments than the new function type, but we 4433 // won't be dropping them. Check that these extra arguments have attributes 4434 // that are compatible with being a vararg call argument. 4435 unsigned SRetIdx; 4436 if (CallerPAL.hasAttrSomewhere(Attribute::StructRet, &SRetIdx) && 4437 SRetIdx > FT->getNumParams()) 4438 return false; 4439 } 4440 4441 // Okay, we decided that this is a safe thing to do: go ahead and start 4442 // inserting cast instructions as necessary. 4443 SmallVector<Value *, 8> Args; 4444 SmallVector<AttributeSet, 8> ArgAttrs; 4445 Args.reserve(NumActualArgs); 4446 ArgAttrs.reserve(NumActualArgs); 4447 4448 // Get any return attributes. 4449 AttrBuilder RAttrs(CallerPAL, AttributeList::ReturnIndex); 4450 4451 // If the return value is not being used, the type may not be compatible 4452 // with the existing attributes. Wipe out any problematic attributes. 4453 RAttrs.remove(AttributeFuncs::typeIncompatible(NewRetTy)); 4454 4455 AI = CS.arg_begin(); 4456 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) { 4457 Type *ParamTy = FT->getParamType(i); 4458 4459 Value *NewArg = *AI; 4460 if ((*AI)->getType() != ParamTy) 4461 NewArg = Builder.CreateBitOrPointerCast(*AI, ParamTy); 4462 Args.push_back(NewArg); 4463 4464 // Add any parameter attributes. 4465 ArgAttrs.push_back(CallerPAL.getParamAttributes(i)); 4466 } 4467 4468 // If the function takes more arguments than the call was taking, add them 4469 // now. 4470 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i) { 4471 Args.push_back(Constant::getNullValue(FT->getParamType(i))); 4472 ArgAttrs.push_back(AttributeSet()); 4473 } 4474 4475 // If we are removing arguments to the function, emit an obnoxious warning. 4476 if (FT->getNumParams() < NumActualArgs) { 4477 // TODO: if (!FT->isVarArg()) this call may be unreachable. PR14722 4478 if (FT->isVarArg()) { 4479 // Add all of the arguments in their promoted form to the arg list. 4480 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) { 4481 Type *PTy = getPromotedType((*AI)->getType()); 4482 Value *NewArg = *AI; 4483 if (PTy != (*AI)->getType()) { 4484 // Must promote to pass through va_arg area! 4485 Instruction::CastOps opcode = 4486 CastInst::getCastOpcode(*AI, false, PTy, false); 4487 NewArg = Builder.CreateCast(opcode, *AI, PTy); 4488 } 4489 Args.push_back(NewArg); 4490 4491 // Add any parameter attributes. 4492 ArgAttrs.push_back(CallerPAL.getParamAttributes(i)); 4493 } 4494 } 4495 } 4496 4497 AttributeSet FnAttrs = CallerPAL.getFnAttributes(); 4498 4499 if (NewRetTy->isVoidTy()) 4500 Caller->setName(""); // Void type should not have a name. 4501 4502 assert((ArgAttrs.size() == FT->getNumParams() || FT->isVarArg()) && 4503 "missing argument attributes"); 4504 LLVMContext &Ctx = Callee->getContext(); 4505 AttributeList NewCallerPAL = AttributeList::get( 4506 Ctx, FnAttrs, AttributeSet::get(Ctx, RAttrs), ArgAttrs); 4507 4508 SmallVector<OperandBundleDef, 1> OpBundles; 4509 CS.getOperandBundlesAsDefs(OpBundles); 4510 4511 CallSite NewCS; 4512 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) { 4513 NewCS = Builder.CreateInvoke(Callee, II->getNormalDest(), 4514 II->getUnwindDest(), Args, OpBundles); 4515 } else { 4516 NewCS = Builder.CreateCall(Callee, Args, OpBundles); 4517 cast<CallInst>(NewCS.getInstruction()) 4518 ->setTailCallKind(cast<CallInst>(Caller)->getTailCallKind()); 4519 } 4520 NewCS->takeName(Caller); 4521 NewCS.setCallingConv(CS.getCallingConv()); 4522 NewCS.setAttributes(NewCallerPAL); 4523 4524 // Preserve the weight metadata for the new call instruction. The metadata 4525 // is used by SamplePGO to check callsite's hotness. 4526 uint64_t W; 4527 if (Caller->extractProfTotalWeight(W)) 4528 NewCS->setProfWeight(W); 4529 4530 // Insert a cast of the return type as necessary. 4531 Instruction *NC = NewCS.getInstruction(); 4532 Value *NV = NC; 4533 if (OldRetTy != NV->getType() && !Caller->use_empty()) { 4534 if (!NV->getType()->isVoidTy()) { 4535 NV = NC = CastInst::CreateBitOrPointerCast(NC, OldRetTy); 4536 NC->setDebugLoc(Caller->getDebugLoc()); 4537 4538 // If this is an invoke instruction, we should insert it after the first 4539 // non-phi, instruction in the normal successor block. 4540 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) { 4541 BasicBlock::iterator I = II->getNormalDest()->getFirstInsertionPt(); 4542 InsertNewInstBefore(NC, *I); 4543 } else { 4544 // Otherwise, it's a call, just insert cast right after the call. 4545 InsertNewInstBefore(NC, *Caller); 4546 } 4547 Worklist.AddUsersToWorkList(*Caller); 4548 } else { 4549 NV = UndefValue::get(Caller->getType()); 4550 } 4551 } 4552 4553 if (!Caller->use_empty()) 4554 replaceInstUsesWith(*Caller, NV); 4555 else if (Caller->hasValueHandle()) { 4556 if (OldRetTy == NV->getType()) 4557 ValueHandleBase::ValueIsRAUWd(Caller, NV); 4558 else 4559 // We cannot call ValueIsRAUWd with a different type, and the 4560 // actual tracked value will disappear. 4561 ValueHandleBase::ValueIsDeleted(Caller); 4562 } 4563 4564 eraseInstFromFunction(*Caller); 4565 return true; 4566 } 4567 4568 /// Turn a call to a function created by init_trampoline / adjust_trampoline 4569 /// intrinsic pair into a direct call to the underlying function. 4570 Instruction * 4571 InstCombiner::transformCallThroughTrampoline(CallSite CS, 4572 IntrinsicInst *Tramp) { 4573 Value *Callee = CS.getCalledValue(); 4574 PointerType *PTy = cast<PointerType>(Callee->getType()); 4575 FunctionType *FTy = cast<FunctionType>(PTy->getElementType()); 4576 AttributeList Attrs = CS.getAttributes(); 4577 4578 // If the call already has the 'nest' attribute somewhere then give up - 4579 // otherwise 'nest' would occur twice after splicing in the chain. 4580 if (Attrs.hasAttrSomewhere(Attribute::Nest)) 4581 return nullptr; 4582 4583 assert(Tramp && 4584 "transformCallThroughTrampoline called with incorrect CallSite."); 4585 4586 Function *NestF =cast<Function>(Tramp->getArgOperand(1)->stripPointerCasts()); 4587 FunctionType *NestFTy = cast<FunctionType>(NestF->getValueType()); 4588 4589 AttributeList NestAttrs = NestF->getAttributes(); 4590 if (!NestAttrs.isEmpty()) { 4591 unsigned NestArgNo = 0; 4592 Type *NestTy = nullptr; 4593 AttributeSet NestAttr; 4594 4595 // Look for a parameter marked with the 'nest' attribute. 4596 for (FunctionType::param_iterator I = NestFTy->param_begin(), 4597 E = NestFTy->param_end(); 4598 I != E; ++NestArgNo, ++I) { 4599 AttributeSet AS = NestAttrs.getParamAttributes(NestArgNo); 4600 if (AS.hasAttribute(Attribute::Nest)) { 4601 // Record the parameter type and any other attributes. 4602 NestTy = *I; 4603 NestAttr = AS; 4604 break; 4605 } 4606 } 4607 4608 if (NestTy) { 4609 Instruction *Caller = CS.getInstruction(); 4610 std::vector<Value*> NewArgs; 4611 std::vector<AttributeSet> NewArgAttrs; 4612 NewArgs.reserve(CS.arg_size() + 1); 4613 NewArgAttrs.reserve(CS.arg_size()); 4614 4615 // Insert the nest argument into the call argument list, which may 4616 // mean appending it. Likewise for attributes. 4617 4618 { 4619 unsigned ArgNo = 0; 4620 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); 4621 do { 4622 if (ArgNo == NestArgNo) { 4623 // Add the chain argument and attributes. 4624 Value *NestVal = Tramp->getArgOperand(2); 4625 if (NestVal->getType() != NestTy) 4626 NestVal = Builder.CreateBitCast(NestVal, NestTy, "nest"); 4627 NewArgs.push_back(NestVal); 4628 NewArgAttrs.push_back(NestAttr); 4629 } 4630 4631 if (I == E) 4632 break; 4633 4634 // Add the original argument and attributes. 4635 NewArgs.push_back(*I); 4636 NewArgAttrs.push_back(Attrs.getParamAttributes(ArgNo)); 4637 4638 ++ArgNo; 4639 ++I; 4640 } while (true); 4641 } 4642 4643 // The trampoline may have been bitcast to a bogus type (FTy). 4644 // Handle this by synthesizing a new function type, equal to FTy 4645 // with the chain parameter inserted. 4646 4647 std::vector<Type*> NewTypes; 4648 NewTypes.reserve(FTy->getNumParams()+1); 4649 4650 // Insert the chain's type into the list of parameter types, which may 4651 // mean appending it. 4652 { 4653 unsigned ArgNo = 0; 4654 FunctionType::param_iterator I = FTy->param_begin(), 4655 E = FTy->param_end(); 4656 4657 do { 4658 if (ArgNo == NestArgNo) 4659 // Add the chain's type. 4660 NewTypes.push_back(NestTy); 4661 4662 if (I == E) 4663 break; 4664 4665 // Add the original type. 4666 NewTypes.push_back(*I); 4667 4668 ++ArgNo; 4669 ++I; 4670 } while (true); 4671 } 4672 4673 // Replace the trampoline call with a direct call. Let the generic 4674 // code sort out any function type mismatches. 4675 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes, 4676 FTy->isVarArg()); 4677 Constant *NewCallee = 4678 NestF->getType() == PointerType::getUnqual(NewFTy) ? 4679 NestF : ConstantExpr::getBitCast(NestF, 4680 PointerType::getUnqual(NewFTy)); 4681 AttributeList NewPAL = 4682 AttributeList::get(FTy->getContext(), Attrs.getFnAttributes(), 4683 Attrs.getRetAttributes(), NewArgAttrs); 4684 4685 SmallVector<OperandBundleDef, 1> OpBundles; 4686 CS.getOperandBundlesAsDefs(OpBundles); 4687 4688 Instruction *NewCaller; 4689 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) { 4690 NewCaller = InvokeInst::Create(NewCallee, 4691 II->getNormalDest(), II->getUnwindDest(), 4692 NewArgs, OpBundles); 4693 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv()); 4694 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL); 4695 } else { 4696 NewCaller = CallInst::Create(NewCallee, NewArgs, OpBundles); 4697 cast<CallInst>(NewCaller)->setTailCallKind( 4698 cast<CallInst>(Caller)->getTailCallKind()); 4699 cast<CallInst>(NewCaller)->setCallingConv( 4700 cast<CallInst>(Caller)->getCallingConv()); 4701 cast<CallInst>(NewCaller)->setAttributes(NewPAL); 4702 } 4703 NewCaller->setDebugLoc(Caller->getDebugLoc()); 4704 4705 return NewCaller; 4706 } 4707 } 4708 4709 // Replace the trampoline call with a direct call. Since there is no 'nest' 4710 // parameter, there is no need to adjust the argument list. Let the generic 4711 // code sort out any function type mismatches. 4712 Constant *NewCallee = 4713 NestF->getType() == PTy ? NestF : 4714 ConstantExpr::getBitCast(NestF, PTy); 4715 CS.setCalledFunction(NewCallee); 4716 return CS.getInstruction(); 4717 } 4718