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 
841 /// If we have a clamp pattern like max (min X, 42), 41 -- where the output
842 /// can only be one of two possible constant values -- turn that into a select
843 /// of constants.
844 static Instruction *foldClampRangeOfTwo(IntrinsicInst *II,
845                                         InstCombiner::BuilderTy &Builder) {
846   Value *I0 = II->getArgOperand(0), *I1 = II->getArgOperand(1);
847   Value *X;
848   const APInt *C0, *C1;
849   if (!match(I1, m_APInt(C1)) || !I0->hasOneUse())
850     return nullptr;
851 
852   CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
853   switch (II->getIntrinsicID()) {
854   case Intrinsic::smax:
855     if (match(I0, m_SMin(m_Value(X), m_APInt(C0))) && *C0 == *C1 + 1)
856       Pred = ICmpInst::ICMP_SGT;
857     break;
858   case Intrinsic::smin:
859     if (match(I0, m_SMax(m_Value(X), m_APInt(C0))) && *C1 == *C0 + 1)
860       Pred = ICmpInst::ICMP_SLT;
861     break;
862   case Intrinsic::umax:
863     if (match(I0, m_UMin(m_Value(X), m_APInt(C0))) && *C0 == *C1 + 1)
864       Pred = ICmpInst::ICMP_UGT;
865     break;
866   case Intrinsic::umin:
867     if (match(I0, m_UMax(m_Value(X), m_APInt(C0))) && *C1 == *C0 + 1)
868       Pred = ICmpInst::ICMP_ULT;
869     break;
870   default:
871     llvm_unreachable("Expected min/max intrinsic");
872   }
873   if (Pred == CmpInst::BAD_ICMP_PREDICATE)
874     return nullptr;
875 
876   // max (min X, 42), 41 --> X > 41 ? 42 : 41
877   // min (max X, 42), 43 --> X < 43 ? 42 : 43
878   Value *Cmp = Builder.CreateICmp(Pred, X, I1);
879   return SelectInst::Create(Cmp, ConstantInt::get(II->getType(), *C0), I1);
880 }
881 
882 /// If this min/max has a constant operand and an operand that is a matching
883 /// min/max with a constant operand, constant-fold the 2 constant operands.
884 static Instruction *reassociateMinMaxWithConstants(IntrinsicInst *II) {
885   Intrinsic::ID MinMaxID = II->getIntrinsicID();
886   auto *LHS = dyn_cast<IntrinsicInst>(II->getArgOperand(0));
887   if (!LHS || LHS->getIntrinsicID() != MinMaxID)
888     return nullptr;
889 
890   Constant *C0, *C1;
891   if (!match(LHS->getArgOperand(1), m_ImmConstant(C0)) ||
892       !match(II->getArgOperand(1), m_ImmConstant(C1)))
893     return nullptr;
894 
895   // max (max X, C0), C1 --> max X, (max C0, C1) --> max X, NewC
896   ICmpInst::Predicate Pred = MinMaxIntrinsic::getPredicate(MinMaxID);
897   Constant *CondC = ConstantExpr::getICmp(Pred, C0, C1);
898   Constant *NewC = ConstantExpr::getSelect(CondC, C0, C1);
899 
900   Module *Mod = II->getModule();
901   Function *MinMax = Intrinsic::getDeclaration(Mod, MinMaxID, II->getType());
902   return CallInst::Create(MinMax, {LHS->getArgOperand(0), NewC});
903 }
904 
905 /// If this min/max has a matching min/max operand with a constant, try to push
906 /// the constant operand into this instruction. This can enable more folds.
907 static Instruction *
908 reassociateMinMaxWithConstantInOperand(IntrinsicInst *II,
909                                        InstCombiner::BuilderTy &Builder) {
910   // Match and capture a min/max operand candidate.
911   Value *X, *Y;
912   Constant *C;
913   Instruction *Inner;
914   if (!match(II, m_c_MaxOrMin(m_OneUse(m_CombineAnd(
915                                   m_Instruction(Inner),
916                                   m_MaxOrMin(m_Value(X), m_ImmConstant(C)))),
917                               m_Value(Y))))
918     return nullptr;
919 
920   // The inner op must match. Check for constants to avoid infinite loops.
921   Intrinsic::ID MinMaxID = II->getIntrinsicID();
922   auto *InnerMM = dyn_cast<IntrinsicInst>(Inner);
923   if (!InnerMM || InnerMM->getIntrinsicID() != MinMaxID ||
924       match(X, m_ImmConstant()) || match(Y, m_ImmConstant()))
925     return nullptr;
926 
927   // max (max X, C), Y --> max (max X, Y), C
928   Function *MinMax =
929       Intrinsic::getDeclaration(II->getModule(), MinMaxID, II->getType());
930   Value *NewInner = Builder.CreateBinaryIntrinsic(MinMaxID, X, Y);
931   NewInner->takeName(Inner);
932   return CallInst::Create(MinMax, {NewInner, C});
933 }
934 
935 /// Reduce a sequence of min/max intrinsics with a common operand.
936 static Instruction *factorizeMinMaxTree(IntrinsicInst *II) {
937   // Match 3 of the same min/max ops. Example: umin(umin(), umin()).
938   auto *LHS = dyn_cast<IntrinsicInst>(II->getArgOperand(0));
939   auto *RHS = dyn_cast<IntrinsicInst>(II->getArgOperand(1));
940   Intrinsic::ID MinMaxID = II->getIntrinsicID();
941   if (!LHS || !RHS || LHS->getIntrinsicID() != MinMaxID ||
942       RHS->getIntrinsicID() != MinMaxID ||
943       (!LHS->hasOneUse() && !RHS->hasOneUse()))
944     return nullptr;
945 
946   Value *A = LHS->getArgOperand(0);
947   Value *B = LHS->getArgOperand(1);
948   Value *C = RHS->getArgOperand(0);
949   Value *D = RHS->getArgOperand(1);
950 
951   // Look for a common operand.
952   Value *MinMaxOp = nullptr;
953   Value *ThirdOp = nullptr;
954   if (LHS->hasOneUse()) {
955     // If the LHS is only used in this chain and the RHS is used outside of it,
956     // reuse the RHS min/max because that will eliminate the LHS.
957     if (D == A || C == A) {
958       // min(min(a, b), min(c, a)) --> min(min(c, a), b)
959       // min(min(a, b), min(a, d)) --> min(min(a, d), b)
960       MinMaxOp = RHS;
961       ThirdOp = B;
962     } else if (D == B || C == B) {
963       // min(min(a, b), min(c, b)) --> min(min(c, b), a)
964       // min(min(a, b), min(b, d)) --> min(min(b, d), a)
965       MinMaxOp = RHS;
966       ThirdOp = A;
967     }
968   } else {
969     assert(RHS->hasOneUse() && "Expected one-use operand");
970     // Reuse the LHS. This will eliminate the RHS.
971     if (D == A || D == B) {
972       // min(min(a, b), min(c, a)) --> min(min(a, b), c)
973       // min(min(a, b), min(c, b)) --> min(min(a, b), c)
974       MinMaxOp = LHS;
975       ThirdOp = C;
976     } else if (C == A || C == B) {
977       // min(min(a, b), min(b, d)) --> min(min(a, b), d)
978       // min(min(a, b), min(c, b)) --> min(min(a, b), d)
979       MinMaxOp = LHS;
980       ThirdOp = D;
981     }
982   }
983 
984   if (!MinMaxOp || !ThirdOp)
985     return nullptr;
986 
987   Module *Mod = II->getModule();
988   Function *MinMax = Intrinsic::getDeclaration(Mod, MinMaxID, II->getType());
989   return CallInst::Create(MinMax, { MinMaxOp, ThirdOp });
990 }
991 
992 /// CallInst simplification. This mostly only handles folding of intrinsic
993 /// instructions. For normal calls, it allows visitCallBase to do the heavy
994 /// lifting.
995 Instruction *InstCombinerImpl::visitCallInst(CallInst &CI) {
996   // Don't try to simplify calls without uses. It will not do anything useful,
997   // but will result in the following folds being skipped.
998   if (!CI.use_empty())
999     if (Value *V = SimplifyCall(&CI, SQ.getWithInstruction(&CI)))
1000       return replaceInstUsesWith(CI, V);
1001 
1002   if (isFreeCall(&CI, &TLI))
1003     return visitFree(CI);
1004 
1005   // If the caller function (i.e. us, the function that contains this CallInst)
1006   // is nounwind, mark the call as nounwind, even if the callee isn't.
1007   if (CI.getFunction()->doesNotThrow() && !CI.doesNotThrow()) {
1008     CI.setDoesNotThrow();
1009     return &CI;
1010   }
1011 
1012   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
1013   if (!II) return visitCallBase(CI);
1014 
1015   // For atomic unordered mem intrinsics if len is not a positive or
1016   // not a multiple of element size then behavior is undefined.
1017   if (auto *AMI = dyn_cast<AtomicMemIntrinsic>(II))
1018     if (ConstantInt *NumBytes = dyn_cast<ConstantInt>(AMI->getLength()))
1019       if (NumBytes->getSExtValue() < 0 ||
1020           (NumBytes->getZExtValue() % AMI->getElementSizeInBytes() != 0)) {
1021         CreateNonTerminatorUnreachable(AMI);
1022         assert(AMI->getType()->isVoidTy() &&
1023                "non void atomic unordered mem intrinsic");
1024         return eraseInstFromFunction(*AMI);
1025       }
1026 
1027   // Intrinsics cannot occur in an invoke or a callbr, so handle them here
1028   // instead of in visitCallBase.
1029   if (auto *MI = dyn_cast<AnyMemIntrinsic>(II)) {
1030     bool Changed = false;
1031 
1032     // memmove/cpy/set of zero bytes is a noop.
1033     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
1034       if (NumBytes->isNullValue())
1035         return eraseInstFromFunction(CI);
1036 
1037       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
1038         if (CI->getZExtValue() == 1) {
1039           // Replace the instruction with just byte operations.  We would
1040           // transform other cases to loads/stores, but we don't know if
1041           // alignment is sufficient.
1042         }
1043     }
1044 
1045     // No other transformations apply to volatile transfers.
1046     if (auto *M = dyn_cast<MemIntrinsic>(MI))
1047       if (M->isVolatile())
1048         return nullptr;
1049 
1050     // If we have a memmove and the source operation is a constant global,
1051     // then the source and dest pointers can't alias, so we can change this
1052     // into a call to memcpy.
1053     if (auto *MMI = dyn_cast<AnyMemMoveInst>(MI)) {
1054       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
1055         if (GVSrc->isConstant()) {
1056           Module *M = CI.getModule();
1057           Intrinsic::ID MemCpyID =
1058               isa<AtomicMemMoveInst>(MMI)
1059                   ? Intrinsic::memcpy_element_unordered_atomic
1060                   : Intrinsic::memcpy;
1061           Type *Tys[3] = { CI.getArgOperand(0)->getType(),
1062                            CI.getArgOperand(1)->getType(),
1063                            CI.getArgOperand(2)->getType() };
1064           CI.setCalledFunction(Intrinsic::getDeclaration(M, MemCpyID, Tys));
1065           Changed = true;
1066         }
1067     }
1068 
1069     if (AnyMemTransferInst *MTI = dyn_cast<AnyMemTransferInst>(MI)) {
1070       // memmove(x,x,size) -> noop.
1071       if (MTI->getSource() == MTI->getDest())
1072         return eraseInstFromFunction(CI);
1073     }
1074 
1075     // If we can determine a pointer alignment that is bigger than currently
1076     // set, update the alignment.
1077     if (auto *MTI = dyn_cast<AnyMemTransferInst>(MI)) {
1078       if (Instruction *I = SimplifyAnyMemTransfer(MTI))
1079         return I;
1080     } else if (auto *MSI = dyn_cast<AnyMemSetInst>(MI)) {
1081       if (Instruction *I = SimplifyAnyMemSet(MSI))
1082         return I;
1083     }
1084 
1085     if (Changed) return II;
1086   }
1087 
1088   // For fixed width vector result intrinsics, use the generic demanded vector
1089   // support.
1090   if (auto *IIFVTy = dyn_cast<FixedVectorType>(II->getType())) {
1091     auto VWidth = IIFVTy->getNumElements();
1092     APInt UndefElts(VWidth, 0);
1093     APInt AllOnesEltMask(APInt::getAllOnes(VWidth));
1094     if (Value *V = SimplifyDemandedVectorElts(II, AllOnesEltMask, UndefElts)) {
1095       if (V != II)
1096         return replaceInstUsesWith(*II, V);
1097       return II;
1098     }
1099   }
1100 
1101   if (II->isCommutative()) {
1102     if (CallInst *NewCall = canonicalizeConstantArg0ToArg1(CI))
1103       return NewCall;
1104   }
1105 
1106   Intrinsic::ID IID = II->getIntrinsicID();
1107   switch (IID) {
1108   case Intrinsic::objectsize:
1109     if (Value *V = lowerObjectSizeCall(II, DL, &TLI, /*MustSucceed=*/false))
1110       return replaceInstUsesWith(CI, V);
1111     return nullptr;
1112   case Intrinsic::abs: {
1113     Value *IIOperand = II->getArgOperand(0);
1114     bool IntMinIsPoison = cast<Constant>(II->getArgOperand(1))->isOneValue();
1115 
1116     // abs(-x) -> abs(x)
1117     // TODO: Copy nsw if it was present on the neg?
1118     Value *X;
1119     if (match(IIOperand, m_Neg(m_Value(X))))
1120       return replaceOperand(*II, 0, X);
1121     if (match(IIOperand, m_Select(m_Value(), m_Value(X), m_Neg(m_Deferred(X)))))
1122       return replaceOperand(*II, 0, X);
1123     if (match(IIOperand, m_Select(m_Value(), m_Neg(m_Value(X)), m_Deferred(X))))
1124       return replaceOperand(*II, 0, X);
1125 
1126     if (Optional<bool> Sign = getKnownSign(IIOperand, II, DL, &AC, &DT)) {
1127       // abs(x) -> x if x >= 0
1128       if (!*Sign)
1129         return replaceInstUsesWith(*II, IIOperand);
1130 
1131       // abs(x) -> -x if x < 0
1132       if (IntMinIsPoison)
1133         return BinaryOperator::CreateNSWNeg(IIOperand);
1134       return BinaryOperator::CreateNeg(IIOperand);
1135     }
1136 
1137     // abs (sext X) --> zext (abs X*)
1138     // Clear the IsIntMin (nsw) bit on the abs to allow narrowing.
1139     if (match(IIOperand, m_OneUse(m_SExt(m_Value(X))))) {
1140       Value *NarrowAbs =
1141           Builder.CreateBinaryIntrinsic(Intrinsic::abs, X, Builder.getFalse());
1142       return CastInst::Create(Instruction::ZExt, NarrowAbs, II->getType());
1143     }
1144 
1145     // Match a complicated way to check if a number is odd/even:
1146     // abs (srem X, 2) --> and X, 1
1147     const APInt *C;
1148     if (match(IIOperand, m_SRem(m_Value(X), m_APInt(C))) && *C == 2)
1149       return BinaryOperator::CreateAnd(X, ConstantInt::get(II->getType(), 1));
1150 
1151     break;
1152   }
1153   case Intrinsic::umin: {
1154     Value *I0 = II->getArgOperand(0), *I1 = II->getArgOperand(1);
1155     // umin(x, 1) == zext(x != 0)
1156     if (match(I1, m_One())) {
1157       Value *Zero = Constant::getNullValue(I0->getType());
1158       Value *Cmp = Builder.CreateICmpNE(I0, Zero);
1159       return CastInst::Create(Instruction::ZExt, Cmp, II->getType());
1160     }
1161     LLVM_FALLTHROUGH;
1162   }
1163   case Intrinsic::umax: {
1164     Value *I0 = II->getArgOperand(0), *I1 = II->getArgOperand(1);
1165     Value *X, *Y;
1166     if (match(I0, m_ZExt(m_Value(X))) && match(I1, m_ZExt(m_Value(Y))) &&
1167         (I0->hasOneUse() || I1->hasOneUse()) && X->getType() == Y->getType()) {
1168       Value *NarrowMaxMin = Builder.CreateBinaryIntrinsic(IID, X, Y);
1169       return CastInst::Create(Instruction::ZExt, NarrowMaxMin, II->getType());
1170     }
1171     Constant *C;
1172     if (match(I0, m_ZExt(m_Value(X))) && match(I1, m_Constant(C)) &&
1173         I0->hasOneUse()) {
1174       Constant *NarrowC = ConstantExpr::getTrunc(C, X->getType());
1175       if (ConstantExpr::getZExt(NarrowC, II->getType()) == C) {
1176         Value *NarrowMaxMin = Builder.CreateBinaryIntrinsic(IID, X, NarrowC);
1177         return CastInst::Create(Instruction::ZExt, NarrowMaxMin, II->getType());
1178       }
1179     }
1180     // If both operands of unsigned min/max are sign-extended, it is still ok
1181     // to narrow the operation.
1182     LLVM_FALLTHROUGH;
1183   }
1184   case Intrinsic::smax:
1185   case Intrinsic::smin: {
1186     Value *I0 = II->getArgOperand(0), *I1 = II->getArgOperand(1);
1187     Value *X, *Y;
1188     if (match(I0, m_SExt(m_Value(X))) && match(I1, m_SExt(m_Value(Y))) &&
1189         (I0->hasOneUse() || I1->hasOneUse()) && X->getType() == Y->getType()) {
1190       Value *NarrowMaxMin = Builder.CreateBinaryIntrinsic(IID, X, Y);
1191       return CastInst::Create(Instruction::SExt, NarrowMaxMin, II->getType());
1192     }
1193 
1194     Constant *C;
1195     if (match(I0, m_SExt(m_Value(X))) && match(I1, m_Constant(C)) &&
1196         I0->hasOneUse()) {
1197       Constant *NarrowC = ConstantExpr::getTrunc(C, X->getType());
1198       if (ConstantExpr::getSExt(NarrowC, II->getType()) == C) {
1199         Value *NarrowMaxMin = Builder.CreateBinaryIntrinsic(IID, X, NarrowC);
1200         return CastInst::Create(Instruction::SExt, NarrowMaxMin, II->getType());
1201       }
1202     }
1203 
1204     if (IID == Intrinsic::smax || IID == Intrinsic::smin) {
1205       // smax (neg nsw X), (neg nsw Y) --> neg nsw (smin X, Y)
1206       // smin (neg nsw X), (neg nsw Y) --> neg nsw (smax X, Y)
1207       // TODO: Canonicalize neg after min/max if I1 is constant.
1208       if (match(I0, m_NSWNeg(m_Value(X))) && match(I1, m_NSWNeg(m_Value(Y))) &&
1209           (I0->hasOneUse() || I1->hasOneUse())) {
1210         Intrinsic::ID InvID = getInverseMinMaxIntrinsic(IID);
1211         Value *InvMaxMin = Builder.CreateBinaryIntrinsic(InvID, X, Y);
1212         return BinaryOperator::CreateNSWNeg(InvMaxMin);
1213       }
1214     }
1215 
1216     // If we can eliminate ~A and Y is free to invert:
1217     // max ~A, Y --> ~(min A, ~Y)
1218     //
1219     // Examples:
1220     // max ~A, ~Y --> ~(min A, Y)
1221     // max ~A, C --> ~(min A, ~C)
1222     // max ~A, (max ~Y, ~Z) --> ~min( A, (min Y, Z))
1223     auto moveNotAfterMinMax = [&](Value *X, Value *Y) -> Instruction * {
1224       Value *A;
1225       if (match(X, m_OneUse(m_Not(m_Value(A)))) &&
1226           !isFreeToInvert(A, A->hasOneUse()) &&
1227           isFreeToInvert(Y, Y->hasOneUse())) {
1228         Value *NotY = Builder.CreateNot(Y);
1229         Intrinsic::ID InvID = getInverseMinMaxIntrinsic(IID);
1230         Value *InvMaxMin = Builder.CreateBinaryIntrinsic(InvID, A, NotY);
1231         return BinaryOperator::CreateNot(InvMaxMin);
1232       }
1233       return nullptr;
1234     };
1235 
1236     if (Instruction *I = moveNotAfterMinMax(I0, I1))
1237       return I;
1238     if (Instruction *I = moveNotAfterMinMax(I1, I0))
1239       return I;
1240 
1241     if (Instruction *I = moveAddAfterMinMax(II, Builder))
1242       return I;
1243 
1244     // smax(X, -X) --> abs(X)
1245     // smin(X, -X) --> -abs(X)
1246     // umax(X, -X) --> -abs(X)
1247     // umin(X, -X) --> abs(X)
1248     if (isKnownNegation(I0, I1)) {
1249       // We can choose either operand as the input to abs(), but if we can
1250       // eliminate the only use of a value, that's better for subsequent
1251       // transforms/analysis.
1252       if (I0->hasOneUse() && !I1->hasOneUse())
1253         std::swap(I0, I1);
1254 
1255       // This is some variant of abs(). See if we can propagate 'nsw' to the abs
1256       // operation and potentially its negation.
1257       bool IntMinIsPoison = isKnownNegation(I0, I1, /* NeedNSW */ true);
1258       Value *Abs = Builder.CreateBinaryIntrinsic(
1259           Intrinsic::abs, I0,
1260           ConstantInt::getBool(II->getContext(), IntMinIsPoison));
1261 
1262       // We don't have a "nabs" intrinsic, so negate if needed based on the
1263       // max/min operation.
1264       if (IID == Intrinsic::smin || IID == Intrinsic::umax)
1265         Abs = Builder.CreateNeg(Abs, "nabs", /* NUW */ false, IntMinIsPoison);
1266       return replaceInstUsesWith(CI, Abs);
1267     }
1268 
1269     if (Instruction *Sel = foldClampRangeOfTwo(II, Builder))
1270       return Sel;
1271 
1272     if (Instruction *SAdd = matchSAddSubSat(*II))
1273       return SAdd;
1274 
1275     if (match(I1, m_ImmConstant()))
1276       if (auto *Sel = dyn_cast<SelectInst>(I0))
1277         if (Instruction *R = FoldOpIntoSelect(*II, Sel))
1278           return R;
1279 
1280     if (Instruction *NewMinMax = reassociateMinMaxWithConstants(II))
1281       return NewMinMax;
1282 
1283     if (Instruction *R = reassociateMinMaxWithConstantInOperand(II, Builder))
1284       return R;
1285 
1286     if (Instruction *NewMinMax = factorizeMinMaxTree(II))
1287        return NewMinMax;
1288 
1289     break;
1290   }
1291   case Intrinsic::bswap: {
1292     Value *IIOperand = II->getArgOperand(0);
1293     Value *X = nullptr;
1294 
1295     KnownBits Known = computeKnownBits(IIOperand, 0, II);
1296     uint64_t LZ = alignDown(Known.countMinLeadingZeros(), 8);
1297     uint64_t TZ = alignDown(Known.countMinTrailingZeros(), 8);
1298 
1299     // bswap(x) -> shift(x) if x has exactly one "active byte"
1300     if (Known.getBitWidth() - LZ - TZ == 8) {
1301       assert(LZ != TZ && "active byte cannot be in the middle");
1302       if (LZ > TZ)  // -> shl(x) if the "active byte" is in the low part of x
1303         return BinaryOperator::CreateNUWShl(
1304             IIOperand, ConstantInt::get(IIOperand->getType(), LZ - TZ));
1305       // -> lshr(x) if the "active byte" is in the high part of x
1306       return BinaryOperator::CreateExactLShr(
1307             IIOperand, ConstantInt::get(IIOperand->getType(), TZ - LZ));
1308     }
1309 
1310     // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
1311     if (match(IIOperand, m_Trunc(m_BSwap(m_Value(X))))) {
1312       unsigned C = X->getType()->getScalarSizeInBits() -
1313                    IIOperand->getType()->getScalarSizeInBits();
1314       Value *CV = ConstantInt::get(X->getType(), C);
1315       Value *V = Builder.CreateLShr(X, CV);
1316       return new TruncInst(V, IIOperand->getType());
1317     }
1318     break;
1319   }
1320   case Intrinsic::masked_load:
1321     if (Value *SimplifiedMaskedOp = simplifyMaskedLoad(*II))
1322       return replaceInstUsesWith(CI, SimplifiedMaskedOp);
1323     break;
1324   case Intrinsic::masked_store:
1325     return simplifyMaskedStore(*II);
1326   case Intrinsic::masked_gather:
1327     return simplifyMaskedGather(*II);
1328   case Intrinsic::masked_scatter:
1329     return simplifyMaskedScatter(*II);
1330   case Intrinsic::launder_invariant_group:
1331   case Intrinsic::strip_invariant_group:
1332     if (auto *SkippedBarrier = simplifyInvariantGroupIntrinsic(*II, *this))
1333       return replaceInstUsesWith(*II, SkippedBarrier);
1334     break;
1335   case Intrinsic::powi:
1336     if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
1337       // 0 and 1 are handled in instsimplify
1338       // powi(x, -1) -> 1/x
1339       if (Power->isMinusOne())
1340         return BinaryOperator::CreateFDivFMF(ConstantFP::get(CI.getType(), 1.0),
1341                                              II->getArgOperand(0), II);
1342       // powi(x, 2) -> x*x
1343       if (Power->equalsInt(2))
1344         return BinaryOperator::CreateFMulFMF(II->getArgOperand(0),
1345                                              II->getArgOperand(0), II);
1346 
1347       if (!Power->getValue()[0]) {
1348         Value *X;
1349         // If power is even:
1350         // powi(-x, p) -> powi(x, p)
1351         // powi(fabs(x), p) -> powi(x, p)
1352         // powi(copysign(x, y), p) -> powi(x, p)
1353         if (match(II->getArgOperand(0), m_FNeg(m_Value(X))) ||
1354             match(II->getArgOperand(0), m_FAbs(m_Value(X))) ||
1355             match(II->getArgOperand(0),
1356                   m_Intrinsic<Intrinsic::copysign>(m_Value(X), m_Value())))
1357           return replaceOperand(*II, 0, X);
1358       }
1359     }
1360     break;
1361 
1362   case Intrinsic::cttz:
1363   case Intrinsic::ctlz:
1364     if (auto *I = foldCttzCtlz(*II, *this))
1365       return I;
1366     break;
1367 
1368   case Intrinsic::ctpop:
1369     if (auto *I = foldCtpop(*II, *this))
1370       return I;
1371     break;
1372 
1373   case Intrinsic::fshl:
1374   case Intrinsic::fshr: {
1375     Value *Op0 = II->getArgOperand(0), *Op1 = II->getArgOperand(1);
1376     Type *Ty = II->getType();
1377     unsigned BitWidth = Ty->getScalarSizeInBits();
1378     Constant *ShAmtC;
1379     if (match(II->getArgOperand(2), m_ImmConstant(ShAmtC)) &&
1380         !ShAmtC->containsConstantExpression()) {
1381       // Canonicalize a shift amount constant operand to modulo the bit-width.
1382       Constant *WidthC = ConstantInt::get(Ty, BitWidth);
1383       Constant *ModuloC = ConstantExpr::getURem(ShAmtC, WidthC);
1384       if (ModuloC != ShAmtC)
1385         return replaceOperand(*II, 2, ModuloC);
1386 
1387       assert(ConstantExpr::getICmp(ICmpInst::ICMP_UGT, WidthC, ShAmtC) ==
1388                  ConstantInt::getTrue(CmpInst::makeCmpResultType(Ty)) &&
1389              "Shift amount expected to be modulo bitwidth");
1390 
1391       // Canonicalize funnel shift right by constant to funnel shift left. This
1392       // is not entirely arbitrary. For historical reasons, the backend may
1393       // recognize rotate left patterns but miss rotate right patterns.
1394       if (IID == Intrinsic::fshr) {
1395         // fshr X, Y, C --> fshl X, Y, (BitWidth - C)
1396         Constant *LeftShiftC = ConstantExpr::getSub(WidthC, ShAmtC);
1397         Module *Mod = II->getModule();
1398         Function *Fshl = Intrinsic::getDeclaration(Mod, Intrinsic::fshl, Ty);
1399         return CallInst::Create(Fshl, { Op0, Op1, LeftShiftC });
1400       }
1401       assert(IID == Intrinsic::fshl &&
1402              "All funnel shifts by simple constants should go left");
1403 
1404       // fshl(X, 0, C) --> shl X, C
1405       // fshl(X, undef, C) --> shl X, C
1406       if (match(Op1, m_ZeroInt()) || match(Op1, m_Undef()))
1407         return BinaryOperator::CreateShl(Op0, ShAmtC);
1408 
1409       // fshl(0, X, C) --> lshr X, (BW-C)
1410       // fshl(undef, X, C) --> lshr X, (BW-C)
1411       if (match(Op0, m_ZeroInt()) || match(Op0, m_Undef()))
1412         return BinaryOperator::CreateLShr(Op1,
1413                                           ConstantExpr::getSub(WidthC, ShAmtC));
1414 
1415       // fshl i16 X, X, 8 --> bswap i16 X (reduce to more-specific form)
1416       if (Op0 == Op1 && BitWidth == 16 && match(ShAmtC, m_SpecificInt(8))) {
1417         Module *Mod = II->getModule();
1418         Function *Bswap = Intrinsic::getDeclaration(Mod, Intrinsic::bswap, Ty);
1419         return CallInst::Create(Bswap, { Op0 });
1420       }
1421     }
1422 
1423     // Left or right might be masked.
1424     if (SimplifyDemandedInstructionBits(*II))
1425       return &CI;
1426 
1427     // The shift amount (operand 2) of a funnel shift is modulo the bitwidth,
1428     // so only the low bits of the shift amount are demanded if the bitwidth is
1429     // a power-of-2.
1430     if (!isPowerOf2_32(BitWidth))
1431       break;
1432     APInt Op2Demanded = APInt::getLowBitsSet(BitWidth, Log2_32_Ceil(BitWidth));
1433     KnownBits Op2Known(BitWidth);
1434     if (SimplifyDemandedBits(II, 2, Op2Demanded, Op2Known))
1435       return &CI;
1436     break;
1437   }
1438   case Intrinsic::uadd_with_overflow:
1439   case Intrinsic::sadd_with_overflow: {
1440     if (Instruction *I = foldIntrinsicWithOverflowCommon(II))
1441       return I;
1442 
1443     // Given 2 constant operands whose sum does not overflow:
1444     // uaddo (X +nuw C0), C1 -> uaddo X, C0 + C1
1445     // saddo (X +nsw C0), C1 -> saddo X, C0 + C1
1446     Value *X;
1447     const APInt *C0, *C1;
1448     Value *Arg0 = II->getArgOperand(0);
1449     Value *Arg1 = II->getArgOperand(1);
1450     bool IsSigned = IID == Intrinsic::sadd_with_overflow;
1451     bool HasNWAdd = IsSigned ? match(Arg0, m_NSWAdd(m_Value(X), m_APInt(C0)))
1452                              : match(Arg0, m_NUWAdd(m_Value(X), m_APInt(C0)));
1453     if (HasNWAdd && match(Arg1, m_APInt(C1))) {
1454       bool Overflow;
1455       APInt NewC =
1456           IsSigned ? C1->sadd_ov(*C0, Overflow) : C1->uadd_ov(*C0, Overflow);
1457       if (!Overflow)
1458         return replaceInstUsesWith(
1459             *II, Builder.CreateBinaryIntrinsic(
1460                      IID, X, ConstantInt::get(Arg1->getType(), NewC)));
1461     }
1462     break;
1463   }
1464 
1465   case Intrinsic::umul_with_overflow:
1466   case Intrinsic::smul_with_overflow:
1467   case Intrinsic::usub_with_overflow:
1468     if (Instruction *I = foldIntrinsicWithOverflowCommon(II))
1469       return I;
1470     break;
1471 
1472   case Intrinsic::ssub_with_overflow: {
1473     if (Instruction *I = foldIntrinsicWithOverflowCommon(II))
1474       return I;
1475 
1476     Constant *C;
1477     Value *Arg0 = II->getArgOperand(0);
1478     Value *Arg1 = II->getArgOperand(1);
1479     // Given a constant C that is not the minimum signed value
1480     // for an integer of a given bit width:
1481     //
1482     // ssubo X, C -> saddo X, -C
1483     if (match(Arg1, m_Constant(C)) && C->isNotMinSignedValue()) {
1484       Value *NegVal = ConstantExpr::getNeg(C);
1485       // Build a saddo call that is equivalent to the discovered
1486       // ssubo call.
1487       return replaceInstUsesWith(
1488           *II, Builder.CreateBinaryIntrinsic(Intrinsic::sadd_with_overflow,
1489                                              Arg0, NegVal));
1490     }
1491 
1492     break;
1493   }
1494 
1495   case Intrinsic::uadd_sat:
1496   case Intrinsic::sadd_sat:
1497   case Intrinsic::usub_sat:
1498   case Intrinsic::ssub_sat: {
1499     SaturatingInst *SI = cast<SaturatingInst>(II);
1500     Type *Ty = SI->getType();
1501     Value *Arg0 = SI->getLHS();
1502     Value *Arg1 = SI->getRHS();
1503 
1504     // Make use of known overflow information.
1505     OverflowResult OR = computeOverflow(SI->getBinaryOp(), SI->isSigned(),
1506                                         Arg0, Arg1, SI);
1507     switch (OR) {
1508       case OverflowResult::MayOverflow:
1509         break;
1510       case OverflowResult::NeverOverflows:
1511         if (SI->isSigned())
1512           return BinaryOperator::CreateNSW(SI->getBinaryOp(), Arg0, Arg1);
1513         else
1514           return BinaryOperator::CreateNUW(SI->getBinaryOp(), Arg0, Arg1);
1515       case OverflowResult::AlwaysOverflowsLow: {
1516         unsigned BitWidth = Ty->getScalarSizeInBits();
1517         APInt Min = APSInt::getMinValue(BitWidth, !SI->isSigned());
1518         return replaceInstUsesWith(*SI, ConstantInt::get(Ty, Min));
1519       }
1520       case OverflowResult::AlwaysOverflowsHigh: {
1521         unsigned BitWidth = Ty->getScalarSizeInBits();
1522         APInt Max = APSInt::getMaxValue(BitWidth, !SI->isSigned());
1523         return replaceInstUsesWith(*SI, ConstantInt::get(Ty, Max));
1524       }
1525     }
1526 
1527     // ssub.sat(X, C) -> sadd.sat(X, -C) if C != MIN
1528     Constant *C;
1529     if (IID == Intrinsic::ssub_sat && match(Arg1, m_Constant(C)) &&
1530         C->isNotMinSignedValue()) {
1531       Value *NegVal = ConstantExpr::getNeg(C);
1532       return replaceInstUsesWith(
1533           *II, Builder.CreateBinaryIntrinsic(
1534               Intrinsic::sadd_sat, Arg0, NegVal));
1535     }
1536 
1537     // sat(sat(X + Val2) + Val) -> sat(X + (Val+Val2))
1538     // sat(sat(X - Val2) - Val) -> sat(X - (Val+Val2))
1539     // if Val and Val2 have the same sign
1540     if (auto *Other = dyn_cast<IntrinsicInst>(Arg0)) {
1541       Value *X;
1542       const APInt *Val, *Val2;
1543       APInt NewVal;
1544       bool IsUnsigned =
1545           IID == Intrinsic::uadd_sat || IID == Intrinsic::usub_sat;
1546       if (Other->getIntrinsicID() == IID &&
1547           match(Arg1, m_APInt(Val)) &&
1548           match(Other->getArgOperand(0), m_Value(X)) &&
1549           match(Other->getArgOperand(1), m_APInt(Val2))) {
1550         if (IsUnsigned)
1551           NewVal = Val->uadd_sat(*Val2);
1552         else if (Val->isNonNegative() == Val2->isNonNegative()) {
1553           bool Overflow;
1554           NewVal = Val->sadd_ov(*Val2, Overflow);
1555           if (Overflow) {
1556             // Both adds together may add more than SignedMaxValue
1557             // without saturating the final result.
1558             break;
1559           }
1560         } else {
1561           // Cannot fold saturated addition with different signs.
1562           break;
1563         }
1564 
1565         return replaceInstUsesWith(
1566             *II, Builder.CreateBinaryIntrinsic(
1567                      IID, X, ConstantInt::get(II->getType(), NewVal)));
1568       }
1569     }
1570     break;
1571   }
1572 
1573   case Intrinsic::minnum:
1574   case Intrinsic::maxnum:
1575   case Intrinsic::minimum:
1576   case Intrinsic::maximum: {
1577     Value *Arg0 = II->getArgOperand(0);
1578     Value *Arg1 = II->getArgOperand(1);
1579     Value *X, *Y;
1580     if (match(Arg0, m_FNeg(m_Value(X))) && match(Arg1, m_FNeg(m_Value(Y))) &&
1581         (Arg0->hasOneUse() || Arg1->hasOneUse())) {
1582       // If both operands are negated, invert the call and negate the result:
1583       // min(-X, -Y) --> -(max(X, Y))
1584       // max(-X, -Y) --> -(min(X, Y))
1585       Intrinsic::ID NewIID;
1586       switch (IID) {
1587       case Intrinsic::maxnum:
1588         NewIID = Intrinsic::minnum;
1589         break;
1590       case Intrinsic::minnum:
1591         NewIID = Intrinsic::maxnum;
1592         break;
1593       case Intrinsic::maximum:
1594         NewIID = Intrinsic::minimum;
1595         break;
1596       case Intrinsic::minimum:
1597         NewIID = Intrinsic::maximum;
1598         break;
1599       default:
1600         llvm_unreachable("unexpected intrinsic ID");
1601       }
1602       Value *NewCall = Builder.CreateBinaryIntrinsic(NewIID, X, Y, II);
1603       Instruction *FNeg = UnaryOperator::CreateFNeg(NewCall);
1604       FNeg->copyIRFlags(II);
1605       return FNeg;
1606     }
1607 
1608     // m(m(X, C2), C1) -> m(X, C)
1609     const APFloat *C1, *C2;
1610     if (auto *M = dyn_cast<IntrinsicInst>(Arg0)) {
1611       if (M->getIntrinsicID() == IID && match(Arg1, m_APFloat(C1)) &&
1612           ((match(M->getArgOperand(0), m_Value(X)) &&
1613             match(M->getArgOperand(1), m_APFloat(C2))) ||
1614            (match(M->getArgOperand(1), m_Value(X)) &&
1615             match(M->getArgOperand(0), m_APFloat(C2))))) {
1616         APFloat Res(0.0);
1617         switch (IID) {
1618         case Intrinsic::maxnum:
1619           Res = maxnum(*C1, *C2);
1620           break;
1621         case Intrinsic::minnum:
1622           Res = minnum(*C1, *C2);
1623           break;
1624         case Intrinsic::maximum:
1625           Res = maximum(*C1, *C2);
1626           break;
1627         case Intrinsic::minimum:
1628           Res = minimum(*C1, *C2);
1629           break;
1630         default:
1631           llvm_unreachable("unexpected intrinsic ID");
1632         }
1633         Instruction *NewCall = Builder.CreateBinaryIntrinsic(
1634             IID, X, ConstantFP::get(Arg0->getType(), Res), II);
1635         // TODO: Conservatively intersecting FMF. If Res == C2, the transform
1636         //       was a simplification (so Arg0 and its original flags could
1637         //       propagate?)
1638         NewCall->andIRFlags(M);
1639         return replaceInstUsesWith(*II, NewCall);
1640       }
1641     }
1642 
1643     // m((fpext X), (fpext Y)) -> fpext (m(X, Y))
1644     if (match(Arg0, m_OneUse(m_FPExt(m_Value(X)))) &&
1645         match(Arg1, m_OneUse(m_FPExt(m_Value(Y)))) &&
1646         X->getType() == Y->getType()) {
1647       Value *NewCall =
1648           Builder.CreateBinaryIntrinsic(IID, X, Y, II, II->getName());
1649       return new FPExtInst(NewCall, II->getType());
1650     }
1651 
1652     // max X, -X --> fabs X
1653     // min X, -X --> -(fabs X)
1654     // TODO: Remove one-use limitation? That is obviously better for max.
1655     //       It would be an extra instruction for min (fnabs), but that is
1656     //       still likely better for analysis and codegen.
1657     if ((match(Arg0, m_OneUse(m_FNeg(m_Value(X)))) && Arg1 == X) ||
1658         (match(Arg1, m_OneUse(m_FNeg(m_Value(X)))) && Arg0 == X)) {
1659       Value *R = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, X, II);
1660       if (IID == Intrinsic::minimum || IID == Intrinsic::minnum)
1661         R = Builder.CreateFNegFMF(R, II);
1662       return replaceInstUsesWith(*II, R);
1663     }
1664 
1665     break;
1666   }
1667   case Intrinsic::fmuladd: {
1668     // Canonicalize fast fmuladd to the separate fmul + fadd.
1669     if (II->isFast()) {
1670       BuilderTy::FastMathFlagGuard Guard(Builder);
1671       Builder.setFastMathFlags(II->getFastMathFlags());
1672       Value *Mul = Builder.CreateFMul(II->getArgOperand(0),
1673                                       II->getArgOperand(1));
1674       Value *Add = Builder.CreateFAdd(Mul, II->getArgOperand(2));
1675       Add->takeName(II);
1676       return replaceInstUsesWith(*II, Add);
1677     }
1678 
1679     // Try to simplify the underlying FMul.
1680     if (Value *V = SimplifyFMulInst(II->getArgOperand(0), II->getArgOperand(1),
1681                                     II->getFastMathFlags(),
1682                                     SQ.getWithInstruction(II))) {
1683       auto *FAdd = BinaryOperator::CreateFAdd(V, II->getArgOperand(2));
1684       FAdd->copyFastMathFlags(II);
1685       return FAdd;
1686     }
1687 
1688     LLVM_FALLTHROUGH;
1689   }
1690   case Intrinsic::fma: {
1691     // fma fneg(x), fneg(y), z -> fma x, y, z
1692     Value *Src0 = II->getArgOperand(0);
1693     Value *Src1 = II->getArgOperand(1);
1694     Value *X, *Y;
1695     if (match(Src0, m_FNeg(m_Value(X))) && match(Src1, m_FNeg(m_Value(Y)))) {
1696       replaceOperand(*II, 0, X);
1697       replaceOperand(*II, 1, Y);
1698       return II;
1699     }
1700 
1701     // fma fabs(x), fabs(x), z -> fma x, x, z
1702     if (match(Src0, m_FAbs(m_Value(X))) &&
1703         match(Src1, m_FAbs(m_Specific(X)))) {
1704       replaceOperand(*II, 0, X);
1705       replaceOperand(*II, 1, X);
1706       return II;
1707     }
1708 
1709     // Try to simplify the underlying FMul. We can only apply simplifications
1710     // that do not require rounding.
1711     if (Value *V = SimplifyFMAFMul(II->getArgOperand(0), II->getArgOperand(1),
1712                                    II->getFastMathFlags(),
1713                                    SQ.getWithInstruction(II))) {
1714       auto *FAdd = BinaryOperator::CreateFAdd(V, II->getArgOperand(2));
1715       FAdd->copyFastMathFlags(II);
1716       return FAdd;
1717     }
1718 
1719     // fma x, y, 0 -> fmul x, y
1720     // This is always valid for -0.0, but requires nsz for +0.0 as
1721     // -0.0 + 0.0 = 0.0, which would not be the same as the fmul on its own.
1722     if (match(II->getArgOperand(2), m_NegZeroFP()) ||
1723         (match(II->getArgOperand(2), m_PosZeroFP()) &&
1724          II->getFastMathFlags().noSignedZeros()))
1725       return BinaryOperator::CreateFMulFMF(Src0, Src1, II);
1726 
1727     break;
1728   }
1729   case Intrinsic::copysign: {
1730     Value *Mag = II->getArgOperand(0), *Sign = II->getArgOperand(1);
1731     if (SignBitMustBeZero(Sign, &TLI)) {
1732       // If we know that the sign argument is positive, reduce to FABS:
1733       // copysign Mag, +Sign --> fabs Mag
1734       Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, Mag, II);
1735       return replaceInstUsesWith(*II, Fabs);
1736     }
1737     // TODO: There should be a ValueTracking sibling like SignBitMustBeOne.
1738     const APFloat *C;
1739     if (match(Sign, m_APFloat(C)) && C->isNegative()) {
1740       // If we know that the sign argument is negative, reduce to FNABS:
1741       // copysign Mag, -Sign --> fneg (fabs Mag)
1742       Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, Mag, II);
1743       return replaceInstUsesWith(*II, Builder.CreateFNegFMF(Fabs, II));
1744     }
1745 
1746     // Propagate sign argument through nested calls:
1747     // copysign Mag, (copysign ?, X) --> copysign Mag, X
1748     Value *X;
1749     if (match(Sign, m_Intrinsic<Intrinsic::copysign>(m_Value(), m_Value(X))))
1750       return replaceOperand(*II, 1, X);
1751 
1752     // Peek through changes of magnitude's sign-bit. This call rewrites those:
1753     // copysign (fabs X), Sign --> copysign X, Sign
1754     // copysign (fneg X), Sign --> copysign X, Sign
1755     if (match(Mag, m_FAbs(m_Value(X))) || match(Mag, m_FNeg(m_Value(X))))
1756       return replaceOperand(*II, 0, X);
1757 
1758     break;
1759   }
1760   case Intrinsic::fabs: {
1761     Value *Cond, *TVal, *FVal;
1762     if (match(II->getArgOperand(0),
1763               m_Select(m_Value(Cond), m_Value(TVal), m_Value(FVal)))) {
1764       // fabs (select Cond, TrueC, FalseC) --> select Cond, AbsT, AbsF
1765       if (isa<Constant>(TVal) && isa<Constant>(FVal)) {
1766         CallInst *AbsT = Builder.CreateCall(II->getCalledFunction(), {TVal});
1767         CallInst *AbsF = Builder.CreateCall(II->getCalledFunction(), {FVal});
1768         return SelectInst::Create(Cond, AbsT, AbsF);
1769       }
1770       // fabs (select Cond, -FVal, FVal) --> fabs FVal
1771       if (match(TVal, m_FNeg(m_Specific(FVal))))
1772         return replaceOperand(*II, 0, FVal);
1773       // fabs (select Cond, TVal, -TVal) --> fabs TVal
1774       if (match(FVal, m_FNeg(m_Specific(TVal))))
1775         return replaceOperand(*II, 0, TVal);
1776     }
1777 
1778     LLVM_FALLTHROUGH;
1779   }
1780   case Intrinsic::ceil:
1781   case Intrinsic::floor:
1782   case Intrinsic::round:
1783   case Intrinsic::roundeven:
1784   case Intrinsic::nearbyint:
1785   case Intrinsic::rint:
1786   case Intrinsic::trunc: {
1787     Value *ExtSrc;
1788     if (match(II->getArgOperand(0), m_OneUse(m_FPExt(m_Value(ExtSrc))))) {
1789       // Narrow the call: intrinsic (fpext x) -> fpext (intrinsic x)
1790       Value *NarrowII = Builder.CreateUnaryIntrinsic(IID, ExtSrc, II);
1791       return new FPExtInst(NarrowII, II->getType());
1792     }
1793     break;
1794   }
1795   case Intrinsic::cos:
1796   case Intrinsic::amdgcn_cos: {
1797     Value *X;
1798     Value *Src = II->getArgOperand(0);
1799     if (match(Src, m_FNeg(m_Value(X))) || match(Src, m_FAbs(m_Value(X)))) {
1800       // cos(-x) -> cos(x)
1801       // cos(fabs(x)) -> cos(x)
1802       return replaceOperand(*II, 0, X);
1803     }
1804     break;
1805   }
1806   case Intrinsic::sin: {
1807     Value *X;
1808     if (match(II->getArgOperand(0), m_OneUse(m_FNeg(m_Value(X))))) {
1809       // sin(-x) --> -sin(x)
1810       Value *NewSin = Builder.CreateUnaryIntrinsic(Intrinsic::sin, X, II);
1811       Instruction *FNeg = UnaryOperator::CreateFNeg(NewSin);
1812       FNeg->copyFastMathFlags(II);
1813       return FNeg;
1814     }
1815     break;
1816   }
1817 
1818   case Intrinsic::arm_neon_vtbl1:
1819   case Intrinsic::aarch64_neon_tbl1:
1820     if (Value *V = simplifyNeonTbl1(*II, Builder))
1821       return replaceInstUsesWith(*II, V);
1822     break;
1823 
1824   case Intrinsic::arm_neon_vmulls:
1825   case Intrinsic::arm_neon_vmullu:
1826   case Intrinsic::aarch64_neon_smull:
1827   case Intrinsic::aarch64_neon_umull: {
1828     Value *Arg0 = II->getArgOperand(0);
1829     Value *Arg1 = II->getArgOperand(1);
1830 
1831     // Handle mul by zero first:
1832     if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) {
1833       return replaceInstUsesWith(CI, ConstantAggregateZero::get(II->getType()));
1834     }
1835 
1836     // Check for constant LHS & RHS - in this case we just simplify.
1837     bool Zext = (IID == Intrinsic::arm_neon_vmullu ||
1838                  IID == Intrinsic::aarch64_neon_umull);
1839     VectorType *NewVT = cast<VectorType>(II->getType());
1840     if (Constant *CV0 = dyn_cast<Constant>(Arg0)) {
1841       if (Constant *CV1 = dyn_cast<Constant>(Arg1)) {
1842         CV0 = ConstantExpr::getIntegerCast(CV0, NewVT, /*isSigned=*/!Zext);
1843         CV1 = ConstantExpr::getIntegerCast(CV1, NewVT, /*isSigned=*/!Zext);
1844 
1845         return replaceInstUsesWith(CI, ConstantExpr::getMul(CV0, CV1));
1846       }
1847 
1848       // Couldn't simplify - canonicalize constant to the RHS.
1849       std::swap(Arg0, Arg1);
1850     }
1851 
1852     // Handle mul by one:
1853     if (Constant *CV1 = dyn_cast<Constant>(Arg1))
1854       if (ConstantInt *Splat =
1855               dyn_cast_or_null<ConstantInt>(CV1->getSplatValue()))
1856         if (Splat->isOne())
1857           return CastInst::CreateIntegerCast(Arg0, II->getType(),
1858                                              /*isSigned=*/!Zext);
1859 
1860     break;
1861   }
1862   case Intrinsic::arm_neon_aesd:
1863   case Intrinsic::arm_neon_aese:
1864   case Intrinsic::aarch64_crypto_aesd:
1865   case Intrinsic::aarch64_crypto_aese: {
1866     Value *DataArg = II->getArgOperand(0);
1867     Value *KeyArg  = II->getArgOperand(1);
1868 
1869     // Try to use the builtin XOR in AESE and AESD to eliminate a prior XOR
1870     Value *Data, *Key;
1871     if (match(KeyArg, m_ZeroInt()) &&
1872         match(DataArg, m_Xor(m_Value(Data), m_Value(Key)))) {
1873       replaceOperand(*II, 0, Data);
1874       replaceOperand(*II, 1, Key);
1875       return II;
1876     }
1877     break;
1878   }
1879   case Intrinsic::hexagon_V6_vandvrt:
1880   case Intrinsic::hexagon_V6_vandvrt_128B: {
1881     // Simplify Q -> V -> Q conversion.
1882     if (auto Op0 = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
1883       Intrinsic::ID ID0 = Op0->getIntrinsicID();
1884       if (ID0 != Intrinsic::hexagon_V6_vandqrt &&
1885           ID0 != Intrinsic::hexagon_V6_vandqrt_128B)
1886         break;
1887       Value *Bytes = Op0->getArgOperand(1), *Mask = II->getArgOperand(1);
1888       uint64_t Bytes1 = computeKnownBits(Bytes, 0, Op0).One.getZExtValue();
1889       uint64_t Mask1 = computeKnownBits(Mask, 0, II).One.getZExtValue();
1890       // Check if every byte has common bits in Bytes and Mask.
1891       uint64_t C = Bytes1 & Mask1;
1892       if ((C & 0xFF) && (C & 0xFF00) && (C & 0xFF0000) && (C & 0xFF000000))
1893         return replaceInstUsesWith(*II, Op0->getArgOperand(0));
1894     }
1895     break;
1896   }
1897   case Intrinsic::stackrestore: {
1898     enum class ClassifyResult {
1899       None,
1900       Alloca,
1901       StackRestore,
1902       CallWithSideEffects,
1903     };
1904     auto Classify = [](const Instruction *I) {
1905       if (isa<AllocaInst>(I))
1906         return ClassifyResult::Alloca;
1907 
1908       if (auto *CI = dyn_cast<CallInst>(I)) {
1909         if (auto *II = dyn_cast<IntrinsicInst>(CI)) {
1910           if (II->getIntrinsicID() == Intrinsic::stackrestore)
1911             return ClassifyResult::StackRestore;
1912 
1913           if (II->mayHaveSideEffects())
1914             return ClassifyResult::CallWithSideEffects;
1915         } else {
1916           // Consider all non-intrinsic calls to be side effects
1917           return ClassifyResult::CallWithSideEffects;
1918         }
1919       }
1920 
1921       return ClassifyResult::None;
1922     };
1923 
1924     // If the stacksave and the stackrestore are in the same BB, and there is
1925     // no intervening call, alloca, or stackrestore of a different stacksave,
1926     // remove the restore. This can happen when variable allocas are DCE'd.
1927     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
1928       if (SS->getIntrinsicID() == Intrinsic::stacksave &&
1929           SS->getParent() == II->getParent()) {
1930         BasicBlock::iterator BI(SS);
1931         bool CannotRemove = false;
1932         for (++BI; &*BI != II; ++BI) {
1933           switch (Classify(&*BI)) {
1934           case ClassifyResult::None:
1935             // So far so good, look at next instructions.
1936             break;
1937 
1938           case ClassifyResult::StackRestore:
1939             // If we found an intervening stackrestore for a different
1940             // stacksave, we can't remove the stackrestore. Otherwise, continue.
1941             if (cast<IntrinsicInst>(*BI).getArgOperand(0) != SS)
1942               CannotRemove = true;
1943             break;
1944 
1945           case ClassifyResult::Alloca:
1946           case ClassifyResult::CallWithSideEffects:
1947             // If we found an alloca, a non-intrinsic call, or an intrinsic
1948             // call with side effects, we can't remove the stackrestore.
1949             CannotRemove = true;
1950             break;
1951           }
1952           if (CannotRemove)
1953             break;
1954         }
1955 
1956         if (!CannotRemove)
1957           return eraseInstFromFunction(CI);
1958       }
1959     }
1960 
1961     // Scan down this block to see if there is another stack restore in the
1962     // same block without an intervening call/alloca.
1963     BasicBlock::iterator BI(II);
1964     Instruction *TI = II->getParent()->getTerminator();
1965     bool CannotRemove = false;
1966     for (++BI; &*BI != TI; ++BI) {
1967       switch (Classify(&*BI)) {
1968       case ClassifyResult::None:
1969         // So far so good, look at next instructions.
1970         break;
1971 
1972       case ClassifyResult::StackRestore:
1973         // If there is a stackrestore below this one, remove this one.
1974         return eraseInstFromFunction(CI);
1975 
1976       case ClassifyResult::Alloca:
1977       case ClassifyResult::CallWithSideEffects:
1978         // If we found an alloca, a non-intrinsic call, or an intrinsic call
1979         // with side effects (such as llvm.stacksave and llvm.read_register),
1980         // we can't remove the stack restore.
1981         CannotRemove = true;
1982         break;
1983       }
1984       if (CannotRemove)
1985         break;
1986     }
1987 
1988     // If the stack restore is in a return, resume, or unwind block and if there
1989     // are no allocas or calls between the restore and the return, nuke the
1990     // restore.
1991     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI)))
1992       return eraseInstFromFunction(CI);
1993     break;
1994   }
1995   case Intrinsic::lifetime_end:
1996     // Asan needs to poison memory to detect invalid access which is possible
1997     // even for empty lifetime range.
1998     if (II->getFunction()->hasFnAttribute(Attribute::SanitizeAddress) ||
1999         II->getFunction()->hasFnAttribute(Attribute::SanitizeMemory) ||
2000         II->getFunction()->hasFnAttribute(Attribute::SanitizeHWAddress))
2001       break;
2002 
2003     if (removeTriviallyEmptyRange(*II, *this, [](const IntrinsicInst &I) {
2004           return I.getIntrinsicID() == Intrinsic::lifetime_start;
2005         }))
2006       return nullptr;
2007     break;
2008   case Intrinsic::assume: {
2009     Value *IIOperand = II->getArgOperand(0);
2010     SmallVector<OperandBundleDef, 4> OpBundles;
2011     II->getOperandBundlesAsDefs(OpBundles);
2012 
2013     /// This will remove the boolean Condition from the assume given as
2014     /// argument and remove the assume if it becomes useless.
2015     /// always returns nullptr for use as a return values.
2016     auto RemoveConditionFromAssume = [&](Instruction *Assume) -> Instruction * {
2017       assert(isa<AssumeInst>(Assume));
2018       if (isAssumeWithEmptyBundle(*cast<AssumeInst>(II)))
2019         return eraseInstFromFunction(CI);
2020       replaceUse(II->getOperandUse(0), ConstantInt::getTrue(II->getContext()));
2021       return nullptr;
2022     };
2023     // Remove an assume if it is followed by an identical assume.
2024     // TODO: Do we need this? Unless there are conflicting assumptions, the
2025     // computeKnownBits(IIOperand) below here eliminates redundant assumes.
2026     Instruction *Next = II->getNextNonDebugInstruction();
2027     if (match(Next, m_Intrinsic<Intrinsic::assume>(m_Specific(IIOperand))))
2028       return RemoveConditionFromAssume(Next);
2029 
2030     // Canonicalize assume(a && b) -> assume(a); assume(b);
2031     // Note: New assumption intrinsics created here are registered by
2032     // the InstCombineIRInserter object.
2033     FunctionType *AssumeIntrinsicTy = II->getFunctionType();
2034     Value *AssumeIntrinsic = II->getCalledOperand();
2035     Value *A, *B;
2036     if (match(IIOperand, m_LogicalAnd(m_Value(A), m_Value(B)))) {
2037       Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic, A, OpBundles,
2038                          II->getName());
2039       Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic, B, II->getName());
2040       return eraseInstFromFunction(*II);
2041     }
2042     // assume(!(a || b)) -> assume(!a); assume(!b);
2043     if (match(IIOperand, m_Not(m_LogicalOr(m_Value(A), m_Value(B))))) {
2044       Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic,
2045                          Builder.CreateNot(A), OpBundles, II->getName());
2046       Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic,
2047                          Builder.CreateNot(B), II->getName());
2048       return eraseInstFromFunction(*II);
2049     }
2050 
2051     // assume( (load addr) != null ) -> add 'nonnull' metadata to load
2052     // (if assume is valid at the load)
2053     CmpInst::Predicate Pred;
2054     Instruction *LHS;
2055     if (match(IIOperand, m_ICmp(Pred, m_Instruction(LHS), m_Zero())) &&
2056         Pred == ICmpInst::ICMP_NE && LHS->getOpcode() == Instruction::Load &&
2057         LHS->getType()->isPointerTy() &&
2058         isValidAssumeForContext(II, LHS, &DT)) {
2059       MDNode *MD = MDNode::get(II->getContext(), None);
2060       LHS->setMetadata(LLVMContext::MD_nonnull, MD);
2061       return RemoveConditionFromAssume(II);
2062 
2063       // TODO: apply nonnull return attributes to calls and invokes
2064       // TODO: apply range metadata for range check patterns?
2065     }
2066 
2067     // Convert nonnull assume like:
2068     // %A = icmp ne i32* %PTR, null
2069     // call void @llvm.assume(i1 %A)
2070     // into
2071     // call void @llvm.assume(i1 true) [ "nonnull"(i32* %PTR) ]
2072     if (EnableKnowledgeRetention &&
2073         match(IIOperand, m_Cmp(Pred, m_Value(A), m_Zero())) &&
2074         Pred == CmpInst::ICMP_NE && A->getType()->isPointerTy()) {
2075       if (auto *Replacement = buildAssumeFromKnowledge(
2076               {RetainedKnowledge{Attribute::NonNull, 0, A}}, Next, &AC, &DT)) {
2077 
2078         Replacement->insertBefore(Next);
2079         AC.registerAssumption(Replacement);
2080         return RemoveConditionFromAssume(II);
2081       }
2082     }
2083 
2084     // Convert alignment assume like:
2085     // %B = ptrtoint i32* %A to i64
2086     // %C = and i64 %B, Constant
2087     // %D = icmp eq i64 %C, 0
2088     // call void @llvm.assume(i1 %D)
2089     // into
2090     // call void @llvm.assume(i1 true) [ "align"(i32* [[A]], i64  Constant + 1)]
2091     uint64_t AlignMask;
2092     if (EnableKnowledgeRetention &&
2093         match(IIOperand,
2094               m_Cmp(Pred, m_And(m_Value(A), m_ConstantInt(AlignMask)),
2095                     m_Zero())) &&
2096         Pred == CmpInst::ICMP_EQ) {
2097       if (isPowerOf2_64(AlignMask + 1)) {
2098         uint64_t Offset = 0;
2099         match(A, m_Add(m_Value(A), m_ConstantInt(Offset)));
2100         if (match(A, m_PtrToInt(m_Value(A)))) {
2101           /// Note: this doesn't preserve the offset information but merges
2102           /// offset and alignment.
2103           /// TODO: we can generate a GEP instead of merging the alignment with
2104           /// the offset.
2105           RetainedKnowledge RK{Attribute::Alignment,
2106                                (unsigned)MinAlign(Offset, AlignMask + 1), A};
2107           if (auto *Replacement =
2108                   buildAssumeFromKnowledge(RK, Next, &AC, &DT)) {
2109 
2110             Replacement->insertAfter(II);
2111             AC.registerAssumption(Replacement);
2112           }
2113           return RemoveConditionFromAssume(II);
2114         }
2115       }
2116     }
2117 
2118     /// Canonicalize Knowledge in operand bundles.
2119     if (EnableKnowledgeRetention && II->hasOperandBundles()) {
2120       for (unsigned Idx = 0; Idx < II->getNumOperandBundles(); Idx++) {
2121         auto &BOI = II->bundle_op_info_begin()[Idx];
2122         RetainedKnowledge RK =
2123           llvm::getKnowledgeFromBundle(cast<AssumeInst>(*II), BOI);
2124         if (BOI.End - BOI.Begin > 2)
2125           continue; // Prevent reducing knowledge in an align with offset since
2126                     // extracting a RetainedKnowledge form them looses offset
2127                     // information
2128         RetainedKnowledge CanonRK =
2129           llvm::simplifyRetainedKnowledge(cast<AssumeInst>(II), RK,
2130                                           &getAssumptionCache(),
2131                                           &getDominatorTree());
2132         if (CanonRK == RK)
2133           continue;
2134         if (!CanonRK) {
2135           if (BOI.End - BOI.Begin > 0) {
2136             Worklist.pushValue(II->op_begin()[BOI.Begin]);
2137             Value::dropDroppableUse(II->op_begin()[BOI.Begin]);
2138           }
2139           continue;
2140         }
2141         assert(RK.AttrKind == CanonRK.AttrKind);
2142         if (BOI.End - BOI.Begin > 0)
2143           II->op_begin()[BOI.Begin].set(CanonRK.WasOn);
2144         if (BOI.End - BOI.Begin > 1)
2145           II->op_begin()[BOI.Begin + 1].set(ConstantInt::get(
2146               Type::getInt64Ty(II->getContext()), CanonRK.ArgValue));
2147         if (RK.WasOn)
2148           Worklist.pushValue(RK.WasOn);
2149         return II;
2150       }
2151     }
2152 
2153     // If there is a dominating assume with the same condition as this one,
2154     // then this one is redundant, and should be removed.
2155     KnownBits Known(1);
2156     computeKnownBits(IIOperand, Known, 0, II);
2157     if (Known.isAllOnes() && isAssumeWithEmptyBundle(cast<AssumeInst>(*II)))
2158       return eraseInstFromFunction(*II);
2159 
2160     // Update the cache of affected values for this assumption (we might be
2161     // here because we just simplified the condition).
2162     AC.updateAffectedValues(cast<AssumeInst>(II));
2163     break;
2164   }
2165   case Intrinsic::experimental_guard: {
2166     // Is this guard followed by another guard?  We scan forward over a small
2167     // fixed window of instructions to handle common cases with conditions
2168     // computed between guards.
2169     Instruction *NextInst = II->getNextNonDebugInstruction();
2170     for (unsigned i = 0; i < GuardWideningWindow; i++) {
2171       // Note: Using context-free form to avoid compile time blow up
2172       if (!isSafeToSpeculativelyExecute(NextInst))
2173         break;
2174       NextInst = NextInst->getNextNonDebugInstruction();
2175     }
2176     Value *NextCond = nullptr;
2177     if (match(NextInst,
2178               m_Intrinsic<Intrinsic::experimental_guard>(m_Value(NextCond)))) {
2179       Value *CurrCond = II->getArgOperand(0);
2180 
2181       // Remove a guard that it is immediately preceded by an identical guard.
2182       // Otherwise canonicalize guard(a); guard(b) -> guard(a & b).
2183       if (CurrCond != NextCond) {
2184         Instruction *MoveI = II->getNextNonDebugInstruction();
2185         while (MoveI != NextInst) {
2186           auto *Temp = MoveI;
2187           MoveI = MoveI->getNextNonDebugInstruction();
2188           Temp->moveBefore(II);
2189         }
2190         replaceOperand(*II, 0, Builder.CreateAnd(CurrCond, NextCond));
2191       }
2192       eraseInstFromFunction(*NextInst);
2193       return II;
2194     }
2195     break;
2196   }
2197   case Intrinsic::experimental_vector_insert: {
2198     Value *Vec = II->getArgOperand(0);
2199     Value *SubVec = II->getArgOperand(1);
2200     Value *Idx = II->getArgOperand(2);
2201     auto *DstTy = dyn_cast<FixedVectorType>(II->getType());
2202     auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType());
2203     auto *SubVecTy = dyn_cast<FixedVectorType>(SubVec->getType());
2204 
2205     // Only canonicalize if the destination vector, Vec, and SubVec are all
2206     // fixed vectors.
2207     if (DstTy && VecTy && SubVecTy) {
2208       unsigned DstNumElts = DstTy->getNumElements();
2209       unsigned VecNumElts = VecTy->getNumElements();
2210       unsigned SubVecNumElts = SubVecTy->getNumElements();
2211       unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
2212 
2213       // An insert that entirely overwrites Vec with SubVec is a nop.
2214       if (VecNumElts == SubVecNumElts)
2215         return replaceInstUsesWith(CI, SubVec);
2216 
2217       // Widen SubVec into a vector of the same width as Vec, since
2218       // shufflevector requires the two input vectors to be the same width.
2219       // Elements beyond the bounds of SubVec within the widened vector are
2220       // undefined.
2221       SmallVector<int, 8> WidenMask;
2222       unsigned i;
2223       for (i = 0; i != SubVecNumElts; ++i)
2224         WidenMask.push_back(i);
2225       for (; i != VecNumElts; ++i)
2226         WidenMask.push_back(UndefMaskElem);
2227 
2228       Value *WidenShuffle = Builder.CreateShuffleVector(SubVec, WidenMask);
2229 
2230       SmallVector<int, 8> Mask;
2231       for (unsigned i = 0; i != IdxN; ++i)
2232         Mask.push_back(i);
2233       for (unsigned i = DstNumElts; i != DstNumElts + SubVecNumElts; ++i)
2234         Mask.push_back(i);
2235       for (unsigned i = IdxN + SubVecNumElts; i != DstNumElts; ++i)
2236         Mask.push_back(i);
2237 
2238       Value *Shuffle = Builder.CreateShuffleVector(Vec, WidenShuffle, Mask);
2239       return replaceInstUsesWith(CI, Shuffle);
2240     }
2241     break;
2242   }
2243   case Intrinsic::experimental_vector_extract: {
2244     Value *Vec = II->getArgOperand(0);
2245     Value *Idx = II->getArgOperand(1);
2246 
2247     auto *DstTy = dyn_cast<FixedVectorType>(II->getType());
2248     auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType());
2249 
2250     // Only canonicalize if the the destination vector and Vec are fixed
2251     // vectors.
2252     if (DstTy && VecTy) {
2253       unsigned DstNumElts = DstTy->getNumElements();
2254       unsigned VecNumElts = VecTy->getNumElements();
2255       unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
2256 
2257       // Extracting the entirety of Vec is a nop.
2258       if (VecNumElts == DstNumElts) {
2259         replaceInstUsesWith(CI, Vec);
2260         return eraseInstFromFunction(CI);
2261       }
2262 
2263       SmallVector<int, 8> Mask;
2264       for (unsigned i = 0; i != DstNumElts; ++i)
2265         Mask.push_back(IdxN + i);
2266 
2267       Value *Shuffle = Builder.CreateShuffleVector(Vec, Mask);
2268       return replaceInstUsesWith(CI, Shuffle);
2269     }
2270     break;
2271   }
2272   case Intrinsic::experimental_vector_reverse: {
2273     Value *BO0, *BO1, *X, *Y;
2274     Value *Vec = II->getArgOperand(0);
2275     if (match(Vec, m_OneUse(m_BinOp(m_Value(BO0), m_Value(BO1))))) {
2276       auto *OldBinOp = cast<BinaryOperator>(Vec);
2277       if (match(BO0, m_Intrinsic<Intrinsic::experimental_vector_reverse>(
2278                          m_Value(X)))) {
2279         // rev(binop rev(X), rev(Y)) --> binop X, Y
2280         if (match(BO1, m_Intrinsic<Intrinsic::experimental_vector_reverse>(
2281                            m_Value(Y))))
2282           return replaceInstUsesWith(CI,
2283                                      BinaryOperator::CreateWithCopiedFlags(
2284                                          OldBinOp->getOpcode(), X, Y, OldBinOp,
2285                                          OldBinOp->getName(), II));
2286         // rev(binop rev(X), BO1Splat) --> binop X, BO1Splat
2287         if (isSplatValue(BO1))
2288           return replaceInstUsesWith(CI,
2289                                      BinaryOperator::CreateWithCopiedFlags(
2290                                          OldBinOp->getOpcode(), X, BO1,
2291                                          OldBinOp, OldBinOp->getName(), II));
2292       }
2293       // rev(binop BO0Splat, rev(Y)) --> binop BO0Splat, Y
2294       if (match(BO1, m_Intrinsic<Intrinsic::experimental_vector_reverse>(
2295                          m_Value(Y))) &&
2296           isSplatValue(BO0))
2297         return replaceInstUsesWith(CI, BinaryOperator::CreateWithCopiedFlags(
2298                                            OldBinOp->getOpcode(), BO0, Y,
2299                                            OldBinOp, OldBinOp->getName(), II));
2300     }
2301     // rev(unop rev(X)) --> unop X
2302     if (match(Vec, m_OneUse(m_UnOp(
2303                        m_Intrinsic<Intrinsic::experimental_vector_reverse>(
2304                            m_Value(X)))))) {
2305       auto *OldUnOp = cast<UnaryOperator>(Vec);
2306       auto *NewUnOp = UnaryOperator::CreateWithCopiedFlags(
2307           OldUnOp->getOpcode(), X, OldUnOp, OldUnOp->getName(), II);
2308       return replaceInstUsesWith(CI, NewUnOp);
2309     }
2310     break;
2311   }
2312   case Intrinsic::vector_reduce_or:
2313   case Intrinsic::vector_reduce_and: {
2314     // Canonicalize logical or/and reductions:
2315     // Or reduction for i1 is represented as:
2316     // %val = bitcast <ReduxWidth x i1> to iReduxWidth
2317     // %res = cmp ne iReduxWidth %val, 0
2318     // And reduction for i1 is represented as:
2319     // %val = bitcast <ReduxWidth x i1> to iReduxWidth
2320     // %res = cmp eq iReduxWidth %val, 11111
2321     Value *Arg = II->getArgOperand(0);
2322     Value *Vect;
2323     if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {
2324       if (auto *FTy = dyn_cast<FixedVectorType>(Vect->getType()))
2325         if (FTy->getElementType() == Builder.getInt1Ty()) {
2326           Value *Res = Builder.CreateBitCast(
2327               Vect, Builder.getIntNTy(FTy->getNumElements()));
2328           if (IID == Intrinsic::vector_reduce_and) {
2329             Res = Builder.CreateICmpEQ(
2330                 Res, ConstantInt::getAllOnesValue(Res->getType()));
2331           } else {
2332             assert(IID == Intrinsic::vector_reduce_or &&
2333                    "Expected or reduction.");
2334             Res = Builder.CreateIsNotNull(Res);
2335           }
2336           if (Arg != Vect)
2337             Res = Builder.CreateCast(cast<CastInst>(Arg)->getOpcode(), Res,
2338                                      II->getType());
2339           return replaceInstUsesWith(CI, Res);
2340         }
2341     }
2342     LLVM_FALLTHROUGH;
2343   }
2344   case Intrinsic::vector_reduce_add: {
2345     if (IID == Intrinsic::vector_reduce_add) {
2346       // Convert vector_reduce_add(ZExt(<n x i1>)) to
2347       // ZExtOrTrunc(ctpop(bitcast <n x i1> to in)).
2348       // Convert vector_reduce_add(SExt(<n x i1>)) to
2349       // -ZExtOrTrunc(ctpop(bitcast <n x i1> to in)).
2350       // Convert vector_reduce_add(<n x i1>) to
2351       // Trunc(ctpop(bitcast <n x i1> to in)).
2352       Value *Arg = II->getArgOperand(0);
2353       Value *Vect;
2354       if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {
2355         if (auto *FTy = dyn_cast<FixedVectorType>(Vect->getType()))
2356           if (FTy->getElementType() == Builder.getInt1Ty()) {
2357             Value *V = Builder.CreateBitCast(
2358                 Vect, Builder.getIntNTy(FTy->getNumElements()));
2359             Value *Res = Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, V);
2360             if (Res->getType() != II->getType())
2361               Res = Builder.CreateZExtOrTrunc(Res, II->getType());
2362             if (Arg != Vect &&
2363                 cast<Instruction>(Arg)->getOpcode() == Instruction::SExt)
2364               Res = Builder.CreateNeg(Res);
2365             return replaceInstUsesWith(CI, Res);
2366           }
2367       }
2368     }
2369     LLVM_FALLTHROUGH;
2370   }
2371   case Intrinsic::vector_reduce_xor: {
2372     if (IID == Intrinsic::vector_reduce_xor) {
2373       // Exclusive disjunction reduction over the vector with
2374       // (potentially-extended) i1 element type is actually a
2375       // (potentially-extended) arithmetic `add` reduction over the original
2376       // non-extended value:
2377       //   vector_reduce_xor(?ext(<n x i1>))
2378       //     -->
2379       //   ?ext(vector_reduce_add(<n x i1>))
2380       Value *Arg = II->getArgOperand(0);
2381       Value *Vect;
2382       if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {
2383         if (auto *FTy = dyn_cast<FixedVectorType>(Vect->getType()))
2384           if (FTy->getElementType() == Builder.getInt1Ty()) {
2385             Value *Res = Builder.CreateAddReduce(Vect);
2386             if (Arg != Vect)
2387               Res = Builder.CreateCast(cast<CastInst>(Arg)->getOpcode(), Res,
2388                                        II->getType());
2389             return replaceInstUsesWith(CI, Res);
2390           }
2391       }
2392     }
2393     LLVM_FALLTHROUGH;
2394   }
2395   case Intrinsic::vector_reduce_mul: {
2396     if (IID == Intrinsic::vector_reduce_mul) {
2397       // Multiplicative reduction over the vector with (potentially-extended)
2398       // i1 element type is actually a (potentially zero-extended)
2399       // logical `and` reduction over the original non-extended value:
2400       //   vector_reduce_mul(?ext(<n x i1>))
2401       //     -->
2402       //   zext(vector_reduce_and(<n x i1>))
2403       Value *Arg = II->getArgOperand(0);
2404       Value *Vect;
2405       if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {
2406         if (auto *FTy = dyn_cast<FixedVectorType>(Vect->getType()))
2407           if (FTy->getElementType() == Builder.getInt1Ty()) {
2408             Value *Res = Builder.CreateAndReduce(Vect);
2409             if (Res->getType() != II->getType())
2410               Res = Builder.CreateZExt(Res, II->getType());
2411             return replaceInstUsesWith(CI, Res);
2412           }
2413       }
2414     }
2415     LLVM_FALLTHROUGH;
2416   }
2417   case Intrinsic::vector_reduce_umin:
2418   case Intrinsic::vector_reduce_umax: {
2419     if (IID == Intrinsic::vector_reduce_umin ||
2420         IID == Intrinsic::vector_reduce_umax) {
2421       // UMin/UMax reduction over the vector with (potentially-extended)
2422       // i1 element type is actually a (potentially-extended)
2423       // logical `and`/`or` reduction over the original non-extended value:
2424       //   vector_reduce_u{min,max}(?ext(<n x i1>))
2425       //     -->
2426       //   ?ext(vector_reduce_{and,or}(<n x i1>))
2427       Value *Arg = II->getArgOperand(0);
2428       Value *Vect;
2429       if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {
2430         if (auto *FTy = dyn_cast<FixedVectorType>(Vect->getType()))
2431           if (FTy->getElementType() == Builder.getInt1Ty()) {
2432             Value *Res = IID == Intrinsic::vector_reduce_umin
2433                              ? Builder.CreateAndReduce(Vect)
2434                              : Builder.CreateOrReduce(Vect);
2435             if (Arg != Vect)
2436               Res = Builder.CreateCast(cast<CastInst>(Arg)->getOpcode(), Res,
2437                                        II->getType());
2438             return replaceInstUsesWith(CI, Res);
2439           }
2440       }
2441     }
2442     LLVM_FALLTHROUGH;
2443   }
2444   case Intrinsic::vector_reduce_smin:
2445   case Intrinsic::vector_reduce_smax: {
2446     if (IID == Intrinsic::vector_reduce_smin ||
2447         IID == Intrinsic::vector_reduce_smax) {
2448       // SMin/SMax reduction over the vector with (potentially-extended)
2449       // i1 element type is actually a (potentially-extended)
2450       // logical `and`/`or` reduction over the original non-extended value:
2451       //   vector_reduce_s{min,max}(<n x i1>)
2452       //     -->
2453       //   vector_reduce_{or,and}(<n x i1>)
2454       // and
2455       //   vector_reduce_s{min,max}(sext(<n x i1>))
2456       //     -->
2457       //   sext(vector_reduce_{or,and}(<n x i1>))
2458       // and
2459       //   vector_reduce_s{min,max}(zext(<n x i1>))
2460       //     -->
2461       //   zext(vector_reduce_{and,or}(<n x i1>))
2462       Value *Arg = II->getArgOperand(0);
2463       Value *Vect;
2464       if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {
2465         if (auto *FTy = dyn_cast<FixedVectorType>(Vect->getType()))
2466           if (FTy->getElementType() == Builder.getInt1Ty()) {
2467             Instruction::CastOps ExtOpc = Instruction::CastOps::CastOpsEnd;
2468             if (Arg != Vect)
2469               ExtOpc = cast<CastInst>(Arg)->getOpcode();
2470             Value *Res = ((IID == Intrinsic::vector_reduce_smin) ==
2471                           (ExtOpc == Instruction::CastOps::ZExt))
2472                              ? Builder.CreateAndReduce(Vect)
2473                              : Builder.CreateOrReduce(Vect);
2474             if (Arg != Vect)
2475               Res = Builder.CreateCast(ExtOpc, Res, II->getType());
2476             return replaceInstUsesWith(CI, Res);
2477           }
2478       }
2479     }
2480     LLVM_FALLTHROUGH;
2481   }
2482   case Intrinsic::vector_reduce_fmax:
2483   case Intrinsic::vector_reduce_fmin:
2484   case Intrinsic::vector_reduce_fadd:
2485   case Intrinsic::vector_reduce_fmul: {
2486     bool CanBeReassociated = (IID != Intrinsic::vector_reduce_fadd &&
2487                               IID != Intrinsic::vector_reduce_fmul) ||
2488                              II->hasAllowReassoc();
2489     const unsigned ArgIdx = (IID == Intrinsic::vector_reduce_fadd ||
2490                              IID == Intrinsic::vector_reduce_fmul)
2491                                 ? 1
2492                                 : 0;
2493     Value *Arg = II->getArgOperand(ArgIdx);
2494     Value *V;
2495     ArrayRef<int> Mask;
2496     if (!isa<FixedVectorType>(Arg->getType()) || !CanBeReassociated ||
2497         !match(Arg, m_Shuffle(m_Value(V), m_Undef(), m_Mask(Mask))) ||
2498         !cast<ShuffleVectorInst>(Arg)->isSingleSource())
2499       break;
2500     int Sz = Mask.size();
2501     SmallBitVector UsedIndices(Sz);
2502     for (int Idx : Mask) {
2503       if (Idx == UndefMaskElem || UsedIndices.test(Idx))
2504         break;
2505       UsedIndices.set(Idx);
2506     }
2507     // Can remove shuffle iff just shuffled elements, no repeats, undefs, or
2508     // other changes.
2509     if (UsedIndices.all()) {
2510       replaceUse(II->getOperandUse(ArgIdx), V);
2511       return nullptr;
2512     }
2513     break;
2514   }
2515   default: {
2516     // Handle target specific intrinsics
2517     Optional<Instruction *> V = targetInstCombineIntrinsic(*II);
2518     if (V.hasValue())
2519       return V.getValue();
2520     break;
2521   }
2522   }
2523   // Some intrinsics (like experimental_gc_statepoint) can be used in invoke
2524   // context, so it is handled in visitCallBase and we should trigger it.
2525   return visitCallBase(*II);
2526 }
2527 
2528 // Fence instruction simplification
2529 Instruction *InstCombinerImpl::visitFenceInst(FenceInst &FI) {
2530   auto *NFI = dyn_cast<FenceInst>(FI.getNextNonDebugInstruction());
2531   // This check is solely here to handle arbitrary target-dependent syncscopes.
2532   // TODO: Can remove if does not matter in practice.
2533   if (NFI && FI.isIdenticalTo(NFI))
2534     return eraseInstFromFunction(FI);
2535 
2536   // Returns true if FI1 is identical or stronger fence than FI2.
2537   auto isIdenticalOrStrongerFence = [](FenceInst *FI1, FenceInst *FI2) {
2538     auto FI1SyncScope = FI1->getSyncScopeID();
2539     // Consider same scope, where scope is global or single-thread.
2540     if (FI1SyncScope != FI2->getSyncScopeID() ||
2541         (FI1SyncScope != SyncScope::System &&
2542          FI1SyncScope != SyncScope::SingleThread))
2543       return false;
2544 
2545     return isAtLeastOrStrongerThan(FI1->getOrdering(), FI2->getOrdering());
2546   };
2547   if (NFI && isIdenticalOrStrongerFence(NFI, &FI))
2548     return eraseInstFromFunction(FI);
2549 
2550   if (auto *PFI = dyn_cast_or_null<FenceInst>(FI.getPrevNonDebugInstruction()))
2551     if (isIdenticalOrStrongerFence(PFI, &FI))
2552       return eraseInstFromFunction(FI);
2553   return nullptr;
2554 }
2555 
2556 // InvokeInst simplification
2557 Instruction *InstCombinerImpl::visitInvokeInst(InvokeInst &II) {
2558   return visitCallBase(II);
2559 }
2560 
2561 // CallBrInst simplification
2562 Instruction *InstCombinerImpl::visitCallBrInst(CallBrInst &CBI) {
2563   return visitCallBase(CBI);
2564 }
2565 
2566 /// If this cast does not affect the value passed through the varargs area, we
2567 /// can eliminate the use of the cast.
2568 static bool isSafeToEliminateVarargsCast(const CallBase &Call,
2569                                          const DataLayout &DL,
2570                                          const CastInst *const CI,
2571                                          const int ix) {
2572   if (!CI->isLosslessCast())
2573     return false;
2574 
2575   // If this is a GC intrinsic, avoid munging types.  We need types for
2576   // statepoint reconstruction in SelectionDAG.
2577   // TODO: This is probably something which should be expanded to all
2578   // intrinsics since the entire point of intrinsics is that
2579   // they are understandable by the optimizer.
2580   if (isa<GCStatepointInst>(Call) || isa<GCRelocateInst>(Call) ||
2581       isa<GCResultInst>(Call))
2582     return false;
2583 
2584   // Opaque pointers are compatible with any byval types.
2585   PointerType *SrcTy = cast<PointerType>(CI->getOperand(0)->getType());
2586   if (SrcTy->isOpaque())
2587     return true;
2588 
2589   // The size of ByVal or InAlloca arguments is derived from the type, so we
2590   // can't change to a type with a different size.  If the size were
2591   // passed explicitly we could avoid this check.
2592   if (!Call.isPassPointeeByValueArgument(ix))
2593     return true;
2594 
2595   // The transform currently only handles type replacement for byval, not other
2596   // type-carrying attributes.
2597   if (!Call.isByValArgument(ix))
2598     return false;
2599 
2600   Type *SrcElemTy = SrcTy->getNonOpaquePointerElementType();
2601   Type *DstElemTy = Call.getParamByValType(ix);
2602   if (!SrcElemTy->isSized() || !DstElemTy->isSized())
2603     return false;
2604   if (DL.getTypeAllocSize(SrcElemTy) != DL.getTypeAllocSize(DstElemTy))
2605     return false;
2606   return true;
2607 }
2608 
2609 Instruction *InstCombinerImpl::tryOptimizeCall(CallInst *CI) {
2610   if (!CI->getCalledFunction()) return nullptr;
2611 
2612   // Skip optimizing notail and musttail calls so
2613   // LibCallSimplifier::optimizeCall doesn't have to preserve those invariants.
2614   // LibCallSimplifier::optimizeCall should try to preseve tail calls though.
2615   if (CI->isMustTailCall() || CI->isNoTailCall())
2616     return nullptr;
2617 
2618   auto InstCombineRAUW = [this](Instruction *From, Value *With) {
2619     replaceInstUsesWith(*From, With);
2620   };
2621   auto InstCombineErase = [this](Instruction *I) {
2622     eraseInstFromFunction(*I);
2623   };
2624   LibCallSimplifier Simplifier(DL, &TLI, ORE, BFI, PSI, InstCombineRAUW,
2625                                InstCombineErase);
2626   if (Value *With = Simplifier.optimizeCall(CI, Builder)) {
2627     ++NumSimplified;
2628     return CI->use_empty() ? CI : replaceInstUsesWith(*CI, With);
2629   }
2630 
2631   return nullptr;
2632 }
2633 
2634 static IntrinsicInst *findInitTrampolineFromAlloca(Value *TrampMem) {
2635   // Strip off at most one level of pointer casts, looking for an alloca.  This
2636   // is good enough in practice and simpler than handling any number of casts.
2637   Value *Underlying = TrampMem->stripPointerCasts();
2638   if (Underlying != TrampMem &&
2639       (!Underlying->hasOneUse() || Underlying->user_back() != TrampMem))
2640     return nullptr;
2641   if (!isa<AllocaInst>(Underlying))
2642     return nullptr;
2643 
2644   IntrinsicInst *InitTrampoline = nullptr;
2645   for (User *U : TrampMem->users()) {
2646     IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
2647     if (!II)
2648       return nullptr;
2649     if (II->getIntrinsicID() == Intrinsic::init_trampoline) {
2650       if (InitTrampoline)
2651         // More than one init_trampoline writes to this value.  Give up.
2652         return nullptr;
2653       InitTrampoline = II;
2654       continue;
2655     }
2656     if (II->getIntrinsicID() == Intrinsic::adjust_trampoline)
2657       // Allow any number of calls to adjust.trampoline.
2658       continue;
2659     return nullptr;
2660   }
2661 
2662   // No call to init.trampoline found.
2663   if (!InitTrampoline)
2664     return nullptr;
2665 
2666   // Check that the alloca is being used in the expected way.
2667   if (InitTrampoline->getOperand(0) != TrampMem)
2668     return nullptr;
2669 
2670   return InitTrampoline;
2671 }
2672 
2673 static IntrinsicInst *findInitTrampolineFromBB(IntrinsicInst *AdjustTramp,
2674                                                Value *TrampMem) {
2675   // Visit all the previous instructions in the basic block, and try to find a
2676   // init.trampoline which has a direct path to the adjust.trampoline.
2677   for (BasicBlock::iterator I = AdjustTramp->getIterator(),
2678                             E = AdjustTramp->getParent()->begin();
2679        I != E;) {
2680     Instruction *Inst = &*--I;
2681     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2682       if (II->getIntrinsicID() == Intrinsic::init_trampoline &&
2683           II->getOperand(0) == TrampMem)
2684         return II;
2685     if (Inst->mayWriteToMemory())
2686       return nullptr;
2687   }
2688   return nullptr;
2689 }
2690 
2691 // Given a call to llvm.adjust.trampoline, find and return the corresponding
2692 // call to llvm.init.trampoline if the call to the trampoline can be optimized
2693 // to a direct call to a function.  Otherwise return NULL.
2694 static IntrinsicInst *findInitTrampoline(Value *Callee) {
2695   Callee = Callee->stripPointerCasts();
2696   IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee);
2697   if (!AdjustTramp ||
2698       AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline)
2699     return nullptr;
2700 
2701   Value *TrampMem = AdjustTramp->getOperand(0);
2702 
2703   if (IntrinsicInst *IT = findInitTrampolineFromAlloca(TrampMem))
2704     return IT;
2705   if (IntrinsicInst *IT = findInitTrampolineFromBB(AdjustTramp, TrampMem))
2706     return IT;
2707   return nullptr;
2708 }
2709 
2710 void InstCombinerImpl::annotateAnyAllocSite(CallBase &Call, const TargetLibraryInfo *TLI) {
2711   // Note: We only handle cases which can't be driven from generic attributes
2712   // here.  So, for example, nonnull and noalias (which are common properties
2713   // of some allocation functions) are expected to be handled via annotation
2714   // of the respective allocator declaration with generic attributes.
2715 
2716   uint64_t Size;
2717   ObjectSizeOpts Opts;
2718   if (getObjectSize(&Call, Size, DL, TLI, Opts) && Size > 0) {
2719     // TODO: We really should just emit deref_or_null here and then
2720     // let the generic inference code combine that with nonnull.
2721     if (Call.hasRetAttr(Attribute::NonNull))
2722       Call.addRetAttr(Attribute::getWithDereferenceableBytes(
2723           Call.getContext(), Size));
2724     else
2725       Call.addRetAttr(Attribute::getWithDereferenceableOrNullBytes(
2726           Call.getContext(), Size));
2727   }
2728 
2729   // Add alignment attribute if alignment is a power of two constant.
2730   Value *Alignment = getAllocAlignment(&Call, TLI);
2731   if (!Alignment)
2732     return;
2733 
2734   ConstantInt *AlignOpC = dyn_cast<ConstantInt>(Alignment);
2735   if (AlignOpC && AlignOpC->getValue().ult(llvm::Value::MaximumAlignment)) {
2736     uint64_t AlignmentVal = AlignOpC->getZExtValue();
2737     if (llvm::isPowerOf2_64(AlignmentVal)) {
2738       Call.removeRetAttr(Attribute::Alignment);
2739       Call.addRetAttr(Attribute::getWithAlignment(Call.getContext(),
2740                                                   Align(AlignmentVal)));
2741     }
2742   }
2743 }
2744 
2745 /// Improvements for call, callbr and invoke instructions.
2746 Instruction *InstCombinerImpl::visitCallBase(CallBase &Call) {
2747   if (isAllocationFn(&Call, &TLI))
2748     annotateAnyAllocSite(Call, &TLI);
2749 
2750   bool Changed = false;
2751 
2752   // Mark any parameters that are known to be non-null with the nonnull
2753   // attribute.  This is helpful for inlining calls to functions with null
2754   // checks on their arguments.
2755   SmallVector<unsigned, 4> ArgNos;
2756   unsigned ArgNo = 0;
2757 
2758   for (Value *V : Call.args()) {
2759     if (V->getType()->isPointerTy() &&
2760         !Call.paramHasAttr(ArgNo, Attribute::NonNull) &&
2761         isKnownNonZero(V, DL, 0, &AC, &Call, &DT))
2762       ArgNos.push_back(ArgNo);
2763     ArgNo++;
2764   }
2765 
2766   assert(ArgNo == Call.arg_size() && "Call arguments not processed correctly.");
2767 
2768   if (!ArgNos.empty()) {
2769     AttributeList AS = Call.getAttributes();
2770     LLVMContext &Ctx = Call.getContext();
2771     AS = AS.addParamAttribute(Ctx, ArgNos,
2772                               Attribute::get(Ctx, Attribute::NonNull));
2773     Call.setAttributes(AS);
2774     Changed = true;
2775   }
2776 
2777   // If the callee is a pointer to a function, attempt to move any casts to the
2778   // arguments of the call/callbr/invoke.
2779   Value *Callee = Call.getCalledOperand();
2780   if (!isa<Function>(Callee) && transformConstExprCastCall(Call))
2781     return nullptr;
2782 
2783   if (Function *CalleeF = dyn_cast<Function>(Callee)) {
2784     // Remove the convergent attr on calls when the callee is not convergent.
2785     if (Call.isConvergent() && !CalleeF->isConvergent() &&
2786         !CalleeF->isIntrinsic()) {
2787       LLVM_DEBUG(dbgs() << "Removing convergent attr from instr " << Call
2788                         << "\n");
2789       Call.setNotConvergent();
2790       return &Call;
2791     }
2792 
2793     // If the call and callee calling conventions don't match, and neither one
2794     // of the calling conventions is compatible with C calling convention
2795     // this call must be unreachable, as the call is undefined.
2796     if ((CalleeF->getCallingConv() != Call.getCallingConv() &&
2797          !(CalleeF->getCallingConv() == llvm::CallingConv::C &&
2798            TargetLibraryInfoImpl::isCallingConvCCompatible(&Call)) &&
2799          !(Call.getCallingConv() == llvm::CallingConv::C &&
2800            TargetLibraryInfoImpl::isCallingConvCCompatible(CalleeF))) &&
2801         // Only do this for calls to a function with a body.  A prototype may
2802         // not actually end up matching the implementation's calling conv for a
2803         // variety of reasons (e.g. it may be written in assembly).
2804         !CalleeF->isDeclaration()) {
2805       Instruction *OldCall = &Call;
2806       CreateNonTerminatorUnreachable(OldCall);
2807       // If OldCall does not return void then replaceInstUsesWith poison.
2808       // This allows ValueHandlers and custom metadata to adjust itself.
2809       if (!OldCall->getType()->isVoidTy())
2810         replaceInstUsesWith(*OldCall, PoisonValue::get(OldCall->getType()));
2811       if (isa<CallInst>(OldCall))
2812         return eraseInstFromFunction(*OldCall);
2813 
2814       // We cannot remove an invoke or a callbr, because it would change thexi
2815       // CFG, just change the callee to a null pointer.
2816       cast<CallBase>(OldCall)->setCalledFunction(
2817           CalleeF->getFunctionType(),
2818           Constant::getNullValue(CalleeF->getType()));
2819       return nullptr;
2820     }
2821   }
2822 
2823   // Calling a null function pointer is undefined if a null address isn't
2824   // dereferenceable.
2825   if ((isa<ConstantPointerNull>(Callee) &&
2826        !NullPointerIsDefined(Call.getFunction())) ||
2827       isa<UndefValue>(Callee)) {
2828     // If Call does not return void then replaceInstUsesWith poison.
2829     // This allows ValueHandlers and custom metadata to adjust itself.
2830     if (!Call.getType()->isVoidTy())
2831       replaceInstUsesWith(Call, PoisonValue::get(Call.getType()));
2832 
2833     if (Call.isTerminator()) {
2834       // Can't remove an invoke or callbr because we cannot change the CFG.
2835       return nullptr;
2836     }
2837 
2838     // This instruction is not reachable, just remove it.
2839     CreateNonTerminatorUnreachable(&Call);
2840     return eraseInstFromFunction(Call);
2841   }
2842 
2843   if (IntrinsicInst *II = findInitTrampoline(Callee))
2844     return transformCallThroughTrampoline(Call, *II);
2845 
2846   // TODO: Drop this transform once opaque pointer transition is done.
2847   FunctionType *FTy = Call.getFunctionType();
2848   if (FTy->isVarArg()) {
2849     int ix = FTy->getNumParams();
2850     // See if we can optimize any arguments passed through the varargs area of
2851     // the call.
2852     for (auto I = Call.arg_begin() + FTy->getNumParams(), E = Call.arg_end();
2853          I != E; ++I, ++ix) {
2854       CastInst *CI = dyn_cast<CastInst>(*I);
2855       if (CI && isSafeToEliminateVarargsCast(Call, DL, CI, ix)) {
2856         replaceUse(*I, CI->getOperand(0));
2857 
2858         // Update the byval type to match the pointer type.
2859         // Not necessary for opaque pointers.
2860         PointerType *NewTy = cast<PointerType>(CI->getOperand(0)->getType());
2861         if (!NewTy->isOpaque() && Call.isByValArgument(ix)) {
2862           Call.removeParamAttr(ix, Attribute::ByVal);
2863           Call.addParamAttr(ix, Attribute::getWithByValType(
2864                                     Call.getContext(),
2865                                     NewTy->getNonOpaquePointerElementType()));
2866         }
2867         Changed = true;
2868       }
2869     }
2870   }
2871 
2872   if (isa<InlineAsm>(Callee) && !Call.doesNotThrow()) {
2873     InlineAsm *IA = cast<InlineAsm>(Callee);
2874     if (!IA->canThrow()) {
2875       // Normal inline asm calls cannot throw - mark them
2876       // 'nounwind'.
2877       Call.setDoesNotThrow();
2878       Changed = true;
2879     }
2880   }
2881 
2882   // Try to optimize the call if possible, we require DataLayout for most of
2883   // this.  None of these calls are seen as possibly dead so go ahead and
2884   // delete the instruction now.
2885   if (CallInst *CI = dyn_cast<CallInst>(&Call)) {
2886     Instruction *I = tryOptimizeCall(CI);
2887     // If we changed something return the result, etc. Otherwise let
2888     // the fallthrough check.
2889     if (I) return eraseInstFromFunction(*I);
2890   }
2891 
2892   if (!Call.use_empty() && !Call.isMustTailCall())
2893     if (Value *ReturnedArg = Call.getReturnedArgOperand()) {
2894       Type *CallTy = Call.getType();
2895       Type *RetArgTy = ReturnedArg->getType();
2896       if (RetArgTy->canLosslesslyBitCastTo(CallTy))
2897         return replaceInstUsesWith(
2898             Call, Builder.CreateBitOrPointerCast(ReturnedArg, CallTy));
2899     }
2900 
2901   if (isAllocationFn(&Call, &TLI) &&
2902       isAllocRemovable(&cast<CallBase>(Call), &TLI))
2903     return visitAllocSite(Call);
2904 
2905   // Handle intrinsics which can be used in both call and invoke context.
2906   switch (Call.getIntrinsicID()) {
2907   case Intrinsic::experimental_gc_statepoint: {
2908     GCStatepointInst &GCSP = *cast<GCStatepointInst>(&Call);
2909     SmallPtrSet<Value *, 32> LiveGcValues;
2910     for (const GCRelocateInst *Reloc : GCSP.getGCRelocates()) {
2911       GCRelocateInst &GCR = *const_cast<GCRelocateInst *>(Reloc);
2912 
2913       // Remove the relocation if unused.
2914       if (GCR.use_empty()) {
2915         eraseInstFromFunction(GCR);
2916         continue;
2917       }
2918 
2919       Value *DerivedPtr = GCR.getDerivedPtr();
2920       Value *BasePtr = GCR.getBasePtr();
2921 
2922       // Undef is undef, even after relocation.
2923       if (isa<UndefValue>(DerivedPtr) || isa<UndefValue>(BasePtr)) {
2924         replaceInstUsesWith(GCR, UndefValue::get(GCR.getType()));
2925         eraseInstFromFunction(GCR);
2926         continue;
2927       }
2928 
2929       if (auto *PT = dyn_cast<PointerType>(GCR.getType())) {
2930         // The relocation of null will be null for most any collector.
2931         // TODO: provide a hook for this in GCStrategy.  There might be some
2932         // weird collector this property does not hold for.
2933         if (isa<ConstantPointerNull>(DerivedPtr)) {
2934           // Use null-pointer of gc_relocate's type to replace it.
2935           replaceInstUsesWith(GCR, ConstantPointerNull::get(PT));
2936           eraseInstFromFunction(GCR);
2937           continue;
2938         }
2939 
2940         // isKnownNonNull -> nonnull attribute
2941         if (!GCR.hasRetAttr(Attribute::NonNull) &&
2942             isKnownNonZero(DerivedPtr, DL, 0, &AC, &Call, &DT)) {
2943           GCR.addRetAttr(Attribute::NonNull);
2944           // We discovered new fact, re-check users.
2945           Worklist.pushUsersToWorkList(GCR);
2946         }
2947       }
2948 
2949       // If we have two copies of the same pointer in the statepoint argument
2950       // list, canonicalize to one.  This may let us common gc.relocates.
2951       if (GCR.getBasePtr() == GCR.getDerivedPtr() &&
2952           GCR.getBasePtrIndex() != GCR.getDerivedPtrIndex()) {
2953         auto *OpIntTy = GCR.getOperand(2)->getType();
2954         GCR.setOperand(2, ConstantInt::get(OpIntTy, GCR.getBasePtrIndex()));
2955       }
2956 
2957       // TODO: bitcast(relocate(p)) -> relocate(bitcast(p))
2958       // Canonicalize on the type from the uses to the defs
2959 
2960       // TODO: relocate((gep p, C, C2, ...)) -> gep(relocate(p), C, C2, ...)
2961       LiveGcValues.insert(BasePtr);
2962       LiveGcValues.insert(DerivedPtr);
2963     }
2964     Optional<OperandBundleUse> Bundle =
2965         GCSP.getOperandBundle(LLVMContext::OB_gc_live);
2966     unsigned NumOfGCLives = LiveGcValues.size();
2967     if (!Bundle.hasValue() || NumOfGCLives == Bundle->Inputs.size())
2968       break;
2969     // We can reduce the size of gc live bundle.
2970     DenseMap<Value *, unsigned> Val2Idx;
2971     std::vector<Value *> NewLiveGc;
2972     for (unsigned I = 0, E = Bundle->Inputs.size(); I < E; ++I) {
2973       Value *V = Bundle->Inputs[I];
2974       if (Val2Idx.count(V))
2975         continue;
2976       if (LiveGcValues.count(V)) {
2977         Val2Idx[V] = NewLiveGc.size();
2978         NewLiveGc.push_back(V);
2979       } else
2980         Val2Idx[V] = NumOfGCLives;
2981     }
2982     // Update all gc.relocates
2983     for (const GCRelocateInst *Reloc : GCSP.getGCRelocates()) {
2984       GCRelocateInst &GCR = *const_cast<GCRelocateInst *>(Reloc);
2985       Value *BasePtr = GCR.getBasePtr();
2986       assert(Val2Idx.count(BasePtr) && Val2Idx[BasePtr] != NumOfGCLives &&
2987              "Missed live gc for base pointer");
2988       auto *OpIntTy1 = GCR.getOperand(1)->getType();
2989       GCR.setOperand(1, ConstantInt::get(OpIntTy1, Val2Idx[BasePtr]));
2990       Value *DerivedPtr = GCR.getDerivedPtr();
2991       assert(Val2Idx.count(DerivedPtr) && Val2Idx[DerivedPtr] != NumOfGCLives &&
2992              "Missed live gc for derived pointer");
2993       auto *OpIntTy2 = GCR.getOperand(2)->getType();
2994       GCR.setOperand(2, ConstantInt::get(OpIntTy2, Val2Idx[DerivedPtr]));
2995     }
2996     // Create new statepoint instruction.
2997     OperandBundleDef NewBundle("gc-live", NewLiveGc);
2998     return CallBase::Create(&Call, NewBundle);
2999   }
3000   default: { break; }
3001   }
3002 
3003   return Changed ? &Call : nullptr;
3004 }
3005 
3006 /// If the callee is a constexpr cast of a function, attempt to move the cast to
3007 /// the arguments of the call/callbr/invoke.
3008 bool InstCombinerImpl::transformConstExprCastCall(CallBase &Call) {
3009   auto *Callee =
3010       dyn_cast<Function>(Call.getCalledOperand()->stripPointerCasts());
3011   if (!Callee)
3012     return false;
3013 
3014   // If this is a call to a thunk function, don't remove the cast. Thunks are
3015   // used to transparently forward all incoming parameters and outgoing return
3016   // values, so it's important to leave the cast in place.
3017   if (Callee->hasFnAttribute("thunk"))
3018     return false;
3019 
3020   // If this is a musttail call, the callee's prototype must match the caller's
3021   // prototype with the exception of pointee types. The code below doesn't
3022   // implement that, so we can't do this transform.
3023   // TODO: Do the transform if it only requires adding pointer casts.
3024   if (Call.isMustTailCall())
3025     return false;
3026 
3027   Instruction *Caller = &Call;
3028   const AttributeList &CallerPAL = Call.getAttributes();
3029 
3030   // Okay, this is a cast from a function to a different type.  Unless doing so
3031   // would cause a type conversion of one of our arguments, change this call to
3032   // be a direct call with arguments casted to the appropriate types.
3033   FunctionType *FT = Callee->getFunctionType();
3034   Type *OldRetTy = Caller->getType();
3035   Type *NewRetTy = FT->getReturnType();
3036 
3037   // Check to see if we are changing the return type...
3038   if (OldRetTy != NewRetTy) {
3039 
3040     if (NewRetTy->isStructTy())
3041       return false; // TODO: Handle multiple return values.
3042 
3043     if (!CastInst::isBitOrNoopPointerCastable(NewRetTy, OldRetTy, DL)) {
3044       if (Callee->isDeclaration())
3045         return false;   // Cannot transform this return value.
3046 
3047       if (!Caller->use_empty() &&
3048           // void -> non-void is handled specially
3049           !NewRetTy->isVoidTy())
3050         return false;   // Cannot transform this return value.
3051     }
3052 
3053     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
3054       AttrBuilder RAttrs(FT->getContext(), CallerPAL.getRetAttrs());
3055       if (RAttrs.overlaps(AttributeFuncs::typeIncompatible(NewRetTy)))
3056         return false;   // Attribute not compatible with transformed value.
3057     }
3058 
3059     // If the callbase is an invoke/callbr instruction, and the return value is
3060     // used by a PHI node in a successor, we cannot change the return type of
3061     // the call because there is no place to put the cast instruction (without
3062     // breaking the critical edge).  Bail out in this case.
3063     if (!Caller->use_empty()) {
3064       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
3065         for (User *U : II->users())
3066           if (PHINode *PN = dyn_cast<PHINode>(U))
3067             if (PN->getParent() == II->getNormalDest() ||
3068                 PN->getParent() == II->getUnwindDest())
3069               return false;
3070       // FIXME: Be conservative for callbr to avoid a quadratic search.
3071       if (isa<CallBrInst>(Caller))
3072         return false;
3073     }
3074   }
3075 
3076   unsigned NumActualArgs = Call.arg_size();
3077   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
3078 
3079   // Prevent us turning:
3080   // declare void @takes_i32_inalloca(i32* inalloca)
3081   //  call void bitcast (void (i32*)* @takes_i32_inalloca to void (i32)*)(i32 0)
3082   //
3083   // into:
3084   //  call void @takes_i32_inalloca(i32* null)
3085   //
3086   //  Similarly, avoid folding away bitcasts of byval calls.
3087   if (Callee->getAttributes().hasAttrSomewhere(Attribute::InAlloca) ||
3088       Callee->getAttributes().hasAttrSomewhere(Attribute::Preallocated) ||
3089       Callee->getAttributes().hasAttrSomewhere(Attribute::ByVal))
3090     return false;
3091 
3092   auto AI = Call.arg_begin();
3093   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
3094     Type *ParamTy = FT->getParamType(i);
3095     Type *ActTy = (*AI)->getType();
3096 
3097     if (!CastInst::isBitOrNoopPointerCastable(ActTy, ParamTy, DL))
3098       return false;   // Cannot transform this parameter value.
3099 
3100     if (AttrBuilder(FT->getContext(), CallerPAL.getParamAttrs(i))
3101             .overlaps(AttributeFuncs::typeIncompatible(ParamTy)))
3102       return false;   // Attribute not compatible with transformed value.
3103 
3104     if (Call.isInAllocaArgument(i))
3105       return false;   // Cannot transform to and from inalloca.
3106 
3107     if (CallerPAL.hasParamAttr(i, Attribute::SwiftError))
3108       return false;
3109 
3110     // If the parameter is passed as a byval argument, then we have to have a
3111     // sized type and the sized type has to have the same size as the old type.
3112     if (ParamTy != ActTy && CallerPAL.hasParamAttr(i, Attribute::ByVal)) {
3113       PointerType *ParamPTy = dyn_cast<PointerType>(ParamTy);
3114       if (!ParamPTy || !ParamPTy->getPointerElementType()->isSized())
3115         return false;
3116 
3117       Type *CurElTy = Call.getParamByValType(i);
3118       if (DL.getTypeAllocSize(CurElTy) !=
3119           DL.getTypeAllocSize(ParamPTy->getPointerElementType()))
3120         return false;
3121     }
3122   }
3123 
3124   if (Callee->isDeclaration()) {
3125     // Do not delete arguments unless we have a function body.
3126     if (FT->getNumParams() < NumActualArgs && !FT->isVarArg())
3127       return false;
3128 
3129     // If the callee is just a declaration, don't change the varargsness of the
3130     // call.  We don't want to introduce a varargs call where one doesn't
3131     // already exist.
3132     if (FT->isVarArg() != Call.getFunctionType()->isVarArg())
3133       return false;
3134 
3135     // If both the callee and the cast type are varargs, we still have to make
3136     // sure the number of fixed parameters are the same or we have the same
3137     // ABI issues as if we introduce a varargs call.
3138     if (FT->isVarArg() && Call.getFunctionType()->isVarArg() &&
3139         FT->getNumParams() != Call.getFunctionType()->getNumParams())
3140       return false;
3141   }
3142 
3143   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
3144       !CallerPAL.isEmpty()) {
3145     // In this case we have more arguments than the new function type, but we
3146     // won't be dropping them.  Check that these extra arguments have attributes
3147     // that are compatible with being a vararg call argument.
3148     unsigned SRetIdx;
3149     if (CallerPAL.hasAttrSomewhere(Attribute::StructRet, &SRetIdx) &&
3150         SRetIdx - AttributeList::FirstArgIndex >= FT->getNumParams())
3151       return false;
3152   }
3153 
3154   // Okay, we decided that this is a safe thing to do: go ahead and start
3155   // inserting cast instructions as necessary.
3156   SmallVector<Value *, 8> Args;
3157   SmallVector<AttributeSet, 8> ArgAttrs;
3158   Args.reserve(NumActualArgs);
3159   ArgAttrs.reserve(NumActualArgs);
3160 
3161   // Get any return attributes.
3162   AttrBuilder RAttrs(FT->getContext(), CallerPAL.getRetAttrs());
3163 
3164   // If the return value is not being used, the type may not be compatible
3165   // with the existing attributes.  Wipe out any problematic attributes.
3166   RAttrs.remove(AttributeFuncs::typeIncompatible(NewRetTy));
3167 
3168   LLVMContext &Ctx = Call.getContext();
3169   AI = Call.arg_begin();
3170   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
3171     Type *ParamTy = FT->getParamType(i);
3172 
3173     Value *NewArg = *AI;
3174     if ((*AI)->getType() != ParamTy)
3175       NewArg = Builder.CreateBitOrPointerCast(*AI, ParamTy);
3176     Args.push_back(NewArg);
3177 
3178     // Add any parameter attributes.
3179     if (CallerPAL.hasParamAttr(i, Attribute::ByVal)) {
3180       AttrBuilder AB(FT->getContext(), CallerPAL.getParamAttrs(i));
3181       AB.addByValAttr(NewArg->getType()->getPointerElementType());
3182       ArgAttrs.push_back(AttributeSet::get(Ctx, AB));
3183     } else
3184       ArgAttrs.push_back(CallerPAL.getParamAttrs(i));
3185   }
3186 
3187   // If the function takes more arguments than the call was taking, add them
3188   // now.
3189   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i) {
3190     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
3191     ArgAttrs.push_back(AttributeSet());
3192   }
3193 
3194   // If we are removing arguments to the function, emit an obnoxious warning.
3195   if (FT->getNumParams() < NumActualArgs) {
3196     // TODO: if (!FT->isVarArg()) this call may be unreachable. PR14722
3197     if (FT->isVarArg()) {
3198       // Add all of the arguments in their promoted form to the arg list.
3199       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
3200         Type *PTy = getPromotedType((*AI)->getType());
3201         Value *NewArg = *AI;
3202         if (PTy != (*AI)->getType()) {
3203           // Must promote to pass through va_arg area!
3204           Instruction::CastOps opcode =
3205             CastInst::getCastOpcode(*AI, false, PTy, false);
3206           NewArg = Builder.CreateCast(opcode, *AI, PTy);
3207         }
3208         Args.push_back(NewArg);
3209 
3210         // Add any parameter attributes.
3211         ArgAttrs.push_back(CallerPAL.getParamAttrs(i));
3212       }
3213     }
3214   }
3215 
3216   AttributeSet FnAttrs = CallerPAL.getFnAttrs();
3217 
3218   if (NewRetTy->isVoidTy())
3219     Caller->setName("");   // Void type should not have a name.
3220 
3221   assert((ArgAttrs.size() == FT->getNumParams() || FT->isVarArg()) &&
3222          "missing argument attributes");
3223   AttributeList NewCallerPAL = AttributeList::get(
3224       Ctx, FnAttrs, AttributeSet::get(Ctx, RAttrs), ArgAttrs);
3225 
3226   SmallVector<OperandBundleDef, 1> OpBundles;
3227   Call.getOperandBundlesAsDefs(OpBundles);
3228 
3229   CallBase *NewCall;
3230   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
3231     NewCall = Builder.CreateInvoke(Callee, II->getNormalDest(),
3232                                    II->getUnwindDest(), Args, OpBundles);
3233   } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(Caller)) {
3234     NewCall = Builder.CreateCallBr(Callee, CBI->getDefaultDest(),
3235                                    CBI->getIndirectDests(), Args, OpBundles);
3236   } else {
3237     NewCall = Builder.CreateCall(Callee, Args, OpBundles);
3238     cast<CallInst>(NewCall)->setTailCallKind(
3239         cast<CallInst>(Caller)->getTailCallKind());
3240   }
3241   NewCall->takeName(Caller);
3242   NewCall->setCallingConv(Call.getCallingConv());
3243   NewCall->setAttributes(NewCallerPAL);
3244 
3245   // Preserve prof metadata if any.
3246   NewCall->copyMetadata(*Caller, {LLVMContext::MD_prof});
3247 
3248   // Insert a cast of the return type as necessary.
3249   Instruction *NC = NewCall;
3250   Value *NV = NC;
3251   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
3252     if (!NV->getType()->isVoidTy()) {
3253       NV = NC = CastInst::CreateBitOrPointerCast(NC, OldRetTy);
3254       NC->setDebugLoc(Caller->getDebugLoc());
3255 
3256       // If this is an invoke/callbr instruction, we should insert it after the
3257       // first non-phi instruction in the normal successor block.
3258       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
3259         BasicBlock::iterator I = II->getNormalDest()->getFirstInsertionPt();
3260         InsertNewInstBefore(NC, *I);
3261       } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(Caller)) {
3262         BasicBlock::iterator I = CBI->getDefaultDest()->getFirstInsertionPt();
3263         InsertNewInstBefore(NC, *I);
3264       } else {
3265         // Otherwise, it's a call, just insert cast right after the call.
3266         InsertNewInstBefore(NC, *Caller);
3267       }
3268       Worklist.pushUsersToWorkList(*Caller);
3269     } else {
3270       NV = UndefValue::get(Caller->getType());
3271     }
3272   }
3273 
3274   if (!Caller->use_empty())
3275     replaceInstUsesWith(*Caller, NV);
3276   else if (Caller->hasValueHandle()) {
3277     if (OldRetTy == NV->getType())
3278       ValueHandleBase::ValueIsRAUWd(Caller, NV);
3279     else
3280       // We cannot call ValueIsRAUWd with a different type, and the
3281       // actual tracked value will disappear.
3282       ValueHandleBase::ValueIsDeleted(Caller);
3283   }
3284 
3285   eraseInstFromFunction(*Caller);
3286   return true;
3287 }
3288 
3289 /// Turn a call to a function created by init_trampoline / adjust_trampoline
3290 /// intrinsic pair into a direct call to the underlying function.
3291 Instruction *
3292 InstCombinerImpl::transformCallThroughTrampoline(CallBase &Call,
3293                                                  IntrinsicInst &Tramp) {
3294   Value *Callee = Call.getCalledOperand();
3295   Type *CalleeTy = Callee->getType();
3296   FunctionType *FTy = Call.getFunctionType();
3297   AttributeList Attrs = Call.getAttributes();
3298 
3299   // If the call already has the 'nest' attribute somewhere then give up -
3300   // otherwise 'nest' would occur twice after splicing in the chain.
3301   if (Attrs.hasAttrSomewhere(Attribute::Nest))
3302     return nullptr;
3303 
3304   Function *NestF = cast<Function>(Tramp.getArgOperand(1)->stripPointerCasts());
3305   FunctionType *NestFTy = NestF->getFunctionType();
3306 
3307   AttributeList NestAttrs = NestF->getAttributes();
3308   if (!NestAttrs.isEmpty()) {
3309     unsigned NestArgNo = 0;
3310     Type *NestTy = nullptr;
3311     AttributeSet NestAttr;
3312 
3313     // Look for a parameter marked with the 'nest' attribute.
3314     for (FunctionType::param_iterator I = NestFTy->param_begin(),
3315                                       E = NestFTy->param_end();
3316          I != E; ++NestArgNo, ++I) {
3317       AttributeSet AS = NestAttrs.getParamAttrs(NestArgNo);
3318       if (AS.hasAttribute(Attribute::Nest)) {
3319         // Record the parameter type and any other attributes.
3320         NestTy = *I;
3321         NestAttr = AS;
3322         break;
3323       }
3324     }
3325 
3326     if (NestTy) {
3327       std::vector<Value*> NewArgs;
3328       std::vector<AttributeSet> NewArgAttrs;
3329       NewArgs.reserve(Call.arg_size() + 1);
3330       NewArgAttrs.reserve(Call.arg_size());
3331 
3332       // Insert the nest argument into the call argument list, which may
3333       // mean appending it.  Likewise for attributes.
3334 
3335       {
3336         unsigned ArgNo = 0;
3337         auto I = Call.arg_begin(), E = Call.arg_end();
3338         do {
3339           if (ArgNo == NestArgNo) {
3340             // Add the chain argument and attributes.
3341             Value *NestVal = Tramp.getArgOperand(2);
3342             if (NestVal->getType() != NestTy)
3343               NestVal = Builder.CreateBitCast(NestVal, NestTy, "nest");
3344             NewArgs.push_back(NestVal);
3345             NewArgAttrs.push_back(NestAttr);
3346           }
3347 
3348           if (I == E)
3349             break;
3350 
3351           // Add the original argument and attributes.
3352           NewArgs.push_back(*I);
3353           NewArgAttrs.push_back(Attrs.getParamAttrs(ArgNo));
3354 
3355           ++ArgNo;
3356           ++I;
3357         } while (true);
3358       }
3359 
3360       // The trampoline may have been bitcast to a bogus type (FTy).
3361       // Handle this by synthesizing a new function type, equal to FTy
3362       // with the chain parameter inserted.
3363 
3364       std::vector<Type*> NewTypes;
3365       NewTypes.reserve(FTy->getNumParams()+1);
3366 
3367       // Insert the chain's type into the list of parameter types, which may
3368       // mean appending it.
3369       {
3370         unsigned ArgNo = 0;
3371         FunctionType::param_iterator I = FTy->param_begin(),
3372           E = FTy->param_end();
3373 
3374         do {
3375           if (ArgNo == NestArgNo)
3376             // Add the chain's type.
3377             NewTypes.push_back(NestTy);
3378 
3379           if (I == E)
3380             break;
3381 
3382           // Add the original type.
3383           NewTypes.push_back(*I);
3384 
3385           ++ArgNo;
3386           ++I;
3387         } while (true);
3388       }
3389 
3390       // Replace the trampoline call with a direct call.  Let the generic
3391       // code sort out any function type mismatches.
3392       FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
3393                                                 FTy->isVarArg());
3394       Constant *NewCallee =
3395         NestF->getType() == PointerType::getUnqual(NewFTy) ?
3396         NestF : ConstantExpr::getBitCast(NestF,
3397                                          PointerType::getUnqual(NewFTy));
3398       AttributeList NewPAL =
3399           AttributeList::get(FTy->getContext(), Attrs.getFnAttrs(),
3400                              Attrs.getRetAttrs(), NewArgAttrs);
3401 
3402       SmallVector<OperandBundleDef, 1> OpBundles;
3403       Call.getOperandBundlesAsDefs(OpBundles);
3404 
3405       Instruction *NewCaller;
3406       if (InvokeInst *II = dyn_cast<InvokeInst>(&Call)) {
3407         NewCaller = InvokeInst::Create(NewFTy, NewCallee,
3408                                        II->getNormalDest(), II->getUnwindDest(),
3409                                        NewArgs, OpBundles);
3410         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
3411         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
3412       } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(&Call)) {
3413         NewCaller =
3414             CallBrInst::Create(NewFTy, NewCallee, CBI->getDefaultDest(),
3415                                CBI->getIndirectDests(), NewArgs, OpBundles);
3416         cast<CallBrInst>(NewCaller)->setCallingConv(CBI->getCallingConv());
3417         cast<CallBrInst>(NewCaller)->setAttributes(NewPAL);
3418       } else {
3419         NewCaller = CallInst::Create(NewFTy, NewCallee, NewArgs, OpBundles);
3420         cast<CallInst>(NewCaller)->setTailCallKind(
3421             cast<CallInst>(Call).getTailCallKind());
3422         cast<CallInst>(NewCaller)->setCallingConv(
3423             cast<CallInst>(Call).getCallingConv());
3424         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
3425       }
3426       NewCaller->setDebugLoc(Call.getDebugLoc());
3427 
3428       return NewCaller;
3429     }
3430   }
3431 
3432   // Replace the trampoline call with a direct call.  Since there is no 'nest'
3433   // parameter, there is no need to adjust the argument list.  Let the generic
3434   // code sort out any function type mismatches.
3435   Constant *NewCallee = ConstantExpr::getBitCast(NestF, CalleeTy);
3436   Call.setCalledFunction(FTy, NewCallee);
3437   return &Call;
3438 }
3439