1 //===- InstCombineCalls.cpp -----------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the visitCall and visitInvoke functions.
12 //===----------------------------------------------------------------------===//
14 #include "InstCombineInternal.h"
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/None.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/Twine.h"
23 #include "llvm/Analysis/InstructionSimplify.h"
24 #include "llvm/Analysis/MemoryBuiltins.h"
25 #include "llvm/Analysis/ValueTracking.h"
26 #include "llvm/IR/BasicBlock.h"
27 #include "llvm/IR/CallSite.h"
28 #include "llvm/IR/Constant.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/GlobalVariable.h"
33 #include "llvm/IR/InstrTypes.h"
34 #include "llvm/IR/Instruction.h"
35 #include "llvm/IR/Instructions.h"
36 #include "llvm/IR/IntrinsicInst.h"
37 #include "llvm/IR/Intrinsics.h"
38 #include "llvm/IR/LLVMContext.h"
39 #include "llvm/IR/Metadata.h"
40 #include "llvm/IR/PatternMatch.h"
41 #include "llvm/IR/Statepoint.h"
42 #include "llvm/IR/Type.h"
43 #include "llvm/IR/Value.h"
44 #include "llvm/IR/ValueHandle.h"
45 #include "llvm/Support/Casting.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/MathExtras.h"
48 #include "llvm/Transforms/Utils/Local.h"
49 #include "llvm/Transforms/Utils/SimplifyLibCalls.h"
57 using namespace PatternMatch;
59 #define DEBUG_TYPE "instcombine"
61 STATISTIC(NumSimplified, "Number of library calls simplified");
63 static cl::opt<unsigned> UnfoldElementAtomicMemcpyMaxElements(
64 "unfold-element-atomic-memcpy-max-elements",
66 cl::desc("Maximum number of elements in atomic memcpy the optimizer is "
67 "allowed to unfold"));
69 /// Return the specified type promoted as it would be to pass though a va_arg
71 static Type *getPromotedType(Type *Ty) {
72 if (IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
73 if (ITy->getBitWidth() < 32)
74 return Type::getInt32Ty(Ty->getContext());
79 /// Return a constant boolean vector that has true elements in all positions
80 /// where the input constant data vector has an element with the sign bit set.
81 static Constant *getNegativeIsTrueBoolVec(ConstantDataVector *V) {
82 SmallVector<Constant *, 32> BoolVec;
83 IntegerType *BoolTy = Type::getInt1Ty(V->getContext());
84 for (unsigned I = 0, E = V->getNumElements(); I != E; ++I) {
85 Constant *Elt = V->getElementAsConstant(I);
86 assert((isa<ConstantInt>(Elt) || isa<ConstantFP>(Elt)) &&
87 "Unexpected constant data vector element type");
88 bool Sign = V->getElementType()->isIntegerTy()
89 ? cast<ConstantInt>(Elt)->isNegative()
90 : cast<ConstantFP>(Elt)->isNegative();
91 BoolVec.push_back(ConstantInt::get(BoolTy, Sign));
93 return ConstantVector::get(BoolVec);
97 InstCombiner::SimplifyElementAtomicMemCpy(ElementAtomicMemCpyInst *AMI) {
98 // Try to unfold this intrinsic into sequence of explicit atomic loads and
100 // First check that number of elements is compile time constant.
101 auto *NumElementsCI = dyn_cast<ConstantInt>(AMI->getNumElements());
105 // Check that there are not too many elements.
106 uint64_t NumElements = NumElementsCI->getZExtValue();
107 if (NumElements >= UnfoldElementAtomicMemcpyMaxElements)
110 // Don't unfold into illegal integers
111 uint64_t ElementSizeInBytes = AMI->getElementSizeInBytes() * 8;
112 if (!getDataLayout().isLegalInteger(ElementSizeInBytes))
115 // Cast source and destination to the correct type. Intrinsic input arguments
116 // are usually represented as i8*.
117 // Often operands will be explicitly casted to i8* and we can just strip
118 // those casts instead of inserting new ones. However it's easier to rely on
119 // other InstCombine rules which will cover trivial cases anyway.
120 Value *Src = AMI->getRawSource();
121 Value *Dst = AMI->getRawDest();
122 Type *ElementPointerType = Type::getIntNPtrTy(
123 AMI->getContext(), ElementSizeInBytes, Src->getType()->getPointerAddressSpace());
125 Value *SrcCasted = Builder->CreatePointerCast(Src, ElementPointerType,
126 "memcpy_unfold.src_casted");
127 Value *DstCasted = Builder->CreatePointerCast(Dst, ElementPointerType,
128 "memcpy_unfold.dst_casted");
130 for (uint64_t i = 0; i < NumElements; ++i) {
131 // Get current element addresses
132 ConstantInt *ElementIdxCI =
133 ConstantInt::get(AMI->getContext(), APInt(64, i));
134 Value *SrcElementAddr =
135 Builder->CreateGEP(SrcCasted, ElementIdxCI, "memcpy_unfold.src_addr");
136 Value *DstElementAddr =
137 Builder->CreateGEP(DstCasted, ElementIdxCI, "memcpy_unfold.dst_addr");
139 // Load from the source. Transfer alignment information and mark load as
141 LoadInst *Load = Builder->CreateLoad(SrcElementAddr, "memcpy_unfold.val");
142 Load->setOrdering(AtomicOrdering::Unordered);
143 // We know alignment of the first element. It is also guaranteed by the
144 // verifier that element size is less or equal than first element alignment
145 // and both of this values are powers of two.
146 // This means that all subsequent accesses are at least element size
148 // TODO: We can infer better alignment but there is no evidence that this
150 Load->setAlignment(i == 0 ? AMI->getSrcAlignment()
151 : AMI->getElementSizeInBytes());
152 Load->setDebugLoc(AMI->getDebugLoc());
154 // Store loaded value via unordered atomic store.
155 StoreInst *Store = Builder->CreateStore(Load, DstElementAddr);
156 Store->setOrdering(AtomicOrdering::Unordered);
157 Store->setAlignment(i == 0 ? AMI->getDstAlignment()
158 : AMI->getElementSizeInBytes());
159 Store->setDebugLoc(AMI->getDebugLoc());
162 // Set the number of elements of the copy to 0, it will be deleted on the
164 AMI->setNumElements(Constant::getNullValue(NumElementsCI->getType()));
168 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
169 unsigned DstAlign = getKnownAlignment(MI->getArgOperand(0), DL, MI, &AC, &DT);
170 unsigned SrcAlign = getKnownAlignment(MI->getArgOperand(1), DL, MI, &AC, &DT);
171 unsigned MinAlign = std::min(DstAlign, SrcAlign);
172 unsigned CopyAlign = MI->getAlignment();
174 if (CopyAlign < MinAlign) {
175 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), MinAlign, false));
179 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
181 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getArgOperand(2));
182 if (!MemOpLength) return nullptr;
184 // Source and destination pointer types are always "i8*" for intrinsic. See
185 // if the size is something we can handle with a single primitive load/store.
186 // A single load+store correctly handles overlapping memory in the memmove
188 uint64_t Size = MemOpLength->getLimitedValue();
189 assert(Size && "0-sized memory transferring should be removed already.");
191 if (Size > 8 || (Size&(Size-1)))
192 return nullptr; // If not 1/2/4/8 bytes, exit.
194 // Use an integer load+store unless we can find something better.
196 cast<PointerType>(MI->getArgOperand(1)->getType())->getAddressSpace();
198 cast<PointerType>(MI->getArgOperand(0)->getType())->getAddressSpace();
200 IntegerType* IntType = IntegerType::get(MI->getContext(), Size<<3);
201 Type *NewSrcPtrTy = PointerType::get(IntType, SrcAddrSp);
202 Type *NewDstPtrTy = PointerType::get(IntType, DstAddrSp);
204 // If the memcpy has metadata describing the members, see if we can get the
205 // TBAA tag describing our copy.
206 MDNode *CopyMD = nullptr;
207 if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa_struct)) {
208 if (M->getNumOperands() == 3 && M->getOperand(0) &&
209 mdconst::hasa<ConstantInt>(M->getOperand(0)) &&
210 mdconst::extract<ConstantInt>(M->getOperand(0))->isNullValue() &&
212 mdconst::hasa<ConstantInt>(M->getOperand(1)) &&
213 mdconst::extract<ConstantInt>(M->getOperand(1))->getValue() ==
215 M->getOperand(2) && isa<MDNode>(M->getOperand(2)))
216 CopyMD = cast<MDNode>(M->getOperand(2));
219 // If the memcpy/memmove provides better alignment info than we can
221 SrcAlign = std::max(SrcAlign, CopyAlign);
222 DstAlign = std::max(DstAlign, CopyAlign);
224 Value *Src = Builder->CreateBitCast(MI->getArgOperand(1), NewSrcPtrTy);
225 Value *Dest = Builder->CreateBitCast(MI->getArgOperand(0), NewDstPtrTy);
226 LoadInst *L = Builder->CreateLoad(Src, MI->isVolatile());
227 L->setAlignment(SrcAlign);
229 L->setMetadata(LLVMContext::MD_tbaa, CopyMD);
230 MDNode *LoopMemParallelMD =
231 MI->getMetadata(LLVMContext::MD_mem_parallel_loop_access);
232 if (LoopMemParallelMD)
233 L->setMetadata(LLVMContext::MD_mem_parallel_loop_access, LoopMemParallelMD);
235 StoreInst *S = Builder->CreateStore(L, Dest, MI->isVolatile());
236 S->setAlignment(DstAlign);
238 S->setMetadata(LLVMContext::MD_tbaa, CopyMD);
239 if (LoopMemParallelMD)
240 S->setMetadata(LLVMContext::MD_mem_parallel_loop_access, LoopMemParallelMD);
242 // Set the size of the copy to 0, it will be deleted on the next iteration.
243 MI->setArgOperand(2, Constant::getNullValue(MemOpLength->getType()));
247 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
248 unsigned Alignment = getKnownAlignment(MI->getDest(), DL, MI, &AC, &DT);
249 if (MI->getAlignment() < Alignment) {
250 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
255 // Extract the length and alignment and fill if they are constant.
256 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
257 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
258 if (!LenC || !FillC || !FillC->getType()->isIntegerTy(8))
260 uint64_t Len = LenC->getLimitedValue();
261 Alignment = MI->getAlignment();
262 assert(Len && "0-sized memory setting should be removed already.");
264 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
265 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
266 Type *ITy = IntegerType::get(MI->getContext(), Len*8); // n=1 -> i8.
268 Value *Dest = MI->getDest();
269 unsigned DstAddrSp = cast<PointerType>(Dest->getType())->getAddressSpace();
270 Type *NewDstPtrTy = PointerType::get(ITy, DstAddrSp);
271 Dest = Builder->CreateBitCast(Dest, NewDstPtrTy);
273 // Alignment 0 is identity for alignment 1 for memset, but not store.
274 if (Alignment == 0) Alignment = 1;
276 // Extract the fill value and store.
277 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
278 StoreInst *S = Builder->CreateStore(ConstantInt::get(ITy, Fill), Dest,
280 S->setAlignment(Alignment);
282 // Set the size of the copy to 0, it will be deleted on the next iteration.
283 MI->setLength(Constant::getNullValue(LenC->getType()));
290 static Value *simplifyX86immShift(const IntrinsicInst &II,
291 InstCombiner::BuilderTy &Builder) {
292 bool LogicalShift = false;
293 bool ShiftLeft = false;
295 switch (II.getIntrinsicID()) {
296 default: llvm_unreachable("Unexpected intrinsic!");
297 case Intrinsic::x86_sse2_psra_d:
298 case Intrinsic::x86_sse2_psra_w:
299 case Intrinsic::x86_sse2_psrai_d:
300 case Intrinsic::x86_sse2_psrai_w:
301 case Intrinsic::x86_avx2_psra_d:
302 case Intrinsic::x86_avx2_psra_w:
303 case Intrinsic::x86_avx2_psrai_d:
304 case Intrinsic::x86_avx2_psrai_w:
305 case Intrinsic::x86_avx512_psra_q_128:
306 case Intrinsic::x86_avx512_psrai_q_128:
307 case Intrinsic::x86_avx512_psra_q_256:
308 case Intrinsic::x86_avx512_psrai_q_256:
309 case Intrinsic::x86_avx512_psra_d_512:
310 case Intrinsic::x86_avx512_psra_q_512:
311 case Intrinsic::x86_avx512_psra_w_512:
312 case Intrinsic::x86_avx512_psrai_d_512:
313 case Intrinsic::x86_avx512_psrai_q_512:
314 case Intrinsic::x86_avx512_psrai_w_512:
315 LogicalShift = false; ShiftLeft = false;
317 case Intrinsic::x86_sse2_psrl_d:
318 case Intrinsic::x86_sse2_psrl_q:
319 case Intrinsic::x86_sse2_psrl_w:
320 case Intrinsic::x86_sse2_psrli_d:
321 case Intrinsic::x86_sse2_psrli_q:
322 case Intrinsic::x86_sse2_psrli_w:
323 case Intrinsic::x86_avx2_psrl_d:
324 case Intrinsic::x86_avx2_psrl_q:
325 case Intrinsic::x86_avx2_psrl_w:
326 case Intrinsic::x86_avx2_psrli_d:
327 case Intrinsic::x86_avx2_psrli_q:
328 case Intrinsic::x86_avx2_psrli_w:
329 case Intrinsic::x86_avx512_psrl_d_512:
330 case Intrinsic::x86_avx512_psrl_q_512:
331 case Intrinsic::x86_avx512_psrl_w_512:
332 case Intrinsic::x86_avx512_psrli_d_512:
333 case Intrinsic::x86_avx512_psrli_q_512:
334 case Intrinsic::x86_avx512_psrli_w_512:
335 LogicalShift = true; ShiftLeft = false;
337 case Intrinsic::x86_sse2_psll_d:
338 case Intrinsic::x86_sse2_psll_q:
339 case Intrinsic::x86_sse2_psll_w:
340 case Intrinsic::x86_sse2_pslli_d:
341 case Intrinsic::x86_sse2_pslli_q:
342 case Intrinsic::x86_sse2_pslli_w:
343 case Intrinsic::x86_avx2_psll_d:
344 case Intrinsic::x86_avx2_psll_q:
345 case Intrinsic::x86_avx2_psll_w:
346 case Intrinsic::x86_avx2_pslli_d:
347 case Intrinsic::x86_avx2_pslli_q:
348 case Intrinsic::x86_avx2_pslli_w:
349 case Intrinsic::x86_avx512_psll_d_512:
350 case Intrinsic::x86_avx512_psll_q_512:
351 case Intrinsic::x86_avx512_psll_w_512:
352 case Intrinsic::x86_avx512_pslli_d_512:
353 case Intrinsic::x86_avx512_pslli_q_512:
354 case Intrinsic::x86_avx512_pslli_w_512:
355 LogicalShift = true; ShiftLeft = true;
358 assert((LogicalShift || !ShiftLeft) && "Only logical shifts can shift left");
360 // Simplify if count is constant.
361 auto Arg1 = II.getArgOperand(1);
362 auto CAZ = dyn_cast<ConstantAggregateZero>(Arg1);
363 auto CDV = dyn_cast<ConstantDataVector>(Arg1);
364 auto CInt = dyn_cast<ConstantInt>(Arg1);
365 if (!CAZ && !CDV && !CInt)
370 // SSE2/AVX2 uses all the first 64-bits of the 128-bit vector
371 // operand to compute the shift amount.
372 auto VT = cast<VectorType>(CDV->getType());
373 unsigned BitWidth = VT->getElementType()->getPrimitiveSizeInBits();
374 assert((64 % BitWidth) == 0 && "Unexpected packed shift size");
375 unsigned NumSubElts = 64 / BitWidth;
377 // Concatenate the sub-elements to create the 64-bit value.
378 for (unsigned i = 0; i != NumSubElts; ++i) {
379 unsigned SubEltIdx = (NumSubElts - 1) - i;
380 auto SubElt = cast<ConstantInt>(CDV->getElementAsConstant(SubEltIdx));
381 Count = Count.shl(BitWidth);
382 Count |= SubElt->getValue().zextOrTrunc(64);
386 Count = CInt->getValue();
388 auto Vec = II.getArgOperand(0);
389 auto VT = cast<VectorType>(Vec->getType());
390 auto SVT = VT->getElementType();
391 unsigned VWidth = VT->getNumElements();
392 unsigned BitWidth = SVT->getPrimitiveSizeInBits();
394 // If shift-by-zero then just return the original value.
398 // Handle cases when Shift >= BitWidth.
399 if (Count.uge(BitWidth)) {
400 // If LogicalShift - just return zero.
402 return ConstantAggregateZero::get(VT);
404 // If ArithmeticShift - clamp Shift to (BitWidth - 1).
405 Count = APInt(64, BitWidth - 1);
408 // Get a constant vector of the same type as the first operand.
409 auto ShiftAmt = ConstantInt::get(SVT, Count.zextOrTrunc(BitWidth));
410 auto ShiftVec = Builder.CreateVectorSplat(VWidth, ShiftAmt);
413 return Builder.CreateShl(Vec, ShiftVec);
416 return Builder.CreateLShr(Vec, ShiftVec);
418 return Builder.CreateAShr(Vec, ShiftVec);
421 // Attempt to simplify AVX2 per-element shift intrinsics to a generic IR shift.
422 // Unlike the generic IR shifts, the intrinsics have defined behaviour for out
423 // of range shift amounts (logical - set to zero, arithmetic - splat sign bit).
424 static Value *simplifyX86varShift(const IntrinsicInst &II,
425 InstCombiner::BuilderTy &Builder) {
426 bool LogicalShift = false;
427 bool ShiftLeft = false;
429 switch (II.getIntrinsicID()) {
430 default: llvm_unreachable("Unexpected intrinsic!");
431 case Intrinsic::x86_avx2_psrav_d:
432 case Intrinsic::x86_avx2_psrav_d_256:
433 case Intrinsic::x86_avx512_psrav_q_128:
434 case Intrinsic::x86_avx512_psrav_q_256:
435 case Intrinsic::x86_avx512_psrav_d_512:
436 case Intrinsic::x86_avx512_psrav_q_512:
437 case Intrinsic::x86_avx512_psrav_w_128:
438 case Intrinsic::x86_avx512_psrav_w_256:
439 case Intrinsic::x86_avx512_psrav_w_512:
440 LogicalShift = false;
443 case Intrinsic::x86_avx2_psrlv_d:
444 case Intrinsic::x86_avx2_psrlv_d_256:
445 case Intrinsic::x86_avx2_psrlv_q:
446 case Intrinsic::x86_avx2_psrlv_q_256:
447 case Intrinsic::x86_avx512_psrlv_d_512:
448 case Intrinsic::x86_avx512_psrlv_q_512:
449 case Intrinsic::x86_avx512_psrlv_w_128:
450 case Intrinsic::x86_avx512_psrlv_w_256:
451 case Intrinsic::x86_avx512_psrlv_w_512:
455 case Intrinsic::x86_avx2_psllv_d:
456 case Intrinsic::x86_avx2_psllv_d_256:
457 case Intrinsic::x86_avx2_psllv_q:
458 case Intrinsic::x86_avx2_psllv_q_256:
459 case Intrinsic::x86_avx512_psllv_d_512:
460 case Intrinsic::x86_avx512_psllv_q_512:
461 case Intrinsic::x86_avx512_psllv_w_128:
462 case Intrinsic::x86_avx512_psllv_w_256:
463 case Intrinsic::x86_avx512_psllv_w_512:
468 assert((LogicalShift || !ShiftLeft) && "Only logical shifts can shift left");
470 // Simplify if all shift amounts are constant/undef.
471 auto *CShift = dyn_cast<Constant>(II.getArgOperand(1));
475 auto Vec = II.getArgOperand(0);
476 auto VT = cast<VectorType>(II.getType());
477 auto SVT = VT->getVectorElementType();
478 int NumElts = VT->getNumElements();
479 int BitWidth = SVT->getIntegerBitWidth();
481 // Collect each element's shift amount.
482 // We also collect special cases: UNDEF = -1, OUT-OF-RANGE = BitWidth.
483 bool AnyOutOfRange = false;
484 SmallVector<int, 8> ShiftAmts;
485 for (int I = 0; I < NumElts; ++I) {
486 auto *CElt = CShift->getAggregateElement(I);
487 if (CElt && isa<UndefValue>(CElt)) {
488 ShiftAmts.push_back(-1);
492 auto *COp = dyn_cast_or_null<ConstantInt>(CElt);
496 // Handle out of range shifts.
497 // If LogicalShift - set to BitWidth (special case).
498 // If ArithmeticShift - set to (BitWidth - 1) (sign splat).
499 APInt ShiftVal = COp->getValue();
500 if (ShiftVal.uge(BitWidth)) {
501 AnyOutOfRange = LogicalShift;
502 ShiftAmts.push_back(LogicalShift ? BitWidth : BitWidth - 1);
506 ShiftAmts.push_back((int)ShiftVal.getZExtValue());
509 // If all elements out of range or UNDEF, return vector of zeros/undefs.
510 // ArithmeticShift should only hit this if they are all UNDEF.
511 auto OutOfRange = [&](int Idx) { return (Idx < 0) || (BitWidth <= Idx); };
512 if (all_of(ShiftAmts, OutOfRange)) {
513 SmallVector<Constant *, 8> ConstantVec;
514 for (int Idx : ShiftAmts) {
516 ConstantVec.push_back(UndefValue::get(SVT));
518 assert(LogicalShift && "Logical shift expected");
519 ConstantVec.push_back(ConstantInt::getNullValue(SVT));
522 return ConstantVector::get(ConstantVec);
525 // We can't handle only some out of range values with generic logical shifts.
529 // Build the shift amount constant vector.
530 SmallVector<Constant *, 8> ShiftVecAmts;
531 for (int Idx : ShiftAmts) {
533 ShiftVecAmts.push_back(UndefValue::get(SVT));
535 ShiftVecAmts.push_back(ConstantInt::get(SVT, Idx));
537 auto ShiftVec = ConstantVector::get(ShiftVecAmts);
540 return Builder.CreateShl(Vec, ShiftVec);
543 return Builder.CreateLShr(Vec, ShiftVec);
545 return Builder.CreateAShr(Vec, ShiftVec);
548 static Value *simplifyX86muldq(const IntrinsicInst &II,
549 InstCombiner::BuilderTy &Builder) {
550 Value *Arg0 = II.getArgOperand(0);
551 Value *Arg1 = II.getArgOperand(1);
552 Type *ResTy = II.getType();
553 assert(Arg0->getType()->getScalarSizeInBits() == 32 &&
554 Arg1->getType()->getScalarSizeInBits() == 32 &&
555 ResTy->getScalarSizeInBits() == 64 && "Unexpected muldq/muludq types");
557 // muldq/muludq(undef, undef) -> zero (matches generic mul behavior)
558 if (isa<UndefValue>(Arg0) || isa<UndefValue>(Arg1))
559 return ConstantAggregateZero::get(ResTy);
562 // PMULDQ = (mul(vXi64 sext(shuffle<0,2,..>(Arg0)),
563 // vXi64 sext(shuffle<0,2,..>(Arg1))))
564 // PMULUDQ = (mul(vXi64 zext(shuffle<0,2,..>(Arg0)),
565 // vXi64 zext(shuffle<0,2,..>(Arg1))))
566 if (!isa<Constant>(Arg0) || !isa<Constant>(Arg1))
569 unsigned NumElts = ResTy->getVectorNumElements();
570 assert(Arg0->getType()->getVectorNumElements() == (2 * NumElts) &&
571 Arg1->getType()->getVectorNumElements() == (2 * NumElts) &&
572 "Unexpected muldq/muludq types");
574 unsigned IntrinsicID = II.getIntrinsicID();
575 bool IsSigned = (Intrinsic::x86_sse41_pmuldq == IntrinsicID ||
576 Intrinsic::x86_avx2_pmul_dq == IntrinsicID ||
577 Intrinsic::x86_avx512_pmul_dq_512 == IntrinsicID);
579 SmallVector<unsigned, 16> ShuffleMask;
580 for (unsigned i = 0; i != NumElts; ++i)
581 ShuffleMask.push_back(i * 2);
583 auto *LHS = Builder.CreateShuffleVector(Arg0, Arg0, ShuffleMask);
584 auto *RHS = Builder.CreateShuffleVector(Arg1, Arg1, ShuffleMask);
587 LHS = Builder.CreateSExt(LHS, ResTy);
588 RHS = Builder.CreateSExt(RHS, ResTy);
590 LHS = Builder.CreateZExt(LHS, ResTy);
591 RHS = Builder.CreateZExt(RHS, ResTy);
594 return Builder.CreateMul(LHS, RHS);
597 static Value *simplifyX86pack(IntrinsicInst &II, InstCombiner &IC,
598 InstCombiner::BuilderTy &Builder, bool IsSigned) {
599 Value *Arg0 = II.getArgOperand(0);
600 Value *Arg1 = II.getArgOperand(1);
601 Type *ResTy = II.getType();
603 // Fast all undef handling.
604 if (isa<UndefValue>(Arg0) && isa<UndefValue>(Arg1))
605 return UndefValue::get(ResTy);
607 Type *ArgTy = Arg0->getType();
608 unsigned NumLanes = ResTy->getPrimitiveSizeInBits() / 128;
609 unsigned NumDstElts = ResTy->getVectorNumElements();
610 unsigned NumSrcElts = ArgTy->getVectorNumElements();
611 assert(NumDstElts == (2 * NumSrcElts) && "Unexpected packing types");
613 unsigned NumDstEltsPerLane = NumDstElts / NumLanes;
614 unsigned NumSrcEltsPerLane = NumSrcElts / NumLanes;
615 unsigned DstScalarSizeInBits = ResTy->getScalarSizeInBits();
616 assert(ArgTy->getScalarSizeInBits() == (2 * DstScalarSizeInBits) &&
617 "Unexpected packing types");
620 auto *Cst0 = dyn_cast<Constant>(Arg0);
621 auto *Cst1 = dyn_cast<Constant>(Arg1);
625 SmallVector<Constant *, 32> Vals;
626 for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
627 for (unsigned Elt = 0; Elt != NumDstEltsPerLane; ++Elt) {
628 unsigned SrcIdx = Lane * NumSrcEltsPerLane + Elt % NumSrcEltsPerLane;
629 auto *Cst = (Elt >= NumSrcEltsPerLane) ? Cst1 : Cst0;
630 auto *COp = Cst->getAggregateElement(SrcIdx);
631 if (COp && isa<UndefValue>(COp)) {
632 Vals.push_back(UndefValue::get(ResTy->getScalarType()));
636 auto *CInt = dyn_cast_or_null<ConstantInt>(COp);
640 APInt Val = CInt->getValue();
641 assert(Val.getBitWidth() == ArgTy->getScalarSizeInBits() &&
642 "Unexpected constant bitwidth");
645 // PACKSS: Truncate signed value with signed saturation.
646 // Source values less than dst minint are saturated to minint.
647 // Source values greater than dst maxint are saturated to maxint.
648 if (Val.isSignedIntN(DstScalarSizeInBits))
649 Val = Val.trunc(DstScalarSizeInBits);
650 else if (Val.isNegative())
651 Val = APInt::getSignedMinValue(DstScalarSizeInBits);
653 Val = APInt::getSignedMaxValue(DstScalarSizeInBits);
655 // PACKUS: Truncate signed value with unsigned saturation.
656 // Source values less than zero are saturated to zero.
657 // Source values greater than dst maxuint are saturated to maxuint.
658 if (Val.isIntN(DstScalarSizeInBits))
659 Val = Val.trunc(DstScalarSizeInBits);
660 else if (Val.isNegative())
661 Val = APInt::getNullValue(DstScalarSizeInBits);
663 Val = APInt::getAllOnesValue(DstScalarSizeInBits);
666 Vals.push_back(ConstantInt::get(ResTy->getScalarType(), Val));
670 return ConstantVector::get(Vals);
673 static Value *simplifyX86movmsk(const IntrinsicInst &II,
674 InstCombiner::BuilderTy &Builder) {
675 Value *Arg = II.getArgOperand(0);
676 Type *ResTy = II.getType();
677 Type *ArgTy = Arg->getType();
679 // movmsk(undef) -> zero as we must ensure the upper bits are zero.
680 if (isa<UndefValue>(Arg))
681 return Constant::getNullValue(ResTy);
683 // We can't easily peek through x86_mmx types.
684 if (!ArgTy->isVectorTy())
687 auto *C = dyn_cast<Constant>(Arg);
691 // Extract signbits of the vector input and pack into integer result.
692 APInt Result(ResTy->getPrimitiveSizeInBits(), 0);
693 for (unsigned I = 0, E = ArgTy->getVectorNumElements(); I != E; ++I) {
694 auto *COp = C->getAggregateElement(I);
697 if (isa<UndefValue>(COp))
700 auto *CInt = dyn_cast<ConstantInt>(COp);
701 auto *CFp = dyn_cast<ConstantFP>(COp);
705 if ((CInt && CInt->isNegative()) || (CFp && CFp->isNegative()))
709 return Constant::getIntegerValue(ResTy, Result);
712 static Value *simplifyX86insertps(const IntrinsicInst &II,
713 InstCombiner::BuilderTy &Builder) {
714 auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2));
718 VectorType *VecTy = cast<VectorType>(II.getType());
719 assert(VecTy->getNumElements() == 4 && "insertps with wrong vector type");
721 // The immediate permute control byte looks like this:
722 // [3:0] - zero mask for each 32-bit lane
723 // [5:4] - select one 32-bit destination lane
724 // [7:6] - select one 32-bit source lane
726 uint8_t Imm = CInt->getZExtValue();
727 uint8_t ZMask = Imm & 0xf;
728 uint8_t DestLane = (Imm >> 4) & 0x3;
729 uint8_t SourceLane = (Imm >> 6) & 0x3;
731 ConstantAggregateZero *ZeroVector = ConstantAggregateZero::get(VecTy);
733 // If all zero mask bits are set, this was just a weird way to
734 // generate a zero vector.
738 // Initialize by passing all of the first source bits through.
739 uint32_t ShuffleMask[4] = { 0, 1, 2, 3 };
741 // We may replace the second operand with the zero vector.
742 Value *V1 = II.getArgOperand(1);
745 // If the zero mask is being used with a single input or the zero mask
746 // overrides the destination lane, this is a shuffle with the zero vector.
747 if ((II.getArgOperand(0) == II.getArgOperand(1)) ||
748 (ZMask & (1 << DestLane))) {
750 // We may still move 32-bits of the first source vector from one lane
752 ShuffleMask[DestLane] = SourceLane;
753 // The zero mask may override the previous insert operation.
754 for (unsigned i = 0; i < 4; ++i)
755 if ((ZMask >> i) & 0x1)
756 ShuffleMask[i] = i + 4;
758 // TODO: Model this case as 2 shuffles or a 'logical and' plus shuffle?
762 // Replace the selected destination lane with the selected source lane.
763 ShuffleMask[DestLane] = SourceLane + 4;
766 return Builder.CreateShuffleVector(II.getArgOperand(0), V1, ShuffleMask);
769 /// Attempt to simplify SSE4A EXTRQ/EXTRQI instructions using constant folding
770 /// or conversion to a shuffle vector.
771 static Value *simplifyX86extrq(IntrinsicInst &II, Value *Op0,
772 ConstantInt *CILength, ConstantInt *CIIndex,
773 InstCombiner::BuilderTy &Builder) {
774 auto LowConstantHighUndef = [&](uint64_t Val) {
775 Type *IntTy64 = Type::getInt64Ty(II.getContext());
776 Constant *Args[] = {ConstantInt::get(IntTy64, Val),
777 UndefValue::get(IntTy64)};
778 return ConstantVector::get(Args);
781 // See if we're dealing with constant values.
782 Constant *C0 = dyn_cast<Constant>(Op0);
784 C0 ? dyn_cast_or_null<ConstantInt>(C0->getAggregateElement((unsigned)0))
787 // Attempt to constant fold.
788 if (CILength && CIIndex) {
789 // From AMD documentation: "The bit index and field length are each six
790 // bits in length other bits of the field are ignored."
791 APInt APIndex = CIIndex->getValue().zextOrTrunc(6);
792 APInt APLength = CILength->getValue().zextOrTrunc(6);
794 unsigned Index = APIndex.getZExtValue();
796 // From AMD documentation: "a value of zero in the field length is
797 // defined as length of 64".
798 unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue();
800 // From AMD documentation: "If the sum of the bit index + length field
801 // is greater than 64, the results are undefined".
802 unsigned End = Index + Length;
804 // Note that both field index and field length are 8-bit quantities.
805 // Since variables 'Index' and 'Length' are unsigned values
806 // obtained from zero-extending field index and field length
807 // respectively, their sum should never wrap around.
809 return UndefValue::get(II.getType());
811 // If we are inserting whole bytes, we can convert this to a shuffle.
812 // Lowering can recognize EXTRQI shuffle masks.
813 if ((Length % 8) == 0 && (Index % 8) == 0) {
814 // Convert bit indices to byte indices.
818 Type *IntTy8 = Type::getInt8Ty(II.getContext());
819 Type *IntTy32 = Type::getInt32Ty(II.getContext());
820 VectorType *ShufTy = VectorType::get(IntTy8, 16);
822 SmallVector<Constant *, 16> ShuffleMask;
823 for (int i = 0; i != (int)Length; ++i)
824 ShuffleMask.push_back(
825 Constant::getIntegerValue(IntTy32, APInt(32, i + Index)));
826 for (int i = Length; i != 8; ++i)
827 ShuffleMask.push_back(
828 Constant::getIntegerValue(IntTy32, APInt(32, i + 16)));
829 for (int i = 8; i != 16; ++i)
830 ShuffleMask.push_back(UndefValue::get(IntTy32));
832 Value *SV = Builder.CreateShuffleVector(
833 Builder.CreateBitCast(Op0, ShufTy),
834 ConstantAggregateZero::get(ShufTy), ConstantVector::get(ShuffleMask));
835 return Builder.CreateBitCast(SV, II.getType());
838 // Constant Fold - shift Index'th bit to lowest position and mask off
841 APInt Elt = CI0->getValue();
842 Elt = Elt.lshr(Index).zextOrTrunc(Length);
843 return LowConstantHighUndef(Elt.getZExtValue());
846 // If we were an EXTRQ call, we'll save registers if we convert to EXTRQI.
847 if (II.getIntrinsicID() == Intrinsic::x86_sse4a_extrq) {
848 Value *Args[] = {Op0, CILength, CIIndex};
849 Module *M = II.getModule();
850 Value *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_extrqi);
851 return Builder.CreateCall(F, Args);
855 // Constant Fold - extraction from zero is always {zero, undef}.
856 if (CI0 && CI0->equalsInt(0))
857 return LowConstantHighUndef(0);
862 /// Attempt to simplify SSE4A INSERTQ/INSERTQI instructions using constant
863 /// folding or conversion to a shuffle vector.
864 static Value *simplifyX86insertq(IntrinsicInst &II, Value *Op0, Value *Op1,
865 APInt APLength, APInt APIndex,
866 InstCombiner::BuilderTy &Builder) {
867 // From AMD documentation: "The bit index and field length are each six bits
868 // in length other bits of the field are ignored."
869 APIndex = APIndex.zextOrTrunc(6);
870 APLength = APLength.zextOrTrunc(6);
872 // Attempt to constant fold.
873 unsigned Index = APIndex.getZExtValue();
875 // From AMD documentation: "a value of zero in the field length is
876 // defined as length of 64".
877 unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue();
879 // From AMD documentation: "If the sum of the bit index + length field
880 // is greater than 64, the results are undefined".
881 unsigned End = Index + Length;
883 // Note that both field index and field length are 8-bit quantities.
884 // Since variables 'Index' and 'Length' are unsigned values
885 // obtained from zero-extending field index and field length
886 // respectively, their sum should never wrap around.
888 return UndefValue::get(II.getType());
890 // If we are inserting whole bytes, we can convert this to a shuffle.
891 // Lowering can recognize INSERTQI shuffle masks.
892 if ((Length % 8) == 0 && (Index % 8) == 0) {
893 // Convert bit indices to byte indices.
897 Type *IntTy8 = Type::getInt8Ty(II.getContext());
898 Type *IntTy32 = Type::getInt32Ty(II.getContext());
899 VectorType *ShufTy = VectorType::get(IntTy8, 16);
901 SmallVector<Constant *, 16> ShuffleMask;
902 for (int i = 0; i != (int)Index; ++i)
903 ShuffleMask.push_back(Constant::getIntegerValue(IntTy32, APInt(32, i)));
904 for (int i = 0; i != (int)Length; ++i)
905 ShuffleMask.push_back(
906 Constant::getIntegerValue(IntTy32, APInt(32, i + 16)));
907 for (int i = Index + Length; i != 8; ++i)
908 ShuffleMask.push_back(Constant::getIntegerValue(IntTy32, APInt(32, i)));
909 for (int i = 8; i != 16; ++i)
910 ShuffleMask.push_back(UndefValue::get(IntTy32));
912 Value *SV = Builder.CreateShuffleVector(Builder.CreateBitCast(Op0, ShufTy),
913 Builder.CreateBitCast(Op1, ShufTy),
914 ConstantVector::get(ShuffleMask));
915 return Builder.CreateBitCast(SV, II.getType());
918 // See if we're dealing with constant values.
919 Constant *C0 = dyn_cast<Constant>(Op0);
920 Constant *C1 = dyn_cast<Constant>(Op1);
922 C0 ? dyn_cast_or_null<ConstantInt>(C0->getAggregateElement((unsigned)0))
925 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)0))
928 // Constant Fold - insert bottom Length bits starting at the Index'th bit.
930 APInt V00 = CI00->getValue();
931 APInt V10 = CI10->getValue();
932 APInt Mask = APInt::getLowBitsSet(64, Length).shl(Index);
934 V10 = V10.zextOrTrunc(Length).zextOrTrunc(64).shl(Index);
935 APInt Val = V00 | V10;
936 Type *IntTy64 = Type::getInt64Ty(II.getContext());
937 Constant *Args[] = {ConstantInt::get(IntTy64, Val.getZExtValue()),
938 UndefValue::get(IntTy64)};
939 return ConstantVector::get(Args);
942 // If we were an INSERTQ call, we'll save demanded elements if we convert to
944 if (II.getIntrinsicID() == Intrinsic::x86_sse4a_insertq) {
945 Type *IntTy8 = Type::getInt8Ty(II.getContext());
946 Constant *CILength = ConstantInt::get(IntTy8, Length, false);
947 Constant *CIIndex = ConstantInt::get(IntTy8, Index, false);
949 Value *Args[] = {Op0, Op1, CILength, CIIndex};
950 Module *M = II.getModule();
951 Value *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_insertqi);
952 return Builder.CreateCall(F, Args);
958 /// Attempt to convert pshufb* to shufflevector if the mask is constant.
959 static Value *simplifyX86pshufb(const IntrinsicInst &II,
960 InstCombiner::BuilderTy &Builder) {
961 Constant *V = dyn_cast<Constant>(II.getArgOperand(1));
965 auto *VecTy = cast<VectorType>(II.getType());
966 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
967 unsigned NumElts = VecTy->getNumElements();
968 assert((NumElts == 16 || NumElts == 32 || NumElts == 64) &&
969 "Unexpected number of elements in shuffle mask!");
971 // Construct a shuffle mask from constant integers or UNDEFs.
972 Constant *Indexes[64] = {nullptr};
974 // Each byte in the shuffle control mask forms an index to permute the
975 // corresponding byte in the destination operand.
976 for (unsigned I = 0; I < NumElts; ++I) {
977 Constant *COp = V->getAggregateElement(I);
978 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
981 if (isa<UndefValue>(COp)) {
982 Indexes[I] = UndefValue::get(MaskEltTy);
986 int8_t Index = cast<ConstantInt>(COp)->getValue().getZExtValue();
988 // If the most significant bit (bit[7]) of each byte of the shuffle
989 // control mask is set, then zero is written in the result byte.
990 // The zero vector is in the right-hand side of the resulting
993 // The value of each index for the high 128-bit lane is the least
994 // significant 4 bits of the respective shuffle control byte.
995 Index = ((Index < 0) ? NumElts : Index & 0x0F) + (I & 0xF0);
996 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
999 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, NumElts));
1000 auto V1 = II.getArgOperand(0);
1001 auto V2 = Constant::getNullValue(VecTy);
1002 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
1005 /// Attempt to convert vpermilvar* to shufflevector if the mask is constant.
1006 static Value *simplifyX86vpermilvar(const IntrinsicInst &II,
1007 InstCombiner::BuilderTy &Builder) {
1008 Constant *V = dyn_cast<Constant>(II.getArgOperand(1));
1012 auto *VecTy = cast<VectorType>(II.getType());
1013 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
1014 unsigned NumElts = VecTy->getVectorNumElements();
1015 bool IsPD = VecTy->getScalarType()->isDoubleTy();
1016 unsigned NumLaneElts = IsPD ? 2 : 4;
1017 assert(NumElts == 16 || NumElts == 8 || NumElts == 4 || NumElts == 2);
1019 // Construct a shuffle mask from constant integers or UNDEFs.
1020 Constant *Indexes[16] = {nullptr};
1022 // The intrinsics only read one or two bits, clear the rest.
1023 for (unsigned I = 0; I < NumElts; ++I) {
1024 Constant *COp = V->getAggregateElement(I);
1025 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
1028 if (isa<UndefValue>(COp)) {
1029 Indexes[I] = UndefValue::get(MaskEltTy);
1033 APInt Index = cast<ConstantInt>(COp)->getValue();
1034 Index = Index.zextOrTrunc(32).getLoBits(2);
1036 // The PD variants uses bit 1 to select per-lane element index, so
1037 // shift down to convert to generic shuffle mask index.
1039 Index = Index.lshr(1);
1041 // The _256 variants are a bit trickier since the mask bits always index
1042 // into the corresponding 128 half. In order to convert to a generic
1043 // shuffle, we have to make that explicit.
1044 Index += APInt(32, (I / NumLaneElts) * NumLaneElts);
1046 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
1049 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, NumElts));
1050 auto V1 = II.getArgOperand(0);
1051 auto V2 = UndefValue::get(V1->getType());
1052 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
1055 /// Attempt to convert vpermd/vpermps to shufflevector if the mask is constant.
1056 static Value *simplifyX86vpermv(const IntrinsicInst &II,
1057 InstCombiner::BuilderTy &Builder) {
1058 auto *V = dyn_cast<Constant>(II.getArgOperand(1));
1062 auto *VecTy = cast<VectorType>(II.getType());
1063 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
1064 unsigned Size = VecTy->getNumElements();
1065 assert((Size == 4 || Size == 8 || Size == 16 || Size == 32 || Size == 64) &&
1066 "Unexpected shuffle mask size");
1068 // Construct a shuffle mask from constant integers or UNDEFs.
1069 Constant *Indexes[64] = {nullptr};
1071 for (unsigned I = 0; I < Size; ++I) {
1072 Constant *COp = V->getAggregateElement(I);
1073 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
1076 if (isa<UndefValue>(COp)) {
1077 Indexes[I] = UndefValue::get(MaskEltTy);
1081 uint32_t Index = cast<ConstantInt>(COp)->getZExtValue();
1083 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
1086 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, Size));
1087 auto V1 = II.getArgOperand(0);
1088 auto V2 = UndefValue::get(VecTy);
1089 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
1092 /// The shuffle mask for a perm2*128 selects any two halves of two 256-bit
1093 /// source vectors, unless a zero bit is set. If a zero bit is set,
1094 /// then ignore that half of the mask and clear that half of the vector.
1095 static Value *simplifyX86vperm2(const IntrinsicInst &II,
1096 InstCombiner::BuilderTy &Builder) {
1097 auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2));
1101 VectorType *VecTy = cast<VectorType>(II.getType());
1102 ConstantAggregateZero *ZeroVector = ConstantAggregateZero::get(VecTy);
1104 // The immediate permute control byte looks like this:
1105 // [1:0] - select 128 bits from sources for low half of destination
1107 // [3] - zero low half of destination
1108 // [5:4] - select 128 bits from sources for high half of destination
1110 // [7] - zero high half of destination
1112 uint8_t Imm = CInt->getZExtValue();
1114 bool LowHalfZero = Imm & 0x08;
1115 bool HighHalfZero = Imm & 0x80;
1117 // If both zero mask bits are set, this was just a weird way to
1118 // generate a zero vector.
1119 if (LowHalfZero && HighHalfZero)
1122 // If 0 or 1 zero mask bits are set, this is a simple shuffle.
1123 unsigned NumElts = VecTy->getNumElements();
1124 unsigned HalfSize = NumElts / 2;
1125 SmallVector<uint32_t, 8> ShuffleMask(NumElts);
1127 // The high bit of the selection field chooses the 1st or 2nd operand.
1128 bool LowInputSelect = Imm & 0x02;
1129 bool HighInputSelect = Imm & 0x20;
1131 // The low bit of the selection field chooses the low or high half
1132 // of the selected operand.
1133 bool LowHalfSelect = Imm & 0x01;
1134 bool HighHalfSelect = Imm & 0x10;
1136 // Determine which operand(s) are actually in use for this instruction.
1137 Value *V0 = LowInputSelect ? II.getArgOperand(1) : II.getArgOperand(0);
1138 Value *V1 = HighInputSelect ? II.getArgOperand(1) : II.getArgOperand(0);
1140 // If needed, replace operands based on zero mask.
1141 V0 = LowHalfZero ? ZeroVector : V0;
1142 V1 = HighHalfZero ? ZeroVector : V1;
1144 // Permute low half of result.
1145 unsigned StartIndex = LowHalfSelect ? HalfSize : 0;
1146 for (unsigned i = 0; i < HalfSize; ++i)
1147 ShuffleMask[i] = StartIndex + i;
1149 // Permute high half of result.
1150 StartIndex = HighHalfSelect ? HalfSize : 0;
1151 StartIndex += NumElts;
1152 for (unsigned i = 0; i < HalfSize; ++i)
1153 ShuffleMask[i + HalfSize] = StartIndex + i;
1155 return Builder.CreateShuffleVector(V0, V1, ShuffleMask);
1158 /// Decode XOP integer vector comparison intrinsics.
1159 static Value *simplifyX86vpcom(const IntrinsicInst &II,
1160 InstCombiner::BuilderTy &Builder,
1162 if (auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2))) {
1163 uint64_t Imm = CInt->getZExtValue() & 0x7;
1164 VectorType *VecTy = cast<VectorType>(II.getType());
1165 CmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1169 Pred = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1172 Pred = IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
1175 Pred = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1178 Pred = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
1181 Pred = ICmpInst::ICMP_EQ; break;
1183 Pred = ICmpInst::ICMP_NE; break;
1185 return ConstantInt::getSigned(VecTy, 0); // FALSE
1187 return ConstantInt::getSigned(VecTy, -1); // TRUE
1190 if (Value *Cmp = Builder.CreateICmp(Pred, II.getArgOperand(0),
1191 II.getArgOperand(1)))
1192 return Builder.CreateSExtOrTrunc(Cmp, VecTy);
1197 // Emit a select instruction and appropriate bitcasts to help simplify
1198 // masked intrinsics.
1199 static Value *emitX86MaskSelect(Value *Mask, Value *Op0, Value *Op1,
1200 InstCombiner::BuilderTy &Builder) {
1201 unsigned VWidth = Op0->getType()->getVectorNumElements();
1203 // If the mask is all ones we don't need the select. But we need to check
1204 // only the bit thats will be used in case VWidth is less than 8.
1205 if (auto *C = dyn_cast<ConstantInt>(Mask))
1206 if (C->getValue().zextOrTrunc(VWidth).isAllOnesValue())
1209 auto *MaskTy = VectorType::get(Builder.getInt1Ty(),
1210 cast<IntegerType>(Mask->getType())->getBitWidth());
1211 Mask = Builder.CreateBitCast(Mask, MaskTy);
1213 // If we have less than 8 elements, then the starting mask was an i8 and
1214 // we need to extract down to the right number of elements.
1216 uint32_t Indices[4];
1217 for (unsigned i = 0; i != VWidth; ++i)
1219 Mask = Builder.CreateShuffleVector(Mask, Mask,
1220 makeArrayRef(Indices, VWidth),
1224 return Builder.CreateSelect(Mask, Op0, Op1);
1227 static Value *simplifyMinnumMaxnum(const IntrinsicInst &II) {
1228 Value *Arg0 = II.getArgOperand(0);
1229 Value *Arg1 = II.getArgOperand(1);
1235 const auto *C1 = dyn_cast<ConstantFP>(Arg1);
1237 // fmin(x, nan) -> x
1238 if (C1 && C1->isNaN())
1241 // This is the value because if undef were NaN, we would return the other
1242 // value and cannot return a NaN unless both operands are.
1244 // fmin(undef, x) -> x
1245 if (isa<UndefValue>(Arg0))
1248 // fmin(x, undef) -> x
1249 if (isa<UndefValue>(Arg1))
1254 if (II.getIntrinsicID() == Intrinsic::minnum) {
1255 // fmin(x, fmin(x, y)) -> fmin(x, y)
1256 // fmin(y, fmin(x, y)) -> fmin(x, y)
1257 if (match(Arg1, m_FMin(m_Value(X), m_Value(Y)))) {
1258 if (Arg0 == X || Arg0 == Y)
1262 // fmin(fmin(x, y), x) -> fmin(x, y)
1263 // fmin(fmin(x, y), y) -> fmin(x, y)
1264 if (match(Arg0, m_FMin(m_Value(X), m_Value(Y)))) {
1265 if (Arg1 == X || Arg1 == Y)
1269 // TODO: fmin(nnan x, inf) -> x
1270 // TODO: fmin(nnan ninf x, flt_max) -> x
1271 if (C1 && C1->isInfinity()) {
1272 // fmin(x, -inf) -> -inf
1273 if (C1->isNegative())
1277 assert(II.getIntrinsicID() == Intrinsic::maxnum);
1278 // fmax(x, fmax(x, y)) -> fmax(x, y)
1279 // fmax(y, fmax(x, y)) -> fmax(x, y)
1280 if (match(Arg1, m_FMax(m_Value(X), m_Value(Y)))) {
1281 if (Arg0 == X || Arg0 == Y)
1285 // fmax(fmax(x, y), x) -> fmax(x, y)
1286 // fmax(fmax(x, y), y) -> fmax(x, y)
1287 if (match(Arg0, m_FMax(m_Value(X), m_Value(Y)))) {
1288 if (Arg1 == X || Arg1 == Y)
1292 // TODO: fmax(nnan x, -inf) -> x
1293 // TODO: fmax(nnan ninf x, -flt_max) -> x
1294 if (C1 && C1->isInfinity()) {
1295 // fmax(x, inf) -> inf
1296 if (!C1->isNegative())
1303 static bool maskIsAllOneOrUndef(Value *Mask) {
1304 auto *ConstMask = dyn_cast<Constant>(Mask);
1307 if (ConstMask->isAllOnesValue() || isa<UndefValue>(ConstMask))
1309 for (unsigned I = 0, E = ConstMask->getType()->getVectorNumElements(); I != E;
1311 if (auto *MaskElt = ConstMask->getAggregateElement(I))
1312 if (MaskElt->isAllOnesValue() || isa<UndefValue>(MaskElt))
1319 static Value *simplifyMaskedLoad(const IntrinsicInst &II,
1320 InstCombiner::BuilderTy &Builder) {
1321 // If the mask is all ones or undefs, this is a plain vector load of the 1st
1323 if (maskIsAllOneOrUndef(II.getArgOperand(2))) {
1324 Value *LoadPtr = II.getArgOperand(0);
1325 unsigned Alignment = cast<ConstantInt>(II.getArgOperand(1))->getZExtValue();
1326 return Builder.CreateAlignedLoad(LoadPtr, Alignment, "unmaskedload");
1332 static Instruction *simplifyMaskedStore(IntrinsicInst &II, InstCombiner &IC) {
1333 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
1337 // If the mask is all zeros, this instruction does nothing.
1338 if (ConstMask->isNullValue())
1339 return IC.eraseInstFromFunction(II);
1341 // If the mask is all ones, this is a plain vector store of the 1st argument.
1342 if (ConstMask->isAllOnesValue()) {
1343 Value *StorePtr = II.getArgOperand(1);
1344 unsigned Alignment = cast<ConstantInt>(II.getArgOperand(2))->getZExtValue();
1345 return new StoreInst(II.getArgOperand(0), StorePtr, false, Alignment);
1351 static Instruction *simplifyMaskedGather(IntrinsicInst &II, InstCombiner &IC) {
1352 // If the mask is all zeros, return the "passthru" argument of the gather.
1353 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(2));
1354 if (ConstMask && ConstMask->isNullValue())
1355 return IC.replaceInstUsesWith(II, II.getArgOperand(3));
1360 static Instruction *simplifyMaskedScatter(IntrinsicInst &II, InstCombiner &IC) {
1361 // If the mask is all zeros, a scatter does nothing.
1362 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
1363 if (ConstMask && ConstMask->isNullValue())
1364 return IC.eraseInstFromFunction(II);
1369 static Instruction *foldCttzCtlz(IntrinsicInst &II, InstCombiner &IC) {
1370 assert((II.getIntrinsicID() == Intrinsic::cttz ||
1371 II.getIntrinsicID() == Intrinsic::ctlz) &&
1372 "Expected cttz or ctlz intrinsic");
1373 Value *Op0 = II.getArgOperand(0);
1374 // FIXME: Try to simplify vectors of integers.
1375 auto *IT = dyn_cast<IntegerType>(Op0->getType());
1379 unsigned BitWidth = IT->getBitWidth();
1380 APInt KnownZero(BitWidth, 0);
1381 APInt KnownOne(BitWidth, 0);
1382 IC.computeKnownBits(Op0, KnownZero, KnownOne, 0, &II);
1384 // Create a mask for bits above (ctlz) or below (cttz) the first known one.
1385 bool IsTZ = II.getIntrinsicID() == Intrinsic::cttz;
1386 unsigned NumMaskBits = IsTZ ? KnownOne.countTrailingZeros()
1387 : KnownOne.countLeadingZeros();
1388 APInt Mask = IsTZ ? APInt::getLowBitsSet(BitWidth, NumMaskBits)
1389 : APInt::getHighBitsSet(BitWidth, NumMaskBits);
1391 // If all bits above (ctlz) or below (cttz) the first known one are known
1392 // zero, this value is constant.
1393 // FIXME: This should be in InstSimplify because we're replacing an
1394 // instruction with a constant.
1395 if ((Mask & KnownZero) == Mask) {
1396 auto *C = ConstantInt::get(IT, APInt(BitWidth, NumMaskBits));
1397 return IC.replaceInstUsesWith(II, C);
1400 // If the input to cttz/ctlz is known to be non-zero,
1401 // then change the 'ZeroIsUndef' parameter to 'true'
1402 // because we know the zero behavior can't affect the result.
1403 if (KnownOne != 0 || isKnownNonZero(Op0, IC.getDataLayout())) {
1404 if (!match(II.getArgOperand(1), m_One())) {
1405 II.setOperand(1, IC.Builder->getTrue());
1413 // TODO: If the x86 backend knew how to convert a bool vector mask back to an
1414 // XMM register mask efficiently, we could transform all x86 masked intrinsics
1415 // to LLVM masked intrinsics and remove the x86 masked intrinsic defs.
1416 static Instruction *simplifyX86MaskedLoad(IntrinsicInst &II, InstCombiner &IC) {
1417 Value *Ptr = II.getOperand(0);
1418 Value *Mask = II.getOperand(1);
1419 Constant *ZeroVec = Constant::getNullValue(II.getType());
1421 // Special case a zero mask since that's not a ConstantDataVector.
1422 // This masked load instruction creates a zero vector.
1423 if (isa<ConstantAggregateZero>(Mask))
1424 return IC.replaceInstUsesWith(II, ZeroVec);
1426 auto *ConstMask = dyn_cast<ConstantDataVector>(Mask);
1430 // The mask is constant. Convert this x86 intrinsic to the LLVM instrinsic
1431 // to allow target-independent optimizations.
1433 // First, cast the x86 intrinsic scalar pointer to a vector pointer to match
1434 // the LLVM intrinsic definition for the pointer argument.
1435 unsigned AddrSpace = cast<PointerType>(Ptr->getType())->getAddressSpace();
1436 PointerType *VecPtrTy = PointerType::get(II.getType(), AddrSpace);
1437 Value *PtrCast = IC.Builder->CreateBitCast(Ptr, VecPtrTy, "castvec");
1439 // Second, convert the x86 XMM integer vector mask to a vector of bools based
1440 // on each element's most significant bit (the sign bit).
1441 Constant *BoolMask = getNegativeIsTrueBoolVec(ConstMask);
1443 // The pass-through vector for an x86 masked load is a zero vector.
1444 CallInst *NewMaskedLoad =
1445 IC.Builder->CreateMaskedLoad(PtrCast, 1, BoolMask, ZeroVec);
1446 return IC.replaceInstUsesWith(II, NewMaskedLoad);
1449 // TODO: If the x86 backend knew how to convert a bool vector mask back to an
1450 // XMM register mask efficiently, we could transform all x86 masked intrinsics
1451 // to LLVM masked intrinsics and remove the x86 masked intrinsic defs.
1452 static bool simplifyX86MaskedStore(IntrinsicInst &II, InstCombiner &IC) {
1453 Value *Ptr = II.getOperand(0);
1454 Value *Mask = II.getOperand(1);
1455 Value *Vec = II.getOperand(2);
1457 // Special case a zero mask since that's not a ConstantDataVector:
1458 // this masked store instruction does nothing.
1459 if (isa<ConstantAggregateZero>(Mask)) {
1460 IC.eraseInstFromFunction(II);
1464 // The SSE2 version is too weird (eg, unaligned but non-temporal) to do
1465 // anything else at this level.
1466 if (II.getIntrinsicID() == Intrinsic::x86_sse2_maskmov_dqu)
1469 auto *ConstMask = dyn_cast<ConstantDataVector>(Mask);
1473 // The mask is constant. Convert this x86 intrinsic to the LLVM instrinsic
1474 // to allow target-independent optimizations.
1476 // First, cast the x86 intrinsic scalar pointer to a vector pointer to match
1477 // the LLVM intrinsic definition for the pointer argument.
1478 unsigned AddrSpace = cast<PointerType>(Ptr->getType())->getAddressSpace();
1479 PointerType *VecPtrTy = PointerType::get(Vec->getType(), AddrSpace);
1480 Value *PtrCast = IC.Builder->CreateBitCast(Ptr, VecPtrTy, "castvec");
1482 // Second, convert the x86 XMM integer vector mask to a vector of bools based
1483 // on each element's most significant bit (the sign bit).
1484 Constant *BoolMask = getNegativeIsTrueBoolVec(ConstMask);
1486 IC.Builder->CreateMaskedStore(Vec, PtrCast, 1, BoolMask);
1488 // 'Replace uses' doesn't work for stores. Erase the original masked store.
1489 IC.eraseInstFromFunction(II);
1493 // Constant fold llvm.amdgcn.fmed3 intrinsics for standard inputs.
1495 // A single NaN input is folded to minnum, so we rely on that folding for
1497 static APFloat fmed3AMDGCN(const APFloat &Src0, const APFloat &Src1,
1498 const APFloat &Src2) {
1499 APFloat Max3 = maxnum(maxnum(Src0, Src1), Src2);
1501 APFloat::cmpResult Cmp0 = Max3.compare(Src0);
1502 assert(Cmp0 != APFloat::cmpUnordered && "nans handled separately");
1503 if (Cmp0 == APFloat::cmpEqual)
1504 return maxnum(Src1, Src2);
1506 APFloat::cmpResult Cmp1 = Max3.compare(Src1);
1507 assert(Cmp1 != APFloat::cmpUnordered && "nans handled separately");
1508 if (Cmp1 == APFloat::cmpEqual)
1509 return maxnum(Src0, Src2);
1511 return maxnum(Src0, Src1);
1514 // Returns true iff the 2 intrinsics have the same operands, limiting the
1515 // comparison to the first NumOperands.
1516 static bool haveSameOperands(const IntrinsicInst &I, const IntrinsicInst &E,
1517 unsigned NumOperands) {
1518 assert(I.getNumArgOperands() >= NumOperands && "Not enough operands");
1519 assert(E.getNumArgOperands() >= NumOperands && "Not enough operands");
1520 for (unsigned i = 0; i < NumOperands; i++)
1521 if (I.getArgOperand(i) != E.getArgOperand(i))
1526 // Remove trivially empty start/end intrinsic ranges, i.e. a start
1527 // immediately followed by an end (ignoring debuginfo or other
1528 // start/end intrinsics in between). As this handles only the most trivial
1529 // cases, tracking the nesting level is not needed:
1531 // call @llvm.foo.start(i1 0) ; &I
1532 // call @llvm.foo.start(i1 0)
1533 // call @llvm.foo.end(i1 0) ; This one will not be skipped: it will be removed
1534 // call @llvm.foo.end(i1 0)
1535 static bool removeTriviallyEmptyRange(IntrinsicInst &I, unsigned StartID,
1536 unsigned EndID, InstCombiner &IC) {
1537 assert(I.getIntrinsicID() == StartID &&
1538 "Start intrinsic does not have expected ID");
1539 BasicBlock::iterator BI(I), BE(I.getParent()->end());
1540 for (++BI; BI != BE; ++BI) {
1541 if (auto *E = dyn_cast<IntrinsicInst>(BI)) {
1542 if (isa<DbgInfoIntrinsic>(E) || E->getIntrinsicID() == StartID)
1544 if (E->getIntrinsicID() == EndID &&
1545 haveSameOperands(I, *E, E->getNumArgOperands())) {
1546 IC.eraseInstFromFunction(*E);
1547 IC.eraseInstFromFunction(I);
1557 // Convert NVVM intrinsics to target-generic LLVM code where possible.
1558 static Instruction *SimplifyNVVMIntrinsic(IntrinsicInst *II, InstCombiner &IC) {
1559 // Each NVVM intrinsic we can simplify can be replaced with one of:
1561 // * an LLVM intrinsic,
1562 // * an LLVM cast operation,
1563 // * an LLVM binary operation, or
1564 // * ad-hoc LLVM IR for the particular operation.
1566 // Some transformations are only valid when the module's
1567 // flush-denormals-to-zero (ftz) setting is true/false, whereas other
1568 // transformations are valid regardless of the module's ftz setting.
1569 enum FtzRequirementTy {
1570 FTZ_Any, // Any ftz setting is ok.
1571 FTZ_MustBeOn, // Transformation is valid only if ftz is on.
1572 FTZ_MustBeOff, // Transformation is valid only if ftz is off.
1574 // Classes of NVVM intrinsics that can't be replaced one-to-one with a
1575 // target-generic intrinsic, cast op, or binary op but that we can nonetheless
1581 // SimplifyAction is a poor-man's variant (plus an additional flag) that
1582 // represents how to replace an NVVM intrinsic with target-generic LLVM IR.
1583 struct SimplifyAction {
1584 // Invariant: At most one of these Optionals has a value.
1585 Optional<Intrinsic::ID> IID;
1586 Optional<Instruction::CastOps> CastOp;
1587 Optional<Instruction::BinaryOps> BinaryOp;
1588 Optional<SpecialCase> Special;
1590 FtzRequirementTy FtzRequirement = FTZ_Any;
1592 SimplifyAction() = default;
1594 SimplifyAction(Intrinsic::ID IID, FtzRequirementTy FtzReq)
1595 : IID(IID), FtzRequirement(FtzReq) {}
1597 // Cast operations don't have anything to do with FTZ, so we skip that
1599 SimplifyAction(Instruction::CastOps CastOp) : CastOp(CastOp) {}
1601 SimplifyAction(Instruction::BinaryOps BinaryOp, FtzRequirementTy FtzReq)
1602 : BinaryOp(BinaryOp), FtzRequirement(FtzReq) {}
1604 SimplifyAction(SpecialCase Special, FtzRequirementTy FtzReq)
1605 : Special(Special), FtzRequirement(FtzReq) {}
1608 // Try to generate a SimplifyAction describing how to replace our
1609 // IntrinsicInstr with target-generic LLVM IR.
1610 const SimplifyAction Action = [II]() -> SimplifyAction {
1611 switch (II->getIntrinsicID()) {
1613 // NVVM intrinsics that map directly to LLVM intrinsics.
1614 case Intrinsic::nvvm_ceil_d:
1615 return {Intrinsic::ceil, FTZ_Any};
1616 case Intrinsic::nvvm_ceil_f:
1617 return {Intrinsic::ceil, FTZ_MustBeOff};
1618 case Intrinsic::nvvm_ceil_ftz_f:
1619 return {Intrinsic::ceil, FTZ_MustBeOn};
1620 case Intrinsic::nvvm_fabs_d:
1621 return {Intrinsic::fabs, FTZ_Any};
1622 case Intrinsic::nvvm_fabs_f:
1623 return {Intrinsic::fabs, FTZ_MustBeOff};
1624 case Intrinsic::nvvm_fabs_ftz_f:
1625 return {Intrinsic::fabs, FTZ_MustBeOn};
1626 case Intrinsic::nvvm_floor_d:
1627 return {Intrinsic::floor, FTZ_Any};
1628 case Intrinsic::nvvm_floor_f:
1629 return {Intrinsic::floor, FTZ_MustBeOff};
1630 case Intrinsic::nvvm_floor_ftz_f:
1631 return {Intrinsic::floor, FTZ_MustBeOn};
1632 case Intrinsic::nvvm_fma_rn_d:
1633 return {Intrinsic::fma, FTZ_Any};
1634 case Intrinsic::nvvm_fma_rn_f:
1635 return {Intrinsic::fma, FTZ_MustBeOff};
1636 case Intrinsic::nvvm_fma_rn_ftz_f:
1637 return {Intrinsic::fma, FTZ_MustBeOn};
1638 case Intrinsic::nvvm_fmax_d:
1639 return {Intrinsic::maxnum, FTZ_Any};
1640 case Intrinsic::nvvm_fmax_f:
1641 return {Intrinsic::maxnum, FTZ_MustBeOff};
1642 case Intrinsic::nvvm_fmax_ftz_f:
1643 return {Intrinsic::maxnum, FTZ_MustBeOn};
1644 case Intrinsic::nvvm_fmin_d:
1645 return {Intrinsic::minnum, FTZ_Any};
1646 case Intrinsic::nvvm_fmin_f:
1647 return {Intrinsic::minnum, FTZ_MustBeOff};
1648 case Intrinsic::nvvm_fmin_ftz_f:
1649 return {Intrinsic::minnum, FTZ_MustBeOn};
1650 case Intrinsic::nvvm_round_d:
1651 return {Intrinsic::round, FTZ_Any};
1652 case Intrinsic::nvvm_round_f:
1653 return {Intrinsic::round, FTZ_MustBeOff};
1654 case Intrinsic::nvvm_round_ftz_f:
1655 return {Intrinsic::round, FTZ_MustBeOn};
1656 case Intrinsic::nvvm_sqrt_rn_d:
1657 return {Intrinsic::sqrt, FTZ_Any};
1658 case Intrinsic::nvvm_sqrt_f:
1659 // nvvm_sqrt_f is a special case. For most intrinsics, foo_ftz_f is the
1660 // ftz version, and foo_f is the non-ftz version. But nvvm_sqrt_f adopts
1661 // the ftz-ness of the surrounding code. sqrt_rn_f and sqrt_rn_ftz_f are
1662 // the versions with explicit ftz-ness.
1663 return {Intrinsic::sqrt, FTZ_Any};
1664 case Intrinsic::nvvm_sqrt_rn_f:
1665 return {Intrinsic::sqrt, FTZ_MustBeOff};
1666 case Intrinsic::nvvm_sqrt_rn_ftz_f:
1667 return {Intrinsic::sqrt, FTZ_MustBeOn};
1668 case Intrinsic::nvvm_trunc_d:
1669 return {Intrinsic::trunc, FTZ_Any};
1670 case Intrinsic::nvvm_trunc_f:
1671 return {Intrinsic::trunc, FTZ_MustBeOff};
1672 case Intrinsic::nvvm_trunc_ftz_f:
1673 return {Intrinsic::trunc, FTZ_MustBeOn};
1675 // NVVM intrinsics that map to LLVM cast operations.
1677 // Note that llvm's target-generic conversion operators correspond to the rz
1678 // (round to zero) versions of the nvvm conversion intrinsics, even though
1679 // most everything else here uses the rn (round to nearest even) nvvm ops.
1680 case Intrinsic::nvvm_d2i_rz:
1681 case Intrinsic::nvvm_f2i_rz:
1682 case Intrinsic::nvvm_d2ll_rz:
1683 case Intrinsic::nvvm_f2ll_rz:
1684 return {Instruction::FPToSI};
1685 case Intrinsic::nvvm_d2ui_rz:
1686 case Intrinsic::nvvm_f2ui_rz:
1687 case Intrinsic::nvvm_d2ull_rz:
1688 case Intrinsic::nvvm_f2ull_rz:
1689 return {Instruction::FPToUI};
1690 case Intrinsic::nvvm_i2d_rz:
1691 case Intrinsic::nvvm_i2f_rz:
1692 case Intrinsic::nvvm_ll2d_rz:
1693 case Intrinsic::nvvm_ll2f_rz:
1694 return {Instruction::SIToFP};
1695 case Intrinsic::nvvm_ui2d_rz:
1696 case Intrinsic::nvvm_ui2f_rz:
1697 case Intrinsic::nvvm_ull2d_rz:
1698 case Intrinsic::nvvm_ull2f_rz:
1699 return {Instruction::UIToFP};
1701 // NVVM intrinsics that map to LLVM binary ops.
1702 case Intrinsic::nvvm_add_rn_d:
1703 return {Instruction::FAdd, FTZ_Any};
1704 case Intrinsic::nvvm_add_rn_f:
1705 return {Instruction::FAdd, FTZ_MustBeOff};
1706 case Intrinsic::nvvm_add_rn_ftz_f:
1707 return {Instruction::FAdd, FTZ_MustBeOn};
1708 case Intrinsic::nvvm_mul_rn_d:
1709 return {Instruction::FMul, FTZ_Any};
1710 case Intrinsic::nvvm_mul_rn_f:
1711 return {Instruction::FMul, FTZ_MustBeOff};
1712 case Intrinsic::nvvm_mul_rn_ftz_f:
1713 return {Instruction::FMul, FTZ_MustBeOn};
1714 case Intrinsic::nvvm_div_rn_d:
1715 return {Instruction::FDiv, FTZ_Any};
1716 case Intrinsic::nvvm_div_rn_f:
1717 return {Instruction::FDiv, FTZ_MustBeOff};
1718 case Intrinsic::nvvm_div_rn_ftz_f:
1719 return {Instruction::FDiv, FTZ_MustBeOn};
1721 // The remainder of cases are NVVM intrinsics that map to LLVM idioms, but
1722 // need special handling.
1724 // We seem to be mising intrinsics for rcp.approx.{ftz.}f32, which is just
1726 case Intrinsic::nvvm_rcp_rn_d:
1727 return {SPC_Reciprocal, FTZ_Any};
1728 case Intrinsic::nvvm_rcp_rn_f:
1729 return {SPC_Reciprocal, FTZ_MustBeOff};
1730 case Intrinsic::nvvm_rcp_rn_ftz_f:
1731 return {SPC_Reciprocal, FTZ_MustBeOn};
1733 // We do not currently simplify intrinsics that give an approximate answer.
1736 // - nvvm_cos_approx_{f,ftz_f}
1737 // - nvvm_ex2_approx_{d,f,ftz_f}
1738 // - nvvm_lg2_approx_{d,f,ftz_f}
1739 // - nvvm_sin_approx_{f,ftz_f}
1740 // - nvvm_sqrt_approx_{f,ftz_f}
1741 // - nvvm_rsqrt_approx_{d,f,ftz_f}
1742 // - nvvm_div_approx_{ftz_d,ftz_f,f}
1743 // - nvvm_rcp_approx_ftz_d
1745 // Ideally we'd encode them as e.g. "fast call @llvm.cos", where "fast"
1746 // means that fastmath is enabled in the intrinsic. Unfortunately only
1747 // binary operators (currently) have a fastmath bit in SelectionDAG, so this
1748 // information gets lost and we can't select on it.
1750 // TODO: div and rcp are lowered to a binary op, so these we could in theory
1751 // lower them to "fast fdiv".
1758 // If Action.FtzRequirementTy is not satisfied by the module's ftz state, we
1759 // can bail out now. (Notice that in the case that IID is not an NVVM
1760 // intrinsic, we don't have to look up any module metadata, as
1761 // FtzRequirementTy will be FTZ_Any.)
1762 if (Action.FtzRequirement != FTZ_Any) {
1764 II->getFunction()->getFnAttribute("nvptx-f32ftz").getValueAsString() ==
1767 if (FtzEnabled != (Action.FtzRequirement == FTZ_MustBeOn))
1771 // Simplify to target-generic intrinsic.
1773 SmallVector<Value *, 4> Args(II->arg_operands());
1774 // All the target-generic intrinsics currently of interest to us have one
1775 // type argument, equal to that of the nvvm intrinsic's argument.
1776 Type *Tys[] = {II->getArgOperand(0)->getType()};
1777 return CallInst::Create(
1778 Intrinsic::getDeclaration(II->getModule(), *Action.IID, Tys), Args);
1781 // Simplify to target-generic binary op.
1782 if (Action.BinaryOp)
1783 return BinaryOperator::Create(*Action.BinaryOp, II->getArgOperand(0),
1784 II->getArgOperand(1), II->getName());
1786 // Simplify to target-generic cast op.
1788 return CastInst::Create(*Action.CastOp, II->getArgOperand(0), II->getType(),
1791 // All that's left are the special cases.
1792 if (!Action.Special)
1795 switch (*Action.Special) {
1796 case SPC_Reciprocal:
1797 // Simplify reciprocal.
1798 return BinaryOperator::Create(
1799 Instruction::FDiv, ConstantFP::get(II->getArgOperand(0)->getType(), 1),
1800 II->getArgOperand(0), II->getName());
1802 llvm_unreachable("All SpecialCase enumerators should be handled in switch.");
1805 Instruction *InstCombiner::visitVAStartInst(VAStartInst &I) {
1806 removeTriviallyEmptyRange(I, Intrinsic::vastart, Intrinsic::vaend, *this);
1810 Instruction *InstCombiner::visitVACopyInst(VACopyInst &I) {
1811 removeTriviallyEmptyRange(I, Intrinsic::vacopy, Intrinsic::vaend, *this);
1815 /// CallInst simplification. This mostly only handles folding of intrinsic
1816 /// instructions. For normal calls, it allows visitCallSite to do the heavy
1818 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
1819 auto Args = CI.arg_operands();
1820 if (Value *V = SimplifyCall(CI.getCalledValue(), Args.begin(), Args.end(), DL,
1822 return replaceInstUsesWith(CI, V);
1824 if (isFreeCall(&CI, &TLI))
1825 return visitFree(CI);
1827 // If the caller function is nounwind, mark the call as nounwind, even if the
1829 if (CI.getFunction()->doesNotThrow() && !CI.doesNotThrow()) {
1830 CI.setDoesNotThrow();
1834 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
1835 if (!II) return visitCallSite(&CI);
1837 // Intrinsics cannot occur in an invoke, so handle them here instead of in
1839 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
1840 bool Changed = false;
1842 // memmove/cpy/set of zero bytes is a noop.
1843 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
1844 if (NumBytes->isNullValue())
1845 return eraseInstFromFunction(CI);
1847 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
1848 if (CI->getZExtValue() == 1) {
1849 // Replace the instruction with just byte operations. We would
1850 // transform other cases to loads/stores, but we don't know if
1851 // alignment is sufficient.
1855 // No other transformations apply to volatile transfers.
1856 if (MI->isVolatile())
1859 // If we have a memmove and the source operation is a constant global,
1860 // then the source and dest pointers can't alias, so we can change this
1861 // into a call to memcpy.
1862 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
1863 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
1864 if (GVSrc->isConstant()) {
1865 Module *M = CI.getModule();
1866 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
1867 Type *Tys[3] = { CI.getArgOperand(0)->getType(),
1868 CI.getArgOperand(1)->getType(),
1869 CI.getArgOperand(2)->getType() };
1870 CI.setCalledFunction(Intrinsic::getDeclaration(M, MemCpyID, Tys));
1875 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
1876 // memmove(x,x,size) -> noop.
1877 if (MTI->getSource() == MTI->getDest())
1878 return eraseInstFromFunction(CI);
1881 // If we can determine a pointer alignment that is bigger than currently
1882 // set, update the alignment.
1883 if (isa<MemTransferInst>(MI)) {
1884 if (Instruction *I = SimplifyMemTransfer(MI))
1886 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
1887 if (Instruction *I = SimplifyMemSet(MSI))
1891 if (Changed) return II;
1894 if (auto *AMI = dyn_cast<ElementAtomicMemCpyInst>(II)) {
1895 if (Constant *C = dyn_cast<Constant>(AMI->getNumElements()))
1896 if (C->isNullValue())
1897 return eraseInstFromFunction(*AMI);
1899 if (Instruction *I = SimplifyElementAtomicMemCpy(AMI))
1903 if (Instruction *I = SimplifyNVVMIntrinsic(II, *this))
1906 auto SimplifyDemandedVectorEltsLow = [this](Value *Op, unsigned Width,
1907 unsigned DemandedWidth) {
1908 APInt UndefElts(Width, 0);
1909 APInt DemandedElts = APInt::getLowBitsSet(Width, DemandedWidth);
1910 return SimplifyDemandedVectorElts(Op, DemandedElts, UndefElts);
1913 switch (II->getIntrinsicID()) {
1915 case Intrinsic::objectsize:
1916 if (ConstantInt *N =
1917 lowerObjectSizeCall(II, DL, &TLI, /*MustSucceed=*/false))
1918 return replaceInstUsesWith(CI, N);
1921 case Intrinsic::bswap: {
1922 Value *IIOperand = II->getArgOperand(0);
1925 // bswap(bswap(x)) -> x
1926 if (match(IIOperand, m_BSwap(m_Value(X))))
1927 return replaceInstUsesWith(CI, X);
1929 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
1930 if (match(IIOperand, m_Trunc(m_BSwap(m_Value(X))))) {
1931 unsigned C = X->getType()->getPrimitiveSizeInBits() -
1932 IIOperand->getType()->getPrimitiveSizeInBits();
1933 Value *CV = ConstantInt::get(X->getType(), C);
1934 Value *V = Builder->CreateLShr(X, CV);
1935 return new TruncInst(V, IIOperand->getType());
1940 case Intrinsic::bitreverse: {
1941 Value *IIOperand = II->getArgOperand(0);
1944 // bitreverse(bitreverse(x)) -> x
1945 if (match(IIOperand, m_Intrinsic<Intrinsic::bitreverse>(m_Value(X))))
1946 return replaceInstUsesWith(CI, X);
1950 case Intrinsic::masked_load:
1951 if (Value *SimplifiedMaskedOp = simplifyMaskedLoad(*II, *Builder))
1952 return replaceInstUsesWith(CI, SimplifiedMaskedOp);
1954 case Intrinsic::masked_store:
1955 return simplifyMaskedStore(*II, *this);
1956 case Intrinsic::masked_gather:
1957 return simplifyMaskedGather(*II, *this);
1958 case Intrinsic::masked_scatter:
1959 return simplifyMaskedScatter(*II, *this);
1961 case Intrinsic::powi:
1962 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
1963 // powi(x, 0) -> 1.0
1964 if (Power->isZero())
1965 return replaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
1968 return replaceInstUsesWith(CI, II->getArgOperand(0));
1969 // powi(x, -1) -> 1/x
1970 if (Power->isAllOnesValue())
1971 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
1972 II->getArgOperand(0));
1976 case Intrinsic::cttz:
1977 case Intrinsic::ctlz:
1978 if (auto *I = foldCttzCtlz(*II, *this))
1982 case Intrinsic::uadd_with_overflow:
1983 case Intrinsic::sadd_with_overflow:
1984 case Intrinsic::umul_with_overflow:
1985 case Intrinsic::smul_with_overflow:
1986 if (isa<Constant>(II->getArgOperand(0)) &&
1987 !isa<Constant>(II->getArgOperand(1))) {
1988 // Canonicalize constants into the RHS.
1989 Value *LHS = II->getArgOperand(0);
1990 II->setArgOperand(0, II->getArgOperand(1));
1991 II->setArgOperand(1, LHS);
1996 case Intrinsic::usub_with_overflow:
1997 case Intrinsic::ssub_with_overflow: {
1998 OverflowCheckFlavor OCF =
1999 IntrinsicIDToOverflowCheckFlavor(II->getIntrinsicID());
2000 assert(OCF != OCF_INVALID && "unexpected!");
2002 Value *OperationResult = nullptr;
2003 Constant *OverflowResult = nullptr;
2004 if (OptimizeOverflowCheck(OCF, II->getArgOperand(0), II->getArgOperand(1),
2005 *II, OperationResult, OverflowResult))
2006 return CreateOverflowTuple(II, OperationResult, OverflowResult);
2011 case Intrinsic::minnum:
2012 case Intrinsic::maxnum: {
2013 Value *Arg0 = II->getArgOperand(0);
2014 Value *Arg1 = II->getArgOperand(1);
2015 // Canonicalize constants to the RHS.
2016 if (isa<ConstantFP>(Arg0) && !isa<ConstantFP>(Arg1)) {
2017 II->setArgOperand(0, Arg1);
2018 II->setArgOperand(1, Arg0);
2021 if (Value *V = simplifyMinnumMaxnum(*II))
2022 return replaceInstUsesWith(*II, V);
2025 case Intrinsic::fmuladd: {
2026 // Canonicalize fast fmuladd to the separate fmul + fadd.
2027 if (II->hasUnsafeAlgebra()) {
2028 BuilderTy::FastMathFlagGuard Guard(*Builder);
2029 Builder->setFastMathFlags(II->getFastMathFlags());
2030 Value *Mul = Builder->CreateFMul(II->getArgOperand(0),
2031 II->getArgOperand(1));
2032 Value *Add = Builder->CreateFAdd(Mul, II->getArgOperand(2));
2034 return replaceInstUsesWith(*II, Add);
2039 case Intrinsic::fma: {
2040 Value *Src0 = II->getArgOperand(0);
2041 Value *Src1 = II->getArgOperand(1);
2043 // Canonicalize constants into the RHS.
2044 if (isa<Constant>(Src0) && !isa<Constant>(Src1)) {
2045 II->setArgOperand(0, Src1);
2046 II->setArgOperand(1, Src0);
2047 std::swap(Src0, Src1);
2050 Value *LHS = nullptr;
2051 Value *RHS = nullptr;
2053 // fma fneg(x), fneg(y), z -> fma x, y, z
2054 if (match(Src0, m_FNeg(m_Value(LHS))) &&
2055 match(Src1, m_FNeg(m_Value(RHS)))) {
2056 II->setArgOperand(0, LHS);
2057 II->setArgOperand(1, RHS);
2061 // fma fabs(x), fabs(x), z -> fma x, x, z
2062 if (match(Src0, m_Intrinsic<Intrinsic::fabs>(m_Value(LHS))) &&
2063 match(Src1, m_Intrinsic<Intrinsic::fabs>(m_Value(RHS))) && LHS == RHS) {
2064 II->setArgOperand(0, LHS);
2065 II->setArgOperand(1, RHS);
2069 // fma x, 1, z -> fadd x, z
2070 if (match(Src1, m_FPOne())) {
2071 Instruction *RI = BinaryOperator::CreateFAdd(Src0, II->getArgOperand(2));
2072 RI->copyFastMathFlags(II);
2078 case Intrinsic::fabs: {
2080 Constant *LHS, *RHS;
2081 if (match(II->getArgOperand(0),
2082 m_Select(m_Value(Cond), m_Constant(LHS), m_Constant(RHS)))) {
2083 CallInst *Call0 = Builder->CreateCall(II->getCalledFunction(), {LHS});
2084 CallInst *Call1 = Builder->CreateCall(II->getCalledFunction(), {RHS});
2085 return SelectInst::Create(Cond, Call0, Call1);
2090 case Intrinsic::ceil:
2091 case Intrinsic::floor:
2092 case Intrinsic::round:
2093 case Intrinsic::nearbyint:
2094 case Intrinsic::rint:
2095 case Intrinsic::trunc: {
2097 if (match(II->getArgOperand(0), m_FPExt(m_Value(ExtSrc))) &&
2098 II->getArgOperand(0)->hasOneUse()) {
2099 // fabs (fpext x) -> fpext (fabs x)
2100 Value *F = Intrinsic::getDeclaration(II->getModule(), II->getIntrinsicID(),
2101 { ExtSrc->getType() });
2102 CallInst *NewFabs = Builder->CreateCall(F, ExtSrc);
2103 NewFabs->copyFastMathFlags(II);
2104 NewFabs->takeName(II);
2105 return new FPExtInst(NewFabs, II->getType());
2110 case Intrinsic::cos:
2111 case Intrinsic::amdgcn_cos: {
2113 Value *Src = II->getArgOperand(0);
2114 if (match(Src, m_FNeg(m_Value(SrcSrc))) ||
2115 match(Src, m_Intrinsic<Intrinsic::fabs>(m_Value(SrcSrc)))) {
2116 // cos(-x) -> cos(x)
2117 // cos(fabs(x)) -> cos(x)
2118 II->setArgOperand(0, SrcSrc);
2124 case Intrinsic::ppc_altivec_lvx:
2125 case Intrinsic::ppc_altivec_lvxl:
2126 // Turn PPC lvx -> load if the pointer is known aligned.
2127 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, &AC,
2129 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
2130 PointerType::getUnqual(II->getType()));
2131 return new LoadInst(Ptr);
2134 case Intrinsic::ppc_vsx_lxvw4x:
2135 case Intrinsic::ppc_vsx_lxvd2x: {
2136 // Turn PPC VSX loads into normal loads.
2137 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
2138 PointerType::getUnqual(II->getType()));
2139 return new LoadInst(Ptr, Twine(""), false, 1);
2141 case Intrinsic::ppc_altivec_stvx:
2142 case Intrinsic::ppc_altivec_stvxl:
2143 // Turn stvx -> store if the pointer is known aligned.
2144 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, &AC,
2147 PointerType::getUnqual(II->getArgOperand(0)->getType());
2148 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
2149 return new StoreInst(II->getArgOperand(0), Ptr);
2152 case Intrinsic::ppc_vsx_stxvw4x:
2153 case Intrinsic::ppc_vsx_stxvd2x: {
2154 // Turn PPC VSX stores into normal stores.
2155 Type *OpPtrTy = PointerType::getUnqual(II->getArgOperand(0)->getType());
2156 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
2157 return new StoreInst(II->getArgOperand(0), Ptr, false, 1);
2159 case Intrinsic::ppc_qpx_qvlfs:
2160 // Turn PPC QPX qvlfs -> load if the pointer is known aligned.
2161 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, &AC,
2163 Type *VTy = VectorType::get(Builder->getFloatTy(),
2164 II->getType()->getVectorNumElements());
2165 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
2166 PointerType::getUnqual(VTy));
2167 Value *Load = Builder->CreateLoad(Ptr);
2168 return new FPExtInst(Load, II->getType());
2171 case Intrinsic::ppc_qpx_qvlfd:
2172 // Turn PPC QPX qvlfd -> load if the pointer is known aligned.
2173 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 32, DL, II, &AC,
2175 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
2176 PointerType::getUnqual(II->getType()));
2177 return new LoadInst(Ptr);
2180 case Intrinsic::ppc_qpx_qvstfs:
2181 // Turn PPC QPX qvstfs -> store if the pointer is known aligned.
2182 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, &AC,
2184 Type *VTy = VectorType::get(Builder->getFloatTy(),
2185 II->getArgOperand(0)->getType()->getVectorNumElements());
2186 Value *TOp = Builder->CreateFPTrunc(II->getArgOperand(0), VTy);
2187 Type *OpPtrTy = PointerType::getUnqual(VTy);
2188 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
2189 return new StoreInst(TOp, Ptr);
2192 case Intrinsic::ppc_qpx_qvstfd:
2193 // Turn PPC QPX qvstfd -> store if the pointer is known aligned.
2194 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 32, DL, II, &AC,
2197 PointerType::getUnqual(II->getArgOperand(0)->getType());
2198 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
2199 return new StoreInst(II->getArgOperand(0), Ptr);
2203 case Intrinsic::x86_vcvtph2ps_128:
2204 case Intrinsic::x86_vcvtph2ps_256: {
2205 auto Arg = II->getArgOperand(0);
2206 auto ArgType = cast<VectorType>(Arg->getType());
2207 auto RetType = cast<VectorType>(II->getType());
2208 unsigned ArgWidth = ArgType->getNumElements();
2209 unsigned RetWidth = RetType->getNumElements();
2210 assert(RetWidth <= ArgWidth && "Unexpected input/return vector widths");
2211 assert(ArgType->isIntOrIntVectorTy() &&
2212 ArgType->getScalarSizeInBits() == 16 &&
2213 "CVTPH2PS input type should be 16-bit integer vector");
2214 assert(RetType->getScalarType()->isFloatTy() &&
2215 "CVTPH2PS output type should be 32-bit float vector");
2217 // Constant folding: Convert to generic half to single conversion.
2218 if (isa<ConstantAggregateZero>(Arg))
2219 return replaceInstUsesWith(*II, ConstantAggregateZero::get(RetType));
2221 if (isa<ConstantDataVector>(Arg)) {
2222 auto VectorHalfAsShorts = Arg;
2223 if (RetWidth < ArgWidth) {
2224 SmallVector<uint32_t, 8> SubVecMask;
2225 for (unsigned i = 0; i != RetWidth; ++i)
2226 SubVecMask.push_back((int)i);
2227 VectorHalfAsShorts = Builder->CreateShuffleVector(
2228 Arg, UndefValue::get(ArgType), SubVecMask);
2231 auto VectorHalfType =
2232 VectorType::get(Type::getHalfTy(II->getContext()), RetWidth);
2234 Builder->CreateBitCast(VectorHalfAsShorts, VectorHalfType);
2235 auto VectorFloats = Builder->CreateFPExt(VectorHalfs, RetType);
2236 return replaceInstUsesWith(*II, VectorFloats);
2239 // We only use the lowest lanes of the argument.
2240 if (Value *V = SimplifyDemandedVectorEltsLow(Arg, ArgWidth, RetWidth)) {
2241 II->setArgOperand(0, V);
2247 case Intrinsic::x86_sse_cvtss2si:
2248 case Intrinsic::x86_sse_cvtss2si64:
2249 case Intrinsic::x86_sse_cvttss2si:
2250 case Intrinsic::x86_sse_cvttss2si64:
2251 case Intrinsic::x86_sse2_cvtsd2si:
2252 case Intrinsic::x86_sse2_cvtsd2si64:
2253 case Intrinsic::x86_sse2_cvttsd2si:
2254 case Intrinsic::x86_sse2_cvttsd2si64:
2255 case Intrinsic::x86_avx512_vcvtss2si32:
2256 case Intrinsic::x86_avx512_vcvtss2si64:
2257 case Intrinsic::x86_avx512_vcvtss2usi32:
2258 case Intrinsic::x86_avx512_vcvtss2usi64:
2259 case Intrinsic::x86_avx512_vcvtsd2si32:
2260 case Intrinsic::x86_avx512_vcvtsd2si64:
2261 case Intrinsic::x86_avx512_vcvtsd2usi32:
2262 case Intrinsic::x86_avx512_vcvtsd2usi64:
2263 case Intrinsic::x86_avx512_cvttss2si:
2264 case Intrinsic::x86_avx512_cvttss2si64:
2265 case Intrinsic::x86_avx512_cvttss2usi:
2266 case Intrinsic::x86_avx512_cvttss2usi64:
2267 case Intrinsic::x86_avx512_cvttsd2si:
2268 case Intrinsic::x86_avx512_cvttsd2si64:
2269 case Intrinsic::x86_avx512_cvttsd2usi:
2270 case Intrinsic::x86_avx512_cvttsd2usi64: {
2271 // These intrinsics only demand the 0th element of their input vectors. If
2272 // we can simplify the input based on that, do so now.
2273 Value *Arg = II->getArgOperand(0);
2274 unsigned VWidth = Arg->getType()->getVectorNumElements();
2275 if (Value *V = SimplifyDemandedVectorEltsLow(Arg, VWidth, 1)) {
2276 II->setArgOperand(0, V);
2282 case Intrinsic::x86_mmx_pmovmskb:
2283 case Intrinsic::x86_sse_movmsk_ps:
2284 case Intrinsic::x86_sse2_movmsk_pd:
2285 case Intrinsic::x86_sse2_pmovmskb_128:
2286 case Intrinsic::x86_avx_movmsk_pd_256:
2287 case Intrinsic::x86_avx_movmsk_ps_256:
2288 case Intrinsic::x86_avx2_pmovmskb: {
2289 if (Value *V = simplifyX86movmsk(*II, *Builder))
2290 return replaceInstUsesWith(*II, V);
2294 case Intrinsic::x86_sse_comieq_ss:
2295 case Intrinsic::x86_sse_comige_ss:
2296 case Intrinsic::x86_sse_comigt_ss:
2297 case Intrinsic::x86_sse_comile_ss:
2298 case Intrinsic::x86_sse_comilt_ss:
2299 case Intrinsic::x86_sse_comineq_ss:
2300 case Intrinsic::x86_sse_ucomieq_ss:
2301 case Intrinsic::x86_sse_ucomige_ss:
2302 case Intrinsic::x86_sse_ucomigt_ss:
2303 case Intrinsic::x86_sse_ucomile_ss:
2304 case Intrinsic::x86_sse_ucomilt_ss:
2305 case Intrinsic::x86_sse_ucomineq_ss:
2306 case Intrinsic::x86_sse2_comieq_sd:
2307 case Intrinsic::x86_sse2_comige_sd:
2308 case Intrinsic::x86_sse2_comigt_sd:
2309 case Intrinsic::x86_sse2_comile_sd:
2310 case Intrinsic::x86_sse2_comilt_sd:
2311 case Intrinsic::x86_sse2_comineq_sd:
2312 case Intrinsic::x86_sse2_ucomieq_sd:
2313 case Intrinsic::x86_sse2_ucomige_sd:
2314 case Intrinsic::x86_sse2_ucomigt_sd:
2315 case Intrinsic::x86_sse2_ucomile_sd:
2316 case Intrinsic::x86_sse2_ucomilt_sd:
2317 case Intrinsic::x86_sse2_ucomineq_sd:
2318 case Intrinsic::x86_avx512_vcomi_ss:
2319 case Intrinsic::x86_avx512_vcomi_sd:
2320 case Intrinsic::x86_avx512_mask_cmp_ss:
2321 case Intrinsic::x86_avx512_mask_cmp_sd: {
2322 // These intrinsics only demand the 0th element of their input vectors. If
2323 // we can simplify the input based on that, do so now.
2324 bool MadeChange = false;
2325 Value *Arg0 = II->getArgOperand(0);
2326 Value *Arg1 = II->getArgOperand(1);
2327 unsigned VWidth = Arg0->getType()->getVectorNumElements();
2328 if (Value *V = SimplifyDemandedVectorEltsLow(Arg0, VWidth, 1)) {
2329 II->setArgOperand(0, V);
2332 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, 1)) {
2333 II->setArgOperand(1, V);
2340 case Intrinsic::x86_avx512_mask_cmp_pd_128:
2341 case Intrinsic::x86_avx512_mask_cmp_pd_256:
2342 case Intrinsic::x86_avx512_mask_cmp_pd_512:
2343 case Intrinsic::x86_avx512_mask_cmp_ps_128:
2344 case Intrinsic::x86_avx512_mask_cmp_ps_256:
2345 case Intrinsic::x86_avx512_mask_cmp_ps_512: {
2346 // Folding cmp(sub(a,b),0) -> cmp(a,b) and cmp(0,sub(a,b)) -> cmp(b,a)
2347 Value *Arg0 = II->getArgOperand(0);
2348 Value *Arg1 = II->getArgOperand(1);
2349 bool Arg0IsZero = match(Arg0, m_Zero());
2351 std::swap(Arg0, Arg1);
2353 // This fold requires only the NINF(not +/- inf) since inf minus
2355 // NSZ(No Signed Zeros) is not needed because zeros of any sign are
2356 // equal for both compares.
2357 // NNAN is not needed because nans compare the same for both compares.
2358 // The compare intrinsic uses the above assumptions and therefore
2359 // doesn't require additional flags.
2360 if ((match(Arg0, m_OneUse(m_FSub(m_Value(A), m_Value(B)))) &&
2361 match(Arg1, m_Zero()) &&
2362 cast<Instruction>(Arg0)->getFastMathFlags().noInfs())) {
2365 II->setArgOperand(0, A);
2366 II->setArgOperand(1, B);
2372 case Intrinsic::x86_avx512_mask_add_ps_512:
2373 case Intrinsic::x86_avx512_mask_div_ps_512:
2374 case Intrinsic::x86_avx512_mask_mul_ps_512:
2375 case Intrinsic::x86_avx512_mask_sub_ps_512:
2376 case Intrinsic::x86_avx512_mask_add_pd_512:
2377 case Intrinsic::x86_avx512_mask_div_pd_512:
2378 case Intrinsic::x86_avx512_mask_mul_pd_512:
2379 case Intrinsic::x86_avx512_mask_sub_pd_512:
2380 // If the rounding mode is CUR_DIRECTION(4) we can turn these into regular
2382 if (auto *R = dyn_cast<ConstantInt>(II->getArgOperand(4))) {
2383 if (R->getValue() == 4) {
2384 Value *Arg0 = II->getArgOperand(0);
2385 Value *Arg1 = II->getArgOperand(1);
2388 switch (II->getIntrinsicID()) {
2389 default: llvm_unreachable("Case stmts out of sync!");
2390 case Intrinsic::x86_avx512_mask_add_ps_512:
2391 case Intrinsic::x86_avx512_mask_add_pd_512:
2392 V = Builder->CreateFAdd(Arg0, Arg1);
2394 case Intrinsic::x86_avx512_mask_sub_ps_512:
2395 case Intrinsic::x86_avx512_mask_sub_pd_512:
2396 V = Builder->CreateFSub(Arg0, Arg1);
2398 case Intrinsic::x86_avx512_mask_mul_ps_512:
2399 case Intrinsic::x86_avx512_mask_mul_pd_512:
2400 V = Builder->CreateFMul(Arg0, Arg1);
2402 case Intrinsic::x86_avx512_mask_div_ps_512:
2403 case Intrinsic::x86_avx512_mask_div_pd_512:
2404 V = Builder->CreateFDiv(Arg0, Arg1);
2408 // Create a select for the masking.
2409 V = emitX86MaskSelect(II->getArgOperand(3), V, II->getArgOperand(2),
2411 return replaceInstUsesWith(*II, V);
2416 case Intrinsic::x86_avx512_mask_add_ss_round:
2417 case Intrinsic::x86_avx512_mask_div_ss_round:
2418 case Intrinsic::x86_avx512_mask_mul_ss_round:
2419 case Intrinsic::x86_avx512_mask_sub_ss_round:
2420 case Intrinsic::x86_avx512_mask_add_sd_round:
2421 case Intrinsic::x86_avx512_mask_div_sd_round:
2422 case Intrinsic::x86_avx512_mask_mul_sd_round:
2423 case Intrinsic::x86_avx512_mask_sub_sd_round:
2424 // If the rounding mode is CUR_DIRECTION(4) we can turn these into regular
2426 if (auto *R = dyn_cast<ConstantInt>(II->getArgOperand(4))) {
2427 if (R->getValue() == 4) {
2428 // Extract the element as scalars.
2429 Value *Arg0 = II->getArgOperand(0);
2430 Value *Arg1 = II->getArgOperand(1);
2431 Value *LHS = Builder->CreateExtractElement(Arg0, (uint64_t)0);
2432 Value *RHS = Builder->CreateExtractElement(Arg1, (uint64_t)0);
2435 switch (II->getIntrinsicID()) {
2436 default: llvm_unreachable("Case stmts out of sync!");
2437 case Intrinsic::x86_avx512_mask_add_ss_round:
2438 case Intrinsic::x86_avx512_mask_add_sd_round:
2439 V = Builder->CreateFAdd(LHS, RHS);
2441 case Intrinsic::x86_avx512_mask_sub_ss_round:
2442 case Intrinsic::x86_avx512_mask_sub_sd_round:
2443 V = Builder->CreateFSub(LHS, RHS);
2445 case Intrinsic::x86_avx512_mask_mul_ss_round:
2446 case Intrinsic::x86_avx512_mask_mul_sd_round:
2447 V = Builder->CreateFMul(LHS, RHS);
2449 case Intrinsic::x86_avx512_mask_div_ss_round:
2450 case Intrinsic::x86_avx512_mask_div_sd_round:
2451 V = Builder->CreateFDiv(LHS, RHS);
2455 // Handle the masking aspect of the intrinsic.
2456 Value *Mask = II->getArgOperand(3);
2457 auto *C = dyn_cast<ConstantInt>(Mask);
2458 // We don't need a select if we know the mask bit is a 1.
2459 if (!C || !C->getValue()[0]) {
2460 // Cast the mask to an i1 vector and then extract the lowest element.
2461 auto *MaskTy = VectorType::get(Builder->getInt1Ty(),
2462 cast<IntegerType>(Mask->getType())->getBitWidth());
2463 Mask = Builder->CreateBitCast(Mask, MaskTy);
2464 Mask = Builder->CreateExtractElement(Mask, (uint64_t)0);
2465 // Extract the lowest element from the passthru operand.
2466 Value *Passthru = Builder->CreateExtractElement(II->getArgOperand(2),
2468 V = Builder->CreateSelect(Mask, V, Passthru);
2471 // Insert the result back into the original argument 0.
2472 V = Builder->CreateInsertElement(Arg0, V, (uint64_t)0);
2474 return replaceInstUsesWith(*II, V);
2479 // X86 scalar intrinsics simplified with SimplifyDemandedVectorElts.
2480 case Intrinsic::x86_avx512_mask_max_ss_round:
2481 case Intrinsic::x86_avx512_mask_min_ss_round:
2482 case Intrinsic::x86_avx512_mask_max_sd_round:
2483 case Intrinsic::x86_avx512_mask_min_sd_round:
2484 case Intrinsic::x86_avx512_mask_vfmadd_ss:
2485 case Intrinsic::x86_avx512_mask_vfmadd_sd:
2486 case Intrinsic::x86_avx512_maskz_vfmadd_ss:
2487 case Intrinsic::x86_avx512_maskz_vfmadd_sd:
2488 case Intrinsic::x86_avx512_mask3_vfmadd_ss:
2489 case Intrinsic::x86_avx512_mask3_vfmadd_sd:
2490 case Intrinsic::x86_avx512_mask3_vfmsub_ss:
2491 case Intrinsic::x86_avx512_mask3_vfmsub_sd:
2492 case Intrinsic::x86_avx512_mask3_vfnmsub_ss:
2493 case Intrinsic::x86_avx512_mask3_vfnmsub_sd:
2494 case Intrinsic::x86_fma_vfmadd_ss:
2495 case Intrinsic::x86_fma_vfmsub_ss:
2496 case Intrinsic::x86_fma_vfnmadd_ss:
2497 case Intrinsic::x86_fma_vfnmsub_ss:
2498 case Intrinsic::x86_fma_vfmadd_sd:
2499 case Intrinsic::x86_fma_vfmsub_sd:
2500 case Intrinsic::x86_fma_vfnmadd_sd:
2501 case Intrinsic::x86_fma_vfnmsub_sd:
2502 case Intrinsic::x86_sse_cmp_ss:
2503 case Intrinsic::x86_sse_min_ss:
2504 case Intrinsic::x86_sse_max_ss:
2505 case Intrinsic::x86_sse2_cmp_sd:
2506 case Intrinsic::x86_sse2_min_sd:
2507 case Intrinsic::x86_sse2_max_sd:
2508 case Intrinsic::x86_sse41_round_ss:
2509 case Intrinsic::x86_sse41_round_sd:
2510 case Intrinsic::x86_xop_vfrcz_ss:
2511 case Intrinsic::x86_xop_vfrcz_sd: {
2512 unsigned VWidth = II->getType()->getVectorNumElements();
2513 APInt UndefElts(VWidth, 0);
2514 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
2515 if (Value *V = SimplifyDemandedVectorElts(II, AllOnesEltMask, UndefElts)) {
2517 return replaceInstUsesWith(*II, V);
2523 // Constant fold ashr( <A x Bi>, Ci ).
2524 // Constant fold lshr( <A x Bi>, Ci ).
2525 // Constant fold shl( <A x Bi>, Ci ).
2526 case Intrinsic::x86_sse2_psrai_d:
2527 case Intrinsic::x86_sse2_psrai_w:
2528 case Intrinsic::x86_avx2_psrai_d:
2529 case Intrinsic::x86_avx2_psrai_w:
2530 case Intrinsic::x86_avx512_psrai_q_128:
2531 case Intrinsic::x86_avx512_psrai_q_256:
2532 case Intrinsic::x86_avx512_psrai_d_512:
2533 case Intrinsic::x86_avx512_psrai_q_512:
2534 case Intrinsic::x86_avx512_psrai_w_512:
2535 case Intrinsic::x86_sse2_psrli_d:
2536 case Intrinsic::x86_sse2_psrli_q:
2537 case Intrinsic::x86_sse2_psrli_w:
2538 case Intrinsic::x86_avx2_psrli_d:
2539 case Intrinsic::x86_avx2_psrli_q:
2540 case Intrinsic::x86_avx2_psrli_w:
2541 case Intrinsic::x86_avx512_psrli_d_512:
2542 case Intrinsic::x86_avx512_psrli_q_512:
2543 case Intrinsic::x86_avx512_psrli_w_512:
2544 case Intrinsic::x86_sse2_pslli_d:
2545 case Intrinsic::x86_sse2_pslli_q:
2546 case Intrinsic::x86_sse2_pslli_w:
2547 case Intrinsic::x86_avx2_pslli_d:
2548 case Intrinsic::x86_avx2_pslli_q:
2549 case Intrinsic::x86_avx2_pslli_w:
2550 case Intrinsic::x86_avx512_pslli_d_512:
2551 case Intrinsic::x86_avx512_pslli_q_512:
2552 case Intrinsic::x86_avx512_pslli_w_512:
2553 if (Value *V = simplifyX86immShift(*II, *Builder))
2554 return replaceInstUsesWith(*II, V);
2557 case Intrinsic::x86_sse2_psra_d:
2558 case Intrinsic::x86_sse2_psra_w:
2559 case Intrinsic::x86_avx2_psra_d:
2560 case Intrinsic::x86_avx2_psra_w:
2561 case Intrinsic::x86_avx512_psra_q_128:
2562 case Intrinsic::x86_avx512_psra_q_256:
2563 case Intrinsic::x86_avx512_psra_d_512:
2564 case Intrinsic::x86_avx512_psra_q_512:
2565 case Intrinsic::x86_avx512_psra_w_512:
2566 case Intrinsic::x86_sse2_psrl_d:
2567 case Intrinsic::x86_sse2_psrl_q:
2568 case Intrinsic::x86_sse2_psrl_w:
2569 case Intrinsic::x86_avx2_psrl_d:
2570 case Intrinsic::x86_avx2_psrl_q:
2571 case Intrinsic::x86_avx2_psrl_w:
2572 case Intrinsic::x86_avx512_psrl_d_512:
2573 case Intrinsic::x86_avx512_psrl_q_512:
2574 case Intrinsic::x86_avx512_psrl_w_512:
2575 case Intrinsic::x86_sse2_psll_d:
2576 case Intrinsic::x86_sse2_psll_q:
2577 case Intrinsic::x86_sse2_psll_w:
2578 case Intrinsic::x86_avx2_psll_d:
2579 case Intrinsic::x86_avx2_psll_q:
2580 case Intrinsic::x86_avx2_psll_w:
2581 case Intrinsic::x86_avx512_psll_d_512:
2582 case Intrinsic::x86_avx512_psll_q_512:
2583 case Intrinsic::x86_avx512_psll_w_512: {
2584 if (Value *V = simplifyX86immShift(*II, *Builder))
2585 return replaceInstUsesWith(*II, V);
2587 // SSE2/AVX2 uses only the first 64-bits of the 128-bit vector
2588 // operand to compute the shift amount.
2589 Value *Arg1 = II->getArgOperand(1);
2590 assert(Arg1->getType()->getPrimitiveSizeInBits() == 128 &&
2591 "Unexpected packed shift size");
2592 unsigned VWidth = Arg1->getType()->getVectorNumElements();
2594 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, VWidth / 2)) {
2595 II->setArgOperand(1, V);
2601 case Intrinsic::x86_avx2_psllv_d:
2602 case Intrinsic::x86_avx2_psllv_d_256:
2603 case Intrinsic::x86_avx2_psllv_q:
2604 case Intrinsic::x86_avx2_psllv_q_256:
2605 case Intrinsic::x86_avx512_psllv_d_512:
2606 case Intrinsic::x86_avx512_psllv_q_512:
2607 case Intrinsic::x86_avx512_psllv_w_128:
2608 case Intrinsic::x86_avx512_psllv_w_256:
2609 case Intrinsic::x86_avx512_psllv_w_512:
2610 case Intrinsic::x86_avx2_psrav_d:
2611 case Intrinsic::x86_avx2_psrav_d_256:
2612 case Intrinsic::x86_avx512_psrav_q_128:
2613 case Intrinsic::x86_avx512_psrav_q_256:
2614 case Intrinsic::x86_avx512_psrav_d_512:
2615 case Intrinsic::x86_avx512_psrav_q_512:
2616 case Intrinsic::x86_avx512_psrav_w_128:
2617 case Intrinsic::x86_avx512_psrav_w_256:
2618 case Intrinsic::x86_avx512_psrav_w_512:
2619 case Intrinsic::x86_avx2_psrlv_d:
2620 case Intrinsic::x86_avx2_psrlv_d_256:
2621 case Intrinsic::x86_avx2_psrlv_q:
2622 case Intrinsic::x86_avx2_psrlv_q_256:
2623 case Intrinsic::x86_avx512_psrlv_d_512:
2624 case Intrinsic::x86_avx512_psrlv_q_512:
2625 case Intrinsic::x86_avx512_psrlv_w_128:
2626 case Intrinsic::x86_avx512_psrlv_w_256:
2627 case Intrinsic::x86_avx512_psrlv_w_512:
2628 if (Value *V = simplifyX86varShift(*II, *Builder))
2629 return replaceInstUsesWith(*II, V);
2632 case Intrinsic::x86_sse2_pmulu_dq:
2633 case Intrinsic::x86_sse41_pmuldq:
2634 case Intrinsic::x86_avx2_pmul_dq:
2635 case Intrinsic::x86_avx2_pmulu_dq:
2636 case Intrinsic::x86_avx512_pmul_dq_512:
2637 case Intrinsic::x86_avx512_pmulu_dq_512: {
2638 if (Value *V = simplifyX86muldq(*II, *Builder))
2639 return replaceInstUsesWith(*II, V);
2641 unsigned VWidth = II->getType()->getVectorNumElements();
2642 APInt UndefElts(VWidth, 0);
2643 APInt DemandedElts = APInt::getAllOnesValue(VWidth);
2644 if (Value *V = SimplifyDemandedVectorElts(II, DemandedElts, UndefElts)) {
2646 return replaceInstUsesWith(*II, V);
2652 case Intrinsic::x86_sse2_packssdw_128:
2653 case Intrinsic::x86_sse2_packsswb_128:
2654 case Intrinsic::x86_avx2_packssdw:
2655 case Intrinsic::x86_avx2_packsswb:
2656 case Intrinsic::x86_avx512_packssdw_512:
2657 case Intrinsic::x86_avx512_packsswb_512:
2658 if (Value *V = simplifyX86pack(*II, *this, *Builder, true))
2659 return replaceInstUsesWith(*II, V);
2662 case Intrinsic::x86_sse2_packuswb_128:
2663 case Intrinsic::x86_sse41_packusdw:
2664 case Intrinsic::x86_avx2_packusdw:
2665 case Intrinsic::x86_avx2_packuswb:
2666 case Intrinsic::x86_avx512_packusdw_512:
2667 case Intrinsic::x86_avx512_packuswb_512:
2668 if (Value *V = simplifyX86pack(*II, *this, *Builder, false))
2669 return replaceInstUsesWith(*II, V);
2672 case Intrinsic::x86_pclmulqdq: {
2673 if (auto *C = dyn_cast<ConstantInt>(II->getArgOperand(2))) {
2674 unsigned Imm = C->getZExtValue();
2676 bool MadeChange = false;
2677 Value *Arg0 = II->getArgOperand(0);
2678 Value *Arg1 = II->getArgOperand(1);
2679 unsigned VWidth = Arg0->getType()->getVectorNumElements();
2680 APInt DemandedElts(VWidth, 0);
2682 APInt UndefElts1(VWidth, 0);
2683 DemandedElts = (Imm & 0x01) ? 2 : 1;
2684 if (Value *V = SimplifyDemandedVectorElts(Arg0, DemandedElts,
2686 II->setArgOperand(0, V);
2690 APInt UndefElts2(VWidth, 0);
2691 DemandedElts = (Imm & 0x10) ? 2 : 1;
2692 if (Value *V = SimplifyDemandedVectorElts(Arg1, DemandedElts,
2694 II->setArgOperand(1, V);
2698 // If both input elements are undef, the result is undef.
2699 if (UndefElts1[(Imm & 0x01) ? 1 : 0] ||
2700 UndefElts2[(Imm & 0x10) ? 1 : 0])
2701 return replaceInstUsesWith(*II,
2702 ConstantAggregateZero::get(II->getType()));
2710 case Intrinsic::x86_sse41_insertps:
2711 if (Value *V = simplifyX86insertps(*II, *Builder))
2712 return replaceInstUsesWith(*II, V);
2715 case Intrinsic::x86_sse4a_extrq: {
2716 Value *Op0 = II->getArgOperand(0);
2717 Value *Op1 = II->getArgOperand(1);
2718 unsigned VWidth0 = Op0->getType()->getVectorNumElements();
2719 unsigned VWidth1 = Op1->getType()->getVectorNumElements();
2720 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
2721 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 &&
2722 VWidth1 == 16 && "Unexpected operand sizes");
2724 // See if we're dealing with constant values.
2725 Constant *C1 = dyn_cast<Constant>(Op1);
2726 ConstantInt *CILength =
2727 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)0))
2729 ConstantInt *CIIndex =
2730 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)1))
2733 // Attempt to simplify to a constant, shuffle vector or EXTRQI call.
2734 if (Value *V = simplifyX86extrq(*II, Op0, CILength, CIIndex, *Builder))
2735 return replaceInstUsesWith(*II, V);
2737 // EXTRQ only uses the lowest 64-bits of the first 128-bit vector
2738 // operands and the lowest 16-bits of the second.
2739 bool MadeChange = false;
2740 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) {
2741 II->setArgOperand(0, V);
2744 if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 2)) {
2745 II->setArgOperand(1, V);
2753 case Intrinsic::x86_sse4a_extrqi: {
2754 // EXTRQI: Extract Length bits starting from Index. Zero pad the remaining
2755 // bits of the lower 64-bits. The upper 64-bits are undefined.
2756 Value *Op0 = II->getArgOperand(0);
2757 unsigned VWidth = Op0->getType()->getVectorNumElements();
2758 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 &&
2759 "Unexpected operand size");
2761 // See if we're dealing with constant values.
2762 ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(1));
2763 ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(2));
2765 // Attempt to simplify to a constant or shuffle vector.
2766 if (Value *V = simplifyX86extrq(*II, Op0, CILength, CIIndex, *Builder))
2767 return replaceInstUsesWith(*II, V);
2769 // EXTRQI only uses the lowest 64-bits of the first 128-bit vector
2771 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) {
2772 II->setArgOperand(0, V);
2778 case Intrinsic::x86_sse4a_insertq: {
2779 Value *Op0 = II->getArgOperand(0);
2780 Value *Op1 = II->getArgOperand(1);
2781 unsigned VWidth = Op0->getType()->getVectorNumElements();
2782 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
2783 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 &&
2784 Op1->getType()->getVectorNumElements() == 2 &&
2785 "Unexpected operand size");
2787 // See if we're dealing with constant values.
2788 Constant *C1 = dyn_cast<Constant>(Op1);
2790 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)1))
2793 // Attempt to simplify to a constant, shuffle vector or INSERTQI call.
2795 const APInt &V11 = CI11->getValue();
2796 APInt Len = V11.zextOrTrunc(6);
2797 APInt Idx = V11.lshr(8).zextOrTrunc(6);
2798 if (Value *V = simplifyX86insertq(*II, Op0, Op1, Len, Idx, *Builder))
2799 return replaceInstUsesWith(*II, V);
2802 // INSERTQ only uses the lowest 64-bits of the first 128-bit vector
2804 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) {
2805 II->setArgOperand(0, V);
2811 case Intrinsic::x86_sse4a_insertqi: {
2812 // INSERTQI: Extract lowest Length bits from lower half of second source and
2813 // insert over first source starting at Index bit. The upper 64-bits are
2815 Value *Op0 = II->getArgOperand(0);
2816 Value *Op1 = II->getArgOperand(1);
2817 unsigned VWidth0 = Op0->getType()->getVectorNumElements();
2818 unsigned VWidth1 = Op1->getType()->getVectorNumElements();
2819 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
2820 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 &&
2821 VWidth1 == 2 && "Unexpected operand sizes");
2823 // See if we're dealing with constant values.
2824 ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(2));
2825 ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(3));
2827 // Attempt to simplify to a constant or shuffle vector.
2828 if (CILength && CIIndex) {
2829 APInt Len = CILength->getValue().zextOrTrunc(6);
2830 APInt Idx = CIIndex->getValue().zextOrTrunc(6);
2831 if (Value *V = simplifyX86insertq(*II, Op0, Op1, Len, Idx, *Builder))
2832 return replaceInstUsesWith(*II, V);
2835 // INSERTQI only uses the lowest 64-bits of the first two 128-bit vector
2837 bool MadeChange = false;
2838 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) {
2839 II->setArgOperand(0, V);
2842 if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 1)) {
2843 II->setArgOperand(1, V);
2851 case Intrinsic::x86_sse41_pblendvb:
2852 case Intrinsic::x86_sse41_blendvps:
2853 case Intrinsic::x86_sse41_blendvpd:
2854 case Intrinsic::x86_avx_blendv_ps_256:
2855 case Intrinsic::x86_avx_blendv_pd_256:
2856 case Intrinsic::x86_avx2_pblendvb: {
2857 // Convert blendv* to vector selects if the mask is constant.
2858 // This optimization is convoluted because the intrinsic is defined as
2859 // getting a vector of floats or doubles for the ps and pd versions.
2860 // FIXME: That should be changed.
2862 Value *Op0 = II->getArgOperand(0);
2863 Value *Op1 = II->getArgOperand(1);
2864 Value *Mask = II->getArgOperand(2);
2866 // fold (blend A, A, Mask) -> A
2868 return replaceInstUsesWith(CI, Op0);
2870 // Zero Mask - select 1st argument.
2871 if (isa<ConstantAggregateZero>(Mask))
2872 return replaceInstUsesWith(CI, Op0);
2874 // Constant Mask - select 1st/2nd argument lane based on top bit of mask.
2875 if (auto *ConstantMask = dyn_cast<ConstantDataVector>(Mask)) {
2876 Constant *NewSelector = getNegativeIsTrueBoolVec(ConstantMask);
2877 return SelectInst::Create(NewSelector, Op1, Op0, "blendv");
2882 case Intrinsic::x86_ssse3_pshuf_b_128:
2883 case Intrinsic::x86_avx2_pshuf_b:
2884 case Intrinsic::x86_avx512_pshuf_b_512:
2885 if (Value *V = simplifyX86pshufb(*II, *Builder))
2886 return replaceInstUsesWith(*II, V);
2889 case Intrinsic::x86_avx_vpermilvar_ps:
2890 case Intrinsic::x86_avx_vpermilvar_ps_256:
2891 case Intrinsic::x86_avx512_vpermilvar_ps_512:
2892 case Intrinsic::x86_avx_vpermilvar_pd:
2893 case Intrinsic::x86_avx_vpermilvar_pd_256:
2894 case Intrinsic::x86_avx512_vpermilvar_pd_512:
2895 if (Value *V = simplifyX86vpermilvar(*II, *Builder))
2896 return replaceInstUsesWith(*II, V);
2899 case Intrinsic::x86_avx2_permd:
2900 case Intrinsic::x86_avx2_permps:
2901 if (Value *V = simplifyX86vpermv(*II, *Builder))
2902 return replaceInstUsesWith(*II, V);
2905 case Intrinsic::x86_avx512_mask_permvar_df_256:
2906 case Intrinsic::x86_avx512_mask_permvar_df_512:
2907 case Intrinsic::x86_avx512_mask_permvar_di_256:
2908 case Intrinsic::x86_avx512_mask_permvar_di_512:
2909 case Intrinsic::x86_avx512_mask_permvar_hi_128:
2910 case Intrinsic::x86_avx512_mask_permvar_hi_256:
2911 case Intrinsic::x86_avx512_mask_permvar_hi_512:
2912 case Intrinsic::x86_avx512_mask_permvar_qi_128:
2913 case Intrinsic::x86_avx512_mask_permvar_qi_256:
2914 case Intrinsic::x86_avx512_mask_permvar_qi_512:
2915 case Intrinsic::x86_avx512_mask_permvar_sf_256:
2916 case Intrinsic::x86_avx512_mask_permvar_sf_512:
2917 case Intrinsic::x86_avx512_mask_permvar_si_256:
2918 case Intrinsic::x86_avx512_mask_permvar_si_512:
2919 if (Value *V = simplifyX86vpermv(*II, *Builder)) {
2920 // We simplified the permuting, now create a select for the masking.
2921 V = emitX86MaskSelect(II->getArgOperand(3), V, II->getArgOperand(2),
2923 return replaceInstUsesWith(*II, V);
2927 case Intrinsic::x86_avx_vperm2f128_pd_256:
2928 case Intrinsic::x86_avx_vperm2f128_ps_256:
2929 case Intrinsic::x86_avx_vperm2f128_si_256:
2930 case Intrinsic::x86_avx2_vperm2i128:
2931 if (Value *V = simplifyX86vperm2(*II, *Builder))
2932 return replaceInstUsesWith(*II, V);
2935 case Intrinsic::x86_avx_maskload_ps:
2936 case Intrinsic::x86_avx_maskload_pd:
2937 case Intrinsic::x86_avx_maskload_ps_256:
2938 case Intrinsic::x86_avx_maskload_pd_256:
2939 case Intrinsic::x86_avx2_maskload_d:
2940 case Intrinsic::x86_avx2_maskload_q:
2941 case Intrinsic::x86_avx2_maskload_d_256:
2942 case Intrinsic::x86_avx2_maskload_q_256:
2943 if (Instruction *I = simplifyX86MaskedLoad(*II, *this))
2947 case Intrinsic::x86_sse2_maskmov_dqu:
2948 case Intrinsic::x86_avx_maskstore_ps:
2949 case Intrinsic::x86_avx_maskstore_pd:
2950 case Intrinsic::x86_avx_maskstore_ps_256:
2951 case Intrinsic::x86_avx_maskstore_pd_256:
2952 case Intrinsic::x86_avx2_maskstore_d:
2953 case Intrinsic::x86_avx2_maskstore_q:
2954 case Intrinsic::x86_avx2_maskstore_d_256:
2955 case Intrinsic::x86_avx2_maskstore_q_256:
2956 if (simplifyX86MaskedStore(*II, *this))
2960 case Intrinsic::x86_xop_vpcomb:
2961 case Intrinsic::x86_xop_vpcomd:
2962 case Intrinsic::x86_xop_vpcomq:
2963 case Intrinsic::x86_xop_vpcomw:
2964 if (Value *V = simplifyX86vpcom(*II, *Builder, true))
2965 return replaceInstUsesWith(*II, V);
2968 case Intrinsic::x86_xop_vpcomub:
2969 case Intrinsic::x86_xop_vpcomud:
2970 case Intrinsic::x86_xop_vpcomuq:
2971 case Intrinsic::x86_xop_vpcomuw:
2972 if (Value *V = simplifyX86vpcom(*II, *Builder, false))
2973 return replaceInstUsesWith(*II, V);
2976 case Intrinsic::ppc_altivec_vperm:
2977 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
2978 // Note that ppc_altivec_vperm has a big-endian bias, so when creating
2979 // a vectorshuffle for little endian, we must undo the transformation
2980 // performed on vec_perm in altivec.h. That is, we must complement
2981 // the permutation mask with respect to 31 and reverse the order of
2983 if (Constant *Mask = dyn_cast<Constant>(II->getArgOperand(2))) {
2984 assert(Mask->getType()->getVectorNumElements() == 16 &&
2985 "Bad type for intrinsic!");
2987 // Check that all of the elements are integer constants or undefs.
2988 bool AllEltsOk = true;
2989 for (unsigned i = 0; i != 16; ++i) {
2990 Constant *Elt = Mask->getAggregateElement(i);
2991 if (!Elt || !(isa<ConstantInt>(Elt) || isa<UndefValue>(Elt))) {
2998 // Cast the input vectors to byte vectors.
2999 Value *Op0 = Builder->CreateBitCast(II->getArgOperand(0),
3001 Value *Op1 = Builder->CreateBitCast(II->getArgOperand(1),
3003 Value *Result = UndefValue::get(Op0->getType());
3005 // Only extract each element once.
3006 Value *ExtractedElts[32];
3007 memset(ExtractedElts, 0, sizeof(ExtractedElts));
3009 for (unsigned i = 0; i != 16; ++i) {
3010 if (isa<UndefValue>(Mask->getAggregateElement(i)))
3013 cast<ConstantInt>(Mask->getAggregateElement(i))->getZExtValue();
3014 Idx &= 31; // Match the hardware behavior.
3015 if (DL.isLittleEndian())
3018 if (!ExtractedElts[Idx]) {
3019 Value *Op0ToUse = (DL.isLittleEndian()) ? Op1 : Op0;
3020 Value *Op1ToUse = (DL.isLittleEndian()) ? Op0 : Op1;
3021 ExtractedElts[Idx] =
3022 Builder->CreateExtractElement(Idx < 16 ? Op0ToUse : Op1ToUse,
3023 Builder->getInt32(Idx&15));
3026 // Insert this value into the result vector.
3027 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
3028 Builder->getInt32(i));
3030 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
3035 case Intrinsic::arm_neon_vld1:
3036 case Intrinsic::arm_neon_vld2:
3037 case Intrinsic::arm_neon_vld3:
3038 case Intrinsic::arm_neon_vld4:
3039 case Intrinsic::arm_neon_vld2lane:
3040 case Intrinsic::arm_neon_vld3lane:
3041 case Intrinsic::arm_neon_vld4lane:
3042 case Intrinsic::arm_neon_vst1:
3043 case Intrinsic::arm_neon_vst2:
3044 case Intrinsic::arm_neon_vst3:
3045 case Intrinsic::arm_neon_vst4:
3046 case Intrinsic::arm_neon_vst2lane:
3047 case Intrinsic::arm_neon_vst3lane:
3048 case Intrinsic::arm_neon_vst4lane: {
3050 getKnownAlignment(II->getArgOperand(0), DL, II, &AC, &DT);
3051 unsigned AlignArg = II->getNumArgOperands() - 1;
3052 ConstantInt *IntrAlign = dyn_cast<ConstantInt>(II->getArgOperand(AlignArg));
3053 if (IntrAlign && IntrAlign->getZExtValue() < MemAlign) {
3054 II->setArgOperand(AlignArg,
3055 ConstantInt::get(Type::getInt32Ty(II->getContext()),
3062 case Intrinsic::arm_neon_vmulls:
3063 case Intrinsic::arm_neon_vmullu:
3064 case Intrinsic::aarch64_neon_smull:
3065 case Intrinsic::aarch64_neon_umull: {
3066 Value *Arg0 = II->getArgOperand(0);
3067 Value *Arg1 = II->getArgOperand(1);
3069 // Handle mul by zero first:
3070 if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) {
3071 return replaceInstUsesWith(CI, ConstantAggregateZero::get(II->getType()));
3074 // Check for constant LHS & RHS - in this case we just simplify.
3075 bool Zext = (II->getIntrinsicID() == Intrinsic::arm_neon_vmullu ||
3076 II->getIntrinsicID() == Intrinsic::aarch64_neon_umull);
3077 VectorType *NewVT = cast<VectorType>(II->getType());
3078 if (Constant *CV0 = dyn_cast<Constant>(Arg0)) {
3079 if (Constant *CV1 = dyn_cast<Constant>(Arg1)) {
3080 CV0 = ConstantExpr::getIntegerCast(CV0, NewVT, /*isSigned=*/!Zext);
3081 CV1 = ConstantExpr::getIntegerCast(CV1, NewVT, /*isSigned=*/!Zext);
3083 return replaceInstUsesWith(CI, ConstantExpr::getMul(CV0, CV1));
3086 // Couldn't simplify - canonicalize constant to the RHS.
3087 std::swap(Arg0, Arg1);
3090 // Handle mul by one:
3091 if (Constant *CV1 = dyn_cast<Constant>(Arg1))
3092 if (ConstantInt *Splat =
3093 dyn_cast_or_null<ConstantInt>(CV1->getSplatValue()))
3095 return CastInst::CreateIntegerCast(Arg0, II->getType(),
3096 /*isSigned=*/!Zext);
3100 case Intrinsic::amdgcn_rcp: {
3101 Value *Src = II->getArgOperand(0);
3103 // TODO: Move to ConstantFolding/InstSimplify?
3104 if (isa<UndefValue>(Src))
3105 return replaceInstUsesWith(CI, Src);
3107 if (const ConstantFP *C = dyn_cast<ConstantFP>(Src)) {
3108 const APFloat &ArgVal = C->getValueAPF();
3109 APFloat Val(ArgVal.getSemantics(), 1.0);
3110 APFloat::opStatus Status = Val.divide(ArgVal,
3111 APFloat::rmNearestTiesToEven);
3112 // Only do this if it was exact and therefore not dependent on the
3114 if (Status == APFloat::opOK)
3115 return replaceInstUsesWith(CI, ConstantFP::get(II->getContext(), Val));
3120 case Intrinsic::amdgcn_rsq: {
3121 Value *Src = II->getArgOperand(0);
3123 // TODO: Move to ConstantFolding/InstSimplify?
3124 if (isa<UndefValue>(Src))
3125 return replaceInstUsesWith(CI, Src);
3128 case Intrinsic::amdgcn_frexp_mant:
3129 case Intrinsic::amdgcn_frexp_exp: {
3130 Value *Src = II->getArgOperand(0);
3131 if (const ConstantFP *C = dyn_cast<ConstantFP>(Src)) {
3133 APFloat Significand = frexp(C->getValueAPF(), Exp,
3134 APFloat::rmNearestTiesToEven);
3136 if (II->getIntrinsicID() == Intrinsic::amdgcn_frexp_mant) {
3137 return replaceInstUsesWith(CI, ConstantFP::get(II->getContext(),
3141 // Match instruction special case behavior.
3142 if (Exp == APFloat::IEK_NaN || Exp == APFloat::IEK_Inf)
3145 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), Exp));
3148 if (isa<UndefValue>(Src))
3149 return replaceInstUsesWith(CI, UndefValue::get(II->getType()));
3153 case Intrinsic::amdgcn_class: {
3155 S_NAN = 1 << 0, // Signaling NaN
3156 Q_NAN = 1 << 1, // Quiet NaN
3157 N_INFINITY = 1 << 2, // Negative infinity
3158 N_NORMAL = 1 << 3, // Negative normal
3159 N_SUBNORMAL = 1 << 4, // Negative subnormal
3160 N_ZERO = 1 << 5, // Negative zero
3161 P_ZERO = 1 << 6, // Positive zero
3162 P_SUBNORMAL = 1 << 7, // Positive subnormal
3163 P_NORMAL = 1 << 8, // Positive normal
3164 P_INFINITY = 1 << 9 // Positive infinity
3167 const uint32_t FullMask = S_NAN | Q_NAN | N_INFINITY | N_NORMAL |
3168 N_SUBNORMAL | N_ZERO | P_ZERO | P_SUBNORMAL | P_NORMAL | P_INFINITY;
3170 Value *Src0 = II->getArgOperand(0);
3171 Value *Src1 = II->getArgOperand(1);
3172 const ConstantInt *CMask = dyn_cast<ConstantInt>(Src1);
3174 if (isa<UndefValue>(Src0))
3175 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
3177 if (isa<UndefValue>(Src1))
3178 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), false));
3182 uint32_t Mask = CMask->getZExtValue();
3184 // If all tests are made, it doesn't matter what the value is.
3185 if ((Mask & FullMask) == FullMask)
3186 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), true));
3188 if ((Mask & FullMask) == 0)
3189 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), false));
3191 if (Mask == (S_NAN | Q_NAN)) {
3192 // Equivalent of isnan. Replace with standard fcmp.
3193 Value *FCmp = Builder->CreateFCmpUNO(Src0, Src0);
3195 return replaceInstUsesWith(*II, FCmp);
3198 const ConstantFP *CVal = dyn_cast<ConstantFP>(Src0);
3200 if (isa<UndefValue>(Src0))
3201 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
3203 // Clamp mask to used bits
3204 if ((Mask & FullMask) != Mask) {
3205 CallInst *NewCall = Builder->CreateCall(II->getCalledFunction(),
3206 { Src0, ConstantInt::get(Src1->getType(), Mask & FullMask) }
3209 NewCall->takeName(II);
3210 return replaceInstUsesWith(*II, NewCall);
3216 const APFloat &Val = CVal->getValueAPF();
3219 ((Mask & S_NAN) && Val.isNaN() && Val.isSignaling()) ||
3220 ((Mask & Q_NAN) && Val.isNaN() && !Val.isSignaling()) ||
3221 ((Mask & N_INFINITY) && Val.isInfinity() && Val.isNegative()) ||
3222 ((Mask & N_NORMAL) && Val.isNormal() && Val.isNegative()) ||
3223 ((Mask & N_SUBNORMAL) && Val.isDenormal() && Val.isNegative()) ||
3224 ((Mask & N_ZERO) && Val.isZero() && Val.isNegative()) ||
3225 ((Mask & P_ZERO) && Val.isZero() && !Val.isNegative()) ||
3226 ((Mask & P_SUBNORMAL) && Val.isDenormal() && !Val.isNegative()) ||
3227 ((Mask & P_NORMAL) && Val.isNormal() && !Val.isNegative()) ||
3228 ((Mask & P_INFINITY) && Val.isInfinity() && !Val.isNegative());
3230 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), Result));
3232 case Intrinsic::amdgcn_cvt_pkrtz: {
3233 Value *Src0 = II->getArgOperand(0);
3234 Value *Src1 = II->getArgOperand(1);
3235 if (const ConstantFP *C0 = dyn_cast<ConstantFP>(Src0)) {
3236 if (const ConstantFP *C1 = dyn_cast<ConstantFP>(Src1)) {
3237 const fltSemantics &HalfSem
3238 = II->getType()->getScalarType()->getFltSemantics();
3240 APFloat Val0 = C0->getValueAPF();
3241 APFloat Val1 = C1->getValueAPF();
3242 Val0.convert(HalfSem, APFloat::rmTowardZero, &LosesInfo);
3243 Val1.convert(HalfSem, APFloat::rmTowardZero, &LosesInfo);
3245 Constant *Folded = ConstantVector::get({
3246 ConstantFP::get(II->getContext(), Val0),
3247 ConstantFP::get(II->getContext(), Val1) });
3248 return replaceInstUsesWith(*II, Folded);
3252 if (isa<UndefValue>(Src0) && isa<UndefValue>(Src1))
3253 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
3257 case Intrinsic::amdgcn_ubfe:
3258 case Intrinsic::amdgcn_sbfe: {
3259 // Decompose simple cases into standard shifts.
3260 Value *Src = II->getArgOperand(0);
3261 if (isa<UndefValue>(Src))
3262 return replaceInstUsesWith(*II, Src);
3265 Type *Ty = II->getType();
3266 unsigned IntSize = Ty->getIntegerBitWidth();
3268 ConstantInt *CWidth = dyn_cast<ConstantInt>(II->getArgOperand(2));
3270 Width = CWidth->getZExtValue();
3271 if ((Width & (IntSize - 1)) == 0)
3272 return replaceInstUsesWith(*II, ConstantInt::getNullValue(Ty));
3274 if (Width >= IntSize) {
3275 // Hardware ignores high bits, so remove those.
3276 II->setArgOperand(2, ConstantInt::get(CWidth->getType(),
3277 Width & (IntSize - 1)));
3283 ConstantInt *COffset = dyn_cast<ConstantInt>(II->getArgOperand(1));
3285 Offset = COffset->getZExtValue();
3286 if (Offset >= IntSize) {
3287 II->setArgOperand(1, ConstantInt::get(COffset->getType(),
3288 Offset & (IntSize - 1)));
3293 bool Signed = II->getIntrinsicID() == Intrinsic::amdgcn_sbfe;
3295 // TODO: Also emit sub if only width is constant.
3296 if (!CWidth && COffset && Offset == 0) {
3297 Constant *KSize = ConstantInt::get(COffset->getType(), IntSize);
3298 Value *ShiftVal = Builder->CreateSub(KSize, II->getArgOperand(2));
3299 ShiftVal = Builder->CreateZExt(ShiftVal, II->getType());
3301 Value *Shl = Builder->CreateShl(Src, ShiftVal);
3302 Value *RightShift = Signed ?
3303 Builder->CreateAShr(Shl, ShiftVal) :
3304 Builder->CreateLShr(Shl, ShiftVal);
3305 RightShift->takeName(II);
3306 return replaceInstUsesWith(*II, RightShift);
3309 if (!CWidth || !COffset)
3312 // TODO: This allows folding to undef when the hardware has specific
3314 if (Offset + Width < IntSize) {
3315 Value *Shl = Builder->CreateShl(Src, IntSize - Offset - Width);
3316 Value *RightShift = Signed ?
3317 Builder->CreateAShr(Shl, IntSize - Width) :
3318 Builder->CreateLShr(Shl, IntSize - Width);
3319 RightShift->takeName(II);
3320 return replaceInstUsesWith(*II, RightShift);
3323 Value *RightShift = Signed ?
3324 Builder->CreateAShr(Src, Offset) :
3325 Builder->CreateLShr(Src, Offset);
3327 RightShift->takeName(II);
3328 return replaceInstUsesWith(*II, RightShift);
3330 case Intrinsic::amdgcn_exp:
3331 case Intrinsic::amdgcn_exp_compr: {
3332 ConstantInt *En = dyn_cast<ConstantInt>(II->getArgOperand(1));
3333 if (!En) // Illegal.
3336 unsigned EnBits = En->getZExtValue();
3338 break; // All inputs enabled.
3340 bool IsCompr = II->getIntrinsicID() == Intrinsic::amdgcn_exp_compr;
3341 bool Changed = false;
3342 for (int I = 0; I < (IsCompr ? 2 : 4); ++I) {
3343 if ((!IsCompr && (EnBits & (1 << I)) == 0) ||
3344 (IsCompr && ((EnBits & (0x3 << (2 * I))) == 0))) {
3345 Value *Src = II->getArgOperand(I + 2);
3346 if (!isa<UndefValue>(Src)) {
3347 II->setArgOperand(I + 2, UndefValue::get(Src->getType()));
3359 case Intrinsic::amdgcn_fmed3: {
3360 // Note this does not preserve proper sNaN behavior if IEEE-mode is enabled
3363 Value *Src0 = II->getArgOperand(0);
3364 Value *Src1 = II->getArgOperand(1);
3365 Value *Src2 = II->getArgOperand(2);
3368 // Canonicalize constants to RHS operands.
3370 // fmed3(c0, x, c1) -> fmed3(x, c0, c1)
3371 if (isa<Constant>(Src0) && !isa<Constant>(Src1)) {
3372 std::swap(Src0, Src1);
3376 if (isa<Constant>(Src1) && !isa<Constant>(Src2)) {
3377 std::swap(Src1, Src2);
3381 if (isa<Constant>(Src0) && !isa<Constant>(Src1)) {
3382 std::swap(Src0, Src1);
3387 II->setArgOperand(0, Src0);
3388 II->setArgOperand(1, Src1);
3389 II->setArgOperand(2, Src2);
3393 if (match(Src2, m_NaN()) || isa<UndefValue>(Src2)) {
3394 CallInst *NewCall = Builder->CreateMinNum(Src0, Src1);
3395 NewCall->copyFastMathFlags(II);
3396 NewCall->takeName(II);
3397 return replaceInstUsesWith(*II, NewCall);
3400 if (const ConstantFP *C0 = dyn_cast<ConstantFP>(Src0)) {
3401 if (const ConstantFP *C1 = dyn_cast<ConstantFP>(Src1)) {
3402 if (const ConstantFP *C2 = dyn_cast<ConstantFP>(Src2)) {
3403 APFloat Result = fmed3AMDGCN(C0->getValueAPF(), C1->getValueAPF(),
3405 return replaceInstUsesWith(*II,
3406 ConstantFP::get(Builder->getContext(), Result));
3413 case Intrinsic::amdgcn_icmp:
3414 case Intrinsic::amdgcn_fcmp: {
3415 const ConstantInt *CC = dyn_cast<ConstantInt>(II->getArgOperand(2));
3419 // Guard against invalid arguments.
3420 int64_t CCVal = CC->getZExtValue();
3421 bool IsInteger = II->getIntrinsicID() == Intrinsic::amdgcn_icmp;
3422 if ((IsInteger && (CCVal < CmpInst::FIRST_ICMP_PREDICATE ||
3423 CCVal > CmpInst::LAST_ICMP_PREDICATE)) ||
3424 (!IsInteger && (CCVal < CmpInst::FIRST_FCMP_PREDICATE ||
3425 CCVal > CmpInst::LAST_FCMP_PREDICATE)))
3428 Value *Src0 = II->getArgOperand(0);
3429 Value *Src1 = II->getArgOperand(1);
3431 if (auto *CSrc0 = dyn_cast<Constant>(Src0)) {
3432 if (auto *CSrc1 = dyn_cast<Constant>(Src1)) {
3433 Constant *CCmp = ConstantExpr::getCompare(CCVal, CSrc0, CSrc1);
3434 return replaceInstUsesWith(*II,
3435 ConstantExpr::getSExt(CCmp, II->getType()));
3438 // Canonicalize constants to RHS.
3439 CmpInst::Predicate SwapPred
3440 = CmpInst::getSwappedPredicate(static_cast<CmpInst::Predicate>(CCVal));
3441 II->setArgOperand(0, Src1);
3442 II->setArgOperand(1, Src0);
3443 II->setArgOperand(2, ConstantInt::get(CC->getType(),
3444 static_cast<int>(SwapPred)));
3448 if (CCVal != CmpInst::ICMP_EQ && CCVal != CmpInst::ICMP_NE)
3451 // Canonicalize compare eq with true value to compare != 0
3452 // llvm.amdgcn.icmp(zext (i1 x), 1, eq)
3453 // -> llvm.amdgcn.icmp(zext (i1 x), 0, ne)
3454 // llvm.amdgcn.icmp(sext (i1 x), -1, eq)
3455 // -> llvm.amdgcn.icmp(sext (i1 x), 0, ne)
3457 if (CCVal == CmpInst::ICMP_EQ &&
3458 ((match(Src1, m_One()) && match(Src0, m_ZExt(m_Value(ExtSrc)))) ||
3459 (match(Src1, m_AllOnes()) && match(Src0, m_SExt(m_Value(ExtSrc))))) &&
3460 ExtSrc->getType()->isIntegerTy(1)) {
3461 II->setArgOperand(1, ConstantInt::getNullValue(Src1->getType()));
3462 II->setArgOperand(2, ConstantInt::get(CC->getType(), CmpInst::ICMP_NE));
3466 CmpInst::Predicate SrcPred;
3470 // Fold compare eq/ne with 0 from a compare result as the predicate to the
3471 // intrinsic. The typical use is a wave vote function in the library, which
3472 // will be fed from a user code condition compared with 0. Fold in the
3473 // redundant compare.
3475 // llvm.amdgcn.icmp([sz]ext ([if]cmp pred a, b), 0, ne)
3476 // -> llvm.amdgcn.[if]cmp(a, b, pred)
3478 // llvm.amdgcn.icmp([sz]ext ([if]cmp pred a, b), 0, eq)
3479 // -> llvm.amdgcn.[if]cmp(a, b, inv pred)
3480 if (match(Src1, m_Zero()) &&
3482 m_ZExtOrSExt(m_Cmp(SrcPred, m_Value(SrcLHS), m_Value(SrcRHS))))) {
3483 if (CCVal == CmpInst::ICMP_EQ)
3484 SrcPred = CmpInst::getInversePredicate(SrcPred);
3486 Intrinsic::ID NewIID = CmpInst::isFPPredicate(SrcPred) ?
3487 Intrinsic::amdgcn_fcmp : Intrinsic::amdgcn_icmp;
3489 Value *NewF = Intrinsic::getDeclaration(II->getModule(), NewIID,
3491 Value *Args[] = { SrcLHS, SrcRHS,
3492 ConstantInt::get(CC->getType(), SrcPred) };
3493 CallInst *NewCall = Builder->CreateCall(NewF, Args);
3494 NewCall->takeName(II);
3495 return replaceInstUsesWith(*II, NewCall);
3500 case Intrinsic::stackrestore: {
3501 // If the save is right next to the restore, remove the restore. This can
3502 // happen when variable allocas are DCE'd.
3503 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
3504 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
3505 if (&*++SS->getIterator() == II)
3506 return eraseInstFromFunction(CI);
3510 // Scan down this block to see if there is another stack restore in the
3511 // same block without an intervening call/alloca.
3512 BasicBlock::iterator BI(II);
3513 TerminatorInst *TI = II->getParent()->getTerminator();
3514 bool CannotRemove = false;
3515 for (++BI; &*BI != TI; ++BI) {
3516 if (isa<AllocaInst>(BI)) {
3517 CannotRemove = true;
3520 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
3521 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
3522 // If there is a stackrestore below this one, remove this one.
3523 if (II->getIntrinsicID() == Intrinsic::stackrestore)
3524 return eraseInstFromFunction(CI);
3526 // Bail if we cross over an intrinsic with side effects, such as
3527 // llvm.stacksave, llvm.read_register, or llvm.setjmp.
3528 if (II->mayHaveSideEffects()) {
3529 CannotRemove = true;
3533 // If we found a non-intrinsic call, we can't remove the stack
3535 CannotRemove = true;
3541 // If the stack restore is in a return, resume, or unwind block and if there
3542 // are no allocas or calls between the restore and the return, nuke the
3544 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI)))
3545 return eraseInstFromFunction(CI);
3548 case Intrinsic::lifetime_start:
3549 // Asan needs to poison memory to detect invalid access which is possible
3550 // even for empty lifetime range.
3551 if (II->getFunction()->hasFnAttribute(Attribute::SanitizeAddress))
3554 if (removeTriviallyEmptyRange(*II, Intrinsic::lifetime_start,
3555 Intrinsic::lifetime_end, *this))
3558 case Intrinsic::assume: {
3559 Value *IIOperand = II->getArgOperand(0);
3560 // Remove an assume if it is immediately followed by an identical assume.
3561 if (match(II->getNextNode(),
3562 m_Intrinsic<Intrinsic::assume>(m_Specific(IIOperand))))
3563 return eraseInstFromFunction(CI);
3565 // Canonicalize assume(a && b) -> assume(a); assume(b);
3566 // Note: New assumption intrinsics created here are registered by
3567 // the InstCombineIRInserter object.
3568 Value *AssumeIntrinsic = II->getCalledValue(), *A, *B;
3569 if (match(IIOperand, m_And(m_Value(A), m_Value(B)))) {
3570 Builder->CreateCall(AssumeIntrinsic, A, II->getName());
3571 Builder->CreateCall(AssumeIntrinsic, B, II->getName());
3572 return eraseInstFromFunction(*II);
3574 // assume(!(a || b)) -> assume(!a); assume(!b);
3575 if (match(IIOperand, m_Not(m_Or(m_Value(A), m_Value(B))))) {
3576 Builder->CreateCall(AssumeIntrinsic, Builder->CreateNot(A),
3578 Builder->CreateCall(AssumeIntrinsic, Builder->CreateNot(B),
3580 return eraseInstFromFunction(*II);
3583 // assume( (load addr) != null ) -> add 'nonnull' metadata to load
3584 // (if assume is valid at the load)
3585 CmpInst::Predicate Pred;
3587 if (match(IIOperand, m_ICmp(Pred, m_Instruction(LHS), m_Zero())) &&
3588 Pred == ICmpInst::ICMP_NE && LHS->getOpcode() == Instruction::Load &&
3589 LHS->getType()->isPointerTy() &&
3590 isValidAssumeForContext(II, LHS, &DT)) {
3591 MDNode *MD = MDNode::get(II->getContext(), None);
3592 LHS->setMetadata(LLVMContext::MD_nonnull, MD);
3593 return eraseInstFromFunction(*II);
3595 // TODO: apply nonnull return attributes to calls and invokes
3596 // TODO: apply range metadata for range check patterns?
3599 // If there is a dominating assume with the same condition as this one,
3600 // then this one is redundant, and should be removed.
3601 APInt KnownZero(1, 0), KnownOne(1, 0);
3602 computeKnownBits(IIOperand, KnownZero, KnownOne, 0, II);
3603 if (KnownOne.isAllOnesValue())
3604 return eraseInstFromFunction(*II);
3606 // Update the cache of affected values for this assumption (we might be
3607 // here because we just simplified the condition).
3608 AC.updateAffectedValues(II);
3611 case Intrinsic::experimental_gc_relocate: {
3612 // Translate facts known about a pointer before relocating into
3613 // facts about the relocate value, while being careful to
3614 // preserve relocation semantics.
3615 Value *DerivedPtr = cast<GCRelocateInst>(II)->getDerivedPtr();
3617 // Remove the relocation if unused, note that this check is required
3618 // to prevent the cases below from looping forever.
3619 if (II->use_empty())
3620 return eraseInstFromFunction(*II);
3622 // Undef is undef, even after relocation.
3623 // TODO: provide a hook for this in GCStrategy. This is clearly legal for
3624 // most practical collectors, but there was discussion in the review thread
3625 // about whether it was legal for all possible collectors.
3626 if (isa<UndefValue>(DerivedPtr))
3627 // Use undef of gc_relocate's type to replace it.
3628 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
3630 if (auto *PT = dyn_cast<PointerType>(II->getType())) {
3631 // The relocation of null will be null for most any collector.
3632 // TODO: provide a hook for this in GCStrategy. There might be some
3633 // weird collector this property does not hold for.
3634 if (isa<ConstantPointerNull>(DerivedPtr))
3635 // Use null-pointer of gc_relocate's type to replace it.
3636 return replaceInstUsesWith(*II, ConstantPointerNull::get(PT));
3638 // isKnownNonNull -> nonnull attribute
3639 if (isKnownNonNullAt(DerivedPtr, II, &DT))
3640 II->addAttribute(AttributeList::ReturnIndex, Attribute::NonNull);
3643 // TODO: bitcast(relocate(p)) -> relocate(bitcast(p))
3644 // Canonicalize on the type from the uses to the defs
3646 // TODO: relocate((gep p, C, C2, ...)) -> gep(relocate(p), C, C2, ...)
3650 case Intrinsic::experimental_guard: {
3651 // Is this guard followed by another guard?
3652 Instruction *NextInst = II->getNextNode();
3653 Value *NextCond = nullptr;
3655 m_Intrinsic<Intrinsic::experimental_guard>(m_Value(NextCond)))) {
3656 Value *CurrCond = II->getArgOperand(0);
3658 // Remove a guard that it is immediately preceded by an identical guard.
3659 if (CurrCond == NextCond)
3660 return eraseInstFromFunction(*NextInst);
3662 // Otherwise canonicalize guard(a); guard(b) -> guard(a & b).
3663 II->setArgOperand(0, Builder->CreateAnd(CurrCond, NextCond));
3664 return eraseInstFromFunction(*NextInst);
3669 return visitCallSite(II);
3672 // Fence instruction simplification
3673 Instruction *InstCombiner::visitFenceInst(FenceInst &FI) {
3674 // Remove identical consecutive fences.
3675 if (auto *NFI = dyn_cast<FenceInst>(FI.getNextNode()))
3676 if (FI.isIdenticalTo(NFI))
3677 return eraseInstFromFunction(FI);
3681 // InvokeInst simplification
3683 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
3684 return visitCallSite(&II);
3687 /// If this cast does not affect the value passed through the varargs area, we
3688 /// can eliminate the use of the cast.
3689 static bool isSafeToEliminateVarargsCast(const CallSite CS,
3690 const DataLayout &DL,
3691 const CastInst *const CI,
3693 if (!CI->isLosslessCast())
3696 // If this is a GC intrinsic, avoid munging types. We need types for
3697 // statepoint reconstruction in SelectionDAG.
3698 // TODO: This is probably something which should be expanded to all
3699 // intrinsics since the entire point of intrinsics is that
3700 // they are understandable by the optimizer.
3701 if (isStatepoint(CS) || isGCRelocate(CS) || isGCResult(CS))
3704 // The size of ByVal or InAlloca arguments is derived from the type, so we
3705 // can't change to a type with a different size. If the size were
3706 // passed explicitly we could avoid this check.
3707 if (!CS.isByValOrInAllocaArgument(ix))
3711 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
3712 Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
3713 if (!SrcTy->isSized() || !DstTy->isSized())
3715 if (DL.getTypeAllocSize(SrcTy) != DL.getTypeAllocSize(DstTy))
3720 Instruction *InstCombiner::tryOptimizeCall(CallInst *CI) {
3721 if (!CI->getCalledFunction()) return nullptr;
3723 auto InstCombineRAUW = [this](Instruction *From, Value *With) {
3724 replaceInstUsesWith(*From, With);
3726 LibCallSimplifier Simplifier(DL, &TLI, InstCombineRAUW);
3727 if (Value *With = Simplifier.optimizeCall(CI)) {
3729 return CI->use_empty() ? CI : replaceInstUsesWith(*CI, With);
3735 static IntrinsicInst *findInitTrampolineFromAlloca(Value *TrampMem) {
3736 // Strip off at most one level of pointer casts, looking for an alloca. This
3737 // is good enough in practice and simpler than handling any number of casts.
3738 Value *Underlying = TrampMem->stripPointerCasts();
3739 if (Underlying != TrampMem &&
3740 (!Underlying->hasOneUse() || Underlying->user_back() != TrampMem))
3742 if (!isa<AllocaInst>(Underlying))
3745 IntrinsicInst *InitTrampoline = nullptr;
3746 for (User *U : TrampMem->users()) {
3747 IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
3750 if (II->getIntrinsicID() == Intrinsic::init_trampoline) {
3752 // More than one init_trampoline writes to this value. Give up.
3754 InitTrampoline = II;
3757 if (II->getIntrinsicID() == Intrinsic::adjust_trampoline)
3758 // Allow any number of calls to adjust.trampoline.
3763 // No call to init.trampoline found.
3764 if (!InitTrampoline)
3767 // Check that the alloca is being used in the expected way.
3768 if (InitTrampoline->getOperand(0) != TrampMem)
3771 return InitTrampoline;
3774 static IntrinsicInst *findInitTrampolineFromBB(IntrinsicInst *AdjustTramp,
3776 // Visit all the previous instructions in the basic block, and try to find a
3777 // init.trampoline which has a direct path to the adjust.trampoline.
3778 for (BasicBlock::iterator I = AdjustTramp->getIterator(),
3779 E = AdjustTramp->getParent()->begin();
3781 Instruction *Inst = &*--I;
3782 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
3783 if (II->getIntrinsicID() == Intrinsic::init_trampoline &&
3784 II->getOperand(0) == TrampMem)
3786 if (Inst->mayWriteToMemory())
3792 // Given a call to llvm.adjust.trampoline, find and return the corresponding
3793 // call to llvm.init.trampoline if the call to the trampoline can be optimized
3794 // to a direct call to a function. Otherwise return NULL.
3796 static IntrinsicInst *findInitTrampoline(Value *Callee) {
3797 Callee = Callee->stripPointerCasts();
3798 IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee);
3800 AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline)
3803 Value *TrampMem = AdjustTramp->getOperand(0);
3805 if (IntrinsicInst *IT = findInitTrampolineFromAlloca(TrampMem))
3807 if (IntrinsicInst *IT = findInitTrampolineFromBB(AdjustTramp, TrampMem))
3812 /// Improvements for call and invoke instructions.
3813 Instruction *InstCombiner::visitCallSite(CallSite CS) {
3814 if (isAllocLikeFn(CS.getInstruction(), &TLI))
3815 return visitAllocSite(*CS.getInstruction());
3817 bool Changed = false;
3819 // Mark any parameters that are known to be non-null with the nonnull
3820 // attribute. This is helpful for inlining calls to functions with null
3821 // checks on their arguments.
3822 SmallVector<unsigned, 4> Indices;
3825 for (Value *V : CS.args()) {
3826 if (V->getType()->isPointerTy() &&
3827 !CS.paramHasAttr(ArgNo, Attribute::NonNull) &&
3828 isKnownNonNullAt(V, CS.getInstruction(), &DT))
3829 Indices.push_back(ArgNo + 1);
3833 assert(ArgNo == CS.arg_size() && "sanity check");
3835 if (!Indices.empty()) {
3836 AttributeList AS = CS.getAttributes();
3837 LLVMContext &Ctx = CS.getInstruction()->getContext();
3838 AS = AS.addAttribute(Ctx, Indices,
3839 Attribute::get(Ctx, Attribute::NonNull));
3840 CS.setAttributes(AS);
3844 // If the callee is a pointer to a function, attempt to move any casts to the
3845 // arguments of the call/invoke.
3846 Value *Callee = CS.getCalledValue();
3847 if (!isa<Function>(Callee) && transformConstExprCastCall(CS))
3850 if (Function *CalleeF = dyn_cast<Function>(Callee)) {
3851 // Remove the convergent attr on calls when the callee is not convergent.
3852 if (CS.isConvergent() && !CalleeF->isConvergent() &&
3853 !CalleeF->isIntrinsic()) {
3854 DEBUG(dbgs() << "Removing convergent attr from instr "
3855 << CS.getInstruction() << "\n");
3856 CS.setNotConvergent();
3857 return CS.getInstruction();
3860 // If the call and callee calling conventions don't match, this call must
3861 // be unreachable, as the call is undefined.
3862 if (CalleeF->getCallingConv() != CS.getCallingConv() &&
3863 // Only do this for calls to a function with a body. A prototype may
3864 // not actually end up matching the implementation's calling conv for a
3865 // variety of reasons (e.g. it may be written in assembly).
3866 !CalleeF->isDeclaration()) {
3867 Instruction *OldCall = CS.getInstruction();
3868 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
3869 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
3871 // If OldCall does not return void then replaceAllUsesWith undef.
3872 // This allows ValueHandlers and custom metadata to adjust itself.
3873 if (!OldCall->getType()->isVoidTy())
3874 replaceInstUsesWith(*OldCall, UndefValue::get(OldCall->getType()));
3875 if (isa<CallInst>(OldCall))
3876 return eraseInstFromFunction(*OldCall);
3878 // We cannot remove an invoke, because it would change the CFG, just
3879 // change the callee to a null pointer.
3880 cast<InvokeInst>(OldCall)->setCalledFunction(
3881 Constant::getNullValue(CalleeF->getType()));
3886 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
3887 // If CS does not return void then replaceAllUsesWith undef.
3888 // This allows ValueHandlers and custom metadata to adjust itself.
3889 if (!CS.getInstruction()->getType()->isVoidTy())
3890 replaceInstUsesWith(*CS.getInstruction(),
3891 UndefValue::get(CS.getInstruction()->getType()));
3893 if (isa<InvokeInst>(CS.getInstruction())) {
3894 // Can't remove an invoke because we cannot change the CFG.
3898 // This instruction is not reachable, just remove it. We insert a store to
3899 // undef so that we know that this code is not reachable, despite the fact
3900 // that we can't modify the CFG here.
3901 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
3902 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
3903 CS.getInstruction());
3905 return eraseInstFromFunction(*CS.getInstruction());
3908 if (IntrinsicInst *II = findInitTrampoline(Callee))
3909 return transformCallThroughTrampoline(CS, II);
3911 PointerType *PTy = cast<PointerType>(Callee->getType());
3912 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
3913 if (FTy->isVarArg()) {
3914 int ix = FTy->getNumParams();
3915 // See if we can optimize any arguments passed through the varargs area of
3917 for (CallSite::arg_iterator I = CS.arg_begin() + FTy->getNumParams(),
3918 E = CS.arg_end(); I != E; ++I, ++ix) {
3919 CastInst *CI = dyn_cast<CastInst>(*I);
3920 if (CI && isSafeToEliminateVarargsCast(CS, DL, CI, ix)) {
3921 *I = CI->getOperand(0);
3927 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
3928 // Inline asm calls cannot throw - mark them 'nounwind'.
3929 CS.setDoesNotThrow();
3933 // Try to optimize the call if possible, we require DataLayout for most of
3934 // this. None of these calls are seen as possibly dead so go ahead and
3935 // delete the instruction now.
3936 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
3937 Instruction *I = tryOptimizeCall(CI);
3938 // If we changed something return the result, etc. Otherwise let
3939 // the fallthrough check.
3940 if (I) return eraseInstFromFunction(*I);
3943 return Changed ? CS.getInstruction() : nullptr;
3946 /// If the callee is a constexpr cast of a function, attempt to move the cast to
3947 /// the arguments of the call/invoke.
3948 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
3949 auto *Callee = dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
3953 // The prototype of a thunk is a lie. Don't directly call such a function.
3954 if (Callee->hasFnAttribute("thunk"))
3957 Instruction *Caller = CS.getInstruction();
3958 const AttributeList &CallerPAL = CS.getAttributes();
3960 // Okay, this is a cast from a function to a different type. Unless doing so
3961 // would cause a type conversion of one of our arguments, change this call to
3962 // be a direct call with arguments casted to the appropriate types.
3964 FunctionType *FT = Callee->getFunctionType();
3965 Type *OldRetTy = Caller->getType();
3966 Type *NewRetTy = FT->getReturnType();
3968 // Check to see if we are changing the return type...
3969 if (OldRetTy != NewRetTy) {
3971 if (NewRetTy->isStructTy())
3972 return false; // TODO: Handle multiple return values.
3974 if (!CastInst::isBitOrNoopPointerCastable(NewRetTy, OldRetTy, DL)) {
3975 if (Callee->isDeclaration())
3976 return false; // Cannot transform this return value.
3978 if (!Caller->use_empty() &&
3979 // void -> non-void is handled specially
3980 !NewRetTy->isVoidTy())
3981 return false; // Cannot transform this return value.
3984 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
3985 AttrBuilder RAttrs(CallerPAL, AttributeList::ReturnIndex);
3986 if (RAttrs.overlaps(AttributeFuncs::typeIncompatible(NewRetTy)))
3987 return false; // Attribute not compatible with transformed value.
3990 // If the callsite is an invoke instruction, and the return value is used by
3991 // a PHI node in a successor, we cannot change the return type of the call
3992 // because there is no place to put the cast instruction (without breaking
3993 // the critical edge). Bail out in this case.
3994 if (!Caller->use_empty())
3995 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
3996 for (User *U : II->users())
3997 if (PHINode *PN = dyn_cast<PHINode>(U))
3998 if (PN->getParent() == II->getNormalDest() ||
3999 PN->getParent() == II->getUnwindDest())
4003 unsigned NumActualArgs = CS.arg_size();
4004 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
4006 // Prevent us turning:
4007 // declare void @takes_i32_inalloca(i32* inalloca)
4008 // call void bitcast (void (i32*)* @takes_i32_inalloca to void (i32)*)(i32 0)
4011 // call void @takes_i32_inalloca(i32* null)
4013 // Similarly, avoid folding away bitcasts of byval calls.
4014 if (Callee->getAttributes().hasAttrSomewhere(Attribute::InAlloca) ||
4015 Callee->getAttributes().hasAttrSomewhere(Attribute::ByVal))
4018 CallSite::arg_iterator AI = CS.arg_begin();
4019 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
4020 Type *ParamTy = FT->getParamType(i);
4021 Type *ActTy = (*AI)->getType();
4023 if (!CastInst::isBitOrNoopPointerCastable(ActTy, ParamTy, DL))
4024 return false; // Cannot transform this parameter value.
4026 if (AttrBuilder(CallerPAL.getParamAttributes(i))
4027 .overlaps(AttributeFuncs::typeIncompatible(ParamTy)))
4028 return false; // Attribute not compatible with transformed value.
4030 if (CS.isInAllocaArgument(i))
4031 return false; // Cannot transform to and from inalloca.
4033 // If the parameter is passed as a byval argument, then we have to have a
4034 // sized type and the sized type has to have the same size as the old type.
4035 if (ParamTy != ActTy && CallerPAL.hasParamAttribute(i, Attribute::ByVal)) {
4036 PointerType *ParamPTy = dyn_cast<PointerType>(ParamTy);
4037 if (!ParamPTy || !ParamPTy->getElementType()->isSized())
4040 Type *CurElTy = ActTy->getPointerElementType();
4041 if (DL.getTypeAllocSize(CurElTy) !=
4042 DL.getTypeAllocSize(ParamPTy->getElementType()))
4047 if (Callee->isDeclaration()) {
4048 // Do not delete arguments unless we have a function body.
4049 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg())
4052 // If the callee is just a declaration, don't change the varargsness of the
4053 // call. We don't want to introduce a varargs call where one doesn't
4055 PointerType *APTy = cast<PointerType>(CS.getCalledValue()->getType());
4056 if (FT->isVarArg()!=cast<FunctionType>(APTy->getElementType())->isVarArg())
4059 // If both the callee and the cast type are varargs, we still have to make
4060 // sure the number of fixed parameters are the same or we have the same
4061 // ABI issues as if we introduce a varargs call.
4062 if (FT->isVarArg() &&
4063 cast<FunctionType>(APTy->getElementType())->isVarArg() &&
4064 FT->getNumParams() !=
4065 cast<FunctionType>(APTy->getElementType())->getNumParams())
4069 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
4070 !CallerPAL.isEmpty())
4071 // In this case we have more arguments than the new function type, but we
4072 // won't be dropping them. Check that these extra arguments have attributes
4073 // that are compatible with being a vararg call argument.
4074 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
4075 unsigned Index = CallerPAL.getSlotIndex(i - 1);
4076 if (Index <= FT->getNumParams())
4079 // Check if it has an attribute that's incompatible with varargs.
4080 AttributeList PAttrs = CallerPAL.getSlotAttributes(i - 1);
4081 if (PAttrs.hasAttribute(Index, Attribute::StructRet))
4086 // Okay, we decided that this is a safe thing to do: go ahead and start
4087 // inserting cast instructions as necessary.
4088 SmallVector<Value *, 8> Args;
4089 SmallVector<AttributeSet, 8> ArgAttrs;
4090 Args.reserve(NumActualArgs);
4091 ArgAttrs.reserve(NumActualArgs);
4093 // Get any return attributes.
4094 AttrBuilder RAttrs(CallerPAL, AttributeList::ReturnIndex);
4096 // If the return value is not being used, the type may not be compatible
4097 // with the existing attributes. Wipe out any problematic attributes.
4098 RAttrs.remove(AttributeFuncs::typeIncompatible(NewRetTy));
4100 AI = CS.arg_begin();
4101 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
4102 Type *ParamTy = FT->getParamType(i);
4104 Value *NewArg = *AI;
4105 if ((*AI)->getType() != ParamTy)
4106 NewArg = Builder->CreateBitOrPointerCast(*AI, ParamTy);
4107 Args.push_back(NewArg);
4109 // Add any parameter attributes.
4110 ArgAttrs.push_back(CallerPAL.getParamAttributes(i));
4113 // If the function takes more arguments than the call was taking, add them
4115 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i) {
4116 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
4117 ArgAttrs.push_back(AttributeSet());
4120 // If we are removing arguments to the function, emit an obnoxious warning.
4121 if (FT->getNumParams() < NumActualArgs) {
4122 // TODO: if (!FT->isVarArg()) this call may be unreachable. PR14722
4123 if (FT->isVarArg()) {
4124 // Add all of the arguments in their promoted form to the arg list.
4125 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
4126 Type *PTy = getPromotedType((*AI)->getType());
4127 Value *NewArg = *AI;
4128 if (PTy != (*AI)->getType()) {
4129 // Must promote to pass through va_arg area!
4130 Instruction::CastOps opcode =
4131 CastInst::getCastOpcode(*AI, false, PTy, false);
4132 NewArg = Builder->CreateCast(opcode, *AI, PTy);
4134 Args.push_back(NewArg);
4136 // Add any parameter attributes.
4137 ArgAttrs.push_back(CallerPAL.getParamAttributes(i));
4142 AttributeSet FnAttrs = CallerPAL.getFnAttributes();
4144 if (NewRetTy->isVoidTy())
4145 Caller->setName(""); // Void type should not have a name.
4147 assert((ArgAttrs.size() == FT->getNumParams() || FT->isVarArg()) &&
4148 "missing argument attributes");
4149 LLVMContext &Ctx = Callee->getContext();
4150 AttributeList NewCallerPAL = AttributeList::get(
4151 Ctx, FnAttrs, AttributeSet::get(Ctx, RAttrs), ArgAttrs);
4153 SmallVector<OperandBundleDef, 1> OpBundles;
4154 CS.getOperandBundlesAsDefs(OpBundles);
4157 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
4158 NewCS = Builder->CreateInvoke(Callee, II->getNormalDest(),
4159 II->getUnwindDest(), Args, OpBundles);
4161 NewCS = Builder->CreateCall(Callee, Args, OpBundles);
4162 cast<CallInst>(NewCS.getInstruction())
4163 ->setTailCallKind(cast<CallInst>(Caller)->getTailCallKind());
4165 NewCS->takeName(Caller);
4166 NewCS.setCallingConv(CS.getCallingConv());
4167 NewCS.setAttributes(NewCallerPAL);
4169 // Preserve the weight metadata for the new call instruction. The metadata
4170 // is used by SamplePGO to check callsite's hotness.
4172 if (Caller->extractProfTotalWeight(W))
4173 NewCS->setProfWeight(W);
4175 // Insert a cast of the return type as necessary.
4176 Instruction *NC = NewCS.getInstruction();
4178 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
4179 if (!NV->getType()->isVoidTy()) {
4180 NV = NC = CastInst::CreateBitOrPointerCast(NC, OldRetTy);
4181 NC->setDebugLoc(Caller->getDebugLoc());
4183 // If this is an invoke instruction, we should insert it after the first
4184 // non-phi, instruction in the normal successor block.
4185 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
4186 BasicBlock::iterator I = II->getNormalDest()->getFirstInsertionPt();
4187 InsertNewInstBefore(NC, *I);
4189 // Otherwise, it's a call, just insert cast right after the call.
4190 InsertNewInstBefore(NC, *Caller);
4192 Worklist.AddUsersToWorkList(*Caller);
4194 NV = UndefValue::get(Caller->getType());
4198 if (!Caller->use_empty())
4199 replaceInstUsesWith(*Caller, NV);
4200 else if (Caller->hasValueHandle()) {
4201 if (OldRetTy == NV->getType())
4202 ValueHandleBase::ValueIsRAUWd(Caller, NV);
4204 // We cannot call ValueIsRAUWd with a different type, and the
4205 // actual tracked value will disappear.
4206 ValueHandleBase::ValueIsDeleted(Caller);
4209 eraseInstFromFunction(*Caller);
4213 /// Turn a call to a function created by init_trampoline / adjust_trampoline
4214 /// intrinsic pair into a direct call to the underlying function.
4216 InstCombiner::transformCallThroughTrampoline(CallSite CS,
4217 IntrinsicInst *Tramp) {
4218 Value *Callee = CS.getCalledValue();
4219 PointerType *PTy = cast<PointerType>(Callee->getType());
4220 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
4221 AttributeList Attrs = CS.getAttributes();
4223 // If the call already has the 'nest' attribute somewhere then give up -
4224 // otherwise 'nest' would occur twice after splicing in the chain.
4225 if (Attrs.hasAttrSomewhere(Attribute::Nest))
4229 "transformCallThroughTrampoline called with incorrect CallSite.");
4231 Function *NestF =cast<Function>(Tramp->getArgOperand(1)->stripPointerCasts());
4232 FunctionType *NestFTy = cast<FunctionType>(NestF->getValueType());
4234 AttributeList NestAttrs = NestF->getAttributes();
4235 if (!NestAttrs.isEmpty()) {
4236 unsigned NestArgNo = 0;
4237 Type *NestTy = nullptr;
4238 AttributeSet NestAttr;
4240 // Look for a parameter marked with the 'nest' attribute.
4241 for (FunctionType::param_iterator I = NestFTy->param_begin(),
4242 E = NestFTy->param_end();
4243 I != E; ++NestArgNo, ++I) {
4244 AttributeSet AS = NestAttrs.getParamAttributes(NestArgNo);
4245 if (AS.hasAttribute(Attribute::Nest)) {
4246 // Record the parameter type and any other attributes.
4254 Instruction *Caller = CS.getInstruction();
4255 std::vector<Value*> NewArgs;
4256 std::vector<AttributeSet> NewArgAttrs;
4257 NewArgs.reserve(CS.arg_size() + 1);
4258 NewArgAttrs.reserve(CS.arg_size());
4260 // Insert the nest argument into the call argument list, which may
4261 // mean appending it. Likewise for attributes.
4265 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
4267 if (ArgNo == NestArgNo) {
4268 // Add the chain argument and attributes.
4269 Value *NestVal = Tramp->getArgOperand(2);
4270 if (NestVal->getType() != NestTy)
4271 NestVal = Builder->CreateBitCast(NestVal, NestTy, "nest");
4272 NewArgs.push_back(NestVal);
4273 NewArgAttrs.push_back(NestAttr);
4279 // Add the original argument and attributes.
4280 NewArgs.push_back(*I);
4281 NewArgAttrs.push_back(Attrs.getParamAttributes(ArgNo));
4288 // The trampoline may have been bitcast to a bogus type (FTy).
4289 // Handle this by synthesizing a new function type, equal to FTy
4290 // with the chain parameter inserted.
4292 std::vector<Type*> NewTypes;
4293 NewTypes.reserve(FTy->getNumParams()+1);
4295 // Insert the chain's type into the list of parameter types, which may
4296 // mean appending it.
4299 FunctionType::param_iterator I = FTy->param_begin(),
4300 E = FTy->param_end();
4303 if (ArgNo == NestArgNo)
4304 // Add the chain's type.
4305 NewTypes.push_back(NestTy);
4310 // Add the original type.
4311 NewTypes.push_back(*I);
4318 // Replace the trampoline call with a direct call. Let the generic
4319 // code sort out any function type mismatches.
4320 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
4322 Constant *NewCallee =
4323 NestF->getType() == PointerType::getUnqual(NewFTy) ?
4324 NestF : ConstantExpr::getBitCast(NestF,
4325 PointerType::getUnqual(NewFTy));
4326 AttributeList NewPAL =
4327 AttributeList::get(FTy->getContext(), Attrs.getFnAttributes(),
4328 Attrs.getRetAttributes(), NewArgAttrs);
4330 SmallVector<OperandBundleDef, 1> OpBundles;
4331 CS.getOperandBundlesAsDefs(OpBundles);
4333 Instruction *NewCaller;
4334 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
4335 NewCaller = InvokeInst::Create(NewCallee,
4336 II->getNormalDest(), II->getUnwindDest(),
4337 NewArgs, OpBundles);
4338 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
4339 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
4341 NewCaller = CallInst::Create(NewCallee, NewArgs, OpBundles);
4342 cast<CallInst>(NewCaller)->setTailCallKind(
4343 cast<CallInst>(Caller)->getTailCallKind());
4344 cast<CallInst>(NewCaller)->setCallingConv(
4345 cast<CallInst>(Caller)->getCallingConv());
4346 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
4353 // Replace the trampoline call with a direct call. Since there is no 'nest'
4354 // parameter, there is no need to adjust the argument list. Let the generic
4355 // code sort out any function type mismatches.
4356 Constant *NewCallee =
4357 NestF->getType() == PTy ? NestF :
4358 ConstantExpr::getBitCast(NestF, PTy);
4359 CS.setCalledFunction(NewCallee);
4360 return CS.getInstruction();