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