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