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