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