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