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