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