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