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