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