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