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