109467b48Spatrick //===- InstructionSimplify.cpp - Fold instruction operands ----------------===//
209467b48Spatrick //
309467b48Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
409467b48Spatrick // See https://llvm.org/LICENSE.txt for license information.
509467b48Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
609467b48Spatrick //
709467b48Spatrick //===----------------------------------------------------------------------===//
809467b48Spatrick //
909467b48Spatrick // This file implements routines for folding instructions into simpler forms
1009467b48Spatrick // that do not require creating new instructions.  This does constant folding
1109467b48Spatrick // ("add i32 1, 1" -> "2") but can also handle non-constant operands, either
1209467b48Spatrick // returning a constant ("and i32 %x, 0" -> "0") or an already existing value
1309467b48Spatrick // ("and i32 %x, %x" -> "%x").  All operands are assumed to have already been
1409467b48Spatrick // simplified: This is usually true and assuming it simplifies the logic (if
1509467b48Spatrick // they have not been simplified then results are correct but maybe suboptimal).
1609467b48Spatrick //
1709467b48Spatrick //===----------------------------------------------------------------------===//
1809467b48Spatrick 
1909467b48Spatrick #include "llvm/Analysis/InstructionSimplify.h"
2073471bf0Spatrick 
2173471bf0Spatrick #include "llvm/ADT/STLExtras.h"
2209467b48Spatrick #include "llvm/ADT/SetVector.h"
2309467b48Spatrick #include "llvm/ADT/Statistic.h"
2409467b48Spatrick #include "llvm/Analysis/AliasAnalysis.h"
2509467b48Spatrick #include "llvm/Analysis/AssumptionCache.h"
2609467b48Spatrick #include "llvm/Analysis/CaptureTracking.h"
2709467b48Spatrick #include "llvm/Analysis/CmpInstAnalysis.h"
2809467b48Spatrick #include "llvm/Analysis/ConstantFolding.h"
29*d415bd75Srobert #include "llvm/Analysis/InstSimplifyFolder.h"
3009467b48Spatrick #include "llvm/Analysis/LoopAnalysisManager.h"
3109467b48Spatrick #include "llvm/Analysis/MemoryBuiltins.h"
3273471bf0Spatrick #include "llvm/Analysis/OverflowInstAnalysis.h"
3309467b48Spatrick #include "llvm/Analysis/ValueTracking.h"
3409467b48Spatrick #include "llvm/Analysis/VectorUtils.h"
3509467b48Spatrick #include "llvm/IR/ConstantRange.h"
3609467b48Spatrick #include "llvm/IR/DataLayout.h"
3709467b48Spatrick #include "llvm/IR/Dominators.h"
3809467b48Spatrick #include "llvm/IR/InstrTypes.h"
3909467b48Spatrick #include "llvm/IR/Instructions.h"
4009467b48Spatrick #include "llvm/IR/Operator.h"
4109467b48Spatrick #include "llvm/IR/PatternMatch.h"
4209467b48Spatrick #include "llvm/Support/KnownBits.h"
4309467b48Spatrick #include <algorithm>
44*d415bd75Srobert #include <optional>
4509467b48Spatrick using namespace llvm;
4609467b48Spatrick using namespace llvm::PatternMatch;
4709467b48Spatrick 
4809467b48Spatrick #define DEBUG_TYPE "instsimplify"
4909467b48Spatrick 
5009467b48Spatrick enum { RecursionLimit = 3 };
5109467b48Spatrick 
5209467b48Spatrick STATISTIC(NumExpand, "Number of expansions");
5309467b48Spatrick STATISTIC(NumReassoc, "Number of reassociations");
5409467b48Spatrick 
55*d415bd75Srobert static Value *simplifyAndInst(Value *, Value *, const SimplifyQuery &,
56*d415bd75Srobert                               unsigned);
5709467b48Spatrick static Value *simplifyUnOp(unsigned, Value *, const SimplifyQuery &, unsigned);
5809467b48Spatrick static Value *simplifyFPUnOp(unsigned, Value *, const FastMathFlags &,
5909467b48Spatrick                              const SimplifyQuery &, unsigned);
60*d415bd75Srobert static Value *simplifyBinOp(unsigned, Value *, Value *, const SimplifyQuery &,
6109467b48Spatrick                             unsigned);
62*d415bd75Srobert static Value *simplifyBinOp(unsigned, Value *, Value *, const FastMathFlags &,
6309467b48Spatrick                             const SimplifyQuery &, unsigned);
64*d415bd75Srobert static Value *simplifyCmpInst(unsigned, Value *, Value *, const SimplifyQuery &,
6509467b48Spatrick                               unsigned);
66*d415bd75Srobert static Value *simplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
6709467b48Spatrick                                const SimplifyQuery &Q, unsigned MaxRecurse);
68*d415bd75Srobert static Value *simplifyOrInst(Value *, Value *, const SimplifyQuery &, unsigned);
69*d415bd75Srobert static Value *simplifyXorInst(Value *, Value *, const SimplifyQuery &,
7009467b48Spatrick                               unsigned);
71*d415bd75Srobert static Value *simplifyCastInst(unsigned, Value *, Type *, const SimplifyQuery &,
72*d415bd75Srobert                                unsigned);
73*d415bd75Srobert static Value *simplifyGEPInst(Type *, Value *, ArrayRef<Value *>, bool,
74*d415bd75Srobert                               const SimplifyQuery &, unsigned);
75*d415bd75Srobert static Value *simplifySelectInst(Value *, Value *, Value *,
7673471bf0Spatrick                                  const SimplifyQuery &, unsigned);
7709467b48Spatrick 
foldSelectWithBinaryOp(Value * Cond,Value * TrueVal,Value * FalseVal)7809467b48Spatrick static Value *foldSelectWithBinaryOp(Value *Cond, Value *TrueVal,
7909467b48Spatrick                                      Value *FalseVal) {
8009467b48Spatrick   BinaryOperator::BinaryOps BinOpCode;
8109467b48Spatrick   if (auto *BO = dyn_cast<BinaryOperator>(Cond))
8209467b48Spatrick     BinOpCode = BO->getOpcode();
8309467b48Spatrick   else
8409467b48Spatrick     return nullptr;
8509467b48Spatrick 
8609467b48Spatrick   CmpInst::Predicate ExpectedPred, Pred1, Pred2;
8709467b48Spatrick   if (BinOpCode == BinaryOperator::Or) {
8809467b48Spatrick     ExpectedPred = ICmpInst::ICMP_NE;
8909467b48Spatrick   } else if (BinOpCode == BinaryOperator::And) {
9009467b48Spatrick     ExpectedPred = ICmpInst::ICMP_EQ;
9109467b48Spatrick   } else
9209467b48Spatrick     return nullptr;
9309467b48Spatrick 
9409467b48Spatrick   // %A = icmp eq %TV, %FV
9509467b48Spatrick   // %B = icmp eq %X, %Y (and one of these is a select operand)
9609467b48Spatrick   // %C = and %A, %B
9709467b48Spatrick   // %D = select %C, %TV, %FV
9809467b48Spatrick   // -->
9909467b48Spatrick   // %FV
10009467b48Spatrick 
10109467b48Spatrick   // %A = icmp ne %TV, %FV
10209467b48Spatrick   // %B = icmp ne %X, %Y (and one of these is a select operand)
10309467b48Spatrick   // %C = or %A, %B
10409467b48Spatrick   // %D = select %C, %TV, %FV
10509467b48Spatrick   // -->
10609467b48Spatrick   // %TV
10709467b48Spatrick   Value *X, *Y;
10809467b48Spatrick   if (!match(Cond, m_c_BinOp(m_c_ICmp(Pred1, m_Specific(TrueVal),
10909467b48Spatrick                                       m_Specific(FalseVal)),
11009467b48Spatrick                              m_ICmp(Pred2, m_Value(X), m_Value(Y)))) ||
11109467b48Spatrick       Pred1 != Pred2 || Pred1 != ExpectedPred)
11209467b48Spatrick     return nullptr;
11309467b48Spatrick 
11409467b48Spatrick   if (X == TrueVal || X == FalseVal || Y == TrueVal || Y == FalseVal)
11509467b48Spatrick     return BinOpCode == BinaryOperator::Or ? TrueVal : FalseVal;
11609467b48Spatrick 
11709467b48Spatrick   return nullptr;
11809467b48Spatrick }
11909467b48Spatrick 
12009467b48Spatrick /// For a boolean type or a vector of boolean type, return false or a vector
12109467b48Spatrick /// with every element false.
getFalse(Type * Ty)122*d415bd75Srobert static Constant *getFalse(Type *Ty) { return ConstantInt::getFalse(Ty); }
12309467b48Spatrick 
12409467b48Spatrick /// For a boolean type or a vector of boolean type, return true or a vector
12509467b48Spatrick /// with every element true.
getTrue(Type * Ty)126*d415bd75Srobert static Constant *getTrue(Type *Ty) { return ConstantInt::getTrue(Ty); }
12709467b48Spatrick 
12809467b48Spatrick /// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
isSameCompare(Value * V,CmpInst::Predicate Pred,Value * LHS,Value * RHS)12909467b48Spatrick static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
13009467b48Spatrick                           Value *RHS) {
13109467b48Spatrick   CmpInst *Cmp = dyn_cast<CmpInst>(V);
13209467b48Spatrick   if (!Cmp)
13309467b48Spatrick     return false;
13409467b48Spatrick   CmpInst::Predicate CPred = Cmp->getPredicate();
13509467b48Spatrick   Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
13609467b48Spatrick   if (CPred == Pred && CLHS == LHS && CRHS == RHS)
13709467b48Spatrick     return true;
13809467b48Spatrick   return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
13909467b48Spatrick          CRHS == LHS;
14009467b48Spatrick }
14109467b48Spatrick 
14209467b48Spatrick /// Simplify comparison with true or false branch of select:
14309467b48Spatrick ///  %sel = select i1 %cond, i32 %tv, i32 %fv
14409467b48Spatrick ///  %cmp = icmp sle i32 %sel, %rhs
14509467b48Spatrick /// Compose new comparison by substituting %sel with either %tv or %fv
14609467b48Spatrick /// and see if it simplifies.
simplifyCmpSelCase(CmpInst::Predicate Pred,Value * LHS,Value * RHS,Value * Cond,const SimplifyQuery & Q,unsigned MaxRecurse,Constant * TrueOrFalse)14709467b48Spatrick static Value *simplifyCmpSelCase(CmpInst::Predicate Pred, Value *LHS,
14809467b48Spatrick                                  Value *RHS, Value *Cond,
14909467b48Spatrick                                  const SimplifyQuery &Q, unsigned MaxRecurse,
15009467b48Spatrick                                  Constant *TrueOrFalse) {
151*d415bd75Srobert   Value *SimplifiedCmp = simplifyCmpInst(Pred, LHS, RHS, Q, MaxRecurse);
15209467b48Spatrick   if (SimplifiedCmp == Cond) {
15309467b48Spatrick     // %cmp simplified to the select condition (%cond).
15409467b48Spatrick     return TrueOrFalse;
15509467b48Spatrick   } else if (!SimplifiedCmp && isSameCompare(Cond, Pred, LHS, RHS)) {
15609467b48Spatrick     // It didn't simplify. However, if composed comparison is equivalent
15709467b48Spatrick     // to the select condition (%cond) then we can replace it.
15809467b48Spatrick     return TrueOrFalse;
15909467b48Spatrick   }
16009467b48Spatrick   return SimplifiedCmp;
16109467b48Spatrick }
16209467b48Spatrick 
16309467b48Spatrick /// Simplify comparison with true branch of select
simplifyCmpSelTrueCase(CmpInst::Predicate Pred,Value * LHS,Value * RHS,Value * Cond,const SimplifyQuery & Q,unsigned MaxRecurse)16409467b48Spatrick static Value *simplifyCmpSelTrueCase(CmpInst::Predicate Pred, Value *LHS,
16509467b48Spatrick                                      Value *RHS, Value *Cond,
16609467b48Spatrick                                      const SimplifyQuery &Q,
16709467b48Spatrick                                      unsigned MaxRecurse) {
16809467b48Spatrick   return simplifyCmpSelCase(Pred, LHS, RHS, Cond, Q, MaxRecurse,
16909467b48Spatrick                             getTrue(Cond->getType()));
17009467b48Spatrick }
17109467b48Spatrick 
17209467b48Spatrick /// Simplify comparison with false branch of select
simplifyCmpSelFalseCase(CmpInst::Predicate Pred,Value * LHS,Value * RHS,Value * Cond,const SimplifyQuery & Q,unsigned MaxRecurse)17309467b48Spatrick static Value *simplifyCmpSelFalseCase(CmpInst::Predicate Pred, Value *LHS,
17409467b48Spatrick                                       Value *RHS, Value *Cond,
17509467b48Spatrick                                       const SimplifyQuery &Q,
17609467b48Spatrick                                       unsigned MaxRecurse) {
17709467b48Spatrick   return simplifyCmpSelCase(Pred, LHS, RHS, Cond, Q, MaxRecurse,
17809467b48Spatrick                             getFalse(Cond->getType()));
17909467b48Spatrick }
18009467b48Spatrick 
18109467b48Spatrick /// We know comparison with both branches of select can be simplified, but they
18209467b48Spatrick /// are not equal. This routine handles some logical simplifications.
handleOtherCmpSelSimplifications(Value * TCmp,Value * FCmp,Value * Cond,const SimplifyQuery & Q,unsigned MaxRecurse)18309467b48Spatrick static Value *handleOtherCmpSelSimplifications(Value *TCmp, Value *FCmp,
18409467b48Spatrick                                                Value *Cond,
18509467b48Spatrick                                                const SimplifyQuery &Q,
18609467b48Spatrick                                                unsigned MaxRecurse) {
18709467b48Spatrick   // If the false value simplified to false, then the result of the compare
18809467b48Spatrick   // is equal to "Cond && TCmp".  This also catches the case when the false
18909467b48Spatrick   // value simplified to false and the true value to true, returning "Cond".
19073471bf0Spatrick   // Folding select to and/or isn't poison-safe in general; impliesPoison
19173471bf0Spatrick   // checks whether folding it does not convert a well-defined value into
19273471bf0Spatrick   // poison.
19373471bf0Spatrick   if (match(FCmp, m_Zero()) && impliesPoison(TCmp, Cond))
194*d415bd75Srobert     if (Value *V = simplifyAndInst(Cond, TCmp, Q, MaxRecurse))
19509467b48Spatrick       return V;
19609467b48Spatrick   // If the true value simplified to true, then the result of the compare
19709467b48Spatrick   // is equal to "Cond || FCmp".
19873471bf0Spatrick   if (match(TCmp, m_One()) && impliesPoison(FCmp, Cond))
199*d415bd75Srobert     if (Value *V = simplifyOrInst(Cond, FCmp, Q, MaxRecurse))
20009467b48Spatrick       return V;
20109467b48Spatrick   // Finally, if the false value simplified to true and the true value to
20209467b48Spatrick   // false, then the result of the compare is equal to "!Cond".
20309467b48Spatrick   if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
204*d415bd75Srobert     if (Value *V = simplifyXorInst(
20509467b48Spatrick             Cond, Constant::getAllOnesValue(Cond->getType()), Q, MaxRecurse))
20609467b48Spatrick       return V;
20709467b48Spatrick   return nullptr;
20809467b48Spatrick }
20909467b48Spatrick 
21009467b48Spatrick /// Does the given value dominate the specified phi node?
valueDominatesPHI(Value * V,PHINode * P,const DominatorTree * DT)21109467b48Spatrick static bool valueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
21209467b48Spatrick   Instruction *I = dyn_cast<Instruction>(V);
21309467b48Spatrick   if (!I)
21409467b48Spatrick     // Arguments and constants dominate all instructions.
21509467b48Spatrick     return true;
21609467b48Spatrick 
21709467b48Spatrick   // If we are processing instructions (and/or basic blocks) that have not been
21809467b48Spatrick   // fully added to a function, the parent nodes may still be null. Simply
21909467b48Spatrick   // return the conservative answer in these cases.
22009467b48Spatrick   if (!I->getParent() || !P->getParent() || !I->getFunction())
22109467b48Spatrick     return false;
22209467b48Spatrick 
22309467b48Spatrick   // If we have a DominatorTree then do a precise test.
22409467b48Spatrick   if (DT)
22509467b48Spatrick     return DT->dominates(I, P);
22609467b48Spatrick 
22709467b48Spatrick   // Otherwise, if the instruction is in the entry block and is not an invoke,
22809467b48Spatrick   // then it obviously dominates all phi nodes.
22973471bf0Spatrick   if (I->getParent()->isEntryBlock() && !isa<InvokeInst>(I) &&
23073471bf0Spatrick       !isa<CallBrInst>(I))
23109467b48Spatrick     return true;
23209467b48Spatrick 
23309467b48Spatrick   return false;
23409467b48Spatrick }
23509467b48Spatrick 
23673471bf0Spatrick /// Try to simplify a binary operator of form "V op OtherOp" where V is
23773471bf0Spatrick /// "(B0 opex B1)" by distributing 'op' across 'opex' as
23873471bf0Spatrick /// "(B0 op OtherOp) opex (B1 op OtherOp)".
expandBinOp(Instruction::BinaryOps Opcode,Value * V,Value * OtherOp,Instruction::BinaryOps OpcodeToExpand,const SimplifyQuery & Q,unsigned MaxRecurse)23973471bf0Spatrick static Value *expandBinOp(Instruction::BinaryOps Opcode, Value *V,
24073471bf0Spatrick                           Value *OtherOp, Instruction::BinaryOps OpcodeToExpand,
24109467b48Spatrick                           const SimplifyQuery &Q, unsigned MaxRecurse) {
24273471bf0Spatrick   auto *B = dyn_cast<BinaryOperator>(V);
24373471bf0Spatrick   if (!B || B->getOpcode() != OpcodeToExpand)
24473471bf0Spatrick     return nullptr;
24573471bf0Spatrick   Value *B0 = B->getOperand(0), *B1 = B->getOperand(1);
246*d415bd75Srobert   Value *L =
247*d415bd75Srobert       simplifyBinOp(Opcode, B0, OtherOp, Q.getWithoutUndef(), MaxRecurse);
24873471bf0Spatrick   if (!L)
24973471bf0Spatrick     return nullptr;
250*d415bd75Srobert   Value *R =
251*d415bd75Srobert       simplifyBinOp(Opcode, B1, OtherOp, Q.getWithoutUndef(), MaxRecurse);
25273471bf0Spatrick   if (!R)
25373471bf0Spatrick     return nullptr;
25473471bf0Spatrick 
25573471bf0Spatrick   // Does the expanded pair of binops simplify to the existing binop?
25673471bf0Spatrick   if ((L == B0 && R == B1) ||
25773471bf0Spatrick       (Instruction::isCommutative(OpcodeToExpand) && L == B1 && R == B0)) {
25873471bf0Spatrick     ++NumExpand;
25973471bf0Spatrick     return B;
26073471bf0Spatrick   }
26173471bf0Spatrick 
26273471bf0Spatrick   // Otherwise, return "L op' R" if it simplifies.
263*d415bd75Srobert   Value *S = simplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse);
26473471bf0Spatrick   if (!S)
26573471bf0Spatrick     return nullptr;
26673471bf0Spatrick 
26773471bf0Spatrick   ++NumExpand;
26873471bf0Spatrick   return S;
26973471bf0Spatrick }
27073471bf0Spatrick 
27173471bf0Spatrick /// Try to simplify binops of form "A op (B op' C)" or the commuted variant by
27273471bf0Spatrick /// distributing op over op'.
expandCommutativeBinOp(Instruction::BinaryOps Opcode,Value * L,Value * R,Instruction::BinaryOps OpcodeToExpand,const SimplifyQuery & Q,unsigned MaxRecurse)273*d415bd75Srobert static Value *expandCommutativeBinOp(Instruction::BinaryOps Opcode, Value *L,
274*d415bd75Srobert                                      Value *R,
27573471bf0Spatrick                                      Instruction::BinaryOps OpcodeToExpand,
27673471bf0Spatrick                                      const SimplifyQuery &Q,
27773471bf0Spatrick                                      unsigned MaxRecurse) {
27809467b48Spatrick   // Recursion is always used, so bail out at once if we already hit the limit.
27909467b48Spatrick   if (!MaxRecurse--)
28009467b48Spatrick     return nullptr;
28109467b48Spatrick 
28273471bf0Spatrick   if (Value *V = expandBinOp(Opcode, L, R, OpcodeToExpand, Q, MaxRecurse))
28309467b48Spatrick     return V;
28473471bf0Spatrick   if (Value *V = expandBinOp(Opcode, R, L, OpcodeToExpand, Q, MaxRecurse))
28509467b48Spatrick     return V;
28609467b48Spatrick   return nullptr;
28709467b48Spatrick }
28809467b48Spatrick 
28909467b48Spatrick /// Generic simplifications for associative binary operations.
29009467b48Spatrick /// Returns the simpler value, or null if none was found.
simplifyAssociativeBinOp(Instruction::BinaryOps Opcode,Value * LHS,Value * RHS,const SimplifyQuery & Q,unsigned MaxRecurse)291*d415bd75Srobert static Value *simplifyAssociativeBinOp(Instruction::BinaryOps Opcode,
29209467b48Spatrick                                        Value *LHS, Value *RHS,
29309467b48Spatrick                                        const SimplifyQuery &Q,
29409467b48Spatrick                                        unsigned MaxRecurse) {
29509467b48Spatrick   assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
29609467b48Spatrick 
29709467b48Spatrick   // Recursion is always used, so bail out at once if we already hit the limit.
29809467b48Spatrick   if (!MaxRecurse--)
29909467b48Spatrick     return nullptr;
30009467b48Spatrick 
30109467b48Spatrick   BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
30209467b48Spatrick   BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
30309467b48Spatrick 
30409467b48Spatrick   // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
30509467b48Spatrick   if (Op0 && Op0->getOpcode() == Opcode) {
30609467b48Spatrick     Value *A = Op0->getOperand(0);
30709467b48Spatrick     Value *B = Op0->getOperand(1);
30809467b48Spatrick     Value *C = RHS;
30909467b48Spatrick 
31009467b48Spatrick     // Does "B op C" simplify?
311*d415bd75Srobert     if (Value *V = simplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
31209467b48Spatrick       // It does!  Return "A op V" if it simplifies or is already available.
31309467b48Spatrick       // If V equals B then "A op V" is just the LHS.
314*d415bd75Srobert       if (V == B)
315*d415bd75Srobert         return LHS;
31609467b48Spatrick       // Otherwise return "A op V" if it simplifies.
317*d415bd75Srobert       if (Value *W = simplifyBinOp(Opcode, A, V, Q, MaxRecurse)) {
31809467b48Spatrick         ++NumReassoc;
31909467b48Spatrick         return W;
32009467b48Spatrick       }
32109467b48Spatrick     }
32209467b48Spatrick   }
32309467b48Spatrick 
32409467b48Spatrick   // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
32509467b48Spatrick   if (Op1 && Op1->getOpcode() == Opcode) {
32609467b48Spatrick     Value *A = LHS;
32709467b48Spatrick     Value *B = Op1->getOperand(0);
32809467b48Spatrick     Value *C = Op1->getOperand(1);
32909467b48Spatrick 
33009467b48Spatrick     // Does "A op B" simplify?
331*d415bd75Srobert     if (Value *V = simplifyBinOp(Opcode, A, B, Q, MaxRecurse)) {
33209467b48Spatrick       // It does!  Return "V op C" if it simplifies or is already available.
33309467b48Spatrick       // If V equals B then "V op C" is just the RHS.
334*d415bd75Srobert       if (V == B)
335*d415bd75Srobert         return RHS;
33609467b48Spatrick       // Otherwise return "V op C" if it simplifies.
337*d415bd75Srobert       if (Value *W = simplifyBinOp(Opcode, V, C, Q, MaxRecurse)) {
33809467b48Spatrick         ++NumReassoc;
33909467b48Spatrick         return W;
34009467b48Spatrick       }
34109467b48Spatrick     }
34209467b48Spatrick   }
34309467b48Spatrick 
34409467b48Spatrick   // The remaining transforms require commutativity as well as associativity.
34509467b48Spatrick   if (!Instruction::isCommutative(Opcode))
34609467b48Spatrick     return nullptr;
34709467b48Spatrick 
34809467b48Spatrick   // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
34909467b48Spatrick   if (Op0 && Op0->getOpcode() == Opcode) {
35009467b48Spatrick     Value *A = Op0->getOperand(0);
35109467b48Spatrick     Value *B = Op0->getOperand(1);
35209467b48Spatrick     Value *C = RHS;
35309467b48Spatrick 
35409467b48Spatrick     // Does "C op A" simplify?
355*d415bd75Srobert     if (Value *V = simplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
35609467b48Spatrick       // It does!  Return "V op B" if it simplifies or is already available.
35709467b48Spatrick       // If V equals A then "V op B" is just the LHS.
358*d415bd75Srobert       if (V == A)
359*d415bd75Srobert         return LHS;
36009467b48Spatrick       // Otherwise return "V op B" if it simplifies.
361*d415bd75Srobert       if (Value *W = simplifyBinOp(Opcode, V, B, Q, MaxRecurse)) {
36209467b48Spatrick         ++NumReassoc;
36309467b48Spatrick         return W;
36409467b48Spatrick       }
36509467b48Spatrick     }
36609467b48Spatrick   }
36709467b48Spatrick 
36809467b48Spatrick   // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
36909467b48Spatrick   if (Op1 && Op1->getOpcode() == Opcode) {
37009467b48Spatrick     Value *A = LHS;
37109467b48Spatrick     Value *B = Op1->getOperand(0);
37209467b48Spatrick     Value *C = Op1->getOperand(1);
37309467b48Spatrick 
37409467b48Spatrick     // Does "C op A" simplify?
375*d415bd75Srobert     if (Value *V = simplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
37609467b48Spatrick       // It does!  Return "B op V" if it simplifies or is already available.
37709467b48Spatrick       // If V equals C then "B op V" is just the RHS.
378*d415bd75Srobert       if (V == C)
379*d415bd75Srobert         return RHS;
38009467b48Spatrick       // Otherwise return "B op V" if it simplifies.
381*d415bd75Srobert       if (Value *W = simplifyBinOp(Opcode, B, V, Q, MaxRecurse)) {
38209467b48Spatrick         ++NumReassoc;
38309467b48Spatrick         return W;
38409467b48Spatrick       }
38509467b48Spatrick     }
38609467b48Spatrick   }
38709467b48Spatrick 
38809467b48Spatrick   return nullptr;
38909467b48Spatrick }
39009467b48Spatrick 
39109467b48Spatrick /// In the case of a binary operation with a select instruction as an operand,
39209467b48Spatrick /// try to simplify the binop by seeing whether evaluating it on both branches
39309467b48Spatrick /// of the select results in the same value. Returns the common value if so,
39409467b48Spatrick /// otherwise returns null.
threadBinOpOverSelect(Instruction::BinaryOps Opcode,Value * LHS,Value * RHS,const SimplifyQuery & Q,unsigned MaxRecurse)395*d415bd75Srobert static Value *threadBinOpOverSelect(Instruction::BinaryOps Opcode, Value *LHS,
39609467b48Spatrick                                     Value *RHS, const SimplifyQuery &Q,
39709467b48Spatrick                                     unsigned MaxRecurse) {
39809467b48Spatrick   // Recursion is always used, so bail out at once if we already hit the limit.
39909467b48Spatrick   if (!MaxRecurse--)
40009467b48Spatrick     return nullptr;
40109467b48Spatrick 
40209467b48Spatrick   SelectInst *SI;
40309467b48Spatrick   if (isa<SelectInst>(LHS)) {
40409467b48Spatrick     SI = cast<SelectInst>(LHS);
40509467b48Spatrick   } else {
40609467b48Spatrick     assert(isa<SelectInst>(RHS) && "No select instruction operand!");
40709467b48Spatrick     SI = cast<SelectInst>(RHS);
40809467b48Spatrick   }
40909467b48Spatrick 
41009467b48Spatrick   // Evaluate the BinOp on the true and false branches of the select.
41109467b48Spatrick   Value *TV;
41209467b48Spatrick   Value *FV;
41309467b48Spatrick   if (SI == LHS) {
414*d415bd75Srobert     TV = simplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse);
415*d415bd75Srobert     FV = simplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse);
41609467b48Spatrick   } else {
417*d415bd75Srobert     TV = simplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse);
418*d415bd75Srobert     FV = simplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse);
41909467b48Spatrick   }
42009467b48Spatrick 
42109467b48Spatrick   // If they simplified to the same value, then return the common value.
42209467b48Spatrick   // If they both failed to simplify then return null.
42309467b48Spatrick   if (TV == FV)
42409467b48Spatrick     return TV;
42509467b48Spatrick 
42609467b48Spatrick   // If one branch simplified to undef, return the other one.
42773471bf0Spatrick   if (TV && Q.isUndefValue(TV))
42809467b48Spatrick     return FV;
42973471bf0Spatrick   if (FV && Q.isUndefValue(FV))
43009467b48Spatrick     return TV;
43109467b48Spatrick 
43209467b48Spatrick   // If applying the operation did not change the true and false select values,
43309467b48Spatrick   // then the result of the binop is the select itself.
43409467b48Spatrick   if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
43509467b48Spatrick     return SI;
43609467b48Spatrick 
43709467b48Spatrick   // If one branch simplified and the other did not, and the simplified
43809467b48Spatrick   // value is equal to the unsimplified one, return the simplified value.
43909467b48Spatrick   // For example, select (cond, X, X & Z) & Z -> X & Z.
44009467b48Spatrick   if ((FV && !TV) || (TV && !FV)) {
44109467b48Spatrick     // Check that the simplified value has the form "X op Y" where "op" is the
44209467b48Spatrick     // same as the original operation.
44309467b48Spatrick     Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
44409467b48Spatrick     if (Simplified && Simplified->getOpcode() == unsigned(Opcode)) {
44509467b48Spatrick       // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
44609467b48Spatrick       // We already know that "op" is the same as for the simplified value.  See
44709467b48Spatrick       // if the operands match too.  If so, return the simplified value.
44809467b48Spatrick       Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
44909467b48Spatrick       Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
45009467b48Spatrick       Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
45109467b48Spatrick       if (Simplified->getOperand(0) == UnsimplifiedLHS &&
45209467b48Spatrick           Simplified->getOperand(1) == UnsimplifiedRHS)
45309467b48Spatrick         return Simplified;
45409467b48Spatrick       if (Simplified->isCommutative() &&
45509467b48Spatrick           Simplified->getOperand(1) == UnsimplifiedLHS &&
45609467b48Spatrick           Simplified->getOperand(0) == UnsimplifiedRHS)
45709467b48Spatrick         return Simplified;
45809467b48Spatrick     }
45909467b48Spatrick   }
46009467b48Spatrick 
46109467b48Spatrick   return nullptr;
46209467b48Spatrick }
46309467b48Spatrick 
46409467b48Spatrick /// In the case of a comparison with a select instruction, try to simplify the
46509467b48Spatrick /// comparison by seeing whether both branches of the select result in the same
46609467b48Spatrick /// value. Returns the common value if so, otherwise returns null.
46709467b48Spatrick /// For example, if we have:
46809467b48Spatrick ///  %tmp = select i1 %cmp, i32 1, i32 2
46909467b48Spatrick ///  %cmp1 = icmp sle i32 %tmp, 3
47009467b48Spatrick /// We can simplify %cmp1 to true, because both branches of select are
47109467b48Spatrick /// less than 3. We compose new comparison by substituting %tmp with both
47209467b48Spatrick /// branches of select and see if it can be simplified.
threadCmpOverSelect(CmpInst::Predicate Pred,Value * LHS,Value * RHS,const SimplifyQuery & Q,unsigned MaxRecurse)473*d415bd75Srobert static Value *threadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
47409467b48Spatrick                                   Value *RHS, const SimplifyQuery &Q,
47509467b48Spatrick                                   unsigned MaxRecurse) {
47609467b48Spatrick   // Recursion is always used, so bail out at once if we already hit the limit.
47709467b48Spatrick   if (!MaxRecurse--)
47809467b48Spatrick     return nullptr;
47909467b48Spatrick 
48009467b48Spatrick   // Make sure the select is on the LHS.
48109467b48Spatrick   if (!isa<SelectInst>(LHS)) {
48209467b48Spatrick     std::swap(LHS, RHS);
48309467b48Spatrick     Pred = CmpInst::getSwappedPredicate(Pred);
48409467b48Spatrick   }
48509467b48Spatrick   assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
48609467b48Spatrick   SelectInst *SI = cast<SelectInst>(LHS);
48709467b48Spatrick   Value *Cond = SI->getCondition();
48809467b48Spatrick   Value *TV = SI->getTrueValue();
48909467b48Spatrick   Value *FV = SI->getFalseValue();
49009467b48Spatrick 
49109467b48Spatrick   // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
49209467b48Spatrick   // Does "cmp TV, RHS" simplify?
49309467b48Spatrick   Value *TCmp = simplifyCmpSelTrueCase(Pred, TV, RHS, Cond, Q, MaxRecurse);
49409467b48Spatrick   if (!TCmp)
49509467b48Spatrick     return nullptr;
49609467b48Spatrick 
49709467b48Spatrick   // Does "cmp FV, RHS" simplify?
49809467b48Spatrick   Value *FCmp = simplifyCmpSelFalseCase(Pred, FV, RHS, Cond, Q, MaxRecurse);
49909467b48Spatrick   if (!FCmp)
50009467b48Spatrick     return nullptr;
50109467b48Spatrick 
50209467b48Spatrick   // If both sides simplified to the same value, then use it as the result of
50309467b48Spatrick   // the original comparison.
50409467b48Spatrick   if (TCmp == FCmp)
50509467b48Spatrick     return TCmp;
50609467b48Spatrick 
50709467b48Spatrick   // The remaining cases only make sense if the select condition has the same
50809467b48Spatrick   // type as the result of the comparison, so bail out if this is not so.
50909467b48Spatrick   if (Cond->getType()->isVectorTy() == RHS->getType()->isVectorTy())
51009467b48Spatrick     return handleOtherCmpSelSimplifications(TCmp, FCmp, Cond, Q, MaxRecurse);
51109467b48Spatrick 
51209467b48Spatrick   return nullptr;
51309467b48Spatrick }
51409467b48Spatrick 
51509467b48Spatrick /// In the case of a binary operation with an operand that is a PHI instruction,
51609467b48Spatrick /// try to simplify the binop by seeing whether evaluating it on the incoming
51709467b48Spatrick /// phi values yields the same result for every value. If so returns the common
51809467b48Spatrick /// value, otherwise returns null.
threadBinOpOverPHI(Instruction::BinaryOps Opcode,Value * LHS,Value * RHS,const SimplifyQuery & Q,unsigned MaxRecurse)519*d415bd75Srobert static Value *threadBinOpOverPHI(Instruction::BinaryOps Opcode, Value *LHS,
52009467b48Spatrick                                  Value *RHS, const SimplifyQuery &Q,
52109467b48Spatrick                                  unsigned MaxRecurse) {
52209467b48Spatrick   // Recursion is always used, so bail out at once if we already hit the limit.
52309467b48Spatrick   if (!MaxRecurse--)
52409467b48Spatrick     return nullptr;
52509467b48Spatrick 
52609467b48Spatrick   PHINode *PI;
52709467b48Spatrick   if (isa<PHINode>(LHS)) {
52809467b48Spatrick     PI = cast<PHINode>(LHS);
52909467b48Spatrick     // Bail out if RHS and the phi may be mutually interdependent due to a loop.
53009467b48Spatrick     if (!valueDominatesPHI(RHS, PI, Q.DT))
53109467b48Spatrick       return nullptr;
53209467b48Spatrick   } else {
53309467b48Spatrick     assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
53409467b48Spatrick     PI = cast<PHINode>(RHS);
53509467b48Spatrick     // Bail out if LHS and the phi may be mutually interdependent due to a loop.
53609467b48Spatrick     if (!valueDominatesPHI(LHS, PI, Q.DT))
53709467b48Spatrick       return nullptr;
53809467b48Spatrick   }
53909467b48Spatrick 
54009467b48Spatrick   // Evaluate the BinOp on the incoming phi values.
54109467b48Spatrick   Value *CommonValue = nullptr;
54209467b48Spatrick   for (Value *Incoming : PI->incoming_values()) {
54309467b48Spatrick     // If the incoming value is the phi node itself, it can safely be skipped.
544*d415bd75Srobert     if (Incoming == PI)
545*d415bd75Srobert       continue;
546*d415bd75Srobert     Value *V = PI == LHS ? simplifyBinOp(Opcode, Incoming, RHS, Q, MaxRecurse)
547*d415bd75Srobert                          : simplifyBinOp(Opcode, LHS, Incoming, Q, MaxRecurse);
54809467b48Spatrick     // If the operation failed to simplify, or simplified to a different value
54909467b48Spatrick     // to previously, then give up.
55009467b48Spatrick     if (!V || (CommonValue && V != CommonValue))
55109467b48Spatrick       return nullptr;
55209467b48Spatrick     CommonValue = V;
55309467b48Spatrick   }
55409467b48Spatrick 
55509467b48Spatrick   return CommonValue;
55609467b48Spatrick }
55709467b48Spatrick 
55809467b48Spatrick /// In the case of a comparison with a PHI instruction, try to simplify the
55909467b48Spatrick /// comparison by seeing whether comparing with all of the incoming phi values
56009467b48Spatrick /// yields the same result every time. If so returns the common result,
56109467b48Spatrick /// otherwise returns null.
threadCmpOverPHI(CmpInst::Predicate Pred,Value * LHS,Value * RHS,const SimplifyQuery & Q,unsigned MaxRecurse)562*d415bd75Srobert static Value *threadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
56309467b48Spatrick                                const SimplifyQuery &Q, unsigned MaxRecurse) {
56409467b48Spatrick   // Recursion is always used, so bail out at once if we already hit the limit.
56509467b48Spatrick   if (!MaxRecurse--)
56609467b48Spatrick     return nullptr;
56709467b48Spatrick 
56809467b48Spatrick   // Make sure the phi is on the LHS.
56909467b48Spatrick   if (!isa<PHINode>(LHS)) {
57009467b48Spatrick     std::swap(LHS, RHS);
57109467b48Spatrick     Pred = CmpInst::getSwappedPredicate(Pred);
57209467b48Spatrick   }
57309467b48Spatrick   assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
57409467b48Spatrick   PHINode *PI = cast<PHINode>(LHS);
57509467b48Spatrick 
57609467b48Spatrick   // Bail out if RHS and the phi may be mutually interdependent due to a loop.
57709467b48Spatrick   if (!valueDominatesPHI(RHS, PI, Q.DT))
57809467b48Spatrick     return nullptr;
57909467b48Spatrick 
58009467b48Spatrick   // Evaluate the BinOp on the incoming phi values.
58109467b48Spatrick   Value *CommonValue = nullptr;
58209467b48Spatrick   for (unsigned u = 0, e = PI->getNumIncomingValues(); u < e; ++u) {
58309467b48Spatrick     Value *Incoming = PI->getIncomingValue(u);
58409467b48Spatrick     Instruction *InTI = PI->getIncomingBlock(u)->getTerminator();
58509467b48Spatrick     // If the incoming value is the phi node itself, it can safely be skipped.
586*d415bd75Srobert     if (Incoming == PI)
587*d415bd75Srobert       continue;
58809467b48Spatrick     // Change the context instruction to the "edge" that flows into the phi.
58909467b48Spatrick     // This is important because that is where incoming is actually "evaluated"
59009467b48Spatrick     // even though it is used later somewhere else.
591*d415bd75Srobert     Value *V = simplifyCmpInst(Pred, Incoming, RHS, Q.getWithInstruction(InTI),
59209467b48Spatrick                                MaxRecurse);
59309467b48Spatrick     // If the operation failed to simplify, or simplified to a different value
59409467b48Spatrick     // to previously, then give up.
59509467b48Spatrick     if (!V || (CommonValue && V != CommonValue))
59609467b48Spatrick       return nullptr;
59709467b48Spatrick     CommonValue = V;
59809467b48Spatrick   }
59909467b48Spatrick 
60009467b48Spatrick   return CommonValue;
60109467b48Spatrick }
60209467b48Spatrick 
foldOrCommuteConstant(Instruction::BinaryOps Opcode,Value * & Op0,Value * & Op1,const SimplifyQuery & Q)60309467b48Spatrick static Constant *foldOrCommuteConstant(Instruction::BinaryOps Opcode,
60409467b48Spatrick                                        Value *&Op0, Value *&Op1,
60509467b48Spatrick                                        const SimplifyQuery &Q) {
60609467b48Spatrick   if (auto *CLHS = dyn_cast<Constant>(Op0)) {
607*d415bd75Srobert     if (auto *CRHS = dyn_cast<Constant>(Op1)) {
608*d415bd75Srobert       switch (Opcode) {
609*d415bd75Srobert       default:
610*d415bd75Srobert         break;
611*d415bd75Srobert       case Instruction::FAdd:
612*d415bd75Srobert       case Instruction::FSub:
613*d415bd75Srobert       case Instruction::FMul:
614*d415bd75Srobert       case Instruction::FDiv:
615*d415bd75Srobert       case Instruction::FRem:
616*d415bd75Srobert         if (Q.CxtI != nullptr)
617*d415bd75Srobert           return ConstantFoldFPInstOperands(Opcode, CLHS, CRHS, Q.DL, Q.CxtI);
618*d415bd75Srobert       }
61909467b48Spatrick       return ConstantFoldBinaryOpOperands(Opcode, CLHS, CRHS, Q.DL);
620*d415bd75Srobert     }
62109467b48Spatrick 
62209467b48Spatrick     // Canonicalize the constant to the RHS if this is a commutative operation.
62309467b48Spatrick     if (Instruction::isCommutative(Opcode))
62409467b48Spatrick       std::swap(Op0, Op1);
62509467b48Spatrick   }
62609467b48Spatrick   return nullptr;
62709467b48Spatrick }
62809467b48Spatrick 
62909467b48Spatrick /// Given operands for an Add, see if we can fold the result.
63009467b48Spatrick /// If not, this returns null.
simplifyAddInst(Value * Op0,Value * Op1,bool IsNSW,bool IsNUW,const SimplifyQuery & Q,unsigned MaxRecurse)631*d415bd75Srobert static Value *simplifyAddInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
63209467b48Spatrick                               const SimplifyQuery &Q, unsigned MaxRecurse) {
63309467b48Spatrick   if (Constant *C = foldOrCommuteConstant(Instruction::Add, Op0, Op1, Q))
63409467b48Spatrick     return C;
63509467b48Spatrick 
636*d415bd75Srobert   // X + poison -> poison
637*d415bd75Srobert   if (isa<PoisonValue>(Op1))
638*d415bd75Srobert     return Op1;
639*d415bd75Srobert 
64009467b48Spatrick   // X + undef -> undef
64173471bf0Spatrick   if (Q.isUndefValue(Op1))
64209467b48Spatrick     return Op1;
64309467b48Spatrick 
64409467b48Spatrick   // X + 0 -> X
64509467b48Spatrick   if (match(Op1, m_Zero()))
64609467b48Spatrick     return Op0;
64709467b48Spatrick 
64809467b48Spatrick   // If two operands are negative, return 0.
64909467b48Spatrick   if (isKnownNegation(Op0, Op1))
65009467b48Spatrick     return Constant::getNullValue(Op0->getType());
65109467b48Spatrick 
65209467b48Spatrick   // X + (Y - X) -> Y
65309467b48Spatrick   // (Y - X) + X -> Y
65409467b48Spatrick   // Eg: X + -X -> 0
65509467b48Spatrick   Value *Y = nullptr;
65609467b48Spatrick   if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
65709467b48Spatrick       match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
65809467b48Spatrick     return Y;
65909467b48Spatrick 
66009467b48Spatrick   // X + ~X -> -1   since   ~X = -X-1
66109467b48Spatrick   Type *Ty = Op0->getType();
662*d415bd75Srobert   if (match(Op0, m_Not(m_Specific(Op1))) || match(Op1, m_Not(m_Specific(Op0))))
66309467b48Spatrick     return Constant::getAllOnesValue(Ty);
66409467b48Spatrick 
66509467b48Spatrick   // add nsw/nuw (xor Y, signmask), signmask --> Y
66609467b48Spatrick   // The no-wrapping add guarantees that the top bit will be set by the add.
66709467b48Spatrick   // Therefore, the xor must be clearing the already set sign bit of Y.
66809467b48Spatrick   if ((IsNSW || IsNUW) && match(Op1, m_SignMask()) &&
66909467b48Spatrick       match(Op0, m_Xor(m_Value(Y), m_SignMask())))
67009467b48Spatrick     return Y;
67109467b48Spatrick 
67209467b48Spatrick   // add nuw %x, -1  ->  -1, because %x can only be 0.
67309467b48Spatrick   if (IsNUW && match(Op1, m_AllOnes()))
67409467b48Spatrick     return Op1; // Which is -1.
67509467b48Spatrick 
67609467b48Spatrick   /// i1 add -> xor.
67709467b48Spatrick   if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(1))
678*d415bd75Srobert     if (Value *V = simplifyXorInst(Op0, Op1, Q, MaxRecurse - 1))
67909467b48Spatrick       return V;
68009467b48Spatrick 
68109467b48Spatrick   // Try some generic simplifications for associative operations.
682*d415bd75Srobert   if (Value *V =
683*d415bd75Srobert           simplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q, MaxRecurse))
68409467b48Spatrick     return V;
68509467b48Spatrick 
68609467b48Spatrick   // Threading Add over selects and phi nodes is pointless, so don't bother.
68709467b48Spatrick   // Threading over the select in "A + select(cond, B, C)" means evaluating
68809467b48Spatrick   // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
68909467b48Spatrick   // only if B and C are equal.  If B and C are equal then (since we assume
69009467b48Spatrick   // that operands have already been simplified) "select(cond, B, C)" should
69109467b48Spatrick   // have been simplified to the common value of B and C already.  Analysing
69209467b48Spatrick   // "A+B" and "A+C" thus gains nothing, but costs compile time.  Similarly
69309467b48Spatrick   // for threading over phi nodes.
69409467b48Spatrick 
69509467b48Spatrick   return nullptr;
69609467b48Spatrick }
69709467b48Spatrick 
simplifyAddInst(Value * Op0,Value * Op1,bool IsNSW,bool IsNUW,const SimplifyQuery & Query)698*d415bd75Srobert Value *llvm::simplifyAddInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
69909467b48Spatrick                              const SimplifyQuery &Query) {
700*d415bd75Srobert   return ::simplifyAddInst(Op0, Op1, IsNSW, IsNUW, Query, RecursionLimit);
70109467b48Spatrick }
70209467b48Spatrick 
70309467b48Spatrick /// Compute the base pointer and cumulative constant offsets for V.
70409467b48Spatrick ///
70509467b48Spatrick /// This strips all constant offsets off of V, leaving it the base pointer, and
706*d415bd75Srobert /// accumulates the total constant offset applied in the returned constant.
707*d415bd75Srobert /// It returns zero if there are no constant offsets applied.
70809467b48Spatrick ///
709*d415bd75Srobert /// This is very similar to stripAndAccumulateConstantOffsets(), except it
710*d415bd75Srobert /// normalizes the offset bitwidth to the stripped pointer type, not the
711*d415bd75Srobert /// original pointer type.
stripAndComputeConstantOffsets(const DataLayout & DL,Value * & V,bool AllowNonInbounds=false)712*d415bd75Srobert static APInt stripAndComputeConstantOffsets(const DataLayout &DL, Value *&V,
71309467b48Spatrick                                             bool AllowNonInbounds = false) {
71409467b48Spatrick   assert(V->getType()->isPtrOrPtrVectorTy());
71509467b48Spatrick 
716*d415bd75Srobert   APInt Offset = APInt::getZero(DL.getIndexTypeSizeInBits(V->getType()));
71709467b48Spatrick   V = V->stripAndAccumulateConstantOffsets(DL, Offset, AllowNonInbounds);
71809467b48Spatrick   // As that strip may trace through `addrspacecast`, need to sext or trunc
71909467b48Spatrick   // the offset calculated.
720*d415bd75Srobert   return Offset.sextOrTrunc(DL.getIndexTypeSizeInBits(V->getType()));
72109467b48Spatrick }
72209467b48Spatrick 
72309467b48Spatrick /// Compute the constant difference between two pointer values.
72409467b48Spatrick /// If the difference is not a constant, returns zero.
computePointerDifference(const DataLayout & DL,Value * LHS,Value * RHS)72509467b48Spatrick static Constant *computePointerDifference(const DataLayout &DL, Value *LHS,
72609467b48Spatrick                                           Value *RHS) {
727*d415bd75Srobert   APInt LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
728*d415bd75Srobert   APInt RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
72909467b48Spatrick 
73009467b48Spatrick   // If LHS and RHS are not related via constant offsets to the same base
73109467b48Spatrick   // value, there is nothing we can do here.
73209467b48Spatrick   if (LHS != RHS)
73309467b48Spatrick     return nullptr;
73409467b48Spatrick 
73509467b48Spatrick   // Otherwise, the difference of LHS - RHS can be computed as:
73609467b48Spatrick   //    LHS - RHS
73709467b48Spatrick   //  = (LHSOffset + Base) - (RHSOffset + Base)
73809467b48Spatrick   //  = LHSOffset - RHSOffset
739*d415bd75Srobert   Constant *Res = ConstantInt::get(LHS->getContext(), LHSOffset - RHSOffset);
740*d415bd75Srobert   if (auto *VecTy = dyn_cast<VectorType>(LHS->getType()))
741*d415bd75Srobert     Res = ConstantVector::getSplat(VecTy->getElementCount(), Res);
742*d415bd75Srobert   return Res;
743*d415bd75Srobert }
744*d415bd75Srobert 
745*d415bd75Srobert /// Test if there is a dominating equivalence condition for the
746*d415bd75Srobert /// two operands. If there is, try to reduce the binary operation
747*d415bd75Srobert /// between the two operands.
748*d415bd75Srobert /// Example: Op0 - Op1 --> 0 when Op0 == Op1
simplifyByDomEq(unsigned Opcode,Value * Op0,Value * Op1,const SimplifyQuery & Q,unsigned MaxRecurse)749*d415bd75Srobert static Value *simplifyByDomEq(unsigned Opcode, Value *Op0, Value *Op1,
750*d415bd75Srobert                               const SimplifyQuery &Q, unsigned MaxRecurse) {
751*d415bd75Srobert   // Recursive run it can not get any benefit
752*d415bd75Srobert   if (MaxRecurse != RecursionLimit)
753*d415bd75Srobert     return nullptr;
754*d415bd75Srobert 
755*d415bd75Srobert   std::optional<bool> Imp =
756*d415bd75Srobert       isImpliedByDomCondition(CmpInst::ICMP_EQ, Op0, Op1, Q.CxtI, Q.DL);
757*d415bd75Srobert   if (Imp && *Imp) {
758*d415bd75Srobert     Type *Ty = Op0->getType();
759*d415bd75Srobert     switch (Opcode) {
760*d415bd75Srobert     case Instruction::Sub:
761*d415bd75Srobert     case Instruction::Xor:
762*d415bd75Srobert     case Instruction::URem:
763*d415bd75Srobert     case Instruction::SRem:
764*d415bd75Srobert       return Constant::getNullValue(Ty);
765*d415bd75Srobert 
766*d415bd75Srobert     case Instruction::SDiv:
767*d415bd75Srobert     case Instruction::UDiv:
768*d415bd75Srobert       return ConstantInt::get(Ty, 1);
769*d415bd75Srobert 
770*d415bd75Srobert     case Instruction::And:
771*d415bd75Srobert     case Instruction::Or:
772*d415bd75Srobert       // Could be either one - choose Op1 since that's more likely a constant.
773*d415bd75Srobert       return Op1;
774*d415bd75Srobert     default:
775*d415bd75Srobert       break;
776*d415bd75Srobert     }
777*d415bd75Srobert   }
778*d415bd75Srobert   return nullptr;
77909467b48Spatrick }
78009467b48Spatrick 
78109467b48Spatrick /// Given operands for a Sub, see if we can fold the result.
78209467b48Spatrick /// If not, this returns null.
simplifySubInst(Value * Op0,Value * Op1,bool IsNSW,bool IsNUW,const SimplifyQuery & Q,unsigned MaxRecurse)783*d415bd75Srobert static Value *simplifySubInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
78409467b48Spatrick                               const SimplifyQuery &Q, unsigned MaxRecurse) {
78509467b48Spatrick   if (Constant *C = foldOrCommuteConstant(Instruction::Sub, Op0, Op1, Q))
78609467b48Spatrick     return C;
78709467b48Spatrick 
78873471bf0Spatrick   // X - poison -> poison
78973471bf0Spatrick   // poison - X -> poison
79073471bf0Spatrick   if (isa<PoisonValue>(Op0) || isa<PoisonValue>(Op1))
79173471bf0Spatrick     return PoisonValue::get(Op0->getType());
79273471bf0Spatrick 
79309467b48Spatrick   // X - undef -> undef
79409467b48Spatrick   // undef - X -> undef
79573471bf0Spatrick   if (Q.isUndefValue(Op0) || Q.isUndefValue(Op1))
79609467b48Spatrick     return UndefValue::get(Op0->getType());
79709467b48Spatrick 
79809467b48Spatrick   // X - 0 -> X
79909467b48Spatrick   if (match(Op1, m_Zero()))
80009467b48Spatrick     return Op0;
80109467b48Spatrick 
80209467b48Spatrick   // X - X -> 0
80309467b48Spatrick   if (Op0 == Op1)
80409467b48Spatrick     return Constant::getNullValue(Op0->getType());
80509467b48Spatrick 
80609467b48Spatrick   // Is this a negation?
80709467b48Spatrick   if (match(Op0, m_Zero())) {
80809467b48Spatrick     // 0 - X -> 0 if the sub is NUW.
809*d415bd75Srobert     if (IsNUW)
81009467b48Spatrick       return Constant::getNullValue(Op0->getType());
81109467b48Spatrick 
81209467b48Spatrick     KnownBits Known = computeKnownBits(Op1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
81309467b48Spatrick     if (Known.Zero.isMaxSignedValue()) {
81409467b48Spatrick       // Op1 is either 0 or the minimum signed value. If the sub is NSW, then
81509467b48Spatrick       // Op1 must be 0 because negating the minimum signed value is undefined.
816*d415bd75Srobert       if (IsNSW)
81709467b48Spatrick         return Constant::getNullValue(Op0->getType());
81809467b48Spatrick 
81909467b48Spatrick       // 0 - X -> X if X is 0 or the minimum signed value.
82009467b48Spatrick       return Op1;
82109467b48Spatrick     }
82209467b48Spatrick   }
82309467b48Spatrick 
82409467b48Spatrick   // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
82509467b48Spatrick   // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
82609467b48Spatrick   Value *X = nullptr, *Y = nullptr, *Z = Op1;
82709467b48Spatrick   if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
82809467b48Spatrick     // See if "V === Y - Z" simplifies.
829*d415bd75Srobert     if (Value *V = simplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse - 1))
83009467b48Spatrick       // It does!  Now see if "X + V" simplifies.
831*d415bd75Srobert       if (Value *W = simplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse - 1)) {
83209467b48Spatrick         // It does, we successfully reassociated!
83309467b48Spatrick         ++NumReassoc;
83409467b48Spatrick         return W;
83509467b48Spatrick       }
83609467b48Spatrick     // See if "V === X - Z" simplifies.
837*d415bd75Srobert     if (Value *V = simplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse - 1))
83809467b48Spatrick       // It does!  Now see if "Y + V" simplifies.
839*d415bd75Srobert       if (Value *W = simplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse - 1)) {
84009467b48Spatrick         // It does, we successfully reassociated!
84109467b48Spatrick         ++NumReassoc;
84209467b48Spatrick         return W;
84309467b48Spatrick       }
84409467b48Spatrick   }
84509467b48Spatrick 
84609467b48Spatrick   // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
84709467b48Spatrick   // For example, X - (X + 1) -> -1
84809467b48Spatrick   X = Op0;
84909467b48Spatrick   if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
85009467b48Spatrick     // See if "V === X - Y" simplifies.
851*d415bd75Srobert     if (Value *V = simplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse - 1))
85209467b48Spatrick       // It does!  Now see if "V - Z" simplifies.
853*d415bd75Srobert       if (Value *W = simplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse - 1)) {
85409467b48Spatrick         // It does, we successfully reassociated!
85509467b48Spatrick         ++NumReassoc;
85609467b48Spatrick         return W;
85709467b48Spatrick       }
85809467b48Spatrick     // See if "V === X - Z" simplifies.
859*d415bd75Srobert     if (Value *V = simplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse - 1))
86009467b48Spatrick       // It does!  Now see if "V - Y" simplifies.
861*d415bd75Srobert       if (Value *W = simplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse - 1)) {
86209467b48Spatrick         // It does, we successfully reassociated!
86309467b48Spatrick         ++NumReassoc;
86409467b48Spatrick         return W;
86509467b48Spatrick       }
86609467b48Spatrick   }
86709467b48Spatrick 
86809467b48Spatrick   // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
86909467b48Spatrick   // For example, X - (X - Y) -> Y.
87009467b48Spatrick   Z = Op0;
87109467b48Spatrick   if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
87209467b48Spatrick     // See if "V === Z - X" simplifies.
873*d415bd75Srobert     if (Value *V = simplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse - 1))
87409467b48Spatrick       // It does!  Now see if "V + Y" simplifies.
875*d415bd75Srobert       if (Value *W = simplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse - 1)) {
87609467b48Spatrick         // It does, we successfully reassociated!
87709467b48Spatrick         ++NumReassoc;
87809467b48Spatrick         return W;
87909467b48Spatrick       }
88009467b48Spatrick 
88109467b48Spatrick   // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
88209467b48Spatrick   if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
88309467b48Spatrick       match(Op1, m_Trunc(m_Value(Y))))
88409467b48Spatrick     if (X->getType() == Y->getType())
88509467b48Spatrick       // See if "V === X - Y" simplifies.
886*d415bd75Srobert       if (Value *V = simplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse - 1))
88709467b48Spatrick         // It does!  Now see if "trunc V" simplifies.
888*d415bd75Srobert         if (Value *W = simplifyCastInst(Instruction::Trunc, V, Op0->getType(),
88909467b48Spatrick                                         Q, MaxRecurse - 1))
89009467b48Spatrick           // It does, return the simplified "trunc V".
89109467b48Spatrick           return W;
89209467b48Spatrick 
89309467b48Spatrick   // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
894*d415bd75Srobert   if (match(Op0, m_PtrToInt(m_Value(X))) && match(Op1, m_PtrToInt(m_Value(Y))))
89509467b48Spatrick     if (Constant *Result = computePointerDifference(Q.DL, X, Y))
89609467b48Spatrick       return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
89709467b48Spatrick 
89809467b48Spatrick   // i1 sub -> xor.
89909467b48Spatrick   if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(1))
900*d415bd75Srobert     if (Value *V = simplifyXorInst(Op0, Op1, Q, MaxRecurse - 1))
90109467b48Spatrick       return V;
90209467b48Spatrick 
90309467b48Spatrick   // Threading Sub over selects and phi nodes is pointless, so don't bother.
90409467b48Spatrick   // Threading over the select in "A - select(cond, B, C)" means evaluating
90509467b48Spatrick   // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
90609467b48Spatrick   // only if B and C are equal.  If B and C are equal then (since we assume
90709467b48Spatrick   // that operands have already been simplified) "select(cond, B, C)" should
90809467b48Spatrick   // have been simplified to the common value of B and C already.  Analysing
90909467b48Spatrick   // "A-B" and "A-C" thus gains nothing, but costs compile time.  Similarly
91009467b48Spatrick   // for threading over phi nodes.
91109467b48Spatrick 
912*d415bd75Srobert   if (Value *V = simplifyByDomEq(Instruction::Sub, Op0, Op1, Q, MaxRecurse))
913*d415bd75Srobert     return V;
914*d415bd75Srobert 
91509467b48Spatrick   return nullptr;
91609467b48Spatrick }
91709467b48Spatrick 
simplifySubInst(Value * Op0,Value * Op1,bool IsNSW,bool IsNUW,const SimplifyQuery & Q)918*d415bd75Srobert Value *llvm::simplifySubInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
91909467b48Spatrick                              const SimplifyQuery &Q) {
920*d415bd75Srobert   return ::simplifySubInst(Op0, Op1, IsNSW, IsNUW, Q, RecursionLimit);
92109467b48Spatrick }
92209467b48Spatrick 
92309467b48Spatrick /// Given operands for a Mul, see if we can fold the result.
92409467b48Spatrick /// If not, this returns null.
simplifyMulInst(Value * Op0,Value * Op1,bool IsNSW,bool IsNUW,const SimplifyQuery & Q,unsigned MaxRecurse)925*d415bd75Srobert static Value *simplifyMulInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
926*d415bd75Srobert                               const SimplifyQuery &Q, unsigned MaxRecurse) {
92709467b48Spatrick   if (Constant *C = foldOrCommuteConstant(Instruction::Mul, Op0, Op1, Q))
92809467b48Spatrick     return C;
92909467b48Spatrick 
93073471bf0Spatrick   // X * poison -> poison
93173471bf0Spatrick   if (isa<PoisonValue>(Op1))
93273471bf0Spatrick     return Op1;
93373471bf0Spatrick 
93409467b48Spatrick   // X * undef -> 0
93509467b48Spatrick   // X * 0 -> 0
93673471bf0Spatrick   if (Q.isUndefValue(Op1) || match(Op1, m_Zero()))
93709467b48Spatrick     return Constant::getNullValue(Op0->getType());
93809467b48Spatrick 
93909467b48Spatrick   // X * 1 -> X
94009467b48Spatrick   if (match(Op1, m_One()))
94109467b48Spatrick     return Op0;
94209467b48Spatrick 
94309467b48Spatrick   // (X / Y) * Y -> X if the division is exact.
94409467b48Spatrick   Value *X = nullptr;
94509467b48Spatrick   if (Q.IIQ.UseInstrInfo &&
94609467b48Spatrick       (match(Op0,
94709467b48Spatrick              m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) ||     // (X / Y) * Y
94809467b48Spatrick        match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0)))))) // Y * (X / Y)
94909467b48Spatrick     return X;
95009467b48Spatrick 
951*d415bd75Srobert    if (Op0->getType()->isIntOrIntVectorTy(1)) {
952*d415bd75Srobert     // mul i1 nsw is a special-case because -1 * -1 is poison (+1 is not
953*d415bd75Srobert     // representable). All other cases reduce to 0, so just return 0.
954*d415bd75Srobert     if (IsNSW)
955*d415bd75Srobert       return ConstantInt::getNullValue(Op0->getType());
956*d415bd75Srobert 
957*d415bd75Srobert     // Treat "mul i1" as "and i1".
958*d415bd75Srobert     if (MaxRecurse)
959*d415bd75Srobert       if (Value *V = simplifyAndInst(Op0, Op1, Q, MaxRecurse - 1))
96009467b48Spatrick         return V;
961*d415bd75Srobert   }
96209467b48Spatrick 
96309467b48Spatrick   // Try some generic simplifications for associative operations.
964*d415bd75Srobert   if (Value *V =
965*d415bd75Srobert           simplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q, MaxRecurse))
96609467b48Spatrick     return V;
96709467b48Spatrick 
96809467b48Spatrick   // Mul distributes over Add. Try some generic simplifications based on this.
96973471bf0Spatrick   if (Value *V = expandCommutativeBinOp(Instruction::Mul, Op0, Op1,
97073471bf0Spatrick                                         Instruction::Add, Q, MaxRecurse))
97109467b48Spatrick     return V;
97209467b48Spatrick 
97309467b48Spatrick   // If the operation is with the result of a select instruction, check whether
97409467b48Spatrick   // operating on either branch of the select always yields the same value.
97509467b48Spatrick   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
976*d415bd75Srobert     if (Value *V =
977*d415bd75Srobert             threadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q, MaxRecurse))
97809467b48Spatrick       return V;
97909467b48Spatrick 
98009467b48Spatrick   // If the operation is with the result of a phi instruction, check whether
98109467b48Spatrick   // operating on all incoming values of the phi always yields the same value.
98209467b48Spatrick   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
983*d415bd75Srobert     if (Value *V =
984*d415bd75Srobert             threadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q, MaxRecurse))
98509467b48Spatrick       return V;
98609467b48Spatrick 
98709467b48Spatrick   return nullptr;
98809467b48Spatrick }
98909467b48Spatrick 
simplifyMulInst(Value * Op0,Value * Op1,bool IsNSW,bool IsNUW,const SimplifyQuery & Q)990*d415bd75Srobert Value *llvm::simplifyMulInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
991*d415bd75Srobert                              const SimplifyQuery &Q) {
992*d415bd75Srobert   return ::simplifyMulInst(Op0, Op1, IsNSW, IsNUW, Q, RecursionLimit);
99309467b48Spatrick }
99409467b48Spatrick 
99509467b48Spatrick /// Check for common or similar folds of integer division or integer remainder.
99609467b48Spatrick /// This applies to all 4 opcodes (sdiv/udiv/srem/urem).
simplifyDivRem(Instruction::BinaryOps Opcode,Value * Op0,Value * Op1,const SimplifyQuery & Q,unsigned MaxRecurse)99773471bf0Spatrick static Value *simplifyDivRem(Instruction::BinaryOps Opcode, Value *Op0,
998*d415bd75Srobert                              Value *Op1, const SimplifyQuery &Q,
999*d415bd75Srobert                              unsigned MaxRecurse) {
100073471bf0Spatrick   bool IsDiv = (Opcode == Instruction::SDiv || Opcode == Instruction::UDiv);
100173471bf0Spatrick   bool IsSigned = (Opcode == Instruction::SDiv || Opcode == Instruction::SRem);
100273471bf0Spatrick 
100309467b48Spatrick   Type *Ty = Op0->getType();
100409467b48Spatrick 
100573471bf0Spatrick   // X / undef -> poison
100673471bf0Spatrick   // X % undef -> poison
1007*d415bd75Srobert   if (Q.isUndefValue(Op1) || isa<PoisonValue>(Op1))
100873471bf0Spatrick     return PoisonValue::get(Ty);
100909467b48Spatrick 
101073471bf0Spatrick   // X / 0 -> poison
101173471bf0Spatrick   // X % 0 -> poison
101209467b48Spatrick   // We don't need to preserve faults!
101309467b48Spatrick   if (match(Op1, m_Zero()))
101473471bf0Spatrick     return PoisonValue::get(Ty);
101509467b48Spatrick 
101673471bf0Spatrick   // If any element of a constant divisor fixed width vector is zero or undef
101773471bf0Spatrick   // the behavior is undefined and we can fold the whole op to poison.
101809467b48Spatrick   auto *Op1C = dyn_cast<Constant>(Op1);
1019097a140dSpatrick   auto *VTy = dyn_cast<FixedVectorType>(Ty);
1020097a140dSpatrick   if (Op1C && VTy) {
1021097a140dSpatrick     unsigned NumElts = VTy->getNumElements();
102209467b48Spatrick     for (unsigned i = 0; i != NumElts; ++i) {
102309467b48Spatrick       Constant *Elt = Op1C->getAggregateElement(i);
102473471bf0Spatrick       if (Elt && (Elt->isNullValue() || Q.isUndefValue(Elt)))
102573471bf0Spatrick         return PoisonValue::get(Ty);
102609467b48Spatrick     }
102709467b48Spatrick   }
102809467b48Spatrick 
102973471bf0Spatrick   // poison / X -> poison
103073471bf0Spatrick   // poison % X -> poison
103173471bf0Spatrick   if (isa<PoisonValue>(Op0))
103273471bf0Spatrick     return Op0;
103373471bf0Spatrick 
103409467b48Spatrick   // undef / X -> 0
103509467b48Spatrick   // undef % X -> 0
103673471bf0Spatrick   if (Q.isUndefValue(Op0))
103709467b48Spatrick     return Constant::getNullValue(Ty);
103809467b48Spatrick 
103909467b48Spatrick   // 0 / X -> 0
104009467b48Spatrick   // 0 % X -> 0
104109467b48Spatrick   if (match(Op0, m_Zero()))
104209467b48Spatrick     return Constant::getNullValue(Op0->getType());
104309467b48Spatrick 
104409467b48Spatrick   // X / X -> 1
104509467b48Spatrick   // X % X -> 0
104609467b48Spatrick   if (Op0 == Op1)
104709467b48Spatrick     return IsDiv ? ConstantInt::get(Ty, 1) : Constant::getNullValue(Ty);
104809467b48Spatrick 
104909467b48Spatrick   // X / 1 -> X
105009467b48Spatrick   // X % 1 -> 0
105109467b48Spatrick   // If this is a boolean op (single-bit element type), we can't have
105209467b48Spatrick   // division-by-zero or remainder-by-zero, so assume the divisor is 1.
105309467b48Spatrick   // Similarly, if we're zero-extending a boolean divisor, then assume it's a 1.
105409467b48Spatrick   Value *X;
105509467b48Spatrick   if (match(Op1, m_One()) || Ty->isIntOrIntVectorTy(1) ||
105609467b48Spatrick       (match(Op1, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)))
105709467b48Spatrick     return IsDiv ? Op0 : Constant::getNullValue(Ty);
105809467b48Spatrick 
105973471bf0Spatrick   // If X * Y does not overflow, then:
106073471bf0Spatrick   //   X * Y / Y -> X
106173471bf0Spatrick   //   X * Y % Y -> 0
106273471bf0Spatrick   if (match(Op0, m_c_Mul(m_Value(X), m_Specific(Op1)))) {
106373471bf0Spatrick     auto *Mul = cast<OverflowingBinaryOperator>(Op0);
106473471bf0Spatrick     // The multiplication can't overflow if it is defined not to, or if
106573471bf0Spatrick     // X == A / Y for some A.
106673471bf0Spatrick     if ((IsSigned && Q.IIQ.hasNoSignedWrap(Mul)) ||
106773471bf0Spatrick         (!IsSigned && Q.IIQ.hasNoUnsignedWrap(Mul)) ||
106873471bf0Spatrick         (IsSigned && match(X, m_SDiv(m_Value(), m_Specific(Op1)))) ||
106973471bf0Spatrick         (!IsSigned && match(X, m_UDiv(m_Value(), m_Specific(Op1))))) {
107073471bf0Spatrick       return IsDiv ? X : Constant::getNullValue(Op0->getType());
107173471bf0Spatrick     }
107273471bf0Spatrick   }
107373471bf0Spatrick 
1074*d415bd75Srobert   if (Value *V = simplifyByDomEq(Opcode, Op0, Op1, Q, MaxRecurse))
1075*d415bd75Srobert     return V;
1076*d415bd75Srobert 
107709467b48Spatrick   return nullptr;
107809467b48Spatrick }
107909467b48Spatrick 
108009467b48Spatrick /// Given a predicate and two operands, return true if the comparison is true.
108109467b48Spatrick /// This is a helper for div/rem simplification where we return some other value
108209467b48Spatrick /// when we can prove a relationship between the operands.
isICmpTrue(ICmpInst::Predicate Pred,Value * LHS,Value * RHS,const SimplifyQuery & Q,unsigned MaxRecurse)108309467b48Spatrick static bool isICmpTrue(ICmpInst::Predicate Pred, Value *LHS, Value *RHS,
108409467b48Spatrick                        const SimplifyQuery &Q, unsigned MaxRecurse) {
1085*d415bd75Srobert   Value *V = simplifyICmpInst(Pred, LHS, RHS, Q, MaxRecurse);
108609467b48Spatrick   Constant *C = dyn_cast_or_null<Constant>(V);
108709467b48Spatrick   return (C && C->isAllOnesValue());
108809467b48Spatrick }
108909467b48Spatrick 
109009467b48Spatrick /// Return true if we can simplify X / Y to 0. Remainder can adapt that answer
109109467b48Spatrick /// to simplify X % Y to X.
isDivZero(Value * X,Value * Y,const SimplifyQuery & Q,unsigned MaxRecurse,bool IsSigned)109209467b48Spatrick static bool isDivZero(Value *X, Value *Y, const SimplifyQuery &Q,
109309467b48Spatrick                       unsigned MaxRecurse, bool IsSigned) {
109409467b48Spatrick   // Recursion is always used, so bail out at once if we already hit the limit.
109509467b48Spatrick   if (!MaxRecurse--)
109609467b48Spatrick     return false;
109709467b48Spatrick 
109809467b48Spatrick   if (IsSigned) {
109909467b48Spatrick     // |X| / |Y| --> 0
110009467b48Spatrick     //
110109467b48Spatrick     // We require that 1 operand is a simple constant. That could be extended to
110209467b48Spatrick     // 2 variables if we computed the sign bit for each.
110309467b48Spatrick     //
110409467b48Spatrick     // Make sure that a constant is not the minimum signed value because taking
110509467b48Spatrick     // the abs() of that is undefined.
110609467b48Spatrick     Type *Ty = X->getType();
110709467b48Spatrick     const APInt *C;
110809467b48Spatrick     if (match(X, m_APInt(C)) && !C->isMinSignedValue()) {
110909467b48Spatrick       // Is the variable divisor magnitude always greater than the constant
111009467b48Spatrick       // dividend magnitude?
111109467b48Spatrick       // |Y| > |C| --> Y < -abs(C) or Y > abs(C)
111209467b48Spatrick       Constant *PosDividendC = ConstantInt::get(Ty, C->abs());
111309467b48Spatrick       Constant *NegDividendC = ConstantInt::get(Ty, -C->abs());
111409467b48Spatrick       if (isICmpTrue(CmpInst::ICMP_SLT, Y, NegDividendC, Q, MaxRecurse) ||
111509467b48Spatrick           isICmpTrue(CmpInst::ICMP_SGT, Y, PosDividendC, Q, MaxRecurse))
111609467b48Spatrick         return true;
111709467b48Spatrick     }
111809467b48Spatrick     if (match(Y, m_APInt(C))) {
111909467b48Spatrick       // Special-case: we can't take the abs() of a minimum signed value. If
112009467b48Spatrick       // that's the divisor, then all we have to do is prove that the dividend
112109467b48Spatrick       // is also not the minimum signed value.
112209467b48Spatrick       if (C->isMinSignedValue())
112309467b48Spatrick         return isICmpTrue(CmpInst::ICMP_NE, X, Y, Q, MaxRecurse);
112409467b48Spatrick 
112509467b48Spatrick       // Is the variable dividend magnitude always less than the constant
112609467b48Spatrick       // divisor magnitude?
112709467b48Spatrick       // |X| < |C| --> X > -abs(C) and X < abs(C)
112809467b48Spatrick       Constant *PosDivisorC = ConstantInt::get(Ty, C->abs());
112909467b48Spatrick       Constant *NegDivisorC = ConstantInt::get(Ty, -C->abs());
113009467b48Spatrick       if (isICmpTrue(CmpInst::ICMP_SGT, X, NegDivisorC, Q, MaxRecurse) &&
113109467b48Spatrick           isICmpTrue(CmpInst::ICMP_SLT, X, PosDivisorC, Q, MaxRecurse))
113209467b48Spatrick         return true;
113309467b48Spatrick     }
113409467b48Spatrick     return false;
113509467b48Spatrick   }
113609467b48Spatrick 
113709467b48Spatrick   // IsSigned == false.
1138*d415bd75Srobert 
1139*d415bd75Srobert   // Is the unsigned dividend known to be less than a constant divisor?
1140*d415bd75Srobert   // TODO: Convert this (and above) to range analysis
1141*d415bd75Srobert   //      ("computeConstantRangeIncludingKnownBits")?
1142*d415bd75Srobert   const APInt *C;
1143*d415bd75Srobert   if (match(Y, m_APInt(C)) &&
1144*d415bd75Srobert       computeKnownBits(X, Q.DL, 0, Q.AC, Q.CxtI, Q.DT).getMaxValue().ult(*C))
1145*d415bd75Srobert     return true;
1146*d415bd75Srobert 
1147*d415bd75Srobert   // Try again for any divisor:
114809467b48Spatrick   // Is the dividend unsigned less than the divisor?
114909467b48Spatrick   return isICmpTrue(ICmpInst::ICMP_ULT, X, Y, Q, MaxRecurse);
115009467b48Spatrick }
115109467b48Spatrick 
115209467b48Spatrick /// These are simplifications common to SDiv and UDiv.
simplifyDiv(Instruction::BinaryOps Opcode,Value * Op0,Value * Op1,bool IsExact,const SimplifyQuery & Q,unsigned MaxRecurse)115309467b48Spatrick static Value *simplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
1154*d415bd75Srobert                           bool IsExact, const SimplifyQuery &Q,
1155*d415bd75Srobert                           unsigned MaxRecurse) {
115609467b48Spatrick   if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
115709467b48Spatrick     return C;
115809467b48Spatrick 
1159*d415bd75Srobert   if (Value *V = simplifyDivRem(Opcode, Op0, Op1, Q, MaxRecurse))
116009467b48Spatrick     return V;
116109467b48Spatrick 
1162*d415bd75Srobert   // If this is an exact divide by a constant, then the dividend (Op0) must have
1163*d415bd75Srobert   // at least as many trailing zeros as the divisor to divide evenly. If it has
1164*d415bd75Srobert   // less trailing zeros, then the result must be poison.
1165*d415bd75Srobert   const APInt *DivC;
1166*d415bd75Srobert   if (IsExact && match(Op1, m_APInt(DivC)) && DivC->countTrailingZeros()) {
1167*d415bd75Srobert     KnownBits KnownOp0 = computeKnownBits(Op0, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1168*d415bd75Srobert     if (KnownOp0.countMaxTrailingZeros() < DivC->countTrailingZeros())
1169*d415bd75Srobert       return PoisonValue::get(Op0->getType());
1170*d415bd75Srobert   }
1171*d415bd75Srobert 
117209467b48Spatrick   bool IsSigned = Opcode == Instruction::SDiv;
117309467b48Spatrick 
117409467b48Spatrick   // (X rem Y) / Y -> 0
117509467b48Spatrick   if ((IsSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
117609467b48Spatrick       (!IsSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
117709467b48Spatrick     return Constant::getNullValue(Op0->getType());
117809467b48Spatrick 
117909467b48Spatrick   // (X /u C1) /u C2 -> 0 if C1 * C2 overflow
118009467b48Spatrick   ConstantInt *C1, *C2;
118173471bf0Spatrick   if (!IsSigned && match(Op0, m_UDiv(m_Value(), m_ConstantInt(C1))) &&
118209467b48Spatrick       match(Op1, m_ConstantInt(C2))) {
118309467b48Spatrick     bool Overflow;
118409467b48Spatrick     (void)C1->getValue().umul_ov(C2->getValue(), Overflow);
118509467b48Spatrick     if (Overflow)
118609467b48Spatrick       return Constant::getNullValue(Op0->getType());
118709467b48Spatrick   }
118809467b48Spatrick 
118909467b48Spatrick   // If the operation is with the result of a select instruction, check whether
119009467b48Spatrick   // operating on either branch of the select always yields the same value.
119109467b48Spatrick   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1192*d415bd75Srobert     if (Value *V = threadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
119309467b48Spatrick       return V;
119409467b48Spatrick 
119509467b48Spatrick   // If the operation is with the result of a phi instruction, check whether
119609467b48Spatrick   // operating on all incoming values of the phi always yields the same value.
119709467b48Spatrick   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1198*d415bd75Srobert     if (Value *V = threadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
119909467b48Spatrick       return V;
120009467b48Spatrick 
120109467b48Spatrick   if (isDivZero(Op0, Op1, Q, MaxRecurse, IsSigned))
120209467b48Spatrick     return Constant::getNullValue(Op0->getType());
120309467b48Spatrick 
120409467b48Spatrick   return nullptr;
120509467b48Spatrick }
120609467b48Spatrick 
120709467b48Spatrick /// These are simplifications common to SRem and URem.
simplifyRem(Instruction::BinaryOps Opcode,Value * Op0,Value * Op1,const SimplifyQuery & Q,unsigned MaxRecurse)120809467b48Spatrick static Value *simplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
120909467b48Spatrick                           const SimplifyQuery &Q, unsigned MaxRecurse) {
121009467b48Spatrick   if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
121109467b48Spatrick     return C;
121209467b48Spatrick 
1213*d415bd75Srobert   if (Value *V = simplifyDivRem(Opcode, Op0, Op1, Q, MaxRecurse))
121409467b48Spatrick     return V;
121509467b48Spatrick 
121609467b48Spatrick   // (X % Y) % Y -> X % Y
121709467b48Spatrick   if ((Opcode == Instruction::SRem &&
121809467b48Spatrick        match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
121909467b48Spatrick       (Opcode == Instruction::URem &&
122009467b48Spatrick        match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
122109467b48Spatrick     return Op0;
122209467b48Spatrick 
122309467b48Spatrick   // (X << Y) % X -> 0
122409467b48Spatrick   if (Q.IIQ.UseInstrInfo &&
122509467b48Spatrick       ((Opcode == Instruction::SRem &&
122609467b48Spatrick         match(Op0, m_NSWShl(m_Specific(Op1), m_Value()))) ||
122709467b48Spatrick        (Opcode == Instruction::URem &&
122809467b48Spatrick         match(Op0, m_NUWShl(m_Specific(Op1), m_Value())))))
122909467b48Spatrick     return Constant::getNullValue(Op0->getType());
123009467b48Spatrick 
123109467b48Spatrick   // If the operation is with the result of a select instruction, check whether
123209467b48Spatrick   // operating on either branch of the select always yields the same value.
123309467b48Spatrick   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1234*d415bd75Srobert     if (Value *V = threadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
123509467b48Spatrick       return V;
123609467b48Spatrick 
123709467b48Spatrick   // If the operation is with the result of a phi instruction, check whether
123809467b48Spatrick   // operating on all incoming values of the phi always yields the same value.
123909467b48Spatrick   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1240*d415bd75Srobert     if (Value *V = threadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
124109467b48Spatrick       return V;
124209467b48Spatrick 
124309467b48Spatrick   // If X / Y == 0, then X % Y == X.
124409467b48Spatrick   if (isDivZero(Op0, Op1, Q, MaxRecurse, Opcode == Instruction::SRem))
124509467b48Spatrick     return Op0;
124609467b48Spatrick 
124709467b48Spatrick   return nullptr;
124809467b48Spatrick }
124909467b48Spatrick 
125009467b48Spatrick /// Given operands for an SDiv, see if we can fold the result.
125109467b48Spatrick /// If not, this returns null.
simplifySDivInst(Value * Op0,Value * Op1,bool IsExact,const SimplifyQuery & Q,unsigned MaxRecurse)1252*d415bd75Srobert static Value *simplifySDivInst(Value *Op0, Value *Op1, bool IsExact,
1253*d415bd75Srobert                                const SimplifyQuery &Q, unsigned MaxRecurse) {
125409467b48Spatrick   // If two operands are negated and no signed overflow, return -1.
125509467b48Spatrick   if (isKnownNegation(Op0, Op1, /*NeedNSW=*/true))
125609467b48Spatrick     return Constant::getAllOnesValue(Op0->getType());
125709467b48Spatrick 
1258*d415bd75Srobert   return simplifyDiv(Instruction::SDiv, Op0, Op1, IsExact, Q, MaxRecurse);
125909467b48Spatrick }
126009467b48Spatrick 
simplifySDivInst(Value * Op0,Value * Op1,bool IsExact,const SimplifyQuery & Q)1261*d415bd75Srobert Value *llvm::simplifySDivInst(Value *Op0, Value *Op1, bool IsExact,
1262*d415bd75Srobert                               const SimplifyQuery &Q) {
1263*d415bd75Srobert   return ::simplifySDivInst(Op0, Op1, IsExact, Q, RecursionLimit);
126409467b48Spatrick }
126509467b48Spatrick 
126609467b48Spatrick /// Given operands for a UDiv, see if we can fold the result.
126709467b48Spatrick /// If not, this returns null.
simplifyUDivInst(Value * Op0,Value * Op1,bool IsExact,const SimplifyQuery & Q,unsigned MaxRecurse)1268*d415bd75Srobert static Value *simplifyUDivInst(Value *Op0, Value *Op1, bool IsExact,
1269*d415bd75Srobert                                const SimplifyQuery &Q, unsigned MaxRecurse) {
1270*d415bd75Srobert   return simplifyDiv(Instruction::UDiv, Op0, Op1, IsExact, Q, MaxRecurse);
127109467b48Spatrick }
127209467b48Spatrick 
simplifyUDivInst(Value * Op0,Value * Op1,bool IsExact,const SimplifyQuery & Q)1273*d415bd75Srobert Value *llvm::simplifyUDivInst(Value *Op0, Value *Op1, bool IsExact,
1274*d415bd75Srobert                               const SimplifyQuery &Q) {
1275*d415bd75Srobert   return ::simplifyUDivInst(Op0, Op1, IsExact, Q, RecursionLimit);
127609467b48Spatrick }
127709467b48Spatrick 
127809467b48Spatrick /// Given operands for an SRem, see if we can fold the result.
127909467b48Spatrick /// If not, this returns null.
simplifySRemInst(Value * Op0,Value * Op1,const SimplifyQuery & Q,unsigned MaxRecurse)1280*d415bd75Srobert static Value *simplifySRemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
128109467b48Spatrick                                unsigned MaxRecurse) {
128209467b48Spatrick   // If the divisor is 0, the result is undefined, so assume the divisor is -1.
128309467b48Spatrick   // srem Op0, (sext i1 X) --> srem Op0, -1 --> 0
128409467b48Spatrick   Value *X;
128509467b48Spatrick   if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
128609467b48Spatrick     return ConstantInt::getNullValue(Op0->getType());
128709467b48Spatrick 
128809467b48Spatrick   // If the two operands are negated, return 0.
128909467b48Spatrick   if (isKnownNegation(Op0, Op1))
129009467b48Spatrick     return ConstantInt::getNullValue(Op0->getType());
129109467b48Spatrick 
129209467b48Spatrick   return simplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse);
129309467b48Spatrick }
129409467b48Spatrick 
simplifySRemInst(Value * Op0,Value * Op1,const SimplifyQuery & Q)1295*d415bd75Srobert Value *llvm::simplifySRemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1296*d415bd75Srobert   return ::simplifySRemInst(Op0, Op1, Q, RecursionLimit);
129709467b48Spatrick }
129809467b48Spatrick 
129909467b48Spatrick /// Given operands for a URem, see if we can fold the result.
130009467b48Spatrick /// If not, this returns null.
simplifyURemInst(Value * Op0,Value * Op1,const SimplifyQuery & Q,unsigned MaxRecurse)1301*d415bd75Srobert static Value *simplifyURemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
130209467b48Spatrick                                unsigned MaxRecurse) {
130309467b48Spatrick   return simplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse);
130409467b48Spatrick }
130509467b48Spatrick 
simplifyURemInst(Value * Op0,Value * Op1,const SimplifyQuery & Q)1306*d415bd75Srobert Value *llvm::simplifyURemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1307*d415bd75Srobert   return ::simplifyURemInst(Op0, Op1, Q, RecursionLimit);
130809467b48Spatrick }
130909467b48Spatrick 
131073471bf0Spatrick /// Returns true if a shift by \c Amount always yields poison.
isPoisonShift(Value * Amount,const SimplifyQuery & Q)131173471bf0Spatrick static bool isPoisonShift(Value *Amount, const SimplifyQuery &Q) {
131209467b48Spatrick   Constant *C = dyn_cast<Constant>(Amount);
131309467b48Spatrick   if (!C)
131409467b48Spatrick     return false;
131509467b48Spatrick 
131673471bf0Spatrick   // X shift by undef -> poison because it may shift by the bitwidth.
131773471bf0Spatrick   if (Q.isUndefValue(C))
131809467b48Spatrick     return true;
131909467b48Spatrick 
1320*d415bd75Srobert   // Shifting by the bitwidth or more is poison. This covers scalars and
1321*d415bd75Srobert   // fixed/scalable vectors with splat constants.
1322*d415bd75Srobert   const APInt *AmountC;
1323*d415bd75Srobert   if (match(C, m_APInt(AmountC)) && AmountC->uge(AmountC->getBitWidth()))
132409467b48Spatrick     return true;
132509467b48Spatrick 
1326*d415bd75Srobert   // Try harder for fixed-length vectors:
1327*d415bd75Srobert   // If all lanes of a vector shift are poison, the whole shift is poison.
132809467b48Spatrick   if (isa<ConstantVector>(C) || isa<ConstantDataVector>(C)) {
132973471bf0Spatrick     for (unsigned I = 0,
133073471bf0Spatrick                   E = cast<FixedVectorType>(C->getType())->getNumElements();
1331097a140dSpatrick          I != E; ++I)
133273471bf0Spatrick       if (!isPoisonShift(C->getAggregateElement(I), Q))
133309467b48Spatrick         return false;
133409467b48Spatrick     return true;
133509467b48Spatrick   }
133609467b48Spatrick 
133709467b48Spatrick   return false;
133809467b48Spatrick }
133909467b48Spatrick 
134009467b48Spatrick /// Given operands for an Shl, LShr or AShr, see if we can fold the result.
134109467b48Spatrick /// If not, this returns null.
simplifyShift(Instruction::BinaryOps Opcode,Value * Op0,Value * Op1,bool IsNSW,const SimplifyQuery & Q,unsigned MaxRecurse)1342*d415bd75Srobert static Value *simplifyShift(Instruction::BinaryOps Opcode, Value *Op0,
134373471bf0Spatrick                             Value *Op1, bool IsNSW, const SimplifyQuery &Q,
134473471bf0Spatrick                             unsigned MaxRecurse) {
134509467b48Spatrick   if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
134609467b48Spatrick     return C;
134709467b48Spatrick 
134873471bf0Spatrick   // poison shift by X -> poison
134973471bf0Spatrick   if (isa<PoisonValue>(Op0))
135073471bf0Spatrick     return Op0;
135173471bf0Spatrick 
135209467b48Spatrick   // 0 shift by X -> 0
135309467b48Spatrick   if (match(Op0, m_Zero()))
135409467b48Spatrick     return Constant::getNullValue(Op0->getType());
135509467b48Spatrick 
135609467b48Spatrick   // X shift by 0 -> X
135709467b48Spatrick   // Shift-by-sign-extended bool must be shift-by-0 because shift-by-all-ones
135809467b48Spatrick   // would be poison.
135909467b48Spatrick   Value *X;
136009467b48Spatrick   if (match(Op1, m_Zero()) ||
136109467b48Spatrick       (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)))
136209467b48Spatrick     return Op0;
136309467b48Spatrick 
136409467b48Spatrick   // Fold undefined shifts.
136573471bf0Spatrick   if (isPoisonShift(Op1, Q))
136673471bf0Spatrick     return PoisonValue::get(Op0->getType());
136709467b48Spatrick 
136809467b48Spatrick   // If the operation is with the result of a select instruction, check whether
136909467b48Spatrick   // operating on either branch of the select always yields the same value.
137009467b48Spatrick   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1371*d415bd75Srobert     if (Value *V = threadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
137209467b48Spatrick       return V;
137309467b48Spatrick 
137409467b48Spatrick   // If the operation is with the result of a phi instruction, check whether
137509467b48Spatrick   // operating on all incoming values of the phi always yields the same value.
137609467b48Spatrick   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1377*d415bd75Srobert     if (Value *V = threadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
137809467b48Spatrick       return V;
137909467b48Spatrick 
138009467b48Spatrick   // If any bits in the shift amount make that value greater than or equal to
138109467b48Spatrick   // the number of bits in the type, the shift is undefined.
138273471bf0Spatrick   KnownBits KnownAmt = computeKnownBits(Op1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
138373471bf0Spatrick   if (KnownAmt.getMinValue().uge(KnownAmt.getBitWidth()))
138473471bf0Spatrick     return PoisonValue::get(Op0->getType());
138509467b48Spatrick 
138609467b48Spatrick   // If all valid bits in the shift amount are known zero, the first operand is
138709467b48Spatrick   // unchanged.
138873471bf0Spatrick   unsigned NumValidShiftBits = Log2_32_Ceil(KnownAmt.getBitWidth());
138973471bf0Spatrick   if (KnownAmt.countMinTrailingZeros() >= NumValidShiftBits)
139009467b48Spatrick     return Op0;
139109467b48Spatrick 
139273471bf0Spatrick   // Check for nsw shl leading to a poison value.
139373471bf0Spatrick   if (IsNSW) {
139473471bf0Spatrick     assert(Opcode == Instruction::Shl && "Expected shl for nsw instruction");
139573471bf0Spatrick     KnownBits KnownVal = computeKnownBits(Op0, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
139673471bf0Spatrick     KnownBits KnownShl = KnownBits::shl(KnownVal, KnownAmt);
139773471bf0Spatrick 
139873471bf0Spatrick     if (KnownVal.Zero.isSignBitSet())
139973471bf0Spatrick       KnownShl.Zero.setSignBit();
140073471bf0Spatrick     if (KnownVal.One.isSignBitSet())
140173471bf0Spatrick       KnownShl.One.setSignBit();
140273471bf0Spatrick 
140373471bf0Spatrick     if (KnownShl.hasConflict())
140473471bf0Spatrick       return PoisonValue::get(Op0->getType());
140573471bf0Spatrick   }
140673471bf0Spatrick 
140709467b48Spatrick   return nullptr;
140809467b48Spatrick }
140909467b48Spatrick 
141009467b48Spatrick /// Given operands for an Shl, LShr or AShr, see if we can
141109467b48Spatrick /// fold the result.  If not, this returns null.
simplifyRightShift(Instruction::BinaryOps Opcode,Value * Op0,Value * Op1,bool IsExact,const SimplifyQuery & Q,unsigned MaxRecurse)1412*d415bd75Srobert static Value *simplifyRightShift(Instruction::BinaryOps Opcode, Value *Op0,
1413*d415bd75Srobert                                  Value *Op1, bool IsExact,
1414*d415bd75Srobert                                  const SimplifyQuery &Q, unsigned MaxRecurse) {
141573471bf0Spatrick   if (Value *V =
1416*d415bd75Srobert           simplifyShift(Opcode, Op0, Op1, /*IsNSW*/ false, Q, MaxRecurse))
141709467b48Spatrick     return V;
141809467b48Spatrick 
141909467b48Spatrick   // X >> X -> 0
142009467b48Spatrick   if (Op0 == Op1)
142109467b48Spatrick     return Constant::getNullValue(Op0->getType());
142209467b48Spatrick 
142309467b48Spatrick   // undef >> X -> 0
142409467b48Spatrick   // undef >> X -> undef (if it's exact)
142573471bf0Spatrick   if (Q.isUndefValue(Op0))
1426*d415bd75Srobert     return IsExact ? Op0 : Constant::getNullValue(Op0->getType());
142709467b48Spatrick 
142809467b48Spatrick   // The low bit cannot be shifted out of an exact shift if it is set.
1429*d415bd75Srobert   // TODO: Generalize by counting trailing zeros (see fold for exact division).
1430*d415bd75Srobert   if (IsExact) {
1431*d415bd75Srobert     KnownBits Op0Known =
1432*d415bd75Srobert         computeKnownBits(Op0, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT);
143309467b48Spatrick     if (Op0Known.One[0])
143409467b48Spatrick       return Op0;
143509467b48Spatrick   }
143609467b48Spatrick 
143709467b48Spatrick   return nullptr;
143809467b48Spatrick }
143909467b48Spatrick 
144009467b48Spatrick /// Given operands for an Shl, see if we can fold the result.
144109467b48Spatrick /// If not, this returns null.
simplifyShlInst(Value * Op0,Value * Op1,bool IsNSW,bool IsNUW,const SimplifyQuery & Q,unsigned MaxRecurse)1442*d415bd75Srobert static Value *simplifyShlInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
144309467b48Spatrick                               const SimplifyQuery &Q, unsigned MaxRecurse) {
144473471bf0Spatrick   if (Value *V =
1445*d415bd75Srobert           simplifyShift(Instruction::Shl, Op0, Op1, IsNSW, Q, MaxRecurse))
144609467b48Spatrick     return V;
144709467b48Spatrick 
144809467b48Spatrick   // undef << X -> 0
144909467b48Spatrick   // undef << X -> undef if (if it's NSW/NUW)
145073471bf0Spatrick   if (Q.isUndefValue(Op0))
1451*d415bd75Srobert     return IsNSW || IsNUW ? Op0 : Constant::getNullValue(Op0->getType());
145209467b48Spatrick 
145309467b48Spatrick   // (X >> A) << A -> X
145409467b48Spatrick   Value *X;
145509467b48Spatrick   if (Q.IIQ.UseInstrInfo &&
145609467b48Spatrick       match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
145709467b48Spatrick     return X;
145809467b48Spatrick 
145909467b48Spatrick   // shl nuw i8 C, %x  ->  C  iff C has sign bit set.
1460*d415bd75Srobert   if (IsNUW && match(Op0, m_Negative()))
146109467b48Spatrick     return Op0;
146209467b48Spatrick   // NOTE: could use computeKnownBits() / LazyValueInfo,
146309467b48Spatrick   // but the cost-benefit analysis suggests it isn't worth it.
146409467b48Spatrick 
146509467b48Spatrick   return nullptr;
146609467b48Spatrick }
146709467b48Spatrick 
simplifyShlInst(Value * Op0,Value * Op1,bool IsNSW,bool IsNUW,const SimplifyQuery & Q)1468*d415bd75Srobert Value *llvm::simplifyShlInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
146909467b48Spatrick                              const SimplifyQuery &Q) {
1470*d415bd75Srobert   return ::simplifyShlInst(Op0, Op1, IsNSW, IsNUW, Q, RecursionLimit);
147109467b48Spatrick }
147209467b48Spatrick 
147309467b48Spatrick /// Given operands for an LShr, see if we can fold the result.
147409467b48Spatrick /// If not, this returns null.
simplifyLShrInst(Value * Op0,Value * Op1,bool IsExact,const SimplifyQuery & Q,unsigned MaxRecurse)1475*d415bd75Srobert static Value *simplifyLShrInst(Value *Op0, Value *Op1, bool IsExact,
147609467b48Spatrick                                const SimplifyQuery &Q, unsigned MaxRecurse) {
1477*d415bd75Srobert   if (Value *V = simplifyRightShift(Instruction::LShr, Op0, Op1, IsExact, Q,
147809467b48Spatrick                                     MaxRecurse))
147909467b48Spatrick     return V;
148009467b48Spatrick 
148109467b48Spatrick   // (X << A) >> A -> X
148209467b48Spatrick   Value *X;
148309467b48Spatrick   if (match(Op0, m_NUWShl(m_Value(X), m_Specific(Op1))))
148409467b48Spatrick     return X;
148509467b48Spatrick 
148609467b48Spatrick   // ((X << A) | Y) >> A -> X  if effective width of Y is not larger than A.
148709467b48Spatrick   // We can return X as we do in the above case since OR alters no bits in X.
148809467b48Spatrick   // SimplifyDemandedBits in InstCombine can do more general optimization for
148909467b48Spatrick   // bit manipulation. This pattern aims to provide opportunities for other
149009467b48Spatrick   // optimizers by supporting a simple but common case in InstSimplify.
149109467b48Spatrick   Value *Y;
149209467b48Spatrick   const APInt *ShRAmt, *ShLAmt;
149309467b48Spatrick   if (match(Op1, m_APInt(ShRAmt)) &&
149409467b48Spatrick       match(Op0, m_c_Or(m_NUWShl(m_Value(X), m_APInt(ShLAmt)), m_Value(Y))) &&
149509467b48Spatrick       *ShRAmt == *ShLAmt) {
149609467b48Spatrick     const KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1497*d415bd75Srobert     const unsigned EffWidthY = YKnown.countMaxActiveBits();
149809467b48Spatrick     if (ShRAmt->uge(EffWidthY))
149909467b48Spatrick       return X;
150009467b48Spatrick   }
150109467b48Spatrick 
150209467b48Spatrick   return nullptr;
150309467b48Spatrick }
150409467b48Spatrick 
simplifyLShrInst(Value * Op0,Value * Op1,bool IsExact,const SimplifyQuery & Q)1505*d415bd75Srobert Value *llvm::simplifyLShrInst(Value *Op0, Value *Op1, bool IsExact,
150609467b48Spatrick                               const SimplifyQuery &Q) {
1507*d415bd75Srobert   return ::simplifyLShrInst(Op0, Op1, IsExact, Q, RecursionLimit);
150809467b48Spatrick }
150909467b48Spatrick 
151009467b48Spatrick /// Given operands for an AShr, see if we can fold the result.
151109467b48Spatrick /// If not, this returns null.
simplifyAShrInst(Value * Op0,Value * Op1,bool IsExact,const SimplifyQuery & Q,unsigned MaxRecurse)1512*d415bd75Srobert static Value *simplifyAShrInst(Value *Op0, Value *Op1, bool IsExact,
151309467b48Spatrick                                const SimplifyQuery &Q, unsigned MaxRecurse) {
1514*d415bd75Srobert   if (Value *V = simplifyRightShift(Instruction::AShr, Op0, Op1, IsExact, Q,
151509467b48Spatrick                                     MaxRecurse))
151609467b48Spatrick     return V;
151709467b48Spatrick 
1518*d415bd75Srobert   // -1 >>a X --> -1
1519*d415bd75Srobert   // (-1 << X) a>> X --> -1
152009467b48Spatrick   // Do not return Op0 because it may contain undef elements if it's a vector.
1521*d415bd75Srobert   if (match(Op0, m_AllOnes()) ||
1522*d415bd75Srobert       match(Op0, m_Shl(m_AllOnes(), m_Specific(Op1))))
152309467b48Spatrick     return Constant::getAllOnesValue(Op0->getType());
152409467b48Spatrick 
152509467b48Spatrick   // (X << A) >> A -> X
152609467b48Spatrick   Value *X;
152709467b48Spatrick   if (Q.IIQ.UseInstrInfo && match(Op0, m_NSWShl(m_Value(X), m_Specific(Op1))))
152809467b48Spatrick     return X;
152909467b48Spatrick 
153009467b48Spatrick   // Arithmetic shifting an all-sign-bit value is a no-op.
153109467b48Spatrick   unsigned NumSignBits = ComputeNumSignBits(Op0, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
153209467b48Spatrick   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
153309467b48Spatrick     return Op0;
153409467b48Spatrick 
153509467b48Spatrick   return nullptr;
153609467b48Spatrick }
153709467b48Spatrick 
simplifyAShrInst(Value * Op0,Value * Op1,bool IsExact,const SimplifyQuery & Q)1538*d415bd75Srobert Value *llvm::simplifyAShrInst(Value *Op0, Value *Op1, bool IsExact,
153909467b48Spatrick                               const SimplifyQuery &Q) {
1540*d415bd75Srobert   return ::simplifyAShrInst(Op0, Op1, IsExact, Q, RecursionLimit);
154109467b48Spatrick }
154209467b48Spatrick 
154309467b48Spatrick /// Commuted variants are assumed to be handled by calling this function again
154409467b48Spatrick /// with the parameters swapped.
simplifyUnsignedRangeCheck(ICmpInst * ZeroICmp,ICmpInst * UnsignedICmp,bool IsAnd,const SimplifyQuery & Q)154509467b48Spatrick static Value *simplifyUnsignedRangeCheck(ICmpInst *ZeroICmp,
154609467b48Spatrick                                          ICmpInst *UnsignedICmp, bool IsAnd,
154709467b48Spatrick                                          const SimplifyQuery &Q) {
154809467b48Spatrick   Value *X, *Y;
154909467b48Spatrick 
155009467b48Spatrick   ICmpInst::Predicate EqPred;
155109467b48Spatrick   if (!match(ZeroICmp, m_ICmp(EqPred, m_Value(Y), m_Zero())) ||
155209467b48Spatrick       !ICmpInst::isEquality(EqPred))
155309467b48Spatrick     return nullptr;
155409467b48Spatrick 
155509467b48Spatrick   ICmpInst::Predicate UnsignedPred;
155609467b48Spatrick 
155709467b48Spatrick   Value *A, *B;
155809467b48Spatrick   // Y = (A - B);
155909467b48Spatrick   if (match(Y, m_Sub(m_Value(A), m_Value(B)))) {
156009467b48Spatrick     if (match(UnsignedICmp,
156109467b48Spatrick               m_c_ICmp(UnsignedPred, m_Specific(A), m_Specific(B))) &&
156209467b48Spatrick         ICmpInst::isUnsigned(UnsignedPred)) {
156309467b48Spatrick       // A >=/<= B || (A - B) != 0  <-->  true
156409467b48Spatrick       if ((UnsignedPred == ICmpInst::ICMP_UGE ||
156509467b48Spatrick            UnsignedPred == ICmpInst::ICMP_ULE) &&
156609467b48Spatrick           EqPred == ICmpInst::ICMP_NE && !IsAnd)
156709467b48Spatrick         return ConstantInt::getTrue(UnsignedICmp->getType());
156809467b48Spatrick       // A </> B && (A - B) == 0  <-->  false
156909467b48Spatrick       if ((UnsignedPred == ICmpInst::ICMP_ULT ||
157009467b48Spatrick            UnsignedPred == ICmpInst::ICMP_UGT) &&
157109467b48Spatrick           EqPred == ICmpInst::ICMP_EQ && IsAnd)
157209467b48Spatrick         return ConstantInt::getFalse(UnsignedICmp->getType());
157309467b48Spatrick 
157409467b48Spatrick       // A </> B && (A - B) != 0  <-->  A </> B
157509467b48Spatrick       // A </> B || (A - B) != 0  <-->  (A - B) != 0
157609467b48Spatrick       if (EqPred == ICmpInst::ICMP_NE && (UnsignedPred == ICmpInst::ICMP_ULT ||
157709467b48Spatrick                                           UnsignedPred == ICmpInst::ICMP_UGT))
157809467b48Spatrick         return IsAnd ? UnsignedICmp : ZeroICmp;
157909467b48Spatrick 
158009467b48Spatrick       // A <=/>= B && (A - B) == 0  <-->  (A - B) == 0
158109467b48Spatrick       // A <=/>= B || (A - B) == 0  <-->  A <=/>= B
158209467b48Spatrick       if (EqPred == ICmpInst::ICMP_EQ && (UnsignedPred == ICmpInst::ICMP_ULE ||
158309467b48Spatrick                                           UnsignedPred == ICmpInst::ICMP_UGE))
158409467b48Spatrick         return IsAnd ? ZeroICmp : UnsignedICmp;
158509467b48Spatrick     }
158609467b48Spatrick 
158709467b48Spatrick     // Given  Y = (A - B)
158809467b48Spatrick     //   Y >= A && Y != 0  --> Y >= A  iff B != 0
158909467b48Spatrick     //   Y <  A || Y == 0  --> Y <  A  iff B != 0
159009467b48Spatrick     if (match(UnsignedICmp,
159109467b48Spatrick               m_c_ICmp(UnsignedPred, m_Specific(Y), m_Specific(A)))) {
159209467b48Spatrick       if (UnsignedPred == ICmpInst::ICMP_UGE && IsAnd &&
159309467b48Spatrick           EqPred == ICmpInst::ICMP_NE &&
159409467b48Spatrick           isKnownNonZero(B, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT))
159509467b48Spatrick         return UnsignedICmp;
159609467b48Spatrick       if (UnsignedPred == ICmpInst::ICMP_ULT && !IsAnd &&
159709467b48Spatrick           EqPred == ICmpInst::ICMP_EQ &&
159809467b48Spatrick           isKnownNonZero(B, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT))
159909467b48Spatrick         return UnsignedICmp;
160009467b48Spatrick     }
160109467b48Spatrick   }
160209467b48Spatrick 
160309467b48Spatrick   if (match(UnsignedICmp, m_ICmp(UnsignedPred, m_Value(X), m_Specific(Y))) &&
160409467b48Spatrick       ICmpInst::isUnsigned(UnsignedPred))
160509467b48Spatrick     ;
160609467b48Spatrick   else if (match(UnsignedICmp,
160709467b48Spatrick                  m_ICmp(UnsignedPred, m_Specific(Y), m_Value(X))) &&
160809467b48Spatrick            ICmpInst::isUnsigned(UnsignedPred))
160909467b48Spatrick     UnsignedPred = ICmpInst::getSwappedPredicate(UnsignedPred);
161009467b48Spatrick   else
161109467b48Spatrick     return nullptr;
161209467b48Spatrick 
1613097a140dSpatrick   // X > Y && Y == 0  -->  Y == 0  iff X != 0
1614097a140dSpatrick   // X > Y || Y == 0  -->  X > Y   iff X != 0
1615097a140dSpatrick   if (UnsignedPred == ICmpInst::ICMP_UGT && EqPred == ICmpInst::ICMP_EQ &&
1616097a140dSpatrick       isKnownNonZero(X, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT))
1617097a140dSpatrick     return IsAnd ? ZeroICmp : UnsignedICmp;
161809467b48Spatrick 
161909467b48Spatrick   // X <= Y && Y != 0  -->  X <= Y  iff X != 0
162009467b48Spatrick   // X <= Y || Y != 0  -->  Y != 0  iff X != 0
162109467b48Spatrick   if (UnsignedPred == ICmpInst::ICMP_ULE && EqPred == ICmpInst::ICMP_NE &&
162209467b48Spatrick       isKnownNonZero(X, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT))
162309467b48Spatrick     return IsAnd ? UnsignedICmp : ZeroICmp;
162409467b48Spatrick 
1625097a140dSpatrick   // The transforms below here are expected to be handled more generally with
1626097a140dSpatrick   // simplifyAndOrOfICmpsWithLimitConst() or in InstCombine's
1627097a140dSpatrick   // foldAndOrOfICmpsWithConstEq(). If we are looking to trim optimizer overlap,
1628097a140dSpatrick   // these are candidates for removal.
1629097a140dSpatrick 
1630097a140dSpatrick   // X < Y && Y != 0  -->  X < Y
1631097a140dSpatrick   // X < Y || Y != 0  -->  Y != 0
1632097a140dSpatrick   if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_NE)
1633097a140dSpatrick     return IsAnd ? UnsignedICmp : ZeroICmp;
1634097a140dSpatrick 
163509467b48Spatrick   // X >= Y && Y == 0  -->  Y == 0
163609467b48Spatrick   // X >= Y || Y == 0  -->  X >= Y
163709467b48Spatrick   if (UnsignedPred == ICmpInst::ICMP_UGE && EqPred == ICmpInst::ICMP_EQ)
163809467b48Spatrick     return IsAnd ? ZeroICmp : UnsignedICmp;
163909467b48Spatrick 
164009467b48Spatrick   // X < Y && Y == 0  -->  false
164109467b48Spatrick   if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_EQ &&
164209467b48Spatrick       IsAnd)
164309467b48Spatrick     return getFalse(UnsignedICmp->getType());
164409467b48Spatrick 
164509467b48Spatrick   // X >= Y || Y != 0  -->  true
164609467b48Spatrick   if (UnsignedPred == ICmpInst::ICMP_UGE && EqPred == ICmpInst::ICMP_NE &&
164709467b48Spatrick       !IsAnd)
164809467b48Spatrick     return getTrue(UnsignedICmp->getType());
164909467b48Spatrick 
165009467b48Spatrick   return nullptr;
165109467b48Spatrick }
165209467b48Spatrick 
165309467b48Spatrick /// Test if a pair of compares with a shared operand and 2 constants has an
165409467b48Spatrick /// empty set intersection, full set union, or if one compare is a superset of
165509467b48Spatrick /// the other.
simplifyAndOrOfICmpsWithConstants(ICmpInst * Cmp0,ICmpInst * Cmp1,bool IsAnd)165609467b48Spatrick static Value *simplifyAndOrOfICmpsWithConstants(ICmpInst *Cmp0, ICmpInst *Cmp1,
165709467b48Spatrick                                                 bool IsAnd) {
165809467b48Spatrick   // Look for this pattern: {and/or} (icmp X, C0), (icmp X, C1)).
165909467b48Spatrick   if (Cmp0->getOperand(0) != Cmp1->getOperand(0))
166009467b48Spatrick     return nullptr;
166109467b48Spatrick 
166209467b48Spatrick   const APInt *C0, *C1;
166309467b48Spatrick   if (!match(Cmp0->getOperand(1), m_APInt(C0)) ||
166409467b48Spatrick       !match(Cmp1->getOperand(1), m_APInt(C1)))
166509467b48Spatrick     return nullptr;
166609467b48Spatrick 
166709467b48Spatrick   auto Range0 = ConstantRange::makeExactICmpRegion(Cmp0->getPredicate(), *C0);
166809467b48Spatrick   auto Range1 = ConstantRange::makeExactICmpRegion(Cmp1->getPredicate(), *C1);
166909467b48Spatrick 
167009467b48Spatrick   // For and-of-compares, check if the intersection is empty:
167109467b48Spatrick   // (icmp X, C0) && (icmp X, C1) --> empty set --> false
167209467b48Spatrick   if (IsAnd && Range0.intersectWith(Range1).isEmptySet())
167309467b48Spatrick     return getFalse(Cmp0->getType());
167409467b48Spatrick 
167509467b48Spatrick   // For or-of-compares, check if the union is full:
167609467b48Spatrick   // (icmp X, C0) || (icmp X, C1) --> full set --> true
167709467b48Spatrick   if (!IsAnd && Range0.unionWith(Range1).isFullSet())
167809467b48Spatrick     return getTrue(Cmp0->getType());
167909467b48Spatrick 
168009467b48Spatrick   // Is one range a superset of the other?
168109467b48Spatrick   // If this is and-of-compares, take the smaller set:
168209467b48Spatrick   // (icmp sgt X, 4) && (icmp sgt X, 42) --> icmp sgt X, 42
168309467b48Spatrick   // If this is or-of-compares, take the larger set:
168409467b48Spatrick   // (icmp sgt X, 4) || (icmp sgt X, 42) --> icmp sgt X, 4
168509467b48Spatrick   if (Range0.contains(Range1))
168609467b48Spatrick     return IsAnd ? Cmp1 : Cmp0;
168709467b48Spatrick   if (Range1.contains(Range0))
168809467b48Spatrick     return IsAnd ? Cmp0 : Cmp1;
168909467b48Spatrick 
169009467b48Spatrick   return nullptr;
169109467b48Spatrick }
169209467b48Spatrick 
simplifyAndOrOfICmpsWithZero(ICmpInst * Cmp0,ICmpInst * Cmp1,bool IsAnd)169309467b48Spatrick static Value *simplifyAndOrOfICmpsWithZero(ICmpInst *Cmp0, ICmpInst *Cmp1,
169409467b48Spatrick                                            bool IsAnd) {
169509467b48Spatrick   ICmpInst::Predicate P0 = Cmp0->getPredicate(), P1 = Cmp1->getPredicate();
169609467b48Spatrick   if (!match(Cmp0->getOperand(1), m_Zero()) ||
169709467b48Spatrick       !match(Cmp1->getOperand(1), m_Zero()) || P0 != P1)
169809467b48Spatrick     return nullptr;
169909467b48Spatrick 
170009467b48Spatrick   if ((IsAnd && P0 != ICmpInst::ICMP_NE) || (!IsAnd && P1 != ICmpInst::ICMP_EQ))
170109467b48Spatrick     return nullptr;
170209467b48Spatrick 
170309467b48Spatrick   // We have either "(X == 0 || Y == 0)" or "(X != 0 && Y != 0)".
170409467b48Spatrick   Value *X = Cmp0->getOperand(0);
170509467b48Spatrick   Value *Y = Cmp1->getOperand(0);
170609467b48Spatrick 
170709467b48Spatrick   // If one of the compares is a masked version of a (not) null check, then
170809467b48Spatrick   // that compare implies the other, so we eliminate the other. Optionally, look
170909467b48Spatrick   // through a pointer-to-int cast to match a null check of a pointer type.
171009467b48Spatrick 
171109467b48Spatrick   // (X == 0) || (([ptrtoint] X & ?) == 0) --> ([ptrtoint] X & ?) == 0
171209467b48Spatrick   // (X == 0) || ((? & [ptrtoint] X) == 0) --> (? & [ptrtoint] X) == 0
171309467b48Spatrick   // (X != 0) && (([ptrtoint] X & ?) != 0) --> ([ptrtoint] X & ?) != 0
171409467b48Spatrick   // (X != 0) && ((? & [ptrtoint] X) != 0) --> (? & [ptrtoint] X) != 0
171509467b48Spatrick   if (match(Y, m_c_And(m_Specific(X), m_Value())) ||
171609467b48Spatrick       match(Y, m_c_And(m_PtrToInt(m_Specific(X)), m_Value())))
171709467b48Spatrick     return Cmp1;
171809467b48Spatrick 
171909467b48Spatrick   // (([ptrtoint] Y & ?) == 0) || (Y == 0) --> ([ptrtoint] Y & ?) == 0
172009467b48Spatrick   // ((? & [ptrtoint] Y) == 0) || (Y == 0) --> (? & [ptrtoint] Y) == 0
172109467b48Spatrick   // (([ptrtoint] Y & ?) != 0) && (Y != 0) --> ([ptrtoint] Y & ?) != 0
172209467b48Spatrick   // ((? & [ptrtoint] Y) != 0) && (Y != 0) --> (? & [ptrtoint] Y) != 0
172309467b48Spatrick   if (match(X, m_c_And(m_Specific(Y), m_Value())) ||
172409467b48Spatrick       match(X, m_c_And(m_PtrToInt(m_Specific(Y)), m_Value())))
172509467b48Spatrick     return Cmp0;
172609467b48Spatrick 
172709467b48Spatrick   return nullptr;
172809467b48Spatrick }
172909467b48Spatrick 
simplifyAndOfICmpsWithAdd(ICmpInst * Op0,ICmpInst * Op1,const InstrInfoQuery & IIQ)173009467b48Spatrick static Value *simplifyAndOfICmpsWithAdd(ICmpInst *Op0, ICmpInst *Op1,
173109467b48Spatrick                                         const InstrInfoQuery &IIQ) {
173209467b48Spatrick   // (icmp (add V, C0), C1) & (icmp V, C0)
173309467b48Spatrick   ICmpInst::Predicate Pred0, Pred1;
173409467b48Spatrick   const APInt *C0, *C1;
173509467b48Spatrick   Value *V;
173609467b48Spatrick   if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
173709467b48Spatrick     return nullptr;
173809467b48Spatrick 
173909467b48Spatrick   if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
174009467b48Spatrick     return nullptr;
174109467b48Spatrick 
174209467b48Spatrick   auto *AddInst = cast<OverflowingBinaryOperator>(Op0->getOperand(0));
174309467b48Spatrick   if (AddInst->getOperand(1) != Op1->getOperand(1))
174409467b48Spatrick     return nullptr;
174509467b48Spatrick 
174609467b48Spatrick   Type *ITy = Op0->getType();
1747*d415bd75Srobert   bool IsNSW = IIQ.hasNoSignedWrap(AddInst);
1748*d415bd75Srobert   bool IsNUW = IIQ.hasNoUnsignedWrap(AddInst);
174909467b48Spatrick 
175009467b48Spatrick   const APInt Delta = *C1 - *C0;
175109467b48Spatrick   if (C0->isStrictlyPositive()) {
175209467b48Spatrick     if (Delta == 2) {
175309467b48Spatrick       if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_SGT)
175409467b48Spatrick         return getFalse(ITy);
1755*d415bd75Srobert       if (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT && IsNSW)
175609467b48Spatrick         return getFalse(ITy);
175709467b48Spatrick     }
175809467b48Spatrick     if (Delta == 1) {
175909467b48Spatrick       if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_SGT)
176009467b48Spatrick         return getFalse(ITy);
1761*d415bd75Srobert       if (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGT && IsNSW)
176209467b48Spatrick         return getFalse(ITy);
176309467b48Spatrick     }
176409467b48Spatrick   }
1765*d415bd75Srobert   if (C0->getBoolValue() && IsNUW) {
176609467b48Spatrick     if (Delta == 2)
176709467b48Spatrick       if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT)
176809467b48Spatrick         return getFalse(ITy);
176909467b48Spatrick     if (Delta == 1)
177009467b48Spatrick       if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGT)
177109467b48Spatrick         return getFalse(ITy);
177209467b48Spatrick   }
177309467b48Spatrick 
177409467b48Spatrick   return nullptr;
177509467b48Spatrick }
177609467b48Spatrick 
1777097a140dSpatrick /// Try to eliminate compares with signed or unsigned min/max constants.
simplifyAndOrOfICmpsWithLimitConst(ICmpInst * Cmp0,ICmpInst * Cmp1,bool IsAnd)1778097a140dSpatrick static Value *simplifyAndOrOfICmpsWithLimitConst(ICmpInst *Cmp0, ICmpInst *Cmp1,
1779097a140dSpatrick                                                  bool IsAnd) {
1780097a140dSpatrick   // Canonicalize an equality compare as Cmp0.
1781097a140dSpatrick   if (Cmp1->isEquality())
1782097a140dSpatrick     std::swap(Cmp0, Cmp1);
1783097a140dSpatrick   if (!Cmp0->isEquality())
1784097a140dSpatrick     return nullptr;
1785097a140dSpatrick 
1786097a140dSpatrick   // The non-equality compare must include a common operand (X). Canonicalize
1787097a140dSpatrick   // the common operand as operand 0 (the predicate is swapped if the common
1788097a140dSpatrick   // operand was operand 1).
1789097a140dSpatrick   ICmpInst::Predicate Pred0 = Cmp0->getPredicate();
1790097a140dSpatrick   Value *X = Cmp0->getOperand(0);
1791097a140dSpatrick   ICmpInst::Predicate Pred1;
179273471bf0Spatrick   bool HasNotOp = match(Cmp1, m_c_ICmp(Pred1, m_Not(m_Specific(X)), m_Value()));
179373471bf0Spatrick   if (!HasNotOp && !match(Cmp1, m_c_ICmp(Pred1, m_Specific(X), m_Value())))
179473471bf0Spatrick     return nullptr;
179573471bf0Spatrick   if (ICmpInst::isEquality(Pred1))
179673471bf0Spatrick     return nullptr;
179773471bf0Spatrick 
179873471bf0Spatrick   // The equality compare must be against a constant. Flip bits if we matched
179973471bf0Spatrick   // a bitwise not. Convert a null pointer constant to an integer zero value.
180073471bf0Spatrick   APInt MinMaxC;
180173471bf0Spatrick   const APInt *C;
180273471bf0Spatrick   if (match(Cmp0->getOperand(1), m_APInt(C)))
180373471bf0Spatrick     MinMaxC = HasNotOp ? ~*C : *C;
180473471bf0Spatrick   else if (isa<ConstantPointerNull>(Cmp0->getOperand(1)))
1805*d415bd75Srobert     MinMaxC = APInt::getZero(8);
180673471bf0Spatrick   else
1807097a140dSpatrick     return nullptr;
1808097a140dSpatrick 
1809097a140dSpatrick   // DeMorganize if this is 'or': P0 || P1 --> !P0 && !P1.
1810097a140dSpatrick   if (!IsAnd) {
1811097a140dSpatrick     Pred0 = ICmpInst::getInversePredicate(Pred0);
1812097a140dSpatrick     Pred1 = ICmpInst::getInversePredicate(Pred1);
1813097a140dSpatrick   }
1814097a140dSpatrick 
1815097a140dSpatrick   // Normalize to unsigned compare and unsigned min/max value.
1816097a140dSpatrick   // Example for 8-bit: -128 + 128 -> 0; 127 + 128 -> 255
1817097a140dSpatrick   if (ICmpInst::isSigned(Pred1)) {
1818097a140dSpatrick     Pred1 = ICmpInst::getUnsignedPredicate(Pred1);
1819097a140dSpatrick     MinMaxC += APInt::getSignedMinValue(MinMaxC.getBitWidth());
1820097a140dSpatrick   }
1821097a140dSpatrick 
1822097a140dSpatrick   // (X != MAX) && (X < Y) --> X < Y
1823097a140dSpatrick   // (X == MAX) || (X >= Y) --> X >= Y
1824097a140dSpatrick   if (MinMaxC.isMaxValue())
1825097a140dSpatrick     if (Pred0 == ICmpInst::ICMP_NE && Pred1 == ICmpInst::ICMP_ULT)
1826097a140dSpatrick       return Cmp1;
1827097a140dSpatrick 
1828097a140dSpatrick   // (X != MIN) && (X > Y) -->  X > Y
1829097a140dSpatrick   // (X == MIN) || (X <= Y) --> X <= Y
1830097a140dSpatrick   if (MinMaxC.isMinValue())
1831097a140dSpatrick     if (Pred0 == ICmpInst::ICMP_NE && Pred1 == ICmpInst::ICMP_UGT)
1832097a140dSpatrick       return Cmp1;
1833097a140dSpatrick 
1834097a140dSpatrick   return nullptr;
1835097a140dSpatrick }
1836097a140dSpatrick 
1837*d415bd75Srobert /// Try to simplify and/or of icmp with ctpop intrinsic.
simplifyAndOrOfICmpsWithCtpop(ICmpInst * Cmp0,ICmpInst * Cmp1,bool IsAnd)1838*d415bd75Srobert static Value *simplifyAndOrOfICmpsWithCtpop(ICmpInst *Cmp0, ICmpInst *Cmp1,
1839*d415bd75Srobert                                             bool IsAnd) {
1840*d415bd75Srobert   ICmpInst::Predicate Pred0, Pred1;
1841*d415bd75Srobert   Value *X;
1842*d415bd75Srobert   const APInt *C;
1843*d415bd75Srobert   if (!match(Cmp0, m_ICmp(Pred0, m_Intrinsic<Intrinsic::ctpop>(m_Value(X)),
1844*d415bd75Srobert                           m_APInt(C))) ||
1845*d415bd75Srobert       !match(Cmp1, m_ICmp(Pred1, m_Specific(X), m_ZeroInt())) || C->isZero())
1846*d415bd75Srobert     return nullptr;
1847*d415bd75Srobert 
1848*d415bd75Srobert   // (ctpop(X) == C) || (X != 0) --> X != 0 where C > 0
1849*d415bd75Srobert   if (!IsAnd && Pred0 == ICmpInst::ICMP_EQ && Pred1 == ICmpInst::ICMP_NE)
1850*d415bd75Srobert     return Cmp1;
1851*d415bd75Srobert   // (ctpop(X) != C) && (X == 0) --> X == 0 where C > 0
1852*d415bd75Srobert   if (IsAnd && Pred0 == ICmpInst::ICMP_NE && Pred1 == ICmpInst::ICMP_EQ)
1853*d415bd75Srobert     return Cmp1;
1854*d415bd75Srobert 
1855*d415bd75Srobert   return nullptr;
1856*d415bd75Srobert }
1857*d415bd75Srobert 
simplifyAndOfICmps(ICmpInst * Op0,ICmpInst * Op1,const SimplifyQuery & Q)185809467b48Spatrick static Value *simplifyAndOfICmps(ICmpInst *Op0, ICmpInst *Op1,
185909467b48Spatrick                                  const SimplifyQuery &Q) {
186009467b48Spatrick   if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/true, Q))
186109467b48Spatrick     return X;
186209467b48Spatrick   if (Value *X = simplifyUnsignedRangeCheck(Op1, Op0, /*IsAnd=*/true, Q))
186309467b48Spatrick     return X;
186409467b48Spatrick 
186509467b48Spatrick   if (Value *X = simplifyAndOrOfICmpsWithConstants(Op0, Op1, true))
186609467b48Spatrick     return X;
186709467b48Spatrick 
1868097a140dSpatrick   if (Value *X = simplifyAndOrOfICmpsWithLimitConst(Op0, Op1, true))
1869097a140dSpatrick     return X;
1870097a140dSpatrick 
187109467b48Spatrick   if (Value *X = simplifyAndOrOfICmpsWithZero(Op0, Op1, true))
187209467b48Spatrick     return X;
187309467b48Spatrick 
1874*d415bd75Srobert   if (Value *X = simplifyAndOrOfICmpsWithCtpop(Op0, Op1, true))
1875*d415bd75Srobert     return X;
1876*d415bd75Srobert   if (Value *X = simplifyAndOrOfICmpsWithCtpop(Op1, Op0, true))
1877*d415bd75Srobert     return X;
1878*d415bd75Srobert 
187909467b48Spatrick   if (Value *X = simplifyAndOfICmpsWithAdd(Op0, Op1, Q.IIQ))
188009467b48Spatrick     return X;
188109467b48Spatrick   if (Value *X = simplifyAndOfICmpsWithAdd(Op1, Op0, Q.IIQ))
188209467b48Spatrick     return X;
188309467b48Spatrick 
188409467b48Spatrick   return nullptr;
188509467b48Spatrick }
188609467b48Spatrick 
simplifyOrOfICmpsWithAdd(ICmpInst * Op0,ICmpInst * Op1,const InstrInfoQuery & IIQ)188709467b48Spatrick static Value *simplifyOrOfICmpsWithAdd(ICmpInst *Op0, ICmpInst *Op1,
188809467b48Spatrick                                        const InstrInfoQuery &IIQ) {
188909467b48Spatrick   // (icmp (add V, C0), C1) | (icmp V, C0)
189009467b48Spatrick   ICmpInst::Predicate Pred0, Pred1;
189109467b48Spatrick   const APInt *C0, *C1;
189209467b48Spatrick   Value *V;
189309467b48Spatrick   if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
189409467b48Spatrick     return nullptr;
189509467b48Spatrick 
189609467b48Spatrick   if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
189709467b48Spatrick     return nullptr;
189809467b48Spatrick 
189909467b48Spatrick   auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
190009467b48Spatrick   if (AddInst->getOperand(1) != Op1->getOperand(1))
190109467b48Spatrick     return nullptr;
190209467b48Spatrick 
190309467b48Spatrick   Type *ITy = Op0->getType();
1904*d415bd75Srobert   bool IsNSW = IIQ.hasNoSignedWrap(AddInst);
1905*d415bd75Srobert   bool IsNUW = IIQ.hasNoUnsignedWrap(AddInst);
190609467b48Spatrick 
190709467b48Spatrick   const APInt Delta = *C1 - *C0;
190809467b48Spatrick   if (C0->isStrictlyPositive()) {
190909467b48Spatrick     if (Delta == 2) {
191009467b48Spatrick       if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_SLE)
191109467b48Spatrick         return getTrue(ITy);
1912*d415bd75Srobert       if (Pred0 == ICmpInst::ICMP_SGE && Pred1 == ICmpInst::ICMP_SLE && IsNSW)
191309467b48Spatrick         return getTrue(ITy);
191409467b48Spatrick     }
191509467b48Spatrick     if (Delta == 1) {
191609467b48Spatrick       if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_SLE)
191709467b48Spatrick         return getTrue(ITy);
1918*d415bd75Srobert       if (Pred0 == ICmpInst::ICMP_SGT && Pred1 == ICmpInst::ICMP_SLE && IsNSW)
191909467b48Spatrick         return getTrue(ITy);
192009467b48Spatrick     }
192109467b48Spatrick   }
1922*d415bd75Srobert   if (C0->getBoolValue() && IsNUW) {
192309467b48Spatrick     if (Delta == 2)
192409467b48Spatrick       if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_ULE)
192509467b48Spatrick         return getTrue(ITy);
192609467b48Spatrick     if (Delta == 1)
192709467b48Spatrick       if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_ULE)
192809467b48Spatrick         return getTrue(ITy);
192909467b48Spatrick   }
193009467b48Spatrick 
193109467b48Spatrick   return nullptr;
193209467b48Spatrick }
193309467b48Spatrick 
simplifyOrOfICmps(ICmpInst * Op0,ICmpInst * Op1,const SimplifyQuery & Q)193409467b48Spatrick static Value *simplifyOrOfICmps(ICmpInst *Op0, ICmpInst *Op1,
193509467b48Spatrick                                 const SimplifyQuery &Q) {
193609467b48Spatrick   if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/false, Q))
193709467b48Spatrick     return X;
193809467b48Spatrick   if (Value *X = simplifyUnsignedRangeCheck(Op1, Op0, /*IsAnd=*/false, Q))
193909467b48Spatrick     return X;
194009467b48Spatrick 
194109467b48Spatrick   if (Value *X = simplifyAndOrOfICmpsWithConstants(Op0, Op1, false))
194209467b48Spatrick     return X;
194309467b48Spatrick 
1944097a140dSpatrick   if (Value *X = simplifyAndOrOfICmpsWithLimitConst(Op0, Op1, false))
1945097a140dSpatrick     return X;
1946097a140dSpatrick 
194709467b48Spatrick   if (Value *X = simplifyAndOrOfICmpsWithZero(Op0, Op1, false))
194809467b48Spatrick     return X;
194909467b48Spatrick 
1950*d415bd75Srobert   if (Value *X = simplifyAndOrOfICmpsWithCtpop(Op0, Op1, false))
1951*d415bd75Srobert     return X;
1952*d415bd75Srobert   if (Value *X = simplifyAndOrOfICmpsWithCtpop(Op1, Op0, false))
1953*d415bd75Srobert     return X;
1954*d415bd75Srobert 
195509467b48Spatrick   if (Value *X = simplifyOrOfICmpsWithAdd(Op0, Op1, Q.IIQ))
195609467b48Spatrick     return X;
195709467b48Spatrick   if (Value *X = simplifyOrOfICmpsWithAdd(Op1, Op0, Q.IIQ))
195809467b48Spatrick     return X;
195909467b48Spatrick 
196009467b48Spatrick   return nullptr;
196109467b48Spatrick }
196209467b48Spatrick 
simplifyAndOrOfFCmps(const TargetLibraryInfo * TLI,FCmpInst * LHS,FCmpInst * RHS,bool IsAnd)1963*d415bd75Srobert static Value *simplifyAndOrOfFCmps(const TargetLibraryInfo *TLI, FCmpInst *LHS,
1964*d415bd75Srobert                                    FCmpInst *RHS, bool IsAnd) {
196509467b48Spatrick   Value *LHS0 = LHS->getOperand(0), *LHS1 = LHS->getOperand(1);
196609467b48Spatrick   Value *RHS0 = RHS->getOperand(0), *RHS1 = RHS->getOperand(1);
196709467b48Spatrick   if (LHS0->getType() != RHS0->getType())
196809467b48Spatrick     return nullptr;
196909467b48Spatrick 
197009467b48Spatrick   FCmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
197109467b48Spatrick   if ((PredL == FCmpInst::FCMP_ORD && PredR == FCmpInst::FCMP_ORD && IsAnd) ||
197209467b48Spatrick       (PredL == FCmpInst::FCMP_UNO && PredR == FCmpInst::FCMP_UNO && !IsAnd)) {
197309467b48Spatrick     // (fcmp ord NNAN, X) & (fcmp ord X, Y) --> fcmp ord X, Y
197409467b48Spatrick     // (fcmp ord NNAN, X) & (fcmp ord Y, X) --> fcmp ord Y, X
197509467b48Spatrick     // (fcmp ord X, NNAN) & (fcmp ord X, Y) --> fcmp ord X, Y
197609467b48Spatrick     // (fcmp ord X, NNAN) & (fcmp ord Y, X) --> fcmp ord Y, X
197709467b48Spatrick     // (fcmp uno NNAN, X) | (fcmp uno X, Y) --> fcmp uno X, Y
197809467b48Spatrick     // (fcmp uno NNAN, X) | (fcmp uno Y, X) --> fcmp uno Y, X
197909467b48Spatrick     // (fcmp uno X, NNAN) | (fcmp uno X, Y) --> fcmp uno X, Y
198009467b48Spatrick     // (fcmp uno X, NNAN) | (fcmp uno Y, X) --> fcmp uno Y, X
198109467b48Spatrick     if ((isKnownNeverNaN(LHS0, TLI) && (LHS1 == RHS0 || LHS1 == RHS1)) ||
198209467b48Spatrick         (isKnownNeverNaN(LHS1, TLI) && (LHS0 == RHS0 || LHS0 == RHS1)))
198309467b48Spatrick       return RHS;
198409467b48Spatrick 
198509467b48Spatrick     // (fcmp ord X, Y) & (fcmp ord NNAN, X) --> fcmp ord X, Y
198609467b48Spatrick     // (fcmp ord Y, X) & (fcmp ord NNAN, X) --> fcmp ord Y, X
198709467b48Spatrick     // (fcmp ord X, Y) & (fcmp ord X, NNAN) --> fcmp ord X, Y
198809467b48Spatrick     // (fcmp ord Y, X) & (fcmp ord X, NNAN) --> fcmp ord Y, X
198909467b48Spatrick     // (fcmp uno X, Y) | (fcmp uno NNAN, X) --> fcmp uno X, Y
199009467b48Spatrick     // (fcmp uno Y, X) | (fcmp uno NNAN, X) --> fcmp uno Y, X
199109467b48Spatrick     // (fcmp uno X, Y) | (fcmp uno X, NNAN) --> fcmp uno X, Y
199209467b48Spatrick     // (fcmp uno Y, X) | (fcmp uno X, NNAN) --> fcmp uno Y, X
199309467b48Spatrick     if ((isKnownNeverNaN(RHS0, TLI) && (RHS1 == LHS0 || RHS1 == LHS1)) ||
199409467b48Spatrick         (isKnownNeverNaN(RHS1, TLI) && (RHS0 == LHS0 || RHS0 == LHS1)))
199509467b48Spatrick       return LHS;
199609467b48Spatrick   }
199709467b48Spatrick 
199809467b48Spatrick   return nullptr;
199909467b48Spatrick }
200009467b48Spatrick 
simplifyAndOrOfCmps(const SimplifyQuery & Q,Value * Op0,Value * Op1,bool IsAnd)2001*d415bd75Srobert static Value *simplifyAndOrOfCmps(const SimplifyQuery &Q, Value *Op0,
2002*d415bd75Srobert                                   Value *Op1, bool IsAnd) {
200309467b48Spatrick   // Look through casts of the 'and' operands to find compares.
200409467b48Spatrick   auto *Cast0 = dyn_cast<CastInst>(Op0);
200509467b48Spatrick   auto *Cast1 = dyn_cast<CastInst>(Op1);
200609467b48Spatrick   if (Cast0 && Cast1 && Cast0->getOpcode() == Cast1->getOpcode() &&
200709467b48Spatrick       Cast0->getSrcTy() == Cast1->getSrcTy()) {
200809467b48Spatrick     Op0 = Cast0->getOperand(0);
200909467b48Spatrick     Op1 = Cast1->getOperand(0);
201009467b48Spatrick   }
201109467b48Spatrick 
201209467b48Spatrick   Value *V = nullptr;
201309467b48Spatrick   auto *ICmp0 = dyn_cast<ICmpInst>(Op0);
201409467b48Spatrick   auto *ICmp1 = dyn_cast<ICmpInst>(Op1);
201509467b48Spatrick   if (ICmp0 && ICmp1)
201609467b48Spatrick     V = IsAnd ? simplifyAndOfICmps(ICmp0, ICmp1, Q)
201709467b48Spatrick               : simplifyOrOfICmps(ICmp0, ICmp1, Q);
201809467b48Spatrick 
201909467b48Spatrick   auto *FCmp0 = dyn_cast<FCmpInst>(Op0);
202009467b48Spatrick   auto *FCmp1 = dyn_cast<FCmpInst>(Op1);
202109467b48Spatrick   if (FCmp0 && FCmp1)
202209467b48Spatrick     V = simplifyAndOrOfFCmps(Q.TLI, FCmp0, FCmp1, IsAnd);
202309467b48Spatrick 
202409467b48Spatrick   if (!V)
202509467b48Spatrick     return nullptr;
202609467b48Spatrick   if (!Cast0)
202709467b48Spatrick     return V;
202809467b48Spatrick 
202909467b48Spatrick   // If we looked through casts, we can only handle a constant simplification
203009467b48Spatrick   // because we are not allowed to create a cast instruction here.
203109467b48Spatrick   if (auto *C = dyn_cast<Constant>(V))
203209467b48Spatrick     return ConstantExpr::getCast(Cast0->getOpcode(), C, Cast0->getType());
203309467b48Spatrick 
203409467b48Spatrick   return nullptr;
203509467b48Spatrick }
203609467b48Spatrick 
203773471bf0Spatrick /// Given a bitwise logic op, check if the operands are add/sub with a common
203873471bf0Spatrick /// source value and inverted constant (identity: C - X -> ~(X + ~C)).
simplifyLogicOfAddSub(Value * Op0,Value * Op1,Instruction::BinaryOps Opcode)203973471bf0Spatrick static Value *simplifyLogicOfAddSub(Value *Op0, Value *Op1,
204073471bf0Spatrick                                     Instruction::BinaryOps Opcode) {
204173471bf0Spatrick   assert(Op0->getType() == Op1->getType() && "Mismatched binop types");
204273471bf0Spatrick   assert(BinaryOperator::isBitwiseLogicOp(Opcode) && "Expected logic op");
204309467b48Spatrick   Value *X;
204473471bf0Spatrick   Constant *C1, *C2;
204573471bf0Spatrick   if ((match(Op0, m_Add(m_Value(X), m_Constant(C1))) &&
204673471bf0Spatrick        match(Op1, m_Sub(m_Constant(C2), m_Specific(X)))) ||
204773471bf0Spatrick       (match(Op1, m_Add(m_Value(X), m_Constant(C1))) &&
204873471bf0Spatrick        match(Op0, m_Sub(m_Constant(C2), m_Specific(X))))) {
204973471bf0Spatrick     if (ConstantExpr::getNot(C1) == C2) {
205073471bf0Spatrick       // (X + C) & (~C - X) --> (X + C) & ~(X + C) --> 0
205173471bf0Spatrick       // (X + C) | (~C - X) --> (X + C) | ~(X + C) --> -1
205273471bf0Spatrick       // (X + C) ^ (~C - X) --> (X + C) ^ ~(X + C) --> -1
205373471bf0Spatrick       Type *Ty = Op0->getType();
205473471bf0Spatrick       return Opcode == Instruction::And ? ConstantInt::getNullValue(Ty)
205573471bf0Spatrick                                         : ConstantInt::getAllOnesValue(Ty);
205609467b48Spatrick     }
205773471bf0Spatrick   }
205809467b48Spatrick   return nullptr;
205909467b48Spatrick }
206009467b48Spatrick 
206109467b48Spatrick /// Given operands for an And, see if we can fold the result.
206209467b48Spatrick /// If not, this returns null.
simplifyAndInst(Value * Op0,Value * Op1,const SimplifyQuery & Q,unsigned MaxRecurse)2063*d415bd75Srobert static Value *simplifyAndInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
206409467b48Spatrick                               unsigned MaxRecurse) {
206509467b48Spatrick   if (Constant *C = foldOrCommuteConstant(Instruction::And, Op0, Op1, Q))
206609467b48Spatrick     return C;
206709467b48Spatrick 
206873471bf0Spatrick   // X & poison -> poison
206973471bf0Spatrick   if (isa<PoisonValue>(Op1))
207073471bf0Spatrick     return Op1;
207173471bf0Spatrick 
207209467b48Spatrick   // X & undef -> 0
207373471bf0Spatrick   if (Q.isUndefValue(Op1))
207409467b48Spatrick     return Constant::getNullValue(Op0->getType());
207509467b48Spatrick 
207609467b48Spatrick   // X & X = X
207709467b48Spatrick   if (Op0 == Op1)
207809467b48Spatrick     return Op0;
207909467b48Spatrick 
208009467b48Spatrick   // X & 0 = 0
208109467b48Spatrick   if (match(Op1, m_Zero()))
208209467b48Spatrick     return Constant::getNullValue(Op0->getType());
208309467b48Spatrick 
208409467b48Spatrick   // X & -1 = X
208509467b48Spatrick   if (match(Op1, m_AllOnes()))
208609467b48Spatrick     return Op0;
208709467b48Spatrick 
208809467b48Spatrick   // A & ~A  =  ~A & A  =  0
2089*d415bd75Srobert   if (match(Op0, m_Not(m_Specific(Op1))) || match(Op1, m_Not(m_Specific(Op0))))
209009467b48Spatrick     return Constant::getNullValue(Op0->getType());
209109467b48Spatrick 
209209467b48Spatrick   // (A | ?) & A = A
209309467b48Spatrick   if (match(Op0, m_c_Or(m_Specific(Op1), m_Value())))
209409467b48Spatrick     return Op1;
209509467b48Spatrick 
209609467b48Spatrick   // A & (A | ?) = A
209709467b48Spatrick   if (match(Op1, m_c_Or(m_Specific(Op0), m_Value())))
209809467b48Spatrick     return Op0;
209909467b48Spatrick 
2100*d415bd75Srobert   // (X | Y) & (X | ~Y) --> X (commuted 8 ways)
2101*d415bd75Srobert   Value *X, *Y;
2102*d415bd75Srobert   if (match(Op0, m_c_Or(m_Value(X), m_Not(m_Value(Y)))) &&
2103*d415bd75Srobert       match(Op1, m_c_Or(m_Deferred(X), m_Deferred(Y))))
2104*d415bd75Srobert     return X;
2105*d415bd75Srobert   if (match(Op1, m_c_Or(m_Value(X), m_Not(m_Value(Y)))) &&
2106*d415bd75Srobert       match(Op0, m_c_Or(m_Deferred(X), m_Deferred(Y))))
2107*d415bd75Srobert     return X;
2108*d415bd75Srobert 
210973471bf0Spatrick   if (Value *V = simplifyLogicOfAddSub(Op0, Op1, Instruction::And))
211073471bf0Spatrick     return V;
211173471bf0Spatrick 
211209467b48Spatrick   // A mask that only clears known zeros of a shifted value is a no-op.
211309467b48Spatrick   const APInt *Mask;
211409467b48Spatrick   const APInt *ShAmt;
211509467b48Spatrick   if (match(Op1, m_APInt(Mask))) {
211609467b48Spatrick     // If all bits in the inverted and shifted mask are clear:
211709467b48Spatrick     // and (shl X, ShAmt), Mask --> shl X, ShAmt
211809467b48Spatrick     if (match(Op0, m_Shl(m_Value(X), m_APInt(ShAmt))) &&
2119*d415bd75Srobert         (~(*Mask)).lshr(*ShAmt).isZero())
212009467b48Spatrick       return Op0;
212109467b48Spatrick 
212209467b48Spatrick     // If all bits in the inverted and shifted mask are clear:
212309467b48Spatrick     // and (lshr X, ShAmt), Mask --> lshr X, ShAmt
212409467b48Spatrick     if (match(Op0, m_LShr(m_Value(X), m_APInt(ShAmt))) &&
2125*d415bd75Srobert         (~(*Mask)).shl(*ShAmt).isZero())
212609467b48Spatrick       return Op0;
212709467b48Spatrick   }
212809467b48Spatrick 
212909467b48Spatrick   // If we have a multiplication overflow check that is being 'and'ed with a
213009467b48Spatrick   // check that one of the multipliers is not zero, we can omit the 'and', and
213109467b48Spatrick   // only keep the overflow check.
213273471bf0Spatrick   if (isCheckForZeroAndMulWithOverflow(Op0, Op1, true))
213373471bf0Spatrick     return Op1;
213473471bf0Spatrick   if (isCheckForZeroAndMulWithOverflow(Op1, Op0, true))
213573471bf0Spatrick     return Op0;
213609467b48Spatrick 
213709467b48Spatrick   // A & (-A) = A if A is a power of two or zero.
213809467b48Spatrick   if (match(Op0, m_Neg(m_Specific(Op1))) ||
213909467b48Spatrick       match(Op1, m_Neg(m_Specific(Op0)))) {
214009467b48Spatrick     if (isKnownToBeAPowerOfTwo(Op0, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
214109467b48Spatrick                                Q.DT))
214209467b48Spatrick       return Op0;
214309467b48Spatrick     if (isKnownToBeAPowerOfTwo(Op1, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
214409467b48Spatrick                                Q.DT))
214509467b48Spatrick       return Op1;
214609467b48Spatrick   }
214709467b48Spatrick 
214809467b48Spatrick   // This is a similar pattern used for checking if a value is a power-of-2:
214909467b48Spatrick   // (A - 1) & A --> 0 (if A is a power-of-2 or 0)
215009467b48Spatrick   // A & (A - 1) --> 0 (if A is a power-of-2 or 0)
215109467b48Spatrick   if (match(Op0, m_Add(m_Specific(Op1), m_AllOnes())) &&
215209467b48Spatrick       isKnownToBeAPowerOfTwo(Op1, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI, Q.DT))
215309467b48Spatrick     return Constant::getNullValue(Op1->getType());
215409467b48Spatrick   if (match(Op1, m_Add(m_Specific(Op0), m_AllOnes())) &&
215509467b48Spatrick       isKnownToBeAPowerOfTwo(Op0, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI, Q.DT))
215609467b48Spatrick     return Constant::getNullValue(Op0->getType());
215709467b48Spatrick 
215809467b48Spatrick   if (Value *V = simplifyAndOrOfCmps(Q, Op0, Op1, true))
215909467b48Spatrick     return V;
216009467b48Spatrick 
216109467b48Spatrick   // Try some generic simplifications for associative operations.
2162*d415bd75Srobert   if (Value *V =
2163*d415bd75Srobert           simplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q, MaxRecurse))
216409467b48Spatrick     return V;
216509467b48Spatrick 
216609467b48Spatrick   // And distributes over Or.  Try some generic simplifications based on this.
216773471bf0Spatrick   if (Value *V = expandCommutativeBinOp(Instruction::And, Op0, Op1,
216873471bf0Spatrick                                         Instruction::Or, Q, MaxRecurse))
216909467b48Spatrick     return V;
217009467b48Spatrick 
217109467b48Spatrick   // And distributes over Xor.  Try some generic simplifications based on this.
217273471bf0Spatrick   if (Value *V = expandCommutativeBinOp(Instruction::And, Op0, Op1,
217373471bf0Spatrick                                         Instruction::Xor, Q, MaxRecurse))
217409467b48Spatrick     return V;
217509467b48Spatrick 
217673471bf0Spatrick   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) {
217773471bf0Spatrick     if (Op0->getType()->isIntOrIntVectorTy(1)) {
217873471bf0Spatrick       // A & (A && B) -> A && B
217973471bf0Spatrick       if (match(Op1, m_Select(m_Specific(Op0), m_Value(), m_Zero())))
218073471bf0Spatrick         return Op1;
218173471bf0Spatrick       else if (match(Op0, m_Select(m_Specific(Op1), m_Value(), m_Zero())))
218273471bf0Spatrick         return Op0;
218373471bf0Spatrick     }
218473471bf0Spatrick     // If the operation is with the result of a select instruction, check
218573471bf0Spatrick     // whether operating on either branch of the select always yields the same
218673471bf0Spatrick     // value.
2187*d415bd75Srobert     if (Value *V =
2188*d415bd75Srobert             threadBinOpOverSelect(Instruction::And, Op0, Op1, Q, MaxRecurse))
218909467b48Spatrick       return V;
219073471bf0Spatrick   }
219109467b48Spatrick 
219209467b48Spatrick   // If the operation is with the result of a phi instruction, check whether
219309467b48Spatrick   // operating on all incoming values of the phi always yields the same value.
219409467b48Spatrick   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
2195*d415bd75Srobert     if (Value *V =
2196*d415bd75Srobert             threadBinOpOverPHI(Instruction::And, Op0, Op1, Q, MaxRecurse))
219709467b48Spatrick       return V;
219809467b48Spatrick 
219909467b48Spatrick   // Assuming the effective width of Y is not larger than A, i.e. all bits
220009467b48Spatrick   // from X and Y are disjoint in (X << A) | Y,
220109467b48Spatrick   // if the mask of this AND op covers all bits of X or Y, while it covers
220209467b48Spatrick   // no bits from the other, we can bypass this AND op. E.g.,
220309467b48Spatrick   // ((X << A) | Y) & Mask -> Y,
220409467b48Spatrick   //     if Mask = ((1 << effective_width_of(Y)) - 1)
220509467b48Spatrick   // ((X << A) | Y) & Mask -> X << A,
220609467b48Spatrick   //     if Mask = ((1 << effective_width_of(X)) - 1) << A
220709467b48Spatrick   // SimplifyDemandedBits in InstCombine can optimize the general case.
220809467b48Spatrick   // This pattern aims to help other passes for a common case.
2209*d415bd75Srobert   Value *XShifted;
221009467b48Spatrick   if (match(Op1, m_APInt(Mask)) &&
221109467b48Spatrick       match(Op0, m_c_Or(m_CombineAnd(m_NUWShl(m_Value(X), m_APInt(ShAmt)),
221209467b48Spatrick                                      m_Value(XShifted)),
221309467b48Spatrick                         m_Value(Y)))) {
221409467b48Spatrick     const unsigned Width = Op0->getType()->getScalarSizeInBits();
221509467b48Spatrick     const unsigned ShftCnt = ShAmt->getLimitedValue(Width);
221609467b48Spatrick     const KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2217*d415bd75Srobert     const unsigned EffWidthY = YKnown.countMaxActiveBits();
221809467b48Spatrick     if (EffWidthY <= ShftCnt) {
2219*d415bd75Srobert       const KnownBits XKnown = computeKnownBits(X, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2220*d415bd75Srobert       const unsigned EffWidthX = XKnown.countMaxActiveBits();
222109467b48Spatrick       const APInt EffBitsY = APInt::getLowBitsSet(Width, EffWidthY);
222209467b48Spatrick       const APInt EffBitsX = APInt::getLowBitsSet(Width, EffWidthX) << ShftCnt;
222309467b48Spatrick       // If the mask is extracting all bits from X or Y as is, we can skip
222409467b48Spatrick       // this AND op.
222509467b48Spatrick       if (EffBitsY.isSubsetOf(*Mask) && !EffBitsX.intersects(*Mask))
222609467b48Spatrick         return Y;
222709467b48Spatrick       if (EffBitsX.isSubsetOf(*Mask) && !EffBitsY.intersects(*Mask))
222809467b48Spatrick         return XShifted;
222909467b48Spatrick     }
223009467b48Spatrick   }
223109467b48Spatrick 
2232*d415bd75Srobert   // ((X | Y) ^ X ) & ((X | Y) ^ Y) --> 0
2233*d415bd75Srobert   // ((X | Y) ^ Y ) & ((X | Y) ^ X) --> 0
2234*d415bd75Srobert   BinaryOperator *Or;
2235*d415bd75Srobert   if (match(Op0, m_c_Xor(m_Value(X),
2236*d415bd75Srobert                          m_CombineAnd(m_BinOp(Or),
2237*d415bd75Srobert                                       m_c_Or(m_Deferred(X), m_Value(Y))))) &&
2238*d415bd75Srobert       match(Op1, m_c_Xor(m_Specific(Or), m_Specific(Y))))
2239*d415bd75Srobert     return Constant::getNullValue(Op0->getType());
2240*d415bd75Srobert 
2241*d415bd75Srobert   if (Op0->getType()->isIntOrIntVectorTy(1)) {
2242*d415bd75Srobert     if (std::optional<bool> Implied = isImpliedCondition(Op0, Op1, Q.DL)) {
2243*d415bd75Srobert       // If Op0 is true implies Op1 is true, then Op0 is a subset of Op1.
2244*d415bd75Srobert       if (*Implied == true)
2245*d415bd75Srobert         return Op0;
2246*d415bd75Srobert       // If Op0 is true implies Op1 is false, then they are not true together.
2247*d415bd75Srobert       if (*Implied == false)
2248*d415bd75Srobert         return ConstantInt::getFalse(Op0->getType());
2249*d415bd75Srobert     }
2250*d415bd75Srobert     if (std::optional<bool> Implied = isImpliedCondition(Op1, Op0, Q.DL)) {
2251*d415bd75Srobert       // If Op1 is true implies Op0 is true, then Op1 is a subset of Op0.
2252*d415bd75Srobert       if (*Implied)
2253*d415bd75Srobert         return Op1;
2254*d415bd75Srobert       // If Op1 is true implies Op0 is false, then they are not true together.
2255*d415bd75Srobert       if (!*Implied)
2256*d415bd75Srobert         return ConstantInt::getFalse(Op1->getType());
2257*d415bd75Srobert     }
2258*d415bd75Srobert   }
2259*d415bd75Srobert 
2260*d415bd75Srobert   if (Value *V = simplifyByDomEq(Instruction::And, Op0, Op1, Q, MaxRecurse))
2261*d415bd75Srobert     return V;
2262*d415bd75Srobert 
226309467b48Spatrick   return nullptr;
226409467b48Spatrick }
226509467b48Spatrick 
simplifyAndInst(Value * Op0,Value * Op1,const SimplifyQuery & Q)2266*d415bd75Srobert Value *llvm::simplifyAndInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
2267*d415bd75Srobert   return ::simplifyAndInst(Op0, Op1, Q, RecursionLimit);
2268*d415bd75Srobert }
2269*d415bd75Srobert 
2270*d415bd75Srobert // TODO: Many of these folds could use LogicalAnd/LogicalOr.
simplifyOrLogic(Value * X,Value * Y)2271*d415bd75Srobert static Value *simplifyOrLogic(Value *X, Value *Y) {
2272*d415bd75Srobert   assert(X->getType() == Y->getType() && "Expected same type for 'or' ops");
2273*d415bd75Srobert   Type *Ty = X->getType();
2274*d415bd75Srobert 
2275*d415bd75Srobert   // X | ~X --> -1
2276*d415bd75Srobert   if (match(Y, m_Not(m_Specific(X))))
2277*d415bd75Srobert     return ConstantInt::getAllOnesValue(Ty);
2278*d415bd75Srobert 
2279*d415bd75Srobert   // X | ~(X & ?) = -1
2280*d415bd75Srobert   if (match(Y, m_Not(m_c_And(m_Specific(X), m_Value()))))
2281*d415bd75Srobert     return ConstantInt::getAllOnesValue(Ty);
2282*d415bd75Srobert 
2283*d415bd75Srobert   // X | (X & ?) --> X
2284*d415bd75Srobert   if (match(Y, m_c_And(m_Specific(X), m_Value())))
2285*d415bd75Srobert     return X;
2286*d415bd75Srobert 
2287*d415bd75Srobert   Value *A, *B;
2288*d415bd75Srobert 
2289*d415bd75Srobert   // (A ^ B) | (A | B) --> A | B
2290*d415bd75Srobert   // (A ^ B) | (B | A) --> B | A
2291*d415bd75Srobert   if (match(X, m_Xor(m_Value(A), m_Value(B))) &&
2292*d415bd75Srobert       match(Y, m_c_Or(m_Specific(A), m_Specific(B))))
2293*d415bd75Srobert     return Y;
2294*d415bd75Srobert 
2295*d415bd75Srobert   // ~(A ^ B) | (A | B) --> -1
2296*d415bd75Srobert   // ~(A ^ B) | (B | A) --> -1
2297*d415bd75Srobert   if (match(X, m_Not(m_Xor(m_Value(A), m_Value(B)))) &&
2298*d415bd75Srobert       match(Y, m_c_Or(m_Specific(A), m_Specific(B))))
2299*d415bd75Srobert     return ConstantInt::getAllOnesValue(Ty);
2300*d415bd75Srobert 
2301*d415bd75Srobert   // (A & ~B) | (A ^ B) --> A ^ B
2302*d415bd75Srobert   // (~B & A) | (A ^ B) --> A ^ B
2303*d415bd75Srobert   // (A & ~B) | (B ^ A) --> B ^ A
2304*d415bd75Srobert   // (~B & A) | (B ^ A) --> B ^ A
2305*d415bd75Srobert   if (match(X, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
2306*d415bd75Srobert       match(Y, m_c_Xor(m_Specific(A), m_Specific(B))))
2307*d415bd75Srobert     return Y;
2308*d415bd75Srobert 
2309*d415bd75Srobert   // (~A ^ B) | (A & B) --> ~A ^ B
2310*d415bd75Srobert   // (B ^ ~A) | (A & B) --> B ^ ~A
2311*d415bd75Srobert   // (~A ^ B) | (B & A) --> ~A ^ B
2312*d415bd75Srobert   // (B ^ ~A) | (B & A) --> B ^ ~A
2313*d415bd75Srobert   if (match(X, m_c_Xor(m_NotForbidUndef(m_Value(A)), m_Value(B))) &&
2314*d415bd75Srobert       match(Y, m_c_And(m_Specific(A), m_Specific(B))))
2315*d415bd75Srobert     return X;
2316*d415bd75Srobert 
2317*d415bd75Srobert   // (~A | B) | (A ^ B) --> -1
2318*d415bd75Srobert   // (~A | B) | (B ^ A) --> -1
2319*d415bd75Srobert   // (B | ~A) | (A ^ B) --> -1
2320*d415bd75Srobert   // (B | ~A) | (B ^ A) --> -1
2321*d415bd75Srobert   if (match(X, m_c_Or(m_Not(m_Value(A)), m_Value(B))) &&
2322*d415bd75Srobert       match(Y, m_c_Xor(m_Specific(A), m_Specific(B))))
2323*d415bd75Srobert     return ConstantInt::getAllOnesValue(Ty);
2324*d415bd75Srobert 
2325*d415bd75Srobert   // (~A & B) | ~(A | B) --> ~A
2326*d415bd75Srobert   // (~A & B) | ~(B | A) --> ~A
2327*d415bd75Srobert   // (B & ~A) | ~(A | B) --> ~A
2328*d415bd75Srobert   // (B & ~A) | ~(B | A) --> ~A
2329*d415bd75Srobert   Value *NotA;
2330*d415bd75Srobert   if (match(X,
2331*d415bd75Srobert             m_c_And(m_CombineAnd(m_Value(NotA), m_NotForbidUndef(m_Value(A))),
2332*d415bd75Srobert                     m_Value(B))) &&
2333*d415bd75Srobert       match(Y, m_Not(m_c_Or(m_Specific(A), m_Specific(B)))))
2334*d415bd75Srobert     return NotA;
2335*d415bd75Srobert   // The same is true of Logical And
2336*d415bd75Srobert   // TODO: This could share the logic of the version above if there was a
2337*d415bd75Srobert   // version of LogicalAnd that allowed more than just i1 types.
2338*d415bd75Srobert   if (match(X, m_c_LogicalAnd(
2339*d415bd75Srobert                    m_CombineAnd(m_Value(NotA), m_NotForbidUndef(m_Value(A))),
2340*d415bd75Srobert                    m_Value(B))) &&
2341*d415bd75Srobert       match(Y, m_Not(m_c_LogicalOr(m_Specific(A), m_Specific(B)))))
2342*d415bd75Srobert     return NotA;
2343*d415bd75Srobert 
2344*d415bd75Srobert   // ~(A ^ B) | (A & B) --> ~(A ^ B)
2345*d415bd75Srobert   // ~(A ^ B) | (B & A) --> ~(A ^ B)
2346*d415bd75Srobert   Value *NotAB;
2347*d415bd75Srobert   if (match(X, m_CombineAnd(m_NotForbidUndef(m_Xor(m_Value(A), m_Value(B))),
2348*d415bd75Srobert                             m_Value(NotAB))) &&
2349*d415bd75Srobert       match(Y, m_c_And(m_Specific(A), m_Specific(B))))
2350*d415bd75Srobert     return NotAB;
2351*d415bd75Srobert 
2352*d415bd75Srobert   // ~(A & B) | (A ^ B) --> ~(A & B)
2353*d415bd75Srobert   // ~(A & B) | (B ^ A) --> ~(A & B)
2354*d415bd75Srobert   if (match(X, m_CombineAnd(m_NotForbidUndef(m_And(m_Value(A), m_Value(B))),
2355*d415bd75Srobert                             m_Value(NotAB))) &&
2356*d415bd75Srobert       match(Y, m_c_Xor(m_Specific(A), m_Specific(B))))
2357*d415bd75Srobert     return NotAB;
2358*d415bd75Srobert 
2359*d415bd75Srobert   return nullptr;
236009467b48Spatrick }
236109467b48Spatrick 
236209467b48Spatrick /// Given operands for an Or, see if we can fold the result.
236309467b48Spatrick /// If not, this returns null.
simplifyOrInst(Value * Op0,Value * Op1,const SimplifyQuery & Q,unsigned MaxRecurse)2364*d415bd75Srobert static Value *simplifyOrInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
236509467b48Spatrick                              unsigned MaxRecurse) {
236609467b48Spatrick   if (Constant *C = foldOrCommuteConstant(Instruction::Or, Op0, Op1, Q))
236709467b48Spatrick     return C;
236809467b48Spatrick 
236973471bf0Spatrick   // X | poison -> poison
237073471bf0Spatrick   if (isa<PoisonValue>(Op1))
237173471bf0Spatrick     return Op1;
237273471bf0Spatrick 
237309467b48Spatrick   // X | undef -> -1
237409467b48Spatrick   // X | -1 = -1
237509467b48Spatrick   // Do not return Op1 because it may contain undef elements if it's a vector.
237673471bf0Spatrick   if (Q.isUndefValue(Op1) || match(Op1, m_AllOnes()))
237709467b48Spatrick     return Constant::getAllOnesValue(Op0->getType());
237809467b48Spatrick 
237909467b48Spatrick   // X | X = X
238009467b48Spatrick   // X | 0 = X
238109467b48Spatrick   if (Op0 == Op1 || match(Op1, m_Zero()))
238209467b48Spatrick     return Op0;
238309467b48Spatrick 
2384*d415bd75Srobert   if (Value *R = simplifyOrLogic(Op0, Op1))
2385*d415bd75Srobert     return R;
2386*d415bd75Srobert   if (Value *R = simplifyOrLogic(Op1, Op0))
2387*d415bd75Srobert     return R;
238809467b48Spatrick 
238973471bf0Spatrick   if (Value *V = simplifyLogicOfAddSub(Op0, Op1, Instruction::Or))
239073471bf0Spatrick     return V;
239173471bf0Spatrick 
2392*d415bd75Srobert   // Rotated -1 is still -1:
2393*d415bd75Srobert   // (-1 << X) | (-1 >> (C - X)) --> -1
2394*d415bd75Srobert   // (-1 >> X) | (-1 << (C - X)) --> -1
2395*d415bd75Srobert   // ...with C <= bitwidth (and commuted variants).
2396*d415bd75Srobert   Value *X, *Y;
2397*d415bd75Srobert   if ((match(Op0, m_Shl(m_AllOnes(), m_Value(X))) &&
2398*d415bd75Srobert        match(Op1, m_LShr(m_AllOnes(), m_Value(Y)))) ||
2399*d415bd75Srobert       (match(Op1, m_Shl(m_AllOnes(), m_Value(X))) &&
2400*d415bd75Srobert        match(Op0, m_LShr(m_AllOnes(), m_Value(Y))))) {
2401*d415bd75Srobert     const APInt *C;
2402*d415bd75Srobert     if ((match(X, m_Sub(m_APInt(C), m_Specific(Y))) ||
2403*d415bd75Srobert          match(Y, m_Sub(m_APInt(C), m_Specific(X)))) &&
2404*d415bd75Srobert         C->ule(X->getType()->getScalarSizeInBits())) {
2405*d415bd75Srobert       return ConstantInt::getAllOnesValue(X->getType());
2406*d415bd75Srobert     }
2407*d415bd75Srobert   }
2408*d415bd75Srobert 
2409*d415bd75Srobert   // A funnel shift (rotate) can be decomposed into simpler shifts. See if we
2410*d415bd75Srobert   // are mixing in another shift that is redundant with the funnel shift.
2411*d415bd75Srobert 
2412*d415bd75Srobert   // (fshl X, ?, Y) | (shl X, Y) --> fshl X, ?, Y
2413*d415bd75Srobert   // (shl X, Y) | (fshl X, ?, Y) --> fshl X, ?, Y
2414*d415bd75Srobert   if (match(Op0,
2415*d415bd75Srobert             m_Intrinsic<Intrinsic::fshl>(m_Value(X), m_Value(), m_Value(Y))) &&
2416*d415bd75Srobert       match(Op1, m_Shl(m_Specific(X), m_Specific(Y))))
2417*d415bd75Srobert     return Op0;
2418*d415bd75Srobert   if (match(Op1,
2419*d415bd75Srobert             m_Intrinsic<Intrinsic::fshl>(m_Value(X), m_Value(), m_Value(Y))) &&
2420*d415bd75Srobert       match(Op0, m_Shl(m_Specific(X), m_Specific(Y))))
242109467b48Spatrick     return Op1;
242209467b48Spatrick 
2423*d415bd75Srobert   // (fshr ?, X, Y) | (lshr X, Y) --> fshr ?, X, Y
2424*d415bd75Srobert   // (lshr X, Y) | (fshr ?, X, Y) --> fshr ?, X, Y
2425*d415bd75Srobert   if (match(Op0,
2426*d415bd75Srobert             m_Intrinsic<Intrinsic::fshr>(m_Value(), m_Value(X), m_Value(Y))) &&
2427*d415bd75Srobert       match(Op1, m_LShr(m_Specific(X), m_Specific(Y))))
242809467b48Spatrick     return Op0;
2429*d415bd75Srobert   if (match(Op1,
2430*d415bd75Srobert             m_Intrinsic<Intrinsic::fshr>(m_Value(), m_Value(X), m_Value(Y))) &&
2431*d415bd75Srobert       match(Op0, m_LShr(m_Specific(X), m_Specific(Y))))
243209467b48Spatrick     return Op1;
243309467b48Spatrick 
243409467b48Spatrick   if (Value *V = simplifyAndOrOfCmps(Q, Op0, Op1, false))
243509467b48Spatrick     return V;
243609467b48Spatrick 
243709467b48Spatrick   // If we have a multiplication overflow check that is being 'and'ed with a
243809467b48Spatrick   // check that one of the multipliers is not zero, we can omit the 'and', and
243909467b48Spatrick   // only keep the overflow check.
244073471bf0Spatrick   if (isCheckForZeroAndMulWithOverflow(Op0, Op1, false))
244173471bf0Spatrick     return Op1;
244273471bf0Spatrick   if (isCheckForZeroAndMulWithOverflow(Op1, Op0, false))
244373471bf0Spatrick     return Op0;
244409467b48Spatrick 
244509467b48Spatrick   // Try some generic simplifications for associative operations.
2446*d415bd75Srobert   if (Value *V =
2447*d415bd75Srobert           simplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q, MaxRecurse))
244809467b48Spatrick     return V;
244909467b48Spatrick 
245009467b48Spatrick   // Or distributes over And.  Try some generic simplifications based on this.
245173471bf0Spatrick   if (Value *V = expandCommutativeBinOp(Instruction::Or, Op0, Op1,
245273471bf0Spatrick                                         Instruction::And, Q, MaxRecurse))
245309467b48Spatrick     return V;
245409467b48Spatrick 
245573471bf0Spatrick   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) {
245673471bf0Spatrick     if (Op0->getType()->isIntOrIntVectorTy(1)) {
245773471bf0Spatrick       // A | (A || B) -> A || B
245873471bf0Spatrick       if (match(Op1, m_Select(m_Specific(Op0), m_One(), m_Value())))
245973471bf0Spatrick         return Op1;
246073471bf0Spatrick       else if (match(Op0, m_Select(m_Specific(Op1), m_One(), m_Value())))
246173471bf0Spatrick         return Op0;
246273471bf0Spatrick     }
246373471bf0Spatrick     // If the operation is with the result of a select instruction, check
246473471bf0Spatrick     // whether operating on either branch of the select always yields the same
246573471bf0Spatrick     // value.
2466*d415bd75Srobert     if (Value *V =
2467*d415bd75Srobert             threadBinOpOverSelect(Instruction::Or, Op0, Op1, Q, MaxRecurse))
246809467b48Spatrick       return V;
246973471bf0Spatrick   }
247009467b48Spatrick 
247109467b48Spatrick   // (A & C1)|(B & C2)
2472*d415bd75Srobert   Value *A, *B;
247309467b48Spatrick   const APInt *C1, *C2;
247409467b48Spatrick   if (match(Op0, m_And(m_Value(A), m_APInt(C1))) &&
247509467b48Spatrick       match(Op1, m_And(m_Value(B), m_APInt(C2)))) {
247609467b48Spatrick     if (*C1 == ~*C2) {
247709467b48Spatrick       // (A & C1)|(B & C2)
247809467b48Spatrick       // If we have: ((V + N) & C1) | (V & C2)
247909467b48Spatrick       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
248009467b48Spatrick       // replace with V+N.
248109467b48Spatrick       Value *N;
248209467b48Spatrick       if (C2->isMask() && // C2 == 0+1+
248309467b48Spatrick           match(A, m_c_Add(m_Specific(B), m_Value(N)))) {
248409467b48Spatrick         // Add commutes, try both ways.
248509467b48Spatrick         if (MaskedValueIsZero(N, *C2, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
248609467b48Spatrick           return A;
248709467b48Spatrick       }
248809467b48Spatrick       // Or commutes, try both ways.
2489*d415bd75Srobert       if (C1->isMask() && match(B, m_c_Add(m_Specific(A), m_Value(N)))) {
249009467b48Spatrick         // Add commutes, try both ways.
249109467b48Spatrick         if (MaskedValueIsZero(N, *C1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
249209467b48Spatrick           return B;
249309467b48Spatrick       }
249409467b48Spatrick     }
249509467b48Spatrick   }
249609467b48Spatrick 
249709467b48Spatrick   // If the operation is with the result of a phi instruction, check whether
249809467b48Spatrick   // operating on all incoming values of the phi always yields the same value.
249909467b48Spatrick   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
2500*d415bd75Srobert     if (Value *V = threadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
2501*d415bd75Srobert       return V;
2502*d415bd75Srobert 
2503*d415bd75Srobert   if (Op0->getType()->isIntOrIntVectorTy(1)) {
2504*d415bd75Srobert     if (std::optional<bool> Implied =
2505*d415bd75Srobert             isImpliedCondition(Op0, Op1, Q.DL, false)) {
2506*d415bd75Srobert       // If Op0 is false implies Op1 is false, then Op1 is a subset of Op0.
2507*d415bd75Srobert       if (*Implied == false)
2508*d415bd75Srobert         return Op0;
2509*d415bd75Srobert       // If Op0 is false implies Op1 is true, then at least one is always true.
2510*d415bd75Srobert       if (*Implied == true)
2511*d415bd75Srobert         return ConstantInt::getTrue(Op0->getType());
2512*d415bd75Srobert     }
2513*d415bd75Srobert     if (std::optional<bool> Implied =
2514*d415bd75Srobert             isImpliedCondition(Op1, Op0, Q.DL, false)) {
2515*d415bd75Srobert       // If Op1 is false implies Op0 is false, then Op0 is a subset of Op1.
2516*d415bd75Srobert       if (*Implied == false)
2517*d415bd75Srobert         return Op1;
2518*d415bd75Srobert       // If Op1 is false implies Op0 is true, then at least one is always true.
2519*d415bd75Srobert       if (*Implied == true)
2520*d415bd75Srobert         return ConstantInt::getTrue(Op1->getType());
2521*d415bd75Srobert     }
2522*d415bd75Srobert   }
2523*d415bd75Srobert 
2524*d415bd75Srobert   if (Value *V = simplifyByDomEq(Instruction::Or, Op0, Op1, Q, MaxRecurse))
252509467b48Spatrick     return V;
252609467b48Spatrick 
252709467b48Spatrick   return nullptr;
252809467b48Spatrick }
252909467b48Spatrick 
simplifyOrInst(Value * Op0,Value * Op1,const SimplifyQuery & Q)2530*d415bd75Srobert Value *llvm::simplifyOrInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
2531*d415bd75Srobert   return ::simplifyOrInst(Op0, Op1, Q, RecursionLimit);
253209467b48Spatrick }
253309467b48Spatrick 
253409467b48Spatrick /// Given operands for a Xor, see if we can fold the result.
253509467b48Spatrick /// If not, this returns null.
simplifyXorInst(Value * Op0,Value * Op1,const SimplifyQuery & Q,unsigned MaxRecurse)2536*d415bd75Srobert static Value *simplifyXorInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
253709467b48Spatrick                               unsigned MaxRecurse) {
253809467b48Spatrick   if (Constant *C = foldOrCommuteConstant(Instruction::Xor, Op0, Op1, Q))
253909467b48Spatrick     return C;
254009467b48Spatrick 
2541*d415bd75Srobert   // X ^ poison -> poison
2542*d415bd75Srobert   if (isa<PoisonValue>(Op1))
2543*d415bd75Srobert     return Op1;
2544*d415bd75Srobert 
254509467b48Spatrick   // A ^ undef -> undef
254673471bf0Spatrick   if (Q.isUndefValue(Op1))
254709467b48Spatrick     return Op1;
254809467b48Spatrick 
254909467b48Spatrick   // A ^ 0 = A
255009467b48Spatrick   if (match(Op1, m_Zero()))
255109467b48Spatrick     return Op0;
255209467b48Spatrick 
255309467b48Spatrick   // A ^ A = 0
255409467b48Spatrick   if (Op0 == Op1)
255509467b48Spatrick     return Constant::getNullValue(Op0->getType());
255609467b48Spatrick 
255709467b48Spatrick   // A ^ ~A  =  ~A ^ A  =  -1
2558*d415bd75Srobert   if (match(Op0, m_Not(m_Specific(Op1))) || match(Op1, m_Not(m_Specific(Op0))))
255909467b48Spatrick     return Constant::getAllOnesValue(Op0->getType());
256009467b48Spatrick 
2561*d415bd75Srobert   auto foldAndOrNot = [](Value *X, Value *Y) -> Value * {
2562*d415bd75Srobert     Value *A, *B;
2563*d415bd75Srobert     // (~A & B) ^ (A | B) --> A -- There are 8 commuted variants.
2564*d415bd75Srobert     if (match(X, m_c_And(m_Not(m_Value(A)), m_Value(B))) &&
2565*d415bd75Srobert         match(Y, m_c_Or(m_Specific(A), m_Specific(B))))
2566*d415bd75Srobert       return A;
2567*d415bd75Srobert 
2568*d415bd75Srobert     // (~A | B) ^ (A & B) --> ~A -- There are 8 commuted variants.
2569*d415bd75Srobert     // The 'not' op must contain a complete -1 operand (no undef elements for
2570*d415bd75Srobert     // vector) for the transform to be safe.
2571*d415bd75Srobert     Value *NotA;
2572*d415bd75Srobert     if (match(X,
2573*d415bd75Srobert               m_c_Or(m_CombineAnd(m_NotForbidUndef(m_Value(A)), m_Value(NotA)),
2574*d415bd75Srobert                      m_Value(B))) &&
2575*d415bd75Srobert         match(Y, m_c_And(m_Specific(A), m_Specific(B))))
2576*d415bd75Srobert       return NotA;
2577*d415bd75Srobert 
2578*d415bd75Srobert     return nullptr;
2579*d415bd75Srobert   };
2580*d415bd75Srobert   if (Value *R = foldAndOrNot(Op0, Op1))
2581*d415bd75Srobert     return R;
2582*d415bd75Srobert   if (Value *R = foldAndOrNot(Op1, Op0))
2583*d415bd75Srobert     return R;
2584*d415bd75Srobert 
258573471bf0Spatrick   if (Value *V = simplifyLogicOfAddSub(Op0, Op1, Instruction::Xor))
258673471bf0Spatrick     return V;
258773471bf0Spatrick 
258809467b48Spatrick   // Try some generic simplifications for associative operations.
2589*d415bd75Srobert   if (Value *V =
2590*d415bd75Srobert           simplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q, MaxRecurse))
259109467b48Spatrick     return V;
259209467b48Spatrick 
259309467b48Spatrick   // Threading Xor over selects and phi nodes is pointless, so don't bother.
259409467b48Spatrick   // Threading over the select in "A ^ select(cond, B, C)" means evaluating
259509467b48Spatrick   // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
259609467b48Spatrick   // only if B and C are equal.  If B and C are equal then (since we assume
259709467b48Spatrick   // that operands have already been simplified) "select(cond, B, C)" should
259809467b48Spatrick   // have been simplified to the common value of B and C already.  Analysing
259909467b48Spatrick   // "A^B" and "A^C" thus gains nothing, but costs compile time.  Similarly
260009467b48Spatrick   // for threading over phi nodes.
260109467b48Spatrick 
2602*d415bd75Srobert   if (Value *V = simplifyByDomEq(Instruction::Xor, Op0, Op1, Q, MaxRecurse))
2603*d415bd75Srobert     return V;
2604*d415bd75Srobert 
260509467b48Spatrick   return nullptr;
260609467b48Spatrick }
260709467b48Spatrick 
simplifyXorInst(Value * Op0,Value * Op1,const SimplifyQuery & Q)2608*d415bd75Srobert Value *llvm::simplifyXorInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
2609*d415bd75Srobert   return ::simplifyXorInst(Op0, Op1, Q, RecursionLimit);
261009467b48Spatrick }
261109467b48Spatrick 
getCompareTy(Value * Op)2612*d415bd75Srobert static Type *getCompareTy(Value *Op) {
261309467b48Spatrick   return CmpInst::makeCmpResultType(Op->getType());
261409467b48Spatrick }
261509467b48Spatrick 
261609467b48Spatrick /// Rummage around inside V looking for something equivalent to the comparison
261709467b48Spatrick /// "LHS Pred RHS". Return such a value if found, otherwise return null.
261809467b48Spatrick /// Helper function for analyzing max/min idioms.
extractEquivalentCondition(Value * V,CmpInst::Predicate Pred,Value * LHS,Value * RHS)2619*d415bd75Srobert static Value *extractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
262009467b48Spatrick                                          Value *LHS, Value *RHS) {
262109467b48Spatrick   SelectInst *SI = dyn_cast<SelectInst>(V);
262209467b48Spatrick   if (!SI)
262309467b48Spatrick     return nullptr;
262409467b48Spatrick   CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
262509467b48Spatrick   if (!Cmp)
262609467b48Spatrick     return nullptr;
262709467b48Spatrick   Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
262809467b48Spatrick   if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
262909467b48Spatrick     return Cmp;
263009467b48Spatrick   if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
263109467b48Spatrick       LHS == CmpRHS && RHS == CmpLHS)
263209467b48Spatrick     return Cmp;
263309467b48Spatrick   return nullptr;
263409467b48Spatrick }
263509467b48Spatrick 
2636*d415bd75Srobert /// Return true if the underlying object (storage) must be disjoint from
2637*d415bd75Srobert /// storage returned by any noalias return call.
isAllocDisjoint(const Value * V)2638*d415bd75Srobert static bool isAllocDisjoint(const Value *V) {
2639*d415bd75Srobert   // For allocas, we consider only static ones (dynamic
2640*d415bd75Srobert   // allocas might be transformed into calls to malloc not simultaneously
2641*d415bd75Srobert   // live with the compared-to allocation). For globals, we exclude symbols
2642*d415bd75Srobert   // that might be resolve lazily to symbols in another dynamically-loaded
2643*d415bd75Srobert   // library (and, thus, could be malloc'ed by the implementation).
2644*d415bd75Srobert   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V))
2645*d415bd75Srobert     return AI->getParent() && AI->getFunction() && AI->isStaticAlloca();
2646*d415bd75Srobert   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
2647*d415bd75Srobert     return (GV->hasLocalLinkage() || GV->hasHiddenVisibility() ||
2648*d415bd75Srobert             GV->hasProtectedVisibility() || GV->hasGlobalUnnamedAddr()) &&
2649*d415bd75Srobert            !GV->isThreadLocal();
2650*d415bd75Srobert   if (const Argument *A = dyn_cast<Argument>(V))
2651*d415bd75Srobert     return A->hasByValAttr();
2652*d415bd75Srobert   return false;
2653*d415bd75Srobert }
2654*d415bd75Srobert 
2655*d415bd75Srobert /// Return true if V1 and V2 are each the base of some distict storage region
2656*d415bd75Srobert /// [V, object_size(V)] which do not overlap.  Note that zero sized regions
2657*d415bd75Srobert /// *are* possible, and that zero sized regions do not overlap with any other.
haveNonOverlappingStorage(const Value * V1,const Value * V2)2658*d415bd75Srobert static bool haveNonOverlappingStorage(const Value *V1, const Value *V2) {
2659*d415bd75Srobert   // Global variables always exist, so they always exist during the lifetime
2660*d415bd75Srobert   // of each other and all allocas.  Global variables themselves usually have
2661*d415bd75Srobert   // non-overlapping storage, but since their addresses are constants, the
2662*d415bd75Srobert   // case involving two globals does not reach here and is instead handled in
2663*d415bd75Srobert   // constant folding.
2664*d415bd75Srobert   //
2665*d415bd75Srobert   // Two different allocas usually have different addresses...
2666*d415bd75Srobert   //
2667*d415bd75Srobert   // However, if there's an @llvm.stackrestore dynamically in between two
2668*d415bd75Srobert   // allocas, they may have the same address. It's tempting to reduce the
2669*d415bd75Srobert   // scope of the problem by only looking at *static* allocas here. That would
2670*d415bd75Srobert   // cover the majority of allocas while significantly reducing the likelihood
2671*d415bd75Srobert   // of having an @llvm.stackrestore pop up in the middle. However, it's not
2672*d415bd75Srobert   // actually impossible for an @llvm.stackrestore to pop up in the middle of
2673*d415bd75Srobert   // an entry block. Also, if we have a block that's not attached to a
2674*d415bd75Srobert   // function, we can't tell if it's "static" under the current definition.
2675*d415bd75Srobert   // Theoretically, this problem could be fixed by creating a new kind of
2676*d415bd75Srobert   // instruction kind specifically for static allocas. Such a new instruction
2677*d415bd75Srobert   // could be required to be at the top of the entry block, thus preventing it
2678*d415bd75Srobert   // from being subject to a @llvm.stackrestore. Instcombine could even
2679*d415bd75Srobert   // convert regular allocas into these special allocas. It'd be nifty.
2680*d415bd75Srobert   // However, until then, this problem remains open.
2681*d415bd75Srobert   //
2682*d415bd75Srobert   // So, we'll assume that two non-empty allocas have different addresses
2683*d415bd75Srobert   // for now.
2684*d415bd75Srobert   auto isByValArg = [](const Value *V) {
2685*d415bd75Srobert     const Argument *A = dyn_cast<Argument>(V);
2686*d415bd75Srobert     return A && A->hasByValAttr();
2687*d415bd75Srobert   };
2688*d415bd75Srobert 
2689*d415bd75Srobert   // Byval args are backed by store which does not overlap with each other,
2690*d415bd75Srobert   // allocas, or globals.
2691*d415bd75Srobert   if (isByValArg(V1))
2692*d415bd75Srobert     return isa<AllocaInst>(V2) || isa<GlobalVariable>(V2) || isByValArg(V2);
2693*d415bd75Srobert   if (isByValArg(V2))
2694*d415bd75Srobert     return isa<AllocaInst>(V1) || isa<GlobalVariable>(V1) || isByValArg(V1);
2695*d415bd75Srobert 
2696*d415bd75Srobert   return isa<AllocaInst>(V1) &&
2697*d415bd75Srobert          (isa<AllocaInst>(V2) || isa<GlobalVariable>(V2));
2698*d415bd75Srobert }
2699*d415bd75Srobert 
270009467b48Spatrick // A significant optimization not implemented here is assuming that alloca
270109467b48Spatrick // addresses are not equal to incoming argument values. They don't *alias*,
270209467b48Spatrick // as we say, but that doesn't mean they aren't equal, so we take a
270309467b48Spatrick // conservative approach.
270409467b48Spatrick //
270509467b48Spatrick // This is inspired in part by C++11 5.10p1:
270609467b48Spatrick //   "Two pointers of the same type compare equal if and only if they are both
270709467b48Spatrick //    null, both point to the same function, or both represent the same
270809467b48Spatrick //    address."
270909467b48Spatrick //
271009467b48Spatrick // This is pretty permissive.
271109467b48Spatrick //
271209467b48Spatrick // It's also partly due to C11 6.5.9p6:
271309467b48Spatrick //   "Two pointers compare equal if and only if both are null pointers, both are
271409467b48Spatrick //    pointers to the same object (including a pointer to an object and a
271509467b48Spatrick //    subobject at its beginning) or function, both are pointers to one past the
271609467b48Spatrick //    last element of the same array object, or one is a pointer to one past the
271709467b48Spatrick //    end of one array object and the other is a pointer to the start of a
271809467b48Spatrick //    different array object that happens to immediately follow the first array
271909467b48Spatrick //    object in the address space.)
272009467b48Spatrick //
272109467b48Spatrick // C11's version is more restrictive, however there's no reason why an argument
272209467b48Spatrick // couldn't be a one-past-the-end value for a stack object in the caller and be
272309467b48Spatrick // equal to the beginning of a stack object in the callee.
272409467b48Spatrick //
272509467b48Spatrick // If the C and C++ standards are ever made sufficiently restrictive in this
272609467b48Spatrick // area, it may be possible to update LLVM's semantics accordingly and reinstate
272709467b48Spatrick // this optimization.
computePointerICmp(CmpInst::Predicate Pred,Value * LHS,Value * RHS,const SimplifyQuery & Q)2728*d415bd75Srobert static Constant *computePointerICmp(CmpInst::Predicate Pred, Value *LHS,
2729*d415bd75Srobert                                     Value *RHS, const SimplifyQuery &Q) {
273073471bf0Spatrick   const DataLayout &DL = Q.DL;
273173471bf0Spatrick   const TargetLibraryInfo *TLI = Q.TLI;
273273471bf0Spatrick   const DominatorTree *DT = Q.DT;
273373471bf0Spatrick   const Instruction *CxtI = Q.CxtI;
273473471bf0Spatrick   const InstrInfoQuery &IIQ = Q.IIQ;
273573471bf0Spatrick 
273609467b48Spatrick   // First, skip past any trivial no-ops.
273709467b48Spatrick   LHS = LHS->stripPointerCasts();
273809467b48Spatrick   RHS = RHS->stripPointerCasts();
273909467b48Spatrick 
274009467b48Spatrick   // A non-null pointer is not equal to a null pointer.
2741097a140dSpatrick   if (isa<ConstantPointerNull>(RHS) && ICmpInst::isEquality(Pred) &&
2742097a140dSpatrick       llvm::isKnownNonZero(LHS, DL, 0, nullptr, nullptr, nullptr,
2743097a140dSpatrick                            IIQ.UseInstrInfo))
2744*d415bd75Srobert     return ConstantInt::get(getCompareTy(LHS), !CmpInst::isTrueWhenEqual(Pred));
274509467b48Spatrick 
274609467b48Spatrick   // We can only fold certain predicates on pointer comparisons.
274709467b48Spatrick   switch (Pred) {
274809467b48Spatrick   default:
274909467b48Spatrick     return nullptr;
275009467b48Spatrick 
2751*d415bd75Srobert     // Equality comparisons are easy to fold.
275209467b48Spatrick   case CmpInst::ICMP_EQ:
275309467b48Spatrick   case CmpInst::ICMP_NE:
275409467b48Spatrick     break;
275509467b48Spatrick 
275609467b48Spatrick     // We can only handle unsigned relational comparisons because 'inbounds' on
275709467b48Spatrick     // a GEP only protects against unsigned wrapping.
275809467b48Spatrick   case CmpInst::ICMP_UGT:
275909467b48Spatrick   case CmpInst::ICMP_UGE:
276009467b48Spatrick   case CmpInst::ICMP_ULT:
276109467b48Spatrick   case CmpInst::ICMP_ULE:
276209467b48Spatrick     // However, we have to switch them to their signed variants to handle
276309467b48Spatrick     // negative indices from the base pointer.
276409467b48Spatrick     Pred = ICmpInst::getSignedPredicate(Pred);
276509467b48Spatrick     break;
276609467b48Spatrick   }
276709467b48Spatrick 
276809467b48Spatrick   // Strip off any constant offsets so that we can reason about them.
276909467b48Spatrick   // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets
277009467b48Spatrick   // here and compare base addresses like AliasAnalysis does, however there are
277109467b48Spatrick   // numerous hazards. AliasAnalysis and its utilities rely on special rules
277209467b48Spatrick   // governing loads and stores which don't apply to icmps. Also, AliasAnalysis
277309467b48Spatrick   // doesn't need to guarantee pointer inequality when it says NoAlias.
2774*d415bd75Srobert 
2775*d415bd75Srobert   // Even if an non-inbounds GEP occurs along the path we can still optimize
2776*d415bd75Srobert   // equality comparisons concerning the result.
2777*d415bd75Srobert   bool AllowNonInbounds = ICmpInst::isEquality(Pred);
2778*d415bd75Srobert   APInt LHSOffset = stripAndComputeConstantOffsets(DL, LHS, AllowNonInbounds);
2779*d415bd75Srobert   APInt RHSOffset = stripAndComputeConstantOffsets(DL, RHS, AllowNonInbounds);
278009467b48Spatrick 
278109467b48Spatrick   // If LHS and RHS are related via constant offsets to the same base
278209467b48Spatrick   // value, we can replace it with an icmp which just compares the offsets.
278309467b48Spatrick   if (LHS == RHS)
2784*d415bd75Srobert     return ConstantInt::get(getCompareTy(LHS),
2785*d415bd75Srobert                             ICmpInst::compare(LHSOffset, RHSOffset, Pred));
278609467b48Spatrick 
278709467b48Spatrick   // Various optimizations for (in)equality comparisons.
278809467b48Spatrick   if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) {
278909467b48Spatrick     // Different non-empty allocations that exist at the same time have
2790*d415bd75Srobert     // different addresses (if the program can tell). If the offsets are
2791*d415bd75Srobert     // within the bounds of their allocations (and not one-past-the-end!
2792*d415bd75Srobert     // so we can't use inbounds!), and their allocations aren't the same,
2793*d415bd75Srobert     // the pointers are not equal.
2794*d415bd75Srobert     if (haveNonOverlappingStorage(LHS, RHS)) {
279509467b48Spatrick       uint64_t LHSSize, RHSSize;
279609467b48Spatrick       ObjectSizeOpts Opts;
2797*d415bd75Srobert       Opts.EvalMode = ObjectSizeOpts::Mode::Min;
2798*d415bd75Srobert       auto *F = [](Value *V) -> Function * {
2799*d415bd75Srobert         if (auto *I = dyn_cast<Instruction>(V))
2800*d415bd75Srobert           return I->getFunction();
2801*d415bd75Srobert         if (auto *A = dyn_cast<Argument>(V))
2802*d415bd75Srobert           return A->getParent();
2803*d415bd75Srobert         return nullptr;
2804*d415bd75Srobert       }(LHS);
2805*d415bd75Srobert       Opts.NullIsUnknownSize = F ? NullPointerIsDefined(F) : true;
2806*d415bd75Srobert       if (getObjectSize(LHS, LHSSize, DL, TLI, Opts) &&
2807*d415bd75Srobert           getObjectSize(RHS, RHSSize, DL, TLI, Opts) &&
2808*d415bd75Srobert           !LHSOffset.isNegative() && !RHSOffset.isNegative() &&
2809*d415bd75Srobert           LHSOffset.ult(LHSSize) && RHSOffset.ult(RHSSize)) {
2810*d415bd75Srobert         return ConstantInt::get(getCompareTy(LHS),
281109467b48Spatrick                                 !CmpInst::isTrueWhenEqual(Pred));
281209467b48Spatrick       }
281309467b48Spatrick     }
281409467b48Spatrick 
281509467b48Spatrick     // If one side of the equality comparison must come from a noalias call
281609467b48Spatrick     // (meaning a system memory allocation function), and the other side must
281709467b48Spatrick     // come from a pointer that cannot overlap with dynamically-allocated
281809467b48Spatrick     // memory within the lifetime of the current function (allocas, byval
281909467b48Spatrick     // arguments, globals), then determine the comparison result here.
282009467b48Spatrick     SmallVector<const Value *, 8> LHSUObjs, RHSUObjs;
282173471bf0Spatrick     getUnderlyingObjects(LHS, LHSUObjs);
282273471bf0Spatrick     getUnderlyingObjects(RHS, RHSUObjs);
282309467b48Spatrick 
282409467b48Spatrick     // Is the set of underlying objects all noalias calls?
282509467b48Spatrick     auto IsNAC = [](ArrayRef<const Value *> Objects) {
282609467b48Spatrick       return all_of(Objects, isNoAliasCall);
282709467b48Spatrick     };
282809467b48Spatrick 
282909467b48Spatrick     // Is the set of underlying objects all things which must be disjoint from
2830*d415bd75Srobert     // noalias calls.  We assume that indexing from such disjoint storage
2831*d415bd75Srobert     // into the heap is undefined, and thus offsets can be safely ignored.
283209467b48Spatrick     auto IsAllocDisjoint = [](ArrayRef<const Value *> Objects) {
2833*d415bd75Srobert       return all_of(Objects, ::isAllocDisjoint);
283409467b48Spatrick     };
283509467b48Spatrick 
283609467b48Spatrick     if ((IsNAC(LHSUObjs) && IsAllocDisjoint(RHSUObjs)) ||
283709467b48Spatrick         (IsNAC(RHSUObjs) && IsAllocDisjoint(LHSUObjs)))
2838*d415bd75Srobert       return ConstantInt::get(getCompareTy(LHS),
283909467b48Spatrick                               !CmpInst::isTrueWhenEqual(Pred));
284009467b48Spatrick 
284109467b48Spatrick     // Fold comparisons for non-escaping pointer even if the allocation call
284209467b48Spatrick     // cannot be elided. We cannot fold malloc comparison to null. Also, the
2843*d415bd75Srobert     // dynamic allocation call could be either of the operands.  Note that
2844*d415bd75Srobert     // the other operand can not be based on the alloc - if it were, then
2845*d415bd75Srobert     // the cmp itself would be a capture.
284609467b48Spatrick     Value *MI = nullptr;
284709467b48Spatrick     if (isAllocLikeFn(LHS, TLI) &&
284809467b48Spatrick         llvm::isKnownNonZero(RHS, DL, 0, nullptr, CxtI, DT))
284909467b48Spatrick       MI = LHS;
285009467b48Spatrick     else if (isAllocLikeFn(RHS, TLI) &&
285109467b48Spatrick              llvm::isKnownNonZero(LHS, DL, 0, nullptr, CxtI, DT))
285209467b48Spatrick       MI = RHS;
285309467b48Spatrick     // FIXME: We should also fold the compare when the pointer escapes, but the
285409467b48Spatrick     // compare dominates the pointer escape
285509467b48Spatrick     if (MI && !PointerMayBeCaptured(MI, true, true))
2856*d415bd75Srobert       return ConstantInt::get(getCompareTy(LHS),
285709467b48Spatrick                               CmpInst::isFalseWhenEqual(Pred));
285809467b48Spatrick   }
285909467b48Spatrick 
286009467b48Spatrick   // Otherwise, fail.
286109467b48Spatrick   return nullptr;
286209467b48Spatrick }
286309467b48Spatrick 
286409467b48Spatrick /// Fold an icmp when its operands have i1 scalar type.
simplifyICmpOfBools(CmpInst::Predicate Pred,Value * LHS,Value * RHS,const SimplifyQuery & Q)286509467b48Spatrick static Value *simplifyICmpOfBools(CmpInst::Predicate Pred, Value *LHS,
286609467b48Spatrick                                   Value *RHS, const SimplifyQuery &Q) {
2867*d415bd75Srobert   Type *ITy = getCompareTy(LHS); // The return type.
286809467b48Spatrick   Type *OpTy = LHS->getType();   // The operand type.
286909467b48Spatrick   if (!OpTy->isIntOrIntVectorTy(1))
287009467b48Spatrick     return nullptr;
287109467b48Spatrick 
2872*d415bd75Srobert   // A boolean compared to true/false can be reduced in 14 out of the 20
2873*d415bd75Srobert   // (10 predicates * 2 constants) possible combinations. The other
2874*d415bd75Srobert   // 6 cases require a 'not' of the LHS.
2875*d415bd75Srobert 
2876*d415bd75Srobert   auto ExtractNotLHS = [](Value *V) -> Value * {
2877*d415bd75Srobert     Value *X;
2878*d415bd75Srobert     if (match(V, m_Not(m_Value(X))))
2879*d415bd75Srobert       return X;
2880*d415bd75Srobert     return nullptr;
2881*d415bd75Srobert   };
2882*d415bd75Srobert 
288309467b48Spatrick   if (match(RHS, m_Zero())) {
288409467b48Spatrick     switch (Pred) {
288509467b48Spatrick     case CmpInst::ICMP_NE:  // X !=  0 -> X
288609467b48Spatrick     case CmpInst::ICMP_UGT: // X >u  0 -> X
288709467b48Spatrick     case CmpInst::ICMP_SLT: // X <s  0 -> X
288809467b48Spatrick       return LHS;
288909467b48Spatrick 
2890*d415bd75Srobert     case CmpInst::ICMP_EQ:  // not(X) ==  0 -> X != 0 -> X
2891*d415bd75Srobert     case CmpInst::ICMP_ULE: // not(X) <=u 0 -> X >u 0 -> X
2892*d415bd75Srobert     case CmpInst::ICMP_SGE: // not(X) >=s 0 -> X <s 0 -> X
2893*d415bd75Srobert       if (Value *X = ExtractNotLHS(LHS))
2894*d415bd75Srobert         return X;
2895*d415bd75Srobert       break;
2896*d415bd75Srobert 
289709467b48Spatrick     case CmpInst::ICMP_ULT: // X <u  0 -> false
289809467b48Spatrick     case CmpInst::ICMP_SGT: // X >s  0 -> false
289909467b48Spatrick       return getFalse(ITy);
290009467b48Spatrick 
290109467b48Spatrick     case CmpInst::ICMP_UGE: // X >=u 0 -> true
290209467b48Spatrick     case CmpInst::ICMP_SLE: // X <=s 0 -> true
290309467b48Spatrick       return getTrue(ITy);
290409467b48Spatrick 
2905*d415bd75Srobert     default:
2906*d415bd75Srobert       break;
290709467b48Spatrick     }
290809467b48Spatrick   } else if (match(RHS, m_One())) {
290909467b48Spatrick     switch (Pred) {
291009467b48Spatrick     case CmpInst::ICMP_EQ:  // X ==   1 -> X
291109467b48Spatrick     case CmpInst::ICMP_UGE: // X >=u  1 -> X
291209467b48Spatrick     case CmpInst::ICMP_SLE: // X <=s -1 -> X
291309467b48Spatrick       return LHS;
291409467b48Spatrick 
2915*d415bd75Srobert     case CmpInst::ICMP_NE:  // not(X) !=  1 -> X ==   1 -> X
2916*d415bd75Srobert     case CmpInst::ICMP_ULT: // not(X) <=u 1 -> X >=u  1 -> X
2917*d415bd75Srobert     case CmpInst::ICMP_SGT: // not(X) >s  1 -> X <=s -1 -> X
2918*d415bd75Srobert       if (Value *X = ExtractNotLHS(LHS))
2919*d415bd75Srobert         return X;
2920*d415bd75Srobert       break;
2921*d415bd75Srobert 
292209467b48Spatrick     case CmpInst::ICMP_UGT: // X >u   1 -> false
292309467b48Spatrick     case CmpInst::ICMP_SLT: // X <s  -1 -> false
292409467b48Spatrick       return getFalse(ITy);
292509467b48Spatrick 
292609467b48Spatrick     case CmpInst::ICMP_ULE: // X <=u  1 -> true
292709467b48Spatrick     case CmpInst::ICMP_SGE: // X >=s -1 -> true
292809467b48Spatrick       return getTrue(ITy);
292909467b48Spatrick 
2930*d415bd75Srobert     default:
2931*d415bd75Srobert       break;
293209467b48Spatrick     }
293309467b48Spatrick   }
293409467b48Spatrick 
293509467b48Spatrick   switch (Pred) {
293609467b48Spatrick   default:
293709467b48Spatrick     break;
293809467b48Spatrick   case ICmpInst::ICMP_UGE:
2939*d415bd75Srobert     if (isImpliedCondition(RHS, LHS, Q.DL).value_or(false))
294009467b48Spatrick       return getTrue(ITy);
294109467b48Spatrick     break;
294209467b48Spatrick   case ICmpInst::ICMP_SGE:
294309467b48Spatrick     /// For signed comparison, the values for an i1 are 0 and -1
294409467b48Spatrick     /// respectively. This maps into a truth table of:
294509467b48Spatrick     /// LHS | RHS | LHS >=s RHS   | LHS implies RHS
294609467b48Spatrick     ///  0  |  0  |  1 (0 >= 0)   |  1
294709467b48Spatrick     ///  0  |  1  |  1 (0 >= -1)  |  1
294809467b48Spatrick     ///  1  |  0  |  0 (-1 >= 0)  |  0
294909467b48Spatrick     ///  1  |  1  |  1 (-1 >= -1) |  1
2950*d415bd75Srobert     if (isImpliedCondition(LHS, RHS, Q.DL).value_or(false))
295109467b48Spatrick       return getTrue(ITy);
295209467b48Spatrick     break;
295309467b48Spatrick   case ICmpInst::ICMP_ULE:
2954*d415bd75Srobert     if (isImpliedCondition(LHS, RHS, Q.DL).value_or(false))
2955*d415bd75Srobert       return getTrue(ITy);
2956*d415bd75Srobert     break;
2957*d415bd75Srobert   case ICmpInst::ICMP_SLE:
2958*d415bd75Srobert     /// SLE follows the same logic as SGE with the LHS and RHS swapped.
2959*d415bd75Srobert     if (isImpliedCondition(RHS, LHS, Q.DL).value_or(false))
296009467b48Spatrick       return getTrue(ITy);
296109467b48Spatrick     break;
296209467b48Spatrick   }
296309467b48Spatrick 
296409467b48Spatrick   return nullptr;
296509467b48Spatrick }
296609467b48Spatrick 
296709467b48Spatrick /// Try hard to fold icmp with zero RHS because this is a common case.
simplifyICmpWithZero(CmpInst::Predicate Pred,Value * LHS,Value * RHS,const SimplifyQuery & Q)296809467b48Spatrick static Value *simplifyICmpWithZero(CmpInst::Predicate Pred, Value *LHS,
296909467b48Spatrick                                    Value *RHS, const SimplifyQuery &Q) {
297009467b48Spatrick   if (!match(RHS, m_Zero()))
297109467b48Spatrick     return nullptr;
297209467b48Spatrick 
2973*d415bd75Srobert   Type *ITy = getCompareTy(LHS); // The return type.
297409467b48Spatrick   switch (Pred) {
297509467b48Spatrick   default:
297609467b48Spatrick     llvm_unreachable("Unknown ICmp predicate!");
297709467b48Spatrick   case ICmpInst::ICMP_ULT:
297809467b48Spatrick     return getFalse(ITy);
297909467b48Spatrick   case ICmpInst::ICMP_UGE:
298009467b48Spatrick     return getTrue(ITy);
298109467b48Spatrick   case ICmpInst::ICMP_EQ:
298209467b48Spatrick   case ICmpInst::ICMP_ULE:
298309467b48Spatrick     if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo))
298409467b48Spatrick       return getFalse(ITy);
298509467b48Spatrick     break;
298609467b48Spatrick   case ICmpInst::ICMP_NE:
298709467b48Spatrick   case ICmpInst::ICMP_UGT:
298809467b48Spatrick     if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo))
298909467b48Spatrick       return getTrue(ITy);
299009467b48Spatrick     break;
299109467b48Spatrick   case ICmpInst::ICMP_SLT: {
299209467b48Spatrick     KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
299309467b48Spatrick     if (LHSKnown.isNegative())
299409467b48Spatrick       return getTrue(ITy);
299509467b48Spatrick     if (LHSKnown.isNonNegative())
299609467b48Spatrick       return getFalse(ITy);
299709467b48Spatrick     break;
299809467b48Spatrick   }
299909467b48Spatrick   case ICmpInst::ICMP_SLE: {
300009467b48Spatrick     KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
300109467b48Spatrick     if (LHSKnown.isNegative())
300209467b48Spatrick       return getTrue(ITy);
300309467b48Spatrick     if (LHSKnown.isNonNegative() &&
300409467b48Spatrick         isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
300509467b48Spatrick       return getFalse(ITy);
300609467b48Spatrick     break;
300709467b48Spatrick   }
300809467b48Spatrick   case ICmpInst::ICMP_SGE: {
300909467b48Spatrick     KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
301009467b48Spatrick     if (LHSKnown.isNegative())
301109467b48Spatrick       return getFalse(ITy);
301209467b48Spatrick     if (LHSKnown.isNonNegative())
301309467b48Spatrick       return getTrue(ITy);
301409467b48Spatrick     break;
301509467b48Spatrick   }
301609467b48Spatrick   case ICmpInst::ICMP_SGT: {
301709467b48Spatrick     KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
301809467b48Spatrick     if (LHSKnown.isNegative())
301909467b48Spatrick       return getFalse(ITy);
302009467b48Spatrick     if (LHSKnown.isNonNegative() &&
302109467b48Spatrick         isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
302209467b48Spatrick       return getTrue(ITy);
302309467b48Spatrick     break;
302409467b48Spatrick   }
302509467b48Spatrick   }
302609467b48Spatrick 
302709467b48Spatrick   return nullptr;
302809467b48Spatrick }
302909467b48Spatrick 
simplifyICmpWithConstant(CmpInst::Predicate Pred,Value * LHS,Value * RHS,const InstrInfoQuery & IIQ)303009467b48Spatrick static Value *simplifyICmpWithConstant(CmpInst::Predicate Pred, Value *LHS,
303109467b48Spatrick                                        Value *RHS, const InstrInfoQuery &IIQ) {
3032*d415bd75Srobert   Type *ITy = getCompareTy(RHS); // The return type.
303309467b48Spatrick 
303409467b48Spatrick   Value *X;
303509467b48Spatrick   // Sign-bit checks can be optimized to true/false after unsigned
303609467b48Spatrick   // floating-point casts:
303709467b48Spatrick   // icmp slt (bitcast (uitofp X)),  0 --> false
303809467b48Spatrick   // icmp sgt (bitcast (uitofp X)), -1 --> true
303909467b48Spatrick   if (match(LHS, m_BitCast(m_UIToFP(m_Value(X))))) {
304009467b48Spatrick     if (Pred == ICmpInst::ICMP_SLT && match(RHS, m_Zero()))
304109467b48Spatrick       return ConstantInt::getFalse(ITy);
304209467b48Spatrick     if (Pred == ICmpInst::ICMP_SGT && match(RHS, m_AllOnes()))
304309467b48Spatrick       return ConstantInt::getTrue(ITy);
304409467b48Spatrick   }
304509467b48Spatrick 
304609467b48Spatrick   const APInt *C;
304773471bf0Spatrick   if (!match(RHS, m_APIntAllowUndef(C)))
304809467b48Spatrick     return nullptr;
304909467b48Spatrick 
305009467b48Spatrick   // Rule out tautological comparisons (eg., ult 0 or uge 0).
305109467b48Spatrick   ConstantRange RHS_CR = ConstantRange::makeExactICmpRegion(Pred, *C);
305209467b48Spatrick   if (RHS_CR.isEmptySet())
305309467b48Spatrick     return ConstantInt::getFalse(ITy);
305409467b48Spatrick   if (RHS_CR.isFullSet())
305509467b48Spatrick     return ConstantInt::getTrue(ITy);
305609467b48Spatrick 
3057*d415bd75Srobert   ConstantRange LHS_CR =
3058*d415bd75Srobert       computeConstantRange(LHS, CmpInst::isSigned(Pred), IIQ.UseInstrInfo);
305909467b48Spatrick   if (!LHS_CR.isFullSet()) {
306009467b48Spatrick     if (RHS_CR.contains(LHS_CR))
306109467b48Spatrick       return ConstantInt::getTrue(ITy);
306209467b48Spatrick     if (RHS_CR.inverse().contains(LHS_CR))
306309467b48Spatrick       return ConstantInt::getFalse(ITy);
306409467b48Spatrick   }
306509467b48Spatrick 
306673471bf0Spatrick   // (mul nuw/nsw X, MulC) != C --> true  (if C is not a multiple of MulC)
306773471bf0Spatrick   // (mul nuw/nsw X, MulC) == C --> false (if C is not a multiple of MulC)
306873471bf0Spatrick   const APInt *MulC;
306973471bf0Spatrick   if (ICmpInst::isEquality(Pred) &&
307073471bf0Spatrick       ((match(LHS, m_NUWMul(m_Value(), m_APIntAllowUndef(MulC))) &&
307173471bf0Spatrick         *MulC != 0 && C->urem(*MulC) != 0) ||
307273471bf0Spatrick        (match(LHS, m_NSWMul(m_Value(), m_APIntAllowUndef(MulC))) &&
307373471bf0Spatrick         *MulC != 0 && C->srem(*MulC) != 0)))
307473471bf0Spatrick     return ConstantInt::get(ITy, Pred == ICmpInst::ICMP_NE);
307573471bf0Spatrick 
307609467b48Spatrick   return nullptr;
307709467b48Spatrick }
307809467b48Spatrick 
simplifyICmpWithBinOpOnLHS(CmpInst::Predicate Pred,BinaryOperator * LBO,Value * RHS,const SimplifyQuery & Q,unsigned MaxRecurse)3079*d415bd75Srobert static Value *simplifyICmpWithBinOpOnLHS(CmpInst::Predicate Pred,
3080*d415bd75Srobert                                          BinaryOperator *LBO, Value *RHS,
3081*d415bd75Srobert                                          const SimplifyQuery &Q,
3082*d415bd75Srobert                                          unsigned MaxRecurse) {
3083*d415bd75Srobert   Type *ITy = getCompareTy(RHS); // The return type.
308473471bf0Spatrick 
308573471bf0Spatrick   Value *Y = nullptr;
308673471bf0Spatrick   // icmp pred (or X, Y), X
308773471bf0Spatrick   if (match(LBO, m_c_Or(m_Value(Y), m_Specific(RHS)))) {
308873471bf0Spatrick     if (Pred == ICmpInst::ICMP_ULT)
308973471bf0Spatrick       return getFalse(ITy);
309073471bf0Spatrick     if (Pred == ICmpInst::ICMP_UGE)
309173471bf0Spatrick       return getTrue(ITy);
309273471bf0Spatrick 
309373471bf0Spatrick     if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
309473471bf0Spatrick       KnownBits RHSKnown = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
309573471bf0Spatrick       KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
309673471bf0Spatrick       if (RHSKnown.isNonNegative() && YKnown.isNegative())
309773471bf0Spatrick         return Pred == ICmpInst::ICMP_SLT ? getTrue(ITy) : getFalse(ITy);
309873471bf0Spatrick       if (RHSKnown.isNegative() || YKnown.isNonNegative())
309973471bf0Spatrick         return Pred == ICmpInst::ICMP_SLT ? getFalse(ITy) : getTrue(ITy);
310073471bf0Spatrick     }
310173471bf0Spatrick   }
310273471bf0Spatrick 
310373471bf0Spatrick   // icmp pred (and X, Y), X
310473471bf0Spatrick   if (match(LBO, m_c_And(m_Value(), m_Specific(RHS)))) {
310573471bf0Spatrick     if (Pred == ICmpInst::ICMP_UGT)
310673471bf0Spatrick       return getFalse(ITy);
310773471bf0Spatrick     if (Pred == ICmpInst::ICMP_ULE)
310873471bf0Spatrick       return getTrue(ITy);
310973471bf0Spatrick   }
311073471bf0Spatrick 
311173471bf0Spatrick   // icmp pred (urem X, Y), Y
311273471bf0Spatrick   if (match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
311373471bf0Spatrick     switch (Pred) {
311473471bf0Spatrick     default:
311573471bf0Spatrick       break;
311673471bf0Spatrick     case ICmpInst::ICMP_SGT:
311773471bf0Spatrick     case ICmpInst::ICMP_SGE: {
311873471bf0Spatrick       KnownBits Known = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
311973471bf0Spatrick       if (!Known.isNonNegative())
312073471bf0Spatrick         break;
3121*d415bd75Srobert       [[fallthrough]];
312273471bf0Spatrick     }
312373471bf0Spatrick     case ICmpInst::ICMP_EQ:
312473471bf0Spatrick     case ICmpInst::ICMP_UGT:
312573471bf0Spatrick     case ICmpInst::ICMP_UGE:
312673471bf0Spatrick       return getFalse(ITy);
312773471bf0Spatrick     case ICmpInst::ICMP_SLT:
312873471bf0Spatrick     case ICmpInst::ICMP_SLE: {
312973471bf0Spatrick       KnownBits Known = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
313073471bf0Spatrick       if (!Known.isNonNegative())
313173471bf0Spatrick         break;
3132*d415bd75Srobert       [[fallthrough]];
313373471bf0Spatrick     }
313473471bf0Spatrick     case ICmpInst::ICMP_NE:
313573471bf0Spatrick     case ICmpInst::ICMP_ULT:
313673471bf0Spatrick     case ICmpInst::ICMP_ULE:
313773471bf0Spatrick       return getTrue(ITy);
313873471bf0Spatrick     }
313973471bf0Spatrick   }
314073471bf0Spatrick 
314173471bf0Spatrick   // icmp pred (urem X, Y), X
314273471bf0Spatrick   if (match(LBO, m_URem(m_Specific(RHS), m_Value()))) {
314373471bf0Spatrick     if (Pred == ICmpInst::ICMP_ULE)
314473471bf0Spatrick       return getTrue(ITy);
314573471bf0Spatrick     if (Pred == ICmpInst::ICMP_UGT)
314673471bf0Spatrick       return getFalse(ITy);
314773471bf0Spatrick   }
314873471bf0Spatrick 
3149*d415bd75Srobert   // x >>u y <=u x --> true.
3150*d415bd75Srobert   // x >>u y >u  x --> false.
3151*d415bd75Srobert   // x udiv y <=u x --> true.
3152*d415bd75Srobert   // x udiv y >u  x --> false.
315373471bf0Spatrick   if (match(LBO, m_LShr(m_Specific(RHS), m_Value())) ||
315473471bf0Spatrick       match(LBO, m_UDiv(m_Specific(RHS), m_Value()))) {
315573471bf0Spatrick     // icmp pred (X op Y), X
315673471bf0Spatrick     if (Pred == ICmpInst::ICMP_UGT)
315773471bf0Spatrick       return getFalse(ITy);
315873471bf0Spatrick     if (Pred == ICmpInst::ICMP_ULE)
315973471bf0Spatrick       return getTrue(ITy);
316073471bf0Spatrick   }
316173471bf0Spatrick 
3162*d415bd75Srobert   // If x is nonzero:
3163*d415bd75Srobert   // x >>u C <u  x --> true  for C != 0.
3164*d415bd75Srobert   // x >>u C !=  x --> true  for C != 0.
3165*d415bd75Srobert   // x >>u C >=u x --> false for C != 0.
3166*d415bd75Srobert   // x >>u C ==  x --> false for C != 0.
3167*d415bd75Srobert   // x udiv C <u  x --> true  for C != 1.
3168*d415bd75Srobert   // x udiv C !=  x --> true  for C != 1.
3169*d415bd75Srobert   // x udiv C >=u x --> false for C != 1.
3170*d415bd75Srobert   // x udiv C ==  x --> false for C != 1.
3171*d415bd75Srobert   // TODO: allow non-constant shift amount/divisor
3172*d415bd75Srobert   const APInt *C;
3173*d415bd75Srobert   if ((match(LBO, m_LShr(m_Specific(RHS), m_APInt(C))) && *C != 0) ||
3174*d415bd75Srobert       (match(LBO, m_UDiv(m_Specific(RHS), m_APInt(C))) && *C != 1)) {
3175*d415bd75Srobert     if (isKnownNonZero(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT)) {
3176*d415bd75Srobert       switch (Pred) {
3177*d415bd75Srobert       default:
3178*d415bd75Srobert         break;
3179*d415bd75Srobert       case ICmpInst::ICMP_EQ:
3180*d415bd75Srobert       case ICmpInst::ICMP_UGE:
3181*d415bd75Srobert         return getFalse(ITy);
3182*d415bd75Srobert       case ICmpInst::ICMP_NE:
3183*d415bd75Srobert       case ICmpInst::ICMP_ULT:
3184*d415bd75Srobert         return getTrue(ITy);
3185*d415bd75Srobert       case ICmpInst::ICMP_UGT:
3186*d415bd75Srobert       case ICmpInst::ICMP_ULE:
3187*d415bd75Srobert         // UGT/ULE are handled by the more general case just above
3188*d415bd75Srobert         llvm_unreachable("Unexpected UGT/ULE, should have been handled");
3189*d415bd75Srobert       }
3190*d415bd75Srobert     }
3191*d415bd75Srobert   }
3192*d415bd75Srobert 
319373471bf0Spatrick   // (x*C1)/C2 <= x for C1 <= C2.
319473471bf0Spatrick   // This holds even if the multiplication overflows: Assume that x != 0 and
319573471bf0Spatrick   // arithmetic is modulo M. For overflow to occur we must have C1 >= M/x and
319673471bf0Spatrick   // thus C2 >= M/x. It follows that (x*C1)/C2 <= (M-1)/C2 <= ((M-1)*x)/M < x.
319773471bf0Spatrick   //
319873471bf0Spatrick   // Additionally, either the multiplication and division might be represented
319973471bf0Spatrick   // as shifts:
320073471bf0Spatrick   // (x*C1)>>C2 <= x for C1 < 2**C2.
320173471bf0Spatrick   // (x<<C1)/C2 <= x for 2**C1 < C2.
320273471bf0Spatrick   const APInt *C1, *C2;
320373471bf0Spatrick   if ((match(LBO, m_UDiv(m_Mul(m_Specific(RHS), m_APInt(C1)), m_APInt(C2))) &&
320473471bf0Spatrick        C1->ule(*C2)) ||
320573471bf0Spatrick       (match(LBO, m_LShr(m_Mul(m_Specific(RHS), m_APInt(C1)), m_APInt(C2))) &&
320673471bf0Spatrick        C1->ule(APInt(C2->getBitWidth(), 1) << *C2)) ||
320773471bf0Spatrick       (match(LBO, m_UDiv(m_Shl(m_Specific(RHS), m_APInt(C1)), m_APInt(C2))) &&
320873471bf0Spatrick        (APInt(C1->getBitWidth(), 1) << *C1).ule(*C2))) {
320973471bf0Spatrick     if (Pred == ICmpInst::ICMP_UGT)
321073471bf0Spatrick       return getFalse(ITy);
321173471bf0Spatrick     if (Pred == ICmpInst::ICMP_ULE)
321273471bf0Spatrick       return getTrue(ITy);
321373471bf0Spatrick   }
321473471bf0Spatrick 
3215*d415bd75Srobert   // (sub C, X) == X, C is odd  --> false
3216*d415bd75Srobert   // (sub C, X) != X, C is odd  --> true
3217*d415bd75Srobert   if (match(LBO, m_Sub(m_APIntAllowUndef(C), m_Specific(RHS))) &&
3218*d415bd75Srobert       (*C & 1) == 1 && ICmpInst::isEquality(Pred))
3219*d415bd75Srobert     return (Pred == ICmpInst::ICMP_EQ) ? getFalse(ITy) : getTrue(ITy);
3220*d415bd75Srobert 
322173471bf0Spatrick   return nullptr;
322273471bf0Spatrick }
322373471bf0Spatrick 
322473471bf0Spatrick // If only one of the icmp's operands has NSW flags, try to prove that:
322573471bf0Spatrick //
322673471bf0Spatrick //   icmp slt (x + C1), (x +nsw C2)
322773471bf0Spatrick //
322873471bf0Spatrick // is equivalent to:
322973471bf0Spatrick //
323073471bf0Spatrick //   icmp slt C1, C2
323173471bf0Spatrick //
323273471bf0Spatrick // which is true if x + C2 has the NSW flags set and:
323373471bf0Spatrick // *) C1 < C2 && C1 >= 0, or
323473471bf0Spatrick // *) C2 < C1 && C1 <= 0.
323573471bf0Spatrick //
trySimplifyICmpWithAdds(CmpInst::Predicate Pred,Value * LHS,Value * RHS)323673471bf0Spatrick static bool trySimplifyICmpWithAdds(CmpInst::Predicate Pred, Value *LHS,
323773471bf0Spatrick                                     Value *RHS) {
323873471bf0Spatrick   // TODO: only support icmp slt for now.
323973471bf0Spatrick   if (Pred != CmpInst::ICMP_SLT)
324073471bf0Spatrick     return false;
324173471bf0Spatrick 
324273471bf0Spatrick   // Canonicalize nsw add as RHS.
324373471bf0Spatrick   if (!match(RHS, m_NSWAdd(m_Value(), m_Value())))
324473471bf0Spatrick     std::swap(LHS, RHS);
324573471bf0Spatrick   if (!match(RHS, m_NSWAdd(m_Value(), m_Value())))
324673471bf0Spatrick     return false;
324773471bf0Spatrick 
324873471bf0Spatrick   Value *X;
324973471bf0Spatrick   const APInt *C1, *C2;
325073471bf0Spatrick   if (!match(LHS, m_c_Add(m_Value(X), m_APInt(C1))) ||
325173471bf0Spatrick       !match(RHS, m_c_Add(m_Specific(X), m_APInt(C2))))
325273471bf0Spatrick     return false;
325373471bf0Spatrick 
325473471bf0Spatrick   return (C1->slt(*C2) && C1->isNonNegative()) ||
325573471bf0Spatrick          (C2->slt(*C1) && C1->isNonPositive());
325673471bf0Spatrick }
325773471bf0Spatrick 
325809467b48Spatrick /// TODO: A large part of this logic is duplicated in InstCombine's
325909467b48Spatrick /// foldICmpBinOp(). We should be able to share that and avoid the code
326009467b48Spatrick /// duplication.
simplifyICmpWithBinOp(CmpInst::Predicate Pred,Value * LHS,Value * RHS,const SimplifyQuery & Q,unsigned MaxRecurse)326109467b48Spatrick static Value *simplifyICmpWithBinOp(CmpInst::Predicate Pred, Value *LHS,
326209467b48Spatrick                                     Value *RHS, const SimplifyQuery &Q,
326309467b48Spatrick                                     unsigned MaxRecurse) {
326409467b48Spatrick   BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
326509467b48Spatrick   BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
326609467b48Spatrick   if (MaxRecurse && (LBO || RBO)) {
326709467b48Spatrick     // Analyze the case when either LHS or RHS is an add instruction.
326809467b48Spatrick     Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
326909467b48Spatrick     // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
327009467b48Spatrick     bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
327109467b48Spatrick     if (LBO && LBO->getOpcode() == Instruction::Add) {
327209467b48Spatrick       A = LBO->getOperand(0);
327309467b48Spatrick       B = LBO->getOperand(1);
327409467b48Spatrick       NoLHSWrapProblem =
327509467b48Spatrick           ICmpInst::isEquality(Pred) ||
327609467b48Spatrick           (CmpInst::isUnsigned(Pred) &&
327709467b48Spatrick            Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(LBO))) ||
327809467b48Spatrick           (CmpInst::isSigned(Pred) &&
327909467b48Spatrick            Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(LBO)));
328009467b48Spatrick     }
328109467b48Spatrick     if (RBO && RBO->getOpcode() == Instruction::Add) {
328209467b48Spatrick       C = RBO->getOperand(0);
328309467b48Spatrick       D = RBO->getOperand(1);
328409467b48Spatrick       NoRHSWrapProblem =
328509467b48Spatrick           ICmpInst::isEquality(Pred) ||
328609467b48Spatrick           (CmpInst::isUnsigned(Pred) &&
328709467b48Spatrick            Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(RBO))) ||
328809467b48Spatrick           (CmpInst::isSigned(Pred) &&
328909467b48Spatrick            Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(RBO)));
329009467b48Spatrick     }
329109467b48Spatrick 
329209467b48Spatrick     // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
329309467b48Spatrick     if ((A == RHS || B == RHS) && NoLHSWrapProblem)
3294*d415bd75Srobert       if (Value *V = simplifyICmpInst(Pred, A == RHS ? B : A,
329509467b48Spatrick                                       Constant::getNullValue(RHS->getType()), Q,
329609467b48Spatrick                                       MaxRecurse - 1))
329709467b48Spatrick         return V;
329809467b48Spatrick 
329909467b48Spatrick     // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
330009467b48Spatrick     if ((C == LHS || D == LHS) && NoRHSWrapProblem)
330109467b48Spatrick       if (Value *V =
3302*d415bd75Srobert               simplifyICmpInst(Pred, Constant::getNullValue(LHS->getType()),
330309467b48Spatrick                                C == LHS ? D : C, Q, MaxRecurse - 1))
330409467b48Spatrick         return V;
330509467b48Spatrick 
330609467b48Spatrick     // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
330773471bf0Spatrick     bool CanSimplify = (NoLHSWrapProblem && NoRHSWrapProblem) ||
330873471bf0Spatrick                        trySimplifyICmpWithAdds(Pred, LHS, RHS);
330973471bf0Spatrick     if (A && C && (A == C || A == D || B == C || B == D) && CanSimplify) {
331009467b48Spatrick       // Determine Y and Z in the form icmp (X+Y), (X+Z).
331109467b48Spatrick       Value *Y, *Z;
331209467b48Spatrick       if (A == C) {
331309467b48Spatrick         // C + B == C + D  ->  B == D
331409467b48Spatrick         Y = B;
331509467b48Spatrick         Z = D;
331609467b48Spatrick       } else if (A == D) {
331709467b48Spatrick         // D + B == C + D  ->  B == C
331809467b48Spatrick         Y = B;
331909467b48Spatrick         Z = C;
332009467b48Spatrick       } else if (B == C) {
332109467b48Spatrick         // A + C == C + D  ->  A == D
332209467b48Spatrick         Y = A;
332309467b48Spatrick         Z = D;
332409467b48Spatrick       } else {
332509467b48Spatrick         assert(B == D);
332609467b48Spatrick         // A + D == C + D  ->  A == C
332709467b48Spatrick         Y = A;
332809467b48Spatrick         Z = C;
332909467b48Spatrick       }
3330*d415bd75Srobert       if (Value *V = simplifyICmpInst(Pred, Y, Z, Q, MaxRecurse - 1))
333109467b48Spatrick         return V;
333209467b48Spatrick     }
333309467b48Spatrick   }
333409467b48Spatrick 
333573471bf0Spatrick   if (LBO)
333673471bf0Spatrick     if (Value *V = simplifyICmpWithBinOpOnLHS(Pred, LBO, RHS, Q, MaxRecurse))
333773471bf0Spatrick       return V;
333809467b48Spatrick 
333973471bf0Spatrick   if (RBO)
334073471bf0Spatrick     if (Value *V = simplifyICmpWithBinOpOnLHS(
334173471bf0Spatrick             ICmpInst::getSwappedPredicate(Pred), RBO, LHS, Q, MaxRecurse))
334273471bf0Spatrick       return V;
334309467b48Spatrick 
334409467b48Spatrick   // 0 - (zext X) pred C
334509467b48Spatrick   if (!CmpInst::isUnsigned(Pred) && match(LHS, m_Neg(m_ZExt(m_Value())))) {
334673471bf0Spatrick     const APInt *C;
334773471bf0Spatrick     if (match(RHS, m_APInt(C))) {
334873471bf0Spatrick       if (C->isStrictlyPositive()) {
334973471bf0Spatrick         if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_NE)
3350*d415bd75Srobert           return ConstantInt::getTrue(getCompareTy(RHS));
335173471bf0Spatrick         if (Pred == ICmpInst::ICMP_SGE || Pred == ICmpInst::ICMP_EQ)
3352*d415bd75Srobert           return ConstantInt::getFalse(getCompareTy(RHS));
335309467b48Spatrick       }
335473471bf0Spatrick       if (C->isNonNegative()) {
335509467b48Spatrick         if (Pred == ICmpInst::ICMP_SLE)
3356*d415bd75Srobert           return ConstantInt::getTrue(getCompareTy(RHS));
335709467b48Spatrick         if (Pred == ICmpInst::ICMP_SGT)
3358*d415bd75Srobert           return ConstantInt::getFalse(getCompareTy(RHS));
335909467b48Spatrick       }
336009467b48Spatrick     }
336109467b48Spatrick   }
336209467b48Spatrick 
336373471bf0Spatrick   //   If C2 is a power-of-2 and C is not:
336473471bf0Spatrick   //   (C2 << X) == C --> false
336573471bf0Spatrick   //   (C2 << X) != C --> true
336673471bf0Spatrick   const APInt *C;
336773471bf0Spatrick   if (match(LHS, m_Shl(m_Power2(), m_Value())) &&
336873471bf0Spatrick       match(RHS, m_APIntAllowUndef(C)) && !C->isPowerOf2()) {
336973471bf0Spatrick     // C2 << X can equal zero in some circumstances.
337073471bf0Spatrick     // This simplification might be unsafe if C is zero.
337109467b48Spatrick     //
337209467b48Spatrick     // We know it is safe if:
337373471bf0Spatrick     // - The shift is nsw. We can't shift out the one bit.
337473471bf0Spatrick     // - The shift is nuw. We can't shift out the one bit.
337573471bf0Spatrick     // - C2 is one.
337673471bf0Spatrick     // - C isn't zero.
337709467b48Spatrick     if (Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(LBO)) ||
337809467b48Spatrick         Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(LBO)) ||
3379*d415bd75Srobert         match(LHS, m_Shl(m_One(), m_Value())) || !C->isZero()) {
338009467b48Spatrick       if (Pred == ICmpInst::ICMP_EQ)
3381*d415bd75Srobert         return ConstantInt::getFalse(getCompareTy(RHS));
338209467b48Spatrick       if (Pred == ICmpInst::ICMP_NE)
3383*d415bd75Srobert         return ConstantInt::getTrue(getCompareTy(RHS));
338409467b48Spatrick     }
338509467b48Spatrick   }
338673471bf0Spatrick 
338773471bf0Spatrick   // TODO: This is overly constrained. LHS can be any power-of-2.
338873471bf0Spatrick   // (1 << X)  >u 0x8000 --> false
338973471bf0Spatrick   // (1 << X) <=u 0x8000 --> true
339073471bf0Spatrick   if (match(LHS, m_Shl(m_One(), m_Value())) && match(RHS, m_SignMask())) {
339109467b48Spatrick     if (Pred == ICmpInst::ICMP_UGT)
3392*d415bd75Srobert       return ConstantInt::getFalse(getCompareTy(RHS));
339309467b48Spatrick     if (Pred == ICmpInst::ICMP_ULE)
3394*d415bd75Srobert       return ConstantInt::getTrue(getCompareTy(RHS));
339509467b48Spatrick   }
339609467b48Spatrick 
339709467b48Spatrick   if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
339809467b48Spatrick       LBO->getOperand(1) == RBO->getOperand(1)) {
339909467b48Spatrick     switch (LBO->getOpcode()) {
340009467b48Spatrick     default:
340109467b48Spatrick       break;
340209467b48Spatrick     case Instruction::UDiv:
340309467b48Spatrick     case Instruction::LShr:
340409467b48Spatrick       if (ICmpInst::isSigned(Pred) || !Q.IIQ.isExact(LBO) ||
340509467b48Spatrick           !Q.IIQ.isExact(RBO))
340609467b48Spatrick         break;
3407*d415bd75Srobert       if (Value *V = simplifyICmpInst(Pred, LBO->getOperand(0),
340809467b48Spatrick                                       RBO->getOperand(0), Q, MaxRecurse - 1))
340909467b48Spatrick         return V;
341009467b48Spatrick       break;
341109467b48Spatrick     case Instruction::SDiv:
341209467b48Spatrick       if (!ICmpInst::isEquality(Pred) || !Q.IIQ.isExact(LBO) ||
341309467b48Spatrick           !Q.IIQ.isExact(RBO))
341409467b48Spatrick         break;
3415*d415bd75Srobert       if (Value *V = simplifyICmpInst(Pred, LBO->getOperand(0),
341609467b48Spatrick                                       RBO->getOperand(0), Q, MaxRecurse - 1))
341709467b48Spatrick         return V;
341809467b48Spatrick       break;
341909467b48Spatrick     case Instruction::AShr:
342009467b48Spatrick       if (!Q.IIQ.isExact(LBO) || !Q.IIQ.isExact(RBO))
342109467b48Spatrick         break;
3422*d415bd75Srobert       if (Value *V = simplifyICmpInst(Pred, LBO->getOperand(0),
342309467b48Spatrick                                       RBO->getOperand(0), Q, MaxRecurse - 1))
342409467b48Spatrick         return V;
342509467b48Spatrick       break;
342609467b48Spatrick     case Instruction::Shl: {
342709467b48Spatrick       bool NUW = Q.IIQ.hasNoUnsignedWrap(LBO) && Q.IIQ.hasNoUnsignedWrap(RBO);
342809467b48Spatrick       bool NSW = Q.IIQ.hasNoSignedWrap(LBO) && Q.IIQ.hasNoSignedWrap(RBO);
342909467b48Spatrick       if (!NUW && !NSW)
343009467b48Spatrick         break;
343109467b48Spatrick       if (!NSW && ICmpInst::isSigned(Pred))
343209467b48Spatrick         break;
3433*d415bd75Srobert       if (Value *V = simplifyICmpInst(Pred, LBO->getOperand(0),
343409467b48Spatrick                                       RBO->getOperand(0), Q, MaxRecurse - 1))
343509467b48Spatrick         return V;
343609467b48Spatrick       break;
343709467b48Spatrick     }
343809467b48Spatrick     }
343909467b48Spatrick   }
344009467b48Spatrick   return nullptr;
344109467b48Spatrick }
344209467b48Spatrick 
3443*d415bd75Srobert /// simplify integer comparisons where at least one operand of the compare
344409467b48Spatrick /// matches an integer min/max idiom.
simplifyICmpWithMinMax(CmpInst::Predicate Pred,Value * LHS,Value * RHS,const SimplifyQuery & Q,unsigned MaxRecurse)344509467b48Spatrick static Value *simplifyICmpWithMinMax(CmpInst::Predicate Pred, Value *LHS,
344609467b48Spatrick                                      Value *RHS, const SimplifyQuery &Q,
344709467b48Spatrick                                      unsigned MaxRecurse) {
3448*d415bd75Srobert   Type *ITy = getCompareTy(LHS); // The return type.
344909467b48Spatrick   Value *A, *B;
345009467b48Spatrick   CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
345109467b48Spatrick   CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
345209467b48Spatrick 
345309467b48Spatrick   // Signed variants on "max(a,b)>=a -> true".
345409467b48Spatrick   if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
345509467b48Spatrick     if (A != RHS)
345609467b48Spatrick       std::swap(A, B);       // smax(A, B) pred A.
345709467b48Spatrick     EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
345809467b48Spatrick     // We analyze this as smax(A, B) pred A.
345909467b48Spatrick     P = Pred;
346009467b48Spatrick   } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
346109467b48Spatrick              (A == LHS || B == LHS)) {
346209467b48Spatrick     if (A != LHS)
346309467b48Spatrick       std::swap(A, B);       // A pred smax(A, B).
346409467b48Spatrick     EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
346509467b48Spatrick     // We analyze this as smax(A, B) swapped-pred A.
346609467b48Spatrick     P = CmpInst::getSwappedPredicate(Pred);
346709467b48Spatrick   } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
346809467b48Spatrick              (A == RHS || B == RHS)) {
346909467b48Spatrick     if (A != RHS)
347009467b48Spatrick       std::swap(A, B);       // smin(A, B) pred A.
347109467b48Spatrick     EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
347209467b48Spatrick     // We analyze this as smax(-A, -B) swapped-pred -A.
347309467b48Spatrick     // Note that we do not need to actually form -A or -B thanks to EqP.
347409467b48Spatrick     P = CmpInst::getSwappedPredicate(Pred);
347509467b48Spatrick   } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
347609467b48Spatrick              (A == LHS || B == LHS)) {
347709467b48Spatrick     if (A != LHS)
347809467b48Spatrick       std::swap(A, B);       // A pred smin(A, B).
347909467b48Spatrick     EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
348009467b48Spatrick     // We analyze this as smax(-A, -B) pred -A.
348109467b48Spatrick     // Note that we do not need to actually form -A or -B thanks to EqP.
348209467b48Spatrick     P = Pred;
348309467b48Spatrick   }
348409467b48Spatrick   if (P != CmpInst::BAD_ICMP_PREDICATE) {
348509467b48Spatrick     // Cases correspond to "max(A, B) p A".
348609467b48Spatrick     switch (P) {
348709467b48Spatrick     default:
348809467b48Spatrick       break;
348909467b48Spatrick     case CmpInst::ICMP_EQ:
349009467b48Spatrick     case CmpInst::ICMP_SLE:
349109467b48Spatrick       // Equivalent to "A EqP B".  This may be the same as the condition tested
349209467b48Spatrick       // in the max/min; if so, we can just return that.
3493*d415bd75Srobert       if (Value *V = extractEquivalentCondition(LHS, EqP, A, B))
349409467b48Spatrick         return V;
3495*d415bd75Srobert       if (Value *V = extractEquivalentCondition(RHS, EqP, A, B))
349609467b48Spatrick         return V;
349709467b48Spatrick       // Otherwise, see if "A EqP B" simplifies.
349809467b48Spatrick       if (MaxRecurse)
3499*d415bd75Srobert         if (Value *V = simplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
350009467b48Spatrick           return V;
350109467b48Spatrick       break;
350209467b48Spatrick     case CmpInst::ICMP_NE:
350309467b48Spatrick     case CmpInst::ICMP_SGT: {
350409467b48Spatrick       CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
350509467b48Spatrick       // Equivalent to "A InvEqP B".  This may be the same as the condition
350609467b48Spatrick       // tested in the max/min; if so, we can just return that.
3507*d415bd75Srobert       if (Value *V = extractEquivalentCondition(LHS, InvEqP, A, B))
350809467b48Spatrick         return V;
3509*d415bd75Srobert       if (Value *V = extractEquivalentCondition(RHS, InvEqP, A, B))
351009467b48Spatrick         return V;
351109467b48Spatrick       // Otherwise, see if "A InvEqP B" simplifies.
351209467b48Spatrick       if (MaxRecurse)
3513*d415bd75Srobert         if (Value *V = simplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
351409467b48Spatrick           return V;
351509467b48Spatrick       break;
351609467b48Spatrick     }
351709467b48Spatrick     case CmpInst::ICMP_SGE:
351809467b48Spatrick       // Always true.
351909467b48Spatrick       return getTrue(ITy);
352009467b48Spatrick     case CmpInst::ICMP_SLT:
352109467b48Spatrick       // Always false.
352209467b48Spatrick       return getFalse(ITy);
352309467b48Spatrick     }
352409467b48Spatrick   }
352509467b48Spatrick 
352609467b48Spatrick   // Unsigned variants on "max(a,b)>=a -> true".
352709467b48Spatrick   P = CmpInst::BAD_ICMP_PREDICATE;
352809467b48Spatrick   if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
352909467b48Spatrick     if (A != RHS)
353009467b48Spatrick       std::swap(A, B);       // umax(A, B) pred A.
353109467b48Spatrick     EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
353209467b48Spatrick     // We analyze this as umax(A, B) pred A.
353309467b48Spatrick     P = Pred;
353409467b48Spatrick   } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
353509467b48Spatrick              (A == LHS || B == LHS)) {
353609467b48Spatrick     if (A != LHS)
353709467b48Spatrick       std::swap(A, B);       // A pred umax(A, B).
353809467b48Spatrick     EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
353909467b48Spatrick     // We analyze this as umax(A, B) swapped-pred A.
354009467b48Spatrick     P = CmpInst::getSwappedPredicate(Pred);
354109467b48Spatrick   } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
354209467b48Spatrick              (A == RHS || B == RHS)) {
354309467b48Spatrick     if (A != RHS)
354409467b48Spatrick       std::swap(A, B);       // umin(A, B) pred A.
354509467b48Spatrick     EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
354609467b48Spatrick     // We analyze this as umax(-A, -B) swapped-pred -A.
354709467b48Spatrick     // Note that we do not need to actually form -A or -B thanks to EqP.
354809467b48Spatrick     P = CmpInst::getSwappedPredicate(Pred);
354909467b48Spatrick   } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
355009467b48Spatrick              (A == LHS || B == LHS)) {
355109467b48Spatrick     if (A != LHS)
355209467b48Spatrick       std::swap(A, B);       // A pred umin(A, B).
355309467b48Spatrick     EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
355409467b48Spatrick     // We analyze this as umax(-A, -B) pred -A.
355509467b48Spatrick     // Note that we do not need to actually form -A or -B thanks to EqP.
355609467b48Spatrick     P = Pred;
355709467b48Spatrick   }
355809467b48Spatrick   if (P != CmpInst::BAD_ICMP_PREDICATE) {
355909467b48Spatrick     // Cases correspond to "max(A, B) p A".
356009467b48Spatrick     switch (P) {
356109467b48Spatrick     default:
356209467b48Spatrick       break;
356309467b48Spatrick     case CmpInst::ICMP_EQ:
356409467b48Spatrick     case CmpInst::ICMP_ULE:
356509467b48Spatrick       // Equivalent to "A EqP B".  This may be the same as the condition tested
356609467b48Spatrick       // in the max/min; if so, we can just return that.
3567*d415bd75Srobert       if (Value *V = extractEquivalentCondition(LHS, EqP, A, B))
356809467b48Spatrick         return V;
3569*d415bd75Srobert       if (Value *V = extractEquivalentCondition(RHS, EqP, A, B))
357009467b48Spatrick         return V;
357109467b48Spatrick       // Otherwise, see if "A EqP B" simplifies.
357209467b48Spatrick       if (MaxRecurse)
3573*d415bd75Srobert         if (Value *V = simplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
357409467b48Spatrick           return V;
357509467b48Spatrick       break;
357609467b48Spatrick     case CmpInst::ICMP_NE:
357709467b48Spatrick     case CmpInst::ICMP_UGT: {
357809467b48Spatrick       CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
357909467b48Spatrick       // Equivalent to "A InvEqP B".  This may be the same as the condition
358009467b48Spatrick       // tested in the max/min; if so, we can just return that.
3581*d415bd75Srobert       if (Value *V = extractEquivalentCondition(LHS, InvEqP, A, B))
358209467b48Spatrick         return V;
3583*d415bd75Srobert       if (Value *V = extractEquivalentCondition(RHS, InvEqP, A, B))
358409467b48Spatrick         return V;
358509467b48Spatrick       // Otherwise, see if "A InvEqP B" simplifies.
358609467b48Spatrick       if (MaxRecurse)
3587*d415bd75Srobert         if (Value *V = simplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
358809467b48Spatrick           return V;
358909467b48Spatrick       break;
359009467b48Spatrick     }
359109467b48Spatrick     case CmpInst::ICMP_UGE:
359209467b48Spatrick       return getTrue(ITy);
359309467b48Spatrick     case CmpInst::ICMP_ULT:
359409467b48Spatrick       return getFalse(ITy);
359509467b48Spatrick     }
359609467b48Spatrick   }
359709467b48Spatrick 
359873471bf0Spatrick   // Comparing 1 each of min/max with a common operand?
359973471bf0Spatrick   // Canonicalize min operand to RHS.
360073471bf0Spatrick   if (match(LHS, m_UMin(m_Value(), m_Value())) ||
360173471bf0Spatrick       match(LHS, m_SMin(m_Value(), m_Value()))) {
360273471bf0Spatrick     std::swap(LHS, RHS);
360373471bf0Spatrick     Pred = ICmpInst::getSwappedPredicate(Pred);
360473471bf0Spatrick   }
360573471bf0Spatrick 
360609467b48Spatrick   Value *C, *D;
360709467b48Spatrick   if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
360809467b48Spatrick       match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
360909467b48Spatrick       (A == C || A == D || B == C || B == D)) {
361073471bf0Spatrick     // smax(A, B) >=s smin(A, D) --> true
361109467b48Spatrick     if (Pred == CmpInst::ICMP_SGE)
361209467b48Spatrick       return getTrue(ITy);
361373471bf0Spatrick     // smax(A, B) <s smin(A, D) --> false
361409467b48Spatrick     if (Pred == CmpInst::ICMP_SLT)
361509467b48Spatrick       return getFalse(ITy);
361609467b48Spatrick   } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
361709467b48Spatrick              match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
361809467b48Spatrick              (A == C || A == D || B == C || B == D)) {
361973471bf0Spatrick     // umax(A, B) >=u umin(A, D) --> true
362009467b48Spatrick     if (Pred == CmpInst::ICMP_UGE)
362109467b48Spatrick       return getTrue(ITy);
362273471bf0Spatrick     // umax(A, B) <u umin(A, D) --> false
362309467b48Spatrick     if (Pred == CmpInst::ICMP_ULT)
362409467b48Spatrick       return getFalse(ITy);
362509467b48Spatrick   }
362609467b48Spatrick 
362709467b48Spatrick   return nullptr;
362809467b48Spatrick }
362909467b48Spatrick 
simplifyICmpWithDominatingAssume(CmpInst::Predicate Predicate,Value * LHS,Value * RHS,const SimplifyQuery & Q)3630097a140dSpatrick static Value *simplifyICmpWithDominatingAssume(CmpInst::Predicate Predicate,
3631097a140dSpatrick                                                Value *LHS, Value *RHS,
3632097a140dSpatrick                                                const SimplifyQuery &Q) {
3633097a140dSpatrick   // Gracefully handle instructions that have not been inserted yet.
3634097a140dSpatrick   if (!Q.AC || !Q.CxtI || !Q.CxtI->getParent())
3635097a140dSpatrick     return nullptr;
3636097a140dSpatrick 
3637097a140dSpatrick   for (Value *AssumeBaseOp : {LHS, RHS}) {
3638097a140dSpatrick     for (auto &AssumeVH : Q.AC->assumptionsFor(AssumeBaseOp)) {
3639097a140dSpatrick       if (!AssumeVH)
3640097a140dSpatrick         continue;
3641097a140dSpatrick 
3642097a140dSpatrick       CallInst *Assume = cast<CallInst>(AssumeVH);
3643*d415bd75Srobert       if (std::optional<bool> Imp = isImpliedCondition(
3644*d415bd75Srobert               Assume->getArgOperand(0), Predicate, LHS, RHS, Q.DL))
3645097a140dSpatrick         if (isValidAssumeForContext(Assume, Q.CxtI, Q.DT))
3646*d415bd75Srobert           return ConstantInt::get(getCompareTy(LHS), *Imp);
3647097a140dSpatrick     }
3648097a140dSpatrick   }
3649097a140dSpatrick 
3650097a140dSpatrick   return nullptr;
3651097a140dSpatrick }
3652097a140dSpatrick 
365309467b48Spatrick /// Given operands for an ICmpInst, see if we can fold the result.
365409467b48Spatrick /// If not, this returns null.
simplifyICmpInst(unsigned Predicate,Value * LHS,Value * RHS,const SimplifyQuery & Q,unsigned MaxRecurse)3655*d415bd75Srobert static Value *simplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
365609467b48Spatrick                                const SimplifyQuery &Q, unsigned MaxRecurse) {
365709467b48Spatrick   CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
365809467b48Spatrick   assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
365909467b48Spatrick 
366009467b48Spatrick   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
366109467b48Spatrick     if (Constant *CRHS = dyn_cast<Constant>(RHS))
366209467b48Spatrick       return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
366309467b48Spatrick 
366409467b48Spatrick     // If we have a constant, make sure it is on the RHS.
366509467b48Spatrick     std::swap(LHS, RHS);
366609467b48Spatrick     Pred = CmpInst::getSwappedPredicate(Pred);
366709467b48Spatrick   }
366809467b48Spatrick   assert(!isa<UndefValue>(LHS) && "Unexpected icmp undef,%X");
366909467b48Spatrick 
3670*d415bd75Srobert   Type *ITy = getCompareTy(LHS); // The return type.
367109467b48Spatrick 
367273471bf0Spatrick   // icmp poison, X -> poison
367373471bf0Spatrick   if (isa<PoisonValue>(RHS))
367473471bf0Spatrick     return PoisonValue::get(ITy);
367573471bf0Spatrick 
367609467b48Spatrick   // For EQ and NE, we can always pick a value for the undef to make the
367709467b48Spatrick   // predicate pass or fail, so we can return undef.
367809467b48Spatrick   // Matches behavior in llvm::ConstantFoldCompareInstruction.
367973471bf0Spatrick   if (Q.isUndefValue(RHS) && ICmpInst::isEquality(Pred))
368009467b48Spatrick     return UndefValue::get(ITy);
368109467b48Spatrick 
368209467b48Spatrick   // icmp X, X -> true/false
368309467b48Spatrick   // icmp X, undef -> true/false because undef could be X.
368473471bf0Spatrick   if (LHS == RHS || Q.isUndefValue(RHS))
368509467b48Spatrick     return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
368609467b48Spatrick 
368709467b48Spatrick   if (Value *V = simplifyICmpOfBools(Pred, LHS, RHS, Q))
368809467b48Spatrick     return V;
368909467b48Spatrick 
369073471bf0Spatrick   // TODO: Sink/common this with other potentially expensive calls that use
369173471bf0Spatrick   //       ValueTracking? See comment below for isKnownNonEqual().
369209467b48Spatrick   if (Value *V = simplifyICmpWithZero(Pred, LHS, RHS, Q))
369309467b48Spatrick     return V;
369409467b48Spatrick 
369509467b48Spatrick   if (Value *V = simplifyICmpWithConstant(Pred, LHS, RHS, Q.IIQ))
369609467b48Spatrick     return V;
369709467b48Spatrick 
369809467b48Spatrick   // If both operands have range metadata, use the metadata
369909467b48Spatrick   // to simplify the comparison.
370009467b48Spatrick   if (isa<Instruction>(RHS) && isa<Instruction>(LHS)) {
370109467b48Spatrick     auto RHS_Instr = cast<Instruction>(RHS);
370209467b48Spatrick     auto LHS_Instr = cast<Instruction>(LHS);
370309467b48Spatrick 
370409467b48Spatrick     if (Q.IIQ.getMetadata(RHS_Instr, LLVMContext::MD_range) &&
370509467b48Spatrick         Q.IIQ.getMetadata(LHS_Instr, LLVMContext::MD_range)) {
370609467b48Spatrick       auto RHS_CR = getConstantRangeFromMetadata(
370709467b48Spatrick           *RHS_Instr->getMetadata(LLVMContext::MD_range));
370809467b48Spatrick       auto LHS_CR = getConstantRangeFromMetadata(
370909467b48Spatrick           *LHS_Instr->getMetadata(LLVMContext::MD_range));
371009467b48Spatrick 
371173471bf0Spatrick       if (LHS_CR.icmp(Pred, RHS_CR))
371209467b48Spatrick         return ConstantInt::getTrue(RHS->getContext());
371309467b48Spatrick 
371473471bf0Spatrick       if (LHS_CR.icmp(CmpInst::getInversePredicate(Pred), RHS_CR))
371509467b48Spatrick         return ConstantInt::getFalse(RHS->getContext());
371609467b48Spatrick     }
371709467b48Spatrick   }
371809467b48Spatrick 
371909467b48Spatrick   // Compare of cast, for example (zext X) != 0 -> X != 0
372009467b48Spatrick   if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
372109467b48Spatrick     Instruction *LI = cast<CastInst>(LHS);
372209467b48Spatrick     Value *SrcOp = LI->getOperand(0);
372309467b48Spatrick     Type *SrcTy = SrcOp->getType();
372409467b48Spatrick     Type *DstTy = LI->getType();
372509467b48Spatrick 
372609467b48Spatrick     // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
372709467b48Spatrick     // if the integer type is the same size as the pointer type.
372809467b48Spatrick     if (MaxRecurse && isa<PtrToIntInst>(LI) &&
372909467b48Spatrick         Q.DL.getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) {
373009467b48Spatrick       if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
373109467b48Spatrick         // Transfer the cast to the constant.
3732*d415bd75Srobert         if (Value *V = simplifyICmpInst(Pred, SrcOp,
373309467b48Spatrick                                         ConstantExpr::getIntToPtr(RHSC, SrcTy),
373409467b48Spatrick                                         Q, MaxRecurse - 1))
373509467b48Spatrick           return V;
373609467b48Spatrick       } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
373709467b48Spatrick         if (RI->getOperand(0)->getType() == SrcTy)
373809467b48Spatrick           // Compare without the cast.
3739*d415bd75Srobert           if (Value *V = simplifyICmpInst(Pred, SrcOp, RI->getOperand(0), Q,
3740*d415bd75Srobert                                           MaxRecurse - 1))
374109467b48Spatrick             return V;
374209467b48Spatrick       }
374309467b48Spatrick     }
374409467b48Spatrick 
374509467b48Spatrick     if (isa<ZExtInst>(LHS)) {
374609467b48Spatrick       // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
374709467b48Spatrick       // same type.
374809467b48Spatrick       if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
374909467b48Spatrick         if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
375009467b48Spatrick           // Compare X and Y.  Note that signed predicates become unsigned.
3751*d415bd75Srobert           if (Value *V =
3752*d415bd75Srobert                   simplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred), SrcOp,
3753*d415bd75Srobert                                    RI->getOperand(0), Q, MaxRecurse - 1))
375409467b48Spatrick             return V;
375509467b48Spatrick       }
3756097a140dSpatrick       // Fold (zext X) ule (sext X), (zext X) sge (sext X) to true.
3757097a140dSpatrick       else if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
3758097a140dSpatrick         if (SrcOp == RI->getOperand(0)) {
3759097a140dSpatrick           if (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_SGE)
3760097a140dSpatrick             return ConstantInt::getTrue(ITy);
3761097a140dSpatrick           if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SLT)
3762097a140dSpatrick             return ConstantInt::getFalse(ITy);
3763097a140dSpatrick         }
3764097a140dSpatrick       }
376509467b48Spatrick       // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
376609467b48Spatrick       // too.  If not, then try to deduce the result of the comparison.
376709467b48Spatrick       else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
376809467b48Spatrick         // Compute the constant that would happen if we truncated to SrcTy then
376909467b48Spatrick         // reextended to DstTy.
377009467b48Spatrick         Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
377109467b48Spatrick         Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
377209467b48Spatrick 
377309467b48Spatrick         // If the re-extended constant didn't change then this is effectively
377409467b48Spatrick         // also a case of comparing two zero-extended values.
377509467b48Spatrick         if (RExt == CI && MaxRecurse)
3776*d415bd75Srobert           if (Value *V = simplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
377709467b48Spatrick                                           SrcOp, Trunc, Q, MaxRecurse - 1))
377809467b48Spatrick             return V;
377909467b48Spatrick 
378009467b48Spatrick         // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
378109467b48Spatrick         // there.  Use this to work out the result of the comparison.
378209467b48Spatrick         if (RExt != CI) {
378309467b48Spatrick           switch (Pred) {
3784*d415bd75Srobert           default:
3785*d415bd75Srobert             llvm_unreachable("Unknown ICmp predicate!");
378609467b48Spatrick           // LHS <u RHS.
378709467b48Spatrick           case ICmpInst::ICMP_EQ:
378809467b48Spatrick           case ICmpInst::ICMP_UGT:
378909467b48Spatrick           case ICmpInst::ICMP_UGE:
379009467b48Spatrick             return ConstantInt::getFalse(CI->getContext());
379109467b48Spatrick 
379209467b48Spatrick           case ICmpInst::ICMP_NE:
379309467b48Spatrick           case ICmpInst::ICMP_ULT:
379409467b48Spatrick           case ICmpInst::ICMP_ULE:
379509467b48Spatrick             return ConstantInt::getTrue(CI->getContext());
379609467b48Spatrick 
379709467b48Spatrick           // LHS is non-negative.  If RHS is negative then LHS >s LHS.  If RHS
379809467b48Spatrick           // is non-negative then LHS <s RHS.
379909467b48Spatrick           case ICmpInst::ICMP_SGT:
380009467b48Spatrick           case ICmpInst::ICMP_SGE:
3801*d415bd75Srobert             return CI->getValue().isNegative()
3802*d415bd75Srobert                        ? ConstantInt::getTrue(CI->getContext())
3803*d415bd75Srobert                        : ConstantInt::getFalse(CI->getContext());
380409467b48Spatrick 
380509467b48Spatrick           case ICmpInst::ICMP_SLT:
380609467b48Spatrick           case ICmpInst::ICMP_SLE:
3807*d415bd75Srobert             return CI->getValue().isNegative()
3808*d415bd75Srobert                        ? ConstantInt::getFalse(CI->getContext())
3809*d415bd75Srobert                        : ConstantInt::getTrue(CI->getContext());
381009467b48Spatrick           }
381109467b48Spatrick         }
381209467b48Spatrick       }
381309467b48Spatrick     }
381409467b48Spatrick 
381509467b48Spatrick     if (isa<SExtInst>(LHS)) {
381609467b48Spatrick       // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
381709467b48Spatrick       // same type.
381809467b48Spatrick       if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
381909467b48Spatrick         if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
382009467b48Spatrick           // Compare X and Y.  Note that the predicate does not change.
3821*d415bd75Srobert           if (Value *V = simplifyICmpInst(Pred, SrcOp, RI->getOperand(0), Q,
3822*d415bd75Srobert                                           MaxRecurse - 1))
382309467b48Spatrick             return V;
382409467b48Spatrick       }
3825097a140dSpatrick       // Fold (sext X) uge (zext X), (sext X) sle (zext X) to true.
3826097a140dSpatrick       else if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
3827097a140dSpatrick         if (SrcOp == RI->getOperand(0)) {
3828097a140dSpatrick           if (Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_SLE)
3829097a140dSpatrick             return ConstantInt::getTrue(ITy);
3830097a140dSpatrick           if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SGT)
3831097a140dSpatrick             return ConstantInt::getFalse(ITy);
3832097a140dSpatrick         }
3833097a140dSpatrick       }
383409467b48Spatrick       // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
383509467b48Spatrick       // too.  If not, then try to deduce the result of the comparison.
383609467b48Spatrick       else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
383709467b48Spatrick         // Compute the constant that would happen if we truncated to SrcTy then
383809467b48Spatrick         // reextended to DstTy.
383909467b48Spatrick         Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
384009467b48Spatrick         Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
384109467b48Spatrick 
384209467b48Spatrick         // If the re-extended constant didn't change then this is effectively
384309467b48Spatrick         // also a case of comparing two sign-extended values.
384409467b48Spatrick         if (RExt == CI && MaxRecurse)
3845*d415bd75Srobert           if (Value *V =
3846*d415bd75Srobert                   simplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse - 1))
384709467b48Spatrick             return V;
384809467b48Spatrick 
384909467b48Spatrick         // Otherwise the upper bits of LHS are all equal, while RHS has varying
385009467b48Spatrick         // bits there.  Use this to work out the result of the comparison.
385109467b48Spatrick         if (RExt != CI) {
385209467b48Spatrick           switch (Pred) {
3853*d415bd75Srobert           default:
3854*d415bd75Srobert             llvm_unreachable("Unknown ICmp predicate!");
385509467b48Spatrick           case ICmpInst::ICMP_EQ:
385609467b48Spatrick             return ConstantInt::getFalse(CI->getContext());
385709467b48Spatrick           case ICmpInst::ICMP_NE:
385809467b48Spatrick             return ConstantInt::getTrue(CI->getContext());
385909467b48Spatrick 
386009467b48Spatrick           // If RHS is non-negative then LHS <s RHS.  If RHS is negative then
386109467b48Spatrick           // LHS >s RHS.
386209467b48Spatrick           case ICmpInst::ICMP_SGT:
386309467b48Spatrick           case ICmpInst::ICMP_SGE:
3864*d415bd75Srobert             return CI->getValue().isNegative()
3865*d415bd75Srobert                        ? ConstantInt::getTrue(CI->getContext())
3866*d415bd75Srobert                        : ConstantInt::getFalse(CI->getContext());
386709467b48Spatrick           case ICmpInst::ICMP_SLT:
386809467b48Spatrick           case ICmpInst::ICMP_SLE:
3869*d415bd75Srobert             return CI->getValue().isNegative()
3870*d415bd75Srobert                        ? ConstantInt::getFalse(CI->getContext())
3871*d415bd75Srobert                        : ConstantInt::getTrue(CI->getContext());
387209467b48Spatrick 
387309467b48Spatrick           // If LHS is non-negative then LHS <u RHS.  If LHS is negative then
387409467b48Spatrick           // LHS >u RHS.
387509467b48Spatrick           case ICmpInst::ICMP_UGT:
387609467b48Spatrick           case ICmpInst::ICMP_UGE:
387709467b48Spatrick             // Comparison is true iff the LHS <s 0.
387809467b48Spatrick             if (MaxRecurse)
3879*d415bd75Srobert               if (Value *V = simplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
3880*d415bd75Srobert                                               Constant::getNullValue(SrcTy), Q,
3881*d415bd75Srobert                                               MaxRecurse - 1))
388209467b48Spatrick                 return V;
388309467b48Spatrick             break;
388409467b48Spatrick           case ICmpInst::ICMP_ULT:
388509467b48Spatrick           case ICmpInst::ICMP_ULE:
388609467b48Spatrick             // Comparison is true iff the LHS >=s 0.
388709467b48Spatrick             if (MaxRecurse)
3888*d415bd75Srobert               if (Value *V = simplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
3889*d415bd75Srobert                                               Constant::getNullValue(SrcTy), Q,
3890*d415bd75Srobert                                               MaxRecurse - 1))
389109467b48Spatrick                 return V;
389209467b48Spatrick             break;
389309467b48Spatrick           }
389409467b48Spatrick         }
389509467b48Spatrick       }
389609467b48Spatrick     }
389709467b48Spatrick   }
389809467b48Spatrick 
389909467b48Spatrick   // icmp eq|ne X, Y -> false|true if X != Y
390073471bf0Spatrick   // This is potentially expensive, and we have already computedKnownBits for
390173471bf0Spatrick   // compares with 0 above here, so only try this for a non-zero compare.
390273471bf0Spatrick   if (ICmpInst::isEquality(Pred) && !match(RHS, m_Zero()) &&
390309467b48Spatrick       isKnownNonEqual(LHS, RHS, Q.DL, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo)) {
390409467b48Spatrick     return Pred == ICmpInst::ICMP_NE ? getTrue(ITy) : getFalse(ITy);
390509467b48Spatrick   }
390609467b48Spatrick 
390709467b48Spatrick   if (Value *V = simplifyICmpWithBinOp(Pred, LHS, RHS, Q, MaxRecurse))
390809467b48Spatrick     return V;
390909467b48Spatrick 
391009467b48Spatrick   if (Value *V = simplifyICmpWithMinMax(Pred, LHS, RHS, Q, MaxRecurse))
391109467b48Spatrick     return V;
391209467b48Spatrick 
3913097a140dSpatrick   if (Value *V = simplifyICmpWithDominatingAssume(Pred, LHS, RHS, Q))
3914097a140dSpatrick     return V;
3915097a140dSpatrick 
391609467b48Spatrick   // Simplify comparisons of related pointers using a powerful, recursive
391709467b48Spatrick   // GEP-walk when we have target data available..
391809467b48Spatrick   if (LHS->getType()->isPointerTy())
391973471bf0Spatrick     if (auto *C = computePointerICmp(Pred, LHS, RHS, Q))
392009467b48Spatrick       return C;
392109467b48Spatrick   if (auto *CLHS = dyn_cast<PtrToIntOperator>(LHS))
392209467b48Spatrick     if (auto *CRHS = dyn_cast<PtrToIntOperator>(RHS))
392309467b48Spatrick       if (Q.DL.getTypeSizeInBits(CLHS->getPointerOperandType()) ==
392409467b48Spatrick               Q.DL.getTypeSizeInBits(CLHS->getType()) &&
392509467b48Spatrick           Q.DL.getTypeSizeInBits(CRHS->getPointerOperandType()) ==
392609467b48Spatrick               Q.DL.getTypeSizeInBits(CRHS->getType()))
392773471bf0Spatrick         if (auto *C = computePointerICmp(Pred, CLHS->getPointerOperand(),
392873471bf0Spatrick                                          CRHS->getPointerOperand(), Q))
392909467b48Spatrick           return C;
393009467b48Spatrick 
393109467b48Spatrick   // If the comparison is with the result of a select instruction, check whether
393209467b48Spatrick   // comparing with either branch of the select always yields the same value.
393309467b48Spatrick   if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
3934*d415bd75Srobert     if (Value *V = threadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
393509467b48Spatrick       return V;
393609467b48Spatrick 
393709467b48Spatrick   // If the comparison is with the result of a phi instruction, check whether
393809467b48Spatrick   // doing the compare with each incoming phi value yields a common result.
393909467b48Spatrick   if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
3940*d415bd75Srobert     if (Value *V = threadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
394109467b48Spatrick       return V;
394209467b48Spatrick 
394309467b48Spatrick   return nullptr;
394409467b48Spatrick }
394509467b48Spatrick 
simplifyICmpInst(unsigned Predicate,Value * LHS,Value * RHS,const SimplifyQuery & Q)3946*d415bd75Srobert Value *llvm::simplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
394709467b48Spatrick                               const SimplifyQuery &Q) {
3948*d415bd75Srobert   return ::simplifyICmpInst(Predicate, LHS, RHS, Q, RecursionLimit);
394909467b48Spatrick }
395009467b48Spatrick 
395109467b48Spatrick /// Given operands for an FCmpInst, see if we can fold the result.
395209467b48Spatrick /// If not, this returns null.
simplifyFCmpInst(unsigned Predicate,Value * LHS,Value * RHS,FastMathFlags FMF,const SimplifyQuery & Q,unsigned MaxRecurse)3953*d415bd75Srobert static Value *simplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
395409467b48Spatrick                                FastMathFlags FMF, const SimplifyQuery &Q,
395509467b48Spatrick                                unsigned MaxRecurse) {
395609467b48Spatrick   CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
395709467b48Spatrick   assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
395809467b48Spatrick 
395909467b48Spatrick   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
396009467b48Spatrick     if (Constant *CRHS = dyn_cast<Constant>(RHS))
3961*d415bd75Srobert       return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI,
3962*d415bd75Srobert                                              Q.CxtI);
396309467b48Spatrick 
396409467b48Spatrick     // If we have a constant, make sure it is on the RHS.
396509467b48Spatrick     std::swap(LHS, RHS);
396609467b48Spatrick     Pred = CmpInst::getSwappedPredicate(Pred);
396709467b48Spatrick   }
396809467b48Spatrick 
396909467b48Spatrick   // Fold trivial predicates.
3970*d415bd75Srobert   Type *RetTy = getCompareTy(LHS);
397109467b48Spatrick   if (Pred == FCmpInst::FCMP_FALSE)
397209467b48Spatrick     return getFalse(RetTy);
397309467b48Spatrick   if (Pred == FCmpInst::FCMP_TRUE)
397409467b48Spatrick     return getTrue(RetTy);
397509467b48Spatrick 
397609467b48Spatrick   // Fold (un)ordered comparison if we can determine there are no NaNs.
397709467b48Spatrick   if (Pred == FCmpInst::FCMP_UNO || Pred == FCmpInst::FCMP_ORD)
397809467b48Spatrick     if (FMF.noNaNs() ||
397909467b48Spatrick         (isKnownNeverNaN(LHS, Q.TLI) && isKnownNeverNaN(RHS, Q.TLI)))
398009467b48Spatrick       return ConstantInt::get(RetTy, Pred == FCmpInst::FCMP_ORD);
398109467b48Spatrick 
398209467b48Spatrick   // NaN is unordered; NaN is not ordered.
398309467b48Spatrick   assert((FCmpInst::isOrdered(Pred) || FCmpInst::isUnordered(Pred)) &&
398409467b48Spatrick          "Comparison must be either ordered or unordered");
398509467b48Spatrick   if (match(RHS, m_NaN()))
398609467b48Spatrick     return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred));
398709467b48Spatrick 
398873471bf0Spatrick   // fcmp pred x, poison and  fcmp pred poison, x
398973471bf0Spatrick   // fold to poison
399073471bf0Spatrick   if (isa<PoisonValue>(LHS) || isa<PoisonValue>(RHS))
399173471bf0Spatrick     return PoisonValue::get(RetTy);
399273471bf0Spatrick 
399309467b48Spatrick   // fcmp pred x, undef  and  fcmp pred undef, x
399409467b48Spatrick   // fold to true if unordered, false if ordered
399573471bf0Spatrick   if (Q.isUndefValue(LHS) || Q.isUndefValue(RHS)) {
399609467b48Spatrick     // Choosing NaN for the undef will always make unordered comparison succeed
399709467b48Spatrick     // and ordered comparison fail.
399809467b48Spatrick     return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred));
399909467b48Spatrick   }
400009467b48Spatrick 
400109467b48Spatrick   // fcmp x,x -> true/false.  Not all compares are foldable.
400209467b48Spatrick   if (LHS == RHS) {
400309467b48Spatrick     if (CmpInst::isTrueWhenEqual(Pred))
400409467b48Spatrick       return getTrue(RetTy);
400509467b48Spatrick     if (CmpInst::isFalseWhenEqual(Pred))
400609467b48Spatrick       return getFalse(RetTy);
400709467b48Spatrick   }
400809467b48Spatrick 
400909467b48Spatrick   // Handle fcmp with constant RHS.
401009467b48Spatrick   // TODO: Use match with a specific FP value, so these work with vectors with
401109467b48Spatrick   // undef lanes.
401209467b48Spatrick   const APFloat *C;
401309467b48Spatrick   if (match(RHS, m_APFloat(C))) {
401409467b48Spatrick     // Check whether the constant is an infinity.
401509467b48Spatrick     if (C->isInfinity()) {
401609467b48Spatrick       if (C->isNegative()) {
401709467b48Spatrick         switch (Pred) {
401809467b48Spatrick         case FCmpInst::FCMP_OLT:
401909467b48Spatrick           // No value is ordered and less than negative infinity.
402009467b48Spatrick           return getFalse(RetTy);
402109467b48Spatrick         case FCmpInst::FCMP_UGE:
402209467b48Spatrick           // All values are unordered with or at least negative infinity.
402309467b48Spatrick           return getTrue(RetTy);
402409467b48Spatrick         default:
402509467b48Spatrick           break;
402609467b48Spatrick         }
402709467b48Spatrick       } else {
402809467b48Spatrick         switch (Pred) {
402909467b48Spatrick         case FCmpInst::FCMP_OGT:
403009467b48Spatrick           // No value is ordered and greater than infinity.
403109467b48Spatrick           return getFalse(RetTy);
403209467b48Spatrick         case FCmpInst::FCMP_ULE:
403309467b48Spatrick           // All values are unordered with and at most infinity.
403409467b48Spatrick           return getTrue(RetTy);
403509467b48Spatrick         default:
403609467b48Spatrick           break;
403709467b48Spatrick         }
403809467b48Spatrick       }
403973471bf0Spatrick 
404073471bf0Spatrick       // LHS == Inf
404173471bf0Spatrick       if (Pred == FCmpInst::FCMP_OEQ && isKnownNeverInfinity(LHS, Q.TLI))
404273471bf0Spatrick         return getFalse(RetTy);
404373471bf0Spatrick       // LHS != Inf
404473471bf0Spatrick       if (Pred == FCmpInst::FCMP_UNE && isKnownNeverInfinity(LHS, Q.TLI))
404573471bf0Spatrick         return getTrue(RetTy);
404673471bf0Spatrick       // LHS == Inf || LHS == NaN
404773471bf0Spatrick       if (Pred == FCmpInst::FCMP_UEQ && isKnownNeverInfinity(LHS, Q.TLI) &&
404873471bf0Spatrick           isKnownNeverNaN(LHS, Q.TLI))
404973471bf0Spatrick         return getFalse(RetTy);
405073471bf0Spatrick       // LHS != Inf && LHS != NaN
405173471bf0Spatrick       if (Pred == FCmpInst::FCMP_ONE && isKnownNeverInfinity(LHS, Q.TLI) &&
405273471bf0Spatrick           isKnownNeverNaN(LHS, Q.TLI))
405373471bf0Spatrick         return getTrue(RetTy);
405409467b48Spatrick     }
405509467b48Spatrick     if (C->isNegative() && !C->isNegZero()) {
405609467b48Spatrick       assert(!C->isNaN() && "Unexpected NaN constant!");
405709467b48Spatrick       // TODO: We can catch more cases by using a range check rather than
405809467b48Spatrick       //       relying on CannotBeOrderedLessThanZero.
405909467b48Spatrick       switch (Pred) {
406009467b48Spatrick       case FCmpInst::FCMP_UGE:
406109467b48Spatrick       case FCmpInst::FCMP_UGT:
406209467b48Spatrick       case FCmpInst::FCMP_UNE:
406309467b48Spatrick         // (X >= 0) implies (X > C) when (C < 0)
406409467b48Spatrick         if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
406509467b48Spatrick           return getTrue(RetTy);
406609467b48Spatrick         break;
406709467b48Spatrick       case FCmpInst::FCMP_OEQ:
406809467b48Spatrick       case FCmpInst::FCMP_OLE:
406909467b48Spatrick       case FCmpInst::FCMP_OLT:
407009467b48Spatrick         // (X >= 0) implies !(X < C) when (C < 0)
407109467b48Spatrick         if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
407209467b48Spatrick           return getFalse(RetTy);
407309467b48Spatrick         break;
407409467b48Spatrick       default:
407509467b48Spatrick         break;
407609467b48Spatrick       }
407709467b48Spatrick     }
407809467b48Spatrick 
407909467b48Spatrick     // Check comparison of [minnum/maxnum with constant] with other constant.
408009467b48Spatrick     const APFloat *C2;
408109467b48Spatrick     if ((match(LHS, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_APFloat(C2))) &&
4082097a140dSpatrick          *C2 < *C) ||
408309467b48Spatrick         (match(LHS, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_APFloat(C2))) &&
4084097a140dSpatrick          *C2 > *C)) {
408509467b48Spatrick       bool IsMaxNum =
408609467b48Spatrick           cast<IntrinsicInst>(LHS)->getIntrinsicID() == Intrinsic::maxnum;
408709467b48Spatrick       // The ordered relationship and minnum/maxnum guarantee that we do not
408809467b48Spatrick       // have NaN constants, so ordered/unordered preds are handled the same.
408909467b48Spatrick       switch (Pred) {
4090*d415bd75Srobert       case FCmpInst::FCMP_OEQ:
4091*d415bd75Srobert       case FCmpInst::FCMP_UEQ:
409209467b48Spatrick         // minnum(X, LesserC)  == C --> false
409309467b48Spatrick         // maxnum(X, GreaterC) == C --> false
409409467b48Spatrick         return getFalse(RetTy);
4095*d415bd75Srobert       case FCmpInst::FCMP_ONE:
4096*d415bd75Srobert       case FCmpInst::FCMP_UNE:
409709467b48Spatrick         // minnum(X, LesserC)  != C --> true
409809467b48Spatrick         // maxnum(X, GreaterC) != C --> true
409909467b48Spatrick         return getTrue(RetTy);
4100*d415bd75Srobert       case FCmpInst::FCMP_OGE:
4101*d415bd75Srobert       case FCmpInst::FCMP_UGE:
4102*d415bd75Srobert       case FCmpInst::FCMP_OGT:
4103*d415bd75Srobert       case FCmpInst::FCMP_UGT:
410409467b48Spatrick         // minnum(X, LesserC)  >= C --> false
410509467b48Spatrick         // minnum(X, LesserC)  >  C --> false
410609467b48Spatrick         // maxnum(X, GreaterC) >= C --> true
410709467b48Spatrick         // maxnum(X, GreaterC) >  C --> true
410809467b48Spatrick         return ConstantInt::get(RetTy, IsMaxNum);
4109*d415bd75Srobert       case FCmpInst::FCMP_OLE:
4110*d415bd75Srobert       case FCmpInst::FCMP_ULE:
4111*d415bd75Srobert       case FCmpInst::FCMP_OLT:
4112*d415bd75Srobert       case FCmpInst::FCMP_ULT:
411309467b48Spatrick         // minnum(X, LesserC)  <= C --> true
411409467b48Spatrick         // minnum(X, LesserC)  <  C --> true
411509467b48Spatrick         // maxnum(X, GreaterC) <= C --> false
411609467b48Spatrick         // maxnum(X, GreaterC) <  C --> false
411709467b48Spatrick         return ConstantInt::get(RetTy, !IsMaxNum);
411809467b48Spatrick       default:
411909467b48Spatrick         // TRUE/FALSE/ORD/UNO should be handled before this.
412009467b48Spatrick         llvm_unreachable("Unexpected fcmp predicate");
412109467b48Spatrick       }
412209467b48Spatrick     }
412309467b48Spatrick   }
412409467b48Spatrick 
412509467b48Spatrick   if (match(RHS, m_AnyZeroFP())) {
412609467b48Spatrick     switch (Pred) {
412709467b48Spatrick     case FCmpInst::FCMP_OGE:
412809467b48Spatrick     case FCmpInst::FCMP_ULT:
412909467b48Spatrick       // Positive or zero X >= 0.0 --> true
413009467b48Spatrick       // Positive or zero X <  0.0 --> false
413109467b48Spatrick       if ((FMF.noNaNs() || isKnownNeverNaN(LHS, Q.TLI)) &&
413209467b48Spatrick           CannotBeOrderedLessThanZero(LHS, Q.TLI))
413309467b48Spatrick         return Pred == FCmpInst::FCMP_OGE ? getTrue(RetTy) : getFalse(RetTy);
413409467b48Spatrick       break;
413509467b48Spatrick     case FCmpInst::FCMP_UGE:
413609467b48Spatrick     case FCmpInst::FCMP_OLT:
413709467b48Spatrick       // Positive or zero or nan X >= 0.0 --> true
413809467b48Spatrick       // Positive or zero or nan X <  0.0 --> false
413909467b48Spatrick       if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
414009467b48Spatrick         return Pred == FCmpInst::FCMP_UGE ? getTrue(RetTy) : getFalse(RetTy);
414109467b48Spatrick       break;
414209467b48Spatrick     default:
414309467b48Spatrick       break;
414409467b48Spatrick     }
414509467b48Spatrick   }
414609467b48Spatrick 
414709467b48Spatrick   // If the comparison is with the result of a select instruction, check whether
414809467b48Spatrick   // comparing with either branch of the select always yields the same value.
414909467b48Spatrick   if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
4150*d415bd75Srobert     if (Value *V = threadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
415109467b48Spatrick       return V;
415209467b48Spatrick 
415309467b48Spatrick   // If the comparison is with the result of a phi instruction, check whether
415409467b48Spatrick   // doing the compare with each incoming phi value yields a common result.
415509467b48Spatrick   if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
4156*d415bd75Srobert     if (Value *V = threadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
415709467b48Spatrick       return V;
415809467b48Spatrick 
415909467b48Spatrick   return nullptr;
416009467b48Spatrick }
416109467b48Spatrick 
simplifyFCmpInst(unsigned Predicate,Value * LHS,Value * RHS,FastMathFlags FMF,const SimplifyQuery & Q)4162*d415bd75Srobert Value *llvm::simplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
416309467b48Spatrick                               FastMathFlags FMF, const SimplifyQuery &Q) {
4164*d415bd75Srobert   return ::simplifyFCmpInst(Predicate, LHS, RHS, FMF, Q, RecursionLimit);
416509467b48Spatrick }
416609467b48Spatrick 
simplifyWithOpReplaced(Value * V,Value * Op,Value * RepOp,const SimplifyQuery & Q,bool AllowRefinement,unsigned MaxRecurse)416773471bf0Spatrick static Value *simplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
416809467b48Spatrick                                      const SimplifyQuery &Q,
4169097a140dSpatrick                                      bool AllowRefinement,
417009467b48Spatrick                                      unsigned MaxRecurse) {
417109467b48Spatrick   // Trivial replacement.
417209467b48Spatrick   if (V == Op)
417309467b48Spatrick     return RepOp;
417409467b48Spatrick 
417509467b48Spatrick   // We cannot replace a constant, and shouldn't even try.
417609467b48Spatrick   if (isa<Constant>(Op))
417709467b48Spatrick     return nullptr;
417809467b48Spatrick 
417909467b48Spatrick   auto *I = dyn_cast<Instruction>(V);
418073471bf0Spatrick   if (!I || !is_contained(I->operands(), Op))
418109467b48Spatrick     return nullptr;
418209467b48Spatrick 
4183*d415bd75Srobert   if (Op->getType()->isVectorTy()) {
4184*d415bd75Srobert     // For vector types, the simplification must hold per-lane, so forbid
4185*d415bd75Srobert     // potentially cross-lane operations like shufflevector.
4186*d415bd75Srobert     assert(I->getType()->isVectorTy() && "Vector type mismatch");
4187*d415bd75Srobert     if (isa<ShuffleVectorInst>(I) || isa<CallBase>(I))
4188*d415bd75Srobert       return nullptr;
4189*d415bd75Srobert   }
4190*d415bd75Srobert 
419173471bf0Spatrick   // Replace Op with RepOp in instruction operands.
419273471bf0Spatrick   SmallVector<Value *, 8> NewOps(I->getNumOperands());
419373471bf0Spatrick   transform(I->operands(), NewOps.begin(),
419473471bf0Spatrick             [&](Value *V) { return V == Op ? RepOp : V; });
419573471bf0Spatrick 
419673471bf0Spatrick   if (!AllowRefinement) {
419773471bf0Spatrick     // General InstSimplify functions may refine the result, e.g. by returning
419873471bf0Spatrick     // a constant for a potentially poison value. To avoid this, implement only
419973471bf0Spatrick     // a few non-refining but profitable transforms here.
420073471bf0Spatrick 
420173471bf0Spatrick     if (auto *BO = dyn_cast<BinaryOperator>(I)) {
420273471bf0Spatrick       unsigned Opcode = BO->getOpcode();
420373471bf0Spatrick       // id op x -> x, x op id -> x
420473471bf0Spatrick       if (NewOps[0] == ConstantExpr::getBinOpIdentity(Opcode, I->getType()))
420573471bf0Spatrick         return NewOps[1];
420673471bf0Spatrick       if (NewOps[1] == ConstantExpr::getBinOpIdentity(Opcode, I->getType(),
420773471bf0Spatrick                                                       /* RHS */ true))
420873471bf0Spatrick         return NewOps[0];
420973471bf0Spatrick 
421073471bf0Spatrick       // x & x -> x, x | x -> x
421173471bf0Spatrick       if ((Opcode == Instruction::And || Opcode == Instruction::Or) &&
421273471bf0Spatrick           NewOps[0] == NewOps[1])
421373471bf0Spatrick         return NewOps[0];
421473471bf0Spatrick     }
421573471bf0Spatrick 
421673471bf0Spatrick     if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
421773471bf0Spatrick       // getelementptr x, 0 -> x
421873471bf0Spatrick       if (NewOps.size() == 2 && match(NewOps[1], m_Zero()) &&
421973471bf0Spatrick           !GEP->isInBounds())
422073471bf0Spatrick         return NewOps[0];
422173471bf0Spatrick     }
422273471bf0Spatrick   } else if (MaxRecurse) {
422373471bf0Spatrick     // The simplification queries below may return the original value. Consider:
422473471bf0Spatrick     //   %div = udiv i32 %arg, %arg2
422573471bf0Spatrick     //   %mul = mul nsw i32 %div, %arg2
422673471bf0Spatrick     //   %cmp = icmp eq i32 %mul, %arg
422773471bf0Spatrick     //   %sel = select i1 %cmp, i32 %div, i32 undef
422873471bf0Spatrick     // Replacing %arg by %mul, %div becomes "udiv i32 %mul, %arg2", which
422973471bf0Spatrick     // simplifies back to %arg. This can only happen because %mul does not
423073471bf0Spatrick     // dominate %div. To ensure a consistent return value contract, we make sure
423173471bf0Spatrick     // that this case returns nullptr as well.
423273471bf0Spatrick     auto PreventSelfSimplify = [V](Value *Simplified) {
423373471bf0Spatrick       return Simplified != V ? Simplified : nullptr;
423473471bf0Spatrick     };
423573471bf0Spatrick 
423673471bf0Spatrick     if (auto *B = dyn_cast<BinaryOperator>(I))
4237*d415bd75Srobert       return PreventSelfSimplify(simplifyBinOp(B->getOpcode(), NewOps[0],
423873471bf0Spatrick                                                NewOps[1], Q, MaxRecurse - 1));
423973471bf0Spatrick 
424073471bf0Spatrick     if (CmpInst *C = dyn_cast<CmpInst>(I))
4241*d415bd75Srobert       return PreventSelfSimplify(simplifyCmpInst(C->getPredicate(), NewOps[0],
424273471bf0Spatrick                                                  NewOps[1], Q, MaxRecurse - 1));
424373471bf0Spatrick 
424473471bf0Spatrick     if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
4245*d415bd75Srobert       return PreventSelfSimplify(simplifyGEPInst(
4246*d415bd75Srobert           GEP->getSourceElementType(), NewOps[0], ArrayRef(NewOps).slice(1),
4247*d415bd75Srobert           GEP->isInBounds(), Q, MaxRecurse - 1));
424873471bf0Spatrick 
424973471bf0Spatrick     if (isa<SelectInst>(I))
4250*d415bd75Srobert       return PreventSelfSimplify(simplifySelectInst(
4251*d415bd75Srobert           NewOps[0], NewOps[1], NewOps[2], Q, MaxRecurse - 1));
425273471bf0Spatrick     // TODO: We could hand off more cases to instsimplify here.
425373471bf0Spatrick   }
425473471bf0Spatrick 
425573471bf0Spatrick   // If all operands are constant after substituting Op for RepOp then we can
425673471bf0Spatrick   // constant fold the instruction.
425773471bf0Spatrick   SmallVector<Constant *, 8> ConstOps;
425873471bf0Spatrick   for (Value *NewOp : NewOps) {
425973471bf0Spatrick     if (Constant *ConstOp = dyn_cast<Constant>(NewOp))
426073471bf0Spatrick       ConstOps.push_back(ConstOp);
426173471bf0Spatrick     else
426273471bf0Spatrick       return nullptr;
426373471bf0Spatrick   }
426473471bf0Spatrick 
426509467b48Spatrick   // Consider:
426609467b48Spatrick   //   %cmp = icmp eq i32 %x, 2147483647
426709467b48Spatrick   //   %add = add nsw i32 %x, 1
426809467b48Spatrick   //   %sel = select i1 %cmp, i32 -2147483648, i32 %add
426909467b48Spatrick   //
427073471bf0Spatrick   // We can't replace %sel with %add unless we strip away the flags (which
427173471bf0Spatrick   // will be done in InstCombine).
427273471bf0Spatrick   // TODO: This may be unsound, because it only catches some forms of
427373471bf0Spatrick   // refinement.
427473471bf0Spatrick   if (!AllowRefinement && canCreatePoison(cast<Operator>(I)))
427509467b48Spatrick     return nullptr;
427609467b48Spatrick 
427709467b48Spatrick   return ConstantFoldInstOperands(I, ConstOps, Q.DL, Q.TLI);
427809467b48Spatrick }
427909467b48Spatrick 
simplifyWithOpReplaced(Value * V,Value * Op,Value * RepOp,const SimplifyQuery & Q,bool AllowRefinement)428073471bf0Spatrick Value *llvm::simplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
4281097a140dSpatrick                                     const SimplifyQuery &Q,
4282097a140dSpatrick                                     bool AllowRefinement) {
428373471bf0Spatrick   return ::simplifyWithOpReplaced(V, Op, RepOp, Q, AllowRefinement,
4284097a140dSpatrick                                   RecursionLimit);
4285097a140dSpatrick }
4286097a140dSpatrick 
428709467b48Spatrick /// Try to simplify a select instruction when its condition operand is an
428809467b48Spatrick /// integer comparison where one operand of the compare is a constant.
simplifySelectBitTest(Value * TrueVal,Value * FalseVal,Value * X,const APInt * Y,bool TrueWhenUnset)428909467b48Spatrick static Value *simplifySelectBitTest(Value *TrueVal, Value *FalseVal, Value *X,
429009467b48Spatrick                                     const APInt *Y, bool TrueWhenUnset) {
429109467b48Spatrick   const APInt *C;
429209467b48Spatrick 
429309467b48Spatrick   // (X & Y) == 0 ? X & ~Y : X  --> X
429409467b48Spatrick   // (X & Y) != 0 ? X & ~Y : X  --> X & ~Y
429509467b48Spatrick   if (FalseVal == X && match(TrueVal, m_And(m_Specific(X), m_APInt(C))) &&
429609467b48Spatrick       *Y == ~*C)
429709467b48Spatrick     return TrueWhenUnset ? FalseVal : TrueVal;
429809467b48Spatrick 
429909467b48Spatrick   // (X & Y) == 0 ? X : X & ~Y  --> X & ~Y
430009467b48Spatrick   // (X & Y) != 0 ? X : X & ~Y  --> X
430109467b48Spatrick   if (TrueVal == X && match(FalseVal, m_And(m_Specific(X), m_APInt(C))) &&
430209467b48Spatrick       *Y == ~*C)
430309467b48Spatrick     return TrueWhenUnset ? FalseVal : TrueVal;
430409467b48Spatrick 
430509467b48Spatrick   if (Y->isPowerOf2()) {
430609467b48Spatrick     // (X & Y) == 0 ? X | Y : X  --> X | Y
430709467b48Spatrick     // (X & Y) != 0 ? X | Y : X  --> X
430809467b48Spatrick     if (FalseVal == X && match(TrueVal, m_Or(m_Specific(X), m_APInt(C))) &&
430909467b48Spatrick         *Y == *C)
431009467b48Spatrick       return TrueWhenUnset ? TrueVal : FalseVal;
431109467b48Spatrick 
431209467b48Spatrick     // (X & Y) == 0 ? X : X | Y  --> X
431309467b48Spatrick     // (X & Y) != 0 ? X : X | Y  --> X | Y
431409467b48Spatrick     if (TrueVal == X && match(FalseVal, m_Or(m_Specific(X), m_APInt(C))) &&
431509467b48Spatrick         *Y == *C)
431609467b48Spatrick       return TrueWhenUnset ? TrueVal : FalseVal;
431709467b48Spatrick   }
431809467b48Spatrick 
431909467b48Spatrick   return nullptr;
432009467b48Spatrick }
432109467b48Spatrick 
simplifyCmpSelOfMaxMin(Value * CmpLHS,Value * CmpRHS,ICmpInst::Predicate Pred,Value * TVal,Value * FVal)4322*d415bd75Srobert static Value *simplifyCmpSelOfMaxMin(Value *CmpLHS, Value *CmpRHS,
4323*d415bd75Srobert                                      ICmpInst::Predicate Pred, Value *TVal,
4324*d415bd75Srobert                                      Value *FVal) {
4325*d415bd75Srobert   // Canonicalize common cmp+sel operand as CmpLHS.
4326*d415bd75Srobert   if (CmpRHS == TVal || CmpRHS == FVal) {
4327*d415bd75Srobert     std::swap(CmpLHS, CmpRHS);
4328*d415bd75Srobert     Pred = ICmpInst::getSwappedPredicate(Pred);
4329*d415bd75Srobert   }
4330*d415bd75Srobert 
4331*d415bd75Srobert   // Canonicalize common cmp+sel operand as TVal.
4332*d415bd75Srobert   if (CmpLHS == FVal) {
4333*d415bd75Srobert     std::swap(TVal, FVal);
4334*d415bd75Srobert     Pred = ICmpInst::getInversePredicate(Pred);
4335*d415bd75Srobert   }
4336*d415bd75Srobert 
4337*d415bd75Srobert   // A vector select may be shuffling together elements that are equivalent
4338*d415bd75Srobert   // based on the max/min/select relationship.
4339*d415bd75Srobert   Value *X = CmpLHS, *Y = CmpRHS;
4340*d415bd75Srobert   bool PeekedThroughSelectShuffle = false;
4341*d415bd75Srobert   auto *Shuf = dyn_cast<ShuffleVectorInst>(FVal);
4342*d415bd75Srobert   if (Shuf && Shuf->isSelect()) {
4343*d415bd75Srobert     if (Shuf->getOperand(0) == Y)
4344*d415bd75Srobert       FVal = Shuf->getOperand(1);
4345*d415bd75Srobert     else if (Shuf->getOperand(1) == Y)
4346*d415bd75Srobert       FVal = Shuf->getOperand(0);
4347*d415bd75Srobert     else
4348*d415bd75Srobert       return nullptr;
4349*d415bd75Srobert     PeekedThroughSelectShuffle = true;
4350*d415bd75Srobert   }
4351*d415bd75Srobert 
4352*d415bd75Srobert   // (X pred Y) ? X : max/min(X, Y)
4353*d415bd75Srobert   auto *MMI = dyn_cast<MinMaxIntrinsic>(FVal);
4354*d415bd75Srobert   if (!MMI || TVal != X ||
4355*d415bd75Srobert       !match(FVal, m_c_MaxOrMin(m_Specific(X), m_Specific(Y))))
4356*d415bd75Srobert     return nullptr;
4357*d415bd75Srobert 
4358*d415bd75Srobert   // (X >  Y) ? X : max(X, Y) --> max(X, Y)
4359*d415bd75Srobert   // (X >= Y) ? X : max(X, Y) --> max(X, Y)
4360*d415bd75Srobert   // (X <  Y) ? X : min(X, Y) --> min(X, Y)
4361*d415bd75Srobert   // (X <= Y) ? X : min(X, Y) --> min(X, Y)
4362*d415bd75Srobert   //
4363*d415bd75Srobert   // The equivalence allows a vector select (shuffle) of max/min and Y. Ex:
4364*d415bd75Srobert   // (X > Y) ? X : (Z ? max(X, Y) : Y)
4365*d415bd75Srobert   // If Z is true, this reduces as above, and if Z is false:
4366*d415bd75Srobert   // (X > Y) ? X : Y --> max(X, Y)
4367*d415bd75Srobert   ICmpInst::Predicate MMPred = MMI->getPredicate();
4368*d415bd75Srobert   if (MMPred == CmpInst::getStrictPredicate(Pred))
4369*d415bd75Srobert     return MMI;
4370*d415bd75Srobert 
4371*d415bd75Srobert   // Other transforms are not valid with a shuffle.
4372*d415bd75Srobert   if (PeekedThroughSelectShuffle)
4373*d415bd75Srobert     return nullptr;
4374*d415bd75Srobert 
4375*d415bd75Srobert   // (X == Y) ? X : max/min(X, Y) --> max/min(X, Y)
4376*d415bd75Srobert   if (Pred == CmpInst::ICMP_EQ)
4377*d415bd75Srobert     return MMI;
4378*d415bd75Srobert 
4379*d415bd75Srobert   // (X != Y) ? X : max/min(X, Y) --> X
4380*d415bd75Srobert   if (Pred == CmpInst::ICMP_NE)
4381*d415bd75Srobert     return X;
4382*d415bd75Srobert 
4383*d415bd75Srobert   // (X <  Y) ? X : max(X, Y) --> X
4384*d415bd75Srobert   // (X <= Y) ? X : max(X, Y) --> X
4385*d415bd75Srobert   // (X >  Y) ? X : min(X, Y) --> X
4386*d415bd75Srobert   // (X >= Y) ? X : min(X, Y) --> X
4387*d415bd75Srobert   ICmpInst::Predicate InvPred = CmpInst::getInversePredicate(Pred);
4388*d415bd75Srobert   if (MMPred == CmpInst::getStrictPredicate(InvPred))
4389*d415bd75Srobert     return X;
4390*d415bd75Srobert 
4391*d415bd75Srobert   return nullptr;
4392*d415bd75Srobert }
4393*d415bd75Srobert 
439409467b48Spatrick /// An alternative way to test if a bit is set or not uses sgt/slt instead of
439509467b48Spatrick /// eq/ne.
simplifySelectWithFakeICmpEq(Value * CmpLHS,Value * CmpRHS,ICmpInst::Predicate Pred,Value * TrueVal,Value * FalseVal)439609467b48Spatrick static Value *simplifySelectWithFakeICmpEq(Value *CmpLHS, Value *CmpRHS,
439709467b48Spatrick                                            ICmpInst::Predicate Pred,
439809467b48Spatrick                                            Value *TrueVal, Value *FalseVal) {
439909467b48Spatrick   Value *X;
440009467b48Spatrick   APInt Mask;
440109467b48Spatrick   if (!decomposeBitTestICmp(CmpLHS, CmpRHS, Pred, X, Mask))
440209467b48Spatrick     return nullptr;
440309467b48Spatrick 
440409467b48Spatrick   return simplifySelectBitTest(TrueVal, FalseVal, X, &Mask,
440509467b48Spatrick                                Pred == ICmpInst::ICMP_EQ);
440609467b48Spatrick }
440709467b48Spatrick 
440809467b48Spatrick /// Try to simplify a select instruction when its condition operand is an
440909467b48Spatrick /// integer comparison.
simplifySelectWithICmpCond(Value * CondVal,Value * TrueVal,Value * FalseVal,const SimplifyQuery & Q,unsigned MaxRecurse)441009467b48Spatrick static Value *simplifySelectWithICmpCond(Value *CondVal, Value *TrueVal,
4411*d415bd75Srobert                                          Value *FalseVal,
4412*d415bd75Srobert                                          const SimplifyQuery &Q,
441309467b48Spatrick                                          unsigned MaxRecurse) {
441409467b48Spatrick   ICmpInst::Predicate Pred;
441509467b48Spatrick   Value *CmpLHS, *CmpRHS;
441609467b48Spatrick   if (!match(CondVal, m_ICmp(Pred, m_Value(CmpLHS), m_Value(CmpRHS))))
441709467b48Spatrick     return nullptr;
441809467b48Spatrick 
4419*d415bd75Srobert   if (Value *V = simplifyCmpSelOfMaxMin(CmpLHS, CmpRHS, Pred, TrueVal, FalseVal))
4420*d415bd75Srobert     return V;
4421*d415bd75Srobert 
4422097a140dSpatrick   // Canonicalize ne to eq predicate.
4423097a140dSpatrick   if (Pred == ICmpInst::ICMP_NE) {
4424097a140dSpatrick     Pred = ICmpInst::ICMP_EQ;
4425097a140dSpatrick     std::swap(TrueVal, FalseVal);
4426097a140dSpatrick   }
4427097a140dSpatrick 
442873471bf0Spatrick   // Check for integer min/max with a limit constant:
442973471bf0Spatrick   // X > MIN_INT ? X : MIN_INT --> X
443073471bf0Spatrick   // X < MAX_INT ? X : MAX_INT --> X
443173471bf0Spatrick   if (TrueVal->getType()->isIntOrIntVectorTy()) {
443273471bf0Spatrick     Value *X, *Y;
443373471bf0Spatrick     SelectPatternFlavor SPF =
443473471bf0Spatrick         matchDecomposedSelectPattern(cast<ICmpInst>(CondVal), TrueVal, FalseVal,
4435*d415bd75Srobert                                      X, Y)
4436*d415bd75Srobert             .Flavor;
443773471bf0Spatrick     if (SelectPatternResult::isMinOrMax(SPF) && Pred == getMinMaxPred(SPF)) {
443873471bf0Spatrick       APInt LimitC = getMinMaxLimit(getInverseMinMaxFlavor(SPF),
443973471bf0Spatrick                                     X->getType()->getScalarSizeInBits());
444073471bf0Spatrick       if (match(Y, m_SpecificInt(LimitC)))
444173471bf0Spatrick         return X;
444273471bf0Spatrick     }
444373471bf0Spatrick   }
444473471bf0Spatrick 
4445097a140dSpatrick   if (Pred == ICmpInst::ICMP_EQ && match(CmpRHS, m_Zero())) {
444609467b48Spatrick     Value *X;
444709467b48Spatrick     const APInt *Y;
444809467b48Spatrick     if (match(CmpLHS, m_And(m_Value(X), m_APInt(Y))))
444909467b48Spatrick       if (Value *V = simplifySelectBitTest(TrueVal, FalseVal, X, Y,
4450097a140dSpatrick                                            /*TrueWhenUnset=*/true))
445109467b48Spatrick         return V;
445209467b48Spatrick 
445309467b48Spatrick     // Test for a bogus zero-shift-guard-op around funnel-shift or rotate.
445409467b48Spatrick     Value *ShAmt;
445573471bf0Spatrick     auto isFsh = m_CombineOr(m_FShl(m_Value(X), m_Value(), m_Value(ShAmt)),
445673471bf0Spatrick                              m_FShr(m_Value(), m_Value(X), m_Value(ShAmt)));
445709467b48Spatrick     // (ShAmt == 0) ? fshl(X, *, ShAmt) : X --> X
445809467b48Spatrick     // (ShAmt == 0) ? fshr(*, X, ShAmt) : X --> X
4459097a140dSpatrick     if (match(TrueVal, isFsh) && FalseVal == X && CmpLHS == ShAmt)
446009467b48Spatrick       return X;
446109467b48Spatrick 
446209467b48Spatrick     // Test for a zero-shift-guard-op around rotates. These are used to
446309467b48Spatrick     // avoid UB from oversized shifts in raw IR rotate patterns, but the
446409467b48Spatrick     // intrinsics do not have that problem.
446509467b48Spatrick     // We do not allow this transform for the general funnel shift case because
446609467b48Spatrick     // that would not preserve the poison safety of the original code.
446773471bf0Spatrick     auto isRotate =
446873471bf0Spatrick         m_CombineOr(m_FShl(m_Value(X), m_Deferred(X), m_Value(ShAmt)),
446973471bf0Spatrick                     m_FShr(m_Value(X), m_Deferred(X), m_Value(ShAmt)));
447009467b48Spatrick     // (ShAmt == 0) ? X : fshl(X, X, ShAmt) --> fshl(X, X, ShAmt)
447109467b48Spatrick     // (ShAmt == 0) ? X : fshr(X, X, ShAmt) --> fshr(X, X, ShAmt)
447209467b48Spatrick     if (match(FalseVal, isRotate) && TrueVal == X && CmpLHS == ShAmt &&
447309467b48Spatrick         Pred == ICmpInst::ICMP_EQ)
447409467b48Spatrick       return FalseVal;
447573471bf0Spatrick 
447673471bf0Spatrick     // X == 0 ? abs(X) : -abs(X) --> -abs(X)
447773471bf0Spatrick     // X == 0 ? -abs(X) : abs(X) --> abs(X)
447873471bf0Spatrick     if (match(TrueVal, m_Intrinsic<Intrinsic::abs>(m_Specific(CmpLHS))) &&
447973471bf0Spatrick         match(FalseVal, m_Neg(m_Intrinsic<Intrinsic::abs>(m_Specific(CmpLHS)))))
448073471bf0Spatrick       return FalseVal;
448173471bf0Spatrick     if (match(TrueVal,
448273471bf0Spatrick               m_Neg(m_Intrinsic<Intrinsic::abs>(m_Specific(CmpLHS)))) &&
448373471bf0Spatrick         match(FalseVal, m_Intrinsic<Intrinsic::abs>(m_Specific(CmpLHS))))
448473471bf0Spatrick       return FalseVal;
448509467b48Spatrick   }
448609467b48Spatrick 
448709467b48Spatrick   // Check for other compares that behave like bit test.
4488*d415bd75Srobert   if (Value *V =
4489*d415bd75Srobert           simplifySelectWithFakeICmpEq(CmpLHS, CmpRHS, Pred, TrueVal, FalseVal))
449009467b48Spatrick     return V;
449109467b48Spatrick 
449273471bf0Spatrick   // If we have a scalar equality comparison, then we know the value in one of
449373471bf0Spatrick   // the arms of the select. See if substituting this value into the arm and
449409467b48Spatrick   // simplifying the result yields the same value as the other arm.
4495*d415bd75Srobert   if (Pred == ICmpInst::ICMP_EQ) {
449673471bf0Spatrick     if (simplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q,
4497*d415bd75Srobert                                /* AllowRefinement */ false,
4498*d415bd75Srobert                                MaxRecurse) == TrueVal ||
449973471bf0Spatrick         simplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q,
4500*d415bd75Srobert                                /* AllowRefinement */ false,
4501*d415bd75Srobert                                MaxRecurse) == TrueVal)
450209467b48Spatrick       return FalseVal;
450373471bf0Spatrick     if (simplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q,
4504*d415bd75Srobert                                /* AllowRefinement */ true,
4505*d415bd75Srobert                                MaxRecurse) == FalseVal ||
450673471bf0Spatrick         simplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q,
4507*d415bd75Srobert                                /* AllowRefinement */ true,
4508*d415bd75Srobert                                MaxRecurse) == FalseVal)
450909467b48Spatrick       return FalseVal;
451009467b48Spatrick   }
451109467b48Spatrick 
451209467b48Spatrick   return nullptr;
451309467b48Spatrick }
451409467b48Spatrick 
451509467b48Spatrick /// Try to simplify a select instruction when its condition operand is a
451609467b48Spatrick /// floating-point comparison.
simplifySelectWithFCmp(Value * Cond,Value * T,Value * F,const SimplifyQuery & Q)451709467b48Spatrick static Value *simplifySelectWithFCmp(Value *Cond, Value *T, Value *F,
451809467b48Spatrick                                      const SimplifyQuery &Q) {
451909467b48Spatrick   FCmpInst::Predicate Pred;
452009467b48Spatrick   if (!match(Cond, m_FCmp(Pred, m_Specific(T), m_Specific(F))) &&
452109467b48Spatrick       !match(Cond, m_FCmp(Pred, m_Specific(F), m_Specific(T))))
452209467b48Spatrick     return nullptr;
452309467b48Spatrick 
452409467b48Spatrick   // This transform is safe if we do not have (do not care about) -0.0 or if
452509467b48Spatrick   // at least one operand is known to not be -0.0. Otherwise, the select can
452609467b48Spatrick   // change the sign of a zero operand.
4527*d415bd75Srobert   bool HasNoSignedZeros =
4528*d415bd75Srobert       Q.CxtI && isa<FPMathOperator>(Q.CxtI) && Q.CxtI->hasNoSignedZeros();
452909467b48Spatrick   const APFloat *C;
453009467b48Spatrick   if (HasNoSignedZeros || (match(T, m_APFloat(C)) && C->isNonZero()) ||
453109467b48Spatrick       (match(F, m_APFloat(C)) && C->isNonZero())) {
453209467b48Spatrick     // (T == F) ? T : F --> F
453309467b48Spatrick     // (F == T) ? T : F --> F
453409467b48Spatrick     if (Pred == FCmpInst::FCMP_OEQ)
453509467b48Spatrick       return F;
453609467b48Spatrick 
453709467b48Spatrick     // (T != F) ? T : F --> T
453809467b48Spatrick     // (F != T) ? T : F --> T
453909467b48Spatrick     if (Pred == FCmpInst::FCMP_UNE)
454009467b48Spatrick       return T;
454109467b48Spatrick   }
454209467b48Spatrick 
454309467b48Spatrick   return nullptr;
454409467b48Spatrick }
454509467b48Spatrick 
454609467b48Spatrick /// Given operands for a SelectInst, see if we can fold the result.
454709467b48Spatrick /// If not, this returns null.
simplifySelectInst(Value * Cond,Value * TrueVal,Value * FalseVal,const SimplifyQuery & Q,unsigned MaxRecurse)4548*d415bd75Srobert static Value *simplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
454909467b48Spatrick                                  const SimplifyQuery &Q, unsigned MaxRecurse) {
455009467b48Spatrick   if (auto *CondC = dyn_cast<Constant>(Cond)) {
455109467b48Spatrick     if (auto *TrueC = dyn_cast<Constant>(TrueVal))
455209467b48Spatrick       if (auto *FalseC = dyn_cast<Constant>(FalseVal))
455309467b48Spatrick         return ConstantFoldSelectInstruction(CondC, TrueC, FalseC);
455409467b48Spatrick 
455573471bf0Spatrick     // select poison, X, Y -> poison
455673471bf0Spatrick     if (isa<PoisonValue>(CondC))
455773471bf0Spatrick       return PoisonValue::get(TrueVal->getType());
455873471bf0Spatrick 
455909467b48Spatrick     // select undef, X, Y -> X or Y
456073471bf0Spatrick     if (Q.isUndefValue(CondC))
456109467b48Spatrick       return isa<Constant>(FalseVal) ? FalseVal : TrueVal;
456209467b48Spatrick 
456373471bf0Spatrick     // select true,  X, Y --> X
456473471bf0Spatrick     // select false, X, Y --> Y
456573471bf0Spatrick     // For vectors, allow undef/poison elements in the condition to match the
456673471bf0Spatrick     // defined elements, so we can eliminate the select.
456773471bf0Spatrick     if (match(CondC, m_One()))
456809467b48Spatrick       return TrueVal;
456973471bf0Spatrick     if (match(CondC, m_Zero()))
457009467b48Spatrick       return FalseVal;
457109467b48Spatrick   }
457209467b48Spatrick 
457309467b48Spatrick   assert(Cond->getType()->isIntOrIntVectorTy(1) &&
457409467b48Spatrick          "Select must have bool or bool vector condition");
457509467b48Spatrick   assert(TrueVal->getType() == FalseVal->getType() &&
457609467b48Spatrick          "Select must have same types for true/false ops");
4577*d415bd75Srobert 
4578*d415bd75Srobert   if (Cond->getType() == TrueVal->getType()) {
4579*d415bd75Srobert     // select i1 Cond, i1 true, i1 false --> i1 Cond
4580*d415bd75Srobert     if (match(TrueVal, m_One()) && match(FalseVal, m_ZeroInt()))
458109467b48Spatrick       return Cond;
458209467b48Spatrick 
4583*d415bd75Srobert     // (X && Y) ? X : Y --> Y (commuted 2 ways)
4584*d415bd75Srobert     if (match(Cond, m_c_LogicalAnd(m_Specific(TrueVal), m_Specific(FalseVal))))
4585*d415bd75Srobert       return FalseVal;
4586*d415bd75Srobert 
4587*d415bd75Srobert     // (X || Y) ? X : Y --> X (commuted 2 ways)
4588*d415bd75Srobert     if (match(Cond, m_c_LogicalOr(m_Specific(TrueVal), m_Specific(FalseVal))))
4589*d415bd75Srobert       return TrueVal;
4590*d415bd75Srobert 
4591*d415bd75Srobert     // (X || Y) ? false : X --> false (commuted 2 ways)
4592*d415bd75Srobert     if (match(Cond, m_c_LogicalOr(m_Specific(FalseVal), m_Value())) &&
4593*d415bd75Srobert         match(TrueVal, m_ZeroInt()))
4594*d415bd75Srobert       return ConstantInt::getFalse(Cond->getType());
4595*d415bd75Srobert 
4596*d415bd75Srobert     // Match patterns that end in logical-and.
4597*d415bd75Srobert     if (match(FalseVal, m_ZeroInt())) {
4598*d415bd75Srobert       // !(X || Y) && X --> false (commuted 2 ways)
4599*d415bd75Srobert       if (match(Cond, m_Not(m_c_LogicalOr(m_Specific(TrueVal), m_Value()))))
4600*d415bd75Srobert         return ConstantInt::getFalse(Cond->getType());
4601*d415bd75Srobert 
4602*d415bd75Srobert       // (X || Y) && Y --> Y (commuted 2 ways)
4603*d415bd75Srobert       if (match(Cond, m_c_LogicalOr(m_Specific(TrueVal), m_Value())))
4604*d415bd75Srobert         return TrueVal;
4605*d415bd75Srobert       // Y && (X || Y) --> Y (commuted 2 ways)
4606*d415bd75Srobert       if (match(TrueVal, m_c_LogicalOr(m_Specific(Cond), m_Value())))
4607*d415bd75Srobert         return Cond;
4608*d415bd75Srobert 
4609*d415bd75Srobert       // (X || Y) && (X || !Y) --> X (commuted 8 ways)
4610*d415bd75Srobert       Value *X, *Y;
4611*d415bd75Srobert       if (match(Cond, m_c_LogicalOr(m_Value(X), m_Not(m_Value(Y)))) &&
4612*d415bd75Srobert           match(TrueVal, m_c_LogicalOr(m_Specific(X), m_Specific(Y))))
4613*d415bd75Srobert         return X;
4614*d415bd75Srobert       if (match(TrueVal, m_c_LogicalOr(m_Value(X), m_Not(m_Value(Y)))) &&
4615*d415bd75Srobert           match(Cond, m_c_LogicalOr(m_Specific(X), m_Specific(Y))))
4616*d415bd75Srobert         return X;
4617*d415bd75Srobert     }
4618*d415bd75Srobert 
4619*d415bd75Srobert     // Match patterns that end in logical-or.
4620*d415bd75Srobert     if (match(TrueVal, m_One())) {
4621*d415bd75Srobert       // (X && Y) || Y --> Y (commuted 2 ways)
4622*d415bd75Srobert       if (match(Cond, m_c_LogicalAnd(m_Specific(FalseVal), m_Value())))
4623*d415bd75Srobert         return FalseVal;
4624*d415bd75Srobert       // Y || (X && Y) --> Y (commuted 2 ways)
4625*d415bd75Srobert       if (match(FalseVal, m_c_LogicalAnd(m_Specific(Cond), m_Value())))
4626*d415bd75Srobert         return Cond;
4627*d415bd75Srobert     }
4628*d415bd75Srobert   }
4629*d415bd75Srobert 
463009467b48Spatrick   // select ?, X, X -> X
463109467b48Spatrick   if (TrueVal == FalseVal)
463209467b48Spatrick     return TrueVal;
463309467b48Spatrick 
4634*d415bd75Srobert   if (Cond == TrueVal) {
4635*d415bd75Srobert     // select i1 X, i1 X, i1 false --> X (logical-and)
4636*d415bd75Srobert     if (match(FalseVal, m_ZeroInt()))
4637*d415bd75Srobert       return Cond;
4638*d415bd75Srobert     // select i1 X, i1 X, i1 true --> true
4639*d415bd75Srobert     if (match(FalseVal, m_One()))
4640*d415bd75Srobert       return ConstantInt::getTrue(Cond->getType());
4641*d415bd75Srobert   }
4642*d415bd75Srobert   if (Cond == FalseVal) {
4643*d415bd75Srobert     // select i1 X, i1 true, i1 X --> X (logical-or)
4644*d415bd75Srobert     if (match(TrueVal, m_One()))
4645*d415bd75Srobert       return Cond;
4646*d415bd75Srobert     // select i1 X, i1 false, i1 X --> false
4647*d415bd75Srobert     if (match(TrueVal, m_ZeroInt()))
4648*d415bd75Srobert       return ConstantInt::getFalse(Cond->getType());
4649*d415bd75Srobert   }
4650*d415bd75Srobert 
465173471bf0Spatrick   // If the true or false value is poison, we can fold to the other value.
465273471bf0Spatrick   // If the true or false value is undef, we can fold to the other value as
465373471bf0Spatrick   // long as the other value isn't poison.
465473471bf0Spatrick   // select ?, poison, X -> X
465573471bf0Spatrick   // select ?, undef,  X -> X
465673471bf0Spatrick   if (isa<PoisonValue>(TrueVal) ||
465773471bf0Spatrick       (Q.isUndefValue(TrueVal) &&
465873471bf0Spatrick        isGuaranteedNotToBePoison(FalseVal, Q.AC, Q.CxtI, Q.DT)))
465909467b48Spatrick     return FalseVal;
466073471bf0Spatrick   // select ?, X, poison -> X
466173471bf0Spatrick   // select ?, X, undef  -> X
466273471bf0Spatrick   if (isa<PoisonValue>(FalseVal) ||
466373471bf0Spatrick       (Q.isUndefValue(FalseVal) &&
466473471bf0Spatrick        isGuaranteedNotToBePoison(TrueVal, Q.AC, Q.CxtI, Q.DT)))
466509467b48Spatrick     return TrueVal;
466609467b48Spatrick 
4667097a140dSpatrick   // Deal with partial undef vector constants: select ?, VecC, VecC' --> VecC''
4668097a140dSpatrick   Constant *TrueC, *FalseC;
466973471bf0Spatrick   if (isa<FixedVectorType>(TrueVal->getType()) &&
467073471bf0Spatrick       match(TrueVal, m_Constant(TrueC)) &&
4671097a140dSpatrick       match(FalseVal, m_Constant(FalseC))) {
467273471bf0Spatrick     unsigned NumElts =
467373471bf0Spatrick         cast<FixedVectorType>(TrueC->getType())->getNumElements();
4674097a140dSpatrick     SmallVector<Constant *, 16> NewC;
4675097a140dSpatrick     for (unsigned i = 0; i != NumElts; ++i) {
4676097a140dSpatrick       // Bail out on incomplete vector constants.
4677097a140dSpatrick       Constant *TEltC = TrueC->getAggregateElement(i);
4678097a140dSpatrick       Constant *FEltC = FalseC->getAggregateElement(i);
4679097a140dSpatrick       if (!TEltC || !FEltC)
4680097a140dSpatrick         break;
4681097a140dSpatrick 
4682097a140dSpatrick       // If the elements match (undef or not), that value is the result. If only
4683097a140dSpatrick       // one element is undef, choose the defined element as the safe result.
4684097a140dSpatrick       if (TEltC == FEltC)
4685097a140dSpatrick         NewC.push_back(TEltC);
468673471bf0Spatrick       else if (isa<PoisonValue>(TEltC) ||
468773471bf0Spatrick                (Q.isUndefValue(TEltC) && isGuaranteedNotToBePoison(FEltC)))
4688097a140dSpatrick         NewC.push_back(FEltC);
468973471bf0Spatrick       else if (isa<PoisonValue>(FEltC) ||
469073471bf0Spatrick                (Q.isUndefValue(FEltC) && isGuaranteedNotToBePoison(TEltC)))
4691097a140dSpatrick         NewC.push_back(TEltC);
4692097a140dSpatrick       else
4693097a140dSpatrick         break;
4694097a140dSpatrick     }
4695097a140dSpatrick     if (NewC.size() == NumElts)
4696097a140dSpatrick       return ConstantVector::get(NewC);
4697097a140dSpatrick   }
4698097a140dSpatrick 
469909467b48Spatrick   if (Value *V =
470009467b48Spatrick           simplifySelectWithICmpCond(Cond, TrueVal, FalseVal, Q, MaxRecurse))
470109467b48Spatrick     return V;
470209467b48Spatrick 
470309467b48Spatrick   if (Value *V = simplifySelectWithFCmp(Cond, TrueVal, FalseVal, Q))
470409467b48Spatrick     return V;
470509467b48Spatrick 
470609467b48Spatrick   if (Value *V = foldSelectWithBinaryOp(Cond, TrueVal, FalseVal))
470709467b48Spatrick     return V;
470809467b48Spatrick 
4709*d415bd75Srobert   std::optional<bool> Imp = isImpliedByDomCondition(Cond, Q.CxtI, Q.DL);
471009467b48Spatrick   if (Imp)
471109467b48Spatrick     return *Imp ? TrueVal : FalseVal;
471209467b48Spatrick 
471309467b48Spatrick   return nullptr;
471409467b48Spatrick }
471509467b48Spatrick 
simplifySelectInst(Value * Cond,Value * TrueVal,Value * FalseVal,const SimplifyQuery & Q)4716*d415bd75Srobert Value *llvm::simplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
471709467b48Spatrick                                 const SimplifyQuery &Q) {
4718*d415bd75Srobert   return ::simplifySelectInst(Cond, TrueVal, FalseVal, Q, RecursionLimit);
471909467b48Spatrick }
472009467b48Spatrick 
472109467b48Spatrick /// Given operands for an GetElementPtrInst, see if we can fold the result.
472209467b48Spatrick /// If not, this returns null.
simplifyGEPInst(Type * SrcTy,Value * Ptr,ArrayRef<Value * > Indices,bool InBounds,const SimplifyQuery & Q,unsigned)4723*d415bd75Srobert static Value *simplifyGEPInst(Type *SrcTy, Value *Ptr,
4724*d415bd75Srobert                               ArrayRef<Value *> Indices, bool InBounds,
472509467b48Spatrick                               const SimplifyQuery &Q, unsigned) {
472609467b48Spatrick   // The type of the GEP pointer operand.
472709467b48Spatrick   unsigned AS =
4728*d415bd75Srobert       cast<PointerType>(Ptr->getType()->getScalarType())->getAddressSpace();
472909467b48Spatrick 
473009467b48Spatrick   // getelementptr P -> P.
4731*d415bd75Srobert   if (Indices.empty())
4732*d415bd75Srobert     return Ptr;
473309467b48Spatrick 
473409467b48Spatrick   // Compute the (pointer) type returned by the GEP instruction.
4735*d415bd75Srobert   Type *LastType = GetElementPtrInst::getIndexedType(SrcTy, Indices);
473609467b48Spatrick   Type *GEPTy = PointerType::get(LastType, AS);
4737*d415bd75Srobert   if (VectorType *VT = dyn_cast<VectorType>(Ptr->getType()))
4738*d415bd75Srobert     GEPTy = VectorType::get(GEPTy, VT->getElementCount());
4739*d415bd75Srobert   else {
4740*d415bd75Srobert     for (Value *Op : Indices) {
474173471bf0Spatrick       // If one of the operands is a vector, the result type is a vector of
474273471bf0Spatrick       // pointers. All vector operands must have the same number of elements.
474373471bf0Spatrick       if (VectorType *VT = dyn_cast<VectorType>(Op->getType())) {
4744097a140dSpatrick         GEPTy = VectorType::get(GEPTy, VT->getElementCount());
474573471bf0Spatrick         break;
474673471bf0Spatrick       }
474773471bf0Spatrick     }
4748*d415bd75Srobert   }
4749*d415bd75Srobert 
4750*d415bd75Srobert   // For opaque pointers an all-zero GEP is a no-op. For typed pointers,
4751*d415bd75Srobert   // it may be equivalent to a bitcast.
4752*d415bd75Srobert   if (Ptr->getType()->getScalarType()->isOpaquePointerTy() &&
4753*d415bd75Srobert       Ptr->getType() == GEPTy &&
4754*d415bd75Srobert       all_of(Indices, [](const auto *V) { return match(V, m_Zero()); }))
4755*d415bd75Srobert     return Ptr;
475609467b48Spatrick 
475773471bf0Spatrick   // getelementptr poison, idx -> poison
475873471bf0Spatrick   // getelementptr baseptr, poison -> poison
4759*d415bd75Srobert   if (isa<PoisonValue>(Ptr) ||
4760*d415bd75Srobert       any_of(Indices, [](const auto *V) { return isa<PoisonValue>(V); }))
476173471bf0Spatrick     return PoisonValue::get(GEPTy);
476273471bf0Spatrick 
4763*d415bd75Srobert   if (Q.isUndefValue(Ptr))
4764*d415bd75Srobert     // If inbounds, we can choose an out-of-bounds pointer as a base pointer.
4765*d415bd75Srobert     return InBounds ? PoisonValue::get(GEPTy) : UndefValue::get(GEPTy);
476609467b48Spatrick 
476773471bf0Spatrick   bool IsScalableVec =
4768*d415bd75Srobert       isa<ScalableVectorType>(SrcTy) || any_of(Indices, [](const Value *V) {
476973471bf0Spatrick         return isa<ScalableVectorType>(V->getType());
477073471bf0Spatrick       });
4771097a140dSpatrick 
4772*d415bd75Srobert   if (Indices.size() == 1) {
477309467b48Spatrick     // getelementptr P, 0 -> P.
4774*d415bd75Srobert     if (match(Indices[0], m_Zero()) && Ptr->getType() == GEPTy)
4775*d415bd75Srobert       return Ptr;
477609467b48Spatrick 
477709467b48Spatrick     Type *Ty = SrcTy;
4778097a140dSpatrick     if (!IsScalableVec && Ty->isSized()) {
477909467b48Spatrick       Value *P;
478009467b48Spatrick       uint64_t C;
478109467b48Spatrick       uint64_t TyAllocSize = Q.DL.getTypeAllocSize(Ty);
478209467b48Spatrick       // getelementptr P, N -> P if P points to a type of zero size.
4783*d415bd75Srobert       if (TyAllocSize == 0 && Ptr->getType() == GEPTy)
4784*d415bd75Srobert         return Ptr;
478509467b48Spatrick 
478609467b48Spatrick       // The following transforms are only safe if the ptrtoint cast
478709467b48Spatrick       // doesn't truncate the pointers.
4788*d415bd75Srobert       if (Indices[0]->getType()->getScalarSizeInBits() ==
478909467b48Spatrick           Q.DL.getPointerSizeInBits(AS)) {
4790*d415bd75Srobert         auto CanSimplify = [GEPTy, &P, Ptr]() -> bool {
479173471bf0Spatrick           return P->getType() == GEPTy &&
4792*d415bd75Srobert                  getUnderlyingObject(P) == getUnderlyingObject(Ptr);
479309467b48Spatrick         };
479409467b48Spatrick         // getelementptr V, (sub P, V) -> P if P points to a type of size 1.
479509467b48Spatrick         if (TyAllocSize == 1 &&
4796*d415bd75Srobert             match(Indices[0],
4797*d415bd75Srobert                   m_Sub(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Specific(Ptr)))) &&
479873471bf0Spatrick             CanSimplify())
479973471bf0Spatrick           return P;
480009467b48Spatrick 
480173471bf0Spatrick         // getelementptr V, (ashr (sub P, V), C) -> P if P points to a type of
480273471bf0Spatrick         // size 1 << C.
4803*d415bd75Srobert         if (match(Indices[0], m_AShr(m_Sub(m_PtrToInt(m_Value(P)),
4804*d415bd75Srobert                                            m_PtrToInt(m_Specific(Ptr))),
480509467b48Spatrick                                      m_ConstantInt(C))) &&
480673471bf0Spatrick             TyAllocSize == 1ULL << C && CanSimplify())
480773471bf0Spatrick           return P;
480809467b48Spatrick 
480973471bf0Spatrick         // getelementptr V, (sdiv (sub P, V), C) -> P if P points to a type of
481073471bf0Spatrick         // size C.
4811*d415bd75Srobert         if (match(Indices[0], m_SDiv(m_Sub(m_PtrToInt(m_Value(P)),
4812*d415bd75Srobert                                            m_PtrToInt(m_Specific(Ptr))),
481373471bf0Spatrick                                      m_SpecificInt(TyAllocSize))) &&
481473471bf0Spatrick             CanSimplify())
481573471bf0Spatrick           return P;
481609467b48Spatrick       }
481709467b48Spatrick     }
481809467b48Spatrick   }
481909467b48Spatrick 
4820097a140dSpatrick   if (!IsScalableVec && Q.DL.getTypeAllocSize(LastType) == 1 &&
4821*d415bd75Srobert       all_of(Indices.drop_back(1),
482209467b48Spatrick              [](Value *Idx) { return match(Idx, m_Zero()); })) {
482309467b48Spatrick     unsigned IdxWidth =
4824*d415bd75Srobert         Q.DL.getIndexSizeInBits(Ptr->getType()->getPointerAddressSpace());
4825*d415bd75Srobert     if (Q.DL.getTypeSizeInBits(Indices.back()->getType()) == IdxWidth) {
482609467b48Spatrick       APInt BasePtrOffset(IdxWidth, 0);
482709467b48Spatrick       Value *StrippedBasePtr =
4828*d415bd75Srobert           Ptr->stripAndAccumulateInBoundsConstantOffsets(Q.DL, BasePtrOffset);
482909467b48Spatrick 
483073471bf0Spatrick       // Avoid creating inttoptr of zero here: While LLVMs treatment of
483173471bf0Spatrick       // inttoptr is generally conservative, this particular case is folded to
483273471bf0Spatrick       // a null pointer, which will have incorrect provenance.
483373471bf0Spatrick 
483409467b48Spatrick       // gep (gep V, C), (sub 0, V) -> C
4835*d415bd75Srobert       if (match(Indices.back(),
483673471bf0Spatrick                 m_Sub(m_Zero(), m_PtrToInt(m_Specific(StrippedBasePtr)))) &&
4837*d415bd75Srobert           !BasePtrOffset.isZero()) {
483809467b48Spatrick         auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset);
483909467b48Spatrick         return ConstantExpr::getIntToPtr(CI, GEPTy);
484009467b48Spatrick       }
484109467b48Spatrick       // gep (gep V, C), (xor V, -1) -> C-1
4842*d415bd75Srobert       if (match(Indices.back(),
484373471bf0Spatrick                 m_Xor(m_PtrToInt(m_Specific(StrippedBasePtr)), m_AllOnes())) &&
4844*d415bd75Srobert           !BasePtrOffset.isOne()) {
484509467b48Spatrick         auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset - 1);
484609467b48Spatrick         return ConstantExpr::getIntToPtr(CI, GEPTy);
484709467b48Spatrick       }
484809467b48Spatrick     }
484909467b48Spatrick   }
485009467b48Spatrick 
485109467b48Spatrick   // Check to see if this is constant foldable.
4852*d415bd75Srobert   if (!isa<Constant>(Ptr) ||
4853*d415bd75Srobert       !all_of(Indices, [](Value *V) { return isa<Constant>(V); }))
485409467b48Spatrick     return nullptr;
485509467b48Spatrick 
4856*d415bd75Srobert   auto *CE = ConstantExpr::getGetElementPtr(SrcTy, cast<Constant>(Ptr), Indices,
4857*d415bd75Srobert                                             InBounds);
4858097a140dSpatrick   return ConstantFoldConstant(CE, Q.DL);
485909467b48Spatrick }
486009467b48Spatrick 
simplifyGEPInst(Type * SrcTy,Value * Ptr,ArrayRef<Value * > Indices,bool InBounds,const SimplifyQuery & Q)4861*d415bd75Srobert Value *llvm::simplifyGEPInst(Type *SrcTy, Value *Ptr, ArrayRef<Value *> Indices,
4862*d415bd75Srobert                              bool InBounds, const SimplifyQuery &Q) {
4863*d415bd75Srobert   return ::simplifyGEPInst(SrcTy, Ptr, Indices, InBounds, Q, RecursionLimit);
486409467b48Spatrick }
486509467b48Spatrick 
486609467b48Spatrick /// Given operands for an InsertValueInst, see if we can fold the result.
486709467b48Spatrick /// If not, this returns null.
simplifyInsertValueInst(Value * Agg,Value * Val,ArrayRef<unsigned> Idxs,const SimplifyQuery & Q,unsigned)4868*d415bd75Srobert static Value *simplifyInsertValueInst(Value *Agg, Value *Val,
4869*d415bd75Srobert                                       ArrayRef<unsigned> Idxs,
4870*d415bd75Srobert                                       const SimplifyQuery &Q, unsigned) {
487109467b48Spatrick   if (Constant *CAgg = dyn_cast<Constant>(Agg))
487209467b48Spatrick     if (Constant *CVal = dyn_cast<Constant>(Val))
487309467b48Spatrick       return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
487409467b48Spatrick 
4875*d415bd75Srobert   // insertvalue x, poison, n -> x
4876*d415bd75Srobert   // insertvalue x, undef, n -> x if x cannot be poison
4877*d415bd75Srobert   if (isa<PoisonValue>(Val) ||
4878*d415bd75Srobert       (Q.isUndefValue(Val) && isGuaranteedNotToBePoison(Agg)))
487909467b48Spatrick     return Agg;
488009467b48Spatrick 
488109467b48Spatrick   // insertvalue x, (extractvalue y, n), n
488209467b48Spatrick   if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
488309467b48Spatrick     if (EV->getAggregateOperand()->getType() == Agg->getType() &&
488409467b48Spatrick         EV->getIndices() == Idxs) {
488509467b48Spatrick       // insertvalue undef, (extractvalue y, n), n -> y
488673471bf0Spatrick       if (Q.isUndefValue(Agg))
488709467b48Spatrick         return EV->getAggregateOperand();
488809467b48Spatrick 
488909467b48Spatrick       // insertvalue y, (extractvalue y, n), n -> y
489009467b48Spatrick       if (Agg == EV->getAggregateOperand())
489109467b48Spatrick         return Agg;
489209467b48Spatrick     }
489309467b48Spatrick 
489409467b48Spatrick   return nullptr;
489509467b48Spatrick }
489609467b48Spatrick 
simplifyInsertValueInst(Value * Agg,Value * Val,ArrayRef<unsigned> Idxs,const SimplifyQuery & Q)4897*d415bd75Srobert Value *llvm::simplifyInsertValueInst(Value *Agg, Value *Val,
489809467b48Spatrick                                      ArrayRef<unsigned> Idxs,
489909467b48Spatrick                                      const SimplifyQuery &Q) {
4900*d415bd75Srobert   return ::simplifyInsertValueInst(Agg, Val, Idxs, Q, RecursionLimit);
490109467b48Spatrick }
490209467b48Spatrick 
simplifyInsertElementInst(Value * Vec,Value * Val,Value * Idx,const SimplifyQuery & Q)4903*d415bd75Srobert Value *llvm::simplifyInsertElementInst(Value *Vec, Value *Val, Value *Idx,
490409467b48Spatrick                                        const SimplifyQuery &Q) {
490509467b48Spatrick   // Try to constant fold.
490609467b48Spatrick   auto *VecC = dyn_cast<Constant>(Vec);
490709467b48Spatrick   auto *ValC = dyn_cast<Constant>(Val);
490809467b48Spatrick   auto *IdxC = dyn_cast<Constant>(Idx);
490909467b48Spatrick   if (VecC && ValC && IdxC)
491073471bf0Spatrick     return ConstantExpr::getInsertElement(VecC, ValC, IdxC);
491109467b48Spatrick 
491273471bf0Spatrick   // For fixed-length vector, fold into poison if index is out of bounds.
491309467b48Spatrick   if (auto *CI = dyn_cast<ConstantInt>(Idx)) {
4914097a140dSpatrick     if (isa<FixedVectorType>(Vec->getType()) &&
4915097a140dSpatrick         CI->uge(cast<FixedVectorType>(Vec->getType())->getNumElements()))
491673471bf0Spatrick       return PoisonValue::get(Vec->getType());
491709467b48Spatrick   }
491809467b48Spatrick 
491909467b48Spatrick   // If index is undef, it might be out of bounds (see above case)
492073471bf0Spatrick   if (Q.isUndefValue(Idx))
492173471bf0Spatrick     return PoisonValue::get(Vec->getType());
492209467b48Spatrick 
492373471bf0Spatrick   // If the scalar is poison, or it is undef and there is no risk of
492473471bf0Spatrick   // propagating poison from the vector value, simplify to the vector value.
492573471bf0Spatrick   if (isa<PoisonValue>(Val) ||
492673471bf0Spatrick       (Q.isUndefValue(Val) && isGuaranteedNotToBePoison(Vec)))
492709467b48Spatrick     return Vec;
492809467b48Spatrick 
492909467b48Spatrick   // If we are extracting a value from a vector, then inserting it into the same
493009467b48Spatrick   // place, that's the input vector:
493109467b48Spatrick   // insertelt Vec, (extractelt Vec, Idx), Idx --> Vec
4932097a140dSpatrick   if (match(Val, m_ExtractElt(m_Specific(Vec), m_Specific(Idx))))
493309467b48Spatrick     return Vec;
493409467b48Spatrick 
493509467b48Spatrick   return nullptr;
493609467b48Spatrick }
493709467b48Spatrick 
493809467b48Spatrick /// Given operands for an ExtractValueInst, see if we can fold the result.
493909467b48Spatrick /// If not, this returns null.
simplifyExtractValueInst(Value * Agg,ArrayRef<unsigned> Idxs,const SimplifyQuery &,unsigned)4940*d415bd75Srobert static Value *simplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
494109467b48Spatrick                                        const SimplifyQuery &, unsigned) {
494209467b48Spatrick   if (auto *CAgg = dyn_cast<Constant>(Agg))
494309467b48Spatrick     return ConstantFoldExtractValueInstruction(CAgg, Idxs);
494409467b48Spatrick 
494509467b48Spatrick   // extractvalue x, (insertvalue y, elt, n), n -> elt
494609467b48Spatrick   unsigned NumIdxs = Idxs.size();
494709467b48Spatrick   for (auto *IVI = dyn_cast<InsertValueInst>(Agg); IVI != nullptr;
494809467b48Spatrick        IVI = dyn_cast<InsertValueInst>(IVI->getAggregateOperand())) {
494909467b48Spatrick     ArrayRef<unsigned> InsertValueIdxs = IVI->getIndices();
495009467b48Spatrick     unsigned NumInsertValueIdxs = InsertValueIdxs.size();
495109467b48Spatrick     unsigned NumCommonIdxs = std::min(NumInsertValueIdxs, NumIdxs);
495209467b48Spatrick     if (InsertValueIdxs.slice(0, NumCommonIdxs) ==
495309467b48Spatrick         Idxs.slice(0, NumCommonIdxs)) {
495409467b48Spatrick       if (NumIdxs == NumInsertValueIdxs)
495509467b48Spatrick         return IVI->getInsertedValueOperand();
495609467b48Spatrick       break;
495709467b48Spatrick     }
495809467b48Spatrick   }
495909467b48Spatrick 
496009467b48Spatrick   return nullptr;
496109467b48Spatrick }
496209467b48Spatrick 
simplifyExtractValueInst(Value * Agg,ArrayRef<unsigned> Idxs,const SimplifyQuery & Q)4963*d415bd75Srobert Value *llvm::simplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
496409467b48Spatrick                                       const SimplifyQuery &Q) {
4965*d415bd75Srobert   return ::simplifyExtractValueInst(Agg, Idxs, Q, RecursionLimit);
496609467b48Spatrick }
496709467b48Spatrick 
496809467b48Spatrick /// Given operands for an ExtractElementInst, see if we can fold the result.
496909467b48Spatrick /// If not, this returns null.
simplifyExtractElementInst(Value * Vec,Value * Idx,const SimplifyQuery & Q,unsigned)4970*d415bd75Srobert static Value *simplifyExtractElementInst(Value *Vec, Value *Idx,
497173471bf0Spatrick                                          const SimplifyQuery &Q, unsigned) {
4972097a140dSpatrick   auto *VecVTy = cast<VectorType>(Vec->getType());
497309467b48Spatrick   if (auto *CVec = dyn_cast<Constant>(Vec)) {
497409467b48Spatrick     if (auto *CIdx = dyn_cast<Constant>(Idx))
497573471bf0Spatrick       return ConstantExpr::getExtractElement(CVec, CIdx);
497609467b48Spatrick 
497773471bf0Spatrick     if (Q.isUndefValue(Vec))
4978097a140dSpatrick       return UndefValue::get(VecVTy->getElementType());
497909467b48Spatrick   }
498009467b48Spatrick 
498173471bf0Spatrick   // An undef extract index can be arbitrarily chosen to be an out-of-range
498273471bf0Spatrick   // index value, which would result in the instruction being poison.
498373471bf0Spatrick   if (Q.isUndefValue(Idx))
498473471bf0Spatrick     return PoisonValue::get(VecVTy->getElementType());
498573471bf0Spatrick 
498609467b48Spatrick   // If extracting a specified index from the vector, see if we can recursively
498709467b48Spatrick   // find a previously computed scalar that was inserted into the vector.
498809467b48Spatrick   if (auto *IdxC = dyn_cast<ConstantInt>(Idx)) {
4989097a140dSpatrick     // For fixed-length vector, fold into undef if index is out of bounds.
499073471bf0Spatrick     unsigned MinNumElts = VecVTy->getElementCount().getKnownMinValue();
499173471bf0Spatrick     if (isa<FixedVectorType>(VecVTy) && IdxC->getValue().uge(MinNumElts))
499273471bf0Spatrick       return PoisonValue::get(VecVTy->getElementType());
499373471bf0Spatrick     // Handle case where an element is extracted from a splat.
499473471bf0Spatrick     if (IdxC->getValue().ult(MinNumElts))
499573471bf0Spatrick       if (auto *Splat = getSplatValue(Vec))
499673471bf0Spatrick         return Splat;
499709467b48Spatrick     if (Value *Elt = findScalarElement(Vec, IdxC->getZExtValue()))
499809467b48Spatrick       return Elt;
499973471bf0Spatrick   } else {
5000*d415bd75Srobert     // extractelt x, (insertelt y, elt, n), n -> elt
5001*d415bd75Srobert     // If the possibly-variable indices are trivially known to be equal
5002*d415bd75Srobert     // (because they are the same operand) then use the value that was
5003*d415bd75Srobert     // inserted directly.
5004*d415bd75Srobert     auto *IE = dyn_cast<InsertElementInst>(Vec);
5005*d415bd75Srobert     if (IE && IE->getOperand(2) == Idx)
5006*d415bd75Srobert       return IE->getOperand(1);
5007*d415bd75Srobert 
500873471bf0Spatrick     // The index is not relevant if our vector is a splat.
500973471bf0Spatrick     if (Value *Splat = getSplatValue(Vec))
501073471bf0Spatrick       return Splat;
501109467b48Spatrick   }
501209467b48Spatrick   return nullptr;
501309467b48Spatrick }
501409467b48Spatrick 
simplifyExtractElementInst(Value * Vec,Value * Idx,const SimplifyQuery & Q)5015*d415bd75Srobert Value *llvm::simplifyExtractElementInst(Value *Vec, Value *Idx,
501609467b48Spatrick                                         const SimplifyQuery &Q) {
5017*d415bd75Srobert   return ::simplifyExtractElementInst(Vec, Idx, Q, RecursionLimit);
501809467b48Spatrick }
501909467b48Spatrick 
502009467b48Spatrick /// See if we can fold the given phi. If not, returns null.
simplifyPHINode(PHINode * PN,ArrayRef<Value * > IncomingValues,const SimplifyQuery & Q)5021*d415bd75Srobert static Value *simplifyPHINode(PHINode *PN, ArrayRef<Value *> IncomingValues,
502273471bf0Spatrick                               const SimplifyQuery &Q) {
502373471bf0Spatrick   // WARNING: no matter how worthwhile it may seem, we can not perform PHI CSE
502473471bf0Spatrick   //          here, because the PHI we may succeed simplifying to was not
502573471bf0Spatrick   //          def-reachable from the original PHI!
502673471bf0Spatrick 
502709467b48Spatrick   // If all of the PHI's incoming values are the same then replace the PHI node
502809467b48Spatrick   // with the common value.
502909467b48Spatrick   Value *CommonValue = nullptr;
503009467b48Spatrick   bool HasUndefInput = false;
503173471bf0Spatrick   for (Value *Incoming : IncomingValues) {
503209467b48Spatrick     // If the incoming value is the phi node itself, it can safely be skipped.
5033*d415bd75Srobert     if (Incoming == PN)
5034*d415bd75Srobert       continue;
503573471bf0Spatrick     if (Q.isUndefValue(Incoming)) {
503609467b48Spatrick       // Remember that we saw an undef value, but otherwise ignore them.
503709467b48Spatrick       HasUndefInput = true;
503809467b48Spatrick       continue;
503909467b48Spatrick     }
504009467b48Spatrick     if (CommonValue && Incoming != CommonValue)
504109467b48Spatrick       return nullptr; // Not the same, bail out.
504209467b48Spatrick     CommonValue = Incoming;
504309467b48Spatrick   }
504409467b48Spatrick 
504509467b48Spatrick   // If CommonValue is null then all of the incoming values were either undef or
504609467b48Spatrick   // equal to the phi node itself.
504709467b48Spatrick   if (!CommonValue)
504809467b48Spatrick     return UndefValue::get(PN->getType());
504909467b48Spatrick 
5050*d415bd75Srobert   if (HasUndefInput) {
505109467b48Spatrick     // If we have a PHI node like phi(X, undef, X), where X is defined by some
505209467b48Spatrick     // instruction, we cannot return X as the result of the PHI node unless it
505309467b48Spatrick     // dominates the PHI block.
505409467b48Spatrick     return valueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr;
5055*d415bd75Srobert   }
505609467b48Spatrick 
505709467b48Spatrick   return CommonValue;
505809467b48Spatrick }
505909467b48Spatrick 
simplifyCastInst(unsigned CastOpc,Value * Op,Type * Ty,const SimplifyQuery & Q,unsigned MaxRecurse)5060*d415bd75Srobert static Value *simplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty,
5061*d415bd75Srobert                                const SimplifyQuery &Q, unsigned MaxRecurse) {
506209467b48Spatrick   if (auto *C = dyn_cast<Constant>(Op))
506309467b48Spatrick     return ConstantFoldCastOperand(CastOpc, C, Ty, Q.DL);
506409467b48Spatrick 
506509467b48Spatrick   if (auto *CI = dyn_cast<CastInst>(Op)) {
506609467b48Spatrick     auto *Src = CI->getOperand(0);
506709467b48Spatrick     Type *SrcTy = Src->getType();
506809467b48Spatrick     Type *MidTy = CI->getType();
506909467b48Spatrick     Type *DstTy = Ty;
507009467b48Spatrick     if (Src->getType() == Ty) {
507109467b48Spatrick       auto FirstOp = static_cast<Instruction::CastOps>(CI->getOpcode());
507209467b48Spatrick       auto SecondOp = static_cast<Instruction::CastOps>(CastOpc);
507309467b48Spatrick       Type *SrcIntPtrTy =
507409467b48Spatrick           SrcTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(SrcTy) : nullptr;
507509467b48Spatrick       Type *MidIntPtrTy =
507609467b48Spatrick           MidTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(MidTy) : nullptr;
507709467b48Spatrick       Type *DstIntPtrTy =
507809467b48Spatrick           DstTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(DstTy) : nullptr;
507909467b48Spatrick       if (CastInst::isEliminableCastPair(FirstOp, SecondOp, SrcTy, MidTy, DstTy,
508009467b48Spatrick                                          SrcIntPtrTy, MidIntPtrTy,
508109467b48Spatrick                                          DstIntPtrTy) == Instruction::BitCast)
508209467b48Spatrick         return Src;
508309467b48Spatrick     }
508409467b48Spatrick   }
508509467b48Spatrick 
508609467b48Spatrick   // bitcast x -> x
508709467b48Spatrick   if (CastOpc == Instruction::BitCast)
508809467b48Spatrick     if (Op->getType() == Ty)
508909467b48Spatrick       return Op;
509009467b48Spatrick 
509109467b48Spatrick   return nullptr;
509209467b48Spatrick }
509309467b48Spatrick 
simplifyCastInst(unsigned CastOpc,Value * Op,Type * Ty,const SimplifyQuery & Q)5094*d415bd75Srobert Value *llvm::simplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty,
509509467b48Spatrick                               const SimplifyQuery &Q) {
5096*d415bd75Srobert   return ::simplifyCastInst(CastOpc, Op, Ty, Q, RecursionLimit);
509709467b48Spatrick }
509809467b48Spatrick 
509909467b48Spatrick /// For the given destination element of a shuffle, peek through shuffles to
510009467b48Spatrick /// match a root vector source operand that contains that element in the same
510109467b48Spatrick /// vector lane (ie, the same mask index), so we can eliminate the shuffle(s).
foldIdentityShuffles(int DestElt,Value * Op0,Value * Op1,int MaskVal,Value * RootVec,unsigned MaxRecurse)510209467b48Spatrick static Value *foldIdentityShuffles(int DestElt, Value *Op0, Value *Op1,
510309467b48Spatrick                                    int MaskVal, Value *RootVec,
510409467b48Spatrick                                    unsigned MaxRecurse) {
510509467b48Spatrick   if (!MaxRecurse--)
510609467b48Spatrick     return nullptr;
510709467b48Spatrick 
510809467b48Spatrick   // Bail out if any mask value is undefined. That kind of shuffle may be
510909467b48Spatrick   // simplified further based on demanded bits or other folds.
511009467b48Spatrick   if (MaskVal == -1)
511109467b48Spatrick     return nullptr;
511209467b48Spatrick 
511309467b48Spatrick   // The mask value chooses which source operand we need to look at next.
511473471bf0Spatrick   int InVecNumElts = cast<FixedVectorType>(Op0->getType())->getNumElements();
511509467b48Spatrick   int RootElt = MaskVal;
511609467b48Spatrick   Value *SourceOp = Op0;
511709467b48Spatrick   if (MaskVal >= InVecNumElts) {
511809467b48Spatrick     RootElt = MaskVal - InVecNumElts;
511909467b48Spatrick     SourceOp = Op1;
512009467b48Spatrick   }
512109467b48Spatrick 
512209467b48Spatrick   // If the source operand is a shuffle itself, look through it to find the
512309467b48Spatrick   // matching root vector.
512409467b48Spatrick   if (auto *SourceShuf = dyn_cast<ShuffleVectorInst>(SourceOp)) {
512509467b48Spatrick     return foldIdentityShuffles(
512609467b48Spatrick         DestElt, SourceShuf->getOperand(0), SourceShuf->getOperand(1),
512709467b48Spatrick         SourceShuf->getMaskValue(RootElt), RootVec, MaxRecurse);
512809467b48Spatrick   }
512909467b48Spatrick 
513009467b48Spatrick   // TODO: Look through bitcasts? What if the bitcast changes the vector element
513109467b48Spatrick   // size?
513209467b48Spatrick 
513309467b48Spatrick   // The source operand is not a shuffle. Initialize the root vector value for
513409467b48Spatrick   // this shuffle if that has not been done yet.
513509467b48Spatrick   if (!RootVec)
513609467b48Spatrick     RootVec = SourceOp;
513709467b48Spatrick 
513809467b48Spatrick   // Give up as soon as a source operand does not match the existing root value.
513909467b48Spatrick   if (RootVec != SourceOp)
514009467b48Spatrick     return nullptr;
514109467b48Spatrick 
514209467b48Spatrick   // The element must be coming from the same lane in the source vector
514309467b48Spatrick   // (although it may have crossed lanes in intermediate shuffles).
514409467b48Spatrick   if (RootElt != DestElt)
514509467b48Spatrick     return nullptr;
514609467b48Spatrick 
514709467b48Spatrick   return RootVec;
514809467b48Spatrick }
514909467b48Spatrick 
simplifyShuffleVectorInst(Value * Op0,Value * Op1,ArrayRef<int> Mask,Type * RetTy,const SimplifyQuery & Q,unsigned MaxRecurse)5150*d415bd75Srobert static Value *simplifyShuffleVectorInst(Value *Op0, Value *Op1,
5151097a140dSpatrick                                         ArrayRef<int> Mask, Type *RetTy,
5152097a140dSpatrick                                         const SimplifyQuery &Q,
515309467b48Spatrick                                         unsigned MaxRecurse) {
5154097a140dSpatrick   if (all_of(Mask, [](int Elem) { return Elem == UndefMaskElem; }))
515509467b48Spatrick     return UndefValue::get(RetTy);
515609467b48Spatrick 
5157097a140dSpatrick   auto *InVecTy = cast<VectorType>(Op0->getType());
5158097a140dSpatrick   unsigned MaskNumElts = Mask.size();
5159097a140dSpatrick   ElementCount InVecEltCount = InVecTy->getElementCount();
5160097a140dSpatrick 
516173471bf0Spatrick   bool Scalable = InVecEltCount.isScalable();
516209467b48Spatrick 
516309467b48Spatrick   SmallVector<int, 32> Indices;
5164097a140dSpatrick   Indices.assign(Mask.begin(), Mask.end());
516509467b48Spatrick 
516609467b48Spatrick   // Canonicalization: If mask does not select elements from an input vector,
516773471bf0Spatrick   // replace that input vector with poison.
5168097a140dSpatrick   if (!Scalable) {
516909467b48Spatrick     bool MaskSelects0 = false, MaskSelects1 = false;
517073471bf0Spatrick     unsigned InVecNumElts = InVecEltCount.getKnownMinValue();
517109467b48Spatrick     for (unsigned i = 0; i != MaskNumElts; ++i) {
517209467b48Spatrick       if (Indices[i] == -1)
517309467b48Spatrick         continue;
517409467b48Spatrick       if ((unsigned)Indices[i] < InVecNumElts)
517509467b48Spatrick         MaskSelects0 = true;
517609467b48Spatrick       else
517709467b48Spatrick         MaskSelects1 = true;
517809467b48Spatrick     }
517909467b48Spatrick     if (!MaskSelects0)
518073471bf0Spatrick       Op0 = PoisonValue::get(InVecTy);
518109467b48Spatrick     if (!MaskSelects1)
518273471bf0Spatrick       Op1 = PoisonValue::get(InVecTy);
5183097a140dSpatrick   }
518409467b48Spatrick 
518509467b48Spatrick   auto *Op0Const = dyn_cast<Constant>(Op0);
518609467b48Spatrick   auto *Op1Const = dyn_cast<Constant>(Op1);
518709467b48Spatrick 
5188097a140dSpatrick   // If all operands are constant, constant fold the shuffle. This
5189097a140dSpatrick   // transformation depends on the value of the mask which is not known at
5190097a140dSpatrick   // compile time for scalable vectors
519173471bf0Spatrick   if (Op0Const && Op1Const)
519273471bf0Spatrick     return ConstantExpr::getShuffleVector(Op0Const, Op1Const, Mask);
519309467b48Spatrick 
519409467b48Spatrick   // Canonicalization: if only one input vector is constant, it shall be the
5195097a140dSpatrick   // second one. This transformation depends on the value of the mask which
5196097a140dSpatrick   // is not known at compile time for scalable vectors
5197097a140dSpatrick   if (!Scalable && Op0Const && !Op1Const) {
519809467b48Spatrick     std::swap(Op0, Op1);
519973471bf0Spatrick     ShuffleVectorInst::commuteShuffleMask(Indices,
520073471bf0Spatrick                                           InVecEltCount.getKnownMinValue());
520109467b48Spatrick   }
520209467b48Spatrick 
520309467b48Spatrick   // A splat of an inserted scalar constant becomes a vector constant:
520409467b48Spatrick   // shuf (inselt ?, C, IndexC), undef, <IndexC, IndexC...> --> <C, C...>
520509467b48Spatrick   // NOTE: We may have commuted above, so analyze the updated Indices, not the
520609467b48Spatrick   //       original mask constant.
5207097a140dSpatrick   // NOTE: This transformation depends on the value of the mask which is not
5208097a140dSpatrick   // known at compile time for scalable vectors
520909467b48Spatrick   Constant *C;
521009467b48Spatrick   ConstantInt *IndexC;
5211097a140dSpatrick   if (!Scalable && match(Op0, m_InsertElt(m_Value(), m_Constant(C),
521209467b48Spatrick                                           m_ConstantInt(IndexC)))) {
521309467b48Spatrick     // Match a splat shuffle mask of the insert index allowing undef elements.
521409467b48Spatrick     int InsertIndex = IndexC->getZExtValue();
521509467b48Spatrick     if (all_of(Indices, [InsertIndex](int MaskElt) {
521609467b48Spatrick           return MaskElt == InsertIndex || MaskElt == -1;
521709467b48Spatrick         })) {
521809467b48Spatrick       assert(isa<UndefValue>(Op1) && "Expected undef operand 1 for splat");
521909467b48Spatrick 
522009467b48Spatrick       // Shuffle mask undefs become undefined constant result elements.
522109467b48Spatrick       SmallVector<Constant *, 16> VecC(MaskNumElts, C);
522209467b48Spatrick       for (unsigned i = 0; i != MaskNumElts; ++i)
522309467b48Spatrick         if (Indices[i] == -1)
522409467b48Spatrick           VecC[i] = UndefValue::get(C->getType());
522509467b48Spatrick       return ConstantVector::get(VecC);
522609467b48Spatrick     }
522709467b48Spatrick   }
522809467b48Spatrick 
522909467b48Spatrick   // A shuffle of a splat is always the splat itself. Legal if the shuffle's
523009467b48Spatrick   // value type is same as the input vectors' type.
523109467b48Spatrick   if (auto *OpShuf = dyn_cast<ShuffleVectorInst>(Op0))
523273471bf0Spatrick     if (Q.isUndefValue(Op1) && RetTy == InVecTy &&
5233*d415bd75Srobert         all_equal(OpShuf->getShuffleMask()))
523409467b48Spatrick       return Op0;
523509467b48Spatrick 
5236097a140dSpatrick   // All remaining transformation depend on the value of the mask, which is
5237097a140dSpatrick   // not known at compile time for scalable vectors.
5238097a140dSpatrick   if (Scalable)
5239097a140dSpatrick     return nullptr;
5240097a140dSpatrick 
524109467b48Spatrick   // Don't fold a shuffle with undef mask elements. This may get folded in a
524209467b48Spatrick   // better way using demanded bits or other analysis.
524309467b48Spatrick   // TODO: Should we allow this?
524473471bf0Spatrick   if (is_contained(Indices, -1))
524509467b48Spatrick     return nullptr;
524609467b48Spatrick 
524709467b48Spatrick   // Check if every element of this shuffle can be mapped back to the
524809467b48Spatrick   // corresponding element of a single root vector. If so, we don't need this
524909467b48Spatrick   // shuffle. This handles simple identity shuffles as well as chains of
525009467b48Spatrick   // shuffles that may widen/narrow and/or move elements across lanes and back.
525109467b48Spatrick   Value *RootVec = nullptr;
525209467b48Spatrick   for (unsigned i = 0; i != MaskNumElts; ++i) {
525309467b48Spatrick     // Note that recursion is limited for each vector element, so if any element
525409467b48Spatrick     // exceeds the limit, this will fail to simplify.
525509467b48Spatrick     RootVec =
525609467b48Spatrick         foldIdentityShuffles(i, Op0, Op1, Indices[i], RootVec, MaxRecurse);
525709467b48Spatrick 
525809467b48Spatrick     // We can't replace a widening/narrowing shuffle with one of its operands.
525909467b48Spatrick     if (!RootVec || RootVec->getType() != RetTy)
526009467b48Spatrick       return nullptr;
526109467b48Spatrick   }
526209467b48Spatrick   return RootVec;
526309467b48Spatrick }
526409467b48Spatrick 
526509467b48Spatrick /// Given operands for a ShuffleVectorInst, fold the result or return null.
simplifyShuffleVectorInst(Value * Op0,Value * Op1,ArrayRef<int> Mask,Type * RetTy,const SimplifyQuery & Q)5266*d415bd75Srobert Value *llvm::simplifyShuffleVectorInst(Value *Op0, Value *Op1,
5267097a140dSpatrick                                        ArrayRef<int> Mask, Type *RetTy,
5268097a140dSpatrick                                        const SimplifyQuery &Q) {
5269*d415bd75Srobert   return ::simplifyShuffleVectorInst(Op0, Op1, Mask, RetTy, Q, RecursionLimit);
527009467b48Spatrick }
527109467b48Spatrick 
foldConstant(Instruction::UnaryOps Opcode,Value * & Op,const SimplifyQuery & Q)5272*d415bd75Srobert static Constant *foldConstant(Instruction::UnaryOps Opcode, Value *&Op,
5273*d415bd75Srobert                               const SimplifyQuery &Q) {
527409467b48Spatrick   if (auto *C = dyn_cast<Constant>(Op))
527509467b48Spatrick     return ConstantFoldUnaryOpOperand(Opcode, C, Q.DL);
527609467b48Spatrick   return nullptr;
527709467b48Spatrick }
527809467b48Spatrick 
527909467b48Spatrick /// Given the operand for an FNeg, see if we can fold the result.  If not, this
528009467b48Spatrick /// returns null.
simplifyFNegInst(Value * Op,FastMathFlags FMF,const SimplifyQuery & Q,unsigned MaxRecurse)528109467b48Spatrick static Value *simplifyFNegInst(Value *Op, FastMathFlags FMF,
528209467b48Spatrick                                const SimplifyQuery &Q, unsigned MaxRecurse) {
528309467b48Spatrick   if (Constant *C = foldConstant(Instruction::FNeg, Op, Q))
528409467b48Spatrick     return C;
528509467b48Spatrick 
528609467b48Spatrick   Value *X;
528709467b48Spatrick   // fneg (fneg X) ==> X
528809467b48Spatrick   if (match(Op, m_FNeg(m_Value(X))))
528909467b48Spatrick     return X;
529009467b48Spatrick 
529109467b48Spatrick   return nullptr;
529209467b48Spatrick }
529309467b48Spatrick 
simplifyFNegInst(Value * Op,FastMathFlags FMF,const SimplifyQuery & Q)5294*d415bd75Srobert Value *llvm::simplifyFNegInst(Value *Op, FastMathFlags FMF,
529509467b48Spatrick                               const SimplifyQuery &Q) {
529609467b48Spatrick   return ::simplifyFNegInst(Op, FMF, Q, RecursionLimit);
529709467b48Spatrick }
529809467b48Spatrick 
5299*d415bd75Srobert /// Try to propagate existing NaN values when possible. If not, replace the
5300*d415bd75Srobert /// constant or elements in the constant with a canonical NaN.
propagateNaN(Constant * In)530109467b48Spatrick static Constant *propagateNaN(Constant *In) {
5302*d415bd75Srobert   if (auto *VecTy = dyn_cast<FixedVectorType>(In->getType())) {
5303*d415bd75Srobert     unsigned NumElts = VecTy->getNumElements();
5304*d415bd75Srobert     SmallVector<Constant *, 32> NewC(NumElts);
5305*d415bd75Srobert     for (unsigned i = 0; i != NumElts; ++i) {
5306*d415bd75Srobert       Constant *EltC = In->getAggregateElement(i);
5307*d415bd75Srobert       // Poison and existing NaN elements propagate.
5308*d415bd75Srobert       // Replace unknown or undef elements with canonical NaN.
5309*d415bd75Srobert       if (EltC && (isa<PoisonValue>(EltC) || EltC->isNaN()))
5310*d415bd75Srobert         NewC[i] = EltC;
5311*d415bd75Srobert       else
5312*d415bd75Srobert         NewC[i] = (ConstantFP::getNaN(VecTy->getElementType()));
5313*d415bd75Srobert     }
5314*d415bd75Srobert     return ConstantVector::get(NewC);
5315*d415bd75Srobert   }
5316*d415bd75Srobert 
5317*d415bd75Srobert   // It is not a fixed vector, but not a simple NaN either?
531809467b48Spatrick   if (!In->isNaN())
531909467b48Spatrick     return ConstantFP::getNaN(In->getType());
532009467b48Spatrick 
532109467b48Spatrick   // Propagate the existing NaN constant when possible.
532209467b48Spatrick   // TODO: Should we quiet a signaling NaN?
532309467b48Spatrick   return In;
532409467b48Spatrick }
532509467b48Spatrick 
532609467b48Spatrick /// Perform folds that are common to any floating-point operation. This implies
532773471bf0Spatrick /// transforms based on poison/undef/NaN because the operation itself makes no
532809467b48Spatrick /// difference to the result.
simplifyFPOp(ArrayRef<Value * > Ops,FastMathFlags FMF,const SimplifyQuery & Q,fp::ExceptionBehavior ExBehavior,RoundingMode Rounding)532973471bf0Spatrick static Constant *simplifyFPOp(ArrayRef<Value *> Ops, FastMathFlags FMF,
533073471bf0Spatrick                               const SimplifyQuery &Q,
533173471bf0Spatrick                               fp::ExceptionBehavior ExBehavior,
533273471bf0Spatrick                               RoundingMode Rounding) {
533373471bf0Spatrick   // Poison is independent of anything else. It always propagates from an
533473471bf0Spatrick   // operand to a math result.
533573471bf0Spatrick   if (any_of(Ops, [](Value *V) { return match(V, m_Poison()); }))
533673471bf0Spatrick     return PoisonValue::get(Ops[0]->getType());
533773471bf0Spatrick 
5338097a140dSpatrick   for (Value *V : Ops) {
5339097a140dSpatrick     bool IsNan = match(V, m_NaN());
5340097a140dSpatrick     bool IsInf = match(V, m_Inf());
534173471bf0Spatrick     bool IsUndef = Q.isUndefValue(V);
534209467b48Spatrick 
5343097a140dSpatrick     // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
5344097a140dSpatrick     // (an undef operand can be chosen to be Nan/Inf), then the result of
534573471bf0Spatrick     // this operation is poison.
5346097a140dSpatrick     if (FMF.noNaNs() && (IsNan || IsUndef))
534773471bf0Spatrick       return PoisonValue::get(V->getType());
5348097a140dSpatrick     if (FMF.noInfs() && (IsInf || IsUndef))
534973471bf0Spatrick       return PoisonValue::get(V->getType());
5350097a140dSpatrick 
535173471bf0Spatrick     if (isDefaultFPEnvironment(ExBehavior, Rounding)) {
5352*d415bd75Srobert       // Undef does not propagate because undef means that all bits can take on
5353*d415bd75Srobert       // any value. If this is undef * NaN for example, then the result values
5354*d415bd75Srobert       // (at least the exponent bits) are limited. Assume the undef is a
5355*d415bd75Srobert       // canonical NaN and propagate that.
5356*d415bd75Srobert       if (IsUndef)
5357*d415bd75Srobert         return ConstantFP::getNaN(V->getType());
5358*d415bd75Srobert       if (IsNan)
535909467b48Spatrick         return propagateNaN(cast<Constant>(V));
536073471bf0Spatrick     } else if (ExBehavior != fp::ebStrict) {
536173471bf0Spatrick       if (IsNan)
536273471bf0Spatrick         return propagateNaN(cast<Constant>(V));
536373471bf0Spatrick     }
5364097a140dSpatrick   }
536509467b48Spatrick   return nullptr;
536609467b48Spatrick }
536709467b48Spatrick 
536809467b48Spatrick /// Given operands for an FAdd, see if we can fold the result.  If not, this
536909467b48Spatrick /// returns null.
537073471bf0Spatrick static Value *
simplifyFAddInst(Value * Op0,Value * Op1,FastMathFlags FMF,const SimplifyQuery & Q,unsigned MaxRecurse,fp::ExceptionBehavior ExBehavior=fp::ebIgnore,RoundingMode Rounding=RoundingMode::NearestTiesToEven)5371*d415bd75Srobert simplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
537273471bf0Spatrick                  const SimplifyQuery &Q, unsigned MaxRecurse,
537373471bf0Spatrick                  fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
537473471bf0Spatrick                  RoundingMode Rounding = RoundingMode::NearestTiesToEven) {
537573471bf0Spatrick   if (isDefaultFPEnvironment(ExBehavior, Rounding))
537609467b48Spatrick     if (Constant *C = foldOrCommuteConstant(Instruction::FAdd, Op0, Op1, Q))
537709467b48Spatrick       return C;
537809467b48Spatrick 
537973471bf0Spatrick   if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding))
538009467b48Spatrick     return C;
538109467b48Spatrick 
538209467b48Spatrick   // fadd X, -0 ==> X
5383*d415bd75Srobert   // With strict/constrained FP, we have these possible edge cases that do
5384*d415bd75Srobert   // not simplify to Op0:
5385*d415bd75Srobert   // fadd SNaN, -0.0 --> QNaN
5386*d415bd75Srobert   // fadd +0.0, -0.0 --> -0.0 (but only with round toward negative)
5387*d415bd75Srobert   if (canIgnoreSNaN(ExBehavior, FMF) &&
5388*d415bd75Srobert       (!canRoundingModeBe(Rounding, RoundingMode::TowardNegative) ||
5389*d415bd75Srobert        FMF.noSignedZeros()))
539009467b48Spatrick     if (match(Op1, m_NegZeroFP()))
539109467b48Spatrick       return Op0;
539209467b48Spatrick 
539309467b48Spatrick   // fadd X, 0 ==> X, when we know X is not -0
5394*d415bd75Srobert   if (canIgnoreSNaN(ExBehavior, FMF))
539509467b48Spatrick     if (match(Op1, m_PosZeroFP()) &&
539609467b48Spatrick         (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
539709467b48Spatrick       return Op0;
539809467b48Spatrick 
5399*d415bd75Srobert   if (!isDefaultFPEnvironment(ExBehavior, Rounding))
5400*d415bd75Srobert     return nullptr;
5401*d415bd75Srobert 
5402*d415bd75Srobert   if (FMF.noNaNs()) {
5403*d415bd75Srobert     // With nnan: X + {+/-}Inf --> {+/-}Inf
5404*d415bd75Srobert     if (match(Op1, m_Inf()))
5405*d415bd75Srobert       return Op1;
5406*d415bd75Srobert 
540709467b48Spatrick     // With nnan: -X + X --> 0.0 (and commuted variant)
540809467b48Spatrick     // We don't have to explicitly exclude infinities (ninf): INF + -INF == NaN.
540909467b48Spatrick     // Negative zeros are allowed because we always end up with positive zero:
541009467b48Spatrick     // X = -0.0: (-0.0 - (-0.0)) + (-0.0) == ( 0.0) + (-0.0) == 0.0
541109467b48Spatrick     // X = -0.0: ( 0.0 - (-0.0)) + (-0.0) == ( 0.0) + (-0.0) == 0.0
541209467b48Spatrick     // X =  0.0: (-0.0 - ( 0.0)) + ( 0.0) == (-0.0) + ( 0.0) == 0.0
541309467b48Spatrick     // X =  0.0: ( 0.0 - ( 0.0)) + ( 0.0) == ( 0.0) + ( 0.0) == 0.0
541409467b48Spatrick     if (match(Op0, m_FSub(m_AnyZeroFP(), m_Specific(Op1))) ||
541509467b48Spatrick         match(Op1, m_FSub(m_AnyZeroFP(), m_Specific(Op0))))
541609467b48Spatrick       return ConstantFP::getNullValue(Op0->getType());
541709467b48Spatrick 
541809467b48Spatrick     if (match(Op0, m_FNeg(m_Specific(Op1))) ||
541909467b48Spatrick         match(Op1, m_FNeg(m_Specific(Op0))))
542009467b48Spatrick       return ConstantFP::getNullValue(Op0->getType());
542109467b48Spatrick   }
542209467b48Spatrick 
542309467b48Spatrick   // (X - Y) + Y --> X
542409467b48Spatrick   // Y + (X - Y) --> X
542509467b48Spatrick   Value *X;
542609467b48Spatrick   if (FMF.noSignedZeros() && FMF.allowReassoc() &&
542709467b48Spatrick       (match(Op0, m_FSub(m_Value(X), m_Specific(Op1))) ||
542809467b48Spatrick        match(Op1, m_FSub(m_Value(X), m_Specific(Op0)))))
542909467b48Spatrick     return X;
543009467b48Spatrick 
543109467b48Spatrick   return nullptr;
543209467b48Spatrick }
543309467b48Spatrick 
543409467b48Spatrick /// Given operands for an FSub, see if we can fold the result.  If not, this
543509467b48Spatrick /// returns null.
543673471bf0Spatrick static Value *
simplifyFSubInst(Value * Op0,Value * Op1,FastMathFlags FMF,const SimplifyQuery & Q,unsigned MaxRecurse,fp::ExceptionBehavior ExBehavior=fp::ebIgnore,RoundingMode Rounding=RoundingMode::NearestTiesToEven)5437*d415bd75Srobert simplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
543873471bf0Spatrick                  const SimplifyQuery &Q, unsigned MaxRecurse,
543973471bf0Spatrick                  fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
544073471bf0Spatrick                  RoundingMode Rounding = RoundingMode::NearestTiesToEven) {
544173471bf0Spatrick   if (isDefaultFPEnvironment(ExBehavior, Rounding))
544209467b48Spatrick     if (Constant *C = foldOrCommuteConstant(Instruction::FSub, Op0, Op1, Q))
544309467b48Spatrick       return C;
544409467b48Spatrick 
544573471bf0Spatrick   if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding))
544609467b48Spatrick     return C;
544709467b48Spatrick 
544809467b48Spatrick   // fsub X, +0 ==> X
5449*d415bd75Srobert   if (canIgnoreSNaN(ExBehavior, FMF) &&
5450*d415bd75Srobert       (!canRoundingModeBe(Rounding, RoundingMode::TowardNegative) ||
5451*d415bd75Srobert        FMF.noSignedZeros()))
545209467b48Spatrick     if (match(Op1, m_PosZeroFP()))
545309467b48Spatrick       return Op0;
545409467b48Spatrick 
545509467b48Spatrick   // fsub X, -0 ==> X, when we know X is not -0
5456*d415bd75Srobert   if (canIgnoreSNaN(ExBehavior, FMF))
545709467b48Spatrick     if (match(Op1, m_NegZeroFP()) &&
545809467b48Spatrick         (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
545909467b48Spatrick       return Op0;
546009467b48Spatrick 
546109467b48Spatrick   // fsub -0.0, (fsub -0.0, X) ==> X
546209467b48Spatrick   // fsub -0.0, (fneg X) ==> X
546309467b48Spatrick   Value *X;
5464*d415bd75Srobert   if (canIgnoreSNaN(ExBehavior, FMF))
5465*d415bd75Srobert     if (match(Op0, m_NegZeroFP()) && match(Op1, m_FNeg(m_Value(X))))
546609467b48Spatrick       return X;
546709467b48Spatrick 
546809467b48Spatrick   // fsub 0.0, (fsub 0.0, X) ==> X if signed zeros are ignored.
546909467b48Spatrick   // fsub 0.0, (fneg X) ==> X if signed zeros are ignored.
5470*d415bd75Srobert   if (canIgnoreSNaN(ExBehavior, FMF))
547109467b48Spatrick     if (FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()) &&
547209467b48Spatrick         (match(Op1, m_FSub(m_AnyZeroFP(), m_Value(X))) ||
547309467b48Spatrick          match(Op1, m_FNeg(m_Value(X)))))
547409467b48Spatrick       return X;
547509467b48Spatrick 
5476*d415bd75Srobert   if (!isDefaultFPEnvironment(ExBehavior, Rounding))
5477*d415bd75Srobert     return nullptr;
5478*d415bd75Srobert 
5479*d415bd75Srobert   if (FMF.noNaNs()) {
548009467b48Spatrick     // fsub nnan x, x ==> 0.0
5481*d415bd75Srobert     if (Op0 == Op1)
548209467b48Spatrick       return Constant::getNullValue(Op0->getType());
548309467b48Spatrick 
5484*d415bd75Srobert     // With nnan: {+/-}Inf - X --> {+/-}Inf
5485*d415bd75Srobert     if (match(Op0, m_Inf()))
5486*d415bd75Srobert       return Op0;
5487*d415bd75Srobert 
5488*d415bd75Srobert     // With nnan: X - {+/-}Inf --> {-/+}Inf
5489*d415bd75Srobert     if (match(Op1, m_Inf()))
5490*d415bd75Srobert       return foldConstant(Instruction::FNeg, Op1, Q);
5491*d415bd75Srobert   }
5492*d415bd75Srobert 
549309467b48Spatrick   // Y - (Y - X) --> X
549409467b48Spatrick   // (X + Y) - Y --> X
549509467b48Spatrick   if (FMF.noSignedZeros() && FMF.allowReassoc() &&
549609467b48Spatrick       (match(Op1, m_FSub(m_Specific(Op0), m_Value(X))) ||
549709467b48Spatrick        match(Op0, m_c_FAdd(m_Specific(Op1), m_Value(X)))))
549809467b48Spatrick     return X;
549909467b48Spatrick 
550009467b48Spatrick   return nullptr;
550109467b48Spatrick }
550209467b48Spatrick 
simplifyFMAFMul(Value * Op0,Value * Op1,FastMathFlags FMF,const SimplifyQuery & Q,unsigned MaxRecurse,fp::ExceptionBehavior ExBehavior,RoundingMode Rounding)5503*d415bd75Srobert static Value *simplifyFMAFMul(Value *Op0, Value *Op1, FastMathFlags FMF,
550473471bf0Spatrick                               const SimplifyQuery &Q, unsigned MaxRecurse,
550573471bf0Spatrick                               fp::ExceptionBehavior ExBehavior,
550673471bf0Spatrick                               RoundingMode Rounding) {
550773471bf0Spatrick   if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding))
550809467b48Spatrick     return C;
550909467b48Spatrick 
551073471bf0Spatrick   if (!isDefaultFPEnvironment(ExBehavior, Rounding))
551173471bf0Spatrick     return nullptr;
551273471bf0Spatrick 
5513*d415bd75Srobert   // Canonicalize special constants as operand 1.
5514*d415bd75Srobert   if (match(Op0, m_FPOne()) || match(Op0, m_AnyZeroFP()))
5515*d415bd75Srobert     std::swap(Op0, Op1);
5516*d415bd75Srobert 
5517*d415bd75Srobert   // X * 1.0 --> X
551809467b48Spatrick   if (match(Op1, m_FPOne()))
551909467b48Spatrick     return Op0;
552009467b48Spatrick 
5521*d415bd75Srobert   if (match(Op1, m_AnyZeroFP())) {
5522*d415bd75Srobert     // X * 0.0 --> 0.0 (with nnan and nsz)
5523*d415bd75Srobert     if (FMF.noNaNs() && FMF.noSignedZeros())
552409467b48Spatrick       return ConstantFP::getNullValue(Op0->getType());
552509467b48Spatrick 
5526*d415bd75Srobert     // +normal number * (-)0.0 --> (-)0.0
5527*d415bd75Srobert     if (isKnownNeverInfinity(Op0, Q.TLI) && isKnownNeverNaN(Op0, Q.TLI) &&
5528*d415bd75Srobert         SignBitMustBeZero(Op0, Q.TLI))
5529*d415bd75Srobert       return Op1;
5530*d415bd75Srobert   }
553109467b48Spatrick 
553209467b48Spatrick   // sqrt(X) * sqrt(X) --> X, if we can:
553309467b48Spatrick   // 1. Remove the intermediate rounding (reassociate).
553409467b48Spatrick   // 2. Ignore non-zero negative numbers because sqrt would produce NAN.
553509467b48Spatrick   // 3. Ignore -0.0 because sqrt(-0.0) == -0.0, but -0.0 * -0.0 == 0.0.
553609467b48Spatrick   Value *X;
5537*d415bd75Srobert   if (Op0 == Op1 && match(Op0, m_Sqrt(m_Value(X))) && FMF.allowReassoc() &&
5538*d415bd75Srobert       FMF.noNaNs() && FMF.noSignedZeros())
553909467b48Spatrick     return X;
554009467b48Spatrick 
554109467b48Spatrick   return nullptr;
554209467b48Spatrick }
554309467b48Spatrick 
554409467b48Spatrick /// Given the operands for an FMul, see if we can fold the result
554573471bf0Spatrick static Value *
simplifyFMulInst(Value * Op0,Value * Op1,FastMathFlags FMF,const SimplifyQuery & Q,unsigned MaxRecurse,fp::ExceptionBehavior ExBehavior=fp::ebIgnore,RoundingMode Rounding=RoundingMode::NearestTiesToEven)5546*d415bd75Srobert simplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
554773471bf0Spatrick                  const SimplifyQuery &Q, unsigned MaxRecurse,
554873471bf0Spatrick                  fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
554973471bf0Spatrick                  RoundingMode Rounding = RoundingMode::NearestTiesToEven) {
555073471bf0Spatrick   if (isDefaultFPEnvironment(ExBehavior, Rounding))
555109467b48Spatrick     if (Constant *C = foldOrCommuteConstant(Instruction::FMul, Op0, Op1, Q))
555209467b48Spatrick       return C;
555309467b48Spatrick 
555409467b48Spatrick   // Now apply simplifications that do not require rounding.
5555*d415bd75Srobert   return simplifyFMAFMul(Op0, Op1, FMF, Q, MaxRecurse, ExBehavior, Rounding);
555609467b48Spatrick }
555709467b48Spatrick 
simplifyFAddInst(Value * Op0,Value * Op1,FastMathFlags FMF,const SimplifyQuery & Q,fp::ExceptionBehavior ExBehavior,RoundingMode Rounding)5558*d415bd75Srobert Value *llvm::simplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
555973471bf0Spatrick                               const SimplifyQuery &Q,
556073471bf0Spatrick                               fp::ExceptionBehavior ExBehavior,
556173471bf0Spatrick                               RoundingMode Rounding) {
5562*d415bd75Srobert   return ::simplifyFAddInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
556373471bf0Spatrick                             Rounding);
556409467b48Spatrick }
556509467b48Spatrick 
simplifyFSubInst(Value * Op0,Value * Op1,FastMathFlags FMF,const SimplifyQuery & Q,fp::ExceptionBehavior ExBehavior,RoundingMode Rounding)5566*d415bd75Srobert Value *llvm::simplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
556773471bf0Spatrick                               const SimplifyQuery &Q,
556873471bf0Spatrick                               fp::ExceptionBehavior ExBehavior,
556973471bf0Spatrick                               RoundingMode Rounding) {
5570*d415bd75Srobert   return ::simplifyFSubInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
557173471bf0Spatrick                             Rounding);
557209467b48Spatrick }
557309467b48Spatrick 
simplifyFMulInst(Value * Op0,Value * Op1,FastMathFlags FMF,const SimplifyQuery & Q,fp::ExceptionBehavior ExBehavior,RoundingMode Rounding)5574*d415bd75Srobert Value *llvm::simplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
557573471bf0Spatrick                               const SimplifyQuery &Q,
557673471bf0Spatrick                               fp::ExceptionBehavior ExBehavior,
557773471bf0Spatrick                               RoundingMode Rounding) {
5578*d415bd75Srobert   return ::simplifyFMulInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
557973471bf0Spatrick                             Rounding);
558009467b48Spatrick }
558109467b48Spatrick 
simplifyFMAFMul(Value * Op0,Value * Op1,FastMathFlags FMF,const SimplifyQuery & Q,fp::ExceptionBehavior ExBehavior,RoundingMode Rounding)5582*d415bd75Srobert Value *llvm::simplifyFMAFMul(Value *Op0, Value *Op1, FastMathFlags FMF,
558373471bf0Spatrick                              const SimplifyQuery &Q,
558473471bf0Spatrick                              fp::ExceptionBehavior ExBehavior,
558573471bf0Spatrick                              RoundingMode Rounding) {
5586*d415bd75Srobert   return ::simplifyFMAFMul(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
558773471bf0Spatrick                            Rounding);
558809467b48Spatrick }
558909467b48Spatrick 
559073471bf0Spatrick static Value *
simplifyFDivInst(Value * Op0,Value * Op1,FastMathFlags FMF,const SimplifyQuery & Q,unsigned,fp::ExceptionBehavior ExBehavior=fp::ebIgnore,RoundingMode Rounding=RoundingMode::NearestTiesToEven)5591*d415bd75Srobert simplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
559273471bf0Spatrick                  const SimplifyQuery &Q, unsigned,
559373471bf0Spatrick                  fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
559473471bf0Spatrick                  RoundingMode Rounding = RoundingMode::NearestTiesToEven) {
559573471bf0Spatrick   if (isDefaultFPEnvironment(ExBehavior, Rounding))
559609467b48Spatrick     if (Constant *C = foldOrCommuteConstant(Instruction::FDiv, Op0, Op1, Q))
559709467b48Spatrick       return C;
559809467b48Spatrick 
559973471bf0Spatrick   if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding))
560009467b48Spatrick     return C;
560109467b48Spatrick 
560273471bf0Spatrick   if (!isDefaultFPEnvironment(ExBehavior, Rounding))
560373471bf0Spatrick     return nullptr;
560473471bf0Spatrick 
560509467b48Spatrick   // X / 1.0 -> X
560609467b48Spatrick   if (match(Op1, m_FPOne()))
560709467b48Spatrick     return Op0;
560809467b48Spatrick 
560909467b48Spatrick   // 0 / X -> 0
561009467b48Spatrick   // Requires that NaNs are off (X could be zero) and signed zeroes are
561109467b48Spatrick   // ignored (X could be positive or negative, so the output sign is unknown).
561209467b48Spatrick   if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()))
561309467b48Spatrick     return ConstantFP::getNullValue(Op0->getType());
561409467b48Spatrick 
561509467b48Spatrick   if (FMF.noNaNs()) {
561609467b48Spatrick     // X / X -> 1.0 is legal when NaNs are ignored.
561709467b48Spatrick     // We can ignore infinities because INF/INF is NaN.
561809467b48Spatrick     if (Op0 == Op1)
561909467b48Spatrick       return ConstantFP::get(Op0->getType(), 1.0);
562009467b48Spatrick 
562109467b48Spatrick     // (X * Y) / Y --> X if we can reassociate to the above form.
562209467b48Spatrick     Value *X;
562309467b48Spatrick     if (FMF.allowReassoc() && match(Op0, m_c_FMul(m_Value(X), m_Specific(Op1))))
562409467b48Spatrick       return X;
562509467b48Spatrick 
562609467b48Spatrick     // -X /  X -> -1.0 and
562709467b48Spatrick     //  X / -X -> -1.0 are legal when NaNs are ignored.
562809467b48Spatrick     // We can ignore signed zeros because +-0.0/+-0.0 is NaN and ignored.
562909467b48Spatrick     if (match(Op0, m_FNegNSZ(m_Specific(Op1))) ||
563009467b48Spatrick         match(Op1, m_FNegNSZ(m_Specific(Op0))))
563109467b48Spatrick       return ConstantFP::get(Op0->getType(), -1.0);
5632*d415bd75Srobert 
5633*d415bd75Srobert     // nnan ninf X / [-]0.0 -> poison
5634*d415bd75Srobert     if (FMF.noInfs() && match(Op1, m_AnyZeroFP()))
5635*d415bd75Srobert       return PoisonValue::get(Op1->getType());
563609467b48Spatrick   }
563709467b48Spatrick 
563809467b48Spatrick   return nullptr;
563909467b48Spatrick }
564009467b48Spatrick 
simplifyFDivInst(Value * Op0,Value * Op1,FastMathFlags FMF,const SimplifyQuery & Q,fp::ExceptionBehavior ExBehavior,RoundingMode Rounding)5641*d415bd75Srobert Value *llvm::simplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
564273471bf0Spatrick                               const SimplifyQuery &Q,
564373471bf0Spatrick                               fp::ExceptionBehavior ExBehavior,
564473471bf0Spatrick                               RoundingMode Rounding) {
5645*d415bd75Srobert   return ::simplifyFDivInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
564673471bf0Spatrick                             Rounding);
564709467b48Spatrick }
564809467b48Spatrick 
564973471bf0Spatrick static Value *
simplifyFRemInst(Value * Op0,Value * Op1,FastMathFlags FMF,const SimplifyQuery & Q,unsigned,fp::ExceptionBehavior ExBehavior=fp::ebIgnore,RoundingMode Rounding=RoundingMode::NearestTiesToEven)5650*d415bd75Srobert simplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
565173471bf0Spatrick                  const SimplifyQuery &Q, unsigned,
565273471bf0Spatrick                  fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
565373471bf0Spatrick                  RoundingMode Rounding = RoundingMode::NearestTiesToEven) {
565473471bf0Spatrick   if (isDefaultFPEnvironment(ExBehavior, Rounding))
565509467b48Spatrick     if (Constant *C = foldOrCommuteConstant(Instruction::FRem, Op0, Op1, Q))
565609467b48Spatrick       return C;
565709467b48Spatrick 
565873471bf0Spatrick   if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding))
565909467b48Spatrick     return C;
566009467b48Spatrick 
566173471bf0Spatrick   if (!isDefaultFPEnvironment(ExBehavior, Rounding))
566273471bf0Spatrick     return nullptr;
566373471bf0Spatrick 
566409467b48Spatrick   // Unlike fdiv, the result of frem always matches the sign of the dividend.
566509467b48Spatrick   // The constant match may include undef elements in a vector, so return a full
566609467b48Spatrick   // zero constant as the result.
566709467b48Spatrick   if (FMF.noNaNs()) {
566809467b48Spatrick     // +0 % X -> 0
566909467b48Spatrick     if (match(Op0, m_PosZeroFP()))
567009467b48Spatrick       return ConstantFP::getNullValue(Op0->getType());
567109467b48Spatrick     // -0 % X -> -0
567209467b48Spatrick     if (match(Op0, m_NegZeroFP()))
567309467b48Spatrick       return ConstantFP::getNegativeZero(Op0->getType());
567409467b48Spatrick   }
567509467b48Spatrick 
567609467b48Spatrick   return nullptr;
567709467b48Spatrick }
567809467b48Spatrick 
simplifyFRemInst(Value * Op0,Value * Op1,FastMathFlags FMF,const SimplifyQuery & Q,fp::ExceptionBehavior ExBehavior,RoundingMode Rounding)5679*d415bd75Srobert Value *llvm::simplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
568073471bf0Spatrick                               const SimplifyQuery &Q,
568173471bf0Spatrick                               fp::ExceptionBehavior ExBehavior,
568273471bf0Spatrick                               RoundingMode Rounding) {
5683*d415bd75Srobert   return ::simplifyFRemInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
568473471bf0Spatrick                             Rounding);
568509467b48Spatrick }
568609467b48Spatrick 
568709467b48Spatrick //=== Helper functions for higher up the class hierarchy.
568809467b48Spatrick 
568909467b48Spatrick /// Given the operand for a UnaryOperator, see if we can fold the result.
569009467b48Spatrick /// If not, this returns null.
simplifyUnOp(unsigned Opcode,Value * Op,const SimplifyQuery & Q,unsigned MaxRecurse)569109467b48Spatrick static Value *simplifyUnOp(unsigned Opcode, Value *Op, const SimplifyQuery &Q,
569209467b48Spatrick                            unsigned MaxRecurse) {
569309467b48Spatrick   switch (Opcode) {
569409467b48Spatrick   case Instruction::FNeg:
569509467b48Spatrick     return simplifyFNegInst(Op, FastMathFlags(), Q, MaxRecurse);
569609467b48Spatrick   default:
569709467b48Spatrick     llvm_unreachable("Unexpected opcode");
569809467b48Spatrick   }
569909467b48Spatrick }
570009467b48Spatrick 
570109467b48Spatrick /// Given the operand for a UnaryOperator, see if we can fold the result.
570209467b48Spatrick /// If not, this returns null.
570309467b48Spatrick /// Try to use FastMathFlags when folding the result.
simplifyFPUnOp(unsigned Opcode,Value * Op,const FastMathFlags & FMF,const SimplifyQuery & Q,unsigned MaxRecurse)570409467b48Spatrick static Value *simplifyFPUnOp(unsigned Opcode, Value *Op,
5705*d415bd75Srobert                              const FastMathFlags &FMF, const SimplifyQuery &Q,
5706*d415bd75Srobert                              unsigned MaxRecurse) {
570709467b48Spatrick   switch (Opcode) {
570809467b48Spatrick   case Instruction::FNeg:
570909467b48Spatrick     return simplifyFNegInst(Op, FMF, Q, MaxRecurse);
571009467b48Spatrick   default:
571109467b48Spatrick     return simplifyUnOp(Opcode, Op, Q, MaxRecurse);
571209467b48Spatrick   }
571309467b48Spatrick }
571409467b48Spatrick 
simplifyUnOp(unsigned Opcode,Value * Op,const SimplifyQuery & Q)5715*d415bd75Srobert Value *llvm::simplifyUnOp(unsigned Opcode, Value *Op, const SimplifyQuery &Q) {
571609467b48Spatrick   return ::simplifyUnOp(Opcode, Op, Q, RecursionLimit);
571709467b48Spatrick }
571809467b48Spatrick 
simplifyUnOp(unsigned Opcode,Value * Op,FastMathFlags FMF,const SimplifyQuery & Q)5719*d415bd75Srobert Value *llvm::simplifyUnOp(unsigned Opcode, Value *Op, FastMathFlags FMF,
572009467b48Spatrick                           const SimplifyQuery &Q) {
572109467b48Spatrick   return ::simplifyFPUnOp(Opcode, Op, FMF, Q, RecursionLimit);
572209467b48Spatrick }
572309467b48Spatrick 
572409467b48Spatrick /// Given operands for a BinaryOperator, see if we can fold the result.
572509467b48Spatrick /// If not, this returns null.
simplifyBinOp(unsigned Opcode,Value * LHS,Value * RHS,const SimplifyQuery & Q,unsigned MaxRecurse)5726*d415bd75Srobert static Value *simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
572709467b48Spatrick                             const SimplifyQuery &Q, unsigned MaxRecurse) {
572809467b48Spatrick   switch (Opcode) {
572909467b48Spatrick   case Instruction::Add:
5730*d415bd75Srobert     return simplifyAddInst(LHS, RHS, /* IsNSW */ false, /* IsNUW */ false, Q,
5731*d415bd75Srobert                            MaxRecurse);
573209467b48Spatrick   case Instruction::Sub:
5733*d415bd75Srobert     return simplifySubInst(LHS, RHS,  /* IsNSW */ false, /* IsNUW */ false, Q,
5734*d415bd75Srobert                            MaxRecurse);
573509467b48Spatrick   case Instruction::Mul:
5736*d415bd75Srobert     return simplifyMulInst(LHS, RHS, /* IsNSW */ false, /* IsNUW */ false, Q,
5737*d415bd75Srobert                            MaxRecurse);
573809467b48Spatrick   case Instruction::SDiv:
5739*d415bd75Srobert     return simplifySDivInst(LHS, RHS, /* IsExact */ false, Q, MaxRecurse);
574009467b48Spatrick   case Instruction::UDiv:
5741*d415bd75Srobert     return simplifyUDivInst(LHS, RHS, /* IsExact */ false, Q, MaxRecurse);
574209467b48Spatrick   case Instruction::SRem:
5743*d415bd75Srobert     return simplifySRemInst(LHS, RHS, Q, MaxRecurse);
574409467b48Spatrick   case Instruction::URem:
5745*d415bd75Srobert     return simplifyURemInst(LHS, RHS, Q, MaxRecurse);
574609467b48Spatrick   case Instruction::Shl:
5747*d415bd75Srobert     return simplifyShlInst(LHS, RHS, /* IsNSW */ false, /* IsNUW */ false, Q,
5748*d415bd75Srobert                            MaxRecurse);
574909467b48Spatrick   case Instruction::LShr:
5750*d415bd75Srobert     return simplifyLShrInst(LHS, RHS, /* IsExact */ false, Q, MaxRecurse);
575109467b48Spatrick   case Instruction::AShr:
5752*d415bd75Srobert     return simplifyAShrInst(LHS, RHS, /* IsExact */ false, Q, MaxRecurse);
575309467b48Spatrick   case Instruction::And:
5754*d415bd75Srobert     return simplifyAndInst(LHS, RHS, Q, MaxRecurse);
575509467b48Spatrick   case Instruction::Or:
5756*d415bd75Srobert     return simplifyOrInst(LHS, RHS, Q, MaxRecurse);
575709467b48Spatrick   case Instruction::Xor:
5758*d415bd75Srobert     return simplifyXorInst(LHS, RHS, Q, MaxRecurse);
575909467b48Spatrick   case Instruction::FAdd:
5760*d415bd75Srobert     return simplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
576109467b48Spatrick   case Instruction::FSub:
5762*d415bd75Srobert     return simplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
576309467b48Spatrick   case Instruction::FMul:
5764*d415bd75Srobert     return simplifyFMulInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
576509467b48Spatrick   case Instruction::FDiv:
5766*d415bd75Srobert     return simplifyFDivInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
576709467b48Spatrick   case Instruction::FRem:
5768*d415bd75Srobert     return simplifyFRemInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
576909467b48Spatrick   default:
577009467b48Spatrick     llvm_unreachable("Unexpected opcode");
577109467b48Spatrick   }
577209467b48Spatrick }
577309467b48Spatrick 
577409467b48Spatrick /// Given operands for a BinaryOperator, see if we can fold the result.
577509467b48Spatrick /// If not, this returns null.
577609467b48Spatrick /// Try to use FastMathFlags when folding the result.
simplifyBinOp(unsigned Opcode,Value * LHS,Value * RHS,const FastMathFlags & FMF,const SimplifyQuery & Q,unsigned MaxRecurse)5777*d415bd75Srobert static Value *simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
577809467b48Spatrick                             const FastMathFlags &FMF, const SimplifyQuery &Q,
577909467b48Spatrick                             unsigned MaxRecurse) {
578009467b48Spatrick   switch (Opcode) {
578109467b48Spatrick   case Instruction::FAdd:
5782*d415bd75Srobert     return simplifyFAddInst(LHS, RHS, FMF, Q, MaxRecurse);
578309467b48Spatrick   case Instruction::FSub:
5784*d415bd75Srobert     return simplifyFSubInst(LHS, RHS, FMF, Q, MaxRecurse);
578509467b48Spatrick   case Instruction::FMul:
5786*d415bd75Srobert     return simplifyFMulInst(LHS, RHS, FMF, Q, MaxRecurse);
578709467b48Spatrick   case Instruction::FDiv:
5788*d415bd75Srobert     return simplifyFDivInst(LHS, RHS, FMF, Q, MaxRecurse);
578909467b48Spatrick   default:
5790*d415bd75Srobert     return simplifyBinOp(Opcode, LHS, RHS, Q, MaxRecurse);
579109467b48Spatrick   }
579209467b48Spatrick }
579309467b48Spatrick 
simplifyBinOp(unsigned Opcode,Value * LHS,Value * RHS,const SimplifyQuery & Q)5794*d415bd75Srobert Value *llvm::simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
579509467b48Spatrick                            const SimplifyQuery &Q) {
5796*d415bd75Srobert   return ::simplifyBinOp(Opcode, LHS, RHS, Q, RecursionLimit);
579709467b48Spatrick }
579809467b48Spatrick 
simplifyBinOp(unsigned Opcode,Value * LHS,Value * RHS,FastMathFlags FMF,const SimplifyQuery & Q)5799*d415bd75Srobert Value *llvm::simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
580009467b48Spatrick                            FastMathFlags FMF, const SimplifyQuery &Q) {
5801*d415bd75Srobert   return ::simplifyBinOp(Opcode, LHS, RHS, FMF, Q, RecursionLimit);
580209467b48Spatrick }
580309467b48Spatrick 
580409467b48Spatrick /// Given operands for a CmpInst, see if we can fold the result.
simplifyCmpInst(unsigned Predicate,Value * LHS,Value * RHS,const SimplifyQuery & Q,unsigned MaxRecurse)5805*d415bd75Srobert static Value *simplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
580609467b48Spatrick                               const SimplifyQuery &Q, unsigned MaxRecurse) {
580709467b48Spatrick   if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
5808*d415bd75Srobert     return simplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
5809*d415bd75Srobert   return simplifyFCmpInst(Predicate, LHS, RHS, FastMathFlags(), Q, MaxRecurse);
581009467b48Spatrick }
581109467b48Spatrick 
simplifyCmpInst(unsigned Predicate,Value * LHS,Value * RHS,const SimplifyQuery & Q)5812*d415bd75Srobert Value *llvm::simplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
581309467b48Spatrick                              const SimplifyQuery &Q) {
5814*d415bd75Srobert   return ::simplifyCmpInst(Predicate, LHS, RHS, Q, RecursionLimit);
581509467b48Spatrick }
581609467b48Spatrick 
isIdempotent(Intrinsic::ID ID)5817*d415bd75Srobert static bool isIdempotent(Intrinsic::ID ID) {
581809467b48Spatrick   switch (ID) {
5819*d415bd75Srobert   default:
5820*d415bd75Srobert     return false;
582109467b48Spatrick 
582209467b48Spatrick   // Unary idempotent: f(f(x)) = f(x)
582309467b48Spatrick   case Intrinsic::fabs:
582409467b48Spatrick   case Intrinsic::floor:
582509467b48Spatrick   case Intrinsic::ceil:
582609467b48Spatrick   case Intrinsic::trunc:
582709467b48Spatrick   case Intrinsic::rint:
582809467b48Spatrick   case Intrinsic::nearbyint:
582909467b48Spatrick   case Intrinsic::round:
5830097a140dSpatrick   case Intrinsic::roundeven:
583109467b48Spatrick   case Intrinsic::canonicalize:
5832*d415bd75Srobert   case Intrinsic::arithmetic_fence:
583309467b48Spatrick     return true;
583409467b48Spatrick   }
583509467b48Spatrick }
583609467b48Spatrick 
5837*d415bd75Srobert /// Return true if the intrinsic rounds a floating-point value to an integral
5838*d415bd75Srobert /// floating-point value (not an integer type).
removesFPFraction(Intrinsic::ID ID)5839*d415bd75Srobert static bool removesFPFraction(Intrinsic::ID ID) {
5840*d415bd75Srobert   switch (ID) {
5841*d415bd75Srobert   default:
5842*d415bd75Srobert     return false;
5843*d415bd75Srobert 
5844*d415bd75Srobert   case Intrinsic::floor:
5845*d415bd75Srobert   case Intrinsic::ceil:
5846*d415bd75Srobert   case Intrinsic::trunc:
5847*d415bd75Srobert   case Intrinsic::rint:
5848*d415bd75Srobert   case Intrinsic::nearbyint:
5849*d415bd75Srobert   case Intrinsic::round:
5850*d415bd75Srobert   case Intrinsic::roundeven:
5851*d415bd75Srobert     return true;
5852*d415bd75Srobert   }
5853*d415bd75Srobert }
5854*d415bd75Srobert 
simplifyRelativeLoad(Constant * Ptr,Constant * Offset,const DataLayout & DL)5855*d415bd75Srobert static Value *simplifyRelativeLoad(Constant *Ptr, Constant *Offset,
585609467b48Spatrick                                    const DataLayout &DL) {
585709467b48Spatrick   GlobalValue *PtrSym;
585809467b48Spatrick   APInt PtrOffset;
585909467b48Spatrick   if (!IsConstantOffsetFromGlobal(Ptr, PtrSym, PtrOffset, DL))
586009467b48Spatrick     return nullptr;
586109467b48Spatrick 
586209467b48Spatrick   Type *Int8PtrTy = Type::getInt8PtrTy(Ptr->getContext());
586309467b48Spatrick   Type *Int32Ty = Type::getInt32Ty(Ptr->getContext());
586409467b48Spatrick   Type *Int32PtrTy = Int32Ty->getPointerTo();
586509467b48Spatrick   Type *Int64Ty = Type::getInt64Ty(Ptr->getContext());
586609467b48Spatrick 
586709467b48Spatrick   auto *OffsetConstInt = dyn_cast<ConstantInt>(Offset);
586809467b48Spatrick   if (!OffsetConstInt || OffsetConstInt->getType()->getBitWidth() > 64)
586909467b48Spatrick     return nullptr;
587009467b48Spatrick 
587109467b48Spatrick   uint64_t OffsetInt = OffsetConstInt->getSExtValue();
587209467b48Spatrick   if (OffsetInt % 4 != 0)
587309467b48Spatrick     return nullptr;
587409467b48Spatrick 
587509467b48Spatrick   Constant *C = ConstantExpr::getGetElementPtr(
587609467b48Spatrick       Int32Ty, ConstantExpr::getBitCast(Ptr, Int32PtrTy),
587709467b48Spatrick       ConstantInt::get(Int64Ty, OffsetInt / 4));
587809467b48Spatrick   Constant *Loaded = ConstantFoldLoadFromConstPtr(C, Int32Ty, DL);
587909467b48Spatrick   if (!Loaded)
588009467b48Spatrick     return nullptr;
588109467b48Spatrick 
588209467b48Spatrick   auto *LoadedCE = dyn_cast<ConstantExpr>(Loaded);
588309467b48Spatrick   if (!LoadedCE)
588409467b48Spatrick     return nullptr;
588509467b48Spatrick 
588609467b48Spatrick   if (LoadedCE->getOpcode() == Instruction::Trunc) {
588709467b48Spatrick     LoadedCE = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
588809467b48Spatrick     if (!LoadedCE)
588909467b48Spatrick       return nullptr;
589009467b48Spatrick   }
589109467b48Spatrick 
589209467b48Spatrick   if (LoadedCE->getOpcode() != Instruction::Sub)
589309467b48Spatrick     return nullptr;
589409467b48Spatrick 
589509467b48Spatrick   auto *LoadedLHS = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
589609467b48Spatrick   if (!LoadedLHS || LoadedLHS->getOpcode() != Instruction::PtrToInt)
589709467b48Spatrick     return nullptr;
589809467b48Spatrick   auto *LoadedLHSPtr = LoadedLHS->getOperand(0);
589909467b48Spatrick 
590009467b48Spatrick   Constant *LoadedRHS = LoadedCE->getOperand(1);
590109467b48Spatrick   GlobalValue *LoadedRHSSym;
590209467b48Spatrick   APInt LoadedRHSOffset;
590309467b48Spatrick   if (!IsConstantOffsetFromGlobal(LoadedRHS, LoadedRHSSym, LoadedRHSOffset,
590409467b48Spatrick                                   DL) ||
590509467b48Spatrick       PtrSym != LoadedRHSSym || PtrOffset != LoadedRHSOffset)
590609467b48Spatrick     return nullptr;
590709467b48Spatrick 
590809467b48Spatrick   return ConstantExpr::getBitCast(LoadedLHSPtr, Int8PtrTy);
590909467b48Spatrick }
591009467b48Spatrick 
simplifyUnaryIntrinsic(Function * F,Value * Op0,const SimplifyQuery & Q)591109467b48Spatrick static Value *simplifyUnaryIntrinsic(Function *F, Value *Op0,
591209467b48Spatrick                                      const SimplifyQuery &Q) {
591309467b48Spatrick   // Idempotent functions return the same result when called repeatedly.
591409467b48Spatrick   Intrinsic::ID IID = F->getIntrinsicID();
5915*d415bd75Srobert   if (isIdempotent(IID))
591609467b48Spatrick     if (auto *II = dyn_cast<IntrinsicInst>(Op0))
591709467b48Spatrick       if (II->getIntrinsicID() == IID)
591809467b48Spatrick         return II;
591909467b48Spatrick 
5920*d415bd75Srobert   if (removesFPFraction(IID)) {
5921*d415bd75Srobert     // Converting from int or calling a rounding function always results in a
5922*d415bd75Srobert     // finite integral number or infinity. For those inputs, rounding functions
5923*d415bd75Srobert     // always return the same value, so the (2nd) rounding is eliminated. Ex:
5924*d415bd75Srobert     // floor (sitofp x) -> sitofp x
5925*d415bd75Srobert     // round (ceil x) -> ceil x
5926*d415bd75Srobert     auto *II = dyn_cast<IntrinsicInst>(Op0);
5927*d415bd75Srobert     if ((II && removesFPFraction(II->getIntrinsicID())) ||
5928*d415bd75Srobert         match(Op0, m_SIToFP(m_Value())) || match(Op0, m_UIToFP(m_Value())))
5929*d415bd75Srobert       return Op0;
5930*d415bd75Srobert   }
5931*d415bd75Srobert 
593209467b48Spatrick   Value *X;
593309467b48Spatrick   switch (IID) {
593409467b48Spatrick   case Intrinsic::fabs:
5935*d415bd75Srobert     if (SignBitMustBeZero(Op0, Q.TLI))
5936*d415bd75Srobert       return Op0;
593709467b48Spatrick     break;
593809467b48Spatrick   case Intrinsic::bswap:
593909467b48Spatrick     // bswap(bswap(x)) -> x
5940*d415bd75Srobert     if (match(Op0, m_BSwap(m_Value(X))))
5941*d415bd75Srobert       return X;
594209467b48Spatrick     break;
594309467b48Spatrick   case Intrinsic::bitreverse:
594409467b48Spatrick     // bitreverse(bitreverse(x)) -> x
5945*d415bd75Srobert     if (match(Op0, m_BitReverse(m_Value(X))))
5946*d415bd75Srobert       return X;
594709467b48Spatrick     break;
594873471bf0Spatrick   case Intrinsic::ctpop: {
5949*d415bd75Srobert     // ctpop(X) -> 1 iff X is non-zero power of 2.
5950*d415bd75Srobert     if (isKnownToBeAPowerOfTwo(Op0, Q.DL, /*OrZero*/ false, 0, Q.AC, Q.CxtI,
5951*d415bd75Srobert                                Q.DT))
5952*d415bd75Srobert       return ConstantInt::get(Op0->getType(), 1);
595373471bf0Spatrick     // If everything but the lowest bit is zero, that bit is the pop-count. Ex:
595473471bf0Spatrick     // ctpop(and X, 1) --> and X, 1
595573471bf0Spatrick     unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
595673471bf0Spatrick     if (MaskedValueIsZero(Op0, APInt::getHighBitsSet(BitWidth, BitWidth - 1),
595773471bf0Spatrick                           Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
595873471bf0Spatrick       return Op0;
595973471bf0Spatrick     break;
596073471bf0Spatrick   }
596109467b48Spatrick   case Intrinsic::exp:
596209467b48Spatrick     // exp(log(x)) -> x
596309467b48Spatrick     if (Q.CxtI->hasAllowReassoc() &&
5964*d415bd75Srobert         match(Op0, m_Intrinsic<Intrinsic::log>(m_Value(X))))
5965*d415bd75Srobert       return X;
596609467b48Spatrick     break;
596709467b48Spatrick   case Intrinsic::exp2:
596809467b48Spatrick     // exp2(log2(x)) -> x
596909467b48Spatrick     if (Q.CxtI->hasAllowReassoc() &&
5970*d415bd75Srobert         match(Op0, m_Intrinsic<Intrinsic::log2>(m_Value(X))))
5971*d415bd75Srobert       return X;
597209467b48Spatrick     break;
597309467b48Spatrick   case Intrinsic::log:
597409467b48Spatrick     // log(exp(x)) -> x
597509467b48Spatrick     if (Q.CxtI->hasAllowReassoc() &&
5976*d415bd75Srobert         match(Op0, m_Intrinsic<Intrinsic::exp>(m_Value(X))))
5977*d415bd75Srobert       return X;
597809467b48Spatrick     break;
597909467b48Spatrick   case Intrinsic::log2:
598009467b48Spatrick     // log2(exp2(x)) -> x
598109467b48Spatrick     if (Q.CxtI->hasAllowReassoc() &&
598209467b48Spatrick         (match(Op0, m_Intrinsic<Intrinsic::exp2>(m_Value(X))) ||
5983*d415bd75Srobert          match(Op0,
5984*d415bd75Srobert                m_Intrinsic<Intrinsic::pow>(m_SpecificFP(2.0), m_Value(X)))))
5985*d415bd75Srobert       return X;
598609467b48Spatrick     break;
598709467b48Spatrick   case Intrinsic::log10:
598809467b48Spatrick     // log10(pow(10.0, x)) -> x
598909467b48Spatrick     if (Q.CxtI->hasAllowReassoc() &&
5990*d415bd75Srobert         match(Op0, m_Intrinsic<Intrinsic::pow>(m_SpecificFP(10.0), m_Value(X))))
5991*d415bd75Srobert       return X;
599209467b48Spatrick     break;
599373471bf0Spatrick   case Intrinsic::experimental_vector_reverse:
599473471bf0Spatrick     // experimental.vector.reverse(experimental.vector.reverse(x)) -> x
5995*d415bd75Srobert     if (match(Op0, m_VecReverse(m_Value(X))))
599673471bf0Spatrick       return X;
5997*d415bd75Srobert     // experimental.vector.reverse(splat(X)) -> splat(X)
5998*d415bd75Srobert     if (isSplatValue(Op0))
5999*d415bd75Srobert       return Op0;
600073471bf0Spatrick     break;
600109467b48Spatrick   default:
600209467b48Spatrick     break;
600309467b48Spatrick   }
600409467b48Spatrick 
600509467b48Spatrick   return nullptr;
600609467b48Spatrick }
600709467b48Spatrick 
600873471bf0Spatrick /// Given a min/max intrinsic, see if it can be removed based on having an
600973471bf0Spatrick /// operand that is another min/max intrinsic with shared operand(s). The caller
601073471bf0Spatrick /// is expected to swap the operand arguments to handle commutation.
foldMinMaxSharedOp(Intrinsic::ID IID,Value * Op0,Value * Op1)601173471bf0Spatrick static Value *foldMinMaxSharedOp(Intrinsic::ID IID, Value *Op0, Value *Op1) {
601273471bf0Spatrick   Value *X, *Y;
601373471bf0Spatrick   if (!match(Op0, m_MaxOrMin(m_Value(X), m_Value(Y))))
601473471bf0Spatrick     return nullptr;
601573471bf0Spatrick 
601673471bf0Spatrick   auto *MM0 = dyn_cast<IntrinsicInst>(Op0);
601773471bf0Spatrick   if (!MM0)
601873471bf0Spatrick     return nullptr;
601973471bf0Spatrick   Intrinsic::ID IID0 = MM0->getIntrinsicID();
602073471bf0Spatrick 
602173471bf0Spatrick   if (Op1 == X || Op1 == Y ||
602273471bf0Spatrick       match(Op1, m_c_MaxOrMin(m_Specific(X), m_Specific(Y)))) {
602373471bf0Spatrick     // max (max X, Y), X --> max X, Y
602473471bf0Spatrick     if (IID0 == IID)
602573471bf0Spatrick       return MM0;
602673471bf0Spatrick     // max (min X, Y), X --> X
602773471bf0Spatrick     if (IID0 == getInverseMinMaxIntrinsic(IID))
602873471bf0Spatrick       return Op1;
602973471bf0Spatrick   }
603073471bf0Spatrick   return nullptr;
603173471bf0Spatrick }
603273471bf0Spatrick 
simplifyBinaryIntrinsic(Function * F,Value * Op0,Value * Op1,const SimplifyQuery & Q)603309467b48Spatrick static Value *simplifyBinaryIntrinsic(Function *F, Value *Op0, Value *Op1,
603409467b48Spatrick                                       const SimplifyQuery &Q) {
603509467b48Spatrick   Intrinsic::ID IID = F->getIntrinsicID();
603609467b48Spatrick   Type *ReturnType = F->getReturnType();
603773471bf0Spatrick   unsigned BitWidth = ReturnType->getScalarSizeInBits();
603809467b48Spatrick   switch (IID) {
603973471bf0Spatrick   case Intrinsic::abs:
604073471bf0Spatrick     // abs(abs(x)) -> abs(x). We don't need to worry about the nsw arg here.
604173471bf0Spatrick     // It is always ok to pick the earlier abs. We'll just lose nsw if its only
604273471bf0Spatrick     // on the outer abs.
604373471bf0Spatrick     if (match(Op0, m_Intrinsic<Intrinsic::abs>(m_Value(), m_Value())))
604473471bf0Spatrick       return Op0;
604573471bf0Spatrick     break;
604673471bf0Spatrick 
604773471bf0Spatrick   case Intrinsic::cttz: {
604873471bf0Spatrick     Value *X;
604973471bf0Spatrick     if (match(Op0, m_Shl(m_One(), m_Value(X))))
605073471bf0Spatrick       return X;
605173471bf0Spatrick     break;
605273471bf0Spatrick   }
605373471bf0Spatrick   case Intrinsic::ctlz: {
605473471bf0Spatrick     Value *X;
605573471bf0Spatrick     if (match(Op0, m_LShr(m_Negative(), m_Value(X))))
605673471bf0Spatrick       return X;
605773471bf0Spatrick     if (match(Op0, m_AShr(m_Negative(), m_Value())))
605873471bf0Spatrick       return Constant::getNullValue(ReturnType);
605973471bf0Spatrick     break;
606073471bf0Spatrick   }
606173471bf0Spatrick   case Intrinsic::smax:
606273471bf0Spatrick   case Intrinsic::smin:
606373471bf0Spatrick   case Intrinsic::umax:
606473471bf0Spatrick   case Intrinsic::umin: {
606573471bf0Spatrick     // If the arguments are the same, this is a no-op.
606673471bf0Spatrick     if (Op0 == Op1)
606773471bf0Spatrick       return Op0;
606873471bf0Spatrick 
6069*d415bd75Srobert     // Canonicalize immediate constant operand as Op1.
6070*d415bd75Srobert     if (match(Op0, m_ImmConstant()))
607173471bf0Spatrick       std::swap(Op0, Op1);
607273471bf0Spatrick 
607373471bf0Spatrick     // Assume undef is the limit value.
607473471bf0Spatrick     if (Q.isUndefValue(Op1))
6075*d415bd75Srobert       return ConstantInt::get(
6076*d415bd75Srobert           ReturnType, MinMaxIntrinsic::getSaturationPoint(IID, BitWidth));
607773471bf0Spatrick 
607873471bf0Spatrick     const APInt *C;
607973471bf0Spatrick     if (match(Op1, m_APIntAllowUndef(C))) {
608073471bf0Spatrick       // Clamp to limit value. For example:
608173471bf0Spatrick       // umax(i8 %x, i8 255) --> 255
6082*d415bd75Srobert       if (*C == MinMaxIntrinsic::getSaturationPoint(IID, BitWidth))
608373471bf0Spatrick         return ConstantInt::get(ReturnType, *C);
608473471bf0Spatrick 
608573471bf0Spatrick       // If the constant op is the opposite of the limit value, the other must
608673471bf0Spatrick       // be larger/smaller or equal. For example:
608773471bf0Spatrick       // umin(i8 %x, i8 255) --> %x
6088*d415bd75Srobert       if (*C == MinMaxIntrinsic::getSaturationPoint(
6089*d415bd75Srobert                     getInverseMinMaxIntrinsic(IID), BitWidth))
609073471bf0Spatrick         return Op0;
609173471bf0Spatrick 
609273471bf0Spatrick       // Remove nested call if constant operands allow it. Example:
609373471bf0Spatrick       // max (max X, 7), 5 -> max X, 7
609473471bf0Spatrick       auto *MinMax0 = dyn_cast<IntrinsicInst>(Op0);
609573471bf0Spatrick       if (MinMax0 && MinMax0->getIntrinsicID() == IID) {
609673471bf0Spatrick         // TODO: loosen undef/splat restrictions for vector constants.
609773471bf0Spatrick         Value *M00 = MinMax0->getOperand(0), *M01 = MinMax0->getOperand(1);
609873471bf0Spatrick         const APInt *InnerC;
609973471bf0Spatrick         if ((match(M00, m_APInt(InnerC)) || match(M01, m_APInt(InnerC))) &&
6100*d415bd75Srobert             ICmpInst::compare(*InnerC, *C,
6101*d415bd75Srobert                               ICmpInst::getNonStrictPredicate(
6102*d415bd75Srobert                                   MinMaxIntrinsic::getPredicate(IID))))
610373471bf0Spatrick           return Op0;
610473471bf0Spatrick       }
610573471bf0Spatrick     }
610673471bf0Spatrick 
610773471bf0Spatrick     if (Value *V = foldMinMaxSharedOp(IID, Op0, Op1))
610873471bf0Spatrick       return V;
610973471bf0Spatrick     if (Value *V = foldMinMaxSharedOp(IID, Op1, Op0))
611073471bf0Spatrick       return V;
611173471bf0Spatrick 
6112*d415bd75Srobert     ICmpInst::Predicate Pred =
6113*d415bd75Srobert         ICmpInst::getNonStrictPredicate(MinMaxIntrinsic::getPredicate(IID));
611473471bf0Spatrick     if (isICmpTrue(Pred, Op0, Op1, Q.getWithoutUndef(), RecursionLimit))
611573471bf0Spatrick       return Op0;
611673471bf0Spatrick     if (isICmpTrue(Pred, Op1, Op0, Q.getWithoutUndef(), RecursionLimit))
611773471bf0Spatrick       return Op1;
611873471bf0Spatrick 
6119*d415bd75Srobert     if (std::optional<bool> Imp =
612073471bf0Spatrick             isImpliedByDomCondition(Pred, Op0, Op1, Q.CxtI, Q.DL))
612173471bf0Spatrick       return *Imp ? Op0 : Op1;
6122*d415bd75Srobert     if (std::optional<bool> Imp =
612373471bf0Spatrick             isImpliedByDomCondition(Pred, Op1, Op0, Q.CxtI, Q.DL))
612473471bf0Spatrick       return *Imp ? Op1 : Op0;
612573471bf0Spatrick 
612673471bf0Spatrick     break;
612773471bf0Spatrick   }
612809467b48Spatrick   case Intrinsic::usub_with_overflow:
612909467b48Spatrick   case Intrinsic::ssub_with_overflow:
613009467b48Spatrick     // X - X -> { 0, false }
613173471bf0Spatrick     // X - undef -> { 0, false }
613273471bf0Spatrick     // undef - X -> { 0, false }
613373471bf0Spatrick     if (Op0 == Op1 || Q.isUndefValue(Op0) || Q.isUndefValue(Op1))
613409467b48Spatrick       return Constant::getNullValue(ReturnType);
613573471bf0Spatrick     break;
613609467b48Spatrick   case Intrinsic::uadd_with_overflow:
613709467b48Spatrick   case Intrinsic::sadd_with_overflow:
613873471bf0Spatrick     // X + undef -> { -1, false }
613973471bf0Spatrick     // undef + x -> { -1, false }
614073471bf0Spatrick     if (Q.isUndefValue(Op0) || Q.isUndefValue(Op1)) {
614109467b48Spatrick       return ConstantStruct::get(
614209467b48Spatrick           cast<StructType>(ReturnType),
614373471bf0Spatrick           {Constant::getAllOnesValue(ReturnType->getStructElementType(0)),
614409467b48Spatrick            Constant::getNullValue(ReturnType->getStructElementType(1))});
614509467b48Spatrick     }
614609467b48Spatrick     break;
614709467b48Spatrick   case Intrinsic::umul_with_overflow:
614809467b48Spatrick   case Intrinsic::smul_with_overflow:
614909467b48Spatrick     // 0 * X -> { 0, false }
615009467b48Spatrick     // X * 0 -> { 0, false }
615109467b48Spatrick     if (match(Op0, m_Zero()) || match(Op1, m_Zero()))
615209467b48Spatrick       return Constant::getNullValue(ReturnType);
615309467b48Spatrick     // undef * X -> { 0, false }
615409467b48Spatrick     // X * undef -> { 0, false }
615573471bf0Spatrick     if (Q.isUndefValue(Op0) || Q.isUndefValue(Op1))
615609467b48Spatrick       return Constant::getNullValue(ReturnType);
615709467b48Spatrick     break;
615809467b48Spatrick   case Intrinsic::uadd_sat:
615909467b48Spatrick     // sat(MAX + X) -> MAX
616009467b48Spatrick     // sat(X + MAX) -> MAX
616109467b48Spatrick     if (match(Op0, m_AllOnes()) || match(Op1, m_AllOnes()))
616209467b48Spatrick       return Constant::getAllOnesValue(ReturnType);
6163*d415bd75Srobert     [[fallthrough]];
616409467b48Spatrick   case Intrinsic::sadd_sat:
616509467b48Spatrick     // sat(X + undef) -> -1
616609467b48Spatrick     // sat(undef + X) -> -1
616709467b48Spatrick     // For unsigned: Assume undef is MAX, thus we saturate to MAX (-1).
616809467b48Spatrick     // For signed: Assume undef is ~X, in which case X + ~X = -1.
616973471bf0Spatrick     if (Q.isUndefValue(Op0) || Q.isUndefValue(Op1))
617009467b48Spatrick       return Constant::getAllOnesValue(ReturnType);
617109467b48Spatrick 
617209467b48Spatrick     // X + 0 -> X
617309467b48Spatrick     if (match(Op1, m_Zero()))
617409467b48Spatrick       return Op0;
617509467b48Spatrick     // 0 + X -> X
617609467b48Spatrick     if (match(Op0, m_Zero()))
617709467b48Spatrick       return Op1;
617809467b48Spatrick     break;
617909467b48Spatrick   case Intrinsic::usub_sat:
618009467b48Spatrick     // sat(0 - X) -> 0, sat(X - MAX) -> 0
618109467b48Spatrick     if (match(Op0, m_Zero()) || match(Op1, m_AllOnes()))
618209467b48Spatrick       return Constant::getNullValue(ReturnType);
6183*d415bd75Srobert     [[fallthrough]];
618409467b48Spatrick   case Intrinsic::ssub_sat:
618509467b48Spatrick     // X - X -> 0, X - undef -> 0, undef - X -> 0
618673471bf0Spatrick     if (Op0 == Op1 || Q.isUndefValue(Op0) || Q.isUndefValue(Op1))
618709467b48Spatrick       return Constant::getNullValue(ReturnType);
618809467b48Spatrick     // X - 0 -> X
618909467b48Spatrick     if (match(Op1, m_Zero()))
619009467b48Spatrick       return Op0;
619109467b48Spatrick     break;
619209467b48Spatrick   case Intrinsic::load_relative:
619309467b48Spatrick     if (auto *C0 = dyn_cast<Constant>(Op0))
619409467b48Spatrick       if (auto *C1 = dyn_cast<Constant>(Op1))
6195*d415bd75Srobert         return simplifyRelativeLoad(C0, C1, Q.DL);
619609467b48Spatrick     break;
619709467b48Spatrick   case Intrinsic::powi:
619809467b48Spatrick     if (auto *Power = dyn_cast<ConstantInt>(Op1)) {
619909467b48Spatrick       // powi(x, 0) -> 1.0
620009467b48Spatrick       if (Power->isZero())
620109467b48Spatrick         return ConstantFP::get(Op0->getType(), 1.0);
620209467b48Spatrick       // powi(x, 1) -> x
620309467b48Spatrick       if (Power->isOne())
620409467b48Spatrick         return Op0;
620509467b48Spatrick     }
620609467b48Spatrick     break;
620709467b48Spatrick   case Intrinsic::copysign:
620809467b48Spatrick     // copysign X, X --> X
620909467b48Spatrick     if (Op0 == Op1)
621009467b48Spatrick       return Op0;
621109467b48Spatrick     // copysign -X, X --> X
621209467b48Spatrick     // copysign X, -X --> -X
621309467b48Spatrick     if (match(Op0, m_FNeg(m_Specific(Op1))) ||
621409467b48Spatrick         match(Op1, m_FNeg(m_Specific(Op0))))
621509467b48Spatrick       return Op1;
621609467b48Spatrick     break;
6217*d415bd75Srobert   case Intrinsic::is_fpclass: {
6218*d415bd75Srobert     if (isa<PoisonValue>(Op0))
6219*d415bd75Srobert       return PoisonValue::get(ReturnType);
6220*d415bd75Srobert 
6221*d415bd75Srobert     uint64_t Mask = cast<ConstantInt>(Op1)->getZExtValue();
6222*d415bd75Srobert     // If all tests are made, it doesn't matter what the value is.
6223*d415bd75Srobert     if ((Mask & fcAllFlags) == fcAllFlags)
6224*d415bd75Srobert       return ConstantInt::get(ReturnType, true);
6225*d415bd75Srobert     if ((Mask & fcAllFlags) == 0)
6226*d415bd75Srobert       return ConstantInt::get(ReturnType, false);
6227*d415bd75Srobert     if (Q.isUndefValue(Op0))
6228*d415bd75Srobert       return UndefValue::get(ReturnType);
6229*d415bd75Srobert     break;
6230*d415bd75Srobert   }
623109467b48Spatrick   case Intrinsic::maxnum:
623209467b48Spatrick   case Intrinsic::minnum:
623309467b48Spatrick   case Intrinsic::maximum:
623409467b48Spatrick   case Intrinsic::minimum: {
623509467b48Spatrick     // If the arguments are the same, this is a no-op.
6236*d415bd75Srobert     if (Op0 == Op1)
6237*d415bd75Srobert       return Op0;
623809467b48Spatrick 
623973471bf0Spatrick     // Canonicalize constant operand as Op1.
624073471bf0Spatrick     if (isa<Constant>(Op0))
624173471bf0Spatrick       std::swap(Op0, Op1);
624273471bf0Spatrick 
624373471bf0Spatrick     // If an argument is undef, return the other argument.
624473471bf0Spatrick     if (Q.isUndefValue(Op1))
624509467b48Spatrick       return Op0;
624609467b48Spatrick 
624709467b48Spatrick     bool PropagateNaN = IID == Intrinsic::minimum || IID == Intrinsic::maximum;
624873471bf0Spatrick     bool IsMin = IID == Intrinsic::minimum || IID == Intrinsic::minnum;
624973471bf0Spatrick 
625073471bf0Spatrick     // minnum(X, nan) -> X
625173471bf0Spatrick     // maxnum(X, nan) -> X
625273471bf0Spatrick     // minimum(X, nan) -> nan
625373471bf0Spatrick     // maximum(X, nan) -> nan
625409467b48Spatrick     if (match(Op1, m_NaN()))
625573471bf0Spatrick       return PropagateNaN ? propagateNaN(cast<Constant>(Op1)) : Op0;
625673471bf0Spatrick 
625773471bf0Spatrick     // In the following folds, inf can be replaced with the largest finite
625873471bf0Spatrick     // float, if the ninf flag is set.
625973471bf0Spatrick     const APFloat *C;
626073471bf0Spatrick     if (match(Op1, m_APFloat(C)) &&
626173471bf0Spatrick         (C->isInfinity() || (Q.CxtI->hasNoInfs() && C->isLargest()))) {
626273471bf0Spatrick       // minnum(X, -inf) -> -inf
626373471bf0Spatrick       // maxnum(X, +inf) -> +inf
626473471bf0Spatrick       // minimum(X, -inf) -> -inf if nnan
626573471bf0Spatrick       // maximum(X, +inf) -> +inf if nnan
626673471bf0Spatrick       if (C->isNegative() == IsMin && (!PropagateNaN || Q.CxtI->hasNoNaNs()))
626773471bf0Spatrick         return ConstantFP::get(ReturnType, *C);
626873471bf0Spatrick 
626973471bf0Spatrick       // minnum(X, +inf) -> X if nnan
627073471bf0Spatrick       // maxnum(X, -inf) -> X if nnan
627173471bf0Spatrick       // minimum(X, +inf) -> X
627273471bf0Spatrick       // maximum(X, -inf) -> X
627373471bf0Spatrick       if (C->isNegative() != IsMin && (PropagateNaN || Q.CxtI->hasNoNaNs()))
627473471bf0Spatrick         return Op0;
627573471bf0Spatrick     }
627609467b48Spatrick 
627709467b48Spatrick     // Min/max of the same operation with common operand:
627809467b48Spatrick     // m(m(X, Y)), X --> m(X, Y) (4 commuted variants)
627909467b48Spatrick     if (auto *M0 = dyn_cast<IntrinsicInst>(Op0))
628009467b48Spatrick       if (M0->getIntrinsicID() == IID &&
628109467b48Spatrick           (M0->getOperand(0) == Op1 || M0->getOperand(1) == Op1))
628209467b48Spatrick         return Op0;
628309467b48Spatrick     if (auto *M1 = dyn_cast<IntrinsicInst>(Op1))
628409467b48Spatrick       if (M1->getIntrinsicID() == IID &&
628509467b48Spatrick           (M1->getOperand(0) == Op0 || M1->getOperand(1) == Op0))
628609467b48Spatrick         return Op1;
628709467b48Spatrick 
628873471bf0Spatrick     break;
628973471bf0Spatrick   }
6290*d415bd75Srobert   case Intrinsic::vector_extract: {
629173471bf0Spatrick     Type *ReturnType = F->getReturnType();
629209467b48Spatrick 
629373471bf0Spatrick     // (extract_vector (insert_vector _, X, 0), 0) -> X
629473471bf0Spatrick     unsigned IdxN = cast<ConstantInt>(Op1)->getZExtValue();
629573471bf0Spatrick     Value *X = nullptr;
6296*d415bd75Srobert     if (match(Op0, m_Intrinsic<Intrinsic::vector_insert>(m_Value(), m_Value(X),
6297*d415bd75Srobert                                                          m_Zero())) &&
629873471bf0Spatrick         IdxN == 0 && X->getType() == ReturnType)
629973471bf0Spatrick       return X;
630073471bf0Spatrick 
630109467b48Spatrick     break;
630209467b48Spatrick   }
630309467b48Spatrick   default:
630409467b48Spatrick     break;
630509467b48Spatrick   }
630609467b48Spatrick 
630709467b48Spatrick   return nullptr;
630809467b48Spatrick }
630909467b48Spatrick 
simplifyIntrinsic(CallBase * Call,const SimplifyQuery & Q)631009467b48Spatrick static Value *simplifyIntrinsic(CallBase *Call, const SimplifyQuery &Q) {
631109467b48Spatrick 
6312*d415bd75Srobert   unsigned NumOperands = Call->arg_size();
631309467b48Spatrick   Function *F = cast<Function>(Call->getCalledFunction());
631409467b48Spatrick   Intrinsic::ID IID = F->getIntrinsicID();
6315*d415bd75Srobert 
6316*d415bd75Srobert   // Most of the intrinsics with no operands have some kind of side effect.
6317*d415bd75Srobert   // Don't simplify.
6318*d415bd75Srobert   if (!NumOperands) {
6319*d415bd75Srobert     switch (IID) {
6320*d415bd75Srobert     case Intrinsic::vscale: {
6321*d415bd75Srobert       // Call may not be inserted into the IR yet at point of calling simplify.
6322*d415bd75Srobert       if (!Call->getParent() || !Call->getParent()->getParent())
6323*d415bd75Srobert         return nullptr;
6324*d415bd75Srobert       auto Attr = Call->getFunction()->getFnAttribute(Attribute::VScaleRange);
6325*d415bd75Srobert       if (!Attr.isValid())
6326*d415bd75Srobert         return nullptr;
6327*d415bd75Srobert       unsigned VScaleMin = Attr.getVScaleRangeMin();
6328*d415bd75Srobert       std::optional<unsigned> VScaleMax = Attr.getVScaleRangeMax();
6329*d415bd75Srobert       if (VScaleMax && VScaleMin == VScaleMax)
6330*d415bd75Srobert         return ConstantInt::get(F->getReturnType(), VScaleMin);
6331*d415bd75Srobert       return nullptr;
6332*d415bd75Srobert     }
6333*d415bd75Srobert     default:
6334*d415bd75Srobert       return nullptr;
6335*d415bd75Srobert     }
6336*d415bd75Srobert   }
6337*d415bd75Srobert 
633809467b48Spatrick   if (NumOperands == 1)
633909467b48Spatrick     return simplifyUnaryIntrinsic(F, Call->getArgOperand(0), Q);
634009467b48Spatrick 
634109467b48Spatrick   if (NumOperands == 2)
634209467b48Spatrick     return simplifyBinaryIntrinsic(F, Call->getArgOperand(0),
634309467b48Spatrick                                    Call->getArgOperand(1), Q);
634409467b48Spatrick 
634509467b48Spatrick   // Handle intrinsics with 3 or more arguments.
634609467b48Spatrick   switch (IID) {
634709467b48Spatrick   case Intrinsic::masked_load:
634809467b48Spatrick   case Intrinsic::masked_gather: {
634909467b48Spatrick     Value *MaskArg = Call->getArgOperand(2);
635009467b48Spatrick     Value *PassthruArg = Call->getArgOperand(3);
635109467b48Spatrick     // If the mask is all zeros or undef, the "passthru" argument is the result.
635209467b48Spatrick     if (maskIsAllZeroOrUndef(MaskArg))
635309467b48Spatrick       return PassthruArg;
635409467b48Spatrick     return nullptr;
635509467b48Spatrick   }
635609467b48Spatrick   case Intrinsic::fshl:
635709467b48Spatrick   case Intrinsic::fshr: {
635809467b48Spatrick     Value *Op0 = Call->getArgOperand(0), *Op1 = Call->getArgOperand(1),
635909467b48Spatrick           *ShAmtArg = Call->getArgOperand(2);
636009467b48Spatrick 
636109467b48Spatrick     // If both operands are undef, the result is undef.
636273471bf0Spatrick     if (Q.isUndefValue(Op0) && Q.isUndefValue(Op1))
636309467b48Spatrick       return UndefValue::get(F->getReturnType());
636409467b48Spatrick 
636509467b48Spatrick     // If shift amount is undef, assume it is zero.
636673471bf0Spatrick     if (Q.isUndefValue(ShAmtArg))
636709467b48Spatrick       return Call->getArgOperand(IID == Intrinsic::fshl ? 0 : 1);
636809467b48Spatrick 
636909467b48Spatrick     const APInt *ShAmtC;
637009467b48Spatrick     if (match(ShAmtArg, m_APInt(ShAmtC))) {
637109467b48Spatrick       // If there's effectively no shift, return the 1st arg or 2nd arg.
637209467b48Spatrick       APInt BitWidth = APInt(ShAmtC->getBitWidth(), ShAmtC->getBitWidth());
6373*d415bd75Srobert       if (ShAmtC->urem(BitWidth).isZero())
637409467b48Spatrick         return Call->getArgOperand(IID == Intrinsic::fshl ? 0 : 1);
637509467b48Spatrick     }
6376*d415bd75Srobert 
6377*d415bd75Srobert     // Rotating zero by anything is zero.
6378*d415bd75Srobert     if (match(Op0, m_Zero()) && match(Op1, m_Zero()))
6379*d415bd75Srobert       return ConstantInt::getNullValue(F->getReturnType());
6380*d415bd75Srobert 
6381*d415bd75Srobert     // Rotating -1 by anything is -1.
6382*d415bd75Srobert     if (match(Op0, m_AllOnes()) && match(Op1, m_AllOnes()))
6383*d415bd75Srobert       return ConstantInt::getAllOnesValue(F->getReturnType());
6384*d415bd75Srobert 
638509467b48Spatrick     return nullptr;
638609467b48Spatrick   }
638773471bf0Spatrick   case Intrinsic::experimental_constrained_fma: {
638873471bf0Spatrick     Value *Op0 = Call->getArgOperand(0);
638973471bf0Spatrick     Value *Op1 = Call->getArgOperand(1);
639073471bf0Spatrick     Value *Op2 = Call->getArgOperand(2);
639173471bf0Spatrick     auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
6392*d415bd75Srobert     if (Value *V =
6393*d415bd75Srobert             simplifyFPOp({Op0, Op1, Op2}, {}, Q, *FPI->getExceptionBehavior(),
6394*d415bd75Srobert                          *FPI->getRoundingMode()))
639573471bf0Spatrick       return V;
639673471bf0Spatrick     return nullptr;
639773471bf0Spatrick   }
639809467b48Spatrick   case Intrinsic::fma:
639909467b48Spatrick   case Intrinsic::fmuladd: {
640009467b48Spatrick     Value *Op0 = Call->getArgOperand(0);
640109467b48Spatrick     Value *Op1 = Call->getArgOperand(1);
640209467b48Spatrick     Value *Op2 = Call->getArgOperand(2);
640373471bf0Spatrick     if (Value *V = simplifyFPOp({Op0, Op1, Op2}, {}, Q, fp::ebIgnore,
640473471bf0Spatrick                                 RoundingMode::NearestTiesToEven))
640509467b48Spatrick       return V;
640609467b48Spatrick     return nullptr;
640709467b48Spatrick   }
640873471bf0Spatrick   case Intrinsic::smul_fix:
640973471bf0Spatrick   case Intrinsic::smul_fix_sat: {
641073471bf0Spatrick     Value *Op0 = Call->getArgOperand(0);
641173471bf0Spatrick     Value *Op1 = Call->getArgOperand(1);
641273471bf0Spatrick     Value *Op2 = Call->getArgOperand(2);
641373471bf0Spatrick     Type *ReturnType = F->getReturnType();
641473471bf0Spatrick 
641573471bf0Spatrick     // Canonicalize constant operand as Op1 (ConstantFolding handles the case
641673471bf0Spatrick     // when both Op0 and Op1 are constant so we do not care about that special
641773471bf0Spatrick     // case here).
641873471bf0Spatrick     if (isa<Constant>(Op0))
641973471bf0Spatrick       std::swap(Op0, Op1);
642073471bf0Spatrick 
642173471bf0Spatrick     // X * 0 -> 0
642273471bf0Spatrick     if (match(Op1, m_Zero()))
642373471bf0Spatrick       return Constant::getNullValue(ReturnType);
642473471bf0Spatrick 
642573471bf0Spatrick     // X * undef -> 0
642673471bf0Spatrick     if (Q.isUndefValue(Op1))
642773471bf0Spatrick       return Constant::getNullValue(ReturnType);
642873471bf0Spatrick 
642973471bf0Spatrick     // X * (1 << Scale) -> X
643073471bf0Spatrick     APInt ScaledOne =
643173471bf0Spatrick         APInt::getOneBitSet(ReturnType->getScalarSizeInBits(),
643273471bf0Spatrick                             cast<ConstantInt>(Op2)->getZExtValue());
643373471bf0Spatrick     if (ScaledOne.isNonNegative() && match(Op1, m_SpecificInt(ScaledOne)))
643473471bf0Spatrick       return Op0;
643573471bf0Spatrick 
643673471bf0Spatrick     return nullptr;
643773471bf0Spatrick   }
6438*d415bd75Srobert   case Intrinsic::vector_insert: {
643973471bf0Spatrick     Value *Vec = Call->getArgOperand(0);
644073471bf0Spatrick     Value *SubVec = Call->getArgOperand(1);
644173471bf0Spatrick     Value *Idx = Call->getArgOperand(2);
644273471bf0Spatrick     Type *ReturnType = F->getReturnType();
644373471bf0Spatrick 
644473471bf0Spatrick     // (insert_vector Y, (extract_vector X, 0), 0) -> X
644573471bf0Spatrick     // where: Y is X, or Y is undef
644673471bf0Spatrick     unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
644773471bf0Spatrick     Value *X = nullptr;
6448*d415bd75Srobert     if (match(SubVec,
6449*d415bd75Srobert               m_Intrinsic<Intrinsic::vector_extract>(m_Value(X), m_Zero())) &&
645073471bf0Spatrick         (Q.isUndefValue(Vec) || Vec == X) && IdxN == 0 &&
645173471bf0Spatrick         X->getType() == ReturnType)
645273471bf0Spatrick       return X;
645373471bf0Spatrick 
645473471bf0Spatrick     return nullptr;
645573471bf0Spatrick   }
645673471bf0Spatrick   case Intrinsic::experimental_constrained_fadd: {
645773471bf0Spatrick     auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
6458*d415bd75Srobert     return simplifyFAddInst(
6459*d415bd75Srobert         FPI->getArgOperand(0), FPI->getArgOperand(1), FPI->getFastMathFlags(),
6460*d415bd75Srobert         Q, *FPI->getExceptionBehavior(), *FPI->getRoundingMode());
646173471bf0Spatrick   }
646273471bf0Spatrick   case Intrinsic::experimental_constrained_fsub: {
646373471bf0Spatrick     auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
6464*d415bd75Srobert     return simplifyFSubInst(
6465*d415bd75Srobert         FPI->getArgOperand(0), FPI->getArgOperand(1), FPI->getFastMathFlags(),
6466*d415bd75Srobert         Q, *FPI->getExceptionBehavior(), *FPI->getRoundingMode());
646773471bf0Spatrick   }
646873471bf0Spatrick   case Intrinsic::experimental_constrained_fmul: {
646973471bf0Spatrick     auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
6470*d415bd75Srobert     return simplifyFMulInst(
6471*d415bd75Srobert         FPI->getArgOperand(0), FPI->getArgOperand(1), FPI->getFastMathFlags(),
6472*d415bd75Srobert         Q, *FPI->getExceptionBehavior(), *FPI->getRoundingMode());
647373471bf0Spatrick   }
647473471bf0Spatrick   case Intrinsic::experimental_constrained_fdiv: {
647573471bf0Spatrick     auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
6476*d415bd75Srobert     return simplifyFDivInst(
6477*d415bd75Srobert         FPI->getArgOperand(0), FPI->getArgOperand(1), FPI->getFastMathFlags(),
6478*d415bd75Srobert         Q, *FPI->getExceptionBehavior(), *FPI->getRoundingMode());
647973471bf0Spatrick   }
648073471bf0Spatrick   case Intrinsic::experimental_constrained_frem: {
648173471bf0Spatrick     auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
6482*d415bd75Srobert     return simplifyFRemInst(
6483*d415bd75Srobert         FPI->getArgOperand(0), FPI->getArgOperand(1), FPI->getFastMathFlags(),
6484*d415bd75Srobert         Q, *FPI->getExceptionBehavior(), *FPI->getRoundingMode());
648573471bf0Spatrick   }
648609467b48Spatrick   default:
648709467b48Spatrick     return nullptr;
648809467b48Spatrick   }
648909467b48Spatrick }
649009467b48Spatrick 
tryConstantFoldCall(CallBase * Call,const SimplifyQuery & Q)649173471bf0Spatrick static Value *tryConstantFoldCall(CallBase *Call, const SimplifyQuery &Q) {
649273471bf0Spatrick   auto *F = dyn_cast<Function>(Call->getCalledOperand());
649373471bf0Spatrick   if (!F || !canConstantFoldCallTo(Call, F))
649409467b48Spatrick     return nullptr;
649509467b48Spatrick 
649609467b48Spatrick   SmallVector<Constant *, 4> ConstantArgs;
6497*d415bd75Srobert   unsigned NumArgs = Call->arg_size();
649809467b48Spatrick   ConstantArgs.reserve(NumArgs);
649909467b48Spatrick   for (auto &Arg : Call->args()) {
650009467b48Spatrick     Constant *C = dyn_cast<Constant>(&Arg);
6501097a140dSpatrick     if (!C) {
6502097a140dSpatrick       if (isa<MetadataAsValue>(Arg.get()))
6503097a140dSpatrick         continue;
650409467b48Spatrick       return nullptr;
6505097a140dSpatrick     }
650609467b48Spatrick     ConstantArgs.push_back(C);
650709467b48Spatrick   }
650809467b48Spatrick 
650909467b48Spatrick   return ConstantFoldCall(Call, F, ConstantArgs, Q.TLI);
651009467b48Spatrick }
651109467b48Spatrick 
simplifyCall(CallBase * Call,const SimplifyQuery & Q)6512*d415bd75Srobert Value *llvm::simplifyCall(CallBase *Call, const SimplifyQuery &Q) {
651373471bf0Spatrick   // musttail calls can only be simplified if they are also DCEd.
651473471bf0Spatrick   // As we can't guarantee this here, don't simplify them.
651573471bf0Spatrick   if (Call->isMustTailCall())
651673471bf0Spatrick     return nullptr;
651773471bf0Spatrick 
651873471bf0Spatrick   // call undef -> poison
651973471bf0Spatrick   // call null -> poison
652073471bf0Spatrick   Value *Callee = Call->getCalledOperand();
652173471bf0Spatrick   if (isa<UndefValue>(Callee) || isa<ConstantPointerNull>(Callee))
652273471bf0Spatrick     return PoisonValue::get(Call->getType());
652373471bf0Spatrick 
652473471bf0Spatrick   if (Value *V = tryConstantFoldCall(Call, Q))
652573471bf0Spatrick     return V;
652673471bf0Spatrick 
652773471bf0Spatrick   auto *F = dyn_cast<Function>(Callee);
652873471bf0Spatrick   if (F && F->isIntrinsic())
652973471bf0Spatrick     if (Value *Ret = simplifyIntrinsic(Call, Q))
653073471bf0Spatrick       return Ret;
653173471bf0Spatrick 
653273471bf0Spatrick   return nullptr;
653373471bf0Spatrick }
653473471bf0Spatrick 
simplifyConstrainedFPCall(CallBase * Call,const SimplifyQuery & Q)6535*d415bd75Srobert Value *llvm::simplifyConstrainedFPCall(CallBase *Call, const SimplifyQuery &Q) {
6536*d415bd75Srobert   assert(isa<ConstrainedFPIntrinsic>(Call));
6537*d415bd75Srobert   if (Value *V = tryConstantFoldCall(Call, Q))
6538*d415bd75Srobert     return V;
6539*d415bd75Srobert   if (Value *Ret = simplifyIntrinsic(Call, Q))
6540*d415bd75Srobert     return Ret;
6541*d415bd75Srobert   return nullptr;
6542*d415bd75Srobert }
6543*d415bd75Srobert 
654409467b48Spatrick /// Given operands for a Freeze, see if we can fold the result.
simplifyFreezeInst(Value * Op0,const SimplifyQuery & Q)6545*d415bd75Srobert static Value *simplifyFreezeInst(Value *Op0, const SimplifyQuery &Q) {
654609467b48Spatrick   // Use a utility function defined in ValueTracking.
654773471bf0Spatrick   if (llvm::isGuaranteedNotToBeUndefOrPoison(Op0, Q.AC, Q.CxtI, Q.DT))
654809467b48Spatrick     return Op0;
654909467b48Spatrick   // We have room for improvement.
655009467b48Spatrick   return nullptr;
655109467b48Spatrick }
655209467b48Spatrick 
simplifyFreezeInst(Value * Op0,const SimplifyQuery & Q)6553*d415bd75Srobert Value *llvm::simplifyFreezeInst(Value *Op0, const SimplifyQuery &Q) {
6554*d415bd75Srobert   return ::simplifyFreezeInst(Op0, Q);
655509467b48Spatrick }
655609467b48Spatrick 
simplifyLoadInst(LoadInst * LI,Value * PtrOp,const SimplifyQuery & Q)6557*d415bd75Srobert static Value *simplifyLoadInst(LoadInst *LI, Value *PtrOp,
655873471bf0Spatrick                                const SimplifyQuery &Q) {
655973471bf0Spatrick   if (LI->isVolatile())
656073471bf0Spatrick     return nullptr;
656173471bf0Spatrick 
6562*d415bd75Srobert   APInt Offset(Q.DL.getIndexTypeSizeInBits(PtrOp->getType()), 0);
656373471bf0Spatrick   auto *PtrOpC = dyn_cast<Constant>(PtrOp);
6564*d415bd75Srobert   // Try to convert operand into a constant by stripping offsets while looking
6565*d415bd75Srobert   // through invariant.group intrinsics. Don't bother if the underlying object
6566*d415bd75Srobert   // is not constant, as calculating GEP offsets is expensive.
6567*d415bd75Srobert   if (!PtrOpC && isa<Constant>(getUnderlyingObject(PtrOp))) {
6568*d415bd75Srobert     PtrOp = PtrOp->stripAndAccumulateConstantOffsets(
6569*d415bd75Srobert         Q.DL, Offset, /* AllowNonInbounts */ true,
6570*d415bd75Srobert         /* AllowInvariantGroup */ true);
6571*d415bd75Srobert     // Index size may have changed due to address space casts.
6572*d415bd75Srobert     Offset = Offset.sextOrTrunc(Q.DL.getIndexTypeSizeInBits(PtrOp->getType()));
6573*d415bd75Srobert     PtrOpC = dyn_cast<Constant>(PtrOp);
6574*d415bd75Srobert   }
657573471bf0Spatrick 
657673471bf0Spatrick   if (PtrOpC)
6577*d415bd75Srobert     return ConstantFoldLoadFromConstPtr(PtrOpC, LI->getType(), Offset, Q.DL);
657873471bf0Spatrick   return nullptr;
657973471bf0Spatrick }
658073471bf0Spatrick 
658109467b48Spatrick /// See if we can compute a simplified version of this instruction.
658209467b48Spatrick /// If not, this returns null.
658309467b48Spatrick 
simplifyInstructionWithOperands(Instruction * I,ArrayRef<Value * > NewOps,const SimplifyQuery & SQ,OptimizationRemarkEmitter * ORE)658473471bf0Spatrick static Value *simplifyInstructionWithOperands(Instruction *I,
658573471bf0Spatrick                                               ArrayRef<Value *> NewOps,
658673471bf0Spatrick                                               const SimplifyQuery &SQ,
658709467b48Spatrick                                               OptimizationRemarkEmitter *ORE) {
658809467b48Spatrick   const SimplifyQuery Q = SQ.CxtI ? SQ : SQ.getWithInstruction(I);
658909467b48Spatrick 
659009467b48Spatrick   switch (I->getOpcode()) {
659109467b48Spatrick   default:
659273471bf0Spatrick     if (llvm::all_of(NewOps, [](Value *V) { return isa<Constant>(V); })) {
659373471bf0Spatrick       SmallVector<Constant *, 8> NewConstOps(NewOps.size());
659473471bf0Spatrick       transform(NewOps, NewConstOps.begin(),
659573471bf0Spatrick                 [](Value *V) { return cast<Constant>(V); });
6596*d415bd75Srobert       return ConstantFoldInstOperands(I, NewConstOps, Q.DL, Q.TLI);
659773471bf0Spatrick     }
6598*d415bd75Srobert     return nullptr;
659909467b48Spatrick   case Instruction::FNeg:
6600*d415bd75Srobert     return simplifyFNegInst(NewOps[0], I->getFastMathFlags(), Q);
660109467b48Spatrick   case Instruction::FAdd:
6602*d415bd75Srobert     return simplifyFAddInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q);
660309467b48Spatrick   case Instruction::Add:
6604*d415bd75Srobert     return simplifyAddInst(NewOps[0], NewOps[1],
6605*d415bd75Srobert                            Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
660609467b48Spatrick                            Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q);
660709467b48Spatrick   case Instruction::FSub:
6608*d415bd75Srobert     return simplifyFSubInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q);
660909467b48Spatrick   case Instruction::Sub:
6610*d415bd75Srobert     return simplifySubInst(NewOps[0], NewOps[1],
6611*d415bd75Srobert                            Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
661209467b48Spatrick                            Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q);
661309467b48Spatrick   case Instruction::FMul:
6614*d415bd75Srobert     return simplifyFMulInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q);
661509467b48Spatrick   case Instruction::Mul:
6616*d415bd75Srobert     return simplifyMulInst(NewOps[0], NewOps[1],
6617*d415bd75Srobert                            Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
661809467b48Spatrick                            Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q);
6619*d415bd75Srobert   case Instruction::SDiv:
6620*d415bd75Srobert     return simplifySDivInst(NewOps[0], NewOps[1],
6621*d415bd75Srobert                             Q.IIQ.isExact(cast<BinaryOperator>(I)), Q);
6622*d415bd75Srobert   case Instruction::UDiv:
6623*d415bd75Srobert     return simplifyUDivInst(NewOps[0], NewOps[1],
6624*d415bd75Srobert                             Q.IIQ.isExact(cast<BinaryOperator>(I)), Q);
6625*d415bd75Srobert   case Instruction::FDiv:
6626*d415bd75Srobert     return simplifyFDivInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q);
6627*d415bd75Srobert   case Instruction::SRem:
6628*d415bd75Srobert     return simplifySRemInst(NewOps[0], NewOps[1], Q);
6629*d415bd75Srobert   case Instruction::URem:
6630*d415bd75Srobert     return simplifyURemInst(NewOps[0], NewOps[1], Q);
6631*d415bd75Srobert   case Instruction::FRem:
6632*d415bd75Srobert     return simplifyFRemInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q);
6633*d415bd75Srobert   case Instruction::Shl:
6634*d415bd75Srobert     return simplifyShlInst(NewOps[0], NewOps[1],
6635*d415bd75Srobert                            Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
6636*d415bd75Srobert                            Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q);
663709467b48Spatrick   case Instruction::LShr:
6638*d415bd75Srobert     return simplifyLShrInst(NewOps[0], NewOps[1],
663909467b48Spatrick                             Q.IIQ.isExact(cast<BinaryOperator>(I)), Q);
664009467b48Spatrick   case Instruction::AShr:
6641*d415bd75Srobert     return simplifyAShrInst(NewOps[0], NewOps[1],
664209467b48Spatrick                             Q.IIQ.isExact(cast<BinaryOperator>(I)), Q);
664309467b48Spatrick   case Instruction::And:
6644*d415bd75Srobert     return simplifyAndInst(NewOps[0], NewOps[1], Q);
664509467b48Spatrick   case Instruction::Or:
6646*d415bd75Srobert     return simplifyOrInst(NewOps[0], NewOps[1], Q);
664709467b48Spatrick   case Instruction::Xor:
6648*d415bd75Srobert     return simplifyXorInst(NewOps[0], NewOps[1], Q);
664909467b48Spatrick   case Instruction::ICmp:
6650*d415bd75Srobert     return simplifyICmpInst(cast<ICmpInst>(I)->getPredicate(), NewOps[0],
665173471bf0Spatrick                             NewOps[1], Q);
665209467b48Spatrick   case Instruction::FCmp:
6653*d415bd75Srobert     return simplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(), NewOps[0],
665473471bf0Spatrick                             NewOps[1], I->getFastMathFlags(), Q);
665509467b48Spatrick   case Instruction::Select:
6656*d415bd75Srobert     return simplifySelectInst(NewOps[0], NewOps[1], NewOps[2], Q);
665709467b48Spatrick     break;
665809467b48Spatrick   case Instruction::GetElementPtr: {
6659*d415bd75Srobert     auto *GEPI = cast<GetElementPtrInst>(I);
6660*d415bd75Srobert     return simplifyGEPInst(GEPI->getSourceElementType(), NewOps[0],
6661*d415bd75Srobert                            ArrayRef(NewOps).slice(1), GEPI->isInBounds(), Q);
666209467b48Spatrick   }
666309467b48Spatrick   case Instruction::InsertValue: {
666409467b48Spatrick     InsertValueInst *IV = cast<InsertValueInst>(I);
6665*d415bd75Srobert     return simplifyInsertValueInst(NewOps[0], NewOps[1], IV->getIndices(), Q);
666609467b48Spatrick   }
6667*d415bd75Srobert   case Instruction::InsertElement:
6668*d415bd75Srobert     return simplifyInsertElementInst(NewOps[0], NewOps[1], NewOps[2], Q);
666909467b48Spatrick   case Instruction::ExtractValue: {
667009467b48Spatrick     auto *EVI = cast<ExtractValueInst>(I);
6671*d415bd75Srobert     return simplifyExtractValueInst(NewOps[0], EVI->getIndices(), Q);
667209467b48Spatrick   }
6673*d415bd75Srobert   case Instruction::ExtractElement:
6674*d415bd75Srobert     return simplifyExtractElementInst(NewOps[0], NewOps[1], Q);
667509467b48Spatrick   case Instruction::ShuffleVector: {
667609467b48Spatrick     auto *SVI = cast<ShuffleVectorInst>(I);
6677*d415bd75Srobert     return simplifyShuffleVectorInst(NewOps[0], NewOps[1],
6678*d415bd75Srobert                                      SVI->getShuffleMask(), SVI->getType(), Q);
667909467b48Spatrick   }
668009467b48Spatrick   case Instruction::PHI:
6681*d415bd75Srobert     return simplifyPHINode(cast<PHINode>(I), NewOps, Q);
6682*d415bd75Srobert   case Instruction::Call:
668373471bf0Spatrick     // TODO: Use NewOps
6684*d415bd75Srobert     return simplifyCall(cast<CallInst>(I), Q);
668509467b48Spatrick   case Instruction::Freeze:
6686*d415bd75Srobert     return llvm::simplifyFreezeInst(NewOps[0], Q);
668709467b48Spatrick #define HANDLE_CAST_INST(num, opc, clas) case Instruction::opc:
668809467b48Spatrick #include "llvm/IR/Instruction.def"
668909467b48Spatrick #undef HANDLE_CAST_INST
6690*d415bd75Srobert     return simplifyCastInst(I->getOpcode(), NewOps[0], I->getType(), Q);
669109467b48Spatrick   case Instruction::Alloca:
669209467b48Spatrick     // No simplifications for Alloca and it can't be constant folded.
6693*d415bd75Srobert     return nullptr;
669473471bf0Spatrick   case Instruction::Load:
6695*d415bd75Srobert     return simplifyLoadInst(cast<LoadInst>(I), NewOps[0], Q);
6696*d415bd75Srobert   }
669709467b48Spatrick }
669809467b48Spatrick 
simplifyInstructionWithOperands(Instruction * I,ArrayRef<Value * > NewOps,const SimplifyQuery & SQ,OptimizationRemarkEmitter * ORE)6699*d415bd75Srobert Value *llvm::simplifyInstructionWithOperands(Instruction *I,
670073471bf0Spatrick                                              ArrayRef<Value *> NewOps,
670173471bf0Spatrick                                              const SimplifyQuery &SQ,
670273471bf0Spatrick                                              OptimizationRemarkEmitter *ORE) {
670373471bf0Spatrick   assert(NewOps.size() == I->getNumOperands() &&
670473471bf0Spatrick          "Number of operands should match the instruction!");
670573471bf0Spatrick   return ::simplifyInstructionWithOperands(I, NewOps, SQ, ORE);
670673471bf0Spatrick }
670773471bf0Spatrick 
simplifyInstruction(Instruction * I,const SimplifyQuery & SQ,OptimizationRemarkEmitter * ORE)6708*d415bd75Srobert Value *llvm::simplifyInstruction(Instruction *I, const SimplifyQuery &SQ,
670973471bf0Spatrick                                  OptimizationRemarkEmitter *ORE) {
671073471bf0Spatrick   SmallVector<Value *, 8> Ops(I->operands());
6711*d415bd75Srobert   Value *Result = ::simplifyInstructionWithOperands(I, Ops, SQ, ORE);
6712*d415bd75Srobert 
6713*d415bd75Srobert   /// If called on unreachable code, the instruction may simplify to itself.
6714*d415bd75Srobert   /// Make life easier for users by detecting that case here, and returning a
6715*d415bd75Srobert   /// safe value instead.
6716*d415bd75Srobert   return Result == I ? UndefValue::get(I->getType()) : Result;
671773471bf0Spatrick }
671873471bf0Spatrick 
671909467b48Spatrick /// Implementation of recursive simplification through an instruction's
672009467b48Spatrick /// uses.
672109467b48Spatrick ///
672209467b48Spatrick /// This is the common implementation of the recursive simplification routines.
672309467b48Spatrick /// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
672409467b48Spatrick /// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
672509467b48Spatrick /// instructions to process and attempt to simplify it using
672609467b48Spatrick /// InstructionSimplify. Recursively visited users which could not be
672709467b48Spatrick /// simplified themselves are to the optional UnsimplifiedUsers set for
672809467b48Spatrick /// further processing by the caller.
672909467b48Spatrick ///
673009467b48Spatrick /// This routine returns 'true' only when *it* simplifies something. The passed
673109467b48Spatrick /// in simplified value does not count toward this.
replaceAndRecursivelySimplifyImpl(Instruction * I,Value * SimpleV,const TargetLibraryInfo * TLI,const DominatorTree * DT,AssumptionCache * AC,SmallSetVector<Instruction *,8> * UnsimplifiedUsers=nullptr)673209467b48Spatrick static bool replaceAndRecursivelySimplifyImpl(
673309467b48Spatrick     Instruction *I, Value *SimpleV, const TargetLibraryInfo *TLI,
673409467b48Spatrick     const DominatorTree *DT, AssumptionCache *AC,
673509467b48Spatrick     SmallSetVector<Instruction *, 8> *UnsimplifiedUsers = nullptr) {
673609467b48Spatrick   bool Simplified = false;
673709467b48Spatrick   SmallSetVector<Instruction *, 8> Worklist;
673809467b48Spatrick   const DataLayout &DL = I->getModule()->getDataLayout();
673909467b48Spatrick 
674009467b48Spatrick   // If we have an explicit value to collapse to, do that round of the
674109467b48Spatrick   // simplification loop by hand initially.
674209467b48Spatrick   if (SimpleV) {
674309467b48Spatrick     for (User *U : I->users())
674409467b48Spatrick       if (U != I)
674509467b48Spatrick         Worklist.insert(cast<Instruction>(U));
674609467b48Spatrick 
674709467b48Spatrick     // Replace the instruction with its simplified value.
674809467b48Spatrick     I->replaceAllUsesWith(SimpleV);
674909467b48Spatrick 
675009467b48Spatrick     // Gracefully handle edge cases where the instruction is not wired into any
675109467b48Spatrick     // parent block.
675209467b48Spatrick     if (I->getParent() && !I->isEHPad() && !I->isTerminator() &&
675309467b48Spatrick         !I->mayHaveSideEffects())
675409467b48Spatrick       I->eraseFromParent();
675509467b48Spatrick   } else {
675609467b48Spatrick     Worklist.insert(I);
675709467b48Spatrick   }
675809467b48Spatrick 
675909467b48Spatrick   // Note that we must test the size on each iteration, the worklist can grow.
676009467b48Spatrick   for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
676109467b48Spatrick     I = Worklist[Idx];
676209467b48Spatrick 
676309467b48Spatrick     // See if this instruction simplifies.
6764*d415bd75Srobert     SimpleV = simplifyInstruction(I, {DL, TLI, DT, AC});
676509467b48Spatrick     if (!SimpleV) {
676609467b48Spatrick       if (UnsimplifiedUsers)
676709467b48Spatrick         UnsimplifiedUsers->insert(I);
676809467b48Spatrick       continue;
676909467b48Spatrick     }
677009467b48Spatrick 
677109467b48Spatrick     Simplified = true;
677209467b48Spatrick 
677309467b48Spatrick     // Stash away all the uses of the old instruction so we can check them for
677409467b48Spatrick     // recursive simplifications after a RAUW. This is cheaper than checking all
677509467b48Spatrick     // uses of To on the recursive step in most cases.
677609467b48Spatrick     for (User *U : I->users())
677709467b48Spatrick       Worklist.insert(cast<Instruction>(U));
677809467b48Spatrick 
677909467b48Spatrick     // Replace the instruction with its simplified value.
678009467b48Spatrick     I->replaceAllUsesWith(SimpleV);
678109467b48Spatrick 
678209467b48Spatrick     // Gracefully handle edge cases where the instruction is not wired into any
678309467b48Spatrick     // parent block.
678409467b48Spatrick     if (I->getParent() && !I->isEHPad() && !I->isTerminator() &&
678509467b48Spatrick         !I->mayHaveSideEffects())
678609467b48Spatrick       I->eraseFromParent();
678709467b48Spatrick   }
678809467b48Spatrick   return Simplified;
678909467b48Spatrick }
679009467b48Spatrick 
replaceAndRecursivelySimplify(Instruction * I,Value * SimpleV,const TargetLibraryInfo * TLI,const DominatorTree * DT,AssumptionCache * AC,SmallSetVector<Instruction *,8> * UnsimplifiedUsers)679109467b48Spatrick bool llvm::replaceAndRecursivelySimplify(
679209467b48Spatrick     Instruction *I, Value *SimpleV, const TargetLibraryInfo *TLI,
679309467b48Spatrick     const DominatorTree *DT, AssumptionCache *AC,
679409467b48Spatrick     SmallSetVector<Instruction *, 8> *UnsimplifiedUsers) {
679509467b48Spatrick   assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
679609467b48Spatrick   assert(SimpleV && "Must provide a simplified value.");
679709467b48Spatrick   return replaceAndRecursivelySimplifyImpl(I, SimpleV, TLI, DT, AC,
679809467b48Spatrick                                            UnsimplifiedUsers);
679909467b48Spatrick }
680009467b48Spatrick 
680109467b48Spatrick namespace llvm {
getBestSimplifyQuery(Pass & P,Function & F)680209467b48Spatrick const SimplifyQuery getBestSimplifyQuery(Pass &P, Function &F) {
680309467b48Spatrick   auto *DTWP = P.getAnalysisIfAvailable<DominatorTreeWrapperPass>();
680409467b48Spatrick   auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
680509467b48Spatrick   auto *TLIWP = P.getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
680609467b48Spatrick   auto *TLI = TLIWP ? &TLIWP->getTLI(F) : nullptr;
680709467b48Spatrick   auto *ACWP = P.getAnalysisIfAvailable<AssumptionCacheTracker>();
680809467b48Spatrick   auto *AC = ACWP ? &ACWP->getAssumptionCache(F) : nullptr;
680909467b48Spatrick   return {F.getParent()->getDataLayout(), TLI, DT, AC};
681009467b48Spatrick }
681109467b48Spatrick 
getBestSimplifyQuery(LoopStandardAnalysisResults & AR,const DataLayout & DL)681209467b48Spatrick const SimplifyQuery getBestSimplifyQuery(LoopStandardAnalysisResults &AR,
681309467b48Spatrick                                          const DataLayout &DL) {
681409467b48Spatrick   return {DL, &AR.TLI, &AR.DT, &AR.AC};
681509467b48Spatrick }
681609467b48Spatrick 
681709467b48Spatrick template <class T, class... TArgs>
getBestSimplifyQuery(AnalysisManager<T,TArgs...> & AM,Function & F)681809467b48Spatrick const SimplifyQuery getBestSimplifyQuery(AnalysisManager<T, TArgs...> &AM,
681909467b48Spatrick                                          Function &F) {
682009467b48Spatrick   auto *DT = AM.template getCachedResult<DominatorTreeAnalysis>(F);
682109467b48Spatrick   auto *TLI = AM.template getCachedResult<TargetLibraryAnalysis>(F);
682209467b48Spatrick   auto *AC = AM.template getCachedResult<AssumptionAnalysis>(F);
682309467b48Spatrick   return {F.getParent()->getDataLayout(), TLI, DT, AC};
682409467b48Spatrick }
682509467b48Spatrick template const SimplifyQuery getBestSimplifyQuery(AnalysisManager<Function> &,
682609467b48Spatrick                                                   Function &);
6827*d415bd75Srobert } // namespace llvm
6828*d415bd75Srobert 
anchor()6829*d415bd75Srobert void InstSimplifyFolder::anchor() {}
6830