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