1 //===- InstCombineInternal.h - InstCombine pass internals -------*- C++ -*-===//
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 /// \file
10 ///
11 /// This file provides internal interfaces used to implement the InstCombine.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #ifndef LLVM_LIB_TRANSFORMS_INSTCOMBINE_INSTCOMBINEINTERNAL_H
16 #define LLVM_LIB_TRANSFORMS_INSTCOMBINE_INSTCOMBINEINTERNAL_H
17 
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/Analysis/InstructionSimplify.h"
22 #include "llvm/Analysis/TargetFolder.h"
23 #include "llvm/Analysis/ValueTracking.h"
24 #include "llvm/IR/Argument.h"
25 #include "llvm/IR/BasicBlock.h"
26 #include "llvm/IR/Constant.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/IRBuilder.h"
30 #include "llvm/IR/InstVisitor.h"
31 #include "llvm/IR/InstrTypes.h"
32 #include "llvm/IR/Instruction.h"
33 #include "llvm/IR/IntrinsicInst.h"
34 #include "llvm/IR/Intrinsics.h"
35 #include "llvm/IR/PatternMatch.h"
36 #include "llvm/IR/Use.h"
37 #include "llvm/IR/Value.h"
38 #include "llvm/Support/Casting.h"
39 #include "llvm/Support/Compiler.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/KnownBits.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include "llvm/Transforms/InstCombine/InstCombineWorklist.h"
44 #include "llvm/Transforms/Utils/Local.h"
45 #include <cassert>
46 #include <cstdint>
47 
48 #define DEBUG_TYPE "instcombine"
49 
50 using namespace llvm::PatternMatch;
51 
52 namespace llvm {
53 
54 class APInt;
55 class AssumptionCache;
56 class BlockFrequencyInfo;
57 class DataLayout;
58 class DominatorTree;
59 class GEPOperator;
60 class GlobalVariable;
61 class LoopInfo;
62 class OptimizationRemarkEmitter;
63 class ProfileSummaryInfo;
64 class TargetLibraryInfo;
65 class User;
66 
67 /// Assign a complexity or rank value to LLVM Values. This is used to reduce
68 /// the amount of pattern matching needed for compares and commutative
69 /// instructions. For example, if we have:
70 ///   icmp ugt X, Constant
71 /// or
72 ///   xor (add X, Constant), cast Z
73 ///
74 /// We do not have to consider the commuted variants of these patterns because
75 /// canonicalization based on complexity guarantees the above ordering.
76 ///
77 /// This routine maps IR values to various complexity ranks:
78 ///   0 -> undef
79 ///   1 -> Constants
80 ///   2 -> Other non-instructions
81 ///   3 -> Arguments
82 ///   4 -> Cast and (f)neg/not instructions
83 ///   5 -> Other instructions
84 static inline unsigned getComplexity(Value *V) {
85   if (isa<Instruction>(V)) {
86     if (isa<CastInst>(V) || match(V, m_Neg(m_Value())) ||
87         match(V, m_Not(m_Value())) || match(V, m_FNeg(m_Value())))
88       return 4;
89     return 5;
90   }
91   if (isa<Argument>(V))
92     return 3;
93   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
94 }
95 
96 /// Predicate canonicalization reduces the number of patterns that need to be
97 /// matched by other transforms. For example, we may swap the operands of a
98 /// conditional branch or select to create a compare with a canonical (inverted)
99 /// predicate which is then more likely to be matched with other values.
100 static inline bool isCanonicalPredicate(CmpInst::Predicate Pred) {
101   switch (Pred) {
102   case CmpInst::ICMP_NE:
103   case CmpInst::ICMP_ULE:
104   case CmpInst::ICMP_SLE:
105   case CmpInst::ICMP_UGE:
106   case CmpInst::ICMP_SGE:
107   // TODO: There are 16 FCMP predicates. Should others be (not) canonical?
108   case CmpInst::FCMP_ONE:
109   case CmpInst::FCMP_OLE:
110   case CmpInst::FCMP_OGE:
111     return false;
112   default:
113     return true;
114   }
115 }
116 
117 /// Given an exploded icmp instruction, return true if the comparison only
118 /// checks the sign bit. If it only checks the sign bit, set TrueIfSigned if the
119 /// result of the comparison is true when the input value is signed.
120 inline bool isSignBitCheck(ICmpInst::Predicate Pred, const APInt &RHS,
121                            bool &TrueIfSigned) {
122   switch (Pred) {
123   case ICmpInst::ICMP_SLT: // True if LHS s< 0
124     TrueIfSigned = true;
125     return RHS.isNullValue();
126   case ICmpInst::ICMP_SLE: // True if LHS s<= -1
127     TrueIfSigned = true;
128     return RHS.isAllOnesValue();
129   case ICmpInst::ICMP_SGT: // True if LHS s> -1
130     TrueIfSigned = false;
131     return RHS.isAllOnesValue();
132   case ICmpInst::ICMP_SGE: // True if LHS s>= 0
133     TrueIfSigned = false;
134     return RHS.isNullValue();
135   case ICmpInst::ICMP_UGT:
136     // True if LHS u> RHS and RHS == sign-bit-mask - 1
137     TrueIfSigned = true;
138     return RHS.isMaxSignedValue();
139   case ICmpInst::ICMP_UGE:
140     // True if LHS u>= RHS and RHS == sign-bit-mask (2^7, 2^15, 2^31, etc)
141     TrueIfSigned = true;
142     return RHS.isMinSignedValue();
143   case ICmpInst::ICMP_ULT:
144     // True if LHS u< RHS and RHS == sign-bit-mask (2^7, 2^15, 2^31, etc)
145     TrueIfSigned = false;
146     return RHS.isMinSignedValue();
147   case ICmpInst::ICMP_ULE:
148     // True if LHS u<= RHS and RHS == sign-bit-mask - 1
149     TrueIfSigned = false;
150     return RHS.isMaxSignedValue();
151   default:
152     return false;
153   }
154 }
155 
156 llvm::Optional<std::pair<CmpInst::Predicate, Constant *>>
157 getFlippedStrictnessPredicateAndConstant(CmpInst::Predicate Pred, Constant *C);
158 
159 /// Return the source operand of a potentially bitcasted value while optionally
160 /// checking if it has one use. If there is no bitcast or the one use check is
161 /// not met, return the input value itself.
162 static inline Value *peekThroughBitcast(Value *V, bool OneUseOnly = false) {
163   if (auto *BitCast = dyn_cast<BitCastInst>(V))
164     if (!OneUseOnly || BitCast->hasOneUse())
165       return BitCast->getOperand(0);
166 
167   // V is not a bitcast or V has more than one use and OneUseOnly is true.
168   return V;
169 }
170 
171 /// Add one to a Constant
172 static inline Constant *AddOne(Constant *C) {
173   return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
174 }
175 
176 /// Subtract one from a Constant
177 static inline Constant *SubOne(Constant *C) {
178   return ConstantExpr::getSub(C, ConstantInt::get(C->getType(), 1));
179 }
180 
181 /// Return true if the specified value is free to invert (apply ~ to).
182 /// This happens in cases where the ~ can be eliminated.  If WillInvertAllUses
183 /// is true, work under the assumption that the caller intends to remove all
184 /// uses of V and only keep uses of ~V.
185 ///
186 /// See also: canFreelyInvertAllUsersOf()
187 static inline bool isFreeToInvert(Value *V, bool WillInvertAllUses) {
188   // ~(~(X)) -> X.
189   if (match(V, m_Not(m_Value())))
190     return true;
191 
192   // Constants can be considered to be not'ed values.
193   if (match(V, m_AnyIntegralConstant()))
194     return true;
195 
196   // Compares can be inverted if all of their uses are being modified to use the
197   // ~V.
198   if (isa<CmpInst>(V))
199     return WillInvertAllUses;
200 
201   // If `V` is of the form `A + Constant` then `-1 - V` can be folded into `(-1
202   // - Constant) - A` if we are willing to invert all of the uses.
203   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(V))
204     if (BO->getOpcode() == Instruction::Add ||
205         BO->getOpcode() == Instruction::Sub)
206       if (isa<Constant>(BO->getOperand(0)) || isa<Constant>(BO->getOperand(1)))
207         return WillInvertAllUses;
208 
209   // Selects with invertible operands are freely invertible
210   if (match(V, m_Select(m_Value(), m_Not(m_Value()), m_Not(m_Value()))))
211     return WillInvertAllUses;
212 
213   return false;
214 }
215 
216 /// Given i1 V, can every user of V be freely adapted if V is changed to !V ?
217 ///
218 /// See also: isFreeToInvert()
219 static inline bool canFreelyInvertAllUsersOf(Value *V, Value *IgnoredUser) {
220   // Look at every user of V.
221   for (User *U : V->users()) {
222     if (U == IgnoredUser)
223       continue; // Don't consider this user.
224 
225     auto *I = cast<Instruction>(U);
226     switch (I->getOpcode()) {
227     case Instruction::Select:
228     case Instruction::Br:
229       break; // Free to invert by swapping true/false values/destinations.
230     case Instruction::Xor: // Can invert 'xor' if it's a 'not', by ignoring it.
231       if (!match(I, m_Not(m_Value())))
232         return false; // Not a 'not'.
233       break;
234     default:
235       return false; // Don't know, likely not freely invertible.
236     }
237     // So far all users were free to invert...
238   }
239   return true; // Can freely invert all users!
240 }
241 
242 /// Some binary operators require special handling to avoid poison and undefined
243 /// behavior. If a constant vector has undef elements, replace those undefs with
244 /// identity constants if possible because those are always safe to execute.
245 /// If no identity constant exists, replace undef with some other safe constant.
246 static inline Constant *getSafeVectorConstantForBinop(
247       BinaryOperator::BinaryOps Opcode, Constant *In, bool IsRHSConstant) {
248   auto *InVTy = dyn_cast<VectorType>(In->getType());
249   assert(InVTy && "Not expecting scalars here");
250 
251   Type *EltTy = InVTy->getElementType();
252   auto *SafeC = ConstantExpr::getBinOpIdentity(Opcode, EltTy, IsRHSConstant);
253   if (!SafeC) {
254     // TODO: Should this be available as a constant utility function? It is
255     // similar to getBinOpAbsorber().
256     if (IsRHSConstant) {
257       switch (Opcode) {
258       case Instruction::SRem: // X % 1 = 0
259       case Instruction::URem: // X %u 1 = 0
260         SafeC = ConstantInt::get(EltTy, 1);
261         break;
262       case Instruction::FRem: // X % 1.0 (doesn't simplify, but it is safe)
263         SafeC = ConstantFP::get(EltTy, 1.0);
264         break;
265       default:
266         llvm_unreachable("Only rem opcodes have no identity constant for RHS");
267       }
268     } else {
269       switch (Opcode) {
270       case Instruction::Shl:  // 0 << X = 0
271       case Instruction::LShr: // 0 >>u X = 0
272       case Instruction::AShr: // 0 >> X = 0
273       case Instruction::SDiv: // 0 / X = 0
274       case Instruction::UDiv: // 0 /u X = 0
275       case Instruction::SRem: // 0 % X = 0
276       case Instruction::URem: // 0 %u X = 0
277       case Instruction::Sub:  // 0 - X (doesn't simplify, but it is safe)
278       case Instruction::FSub: // 0.0 - X (doesn't simplify, but it is safe)
279       case Instruction::FDiv: // 0.0 / X (doesn't simplify, but it is safe)
280       case Instruction::FRem: // 0.0 % X = 0
281         SafeC = Constant::getNullValue(EltTy);
282         break;
283       default:
284         llvm_unreachable("Expected to find identity constant for opcode");
285       }
286     }
287   }
288   assert(SafeC && "Must have safe constant for binop");
289   unsigned NumElts = InVTy->getNumElements();
290   SmallVector<Constant *, 16> Out(NumElts);
291   for (unsigned i = 0; i != NumElts; ++i) {
292     Constant *C = In->getAggregateElement(i);
293     Out[i] = isa<UndefValue>(C) ? SafeC : C;
294   }
295   return ConstantVector::get(Out);
296 }
297 
298 /// The core instruction combiner logic.
299 ///
300 /// This class provides both the logic to recursively visit instructions and
301 /// combine them.
302 class LLVM_LIBRARY_VISIBILITY InstCombiner
303     : public InstVisitor<InstCombiner, Instruction *> {
304   // FIXME: These members shouldn't be public.
305 public:
306   /// A worklist of the instructions that need to be simplified.
307   InstCombineWorklist &Worklist;
308 
309   /// An IRBuilder that automatically inserts new instructions into the
310   /// worklist.
311   using BuilderTy = IRBuilder<TargetFolder, IRBuilderCallbackInserter>;
312   BuilderTy &Builder;
313 
314 private:
315   // Mode in which we are running the combiner.
316   const bool MinimizeSize;
317 
318   AliasAnalysis *AA;
319 
320   // Required analyses.
321   AssumptionCache &AC;
322   TargetLibraryInfo &TLI;
323   DominatorTree &DT;
324   const DataLayout &DL;
325   const SimplifyQuery SQ;
326   OptimizationRemarkEmitter &ORE;
327   BlockFrequencyInfo *BFI;
328   ProfileSummaryInfo *PSI;
329 
330   // Optional analyses. When non-null, these can both be used to do better
331   // combining and will be updated to reflect any changes.
332   LoopInfo *LI;
333 
334   bool MadeIRChange = false;
335 
336 public:
337   InstCombiner(InstCombineWorklist &Worklist, BuilderTy &Builder,
338                bool MinimizeSize, AliasAnalysis *AA,
339                AssumptionCache &AC, TargetLibraryInfo &TLI, DominatorTree &DT,
340                OptimizationRemarkEmitter &ORE, BlockFrequencyInfo *BFI,
341                ProfileSummaryInfo *PSI, const DataLayout &DL, LoopInfo *LI)
342       : Worklist(Worklist), Builder(Builder), MinimizeSize(MinimizeSize),
343         AA(AA), AC(AC), TLI(TLI), DT(DT),
344         DL(DL), SQ(DL, &TLI, &DT, &AC), ORE(ORE), BFI(BFI), PSI(PSI), LI(LI) {}
345 
346   /// Run the combiner over the entire worklist until it is empty.
347   ///
348   /// \returns true if the IR is changed.
349   bool run();
350 
351   AssumptionCache &getAssumptionCache() const { return AC; }
352 
353   const DataLayout &getDataLayout() const { return DL; }
354 
355   DominatorTree &getDominatorTree() const { return DT; }
356 
357   LoopInfo *getLoopInfo() const { return LI; }
358 
359   TargetLibraryInfo &getTargetLibraryInfo() const { return TLI; }
360 
361   // Visitation implementation - Implement instruction combining for different
362   // instruction types.  The semantics are as follows:
363   // Return Value:
364   //    null        - No change was made
365   //     I          - Change was made, I is still valid, I may be dead though
366   //   otherwise    - Change was made, replace I with returned instruction
367   //
368   Instruction *visitFNeg(UnaryOperator &I);
369   Instruction *visitAdd(BinaryOperator &I);
370   Instruction *visitFAdd(BinaryOperator &I);
371   Value *OptimizePointerDifference(
372       Value *LHS, Value *RHS, Type *Ty, bool isNUW);
373   Instruction *visitSub(BinaryOperator &I);
374   Instruction *visitFSub(BinaryOperator &I);
375   Instruction *visitMul(BinaryOperator &I);
376   Instruction *visitFMul(BinaryOperator &I);
377   Instruction *visitURem(BinaryOperator &I);
378   Instruction *visitSRem(BinaryOperator &I);
379   Instruction *visitFRem(BinaryOperator &I);
380   bool simplifyDivRemOfSelectWithZeroOp(BinaryOperator &I);
381   Instruction *commonRemTransforms(BinaryOperator &I);
382   Instruction *commonIRemTransforms(BinaryOperator &I);
383   Instruction *commonDivTransforms(BinaryOperator &I);
384   Instruction *commonIDivTransforms(BinaryOperator &I);
385   Instruction *visitUDiv(BinaryOperator &I);
386   Instruction *visitSDiv(BinaryOperator &I);
387   Instruction *visitFDiv(BinaryOperator &I);
388   Value *simplifyRangeCheck(ICmpInst *Cmp0, ICmpInst *Cmp1, bool Inverted);
389   Instruction *visitAnd(BinaryOperator &I);
390   Instruction *visitOr(BinaryOperator &I);
391   Instruction *visitXor(BinaryOperator &I);
392   Instruction *visitShl(BinaryOperator &I);
393   Value *reassociateShiftAmtsOfTwoSameDirectionShifts(
394       BinaryOperator *Sh0, const SimplifyQuery &SQ,
395       bool AnalyzeForSignBitExtraction = false);
396   Instruction *canonicalizeCondSignextOfHighBitExtractToSignextHighBitExtract(
397       BinaryOperator &I);
398   Instruction *foldVariableSignZeroExtensionOfVariableHighBitExtract(
399       BinaryOperator &OldAShr);
400   Instruction *visitAShr(BinaryOperator &I);
401   Instruction *visitLShr(BinaryOperator &I);
402   Instruction *commonShiftTransforms(BinaryOperator &I);
403   Instruction *visitFCmpInst(FCmpInst &I);
404   Instruction *visitICmpInst(ICmpInst &I);
405   Instruction *FoldShiftByConstant(Value *Op0, Constant *Op1,
406                                    BinaryOperator &I);
407   Instruction *commonCastTransforms(CastInst &CI);
408   Instruction *commonPointerCastTransforms(CastInst &CI);
409   Instruction *visitTrunc(TruncInst &CI);
410   Instruction *visitZExt(ZExtInst &CI);
411   Instruction *visitSExt(SExtInst &CI);
412   Instruction *visitFPTrunc(FPTruncInst &CI);
413   Instruction *visitFPExt(CastInst &CI);
414   Instruction *visitFPToUI(FPToUIInst &FI);
415   Instruction *visitFPToSI(FPToSIInst &FI);
416   Instruction *visitUIToFP(CastInst &CI);
417   Instruction *visitSIToFP(CastInst &CI);
418   Instruction *visitPtrToInt(PtrToIntInst &CI);
419   Instruction *visitIntToPtr(IntToPtrInst &CI);
420   Instruction *visitBitCast(BitCastInst &CI);
421   Instruction *visitAddrSpaceCast(AddrSpaceCastInst &CI);
422   Instruction *FoldItoFPtoI(Instruction &FI);
423   Instruction *visitSelectInst(SelectInst &SI);
424   Instruction *visitCallInst(CallInst &CI);
425   Instruction *visitInvokeInst(InvokeInst &II);
426   Instruction *visitCallBrInst(CallBrInst &CBI);
427 
428   Instruction *SliceUpIllegalIntegerPHI(PHINode &PN);
429   Instruction *visitPHINode(PHINode &PN);
430   Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
431   Instruction *visitAllocaInst(AllocaInst &AI);
432   Instruction *visitAllocSite(Instruction &FI);
433   Instruction *visitFree(CallInst &FI);
434   Instruction *visitLoadInst(LoadInst &LI);
435   Instruction *visitStoreInst(StoreInst &SI);
436   Instruction *visitAtomicRMWInst(AtomicRMWInst &SI);
437   Instruction *visitBranchInst(BranchInst &BI);
438   Instruction *visitFenceInst(FenceInst &FI);
439   Instruction *visitSwitchInst(SwitchInst &SI);
440   Instruction *visitReturnInst(ReturnInst &RI);
441   Instruction *visitInsertValueInst(InsertValueInst &IV);
442   Instruction *visitInsertElementInst(InsertElementInst &IE);
443   Instruction *visitExtractElementInst(ExtractElementInst &EI);
444   Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
445   Instruction *visitExtractValueInst(ExtractValueInst &EV);
446   Instruction *visitLandingPadInst(LandingPadInst &LI);
447   Instruction *visitVAEndInst(VAEndInst &I);
448   Instruction *visitFreeze(FreezeInst &I);
449 
450   /// Specify what to return for unhandled instructions.
451   Instruction *visitInstruction(Instruction &I) { return nullptr; }
452 
453   /// True when DB dominates all uses of DI except UI.
454   /// UI must be in the same block as DI.
455   /// The routine checks that the DI parent and DB are different.
456   bool dominatesAllUses(const Instruction *DI, const Instruction *UI,
457                         const BasicBlock *DB) const;
458 
459   /// Try to replace select with select operand SIOpd in SI-ICmp sequence.
460   bool replacedSelectWithOperand(SelectInst *SI, const ICmpInst *Icmp,
461                                  const unsigned SIOpd);
462 
463   /// Try to replace instruction \p I with value \p V which are pointers
464   /// in different address space.
465   /// \return true if successful.
466   bool replacePointer(Instruction &I, Value *V);
467 
468   LoadInst *combineLoadToNewType(LoadInst &LI, Type *NewTy,
469                                  const Twine &Suffix = "");
470 
471 private:
472   bool shouldChangeType(unsigned FromBitWidth, unsigned ToBitWidth) const;
473   bool shouldChangeType(Type *From, Type *To) const;
474   Value *dyn_castNegVal(Value *V) const;
475   Type *FindElementAtOffset(PointerType *PtrTy, int64_t Offset,
476                             SmallVectorImpl<Value *> &NewIndices);
477 
478   /// Classify whether a cast is worth optimizing.
479   ///
480   /// This is a helper to decide whether the simplification of
481   /// logic(cast(A), cast(B)) to cast(logic(A, B)) should be performed.
482   ///
483   /// \param CI The cast we are interested in.
484   ///
485   /// \return true if this cast actually results in any code being generated and
486   /// if it cannot already be eliminated by some other transformation.
487   bool shouldOptimizeCast(CastInst *CI);
488 
489   /// Try to optimize a sequence of instructions checking if an operation
490   /// on LHS and RHS overflows.
491   ///
492   /// If this overflow check is done via one of the overflow check intrinsics,
493   /// then CtxI has to be the call instruction calling that intrinsic.  If this
494   /// overflow check is done by arithmetic followed by a compare, then CtxI has
495   /// to be the arithmetic instruction.
496   ///
497   /// If a simplification is possible, stores the simplified result of the
498   /// operation in OperationResult and result of the overflow check in
499   /// OverflowResult, and return true.  If no simplification is possible,
500   /// returns false.
501   bool OptimizeOverflowCheck(Instruction::BinaryOps BinaryOp, bool IsSigned,
502                              Value *LHS, Value *RHS,
503                              Instruction &CtxI, Value *&OperationResult,
504                              Constant *&OverflowResult);
505 
506   Instruction *visitCallBase(CallBase &Call);
507   Instruction *tryOptimizeCall(CallInst *CI);
508   bool transformConstExprCastCall(CallBase &Call);
509   Instruction *transformCallThroughTrampoline(CallBase &Call,
510                                               IntrinsicInst &Tramp);
511 
512   Value *simplifyMaskedLoad(IntrinsicInst &II);
513   Instruction *simplifyMaskedStore(IntrinsicInst &II);
514   Instruction *simplifyMaskedGather(IntrinsicInst &II);
515   Instruction *simplifyMaskedScatter(IntrinsicInst &II);
516 
517   /// Transform (zext icmp) to bitwise / integer operations in order to
518   /// eliminate it.
519   ///
520   /// \param ICI The icmp of the (zext icmp) pair we are interested in.
521   /// \parem CI The zext of the (zext icmp) pair we are interested in.
522   /// \param DoTransform Pass false to just test whether the given (zext icmp)
523   /// would be transformed. Pass true to actually perform the transformation.
524   ///
525   /// \return null if the transformation cannot be performed. If the
526   /// transformation can be performed the new instruction that replaces the
527   /// (zext icmp) pair will be returned (if \p DoTransform is false the
528   /// unmodified \p ICI will be returned in this case).
529   Instruction *transformZExtICmp(ICmpInst *ICI, ZExtInst &CI,
530                                  bool DoTransform = true);
531 
532   Instruction *transformSExtICmp(ICmpInst *ICI, Instruction &CI);
533 
534   bool willNotOverflowSignedAdd(const Value *LHS, const Value *RHS,
535                                 const Instruction &CxtI) const {
536     return computeOverflowForSignedAdd(LHS, RHS, &CxtI) ==
537            OverflowResult::NeverOverflows;
538   }
539 
540   bool willNotOverflowUnsignedAdd(const Value *LHS, const Value *RHS,
541                                   const Instruction &CxtI) const {
542     return computeOverflowForUnsignedAdd(LHS, RHS, &CxtI) ==
543            OverflowResult::NeverOverflows;
544   }
545 
546   bool willNotOverflowAdd(const Value *LHS, const Value *RHS,
547                           const Instruction &CxtI, bool IsSigned) const {
548     return IsSigned ? willNotOverflowSignedAdd(LHS, RHS, CxtI)
549                     : willNotOverflowUnsignedAdd(LHS, RHS, CxtI);
550   }
551 
552   bool willNotOverflowSignedSub(const Value *LHS, const Value *RHS,
553                                 const Instruction &CxtI) const {
554     return computeOverflowForSignedSub(LHS, RHS, &CxtI) ==
555            OverflowResult::NeverOverflows;
556   }
557 
558   bool willNotOverflowUnsignedSub(const Value *LHS, const Value *RHS,
559                                   const Instruction &CxtI) const {
560     return computeOverflowForUnsignedSub(LHS, RHS, &CxtI) ==
561            OverflowResult::NeverOverflows;
562   }
563 
564   bool willNotOverflowSub(const Value *LHS, const Value *RHS,
565                           const Instruction &CxtI, bool IsSigned) const {
566     return IsSigned ? willNotOverflowSignedSub(LHS, RHS, CxtI)
567                     : willNotOverflowUnsignedSub(LHS, RHS, CxtI);
568   }
569 
570   bool willNotOverflowSignedMul(const Value *LHS, const Value *RHS,
571                                 const Instruction &CxtI) const {
572     return computeOverflowForSignedMul(LHS, RHS, &CxtI) ==
573            OverflowResult::NeverOverflows;
574   }
575 
576   bool willNotOverflowUnsignedMul(const Value *LHS, const Value *RHS,
577                                   const Instruction &CxtI) const {
578     return computeOverflowForUnsignedMul(LHS, RHS, &CxtI) ==
579            OverflowResult::NeverOverflows;
580   }
581 
582   bool willNotOverflowMul(const Value *LHS, const Value *RHS,
583                           const Instruction &CxtI, bool IsSigned) const {
584     return IsSigned ? willNotOverflowSignedMul(LHS, RHS, CxtI)
585                     : willNotOverflowUnsignedMul(LHS, RHS, CxtI);
586   }
587 
588   bool willNotOverflow(BinaryOperator::BinaryOps Opcode, const Value *LHS,
589                        const Value *RHS, const Instruction &CxtI,
590                        bool IsSigned) const {
591     switch (Opcode) {
592     case Instruction::Add: return willNotOverflowAdd(LHS, RHS, CxtI, IsSigned);
593     case Instruction::Sub: return willNotOverflowSub(LHS, RHS, CxtI, IsSigned);
594     case Instruction::Mul: return willNotOverflowMul(LHS, RHS, CxtI, IsSigned);
595     default: llvm_unreachable("Unexpected opcode for overflow query");
596     }
597   }
598 
599   Value *EmitGEPOffset(User *GEP);
600   Instruction *scalarizePHI(ExtractElementInst &EI, PHINode *PN);
601   Instruction *foldCastedBitwiseLogic(BinaryOperator &I);
602   Instruction *narrowBinOp(TruncInst &Trunc);
603   Instruction *narrowMaskedBinOp(BinaryOperator &And);
604   Instruction *narrowMathIfNoOverflow(BinaryOperator &I);
605   Instruction *narrowRotate(TruncInst &Trunc);
606   Instruction *optimizeBitCastFromPhi(CastInst &CI, PHINode *PN);
607   Instruction *matchSAddSubSat(SelectInst &MinMax1);
608 
609   /// Determine if a pair of casts can be replaced by a single cast.
610   ///
611   /// \param CI1 The first of a pair of casts.
612   /// \param CI2 The second of a pair of casts.
613   ///
614   /// \return 0 if the cast pair cannot be eliminated, otherwise returns an
615   /// Instruction::CastOps value for a cast that can replace the pair, casting
616   /// CI1->getSrcTy() to CI2->getDstTy().
617   ///
618   /// \see CastInst::isEliminableCastPair
619   Instruction::CastOps isEliminableCastPair(const CastInst *CI1,
620                                             const CastInst *CI2);
621 
622   Value *foldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS, BinaryOperator &And);
623   Value *foldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS, BinaryOperator &Or);
624   Value *foldXorOfICmps(ICmpInst *LHS, ICmpInst *RHS, BinaryOperator &Xor);
625 
626   /// Optimize (fcmp)&(fcmp) or (fcmp)|(fcmp).
627   /// NOTE: Unlike most of instcombine, this returns a Value which should
628   /// already be inserted into the function.
629   Value *foldLogicOfFCmps(FCmpInst *LHS, FCmpInst *RHS, bool IsAnd);
630 
631   Value *foldAndOrOfICmpsOfAndWithPow2(ICmpInst *LHS, ICmpInst *RHS,
632                                        BinaryOperator &Logic);
633   Value *matchSelectFromAndOr(Value *A, Value *B, Value *C, Value *D);
634   Value *getSelectCondition(Value *A, Value *B);
635 
636   Instruction *foldIntrinsicWithOverflowCommon(IntrinsicInst *II);
637 
638 public:
639   /// Inserts an instruction \p New before instruction \p Old
640   ///
641   /// Also adds the new instruction to the worklist and returns \p New so that
642   /// it is suitable for use as the return from the visitation patterns.
643   Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
644     assert(New && !New->getParent() &&
645            "New instruction already inserted into a basic block!");
646     BasicBlock *BB = Old.getParent();
647     BB->getInstList().insert(Old.getIterator(), New); // Insert inst
648     Worklist.push(New);
649     return New;
650   }
651 
652   /// Same as InsertNewInstBefore, but also sets the debug loc.
653   Instruction *InsertNewInstWith(Instruction *New, Instruction &Old) {
654     New->setDebugLoc(Old.getDebugLoc());
655     return InsertNewInstBefore(New, Old);
656   }
657 
658   /// A combiner-aware RAUW-like routine.
659   ///
660   /// This method is to be used when an instruction is found to be dead,
661   /// replaceable with another preexisting expression. Here we add all uses of
662   /// I to the worklist, replace all uses of I with the new value, then return
663   /// I, so that the inst combiner will know that I was modified.
664   Instruction *replaceInstUsesWith(Instruction &I, Value *V) {
665     // If there are no uses to replace, then we return nullptr to indicate that
666     // no changes were made to the program.
667     if (I.use_empty()) return nullptr;
668 
669     Worklist.pushUsersToWorkList(I); // Add all modified instrs to worklist.
670 
671     // If we are replacing the instruction with itself, this must be in a
672     // segment of unreachable code, so just clobber the instruction.
673     if (&I == V)
674       V = UndefValue::get(I.getType());
675 
676     LLVM_DEBUG(dbgs() << "IC: Replacing " << I << "\n"
677                       << "    with " << *V << '\n');
678 
679     I.replaceAllUsesWith(V);
680     return &I;
681   }
682 
683   /// Replace operand of instruction and add old operand to the worklist.
684   Instruction *replaceOperand(Instruction &I, unsigned OpNum, Value *V) {
685     Worklist.addValue(I.getOperand(OpNum));
686     I.setOperand(OpNum, V);
687     return &I;
688   }
689 
690   /// Replace use and add the previously used value to the worklist.
691   void replaceUse(Use &U, Value *NewValue) {
692     Worklist.addValue(U);
693     U = NewValue;
694   }
695 
696   /// Creates a result tuple for an overflow intrinsic \p II with a given
697   /// \p Result and a constant \p Overflow value.
698   Instruction *CreateOverflowTuple(IntrinsicInst *II, Value *Result,
699                                    Constant *Overflow) {
700     Constant *V[] = {UndefValue::get(Result->getType()), Overflow};
701     StructType *ST = cast<StructType>(II->getType());
702     Constant *Struct = ConstantStruct::get(ST, V);
703     return InsertValueInst::Create(Struct, Result, 0);
704   }
705 
706   /// Create and insert the idiom we use to indicate a block is unreachable
707   /// without having to rewrite the CFG from within InstCombine.
708   void CreateNonTerminatorUnreachable(Instruction *InsertAt) {
709     auto &Ctx = InsertAt->getContext();
710     new StoreInst(ConstantInt::getTrue(Ctx),
711                   UndefValue::get(Type::getInt1PtrTy(Ctx)),
712                   InsertAt);
713   }
714 
715 
716   /// Combiner aware instruction erasure.
717   ///
718   /// When dealing with an instruction that has side effects or produces a void
719   /// value, we can't rely on DCE to delete the instruction. Instead, visit
720   /// methods should return the value returned by this function.
721   Instruction *eraseInstFromFunction(Instruction &I) {
722     LLVM_DEBUG(dbgs() << "IC: ERASE " << I << '\n');
723     assert(I.use_empty() && "Cannot erase instruction that is used!");
724     salvageDebugInfoOrMarkUndef(I);
725 
726     // Make sure that we reprocess all operands now that we reduced their
727     // use counts.
728     for (Use &Operand : I.operands())
729       if (auto *Inst = dyn_cast<Instruction>(Operand))
730         Worklist.add(Inst);
731 
732     Worklist.remove(&I);
733     I.eraseFromParent();
734     MadeIRChange = true;
735     return nullptr; // Don't do anything with FI
736   }
737 
738   void computeKnownBits(const Value *V, KnownBits &Known,
739                         unsigned Depth, const Instruction *CxtI) const {
740     llvm::computeKnownBits(V, Known, DL, Depth, &AC, CxtI, &DT);
741   }
742 
743   KnownBits computeKnownBits(const Value *V, unsigned Depth,
744                              const Instruction *CxtI) const {
745     return llvm::computeKnownBits(V, DL, Depth, &AC, CxtI, &DT);
746   }
747 
748   bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero = false,
749                               unsigned Depth = 0,
750                               const Instruction *CxtI = nullptr) {
751     return llvm::isKnownToBeAPowerOfTwo(V, DL, OrZero, Depth, &AC, CxtI, &DT);
752   }
753 
754   bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth = 0,
755                          const Instruction *CxtI = nullptr) const {
756     return llvm::MaskedValueIsZero(V, Mask, DL, Depth, &AC, CxtI, &DT);
757   }
758 
759   unsigned ComputeNumSignBits(const Value *Op, unsigned Depth = 0,
760                               const Instruction *CxtI = nullptr) const {
761     return llvm::ComputeNumSignBits(Op, DL, Depth, &AC, CxtI, &DT);
762   }
763 
764   OverflowResult computeOverflowForUnsignedMul(const Value *LHS,
765                                                const Value *RHS,
766                                                const Instruction *CxtI) const {
767     return llvm::computeOverflowForUnsignedMul(LHS, RHS, DL, &AC, CxtI, &DT);
768   }
769 
770   OverflowResult computeOverflowForSignedMul(const Value *LHS,
771                                              const Value *RHS,
772                                              const Instruction *CxtI) const {
773     return llvm::computeOverflowForSignedMul(LHS, RHS, DL, &AC, CxtI, &DT);
774   }
775 
776   OverflowResult computeOverflowForUnsignedAdd(const Value *LHS,
777                                                const Value *RHS,
778                                                const Instruction *CxtI) const {
779     return llvm::computeOverflowForUnsignedAdd(LHS, RHS, DL, &AC, CxtI, &DT);
780   }
781 
782   OverflowResult computeOverflowForSignedAdd(const Value *LHS,
783                                              const Value *RHS,
784                                              const Instruction *CxtI) const {
785     return llvm::computeOverflowForSignedAdd(LHS, RHS, DL, &AC, CxtI, &DT);
786   }
787 
788   OverflowResult computeOverflowForUnsignedSub(const Value *LHS,
789                                                const Value *RHS,
790                                                const Instruction *CxtI) const {
791     return llvm::computeOverflowForUnsignedSub(LHS, RHS, DL, &AC, CxtI, &DT);
792   }
793 
794   OverflowResult computeOverflowForSignedSub(const Value *LHS, const Value *RHS,
795                                              const Instruction *CxtI) const {
796     return llvm::computeOverflowForSignedSub(LHS, RHS, DL, &AC, CxtI, &DT);
797   }
798 
799   OverflowResult computeOverflow(
800       Instruction::BinaryOps BinaryOp, bool IsSigned,
801       Value *LHS, Value *RHS, Instruction *CxtI) const;
802 
803   /// Maximum size of array considered when transforming.
804   uint64_t MaxArraySizeForCombine = 0;
805 
806 private:
807   /// Performs a few simplifications for operators which are associative
808   /// or commutative.
809   bool SimplifyAssociativeOrCommutative(BinaryOperator &I);
810 
811   /// Tries to simplify binary operations which some other binary
812   /// operation distributes over.
813   ///
814   /// It does this by either by factorizing out common terms (eg "(A*B)+(A*C)"
815   /// -> "A*(B+C)") or expanding out if this results in simplifications (eg: "A
816   /// & (B | C) -> (A&B) | (A&C)" if this is a win).  Returns the simplified
817   /// value, or null if it didn't simplify.
818   Value *SimplifyUsingDistributiveLaws(BinaryOperator &I);
819 
820   /// Tries to simplify add operations using the definition of remainder.
821   ///
822   /// The definition of remainder is X % C = X - (X / C ) * C. The add
823   /// expression X % C0 + (( X / C0 ) % C1) * C0 can be simplified to
824   /// X % (C0 * C1)
825   Value *SimplifyAddWithRemainder(BinaryOperator &I);
826 
827   // Binary Op helper for select operations where the expression can be
828   // efficiently reorganized.
829   Value *SimplifySelectsFeedingBinaryOp(BinaryOperator &I, Value *LHS,
830                                         Value *RHS);
831 
832   /// This tries to simplify binary operations by factorizing out common terms
833   /// (e. g. "(A*B)+(A*C)" -> "A*(B+C)").
834   Value *tryFactorization(BinaryOperator &, Instruction::BinaryOps, Value *,
835                           Value *, Value *, Value *);
836 
837   /// Match a select chain which produces one of three values based on whether
838   /// the LHS is less than, equal to, or greater than RHS respectively.
839   /// Return true if we matched a three way compare idiom. The LHS, RHS, Less,
840   /// Equal and Greater values are saved in the matching process and returned to
841   /// the caller.
842   bool matchThreeWayIntCompare(SelectInst *SI, Value *&LHS, Value *&RHS,
843                                ConstantInt *&Less, ConstantInt *&Equal,
844                                ConstantInt *&Greater);
845 
846   /// Attempts to replace V with a simpler value based on the demanded
847   /// bits.
848   Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, KnownBits &Known,
849                                  unsigned Depth, Instruction *CxtI);
850   bool SimplifyDemandedBits(Instruction *I, unsigned Op,
851                             const APInt &DemandedMask, KnownBits &Known,
852                             unsigned Depth = 0);
853 
854   /// Helper routine of SimplifyDemandedUseBits. It computes KnownZero/KnownOne
855   /// bits. It also tries to handle simplifications that can be done based on
856   /// DemandedMask, but without modifying the Instruction.
857   Value *SimplifyMultipleUseDemandedBits(Instruction *I,
858                                          const APInt &DemandedMask,
859                                          KnownBits &Known,
860                                          unsigned Depth, Instruction *CxtI);
861 
862   /// Helper routine of SimplifyDemandedUseBits. It tries to simplify demanded
863   /// bit for "r1 = shr x, c1; r2 = shl r1, c2" instruction sequence.
864   Value *simplifyShrShlDemandedBits(
865       Instruction *Shr, const APInt &ShrOp1, Instruction *Shl,
866       const APInt &ShlOp1, const APInt &DemandedMask, KnownBits &Known);
867 
868   /// Tries to simplify operands to an integer instruction based on its
869   /// demanded bits.
870   bool SimplifyDemandedInstructionBits(Instruction &Inst);
871 
872   Value *simplifyAMDGCNMemoryIntrinsicDemanded(IntrinsicInst *II,
873                                                APInt DemandedElts,
874                                                int DmaskIdx = -1);
875 
876   Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
877                                     APInt &UndefElts, unsigned Depth = 0,
878                                     bool AllowMultipleUsers = false);
879 
880   /// Canonicalize the position of binops relative to shufflevector.
881   Instruction *foldVectorBinop(BinaryOperator &Inst);
882 
883   /// Given a binary operator, cast instruction, or select which has a PHI node
884   /// as operand #0, see if we can fold the instruction into the PHI (which is
885   /// only possible if all operands to the PHI are constants).
886   Instruction *foldOpIntoPhi(Instruction &I, PHINode *PN);
887 
888   /// Given an instruction with a select as one operand and a constant as the
889   /// other operand, try to fold the binary operator into the select arguments.
890   /// This also works for Cast instructions, which obviously do not have a
891   /// second operand.
892   Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI);
893 
894   /// This is a convenience wrapper function for the above two functions.
895   Instruction *foldBinOpIntoSelectOrPhi(BinaryOperator &I);
896 
897   Instruction *foldAddWithConstant(BinaryOperator &Add);
898 
899   /// Try to rotate an operation below a PHI node, using PHI nodes for
900   /// its operands.
901   Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
902   Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
903   Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
904   Instruction *FoldPHIArgLoadIntoPHI(PHINode &PN);
905   Instruction *FoldPHIArgZextsIntoPHI(PHINode &PN);
906 
907   /// If an integer typed PHI has only one use which is an IntToPtr operation,
908   /// replace the PHI with an existing pointer typed PHI if it exists. Otherwise
909   /// insert a new pointer typed PHI and replace the original one.
910   Instruction *FoldIntegerTypedPHI(PHINode &PN);
911 
912   /// Helper function for FoldPHIArgXIntoPHI() to set debug location for the
913   /// folded operation.
914   void PHIArgMergedDebugLoc(Instruction *Inst, PHINode &PN);
915 
916   Instruction *foldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
917                            ICmpInst::Predicate Cond, Instruction &I);
918   Instruction *foldAllocaCmp(ICmpInst &ICI, const AllocaInst *Alloca,
919                              const Value *Other);
920   Instruction *foldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP,
921                                             GlobalVariable *GV, CmpInst &ICI,
922                                             ConstantInt *AndCst = nullptr);
923   Instruction *foldFCmpIntToFPConst(FCmpInst &I, Instruction *LHSI,
924                                     Constant *RHSC);
925   Instruction *foldICmpAddOpConst(Value *X, const APInt &C,
926                                   ICmpInst::Predicate Pred);
927   Instruction *foldICmpWithCastOp(ICmpInst &ICI);
928 
929   Instruction *foldICmpUsingKnownBits(ICmpInst &Cmp);
930   Instruction *foldICmpWithDominatingICmp(ICmpInst &Cmp);
931   Instruction *foldICmpWithConstant(ICmpInst &Cmp);
932   Instruction *foldICmpInstWithConstant(ICmpInst &Cmp);
933   Instruction *foldICmpInstWithConstantNotInt(ICmpInst &Cmp);
934   Instruction *foldICmpBinOp(ICmpInst &Cmp, const SimplifyQuery &SQ);
935   Instruction *foldICmpEquality(ICmpInst &Cmp);
936   Instruction *foldIRemByPowerOfTwoToBitTest(ICmpInst &I);
937   Instruction *foldSignBitTest(ICmpInst &I);
938   Instruction *foldICmpWithZero(ICmpInst &Cmp);
939 
940   Value *foldUnsignedMultiplicationOverflowCheck(ICmpInst &Cmp);
941 
942   Instruction *foldICmpSelectConstant(ICmpInst &Cmp, SelectInst *Select,
943                                       ConstantInt *C);
944   Instruction *foldICmpTruncConstant(ICmpInst &Cmp, TruncInst *Trunc,
945                                      const APInt &C);
946   Instruction *foldICmpAndConstant(ICmpInst &Cmp, BinaryOperator *And,
947                                    const APInt &C);
948   Instruction *foldICmpXorConstant(ICmpInst &Cmp, BinaryOperator *Xor,
949                                    const APInt &C);
950   Instruction *foldICmpOrConstant(ICmpInst &Cmp, BinaryOperator *Or,
951                                   const APInt &C);
952   Instruction *foldICmpMulConstant(ICmpInst &Cmp, BinaryOperator *Mul,
953                                    const APInt &C);
954   Instruction *foldICmpShlConstant(ICmpInst &Cmp, BinaryOperator *Shl,
955                                    const APInt &C);
956   Instruction *foldICmpShrConstant(ICmpInst &Cmp, BinaryOperator *Shr,
957                                    const APInt &C);
958   Instruction *foldICmpSRemConstant(ICmpInst &Cmp, BinaryOperator *UDiv,
959                                     const APInt &C);
960   Instruction *foldICmpUDivConstant(ICmpInst &Cmp, BinaryOperator *UDiv,
961                                     const APInt &C);
962   Instruction *foldICmpDivConstant(ICmpInst &Cmp, BinaryOperator *Div,
963                                    const APInt &C);
964   Instruction *foldICmpSubConstant(ICmpInst &Cmp, BinaryOperator *Sub,
965                                    const APInt &C);
966   Instruction *foldICmpAddConstant(ICmpInst &Cmp, BinaryOperator *Add,
967                                    const APInt &C);
968   Instruction *foldICmpAndConstConst(ICmpInst &Cmp, BinaryOperator *And,
969                                      const APInt &C1);
970   Instruction *foldICmpAndShift(ICmpInst &Cmp, BinaryOperator *And,
971                                 const APInt &C1, const APInt &C2);
972   Instruction *foldICmpShrConstConst(ICmpInst &I, Value *ShAmt, const APInt &C1,
973                                      const APInt &C2);
974   Instruction *foldICmpShlConstConst(ICmpInst &I, Value *ShAmt, const APInt &C1,
975                                      const APInt &C2);
976 
977   Instruction *foldICmpBinOpEqualityWithConstant(ICmpInst &Cmp,
978                                                  BinaryOperator *BO,
979                                                  const APInt &C);
980   Instruction *foldICmpIntrinsicWithConstant(ICmpInst &ICI, IntrinsicInst *II,
981                                              const APInt &C);
982   Instruction *foldICmpEqIntrinsicWithConstant(ICmpInst &ICI, IntrinsicInst *II,
983                                                const APInt &C);
984 
985   // Helpers of visitSelectInst().
986   Instruction *foldSelectExtConst(SelectInst &Sel);
987   Instruction *foldSelectOpOp(SelectInst &SI, Instruction *TI, Instruction *FI);
988   Instruction *foldSelectIntoOp(SelectInst &SI, Value *, Value *);
989   Instruction *foldSPFofSPF(Instruction *Inner, SelectPatternFlavor SPF1,
990                             Value *A, Value *B, Instruction &Outer,
991                             SelectPatternFlavor SPF2, Value *C);
992   Instruction *foldSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
993 
994   Instruction *OptAndOp(BinaryOperator *Op, ConstantInt *OpRHS,
995                         ConstantInt *AndRHS, BinaryOperator &TheAnd);
996 
997   Value *insertRangeTest(Value *V, const APInt &Lo, const APInt &Hi,
998                          bool isSigned, bool Inside);
999   Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocaInst &AI);
1000   bool mergeStoreIntoSuccessor(StoreInst &SI);
1001 
1002   /// Given an 'or' instruction, check to see if it is part of a bswap idiom.
1003   /// If so, return the equivalent bswap intrinsic.
1004   Instruction *matchBSwap(BinaryOperator &Or);
1005 
1006   Instruction *SimplifyAnyMemTransfer(AnyMemTransferInst *MI);
1007   Instruction *SimplifyAnyMemSet(AnyMemSetInst *MI);
1008 
1009   Value *EvaluateInDifferentType(Value *V, Type *Ty, bool isSigned);
1010 
1011   /// Returns a value X such that Val = X * Scale, or null if none.
1012   ///
1013   /// If the multiplication is known not to overflow then NoSignedWrap is set.
1014   Value *Descale(Value *Val, APInt Scale, bool &NoSignedWrap);
1015 };
1016 
1017 namespace {
1018 
1019 // As a default, let's assume that we want to be aggressive,
1020 // and attempt to traverse with no limits in attempt to sink negation.
1021 static constexpr unsigned NegatorDefaultMaxDepth = ~0U;
1022 
1023 // Let's guesstimate that most often we will end up visiting/producing
1024 // fairly small number of new instructions.
1025 static constexpr unsigned NegatorMaxNodesSSO = 16;
1026 
1027 } // namespace
1028 
1029 class Negator final {
1030   /// Top-to-bottom, def-to-use negated instruction tree we produced.
1031   SmallVector<Instruction *, NegatorMaxNodesSSO> NewInstructions;
1032 
1033   using BuilderTy = IRBuilder<TargetFolder, IRBuilderCallbackInserter>;
1034   BuilderTy Builder;
1035 
1036   const DataLayout &DL;
1037   AssumptionCache &AC;
1038   const DominatorTree &DT;
1039 
1040   const bool IsTrulyNegation;
1041 
1042   Negator(LLVMContext &C, const DataLayout &DL, AssumptionCache &AC,
1043           const DominatorTree &DT, bool IsTrulyNegation);
1044 
1045 #if LLVM_ENABLE_STATS
1046   unsigned NumValuesVisitedInThisNegator = 0;
1047   ~Negator();
1048 #endif
1049 
1050   using Result = std::pair<ArrayRef<Instruction *> /*NewInstructions*/,
1051                            Value * /*NegatedRoot*/>;
1052 
1053   LLVM_NODISCARD Value *visit(Value *V, unsigned Depth);
1054 
1055   /// Recurse depth-first and attempt to sink the negation.
1056   /// FIXME: use worklist?
1057   LLVM_NODISCARD Optional<Result> run(Value *Root);
1058 
1059   Negator(const Negator &) = delete;
1060   Negator(Negator &&) = delete;
1061   Negator &operator=(const Negator &) = delete;
1062   Negator &operator=(Negator &&) = delete;
1063 
1064 public:
1065   /// Attempt to negate \p Root. Retuns nullptr if negation can't be performed,
1066   /// otherwise returns negated value.
1067   LLVM_NODISCARD static Value *Negate(bool LHSIsZero, Value *Root,
1068                                       InstCombiner &IC);
1069 };
1070 
1071 } // end namespace llvm
1072 
1073 #undef DEBUG_TYPE
1074 
1075 #endif // LLVM_LIB_TRANSFORMS_INSTCOMBINE_INSTCOMBINEINTERNAL_H
1076