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