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