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/SmallBitVector.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/Twine.h"
26 #include "llvm/Analysis/AliasAnalysis.h"
27 #include "llvm/Analysis/AssumeBundleQueries.h"
28 #include "llvm/Analysis/AssumptionCache.h"
29 #include "llvm/Analysis/InstructionSimplify.h"
30 #include "llvm/Analysis/Loads.h"
31 #include "llvm/Analysis/MemoryBuiltins.h"
32 #include "llvm/Analysis/TargetTransformInfo.h"
33 #include "llvm/Analysis/ValueTracking.h"
34 #include "llvm/Analysis/VectorUtils.h"
35 #include "llvm/IR/Attributes.h"
36 #include "llvm/IR/BasicBlock.h"
37 #include "llvm/IR/Constant.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/DataLayout.h"
40 #include "llvm/IR/DerivedTypes.h"
41 #include "llvm/IR/Function.h"
42 #include "llvm/IR/GlobalVariable.h"
43 #include "llvm/IR/InlineAsm.h"
44 #include "llvm/IR/InstrTypes.h"
45 #include "llvm/IR/Instruction.h"
46 #include "llvm/IR/Instructions.h"
47 #include "llvm/IR/IntrinsicInst.h"
48 #include "llvm/IR/Intrinsics.h"
49 #include "llvm/IR/IntrinsicsAArch64.h"
50 #include "llvm/IR/IntrinsicsAMDGPU.h"
51 #include "llvm/IR/IntrinsicsARM.h"
52 #include "llvm/IR/IntrinsicsHexagon.h"
53 #include "llvm/IR/LLVMContext.h"
54 #include "llvm/IR/Metadata.h"
55 #include "llvm/IR/PatternMatch.h"
56 #include "llvm/IR/Statepoint.h"
57 #include "llvm/IR/Type.h"
58 #include "llvm/IR/User.h"
59 #include "llvm/IR/Value.h"
60 #include "llvm/IR/ValueHandle.h"
61 #include "llvm/Support/AtomicOrdering.h"
62 #include "llvm/Support/Casting.h"
63 #include "llvm/Support/CommandLine.h"
64 #include "llvm/Support/Compiler.h"
65 #include "llvm/Support/Debug.h"
66 #include "llvm/Support/ErrorHandling.h"
67 #include "llvm/Support/KnownBits.h"
68 #include "llvm/Support/MathExtras.h"
69 #include "llvm/Support/raw_ostream.h"
70 #include "llvm/Transforms/InstCombine/InstCombiner.h"
71 #include "llvm/Transforms/Utils/AssumeBundleBuilder.h"
72 #include "llvm/Transforms/Utils/Local.h"
73 #include "llvm/Transforms/Utils/SimplifyLibCalls.h"
74 #include <algorithm>
75 #include <cassert>
76 #include <cstdint>
77 #include <cstring>
78 #include <utility>
79 #include <vector>
80 
81 #define DEBUG_TYPE "instcombine"
82 #include "llvm/Transforms/Utils/InstructionWorklist.h"
83 
84 using namespace llvm;
85 using namespace PatternMatch;
86 
87 STATISTIC(NumSimplified, "Number of library calls simplified");
88 
89 static cl::opt<unsigned> GuardWideningWindow(
90     "instcombine-guard-widening-window",
91     cl::init(3),
92     cl::desc("How wide an instruction window to bypass looking for "
93              "another guard"));
94 
95 namespace llvm {
96 /// enable preservation of attributes in assume like:
97 /// call void @llvm.assume(i1 true) [ "nonnull"(i32* %PTR) ]
98 extern cl::opt<bool> EnableKnowledgeRetention;
99 } // namespace llvm
100 
101 /// Return the specified type promoted as it would be to pass though a va_arg
102 /// area.
103 static Type *getPromotedType(Type *Ty) {
104   if (IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
105     if (ITy->getBitWidth() < 32)
106       return Type::getInt32Ty(Ty->getContext());
107   }
108   return Ty;
109 }
110 
111 Instruction *InstCombinerImpl::SimplifyAnyMemTransfer(AnyMemTransferInst *MI) {
112   Align DstAlign = getKnownAlignment(MI->getRawDest(), DL, MI, &AC, &DT);
113   MaybeAlign CopyDstAlign = MI->getDestAlign();
114   if (!CopyDstAlign || *CopyDstAlign < DstAlign) {
115     MI->setDestAlignment(DstAlign);
116     return MI;
117   }
118 
119   Align SrcAlign = getKnownAlignment(MI->getRawSource(), DL, MI, &AC, &DT);
120   MaybeAlign CopySrcAlign = MI->getSourceAlign();
121   if (!CopySrcAlign || *CopySrcAlign < SrcAlign) {
122     MI->setSourceAlignment(SrcAlign);
123     return MI;
124   }
125 
126   // If we have a store to a location which is known constant, we can conclude
127   // that the store must be storing the constant value (else the memory
128   // wouldn't be constant), and this must be a noop.
129   if (AA->pointsToConstantMemory(MI->getDest())) {
130     // Set the size of the copy to 0, it will be deleted on the next iteration.
131     MI->setLength(Constant::getNullValue(MI->getLength()->getType()));
132     return MI;
133   }
134 
135   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
136   // load/store.
137   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getLength());
138   if (!MemOpLength) return nullptr;
139 
140   // Source and destination pointer types are always "i8*" for intrinsic.  See
141   // if the size is something we can handle with a single primitive load/store.
142   // A single load+store correctly handles overlapping memory in the memmove
143   // case.
144   uint64_t Size = MemOpLength->getLimitedValue();
145   assert(Size && "0-sized memory transferring should be removed already.");
146 
147   if (Size > 8 || (Size&(Size-1)))
148     return nullptr;  // If not 1/2/4/8 bytes, exit.
149 
150   // If it is an atomic and alignment is less than the size then we will
151   // introduce the unaligned memory access which will be later transformed
152   // into libcall in CodeGen. This is not evident performance gain so disable
153   // it now.
154   if (isa<AtomicMemTransferInst>(MI))
155     if (*CopyDstAlign < Size || *CopySrcAlign < Size)
156       return nullptr;
157 
158   // Use an integer load+store unless we can find something better.
159   unsigned SrcAddrSp =
160     cast<PointerType>(MI->getArgOperand(1)->getType())->getAddressSpace();
161   unsigned DstAddrSp =
162     cast<PointerType>(MI->getArgOperand(0)->getType())->getAddressSpace();
163 
164   IntegerType* IntType = IntegerType::get(MI->getContext(), Size<<3);
165   Type *NewSrcPtrTy = PointerType::get(IntType, SrcAddrSp);
166   Type *NewDstPtrTy = PointerType::get(IntType, DstAddrSp);
167 
168   // If the memcpy has metadata describing the members, see if we can get the
169   // TBAA tag describing our copy.
170   MDNode *CopyMD = nullptr;
171   if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa)) {
172     CopyMD = M;
173   } else if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa_struct)) {
174     if (M->getNumOperands() == 3 && M->getOperand(0) &&
175         mdconst::hasa<ConstantInt>(M->getOperand(0)) &&
176         mdconst::extract<ConstantInt>(M->getOperand(0))->isZero() &&
177         M->getOperand(1) &&
178         mdconst::hasa<ConstantInt>(M->getOperand(1)) &&
179         mdconst::extract<ConstantInt>(M->getOperand(1))->getValue() ==
180         Size &&
181         M->getOperand(2) && isa<MDNode>(M->getOperand(2)))
182       CopyMD = cast<MDNode>(M->getOperand(2));
183   }
184 
185   Value *Src = Builder.CreateBitCast(MI->getArgOperand(1), NewSrcPtrTy);
186   Value *Dest = Builder.CreateBitCast(MI->getArgOperand(0), NewDstPtrTy);
187   LoadInst *L = Builder.CreateLoad(IntType, Src);
188   // Alignment from the mem intrinsic will be better, so use it.
189   L->setAlignment(*CopySrcAlign);
190   if (CopyMD)
191     L->setMetadata(LLVMContext::MD_tbaa, CopyMD);
192   MDNode *LoopMemParallelMD =
193     MI->getMetadata(LLVMContext::MD_mem_parallel_loop_access);
194   if (LoopMemParallelMD)
195     L->setMetadata(LLVMContext::MD_mem_parallel_loop_access, LoopMemParallelMD);
196   MDNode *AccessGroupMD = MI->getMetadata(LLVMContext::MD_access_group);
197   if (AccessGroupMD)
198     L->setMetadata(LLVMContext::MD_access_group, AccessGroupMD);
199 
200   StoreInst *S = Builder.CreateStore(L, Dest);
201   // Alignment from the mem intrinsic will be better, so use it.
202   S->setAlignment(*CopyDstAlign);
203   if (CopyMD)
204     S->setMetadata(LLVMContext::MD_tbaa, CopyMD);
205   if (LoopMemParallelMD)
206     S->setMetadata(LLVMContext::MD_mem_parallel_loop_access, LoopMemParallelMD);
207   if (AccessGroupMD)
208     S->setMetadata(LLVMContext::MD_access_group, AccessGroupMD);
209 
210   if (auto *MT = dyn_cast<MemTransferInst>(MI)) {
211     // non-atomics can be volatile
212     L->setVolatile(MT->isVolatile());
213     S->setVolatile(MT->isVolatile());
214   }
215   if (isa<AtomicMemTransferInst>(MI)) {
216     // atomics have to be unordered
217     L->setOrdering(AtomicOrdering::Unordered);
218     S->setOrdering(AtomicOrdering::Unordered);
219   }
220 
221   // Set the size of the copy to 0, it will be deleted on the next iteration.
222   MI->setLength(Constant::getNullValue(MemOpLength->getType()));
223   return MI;
224 }
225 
226 Instruction *InstCombinerImpl::SimplifyAnyMemSet(AnyMemSetInst *MI) {
227   const Align KnownAlignment =
228       getKnownAlignment(MI->getDest(), DL, MI, &AC, &DT);
229   MaybeAlign MemSetAlign = MI->getDestAlign();
230   if (!MemSetAlign || *MemSetAlign < KnownAlignment) {
231     MI->setDestAlignment(KnownAlignment);
232     return MI;
233   }
234 
235   // If we have a store to a location which is known constant, we can conclude
236   // that the store must be storing the constant value (else the memory
237   // wouldn't be constant), and this must be a noop.
238   if (AA->pointsToConstantMemory(MI->getDest())) {
239     // Set the size of the copy to 0, it will be deleted on the next iteration.
240     MI->setLength(Constant::getNullValue(MI->getLength()->getType()));
241     return MI;
242   }
243 
244   // Extract the length and alignment and fill if they are constant.
245   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
246   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
247   if (!LenC || !FillC || !FillC->getType()->isIntegerTy(8))
248     return nullptr;
249   const uint64_t Len = LenC->getLimitedValue();
250   assert(Len && "0-sized memory setting should be removed already.");
251   const Align Alignment = assumeAligned(MI->getDestAlignment());
252 
253   // If it is an atomic and alignment is less than the size then we will
254   // introduce the unaligned memory access which will be later transformed
255   // into libcall in CodeGen. This is not evident performance gain so disable
256   // it now.
257   if (isa<AtomicMemSetInst>(MI))
258     if (Alignment < Len)
259       return nullptr;
260 
261   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
262   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
263     Type *ITy = IntegerType::get(MI->getContext(), Len*8);  // n=1 -> i8.
264 
265     Value *Dest = MI->getDest();
266     unsigned DstAddrSp = cast<PointerType>(Dest->getType())->getAddressSpace();
267     Type *NewDstPtrTy = PointerType::get(ITy, DstAddrSp);
268     Dest = Builder.CreateBitCast(Dest, NewDstPtrTy);
269 
270     // Extract the fill value and store.
271     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
272     StoreInst *S = Builder.CreateStore(ConstantInt::get(ITy, Fill), Dest,
273                                        MI->isVolatile());
274     S->setAlignment(Alignment);
275     if (isa<AtomicMemSetInst>(MI))
276       S->setOrdering(AtomicOrdering::Unordered);
277 
278     // Set the size of the copy to 0, it will be deleted on the next iteration.
279     MI->setLength(Constant::getNullValue(LenC->getType()));
280     return MI;
281   }
282 
283   return nullptr;
284 }
285 
286 // TODO, Obvious Missing Transforms:
287 // * Narrow width by halfs excluding zero/undef lanes
288 Value *InstCombinerImpl::simplifyMaskedLoad(IntrinsicInst &II) {
289   Value *LoadPtr = II.getArgOperand(0);
290   const Align Alignment =
291       cast<ConstantInt>(II.getArgOperand(1))->getAlignValue();
292 
293   // If the mask is all ones or undefs, this is a plain vector load of the 1st
294   // argument.
295   if (maskIsAllOneOrUndef(II.getArgOperand(2))) {
296     LoadInst *L = Builder.CreateAlignedLoad(II.getType(), LoadPtr, Alignment,
297                                             "unmaskedload");
298     L->copyMetadata(II);
299     return L;
300   }
301 
302   // If we can unconditionally load from this address, replace with a
303   // load/select idiom. TODO: use DT for context sensitive query
304   if (isDereferenceablePointer(LoadPtr, II.getType(),
305                                II.getModule()->getDataLayout(), &II, nullptr)) {
306     LoadInst *LI = Builder.CreateAlignedLoad(II.getType(), LoadPtr, Alignment,
307                                              "unmaskedload");
308     LI->copyMetadata(II);
309     return Builder.CreateSelect(II.getArgOperand(2), LI, II.getArgOperand(3));
310   }
311 
312   return nullptr;
313 }
314 
315 // TODO, Obvious Missing Transforms:
316 // * Single constant active lane -> store
317 // * Narrow width by halfs excluding zero/undef lanes
318 Instruction *InstCombinerImpl::simplifyMaskedStore(IntrinsicInst &II) {
319   auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
320   if (!ConstMask)
321     return nullptr;
322 
323   // If the mask is all zeros, this instruction does nothing.
324   if (ConstMask->isNullValue())
325     return eraseInstFromFunction(II);
326 
327   // If the mask is all ones, this is a plain vector store of the 1st argument.
328   if (ConstMask->isAllOnesValue()) {
329     Value *StorePtr = II.getArgOperand(1);
330     Align Alignment = cast<ConstantInt>(II.getArgOperand(2))->getAlignValue();
331     StoreInst *S =
332         new StoreInst(II.getArgOperand(0), StorePtr, false, Alignment);
333     S->copyMetadata(II);
334     return S;
335   }
336 
337   if (isa<ScalableVectorType>(ConstMask->getType()))
338     return nullptr;
339 
340   // Use masked off lanes to simplify operands via SimplifyDemandedVectorElts
341   APInt DemandedElts = possiblyDemandedEltsInMask(ConstMask);
342   APInt UndefElts(DemandedElts.getBitWidth(), 0);
343   if (Value *V =
344           SimplifyDemandedVectorElts(II.getOperand(0), DemandedElts, UndefElts))
345     return replaceOperand(II, 0, V);
346 
347   return nullptr;
348 }
349 
350 // TODO, Obvious Missing Transforms:
351 // * Single constant active lane load -> load
352 // * Dereferenceable address & few lanes -> scalarize speculative load/selects
353 // * Adjacent vector addresses -> masked.load
354 // * Narrow width by halfs excluding zero/undef lanes
355 // * Vector incrementing address -> vector masked load
356 Instruction *InstCombinerImpl::simplifyMaskedGather(IntrinsicInst &II) {
357   auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(2));
358   if (!ConstMask)
359     return nullptr;
360 
361   // Vector splat address w/known mask -> scalar load
362   // Fold the gather to load the source vector first lane
363   // because it is reloading the same value each time
364   if (ConstMask->isAllOnesValue())
365     if (auto *SplatPtr = getSplatValue(II.getArgOperand(0))) {
366       auto *VecTy = cast<VectorType>(II.getType());
367       const Align Alignment =
368           cast<ConstantInt>(II.getArgOperand(1))->getAlignValue();
369       LoadInst *L = Builder.CreateAlignedLoad(VecTy->getElementType(), SplatPtr,
370                                               Alignment, "load.scalar");
371       Value *Shuf =
372           Builder.CreateVectorSplat(VecTy->getElementCount(), L, "broadcast");
373       return replaceInstUsesWith(II, cast<Instruction>(Shuf));
374     }
375 
376   return nullptr;
377 }
378 
379 // TODO, Obvious Missing Transforms:
380 // * Single constant active lane -> store
381 // * Adjacent vector addresses -> masked.store
382 // * Narrow store width by halfs excluding zero/undef lanes
383 // * Vector incrementing address -> vector masked store
384 Instruction *InstCombinerImpl::simplifyMaskedScatter(IntrinsicInst &II) {
385   auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
386   if (!ConstMask)
387     return nullptr;
388 
389   // If the mask is all zeros, a scatter does nothing.
390   if (ConstMask->isNullValue())
391     return eraseInstFromFunction(II);
392 
393   // Vector splat address -> scalar store
394   if (auto *SplatPtr = getSplatValue(II.getArgOperand(1))) {
395     // scatter(splat(value), splat(ptr), non-zero-mask) -> store value, ptr
396     if (auto *SplatValue = getSplatValue(II.getArgOperand(0))) {
397       Align Alignment = cast<ConstantInt>(II.getArgOperand(2))->getAlignValue();
398       StoreInst *S =
399           new StoreInst(SplatValue, SplatPtr, /*IsVolatile=*/false, Alignment);
400       S->copyMetadata(II);
401       return S;
402     }
403     // scatter(vector, splat(ptr), splat(true)) -> store extract(vector,
404     // lastlane), ptr
405     if (ConstMask->isAllOnesValue()) {
406       Align Alignment = cast<ConstantInt>(II.getArgOperand(2))->getAlignValue();
407       VectorType *WideLoadTy = cast<VectorType>(II.getArgOperand(1)->getType());
408       ElementCount VF = WideLoadTy->getElementCount();
409       Constant *EC =
410           ConstantInt::get(Builder.getInt32Ty(), VF.getKnownMinValue());
411       Value *RunTimeVF = VF.isScalable() ? Builder.CreateVScale(EC) : EC;
412       Value *LastLane = Builder.CreateSub(RunTimeVF, Builder.getInt32(1));
413       Value *Extract =
414           Builder.CreateExtractElement(II.getArgOperand(0), LastLane);
415       StoreInst *S =
416           new StoreInst(Extract, SplatPtr, /*IsVolatile=*/false, Alignment);
417       S->copyMetadata(II);
418       return S;
419     }
420   }
421   if (isa<ScalableVectorType>(ConstMask->getType()))
422     return nullptr;
423 
424   // Use masked off lanes to simplify operands via SimplifyDemandedVectorElts
425   APInt DemandedElts = possiblyDemandedEltsInMask(ConstMask);
426   APInt UndefElts(DemandedElts.getBitWidth(), 0);
427   if (Value *V =
428           SimplifyDemandedVectorElts(II.getOperand(0), DemandedElts, UndefElts))
429     return replaceOperand(II, 0, V);
430   if (Value *V =
431           SimplifyDemandedVectorElts(II.getOperand(1), DemandedElts, UndefElts))
432     return replaceOperand(II, 1, V);
433 
434   return nullptr;
435 }
436 
437 /// This function transforms launder.invariant.group and strip.invariant.group
438 /// like:
439 /// launder(launder(%x)) -> launder(%x)       (the result is not the argument)
440 /// launder(strip(%x)) -> launder(%x)
441 /// strip(strip(%x)) -> strip(%x)             (the result is not the argument)
442 /// strip(launder(%x)) -> strip(%x)
443 /// This is legal because it preserves the most recent information about
444 /// the presence or absence of invariant.group.
445 static Instruction *simplifyInvariantGroupIntrinsic(IntrinsicInst &II,
446                                                     InstCombinerImpl &IC) {
447   auto *Arg = II.getArgOperand(0);
448   auto *StrippedArg = Arg->stripPointerCasts();
449   auto *StrippedInvariantGroupsArg = StrippedArg;
450   while (auto *Intr = dyn_cast<IntrinsicInst>(StrippedInvariantGroupsArg)) {
451     if (Intr->getIntrinsicID() != Intrinsic::launder_invariant_group &&
452         Intr->getIntrinsicID() != Intrinsic::strip_invariant_group)
453       break;
454     StrippedInvariantGroupsArg = Intr->getArgOperand(0)->stripPointerCasts();
455   }
456   if (StrippedArg == StrippedInvariantGroupsArg)
457     return nullptr; // No launders/strips to remove.
458 
459   Value *Result = nullptr;
460 
461   if (II.getIntrinsicID() == Intrinsic::launder_invariant_group)
462     Result = IC.Builder.CreateLaunderInvariantGroup(StrippedInvariantGroupsArg);
463   else if (II.getIntrinsicID() == Intrinsic::strip_invariant_group)
464     Result = IC.Builder.CreateStripInvariantGroup(StrippedInvariantGroupsArg);
465   else
466     llvm_unreachable(
467         "simplifyInvariantGroupIntrinsic only handles launder and strip");
468   if (Result->getType()->getPointerAddressSpace() !=
469       II.getType()->getPointerAddressSpace())
470     Result = IC.Builder.CreateAddrSpaceCast(Result, II.getType());
471   if (Result->getType() != II.getType())
472     Result = IC.Builder.CreateBitCast(Result, II.getType());
473 
474   return cast<Instruction>(Result);
475 }
476 
477 static Instruction *foldCttzCtlz(IntrinsicInst &II, InstCombinerImpl &IC) {
478   assert((II.getIntrinsicID() == Intrinsic::cttz ||
479           II.getIntrinsicID() == Intrinsic::ctlz) &&
480          "Expected cttz or ctlz intrinsic");
481   bool IsTZ = II.getIntrinsicID() == Intrinsic::cttz;
482   Value *Op0 = II.getArgOperand(0);
483   Value *Op1 = II.getArgOperand(1);
484   Value *X;
485   // ctlz(bitreverse(x)) -> cttz(x)
486   // cttz(bitreverse(x)) -> ctlz(x)
487   if (match(Op0, m_BitReverse(m_Value(X)))) {
488     Intrinsic::ID ID = IsTZ ? Intrinsic::ctlz : Intrinsic::cttz;
489     Function *F = Intrinsic::getDeclaration(II.getModule(), ID, II.getType());
490     return CallInst::Create(F, {X, II.getArgOperand(1)});
491   }
492 
493   if (II.getType()->isIntOrIntVectorTy(1)) {
494     // ctlz/cttz i1 Op0 --> not Op0
495     if (match(Op1, m_Zero()))
496       return BinaryOperator::CreateNot(Op0);
497     // If zero is poison, then the input can be assumed to be "true", so the
498     // instruction simplifies to "false".
499     assert(match(Op1, m_One()) && "Expected ctlz/cttz operand to be 0 or 1");
500     return IC.replaceInstUsesWith(II, ConstantInt::getNullValue(II.getType()));
501   }
502 
503   // If the operand is a select with constant arm(s), try to hoist ctlz/cttz.
504   if (auto *Sel = dyn_cast<SelectInst>(Op0))
505     if (Instruction *R = IC.FoldOpIntoSelect(II, Sel))
506       return R;
507 
508   if (IsTZ) {
509     // cttz(-x) -> cttz(x)
510     if (match(Op0, m_Neg(m_Value(X))))
511       return IC.replaceOperand(II, 0, X);
512 
513     // cttz(sext(x)) -> cttz(zext(x))
514     if (match(Op0, m_OneUse(m_SExt(m_Value(X))))) {
515       auto *Zext = IC.Builder.CreateZExt(X, II.getType());
516       auto *CttzZext =
517           IC.Builder.CreateBinaryIntrinsic(Intrinsic::cttz, Zext, Op1);
518       return IC.replaceInstUsesWith(II, CttzZext);
519     }
520 
521     // Zext doesn't change the number of trailing zeros, so narrow:
522     // cttz(zext(x)) -> zext(cttz(x)) if the 'ZeroIsPoison' parameter is 'true'.
523     if (match(Op0, m_OneUse(m_ZExt(m_Value(X)))) && match(Op1, m_One())) {
524       auto *Cttz = IC.Builder.CreateBinaryIntrinsic(Intrinsic::cttz, X,
525                                                     IC.Builder.getTrue());
526       auto *ZextCttz = IC.Builder.CreateZExt(Cttz, II.getType());
527       return IC.replaceInstUsesWith(II, ZextCttz);
528     }
529 
530     // cttz(abs(x)) -> cttz(x)
531     // cttz(nabs(x)) -> cttz(x)
532     Value *Y;
533     SelectPatternFlavor SPF = matchSelectPattern(Op0, X, Y).Flavor;
534     if (SPF == SPF_ABS || SPF == SPF_NABS)
535       return IC.replaceOperand(II, 0, X);
536 
537     if (match(Op0, m_Intrinsic<Intrinsic::abs>(m_Value(X))))
538       return IC.replaceOperand(II, 0, X);
539   }
540 
541   KnownBits Known = IC.computeKnownBits(Op0, 0, &II);
542 
543   // Create a mask for bits above (ctlz) or below (cttz) the first known one.
544   unsigned PossibleZeros = IsTZ ? Known.countMaxTrailingZeros()
545                                 : Known.countMaxLeadingZeros();
546   unsigned DefiniteZeros = IsTZ ? Known.countMinTrailingZeros()
547                                 : Known.countMinLeadingZeros();
548 
549   // If all bits above (ctlz) or below (cttz) the first known one are known
550   // zero, this value is constant.
551   // FIXME: This should be in InstSimplify because we're replacing an
552   // instruction with a constant.
553   if (PossibleZeros == DefiniteZeros) {
554     auto *C = ConstantInt::get(Op0->getType(), DefiniteZeros);
555     return IC.replaceInstUsesWith(II, C);
556   }
557 
558   // If the input to cttz/ctlz is known to be non-zero,
559   // then change the 'ZeroIsPoison' parameter to 'true'
560   // because we know the zero behavior can't affect the result.
561   if (!Known.One.isZero() ||
562       isKnownNonZero(Op0, IC.getDataLayout(), 0, &IC.getAssumptionCache(), &II,
563                      &IC.getDominatorTree())) {
564     if (!match(II.getArgOperand(1), m_One()))
565       return IC.replaceOperand(II, 1, IC.Builder.getTrue());
566   }
567 
568   // Add range metadata since known bits can't completely reflect what we know.
569   // TODO: Handle splat vectors.
570   auto *IT = dyn_cast<IntegerType>(Op0->getType());
571   if (IT && IT->getBitWidth() != 1 && !II.getMetadata(LLVMContext::MD_range)) {
572     Metadata *LowAndHigh[] = {
573         ConstantAsMetadata::get(ConstantInt::get(IT, DefiniteZeros)),
574         ConstantAsMetadata::get(ConstantInt::get(IT, PossibleZeros + 1))};
575     II.setMetadata(LLVMContext::MD_range,
576                    MDNode::get(II.getContext(), LowAndHigh));
577     return &II;
578   }
579 
580   return nullptr;
581 }
582 
583 static Instruction *foldCtpop(IntrinsicInst &II, InstCombinerImpl &IC) {
584   assert(II.getIntrinsicID() == Intrinsic::ctpop &&
585          "Expected ctpop intrinsic");
586   Type *Ty = II.getType();
587   unsigned BitWidth = Ty->getScalarSizeInBits();
588   Value *Op0 = II.getArgOperand(0);
589   Value *X, *Y;
590 
591   // ctpop(bitreverse(x)) -> ctpop(x)
592   // ctpop(bswap(x)) -> ctpop(x)
593   if (match(Op0, m_BitReverse(m_Value(X))) || match(Op0, m_BSwap(m_Value(X))))
594     return IC.replaceOperand(II, 0, X);
595 
596   // ctpop(rot(x)) -> ctpop(x)
597   if ((match(Op0, m_FShl(m_Value(X), m_Value(Y), m_Value())) ||
598        match(Op0, m_FShr(m_Value(X), m_Value(Y), m_Value()))) &&
599       X == Y)
600     return IC.replaceOperand(II, 0, X);
601 
602   // ctpop(x | -x) -> bitwidth - cttz(x, false)
603   if (Op0->hasOneUse() &&
604       match(Op0, m_c_Or(m_Value(X), m_Neg(m_Deferred(X))))) {
605     Function *F =
606         Intrinsic::getDeclaration(II.getModule(), Intrinsic::cttz, Ty);
607     auto *Cttz = IC.Builder.CreateCall(F, {X, IC.Builder.getFalse()});
608     auto *Bw = ConstantInt::get(Ty, APInt(BitWidth, BitWidth));
609     return IC.replaceInstUsesWith(II, IC.Builder.CreateSub(Bw, Cttz));
610   }
611 
612   // ctpop(~x & (x - 1)) -> cttz(x, false)
613   if (match(Op0,
614             m_c_And(m_Not(m_Value(X)), m_Add(m_Deferred(X), m_AllOnes())))) {
615     Function *F =
616         Intrinsic::getDeclaration(II.getModule(), Intrinsic::cttz, Ty);
617     return CallInst::Create(F, {X, IC.Builder.getFalse()});
618   }
619 
620   // Zext doesn't change the number of set bits, so narrow:
621   // ctpop (zext X) --> zext (ctpop X)
622   if (match(Op0, m_OneUse(m_ZExt(m_Value(X))))) {
623     Value *NarrowPop = IC.Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, X);
624     return CastInst::Create(Instruction::ZExt, NarrowPop, Ty);
625   }
626 
627   // If the operand is a select with constant arm(s), try to hoist ctpop.
628   if (auto *Sel = dyn_cast<SelectInst>(Op0))
629     if (Instruction *R = IC.FoldOpIntoSelect(II, Sel))
630       return R;
631 
632   KnownBits Known(BitWidth);
633   IC.computeKnownBits(Op0, Known, 0, &II);
634 
635   // If all bits are zero except for exactly one fixed bit, then the result
636   // must be 0 or 1, and we can get that answer by shifting to LSB:
637   // ctpop (X & 32) --> (X & 32) >> 5
638   if ((~Known.Zero).isPowerOf2())
639     return BinaryOperator::CreateLShr(
640         Op0, ConstantInt::get(Ty, (~Known.Zero).exactLogBase2()));
641 
642   // FIXME: Try to simplify vectors of integers.
643   auto *IT = dyn_cast<IntegerType>(Ty);
644   if (!IT)
645     return nullptr;
646 
647   // Add range metadata since known bits can't completely reflect what we know.
648   unsigned MinCount = Known.countMinPopulation();
649   unsigned MaxCount = Known.countMaxPopulation();
650   if (IT->getBitWidth() != 1 && !II.getMetadata(LLVMContext::MD_range)) {
651     Metadata *LowAndHigh[] = {
652         ConstantAsMetadata::get(ConstantInt::get(IT, MinCount)),
653         ConstantAsMetadata::get(ConstantInt::get(IT, MaxCount + 1))};
654     II.setMetadata(LLVMContext::MD_range,
655                    MDNode::get(II.getContext(), LowAndHigh));
656     return &II;
657   }
658 
659   return nullptr;
660 }
661 
662 /// Convert a table lookup to shufflevector if the mask is constant.
663 /// This could benefit tbl1 if the mask is { 7,6,5,4,3,2,1,0 }, in
664 /// which case we could lower the shufflevector with rev64 instructions
665 /// as it's actually a byte reverse.
666 static Value *simplifyNeonTbl1(const IntrinsicInst &II,
667                                InstCombiner::BuilderTy &Builder) {
668   // Bail out if the mask is not a constant.
669   auto *C = dyn_cast<Constant>(II.getArgOperand(1));
670   if (!C)
671     return nullptr;
672 
673   auto *VecTy = cast<FixedVectorType>(II.getType());
674   unsigned NumElts = VecTy->getNumElements();
675 
676   // Only perform this transformation for <8 x i8> vector types.
677   if (!VecTy->getElementType()->isIntegerTy(8) || NumElts != 8)
678     return nullptr;
679 
680   int Indexes[8];
681 
682   for (unsigned I = 0; I < NumElts; ++I) {
683     Constant *COp = C->getAggregateElement(I);
684 
685     if (!COp || !isa<ConstantInt>(COp))
686       return nullptr;
687 
688     Indexes[I] = cast<ConstantInt>(COp)->getLimitedValue();
689 
690     // Make sure the mask indices are in range.
691     if ((unsigned)Indexes[I] >= NumElts)
692       return nullptr;
693   }
694 
695   auto *V1 = II.getArgOperand(0);
696   auto *V2 = Constant::getNullValue(V1->getType());
697   return Builder.CreateShuffleVector(V1, V2, makeArrayRef(Indexes));
698 }
699 
700 // Returns true iff the 2 intrinsics have the same operands, limiting the
701 // comparison to the first NumOperands.
702 static bool haveSameOperands(const IntrinsicInst &I, const IntrinsicInst &E,
703                              unsigned NumOperands) {
704   assert(I.arg_size() >= NumOperands && "Not enough operands");
705   assert(E.arg_size() >= NumOperands && "Not enough operands");
706   for (unsigned i = 0; i < NumOperands; i++)
707     if (I.getArgOperand(i) != E.getArgOperand(i))
708       return false;
709   return true;
710 }
711 
712 // Remove trivially empty start/end intrinsic ranges, i.e. a start
713 // immediately followed by an end (ignoring debuginfo or other
714 // start/end intrinsics in between). As this handles only the most trivial
715 // cases, tracking the nesting level is not needed:
716 //
717 //   call @llvm.foo.start(i1 0)
718 //   call @llvm.foo.start(i1 0) ; This one won't be skipped: it will be removed
719 //   call @llvm.foo.end(i1 0)
720 //   call @llvm.foo.end(i1 0) ; &I
721 static bool
722 removeTriviallyEmptyRange(IntrinsicInst &EndI, InstCombinerImpl &IC,
723                           std::function<bool(const IntrinsicInst &)> IsStart) {
724   // We start from the end intrinsic and scan backwards, so that InstCombine
725   // has already processed (and potentially removed) all the instructions
726   // before the end intrinsic.
727   BasicBlock::reverse_iterator BI(EndI), BE(EndI.getParent()->rend());
728   for (; BI != BE; ++BI) {
729     if (auto *I = dyn_cast<IntrinsicInst>(&*BI)) {
730       if (I->isDebugOrPseudoInst() ||
731           I->getIntrinsicID() == EndI.getIntrinsicID())
732         continue;
733       if (IsStart(*I)) {
734         if (haveSameOperands(EndI, *I, EndI.arg_size())) {
735           IC.eraseInstFromFunction(*I);
736           IC.eraseInstFromFunction(EndI);
737           return true;
738         }
739         // Skip start intrinsics that don't pair with this end intrinsic.
740         continue;
741       }
742     }
743     break;
744   }
745 
746   return false;
747 }
748 
749 Instruction *InstCombinerImpl::visitVAEndInst(VAEndInst &I) {
750   removeTriviallyEmptyRange(I, *this, [](const IntrinsicInst &I) {
751     return I.getIntrinsicID() == Intrinsic::vastart ||
752            I.getIntrinsicID() == Intrinsic::vacopy;
753   });
754   return nullptr;
755 }
756 
757 static CallInst *canonicalizeConstantArg0ToArg1(CallInst &Call) {
758   assert(Call.arg_size() > 1 && "Need at least 2 args to swap");
759   Value *Arg0 = Call.getArgOperand(0), *Arg1 = Call.getArgOperand(1);
760   if (isa<Constant>(Arg0) && !isa<Constant>(Arg1)) {
761     Call.setArgOperand(0, Arg1);
762     Call.setArgOperand(1, Arg0);
763     return &Call;
764   }
765   return nullptr;
766 }
767 
768 /// Creates a result tuple for an overflow intrinsic \p II with a given
769 /// \p Result and a constant \p Overflow value.
770 static Instruction *createOverflowTuple(IntrinsicInst *II, Value *Result,
771                                         Constant *Overflow) {
772   Constant *V[] = {UndefValue::get(Result->getType()), Overflow};
773   StructType *ST = cast<StructType>(II->getType());
774   Constant *Struct = ConstantStruct::get(ST, V);
775   return InsertValueInst::Create(Struct, Result, 0);
776 }
777 
778 Instruction *
779 InstCombinerImpl::foldIntrinsicWithOverflowCommon(IntrinsicInst *II) {
780   WithOverflowInst *WO = cast<WithOverflowInst>(II);
781   Value *OperationResult = nullptr;
782   Constant *OverflowResult = nullptr;
783   if (OptimizeOverflowCheck(WO->getBinaryOp(), WO->isSigned(), WO->getLHS(),
784                             WO->getRHS(), *WO, OperationResult, OverflowResult))
785     return createOverflowTuple(WO, OperationResult, OverflowResult);
786   return nullptr;
787 }
788 
789 static Optional<bool> getKnownSign(Value *Op, Instruction *CxtI,
790                                    const DataLayout &DL, AssumptionCache *AC,
791                                    DominatorTree *DT) {
792   KnownBits Known = computeKnownBits(Op, DL, 0, AC, CxtI, DT);
793   if (Known.isNonNegative())
794     return false;
795   if (Known.isNegative())
796     return true;
797 
798   return isImpliedByDomCondition(
799       ICmpInst::ICMP_SLT, Op, Constant::getNullValue(Op->getType()), CxtI, DL);
800 }
801 
802 /// Try to canonicalize min/max(X + C0, C1) as min/max(X, C1 - C0) + C0. This
803 /// can trigger other combines.
804 static Instruction *moveAddAfterMinMax(IntrinsicInst *II,
805                                        InstCombiner::BuilderTy &Builder) {
806   Intrinsic::ID MinMaxID = II->getIntrinsicID();
807   assert((MinMaxID == Intrinsic::smax || MinMaxID == Intrinsic::smin ||
808           MinMaxID == Intrinsic::umax || MinMaxID == Intrinsic::umin) &&
809          "Expected a min or max intrinsic");
810 
811   // TODO: Match vectors with undef elements, but undef may not propagate.
812   Value *Op0 = II->getArgOperand(0), *Op1 = II->getArgOperand(1);
813   Value *X;
814   const APInt *C0, *C1;
815   if (!match(Op0, m_OneUse(m_Add(m_Value(X), m_APInt(C0)))) ||
816       !match(Op1, m_APInt(C1)))
817     return nullptr;
818 
819   // Check for necessary no-wrap and overflow constraints.
820   bool IsSigned = MinMaxID == Intrinsic::smax || MinMaxID == Intrinsic::smin;
821   auto *Add = cast<BinaryOperator>(Op0);
822   if ((IsSigned && !Add->hasNoSignedWrap()) ||
823       (!IsSigned && !Add->hasNoUnsignedWrap()))
824     return nullptr;
825 
826   // If the constant difference overflows, then instsimplify should reduce the
827   // min/max to the add or C1.
828   bool Overflow;
829   APInt CDiff =
830       IsSigned ? C1->ssub_ov(*C0, Overflow) : C1->usub_ov(*C0, Overflow);
831   assert(!Overflow && "Expected simplify of min/max");
832 
833   // min/max (add X, C0), C1 --> add (min/max X, C1 - C0), C0
834   // Note: the "mismatched" no-overflow setting does not propagate.
835   Constant *NewMinMaxC = ConstantInt::get(II->getType(), CDiff);
836   Value *NewMinMax = Builder.CreateBinaryIntrinsic(MinMaxID, X, NewMinMaxC);
837   return IsSigned ? BinaryOperator::CreateNSWAdd(NewMinMax, Add->getOperand(1))
838                   : BinaryOperator::CreateNUWAdd(NewMinMax, Add->getOperand(1));
839 }
840 /// Match a sadd_sat or ssub_sat which is using min/max to clamp the value.
841 Instruction *InstCombinerImpl::matchSAddSubSat(IntrinsicInst &MinMax1) {
842   Type *Ty = MinMax1.getType();
843 
844   // We are looking for a tree of:
845   // max(INT_MIN, min(INT_MAX, add(sext(A), sext(B))))
846   // Where the min and max could be reversed
847   Instruction *MinMax2;
848   BinaryOperator *AddSub;
849   const APInt *MinValue, *MaxValue;
850   if (match(&MinMax1, m_SMin(m_Instruction(MinMax2), m_APInt(MaxValue)))) {
851     if (!match(MinMax2, m_SMax(m_BinOp(AddSub), m_APInt(MinValue))))
852       return nullptr;
853   } else if (match(&MinMax1,
854                    m_SMax(m_Instruction(MinMax2), m_APInt(MinValue)))) {
855     if (!match(MinMax2, m_SMin(m_BinOp(AddSub), m_APInt(MaxValue))))
856       return nullptr;
857   } else
858     return nullptr;
859 
860   // Check that the constants clamp a saturate, and that the new type would be
861   // sensible to convert to.
862   if (!(*MaxValue + 1).isPowerOf2() || -*MinValue != *MaxValue + 1)
863     return nullptr;
864   // In what bitwidth can this be treated as saturating arithmetics?
865   unsigned NewBitWidth = (*MaxValue + 1).logBase2() + 1;
866   // FIXME: This isn't quite right for vectors, but using the scalar type is a
867   // good first approximation for what should be done there.
868   if (!shouldChangeType(Ty->getScalarType()->getIntegerBitWidth(), NewBitWidth))
869     return nullptr;
870 
871   // Also make sure that the inner min/max and the add/sub have one use.
872   if (!MinMax2->hasOneUse() || !AddSub->hasOneUse())
873     return nullptr;
874 
875   // Create the new type (which can be a vector type)
876   Type *NewTy = Ty->getWithNewBitWidth(NewBitWidth);
877 
878   Intrinsic::ID IntrinsicID;
879   if (AddSub->getOpcode() == Instruction::Add)
880     IntrinsicID = Intrinsic::sadd_sat;
881   else if (AddSub->getOpcode() == Instruction::Sub)
882     IntrinsicID = Intrinsic::ssub_sat;
883   else
884     return nullptr;
885 
886   // The two operands of the add/sub must be nsw-truncatable to the NewTy. This
887   // is usually achieved via a sext from a smaller type.
888   if (ComputeMaxSignificantBits(AddSub->getOperand(0), 0, AddSub) >
889           NewBitWidth ||
890       ComputeMaxSignificantBits(AddSub->getOperand(1), 0, AddSub) > NewBitWidth)
891     return nullptr;
892 
893   // Finally create and return the sat intrinsic, truncated to the new type
894   Function *F = Intrinsic::getDeclaration(MinMax1.getModule(), IntrinsicID, NewTy);
895   Value *AT = Builder.CreateTrunc(AddSub->getOperand(0), NewTy);
896   Value *BT = Builder.CreateTrunc(AddSub->getOperand(1), NewTy);
897   Value *Sat = Builder.CreateCall(F, {AT, BT});
898   return CastInst::Create(Instruction::SExt, Sat, Ty);
899 }
900 
901 
902 /// If we have a clamp pattern like max (min X, 42), 41 -- where the output
903 /// can only be one of two possible constant values -- turn that into a select
904 /// of constants.
905 static Instruction *foldClampRangeOfTwo(IntrinsicInst *II,
906                                         InstCombiner::BuilderTy &Builder) {
907   Value *I0 = II->getArgOperand(0), *I1 = II->getArgOperand(1);
908   Value *X;
909   const APInt *C0, *C1;
910   if (!match(I1, m_APInt(C1)) || !I0->hasOneUse())
911     return nullptr;
912 
913   CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
914   switch (II->getIntrinsicID()) {
915   case Intrinsic::smax:
916     if (match(I0, m_SMin(m_Value(X), m_APInt(C0))) && *C0 == *C1 + 1)
917       Pred = ICmpInst::ICMP_SGT;
918     break;
919   case Intrinsic::smin:
920     if (match(I0, m_SMax(m_Value(X), m_APInt(C0))) && *C1 == *C0 + 1)
921       Pred = ICmpInst::ICMP_SLT;
922     break;
923   case Intrinsic::umax:
924     if (match(I0, m_UMin(m_Value(X), m_APInt(C0))) && *C0 == *C1 + 1)
925       Pred = ICmpInst::ICMP_UGT;
926     break;
927   case Intrinsic::umin:
928     if (match(I0, m_UMax(m_Value(X), m_APInt(C0))) && *C1 == *C0 + 1)
929       Pred = ICmpInst::ICMP_ULT;
930     break;
931   default:
932     llvm_unreachable("Expected min/max intrinsic");
933   }
934   if (Pred == CmpInst::BAD_ICMP_PREDICATE)
935     return nullptr;
936 
937   // max (min X, 42), 41 --> X > 41 ? 42 : 41
938   // min (max X, 42), 43 --> X < 43 ? 42 : 43
939   Value *Cmp = Builder.CreateICmp(Pred, X, I1);
940   return SelectInst::Create(Cmp, ConstantInt::get(II->getType(), *C0), I1);
941 }
942 
943 /// If this min/max has a constant operand and an operand that is a matching
944 /// min/max with a constant operand, constant-fold the 2 constant operands.
945 static Instruction *reassociateMinMaxWithConstants(IntrinsicInst *II) {
946   Intrinsic::ID MinMaxID = II->getIntrinsicID();
947   auto *LHS = dyn_cast<IntrinsicInst>(II->getArgOperand(0));
948   if (!LHS || LHS->getIntrinsicID() != MinMaxID)
949     return nullptr;
950 
951   Constant *C0, *C1;
952   if (!match(LHS->getArgOperand(1), m_ImmConstant(C0)) ||
953       !match(II->getArgOperand(1), m_ImmConstant(C1)))
954     return nullptr;
955 
956   // max (max X, C0), C1 --> max X, (max C0, C1) --> max X, NewC
957   ICmpInst::Predicate Pred = MinMaxIntrinsic::getPredicate(MinMaxID);
958   Constant *CondC = ConstantExpr::getICmp(Pred, C0, C1);
959   Constant *NewC = ConstantExpr::getSelect(CondC, C0, C1);
960 
961   Module *Mod = II->getModule();
962   Function *MinMax = Intrinsic::getDeclaration(Mod, MinMaxID, II->getType());
963   return CallInst::Create(MinMax, {LHS->getArgOperand(0), NewC});
964 }
965 
966 /// If this min/max has a matching min/max operand with a constant, try to push
967 /// the constant operand into this instruction. This can enable more folds.
968 static Instruction *
969 reassociateMinMaxWithConstantInOperand(IntrinsicInst *II,
970                                        InstCombiner::BuilderTy &Builder) {
971   // Match and capture a min/max operand candidate.
972   Value *X, *Y;
973   Constant *C;
974   Instruction *Inner;
975   if (!match(II, m_c_MaxOrMin(m_OneUse(m_CombineAnd(
976                                   m_Instruction(Inner),
977                                   m_MaxOrMin(m_Value(X), m_ImmConstant(C)))),
978                               m_Value(Y))))
979     return nullptr;
980 
981   // The inner op must match. Check for constants to avoid infinite loops.
982   Intrinsic::ID MinMaxID = II->getIntrinsicID();
983   auto *InnerMM = dyn_cast<IntrinsicInst>(Inner);
984   if (!InnerMM || InnerMM->getIntrinsicID() != MinMaxID ||
985       match(X, m_ImmConstant()) || match(Y, m_ImmConstant()))
986     return nullptr;
987 
988   // max (max X, C), Y --> max (max X, Y), C
989   Function *MinMax =
990       Intrinsic::getDeclaration(II->getModule(), MinMaxID, II->getType());
991   Value *NewInner = Builder.CreateBinaryIntrinsic(MinMaxID, X, Y);
992   NewInner->takeName(Inner);
993   return CallInst::Create(MinMax, {NewInner, C});
994 }
995 
996 /// Reduce a sequence of min/max intrinsics with a common operand.
997 static Instruction *factorizeMinMaxTree(IntrinsicInst *II) {
998   // Match 3 of the same min/max ops. Example: umin(umin(), umin()).
999   auto *LHS = dyn_cast<IntrinsicInst>(II->getArgOperand(0));
1000   auto *RHS = dyn_cast<IntrinsicInst>(II->getArgOperand(1));
1001   Intrinsic::ID MinMaxID = II->getIntrinsicID();
1002   if (!LHS || !RHS || LHS->getIntrinsicID() != MinMaxID ||
1003       RHS->getIntrinsicID() != MinMaxID ||
1004       (!LHS->hasOneUse() && !RHS->hasOneUse()))
1005     return nullptr;
1006 
1007   Value *A = LHS->getArgOperand(0);
1008   Value *B = LHS->getArgOperand(1);
1009   Value *C = RHS->getArgOperand(0);
1010   Value *D = RHS->getArgOperand(1);
1011 
1012   // Look for a common operand.
1013   Value *MinMaxOp = nullptr;
1014   Value *ThirdOp = nullptr;
1015   if (LHS->hasOneUse()) {
1016     // If the LHS is only used in this chain and the RHS is used outside of it,
1017     // reuse the RHS min/max because that will eliminate the LHS.
1018     if (D == A || C == A) {
1019       // min(min(a, b), min(c, a)) --> min(min(c, a), b)
1020       // min(min(a, b), min(a, d)) --> min(min(a, d), b)
1021       MinMaxOp = RHS;
1022       ThirdOp = B;
1023     } else if (D == B || C == B) {
1024       // min(min(a, b), min(c, b)) --> min(min(c, b), a)
1025       // min(min(a, b), min(b, d)) --> min(min(b, d), a)
1026       MinMaxOp = RHS;
1027       ThirdOp = A;
1028     }
1029   } else {
1030     assert(RHS->hasOneUse() && "Expected one-use operand");
1031     // Reuse the LHS. This will eliminate the RHS.
1032     if (D == A || D == B) {
1033       // min(min(a, b), min(c, a)) --> min(min(a, b), c)
1034       // min(min(a, b), min(c, b)) --> min(min(a, b), c)
1035       MinMaxOp = LHS;
1036       ThirdOp = C;
1037     } else if (C == A || C == B) {
1038       // min(min(a, b), min(b, d)) --> min(min(a, b), d)
1039       // min(min(a, b), min(c, b)) --> min(min(a, b), d)
1040       MinMaxOp = LHS;
1041       ThirdOp = D;
1042     }
1043   }
1044 
1045   if (!MinMaxOp || !ThirdOp)
1046     return nullptr;
1047 
1048   Module *Mod = II->getModule();
1049   Function *MinMax = Intrinsic::getDeclaration(Mod, MinMaxID, II->getType());
1050   return CallInst::Create(MinMax, { MinMaxOp, ThirdOp });
1051 }
1052 
1053 /// CallInst simplification. This mostly only handles folding of intrinsic
1054 /// instructions. For normal calls, it allows visitCallBase to do the heavy
1055 /// lifting.
1056 Instruction *InstCombinerImpl::visitCallInst(CallInst &CI) {
1057   // Don't try to simplify calls without uses. It will not do anything useful,
1058   // but will result in the following folds being skipped.
1059   if (!CI.use_empty())
1060     if (Value *V = SimplifyCall(&CI, SQ.getWithInstruction(&CI)))
1061       return replaceInstUsesWith(CI, V);
1062 
1063   if (isFreeCall(&CI, &TLI))
1064     return visitFree(CI);
1065 
1066   // If the caller function (i.e. us, the function that contains this CallInst)
1067   // is nounwind, mark the call as nounwind, even if the callee isn't.
1068   if (CI.getFunction()->doesNotThrow() && !CI.doesNotThrow()) {
1069     CI.setDoesNotThrow();
1070     return &CI;
1071   }
1072 
1073   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
1074   if (!II) return visitCallBase(CI);
1075 
1076   // For atomic unordered mem intrinsics if len is not a positive or
1077   // not a multiple of element size then behavior is undefined.
1078   if (auto *AMI = dyn_cast<AtomicMemIntrinsic>(II))
1079     if (ConstantInt *NumBytes = dyn_cast<ConstantInt>(AMI->getLength()))
1080       if (NumBytes->getSExtValue() < 0 ||
1081           (NumBytes->getZExtValue() % AMI->getElementSizeInBytes() != 0)) {
1082         CreateNonTerminatorUnreachable(AMI);
1083         assert(AMI->getType()->isVoidTy() &&
1084                "non void atomic unordered mem intrinsic");
1085         return eraseInstFromFunction(*AMI);
1086       }
1087 
1088   // Intrinsics cannot occur in an invoke or a callbr, so handle them here
1089   // instead of in visitCallBase.
1090   if (auto *MI = dyn_cast<AnyMemIntrinsic>(II)) {
1091     bool Changed = false;
1092 
1093     // memmove/cpy/set of zero bytes is a noop.
1094     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
1095       if (NumBytes->isNullValue())
1096         return eraseInstFromFunction(CI);
1097 
1098       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
1099         if (CI->getZExtValue() == 1) {
1100           // Replace the instruction with just byte operations.  We would
1101           // transform other cases to loads/stores, but we don't know if
1102           // alignment is sufficient.
1103         }
1104     }
1105 
1106     // No other transformations apply to volatile transfers.
1107     if (auto *M = dyn_cast<MemIntrinsic>(MI))
1108       if (M->isVolatile())
1109         return nullptr;
1110 
1111     // If we have a memmove and the source operation is a constant global,
1112     // then the source and dest pointers can't alias, so we can change this
1113     // into a call to memcpy.
1114     if (auto *MMI = dyn_cast<AnyMemMoveInst>(MI)) {
1115       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
1116         if (GVSrc->isConstant()) {
1117           Module *M = CI.getModule();
1118           Intrinsic::ID MemCpyID =
1119               isa<AtomicMemMoveInst>(MMI)
1120                   ? Intrinsic::memcpy_element_unordered_atomic
1121                   : Intrinsic::memcpy;
1122           Type *Tys[3] = { CI.getArgOperand(0)->getType(),
1123                            CI.getArgOperand(1)->getType(),
1124                            CI.getArgOperand(2)->getType() };
1125           CI.setCalledFunction(Intrinsic::getDeclaration(M, MemCpyID, Tys));
1126           Changed = true;
1127         }
1128     }
1129 
1130     if (AnyMemTransferInst *MTI = dyn_cast<AnyMemTransferInst>(MI)) {
1131       // memmove(x,x,size) -> noop.
1132       if (MTI->getSource() == MTI->getDest())
1133         return eraseInstFromFunction(CI);
1134     }
1135 
1136     // If we can determine a pointer alignment that is bigger than currently
1137     // set, update the alignment.
1138     if (auto *MTI = dyn_cast<AnyMemTransferInst>(MI)) {
1139       if (Instruction *I = SimplifyAnyMemTransfer(MTI))
1140         return I;
1141     } else if (auto *MSI = dyn_cast<AnyMemSetInst>(MI)) {
1142       if (Instruction *I = SimplifyAnyMemSet(MSI))
1143         return I;
1144     }
1145 
1146     if (Changed) return II;
1147   }
1148 
1149   // For fixed width vector result intrinsics, use the generic demanded vector
1150   // support.
1151   if (auto *IIFVTy = dyn_cast<FixedVectorType>(II->getType())) {
1152     auto VWidth = IIFVTy->getNumElements();
1153     APInt UndefElts(VWidth, 0);
1154     APInt AllOnesEltMask(APInt::getAllOnes(VWidth));
1155     if (Value *V = SimplifyDemandedVectorElts(II, AllOnesEltMask, UndefElts)) {
1156       if (V != II)
1157         return replaceInstUsesWith(*II, V);
1158       return II;
1159     }
1160   }
1161 
1162   if (II->isCommutative()) {
1163     if (CallInst *NewCall = canonicalizeConstantArg0ToArg1(CI))
1164       return NewCall;
1165   }
1166 
1167   Intrinsic::ID IID = II->getIntrinsicID();
1168   switch (IID) {
1169   case Intrinsic::objectsize:
1170     if (Value *V = lowerObjectSizeCall(II, DL, &TLI, /*MustSucceed=*/false))
1171       return replaceInstUsesWith(CI, V);
1172     return nullptr;
1173   case Intrinsic::abs: {
1174     Value *IIOperand = II->getArgOperand(0);
1175     bool IntMinIsPoison = cast<Constant>(II->getArgOperand(1))->isOneValue();
1176 
1177     // abs(-x) -> abs(x)
1178     // TODO: Copy nsw if it was present on the neg?
1179     Value *X;
1180     if (match(IIOperand, m_Neg(m_Value(X))))
1181       return replaceOperand(*II, 0, X);
1182     if (match(IIOperand, m_Select(m_Value(), m_Value(X), m_Neg(m_Deferred(X)))))
1183       return replaceOperand(*II, 0, X);
1184     if (match(IIOperand, m_Select(m_Value(), m_Neg(m_Value(X)), m_Deferred(X))))
1185       return replaceOperand(*II, 0, X);
1186 
1187     if (Optional<bool> Sign = getKnownSign(IIOperand, II, DL, &AC, &DT)) {
1188       // abs(x) -> x if x >= 0
1189       if (!*Sign)
1190         return replaceInstUsesWith(*II, IIOperand);
1191 
1192       // abs(x) -> -x if x < 0
1193       if (IntMinIsPoison)
1194         return BinaryOperator::CreateNSWNeg(IIOperand);
1195       return BinaryOperator::CreateNeg(IIOperand);
1196     }
1197 
1198     // abs (sext X) --> zext (abs X*)
1199     // Clear the IsIntMin (nsw) bit on the abs to allow narrowing.
1200     if (match(IIOperand, m_OneUse(m_SExt(m_Value(X))))) {
1201       Value *NarrowAbs =
1202           Builder.CreateBinaryIntrinsic(Intrinsic::abs, X, Builder.getFalse());
1203       return CastInst::Create(Instruction::ZExt, NarrowAbs, II->getType());
1204     }
1205 
1206     // Match a complicated way to check if a number is odd/even:
1207     // abs (srem X, 2) --> and X, 1
1208     const APInt *C;
1209     if (match(IIOperand, m_SRem(m_Value(X), m_APInt(C))) && *C == 2)
1210       return BinaryOperator::CreateAnd(X, ConstantInt::get(II->getType(), 1));
1211 
1212     break;
1213   }
1214   case Intrinsic::umin: {
1215     Value *I0 = II->getArgOperand(0), *I1 = II->getArgOperand(1);
1216     // umin(x, 1) == zext(x != 0)
1217     if (match(I1, m_One())) {
1218       Value *Zero = Constant::getNullValue(I0->getType());
1219       Value *Cmp = Builder.CreateICmpNE(I0, Zero);
1220       return CastInst::Create(Instruction::ZExt, Cmp, II->getType());
1221     }
1222     LLVM_FALLTHROUGH;
1223   }
1224   case Intrinsic::umax: {
1225     Value *I0 = II->getArgOperand(0), *I1 = II->getArgOperand(1);
1226     Value *X, *Y;
1227     if (match(I0, m_ZExt(m_Value(X))) && match(I1, m_ZExt(m_Value(Y))) &&
1228         (I0->hasOneUse() || I1->hasOneUse()) && X->getType() == Y->getType()) {
1229       Value *NarrowMaxMin = Builder.CreateBinaryIntrinsic(IID, X, Y);
1230       return CastInst::Create(Instruction::ZExt, NarrowMaxMin, II->getType());
1231     }
1232     Constant *C;
1233     if (match(I0, m_ZExt(m_Value(X))) && match(I1, m_Constant(C)) &&
1234         I0->hasOneUse()) {
1235       Constant *NarrowC = ConstantExpr::getTrunc(C, X->getType());
1236       if (ConstantExpr::getZExt(NarrowC, II->getType()) == C) {
1237         Value *NarrowMaxMin = Builder.CreateBinaryIntrinsic(IID, X, NarrowC);
1238         return CastInst::Create(Instruction::ZExt, NarrowMaxMin, II->getType());
1239       }
1240     }
1241     // If both operands of unsigned min/max are sign-extended, it is still ok
1242     // to narrow the operation.
1243     LLVM_FALLTHROUGH;
1244   }
1245   case Intrinsic::smax:
1246   case Intrinsic::smin: {
1247     Value *I0 = II->getArgOperand(0), *I1 = II->getArgOperand(1);
1248     Value *X, *Y;
1249     if (match(I0, m_SExt(m_Value(X))) && match(I1, m_SExt(m_Value(Y))) &&
1250         (I0->hasOneUse() || I1->hasOneUse()) && X->getType() == Y->getType()) {
1251       Value *NarrowMaxMin = Builder.CreateBinaryIntrinsic(IID, X, Y);
1252       return CastInst::Create(Instruction::SExt, NarrowMaxMin, II->getType());
1253     }
1254 
1255     Constant *C;
1256     if (match(I0, m_SExt(m_Value(X))) && match(I1, m_Constant(C)) &&
1257         I0->hasOneUse()) {
1258       Constant *NarrowC = ConstantExpr::getTrunc(C, X->getType());
1259       if (ConstantExpr::getSExt(NarrowC, II->getType()) == C) {
1260         Value *NarrowMaxMin = Builder.CreateBinaryIntrinsic(IID, X, NarrowC);
1261         return CastInst::Create(Instruction::SExt, NarrowMaxMin, II->getType());
1262       }
1263     }
1264 
1265     if (IID == Intrinsic::smax || IID == Intrinsic::smin) {
1266       // smax (neg nsw X), (neg nsw Y) --> neg nsw (smin X, Y)
1267       // smin (neg nsw X), (neg nsw Y) --> neg nsw (smax X, Y)
1268       // TODO: Canonicalize neg after min/max if I1 is constant.
1269       if (match(I0, m_NSWNeg(m_Value(X))) && match(I1, m_NSWNeg(m_Value(Y))) &&
1270           (I0->hasOneUse() || I1->hasOneUse())) {
1271         Intrinsic::ID InvID = getInverseMinMaxIntrinsic(IID);
1272         Value *InvMaxMin = Builder.CreateBinaryIntrinsic(InvID, X, Y);
1273         return BinaryOperator::CreateNSWNeg(InvMaxMin);
1274       }
1275     }
1276 
1277     // If we can eliminate ~A and Y is free to invert:
1278     // max ~A, Y --> ~(min A, ~Y)
1279     //
1280     // Examples:
1281     // max ~A, ~Y --> ~(min A, Y)
1282     // max ~A, C --> ~(min A, ~C)
1283     // max ~A, (max ~Y, ~Z) --> ~min( A, (min Y, Z))
1284     auto moveNotAfterMinMax = [&](Value *X, Value *Y) -> Instruction * {
1285       Value *A;
1286       if (match(X, m_OneUse(m_Not(m_Value(A)))) &&
1287           !isFreeToInvert(A, A->hasOneUse()) &&
1288           isFreeToInvert(Y, Y->hasOneUse())) {
1289         Value *NotY = Builder.CreateNot(Y);
1290         Intrinsic::ID InvID = getInverseMinMaxIntrinsic(IID);
1291         Value *InvMaxMin = Builder.CreateBinaryIntrinsic(InvID, A, NotY);
1292         return BinaryOperator::CreateNot(InvMaxMin);
1293       }
1294       return nullptr;
1295     };
1296 
1297     if (Instruction *I = moveNotAfterMinMax(I0, I1))
1298       return I;
1299     if (Instruction *I = moveNotAfterMinMax(I1, I0))
1300       return I;
1301 
1302     if (Instruction *I = moveAddAfterMinMax(II, Builder))
1303       return I;
1304 
1305     // smax(X, -X) --> abs(X)
1306     // smin(X, -X) --> -abs(X)
1307     // umax(X, -X) --> -abs(X)
1308     // umin(X, -X) --> abs(X)
1309     if (isKnownNegation(I0, I1)) {
1310       // We can choose either operand as the input to abs(), but if we can
1311       // eliminate the only use of a value, that's better for subsequent
1312       // transforms/analysis.
1313       if (I0->hasOneUse() && !I1->hasOneUse())
1314         std::swap(I0, I1);
1315 
1316       // This is some variant of abs(). See if we can propagate 'nsw' to the abs
1317       // operation and potentially its negation.
1318       bool IntMinIsPoison = isKnownNegation(I0, I1, /* NeedNSW */ true);
1319       Value *Abs = Builder.CreateBinaryIntrinsic(
1320           Intrinsic::abs, I0,
1321           ConstantInt::getBool(II->getContext(), IntMinIsPoison));
1322 
1323       // We don't have a "nabs" intrinsic, so negate if needed based on the
1324       // max/min operation.
1325       if (IID == Intrinsic::smin || IID == Intrinsic::umax)
1326         Abs = Builder.CreateNeg(Abs, "nabs", /* NUW */ false, IntMinIsPoison);
1327       return replaceInstUsesWith(CI, Abs);
1328     }
1329 
1330     if (Instruction *Sel = foldClampRangeOfTwo(II, Builder))
1331       return Sel;
1332 
1333     if (Instruction *SAdd = matchSAddSubSat(*II))
1334       return SAdd;
1335 
1336     if (match(I1, m_ImmConstant()))
1337       if (auto *Sel = dyn_cast<SelectInst>(I0))
1338         if (Instruction *R = FoldOpIntoSelect(*II, Sel))
1339           return R;
1340 
1341     if (Instruction *NewMinMax = reassociateMinMaxWithConstants(II))
1342       return NewMinMax;
1343 
1344     if (Instruction *R = reassociateMinMaxWithConstantInOperand(II, Builder))
1345       return R;
1346 
1347     if (Instruction *NewMinMax = factorizeMinMaxTree(II))
1348        return NewMinMax;
1349 
1350     break;
1351   }
1352   case Intrinsic::bswap: {
1353     Value *IIOperand = II->getArgOperand(0);
1354     Value *X = nullptr;
1355 
1356     KnownBits Known = computeKnownBits(IIOperand, 0, II);
1357     uint64_t LZ = alignDown(Known.countMinLeadingZeros(), 8);
1358     uint64_t TZ = alignDown(Known.countMinTrailingZeros(), 8);
1359     unsigned BW = Known.getBitWidth();
1360 
1361     // bswap(x) -> shift(x) if x has exactly one "active byte"
1362     if (BW - LZ - TZ == 8) {
1363       assert(LZ != TZ && "active byte cannot be in the middle");
1364       if (LZ > TZ)  // -> shl(x) if the "active byte" is in the low part of x
1365         return BinaryOperator::CreateNUWShl(
1366             IIOperand, ConstantInt::get(IIOperand->getType(), LZ - TZ));
1367       // -> lshr(x) if the "active byte" is in the high part of x
1368       return BinaryOperator::CreateExactLShr(
1369             IIOperand, ConstantInt::get(IIOperand->getType(), TZ - LZ));
1370     }
1371 
1372     // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
1373     if (match(IIOperand, m_Trunc(m_BSwap(m_Value(X))))) {
1374       unsigned C = X->getType()->getScalarSizeInBits() - BW;
1375       Value *CV = ConstantInt::get(X->getType(), C);
1376       Value *V = Builder.CreateLShr(X, CV);
1377       return new TruncInst(V, IIOperand->getType());
1378     }
1379     break;
1380   }
1381   case Intrinsic::masked_load:
1382     if (Value *SimplifiedMaskedOp = simplifyMaskedLoad(*II))
1383       return replaceInstUsesWith(CI, SimplifiedMaskedOp);
1384     break;
1385   case Intrinsic::masked_store:
1386     return simplifyMaskedStore(*II);
1387   case Intrinsic::masked_gather:
1388     return simplifyMaskedGather(*II);
1389   case Intrinsic::masked_scatter:
1390     return simplifyMaskedScatter(*II);
1391   case Intrinsic::launder_invariant_group:
1392   case Intrinsic::strip_invariant_group:
1393     if (auto *SkippedBarrier = simplifyInvariantGroupIntrinsic(*II, *this))
1394       return replaceInstUsesWith(*II, SkippedBarrier);
1395     break;
1396   case Intrinsic::powi:
1397     if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
1398       // 0 and 1 are handled in instsimplify
1399       // powi(x, -1) -> 1/x
1400       if (Power->isMinusOne())
1401         return BinaryOperator::CreateFDivFMF(ConstantFP::get(CI.getType(), 1.0),
1402                                              II->getArgOperand(0), II);
1403       // powi(x, 2) -> x*x
1404       if (Power->equalsInt(2))
1405         return BinaryOperator::CreateFMulFMF(II->getArgOperand(0),
1406                                              II->getArgOperand(0), II);
1407 
1408       if (!Power->getValue()[0]) {
1409         Value *X;
1410         // If power is even:
1411         // powi(-x, p) -> powi(x, p)
1412         // powi(fabs(x), p) -> powi(x, p)
1413         // powi(copysign(x, y), p) -> powi(x, p)
1414         if (match(II->getArgOperand(0), m_FNeg(m_Value(X))) ||
1415             match(II->getArgOperand(0), m_FAbs(m_Value(X))) ||
1416             match(II->getArgOperand(0),
1417                   m_Intrinsic<Intrinsic::copysign>(m_Value(X), m_Value())))
1418           return replaceOperand(*II, 0, X);
1419       }
1420     }
1421     break;
1422 
1423   case Intrinsic::cttz:
1424   case Intrinsic::ctlz:
1425     if (auto *I = foldCttzCtlz(*II, *this))
1426       return I;
1427     break;
1428 
1429   case Intrinsic::ctpop:
1430     if (auto *I = foldCtpop(*II, *this))
1431       return I;
1432     break;
1433 
1434   case Intrinsic::fshl:
1435   case Intrinsic::fshr: {
1436     Value *Op0 = II->getArgOperand(0), *Op1 = II->getArgOperand(1);
1437     Type *Ty = II->getType();
1438     unsigned BitWidth = Ty->getScalarSizeInBits();
1439     Constant *ShAmtC;
1440     if (match(II->getArgOperand(2), m_ImmConstant(ShAmtC)) &&
1441         !ShAmtC->containsConstantExpression()) {
1442       // Canonicalize a shift amount constant operand to modulo the bit-width.
1443       Constant *WidthC = ConstantInt::get(Ty, BitWidth);
1444       Constant *ModuloC = ConstantExpr::getURem(ShAmtC, WidthC);
1445       if (ModuloC != ShAmtC)
1446         return replaceOperand(*II, 2, ModuloC);
1447 
1448       assert(ConstantExpr::getICmp(ICmpInst::ICMP_UGT, WidthC, ShAmtC) ==
1449                  ConstantInt::getTrue(CmpInst::makeCmpResultType(Ty)) &&
1450              "Shift amount expected to be modulo bitwidth");
1451 
1452       // Canonicalize funnel shift right by constant to funnel shift left. This
1453       // is not entirely arbitrary. For historical reasons, the backend may
1454       // recognize rotate left patterns but miss rotate right patterns.
1455       if (IID == Intrinsic::fshr) {
1456         // fshr X, Y, C --> fshl X, Y, (BitWidth - C)
1457         Constant *LeftShiftC = ConstantExpr::getSub(WidthC, ShAmtC);
1458         Module *Mod = II->getModule();
1459         Function *Fshl = Intrinsic::getDeclaration(Mod, Intrinsic::fshl, Ty);
1460         return CallInst::Create(Fshl, { Op0, Op1, LeftShiftC });
1461       }
1462       assert(IID == Intrinsic::fshl &&
1463              "All funnel shifts by simple constants should go left");
1464 
1465       // fshl(X, 0, C) --> shl X, C
1466       // fshl(X, undef, C) --> shl X, C
1467       if (match(Op1, m_ZeroInt()) || match(Op1, m_Undef()))
1468         return BinaryOperator::CreateShl(Op0, ShAmtC);
1469 
1470       // fshl(0, X, C) --> lshr X, (BW-C)
1471       // fshl(undef, X, C) --> lshr X, (BW-C)
1472       if (match(Op0, m_ZeroInt()) || match(Op0, m_Undef()))
1473         return BinaryOperator::CreateLShr(Op1,
1474                                           ConstantExpr::getSub(WidthC, ShAmtC));
1475 
1476       // fshl i16 X, X, 8 --> bswap i16 X (reduce to more-specific form)
1477       if (Op0 == Op1 && BitWidth == 16 && match(ShAmtC, m_SpecificInt(8))) {
1478         Module *Mod = II->getModule();
1479         Function *Bswap = Intrinsic::getDeclaration(Mod, Intrinsic::bswap, Ty);
1480         return CallInst::Create(Bswap, { Op0 });
1481       }
1482     }
1483 
1484     // Left or right might be masked.
1485     if (SimplifyDemandedInstructionBits(*II))
1486       return &CI;
1487 
1488     // The shift amount (operand 2) of a funnel shift is modulo the bitwidth,
1489     // so only the low bits of the shift amount are demanded if the bitwidth is
1490     // a power-of-2.
1491     if (!isPowerOf2_32(BitWidth))
1492       break;
1493     APInt Op2Demanded = APInt::getLowBitsSet(BitWidth, Log2_32_Ceil(BitWidth));
1494     KnownBits Op2Known(BitWidth);
1495     if (SimplifyDemandedBits(II, 2, Op2Demanded, Op2Known))
1496       return &CI;
1497     break;
1498   }
1499   case Intrinsic::uadd_with_overflow:
1500   case Intrinsic::sadd_with_overflow: {
1501     if (Instruction *I = foldIntrinsicWithOverflowCommon(II))
1502       return I;
1503 
1504     // Given 2 constant operands whose sum does not overflow:
1505     // uaddo (X +nuw C0), C1 -> uaddo X, C0 + C1
1506     // saddo (X +nsw C0), C1 -> saddo X, C0 + C1
1507     Value *X;
1508     const APInt *C0, *C1;
1509     Value *Arg0 = II->getArgOperand(0);
1510     Value *Arg1 = II->getArgOperand(1);
1511     bool IsSigned = IID == Intrinsic::sadd_with_overflow;
1512     bool HasNWAdd = IsSigned ? match(Arg0, m_NSWAdd(m_Value(X), m_APInt(C0)))
1513                              : match(Arg0, m_NUWAdd(m_Value(X), m_APInt(C0)));
1514     if (HasNWAdd && match(Arg1, m_APInt(C1))) {
1515       bool Overflow;
1516       APInt NewC =
1517           IsSigned ? C1->sadd_ov(*C0, Overflow) : C1->uadd_ov(*C0, Overflow);
1518       if (!Overflow)
1519         return replaceInstUsesWith(
1520             *II, Builder.CreateBinaryIntrinsic(
1521                      IID, X, ConstantInt::get(Arg1->getType(), NewC)));
1522     }
1523     break;
1524   }
1525 
1526   case Intrinsic::umul_with_overflow:
1527   case Intrinsic::smul_with_overflow:
1528   case Intrinsic::usub_with_overflow:
1529     if (Instruction *I = foldIntrinsicWithOverflowCommon(II))
1530       return I;
1531     break;
1532 
1533   case Intrinsic::ssub_with_overflow: {
1534     if (Instruction *I = foldIntrinsicWithOverflowCommon(II))
1535       return I;
1536 
1537     Constant *C;
1538     Value *Arg0 = II->getArgOperand(0);
1539     Value *Arg1 = II->getArgOperand(1);
1540     // Given a constant C that is not the minimum signed value
1541     // for an integer of a given bit width:
1542     //
1543     // ssubo X, C -> saddo X, -C
1544     if (match(Arg1, m_Constant(C)) && C->isNotMinSignedValue()) {
1545       Value *NegVal = ConstantExpr::getNeg(C);
1546       // Build a saddo call that is equivalent to the discovered
1547       // ssubo call.
1548       return replaceInstUsesWith(
1549           *II, Builder.CreateBinaryIntrinsic(Intrinsic::sadd_with_overflow,
1550                                              Arg0, NegVal));
1551     }
1552 
1553     break;
1554   }
1555 
1556   case Intrinsic::uadd_sat:
1557   case Intrinsic::sadd_sat:
1558   case Intrinsic::usub_sat:
1559   case Intrinsic::ssub_sat: {
1560     SaturatingInst *SI = cast<SaturatingInst>(II);
1561     Type *Ty = SI->getType();
1562     Value *Arg0 = SI->getLHS();
1563     Value *Arg1 = SI->getRHS();
1564 
1565     // Make use of known overflow information.
1566     OverflowResult OR = computeOverflow(SI->getBinaryOp(), SI->isSigned(),
1567                                         Arg0, Arg1, SI);
1568     switch (OR) {
1569       case OverflowResult::MayOverflow:
1570         break;
1571       case OverflowResult::NeverOverflows:
1572         if (SI->isSigned())
1573           return BinaryOperator::CreateNSW(SI->getBinaryOp(), Arg0, Arg1);
1574         else
1575           return BinaryOperator::CreateNUW(SI->getBinaryOp(), Arg0, Arg1);
1576       case OverflowResult::AlwaysOverflowsLow: {
1577         unsigned BitWidth = Ty->getScalarSizeInBits();
1578         APInt Min = APSInt::getMinValue(BitWidth, !SI->isSigned());
1579         return replaceInstUsesWith(*SI, ConstantInt::get(Ty, Min));
1580       }
1581       case OverflowResult::AlwaysOverflowsHigh: {
1582         unsigned BitWidth = Ty->getScalarSizeInBits();
1583         APInt Max = APSInt::getMaxValue(BitWidth, !SI->isSigned());
1584         return replaceInstUsesWith(*SI, ConstantInt::get(Ty, Max));
1585       }
1586     }
1587 
1588     // ssub.sat(X, C) -> sadd.sat(X, -C) if C != MIN
1589     Constant *C;
1590     if (IID == Intrinsic::ssub_sat && match(Arg1, m_Constant(C)) &&
1591         C->isNotMinSignedValue()) {
1592       Value *NegVal = ConstantExpr::getNeg(C);
1593       return replaceInstUsesWith(
1594           *II, Builder.CreateBinaryIntrinsic(
1595               Intrinsic::sadd_sat, Arg0, NegVal));
1596     }
1597 
1598     // sat(sat(X + Val2) + Val) -> sat(X + (Val+Val2))
1599     // sat(sat(X - Val2) - Val) -> sat(X - (Val+Val2))
1600     // if Val and Val2 have the same sign
1601     if (auto *Other = dyn_cast<IntrinsicInst>(Arg0)) {
1602       Value *X;
1603       const APInt *Val, *Val2;
1604       APInt NewVal;
1605       bool IsUnsigned =
1606           IID == Intrinsic::uadd_sat || IID == Intrinsic::usub_sat;
1607       if (Other->getIntrinsicID() == IID &&
1608           match(Arg1, m_APInt(Val)) &&
1609           match(Other->getArgOperand(0), m_Value(X)) &&
1610           match(Other->getArgOperand(1), m_APInt(Val2))) {
1611         if (IsUnsigned)
1612           NewVal = Val->uadd_sat(*Val2);
1613         else if (Val->isNonNegative() == Val2->isNonNegative()) {
1614           bool Overflow;
1615           NewVal = Val->sadd_ov(*Val2, Overflow);
1616           if (Overflow) {
1617             // Both adds together may add more than SignedMaxValue
1618             // without saturating the final result.
1619             break;
1620           }
1621         } else {
1622           // Cannot fold saturated addition with different signs.
1623           break;
1624         }
1625 
1626         return replaceInstUsesWith(
1627             *II, Builder.CreateBinaryIntrinsic(
1628                      IID, X, ConstantInt::get(II->getType(), NewVal)));
1629       }
1630     }
1631     break;
1632   }
1633 
1634   case Intrinsic::minnum:
1635   case Intrinsic::maxnum:
1636   case Intrinsic::minimum:
1637   case Intrinsic::maximum: {
1638     Value *Arg0 = II->getArgOperand(0);
1639     Value *Arg1 = II->getArgOperand(1);
1640     Value *X, *Y;
1641     if (match(Arg0, m_FNeg(m_Value(X))) && match(Arg1, m_FNeg(m_Value(Y))) &&
1642         (Arg0->hasOneUse() || Arg1->hasOneUse())) {
1643       // If both operands are negated, invert the call and negate the result:
1644       // min(-X, -Y) --> -(max(X, Y))
1645       // max(-X, -Y) --> -(min(X, Y))
1646       Intrinsic::ID NewIID;
1647       switch (IID) {
1648       case Intrinsic::maxnum:
1649         NewIID = Intrinsic::minnum;
1650         break;
1651       case Intrinsic::minnum:
1652         NewIID = Intrinsic::maxnum;
1653         break;
1654       case Intrinsic::maximum:
1655         NewIID = Intrinsic::minimum;
1656         break;
1657       case Intrinsic::minimum:
1658         NewIID = Intrinsic::maximum;
1659         break;
1660       default:
1661         llvm_unreachable("unexpected intrinsic ID");
1662       }
1663       Value *NewCall = Builder.CreateBinaryIntrinsic(NewIID, X, Y, II);
1664       Instruction *FNeg = UnaryOperator::CreateFNeg(NewCall);
1665       FNeg->copyIRFlags(II);
1666       return FNeg;
1667     }
1668 
1669     // m(m(X, C2), C1) -> m(X, C)
1670     const APFloat *C1, *C2;
1671     if (auto *M = dyn_cast<IntrinsicInst>(Arg0)) {
1672       if (M->getIntrinsicID() == IID && match(Arg1, m_APFloat(C1)) &&
1673           ((match(M->getArgOperand(0), m_Value(X)) &&
1674             match(M->getArgOperand(1), m_APFloat(C2))) ||
1675            (match(M->getArgOperand(1), m_Value(X)) &&
1676             match(M->getArgOperand(0), m_APFloat(C2))))) {
1677         APFloat Res(0.0);
1678         switch (IID) {
1679         case Intrinsic::maxnum:
1680           Res = maxnum(*C1, *C2);
1681           break;
1682         case Intrinsic::minnum:
1683           Res = minnum(*C1, *C2);
1684           break;
1685         case Intrinsic::maximum:
1686           Res = maximum(*C1, *C2);
1687           break;
1688         case Intrinsic::minimum:
1689           Res = minimum(*C1, *C2);
1690           break;
1691         default:
1692           llvm_unreachable("unexpected intrinsic ID");
1693         }
1694         Instruction *NewCall = Builder.CreateBinaryIntrinsic(
1695             IID, X, ConstantFP::get(Arg0->getType(), Res), II);
1696         // TODO: Conservatively intersecting FMF. If Res == C2, the transform
1697         //       was a simplification (so Arg0 and its original flags could
1698         //       propagate?)
1699         NewCall->andIRFlags(M);
1700         return replaceInstUsesWith(*II, NewCall);
1701       }
1702     }
1703 
1704     // m((fpext X), (fpext Y)) -> fpext (m(X, Y))
1705     if (match(Arg0, m_OneUse(m_FPExt(m_Value(X)))) &&
1706         match(Arg1, m_OneUse(m_FPExt(m_Value(Y)))) &&
1707         X->getType() == Y->getType()) {
1708       Value *NewCall =
1709           Builder.CreateBinaryIntrinsic(IID, X, Y, II, II->getName());
1710       return new FPExtInst(NewCall, II->getType());
1711     }
1712 
1713     // max X, -X --> fabs X
1714     // min X, -X --> -(fabs X)
1715     // TODO: Remove one-use limitation? That is obviously better for max.
1716     //       It would be an extra instruction for min (fnabs), but that is
1717     //       still likely better for analysis and codegen.
1718     if ((match(Arg0, m_OneUse(m_FNeg(m_Value(X)))) && Arg1 == X) ||
1719         (match(Arg1, m_OneUse(m_FNeg(m_Value(X)))) && Arg0 == X)) {
1720       Value *R = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, X, II);
1721       if (IID == Intrinsic::minimum || IID == Intrinsic::minnum)
1722         R = Builder.CreateFNegFMF(R, II);
1723       return replaceInstUsesWith(*II, R);
1724     }
1725 
1726     break;
1727   }
1728   case Intrinsic::fmuladd: {
1729     // Canonicalize fast fmuladd to the separate fmul + fadd.
1730     if (II->isFast()) {
1731       BuilderTy::FastMathFlagGuard Guard(Builder);
1732       Builder.setFastMathFlags(II->getFastMathFlags());
1733       Value *Mul = Builder.CreateFMul(II->getArgOperand(0),
1734                                       II->getArgOperand(1));
1735       Value *Add = Builder.CreateFAdd(Mul, II->getArgOperand(2));
1736       Add->takeName(II);
1737       return replaceInstUsesWith(*II, Add);
1738     }
1739 
1740     // Try to simplify the underlying FMul.
1741     if (Value *V = SimplifyFMulInst(II->getArgOperand(0), II->getArgOperand(1),
1742                                     II->getFastMathFlags(),
1743                                     SQ.getWithInstruction(II))) {
1744       auto *FAdd = BinaryOperator::CreateFAdd(V, II->getArgOperand(2));
1745       FAdd->copyFastMathFlags(II);
1746       return FAdd;
1747     }
1748 
1749     LLVM_FALLTHROUGH;
1750   }
1751   case Intrinsic::fma: {
1752     // fma fneg(x), fneg(y), z -> fma x, y, z
1753     Value *Src0 = II->getArgOperand(0);
1754     Value *Src1 = II->getArgOperand(1);
1755     Value *X, *Y;
1756     if (match(Src0, m_FNeg(m_Value(X))) && match(Src1, m_FNeg(m_Value(Y)))) {
1757       replaceOperand(*II, 0, X);
1758       replaceOperand(*II, 1, Y);
1759       return II;
1760     }
1761 
1762     // fma fabs(x), fabs(x), z -> fma x, x, z
1763     if (match(Src0, m_FAbs(m_Value(X))) &&
1764         match(Src1, m_FAbs(m_Specific(X)))) {
1765       replaceOperand(*II, 0, X);
1766       replaceOperand(*II, 1, X);
1767       return II;
1768     }
1769 
1770     // Try to simplify the underlying FMul. We can only apply simplifications
1771     // that do not require rounding.
1772     if (Value *V = SimplifyFMAFMul(II->getArgOperand(0), II->getArgOperand(1),
1773                                    II->getFastMathFlags(),
1774                                    SQ.getWithInstruction(II))) {
1775       auto *FAdd = BinaryOperator::CreateFAdd(V, II->getArgOperand(2));
1776       FAdd->copyFastMathFlags(II);
1777       return FAdd;
1778     }
1779 
1780     // fma x, y, 0 -> fmul x, y
1781     // This is always valid for -0.0, but requires nsz for +0.0 as
1782     // -0.0 + 0.0 = 0.0, which would not be the same as the fmul on its own.
1783     if (match(II->getArgOperand(2), m_NegZeroFP()) ||
1784         (match(II->getArgOperand(2), m_PosZeroFP()) &&
1785          II->getFastMathFlags().noSignedZeros()))
1786       return BinaryOperator::CreateFMulFMF(Src0, Src1, II);
1787 
1788     break;
1789   }
1790   case Intrinsic::copysign: {
1791     Value *Mag = II->getArgOperand(0), *Sign = II->getArgOperand(1);
1792     if (SignBitMustBeZero(Sign, &TLI)) {
1793       // If we know that the sign argument is positive, reduce to FABS:
1794       // copysign Mag, +Sign --> fabs Mag
1795       Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, Mag, II);
1796       return replaceInstUsesWith(*II, Fabs);
1797     }
1798     // TODO: There should be a ValueTracking sibling like SignBitMustBeOne.
1799     const APFloat *C;
1800     if (match(Sign, m_APFloat(C)) && C->isNegative()) {
1801       // If we know that the sign argument is negative, reduce to FNABS:
1802       // copysign Mag, -Sign --> fneg (fabs Mag)
1803       Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, Mag, II);
1804       return replaceInstUsesWith(*II, Builder.CreateFNegFMF(Fabs, II));
1805     }
1806 
1807     // Propagate sign argument through nested calls:
1808     // copysign Mag, (copysign ?, X) --> copysign Mag, X
1809     Value *X;
1810     if (match(Sign, m_Intrinsic<Intrinsic::copysign>(m_Value(), m_Value(X))))
1811       return replaceOperand(*II, 1, X);
1812 
1813     // Peek through changes of magnitude's sign-bit. This call rewrites those:
1814     // copysign (fabs X), Sign --> copysign X, Sign
1815     // copysign (fneg X), Sign --> copysign X, Sign
1816     if (match(Mag, m_FAbs(m_Value(X))) || match(Mag, m_FNeg(m_Value(X))))
1817       return replaceOperand(*II, 0, X);
1818 
1819     break;
1820   }
1821   case Intrinsic::fabs: {
1822     Value *Cond, *TVal, *FVal;
1823     if (match(II->getArgOperand(0),
1824               m_Select(m_Value(Cond), m_Value(TVal), m_Value(FVal)))) {
1825       // fabs (select Cond, TrueC, FalseC) --> select Cond, AbsT, AbsF
1826       if (isa<Constant>(TVal) && isa<Constant>(FVal)) {
1827         CallInst *AbsT = Builder.CreateCall(II->getCalledFunction(), {TVal});
1828         CallInst *AbsF = Builder.CreateCall(II->getCalledFunction(), {FVal});
1829         return SelectInst::Create(Cond, AbsT, AbsF);
1830       }
1831       // fabs (select Cond, -FVal, FVal) --> fabs FVal
1832       if (match(TVal, m_FNeg(m_Specific(FVal))))
1833         return replaceOperand(*II, 0, FVal);
1834       // fabs (select Cond, TVal, -TVal) --> fabs TVal
1835       if (match(FVal, m_FNeg(m_Specific(TVal))))
1836         return replaceOperand(*II, 0, TVal);
1837     }
1838 
1839     LLVM_FALLTHROUGH;
1840   }
1841   case Intrinsic::ceil:
1842   case Intrinsic::floor:
1843   case Intrinsic::round:
1844   case Intrinsic::roundeven:
1845   case Intrinsic::nearbyint:
1846   case Intrinsic::rint:
1847   case Intrinsic::trunc: {
1848     Value *ExtSrc;
1849     if (match(II->getArgOperand(0), m_OneUse(m_FPExt(m_Value(ExtSrc))))) {
1850       // Narrow the call: intrinsic (fpext x) -> fpext (intrinsic x)
1851       Value *NarrowII = Builder.CreateUnaryIntrinsic(IID, ExtSrc, II);
1852       return new FPExtInst(NarrowII, II->getType());
1853     }
1854     break;
1855   }
1856   case Intrinsic::cos:
1857   case Intrinsic::amdgcn_cos: {
1858     Value *X;
1859     Value *Src = II->getArgOperand(0);
1860     if (match(Src, m_FNeg(m_Value(X))) || match(Src, m_FAbs(m_Value(X)))) {
1861       // cos(-x) -> cos(x)
1862       // cos(fabs(x)) -> cos(x)
1863       return replaceOperand(*II, 0, X);
1864     }
1865     break;
1866   }
1867   case Intrinsic::sin: {
1868     Value *X;
1869     if (match(II->getArgOperand(0), m_OneUse(m_FNeg(m_Value(X))))) {
1870       // sin(-x) --> -sin(x)
1871       Value *NewSin = Builder.CreateUnaryIntrinsic(Intrinsic::sin, X, II);
1872       Instruction *FNeg = UnaryOperator::CreateFNeg(NewSin);
1873       FNeg->copyFastMathFlags(II);
1874       return FNeg;
1875     }
1876     break;
1877   }
1878 
1879   case Intrinsic::arm_neon_vtbl1:
1880   case Intrinsic::aarch64_neon_tbl1:
1881     if (Value *V = simplifyNeonTbl1(*II, Builder))
1882       return replaceInstUsesWith(*II, V);
1883     break;
1884 
1885   case Intrinsic::arm_neon_vmulls:
1886   case Intrinsic::arm_neon_vmullu:
1887   case Intrinsic::aarch64_neon_smull:
1888   case Intrinsic::aarch64_neon_umull: {
1889     Value *Arg0 = II->getArgOperand(0);
1890     Value *Arg1 = II->getArgOperand(1);
1891 
1892     // Handle mul by zero first:
1893     if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) {
1894       return replaceInstUsesWith(CI, ConstantAggregateZero::get(II->getType()));
1895     }
1896 
1897     // Check for constant LHS & RHS - in this case we just simplify.
1898     bool Zext = (IID == Intrinsic::arm_neon_vmullu ||
1899                  IID == Intrinsic::aarch64_neon_umull);
1900     VectorType *NewVT = cast<VectorType>(II->getType());
1901     if (Constant *CV0 = dyn_cast<Constant>(Arg0)) {
1902       if (Constant *CV1 = dyn_cast<Constant>(Arg1)) {
1903         CV0 = ConstantExpr::getIntegerCast(CV0, NewVT, /*isSigned=*/!Zext);
1904         CV1 = ConstantExpr::getIntegerCast(CV1, NewVT, /*isSigned=*/!Zext);
1905 
1906         return replaceInstUsesWith(CI, ConstantExpr::getMul(CV0, CV1));
1907       }
1908 
1909       // Couldn't simplify - canonicalize constant to the RHS.
1910       std::swap(Arg0, Arg1);
1911     }
1912 
1913     // Handle mul by one:
1914     if (Constant *CV1 = dyn_cast<Constant>(Arg1))
1915       if (ConstantInt *Splat =
1916               dyn_cast_or_null<ConstantInt>(CV1->getSplatValue()))
1917         if (Splat->isOne())
1918           return CastInst::CreateIntegerCast(Arg0, II->getType(),
1919                                              /*isSigned=*/!Zext);
1920 
1921     break;
1922   }
1923   case Intrinsic::arm_neon_aesd:
1924   case Intrinsic::arm_neon_aese:
1925   case Intrinsic::aarch64_crypto_aesd:
1926   case Intrinsic::aarch64_crypto_aese: {
1927     Value *DataArg = II->getArgOperand(0);
1928     Value *KeyArg  = II->getArgOperand(1);
1929 
1930     // Try to use the builtin XOR in AESE and AESD to eliminate a prior XOR
1931     Value *Data, *Key;
1932     if (match(KeyArg, m_ZeroInt()) &&
1933         match(DataArg, m_Xor(m_Value(Data), m_Value(Key)))) {
1934       replaceOperand(*II, 0, Data);
1935       replaceOperand(*II, 1, Key);
1936       return II;
1937     }
1938     break;
1939   }
1940   case Intrinsic::hexagon_V6_vandvrt:
1941   case Intrinsic::hexagon_V6_vandvrt_128B: {
1942     // Simplify Q -> V -> Q conversion.
1943     if (auto Op0 = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
1944       Intrinsic::ID ID0 = Op0->getIntrinsicID();
1945       if (ID0 != Intrinsic::hexagon_V6_vandqrt &&
1946           ID0 != Intrinsic::hexagon_V6_vandqrt_128B)
1947         break;
1948       Value *Bytes = Op0->getArgOperand(1), *Mask = II->getArgOperand(1);
1949       uint64_t Bytes1 = computeKnownBits(Bytes, 0, Op0).One.getZExtValue();
1950       uint64_t Mask1 = computeKnownBits(Mask, 0, II).One.getZExtValue();
1951       // Check if every byte has common bits in Bytes and Mask.
1952       uint64_t C = Bytes1 & Mask1;
1953       if ((C & 0xFF) && (C & 0xFF00) && (C & 0xFF0000) && (C & 0xFF000000))
1954         return replaceInstUsesWith(*II, Op0->getArgOperand(0));
1955     }
1956     break;
1957   }
1958   case Intrinsic::stackrestore: {
1959     enum class ClassifyResult {
1960       None,
1961       Alloca,
1962       StackRestore,
1963       CallWithSideEffects,
1964     };
1965     auto Classify = [](const Instruction *I) {
1966       if (isa<AllocaInst>(I))
1967         return ClassifyResult::Alloca;
1968 
1969       if (auto *CI = dyn_cast<CallInst>(I)) {
1970         if (auto *II = dyn_cast<IntrinsicInst>(CI)) {
1971           if (II->getIntrinsicID() == Intrinsic::stackrestore)
1972             return ClassifyResult::StackRestore;
1973 
1974           if (II->mayHaveSideEffects())
1975             return ClassifyResult::CallWithSideEffects;
1976         } else {
1977           // Consider all non-intrinsic calls to be side effects
1978           return ClassifyResult::CallWithSideEffects;
1979         }
1980       }
1981 
1982       return ClassifyResult::None;
1983     };
1984 
1985     // If the stacksave and the stackrestore are in the same BB, and there is
1986     // no intervening call, alloca, or stackrestore of a different stacksave,
1987     // remove the restore. This can happen when variable allocas are DCE'd.
1988     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
1989       if (SS->getIntrinsicID() == Intrinsic::stacksave &&
1990           SS->getParent() == II->getParent()) {
1991         BasicBlock::iterator BI(SS);
1992         bool CannotRemove = false;
1993         for (++BI; &*BI != II; ++BI) {
1994           switch (Classify(&*BI)) {
1995           case ClassifyResult::None:
1996             // So far so good, look at next instructions.
1997             break;
1998 
1999           case ClassifyResult::StackRestore:
2000             // If we found an intervening stackrestore for a different
2001             // stacksave, we can't remove the stackrestore. Otherwise, continue.
2002             if (cast<IntrinsicInst>(*BI).getArgOperand(0) != SS)
2003               CannotRemove = true;
2004             break;
2005 
2006           case ClassifyResult::Alloca:
2007           case ClassifyResult::CallWithSideEffects:
2008             // If we found an alloca, a non-intrinsic call, or an intrinsic
2009             // call with side effects, we can't remove the stackrestore.
2010             CannotRemove = true;
2011             break;
2012           }
2013           if (CannotRemove)
2014             break;
2015         }
2016 
2017         if (!CannotRemove)
2018           return eraseInstFromFunction(CI);
2019       }
2020     }
2021 
2022     // Scan down this block to see if there is another stack restore in the
2023     // same block without an intervening call/alloca.
2024     BasicBlock::iterator BI(II);
2025     Instruction *TI = II->getParent()->getTerminator();
2026     bool CannotRemove = false;
2027     for (++BI; &*BI != TI; ++BI) {
2028       switch (Classify(&*BI)) {
2029       case ClassifyResult::None:
2030         // So far so good, look at next instructions.
2031         break;
2032 
2033       case ClassifyResult::StackRestore:
2034         // If there is a stackrestore below this one, remove this one.
2035         return eraseInstFromFunction(CI);
2036 
2037       case ClassifyResult::Alloca:
2038       case ClassifyResult::CallWithSideEffects:
2039         // If we found an alloca, a non-intrinsic call, or an intrinsic call
2040         // with side effects (such as llvm.stacksave and llvm.read_register),
2041         // we can't remove the stack restore.
2042         CannotRemove = true;
2043         break;
2044       }
2045       if (CannotRemove)
2046         break;
2047     }
2048 
2049     // If the stack restore is in a return, resume, or unwind block and if there
2050     // are no allocas or calls between the restore and the return, nuke the
2051     // restore.
2052     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI)))
2053       return eraseInstFromFunction(CI);
2054     break;
2055   }
2056   case Intrinsic::lifetime_end:
2057     // Asan needs to poison memory to detect invalid access which is possible
2058     // even for empty lifetime range.
2059     if (II->getFunction()->hasFnAttribute(Attribute::SanitizeAddress) ||
2060         II->getFunction()->hasFnAttribute(Attribute::SanitizeMemory) ||
2061         II->getFunction()->hasFnAttribute(Attribute::SanitizeHWAddress))
2062       break;
2063 
2064     if (removeTriviallyEmptyRange(*II, *this, [](const IntrinsicInst &I) {
2065           return I.getIntrinsicID() == Intrinsic::lifetime_start;
2066         }))
2067       return nullptr;
2068     break;
2069   case Intrinsic::assume: {
2070     Value *IIOperand = II->getArgOperand(0);
2071     SmallVector<OperandBundleDef, 4> OpBundles;
2072     II->getOperandBundlesAsDefs(OpBundles);
2073 
2074     /// This will remove the boolean Condition from the assume given as
2075     /// argument and remove the assume if it becomes useless.
2076     /// always returns nullptr for use as a return values.
2077     auto RemoveConditionFromAssume = [&](Instruction *Assume) -> Instruction * {
2078       assert(isa<AssumeInst>(Assume));
2079       if (isAssumeWithEmptyBundle(*cast<AssumeInst>(II)))
2080         return eraseInstFromFunction(CI);
2081       replaceUse(II->getOperandUse(0), ConstantInt::getTrue(II->getContext()));
2082       return nullptr;
2083     };
2084     // Remove an assume if it is followed by an identical assume.
2085     // TODO: Do we need this? Unless there are conflicting assumptions, the
2086     // computeKnownBits(IIOperand) below here eliminates redundant assumes.
2087     Instruction *Next = II->getNextNonDebugInstruction();
2088     if (match(Next, m_Intrinsic<Intrinsic::assume>(m_Specific(IIOperand))))
2089       return RemoveConditionFromAssume(Next);
2090 
2091     // Canonicalize assume(a && b) -> assume(a); assume(b);
2092     // Note: New assumption intrinsics created here are registered by
2093     // the InstCombineIRInserter object.
2094     FunctionType *AssumeIntrinsicTy = II->getFunctionType();
2095     Value *AssumeIntrinsic = II->getCalledOperand();
2096     Value *A, *B;
2097     if (match(IIOperand, m_LogicalAnd(m_Value(A), m_Value(B)))) {
2098       Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic, A, OpBundles,
2099                          II->getName());
2100       Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic, B, II->getName());
2101       return eraseInstFromFunction(*II);
2102     }
2103     // assume(!(a || b)) -> assume(!a); assume(!b);
2104     if (match(IIOperand, m_Not(m_LogicalOr(m_Value(A), m_Value(B))))) {
2105       Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic,
2106                          Builder.CreateNot(A), OpBundles, II->getName());
2107       Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic,
2108                          Builder.CreateNot(B), II->getName());
2109       return eraseInstFromFunction(*II);
2110     }
2111 
2112     // assume( (load addr) != null ) -> add 'nonnull' metadata to load
2113     // (if assume is valid at the load)
2114     CmpInst::Predicate Pred;
2115     Instruction *LHS;
2116     if (match(IIOperand, m_ICmp(Pred, m_Instruction(LHS), m_Zero())) &&
2117         Pred == ICmpInst::ICMP_NE && LHS->getOpcode() == Instruction::Load &&
2118         LHS->getType()->isPointerTy() &&
2119         isValidAssumeForContext(II, LHS, &DT)) {
2120       MDNode *MD = MDNode::get(II->getContext(), None);
2121       LHS->setMetadata(LLVMContext::MD_nonnull, MD);
2122       return RemoveConditionFromAssume(II);
2123 
2124       // TODO: apply nonnull return attributes to calls and invokes
2125       // TODO: apply range metadata for range check patterns?
2126     }
2127 
2128     // Convert nonnull assume like:
2129     // %A = icmp ne i32* %PTR, null
2130     // call void @llvm.assume(i1 %A)
2131     // into
2132     // call void @llvm.assume(i1 true) [ "nonnull"(i32* %PTR) ]
2133     if (EnableKnowledgeRetention &&
2134         match(IIOperand, m_Cmp(Pred, m_Value(A), m_Zero())) &&
2135         Pred == CmpInst::ICMP_NE && A->getType()->isPointerTy()) {
2136       if (auto *Replacement = buildAssumeFromKnowledge(
2137               {RetainedKnowledge{Attribute::NonNull, 0, A}}, Next, &AC, &DT)) {
2138 
2139         Replacement->insertBefore(Next);
2140         AC.registerAssumption(Replacement);
2141         return RemoveConditionFromAssume(II);
2142       }
2143     }
2144 
2145     // Convert alignment assume like:
2146     // %B = ptrtoint i32* %A to i64
2147     // %C = and i64 %B, Constant
2148     // %D = icmp eq i64 %C, 0
2149     // call void @llvm.assume(i1 %D)
2150     // into
2151     // call void @llvm.assume(i1 true) [ "align"(i32* [[A]], i64  Constant + 1)]
2152     uint64_t AlignMask;
2153     if (EnableKnowledgeRetention &&
2154         match(IIOperand,
2155               m_Cmp(Pred, m_And(m_Value(A), m_ConstantInt(AlignMask)),
2156                     m_Zero())) &&
2157         Pred == CmpInst::ICMP_EQ) {
2158       if (isPowerOf2_64(AlignMask + 1)) {
2159         uint64_t Offset = 0;
2160         match(A, m_Add(m_Value(A), m_ConstantInt(Offset)));
2161         if (match(A, m_PtrToInt(m_Value(A)))) {
2162           /// Note: this doesn't preserve the offset information but merges
2163           /// offset and alignment.
2164           /// TODO: we can generate a GEP instead of merging the alignment with
2165           /// the offset.
2166           RetainedKnowledge RK{Attribute::Alignment,
2167                                (unsigned)MinAlign(Offset, AlignMask + 1), A};
2168           if (auto *Replacement =
2169                   buildAssumeFromKnowledge(RK, Next, &AC, &DT)) {
2170 
2171             Replacement->insertAfter(II);
2172             AC.registerAssumption(Replacement);
2173           }
2174           return RemoveConditionFromAssume(II);
2175         }
2176       }
2177     }
2178 
2179     /// Canonicalize Knowledge in operand bundles.
2180     if (EnableKnowledgeRetention && II->hasOperandBundles()) {
2181       for (unsigned Idx = 0; Idx < II->getNumOperandBundles(); Idx++) {
2182         auto &BOI = II->bundle_op_info_begin()[Idx];
2183         RetainedKnowledge RK =
2184           llvm::getKnowledgeFromBundle(cast<AssumeInst>(*II), BOI);
2185         if (BOI.End - BOI.Begin > 2)
2186           continue; // Prevent reducing knowledge in an align with offset since
2187                     // extracting a RetainedKnowledge form them looses offset
2188                     // information
2189         RetainedKnowledge CanonRK =
2190           llvm::simplifyRetainedKnowledge(cast<AssumeInst>(II), RK,
2191                                           &getAssumptionCache(),
2192                                           &getDominatorTree());
2193         if (CanonRK == RK)
2194           continue;
2195         if (!CanonRK) {
2196           if (BOI.End - BOI.Begin > 0) {
2197             Worklist.pushValue(II->op_begin()[BOI.Begin]);
2198             Value::dropDroppableUse(II->op_begin()[BOI.Begin]);
2199           }
2200           continue;
2201         }
2202         assert(RK.AttrKind == CanonRK.AttrKind);
2203         if (BOI.End - BOI.Begin > 0)
2204           II->op_begin()[BOI.Begin].set(CanonRK.WasOn);
2205         if (BOI.End - BOI.Begin > 1)
2206           II->op_begin()[BOI.Begin + 1].set(ConstantInt::get(
2207               Type::getInt64Ty(II->getContext()), CanonRK.ArgValue));
2208         if (RK.WasOn)
2209           Worklist.pushValue(RK.WasOn);
2210         return II;
2211       }
2212     }
2213 
2214     // If there is a dominating assume with the same condition as this one,
2215     // then this one is redundant, and should be removed.
2216     KnownBits Known(1);
2217     computeKnownBits(IIOperand, Known, 0, II);
2218     if (Known.isAllOnes() && isAssumeWithEmptyBundle(cast<AssumeInst>(*II)))
2219       return eraseInstFromFunction(*II);
2220 
2221     // Update the cache of affected values for this assumption (we might be
2222     // here because we just simplified the condition).
2223     AC.updateAffectedValues(cast<AssumeInst>(II));
2224     break;
2225   }
2226   case Intrinsic::experimental_guard: {
2227     // Is this guard followed by another guard?  We scan forward over a small
2228     // fixed window of instructions to handle common cases with conditions
2229     // computed between guards.
2230     Instruction *NextInst = II->getNextNonDebugInstruction();
2231     for (unsigned i = 0; i < GuardWideningWindow; i++) {
2232       // Note: Using context-free form to avoid compile time blow up
2233       if (!isSafeToSpeculativelyExecute(NextInst))
2234         break;
2235       NextInst = NextInst->getNextNonDebugInstruction();
2236     }
2237     Value *NextCond = nullptr;
2238     if (match(NextInst,
2239               m_Intrinsic<Intrinsic::experimental_guard>(m_Value(NextCond)))) {
2240       Value *CurrCond = II->getArgOperand(0);
2241 
2242       // Remove a guard that it is immediately preceded by an identical guard.
2243       // Otherwise canonicalize guard(a); guard(b) -> guard(a & b).
2244       if (CurrCond != NextCond) {
2245         Instruction *MoveI = II->getNextNonDebugInstruction();
2246         while (MoveI != NextInst) {
2247           auto *Temp = MoveI;
2248           MoveI = MoveI->getNextNonDebugInstruction();
2249           Temp->moveBefore(II);
2250         }
2251         replaceOperand(*II, 0, Builder.CreateAnd(CurrCond, NextCond));
2252       }
2253       eraseInstFromFunction(*NextInst);
2254       return II;
2255     }
2256     break;
2257   }
2258   case Intrinsic::experimental_vector_insert: {
2259     Value *Vec = II->getArgOperand(0);
2260     Value *SubVec = II->getArgOperand(1);
2261     Value *Idx = II->getArgOperand(2);
2262     auto *DstTy = dyn_cast<FixedVectorType>(II->getType());
2263     auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType());
2264     auto *SubVecTy = dyn_cast<FixedVectorType>(SubVec->getType());
2265 
2266     // Only canonicalize if the destination vector, Vec, and SubVec are all
2267     // fixed vectors.
2268     if (DstTy && VecTy && SubVecTy) {
2269       unsigned DstNumElts = DstTy->getNumElements();
2270       unsigned VecNumElts = VecTy->getNumElements();
2271       unsigned SubVecNumElts = SubVecTy->getNumElements();
2272       unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
2273 
2274       // An insert that entirely overwrites Vec with SubVec is a nop.
2275       if (VecNumElts == SubVecNumElts)
2276         return replaceInstUsesWith(CI, SubVec);
2277 
2278       // Widen SubVec into a vector of the same width as Vec, since
2279       // shufflevector requires the two input vectors to be the same width.
2280       // Elements beyond the bounds of SubVec within the widened vector are
2281       // undefined.
2282       SmallVector<int, 8> WidenMask;
2283       unsigned i;
2284       for (i = 0; i != SubVecNumElts; ++i)
2285         WidenMask.push_back(i);
2286       for (; i != VecNumElts; ++i)
2287         WidenMask.push_back(UndefMaskElem);
2288 
2289       Value *WidenShuffle = Builder.CreateShuffleVector(SubVec, WidenMask);
2290 
2291       SmallVector<int, 8> Mask;
2292       for (unsigned i = 0; i != IdxN; ++i)
2293         Mask.push_back(i);
2294       for (unsigned i = DstNumElts; i != DstNumElts + SubVecNumElts; ++i)
2295         Mask.push_back(i);
2296       for (unsigned i = IdxN + SubVecNumElts; i != DstNumElts; ++i)
2297         Mask.push_back(i);
2298 
2299       Value *Shuffle = Builder.CreateShuffleVector(Vec, WidenShuffle, Mask);
2300       return replaceInstUsesWith(CI, Shuffle);
2301     }
2302     break;
2303   }
2304   case Intrinsic::experimental_vector_extract: {
2305     Value *Vec = II->getArgOperand(0);
2306     Value *Idx = II->getArgOperand(1);
2307 
2308     auto *DstTy = dyn_cast<FixedVectorType>(II->getType());
2309     auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType());
2310 
2311     // Only canonicalize if the the destination vector and Vec are fixed
2312     // vectors.
2313     if (DstTy && VecTy) {
2314       unsigned DstNumElts = DstTy->getNumElements();
2315       unsigned VecNumElts = VecTy->getNumElements();
2316       unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
2317 
2318       // Extracting the entirety of Vec is a nop.
2319       if (VecNumElts == DstNumElts) {
2320         replaceInstUsesWith(CI, Vec);
2321         return eraseInstFromFunction(CI);
2322       }
2323 
2324       SmallVector<int, 8> Mask;
2325       for (unsigned i = 0; i != DstNumElts; ++i)
2326         Mask.push_back(IdxN + i);
2327 
2328       Value *Shuffle = Builder.CreateShuffleVector(Vec, Mask);
2329       return replaceInstUsesWith(CI, Shuffle);
2330     }
2331     break;
2332   }
2333   case Intrinsic::experimental_vector_reverse: {
2334     Value *BO0, *BO1, *X, *Y;
2335     Value *Vec = II->getArgOperand(0);
2336     if (match(Vec, m_OneUse(m_BinOp(m_Value(BO0), m_Value(BO1))))) {
2337       auto *OldBinOp = cast<BinaryOperator>(Vec);
2338       if (match(BO0, m_Intrinsic<Intrinsic::experimental_vector_reverse>(
2339                          m_Value(X)))) {
2340         // rev(binop rev(X), rev(Y)) --> binop X, Y
2341         if (match(BO1, m_Intrinsic<Intrinsic::experimental_vector_reverse>(
2342                            m_Value(Y))))
2343           return replaceInstUsesWith(CI,
2344                                      BinaryOperator::CreateWithCopiedFlags(
2345                                          OldBinOp->getOpcode(), X, Y, OldBinOp,
2346                                          OldBinOp->getName(), II));
2347         // rev(binop rev(X), BO1Splat) --> binop X, BO1Splat
2348         if (isSplatValue(BO1))
2349           return replaceInstUsesWith(CI,
2350                                      BinaryOperator::CreateWithCopiedFlags(
2351                                          OldBinOp->getOpcode(), X, BO1,
2352                                          OldBinOp, OldBinOp->getName(), II));
2353       }
2354       // rev(binop BO0Splat, rev(Y)) --> binop BO0Splat, Y
2355       if (match(BO1, m_Intrinsic<Intrinsic::experimental_vector_reverse>(
2356                          m_Value(Y))) &&
2357           isSplatValue(BO0))
2358         return replaceInstUsesWith(CI, BinaryOperator::CreateWithCopiedFlags(
2359                                            OldBinOp->getOpcode(), BO0, Y,
2360                                            OldBinOp, OldBinOp->getName(), II));
2361     }
2362     // rev(unop rev(X)) --> unop X
2363     if (match(Vec, m_OneUse(m_UnOp(
2364                        m_Intrinsic<Intrinsic::experimental_vector_reverse>(
2365                            m_Value(X)))))) {
2366       auto *OldUnOp = cast<UnaryOperator>(Vec);
2367       auto *NewUnOp = UnaryOperator::CreateWithCopiedFlags(
2368           OldUnOp->getOpcode(), X, OldUnOp, OldUnOp->getName(), II);
2369       return replaceInstUsesWith(CI, NewUnOp);
2370     }
2371     break;
2372   }
2373   case Intrinsic::vector_reduce_or:
2374   case Intrinsic::vector_reduce_and: {
2375     // Canonicalize logical or/and reductions:
2376     // Or reduction for i1 is represented as:
2377     // %val = bitcast <ReduxWidth x i1> to iReduxWidth
2378     // %res = cmp ne iReduxWidth %val, 0
2379     // And reduction for i1 is represented as:
2380     // %val = bitcast <ReduxWidth x i1> to iReduxWidth
2381     // %res = cmp eq iReduxWidth %val, 11111
2382     Value *Arg = II->getArgOperand(0);
2383     Value *Vect;
2384     if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {
2385       if (auto *FTy = dyn_cast<FixedVectorType>(Vect->getType()))
2386         if (FTy->getElementType() == Builder.getInt1Ty()) {
2387           Value *Res = Builder.CreateBitCast(
2388               Vect, Builder.getIntNTy(FTy->getNumElements()));
2389           if (IID == Intrinsic::vector_reduce_and) {
2390             Res = Builder.CreateICmpEQ(
2391                 Res, ConstantInt::getAllOnesValue(Res->getType()));
2392           } else {
2393             assert(IID == Intrinsic::vector_reduce_or &&
2394                    "Expected or reduction.");
2395             Res = Builder.CreateIsNotNull(Res);
2396           }
2397           if (Arg != Vect)
2398             Res = Builder.CreateCast(cast<CastInst>(Arg)->getOpcode(), Res,
2399                                      II->getType());
2400           return replaceInstUsesWith(CI, Res);
2401         }
2402     }
2403     LLVM_FALLTHROUGH;
2404   }
2405   case Intrinsic::vector_reduce_add: {
2406     if (IID == Intrinsic::vector_reduce_add) {
2407       // Convert vector_reduce_add(ZExt(<n x i1>)) to
2408       // ZExtOrTrunc(ctpop(bitcast <n x i1> to in)).
2409       // Convert vector_reduce_add(SExt(<n x i1>)) to
2410       // -ZExtOrTrunc(ctpop(bitcast <n x i1> to in)).
2411       // Convert vector_reduce_add(<n x i1>) to
2412       // Trunc(ctpop(bitcast <n x i1> to in)).
2413       Value *Arg = II->getArgOperand(0);
2414       Value *Vect;
2415       if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {
2416         if (auto *FTy = dyn_cast<FixedVectorType>(Vect->getType()))
2417           if (FTy->getElementType() == Builder.getInt1Ty()) {
2418             Value *V = Builder.CreateBitCast(
2419                 Vect, Builder.getIntNTy(FTy->getNumElements()));
2420             Value *Res = Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, V);
2421             if (Res->getType() != II->getType())
2422               Res = Builder.CreateZExtOrTrunc(Res, II->getType());
2423             if (Arg != Vect &&
2424                 cast<Instruction>(Arg)->getOpcode() == Instruction::SExt)
2425               Res = Builder.CreateNeg(Res);
2426             return replaceInstUsesWith(CI, Res);
2427           }
2428       }
2429     }
2430     LLVM_FALLTHROUGH;
2431   }
2432   case Intrinsic::vector_reduce_xor: {
2433     if (IID == Intrinsic::vector_reduce_xor) {
2434       // Exclusive disjunction reduction over the vector with
2435       // (potentially-extended) i1 element type is actually a
2436       // (potentially-extended) arithmetic `add` reduction over the original
2437       // non-extended value:
2438       //   vector_reduce_xor(?ext(<n x i1>))
2439       //     -->
2440       //   ?ext(vector_reduce_add(<n x i1>))
2441       Value *Arg = II->getArgOperand(0);
2442       Value *Vect;
2443       if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {
2444         if (auto *FTy = dyn_cast<FixedVectorType>(Vect->getType()))
2445           if (FTy->getElementType() == Builder.getInt1Ty()) {
2446             Value *Res = Builder.CreateAddReduce(Vect);
2447             if (Arg != Vect)
2448               Res = Builder.CreateCast(cast<CastInst>(Arg)->getOpcode(), Res,
2449                                        II->getType());
2450             return replaceInstUsesWith(CI, Res);
2451           }
2452       }
2453     }
2454     LLVM_FALLTHROUGH;
2455   }
2456   case Intrinsic::vector_reduce_mul: {
2457     if (IID == Intrinsic::vector_reduce_mul) {
2458       // Multiplicative reduction over the vector with (potentially-extended)
2459       // i1 element type is actually a (potentially zero-extended)
2460       // logical `and` reduction over the original non-extended value:
2461       //   vector_reduce_mul(?ext(<n x i1>))
2462       //     -->
2463       //   zext(vector_reduce_and(<n x i1>))
2464       Value *Arg = II->getArgOperand(0);
2465       Value *Vect;
2466       if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {
2467         if (auto *FTy = dyn_cast<FixedVectorType>(Vect->getType()))
2468           if (FTy->getElementType() == Builder.getInt1Ty()) {
2469             Value *Res = Builder.CreateAndReduce(Vect);
2470             if (Res->getType() != II->getType())
2471               Res = Builder.CreateZExt(Res, II->getType());
2472             return replaceInstUsesWith(CI, Res);
2473           }
2474       }
2475     }
2476     LLVM_FALLTHROUGH;
2477   }
2478   case Intrinsic::vector_reduce_umin:
2479   case Intrinsic::vector_reduce_umax: {
2480     if (IID == Intrinsic::vector_reduce_umin ||
2481         IID == Intrinsic::vector_reduce_umax) {
2482       // UMin/UMax reduction over the vector with (potentially-extended)
2483       // i1 element type is actually a (potentially-extended)
2484       // logical `and`/`or` reduction over the original non-extended value:
2485       //   vector_reduce_u{min,max}(?ext(<n x i1>))
2486       //     -->
2487       //   ?ext(vector_reduce_{and,or}(<n x i1>))
2488       Value *Arg = II->getArgOperand(0);
2489       Value *Vect;
2490       if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {
2491         if (auto *FTy = dyn_cast<FixedVectorType>(Vect->getType()))
2492           if (FTy->getElementType() == Builder.getInt1Ty()) {
2493             Value *Res = IID == Intrinsic::vector_reduce_umin
2494                              ? Builder.CreateAndReduce(Vect)
2495                              : Builder.CreateOrReduce(Vect);
2496             if (Arg != Vect)
2497               Res = Builder.CreateCast(cast<CastInst>(Arg)->getOpcode(), Res,
2498                                        II->getType());
2499             return replaceInstUsesWith(CI, Res);
2500           }
2501       }
2502     }
2503     LLVM_FALLTHROUGH;
2504   }
2505   case Intrinsic::vector_reduce_smin:
2506   case Intrinsic::vector_reduce_smax: {
2507     if (IID == Intrinsic::vector_reduce_smin ||
2508         IID == Intrinsic::vector_reduce_smax) {
2509       // SMin/SMax reduction over the vector with (potentially-extended)
2510       // i1 element type is actually a (potentially-extended)
2511       // logical `and`/`or` reduction over the original non-extended value:
2512       //   vector_reduce_s{min,max}(<n x i1>)
2513       //     -->
2514       //   vector_reduce_{or,and}(<n x i1>)
2515       // and
2516       //   vector_reduce_s{min,max}(sext(<n x i1>))
2517       //     -->
2518       //   sext(vector_reduce_{or,and}(<n x i1>))
2519       // and
2520       //   vector_reduce_s{min,max}(zext(<n x i1>))
2521       //     -->
2522       //   zext(vector_reduce_{and,or}(<n x i1>))
2523       Value *Arg = II->getArgOperand(0);
2524       Value *Vect;
2525       if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {
2526         if (auto *FTy = dyn_cast<FixedVectorType>(Vect->getType()))
2527           if (FTy->getElementType() == Builder.getInt1Ty()) {
2528             Instruction::CastOps ExtOpc = Instruction::CastOps::CastOpsEnd;
2529             if (Arg != Vect)
2530               ExtOpc = cast<CastInst>(Arg)->getOpcode();
2531             Value *Res = ((IID == Intrinsic::vector_reduce_smin) ==
2532                           (ExtOpc == Instruction::CastOps::ZExt))
2533                              ? Builder.CreateAndReduce(Vect)
2534                              : Builder.CreateOrReduce(Vect);
2535             if (Arg != Vect)
2536               Res = Builder.CreateCast(ExtOpc, Res, II->getType());
2537             return replaceInstUsesWith(CI, Res);
2538           }
2539       }
2540     }
2541     LLVM_FALLTHROUGH;
2542   }
2543   case Intrinsic::vector_reduce_fmax:
2544   case Intrinsic::vector_reduce_fmin:
2545   case Intrinsic::vector_reduce_fadd:
2546   case Intrinsic::vector_reduce_fmul: {
2547     bool CanBeReassociated = (IID != Intrinsic::vector_reduce_fadd &&
2548                               IID != Intrinsic::vector_reduce_fmul) ||
2549                              II->hasAllowReassoc();
2550     const unsigned ArgIdx = (IID == Intrinsic::vector_reduce_fadd ||
2551                              IID == Intrinsic::vector_reduce_fmul)
2552                                 ? 1
2553                                 : 0;
2554     Value *Arg = II->getArgOperand(ArgIdx);
2555     Value *V;
2556     ArrayRef<int> Mask;
2557     if (!isa<FixedVectorType>(Arg->getType()) || !CanBeReassociated ||
2558         !match(Arg, m_Shuffle(m_Value(V), m_Undef(), m_Mask(Mask))) ||
2559         !cast<ShuffleVectorInst>(Arg)->isSingleSource())
2560       break;
2561     int Sz = Mask.size();
2562     SmallBitVector UsedIndices(Sz);
2563     for (int Idx : Mask) {
2564       if (Idx == UndefMaskElem || UsedIndices.test(Idx))
2565         break;
2566       UsedIndices.set(Idx);
2567     }
2568     // Can remove shuffle iff just shuffled elements, no repeats, undefs, or
2569     // other changes.
2570     if (UsedIndices.all()) {
2571       replaceUse(II->getOperandUse(ArgIdx), V);
2572       return nullptr;
2573     }
2574     break;
2575   }
2576   default: {
2577     // Handle target specific intrinsics
2578     Optional<Instruction *> V = targetInstCombineIntrinsic(*II);
2579     if (V.hasValue())
2580       return V.getValue();
2581     break;
2582   }
2583   }
2584   // Some intrinsics (like experimental_gc_statepoint) can be used in invoke
2585   // context, so it is handled in visitCallBase and we should trigger it.
2586   return visitCallBase(*II);
2587 }
2588 
2589 // Fence instruction simplification
2590 Instruction *InstCombinerImpl::visitFenceInst(FenceInst &FI) {
2591   auto *NFI = dyn_cast<FenceInst>(FI.getNextNonDebugInstruction());
2592   // This check is solely here to handle arbitrary target-dependent syncscopes.
2593   // TODO: Can remove if does not matter in practice.
2594   if (NFI && FI.isIdenticalTo(NFI))
2595     return eraseInstFromFunction(FI);
2596 
2597   // Returns true if FI1 is identical or stronger fence than FI2.
2598   auto isIdenticalOrStrongerFence = [](FenceInst *FI1, FenceInst *FI2) {
2599     auto FI1SyncScope = FI1->getSyncScopeID();
2600     // Consider same scope, where scope is global or single-thread.
2601     if (FI1SyncScope != FI2->getSyncScopeID() ||
2602         (FI1SyncScope != SyncScope::System &&
2603          FI1SyncScope != SyncScope::SingleThread))
2604       return false;
2605 
2606     return isAtLeastOrStrongerThan(FI1->getOrdering(), FI2->getOrdering());
2607   };
2608   if (NFI && isIdenticalOrStrongerFence(NFI, &FI))
2609     return eraseInstFromFunction(FI);
2610 
2611   if (auto *PFI = dyn_cast_or_null<FenceInst>(FI.getPrevNonDebugInstruction()))
2612     if (isIdenticalOrStrongerFence(PFI, &FI))
2613       return eraseInstFromFunction(FI);
2614   return nullptr;
2615 }
2616 
2617 // InvokeInst simplification
2618 Instruction *InstCombinerImpl::visitInvokeInst(InvokeInst &II) {
2619   return visitCallBase(II);
2620 }
2621 
2622 // CallBrInst simplification
2623 Instruction *InstCombinerImpl::visitCallBrInst(CallBrInst &CBI) {
2624   return visitCallBase(CBI);
2625 }
2626 
2627 /// If this cast does not affect the value passed through the varargs area, we
2628 /// can eliminate the use of the cast.
2629 static bool isSafeToEliminateVarargsCast(const CallBase &Call,
2630                                          const DataLayout &DL,
2631                                          const CastInst *const CI,
2632                                          const int ix) {
2633   if (!CI->isLosslessCast())
2634     return false;
2635 
2636   // If this is a GC intrinsic, avoid munging types.  We need types for
2637   // statepoint reconstruction in SelectionDAG.
2638   // TODO: This is probably something which should be expanded to all
2639   // intrinsics since the entire point of intrinsics is that
2640   // they are understandable by the optimizer.
2641   if (isa<GCStatepointInst>(Call) || isa<GCRelocateInst>(Call) ||
2642       isa<GCResultInst>(Call))
2643     return false;
2644 
2645   // Opaque pointers are compatible with any byval types.
2646   PointerType *SrcTy = cast<PointerType>(CI->getOperand(0)->getType());
2647   if (SrcTy->isOpaque())
2648     return true;
2649 
2650   // The size of ByVal or InAlloca arguments is derived from the type, so we
2651   // can't change to a type with a different size.  If the size were
2652   // passed explicitly we could avoid this check.
2653   if (!Call.isPassPointeeByValueArgument(ix))
2654     return true;
2655 
2656   // The transform currently only handles type replacement for byval, not other
2657   // type-carrying attributes.
2658   if (!Call.isByValArgument(ix))
2659     return false;
2660 
2661   Type *SrcElemTy = SrcTy->getNonOpaquePointerElementType();
2662   Type *DstElemTy = Call.getParamByValType(ix);
2663   if (!SrcElemTy->isSized() || !DstElemTy->isSized())
2664     return false;
2665   if (DL.getTypeAllocSize(SrcElemTy) != DL.getTypeAllocSize(DstElemTy))
2666     return false;
2667   return true;
2668 }
2669 
2670 Instruction *InstCombinerImpl::tryOptimizeCall(CallInst *CI) {
2671   if (!CI->getCalledFunction()) return nullptr;
2672 
2673   // Skip optimizing notail and musttail calls so
2674   // LibCallSimplifier::optimizeCall doesn't have to preserve those invariants.
2675   // LibCallSimplifier::optimizeCall should try to preseve tail calls though.
2676   if (CI->isMustTailCall() || CI->isNoTailCall())
2677     return nullptr;
2678 
2679   auto InstCombineRAUW = [this](Instruction *From, Value *With) {
2680     replaceInstUsesWith(*From, With);
2681   };
2682   auto InstCombineErase = [this](Instruction *I) {
2683     eraseInstFromFunction(*I);
2684   };
2685   LibCallSimplifier Simplifier(DL, &TLI, ORE, BFI, PSI, InstCombineRAUW,
2686                                InstCombineErase);
2687   if (Value *With = Simplifier.optimizeCall(CI, Builder)) {
2688     ++NumSimplified;
2689     return CI->use_empty() ? CI : replaceInstUsesWith(*CI, With);
2690   }
2691 
2692   return nullptr;
2693 }
2694 
2695 static IntrinsicInst *findInitTrampolineFromAlloca(Value *TrampMem) {
2696   // Strip off at most one level of pointer casts, looking for an alloca.  This
2697   // is good enough in practice and simpler than handling any number of casts.
2698   Value *Underlying = TrampMem->stripPointerCasts();
2699   if (Underlying != TrampMem &&
2700       (!Underlying->hasOneUse() || Underlying->user_back() != TrampMem))
2701     return nullptr;
2702   if (!isa<AllocaInst>(Underlying))
2703     return nullptr;
2704 
2705   IntrinsicInst *InitTrampoline = nullptr;
2706   for (User *U : TrampMem->users()) {
2707     IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
2708     if (!II)
2709       return nullptr;
2710     if (II->getIntrinsicID() == Intrinsic::init_trampoline) {
2711       if (InitTrampoline)
2712         // More than one init_trampoline writes to this value.  Give up.
2713         return nullptr;
2714       InitTrampoline = II;
2715       continue;
2716     }
2717     if (II->getIntrinsicID() == Intrinsic::adjust_trampoline)
2718       // Allow any number of calls to adjust.trampoline.
2719       continue;
2720     return nullptr;
2721   }
2722 
2723   // No call to init.trampoline found.
2724   if (!InitTrampoline)
2725     return nullptr;
2726 
2727   // Check that the alloca is being used in the expected way.
2728   if (InitTrampoline->getOperand(0) != TrampMem)
2729     return nullptr;
2730 
2731   return InitTrampoline;
2732 }
2733 
2734 static IntrinsicInst *findInitTrampolineFromBB(IntrinsicInst *AdjustTramp,
2735                                                Value *TrampMem) {
2736   // Visit all the previous instructions in the basic block, and try to find a
2737   // init.trampoline which has a direct path to the adjust.trampoline.
2738   for (BasicBlock::iterator I = AdjustTramp->getIterator(),
2739                             E = AdjustTramp->getParent()->begin();
2740        I != E;) {
2741     Instruction *Inst = &*--I;
2742     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2743       if (II->getIntrinsicID() == Intrinsic::init_trampoline &&
2744           II->getOperand(0) == TrampMem)
2745         return II;
2746     if (Inst->mayWriteToMemory())
2747       return nullptr;
2748   }
2749   return nullptr;
2750 }
2751 
2752 // Given a call to llvm.adjust.trampoline, find and return the corresponding
2753 // call to llvm.init.trampoline if the call to the trampoline can be optimized
2754 // to a direct call to a function.  Otherwise return NULL.
2755 static IntrinsicInst *findInitTrampoline(Value *Callee) {
2756   Callee = Callee->stripPointerCasts();
2757   IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee);
2758   if (!AdjustTramp ||
2759       AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline)
2760     return nullptr;
2761 
2762   Value *TrampMem = AdjustTramp->getOperand(0);
2763 
2764   if (IntrinsicInst *IT = findInitTrampolineFromAlloca(TrampMem))
2765     return IT;
2766   if (IntrinsicInst *IT = findInitTrampolineFromBB(AdjustTramp, TrampMem))
2767     return IT;
2768   return nullptr;
2769 }
2770 
2771 void InstCombinerImpl::annotateAnyAllocSite(CallBase &Call, const TargetLibraryInfo *TLI) {
2772   // Note: We only handle cases which can't be driven from generic attributes
2773   // here.  So, for example, nonnull and noalias (which are common properties
2774   // of some allocation functions) are expected to be handled via annotation
2775   // of the respective allocator declaration with generic attributes.
2776 
2777   uint64_t Size;
2778   ObjectSizeOpts Opts;
2779   if (getObjectSize(&Call, Size, DL, TLI, Opts) && Size > 0) {
2780     // TODO: We really should just emit deref_or_null here and then
2781     // let the generic inference code combine that with nonnull.
2782     if (Call.hasRetAttr(Attribute::NonNull))
2783       Call.addRetAttr(Attribute::getWithDereferenceableBytes(
2784           Call.getContext(), Size));
2785     else
2786       Call.addRetAttr(Attribute::getWithDereferenceableOrNullBytes(
2787           Call.getContext(), Size));
2788   }
2789 
2790   // Add alignment attribute if alignment is a power of two constant.
2791   Value *Alignment = getAllocAlignment(&Call, TLI);
2792   if (!Alignment)
2793     return;
2794 
2795   ConstantInt *AlignOpC = dyn_cast<ConstantInt>(Alignment);
2796   if (AlignOpC && AlignOpC->getValue().ult(llvm::Value::MaximumAlignment)) {
2797     uint64_t AlignmentVal = AlignOpC->getZExtValue();
2798     if (llvm::isPowerOf2_64(AlignmentVal)) {
2799       Call.removeRetAttr(Attribute::Alignment);
2800       Call.addRetAttr(Attribute::getWithAlignment(Call.getContext(),
2801                                                   Align(AlignmentVal)));
2802     }
2803   }
2804 }
2805 
2806 /// Improvements for call, callbr and invoke instructions.
2807 Instruction *InstCombinerImpl::visitCallBase(CallBase &Call) {
2808   if (isAllocationFn(&Call, &TLI))
2809     annotateAnyAllocSite(Call, &TLI);
2810 
2811   bool Changed = false;
2812 
2813   // Mark any parameters that are known to be non-null with the nonnull
2814   // attribute.  This is helpful for inlining calls to functions with null
2815   // checks on their arguments.
2816   SmallVector<unsigned, 4> ArgNos;
2817   unsigned ArgNo = 0;
2818 
2819   for (Value *V : Call.args()) {
2820     if (V->getType()->isPointerTy() &&
2821         !Call.paramHasAttr(ArgNo, Attribute::NonNull) &&
2822         isKnownNonZero(V, DL, 0, &AC, &Call, &DT))
2823       ArgNos.push_back(ArgNo);
2824     ArgNo++;
2825   }
2826 
2827   assert(ArgNo == Call.arg_size() && "Call arguments not processed correctly.");
2828 
2829   if (!ArgNos.empty()) {
2830     AttributeList AS = Call.getAttributes();
2831     LLVMContext &Ctx = Call.getContext();
2832     AS = AS.addParamAttribute(Ctx, ArgNos,
2833                               Attribute::get(Ctx, Attribute::NonNull));
2834     Call.setAttributes(AS);
2835     Changed = true;
2836   }
2837 
2838   // If the callee is a pointer to a function, attempt to move any casts to the
2839   // arguments of the call/callbr/invoke.
2840   Value *Callee = Call.getCalledOperand();
2841   if (!isa<Function>(Callee) && transformConstExprCastCall(Call))
2842     return nullptr;
2843 
2844   if (Function *CalleeF = dyn_cast<Function>(Callee)) {
2845     // Remove the convergent attr on calls when the callee is not convergent.
2846     if (Call.isConvergent() && !CalleeF->isConvergent() &&
2847         !CalleeF->isIntrinsic()) {
2848       LLVM_DEBUG(dbgs() << "Removing convergent attr from instr " << Call
2849                         << "\n");
2850       Call.setNotConvergent();
2851       return &Call;
2852     }
2853 
2854     // If the call and callee calling conventions don't match, and neither one
2855     // of the calling conventions is compatible with C calling convention
2856     // this call must be unreachable, as the call is undefined.
2857     if ((CalleeF->getCallingConv() != Call.getCallingConv() &&
2858          !(CalleeF->getCallingConv() == llvm::CallingConv::C &&
2859            TargetLibraryInfoImpl::isCallingConvCCompatible(&Call)) &&
2860          !(Call.getCallingConv() == llvm::CallingConv::C &&
2861            TargetLibraryInfoImpl::isCallingConvCCompatible(CalleeF))) &&
2862         // Only do this for calls to a function with a body.  A prototype may
2863         // not actually end up matching the implementation's calling conv for a
2864         // variety of reasons (e.g. it may be written in assembly).
2865         !CalleeF->isDeclaration()) {
2866       Instruction *OldCall = &Call;
2867       CreateNonTerminatorUnreachable(OldCall);
2868       // If OldCall does not return void then replaceInstUsesWith poison.
2869       // This allows ValueHandlers and custom metadata to adjust itself.
2870       if (!OldCall->getType()->isVoidTy())
2871         replaceInstUsesWith(*OldCall, PoisonValue::get(OldCall->getType()));
2872       if (isa<CallInst>(OldCall))
2873         return eraseInstFromFunction(*OldCall);
2874 
2875       // We cannot remove an invoke or a callbr, because it would change thexi
2876       // CFG, just change the callee to a null pointer.
2877       cast<CallBase>(OldCall)->setCalledFunction(
2878           CalleeF->getFunctionType(),
2879           Constant::getNullValue(CalleeF->getType()));
2880       return nullptr;
2881     }
2882   }
2883 
2884   // Calling a null function pointer is undefined if a null address isn't
2885   // dereferenceable.
2886   if ((isa<ConstantPointerNull>(Callee) &&
2887        !NullPointerIsDefined(Call.getFunction())) ||
2888       isa<UndefValue>(Callee)) {
2889     // If Call does not return void then replaceInstUsesWith poison.
2890     // This allows ValueHandlers and custom metadata to adjust itself.
2891     if (!Call.getType()->isVoidTy())
2892       replaceInstUsesWith(Call, PoisonValue::get(Call.getType()));
2893 
2894     if (Call.isTerminator()) {
2895       // Can't remove an invoke or callbr because we cannot change the CFG.
2896       return nullptr;
2897     }
2898 
2899     // This instruction is not reachable, just remove it.
2900     CreateNonTerminatorUnreachable(&Call);
2901     return eraseInstFromFunction(Call);
2902   }
2903 
2904   if (IntrinsicInst *II = findInitTrampoline(Callee))
2905     return transformCallThroughTrampoline(Call, *II);
2906 
2907   // TODO: Drop this transform once opaque pointer transition is done.
2908   FunctionType *FTy = Call.getFunctionType();
2909   if (FTy->isVarArg()) {
2910     int ix = FTy->getNumParams();
2911     // See if we can optimize any arguments passed through the varargs area of
2912     // the call.
2913     for (auto I = Call.arg_begin() + FTy->getNumParams(), E = Call.arg_end();
2914          I != E; ++I, ++ix) {
2915       CastInst *CI = dyn_cast<CastInst>(*I);
2916       if (CI && isSafeToEliminateVarargsCast(Call, DL, CI, ix)) {
2917         replaceUse(*I, CI->getOperand(0));
2918 
2919         // Update the byval type to match the pointer type.
2920         // Not necessary for opaque pointers.
2921         PointerType *NewTy = cast<PointerType>(CI->getOperand(0)->getType());
2922         if (!NewTy->isOpaque() && Call.isByValArgument(ix)) {
2923           Call.removeParamAttr(ix, Attribute::ByVal);
2924           Call.addParamAttr(ix, Attribute::getWithByValType(
2925                                     Call.getContext(),
2926                                     NewTy->getNonOpaquePointerElementType()));
2927         }
2928         Changed = true;
2929       }
2930     }
2931   }
2932 
2933   if (isa<InlineAsm>(Callee) && !Call.doesNotThrow()) {
2934     InlineAsm *IA = cast<InlineAsm>(Callee);
2935     if (!IA->canThrow()) {
2936       // Normal inline asm calls cannot throw - mark them
2937       // 'nounwind'.
2938       Call.setDoesNotThrow();
2939       Changed = true;
2940     }
2941   }
2942 
2943   // Try to optimize the call if possible, we require DataLayout for most of
2944   // this.  None of these calls are seen as possibly dead so go ahead and
2945   // delete the instruction now.
2946   if (CallInst *CI = dyn_cast<CallInst>(&Call)) {
2947     Instruction *I = tryOptimizeCall(CI);
2948     // If we changed something return the result, etc. Otherwise let
2949     // the fallthrough check.
2950     if (I) return eraseInstFromFunction(*I);
2951   }
2952 
2953   if (!Call.use_empty() && !Call.isMustTailCall())
2954     if (Value *ReturnedArg = Call.getReturnedArgOperand()) {
2955       Type *CallTy = Call.getType();
2956       Type *RetArgTy = ReturnedArg->getType();
2957       if (RetArgTy->canLosslesslyBitCastTo(CallTy))
2958         return replaceInstUsesWith(
2959             Call, Builder.CreateBitOrPointerCast(ReturnedArg, CallTy));
2960     }
2961 
2962   if (isAllocationFn(&Call, &TLI) &&
2963       isAllocRemovable(&cast<CallBase>(Call), &TLI))
2964     return visitAllocSite(Call);
2965 
2966   // Handle intrinsics which can be used in both call and invoke context.
2967   switch (Call.getIntrinsicID()) {
2968   case Intrinsic::experimental_gc_statepoint: {
2969     GCStatepointInst &GCSP = *cast<GCStatepointInst>(&Call);
2970     SmallPtrSet<Value *, 32> LiveGcValues;
2971     for (const GCRelocateInst *Reloc : GCSP.getGCRelocates()) {
2972       GCRelocateInst &GCR = *const_cast<GCRelocateInst *>(Reloc);
2973 
2974       // Remove the relocation if unused.
2975       if (GCR.use_empty()) {
2976         eraseInstFromFunction(GCR);
2977         continue;
2978       }
2979 
2980       Value *DerivedPtr = GCR.getDerivedPtr();
2981       Value *BasePtr = GCR.getBasePtr();
2982 
2983       // Undef is undef, even after relocation.
2984       if (isa<UndefValue>(DerivedPtr) || isa<UndefValue>(BasePtr)) {
2985         replaceInstUsesWith(GCR, UndefValue::get(GCR.getType()));
2986         eraseInstFromFunction(GCR);
2987         continue;
2988       }
2989 
2990       if (auto *PT = dyn_cast<PointerType>(GCR.getType())) {
2991         // The relocation of null will be null for most any collector.
2992         // TODO: provide a hook for this in GCStrategy.  There might be some
2993         // weird collector this property does not hold for.
2994         if (isa<ConstantPointerNull>(DerivedPtr)) {
2995           // Use null-pointer of gc_relocate's type to replace it.
2996           replaceInstUsesWith(GCR, ConstantPointerNull::get(PT));
2997           eraseInstFromFunction(GCR);
2998           continue;
2999         }
3000 
3001         // isKnownNonNull -> nonnull attribute
3002         if (!GCR.hasRetAttr(Attribute::NonNull) &&
3003             isKnownNonZero(DerivedPtr, DL, 0, &AC, &Call, &DT)) {
3004           GCR.addRetAttr(Attribute::NonNull);
3005           // We discovered new fact, re-check users.
3006           Worklist.pushUsersToWorkList(GCR);
3007         }
3008       }
3009 
3010       // If we have two copies of the same pointer in the statepoint argument
3011       // list, canonicalize to one.  This may let us common gc.relocates.
3012       if (GCR.getBasePtr() == GCR.getDerivedPtr() &&
3013           GCR.getBasePtrIndex() != GCR.getDerivedPtrIndex()) {
3014         auto *OpIntTy = GCR.getOperand(2)->getType();
3015         GCR.setOperand(2, ConstantInt::get(OpIntTy, GCR.getBasePtrIndex()));
3016       }
3017 
3018       // TODO: bitcast(relocate(p)) -> relocate(bitcast(p))
3019       // Canonicalize on the type from the uses to the defs
3020 
3021       // TODO: relocate((gep p, C, C2, ...)) -> gep(relocate(p), C, C2, ...)
3022       LiveGcValues.insert(BasePtr);
3023       LiveGcValues.insert(DerivedPtr);
3024     }
3025     Optional<OperandBundleUse> Bundle =
3026         GCSP.getOperandBundle(LLVMContext::OB_gc_live);
3027     unsigned NumOfGCLives = LiveGcValues.size();
3028     if (!Bundle.hasValue() || NumOfGCLives == Bundle->Inputs.size())
3029       break;
3030     // We can reduce the size of gc live bundle.
3031     DenseMap<Value *, unsigned> Val2Idx;
3032     std::vector<Value *> NewLiveGc;
3033     for (unsigned I = 0, E = Bundle->Inputs.size(); I < E; ++I) {
3034       Value *V = Bundle->Inputs[I];
3035       if (Val2Idx.count(V))
3036         continue;
3037       if (LiveGcValues.count(V)) {
3038         Val2Idx[V] = NewLiveGc.size();
3039         NewLiveGc.push_back(V);
3040       } else
3041         Val2Idx[V] = NumOfGCLives;
3042     }
3043     // Update all gc.relocates
3044     for (const GCRelocateInst *Reloc : GCSP.getGCRelocates()) {
3045       GCRelocateInst &GCR = *const_cast<GCRelocateInst *>(Reloc);
3046       Value *BasePtr = GCR.getBasePtr();
3047       assert(Val2Idx.count(BasePtr) && Val2Idx[BasePtr] != NumOfGCLives &&
3048              "Missed live gc for base pointer");
3049       auto *OpIntTy1 = GCR.getOperand(1)->getType();
3050       GCR.setOperand(1, ConstantInt::get(OpIntTy1, Val2Idx[BasePtr]));
3051       Value *DerivedPtr = GCR.getDerivedPtr();
3052       assert(Val2Idx.count(DerivedPtr) && Val2Idx[DerivedPtr] != NumOfGCLives &&
3053              "Missed live gc for derived pointer");
3054       auto *OpIntTy2 = GCR.getOperand(2)->getType();
3055       GCR.setOperand(2, ConstantInt::get(OpIntTy2, Val2Idx[DerivedPtr]));
3056     }
3057     // Create new statepoint instruction.
3058     OperandBundleDef NewBundle("gc-live", NewLiveGc);
3059     return CallBase::Create(&Call, NewBundle);
3060   }
3061   default: { break; }
3062   }
3063 
3064   return Changed ? &Call : nullptr;
3065 }
3066 
3067 /// If the callee is a constexpr cast of a function, attempt to move the cast to
3068 /// the arguments of the call/callbr/invoke.
3069 bool InstCombinerImpl::transformConstExprCastCall(CallBase &Call) {
3070   auto *Callee =
3071       dyn_cast<Function>(Call.getCalledOperand()->stripPointerCasts());
3072   if (!Callee)
3073     return false;
3074 
3075   // If this is a call to a thunk function, don't remove the cast. Thunks are
3076   // used to transparently forward all incoming parameters and outgoing return
3077   // values, so it's important to leave the cast in place.
3078   if (Callee->hasFnAttribute("thunk"))
3079     return false;
3080 
3081   // If this is a musttail call, the callee's prototype must match the caller's
3082   // prototype with the exception of pointee types. The code below doesn't
3083   // implement that, so we can't do this transform.
3084   // TODO: Do the transform if it only requires adding pointer casts.
3085   if (Call.isMustTailCall())
3086     return false;
3087 
3088   Instruction *Caller = &Call;
3089   const AttributeList &CallerPAL = Call.getAttributes();
3090 
3091   // Okay, this is a cast from a function to a different type.  Unless doing so
3092   // would cause a type conversion of one of our arguments, change this call to
3093   // be a direct call with arguments casted to the appropriate types.
3094   FunctionType *FT = Callee->getFunctionType();
3095   Type *OldRetTy = Caller->getType();
3096   Type *NewRetTy = FT->getReturnType();
3097 
3098   // Check to see if we are changing the return type...
3099   if (OldRetTy != NewRetTy) {
3100 
3101     if (NewRetTy->isStructTy())
3102       return false; // TODO: Handle multiple return values.
3103 
3104     if (!CastInst::isBitOrNoopPointerCastable(NewRetTy, OldRetTy, DL)) {
3105       if (Callee->isDeclaration())
3106         return false;   // Cannot transform this return value.
3107 
3108       if (!Caller->use_empty() &&
3109           // void -> non-void is handled specially
3110           !NewRetTy->isVoidTy())
3111         return false;   // Cannot transform this return value.
3112     }
3113 
3114     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
3115       AttrBuilder RAttrs(FT->getContext(), CallerPAL.getRetAttrs());
3116       if (RAttrs.overlaps(AttributeFuncs::typeIncompatible(NewRetTy)))
3117         return false;   // Attribute not compatible with transformed value.
3118     }
3119 
3120     // If the callbase is an invoke/callbr instruction, and the return value is
3121     // used by a PHI node in a successor, we cannot change the return type of
3122     // the call because there is no place to put the cast instruction (without
3123     // breaking the critical edge).  Bail out in this case.
3124     if (!Caller->use_empty()) {
3125       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
3126         for (User *U : II->users())
3127           if (PHINode *PN = dyn_cast<PHINode>(U))
3128             if (PN->getParent() == II->getNormalDest() ||
3129                 PN->getParent() == II->getUnwindDest())
3130               return false;
3131       // FIXME: Be conservative for callbr to avoid a quadratic search.
3132       if (isa<CallBrInst>(Caller))
3133         return false;
3134     }
3135   }
3136 
3137   unsigned NumActualArgs = Call.arg_size();
3138   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
3139 
3140   // Prevent us turning:
3141   // declare void @takes_i32_inalloca(i32* inalloca)
3142   //  call void bitcast (void (i32*)* @takes_i32_inalloca to void (i32)*)(i32 0)
3143   //
3144   // into:
3145   //  call void @takes_i32_inalloca(i32* null)
3146   //
3147   //  Similarly, avoid folding away bitcasts of byval calls.
3148   if (Callee->getAttributes().hasAttrSomewhere(Attribute::InAlloca) ||
3149       Callee->getAttributes().hasAttrSomewhere(Attribute::Preallocated) ||
3150       Callee->getAttributes().hasAttrSomewhere(Attribute::ByVal))
3151     return false;
3152 
3153   auto AI = Call.arg_begin();
3154   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
3155     Type *ParamTy = FT->getParamType(i);
3156     Type *ActTy = (*AI)->getType();
3157 
3158     if (!CastInst::isBitOrNoopPointerCastable(ActTy, ParamTy, DL))
3159       return false;   // Cannot transform this parameter value.
3160 
3161     if (AttrBuilder(FT->getContext(), CallerPAL.getParamAttrs(i))
3162             .overlaps(AttributeFuncs::typeIncompatible(ParamTy)))
3163       return false;   // Attribute not compatible with transformed value.
3164 
3165     if (Call.isInAllocaArgument(i))
3166       return false;   // Cannot transform to and from inalloca.
3167 
3168     if (CallerPAL.hasParamAttr(i, Attribute::SwiftError))
3169       return false;
3170 
3171     // If the parameter is passed as a byval argument, then we have to have a
3172     // sized type and the sized type has to have the same size as the old type.
3173     if (ParamTy != ActTy && CallerPAL.hasParamAttr(i, Attribute::ByVal)) {
3174       PointerType *ParamPTy = dyn_cast<PointerType>(ParamTy);
3175       if (!ParamPTy || !ParamPTy->getPointerElementType()->isSized())
3176         return false;
3177 
3178       Type *CurElTy = Call.getParamByValType(i);
3179       if (DL.getTypeAllocSize(CurElTy) !=
3180           DL.getTypeAllocSize(ParamPTy->getPointerElementType()))
3181         return false;
3182     }
3183   }
3184 
3185   if (Callee->isDeclaration()) {
3186     // Do not delete arguments unless we have a function body.
3187     if (FT->getNumParams() < NumActualArgs && !FT->isVarArg())
3188       return false;
3189 
3190     // If the callee is just a declaration, don't change the varargsness of the
3191     // call.  We don't want to introduce a varargs call where one doesn't
3192     // already exist.
3193     if (FT->isVarArg() != Call.getFunctionType()->isVarArg())
3194       return false;
3195 
3196     // If both the callee and the cast type are varargs, we still have to make
3197     // sure the number of fixed parameters are the same or we have the same
3198     // ABI issues as if we introduce a varargs call.
3199     if (FT->isVarArg() && Call.getFunctionType()->isVarArg() &&
3200         FT->getNumParams() != Call.getFunctionType()->getNumParams())
3201       return false;
3202   }
3203 
3204   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
3205       !CallerPAL.isEmpty()) {
3206     // In this case we have more arguments than the new function type, but we
3207     // won't be dropping them.  Check that these extra arguments have attributes
3208     // that are compatible with being a vararg call argument.
3209     unsigned SRetIdx;
3210     if (CallerPAL.hasAttrSomewhere(Attribute::StructRet, &SRetIdx) &&
3211         SRetIdx - AttributeList::FirstArgIndex >= FT->getNumParams())
3212       return false;
3213   }
3214 
3215   // Okay, we decided that this is a safe thing to do: go ahead and start
3216   // inserting cast instructions as necessary.
3217   SmallVector<Value *, 8> Args;
3218   SmallVector<AttributeSet, 8> ArgAttrs;
3219   Args.reserve(NumActualArgs);
3220   ArgAttrs.reserve(NumActualArgs);
3221 
3222   // Get any return attributes.
3223   AttrBuilder RAttrs(FT->getContext(), CallerPAL.getRetAttrs());
3224 
3225   // If the return value is not being used, the type may not be compatible
3226   // with the existing attributes.  Wipe out any problematic attributes.
3227   RAttrs.remove(AttributeFuncs::typeIncompatible(NewRetTy));
3228 
3229   LLVMContext &Ctx = Call.getContext();
3230   AI = Call.arg_begin();
3231   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
3232     Type *ParamTy = FT->getParamType(i);
3233 
3234     Value *NewArg = *AI;
3235     if ((*AI)->getType() != ParamTy)
3236       NewArg = Builder.CreateBitOrPointerCast(*AI, ParamTy);
3237     Args.push_back(NewArg);
3238 
3239     // Add any parameter attributes.
3240     if (CallerPAL.hasParamAttr(i, Attribute::ByVal)) {
3241       AttrBuilder AB(FT->getContext(), CallerPAL.getParamAttrs(i));
3242       AB.addByValAttr(NewArg->getType()->getPointerElementType());
3243       ArgAttrs.push_back(AttributeSet::get(Ctx, AB));
3244     } else
3245       ArgAttrs.push_back(CallerPAL.getParamAttrs(i));
3246   }
3247 
3248   // If the function takes more arguments than the call was taking, add them
3249   // now.
3250   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i) {
3251     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
3252     ArgAttrs.push_back(AttributeSet());
3253   }
3254 
3255   // If we are removing arguments to the function, emit an obnoxious warning.
3256   if (FT->getNumParams() < NumActualArgs) {
3257     // TODO: if (!FT->isVarArg()) this call may be unreachable. PR14722
3258     if (FT->isVarArg()) {
3259       // Add all of the arguments in their promoted form to the arg list.
3260       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
3261         Type *PTy = getPromotedType((*AI)->getType());
3262         Value *NewArg = *AI;
3263         if (PTy != (*AI)->getType()) {
3264           // Must promote to pass through va_arg area!
3265           Instruction::CastOps opcode =
3266             CastInst::getCastOpcode(*AI, false, PTy, false);
3267           NewArg = Builder.CreateCast(opcode, *AI, PTy);
3268         }
3269         Args.push_back(NewArg);
3270 
3271         // Add any parameter attributes.
3272         ArgAttrs.push_back(CallerPAL.getParamAttrs(i));
3273       }
3274     }
3275   }
3276 
3277   AttributeSet FnAttrs = CallerPAL.getFnAttrs();
3278 
3279   if (NewRetTy->isVoidTy())
3280     Caller->setName("");   // Void type should not have a name.
3281 
3282   assert((ArgAttrs.size() == FT->getNumParams() || FT->isVarArg()) &&
3283          "missing argument attributes");
3284   AttributeList NewCallerPAL = AttributeList::get(
3285       Ctx, FnAttrs, AttributeSet::get(Ctx, RAttrs), ArgAttrs);
3286 
3287   SmallVector<OperandBundleDef, 1> OpBundles;
3288   Call.getOperandBundlesAsDefs(OpBundles);
3289 
3290   CallBase *NewCall;
3291   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
3292     NewCall = Builder.CreateInvoke(Callee, II->getNormalDest(),
3293                                    II->getUnwindDest(), Args, OpBundles);
3294   } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(Caller)) {
3295     NewCall = Builder.CreateCallBr(Callee, CBI->getDefaultDest(),
3296                                    CBI->getIndirectDests(), Args, OpBundles);
3297   } else {
3298     NewCall = Builder.CreateCall(Callee, Args, OpBundles);
3299     cast<CallInst>(NewCall)->setTailCallKind(
3300         cast<CallInst>(Caller)->getTailCallKind());
3301   }
3302   NewCall->takeName(Caller);
3303   NewCall->setCallingConv(Call.getCallingConv());
3304   NewCall->setAttributes(NewCallerPAL);
3305 
3306   // Preserve prof metadata if any.
3307   NewCall->copyMetadata(*Caller, {LLVMContext::MD_prof});
3308 
3309   // Insert a cast of the return type as necessary.
3310   Instruction *NC = NewCall;
3311   Value *NV = NC;
3312   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
3313     if (!NV->getType()->isVoidTy()) {
3314       NV = NC = CastInst::CreateBitOrPointerCast(NC, OldRetTy);
3315       NC->setDebugLoc(Caller->getDebugLoc());
3316 
3317       // If this is an invoke/callbr instruction, we should insert it after the
3318       // first non-phi instruction in the normal successor block.
3319       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
3320         BasicBlock::iterator I = II->getNormalDest()->getFirstInsertionPt();
3321         InsertNewInstBefore(NC, *I);
3322       } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(Caller)) {
3323         BasicBlock::iterator I = CBI->getDefaultDest()->getFirstInsertionPt();
3324         InsertNewInstBefore(NC, *I);
3325       } else {
3326         // Otherwise, it's a call, just insert cast right after the call.
3327         InsertNewInstBefore(NC, *Caller);
3328       }
3329       Worklist.pushUsersToWorkList(*Caller);
3330     } else {
3331       NV = UndefValue::get(Caller->getType());
3332     }
3333   }
3334 
3335   if (!Caller->use_empty())
3336     replaceInstUsesWith(*Caller, NV);
3337   else if (Caller->hasValueHandle()) {
3338     if (OldRetTy == NV->getType())
3339       ValueHandleBase::ValueIsRAUWd(Caller, NV);
3340     else
3341       // We cannot call ValueIsRAUWd with a different type, and the
3342       // actual tracked value will disappear.
3343       ValueHandleBase::ValueIsDeleted(Caller);
3344   }
3345 
3346   eraseInstFromFunction(*Caller);
3347   return true;
3348 }
3349 
3350 /// Turn a call to a function created by init_trampoline / adjust_trampoline
3351 /// intrinsic pair into a direct call to the underlying function.
3352 Instruction *
3353 InstCombinerImpl::transformCallThroughTrampoline(CallBase &Call,
3354                                                  IntrinsicInst &Tramp) {
3355   Value *Callee = Call.getCalledOperand();
3356   Type *CalleeTy = Callee->getType();
3357   FunctionType *FTy = Call.getFunctionType();
3358   AttributeList Attrs = Call.getAttributes();
3359 
3360   // If the call already has the 'nest' attribute somewhere then give up -
3361   // otherwise 'nest' would occur twice after splicing in the chain.
3362   if (Attrs.hasAttrSomewhere(Attribute::Nest))
3363     return nullptr;
3364 
3365   Function *NestF = cast<Function>(Tramp.getArgOperand(1)->stripPointerCasts());
3366   FunctionType *NestFTy = NestF->getFunctionType();
3367 
3368   AttributeList NestAttrs = NestF->getAttributes();
3369   if (!NestAttrs.isEmpty()) {
3370     unsigned NestArgNo = 0;
3371     Type *NestTy = nullptr;
3372     AttributeSet NestAttr;
3373 
3374     // Look for a parameter marked with the 'nest' attribute.
3375     for (FunctionType::param_iterator I = NestFTy->param_begin(),
3376                                       E = NestFTy->param_end();
3377          I != E; ++NestArgNo, ++I) {
3378       AttributeSet AS = NestAttrs.getParamAttrs(NestArgNo);
3379       if (AS.hasAttribute(Attribute::Nest)) {
3380         // Record the parameter type and any other attributes.
3381         NestTy = *I;
3382         NestAttr = AS;
3383         break;
3384       }
3385     }
3386 
3387     if (NestTy) {
3388       std::vector<Value*> NewArgs;
3389       std::vector<AttributeSet> NewArgAttrs;
3390       NewArgs.reserve(Call.arg_size() + 1);
3391       NewArgAttrs.reserve(Call.arg_size());
3392 
3393       // Insert the nest argument into the call argument list, which may
3394       // mean appending it.  Likewise for attributes.
3395 
3396       {
3397         unsigned ArgNo = 0;
3398         auto I = Call.arg_begin(), E = Call.arg_end();
3399         do {
3400           if (ArgNo == NestArgNo) {
3401             // Add the chain argument and attributes.
3402             Value *NestVal = Tramp.getArgOperand(2);
3403             if (NestVal->getType() != NestTy)
3404               NestVal = Builder.CreateBitCast(NestVal, NestTy, "nest");
3405             NewArgs.push_back(NestVal);
3406             NewArgAttrs.push_back(NestAttr);
3407           }
3408 
3409           if (I == E)
3410             break;
3411 
3412           // Add the original argument and attributes.
3413           NewArgs.push_back(*I);
3414           NewArgAttrs.push_back(Attrs.getParamAttrs(ArgNo));
3415 
3416           ++ArgNo;
3417           ++I;
3418         } while (true);
3419       }
3420 
3421       // The trampoline may have been bitcast to a bogus type (FTy).
3422       // Handle this by synthesizing a new function type, equal to FTy
3423       // with the chain parameter inserted.
3424 
3425       std::vector<Type*> NewTypes;
3426       NewTypes.reserve(FTy->getNumParams()+1);
3427 
3428       // Insert the chain's type into the list of parameter types, which may
3429       // mean appending it.
3430       {
3431         unsigned ArgNo = 0;
3432         FunctionType::param_iterator I = FTy->param_begin(),
3433           E = FTy->param_end();
3434 
3435         do {
3436           if (ArgNo == NestArgNo)
3437             // Add the chain's type.
3438             NewTypes.push_back(NestTy);
3439 
3440           if (I == E)
3441             break;
3442 
3443           // Add the original type.
3444           NewTypes.push_back(*I);
3445 
3446           ++ArgNo;
3447           ++I;
3448         } while (true);
3449       }
3450 
3451       // Replace the trampoline call with a direct call.  Let the generic
3452       // code sort out any function type mismatches.
3453       FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
3454                                                 FTy->isVarArg());
3455       Constant *NewCallee =
3456         NestF->getType() == PointerType::getUnqual(NewFTy) ?
3457         NestF : ConstantExpr::getBitCast(NestF,
3458                                          PointerType::getUnqual(NewFTy));
3459       AttributeList NewPAL =
3460           AttributeList::get(FTy->getContext(), Attrs.getFnAttrs(),
3461                              Attrs.getRetAttrs(), NewArgAttrs);
3462 
3463       SmallVector<OperandBundleDef, 1> OpBundles;
3464       Call.getOperandBundlesAsDefs(OpBundles);
3465 
3466       Instruction *NewCaller;
3467       if (InvokeInst *II = dyn_cast<InvokeInst>(&Call)) {
3468         NewCaller = InvokeInst::Create(NewFTy, NewCallee,
3469                                        II->getNormalDest(), II->getUnwindDest(),
3470                                        NewArgs, OpBundles);
3471         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
3472         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
3473       } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(&Call)) {
3474         NewCaller =
3475             CallBrInst::Create(NewFTy, NewCallee, CBI->getDefaultDest(),
3476                                CBI->getIndirectDests(), NewArgs, OpBundles);
3477         cast<CallBrInst>(NewCaller)->setCallingConv(CBI->getCallingConv());
3478         cast<CallBrInst>(NewCaller)->setAttributes(NewPAL);
3479       } else {
3480         NewCaller = CallInst::Create(NewFTy, NewCallee, NewArgs, OpBundles);
3481         cast<CallInst>(NewCaller)->setTailCallKind(
3482             cast<CallInst>(Call).getTailCallKind());
3483         cast<CallInst>(NewCaller)->setCallingConv(
3484             cast<CallInst>(Call).getCallingConv());
3485         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
3486       }
3487       NewCaller->setDebugLoc(Call.getDebugLoc());
3488 
3489       return NewCaller;
3490     }
3491   }
3492 
3493   // Replace the trampoline call with a direct call.  Since there is no 'nest'
3494   // parameter, there is no need to adjust the argument list.  Let the generic
3495   // code sort out any function type mismatches.
3496   Constant *NewCallee = ConstantExpr::getBitCast(NestF, CalleeTy);
3497   Call.setCalledFunction(FTy, NewCallee);
3498   return &Call;
3499 }
3500