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