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