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