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