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