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