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