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