10b57cec5SDimitry Andric //===- InstCombineAndOrXor.cpp --------------------------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file implements the visitAnd, visitOr, and visitXor functions.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric 
130b57cec5SDimitry Andric #include "InstCombineInternal.h"
140b57cec5SDimitry Andric #include "llvm/Analysis/CmpInstAnalysis.h"
150b57cec5SDimitry Andric #include "llvm/Analysis/InstructionSimplify.h"
160b57cec5SDimitry Andric #include "llvm/IR/ConstantRange.h"
170b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h"
180b57cec5SDimitry Andric #include "llvm/IR/PatternMatch.h"
19e8d8bef9SDimitry Andric #include "llvm/Transforms/InstCombine/InstCombiner.h"
20e8d8bef9SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
21e8d8bef9SDimitry Andric 
220b57cec5SDimitry Andric using namespace llvm;
230b57cec5SDimitry Andric using namespace PatternMatch;
240b57cec5SDimitry Andric 
250b57cec5SDimitry Andric #define DEBUG_TYPE "instcombine"
260b57cec5SDimitry Andric 
270b57cec5SDimitry Andric /// This is the complement of getICmpCode, which turns an opcode and two
280b57cec5SDimitry Andric /// operands into either a constant true or false, or a brand new ICmp
290b57cec5SDimitry Andric /// instruction. The sign is passed in to determine which kind of predicate to
300b57cec5SDimitry Andric /// use in the new icmp instruction.
getNewICmpValue(unsigned Code,bool Sign,Value * LHS,Value * RHS,InstCombiner::BuilderTy & Builder)310b57cec5SDimitry Andric static Value *getNewICmpValue(unsigned Code, bool Sign, Value *LHS, Value *RHS,
320b57cec5SDimitry Andric                               InstCombiner::BuilderTy &Builder) {
330b57cec5SDimitry Andric   ICmpInst::Predicate NewPred;
340b57cec5SDimitry Andric   if (Constant *TorF = getPredForICmpCode(Code, Sign, LHS->getType(), NewPred))
350b57cec5SDimitry Andric     return TorF;
360b57cec5SDimitry Andric   return Builder.CreateICmp(NewPred, LHS, RHS);
370b57cec5SDimitry Andric }
380b57cec5SDimitry Andric 
390b57cec5SDimitry Andric /// This is the complement of getFCmpCode, which turns an opcode and two
400b57cec5SDimitry Andric /// operands into either a FCmp instruction, or a true/false constant.
getFCmpValue(unsigned Code,Value * LHS,Value * RHS,InstCombiner::BuilderTy & Builder)410b57cec5SDimitry Andric static Value *getFCmpValue(unsigned Code, Value *LHS, Value *RHS,
420b57cec5SDimitry Andric                            InstCombiner::BuilderTy &Builder) {
4381ad6265SDimitry Andric   FCmpInst::Predicate NewPred;
4481ad6265SDimitry Andric   if (Constant *TorF = getPredForFCmpCode(Code, LHS->getType(), NewPred))
4581ad6265SDimitry Andric     return TorF;
4681ad6265SDimitry Andric   return Builder.CreateFCmp(NewPred, LHS, RHS);
470b57cec5SDimitry Andric }
480b57cec5SDimitry Andric 
490b57cec5SDimitry Andric /// Emit a computation of: (V >= Lo && V < Hi) if Inside is true, otherwise
508bcb0991SDimitry Andric /// (V < Lo || V >= Hi). This method expects that Lo < Hi. IsSigned indicates
510b57cec5SDimitry Andric /// whether to treat V, Lo, and Hi as signed or not.
insertRangeTest(Value * V,const APInt & Lo,const APInt & Hi,bool isSigned,bool Inside)52e8d8bef9SDimitry Andric Value *InstCombinerImpl::insertRangeTest(Value *V, const APInt &Lo,
53e8d8bef9SDimitry Andric                                          const APInt &Hi, bool isSigned,
54e8d8bef9SDimitry Andric                                          bool Inside) {
558bcb0991SDimitry Andric   assert((isSigned ? Lo.slt(Hi) : Lo.ult(Hi)) &&
568bcb0991SDimitry Andric          "Lo is not < Hi in range emission code!");
570b57cec5SDimitry Andric 
580b57cec5SDimitry Andric   Type *Ty = V->getType();
590b57cec5SDimitry Andric 
600b57cec5SDimitry Andric   // V >= Min && V <  Hi --> V <  Hi
610b57cec5SDimitry Andric   // V <  Min || V >= Hi --> V >= Hi
620b57cec5SDimitry Andric   ICmpInst::Predicate Pred = Inside ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_UGE;
630b57cec5SDimitry Andric   if (isSigned ? Lo.isMinSignedValue() : Lo.isMinValue()) {
640b57cec5SDimitry Andric     Pred = isSigned ? ICmpInst::getSignedPredicate(Pred) : Pred;
650b57cec5SDimitry Andric     return Builder.CreateICmp(Pred, V, ConstantInt::get(Ty, Hi));
660b57cec5SDimitry Andric   }
670b57cec5SDimitry Andric 
680b57cec5SDimitry Andric   // V >= Lo && V <  Hi --> V - Lo u<  Hi - Lo
690b57cec5SDimitry Andric   // V <  Lo || V >= Hi --> V - Lo u>= Hi - Lo
700b57cec5SDimitry Andric   Value *VMinusLo =
710b57cec5SDimitry Andric       Builder.CreateSub(V, ConstantInt::get(Ty, Lo), V->getName() + ".off");
720b57cec5SDimitry Andric   Constant *HiMinusLo = ConstantInt::get(Ty, Hi - Lo);
730b57cec5SDimitry Andric   return Builder.CreateICmp(Pred, VMinusLo, HiMinusLo);
740b57cec5SDimitry Andric }
750b57cec5SDimitry Andric 
760b57cec5SDimitry Andric /// Classify (icmp eq (A & B), C) and (icmp ne (A & B), C) as matching patterns
770b57cec5SDimitry Andric /// that can be simplified.
780b57cec5SDimitry Andric /// One of A and B is considered the mask. The other is the value. This is
790b57cec5SDimitry Andric /// described as the "AMask" or "BMask" part of the enum. If the enum contains
800b57cec5SDimitry Andric /// only "Mask", then both A and B can be considered masks. If A is the mask,
810b57cec5SDimitry Andric /// then it was proven that (A & C) == C. This is trivial if C == A or C == 0.
820b57cec5SDimitry Andric /// If both A and C are constants, this proof is also easy.
830b57cec5SDimitry Andric /// For the following explanations, we assume that A is the mask.
840b57cec5SDimitry Andric ///
850b57cec5SDimitry Andric /// "AllOnes" declares that the comparison is true only if (A & B) == A or all
860b57cec5SDimitry Andric /// bits of A are set in B.
870b57cec5SDimitry Andric ///   Example: (icmp eq (A & 3), 3) -> AMask_AllOnes
880b57cec5SDimitry Andric ///
890b57cec5SDimitry Andric /// "AllZeros" declares that the comparison is true only if (A & B) == 0 or all
900b57cec5SDimitry Andric /// bits of A are cleared in B.
910b57cec5SDimitry Andric ///   Example: (icmp eq (A & 3), 0) -> Mask_AllZeroes
920b57cec5SDimitry Andric ///
930b57cec5SDimitry Andric /// "Mixed" declares that (A & B) == C and C might or might not contain any
940b57cec5SDimitry Andric /// number of one bits and zero bits.
950b57cec5SDimitry Andric ///   Example: (icmp eq (A & 3), 1) -> AMask_Mixed
960b57cec5SDimitry Andric ///
970b57cec5SDimitry Andric /// "Not" means that in above descriptions "==" should be replaced by "!=".
980b57cec5SDimitry Andric ///   Example: (icmp ne (A & 3), 3) -> AMask_NotAllOnes
990b57cec5SDimitry Andric ///
1000b57cec5SDimitry Andric /// If the mask A contains a single bit, then the following is equivalent:
1010b57cec5SDimitry Andric ///    (icmp eq (A & B), A) equals (icmp ne (A & B), 0)
1020b57cec5SDimitry Andric ///    (icmp ne (A & B), A) equals (icmp eq (A & B), 0)
1030b57cec5SDimitry Andric enum MaskedICmpType {
1040b57cec5SDimitry Andric   AMask_AllOnes           =     1,
1050b57cec5SDimitry Andric   AMask_NotAllOnes        =     2,
1060b57cec5SDimitry Andric   BMask_AllOnes           =     4,
1070b57cec5SDimitry Andric   BMask_NotAllOnes        =     8,
1080b57cec5SDimitry Andric   Mask_AllZeros           =    16,
1090b57cec5SDimitry Andric   Mask_NotAllZeros        =    32,
1100b57cec5SDimitry Andric   AMask_Mixed             =    64,
1110b57cec5SDimitry Andric   AMask_NotMixed          =   128,
1120b57cec5SDimitry Andric   BMask_Mixed             =   256,
1130b57cec5SDimitry Andric   BMask_NotMixed          =   512
1140b57cec5SDimitry Andric };
1150b57cec5SDimitry Andric 
1160b57cec5SDimitry Andric /// Return the set of patterns (from MaskedICmpType) that (icmp SCC (A & B), C)
1170b57cec5SDimitry Andric /// satisfies.
getMaskedICmpType(Value * A,Value * B,Value * C,ICmpInst::Predicate Pred)1180b57cec5SDimitry Andric static unsigned getMaskedICmpType(Value *A, Value *B, Value *C,
1190b57cec5SDimitry Andric                                   ICmpInst::Predicate Pred) {
120349cc55cSDimitry Andric   const APInt *ConstA = nullptr, *ConstB = nullptr, *ConstC = nullptr;
121349cc55cSDimitry Andric   match(A, m_APInt(ConstA));
122349cc55cSDimitry Andric   match(B, m_APInt(ConstB));
123349cc55cSDimitry Andric   match(C, m_APInt(ConstC));
1240b57cec5SDimitry Andric   bool IsEq = (Pred == ICmpInst::ICMP_EQ);
125349cc55cSDimitry Andric   bool IsAPow2 = ConstA && ConstA->isPowerOf2();
126349cc55cSDimitry Andric   bool IsBPow2 = ConstB && ConstB->isPowerOf2();
1270b57cec5SDimitry Andric   unsigned MaskVal = 0;
128349cc55cSDimitry Andric   if (ConstC && ConstC->isZero()) {
1290b57cec5SDimitry Andric     // if C is zero, then both A and B qualify as mask
1300b57cec5SDimitry Andric     MaskVal |= (IsEq ? (Mask_AllZeros | AMask_Mixed | BMask_Mixed)
1310b57cec5SDimitry Andric                      : (Mask_NotAllZeros | AMask_NotMixed | BMask_NotMixed));
1320b57cec5SDimitry Andric     if (IsAPow2)
1330b57cec5SDimitry Andric       MaskVal |= (IsEq ? (AMask_NotAllOnes | AMask_NotMixed)
1340b57cec5SDimitry Andric                        : (AMask_AllOnes | AMask_Mixed));
1350b57cec5SDimitry Andric     if (IsBPow2)
1360b57cec5SDimitry Andric       MaskVal |= (IsEq ? (BMask_NotAllOnes | BMask_NotMixed)
1370b57cec5SDimitry Andric                        : (BMask_AllOnes | BMask_Mixed));
1380b57cec5SDimitry Andric     return MaskVal;
1390b57cec5SDimitry Andric   }
1400b57cec5SDimitry Andric 
1410b57cec5SDimitry Andric   if (A == C) {
1420b57cec5SDimitry Andric     MaskVal |= (IsEq ? (AMask_AllOnes | AMask_Mixed)
1430b57cec5SDimitry Andric                      : (AMask_NotAllOnes | AMask_NotMixed));
1440b57cec5SDimitry Andric     if (IsAPow2)
1450b57cec5SDimitry Andric       MaskVal |= (IsEq ? (Mask_NotAllZeros | AMask_NotMixed)
1460b57cec5SDimitry Andric                        : (Mask_AllZeros | AMask_Mixed));
147349cc55cSDimitry Andric   } else if (ConstA && ConstC && ConstC->isSubsetOf(*ConstA)) {
1480b57cec5SDimitry Andric     MaskVal |= (IsEq ? AMask_Mixed : AMask_NotMixed);
1490b57cec5SDimitry Andric   }
1500b57cec5SDimitry Andric 
1510b57cec5SDimitry Andric   if (B == C) {
1520b57cec5SDimitry Andric     MaskVal |= (IsEq ? (BMask_AllOnes | BMask_Mixed)
1530b57cec5SDimitry Andric                      : (BMask_NotAllOnes | BMask_NotMixed));
1540b57cec5SDimitry Andric     if (IsBPow2)
1550b57cec5SDimitry Andric       MaskVal |= (IsEq ? (Mask_NotAllZeros | BMask_NotMixed)
1560b57cec5SDimitry Andric                        : (Mask_AllZeros | BMask_Mixed));
157349cc55cSDimitry Andric   } else if (ConstB && ConstC && ConstC->isSubsetOf(*ConstB)) {
1580b57cec5SDimitry Andric     MaskVal |= (IsEq ? BMask_Mixed : BMask_NotMixed);
1590b57cec5SDimitry Andric   }
1600b57cec5SDimitry Andric 
1610b57cec5SDimitry Andric   return MaskVal;
1620b57cec5SDimitry Andric }
1630b57cec5SDimitry Andric 
1640b57cec5SDimitry Andric /// Convert an analysis of a masked ICmp into its equivalent if all boolean
1650b57cec5SDimitry Andric /// operations had the opposite sense. Since each "NotXXX" flag (recording !=)
1660b57cec5SDimitry Andric /// is adjacent to the corresponding normal flag (recording ==), this just
1670b57cec5SDimitry Andric /// involves swapping those bits over.
conjugateICmpMask(unsigned Mask)1680b57cec5SDimitry Andric static unsigned conjugateICmpMask(unsigned Mask) {
1690b57cec5SDimitry Andric   unsigned NewMask;
1700b57cec5SDimitry Andric   NewMask = (Mask & (AMask_AllOnes | BMask_AllOnes | Mask_AllZeros |
1710b57cec5SDimitry Andric                      AMask_Mixed | BMask_Mixed))
1720b57cec5SDimitry Andric             << 1;
1730b57cec5SDimitry Andric 
1740b57cec5SDimitry Andric   NewMask |= (Mask & (AMask_NotAllOnes | BMask_NotAllOnes | Mask_NotAllZeros |
1750b57cec5SDimitry Andric                       AMask_NotMixed | BMask_NotMixed))
1760b57cec5SDimitry Andric              >> 1;
1770b57cec5SDimitry Andric 
1780b57cec5SDimitry Andric   return NewMask;
1790b57cec5SDimitry Andric }
1800b57cec5SDimitry Andric 
1810b57cec5SDimitry Andric // Adapts the external decomposeBitTestICmp for local use.
decomposeBitTestICmp(Value * LHS,Value * RHS,CmpInst::Predicate & Pred,Value * & X,Value * & Y,Value * & Z)1820b57cec5SDimitry Andric static bool decomposeBitTestICmp(Value *LHS, Value *RHS, CmpInst::Predicate &Pred,
1830b57cec5SDimitry Andric                                  Value *&X, Value *&Y, Value *&Z) {
1840b57cec5SDimitry Andric   APInt Mask;
1850b57cec5SDimitry Andric   if (!llvm::decomposeBitTestICmp(LHS, RHS, Pred, X, Mask))
1860b57cec5SDimitry Andric     return false;
1870b57cec5SDimitry Andric 
1880b57cec5SDimitry Andric   Y = ConstantInt::get(X->getType(), Mask);
1890b57cec5SDimitry Andric   Z = ConstantInt::get(X->getType(), 0);
1900b57cec5SDimitry Andric   return true;
1910b57cec5SDimitry Andric }
1920b57cec5SDimitry Andric 
1930b57cec5SDimitry Andric /// Handle (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E).
1940b57cec5SDimitry Andric /// Return the pattern classes (from MaskedICmpType) for the left hand side and
1950b57cec5SDimitry Andric /// the right hand side as a pair.
1960b57cec5SDimitry Andric /// LHS and RHS are the left hand side and the right hand side ICmps and PredL
1970b57cec5SDimitry Andric /// and PredR are their predicates, respectively.
getMaskedTypeForICmpPair(Value * & A,Value * & B,Value * & C,Value * & D,Value * & E,ICmpInst * LHS,ICmpInst * RHS,ICmpInst::Predicate & PredL,ICmpInst::Predicate & PredR)198bdd1243dSDimitry Andric static std::optional<std::pair<unsigned, unsigned>> getMaskedTypeForICmpPair(
199bdd1243dSDimitry Andric     Value *&A, Value *&B, Value *&C, Value *&D, Value *&E, ICmpInst *LHS,
200bdd1243dSDimitry Andric     ICmpInst *RHS, ICmpInst::Predicate &PredL, ICmpInst::Predicate &PredR) {
201349cc55cSDimitry Andric   // Don't allow pointers. Splat vectors are fine.
202349cc55cSDimitry Andric   if (!LHS->getOperand(0)->getType()->isIntOrIntVectorTy() ||
203349cc55cSDimitry Andric       !RHS->getOperand(0)->getType()->isIntOrIntVectorTy())
204bdd1243dSDimitry Andric     return std::nullopt;
2050b57cec5SDimitry Andric 
2060b57cec5SDimitry Andric   // Here comes the tricky part:
2070b57cec5SDimitry Andric   // LHS might be of the form L11 & L12 == X, X == L21 & L22,
2080b57cec5SDimitry Andric   // and L11 & L12 == L21 & L22. The same goes for RHS.
2090b57cec5SDimitry Andric   // Now we must find those components L** and R**, that are equal, so
2100b57cec5SDimitry Andric   // that we can extract the parameters A, B, C, D, and E for the canonical
2110b57cec5SDimitry Andric   // above.
2120b57cec5SDimitry Andric   Value *L1 = LHS->getOperand(0);
2130b57cec5SDimitry Andric   Value *L2 = LHS->getOperand(1);
2140b57cec5SDimitry Andric   Value *L11, *L12, *L21, *L22;
2150b57cec5SDimitry Andric   // Check whether the icmp can be decomposed into a bit test.
2160b57cec5SDimitry Andric   if (decomposeBitTestICmp(L1, L2, PredL, L11, L12, L2)) {
2170b57cec5SDimitry Andric     L21 = L22 = L1 = nullptr;
2180b57cec5SDimitry Andric   } else {
2190b57cec5SDimitry Andric     // Look for ANDs in the LHS icmp.
2200b57cec5SDimitry Andric     if (!match(L1, m_And(m_Value(L11), m_Value(L12)))) {
2210b57cec5SDimitry Andric       // Any icmp can be viewed as being trivially masked; if it allows us to
2220b57cec5SDimitry Andric       // remove one, it's worth it.
2230b57cec5SDimitry Andric       L11 = L1;
2240b57cec5SDimitry Andric       L12 = Constant::getAllOnesValue(L1->getType());
2250b57cec5SDimitry Andric     }
2260b57cec5SDimitry Andric 
2270b57cec5SDimitry Andric     if (!match(L2, m_And(m_Value(L21), m_Value(L22)))) {
2280b57cec5SDimitry Andric       L21 = L2;
2290b57cec5SDimitry Andric       L22 = Constant::getAllOnesValue(L2->getType());
2300b57cec5SDimitry Andric     }
2310b57cec5SDimitry Andric   }
2320b57cec5SDimitry Andric 
2330b57cec5SDimitry Andric   // Bail if LHS was a icmp that can't be decomposed into an equality.
2340b57cec5SDimitry Andric   if (!ICmpInst::isEquality(PredL))
235bdd1243dSDimitry Andric     return std::nullopt;
2360b57cec5SDimitry Andric 
2370b57cec5SDimitry Andric   Value *R1 = RHS->getOperand(0);
2380b57cec5SDimitry Andric   Value *R2 = RHS->getOperand(1);
2390b57cec5SDimitry Andric   Value *R11, *R12;
2400b57cec5SDimitry Andric   bool Ok = false;
2410b57cec5SDimitry Andric   if (decomposeBitTestICmp(R1, R2, PredR, R11, R12, R2)) {
2420b57cec5SDimitry Andric     if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
2430b57cec5SDimitry Andric       A = R11;
2440b57cec5SDimitry Andric       D = R12;
2450b57cec5SDimitry Andric     } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
2460b57cec5SDimitry Andric       A = R12;
2470b57cec5SDimitry Andric       D = R11;
2480b57cec5SDimitry Andric     } else {
249bdd1243dSDimitry Andric       return std::nullopt;
2500b57cec5SDimitry Andric     }
2510b57cec5SDimitry Andric     E = R2;
2520b57cec5SDimitry Andric     R1 = nullptr;
2530b57cec5SDimitry Andric     Ok = true;
2540b57cec5SDimitry Andric   } else {
2550b57cec5SDimitry Andric     if (!match(R1, m_And(m_Value(R11), m_Value(R12)))) {
2560b57cec5SDimitry Andric       // As before, model no mask as a trivial mask if it'll let us do an
2570b57cec5SDimitry Andric       // optimization.
2580b57cec5SDimitry Andric       R11 = R1;
2590b57cec5SDimitry Andric       R12 = Constant::getAllOnesValue(R1->getType());
2600b57cec5SDimitry Andric     }
2610b57cec5SDimitry Andric 
2620b57cec5SDimitry Andric     if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
2630b57cec5SDimitry Andric       A = R11;
2640b57cec5SDimitry Andric       D = R12;
2650b57cec5SDimitry Andric       E = R2;
2660b57cec5SDimitry Andric       Ok = true;
2670b57cec5SDimitry Andric     } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
2680b57cec5SDimitry Andric       A = R12;
2690b57cec5SDimitry Andric       D = R11;
2700b57cec5SDimitry Andric       E = R2;
2710b57cec5SDimitry Andric       Ok = true;
2720b57cec5SDimitry Andric     }
2730b57cec5SDimitry Andric   }
2740b57cec5SDimitry Andric 
2750b57cec5SDimitry Andric   // Bail if RHS was a icmp that can't be decomposed into an equality.
2760b57cec5SDimitry Andric   if (!ICmpInst::isEquality(PredR))
277bdd1243dSDimitry Andric     return std::nullopt;
2780b57cec5SDimitry Andric 
2790b57cec5SDimitry Andric   // Look for ANDs on the right side of the RHS icmp.
2800b57cec5SDimitry Andric   if (!Ok) {
2810b57cec5SDimitry Andric     if (!match(R2, m_And(m_Value(R11), m_Value(R12)))) {
2820b57cec5SDimitry Andric       R11 = R2;
2830b57cec5SDimitry Andric       R12 = Constant::getAllOnesValue(R2->getType());
2840b57cec5SDimitry Andric     }
2850b57cec5SDimitry Andric 
2860b57cec5SDimitry Andric     if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
2870b57cec5SDimitry Andric       A = R11;
2880b57cec5SDimitry Andric       D = R12;
2890b57cec5SDimitry Andric       E = R1;
2900b57cec5SDimitry Andric       Ok = true;
2910b57cec5SDimitry Andric     } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
2920b57cec5SDimitry Andric       A = R12;
2930b57cec5SDimitry Andric       D = R11;
2940b57cec5SDimitry Andric       E = R1;
2950b57cec5SDimitry Andric       Ok = true;
2960b57cec5SDimitry Andric     } else {
297bdd1243dSDimitry Andric       return std::nullopt;
2980b57cec5SDimitry Andric     }
299349cc55cSDimitry Andric 
300349cc55cSDimitry Andric     assert(Ok && "Failed to find AND on the right side of the RHS icmp.");
3010b57cec5SDimitry Andric   }
3020b57cec5SDimitry Andric 
3030b57cec5SDimitry Andric   if (L11 == A) {
3040b57cec5SDimitry Andric     B = L12;
3050b57cec5SDimitry Andric     C = L2;
3060b57cec5SDimitry Andric   } else if (L12 == A) {
3070b57cec5SDimitry Andric     B = L11;
3080b57cec5SDimitry Andric     C = L2;
3090b57cec5SDimitry Andric   } else if (L21 == A) {
3100b57cec5SDimitry Andric     B = L22;
3110b57cec5SDimitry Andric     C = L1;
3120b57cec5SDimitry Andric   } else if (L22 == A) {
3130b57cec5SDimitry Andric     B = L21;
3140b57cec5SDimitry Andric     C = L1;
3150b57cec5SDimitry Andric   }
3160b57cec5SDimitry Andric 
3170b57cec5SDimitry Andric   unsigned LeftType = getMaskedICmpType(A, B, C, PredL);
3180b57cec5SDimitry Andric   unsigned RightType = getMaskedICmpType(A, D, E, PredR);
319bdd1243dSDimitry Andric   return std::optional<std::pair<unsigned, unsigned>>(
320bdd1243dSDimitry Andric       std::make_pair(LeftType, RightType));
3210b57cec5SDimitry Andric }
3220b57cec5SDimitry Andric 
3230b57cec5SDimitry Andric /// Try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E) into a single
3240b57cec5SDimitry Andric /// (icmp(A & X) ==/!= Y), where the left-hand side is of type Mask_NotAllZeros
3250b57cec5SDimitry Andric /// and the right hand side is of type BMask_Mixed. For example,
3260b57cec5SDimitry Andric /// (icmp (A & 12) != 0) & (icmp (A & 15) == 8) -> (icmp (A & 15) == 8).
32781ad6265SDimitry Andric /// Also used for logical and/or, must be poison safe.
foldLogOpOfMaskedICmps_NotAllZeros_BMask_Mixed(ICmpInst * LHS,ICmpInst * RHS,bool IsAnd,Value * A,Value * B,Value * C,Value * D,Value * E,ICmpInst::Predicate PredL,ICmpInst::Predicate PredR,InstCombiner::BuilderTy & Builder)3280b57cec5SDimitry Andric static Value *foldLogOpOfMaskedICmps_NotAllZeros_BMask_Mixed(
329e8d8bef9SDimitry Andric     ICmpInst *LHS, ICmpInst *RHS, bool IsAnd, Value *A, Value *B, Value *C,
330e8d8bef9SDimitry Andric     Value *D, Value *E, ICmpInst::Predicate PredL, ICmpInst::Predicate PredR,
331e8d8bef9SDimitry Andric     InstCombiner::BuilderTy &Builder) {
3320b57cec5SDimitry Andric   // We are given the canonical form:
3330b57cec5SDimitry Andric   //   (icmp ne (A & B), 0) & (icmp eq (A & D), E).
3340b57cec5SDimitry Andric   // where D & E == E.
3350b57cec5SDimitry Andric   //
3360b57cec5SDimitry Andric   // If IsAnd is false, we get it in negated form:
3370b57cec5SDimitry Andric   //   (icmp eq (A & B), 0) | (icmp ne (A & D), E) ->
3380b57cec5SDimitry Andric   //      !((icmp ne (A & B), 0) & (icmp eq (A & D), E)).
3390b57cec5SDimitry Andric   //
3400b57cec5SDimitry Andric   // We currently handle the case of B, C, D, E are constant.
3410b57cec5SDimitry Andric   //
34281ad6265SDimitry Andric   const APInt *BCst, *CCst, *DCst, *OrigECst;
34381ad6265SDimitry Andric   if (!match(B, m_APInt(BCst)) || !match(C, m_APInt(CCst)) ||
34481ad6265SDimitry Andric       !match(D, m_APInt(DCst)) || !match(E, m_APInt(OrigECst)))
3450b57cec5SDimitry Andric     return nullptr;
3460b57cec5SDimitry Andric 
3470b57cec5SDimitry Andric   ICmpInst::Predicate NewCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
3480b57cec5SDimitry Andric 
3490b57cec5SDimitry Andric   // Update E to the canonical form when D is a power of two and RHS is
3500b57cec5SDimitry Andric   // canonicalized as,
3510b57cec5SDimitry Andric   // (icmp ne (A & D), 0) -> (icmp eq (A & D), D) or
3520b57cec5SDimitry Andric   // (icmp ne (A & D), D) -> (icmp eq (A & D), 0).
35381ad6265SDimitry Andric   APInt ECst = *OrigECst;
3540b57cec5SDimitry Andric   if (PredR != NewCC)
35581ad6265SDimitry Andric     ECst ^= *DCst;
3560b57cec5SDimitry Andric 
3570b57cec5SDimitry Andric   // If B or D is zero, skip because if LHS or RHS can be trivially folded by
3580b57cec5SDimitry Andric   // other folding rules and this pattern won't apply any more.
35981ad6265SDimitry Andric   if (*BCst == 0 || *DCst == 0)
3600b57cec5SDimitry Andric     return nullptr;
3610b57cec5SDimitry Andric 
3620b57cec5SDimitry Andric   // If B and D don't intersect, ie. (B & D) == 0, no folding because we can't
3630b57cec5SDimitry Andric   // deduce anything from it.
3640b57cec5SDimitry Andric   // For example,
3650b57cec5SDimitry Andric   // (icmp ne (A & 12), 0) & (icmp eq (A & 3), 1) -> no folding.
36681ad6265SDimitry Andric   if ((*BCst & *DCst) == 0)
3670b57cec5SDimitry Andric     return nullptr;
3680b57cec5SDimitry Andric 
3690b57cec5SDimitry Andric   // If the following two conditions are met:
3700b57cec5SDimitry Andric   //
3710b57cec5SDimitry Andric   // 1. mask B covers only a single bit that's not covered by mask D, that is,
3720b57cec5SDimitry Andric   // (B & (B ^ D)) is a power of 2 (in other words, B minus the intersection of
3730b57cec5SDimitry Andric   // B and D has only one bit set) and,
3740b57cec5SDimitry Andric   //
3750b57cec5SDimitry Andric   // 2. RHS (and E) indicates that the rest of B's bits are zero (in other
3760b57cec5SDimitry Andric   // words, the intersection of B and D is zero), that is, ((B & D) & E) == 0
3770b57cec5SDimitry Andric   //
3780b57cec5SDimitry Andric   // then that single bit in B must be one and thus the whole expression can be
3790b57cec5SDimitry Andric   // folded to
3800b57cec5SDimitry Andric   //   (A & (B | D)) == (B & (B ^ D)) | E.
3810b57cec5SDimitry Andric   //
3820b57cec5SDimitry Andric   // For example,
3830b57cec5SDimitry Andric   // (icmp ne (A & 12), 0) & (icmp eq (A & 7), 1) -> (icmp eq (A & 15), 9)
3840b57cec5SDimitry Andric   // (icmp ne (A & 15), 0) & (icmp eq (A & 7), 0) -> (icmp eq (A & 15), 8)
38581ad6265SDimitry Andric   if ((((*BCst & *DCst) & ECst) == 0) &&
38681ad6265SDimitry Andric       (*BCst & (*BCst ^ *DCst)).isPowerOf2()) {
38781ad6265SDimitry Andric     APInt BorD = *BCst | *DCst;
38881ad6265SDimitry Andric     APInt BandBxorDorE = (*BCst & (*BCst ^ *DCst)) | ECst;
38981ad6265SDimitry Andric     Value *NewMask = ConstantInt::get(A->getType(), BorD);
39081ad6265SDimitry Andric     Value *NewMaskedValue = ConstantInt::get(A->getType(), BandBxorDorE);
3910b57cec5SDimitry Andric     Value *NewAnd = Builder.CreateAnd(A, NewMask);
3920b57cec5SDimitry Andric     return Builder.CreateICmp(NewCC, NewAnd, NewMaskedValue);
3930b57cec5SDimitry Andric   }
3940b57cec5SDimitry Andric 
39581ad6265SDimitry Andric   auto IsSubSetOrEqual = [](const APInt *C1, const APInt *C2) {
39681ad6265SDimitry Andric     return (*C1 & *C2) == *C1;
3970b57cec5SDimitry Andric   };
39881ad6265SDimitry Andric   auto IsSuperSetOrEqual = [](const APInt *C1, const APInt *C2) {
39981ad6265SDimitry Andric     return (*C1 & *C2) == *C2;
4000b57cec5SDimitry Andric   };
4010b57cec5SDimitry Andric 
4020b57cec5SDimitry Andric   // In the following, we consider only the cases where B is a superset of D, B
4030b57cec5SDimitry Andric   // is a subset of D, or B == D because otherwise there's at least one bit
4040b57cec5SDimitry Andric   // covered by B but not D, in which case we can't deduce much from it, so
4050b57cec5SDimitry Andric   // no folding (aside from the single must-be-one bit case right above.)
4060b57cec5SDimitry Andric   // For example,
4070b57cec5SDimitry Andric   // (icmp ne (A & 14), 0) & (icmp eq (A & 3), 1) -> no folding.
4080b57cec5SDimitry Andric   if (!IsSubSetOrEqual(BCst, DCst) && !IsSuperSetOrEqual(BCst, DCst))
4090b57cec5SDimitry Andric     return nullptr;
4100b57cec5SDimitry Andric 
4110b57cec5SDimitry Andric   // At this point, either B is a superset of D, B is a subset of D or B == D.
4120b57cec5SDimitry Andric 
4130b57cec5SDimitry Andric   // If E is zero, if B is a subset of (or equal to) D, LHS and RHS contradict
4140b57cec5SDimitry Andric   // and the whole expression becomes false (or true if negated), otherwise, no
4150b57cec5SDimitry Andric   // folding.
4160b57cec5SDimitry Andric   // For example,
4170b57cec5SDimitry Andric   // (icmp ne (A & 3), 0) & (icmp eq (A & 7), 0) -> false.
4180b57cec5SDimitry Andric   // (icmp ne (A & 15), 0) & (icmp eq (A & 3), 0) -> no folding.
41981ad6265SDimitry Andric   if (ECst.isZero()) {
4200b57cec5SDimitry Andric     if (IsSubSetOrEqual(BCst, DCst))
4210b57cec5SDimitry Andric       return ConstantInt::get(LHS->getType(), !IsAnd);
4220b57cec5SDimitry Andric     return nullptr;
4230b57cec5SDimitry Andric   }
4240b57cec5SDimitry Andric 
4250b57cec5SDimitry Andric   // At this point, B, D, E aren't zero and (B & D) == B, (B & D) == D or B ==
4260b57cec5SDimitry Andric   // D. If B is a superset of (or equal to) D, since E is not zero, LHS is
4270b57cec5SDimitry Andric   // subsumed by RHS (RHS implies LHS.) So the whole expression becomes
4280b57cec5SDimitry Andric   // RHS. For example,
4290b57cec5SDimitry Andric   // (icmp ne (A & 255), 0) & (icmp eq (A & 15), 8) -> (icmp eq (A & 15), 8).
4300b57cec5SDimitry Andric   // (icmp ne (A & 15), 0) & (icmp eq (A & 15), 8) -> (icmp eq (A & 15), 8).
4310b57cec5SDimitry Andric   if (IsSuperSetOrEqual(BCst, DCst))
4320b57cec5SDimitry Andric     return RHS;
4330b57cec5SDimitry Andric   // Otherwise, B is a subset of D. If B and E have a common bit set,
4340b57cec5SDimitry Andric   // ie. (B & E) != 0, then LHS is subsumed by RHS. For example.
4350b57cec5SDimitry Andric   // (icmp ne (A & 12), 0) & (icmp eq (A & 15), 8) -> (icmp eq (A & 15), 8).
4360b57cec5SDimitry Andric   assert(IsSubSetOrEqual(BCst, DCst) && "Precondition due to above code");
43781ad6265SDimitry Andric   if ((*BCst & ECst) != 0)
4380b57cec5SDimitry Andric     return RHS;
4390b57cec5SDimitry Andric   // Otherwise, LHS and RHS contradict and the whole expression becomes false
4400b57cec5SDimitry Andric   // (or true if negated.) For example,
4410b57cec5SDimitry Andric   // (icmp ne (A & 7), 0) & (icmp eq (A & 15), 8) -> false.
4420b57cec5SDimitry Andric   // (icmp ne (A & 6), 0) & (icmp eq (A & 15), 8) -> false.
4430b57cec5SDimitry Andric   return ConstantInt::get(LHS->getType(), !IsAnd);
4440b57cec5SDimitry Andric }
4450b57cec5SDimitry Andric 
4460b57cec5SDimitry Andric /// Try to fold (icmp(A & B) ==/!= 0) &/| (icmp(A & D) ==/!= E) into a single
4470b57cec5SDimitry Andric /// (icmp(A & X) ==/!= Y), where the left-hand side and the right hand side
4480b57cec5SDimitry Andric /// aren't of the common mask pattern type.
44981ad6265SDimitry Andric /// Also used for logical and/or, must be poison safe.
foldLogOpOfMaskedICmpsAsymmetric(ICmpInst * LHS,ICmpInst * RHS,bool IsAnd,Value * A,Value * B,Value * C,Value * D,Value * E,ICmpInst::Predicate PredL,ICmpInst::Predicate PredR,unsigned LHSMask,unsigned RHSMask,InstCombiner::BuilderTy & Builder)4500b57cec5SDimitry Andric static Value *foldLogOpOfMaskedICmpsAsymmetric(
451e8d8bef9SDimitry Andric     ICmpInst *LHS, ICmpInst *RHS, bool IsAnd, Value *A, Value *B, Value *C,
452e8d8bef9SDimitry Andric     Value *D, Value *E, ICmpInst::Predicate PredL, ICmpInst::Predicate PredR,
453e8d8bef9SDimitry Andric     unsigned LHSMask, unsigned RHSMask, InstCombiner::BuilderTy &Builder) {
4540b57cec5SDimitry Andric   assert(ICmpInst::isEquality(PredL) && ICmpInst::isEquality(PredR) &&
4550b57cec5SDimitry Andric          "Expected equality predicates for masked type of icmps.");
4560b57cec5SDimitry Andric   // Handle Mask_NotAllZeros-BMask_Mixed cases.
4570b57cec5SDimitry Andric   // (icmp ne/eq (A & B), C) &/| (icmp eq/ne (A & D), E), or
4580b57cec5SDimitry Andric   // (icmp eq/ne (A & B), C) &/| (icmp ne/eq (A & D), E)
4590b57cec5SDimitry Andric   //    which gets swapped to
4600b57cec5SDimitry Andric   //    (icmp ne/eq (A & D), E) &/| (icmp eq/ne (A & B), C).
4610b57cec5SDimitry Andric   if (!IsAnd) {
4620b57cec5SDimitry Andric     LHSMask = conjugateICmpMask(LHSMask);
4630b57cec5SDimitry Andric     RHSMask = conjugateICmpMask(RHSMask);
4640b57cec5SDimitry Andric   }
4650b57cec5SDimitry Andric   if ((LHSMask & Mask_NotAllZeros) && (RHSMask & BMask_Mixed)) {
4660b57cec5SDimitry Andric     if (Value *V = foldLogOpOfMaskedICmps_NotAllZeros_BMask_Mixed(
4670b57cec5SDimitry Andric             LHS, RHS, IsAnd, A, B, C, D, E,
4680b57cec5SDimitry Andric             PredL, PredR, Builder)) {
4690b57cec5SDimitry Andric       return V;
4700b57cec5SDimitry Andric     }
4710b57cec5SDimitry Andric   } else if ((LHSMask & BMask_Mixed) && (RHSMask & Mask_NotAllZeros)) {
4720b57cec5SDimitry Andric     if (Value *V = foldLogOpOfMaskedICmps_NotAllZeros_BMask_Mixed(
4730b57cec5SDimitry Andric             RHS, LHS, IsAnd, A, D, E, B, C,
4740b57cec5SDimitry Andric             PredR, PredL, Builder)) {
4750b57cec5SDimitry Andric       return V;
4760b57cec5SDimitry Andric     }
4770b57cec5SDimitry Andric   }
4780b57cec5SDimitry Andric   return nullptr;
4790b57cec5SDimitry Andric }
4800b57cec5SDimitry Andric 
4810b57cec5SDimitry Andric /// Try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
4820b57cec5SDimitry Andric /// into a single (icmp(A & X) ==/!= Y).
foldLogOpOfMaskedICmps(ICmpInst * LHS,ICmpInst * RHS,bool IsAnd,bool IsLogical,InstCombiner::BuilderTy & Builder)4830b57cec5SDimitry Andric static Value *foldLogOpOfMaskedICmps(ICmpInst *LHS, ICmpInst *RHS, bool IsAnd,
48481ad6265SDimitry Andric                                      bool IsLogical,
485e8d8bef9SDimitry Andric                                      InstCombiner::BuilderTy &Builder) {
4860b57cec5SDimitry Andric   Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr, *E = nullptr;
4870b57cec5SDimitry Andric   ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
488bdd1243dSDimitry Andric   std::optional<std::pair<unsigned, unsigned>> MaskPair =
4890b57cec5SDimitry Andric       getMaskedTypeForICmpPair(A, B, C, D, E, LHS, RHS, PredL, PredR);
4900b57cec5SDimitry Andric   if (!MaskPair)
4910b57cec5SDimitry Andric     return nullptr;
4920b57cec5SDimitry Andric   assert(ICmpInst::isEquality(PredL) && ICmpInst::isEquality(PredR) &&
4930b57cec5SDimitry Andric          "Expected equality predicates for masked type of icmps.");
4940b57cec5SDimitry Andric   unsigned LHSMask = MaskPair->first;
4950b57cec5SDimitry Andric   unsigned RHSMask = MaskPair->second;
4960b57cec5SDimitry Andric   unsigned Mask = LHSMask & RHSMask;
4970b57cec5SDimitry Andric   if (Mask == 0) {
4980b57cec5SDimitry Andric     // Even if the two sides don't share a common pattern, check if folding can
4990b57cec5SDimitry Andric     // still happen.
5000b57cec5SDimitry Andric     if (Value *V = foldLogOpOfMaskedICmpsAsymmetric(
5010b57cec5SDimitry Andric             LHS, RHS, IsAnd, A, B, C, D, E, PredL, PredR, LHSMask, RHSMask,
5020b57cec5SDimitry Andric             Builder))
5030b57cec5SDimitry Andric       return V;
5040b57cec5SDimitry Andric     return nullptr;
5050b57cec5SDimitry Andric   }
5060b57cec5SDimitry Andric 
5070b57cec5SDimitry Andric   // In full generality:
5080b57cec5SDimitry Andric   //     (icmp (A & B) Op C) | (icmp (A & D) Op E)
5090b57cec5SDimitry Andric   // ==  ![ (icmp (A & B) !Op C) & (icmp (A & D) !Op E) ]
5100b57cec5SDimitry Andric   //
5110b57cec5SDimitry Andric   // If the latter can be converted into (icmp (A & X) Op Y) then the former is
5120b57cec5SDimitry Andric   // equivalent to (icmp (A & X) !Op Y).
5130b57cec5SDimitry Andric   //
5140b57cec5SDimitry Andric   // Therefore, we can pretend for the rest of this function that we're dealing
5150b57cec5SDimitry Andric   // with the conjunction, provided we flip the sense of any comparisons (both
5160b57cec5SDimitry Andric   // input and output).
5170b57cec5SDimitry Andric 
5180b57cec5SDimitry Andric   // In most cases we're going to produce an EQ for the "&&" case.
5190b57cec5SDimitry Andric   ICmpInst::Predicate NewCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
5200b57cec5SDimitry Andric   if (!IsAnd) {
5210b57cec5SDimitry Andric     // Convert the masking analysis into its equivalent with negated
5220b57cec5SDimitry Andric     // comparisons.
5230b57cec5SDimitry Andric     Mask = conjugateICmpMask(Mask);
5240b57cec5SDimitry Andric   }
5250b57cec5SDimitry Andric 
5260b57cec5SDimitry Andric   if (Mask & Mask_AllZeros) {
5270b57cec5SDimitry Andric     // (icmp eq (A & B), 0) & (icmp eq (A & D), 0)
5280b57cec5SDimitry Andric     // -> (icmp eq (A & (B|D)), 0)
52981ad6265SDimitry Andric     if (IsLogical && !isGuaranteedNotToBeUndefOrPoison(D))
53081ad6265SDimitry Andric       return nullptr; // TODO: Use freeze?
5310b57cec5SDimitry Andric     Value *NewOr = Builder.CreateOr(B, D);
5320b57cec5SDimitry Andric     Value *NewAnd = Builder.CreateAnd(A, NewOr);
5330b57cec5SDimitry Andric     // We can't use C as zero because we might actually handle
5340b57cec5SDimitry Andric     //   (icmp ne (A & B), B) & (icmp ne (A & D), D)
5350b57cec5SDimitry Andric     // with B and D, having a single bit set.
5360b57cec5SDimitry Andric     Value *Zero = Constant::getNullValue(A->getType());
5370b57cec5SDimitry Andric     return Builder.CreateICmp(NewCC, NewAnd, Zero);
5380b57cec5SDimitry Andric   }
5390b57cec5SDimitry Andric   if (Mask & BMask_AllOnes) {
5400b57cec5SDimitry Andric     // (icmp eq (A & B), B) & (icmp eq (A & D), D)
5410b57cec5SDimitry Andric     // -> (icmp eq (A & (B|D)), (B|D))
54281ad6265SDimitry Andric     if (IsLogical && !isGuaranteedNotToBeUndefOrPoison(D))
54381ad6265SDimitry Andric       return nullptr; // TODO: Use freeze?
5440b57cec5SDimitry Andric     Value *NewOr = Builder.CreateOr(B, D);
5450b57cec5SDimitry Andric     Value *NewAnd = Builder.CreateAnd(A, NewOr);
5460b57cec5SDimitry Andric     return Builder.CreateICmp(NewCC, NewAnd, NewOr);
5470b57cec5SDimitry Andric   }
5480b57cec5SDimitry Andric   if (Mask & AMask_AllOnes) {
5490b57cec5SDimitry Andric     // (icmp eq (A & B), A) & (icmp eq (A & D), A)
5500b57cec5SDimitry Andric     // -> (icmp eq (A & (B&D)), A)
55181ad6265SDimitry Andric     if (IsLogical && !isGuaranteedNotToBeUndefOrPoison(D))
55281ad6265SDimitry Andric       return nullptr; // TODO: Use freeze?
5530b57cec5SDimitry Andric     Value *NewAnd1 = Builder.CreateAnd(B, D);
5540b57cec5SDimitry Andric     Value *NewAnd2 = Builder.CreateAnd(A, NewAnd1);
5550b57cec5SDimitry Andric     return Builder.CreateICmp(NewCC, NewAnd2, A);
5560b57cec5SDimitry Andric   }
5570b57cec5SDimitry Andric 
5580b57cec5SDimitry Andric   // Remaining cases assume at least that B and D are constant, and depend on
5590b57cec5SDimitry Andric   // their actual values. This isn't strictly necessary, just a "handle the
5600b57cec5SDimitry Andric   // easy cases for now" decision.
561349cc55cSDimitry Andric   const APInt *ConstB, *ConstD;
562349cc55cSDimitry Andric   if (!match(B, m_APInt(ConstB)) || !match(D, m_APInt(ConstD)))
5630b57cec5SDimitry Andric     return nullptr;
5640b57cec5SDimitry Andric 
5650b57cec5SDimitry Andric   if (Mask & (Mask_NotAllZeros | BMask_NotAllOnes)) {
5660b57cec5SDimitry Andric     // (icmp ne (A & B), 0) & (icmp ne (A & D), 0) and
5670b57cec5SDimitry Andric     // (icmp ne (A & B), B) & (icmp ne (A & D), D)
5680b57cec5SDimitry Andric     //     -> (icmp ne (A & B), 0) or (icmp ne (A & D), 0)
5690b57cec5SDimitry Andric     // Only valid if one of the masks is a superset of the other (check "B&D" is
5700b57cec5SDimitry Andric     // the same as either B or D).
571349cc55cSDimitry Andric     APInt NewMask = *ConstB & *ConstD;
572349cc55cSDimitry Andric     if (NewMask == *ConstB)
5730b57cec5SDimitry Andric       return LHS;
574349cc55cSDimitry Andric     else if (NewMask == *ConstD)
5750b57cec5SDimitry Andric       return RHS;
5760b57cec5SDimitry Andric   }
5770b57cec5SDimitry Andric 
5780b57cec5SDimitry Andric   if (Mask & AMask_NotAllOnes) {
5790b57cec5SDimitry Andric     // (icmp ne (A & B), B) & (icmp ne (A & D), D)
5800b57cec5SDimitry Andric     //     -> (icmp ne (A & B), A) or (icmp ne (A & D), A)
5810b57cec5SDimitry Andric     // Only valid if one of the masks is a superset of the other (check "B|D" is
5820b57cec5SDimitry Andric     // the same as either B or D).
583349cc55cSDimitry Andric     APInt NewMask = *ConstB | *ConstD;
584349cc55cSDimitry Andric     if (NewMask == *ConstB)
5850b57cec5SDimitry Andric       return LHS;
586349cc55cSDimitry Andric     else if (NewMask == *ConstD)
5870b57cec5SDimitry Andric       return RHS;
5880b57cec5SDimitry Andric   }
5890b57cec5SDimitry Andric 
59006c3fb27SDimitry Andric   if (Mask & (BMask_Mixed | BMask_NotMixed)) {
59106c3fb27SDimitry Andric     // Mixed:
5920b57cec5SDimitry Andric     // (icmp eq (A & B), C) & (icmp eq (A & D), E)
5930b57cec5SDimitry Andric     // We already know that B & C == C && D & E == E.
5940b57cec5SDimitry Andric     // If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of
5950b57cec5SDimitry Andric     // C and E, which are shared by both the mask B and the mask D, don't
5960b57cec5SDimitry Andric     // contradict, then we can transform to
5970b57cec5SDimitry Andric     // -> (icmp eq (A & (B|D)), (C|E))
5980b57cec5SDimitry Andric     // Currently, we only handle the case of B, C, D, and E being constant.
5990b57cec5SDimitry Andric     // We can't simply use C and E because we might actually handle
6000b57cec5SDimitry Andric     //   (icmp ne (A & B), B) & (icmp eq (A & D), D)
6010b57cec5SDimitry Andric     // with B and D, having a single bit set.
60206c3fb27SDimitry Andric 
60306c3fb27SDimitry Andric     // NotMixed:
60406c3fb27SDimitry Andric     // (icmp ne (A & B), C) & (icmp ne (A & D), E)
60506c3fb27SDimitry Andric     // -> (icmp ne (A & (B & D)), (C & E))
60606c3fb27SDimitry Andric     // Check the intersection (B & D) for inequality.
60706c3fb27SDimitry Andric     // Assume that (B & D) == B || (B & D) == D, i.e B/D is a subset of D/B
60806c3fb27SDimitry Andric     // and (B & D) & (C ^ E) == 0, bits of C and E, which are shared by both the
60906c3fb27SDimitry Andric     // B and the D, don't contradict.
61006c3fb27SDimitry Andric     // Note that we can assume (~B & C) == 0 && (~D & E) == 0, previous
61106c3fb27SDimitry Andric     // operation should delete these icmps if it hadn't been met.
61206c3fb27SDimitry Andric 
613349cc55cSDimitry Andric     const APInt *OldConstC, *OldConstE;
614349cc55cSDimitry Andric     if (!match(C, m_APInt(OldConstC)) || !match(E, m_APInt(OldConstE)))
6150b57cec5SDimitry Andric       return nullptr;
616349cc55cSDimitry Andric 
61706c3fb27SDimitry Andric     auto FoldBMixed = [&](ICmpInst::Predicate CC, bool IsNot) -> Value * {
61806c3fb27SDimitry Andric       CC = IsNot ? CmpInst::getInversePredicate(CC) : CC;
61906c3fb27SDimitry Andric       const APInt ConstC = PredL != CC ? *ConstB ^ *OldConstC : *OldConstC;
62006c3fb27SDimitry Andric       const APInt ConstE = PredR != CC ? *ConstD ^ *OldConstE : *OldConstE;
6210b57cec5SDimitry Andric 
622349cc55cSDimitry Andric       if (((*ConstB & *ConstD) & (ConstC ^ ConstE)).getBoolValue())
62306c3fb27SDimitry Andric         return IsNot ? nullptr : ConstantInt::get(LHS->getType(), !IsAnd);
6240b57cec5SDimitry Andric 
62506c3fb27SDimitry Andric       if (IsNot && !ConstB->isSubsetOf(*ConstD) && !ConstD->isSubsetOf(*ConstB))
62606c3fb27SDimitry Andric         return nullptr;
62706c3fb27SDimitry Andric 
62806c3fb27SDimitry Andric       APInt BD, CE;
62906c3fb27SDimitry Andric       if (IsNot) {
63006c3fb27SDimitry Andric         BD = *ConstB & *ConstD;
63106c3fb27SDimitry Andric         CE = ConstC & ConstE;
63206c3fb27SDimitry Andric       } else {
63306c3fb27SDimitry Andric         BD = *ConstB | *ConstD;
63406c3fb27SDimitry Andric         CE = ConstC | ConstE;
6350b57cec5SDimitry Andric       }
63606c3fb27SDimitry Andric       Value *NewAnd = Builder.CreateAnd(A, BD);
63706c3fb27SDimitry Andric       Value *CEVal = ConstantInt::get(A->getType(), CE);
63806c3fb27SDimitry Andric       return Builder.CreateICmp(CC, CEVal, NewAnd);
63906c3fb27SDimitry Andric     };
6400b57cec5SDimitry Andric 
64106c3fb27SDimitry Andric     if (Mask & BMask_Mixed)
64206c3fb27SDimitry Andric       return FoldBMixed(NewCC, false);
64306c3fb27SDimitry Andric     if (Mask & BMask_NotMixed) // can be else also
64406c3fb27SDimitry Andric       return FoldBMixed(NewCC, true);
64506c3fb27SDimitry Andric   }
6460b57cec5SDimitry Andric   return nullptr;
6470b57cec5SDimitry Andric }
6480b57cec5SDimitry Andric 
6490b57cec5SDimitry Andric /// Try to fold a signed range checked with lower bound 0 to an unsigned icmp.
6500b57cec5SDimitry Andric /// Example: (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
6510b57cec5SDimitry Andric /// If \p Inverted is true then the check is for the inverted range, e.g.
6520b57cec5SDimitry Andric /// (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
simplifyRangeCheck(ICmpInst * Cmp0,ICmpInst * Cmp1,bool Inverted)653e8d8bef9SDimitry Andric Value *InstCombinerImpl::simplifyRangeCheck(ICmpInst *Cmp0, ICmpInst *Cmp1,
6540b57cec5SDimitry Andric                                             bool Inverted) {
6550b57cec5SDimitry Andric   // Check the lower range comparison, e.g. x >= 0
6560b57cec5SDimitry Andric   // InstCombine already ensured that if there is a constant it's on the RHS.
6570b57cec5SDimitry Andric   ConstantInt *RangeStart = dyn_cast<ConstantInt>(Cmp0->getOperand(1));
6580b57cec5SDimitry Andric   if (!RangeStart)
6590b57cec5SDimitry Andric     return nullptr;
6600b57cec5SDimitry Andric 
6610b57cec5SDimitry Andric   ICmpInst::Predicate Pred0 = (Inverted ? Cmp0->getInversePredicate() :
6620b57cec5SDimitry Andric                                Cmp0->getPredicate());
6630b57cec5SDimitry Andric 
6640b57cec5SDimitry Andric   // Accept x > -1 or x >= 0 (after potentially inverting the predicate).
6650b57cec5SDimitry Andric   if (!((Pred0 == ICmpInst::ICMP_SGT && RangeStart->isMinusOne()) ||
6660b57cec5SDimitry Andric         (Pred0 == ICmpInst::ICMP_SGE && RangeStart->isZero())))
6670b57cec5SDimitry Andric     return nullptr;
6680b57cec5SDimitry Andric 
6690b57cec5SDimitry Andric   ICmpInst::Predicate Pred1 = (Inverted ? Cmp1->getInversePredicate() :
6700b57cec5SDimitry Andric                                Cmp1->getPredicate());
6710b57cec5SDimitry Andric 
6720b57cec5SDimitry Andric   Value *Input = Cmp0->getOperand(0);
6730b57cec5SDimitry Andric   Value *RangeEnd;
6740b57cec5SDimitry Andric   if (Cmp1->getOperand(0) == Input) {
6750b57cec5SDimitry Andric     // For the upper range compare we have: icmp x, n
6760b57cec5SDimitry Andric     RangeEnd = Cmp1->getOperand(1);
6770b57cec5SDimitry Andric   } else if (Cmp1->getOperand(1) == Input) {
6780b57cec5SDimitry Andric     // For the upper range compare we have: icmp n, x
6790b57cec5SDimitry Andric     RangeEnd = Cmp1->getOperand(0);
6800b57cec5SDimitry Andric     Pred1 = ICmpInst::getSwappedPredicate(Pred1);
6810b57cec5SDimitry Andric   } else {
6820b57cec5SDimitry Andric     return nullptr;
6830b57cec5SDimitry Andric   }
6840b57cec5SDimitry Andric 
6850b57cec5SDimitry Andric   // Check the upper range comparison, e.g. x < n
6860b57cec5SDimitry Andric   ICmpInst::Predicate NewPred;
6870b57cec5SDimitry Andric   switch (Pred1) {
6880b57cec5SDimitry Andric     case ICmpInst::ICMP_SLT: NewPred = ICmpInst::ICMP_ULT; break;
6890b57cec5SDimitry Andric     case ICmpInst::ICMP_SLE: NewPred = ICmpInst::ICMP_ULE; break;
6900b57cec5SDimitry Andric     default: return nullptr;
6910b57cec5SDimitry Andric   }
6920b57cec5SDimitry Andric 
6930b57cec5SDimitry Andric   // This simplification is only valid if the upper range is not negative.
6940b57cec5SDimitry Andric   KnownBits Known = computeKnownBits(RangeEnd, /*Depth=*/0, Cmp1);
6950b57cec5SDimitry Andric   if (!Known.isNonNegative())
6960b57cec5SDimitry Andric     return nullptr;
6970b57cec5SDimitry Andric 
6980b57cec5SDimitry Andric   if (Inverted)
6990b57cec5SDimitry Andric     NewPred = ICmpInst::getInversePredicate(NewPred);
7000b57cec5SDimitry Andric 
7010b57cec5SDimitry Andric   return Builder.CreateICmp(NewPred, Input, RangeEnd);
7020b57cec5SDimitry Andric }
7030b57cec5SDimitry Andric 
7040b57cec5SDimitry Andric // Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
7050b57cec5SDimitry Andric // Fold (!iszero(A & K1) & !iszero(A & K2)) -> (A & (K1 | K2)) == (K1 | K2)
foldAndOrOfICmpsOfAndWithPow2(ICmpInst * LHS,ICmpInst * RHS,Instruction * CxtI,bool IsAnd,bool IsLogical)706e8d8bef9SDimitry Andric Value *InstCombinerImpl::foldAndOrOfICmpsOfAndWithPow2(ICmpInst *LHS,
707e8d8bef9SDimitry Andric                                                        ICmpInst *RHS,
708fe6060f1SDimitry Andric                                                        Instruction *CxtI,
709fe6060f1SDimitry Andric                                                        bool IsAnd,
710fe6060f1SDimitry Andric                                                        bool IsLogical) {
711fe6060f1SDimitry Andric   CmpInst::Predicate Pred = IsAnd ? CmpInst::ICMP_NE : CmpInst::ICMP_EQ;
712fe6060f1SDimitry Andric   if (LHS->getPredicate() != Pred || RHS->getPredicate() != Pred)
7130b57cec5SDimitry Andric     return nullptr;
7140b57cec5SDimitry Andric 
715e8d8bef9SDimitry Andric   if (!match(LHS->getOperand(1), m_Zero()) ||
716e8d8bef9SDimitry Andric       !match(RHS->getOperand(1), m_Zero()))
7170b57cec5SDimitry Andric     return nullptr;
7180b57cec5SDimitry Andric 
719fe6060f1SDimitry Andric   Value *L1, *L2, *R1, *R2;
720fe6060f1SDimitry Andric   if (match(LHS->getOperand(0), m_And(m_Value(L1), m_Value(L2))) &&
721fe6060f1SDimitry Andric       match(RHS->getOperand(0), m_And(m_Value(R1), m_Value(R2)))) {
722fe6060f1SDimitry Andric     if (L1 == R2 || L2 == R2)
723fe6060f1SDimitry Andric       std::swap(R1, R2);
724fe6060f1SDimitry Andric     if (L2 == R1)
725fe6060f1SDimitry Andric       std::swap(L1, L2);
7260b57cec5SDimitry Andric 
727fe6060f1SDimitry Andric     if (L1 == R1 &&
728fe6060f1SDimitry Andric         isKnownToBeAPowerOfTwo(L2, false, 0, CxtI) &&
729fe6060f1SDimitry Andric         isKnownToBeAPowerOfTwo(R2, false, 0, CxtI)) {
730fe6060f1SDimitry Andric       // If this is a logical and/or, then we must prevent propagation of a
731fe6060f1SDimitry Andric       // poison value from the RHS by inserting freeze.
732fe6060f1SDimitry Andric       if (IsLogical)
733fe6060f1SDimitry Andric         R2 = Builder.CreateFreeze(R2);
734fe6060f1SDimitry Andric       Value *Mask = Builder.CreateOr(L2, R2);
735fe6060f1SDimitry Andric       Value *Masked = Builder.CreateAnd(L1, Mask);
736fe6060f1SDimitry Andric       auto NewPred = IsAnd ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;
7370b57cec5SDimitry Andric       return Builder.CreateICmp(NewPred, Masked, Mask);
7380b57cec5SDimitry Andric     }
7390b57cec5SDimitry Andric   }
7400b57cec5SDimitry Andric 
7410b57cec5SDimitry Andric   return nullptr;
7420b57cec5SDimitry Andric }
7430b57cec5SDimitry Andric 
7440b57cec5SDimitry Andric /// General pattern:
7450b57cec5SDimitry Andric ///   X & Y
7460b57cec5SDimitry Andric ///
7470b57cec5SDimitry Andric /// Where Y is checking that all the high bits (covered by a mask 4294967168)
7480b57cec5SDimitry Andric /// are uniform, i.e.  %arg & 4294967168  can be either  4294967168  or  0
7490b57cec5SDimitry Andric /// Pattern can be one of:
7500b57cec5SDimitry Andric ///   %t = add        i32 %arg,    128
7510b57cec5SDimitry Andric ///   %r = icmp   ult i32 %t,      256
7520b57cec5SDimitry Andric /// Or
7530b57cec5SDimitry Andric ///   %t0 = shl       i32 %arg,    24
7540b57cec5SDimitry Andric ///   %t1 = ashr      i32 %t0,     24
7550b57cec5SDimitry Andric ///   %r  = icmp  eq  i32 %t1,     %arg
7560b57cec5SDimitry Andric /// Or
7570b57cec5SDimitry Andric ///   %t0 = trunc     i32 %arg  to i8
7580b57cec5SDimitry Andric ///   %t1 = sext      i8  %t0   to i32
7590b57cec5SDimitry Andric ///   %r  = icmp  eq  i32 %t1,     %arg
7600b57cec5SDimitry Andric /// This pattern is a signed truncation check.
7610b57cec5SDimitry Andric ///
7620b57cec5SDimitry Andric /// And X is checking that some bit in that same mask is zero.
7630b57cec5SDimitry Andric /// I.e. can be one of:
7640b57cec5SDimitry Andric ///   %r = icmp sgt i32   %arg,    -1
7650b57cec5SDimitry Andric /// Or
7660b57cec5SDimitry Andric ///   %t = and      i32   %arg,    2147483648
7670b57cec5SDimitry Andric ///   %r = icmp eq  i32   %t,      0
7680b57cec5SDimitry Andric ///
7690b57cec5SDimitry Andric /// Since we are checking that all the bits in that mask are the same,
7700b57cec5SDimitry Andric /// and a particular bit is zero, what we are really checking is that all the
7710b57cec5SDimitry Andric /// masked bits are zero.
7720b57cec5SDimitry Andric /// So this should be transformed to:
7730b57cec5SDimitry Andric ///   %r = icmp ult i32 %arg, 128
foldSignedTruncationCheck(ICmpInst * ICmp0,ICmpInst * ICmp1,Instruction & CxtI,InstCombiner::BuilderTy & Builder)7740b57cec5SDimitry Andric static Value *foldSignedTruncationCheck(ICmpInst *ICmp0, ICmpInst *ICmp1,
7750b57cec5SDimitry Andric                                         Instruction &CxtI,
7760b57cec5SDimitry Andric                                         InstCombiner::BuilderTy &Builder) {
7770b57cec5SDimitry Andric   assert(CxtI.getOpcode() == Instruction::And);
7780b57cec5SDimitry Andric 
7790b57cec5SDimitry Andric   // Match  icmp ult (add %arg, C01), C1   (C1 == C01 << 1; powers of two)
7800b57cec5SDimitry Andric   auto tryToMatchSignedTruncationCheck = [](ICmpInst *ICmp, Value *&X,
7810b57cec5SDimitry Andric                                             APInt &SignBitMask) -> bool {
7820b57cec5SDimitry Andric     CmpInst::Predicate Pred;
7830b57cec5SDimitry Andric     const APInt *I01, *I1; // powers of two; I1 == I01 << 1
7840b57cec5SDimitry Andric     if (!(match(ICmp,
7850b57cec5SDimitry Andric                 m_ICmp(Pred, m_Add(m_Value(X), m_Power2(I01)), m_Power2(I1))) &&
7860b57cec5SDimitry Andric           Pred == ICmpInst::ICMP_ULT && I1->ugt(*I01) && I01->shl(1) == *I1))
7870b57cec5SDimitry Andric       return false;
7880b57cec5SDimitry Andric     // Which bit is the new sign bit as per the 'signed truncation' pattern?
7890b57cec5SDimitry Andric     SignBitMask = *I01;
7900b57cec5SDimitry Andric     return true;
7910b57cec5SDimitry Andric   };
7920b57cec5SDimitry Andric 
7930b57cec5SDimitry Andric   // One icmp needs to be 'signed truncation check'.
7940b57cec5SDimitry Andric   // We need to match this first, else we will mismatch commutative cases.
7950b57cec5SDimitry Andric   Value *X1;
7960b57cec5SDimitry Andric   APInt HighestBit;
7970b57cec5SDimitry Andric   ICmpInst *OtherICmp;
7980b57cec5SDimitry Andric   if (tryToMatchSignedTruncationCheck(ICmp1, X1, HighestBit))
7990b57cec5SDimitry Andric     OtherICmp = ICmp0;
8000b57cec5SDimitry Andric   else if (tryToMatchSignedTruncationCheck(ICmp0, X1, HighestBit))
8010b57cec5SDimitry Andric     OtherICmp = ICmp1;
8020b57cec5SDimitry Andric   else
8030b57cec5SDimitry Andric     return nullptr;
8040b57cec5SDimitry Andric 
8050b57cec5SDimitry Andric   assert(HighestBit.isPowerOf2() && "expected to be power of two (non-zero)");
8060b57cec5SDimitry Andric 
8070b57cec5SDimitry Andric   // Try to match/decompose into:  icmp eq (X & Mask), 0
8080b57cec5SDimitry Andric   auto tryToDecompose = [](ICmpInst *ICmp, Value *&X,
8090b57cec5SDimitry Andric                            APInt &UnsetBitsMask) -> bool {
8100b57cec5SDimitry Andric     CmpInst::Predicate Pred = ICmp->getPredicate();
8110b57cec5SDimitry Andric     // Can it be decomposed into  icmp eq (X & Mask), 0  ?
8120b57cec5SDimitry Andric     if (llvm::decomposeBitTestICmp(ICmp->getOperand(0), ICmp->getOperand(1),
8130b57cec5SDimitry Andric                                    Pred, X, UnsetBitsMask,
8140b57cec5SDimitry Andric                                    /*LookThroughTrunc=*/false) &&
8150b57cec5SDimitry Andric         Pred == ICmpInst::ICMP_EQ)
8160b57cec5SDimitry Andric       return true;
8170b57cec5SDimitry Andric     // Is it  icmp eq (X & Mask), 0  already?
8180b57cec5SDimitry Andric     const APInt *Mask;
8190b57cec5SDimitry Andric     if (match(ICmp, m_ICmp(Pred, m_And(m_Value(X), m_APInt(Mask)), m_Zero())) &&
8200b57cec5SDimitry Andric         Pred == ICmpInst::ICMP_EQ) {
8210b57cec5SDimitry Andric       UnsetBitsMask = *Mask;
8220b57cec5SDimitry Andric       return true;
8230b57cec5SDimitry Andric     }
8240b57cec5SDimitry Andric     return false;
8250b57cec5SDimitry Andric   };
8260b57cec5SDimitry Andric 
8270b57cec5SDimitry Andric   // And the other icmp needs to be decomposable into a bit test.
8280b57cec5SDimitry Andric   Value *X0;
8290b57cec5SDimitry Andric   APInt UnsetBitsMask;
8300b57cec5SDimitry Andric   if (!tryToDecompose(OtherICmp, X0, UnsetBitsMask))
8310b57cec5SDimitry Andric     return nullptr;
8320b57cec5SDimitry Andric 
833349cc55cSDimitry Andric   assert(!UnsetBitsMask.isZero() && "empty mask makes no sense.");
8340b57cec5SDimitry Andric 
8350b57cec5SDimitry Andric   // Are they working on the same value?
8360b57cec5SDimitry Andric   Value *X;
8370b57cec5SDimitry Andric   if (X1 == X0) {
8380b57cec5SDimitry Andric     // Ok as is.
8390b57cec5SDimitry Andric     X = X1;
8400b57cec5SDimitry Andric   } else if (match(X0, m_Trunc(m_Specific(X1)))) {
8410b57cec5SDimitry Andric     UnsetBitsMask = UnsetBitsMask.zext(X1->getType()->getScalarSizeInBits());
8420b57cec5SDimitry Andric     X = X1;
8430b57cec5SDimitry Andric   } else
8440b57cec5SDimitry Andric     return nullptr;
8450b57cec5SDimitry Andric 
8460b57cec5SDimitry Andric   // So which bits should be uniform as per the 'signed truncation check'?
8470b57cec5SDimitry Andric   // (all the bits starting with (i.e. including) HighestBit)
8480b57cec5SDimitry Andric   APInt SignBitsMask = ~(HighestBit - 1U);
8490b57cec5SDimitry Andric 
8500b57cec5SDimitry Andric   // UnsetBitsMask must have some common bits with SignBitsMask,
8510b57cec5SDimitry Andric   if (!UnsetBitsMask.intersects(SignBitsMask))
8520b57cec5SDimitry Andric     return nullptr;
8530b57cec5SDimitry Andric 
8540b57cec5SDimitry Andric   // Does UnsetBitsMask contain any bits outside of SignBitsMask?
8550b57cec5SDimitry Andric   if (!UnsetBitsMask.isSubsetOf(SignBitsMask)) {
8560b57cec5SDimitry Andric     APInt OtherHighestBit = (~UnsetBitsMask) + 1U;
8570b57cec5SDimitry Andric     if (!OtherHighestBit.isPowerOf2())
8580b57cec5SDimitry Andric       return nullptr;
8590b57cec5SDimitry Andric     HighestBit = APIntOps::umin(HighestBit, OtherHighestBit);
8600b57cec5SDimitry Andric   }
8610b57cec5SDimitry Andric   // Else, if it does not, then all is ok as-is.
8620b57cec5SDimitry Andric 
8630b57cec5SDimitry Andric   // %r = icmp ult %X, SignBit
8640b57cec5SDimitry Andric   return Builder.CreateICmpULT(X, ConstantInt::get(X->getType(), HighestBit),
8650b57cec5SDimitry Andric                                CxtI.getName() + ".simplified");
8660b57cec5SDimitry Andric }
8670b57cec5SDimitry Andric 
86881ad6265SDimitry Andric /// Fold (icmp eq ctpop(X) 1) | (icmp eq X 0) into (icmp ult ctpop(X) 2) and
86981ad6265SDimitry Andric /// fold (icmp ne ctpop(X) 1) & (icmp ne X 0) into (icmp ugt ctpop(X) 1).
87081ad6265SDimitry Andric /// Also used for logical and/or, must be poison safe.
foldIsPowerOf2OrZero(ICmpInst * Cmp0,ICmpInst * Cmp1,bool IsAnd,InstCombiner::BuilderTy & Builder)87181ad6265SDimitry Andric static Value *foldIsPowerOf2OrZero(ICmpInst *Cmp0, ICmpInst *Cmp1, bool IsAnd,
87281ad6265SDimitry Andric                                    InstCombiner::BuilderTy &Builder) {
87381ad6265SDimitry Andric   CmpInst::Predicate Pred0, Pred1;
87481ad6265SDimitry Andric   Value *X;
87581ad6265SDimitry Andric   if (!match(Cmp0, m_ICmp(Pred0, m_Intrinsic<Intrinsic::ctpop>(m_Value(X)),
87681ad6265SDimitry Andric                           m_SpecificInt(1))) ||
87781ad6265SDimitry Andric       !match(Cmp1, m_ICmp(Pred1, m_Specific(X), m_ZeroInt())))
87881ad6265SDimitry Andric     return nullptr;
87981ad6265SDimitry Andric 
88081ad6265SDimitry Andric   Value *CtPop = Cmp0->getOperand(0);
88181ad6265SDimitry Andric   if (IsAnd && Pred0 == ICmpInst::ICMP_NE && Pred1 == ICmpInst::ICMP_NE)
88281ad6265SDimitry Andric     return Builder.CreateICmpUGT(CtPop, ConstantInt::get(CtPop->getType(), 1));
88381ad6265SDimitry Andric   if (!IsAnd && Pred0 == ICmpInst::ICMP_EQ && Pred1 == ICmpInst::ICMP_EQ)
88481ad6265SDimitry Andric     return Builder.CreateICmpULT(CtPop, ConstantInt::get(CtPop->getType(), 2));
88581ad6265SDimitry Andric 
88681ad6265SDimitry Andric   return nullptr;
88781ad6265SDimitry Andric }
88881ad6265SDimitry Andric 
8890b57cec5SDimitry Andric /// Reduce a pair of compares that check if a value has exactly 1 bit set.
89081ad6265SDimitry Andric /// Also used for logical and/or, must be poison safe.
foldIsPowerOf2(ICmpInst * Cmp0,ICmpInst * Cmp1,bool JoinedByAnd,InstCombiner::BuilderTy & Builder)8910b57cec5SDimitry Andric static Value *foldIsPowerOf2(ICmpInst *Cmp0, ICmpInst *Cmp1, bool JoinedByAnd,
8920b57cec5SDimitry Andric                              InstCombiner::BuilderTy &Builder) {
8930b57cec5SDimitry Andric   // Handle 'and' / 'or' commutation: make the equality check the first operand.
8940b57cec5SDimitry Andric   if (JoinedByAnd && Cmp1->getPredicate() == ICmpInst::ICMP_NE)
8950b57cec5SDimitry Andric     std::swap(Cmp0, Cmp1);
8960b57cec5SDimitry Andric   else if (!JoinedByAnd && Cmp1->getPredicate() == ICmpInst::ICMP_EQ)
8970b57cec5SDimitry Andric     std::swap(Cmp0, Cmp1);
8980b57cec5SDimitry Andric 
8990b57cec5SDimitry Andric   // (X != 0) && (ctpop(X) u< 2) --> ctpop(X) == 1
9000b57cec5SDimitry Andric   CmpInst::Predicate Pred0, Pred1;
9010b57cec5SDimitry Andric   Value *X;
9020b57cec5SDimitry Andric   if (JoinedByAnd && match(Cmp0, m_ICmp(Pred0, m_Value(X), m_ZeroInt())) &&
9030b57cec5SDimitry Andric       match(Cmp1, m_ICmp(Pred1, m_Intrinsic<Intrinsic::ctpop>(m_Specific(X)),
9040b57cec5SDimitry Andric                          m_SpecificInt(2))) &&
9050b57cec5SDimitry Andric       Pred0 == ICmpInst::ICMP_NE && Pred1 == ICmpInst::ICMP_ULT) {
9060b57cec5SDimitry Andric     Value *CtPop = Cmp1->getOperand(0);
9070b57cec5SDimitry Andric     return Builder.CreateICmpEQ(CtPop, ConstantInt::get(CtPop->getType(), 1));
9080b57cec5SDimitry Andric   }
9090b57cec5SDimitry Andric   // (X == 0) || (ctpop(X) u> 1) --> ctpop(X) != 1
9100b57cec5SDimitry Andric   if (!JoinedByAnd && match(Cmp0, m_ICmp(Pred0, m_Value(X), m_ZeroInt())) &&
9110b57cec5SDimitry Andric       match(Cmp1, m_ICmp(Pred1, m_Intrinsic<Intrinsic::ctpop>(m_Specific(X)),
9120b57cec5SDimitry Andric                          m_SpecificInt(1))) &&
9130b57cec5SDimitry Andric       Pred0 == ICmpInst::ICMP_EQ && Pred1 == ICmpInst::ICMP_UGT) {
9140b57cec5SDimitry Andric     Value *CtPop = Cmp1->getOperand(0);
9150b57cec5SDimitry Andric     return Builder.CreateICmpNE(CtPop, ConstantInt::get(CtPop->getType(), 1));
9160b57cec5SDimitry Andric   }
9170b57cec5SDimitry Andric   return nullptr;
9180b57cec5SDimitry Andric }
9190b57cec5SDimitry Andric 
92006c3fb27SDimitry Andric /// Try to fold (icmp(A & B) == 0) & (icmp(A & D) != E) into (icmp A u< D) iff
92106c3fb27SDimitry Andric /// B is a contiguous set of ones starting from the most significant bit
92206c3fb27SDimitry Andric /// (negative power of 2), D and E are equal, and D is a contiguous set of ones
92306c3fb27SDimitry Andric /// starting at the most significant zero bit in B. Parameter B supports masking
92406c3fb27SDimitry Andric /// using undef/poison in either scalar or vector values.
foldNegativePower2AndShiftedMask(Value * A,Value * B,Value * D,Value * E,ICmpInst::Predicate PredL,ICmpInst::Predicate PredR,InstCombiner::BuilderTy & Builder)92506c3fb27SDimitry Andric static Value *foldNegativePower2AndShiftedMask(
92606c3fb27SDimitry Andric     Value *A, Value *B, Value *D, Value *E, ICmpInst::Predicate PredL,
92706c3fb27SDimitry Andric     ICmpInst::Predicate PredR, InstCombiner::BuilderTy &Builder) {
92806c3fb27SDimitry Andric   assert(ICmpInst::isEquality(PredL) && ICmpInst::isEquality(PredR) &&
92906c3fb27SDimitry Andric          "Expected equality predicates for masked type of icmps.");
93006c3fb27SDimitry Andric   if (PredL != ICmpInst::ICMP_EQ || PredR != ICmpInst::ICMP_NE)
93106c3fb27SDimitry Andric     return nullptr;
93206c3fb27SDimitry Andric 
93306c3fb27SDimitry Andric   if (!match(B, m_NegatedPower2()) || !match(D, m_ShiftedMask()) ||
93406c3fb27SDimitry Andric       !match(E, m_ShiftedMask()))
93506c3fb27SDimitry Andric     return nullptr;
93606c3fb27SDimitry Andric 
93706c3fb27SDimitry Andric   // Test scalar arguments for conversion. B has been validated earlier to be a
93806c3fb27SDimitry Andric   // negative power of two and thus is guaranteed to have one or more contiguous
93906c3fb27SDimitry Andric   // ones starting from the MSB followed by zero or more contiguous zeros. D has
94006c3fb27SDimitry Andric   // been validated earlier to be a shifted set of one or more contiguous ones.
94106c3fb27SDimitry Andric   // In order to match, B leading ones and D leading zeros should be equal. The
94206c3fb27SDimitry Andric   // predicate that B be a negative power of 2 prevents the condition of there
94306c3fb27SDimitry Andric   // ever being zero leading ones. Thus 0 == 0 cannot occur. The predicate that
94406c3fb27SDimitry Andric   // D always be a shifted mask prevents the condition of D equaling 0. This
94506c3fb27SDimitry Andric   // prevents matching the condition where B contains the maximum number of
94606c3fb27SDimitry Andric   // leading one bits (-1) and D contains the maximum number of leading zero
94706c3fb27SDimitry Andric   // bits (0).
94806c3fb27SDimitry Andric   auto isReducible = [](const Value *B, const Value *D, const Value *E) {
94906c3fb27SDimitry Andric     const APInt *BCst, *DCst, *ECst;
95006c3fb27SDimitry Andric     return match(B, m_APIntAllowUndef(BCst)) && match(D, m_APInt(DCst)) &&
95106c3fb27SDimitry Andric            match(E, m_APInt(ECst)) && *DCst == *ECst &&
95206c3fb27SDimitry Andric            (isa<UndefValue>(B) ||
95306c3fb27SDimitry Andric             (BCst->countLeadingOnes() == DCst->countLeadingZeros()));
95406c3fb27SDimitry Andric   };
95506c3fb27SDimitry Andric 
95606c3fb27SDimitry Andric   // Test vector type arguments for conversion.
95706c3fb27SDimitry Andric   if (const auto *BVTy = dyn_cast<VectorType>(B->getType())) {
95806c3fb27SDimitry Andric     const auto *BFVTy = dyn_cast<FixedVectorType>(BVTy);
95906c3fb27SDimitry Andric     const auto *BConst = dyn_cast<Constant>(B);
96006c3fb27SDimitry Andric     const auto *DConst = dyn_cast<Constant>(D);
96106c3fb27SDimitry Andric     const auto *EConst = dyn_cast<Constant>(E);
96206c3fb27SDimitry Andric 
96306c3fb27SDimitry Andric     if (!BFVTy || !BConst || !DConst || !EConst)
96406c3fb27SDimitry Andric       return nullptr;
96506c3fb27SDimitry Andric 
96606c3fb27SDimitry Andric     for (unsigned I = 0; I != BFVTy->getNumElements(); ++I) {
96706c3fb27SDimitry Andric       const auto *BElt = BConst->getAggregateElement(I);
96806c3fb27SDimitry Andric       const auto *DElt = DConst->getAggregateElement(I);
96906c3fb27SDimitry Andric       const auto *EElt = EConst->getAggregateElement(I);
97006c3fb27SDimitry Andric 
97106c3fb27SDimitry Andric       if (!BElt || !DElt || !EElt)
97206c3fb27SDimitry Andric         return nullptr;
97306c3fb27SDimitry Andric       if (!isReducible(BElt, DElt, EElt))
97406c3fb27SDimitry Andric         return nullptr;
97506c3fb27SDimitry Andric     }
97606c3fb27SDimitry Andric   } else {
97706c3fb27SDimitry Andric     // Test scalar type arguments for conversion.
97806c3fb27SDimitry Andric     if (!isReducible(B, D, E))
97906c3fb27SDimitry Andric       return nullptr;
98006c3fb27SDimitry Andric   }
98106c3fb27SDimitry Andric   return Builder.CreateICmp(ICmpInst::ICMP_ULT, A, D);
98206c3fb27SDimitry Andric }
98306c3fb27SDimitry Andric 
98406c3fb27SDimitry Andric /// Try to fold ((icmp X u< P) & (icmp(X & M) != M)) or ((icmp X s> -1) &
98506c3fb27SDimitry Andric /// (icmp(X & M) != M)) into (icmp X u< M). Where P is a power of 2, M < P, and
98606c3fb27SDimitry Andric /// M is a contiguous shifted mask starting at the right most significant zero
98706c3fb27SDimitry Andric /// bit in P. SGT is supported as when P is the largest representable power of
98806c3fb27SDimitry Andric /// 2, an earlier optimization converts the expression into (icmp X s> -1).
98906c3fb27SDimitry Andric /// Parameter P supports masking using undef/poison in either scalar or vector
99006c3fb27SDimitry Andric /// values.
foldPowerOf2AndShiftedMask(ICmpInst * Cmp0,ICmpInst * Cmp1,bool JoinedByAnd,InstCombiner::BuilderTy & Builder)99106c3fb27SDimitry Andric static Value *foldPowerOf2AndShiftedMask(ICmpInst *Cmp0, ICmpInst *Cmp1,
99206c3fb27SDimitry Andric                                          bool JoinedByAnd,
99306c3fb27SDimitry Andric                                          InstCombiner::BuilderTy &Builder) {
99406c3fb27SDimitry Andric   if (!JoinedByAnd)
99506c3fb27SDimitry Andric     return nullptr;
99606c3fb27SDimitry Andric   Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr, *E = nullptr;
99706c3fb27SDimitry Andric   ICmpInst::Predicate CmpPred0 = Cmp0->getPredicate(),
99806c3fb27SDimitry Andric                       CmpPred1 = Cmp1->getPredicate();
99906c3fb27SDimitry Andric   // Assuming P is a 2^n, getMaskedTypeForICmpPair will normalize (icmp X u<
100006c3fb27SDimitry Andric   // 2^n) into (icmp (X & ~(2^n-1)) == 0) and (icmp X s> -1) into (icmp (X &
100106c3fb27SDimitry Andric   // SignMask) == 0).
100206c3fb27SDimitry Andric   std::optional<std::pair<unsigned, unsigned>> MaskPair =
100306c3fb27SDimitry Andric       getMaskedTypeForICmpPair(A, B, C, D, E, Cmp0, Cmp1, CmpPred0, CmpPred1);
100406c3fb27SDimitry Andric   if (!MaskPair)
100506c3fb27SDimitry Andric     return nullptr;
100606c3fb27SDimitry Andric 
100706c3fb27SDimitry Andric   const auto compareBMask = BMask_NotMixed | BMask_NotAllOnes;
100806c3fb27SDimitry Andric   unsigned CmpMask0 = MaskPair->first;
100906c3fb27SDimitry Andric   unsigned CmpMask1 = MaskPair->second;
101006c3fb27SDimitry Andric   if ((CmpMask0 & Mask_AllZeros) && (CmpMask1 == compareBMask)) {
101106c3fb27SDimitry Andric     if (Value *V = foldNegativePower2AndShiftedMask(A, B, D, E, CmpPred0,
101206c3fb27SDimitry Andric                                                     CmpPred1, Builder))
101306c3fb27SDimitry Andric       return V;
101406c3fb27SDimitry Andric   } else if ((CmpMask0 == compareBMask) && (CmpMask1 & Mask_AllZeros)) {
101506c3fb27SDimitry Andric     if (Value *V = foldNegativePower2AndShiftedMask(A, D, B, C, CmpPred1,
101606c3fb27SDimitry Andric                                                     CmpPred0, Builder))
101706c3fb27SDimitry Andric       return V;
101806c3fb27SDimitry Andric   }
101906c3fb27SDimitry Andric   return nullptr;
102006c3fb27SDimitry Andric }
102106c3fb27SDimitry Andric 
10228bcb0991SDimitry Andric /// Commuted variants are assumed to be handled by calling this function again
10238bcb0991SDimitry Andric /// with the parameters swapped.
foldUnsignedUnderflowCheck(ICmpInst * ZeroICmp,ICmpInst * UnsignedICmp,bool IsAnd,const SimplifyQuery & Q,InstCombiner::BuilderTy & Builder)10248bcb0991SDimitry Andric static Value *foldUnsignedUnderflowCheck(ICmpInst *ZeroICmp,
10258bcb0991SDimitry Andric                                          ICmpInst *UnsignedICmp, bool IsAnd,
10268bcb0991SDimitry Andric                                          const SimplifyQuery &Q,
10278bcb0991SDimitry Andric                                          InstCombiner::BuilderTy &Builder) {
10288bcb0991SDimitry Andric   Value *ZeroCmpOp;
10298bcb0991SDimitry Andric   ICmpInst::Predicate EqPred;
10308bcb0991SDimitry Andric   if (!match(ZeroICmp, m_ICmp(EqPred, m_Value(ZeroCmpOp), m_Zero())) ||
10318bcb0991SDimitry Andric       !ICmpInst::isEquality(EqPred))
10328bcb0991SDimitry Andric     return nullptr;
10338bcb0991SDimitry Andric 
10348bcb0991SDimitry Andric   auto IsKnownNonZero = [&](Value *V) {
10358bcb0991SDimitry Andric     return isKnownNonZero(V, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT);
10368bcb0991SDimitry Andric   };
10378bcb0991SDimitry Andric 
10388bcb0991SDimitry Andric   ICmpInst::Predicate UnsignedPred;
10398bcb0991SDimitry Andric 
10408bcb0991SDimitry Andric   Value *A, *B;
10418bcb0991SDimitry Andric   if (match(UnsignedICmp,
10428bcb0991SDimitry Andric             m_c_ICmp(UnsignedPred, m_Specific(ZeroCmpOp), m_Value(A))) &&
10438bcb0991SDimitry Andric       match(ZeroCmpOp, m_c_Add(m_Specific(A), m_Value(B))) &&
10448bcb0991SDimitry Andric       (ZeroICmp->hasOneUse() || UnsignedICmp->hasOneUse())) {
10458bcb0991SDimitry Andric     auto GetKnownNonZeroAndOther = [&](Value *&NonZero, Value *&Other) {
10468bcb0991SDimitry Andric       if (!IsKnownNonZero(NonZero))
10478bcb0991SDimitry Andric         std::swap(NonZero, Other);
10488bcb0991SDimitry Andric       return IsKnownNonZero(NonZero);
10498bcb0991SDimitry Andric     };
10508bcb0991SDimitry Andric 
10518bcb0991SDimitry Andric     // Given  ZeroCmpOp = (A + B)
10528bcb0991SDimitry Andric     //   ZeroCmpOp <  A && ZeroCmpOp != 0  -->  (0-X) <  Y  iff
10538bcb0991SDimitry Andric     //   ZeroCmpOp >= A || ZeroCmpOp == 0  -->  (0-X) >= Y  iff
10548bcb0991SDimitry Andric     //     with X being the value (A/B) that is known to be non-zero,
10558bcb0991SDimitry Andric     //     and Y being remaining value.
10568bcb0991SDimitry Andric     if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_NE &&
10578bcb0991SDimitry Andric         IsAnd && GetKnownNonZeroAndOther(B, A))
10588bcb0991SDimitry Andric       return Builder.CreateICmpULT(Builder.CreateNeg(B), A);
10598bcb0991SDimitry Andric     if (UnsignedPred == ICmpInst::ICMP_UGE && EqPred == ICmpInst::ICMP_EQ &&
10608bcb0991SDimitry Andric         !IsAnd && GetKnownNonZeroAndOther(B, A))
10618bcb0991SDimitry Andric       return Builder.CreateICmpUGE(Builder.CreateNeg(B), A);
10628bcb0991SDimitry Andric   }
10638bcb0991SDimitry Andric 
10648bcb0991SDimitry Andric   return nullptr;
10658bcb0991SDimitry Andric }
10668bcb0991SDimitry Andric 
1067fe6060f1SDimitry Andric struct IntPart {
1068fe6060f1SDimitry Andric   Value *From;
1069fe6060f1SDimitry Andric   unsigned StartBit;
1070fe6060f1SDimitry Andric   unsigned NumBits;
1071fe6060f1SDimitry Andric };
1072fe6060f1SDimitry Andric 
1073fe6060f1SDimitry Andric /// Match an extraction of bits from an integer.
matchIntPart(Value * V)1074bdd1243dSDimitry Andric static std::optional<IntPart> matchIntPart(Value *V) {
1075fe6060f1SDimitry Andric   Value *X;
1076fe6060f1SDimitry Andric   if (!match(V, m_OneUse(m_Trunc(m_Value(X)))))
1077bdd1243dSDimitry Andric     return std::nullopt;
1078fe6060f1SDimitry Andric 
1079fe6060f1SDimitry Andric   unsigned NumOriginalBits = X->getType()->getScalarSizeInBits();
1080fe6060f1SDimitry Andric   unsigned NumExtractedBits = V->getType()->getScalarSizeInBits();
1081fe6060f1SDimitry Andric   Value *Y;
1082fe6060f1SDimitry Andric   const APInt *Shift;
1083fe6060f1SDimitry Andric   // For a trunc(lshr Y, Shift) pattern, make sure we're only extracting bits
1084fe6060f1SDimitry Andric   // from Y, not any shifted-in zeroes.
1085fe6060f1SDimitry Andric   if (match(X, m_OneUse(m_LShr(m_Value(Y), m_APInt(Shift)))) &&
1086fe6060f1SDimitry Andric       Shift->ule(NumOriginalBits - NumExtractedBits))
1087fe6060f1SDimitry Andric     return {{Y, (unsigned)Shift->getZExtValue(), NumExtractedBits}};
1088fe6060f1SDimitry Andric   return {{X, 0, NumExtractedBits}};
1089fe6060f1SDimitry Andric }
1090fe6060f1SDimitry Andric 
1091fe6060f1SDimitry Andric /// Materialize an extraction of bits from an integer in IR.
extractIntPart(const IntPart & P,IRBuilderBase & Builder)1092fe6060f1SDimitry Andric static Value *extractIntPart(const IntPart &P, IRBuilderBase &Builder) {
1093fe6060f1SDimitry Andric   Value *V = P.From;
1094fe6060f1SDimitry Andric   if (P.StartBit)
1095fe6060f1SDimitry Andric     V = Builder.CreateLShr(V, P.StartBit);
1096fe6060f1SDimitry Andric   Type *TruncTy = V->getType()->getWithNewBitWidth(P.NumBits);
1097fe6060f1SDimitry Andric   if (TruncTy != V->getType())
1098fe6060f1SDimitry Andric     V = Builder.CreateTrunc(V, TruncTy);
1099fe6060f1SDimitry Andric   return V;
1100fe6060f1SDimitry Andric }
1101fe6060f1SDimitry Andric 
1102fe6060f1SDimitry Andric /// (icmp eq X0, Y0) & (icmp eq X1, Y1) -> icmp eq X01, Y01
1103fe6060f1SDimitry Andric /// (icmp ne X0, Y0) | (icmp ne X1, Y1) -> icmp ne X01, Y01
1104fe6060f1SDimitry Andric /// where X0, X1 and Y0, Y1 are adjacent parts extracted from an integer.
foldEqOfParts(ICmpInst * Cmp0,ICmpInst * Cmp1,bool IsAnd)1105349cc55cSDimitry Andric Value *InstCombinerImpl::foldEqOfParts(ICmpInst *Cmp0, ICmpInst *Cmp1,
1106349cc55cSDimitry Andric                                        bool IsAnd) {
1107fe6060f1SDimitry Andric   if (!Cmp0->hasOneUse() || !Cmp1->hasOneUse())
1108fe6060f1SDimitry Andric     return nullptr;
1109fe6060f1SDimitry Andric 
1110fe6060f1SDimitry Andric   CmpInst::Predicate Pred = IsAnd ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;
11115f757f3fSDimitry Andric   auto GetMatchPart = [&](ICmpInst *Cmp,
11125f757f3fSDimitry Andric                           unsigned OpNo) -> std::optional<IntPart> {
11135f757f3fSDimitry Andric     if (Pred == Cmp->getPredicate())
11145f757f3fSDimitry Andric       return matchIntPart(Cmp->getOperand(OpNo));
1115fe6060f1SDimitry Andric 
11165f757f3fSDimitry Andric     const APInt *C;
11175f757f3fSDimitry Andric     // (icmp eq (lshr x, C), (lshr y, C)) gets optimized to:
11185f757f3fSDimitry Andric     // (icmp ult (xor x, y), 1 << C) so also look for that.
11195f757f3fSDimitry Andric     if (Pred == CmpInst::ICMP_EQ && Cmp->getPredicate() == CmpInst::ICMP_ULT) {
11205f757f3fSDimitry Andric       if (!match(Cmp->getOperand(1), m_Power2(C)) ||
11215f757f3fSDimitry Andric           !match(Cmp->getOperand(0), m_Xor(m_Value(), m_Value())))
11225f757f3fSDimitry Andric         return std::nullopt;
11235f757f3fSDimitry Andric     }
11245f757f3fSDimitry Andric 
11255f757f3fSDimitry Andric     // (icmp ne (lshr x, C), (lshr y, C)) gets optimized to:
11265f757f3fSDimitry Andric     // (icmp ugt (xor x, y), (1 << C) - 1) so also look for that.
11275f757f3fSDimitry Andric     else if (Pred == CmpInst::ICMP_NE &&
11285f757f3fSDimitry Andric              Cmp->getPredicate() == CmpInst::ICMP_UGT) {
11295f757f3fSDimitry Andric       if (!match(Cmp->getOperand(1), m_LowBitMask(C)) ||
11305f757f3fSDimitry Andric           !match(Cmp->getOperand(0), m_Xor(m_Value(), m_Value())))
11315f757f3fSDimitry Andric         return std::nullopt;
11325f757f3fSDimitry Andric     } else {
11335f757f3fSDimitry Andric       return std::nullopt;
11345f757f3fSDimitry Andric     }
11355f757f3fSDimitry Andric 
11365f757f3fSDimitry Andric     unsigned From = Pred == CmpInst::ICMP_NE ? C->popcount() : C->countr_zero();
11375f757f3fSDimitry Andric     Instruction *I = cast<Instruction>(Cmp->getOperand(0));
11385f757f3fSDimitry Andric     return {{I->getOperand(OpNo), From, C->getBitWidth() - From}};
11395f757f3fSDimitry Andric   };
11405f757f3fSDimitry Andric 
11415f757f3fSDimitry Andric   std::optional<IntPart> L0 = GetMatchPart(Cmp0, 0);
11425f757f3fSDimitry Andric   std::optional<IntPart> R0 = GetMatchPart(Cmp0, 1);
11435f757f3fSDimitry Andric   std::optional<IntPart> L1 = GetMatchPart(Cmp1, 0);
11445f757f3fSDimitry Andric   std::optional<IntPart> R1 = GetMatchPart(Cmp1, 1);
1145fe6060f1SDimitry Andric   if (!L0 || !R0 || !L1 || !R1)
1146fe6060f1SDimitry Andric     return nullptr;
1147fe6060f1SDimitry Andric 
1148fe6060f1SDimitry Andric   // Make sure the LHS/RHS compare a part of the same value, possibly after
1149fe6060f1SDimitry Andric   // an operand swap.
1150fe6060f1SDimitry Andric   if (L0->From != L1->From || R0->From != R1->From) {
1151fe6060f1SDimitry Andric     if (L0->From != R1->From || R0->From != L1->From)
1152fe6060f1SDimitry Andric       return nullptr;
1153fe6060f1SDimitry Andric     std::swap(L1, R1);
1154fe6060f1SDimitry Andric   }
1155fe6060f1SDimitry Andric 
1156fe6060f1SDimitry Andric   // Make sure the extracted parts are adjacent, canonicalizing to L0/R0 being
1157fe6060f1SDimitry Andric   // the low part and L1/R1 being the high part.
1158fe6060f1SDimitry Andric   if (L0->StartBit + L0->NumBits != L1->StartBit ||
1159fe6060f1SDimitry Andric       R0->StartBit + R0->NumBits != R1->StartBit) {
1160fe6060f1SDimitry Andric     if (L1->StartBit + L1->NumBits != L0->StartBit ||
1161fe6060f1SDimitry Andric         R1->StartBit + R1->NumBits != R0->StartBit)
1162fe6060f1SDimitry Andric       return nullptr;
1163fe6060f1SDimitry Andric     std::swap(L0, L1);
1164fe6060f1SDimitry Andric     std::swap(R0, R1);
1165fe6060f1SDimitry Andric   }
1166fe6060f1SDimitry Andric 
1167fe6060f1SDimitry Andric   // We can simplify to a comparison of these larger parts of the integers.
1168fe6060f1SDimitry Andric   IntPart L = {L0->From, L0->StartBit, L0->NumBits + L1->NumBits};
1169fe6060f1SDimitry Andric   IntPart R = {R0->From, R0->StartBit, R0->NumBits + R1->NumBits};
1170fe6060f1SDimitry Andric   Value *LValue = extractIntPart(L, Builder);
1171fe6060f1SDimitry Andric   Value *RValue = extractIntPart(R, Builder);
1172fe6060f1SDimitry Andric   return Builder.CreateICmp(Pred, LValue, RValue);
1173fe6060f1SDimitry Andric }
1174fe6060f1SDimitry Andric 
11755ffd83dbSDimitry Andric /// Reduce logic-of-compares with equality to a constant by substituting a
11765ffd83dbSDimitry Andric /// common operand with the constant. Callers are expected to call this with
11775ffd83dbSDimitry Andric /// Cmp0/Cmp1 switched to handle logic op commutativity.
foldAndOrOfICmpsWithConstEq(ICmpInst * Cmp0,ICmpInst * Cmp1,bool IsAnd,bool IsLogical,InstCombiner::BuilderTy & Builder,const SimplifyQuery & Q)11785ffd83dbSDimitry Andric static Value *foldAndOrOfICmpsWithConstEq(ICmpInst *Cmp0, ICmpInst *Cmp1,
1179bdd1243dSDimitry Andric                                           bool IsAnd, bool IsLogical,
11805ffd83dbSDimitry Andric                                           InstCombiner::BuilderTy &Builder,
11815ffd83dbSDimitry Andric                                           const SimplifyQuery &Q) {
11825ffd83dbSDimitry Andric   // Match an equality compare with a non-poison constant as Cmp0.
1183590d96feSDimitry Andric   // Also, give up if the compare can be constant-folded to avoid looping.
11845ffd83dbSDimitry Andric   ICmpInst::Predicate Pred0;
11855ffd83dbSDimitry Andric   Value *X;
11865ffd83dbSDimitry Andric   Constant *C;
11875ffd83dbSDimitry Andric   if (!match(Cmp0, m_ICmp(Pred0, m_Value(X), m_Constant(C))) ||
1188590d96feSDimitry Andric       !isGuaranteedNotToBeUndefOrPoison(C) || isa<Constant>(X))
11895ffd83dbSDimitry Andric     return nullptr;
11905ffd83dbSDimitry Andric   if ((IsAnd && Pred0 != ICmpInst::ICMP_EQ) ||
11915ffd83dbSDimitry Andric       (!IsAnd && Pred0 != ICmpInst::ICMP_NE))
11925ffd83dbSDimitry Andric     return nullptr;
11935ffd83dbSDimitry Andric 
11945ffd83dbSDimitry Andric   // The other compare must include a common operand (X). Canonicalize the
11955ffd83dbSDimitry Andric   // common operand as operand 1 (Pred1 is swapped if the common operand was
11965ffd83dbSDimitry Andric   // operand 0).
11975ffd83dbSDimitry Andric   Value *Y;
11985ffd83dbSDimitry Andric   ICmpInst::Predicate Pred1;
11995ffd83dbSDimitry Andric   if (!match(Cmp1, m_c_ICmp(Pred1, m_Value(Y), m_Deferred(X))))
12005ffd83dbSDimitry Andric     return nullptr;
12015ffd83dbSDimitry Andric 
12025ffd83dbSDimitry Andric   // Replace variable with constant value equivalence to remove a variable use:
12035ffd83dbSDimitry Andric   // (X == C) && (Y Pred1 X) --> (X == C) && (Y Pred1 C)
12045ffd83dbSDimitry Andric   // (X != C) || (Y Pred1 X) --> (X != C) || (Y Pred1 C)
12055ffd83dbSDimitry Andric   // Can think of the 'or' substitution with the 'and' bool equivalent:
12065ffd83dbSDimitry Andric   // A || B --> A || (!A && B)
120781ad6265SDimitry Andric   Value *SubstituteCmp = simplifyICmpInst(Pred1, Y, C, Q);
12085ffd83dbSDimitry Andric   if (!SubstituteCmp) {
12095ffd83dbSDimitry Andric     // If we need to create a new instruction, require that the old compare can
12105ffd83dbSDimitry Andric     // be removed.
12115ffd83dbSDimitry Andric     if (!Cmp1->hasOneUse())
12125ffd83dbSDimitry Andric       return nullptr;
12135ffd83dbSDimitry Andric     SubstituteCmp = Builder.CreateICmp(Pred1, Y, C);
12145ffd83dbSDimitry Andric   }
1215bdd1243dSDimitry Andric   if (IsLogical)
1216bdd1243dSDimitry Andric     return IsAnd ? Builder.CreateLogicalAnd(Cmp0, SubstituteCmp)
1217bdd1243dSDimitry Andric                  : Builder.CreateLogicalOr(Cmp0, SubstituteCmp);
121881ad6265SDimitry Andric   return Builder.CreateBinOp(IsAnd ? Instruction::And : Instruction::Or, Cmp0,
121981ad6265SDimitry Andric                              SubstituteCmp);
12205ffd83dbSDimitry Andric }
12215ffd83dbSDimitry Andric 
1222349cc55cSDimitry Andric /// Fold (icmp Pred1 V1, C1) & (icmp Pred2 V2, C2)
1223349cc55cSDimitry Andric /// or   (icmp Pred1 V1, C1) | (icmp Pred2 V2, C2)
1224349cc55cSDimitry Andric /// into a single comparison using range-based reasoning.
122581ad6265SDimitry Andric /// NOTE: This is also used for logical and/or, must be poison-safe!
foldAndOrOfICmpsUsingRanges(ICmpInst * ICmp1,ICmpInst * ICmp2,bool IsAnd)122681ad6265SDimitry Andric Value *InstCombinerImpl::foldAndOrOfICmpsUsingRanges(ICmpInst *ICmp1,
122781ad6265SDimitry Andric                                                      ICmpInst *ICmp2,
122881ad6265SDimitry Andric                                                      bool IsAnd) {
122981ad6265SDimitry Andric   ICmpInst::Predicate Pred1, Pred2;
123081ad6265SDimitry Andric   Value *V1, *V2;
123181ad6265SDimitry Andric   const APInt *C1, *C2;
123281ad6265SDimitry Andric   if (!match(ICmp1, m_ICmp(Pred1, m_Value(V1), m_APInt(C1))) ||
123381ad6265SDimitry Andric       !match(ICmp2, m_ICmp(Pred2, m_Value(V2), m_APInt(C2))))
123481ad6265SDimitry Andric     return nullptr;
123581ad6265SDimitry Andric 
1236349cc55cSDimitry Andric   // Look through add of a constant offset on V1, V2, or both operands. This
1237349cc55cSDimitry Andric   // allows us to interpret the V + C' < C'' range idiom into a proper range.
1238349cc55cSDimitry Andric   const APInt *Offset1 = nullptr, *Offset2 = nullptr;
1239349cc55cSDimitry Andric   if (V1 != V2) {
1240349cc55cSDimitry Andric     Value *X;
1241349cc55cSDimitry Andric     if (match(V1, m_Add(m_Value(X), m_APInt(Offset1))))
1242349cc55cSDimitry Andric       V1 = X;
1243349cc55cSDimitry Andric     if (match(V2, m_Add(m_Value(X), m_APInt(Offset2))))
1244349cc55cSDimitry Andric       V2 = X;
1245349cc55cSDimitry Andric   }
1246349cc55cSDimitry Andric 
1247349cc55cSDimitry Andric   if (V1 != V2)
1248349cc55cSDimitry Andric     return nullptr;
1249349cc55cSDimitry Andric 
125081ad6265SDimitry Andric   ConstantRange CR1 = ConstantRange::makeExactICmpRegion(
125181ad6265SDimitry Andric       IsAnd ? ICmpInst::getInversePredicate(Pred1) : Pred1, *C1);
1252349cc55cSDimitry Andric   if (Offset1)
1253349cc55cSDimitry Andric     CR1 = CR1.subtract(*Offset1);
1254349cc55cSDimitry Andric 
125581ad6265SDimitry Andric   ConstantRange CR2 = ConstantRange::makeExactICmpRegion(
125681ad6265SDimitry Andric       IsAnd ? ICmpInst::getInversePredicate(Pred2) : Pred2, *C2);
1257349cc55cSDimitry Andric   if (Offset2)
1258349cc55cSDimitry Andric     CR2 = CR2.subtract(*Offset2);
1259349cc55cSDimitry Andric 
126081ad6265SDimitry Andric   Type *Ty = V1->getType();
126181ad6265SDimitry Andric   Value *NewV = V1;
1262bdd1243dSDimitry Andric   std::optional<ConstantRange> CR = CR1.exactUnionWith(CR2);
126381ad6265SDimitry Andric   if (!CR) {
126481ad6265SDimitry Andric     if (!(ICmp1->hasOneUse() && ICmp2->hasOneUse()) || CR1.isWrappedSet() ||
126581ad6265SDimitry Andric         CR2.isWrappedSet())
1266349cc55cSDimitry Andric       return nullptr;
1267349cc55cSDimitry Andric 
126881ad6265SDimitry Andric     // Check whether we have equal-size ranges that only differ by one bit.
126981ad6265SDimitry Andric     // In that case we can apply a mask to map one range onto the other.
127081ad6265SDimitry Andric     APInt LowerDiff = CR1.getLower() ^ CR2.getLower();
127181ad6265SDimitry Andric     APInt UpperDiff = (CR1.getUpper() - 1) ^ (CR2.getUpper() - 1);
127281ad6265SDimitry Andric     APInt CR1Size = CR1.getUpper() - CR1.getLower();
127381ad6265SDimitry Andric     if (!LowerDiff.isPowerOf2() || LowerDiff != UpperDiff ||
127481ad6265SDimitry Andric         CR1Size != CR2.getUpper() - CR2.getLower())
127581ad6265SDimitry Andric       return nullptr;
127681ad6265SDimitry Andric 
127781ad6265SDimitry Andric     CR = CR1.getLower().ult(CR2.getLower()) ? CR1 : CR2;
127881ad6265SDimitry Andric     NewV = Builder.CreateAnd(NewV, ConstantInt::get(Ty, ~LowerDiff));
127981ad6265SDimitry Andric   }
128081ad6265SDimitry Andric 
128181ad6265SDimitry Andric   if (IsAnd)
128281ad6265SDimitry Andric     CR = CR->inverse();
128381ad6265SDimitry Andric 
1284349cc55cSDimitry Andric   CmpInst::Predicate NewPred;
1285349cc55cSDimitry Andric   APInt NewC, Offset;
1286349cc55cSDimitry Andric   CR->getEquivalentICmp(NewPred, NewC, Offset);
1287349cc55cSDimitry Andric 
1288349cc55cSDimitry Andric   if (Offset != 0)
1289349cc55cSDimitry Andric     NewV = Builder.CreateAdd(NewV, ConstantInt::get(Ty, Offset));
1290349cc55cSDimitry Andric   return Builder.CreateICmp(NewPred, NewV, ConstantInt::get(Ty, NewC));
1291349cc55cSDimitry Andric }
1292349cc55cSDimitry Andric 
1293bdd1243dSDimitry Andric /// Ignore all operations which only change the sign of a value, returning the
1294bdd1243dSDimitry Andric /// underlying magnitude value.
stripSignOnlyFPOps(Value * Val)1295bdd1243dSDimitry Andric static Value *stripSignOnlyFPOps(Value *Val) {
1296bdd1243dSDimitry Andric   match(Val, m_FNeg(m_Value(Val)));
1297bdd1243dSDimitry Andric   match(Val, m_FAbs(m_Value(Val)));
1298bdd1243dSDimitry Andric   match(Val, m_CopySign(m_Value(Val), m_Value()));
1299bdd1243dSDimitry Andric   return Val;
1300bdd1243dSDimitry Andric }
1301bdd1243dSDimitry Andric 
1302bdd1243dSDimitry Andric /// Matches canonical form of isnan, fcmp ord x, 0
matchIsNotNaN(FCmpInst::Predicate P,Value * LHS,Value * RHS)1303bdd1243dSDimitry Andric static bool matchIsNotNaN(FCmpInst::Predicate P, Value *LHS, Value *RHS) {
1304bdd1243dSDimitry Andric   return P == FCmpInst::FCMP_ORD && match(RHS, m_AnyZeroFP());
1305bdd1243dSDimitry Andric }
1306bdd1243dSDimitry Andric 
1307bdd1243dSDimitry Andric /// Matches fcmp u__ x, +/-inf
matchUnorderedInfCompare(FCmpInst::Predicate P,Value * LHS,Value * RHS)1308bdd1243dSDimitry Andric static bool matchUnorderedInfCompare(FCmpInst::Predicate P, Value *LHS,
1309bdd1243dSDimitry Andric                                      Value *RHS) {
1310bdd1243dSDimitry Andric   return FCmpInst::isUnordered(P) && match(RHS, m_Inf());
1311bdd1243dSDimitry Andric }
1312bdd1243dSDimitry Andric 
1313bdd1243dSDimitry Andric /// and (fcmp ord x, 0), (fcmp u* x, inf) -> fcmp o* x, inf
1314bdd1243dSDimitry Andric ///
1315bdd1243dSDimitry Andric /// Clang emits this pattern for doing an isfinite check in __builtin_isnormal.
matchIsFiniteTest(InstCombiner::BuilderTy & Builder,FCmpInst * LHS,FCmpInst * RHS)1316bdd1243dSDimitry Andric static Value *matchIsFiniteTest(InstCombiner::BuilderTy &Builder, FCmpInst *LHS,
1317bdd1243dSDimitry Andric                                 FCmpInst *RHS) {
1318bdd1243dSDimitry Andric   Value *LHS0 = LHS->getOperand(0), *LHS1 = LHS->getOperand(1);
1319bdd1243dSDimitry Andric   Value *RHS0 = RHS->getOperand(0), *RHS1 = RHS->getOperand(1);
1320bdd1243dSDimitry Andric   FCmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
1321bdd1243dSDimitry Andric 
1322bdd1243dSDimitry Andric   if (!matchIsNotNaN(PredL, LHS0, LHS1) ||
1323bdd1243dSDimitry Andric       !matchUnorderedInfCompare(PredR, RHS0, RHS1))
1324bdd1243dSDimitry Andric     return nullptr;
1325bdd1243dSDimitry Andric 
1326bdd1243dSDimitry Andric   IRBuilder<>::FastMathFlagGuard FMFG(Builder);
1327bdd1243dSDimitry Andric   FastMathFlags FMF = LHS->getFastMathFlags();
1328bdd1243dSDimitry Andric   FMF &= RHS->getFastMathFlags();
1329bdd1243dSDimitry Andric   Builder.setFastMathFlags(FMF);
1330bdd1243dSDimitry Andric 
1331bdd1243dSDimitry Andric   return Builder.CreateFCmp(FCmpInst::getOrderedPredicate(PredR), RHS0, RHS1);
1332bdd1243dSDimitry Andric }
1333bdd1243dSDimitry Andric 
foldLogicOfFCmps(FCmpInst * LHS,FCmpInst * RHS,bool IsAnd,bool IsLogicalSelect)1334e8d8bef9SDimitry Andric Value *InstCombinerImpl::foldLogicOfFCmps(FCmpInst *LHS, FCmpInst *RHS,
133581ad6265SDimitry Andric                                           bool IsAnd, bool IsLogicalSelect) {
13360b57cec5SDimitry Andric   Value *LHS0 = LHS->getOperand(0), *LHS1 = LHS->getOperand(1);
13370b57cec5SDimitry Andric   Value *RHS0 = RHS->getOperand(0), *RHS1 = RHS->getOperand(1);
13380b57cec5SDimitry Andric   FCmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
13390b57cec5SDimitry Andric 
13400b57cec5SDimitry Andric   if (LHS0 == RHS1 && RHS0 == LHS1) {
13410b57cec5SDimitry Andric     // Swap RHS operands to match LHS.
13420b57cec5SDimitry Andric     PredR = FCmpInst::getSwappedPredicate(PredR);
13430b57cec5SDimitry Andric     std::swap(RHS0, RHS1);
13440b57cec5SDimitry Andric   }
13450b57cec5SDimitry Andric 
13460b57cec5SDimitry Andric   // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
13470b57cec5SDimitry Andric   // Suppose the relation between x and y is R, where R is one of
13480b57cec5SDimitry Andric   // U(1000), L(0100), G(0010) or E(0001), and CC0 and CC1 are the bitmasks for
13490b57cec5SDimitry Andric   // testing the desired relations.
13500b57cec5SDimitry Andric   //
13510b57cec5SDimitry Andric   // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
13520b57cec5SDimitry Andric   //    bool(R & CC0) && bool(R & CC1)
13530b57cec5SDimitry Andric   //  = bool((R & CC0) & (R & CC1))
13540b57cec5SDimitry Andric   //  = bool(R & (CC0 & CC1)) <= by re-association, commutation, and idempotency
13550b57cec5SDimitry Andric   //
13560b57cec5SDimitry Andric   // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
13570b57cec5SDimitry Andric   //    bool(R & CC0) || bool(R & CC1)
13580b57cec5SDimitry Andric   //  = bool((R & CC0) | (R & CC1))
13590b57cec5SDimitry Andric   //  = bool(R & (CC0 | CC1)) <= by reversed distribution (contribution? ;)
13600b57cec5SDimitry Andric   if (LHS0 == RHS0 && LHS1 == RHS1) {
13610b57cec5SDimitry Andric     unsigned FCmpCodeL = getFCmpCode(PredL);
13620b57cec5SDimitry Andric     unsigned FCmpCodeR = getFCmpCode(PredR);
13630b57cec5SDimitry Andric     unsigned NewPred = IsAnd ? FCmpCodeL & FCmpCodeR : FCmpCodeL | FCmpCodeR;
136481ad6265SDimitry Andric 
136581ad6265SDimitry Andric     // Intersect the fast math flags.
136681ad6265SDimitry Andric     // TODO: We can union the fast math flags unless this is a logical select.
136781ad6265SDimitry Andric     IRBuilder<>::FastMathFlagGuard FMFG(Builder);
136881ad6265SDimitry Andric     FastMathFlags FMF = LHS->getFastMathFlags();
136981ad6265SDimitry Andric     FMF &= RHS->getFastMathFlags();
137081ad6265SDimitry Andric     Builder.setFastMathFlags(FMF);
137181ad6265SDimitry Andric 
13720b57cec5SDimitry Andric     return getFCmpValue(NewPred, LHS0, LHS1, Builder);
13730b57cec5SDimitry Andric   }
13740b57cec5SDimitry Andric 
137581ad6265SDimitry Andric   // This transform is not valid for a logical select.
137681ad6265SDimitry Andric   if (!IsLogicalSelect &&
137781ad6265SDimitry Andric       ((PredL == FCmpInst::FCMP_ORD && PredR == FCmpInst::FCMP_ORD && IsAnd) ||
137881ad6265SDimitry Andric        (PredL == FCmpInst::FCMP_UNO && PredR == FCmpInst::FCMP_UNO &&
137981ad6265SDimitry Andric         !IsAnd))) {
13800b57cec5SDimitry Andric     if (LHS0->getType() != RHS0->getType())
13810b57cec5SDimitry Andric       return nullptr;
13820b57cec5SDimitry Andric 
13830b57cec5SDimitry Andric     // FCmp canonicalization ensures that (fcmp ord/uno X, X) and
13840b57cec5SDimitry Andric     // (fcmp ord/uno X, C) will be transformed to (fcmp X, +0.0).
13850b57cec5SDimitry Andric     if (match(LHS1, m_PosZeroFP()) && match(RHS1, m_PosZeroFP()))
13860b57cec5SDimitry Andric       // Ignore the constants because they are obviously not NANs:
13870b57cec5SDimitry Andric       // (fcmp ord x, 0.0) & (fcmp ord y, 0.0)  -> (fcmp ord x, y)
13880b57cec5SDimitry Andric       // (fcmp uno x, 0.0) | (fcmp uno y, 0.0)  -> (fcmp uno x, y)
13890b57cec5SDimitry Andric       return Builder.CreateFCmp(PredL, LHS0, RHS0);
13900b57cec5SDimitry Andric   }
13910b57cec5SDimitry Andric 
1392bdd1243dSDimitry Andric   if (IsAnd && stripSignOnlyFPOps(LHS0) == stripSignOnlyFPOps(RHS0)) {
1393bdd1243dSDimitry Andric     // and (fcmp ord x, 0), (fcmp u* x, inf) -> fcmp o* x, inf
1394bdd1243dSDimitry Andric     // and (fcmp ord x, 0), (fcmp u* fabs(x), inf) -> fcmp o* x, inf
1395bdd1243dSDimitry Andric     if (Value *Left = matchIsFiniteTest(Builder, LHS, RHS))
1396bdd1243dSDimitry Andric       return Left;
1397bdd1243dSDimitry Andric     if (Value *Right = matchIsFiniteTest(Builder, RHS, LHS))
1398bdd1243dSDimitry Andric       return Right;
1399bdd1243dSDimitry Andric   }
1400bdd1243dSDimitry Andric 
140106c3fb27SDimitry Andric   // Turn at least two fcmps with constants into llvm.is.fpclass.
140206c3fb27SDimitry Andric   //
140306c3fb27SDimitry Andric   // If we can represent a combined value test with one class call, we can
140406c3fb27SDimitry Andric   // potentially eliminate 4-6 instructions. If we can represent a test with a
140506c3fb27SDimitry Andric   // single fcmp with fneg and fabs, that's likely a better canonical form.
140606c3fb27SDimitry Andric   if (LHS->hasOneUse() && RHS->hasOneUse()) {
140706c3fb27SDimitry Andric     auto [ClassValRHS, ClassMaskRHS] =
140806c3fb27SDimitry Andric         fcmpToClassTest(PredR, *RHS->getFunction(), RHS0, RHS1);
140906c3fb27SDimitry Andric     if (ClassValRHS) {
141006c3fb27SDimitry Andric       auto [ClassValLHS, ClassMaskLHS] =
141106c3fb27SDimitry Andric           fcmpToClassTest(PredL, *LHS->getFunction(), LHS0, LHS1);
141206c3fb27SDimitry Andric       if (ClassValLHS == ClassValRHS) {
141306c3fb27SDimitry Andric         unsigned CombinedMask = IsAnd ? (ClassMaskLHS & ClassMaskRHS)
141406c3fb27SDimitry Andric                                       : (ClassMaskLHS | ClassMaskRHS);
141506c3fb27SDimitry Andric         return Builder.CreateIntrinsic(
141606c3fb27SDimitry Andric             Intrinsic::is_fpclass, {ClassValLHS->getType()},
141706c3fb27SDimitry Andric             {ClassValLHS, Builder.getInt32(CombinedMask)});
141806c3fb27SDimitry Andric       }
141906c3fb27SDimitry Andric     }
142006c3fb27SDimitry Andric   }
142106c3fb27SDimitry Andric 
14220b57cec5SDimitry Andric   return nullptr;
14230b57cec5SDimitry Andric }
14240b57cec5SDimitry Andric 
142506c3fb27SDimitry Andric /// Match an fcmp against a special value that performs a test possible by
142606c3fb27SDimitry Andric /// llvm.is.fpclass.
matchIsFPClassLikeFCmp(Value * Op,Value * & ClassVal,uint64_t & ClassMask)142706c3fb27SDimitry Andric static bool matchIsFPClassLikeFCmp(Value *Op, Value *&ClassVal,
142806c3fb27SDimitry Andric                                    uint64_t &ClassMask) {
142906c3fb27SDimitry Andric   auto *FCmp = dyn_cast<FCmpInst>(Op);
143006c3fb27SDimitry Andric   if (!FCmp || !FCmp->hasOneUse())
143106c3fb27SDimitry Andric     return false;
143206c3fb27SDimitry Andric 
143306c3fb27SDimitry Andric   std::tie(ClassVal, ClassMask) =
143406c3fb27SDimitry Andric       fcmpToClassTest(FCmp->getPredicate(), *FCmp->getParent()->getParent(),
143506c3fb27SDimitry Andric                       FCmp->getOperand(0), FCmp->getOperand(1));
143606c3fb27SDimitry Andric   return ClassVal != nullptr;
143706c3fb27SDimitry Andric }
143806c3fb27SDimitry Andric 
1439bdd1243dSDimitry Andric /// or (is_fpclass x, mask0), (is_fpclass x, mask1)
1440bdd1243dSDimitry Andric ///     -> is_fpclass x, (mask0 | mask1)
1441bdd1243dSDimitry Andric /// and (is_fpclass x, mask0), (is_fpclass x, mask1)
1442bdd1243dSDimitry Andric ///     -> is_fpclass x, (mask0 & mask1)
1443bdd1243dSDimitry Andric /// xor (is_fpclass x, mask0), (is_fpclass x, mask1)
1444bdd1243dSDimitry Andric ///     -> is_fpclass x, (mask0 ^ mask1)
foldLogicOfIsFPClass(BinaryOperator & BO,Value * Op0,Value * Op1)1445bdd1243dSDimitry Andric Instruction *InstCombinerImpl::foldLogicOfIsFPClass(BinaryOperator &BO,
1446bdd1243dSDimitry Andric                                                     Value *Op0, Value *Op1) {
144706c3fb27SDimitry Andric   Value *ClassVal0 = nullptr;
144806c3fb27SDimitry Andric   Value *ClassVal1 = nullptr;
1449bdd1243dSDimitry Andric   uint64_t ClassMask0, ClassMask1;
1450bdd1243dSDimitry Andric 
145106c3fb27SDimitry Andric   // Restrict to folding one fcmp into one is.fpclass for now, don't introduce a
145206c3fb27SDimitry Andric   // new class.
145306c3fb27SDimitry Andric   //
145406c3fb27SDimitry Andric   // TODO: Support forming is.fpclass out of 2 separate fcmps when codegen is
145506c3fb27SDimitry Andric   // better.
145606c3fb27SDimitry Andric 
145706c3fb27SDimitry Andric   bool IsLHSClass =
145806c3fb27SDimitry Andric       match(Op0, m_OneUse(m_Intrinsic<Intrinsic::is_fpclass>(
145906c3fb27SDimitry Andric                      m_Value(ClassVal0), m_ConstantInt(ClassMask0))));
146006c3fb27SDimitry Andric   bool IsRHSClass =
1461bdd1243dSDimitry Andric       match(Op1, m_OneUse(m_Intrinsic<Intrinsic::is_fpclass>(
146206c3fb27SDimitry Andric                      m_Value(ClassVal1), m_ConstantInt(ClassMask1))));
146306c3fb27SDimitry Andric   if ((((IsLHSClass || matchIsFPClassLikeFCmp(Op0, ClassVal0, ClassMask0)) &&
146406c3fb27SDimitry Andric         (IsRHSClass || matchIsFPClassLikeFCmp(Op1, ClassVal1, ClassMask1)))) &&
146506c3fb27SDimitry Andric       ClassVal0 == ClassVal1) {
1466bdd1243dSDimitry Andric     unsigned NewClassMask;
1467bdd1243dSDimitry Andric     switch (BO.getOpcode()) {
1468bdd1243dSDimitry Andric     case Instruction::And:
1469bdd1243dSDimitry Andric       NewClassMask = ClassMask0 & ClassMask1;
1470bdd1243dSDimitry Andric       break;
1471bdd1243dSDimitry Andric     case Instruction::Or:
1472bdd1243dSDimitry Andric       NewClassMask = ClassMask0 | ClassMask1;
1473bdd1243dSDimitry Andric       break;
1474bdd1243dSDimitry Andric     case Instruction::Xor:
1475bdd1243dSDimitry Andric       NewClassMask = ClassMask0 ^ ClassMask1;
1476bdd1243dSDimitry Andric       break;
1477bdd1243dSDimitry Andric     default:
1478bdd1243dSDimitry Andric       llvm_unreachable("not a binary logic operator");
1479bdd1243dSDimitry Andric     }
1480bdd1243dSDimitry Andric 
148106c3fb27SDimitry Andric     if (IsLHSClass) {
1482bdd1243dSDimitry Andric       auto *II = cast<IntrinsicInst>(Op0);
1483bdd1243dSDimitry Andric       II->setArgOperand(
1484bdd1243dSDimitry Andric           1, ConstantInt::get(II->getArgOperand(1)->getType(), NewClassMask));
1485bdd1243dSDimitry Andric       return replaceInstUsesWith(BO, II);
1486bdd1243dSDimitry Andric     }
1487bdd1243dSDimitry Andric 
148806c3fb27SDimitry Andric     if (IsRHSClass) {
148906c3fb27SDimitry Andric       auto *II = cast<IntrinsicInst>(Op1);
149006c3fb27SDimitry Andric       II->setArgOperand(
149106c3fb27SDimitry Andric           1, ConstantInt::get(II->getArgOperand(1)->getType(), NewClassMask));
149206c3fb27SDimitry Andric       return replaceInstUsesWith(BO, II);
149306c3fb27SDimitry Andric     }
149406c3fb27SDimitry Andric 
149506c3fb27SDimitry Andric     CallInst *NewClass =
149606c3fb27SDimitry Andric         Builder.CreateIntrinsic(Intrinsic::is_fpclass, {ClassVal0->getType()},
149706c3fb27SDimitry Andric                                 {ClassVal0, Builder.getInt32(NewClassMask)});
149806c3fb27SDimitry Andric     return replaceInstUsesWith(BO, NewClass);
149906c3fb27SDimitry Andric   }
150006c3fb27SDimitry Andric 
1501bdd1243dSDimitry Andric   return nullptr;
1502bdd1243dSDimitry Andric }
1503bdd1243dSDimitry Andric 
1504bdd1243dSDimitry Andric /// Look for the pattern that conditionally negates a value via math operations:
1505bdd1243dSDimitry Andric ///   cond.splat = sext i1 cond
1506bdd1243dSDimitry Andric ///   sub = add cond.splat, x
1507bdd1243dSDimitry Andric ///   xor = xor sub, cond.splat
1508bdd1243dSDimitry Andric /// and rewrite it to do the same, but via logical operations:
1509bdd1243dSDimitry Andric ///   value.neg = sub 0, value
1510bdd1243dSDimitry Andric ///   cond = select i1 neg, value.neg, value
canonicalizeConditionalNegationViaMathToSelect(BinaryOperator & I)1511bdd1243dSDimitry Andric Instruction *InstCombinerImpl::canonicalizeConditionalNegationViaMathToSelect(
1512bdd1243dSDimitry Andric     BinaryOperator &I) {
1513bdd1243dSDimitry Andric   assert(I.getOpcode() == BinaryOperator::Xor && "Only for xor!");
1514bdd1243dSDimitry Andric   Value *Cond, *X;
1515bdd1243dSDimitry Andric   // As per complexity ordering, `xor` is not commutative here.
1516bdd1243dSDimitry Andric   if (!match(&I, m_c_BinOp(m_OneUse(m_Value()), m_Value())) ||
1517bdd1243dSDimitry Andric       !match(I.getOperand(1), m_SExt(m_Value(Cond))) ||
1518bdd1243dSDimitry Andric       !Cond->getType()->isIntOrIntVectorTy(1) ||
1519bdd1243dSDimitry Andric       !match(I.getOperand(0), m_c_Add(m_SExt(m_Deferred(Cond)), m_Value(X))))
1520bdd1243dSDimitry Andric     return nullptr;
1521bdd1243dSDimitry Andric   return SelectInst::Create(Cond, Builder.CreateNeg(X, X->getName() + ".neg"),
1522bdd1243dSDimitry Andric                             X);
1523bdd1243dSDimitry Andric }
1524bdd1243dSDimitry Andric 
15250b57cec5SDimitry Andric /// This a limited reassociation for a special case (see above) where we are
15260b57cec5SDimitry Andric /// checking if two values are either both NAN (unordered) or not-NAN (ordered).
15270b57cec5SDimitry Andric /// This could be handled more generally in '-reassociation', but it seems like
15280b57cec5SDimitry Andric /// an unlikely pattern for a large number of logic ops and fcmps.
reassociateFCmps(BinaryOperator & BO,InstCombiner::BuilderTy & Builder)15290b57cec5SDimitry Andric static Instruction *reassociateFCmps(BinaryOperator &BO,
15300b57cec5SDimitry Andric                                      InstCombiner::BuilderTy &Builder) {
15310b57cec5SDimitry Andric   Instruction::BinaryOps Opcode = BO.getOpcode();
15320b57cec5SDimitry Andric   assert((Opcode == Instruction::And || Opcode == Instruction::Or) &&
15330b57cec5SDimitry Andric          "Expecting and/or op for fcmp transform");
15340b57cec5SDimitry Andric 
15350b57cec5SDimitry Andric   // There are 4 commuted variants of the pattern. Canonicalize operands of this
15360b57cec5SDimitry Andric   // logic op so an fcmp is operand 0 and a matching logic op is operand 1.
15370b57cec5SDimitry Andric   Value *Op0 = BO.getOperand(0), *Op1 = BO.getOperand(1), *X;
15380b57cec5SDimitry Andric   FCmpInst::Predicate Pred;
15390b57cec5SDimitry Andric   if (match(Op1, m_FCmp(Pred, m_Value(), m_AnyZeroFP())))
15400b57cec5SDimitry Andric     std::swap(Op0, Op1);
15410b57cec5SDimitry Andric 
15420b57cec5SDimitry Andric   // Match inner binop and the predicate for combining 2 NAN checks into 1.
1543349cc55cSDimitry Andric   Value *BO10, *BO11;
15440b57cec5SDimitry Andric   FCmpInst::Predicate NanPred = Opcode == Instruction::And ? FCmpInst::FCMP_ORD
15450b57cec5SDimitry Andric                                                            : FCmpInst::FCMP_UNO;
15460b57cec5SDimitry Andric   if (!match(Op0, m_FCmp(Pred, m_Value(X), m_AnyZeroFP())) || Pred != NanPred ||
1547349cc55cSDimitry Andric       !match(Op1, m_BinOp(Opcode, m_Value(BO10), m_Value(BO11))))
15480b57cec5SDimitry Andric     return nullptr;
15490b57cec5SDimitry Andric 
15500b57cec5SDimitry Andric   // The inner logic op must have a matching fcmp operand.
1551349cc55cSDimitry Andric   Value *Y;
15520b57cec5SDimitry Andric   if (!match(BO10, m_FCmp(Pred, m_Value(Y), m_AnyZeroFP())) ||
15530b57cec5SDimitry Andric       Pred != NanPred || X->getType() != Y->getType())
15540b57cec5SDimitry Andric     std::swap(BO10, BO11);
15550b57cec5SDimitry Andric 
15560b57cec5SDimitry Andric   if (!match(BO10, m_FCmp(Pred, m_Value(Y), m_AnyZeroFP())) ||
15570b57cec5SDimitry Andric       Pred != NanPred || X->getType() != Y->getType())
15580b57cec5SDimitry Andric     return nullptr;
15590b57cec5SDimitry Andric 
15600b57cec5SDimitry Andric   // and (fcmp ord X, 0), (and (fcmp ord Y, 0), Z) --> and (fcmp ord X, Y), Z
15610b57cec5SDimitry Andric   // or  (fcmp uno X, 0), (or  (fcmp uno Y, 0), Z) --> or  (fcmp uno X, Y), Z
15620b57cec5SDimitry Andric   Value *NewFCmp = Builder.CreateFCmp(Pred, X, Y);
15630b57cec5SDimitry Andric   if (auto *NewFCmpInst = dyn_cast<FCmpInst>(NewFCmp)) {
15640b57cec5SDimitry Andric     // Intersect FMF from the 2 source fcmps.
15650b57cec5SDimitry Andric     NewFCmpInst->copyIRFlags(Op0);
15660b57cec5SDimitry Andric     NewFCmpInst->andIRFlags(BO10);
15670b57cec5SDimitry Andric   }
15680b57cec5SDimitry Andric   return BinaryOperator::Create(Opcode, NewFCmp, BO11);
15690b57cec5SDimitry Andric }
15700b57cec5SDimitry Andric 
1571349cc55cSDimitry Andric /// Match variations of De Morgan's Laws:
15720b57cec5SDimitry Andric /// (~A & ~B) == (~(A | B))
15730b57cec5SDimitry Andric /// (~A | ~B) == (~(A & B))
matchDeMorgansLaws(BinaryOperator & I,InstCombiner & IC)15740b57cec5SDimitry Andric static Instruction *matchDeMorgansLaws(BinaryOperator &I,
15755f757f3fSDimitry Andric                                        InstCombiner &IC) {
1576349cc55cSDimitry Andric   const Instruction::BinaryOps Opcode = I.getOpcode();
15770b57cec5SDimitry Andric   assert((Opcode == Instruction::And || Opcode == Instruction::Or) &&
15780b57cec5SDimitry Andric          "Trying to match De Morgan's Laws with something other than and/or");
15790b57cec5SDimitry Andric 
15800b57cec5SDimitry Andric   // Flip the logic operation.
1581349cc55cSDimitry Andric   const Instruction::BinaryOps FlippedOpcode =
1582349cc55cSDimitry Andric       (Opcode == Instruction::And) ? Instruction::Or : Instruction::And;
15830b57cec5SDimitry Andric 
1584349cc55cSDimitry Andric   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
15850b57cec5SDimitry Andric   Value *A, *B;
1586349cc55cSDimitry Andric   if (match(Op0, m_OneUse(m_Not(m_Value(A)))) &&
1587349cc55cSDimitry Andric       match(Op1, m_OneUse(m_Not(m_Value(B)))) &&
15885f757f3fSDimitry Andric       !IC.isFreeToInvert(A, A->hasOneUse()) &&
15895f757f3fSDimitry Andric       !IC.isFreeToInvert(B, B->hasOneUse())) {
1590349cc55cSDimitry Andric     Value *AndOr =
15915f757f3fSDimitry Andric         IC.Builder.CreateBinOp(FlippedOpcode, A, B, I.getName() + ".demorgan");
15920b57cec5SDimitry Andric     return BinaryOperator::CreateNot(AndOr);
15930b57cec5SDimitry Andric   }
15940b57cec5SDimitry Andric 
1595349cc55cSDimitry Andric   // The 'not' ops may require reassociation.
1596349cc55cSDimitry Andric   // (A & ~B) & ~C --> A & ~(B | C)
1597349cc55cSDimitry Andric   // (~B & A) & ~C --> A & ~(B | C)
1598349cc55cSDimitry Andric   // (A | ~B) | ~C --> A | ~(B & C)
1599349cc55cSDimitry Andric   // (~B | A) | ~C --> A | ~(B & C)
1600349cc55cSDimitry Andric   Value *C;
1601349cc55cSDimitry Andric   if (match(Op0, m_OneUse(m_c_BinOp(Opcode, m_Value(A), m_Not(m_Value(B))))) &&
1602349cc55cSDimitry Andric       match(Op1, m_Not(m_Value(C)))) {
16035f757f3fSDimitry Andric     Value *FlippedBO = IC.Builder.CreateBinOp(FlippedOpcode, B, C);
16045f757f3fSDimitry Andric     return BinaryOperator::Create(Opcode, A, IC.Builder.CreateNot(FlippedBO));
1605349cc55cSDimitry Andric   }
1606349cc55cSDimitry Andric 
16070b57cec5SDimitry Andric   return nullptr;
16080b57cec5SDimitry Andric }
16090b57cec5SDimitry Andric 
shouldOptimizeCast(CastInst * CI)1610e8d8bef9SDimitry Andric bool InstCombinerImpl::shouldOptimizeCast(CastInst *CI) {
16110b57cec5SDimitry Andric   Value *CastSrc = CI->getOperand(0);
16120b57cec5SDimitry Andric 
16130b57cec5SDimitry Andric   // Noop casts and casts of constants should be eliminated trivially.
16140b57cec5SDimitry Andric   if (CI->getSrcTy() == CI->getDestTy() || isa<Constant>(CastSrc))
16150b57cec5SDimitry Andric     return false;
16160b57cec5SDimitry Andric 
16170b57cec5SDimitry Andric   // If this cast is paired with another cast that can be eliminated, we prefer
16180b57cec5SDimitry Andric   // to have it eliminated.
16190b57cec5SDimitry Andric   if (const auto *PrecedingCI = dyn_cast<CastInst>(CastSrc))
16200b57cec5SDimitry Andric     if (isEliminableCastPair(PrecedingCI, CI))
16210b57cec5SDimitry Andric       return false;
16220b57cec5SDimitry Andric 
16230b57cec5SDimitry Andric   return true;
16240b57cec5SDimitry Andric }
16250b57cec5SDimitry Andric 
16260b57cec5SDimitry Andric /// Fold {and,or,xor} (cast X), C.
foldLogicCastConstant(BinaryOperator & Logic,CastInst * Cast,InstCombinerImpl & IC)16270b57cec5SDimitry Andric static Instruction *foldLogicCastConstant(BinaryOperator &Logic, CastInst *Cast,
16285f757f3fSDimitry Andric                                           InstCombinerImpl &IC) {
16290b57cec5SDimitry Andric   Constant *C = dyn_cast<Constant>(Logic.getOperand(1));
16300b57cec5SDimitry Andric   if (!C)
16310b57cec5SDimitry Andric     return nullptr;
16320b57cec5SDimitry Andric 
16330b57cec5SDimitry Andric   auto LogicOpc = Logic.getOpcode();
16340b57cec5SDimitry Andric   Type *DestTy = Logic.getType();
16350b57cec5SDimitry Andric   Type *SrcTy = Cast->getSrcTy();
16360b57cec5SDimitry Andric 
16370b57cec5SDimitry Andric   // Move the logic operation ahead of a zext or sext if the constant is
16380b57cec5SDimitry Andric   // unchanged in the smaller source type. Performing the logic in a smaller
16390b57cec5SDimitry Andric   // type may provide more information to later folds, and the smaller logic
16400b57cec5SDimitry Andric   // instruction may be cheaper (particularly in the case of vectors).
16410b57cec5SDimitry Andric   Value *X;
16420b57cec5SDimitry Andric   if (match(Cast, m_OneUse(m_ZExt(m_Value(X))))) {
16435f757f3fSDimitry Andric     if (Constant *TruncC = IC.getLosslessUnsignedTrunc(C, SrcTy)) {
16440b57cec5SDimitry Andric       // LogicOpc (zext X), C --> zext (LogicOpc X, C)
16455f757f3fSDimitry Andric       Value *NewOp = IC.Builder.CreateBinOp(LogicOpc, X, TruncC);
16460b57cec5SDimitry Andric       return new ZExtInst(NewOp, DestTy);
16470b57cec5SDimitry Andric     }
16480b57cec5SDimitry Andric   }
16490b57cec5SDimitry Andric 
16500b57cec5SDimitry Andric   if (match(Cast, m_OneUse(m_SExt(m_Value(X))))) {
16515f757f3fSDimitry Andric     if (Constant *TruncC = IC.getLosslessSignedTrunc(C, SrcTy)) {
16520b57cec5SDimitry Andric       // LogicOpc (sext X), C --> sext (LogicOpc X, C)
16535f757f3fSDimitry Andric       Value *NewOp = IC.Builder.CreateBinOp(LogicOpc, X, TruncC);
16540b57cec5SDimitry Andric       return new SExtInst(NewOp, DestTy);
16550b57cec5SDimitry Andric     }
16560b57cec5SDimitry Andric   }
16570b57cec5SDimitry Andric 
16580b57cec5SDimitry Andric   return nullptr;
16590b57cec5SDimitry Andric }
16600b57cec5SDimitry Andric 
16610b57cec5SDimitry Andric /// Fold {and,or,xor} (cast X), Y.
foldCastedBitwiseLogic(BinaryOperator & I)1662e8d8bef9SDimitry Andric Instruction *InstCombinerImpl::foldCastedBitwiseLogic(BinaryOperator &I) {
16630b57cec5SDimitry Andric   auto LogicOpc = I.getOpcode();
16640b57cec5SDimitry Andric   assert(I.isBitwiseLogicOp() && "Unexpected opcode for bitwise logic folding");
16650b57cec5SDimitry Andric 
16660b57cec5SDimitry Andric   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
166706c3fb27SDimitry Andric 
166806c3fb27SDimitry Andric   // fold bitwise(A >> BW - 1, zext(icmp))     (BW is the scalar bits of the
166906c3fb27SDimitry Andric   // type of A)
167006c3fb27SDimitry Andric   //   -> bitwise(zext(A < 0), zext(icmp))
167106c3fb27SDimitry Andric   //   -> zext(bitwise(A < 0, icmp))
167206c3fb27SDimitry Andric   auto FoldBitwiseICmpZeroWithICmp = [&](Value *Op0,
167306c3fb27SDimitry Andric                                          Value *Op1) -> Instruction * {
167406c3fb27SDimitry Andric     ICmpInst::Predicate Pred;
167506c3fb27SDimitry Andric     Value *A;
167606c3fb27SDimitry Andric     bool IsMatched =
167706c3fb27SDimitry Andric         match(Op0,
167806c3fb27SDimitry Andric               m_OneUse(m_LShr(
167906c3fb27SDimitry Andric                   m_Value(A),
168006c3fb27SDimitry Andric                   m_SpecificInt(Op0->getType()->getScalarSizeInBits() - 1)))) &&
168106c3fb27SDimitry Andric         match(Op1, m_OneUse(m_ZExt(m_ICmp(Pred, m_Value(), m_Value()))));
168206c3fb27SDimitry Andric 
168306c3fb27SDimitry Andric     if (!IsMatched)
168406c3fb27SDimitry Andric       return nullptr;
168506c3fb27SDimitry Andric 
168606c3fb27SDimitry Andric     auto *ICmpL =
168706c3fb27SDimitry Andric         Builder.CreateICmpSLT(A, Constant::getNullValue(A->getType()));
168806c3fb27SDimitry Andric     auto *ICmpR = cast<ZExtInst>(Op1)->getOperand(0);
168906c3fb27SDimitry Andric     auto *BitwiseOp = Builder.CreateBinOp(LogicOpc, ICmpL, ICmpR);
169006c3fb27SDimitry Andric 
169106c3fb27SDimitry Andric     return new ZExtInst(BitwiseOp, Op0->getType());
169206c3fb27SDimitry Andric   };
169306c3fb27SDimitry Andric 
169406c3fb27SDimitry Andric   if (auto *Ret = FoldBitwiseICmpZeroWithICmp(Op0, Op1))
169506c3fb27SDimitry Andric     return Ret;
169606c3fb27SDimitry Andric 
169706c3fb27SDimitry Andric   if (auto *Ret = FoldBitwiseICmpZeroWithICmp(Op1, Op0))
169806c3fb27SDimitry Andric     return Ret;
169906c3fb27SDimitry Andric 
17000b57cec5SDimitry Andric   CastInst *Cast0 = dyn_cast<CastInst>(Op0);
17010b57cec5SDimitry Andric   if (!Cast0)
17020b57cec5SDimitry Andric     return nullptr;
17030b57cec5SDimitry Andric 
17040b57cec5SDimitry Andric   // This must be a cast from an integer or integer vector source type to allow
17050b57cec5SDimitry Andric   // transformation of the logic operation to the source type.
17060b57cec5SDimitry Andric   Type *DestTy = I.getType();
17070b57cec5SDimitry Andric   Type *SrcTy = Cast0->getSrcTy();
17080b57cec5SDimitry Andric   if (!SrcTy->isIntOrIntVectorTy())
17090b57cec5SDimitry Andric     return nullptr;
17100b57cec5SDimitry Andric 
17115f757f3fSDimitry Andric   if (Instruction *Ret = foldLogicCastConstant(I, Cast0, *this))
17120b57cec5SDimitry Andric     return Ret;
17130b57cec5SDimitry Andric 
17140b57cec5SDimitry Andric   CastInst *Cast1 = dyn_cast<CastInst>(Op1);
17150b57cec5SDimitry Andric   if (!Cast1)
17160b57cec5SDimitry Andric     return nullptr;
17170b57cec5SDimitry Andric 
1718bdd1243dSDimitry Andric   // Both operands of the logic operation are casts. The casts must be the
1719bdd1243dSDimitry Andric   // same kind for reduction.
1720bdd1243dSDimitry Andric   Instruction::CastOps CastOpcode = Cast0->getOpcode();
1721bdd1243dSDimitry Andric   if (CastOpcode != Cast1->getOpcode())
17220b57cec5SDimitry Andric     return nullptr;
17230b57cec5SDimitry Andric 
1724bdd1243dSDimitry Andric   // If the source types do not match, but the casts are matching extends, we
1725bdd1243dSDimitry Andric   // can still narrow the logic op.
1726bdd1243dSDimitry Andric   if (SrcTy != Cast1->getSrcTy()) {
1727bdd1243dSDimitry Andric     Value *X, *Y;
1728bdd1243dSDimitry Andric     if (match(Cast0, m_OneUse(m_ZExtOrSExt(m_Value(X)))) &&
1729bdd1243dSDimitry Andric         match(Cast1, m_OneUse(m_ZExtOrSExt(m_Value(Y))))) {
1730bdd1243dSDimitry Andric       // Cast the narrower source to the wider source type.
1731bdd1243dSDimitry Andric       unsigned XNumBits = X->getType()->getScalarSizeInBits();
1732bdd1243dSDimitry Andric       unsigned YNumBits = Y->getType()->getScalarSizeInBits();
1733bdd1243dSDimitry Andric       if (XNumBits < YNumBits)
1734bdd1243dSDimitry Andric         X = Builder.CreateCast(CastOpcode, X, Y->getType());
1735bdd1243dSDimitry Andric       else
1736bdd1243dSDimitry Andric         Y = Builder.CreateCast(CastOpcode, Y, X->getType());
1737bdd1243dSDimitry Andric       // Do the logic op in the intermediate width, then widen more.
1738bdd1243dSDimitry Andric       Value *NarrowLogic = Builder.CreateBinOp(LogicOpc, X, Y);
1739bdd1243dSDimitry Andric       return CastInst::Create(CastOpcode, NarrowLogic, DestTy);
1740bdd1243dSDimitry Andric     }
1741bdd1243dSDimitry Andric 
1742bdd1243dSDimitry Andric     // Give up for other cast opcodes.
1743bdd1243dSDimitry Andric     return nullptr;
1744bdd1243dSDimitry Andric   }
1745bdd1243dSDimitry Andric 
17460b57cec5SDimitry Andric   Value *Cast0Src = Cast0->getOperand(0);
17470b57cec5SDimitry Andric   Value *Cast1Src = Cast1->getOperand(0);
17480b57cec5SDimitry Andric 
17490b57cec5SDimitry Andric   // fold logic(cast(A), cast(B)) -> cast(logic(A, B))
175081ad6265SDimitry Andric   if ((Cast0->hasOneUse() || Cast1->hasOneUse()) &&
175181ad6265SDimitry Andric       shouldOptimizeCast(Cast0) && shouldOptimizeCast(Cast1)) {
17520b57cec5SDimitry Andric     Value *NewOp = Builder.CreateBinOp(LogicOpc, Cast0Src, Cast1Src,
17530b57cec5SDimitry Andric                                        I.getName());
17540b57cec5SDimitry Andric     return CastInst::Create(CastOpcode, NewOp, DestTy);
17550b57cec5SDimitry Andric   }
17560b57cec5SDimitry Andric 
17570b57cec5SDimitry Andric   return nullptr;
17580b57cec5SDimitry Andric }
17590b57cec5SDimitry Andric 
foldAndToXor(BinaryOperator & I,InstCombiner::BuilderTy & Builder)17600b57cec5SDimitry Andric static Instruction *foldAndToXor(BinaryOperator &I,
17610b57cec5SDimitry Andric                                  InstCombiner::BuilderTy &Builder) {
17620b57cec5SDimitry Andric   assert(I.getOpcode() == Instruction::And);
17630b57cec5SDimitry Andric   Value *Op0 = I.getOperand(0);
17640b57cec5SDimitry Andric   Value *Op1 = I.getOperand(1);
17650b57cec5SDimitry Andric   Value *A, *B;
17660b57cec5SDimitry Andric 
17670b57cec5SDimitry Andric   // Operand complexity canonicalization guarantees that the 'or' is Op0.
17680b57cec5SDimitry Andric   // (A | B) & ~(A & B) --> A ^ B
17690b57cec5SDimitry Andric   // (A | B) & ~(B & A) --> A ^ B
17700b57cec5SDimitry Andric   if (match(&I, m_BinOp(m_Or(m_Value(A), m_Value(B)),
17710b57cec5SDimitry Andric                         m_Not(m_c_And(m_Deferred(A), m_Deferred(B))))))
17720b57cec5SDimitry Andric     return BinaryOperator::CreateXor(A, B);
17730b57cec5SDimitry Andric 
17740b57cec5SDimitry Andric   // (A | ~B) & (~A | B) --> ~(A ^ B)
17750b57cec5SDimitry Andric   // (A | ~B) & (B | ~A) --> ~(A ^ B)
17760b57cec5SDimitry Andric   // (~B | A) & (~A | B) --> ~(A ^ B)
17770b57cec5SDimitry Andric   // (~B | A) & (B | ~A) --> ~(A ^ B)
17780b57cec5SDimitry Andric   if (Op0->hasOneUse() || Op1->hasOneUse())
17790b57cec5SDimitry Andric     if (match(&I, m_BinOp(m_c_Or(m_Value(A), m_Not(m_Value(B))),
17800b57cec5SDimitry Andric                           m_c_Or(m_Not(m_Deferred(A)), m_Deferred(B)))))
17810b57cec5SDimitry Andric       return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
17820b57cec5SDimitry Andric 
17830b57cec5SDimitry Andric   return nullptr;
17840b57cec5SDimitry Andric }
17850b57cec5SDimitry Andric 
foldOrToXor(BinaryOperator & I,InstCombiner::BuilderTy & Builder)17860b57cec5SDimitry Andric static Instruction *foldOrToXor(BinaryOperator &I,
17870b57cec5SDimitry Andric                                 InstCombiner::BuilderTy &Builder) {
17880b57cec5SDimitry Andric   assert(I.getOpcode() == Instruction::Or);
17890b57cec5SDimitry Andric   Value *Op0 = I.getOperand(0);
17900b57cec5SDimitry Andric   Value *Op1 = I.getOperand(1);
17910b57cec5SDimitry Andric   Value *A, *B;
17920b57cec5SDimitry Andric 
17930b57cec5SDimitry Andric   // Operand complexity canonicalization guarantees that the 'and' is Op0.
17940b57cec5SDimitry Andric   // (A & B) | ~(A | B) --> ~(A ^ B)
17950b57cec5SDimitry Andric   // (A & B) | ~(B | A) --> ~(A ^ B)
17960b57cec5SDimitry Andric   if (Op0->hasOneUse() || Op1->hasOneUse())
17970b57cec5SDimitry Andric     if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
17980b57cec5SDimitry Andric         match(Op1, m_Not(m_c_Or(m_Specific(A), m_Specific(B)))))
17990b57cec5SDimitry Andric       return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
18000b57cec5SDimitry Andric 
1801e8d8bef9SDimitry Andric   // Operand complexity canonicalization guarantees that the 'xor' is Op0.
1802e8d8bef9SDimitry Andric   // (A ^ B) | ~(A | B) --> ~(A & B)
1803e8d8bef9SDimitry Andric   // (A ^ B) | ~(B | A) --> ~(A & B)
1804e8d8bef9SDimitry Andric   if (Op0->hasOneUse() || Op1->hasOneUse())
1805e8d8bef9SDimitry Andric     if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
1806e8d8bef9SDimitry Andric         match(Op1, m_Not(m_c_Or(m_Specific(A), m_Specific(B)))))
1807e8d8bef9SDimitry Andric       return BinaryOperator::CreateNot(Builder.CreateAnd(A, B));
1808e8d8bef9SDimitry Andric 
18090b57cec5SDimitry Andric   // (A & ~B) | (~A & B) --> A ^ B
18100b57cec5SDimitry Andric   // (A & ~B) | (B & ~A) --> A ^ B
18110b57cec5SDimitry Andric   // (~B & A) | (~A & B) --> A ^ B
18120b57cec5SDimitry Andric   // (~B & A) | (B & ~A) --> A ^ B
18130b57cec5SDimitry Andric   if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
18140b57cec5SDimitry Andric       match(Op1, m_c_And(m_Not(m_Specific(A)), m_Specific(B))))
18150b57cec5SDimitry Andric     return BinaryOperator::CreateXor(A, B);
18160b57cec5SDimitry Andric 
18170b57cec5SDimitry Andric   return nullptr;
18180b57cec5SDimitry Andric }
18190b57cec5SDimitry Andric 
18200b57cec5SDimitry Andric /// Return true if a constant shift amount is always less than the specified
18210b57cec5SDimitry Andric /// bit-width. If not, the shift could create poison in the narrower type.
canNarrowShiftAmt(Constant * C,unsigned BitWidth)18220b57cec5SDimitry Andric static bool canNarrowShiftAmt(Constant *C, unsigned BitWidth) {
1823e8d8bef9SDimitry Andric   APInt Threshold(C->getType()->getScalarSizeInBits(), BitWidth);
1824e8d8bef9SDimitry Andric   return match(C, m_SpecificInt_ICMP(ICmpInst::ICMP_ULT, Threshold));
18250b57cec5SDimitry Andric }
18260b57cec5SDimitry Andric 
18270b57cec5SDimitry Andric /// Try to use narrower ops (sink zext ops) for an 'and' with binop operand and
18280b57cec5SDimitry Andric /// a common zext operand: and (binop (zext X), C), (zext X).
narrowMaskedBinOp(BinaryOperator & And)1829e8d8bef9SDimitry Andric Instruction *InstCombinerImpl::narrowMaskedBinOp(BinaryOperator &And) {
18300b57cec5SDimitry Andric   // This transform could also apply to {or, and, xor}, but there are better
18310b57cec5SDimitry Andric   // folds for those cases, so we don't expect those patterns here. AShr is not
18320b57cec5SDimitry Andric   // handled because it should always be transformed to LShr in this sequence.
18330b57cec5SDimitry Andric   // The subtract transform is different because it has a constant on the left.
18340b57cec5SDimitry Andric   // Add/mul commute the constant to RHS; sub with constant RHS becomes add.
18350b57cec5SDimitry Andric   Value *Op0 = And.getOperand(0), *Op1 = And.getOperand(1);
18360b57cec5SDimitry Andric   Constant *C;
18370b57cec5SDimitry Andric   if (!match(Op0, m_OneUse(m_Add(m_Specific(Op1), m_Constant(C)))) &&
18380b57cec5SDimitry Andric       !match(Op0, m_OneUse(m_Mul(m_Specific(Op1), m_Constant(C)))) &&
18390b57cec5SDimitry Andric       !match(Op0, m_OneUse(m_LShr(m_Specific(Op1), m_Constant(C)))) &&
18400b57cec5SDimitry Andric       !match(Op0, m_OneUse(m_Shl(m_Specific(Op1), m_Constant(C)))) &&
18410b57cec5SDimitry Andric       !match(Op0, m_OneUse(m_Sub(m_Constant(C), m_Specific(Op1)))))
18420b57cec5SDimitry Andric     return nullptr;
18430b57cec5SDimitry Andric 
18440b57cec5SDimitry Andric   Value *X;
18450b57cec5SDimitry Andric   if (!match(Op1, m_ZExt(m_Value(X))) || Op1->hasNUsesOrMore(3))
18460b57cec5SDimitry Andric     return nullptr;
18470b57cec5SDimitry Andric 
18480b57cec5SDimitry Andric   Type *Ty = And.getType();
18490b57cec5SDimitry Andric   if (!isa<VectorType>(Ty) && !shouldChangeType(Ty, X->getType()))
18500b57cec5SDimitry Andric     return nullptr;
18510b57cec5SDimitry Andric 
18520b57cec5SDimitry Andric   // If we're narrowing a shift, the shift amount must be safe (less than the
18530b57cec5SDimitry Andric   // width) in the narrower type. If the shift amount is greater, instsimplify
18540b57cec5SDimitry Andric   // usually handles that case, but we can't guarantee/assert it.
18550b57cec5SDimitry Andric   Instruction::BinaryOps Opc = cast<BinaryOperator>(Op0)->getOpcode();
18560b57cec5SDimitry Andric   if (Opc == Instruction::LShr || Opc == Instruction::Shl)
18570b57cec5SDimitry Andric     if (!canNarrowShiftAmt(C, X->getType()->getScalarSizeInBits()))
18580b57cec5SDimitry Andric       return nullptr;
18590b57cec5SDimitry Andric 
18600b57cec5SDimitry Andric   // and (sub C, (zext X)), (zext X) --> zext (and (sub C', X), X)
18610b57cec5SDimitry Andric   // and (binop (zext X), C), (zext X) --> zext (and (binop X, C'), X)
18620b57cec5SDimitry Andric   Value *NewC = ConstantExpr::getTrunc(C, X->getType());
18630b57cec5SDimitry Andric   Value *NewBO = Opc == Instruction::Sub ? Builder.CreateBinOp(Opc, NewC, X)
18640b57cec5SDimitry Andric                                          : Builder.CreateBinOp(Opc, X, NewC);
18650b57cec5SDimitry Andric   return new ZExtInst(Builder.CreateAnd(NewBO, X), Ty);
18660b57cec5SDimitry Andric }
18670b57cec5SDimitry Andric 
1868349cc55cSDimitry Andric /// Try folding relatively complex patterns for both And and Or operations
1869349cc55cSDimitry Andric /// with all And and Or swapped.
foldComplexAndOrPatterns(BinaryOperator & I,InstCombiner::BuilderTy & Builder)1870349cc55cSDimitry Andric static Instruction *foldComplexAndOrPatterns(BinaryOperator &I,
1871349cc55cSDimitry Andric                                              InstCombiner::BuilderTy &Builder) {
1872349cc55cSDimitry Andric   const Instruction::BinaryOps Opcode = I.getOpcode();
1873349cc55cSDimitry Andric   assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1874349cc55cSDimitry Andric 
1875349cc55cSDimitry Andric   // Flip the logic operation.
1876349cc55cSDimitry Andric   const Instruction::BinaryOps FlippedOpcode =
1877349cc55cSDimitry Andric       (Opcode == Instruction::And) ? Instruction::Or : Instruction::And;
1878349cc55cSDimitry Andric 
1879349cc55cSDimitry Andric   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
188004eeddc0SDimitry Andric   Value *A, *B, *C, *X, *Y, *Dummy;
188104eeddc0SDimitry Andric 
188204eeddc0SDimitry Andric   // Match following expressions:
188304eeddc0SDimitry Andric   // (~(A | B) & C)
188404eeddc0SDimitry Andric   // (~(A & B) | C)
188504eeddc0SDimitry Andric   // Captures X = ~(A | B) or ~(A & B)
188604eeddc0SDimitry Andric   const auto matchNotOrAnd =
188704eeddc0SDimitry Andric       [Opcode, FlippedOpcode](Value *Op, auto m_A, auto m_B, auto m_C,
188804eeddc0SDimitry Andric                               Value *&X, bool CountUses = false) -> bool {
188904eeddc0SDimitry Andric     if (CountUses && !Op->hasOneUse())
189004eeddc0SDimitry Andric       return false;
189104eeddc0SDimitry Andric 
189204eeddc0SDimitry Andric     if (match(Op, m_c_BinOp(FlippedOpcode,
189304eeddc0SDimitry Andric                             m_CombineAnd(m_Value(X),
189404eeddc0SDimitry Andric                                          m_Not(m_c_BinOp(Opcode, m_A, m_B))),
189504eeddc0SDimitry Andric                             m_C)))
189604eeddc0SDimitry Andric       return !CountUses || X->hasOneUse();
189704eeddc0SDimitry Andric 
189804eeddc0SDimitry Andric     return false;
189904eeddc0SDimitry Andric   };
1900349cc55cSDimitry Andric 
1901349cc55cSDimitry Andric   // (~(A | B) & C) | ... --> ...
1902349cc55cSDimitry Andric   // (~(A & B) | C) & ... --> ...
1903349cc55cSDimitry Andric   // TODO: One use checks are conservative. We just need to check that a total
1904349cc55cSDimitry Andric   //       number of multiple used values does not exceed reduction
1905349cc55cSDimitry Andric   //       in operations.
190604eeddc0SDimitry Andric   if (matchNotOrAnd(Op0, m_Value(A), m_Value(B), m_Value(C), X)) {
1907349cc55cSDimitry Andric     // (~(A | B) & C) | (~(A | C) & B) --> (B ^ C) & ~A
1908349cc55cSDimitry Andric     // (~(A & B) | C) & (~(A & C) | B) --> ~((B ^ C) & A)
190904eeddc0SDimitry Andric     if (matchNotOrAnd(Op1, m_Specific(A), m_Specific(C), m_Specific(B), Dummy,
191004eeddc0SDimitry Andric                       true)) {
1911349cc55cSDimitry Andric       Value *Xor = Builder.CreateXor(B, C);
1912349cc55cSDimitry Andric       return (Opcode == Instruction::Or)
1913349cc55cSDimitry Andric                  ? BinaryOperator::CreateAnd(Xor, Builder.CreateNot(A))
1914349cc55cSDimitry Andric                  : BinaryOperator::CreateNot(Builder.CreateAnd(Xor, A));
1915349cc55cSDimitry Andric     }
1916349cc55cSDimitry Andric 
1917349cc55cSDimitry Andric     // (~(A | B) & C) | (~(B | C) & A) --> (A ^ C) & ~B
1918349cc55cSDimitry Andric     // (~(A & B) | C) & (~(B & C) | A) --> ~((A ^ C) & B)
191904eeddc0SDimitry Andric     if (matchNotOrAnd(Op1, m_Specific(B), m_Specific(C), m_Specific(A), Dummy,
192004eeddc0SDimitry Andric                       true)) {
1921349cc55cSDimitry Andric       Value *Xor = Builder.CreateXor(A, C);
1922349cc55cSDimitry Andric       return (Opcode == Instruction::Or)
1923349cc55cSDimitry Andric                  ? BinaryOperator::CreateAnd(Xor, Builder.CreateNot(B))
1924349cc55cSDimitry Andric                  : BinaryOperator::CreateNot(Builder.CreateAnd(Xor, B));
1925349cc55cSDimitry Andric     }
1926349cc55cSDimitry Andric 
1927349cc55cSDimitry Andric     // (~(A | B) & C) | ~(A | C) --> ~((B & C) | A)
1928349cc55cSDimitry Andric     // (~(A & B) | C) & ~(A & C) --> ~((B | C) & A)
1929349cc55cSDimitry Andric     if (match(Op1, m_OneUse(m_Not(m_OneUse(
1930349cc55cSDimitry Andric                        m_c_BinOp(Opcode, m_Specific(A), m_Specific(C)))))))
1931349cc55cSDimitry Andric       return BinaryOperator::CreateNot(Builder.CreateBinOp(
1932349cc55cSDimitry Andric           Opcode, Builder.CreateBinOp(FlippedOpcode, B, C), A));
1933349cc55cSDimitry Andric 
1934349cc55cSDimitry Andric     // (~(A | B) & C) | ~(B | C) --> ~((A & C) | B)
1935349cc55cSDimitry Andric     // (~(A & B) | C) & ~(B & C) --> ~((A | C) & B)
1936349cc55cSDimitry Andric     if (match(Op1, m_OneUse(m_Not(m_OneUse(
1937349cc55cSDimitry Andric                        m_c_BinOp(Opcode, m_Specific(B), m_Specific(C)))))))
1938349cc55cSDimitry Andric       return BinaryOperator::CreateNot(Builder.CreateBinOp(
1939349cc55cSDimitry Andric           Opcode, Builder.CreateBinOp(FlippedOpcode, A, C), B));
19404824e7fdSDimitry Andric 
19414824e7fdSDimitry Andric     // (~(A | B) & C) | ~(C | (A ^ B)) --> ~((A | B) & (C | (A ^ B)))
19424824e7fdSDimitry Andric     // Note, the pattern with swapped and/or is not handled because the
19434824e7fdSDimitry Andric     // result is more undefined than a source:
19444824e7fdSDimitry Andric     // (~(A & B) | C) & ~(C & (A ^ B)) --> (A ^ B ^ C) | ~(A | C) is invalid.
19454824e7fdSDimitry Andric     if (Opcode == Instruction::Or && Op0->hasOneUse() &&
19464824e7fdSDimitry Andric         match(Op1, m_OneUse(m_Not(m_CombineAnd(
19474824e7fdSDimitry Andric                        m_Value(Y),
19484824e7fdSDimitry Andric                        m_c_BinOp(Opcode, m_Specific(C),
19494824e7fdSDimitry Andric                                  m_c_Xor(m_Specific(A), m_Specific(B)))))))) {
19504824e7fdSDimitry Andric       // X = ~(A | B)
19514824e7fdSDimitry Andric       // Y = (C | (A ^ B)
19524824e7fdSDimitry Andric       Value *Or = cast<BinaryOperator>(X)->getOperand(0);
19534824e7fdSDimitry Andric       return BinaryOperator::CreateNot(Builder.CreateAnd(Or, Y));
19544824e7fdSDimitry Andric     }
1955349cc55cSDimitry Andric   }
1956349cc55cSDimitry Andric 
19570eae32dcSDimitry Andric   // (~A & B & C) | ... --> ...
19580eae32dcSDimitry Andric   // (~A | B | C) | ... --> ...
19590eae32dcSDimitry Andric   // TODO: One use checks are conservative. We just need to check that a total
19600eae32dcSDimitry Andric   //       number of multiple used values does not exceed reduction
19610eae32dcSDimitry Andric   //       in operations.
19620eae32dcSDimitry Andric   if (match(Op0,
19630eae32dcSDimitry Andric             m_OneUse(m_c_BinOp(FlippedOpcode,
19640eae32dcSDimitry Andric                                m_BinOp(FlippedOpcode, m_Value(B), m_Value(C)),
19650eae32dcSDimitry Andric                                m_CombineAnd(m_Value(X), m_Not(m_Value(A)))))) ||
19660eae32dcSDimitry Andric       match(Op0, m_OneUse(m_c_BinOp(
19670eae32dcSDimitry Andric                      FlippedOpcode,
19680eae32dcSDimitry Andric                      m_c_BinOp(FlippedOpcode, m_Value(C),
19690eae32dcSDimitry Andric                                m_CombineAnd(m_Value(X), m_Not(m_Value(A)))),
19700eae32dcSDimitry Andric                      m_Value(B))))) {
19710eae32dcSDimitry Andric     // X = ~A
19720eae32dcSDimitry Andric     // (~A & B & C) | ~(A | B | C) --> ~(A | (B ^ C))
19730eae32dcSDimitry Andric     // (~A | B | C) & ~(A & B & C) --> (~A | (B ^ C))
19740eae32dcSDimitry Andric     if (match(Op1, m_OneUse(m_Not(m_c_BinOp(
19750eae32dcSDimitry Andric                        Opcode, m_c_BinOp(Opcode, m_Specific(A), m_Specific(B)),
19760eae32dcSDimitry Andric                        m_Specific(C))))) ||
19770eae32dcSDimitry Andric         match(Op1, m_OneUse(m_Not(m_c_BinOp(
19780eae32dcSDimitry Andric                        Opcode, m_c_BinOp(Opcode, m_Specific(B), m_Specific(C)),
19790eae32dcSDimitry Andric                        m_Specific(A))))) ||
19800eae32dcSDimitry Andric         match(Op1, m_OneUse(m_Not(m_c_BinOp(
19810eae32dcSDimitry Andric                        Opcode, m_c_BinOp(Opcode, m_Specific(A), m_Specific(C)),
19820eae32dcSDimitry Andric                        m_Specific(B)))))) {
19830eae32dcSDimitry Andric       Value *Xor = Builder.CreateXor(B, C);
19840eae32dcSDimitry Andric       return (Opcode == Instruction::Or)
19850eae32dcSDimitry Andric                  ? BinaryOperator::CreateNot(Builder.CreateOr(Xor, A))
19860eae32dcSDimitry Andric                  : BinaryOperator::CreateOr(Xor, X);
19870eae32dcSDimitry Andric     }
19880eae32dcSDimitry Andric 
19890eae32dcSDimitry Andric     // (~A & B & C) | ~(A | B) --> (C | ~B) & ~A
19900eae32dcSDimitry Andric     // (~A | B | C) & ~(A & B) --> (C & ~B) | ~A
19910eae32dcSDimitry Andric     if (match(Op1, m_OneUse(m_Not(m_OneUse(
19920eae32dcSDimitry Andric                        m_c_BinOp(Opcode, m_Specific(A), m_Specific(B)))))))
19930eae32dcSDimitry Andric       return BinaryOperator::Create(
19940eae32dcSDimitry Andric           FlippedOpcode, Builder.CreateBinOp(Opcode, C, Builder.CreateNot(B)),
19950eae32dcSDimitry Andric           X);
19960eae32dcSDimitry Andric 
19970eae32dcSDimitry Andric     // (~A & B & C) | ~(A | C) --> (B | ~C) & ~A
19980eae32dcSDimitry Andric     // (~A | B | C) & ~(A & C) --> (B & ~C) | ~A
19990eae32dcSDimitry Andric     if (match(Op1, m_OneUse(m_Not(m_OneUse(
20000eae32dcSDimitry Andric                        m_c_BinOp(Opcode, m_Specific(A), m_Specific(C)))))))
20010eae32dcSDimitry Andric       return BinaryOperator::Create(
20020eae32dcSDimitry Andric           FlippedOpcode, Builder.CreateBinOp(Opcode, B, Builder.CreateNot(C)),
20030eae32dcSDimitry Andric           X);
20040eae32dcSDimitry Andric   }
20050eae32dcSDimitry Andric 
2006349cc55cSDimitry Andric   return nullptr;
2007349cc55cSDimitry Andric }
2008349cc55cSDimitry Andric 
2009bdd1243dSDimitry Andric /// Try to reassociate a pair of binops so that values with one use only are
2010bdd1243dSDimitry Andric /// part of the same instruction. This may enable folds that are limited with
2011bdd1243dSDimitry Andric /// multi-use restrictions and makes it more likely to match other patterns that
2012bdd1243dSDimitry Andric /// are looking for a common operand.
reassociateForUses(BinaryOperator & BO,InstCombinerImpl::BuilderTy & Builder)2013bdd1243dSDimitry Andric static Instruction *reassociateForUses(BinaryOperator &BO,
2014bdd1243dSDimitry Andric                                        InstCombinerImpl::BuilderTy &Builder) {
2015bdd1243dSDimitry Andric   Instruction::BinaryOps Opcode = BO.getOpcode();
2016bdd1243dSDimitry Andric   Value *X, *Y, *Z;
2017bdd1243dSDimitry Andric   if (match(&BO,
2018bdd1243dSDimitry Andric             m_c_BinOp(Opcode, m_OneUse(m_BinOp(Opcode, m_Value(X), m_Value(Y))),
2019bdd1243dSDimitry Andric                       m_OneUse(m_Value(Z))))) {
2020bdd1243dSDimitry Andric     if (!isa<Constant>(X) && !isa<Constant>(Y) && !isa<Constant>(Z)) {
2021bdd1243dSDimitry Andric       // (X op Y) op Z --> (Y op Z) op X
2022bdd1243dSDimitry Andric       if (!X->hasOneUse()) {
2023bdd1243dSDimitry Andric         Value *YZ = Builder.CreateBinOp(Opcode, Y, Z);
2024bdd1243dSDimitry Andric         return BinaryOperator::Create(Opcode, YZ, X);
2025bdd1243dSDimitry Andric       }
2026bdd1243dSDimitry Andric       // (X op Y) op Z --> (X op Z) op Y
2027bdd1243dSDimitry Andric       if (!Y->hasOneUse()) {
2028bdd1243dSDimitry Andric         Value *XZ = Builder.CreateBinOp(Opcode, X, Z);
2029bdd1243dSDimitry Andric         return BinaryOperator::Create(Opcode, XZ, Y);
2030bdd1243dSDimitry Andric       }
2031bdd1243dSDimitry Andric     }
2032bdd1243dSDimitry Andric   }
2033bdd1243dSDimitry Andric 
2034bdd1243dSDimitry Andric   return nullptr;
2035bdd1243dSDimitry Andric }
2036bdd1243dSDimitry Andric 
2037bdd1243dSDimitry Andric // Match
2038bdd1243dSDimitry Andric // (X + C2) | C
2039bdd1243dSDimitry Andric // (X + C2) ^ C
2040bdd1243dSDimitry Andric // (X + C2) & C
2041bdd1243dSDimitry Andric // and convert to do the bitwise logic first:
2042bdd1243dSDimitry Andric // (X | C) + C2
2043bdd1243dSDimitry Andric // (X ^ C) + C2
2044bdd1243dSDimitry Andric // (X & C) + C2
2045bdd1243dSDimitry Andric // iff bits affected by logic op are lower than last bit affected by math op
canonicalizeLogicFirst(BinaryOperator & I,InstCombiner::BuilderTy & Builder)2046bdd1243dSDimitry Andric static Instruction *canonicalizeLogicFirst(BinaryOperator &I,
2047bdd1243dSDimitry Andric                                            InstCombiner::BuilderTy &Builder) {
2048bdd1243dSDimitry Andric   Type *Ty = I.getType();
2049bdd1243dSDimitry Andric   Instruction::BinaryOps OpC = I.getOpcode();
2050bdd1243dSDimitry Andric   Value *Op0 = I.getOperand(0);
2051bdd1243dSDimitry Andric   Value *Op1 = I.getOperand(1);
2052bdd1243dSDimitry Andric   Value *X;
2053bdd1243dSDimitry Andric   const APInt *C, *C2;
2054bdd1243dSDimitry Andric 
2055bdd1243dSDimitry Andric   if (!(match(Op0, m_OneUse(m_Add(m_Value(X), m_APInt(C2)))) &&
2056bdd1243dSDimitry Andric         match(Op1, m_APInt(C))))
2057bdd1243dSDimitry Andric     return nullptr;
2058bdd1243dSDimitry Andric 
2059bdd1243dSDimitry Andric   unsigned Width = Ty->getScalarSizeInBits();
206006c3fb27SDimitry Andric   unsigned LastOneMath = Width - C2->countr_zero();
2061bdd1243dSDimitry Andric 
2062bdd1243dSDimitry Andric   switch (OpC) {
2063bdd1243dSDimitry Andric   case Instruction::And:
206406c3fb27SDimitry Andric     if (C->countl_one() < LastOneMath)
2065bdd1243dSDimitry Andric       return nullptr;
2066bdd1243dSDimitry Andric     break;
2067bdd1243dSDimitry Andric   case Instruction::Xor:
2068bdd1243dSDimitry Andric   case Instruction::Or:
206906c3fb27SDimitry Andric     if (C->countl_zero() < LastOneMath)
2070bdd1243dSDimitry Andric       return nullptr;
2071bdd1243dSDimitry Andric     break;
2072bdd1243dSDimitry Andric   default:
2073bdd1243dSDimitry Andric     llvm_unreachable("Unexpected BinaryOp!");
2074bdd1243dSDimitry Andric   }
2075bdd1243dSDimitry Andric 
2076bdd1243dSDimitry Andric   Value *NewBinOp = Builder.CreateBinOp(OpC, X, ConstantInt::get(Ty, *C));
207706c3fb27SDimitry Andric   return BinaryOperator::CreateWithCopiedFlags(Instruction::Add, NewBinOp,
207806c3fb27SDimitry Andric                                                ConstantInt::get(Ty, *C2), Op0);
207906c3fb27SDimitry Andric }
208006c3fb27SDimitry Andric 
208106c3fb27SDimitry Andric // binop(shift(ShiftedC1, ShAmt), shift(ShiftedC2, add(ShAmt, AddC))) ->
208206c3fb27SDimitry Andric // shift(binop(ShiftedC1, shift(ShiftedC2, AddC)), ShAmt)
208306c3fb27SDimitry Andric // where both shifts are the same and AddC is a valid shift amount.
foldBinOpOfDisplacedShifts(BinaryOperator & I)208406c3fb27SDimitry Andric Instruction *InstCombinerImpl::foldBinOpOfDisplacedShifts(BinaryOperator &I) {
208506c3fb27SDimitry Andric   assert((I.isBitwiseLogicOp() || I.getOpcode() == Instruction::Add) &&
208606c3fb27SDimitry Andric          "Unexpected opcode");
208706c3fb27SDimitry Andric 
208806c3fb27SDimitry Andric   Value *ShAmt;
208906c3fb27SDimitry Andric   Constant *ShiftedC1, *ShiftedC2, *AddC;
209006c3fb27SDimitry Andric   Type *Ty = I.getType();
209106c3fb27SDimitry Andric   unsigned BitWidth = Ty->getScalarSizeInBits();
20925f757f3fSDimitry Andric   if (!match(&I, m_c_BinOp(m_Shift(m_ImmConstant(ShiftedC1), m_Value(ShAmt)),
209306c3fb27SDimitry Andric                            m_Shift(m_ImmConstant(ShiftedC2),
20945f757f3fSDimitry Andric                                    m_AddLike(m_Deferred(ShAmt),
20955f757f3fSDimitry Andric                                              m_ImmConstant(AddC))))))
209606c3fb27SDimitry Andric     return nullptr;
209706c3fb27SDimitry Andric 
209806c3fb27SDimitry Andric   // Make sure the add constant is a valid shift amount.
209906c3fb27SDimitry Andric   if (!match(AddC,
210006c3fb27SDimitry Andric              m_SpecificInt_ICMP(ICmpInst::ICMP_ULT, APInt(BitWidth, BitWidth))))
210106c3fb27SDimitry Andric     return nullptr;
210206c3fb27SDimitry Andric 
210306c3fb27SDimitry Andric   // Avoid constant expressions.
210406c3fb27SDimitry Andric   auto *Op0Inst = dyn_cast<Instruction>(I.getOperand(0));
210506c3fb27SDimitry Andric   auto *Op1Inst = dyn_cast<Instruction>(I.getOperand(1));
210606c3fb27SDimitry Andric   if (!Op0Inst || !Op1Inst)
210706c3fb27SDimitry Andric     return nullptr;
210806c3fb27SDimitry Andric 
210906c3fb27SDimitry Andric   // Both shifts must be the same.
211006c3fb27SDimitry Andric   Instruction::BinaryOps ShiftOp =
211106c3fb27SDimitry Andric       static_cast<Instruction::BinaryOps>(Op0Inst->getOpcode());
211206c3fb27SDimitry Andric   if (ShiftOp != Op1Inst->getOpcode())
211306c3fb27SDimitry Andric     return nullptr;
211406c3fb27SDimitry Andric 
211506c3fb27SDimitry Andric   // For adds, only left shifts are supported.
211606c3fb27SDimitry Andric   if (I.getOpcode() == Instruction::Add && ShiftOp != Instruction::Shl)
211706c3fb27SDimitry Andric     return nullptr;
211806c3fb27SDimitry Andric 
211906c3fb27SDimitry Andric   Value *NewC = Builder.CreateBinOp(
212006c3fb27SDimitry Andric       I.getOpcode(), ShiftedC1, Builder.CreateBinOp(ShiftOp, ShiftedC2, AddC));
212106c3fb27SDimitry Andric   return BinaryOperator::Create(ShiftOp, NewC, ShAmt);
2122bdd1243dSDimitry Andric }
2123bdd1243dSDimitry Andric 
2124297eecfbSDimitry Andric // Fold and/or/xor with two equal intrinsic IDs:
2125297eecfbSDimitry Andric // bitwise(fshl (A, B, ShAmt), fshl(C, D, ShAmt))
2126297eecfbSDimitry Andric // -> fshl(bitwise(A, C), bitwise(B, D), ShAmt)
2127297eecfbSDimitry Andric // bitwise(fshr (A, B, ShAmt), fshr(C, D, ShAmt))
2128297eecfbSDimitry Andric // -> fshr(bitwise(A, C), bitwise(B, D), ShAmt)
2129297eecfbSDimitry Andric // bitwise(bswap(A), bswap(B)) -> bswap(bitwise(A, B))
2130297eecfbSDimitry Andric // bitwise(bswap(A), C) -> bswap(bitwise(A, bswap(C)))
2131297eecfbSDimitry Andric // bitwise(bitreverse(A), bitreverse(B)) -> bitreverse(bitwise(A, B))
2132297eecfbSDimitry Andric // bitwise(bitreverse(A), C) -> bitreverse(bitwise(A, bitreverse(C)))
2133297eecfbSDimitry Andric static Instruction *
foldBitwiseLogicWithIntrinsics(BinaryOperator & I,InstCombiner::BuilderTy & Builder)2134297eecfbSDimitry Andric foldBitwiseLogicWithIntrinsics(BinaryOperator &I,
2135297eecfbSDimitry Andric                                InstCombiner::BuilderTy &Builder) {
2136297eecfbSDimitry Andric   assert(I.isBitwiseLogicOp() && "Should and/or/xor");
2137297eecfbSDimitry Andric   if (!I.getOperand(0)->hasOneUse())
2138297eecfbSDimitry Andric     return nullptr;
2139297eecfbSDimitry Andric   IntrinsicInst *X = dyn_cast<IntrinsicInst>(I.getOperand(0));
2140297eecfbSDimitry Andric   if (!X)
2141297eecfbSDimitry Andric     return nullptr;
2142297eecfbSDimitry Andric 
2143297eecfbSDimitry Andric   IntrinsicInst *Y = dyn_cast<IntrinsicInst>(I.getOperand(1));
2144297eecfbSDimitry Andric   if (Y && (!Y->hasOneUse() || X->getIntrinsicID() != Y->getIntrinsicID()))
2145297eecfbSDimitry Andric     return nullptr;
2146297eecfbSDimitry Andric 
2147297eecfbSDimitry Andric   Intrinsic::ID IID = X->getIntrinsicID();
2148297eecfbSDimitry Andric   const APInt *RHSC;
2149297eecfbSDimitry Andric   // Try to match constant RHS.
2150297eecfbSDimitry Andric   if (!Y && (!(IID == Intrinsic::bswap || IID == Intrinsic::bitreverse) ||
2151297eecfbSDimitry Andric              !match(I.getOperand(1), m_APInt(RHSC))))
2152297eecfbSDimitry Andric     return nullptr;
2153297eecfbSDimitry Andric 
2154297eecfbSDimitry Andric   switch (IID) {
2155297eecfbSDimitry Andric   case Intrinsic::fshl:
2156297eecfbSDimitry Andric   case Intrinsic::fshr: {
2157297eecfbSDimitry Andric     if (X->getOperand(2) != Y->getOperand(2))
2158297eecfbSDimitry Andric       return nullptr;
2159297eecfbSDimitry Andric     Value *NewOp0 =
2160297eecfbSDimitry Andric         Builder.CreateBinOp(I.getOpcode(), X->getOperand(0), Y->getOperand(0));
2161297eecfbSDimitry Andric     Value *NewOp1 =
2162297eecfbSDimitry Andric         Builder.CreateBinOp(I.getOpcode(), X->getOperand(1), Y->getOperand(1));
2163297eecfbSDimitry Andric     Function *F = Intrinsic::getDeclaration(I.getModule(), IID, I.getType());
2164297eecfbSDimitry Andric     return CallInst::Create(F, {NewOp0, NewOp1, X->getOperand(2)});
2165297eecfbSDimitry Andric   }
2166297eecfbSDimitry Andric   case Intrinsic::bswap:
2167297eecfbSDimitry Andric   case Intrinsic::bitreverse: {
2168297eecfbSDimitry Andric     Value *NewOp0 = Builder.CreateBinOp(
2169297eecfbSDimitry Andric         I.getOpcode(), X->getOperand(0),
2170297eecfbSDimitry Andric         Y ? Y->getOperand(0)
2171297eecfbSDimitry Andric           : ConstantInt::get(I.getType(), IID == Intrinsic::bswap
2172297eecfbSDimitry Andric                                               ? RHSC->byteSwap()
2173297eecfbSDimitry Andric                                               : RHSC->reverseBits()));
2174297eecfbSDimitry Andric     Function *F = Intrinsic::getDeclaration(I.getModule(), IID, I.getType());
2175297eecfbSDimitry Andric     return CallInst::Create(F, {NewOp0});
2176297eecfbSDimitry Andric   }
2177297eecfbSDimitry Andric   default:
2178297eecfbSDimitry Andric     return nullptr;
2179297eecfbSDimitry Andric   }
2180297eecfbSDimitry Andric }
2181297eecfbSDimitry Andric 
21820b57cec5SDimitry Andric // FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
21830b57cec5SDimitry Andric // here. We should standardize that construct where it is needed or choose some
21840b57cec5SDimitry Andric // other way to ensure that commutated variants of patterns are not missed.
visitAnd(BinaryOperator & I)2185e8d8bef9SDimitry Andric Instruction *InstCombinerImpl::visitAnd(BinaryOperator &I) {
2186e8d8bef9SDimitry Andric   Type *Ty = I.getType();
2187e8d8bef9SDimitry Andric 
218881ad6265SDimitry Andric   if (Value *V = simplifyAndInst(I.getOperand(0), I.getOperand(1),
21890b57cec5SDimitry Andric                                  SQ.getWithInstruction(&I)))
21900b57cec5SDimitry Andric     return replaceInstUsesWith(I, V);
21910b57cec5SDimitry Andric 
21920b57cec5SDimitry Andric   if (SimplifyAssociativeOrCommutative(I))
21930b57cec5SDimitry Andric     return &I;
21940b57cec5SDimitry Andric 
21950b57cec5SDimitry Andric   if (Instruction *X = foldVectorBinop(I))
21960b57cec5SDimitry Andric     return X;
21970b57cec5SDimitry Andric 
219804eeddc0SDimitry Andric   if (Instruction *Phi = foldBinopWithPhiOperands(I))
219904eeddc0SDimitry Andric     return Phi;
220004eeddc0SDimitry Andric 
22010b57cec5SDimitry Andric   // See if we can simplify any instructions used by the instruction whose sole
22020b57cec5SDimitry Andric   // purpose is to compute bits we don't care about.
22030b57cec5SDimitry Andric   if (SimplifyDemandedInstructionBits(I))
22040b57cec5SDimitry Andric     return &I;
22050b57cec5SDimitry Andric 
22060b57cec5SDimitry Andric   // Do this before using distributive laws to catch simple and/or/not patterns.
22070b57cec5SDimitry Andric   if (Instruction *Xor = foldAndToXor(I, Builder))
22080b57cec5SDimitry Andric     return Xor;
22090b57cec5SDimitry Andric 
2210349cc55cSDimitry Andric   if (Instruction *X = foldComplexAndOrPatterns(I, Builder))
2211349cc55cSDimitry Andric     return X;
2212349cc55cSDimitry Andric 
22130b57cec5SDimitry Andric   // (A|B)&(A|C) -> A|(B&C) etc
2214bdd1243dSDimitry Andric   if (Value *V = foldUsingDistributiveLaws(I))
22150b57cec5SDimitry Andric     return replaceInstUsesWith(I, V);
22160b57cec5SDimitry Andric 
221706c3fb27SDimitry Andric   if (Instruction *R = foldBinOpShiftWithShift(I))
221806c3fb27SDimitry Andric     return R;
221906c3fb27SDimitry Andric 
22200b57cec5SDimitry Andric   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2221e8d8bef9SDimitry Andric 
22220b57cec5SDimitry Andric   Value *X, *Y;
22230b57cec5SDimitry Andric   if (match(Op0, m_OneUse(m_LogicalShift(m_One(), m_Value(X)))) &&
2224e8d8bef9SDimitry Andric       match(Op1, m_One())) {
22250b57cec5SDimitry Andric     // (1 << X) & 1 --> zext(X == 0)
22260b57cec5SDimitry Andric     // (1 >> X) & 1 --> zext(X == 0)
2227e8d8bef9SDimitry Andric     Value *IsZero = Builder.CreateICmpEQ(X, ConstantInt::get(Ty, 0));
2228e8d8bef9SDimitry Andric     return new ZExtInst(IsZero, Ty);
22290b57cec5SDimitry Andric   }
22300b57cec5SDimitry Andric 
2231753f127fSDimitry Andric   // (-(X & 1)) & Y --> (X & 1) == 0 ? 0 : Y
2232753f127fSDimitry Andric   Value *Neg;
2233753f127fSDimitry Andric   if (match(&I,
2234753f127fSDimitry Andric             m_c_And(m_CombineAnd(m_Value(Neg),
2235753f127fSDimitry Andric                                  m_OneUse(m_Neg(m_And(m_Value(), m_One())))),
2236753f127fSDimitry Andric                     m_Value(Y)))) {
2237753f127fSDimitry Andric     Value *Cmp = Builder.CreateIsNull(Neg);
2238753f127fSDimitry Andric     return SelectInst::Create(Cmp, ConstantInt::getNullValue(Ty), Y);
2239753f127fSDimitry Andric   }
2240753f127fSDimitry Andric 
22415f757f3fSDimitry Andric   // Canonicalize:
22425f757f3fSDimitry Andric   // (X +/- Y) & Y --> ~X & Y when Y is a power of 2.
22435f757f3fSDimitry Andric   if (match(&I, m_c_And(m_Value(Y), m_OneUse(m_CombineOr(
22445f757f3fSDimitry Andric                                         m_c_Add(m_Value(X), m_Deferred(Y)),
22455f757f3fSDimitry Andric                                         m_Sub(m_Value(X), m_Deferred(Y)))))) &&
22465f757f3fSDimitry Andric       isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, /*Depth*/ 0, &I))
22475f757f3fSDimitry Andric     return BinaryOperator::CreateAnd(Builder.CreateNot(X), Y);
22485f757f3fSDimitry Andric 
2249e8d8bef9SDimitry Andric   const APInt *C;
2250e8d8bef9SDimitry Andric   if (match(Op1, m_APInt(C))) {
22510b57cec5SDimitry Andric     const APInt *XorC;
22520b57cec5SDimitry Andric     if (match(Op0, m_OneUse(m_Xor(m_Value(X), m_APInt(XorC))))) {
22530b57cec5SDimitry Andric       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2254e8d8bef9SDimitry Andric       Constant *NewC = ConstantInt::get(Ty, *C & *XorC);
22550b57cec5SDimitry Andric       Value *And = Builder.CreateAnd(X, Op1);
22560b57cec5SDimitry Andric       And->takeName(Op0);
22570b57cec5SDimitry Andric       return BinaryOperator::CreateXor(And, NewC);
22580b57cec5SDimitry Andric     }
22590b57cec5SDimitry Andric 
22600b57cec5SDimitry Andric     const APInt *OrC;
22610b57cec5SDimitry Andric     if (match(Op0, m_OneUse(m_Or(m_Value(X), m_APInt(OrC))))) {
22620b57cec5SDimitry Andric       // (X | C1) & C2 --> (X & C2^(C1&C2)) | (C1&C2)
22630b57cec5SDimitry Andric       // NOTE: This reduces the number of bits set in the & mask, which
22640b57cec5SDimitry Andric       // can expose opportunities for store narrowing for scalars.
22650b57cec5SDimitry Andric       // NOTE: SimplifyDemandedBits should have already removed bits from C1
22660b57cec5SDimitry Andric       // that aren't set in C2. Meaning we can replace (C1&C2) with C1 in
22670b57cec5SDimitry Andric       // above, but this feels safer.
22680b57cec5SDimitry Andric       APInt Together = *C & *OrC;
2269e8d8bef9SDimitry Andric       Value *And = Builder.CreateAnd(X, ConstantInt::get(Ty, Together ^ *C));
22700b57cec5SDimitry Andric       And->takeName(Op0);
2271e8d8bef9SDimitry Andric       return BinaryOperator::CreateOr(And, ConstantInt::get(Ty, Together));
22720b57cec5SDimitry Andric     }
22730b57cec5SDimitry Andric 
2274e8d8bef9SDimitry Andric     unsigned Width = Ty->getScalarSizeInBits();
22755ffd83dbSDimitry Andric     const APInt *ShiftC;
2276753f127fSDimitry Andric     if (match(Op0, m_OneUse(m_SExt(m_AShr(m_Value(X), m_APInt(ShiftC))))) &&
2277753f127fSDimitry Andric         ShiftC->ult(Width)) {
22785ffd83dbSDimitry Andric       if (*C == APInt::getLowBitsSet(Width, Width - ShiftC->getZExtValue())) {
22795ffd83dbSDimitry Andric         // We are clearing high bits that were potentially set by sext+ashr:
22805ffd83dbSDimitry Andric         // and (sext (ashr X, ShiftC)), C --> lshr (sext X), ShiftC
2281e8d8bef9SDimitry Andric         Value *Sext = Builder.CreateSExt(X, Ty);
2282e8d8bef9SDimitry Andric         Constant *ShAmtC = ConstantInt::get(Ty, ShiftC->zext(Width));
22835ffd83dbSDimitry Andric         return BinaryOperator::CreateLShr(Sext, ShAmtC);
22845ffd83dbSDimitry Andric       }
22855ffd83dbSDimitry Andric     }
2286e8d8bef9SDimitry Andric 
22873a9a9c0cSDimitry Andric     // If this 'and' clears the sign-bits added by ashr, replace with lshr:
22883a9a9c0cSDimitry Andric     // and (ashr X, ShiftC), C --> lshr X, ShiftC
22893a9a9c0cSDimitry Andric     if (match(Op0, m_AShr(m_Value(X), m_APInt(ShiftC))) && ShiftC->ult(Width) &&
22903a9a9c0cSDimitry Andric         C->isMask(Width - ShiftC->getZExtValue()))
22913a9a9c0cSDimitry Andric       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, *ShiftC));
22923a9a9c0cSDimitry Andric 
2293e8d8bef9SDimitry Andric     const APInt *AddC;
2294e8d8bef9SDimitry Andric     if (match(Op0, m_Add(m_Value(X), m_APInt(AddC)))) {
2295e8d8bef9SDimitry Andric       // If we are masking the result of the add down to exactly one bit and
2296e8d8bef9SDimitry Andric       // the constant we are adding has no bits set below that bit, then the
2297e8d8bef9SDimitry Andric       // add is flipping a single bit. Example:
2298e8d8bef9SDimitry Andric       // (X + 4) & 4 --> (X & 4) ^ 4
2299e8d8bef9SDimitry Andric       if (Op0->hasOneUse() && C->isPowerOf2() && (*AddC & (*C - 1)) == 0) {
2300e8d8bef9SDimitry Andric         assert((*C & *AddC) != 0 && "Expected common bit");
2301e8d8bef9SDimitry Andric         Value *NewAnd = Builder.CreateAnd(X, Op1);
2302e8d8bef9SDimitry Andric         return BinaryOperator::CreateXor(NewAnd, Op1);
2303e8d8bef9SDimitry Andric       }
2304e8d8bef9SDimitry Andric     }
23050b57cec5SDimitry Andric 
2306349cc55cSDimitry Andric     // ((C1 OP zext(X)) & C2) -> zext((C1 OP X) & C2) if C2 fits in the
2307349cc55cSDimitry Andric     // bitwidth of X and OP behaves well when given trunc(C1) and X.
230881ad6265SDimitry Andric     auto isNarrowableBinOpcode = [](BinaryOperator *B) {
2309349cc55cSDimitry Andric       switch (B->getOpcode()) {
23100b57cec5SDimitry Andric       case Instruction::Xor:
23110b57cec5SDimitry Andric       case Instruction::Or:
23120b57cec5SDimitry Andric       case Instruction::Mul:
23130b57cec5SDimitry Andric       case Instruction::Add:
23140b57cec5SDimitry Andric       case Instruction::Sub:
2315349cc55cSDimitry Andric         return true;
2316349cc55cSDimitry Andric       default:
2317349cc55cSDimitry Andric         return false;
2318349cc55cSDimitry Andric       }
2319349cc55cSDimitry Andric     };
2320349cc55cSDimitry Andric     BinaryOperator *BO;
232181ad6265SDimitry Andric     if (match(Op0, m_OneUse(m_BinOp(BO))) && isNarrowableBinOpcode(BO)) {
232281ad6265SDimitry Andric       Instruction::BinaryOps BOpcode = BO->getOpcode();
23230b57cec5SDimitry Andric       Value *X;
2324349cc55cSDimitry Andric       const APInt *C1;
2325349cc55cSDimitry Andric       // TODO: The one-use restrictions could be relaxed a little if the AND
23260b57cec5SDimitry Andric       // is going to be removed.
232781ad6265SDimitry Andric       // Try to narrow the 'and' and a binop with constant operand:
232881ad6265SDimitry Andric       // and (bo (zext X), C1), C --> zext (and (bo X, TruncC1), TruncC)
2329349cc55cSDimitry Andric       if (match(BO, m_c_BinOp(m_OneUse(m_ZExt(m_Value(X))), m_APInt(C1))) &&
2330349cc55cSDimitry Andric           C->isIntN(X->getType()->getScalarSizeInBits())) {
2331349cc55cSDimitry Andric         unsigned XWidth = X->getType()->getScalarSizeInBits();
2332349cc55cSDimitry Andric         Constant *TruncC1 = ConstantInt::get(X->getType(), C1->trunc(XWidth));
2333349cc55cSDimitry Andric         Value *BinOp = isa<ZExtInst>(BO->getOperand(0))
233481ad6265SDimitry Andric                            ? Builder.CreateBinOp(BOpcode, X, TruncC1)
233581ad6265SDimitry Andric                            : Builder.CreateBinOp(BOpcode, TruncC1, X);
2336349cc55cSDimitry Andric         Constant *TruncC = ConstantInt::get(X->getType(), C->trunc(XWidth));
2337349cc55cSDimitry Andric         Value *And = Builder.CreateAnd(BinOp, TruncC);
2338e8d8bef9SDimitry Andric         return new ZExtInst(And, Ty);
2339e8d8bef9SDimitry Andric       }
234081ad6265SDimitry Andric 
234181ad6265SDimitry Andric       // Similar to above: if the mask matches the zext input width, then the
234281ad6265SDimitry Andric       // 'and' can be eliminated, so we can truncate the other variable op:
234381ad6265SDimitry Andric       // and (bo (zext X), Y), C --> zext (bo X, (trunc Y))
234481ad6265SDimitry Andric       if (isa<Instruction>(BO->getOperand(0)) &&
234581ad6265SDimitry Andric           match(BO->getOperand(0), m_OneUse(m_ZExt(m_Value(X)))) &&
234681ad6265SDimitry Andric           C->isMask(X->getType()->getScalarSizeInBits())) {
234781ad6265SDimitry Andric         Y = BO->getOperand(1);
234881ad6265SDimitry Andric         Value *TrY = Builder.CreateTrunc(Y, X->getType(), Y->getName() + ".tr");
234981ad6265SDimitry Andric         Value *NewBO =
235081ad6265SDimitry Andric             Builder.CreateBinOp(BOpcode, X, TrY, BO->getName() + ".narrow");
235181ad6265SDimitry Andric         return new ZExtInst(NewBO, Ty);
235281ad6265SDimitry Andric       }
235381ad6265SDimitry Andric       // and (bo Y, (zext X)), C --> zext (bo (trunc Y), X)
235481ad6265SDimitry Andric       if (isa<Instruction>(BO->getOperand(1)) &&
235581ad6265SDimitry Andric           match(BO->getOperand(1), m_OneUse(m_ZExt(m_Value(X)))) &&
235681ad6265SDimitry Andric           C->isMask(X->getType()->getScalarSizeInBits())) {
235781ad6265SDimitry Andric         Y = BO->getOperand(0);
235881ad6265SDimitry Andric         Value *TrY = Builder.CreateTrunc(Y, X->getType(), Y->getName() + ".tr");
235981ad6265SDimitry Andric         Value *NewBO =
236081ad6265SDimitry Andric             Builder.CreateBinOp(BOpcode, TrY, X, BO->getName() + ".narrow");
236181ad6265SDimitry Andric         return new ZExtInst(NewBO, Ty);
236281ad6265SDimitry Andric       }
236381ad6265SDimitry Andric     }
236481ad6265SDimitry Andric 
236581ad6265SDimitry Andric     // This is intentionally placed after the narrowing transforms for
236681ad6265SDimitry Andric     // efficiency (transform directly to the narrow logic op if possible).
236781ad6265SDimitry Andric     // If the mask is only needed on one incoming arm, push the 'and' op up.
236881ad6265SDimitry Andric     if (match(Op0, m_OneUse(m_Xor(m_Value(X), m_Value(Y)))) ||
236981ad6265SDimitry Andric         match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
237081ad6265SDimitry Andric       APInt NotAndMask(~(*C));
237181ad6265SDimitry Andric       BinaryOperator::BinaryOps BinOp = cast<BinaryOperator>(Op0)->getOpcode();
237281ad6265SDimitry Andric       if (MaskedValueIsZero(X, NotAndMask, 0, &I)) {
237381ad6265SDimitry Andric         // Not masking anything out for the LHS, move mask to RHS.
237481ad6265SDimitry Andric         // and ({x}or X, Y), C --> {x}or X, (and Y, C)
237581ad6265SDimitry Andric         Value *NewRHS = Builder.CreateAnd(Y, Op1, Y->getName() + ".masked");
237681ad6265SDimitry Andric         return BinaryOperator::Create(BinOp, X, NewRHS);
237781ad6265SDimitry Andric       }
237881ad6265SDimitry Andric       if (!isa<Constant>(Y) && MaskedValueIsZero(Y, NotAndMask, 0, &I)) {
237981ad6265SDimitry Andric         // Not masking anything out for the RHS, move mask to LHS.
238081ad6265SDimitry Andric         // and ({x}or X, Y), C --> {x}or (and X, C), Y
238181ad6265SDimitry Andric         Value *NewLHS = Builder.CreateAnd(X, Op1, X->getName() + ".masked");
238281ad6265SDimitry Andric         return BinaryOperator::Create(BinOp, NewLHS, Y);
238381ad6265SDimitry Andric       }
238481ad6265SDimitry Andric     }
238581ad6265SDimitry Andric 
238681ad6265SDimitry Andric     // When the mask is a power-of-2 constant and op0 is a shifted-power-of-2
238781ad6265SDimitry Andric     // constant, test if the shift amount equals the offset bit index:
238881ad6265SDimitry Andric     // (ShiftC << X) & C --> X == (log2(C) - log2(ShiftC)) ? C : 0
238981ad6265SDimitry Andric     // (ShiftC >> X) & C --> X == (log2(ShiftC) - log2(C)) ? C : 0
239081ad6265SDimitry Andric     if (C->isPowerOf2() &&
239181ad6265SDimitry Andric         match(Op0, m_OneUse(m_LogicalShift(m_Power2(ShiftC), m_Value(X))))) {
239281ad6265SDimitry Andric       int Log2ShiftC = ShiftC->exactLogBase2();
239381ad6265SDimitry Andric       int Log2C = C->exactLogBase2();
239481ad6265SDimitry Andric       bool IsShiftLeft =
239581ad6265SDimitry Andric          cast<BinaryOperator>(Op0)->getOpcode() == Instruction::Shl;
239681ad6265SDimitry Andric       int BitNum = IsShiftLeft ? Log2C - Log2ShiftC : Log2ShiftC - Log2C;
239781ad6265SDimitry Andric       assert(BitNum >= 0 && "Expected demanded bits to handle impossible mask");
239881ad6265SDimitry Andric       Value *Cmp = Builder.CreateICmpEQ(X, ConstantInt::get(Ty, BitNum));
239981ad6265SDimitry Andric       return SelectInst::Create(Cmp, ConstantInt::get(Ty, *C),
240081ad6265SDimitry Andric                                 ConstantInt::getNullValue(Ty));
240181ad6265SDimitry Andric     }
240281ad6265SDimitry Andric 
240381ad6265SDimitry Andric     Constant *C1, *C2;
240481ad6265SDimitry Andric     const APInt *C3 = C;
240581ad6265SDimitry Andric     Value *X;
240681ad6265SDimitry Andric     if (C3->isPowerOf2()) {
240706c3fb27SDimitry Andric       Constant *Log2C3 = ConstantInt::get(Ty, C3->countr_zero());
240881ad6265SDimitry Andric       if (match(Op0, m_OneUse(m_LShr(m_Shl(m_ImmConstant(C1), m_Value(X)),
240981ad6265SDimitry Andric                                      m_ImmConstant(C2)))) &&
241081ad6265SDimitry Andric           match(C1, m_Power2())) {
241181ad6265SDimitry Andric         Constant *Log2C1 = ConstantExpr::getExactLogBase2(C1);
241281ad6265SDimitry Andric         Constant *LshrC = ConstantExpr::getAdd(C2, Log2C3);
241381ad6265SDimitry Andric         KnownBits KnownLShrc = computeKnownBits(LshrC, 0, nullptr);
241481ad6265SDimitry Andric         if (KnownLShrc.getMaxValue().ult(Width)) {
241581ad6265SDimitry Andric           // iff C1,C3 is pow2 and C2 + cttz(C3) < BitWidth:
241681ad6265SDimitry Andric           // ((C1 << X) >> C2) & C3 -> X == (cttz(C3)+C2-cttz(C1)) ? C3 : 0
241781ad6265SDimitry Andric           Constant *CmpC = ConstantExpr::getSub(LshrC, Log2C1);
241881ad6265SDimitry Andric           Value *Cmp = Builder.CreateICmpEQ(X, CmpC);
241981ad6265SDimitry Andric           return SelectInst::Create(Cmp, ConstantInt::get(Ty, *C3),
242081ad6265SDimitry Andric                                     ConstantInt::getNullValue(Ty));
242181ad6265SDimitry Andric         }
242281ad6265SDimitry Andric       }
242381ad6265SDimitry Andric 
242481ad6265SDimitry Andric       if (match(Op0, m_OneUse(m_Shl(m_LShr(m_ImmConstant(C1), m_Value(X)),
242581ad6265SDimitry Andric                                     m_ImmConstant(C2)))) &&
242681ad6265SDimitry Andric           match(C1, m_Power2())) {
242781ad6265SDimitry Andric         Constant *Log2C1 = ConstantExpr::getExactLogBase2(C1);
242881ad6265SDimitry Andric         Constant *Cmp =
242981ad6265SDimitry Andric             ConstantExpr::getCompare(ICmpInst::ICMP_ULT, Log2C3, C2);
243081ad6265SDimitry Andric         if (Cmp->isZeroValue()) {
243181ad6265SDimitry Andric           // iff C1,C3 is pow2 and Log2(C3) >= C2:
243281ad6265SDimitry Andric           // ((C1 >> X) << C2) & C3 -> X == (cttz(C1)+C2-cttz(C3)) ? C3 : 0
243381ad6265SDimitry Andric           Constant *ShlC = ConstantExpr::getAdd(C2, Log2C1);
243481ad6265SDimitry Andric           Constant *CmpC = ConstantExpr::getSub(ShlC, Log2C3);
243581ad6265SDimitry Andric           Value *Cmp = Builder.CreateICmpEQ(X, CmpC);
243681ad6265SDimitry Andric           return SelectInst::Create(Cmp, ConstantInt::get(Ty, *C3),
243781ad6265SDimitry Andric                                     ConstantInt::getNullValue(Ty));
243881ad6265SDimitry Andric         }
243981ad6265SDimitry Andric       }
2440e8d8bef9SDimitry Andric     }
24410b57cec5SDimitry Andric   }
24420b57cec5SDimitry Andric 
24435f757f3fSDimitry Andric   // If we are clearing the sign bit of a floating-point value, convert this to
24445f757f3fSDimitry Andric   // fabs, then cast back to integer.
24455f757f3fSDimitry Andric   //
24465f757f3fSDimitry Andric   // This is a generous interpretation for noimplicitfloat, this is not a true
24475f757f3fSDimitry Andric   // floating-point operation.
24485f757f3fSDimitry Andric   //
24495f757f3fSDimitry Andric   // Assumes any IEEE-represented type has the sign bit in the high bit.
24505f757f3fSDimitry Andric   // TODO: Unify with APInt matcher. This version allows undef unlike m_APInt
24515f757f3fSDimitry Andric   Value *CastOp;
24525f757f3fSDimitry Andric   if (match(Op0, m_BitCast(m_Value(CastOp))) &&
24535f757f3fSDimitry Andric       match(Op1, m_MaxSignedValue()) &&
24545f757f3fSDimitry Andric       !Builder.GetInsertBlock()->getParent()->hasFnAttribute(
24555f757f3fSDimitry Andric         Attribute::NoImplicitFloat)) {
24565f757f3fSDimitry Andric     Type *EltTy = CastOp->getType()->getScalarType();
24575f757f3fSDimitry Andric     if (EltTy->isFloatingPointTy() && EltTy->isIEEE() &&
24585f757f3fSDimitry Andric         EltTy->getPrimitiveSizeInBits() ==
24595f757f3fSDimitry Andric         I.getType()->getScalarType()->getPrimitiveSizeInBits()) {
24605f757f3fSDimitry Andric       Value *FAbs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, CastOp);
24615f757f3fSDimitry Andric       return new BitCastInst(FAbs, I.getType());
24625f757f3fSDimitry Andric     }
24635f757f3fSDimitry Andric   }
24645f757f3fSDimitry Andric 
2465e8d8bef9SDimitry Andric   if (match(&I, m_And(m_OneUse(m_Shl(m_ZExt(m_Value(X)), m_Value(Y))),
2466e8d8bef9SDimitry Andric                       m_SignMask())) &&
2467e8d8bef9SDimitry Andric       match(Y, m_SpecificInt_ICMP(
2468e8d8bef9SDimitry Andric                    ICmpInst::Predicate::ICMP_EQ,
2469e8d8bef9SDimitry Andric                    APInt(Ty->getScalarSizeInBits(),
2470e8d8bef9SDimitry Andric                          Ty->getScalarSizeInBits() -
2471e8d8bef9SDimitry Andric                              X->getType()->getScalarSizeInBits())))) {
2472e8d8bef9SDimitry Andric     auto *SExt = Builder.CreateSExt(X, Ty, X->getName() + ".signext");
2473e8d8bef9SDimitry Andric     auto *SanitizedSignMask = cast<Constant>(Op1);
2474e8d8bef9SDimitry Andric     // We must be careful with the undef elements of the sign bit mask, however:
2475e8d8bef9SDimitry Andric     // the mask elt can be undef iff the shift amount for that lane was undef,
2476e8d8bef9SDimitry Andric     // otherwise we need to sanitize undef masks to zero.
2477e8d8bef9SDimitry Andric     SanitizedSignMask = Constant::replaceUndefsWith(
2478e8d8bef9SDimitry Andric         SanitizedSignMask, ConstantInt::getNullValue(Ty->getScalarType()));
2479e8d8bef9SDimitry Andric     SanitizedSignMask =
2480e8d8bef9SDimitry Andric         Constant::mergeUndefsWith(SanitizedSignMask, cast<Constant>(Y));
2481e8d8bef9SDimitry Andric     return BinaryOperator::CreateAnd(SExt, SanitizedSignMask);
24820b57cec5SDimitry Andric   }
24830b57cec5SDimitry Andric 
24840b57cec5SDimitry Andric   if (Instruction *Z = narrowMaskedBinOp(I))
24850b57cec5SDimitry Andric     return Z;
24860b57cec5SDimitry Andric 
2487fe6060f1SDimitry Andric   if (I.getType()->isIntOrIntVectorTy(1)) {
2488fe6060f1SDimitry Andric     if (auto *SI0 = dyn_cast<SelectInst>(Op0)) {
24895f757f3fSDimitry Andric       if (auto *R =
2490fe6060f1SDimitry Andric               foldAndOrOfSelectUsingImpliedCond(Op1, *SI0, /* IsAnd */ true))
24915f757f3fSDimitry Andric         return R;
2492fe6060f1SDimitry Andric     }
2493fe6060f1SDimitry Andric     if (auto *SI1 = dyn_cast<SelectInst>(Op1)) {
24945f757f3fSDimitry Andric       if (auto *R =
2495fe6060f1SDimitry Andric               foldAndOrOfSelectUsingImpliedCond(Op0, *SI1, /* IsAnd */ true))
24965f757f3fSDimitry Andric         return R;
2497fe6060f1SDimitry Andric     }
2498fe6060f1SDimitry Andric   }
2499fe6060f1SDimitry Andric 
25000b57cec5SDimitry Andric   if (Instruction *FoldedLogic = foldBinOpIntoSelectOrPhi(I))
25010b57cec5SDimitry Andric     return FoldedLogic;
25020b57cec5SDimitry Andric 
25035f757f3fSDimitry Andric   if (Instruction *DeMorgan = matchDeMorgansLaws(I, *this))
25040b57cec5SDimitry Andric     return DeMorgan;
25050b57cec5SDimitry Andric 
25060b57cec5SDimitry Andric   {
25070b57cec5SDimitry Andric     Value *A, *B, *C;
25080b57cec5SDimitry Andric     // A & (A ^ B) --> A & ~B
25090b57cec5SDimitry Andric     if (match(Op1, m_OneUse(m_c_Xor(m_Specific(Op0), m_Value(B)))))
25100b57cec5SDimitry Andric       return BinaryOperator::CreateAnd(Op0, Builder.CreateNot(B));
25110b57cec5SDimitry Andric     // (A ^ B) & A --> A & ~B
25120b57cec5SDimitry Andric     if (match(Op0, m_OneUse(m_c_Xor(m_Specific(Op1), m_Value(B)))))
25130b57cec5SDimitry Andric       return BinaryOperator::CreateAnd(Op1, Builder.CreateNot(B));
25140b57cec5SDimitry Andric 
2515e8d8bef9SDimitry Andric     // A & ~(A ^ B) --> A & B
2516e8d8bef9SDimitry Andric     if (match(Op1, m_Not(m_c_Xor(m_Specific(Op0), m_Value(B)))))
2517e8d8bef9SDimitry Andric       return BinaryOperator::CreateAnd(Op0, B);
2518e8d8bef9SDimitry Andric     // ~(A ^ B) & A --> A & B
2519e8d8bef9SDimitry Andric     if (match(Op0, m_Not(m_c_Xor(m_Specific(Op1), m_Value(B)))))
2520e8d8bef9SDimitry Andric       return BinaryOperator::CreateAnd(Op1, B);
2521e8d8bef9SDimitry Andric 
25220b57cec5SDimitry Andric     // (A ^ B) & ((B ^ C) ^ A) -> (A ^ B) & ~C
25235f757f3fSDimitry Andric     if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
25245f757f3fSDimitry Andric         match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A)))) {
25255f757f3fSDimitry Andric       Value *NotC = Op1->hasOneUse()
25265f757f3fSDimitry Andric                         ? Builder.CreateNot(C)
25275f757f3fSDimitry Andric                         : getFreelyInverted(C, C->hasOneUse(), &Builder);
25285f757f3fSDimitry Andric       if (NotC != nullptr)
25295f757f3fSDimitry Andric         return BinaryOperator::CreateAnd(Op0, NotC);
25305f757f3fSDimitry Andric     }
25310b57cec5SDimitry Andric 
25320b57cec5SDimitry Andric     // ((A ^ C) ^ B) & (B ^ A) -> (B ^ A) & ~C
25335f757f3fSDimitry Andric     if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))) &&
25345f757f3fSDimitry Andric         match(Op1, m_Xor(m_Specific(B), m_Specific(A)))) {
25355f757f3fSDimitry Andric       Value *NotC = Op0->hasOneUse()
25365f757f3fSDimitry Andric                         ? Builder.CreateNot(C)
25375f757f3fSDimitry Andric                         : getFreelyInverted(C, C->hasOneUse(), &Builder);
25385f757f3fSDimitry Andric       if (NotC != nullptr)
25390b57cec5SDimitry Andric         return BinaryOperator::CreateAnd(Op1, Builder.CreateNot(C));
25405f757f3fSDimitry Andric     }
25410b57cec5SDimitry Andric 
254204eeddc0SDimitry Andric     // (A | B) & (~A ^ B) -> A & B
254304eeddc0SDimitry Andric     // (A | B) & (B ^ ~A) -> A & B
254404eeddc0SDimitry Andric     // (B | A) & (~A ^ B) -> A & B
254504eeddc0SDimitry Andric     // (B | A) & (B ^ ~A) -> A & B
25460b57cec5SDimitry Andric     if (match(Op1, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
25470b57cec5SDimitry Andric         match(Op0, m_c_Or(m_Specific(A), m_Specific(B))))
25480b57cec5SDimitry Andric       return BinaryOperator::CreateAnd(A, B);
25490b57cec5SDimitry Andric 
255004eeddc0SDimitry Andric     // (~A ^ B) & (A | B) -> A & B
255104eeddc0SDimitry Andric     // (~A ^ B) & (B | A) -> A & B
255204eeddc0SDimitry Andric     // (B ^ ~A) & (A | B) -> A & B
255304eeddc0SDimitry Andric     // (B ^ ~A) & (B | A) -> A & B
25540b57cec5SDimitry Andric     if (match(Op0, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
25550b57cec5SDimitry Andric         match(Op1, m_c_Or(m_Specific(A), m_Specific(B))))
25560b57cec5SDimitry Andric       return BinaryOperator::CreateAnd(A, B);
255704eeddc0SDimitry Andric 
255804eeddc0SDimitry Andric     // (~A | B) & (A ^ B) -> ~A & B
255904eeddc0SDimitry Andric     // (~A | B) & (B ^ A) -> ~A & B
256004eeddc0SDimitry Andric     // (B | ~A) & (A ^ B) -> ~A & B
256104eeddc0SDimitry Andric     // (B | ~A) & (B ^ A) -> ~A & B
256204eeddc0SDimitry Andric     if (match(Op0, m_c_Or(m_Not(m_Value(A)), m_Value(B))) &&
256304eeddc0SDimitry Andric         match(Op1, m_c_Xor(m_Specific(A), m_Specific(B))))
256404eeddc0SDimitry Andric       return BinaryOperator::CreateAnd(Builder.CreateNot(A), B);
256504eeddc0SDimitry Andric 
256604eeddc0SDimitry Andric     // (A ^ B) & (~A | B) -> ~A & B
256704eeddc0SDimitry Andric     // (B ^ A) & (~A | B) -> ~A & B
256804eeddc0SDimitry Andric     // (A ^ B) & (B | ~A) -> ~A & B
256904eeddc0SDimitry Andric     // (B ^ A) & (B | ~A) -> ~A & B
257004eeddc0SDimitry Andric     if (match(Op1, m_c_Or(m_Not(m_Value(A)), m_Value(B))) &&
257104eeddc0SDimitry Andric         match(Op0, m_c_Xor(m_Specific(A), m_Specific(B))))
257204eeddc0SDimitry Andric       return BinaryOperator::CreateAnd(Builder.CreateNot(A), B);
25730b57cec5SDimitry Andric   }
25740b57cec5SDimitry Andric 
25750b57cec5SDimitry Andric   {
25760b57cec5SDimitry Andric     ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
25770b57cec5SDimitry Andric     ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
25780b57cec5SDimitry Andric     if (LHS && RHS)
257981ad6265SDimitry Andric       if (Value *Res = foldAndOrOfICmps(LHS, RHS, I, /* IsAnd */ true))
25800b57cec5SDimitry Andric         return replaceInstUsesWith(I, Res);
25810b57cec5SDimitry Andric 
25820b57cec5SDimitry Andric     // TODO: Make this recursive; it's a little tricky because an arbitrary
25830b57cec5SDimitry Andric     // number of 'and' instructions might have to be created.
258481ad6265SDimitry Andric     if (LHS && match(Op1, m_OneUse(m_LogicalAnd(m_Value(X), m_Value(Y))))) {
258581ad6265SDimitry Andric       bool IsLogical = isa<SelectInst>(Op1);
258681ad6265SDimitry Andric       // LHS & (X && Y) --> (LHS && X) && Y
25870b57cec5SDimitry Andric       if (auto *Cmp = dyn_cast<ICmpInst>(X))
258881ad6265SDimitry Andric         if (Value *Res =
258981ad6265SDimitry Andric                 foldAndOrOfICmps(LHS, Cmp, I, /* IsAnd */ true, IsLogical))
259081ad6265SDimitry Andric           return replaceInstUsesWith(I, IsLogical
259181ad6265SDimitry Andric                                             ? Builder.CreateLogicalAnd(Res, Y)
259281ad6265SDimitry Andric                                             : Builder.CreateAnd(Res, Y));
259381ad6265SDimitry Andric       // LHS & (X && Y) --> X && (LHS & Y)
25940b57cec5SDimitry Andric       if (auto *Cmp = dyn_cast<ICmpInst>(Y))
259581ad6265SDimitry Andric         if (Value *Res = foldAndOrOfICmps(LHS, Cmp, I, /* IsAnd */ true,
259681ad6265SDimitry Andric                                           /* IsLogical */ false))
259781ad6265SDimitry Andric           return replaceInstUsesWith(I, IsLogical
259881ad6265SDimitry Andric                                             ? Builder.CreateLogicalAnd(X, Res)
259981ad6265SDimitry Andric                                             : Builder.CreateAnd(X, Res));
26000b57cec5SDimitry Andric     }
260181ad6265SDimitry Andric     if (RHS && match(Op0, m_OneUse(m_LogicalAnd(m_Value(X), m_Value(Y))))) {
260281ad6265SDimitry Andric       bool IsLogical = isa<SelectInst>(Op0);
260381ad6265SDimitry Andric       // (X && Y) & RHS --> (X && RHS) && Y
26040b57cec5SDimitry Andric       if (auto *Cmp = dyn_cast<ICmpInst>(X))
260581ad6265SDimitry Andric         if (Value *Res =
260681ad6265SDimitry Andric                 foldAndOrOfICmps(Cmp, RHS, I, /* IsAnd */ true, IsLogical))
260781ad6265SDimitry Andric           return replaceInstUsesWith(I, IsLogical
260881ad6265SDimitry Andric                                             ? Builder.CreateLogicalAnd(Res, Y)
260981ad6265SDimitry Andric                                             : Builder.CreateAnd(Res, Y));
261081ad6265SDimitry Andric       // (X && Y) & RHS --> X && (Y & RHS)
26110b57cec5SDimitry Andric       if (auto *Cmp = dyn_cast<ICmpInst>(Y))
261281ad6265SDimitry Andric         if (Value *Res = foldAndOrOfICmps(Cmp, RHS, I, /* IsAnd */ true,
261381ad6265SDimitry Andric                                           /* IsLogical */ false))
261481ad6265SDimitry Andric           return replaceInstUsesWith(I, IsLogical
261581ad6265SDimitry Andric                                             ? Builder.CreateLogicalAnd(X, Res)
261681ad6265SDimitry Andric                                             : Builder.CreateAnd(X, Res));
26170b57cec5SDimitry Andric     }
26180b57cec5SDimitry Andric   }
26190b57cec5SDimitry Andric 
26200b57cec5SDimitry Andric   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
26210b57cec5SDimitry Andric     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
262281ad6265SDimitry Andric       if (Value *Res = foldLogicOfFCmps(LHS, RHS, /*IsAnd*/ true))
26230b57cec5SDimitry Andric         return replaceInstUsesWith(I, Res);
26240b57cec5SDimitry Andric 
26250b57cec5SDimitry Andric   if (Instruction *FoldedFCmps = reassociateFCmps(I, Builder))
26260b57cec5SDimitry Andric     return FoldedFCmps;
26270b57cec5SDimitry Andric 
26280b57cec5SDimitry Andric   if (Instruction *CastedAnd = foldCastedBitwiseLogic(I))
26290b57cec5SDimitry Andric     return CastedAnd;
26300b57cec5SDimitry Andric 
26314824e7fdSDimitry Andric   if (Instruction *Sel = foldBinopOfSextBoolToSelect(I))
26324824e7fdSDimitry Andric     return Sel;
26334824e7fdSDimitry Andric 
26340b57cec5SDimitry Andric   // and(sext(A), B) / and(B, sext(A)) --> A ? B : 0, where A is i1 or <N x i1>.
26354824e7fdSDimitry Andric   // TODO: Move this into foldBinopOfSextBoolToSelect as a more generalized fold
26364824e7fdSDimitry Andric   //       with binop identity constant. But creating a select with non-constant
26374824e7fdSDimitry Andric   //       arm may not be reversible due to poison semantics. Is that a good
26384824e7fdSDimitry Andric   //       canonicalization?
26395f757f3fSDimitry Andric   Value *A, *B;
26405f757f3fSDimitry Andric   if (match(&I, m_c_And(m_OneUse(m_SExt(m_Value(A))), m_Value(B))) &&
26410b57cec5SDimitry Andric       A->getType()->isIntOrIntVectorTy(1))
26425f757f3fSDimitry Andric     return SelectInst::Create(A, B, Constant::getNullValue(Ty));
26430b57cec5SDimitry Andric 
2644bdd1243dSDimitry Andric   // Similarly, a 'not' of the bool translates to a swap of the select arms:
26455f757f3fSDimitry Andric   // ~sext(A) & B / B & ~sext(A) --> A ? 0 : B
26465f757f3fSDimitry Andric   if (match(&I, m_c_And(m_Not(m_SExt(m_Value(A))), m_Value(B))) &&
2647bdd1243dSDimitry Andric       A->getType()->isIntOrIntVectorTy(1))
26485f757f3fSDimitry Andric     return SelectInst::Create(A, Constant::getNullValue(Ty), B);
26495f757f3fSDimitry Andric 
26505f757f3fSDimitry Andric   // and(zext(A), B) -> A ? (B & 1) : 0
26515f757f3fSDimitry Andric   if (match(&I, m_c_And(m_OneUse(m_ZExt(m_Value(A))), m_Value(B))) &&
2652bdd1243dSDimitry Andric       A->getType()->isIntOrIntVectorTy(1))
26535f757f3fSDimitry Andric     return SelectInst::Create(A, Builder.CreateAnd(B, ConstantInt::get(Ty, 1)),
26545f757f3fSDimitry Andric                               Constant::getNullValue(Ty));
26555f757f3fSDimitry Andric 
26565f757f3fSDimitry Andric   // (-1 + A) & B --> A ? 0 : B where A is 0/1.
26575f757f3fSDimitry Andric   if (match(&I, m_c_And(m_OneUse(m_Add(m_ZExtOrSelf(m_Value(A)), m_AllOnes())),
26585f757f3fSDimitry Andric                         m_Value(B)))) {
26595f757f3fSDimitry Andric     if (A->getType()->isIntOrIntVectorTy(1))
26605f757f3fSDimitry Andric       return SelectInst::Create(A, Constant::getNullValue(Ty), B);
26615f757f3fSDimitry Andric     if (computeKnownBits(A, /* Depth */ 0, &I).countMaxActiveBits() <= 1) {
26625f757f3fSDimitry Andric       return SelectInst::Create(
26635f757f3fSDimitry Andric           Builder.CreateICmpEQ(A, Constant::getNullValue(A->getType())), B,
26645f757f3fSDimitry Andric           Constant::getNullValue(Ty));
26655f757f3fSDimitry Andric     }
26665f757f3fSDimitry Andric   }
2667bdd1243dSDimitry Andric 
2668bdd1243dSDimitry Andric   // (iN X s>> (N-1)) & Y --> (X s< 0) ? Y : 0 -- with optional sext
2669bdd1243dSDimitry Andric   if (match(&I, m_c_And(m_OneUse(m_SExtOrSelf(
2670bdd1243dSDimitry Andric                             m_AShr(m_Value(X), m_APIntAllowUndef(C)))),
2671bdd1243dSDimitry Andric                         m_Value(Y))) &&
2672bdd1243dSDimitry Andric       *C == X->getType()->getScalarSizeInBits() - 1) {
267381ad6265SDimitry Andric     Value *IsNeg = Builder.CreateIsNeg(X, "isneg");
267481ad6265SDimitry Andric     return SelectInst::Create(IsNeg, Y, ConstantInt::getNullValue(Ty));
26758bcb0991SDimitry Andric   }
26760eae32dcSDimitry Andric   // If there's a 'not' of the shifted value, swap the select operands:
2677bdd1243dSDimitry Andric   // ~(iN X s>> (N-1)) & Y --> (X s< 0) ? 0 : Y -- with optional sext
2678bdd1243dSDimitry Andric   if (match(&I, m_c_And(m_OneUse(m_SExtOrSelf(
2679bdd1243dSDimitry Andric                             m_Not(m_AShr(m_Value(X), m_APIntAllowUndef(C))))),
2680bdd1243dSDimitry Andric                         m_Value(Y))) &&
2681bdd1243dSDimitry Andric       *C == X->getType()->getScalarSizeInBits() - 1) {
268281ad6265SDimitry Andric     Value *IsNeg = Builder.CreateIsNeg(X, "isneg");
268381ad6265SDimitry Andric     return SelectInst::Create(IsNeg, ConstantInt::getNullValue(Ty), Y);
26840eae32dcSDimitry Andric   }
2685e8d8bef9SDimitry Andric 
2686e8d8bef9SDimitry Andric   // (~x) & y  -->  ~(x | (~y))  iff that gets rid of inversions
2687bdd1243dSDimitry Andric   if (sinkNotIntoOtherHandOfLogicalOp(I))
2688e8d8bef9SDimitry Andric     return &I;
26898bcb0991SDimitry Andric 
2690fe6060f1SDimitry Andric   // An and recurrence w/loop invariant step is equivelent to (and start, step)
2691fe6060f1SDimitry Andric   PHINode *PN = nullptr;
2692fe6060f1SDimitry Andric   Value *Start = nullptr, *Step = nullptr;
2693fe6060f1SDimitry Andric   if (matchSimpleRecurrence(&I, PN, Start, Step) && DT.dominates(Step, PN))
2694fe6060f1SDimitry Andric     return replaceInstUsesWith(I, Builder.CreateAnd(Start, Step));
2695fe6060f1SDimitry Andric 
2696bdd1243dSDimitry Andric   if (Instruction *R = reassociateForUses(I, Builder))
2697bdd1243dSDimitry Andric     return R;
2698bdd1243dSDimitry Andric 
2699bdd1243dSDimitry Andric   if (Instruction *Canonicalized = canonicalizeLogicFirst(I, Builder))
2700bdd1243dSDimitry Andric     return Canonicalized;
2701bdd1243dSDimitry Andric 
2702bdd1243dSDimitry Andric   if (Instruction *Folded = foldLogicOfIsFPClass(I, Op0, Op1))
2703bdd1243dSDimitry Andric     return Folded;
2704bdd1243dSDimitry Andric 
270506c3fb27SDimitry Andric   if (Instruction *Res = foldBinOpOfDisplacedShifts(I))
270606c3fb27SDimitry Andric     return Res;
270706c3fb27SDimitry Andric 
2708297eecfbSDimitry Andric   if (Instruction *Res = foldBitwiseLogicWithIntrinsics(I, Builder))
2709297eecfbSDimitry Andric     return Res;
2710297eecfbSDimitry Andric 
27110b57cec5SDimitry Andric   return nullptr;
27120b57cec5SDimitry Andric }
27130b57cec5SDimitry Andric 
matchBSwapOrBitReverse(Instruction & I,bool MatchBSwaps,bool MatchBitReversals)2714fe6060f1SDimitry Andric Instruction *InstCombinerImpl::matchBSwapOrBitReverse(Instruction &I,
2715e8d8bef9SDimitry Andric                                                       bool MatchBSwaps,
2716e8d8bef9SDimitry Andric                                                       bool MatchBitReversals) {
27170b57cec5SDimitry Andric   SmallVector<Instruction *, 4> Insts;
2718fe6060f1SDimitry Andric   if (!recognizeBSwapOrBitReverseIdiom(&I, MatchBSwaps, MatchBitReversals,
2719e8d8bef9SDimitry Andric                                        Insts))
27200b57cec5SDimitry Andric     return nullptr;
27210b57cec5SDimitry Andric   Instruction *LastInst = Insts.pop_back_val();
27220b57cec5SDimitry Andric   LastInst->removeFromParent();
27230b57cec5SDimitry Andric 
27240b57cec5SDimitry Andric   for (auto *Inst : Insts)
27255ffd83dbSDimitry Andric     Worklist.push(Inst);
27260b57cec5SDimitry Andric   return LastInst;
27270b57cec5SDimitry Andric }
27280b57cec5SDimitry Andric 
2729e8d8bef9SDimitry Andric /// Match UB-safe variants of the funnel shift intrinsic.
matchFunnelShift(Instruction & Or,InstCombinerImpl & IC,const DominatorTree & DT)27305f757f3fSDimitry Andric static Instruction *matchFunnelShift(Instruction &Or, InstCombinerImpl &IC,
27315f757f3fSDimitry Andric                                      const DominatorTree &DT) {
27320b57cec5SDimitry Andric   // TODO: Can we reduce the code duplication between this and the related
27330b57cec5SDimitry Andric   // rotate matching code under visitSelect and visitTrunc?
27340b57cec5SDimitry Andric   unsigned Width = Or.getType()->getScalarSizeInBits();
27350b57cec5SDimitry Andric 
27365f757f3fSDimitry Andric   Instruction *Or0, *Or1;
27375f757f3fSDimitry Andric   if (!match(Or.getOperand(0), m_Instruction(Or0)) ||
27385f757f3fSDimitry Andric       !match(Or.getOperand(1), m_Instruction(Or1)))
27390b57cec5SDimitry Andric     return nullptr;
27400b57cec5SDimitry Andric 
27415f757f3fSDimitry Andric   bool IsFshl = true; // Sub on LSHR.
27425f757f3fSDimitry Andric   SmallVector<Value *, 3> FShiftArgs;
27435f757f3fSDimitry Andric 
27445f757f3fSDimitry Andric   // First, find an or'd pair of opposite shifts:
27455f757f3fSDimitry Andric   // or (lshr ShVal0, ShAmt0), (shl ShVal1, ShAmt1)
27465f757f3fSDimitry Andric   if (isa<BinaryOperator>(Or0) && isa<BinaryOperator>(Or1)) {
2747e8d8bef9SDimitry Andric     Value *ShVal0, *ShVal1, *ShAmt0, *ShAmt1;
27485f757f3fSDimitry Andric     if (!match(Or0,
27495f757f3fSDimitry Andric                m_OneUse(m_LogicalShift(m_Value(ShVal0), m_Value(ShAmt0)))) ||
27505f757f3fSDimitry Andric         !match(Or1,
27515f757f3fSDimitry Andric                m_OneUse(m_LogicalShift(m_Value(ShVal1), m_Value(ShAmt1)))) ||
2752e8d8bef9SDimitry Andric         Or0->getOpcode() == Or1->getOpcode())
27530b57cec5SDimitry Andric       return nullptr;
27540b57cec5SDimitry Andric 
2755e8d8bef9SDimitry Andric     // Canonicalize to or(shl(ShVal0, ShAmt0), lshr(ShVal1, ShAmt1)).
2756e8d8bef9SDimitry Andric     if (Or0->getOpcode() == BinaryOperator::LShr) {
2757e8d8bef9SDimitry Andric       std::swap(Or0, Or1);
2758e8d8bef9SDimitry Andric       std::swap(ShVal0, ShVal1);
2759e8d8bef9SDimitry Andric       std::swap(ShAmt0, ShAmt1);
2760e8d8bef9SDimitry Andric     }
2761e8d8bef9SDimitry Andric     assert(Or0->getOpcode() == BinaryOperator::Shl &&
2762e8d8bef9SDimitry Andric            Or1->getOpcode() == BinaryOperator::LShr &&
2763e8d8bef9SDimitry Andric            "Illegal or(shift,shift) pair");
2764e8d8bef9SDimitry Andric 
2765e8d8bef9SDimitry Andric     // Match the shift amount operands for a funnel shift pattern. This always
2766e8d8bef9SDimitry Andric     // matches a subtraction on the R operand.
2767e8d8bef9SDimitry Andric     auto matchShiftAmount = [&](Value *L, Value *R, unsigned Width) -> Value * {
2768e8d8bef9SDimitry Andric       // Check for constant shift amounts that sum to the bitwidth.
2769e8d8bef9SDimitry Andric       const APInt *LI, *RI;
2770e8d8bef9SDimitry Andric       if (match(L, m_APIntAllowUndef(LI)) && match(R, m_APIntAllowUndef(RI)))
2771e8d8bef9SDimitry Andric         if (LI->ult(Width) && RI->ult(Width) && (*LI + *RI) == Width)
2772e8d8bef9SDimitry Andric           return ConstantInt::get(L->getType(), *LI);
2773e8d8bef9SDimitry Andric 
2774e8d8bef9SDimitry Andric       Constant *LC, *RC;
2775e8d8bef9SDimitry Andric       if (match(L, m_Constant(LC)) && match(R, m_Constant(RC)) &&
27765f757f3fSDimitry Andric           match(L,
27775f757f3fSDimitry Andric                 m_SpecificInt_ICMP(ICmpInst::ICMP_ULT, APInt(Width, Width))) &&
27785f757f3fSDimitry Andric           match(R,
27795f757f3fSDimitry Andric                 m_SpecificInt_ICMP(ICmpInst::ICMP_ULT, APInt(Width, Width))) &&
2780e8d8bef9SDimitry Andric           match(ConstantExpr::getAdd(LC, RC), m_SpecificIntAllowUndef(Width)))
2781e8d8bef9SDimitry Andric         return ConstantExpr::mergeUndefsWith(LC, RC);
2782e8d8bef9SDimitry Andric 
2783e8d8bef9SDimitry Andric       // (shl ShVal, X) | (lshr ShVal, (Width - x)) iff X < Width.
27845f757f3fSDimitry Andric       // We limit this to X < Width in case the backend re-expands the
27855f757f3fSDimitry Andric       // intrinsic, and has to reintroduce a shift modulo operation (InstCombine
27865f757f3fSDimitry Andric       // might remove it after this fold). This still doesn't guarantee that the
27875f757f3fSDimitry Andric       // final codegen will match this original pattern.
2788e8d8bef9SDimitry Andric       if (match(R, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(L))))) {
2789e8d8bef9SDimitry Andric         KnownBits KnownL = IC.computeKnownBits(L, /*Depth*/ 0, &Or);
2790e8d8bef9SDimitry Andric         return KnownL.getMaxValue().ult(Width) ? L : nullptr;
2791e8d8bef9SDimitry Andric       }
2792e8d8bef9SDimitry Andric 
2793e8d8bef9SDimitry Andric       // For non-constant cases, the following patterns currently only work for
2794e8d8bef9SDimitry Andric       // rotation patterns.
2795e8d8bef9SDimitry Andric       // TODO: Add general funnel-shift compatible patterns.
2796e8d8bef9SDimitry Andric       if (ShVal0 != ShVal1)
27970b57cec5SDimitry Andric         return nullptr;
27980b57cec5SDimitry Andric 
2799e8d8bef9SDimitry Andric       // For non-constant cases we don't support non-pow2 shift masks.
2800e8d8bef9SDimitry Andric       // TODO: Is it worth matching urem as well?
2801e8d8bef9SDimitry Andric       if (!isPowerOf2_32(Width))
2802e8d8bef9SDimitry Andric         return nullptr;
2803e8d8bef9SDimitry Andric 
28040b57cec5SDimitry Andric       // The shift amount may be masked with negation:
28050b57cec5SDimitry Andric       // (shl ShVal, (X & (Width - 1))) | (lshr ShVal, ((-X) & (Width - 1)))
28060b57cec5SDimitry Andric       Value *X;
28070b57cec5SDimitry Andric       unsigned Mask = Width - 1;
28080b57cec5SDimitry Andric       if (match(L, m_And(m_Value(X), m_SpecificInt(Mask))) &&
28090b57cec5SDimitry Andric           match(R, m_And(m_Neg(m_Specific(X)), m_SpecificInt(Mask))))
28100b57cec5SDimitry Andric         return X;
28110b57cec5SDimitry Andric 
28127a6dacacSDimitry Andric       // (shl ShVal, X) | (lshr ShVal, ((-X) & (Width - 1)))
28137a6dacacSDimitry Andric       if (match(R, m_And(m_Neg(m_Specific(L)), m_SpecificInt(Mask))))
28147a6dacacSDimitry Andric         return L;
28157a6dacacSDimitry Andric 
28160b57cec5SDimitry Andric       // Similar to above, but the shift amount may be extended after masking,
28170b57cec5SDimitry Andric       // so return the extended value as the parameter for the intrinsic.
28180b57cec5SDimitry Andric       if (match(L, m_ZExt(m_And(m_Value(X), m_SpecificInt(Mask)))) &&
28195f757f3fSDimitry Andric           match(R,
28205f757f3fSDimitry Andric                 m_And(m_Neg(m_ZExt(m_And(m_Specific(X), m_SpecificInt(Mask)))),
28210b57cec5SDimitry Andric                       m_SpecificInt(Mask))))
28220b57cec5SDimitry Andric         return L;
28230b57cec5SDimitry Andric 
2824e8d8bef9SDimitry Andric       if (match(L, m_ZExt(m_And(m_Value(X), m_SpecificInt(Mask)))) &&
2825e8d8bef9SDimitry Andric           match(R, m_ZExt(m_And(m_Neg(m_Specific(X)), m_SpecificInt(Mask)))))
2826e8d8bef9SDimitry Andric         return L;
2827e8d8bef9SDimitry Andric 
28280b57cec5SDimitry Andric       return nullptr;
28290b57cec5SDimitry Andric     };
28300b57cec5SDimitry Andric 
28310b57cec5SDimitry Andric     Value *ShAmt = matchShiftAmount(ShAmt0, ShAmt1, Width);
28320b57cec5SDimitry Andric     if (!ShAmt) {
28330b57cec5SDimitry Andric       ShAmt = matchShiftAmount(ShAmt1, ShAmt0, Width);
2834e8d8bef9SDimitry Andric       IsFshl = false; // Sub on SHL.
28350b57cec5SDimitry Andric     }
28360b57cec5SDimitry Andric     if (!ShAmt)
28370b57cec5SDimitry Andric       return nullptr;
28380b57cec5SDimitry Andric 
28395f757f3fSDimitry Andric     FShiftArgs = {ShVal0, ShVal1, ShAmt};
28405f757f3fSDimitry Andric   } else if (isa<ZExtInst>(Or0) || isa<ZExtInst>(Or1)) {
28415f757f3fSDimitry Andric     // If there are two 'or' instructions concat variables in opposite order:
28425f757f3fSDimitry Andric     //
28435f757f3fSDimitry Andric     // Slot1 and Slot2 are all zero bits.
28445f757f3fSDimitry Andric     // | Slot1 | Low | Slot2 | High |
28455f757f3fSDimitry Andric     // LowHigh = or (shl (zext Low), ZextLowShlAmt), (zext High)
28465f757f3fSDimitry Andric     // | Slot2 | High | Slot1 | Low |
28475f757f3fSDimitry Andric     // HighLow = or (shl (zext High), ZextHighShlAmt), (zext Low)
28485f757f3fSDimitry Andric     //
28495f757f3fSDimitry Andric     // the latter 'or' can be safely convert to
28505f757f3fSDimitry Andric     // -> HighLow = fshl LowHigh, LowHigh, ZextHighShlAmt
28515f757f3fSDimitry Andric     // if ZextLowShlAmt + ZextHighShlAmt == Width.
28525f757f3fSDimitry Andric     if (!isa<ZExtInst>(Or1))
28535f757f3fSDimitry Andric       std::swap(Or0, Or1);
28545f757f3fSDimitry Andric 
28555f757f3fSDimitry Andric     Value *High, *ZextHigh, *Low;
28565f757f3fSDimitry Andric     const APInt *ZextHighShlAmt;
28575f757f3fSDimitry Andric     if (!match(Or0,
28585f757f3fSDimitry Andric                m_OneUse(m_Shl(m_Value(ZextHigh), m_APInt(ZextHighShlAmt)))))
28595f757f3fSDimitry Andric       return nullptr;
28605f757f3fSDimitry Andric 
28615f757f3fSDimitry Andric     if (!match(Or1, m_ZExt(m_Value(Low))) ||
28625f757f3fSDimitry Andric         !match(ZextHigh, m_ZExt(m_Value(High))))
28635f757f3fSDimitry Andric       return nullptr;
28645f757f3fSDimitry Andric 
28655f757f3fSDimitry Andric     unsigned HighSize = High->getType()->getScalarSizeInBits();
28665f757f3fSDimitry Andric     unsigned LowSize = Low->getType()->getScalarSizeInBits();
28675f757f3fSDimitry Andric     // Make sure High does not overlap with Low and most significant bits of
28685f757f3fSDimitry Andric     // High aren't shifted out.
28695f757f3fSDimitry Andric     if (ZextHighShlAmt->ult(LowSize) || ZextHighShlAmt->ugt(Width - HighSize))
28705f757f3fSDimitry Andric       return nullptr;
28715f757f3fSDimitry Andric 
28725f757f3fSDimitry Andric     for (User *U : ZextHigh->users()) {
28735f757f3fSDimitry Andric       Value *X, *Y;
28745f757f3fSDimitry Andric       if (!match(U, m_Or(m_Value(X), m_Value(Y))))
28755f757f3fSDimitry Andric         continue;
28765f757f3fSDimitry Andric 
28775f757f3fSDimitry Andric       if (!isa<ZExtInst>(Y))
28785f757f3fSDimitry Andric         std::swap(X, Y);
28795f757f3fSDimitry Andric 
28805f757f3fSDimitry Andric       const APInt *ZextLowShlAmt;
28815f757f3fSDimitry Andric       if (!match(X, m_Shl(m_Specific(Or1), m_APInt(ZextLowShlAmt))) ||
28825f757f3fSDimitry Andric           !match(Y, m_Specific(ZextHigh)) || !DT.dominates(U, &Or))
28835f757f3fSDimitry Andric         continue;
28845f757f3fSDimitry Andric 
28855f757f3fSDimitry Andric       // HighLow is good concat. If sum of two shifts amount equals to Width,
28865f757f3fSDimitry Andric       // LowHigh must also be a good concat.
28875f757f3fSDimitry Andric       if (*ZextLowShlAmt + *ZextHighShlAmt != Width)
28885f757f3fSDimitry Andric         continue;
28895f757f3fSDimitry Andric 
28905f757f3fSDimitry Andric       // Low must not overlap with High and most significant bits of Low must
28915f757f3fSDimitry Andric       // not be shifted out.
28925f757f3fSDimitry Andric       assert(ZextLowShlAmt->uge(HighSize) &&
28935f757f3fSDimitry Andric              ZextLowShlAmt->ule(Width - LowSize) && "Invalid concat");
28945f757f3fSDimitry Andric 
28955f757f3fSDimitry Andric       FShiftArgs = {U, U, ConstantInt::get(Or0->getType(), *ZextHighShlAmt)};
28965f757f3fSDimitry Andric       break;
28975f757f3fSDimitry Andric     }
28985f757f3fSDimitry Andric   }
28995f757f3fSDimitry Andric 
29005f757f3fSDimitry Andric   if (FShiftArgs.empty())
29015f757f3fSDimitry Andric     return nullptr;
29025f757f3fSDimitry Andric 
29030b57cec5SDimitry Andric   Intrinsic::ID IID = IsFshl ? Intrinsic::fshl : Intrinsic::fshr;
29040b57cec5SDimitry Andric   Function *F = Intrinsic::getDeclaration(Or.getModule(), IID, Or.getType());
29055f757f3fSDimitry Andric   return CallInst::Create(F, FShiftArgs);
29060b57cec5SDimitry Andric }
29070b57cec5SDimitry Andric 
29085ffd83dbSDimitry Andric /// Attempt to combine or(zext(x),shl(zext(y),bw/2) concat packing patterns.
matchOrConcat(Instruction & Or,InstCombiner::BuilderTy & Builder)29095ffd83dbSDimitry Andric static Instruction *matchOrConcat(Instruction &Or,
29105ffd83dbSDimitry Andric                                   InstCombiner::BuilderTy &Builder) {
29115ffd83dbSDimitry Andric   assert(Or.getOpcode() == Instruction::Or && "bswap requires an 'or'");
29125ffd83dbSDimitry Andric   Value *Op0 = Or.getOperand(0), *Op1 = Or.getOperand(1);
29135ffd83dbSDimitry Andric   Type *Ty = Or.getType();
29145ffd83dbSDimitry Andric 
29155ffd83dbSDimitry Andric   unsigned Width = Ty->getScalarSizeInBits();
29165ffd83dbSDimitry Andric   if ((Width & 1) != 0)
29175ffd83dbSDimitry Andric     return nullptr;
29185ffd83dbSDimitry Andric   unsigned HalfWidth = Width / 2;
29195ffd83dbSDimitry Andric 
29205ffd83dbSDimitry Andric   // Canonicalize zext (lower half) to LHS.
29215ffd83dbSDimitry Andric   if (!isa<ZExtInst>(Op0))
29225ffd83dbSDimitry Andric     std::swap(Op0, Op1);
29235ffd83dbSDimitry Andric 
29245ffd83dbSDimitry Andric   // Find lower/upper half.
29255ffd83dbSDimitry Andric   Value *LowerSrc, *ShlVal, *UpperSrc;
29265ffd83dbSDimitry Andric   const APInt *C;
29275ffd83dbSDimitry Andric   if (!match(Op0, m_OneUse(m_ZExt(m_Value(LowerSrc)))) ||
29285ffd83dbSDimitry Andric       !match(Op1, m_OneUse(m_Shl(m_Value(ShlVal), m_APInt(C)))) ||
29295ffd83dbSDimitry Andric       !match(ShlVal, m_OneUse(m_ZExt(m_Value(UpperSrc)))))
29305ffd83dbSDimitry Andric     return nullptr;
29315ffd83dbSDimitry Andric   if (*C != HalfWidth || LowerSrc->getType() != UpperSrc->getType() ||
29325ffd83dbSDimitry Andric       LowerSrc->getType()->getScalarSizeInBits() != HalfWidth)
29335ffd83dbSDimitry Andric     return nullptr;
29345ffd83dbSDimitry Andric 
29355ffd83dbSDimitry Andric   auto ConcatIntrinsicCalls = [&](Intrinsic::ID id, Value *Lo, Value *Hi) {
29365ffd83dbSDimitry Andric     Value *NewLower = Builder.CreateZExt(Lo, Ty);
29375ffd83dbSDimitry Andric     Value *NewUpper = Builder.CreateZExt(Hi, Ty);
29385ffd83dbSDimitry Andric     NewUpper = Builder.CreateShl(NewUpper, HalfWidth);
29395ffd83dbSDimitry Andric     Value *BinOp = Builder.CreateOr(NewLower, NewUpper);
29405ffd83dbSDimitry Andric     Function *F = Intrinsic::getDeclaration(Or.getModule(), id, Ty);
29415ffd83dbSDimitry Andric     return Builder.CreateCall(F, BinOp);
29425ffd83dbSDimitry Andric   };
29435ffd83dbSDimitry Andric 
29445ffd83dbSDimitry Andric   // BSWAP: Push the concat down, swapping the lower/upper sources.
29455ffd83dbSDimitry Andric   // concat(bswap(x),bswap(y)) -> bswap(concat(x,y))
29465ffd83dbSDimitry Andric   Value *LowerBSwap, *UpperBSwap;
29475ffd83dbSDimitry Andric   if (match(LowerSrc, m_BSwap(m_Value(LowerBSwap))) &&
29485ffd83dbSDimitry Andric       match(UpperSrc, m_BSwap(m_Value(UpperBSwap))))
29495ffd83dbSDimitry Andric     return ConcatIntrinsicCalls(Intrinsic::bswap, UpperBSwap, LowerBSwap);
29505ffd83dbSDimitry Andric 
29515ffd83dbSDimitry Andric   // BITREVERSE: Push the concat down, swapping the lower/upper sources.
29525ffd83dbSDimitry Andric   // concat(bitreverse(x),bitreverse(y)) -> bitreverse(concat(x,y))
29535ffd83dbSDimitry Andric   Value *LowerBRev, *UpperBRev;
29545ffd83dbSDimitry Andric   if (match(LowerSrc, m_BitReverse(m_Value(LowerBRev))) &&
29555ffd83dbSDimitry Andric       match(UpperSrc, m_BitReverse(m_Value(UpperBRev))))
29565ffd83dbSDimitry Andric     return ConcatIntrinsicCalls(Intrinsic::bitreverse, UpperBRev, LowerBRev);
29575ffd83dbSDimitry Andric 
29585ffd83dbSDimitry Andric   return nullptr;
29595ffd83dbSDimitry Andric }
29605ffd83dbSDimitry Andric 
29610b57cec5SDimitry Andric /// If all elements of two constant vectors are 0/-1 and inverses, return true.
areInverseVectorBitmasks(Constant * C1,Constant * C2)29620b57cec5SDimitry Andric static bool areInverseVectorBitmasks(Constant *C1, Constant *C2) {
2963e8d8bef9SDimitry Andric   unsigned NumElts = cast<FixedVectorType>(C1->getType())->getNumElements();
29640b57cec5SDimitry Andric   for (unsigned i = 0; i != NumElts; ++i) {
29650b57cec5SDimitry Andric     Constant *EltC1 = C1->getAggregateElement(i);
29660b57cec5SDimitry Andric     Constant *EltC2 = C2->getAggregateElement(i);
29670b57cec5SDimitry Andric     if (!EltC1 || !EltC2)
29680b57cec5SDimitry Andric       return false;
29690b57cec5SDimitry Andric 
29700b57cec5SDimitry Andric     // One element must be all ones, and the other must be all zeros.
29710b57cec5SDimitry Andric     if (!((match(EltC1, m_Zero()) && match(EltC2, m_AllOnes())) ||
29720b57cec5SDimitry Andric           (match(EltC2, m_Zero()) && match(EltC1, m_AllOnes()))))
29730b57cec5SDimitry Andric       return false;
29740b57cec5SDimitry Andric   }
29750b57cec5SDimitry Andric   return true;
29760b57cec5SDimitry Andric }
29770b57cec5SDimitry Andric 
29780b57cec5SDimitry Andric /// We have an expression of the form (A & C) | (B & D). If A is a scalar or
29790b57cec5SDimitry Andric /// vector composed of all-zeros or all-ones values and is the bitwise 'not' of
29800b57cec5SDimitry Andric /// B, it can be used as the condition operand of a select instruction.
2981bdd1243dSDimitry Andric /// We will detect (A & C) | ~(B | D) when the flag ABIsTheSame enabled.
getSelectCondition(Value * A,Value * B,bool ABIsTheSame)2982bdd1243dSDimitry Andric Value *InstCombinerImpl::getSelectCondition(Value *A, Value *B,
2983bdd1243dSDimitry Andric                                             bool ABIsTheSame) {
2984349cc55cSDimitry Andric   // We may have peeked through bitcasts in the caller.
29850b57cec5SDimitry Andric   // Exit immediately if we don't have (vector) integer types.
29860b57cec5SDimitry Andric   Type *Ty = A->getType();
29870b57cec5SDimitry Andric   if (!Ty->isIntOrIntVectorTy() || !B->getType()->isIntOrIntVectorTy())
29880b57cec5SDimitry Andric     return nullptr;
29890b57cec5SDimitry Andric 
2990349cc55cSDimitry Andric   // If A is the 'not' operand of B and has enough signbits, we have our answer.
2991bdd1243dSDimitry Andric   if (ABIsTheSame ? (A == B) : match(B, m_Not(m_Specific(A)))) {
29920b57cec5SDimitry Andric     // If these are scalars or vectors of i1, A can be used directly.
29930b57cec5SDimitry Andric     if (Ty->isIntOrIntVectorTy(1))
29940b57cec5SDimitry Andric       return A;
2995349cc55cSDimitry Andric 
2996349cc55cSDimitry Andric     // If we look through a vector bitcast, the caller will bitcast the operands
2997349cc55cSDimitry Andric     // to match the condition's number of bits (N x i1).
2998349cc55cSDimitry Andric     // To make this poison-safe, disallow bitcast from wide element to narrow
2999349cc55cSDimitry Andric     // element. That could allow poison in lanes where it was not present in the
3000349cc55cSDimitry Andric     // original code.
3001349cc55cSDimitry Andric     A = peekThroughBitcast(A);
3002349cc55cSDimitry Andric     if (A->getType()->isIntOrIntVectorTy()) {
3003349cc55cSDimitry Andric       unsigned NumSignBits = ComputeNumSignBits(A);
3004349cc55cSDimitry Andric       if (NumSignBits == A->getType()->getScalarSizeInBits() &&
3005349cc55cSDimitry Andric           NumSignBits <= Ty->getScalarSizeInBits())
3006349cc55cSDimitry Andric         return Builder.CreateTrunc(A, CmpInst::makeCmpResultType(A->getType()));
3007349cc55cSDimitry Andric     }
3008349cc55cSDimitry Andric     return nullptr;
30090b57cec5SDimitry Andric   }
30100b57cec5SDimitry Andric 
3011bdd1243dSDimitry Andric   // TODO: add support for sext and constant case
3012bdd1243dSDimitry Andric   if (ABIsTheSame)
3013bdd1243dSDimitry Andric     return nullptr;
3014bdd1243dSDimitry Andric 
30150b57cec5SDimitry Andric   // If both operands are constants, see if the constants are inverse bitmasks.
30160b57cec5SDimitry Andric   Constant *AConst, *BConst;
30170b57cec5SDimitry Andric   if (match(A, m_Constant(AConst)) && match(B, m_Constant(BConst)))
3018349cc55cSDimitry Andric     if (AConst == ConstantExpr::getNot(BConst) &&
3019349cc55cSDimitry Andric         ComputeNumSignBits(A) == Ty->getScalarSizeInBits())
30200b57cec5SDimitry Andric       return Builder.CreateZExtOrTrunc(A, CmpInst::makeCmpResultType(Ty));
30210b57cec5SDimitry Andric 
30220b57cec5SDimitry Andric   // Look for more complex patterns. The 'not' op may be hidden behind various
30230b57cec5SDimitry Andric   // casts. Look through sexts and bitcasts to find the booleans.
30240b57cec5SDimitry Andric   Value *Cond;
30250b57cec5SDimitry Andric   Value *NotB;
30260b57cec5SDimitry Andric   if (match(A, m_SExt(m_Value(Cond))) &&
30274824e7fdSDimitry Andric       Cond->getType()->isIntOrIntVectorTy(1)) {
30284824e7fdSDimitry Andric     // A = sext i1 Cond; B = sext (not (i1 Cond))
30294824e7fdSDimitry Andric     if (match(B, m_SExt(m_Not(m_Specific(Cond)))))
30304824e7fdSDimitry Andric       return Cond;
30314824e7fdSDimitry Andric 
30324824e7fdSDimitry Andric     // A = sext i1 Cond; B = not ({bitcast} (sext (i1 Cond)))
30334824e7fdSDimitry Andric     // TODO: The one-use checks are unnecessary or misplaced. If the caller
30344824e7fdSDimitry Andric     //       checked for uses on logic ops/casts, that should be enough to
30354824e7fdSDimitry Andric     //       make this transform worthwhile.
30364824e7fdSDimitry Andric     if (match(B, m_OneUse(m_Not(m_Value(NotB))))) {
30370b57cec5SDimitry Andric       NotB = peekThroughBitcast(NotB, true);
30380b57cec5SDimitry Andric       if (match(NotB, m_SExt(m_Specific(Cond))))
30390b57cec5SDimitry Andric         return Cond;
30400b57cec5SDimitry Andric     }
30414824e7fdSDimitry Andric   }
30420b57cec5SDimitry Andric 
30430b57cec5SDimitry Andric   // All scalar (and most vector) possibilities should be handled now.
30440b57cec5SDimitry Andric   // Try more matches that only apply to non-splat constant vectors.
30450b57cec5SDimitry Andric   if (!Ty->isVectorTy())
30460b57cec5SDimitry Andric     return nullptr;
30470b57cec5SDimitry Andric 
30480b57cec5SDimitry Andric   // If both operands are xor'd with constants using the same sexted boolean
30490b57cec5SDimitry Andric   // operand, see if the constants are inverse bitmasks.
30500b57cec5SDimitry Andric   // TODO: Use ConstantExpr::getNot()?
30510b57cec5SDimitry Andric   if (match(A, (m_Xor(m_SExt(m_Value(Cond)), m_Constant(AConst)))) &&
30520b57cec5SDimitry Andric       match(B, (m_Xor(m_SExt(m_Specific(Cond)), m_Constant(BConst)))) &&
30530b57cec5SDimitry Andric       Cond->getType()->isIntOrIntVectorTy(1) &&
30540b57cec5SDimitry Andric       areInverseVectorBitmasks(AConst, BConst)) {
30550b57cec5SDimitry Andric     AConst = ConstantExpr::getTrunc(AConst, CmpInst::makeCmpResultType(Ty));
30560b57cec5SDimitry Andric     return Builder.CreateXor(Cond, AConst);
30570b57cec5SDimitry Andric   }
30580b57cec5SDimitry Andric   return nullptr;
30590b57cec5SDimitry Andric }
30600b57cec5SDimitry Andric 
30610b57cec5SDimitry Andric /// We have an expression of the form (A & C) | (B & D). Try to simplify this
30620b57cec5SDimitry Andric /// to "A' ? C : D", where A' is a boolean or vector of booleans.
3063bdd1243dSDimitry Andric /// When InvertFalseVal is set to true, we try to match the pattern
3064bdd1243dSDimitry Andric /// where we have peeked through a 'not' op and A and B are the same:
3065bdd1243dSDimitry Andric /// (A & C) | ~(A | D) --> (A & C) | (~A & ~D) --> A' ? C : ~D
matchSelectFromAndOr(Value * A,Value * C,Value * B,Value * D,bool InvertFalseVal)3066e8d8bef9SDimitry Andric Value *InstCombinerImpl::matchSelectFromAndOr(Value *A, Value *C, Value *B,
3067bdd1243dSDimitry Andric                                               Value *D, bool InvertFalseVal) {
30680b57cec5SDimitry Andric   // The potential condition of the select may be bitcasted. In that case, look
30690b57cec5SDimitry Andric   // through its bitcast and the corresponding bitcast of the 'not' condition.
30700b57cec5SDimitry Andric   Type *OrigType = A->getType();
30710b57cec5SDimitry Andric   A = peekThroughBitcast(A, true);
30720b57cec5SDimitry Andric   B = peekThroughBitcast(B, true);
3073bdd1243dSDimitry Andric   if (Value *Cond = getSelectCondition(A, B, InvertFalseVal)) {
30740b57cec5SDimitry Andric     // ((bc Cond) & C) | ((bc ~Cond) & D) --> bc (select Cond, (bc C), (bc D))
3075349cc55cSDimitry Andric     // If this is a vector, we may need to cast to match the condition's length.
30760b57cec5SDimitry Andric     // The bitcasts will either all exist or all not exist. The builder will
30770b57cec5SDimitry Andric     // not create unnecessary casts if the types already match.
3078349cc55cSDimitry Andric     Type *SelTy = A->getType();
3079349cc55cSDimitry Andric     if (auto *VecTy = dyn_cast<VectorType>(Cond->getType())) {
30802a66634dSDimitry Andric       // For a fixed or scalable vector get N from <{vscale x} N x iM>
3081349cc55cSDimitry Andric       unsigned Elts = VecTy->getElementCount().getKnownMinValue();
30822a66634dSDimitry Andric       // For a fixed or scalable vector, get the size in bits of N x iM; for a
30832a66634dSDimitry Andric       // scalar this is just M.
3084bdd1243dSDimitry Andric       unsigned SelEltSize = SelTy->getPrimitiveSizeInBits().getKnownMinValue();
30852a66634dSDimitry Andric       Type *EltTy = Builder.getIntNTy(SelEltSize / Elts);
3086349cc55cSDimitry Andric       SelTy = VectorType::get(EltTy, VecTy->getElementCount());
3087349cc55cSDimitry Andric     }
3088349cc55cSDimitry Andric     Value *BitcastC = Builder.CreateBitCast(C, SelTy);
3089bdd1243dSDimitry Andric     if (InvertFalseVal)
3090bdd1243dSDimitry Andric       D = Builder.CreateNot(D);
3091349cc55cSDimitry Andric     Value *BitcastD = Builder.CreateBitCast(D, SelTy);
30920b57cec5SDimitry Andric     Value *Select = Builder.CreateSelect(Cond, BitcastC, BitcastD);
30930b57cec5SDimitry Andric     return Builder.CreateBitCast(Select, OrigType);
30940b57cec5SDimitry Andric   }
30950b57cec5SDimitry Andric 
30960b57cec5SDimitry Andric   return nullptr;
30970b57cec5SDimitry Andric }
30980b57cec5SDimitry Andric 
309906c3fb27SDimitry Andric // (icmp eq X, C) | (icmp ult Other, (X - C)) -> (icmp ule Other, (X - (C + 1)))
310006c3fb27SDimitry Andric // (icmp ne X, C) & (icmp uge Other, (X - C)) -> (icmp ugt Other, (X - (C + 1)))
foldAndOrOfICmpEqConstantAndICmp(ICmpInst * LHS,ICmpInst * RHS,bool IsAnd,bool IsLogical,IRBuilderBase & Builder)310106c3fb27SDimitry Andric static Value *foldAndOrOfICmpEqConstantAndICmp(ICmpInst *LHS, ICmpInst *RHS,
3102bdd1243dSDimitry Andric                                                bool IsAnd, bool IsLogical,
310381ad6265SDimitry Andric                                                IRBuilderBase &Builder) {
310406c3fb27SDimitry Andric   Value *LHS0 = LHS->getOperand(0);
310506c3fb27SDimitry Andric   Value *RHS0 = RHS->getOperand(0);
310606c3fb27SDimitry Andric   Value *RHS1 = RHS->getOperand(1);
310706c3fb27SDimitry Andric 
310881ad6265SDimitry Andric   ICmpInst::Predicate LPred =
310981ad6265SDimitry Andric       IsAnd ? LHS->getInversePredicate() : LHS->getPredicate();
311081ad6265SDimitry Andric   ICmpInst::Predicate RPred =
311181ad6265SDimitry Andric       IsAnd ? RHS->getInversePredicate() : RHS->getPredicate();
311206c3fb27SDimitry Andric 
311306c3fb27SDimitry Andric   const APInt *CInt;
311406c3fb27SDimitry Andric   if (LPred != ICmpInst::ICMP_EQ ||
311506c3fb27SDimitry Andric       !match(LHS->getOperand(1), m_APIntAllowUndef(CInt)) ||
311681ad6265SDimitry Andric       !LHS0->getType()->isIntOrIntVectorTy() ||
311781ad6265SDimitry Andric       !(LHS->hasOneUse() || RHS->hasOneUse()))
311881ad6265SDimitry Andric     return nullptr;
311981ad6265SDimitry Andric 
312006c3fb27SDimitry Andric   auto MatchRHSOp = [LHS0, CInt](const Value *RHSOp) {
312106c3fb27SDimitry Andric     return match(RHSOp,
312206c3fb27SDimitry Andric                  m_Add(m_Specific(LHS0), m_SpecificIntAllowUndef(-*CInt))) ||
312306c3fb27SDimitry Andric            (CInt->isZero() && RHSOp == LHS0);
312406c3fb27SDimitry Andric   };
312506c3fb27SDimitry Andric 
312681ad6265SDimitry Andric   Value *Other;
312706c3fb27SDimitry Andric   if (RPred == ICmpInst::ICMP_ULT && MatchRHSOp(RHS1))
312806c3fb27SDimitry Andric     Other = RHS0;
312906c3fb27SDimitry Andric   else if (RPred == ICmpInst::ICMP_UGT && MatchRHSOp(RHS0))
313006c3fb27SDimitry Andric     Other = RHS1;
313181ad6265SDimitry Andric   else
313281ad6265SDimitry Andric     return nullptr;
313381ad6265SDimitry Andric 
3134bdd1243dSDimitry Andric   if (IsLogical)
3135bdd1243dSDimitry Andric     Other = Builder.CreateFreeze(Other);
313606c3fb27SDimitry Andric 
313781ad6265SDimitry Andric   return Builder.CreateICmp(
313881ad6265SDimitry Andric       IsAnd ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_UGE,
313906c3fb27SDimitry Andric       Builder.CreateSub(LHS0, ConstantInt::get(LHS0->getType(), *CInt + 1)),
314081ad6265SDimitry Andric       Other);
314181ad6265SDimitry Andric }
314281ad6265SDimitry Andric 
314381ad6265SDimitry Andric /// Fold (icmp)&(icmp) or (icmp)|(icmp) if possible.
314481ad6265SDimitry Andric /// If IsLogical is true, then the and/or is in select form and the transform
314581ad6265SDimitry Andric /// must be poison-safe.
foldAndOrOfICmps(ICmpInst * LHS,ICmpInst * RHS,Instruction & I,bool IsAnd,bool IsLogical)314681ad6265SDimitry Andric Value *InstCombinerImpl::foldAndOrOfICmps(ICmpInst *LHS, ICmpInst *RHS,
314781ad6265SDimitry Andric                                           Instruction &I, bool IsAnd,
314881ad6265SDimitry Andric                                           bool IsLogical) {
314981ad6265SDimitry Andric   const SimplifyQuery Q = SQ.getWithInstruction(&I);
31508bcb0991SDimitry Andric 
31510b57cec5SDimitry Andric   // Fold (iszero(A & K1) | iszero(A & K2)) ->  (A & (K1 | K2)) != (K1 | K2)
315281ad6265SDimitry Andric   // Fold (!iszero(A & K1) & !iszero(A & K2)) ->  (A & (K1 | K2)) == (K1 | K2)
31530b57cec5SDimitry Andric   // if K1 and K2 are a one-bit mask.
315481ad6265SDimitry Andric   if (Value *V = foldAndOrOfICmpsOfAndWithPow2(LHS, RHS, &I, IsAnd, IsLogical))
31550b57cec5SDimitry Andric     return V;
31560b57cec5SDimitry Andric 
31570b57cec5SDimitry Andric   ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
3158e8d8bef9SDimitry Andric   Value *LHS0 = LHS->getOperand(0), *RHS0 = RHS->getOperand(0);
3159e8d8bef9SDimitry Andric   Value *LHS1 = LHS->getOperand(1), *RHS1 = RHS->getOperand(1);
3160349cc55cSDimitry Andric   const APInt *LHSC = nullptr, *RHSC = nullptr;
3161349cc55cSDimitry Andric   match(LHS1, m_APInt(LHSC));
3162349cc55cSDimitry Andric   match(RHS1, m_APInt(RHSC));
31630b57cec5SDimitry Andric 
31640b57cec5SDimitry Andric   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
316581ad6265SDimitry Andric   // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
31660b57cec5SDimitry Andric   if (predicatesFoldable(PredL, PredR)) {
316781ad6265SDimitry Andric     if (LHS0 == RHS1 && LHS1 == RHS0) {
316881ad6265SDimitry Andric       PredL = ICmpInst::getSwappedPredicate(PredL);
316981ad6265SDimitry Andric       std::swap(LHS0, LHS1);
317081ad6265SDimitry Andric     }
3171e8d8bef9SDimitry Andric     if (LHS0 == RHS0 && LHS1 == RHS1) {
317281ad6265SDimitry Andric       unsigned Code = IsAnd ? getICmpCode(PredL) & getICmpCode(PredR)
317381ad6265SDimitry Andric                             : getICmpCode(PredL) | getICmpCode(PredR);
31740b57cec5SDimitry Andric       bool IsSigned = LHS->isSigned() || RHS->isSigned();
3175e8d8bef9SDimitry Andric       return getNewICmpValue(Code, IsSigned, LHS0, LHS1, Builder);
31760b57cec5SDimitry Andric     }
31770b57cec5SDimitry Andric   }
31780b57cec5SDimitry Andric 
31790b57cec5SDimitry Andric   // handle (roughly):
31800b57cec5SDimitry Andric   // (icmp ne (A & B), C) | (icmp ne (A & D), E)
318181ad6265SDimitry Andric   // (icmp eq (A & B), C) & (icmp eq (A & D), E)
318281ad6265SDimitry Andric   if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, IsAnd, IsLogical, Builder))
31830b57cec5SDimitry Andric     return V;
31840b57cec5SDimitry Andric 
3185bdd1243dSDimitry Andric   if (Value *V =
318606c3fb27SDimitry Andric           foldAndOrOfICmpEqConstantAndICmp(LHS, RHS, IsAnd, IsLogical, Builder))
318781ad6265SDimitry Andric     return V;
3188bdd1243dSDimitry Andric   // We can treat logical like bitwise here, because both operands are used on
3189bdd1243dSDimitry Andric   // the LHS, and as such poison from both will propagate.
319006c3fb27SDimitry Andric   if (Value *V = foldAndOrOfICmpEqConstantAndICmp(RHS, LHS, IsAnd,
3191bdd1243dSDimitry Andric                                                   /*IsLogical*/ false, Builder))
319281ad6265SDimitry Andric     return V;
31930b57cec5SDimitry Andric 
3194bdd1243dSDimitry Andric   if (Value *V =
3195bdd1243dSDimitry Andric           foldAndOrOfICmpsWithConstEq(LHS, RHS, IsAnd, IsLogical, Builder, Q))
31965ffd83dbSDimitry Andric     return V;
3197bdd1243dSDimitry Andric   // We can convert this case to bitwise and, because both operands are used
3198bdd1243dSDimitry Andric   // on the LHS, and as such poison from both will propagate.
3199bdd1243dSDimitry Andric   if (Value *V = foldAndOrOfICmpsWithConstEq(RHS, LHS, IsAnd,
3200bdd1243dSDimitry Andric                                              /*IsLogical*/ false, Builder, Q))
320181ad6265SDimitry Andric     return V;
320281ad6265SDimitry Andric 
320381ad6265SDimitry Andric   if (Value *V = foldIsPowerOf2OrZero(LHS, RHS, IsAnd, Builder))
320481ad6265SDimitry Andric     return V;
320581ad6265SDimitry Andric   if (Value *V = foldIsPowerOf2OrZero(RHS, LHS, IsAnd, Builder))
32065ffd83dbSDimitry Andric     return V;
32075ffd83dbSDimitry Andric 
320881ad6265SDimitry Andric   // TODO: One of these directions is fine with logical and/or, the other could
320981ad6265SDimitry Andric   // be supported by inserting freeze.
321081ad6265SDimitry Andric   if (!IsLogical) {
32110b57cec5SDimitry Andric     // E.g. (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
321281ad6265SDimitry Andric     // E.g. (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
321381ad6265SDimitry Andric     if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/!IsAnd))
32140b57cec5SDimitry Andric       return V;
32150b57cec5SDimitry Andric 
32160b57cec5SDimitry Andric     // E.g. (icmp sgt x, n) | (icmp slt x, 0) --> icmp ugt x, n
321781ad6265SDimitry Andric     // E.g. (icmp slt x, n) & (icmp sge x, 0) --> icmp ult x, n
321881ad6265SDimitry Andric     if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/!IsAnd))
321981ad6265SDimitry Andric       return V;
322081ad6265SDimitry Andric   }
322181ad6265SDimitry Andric 
322281ad6265SDimitry Andric   // TODO: Add conjugated or fold, check whether it is safe for logical and/or.
322381ad6265SDimitry Andric   if (IsAnd && !IsLogical)
322481ad6265SDimitry Andric     if (Value *V = foldSignedTruncationCheck(LHS, RHS, I, Builder))
32250b57cec5SDimitry Andric       return V;
32260b57cec5SDimitry Andric 
322781ad6265SDimitry Andric   if (Value *V = foldIsPowerOf2(LHS, RHS, IsAnd, Builder))
32280b57cec5SDimitry Andric     return V;
32290b57cec5SDimitry Andric 
323006c3fb27SDimitry Andric   if (Value *V = foldPowerOf2AndShiftedMask(LHS, RHS, IsAnd, Builder))
323106c3fb27SDimitry Andric     return V;
323206c3fb27SDimitry Andric 
323381ad6265SDimitry Andric   // TODO: Verify whether this is safe for logical and/or.
323481ad6265SDimitry Andric   if (!IsLogical) {
323581ad6265SDimitry Andric     if (Value *X = foldUnsignedUnderflowCheck(LHS, RHS, IsAnd, Q, Builder))
32368bcb0991SDimitry Andric       return X;
323781ad6265SDimitry Andric     if (Value *X = foldUnsignedUnderflowCheck(RHS, LHS, IsAnd, Q, Builder))
32388bcb0991SDimitry Andric       return X;
323981ad6265SDimitry Andric   }
32408bcb0991SDimitry Andric 
324181ad6265SDimitry Andric   if (Value *X = foldEqOfParts(LHS, RHS, IsAnd))
3242fe6060f1SDimitry Andric     return X;
3243fe6060f1SDimitry Andric 
3244e8d8bef9SDimitry Andric   // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
324581ad6265SDimitry Andric   // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
324606c3fb27SDimitry Andric   // TODO: Remove this and below when foldLogOpOfMaskedICmps can handle undefs.
324781ad6265SDimitry Andric   if (!IsLogical && PredL == (IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE) &&
324881ad6265SDimitry Andric       PredL == PredR && match(LHS1, m_ZeroInt()) && match(RHS1, m_ZeroInt()) &&
3249e8d8bef9SDimitry Andric       LHS0->getType() == RHS0->getType()) {
3250e8d8bef9SDimitry Andric     Value *NewOr = Builder.CreateOr(LHS0, RHS0);
3251e8d8bef9SDimitry Andric     return Builder.CreateICmp(PredL, NewOr,
3252e8d8bef9SDimitry Andric                               Constant::getNullValue(NewOr->getType()));
3253e8d8bef9SDimitry Andric   }
3254e8d8bef9SDimitry Andric 
325506c3fb27SDimitry Andric   // (icmp ne A, -1) | (icmp ne B, -1) --> (icmp ne (A&B), -1)
325606c3fb27SDimitry Andric   // (icmp eq A, -1) & (icmp eq B, -1) --> (icmp eq (A&B), -1)
325706c3fb27SDimitry Andric   if (!IsLogical && PredL == (IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE) &&
325806c3fb27SDimitry Andric       PredL == PredR && match(LHS1, m_AllOnes()) && match(RHS1, m_AllOnes()) &&
325906c3fb27SDimitry Andric       LHS0->getType() == RHS0->getType()) {
326006c3fb27SDimitry Andric     Value *NewAnd = Builder.CreateAnd(LHS0, RHS0);
326106c3fb27SDimitry Andric     return Builder.CreateICmp(PredL, NewAnd,
326206c3fb27SDimitry Andric                               Constant::getAllOnesValue(LHS0->getType()));
326306c3fb27SDimitry Andric   }
326406c3fb27SDimitry Andric 
32650b57cec5SDimitry Andric   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
32660b57cec5SDimitry Andric   if (!LHSC || !RHSC)
32670b57cec5SDimitry Andric     return nullptr;
32680b57cec5SDimitry Andric 
326981ad6265SDimitry Andric   // (trunc x) == C1 & (and x, CA) == C2 -> (and x, CA|CMAX) == C1|C2
327081ad6265SDimitry Andric   // (trunc x) != C1 | (and x, CA) != C2 -> (and x, CA|CMAX) != C1|C2
327181ad6265SDimitry Andric   // where CMAX is the all ones value for the truncated type,
327281ad6265SDimitry Andric   // iff the lower bits of C2 and CA are zero.
327381ad6265SDimitry Andric   if (PredL == (IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE) &&
327481ad6265SDimitry Andric       PredL == PredR && LHS->hasOneUse() && RHS->hasOneUse()) {
327581ad6265SDimitry Andric     Value *V;
327681ad6265SDimitry Andric     const APInt *AndC, *SmallC = nullptr, *BigC = nullptr;
327781ad6265SDimitry Andric 
327881ad6265SDimitry Andric     // (trunc x) == C1 & (and x, CA) == C2
327981ad6265SDimitry Andric     // (and x, CA) == C2 & (trunc x) == C1
328081ad6265SDimitry Andric     if (match(RHS0, m_Trunc(m_Value(V))) &&
328181ad6265SDimitry Andric         match(LHS0, m_And(m_Specific(V), m_APInt(AndC)))) {
328281ad6265SDimitry Andric       SmallC = RHSC;
328381ad6265SDimitry Andric       BigC = LHSC;
328481ad6265SDimitry Andric     } else if (match(LHS0, m_Trunc(m_Value(V))) &&
328581ad6265SDimitry Andric                match(RHS0, m_And(m_Specific(V), m_APInt(AndC)))) {
328681ad6265SDimitry Andric       SmallC = LHSC;
328781ad6265SDimitry Andric       BigC = RHSC;
328881ad6265SDimitry Andric     }
328981ad6265SDimitry Andric 
329081ad6265SDimitry Andric     if (SmallC && BigC) {
329181ad6265SDimitry Andric       unsigned BigBitSize = BigC->getBitWidth();
329281ad6265SDimitry Andric       unsigned SmallBitSize = SmallC->getBitWidth();
329381ad6265SDimitry Andric 
329481ad6265SDimitry Andric       // Check that the low bits are zero.
329581ad6265SDimitry Andric       APInt Low = APInt::getLowBitsSet(BigBitSize, SmallBitSize);
329681ad6265SDimitry Andric       if ((Low & *AndC).isZero() && (Low & *BigC).isZero()) {
329781ad6265SDimitry Andric         Value *NewAnd = Builder.CreateAnd(V, Low | *AndC);
329881ad6265SDimitry Andric         APInt N = SmallC->zext(BigBitSize) | *BigC;
329981ad6265SDimitry Andric         Value *NewVal = ConstantInt::get(NewAnd->getType(), N);
330081ad6265SDimitry Andric         return Builder.CreateICmp(PredL, NewAnd, NewVal);
330181ad6265SDimitry Andric       }
330281ad6265SDimitry Andric     }
330381ad6265SDimitry Andric   }
330481ad6265SDimitry Andric 
330581ad6265SDimitry Andric   // Match naive pattern (and its inverted form) for checking if two values
330681ad6265SDimitry Andric   // share same sign. An example of the pattern:
330781ad6265SDimitry Andric   // (icmp slt (X & Y), 0) | (icmp sgt (X | Y), -1) -> (icmp sgt (X ^ Y), -1)
330881ad6265SDimitry Andric   // Inverted form (example):
330981ad6265SDimitry Andric   // (icmp slt (X | Y), 0) & (icmp sgt (X & Y), -1) -> (icmp slt (X ^ Y), 0)
331081ad6265SDimitry Andric   bool TrueIfSignedL, TrueIfSignedR;
3311fcaf7f86SDimitry Andric   if (isSignBitCheck(PredL, *LHSC, TrueIfSignedL) &&
3312fcaf7f86SDimitry Andric       isSignBitCheck(PredR, *RHSC, TrueIfSignedR) &&
331381ad6265SDimitry Andric       (RHS->hasOneUse() || LHS->hasOneUse())) {
331481ad6265SDimitry Andric     Value *X, *Y;
331581ad6265SDimitry Andric     if (IsAnd) {
331681ad6265SDimitry Andric       if ((TrueIfSignedL && !TrueIfSignedR &&
331781ad6265SDimitry Andric            match(LHS0, m_Or(m_Value(X), m_Value(Y))) &&
331881ad6265SDimitry Andric            match(RHS0, m_c_And(m_Specific(X), m_Specific(Y)))) ||
331981ad6265SDimitry Andric           (!TrueIfSignedL && TrueIfSignedR &&
332081ad6265SDimitry Andric            match(LHS0, m_And(m_Value(X), m_Value(Y))) &&
332181ad6265SDimitry Andric            match(RHS0, m_c_Or(m_Specific(X), m_Specific(Y))))) {
332281ad6265SDimitry Andric         Value *NewXor = Builder.CreateXor(X, Y);
332381ad6265SDimitry Andric         return Builder.CreateIsNeg(NewXor);
332481ad6265SDimitry Andric       }
332581ad6265SDimitry Andric     } else {
332681ad6265SDimitry Andric       if ((TrueIfSignedL && !TrueIfSignedR &&
332781ad6265SDimitry Andric             match(LHS0, m_And(m_Value(X), m_Value(Y))) &&
332881ad6265SDimitry Andric             match(RHS0, m_c_Or(m_Specific(X), m_Specific(Y)))) ||
332981ad6265SDimitry Andric           (!TrueIfSignedL && TrueIfSignedR &&
333081ad6265SDimitry Andric            match(LHS0, m_Or(m_Value(X), m_Value(Y))) &&
333181ad6265SDimitry Andric            match(RHS0, m_c_And(m_Specific(X), m_Specific(Y))))) {
333281ad6265SDimitry Andric         Value *NewXor = Builder.CreateXor(X, Y);
333381ad6265SDimitry Andric         return Builder.CreateIsNotNeg(NewXor);
333481ad6265SDimitry Andric       }
333581ad6265SDimitry Andric     }
333681ad6265SDimitry Andric   }
333781ad6265SDimitry Andric 
333881ad6265SDimitry Andric   return foldAndOrOfICmpsUsingRanges(LHS, RHS, IsAnd);
33390b57cec5SDimitry Andric }
33400b57cec5SDimitry Andric 
33410b57cec5SDimitry Andric // FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
33420b57cec5SDimitry Andric // here. We should standardize that construct where it is needed or choose some
33430b57cec5SDimitry Andric // other way to ensure that commutated variants of patterns are not missed.
visitOr(BinaryOperator & I)3344e8d8bef9SDimitry Andric Instruction *InstCombinerImpl::visitOr(BinaryOperator &I) {
334581ad6265SDimitry Andric   if (Value *V = simplifyOrInst(I.getOperand(0), I.getOperand(1),
33460b57cec5SDimitry Andric                                 SQ.getWithInstruction(&I)))
33470b57cec5SDimitry Andric     return replaceInstUsesWith(I, V);
33480b57cec5SDimitry Andric 
33490b57cec5SDimitry Andric   if (SimplifyAssociativeOrCommutative(I))
33500b57cec5SDimitry Andric     return &I;
33510b57cec5SDimitry Andric 
33520b57cec5SDimitry Andric   if (Instruction *X = foldVectorBinop(I))
33530b57cec5SDimitry Andric     return X;
33540b57cec5SDimitry Andric 
335504eeddc0SDimitry Andric   if (Instruction *Phi = foldBinopWithPhiOperands(I))
335604eeddc0SDimitry Andric     return Phi;
335704eeddc0SDimitry Andric 
33580b57cec5SDimitry Andric   // See if we can simplify any instructions used by the instruction whose sole
33590b57cec5SDimitry Andric   // purpose is to compute bits we don't care about.
33600b57cec5SDimitry Andric   if (SimplifyDemandedInstructionBits(I))
33610b57cec5SDimitry Andric     return &I;
33620b57cec5SDimitry Andric 
33630b57cec5SDimitry Andric   // Do this before using distributive laws to catch simple and/or/not patterns.
33640b57cec5SDimitry Andric   if (Instruction *Xor = foldOrToXor(I, Builder))
33650b57cec5SDimitry Andric     return Xor;
33660b57cec5SDimitry Andric 
3367349cc55cSDimitry Andric   if (Instruction *X = foldComplexAndOrPatterns(I, Builder))
3368349cc55cSDimitry Andric     return X;
3369349cc55cSDimitry Andric 
33700b57cec5SDimitry Andric   // (A&B)|(A&C) -> A&(B|C) etc
3371bdd1243dSDimitry Andric   if (Value *V = foldUsingDistributiveLaws(I))
33720b57cec5SDimitry Andric     return replaceInstUsesWith(I, V);
33730b57cec5SDimitry Andric 
3374fe6060f1SDimitry Andric   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
33754824e7fdSDimitry Andric   Type *Ty = I.getType();
33764824e7fdSDimitry Andric   if (Ty->isIntOrIntVectorTy(1)) {
3377fe6060f1SDimitry Andric     if (auto *SI0 = dyn_cast<SelectInst>(Op0)) {
33785f757f3fSDimitry Andric       if (auto *R =
3379fe6060f1SDimitry Andric               foldAndOrOfSelectUsingImpliedCond(Op1, *SI0, /* IsAnd */ false))
33805f757f3fSDimitry Andric         return R;
3381fe6060f1SDimitry Andric     }
3382fe6060f1SDimitry Andric     if (auto *SI1 = dyn_cast<SelectInst>(Op1)) {
33835f757f3fSDimitry Andric       if (auto *R =
3384fe6060f1SDimitry Andric               foldAndOrOfSelectUsingImpliedCond(Op0, *SI1, /* IsAnd */ false))
33855f757f3fSDimitry Andric         return R;
3386fe6060f1SDimitry Andric     }
3387fe6060f1SDimitry Andric   }
3388fe6060f1SDimitry Andric 
33890b57cec5SDimitry Andric   if (Instruction *FoldedLogic = foldBinOpIntoSelectOrPhi(I))
33900b57cec5SDimitry Andric     return FoldedLogic;
33910b57cec5SDimitry Andric 
3392fe6060f1SDimitry Andric   if (Instruction *BitOp = matchBSwapOrBitReverse(I, /*MatchBSwaps*/ true,
3393fe6060f1SDimitry Andric                                                   /*MatchBitReversals*/ true))
3394fe6060f1SDimitry Andric     return BitOp;
33950b57cec5SDimitry Andric 
33965f757f3fSDimitry Andric   if (Instruction *Funnel = matchFunnelShift(I, *this, DT))
3397e8d8bef9SDimitry Andric     return Funnel;
33980b57cec5SDimitry Andric 
33995ffd83dbSDimitry Andric   if (Instruction *Concat = matchOrConcat(I, Builder))
34005ffd83dbSDimitry Andric     return replaceInstUsesWith(I, Concat);
34015ffd83dbSDimitry Andric 
340206c3fb27SDimitry Andric   if (Instruction *R = foldBinOpShiftWithShift(I))
340306c3fb27SDimitry Andric     return R;
340406c3fb27SDimitry Andric 
34057a6dacacSDimitry Andric   if (Instruction *R = tryFoldInstWithCtpopWithNot(&I))
34067a6dacacSDimitry Andric     return R;
34077a6dacacSDimitry Andric 
34080b57cec5SDimitry Andric   Value *X, *Y;
34090b57cec5SDimitry Andric   const APInt *CV;
34100b57cec5SDimitry Andric   if (match(&I, m_c_Or(m_OneUse(m_Xor(m_Value(X), m_APInt(CV))), m_Value(Y))) &&
3411349cc55cSDimitry Andric       !CV->isAllOnes() && MaskedValueIsZero(Y, *CV, 0, &I)) {
34120b57cec5SDimitry Andric     // (X ^ C) | Y -> (X | Y) ^ C iff Y & C == 0
34130b57cec5SDimitry Andric     // The check for a 'not' op is for efficiency (if Y is known zero --> ~X).
34140b57cec5SDimitry Andric     Value *Or = Builder.CreateOr(X, Y);
34154824e7fdSDimitry Andric     return BinaryOperator::CreateXor(Or, ConstantInt::get(Ty, *CV));
34164824e7fdSDimitry Andric   }
34174824e7fdSDimitry Andric 
34184824e7fdSDimitry Andric   // If the operands have no common bits set:
34194824e7fdSDimitry Andric   // or (mul X, Y), X --> add (mul X, Y), X --> mul X, (Y + 1)
34205f757f3fSDimitry Andric   if (match(&I, m_c_DisjointOr(m_OneUse(m_Mul(m_Value(X), m_Value(Y))),
34215f757f3fSDimitry Andric                                m_Deferred(X)))) {
34224824e7fdSDimitry Andric     Value *IncrementY = Builder.CreateAdd(Y, ConstantInt::get(Ty, 1));
34234824e7fdSDimitry Andric     return BinaryOperator::CreateMul(X, IncrementY);
34240b57cec5SDimitry Andric   }
34250b57cec5SDimitry Andric 
3426bdd1243dSDimitry Andric   // X | (X ^ Y) --> X | Y (4 commuted patterns)
3427bdd1243dSDimitry Andric   if (match(&I, m_c_Or(m_Value(X), m_c_Xor(m_Deferred(X), m_Value(Y)))))
3428bdd1243dSDimitry Andric     return BinaryOperator::CreateOr(X, Y);
3429bdd1243dSDimitry Andric 
34300b57cec5SDimitry Andric   // (A & C) | (B & D)
34310b57cec5SDimitry Andric   Value *A, *B, *C, *D;
34320b57cec5SDimitry Andric   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
34330b57cec5SDimitry Andric       match(Op1, m_And(m_Value(B), m_Value(D)))) {
34340b57cec5SDimitry Andric 
3435349cc55cSDimitry Andric     // (A & C0) | (B & C1)
3436349cc55cSDimitry Andric     const APInt *C0, *C1;
3437349cc55cSDimitry Andric     if (match(C, m_APInt(C0)) && match(D, m_APInt(C1))) {
34380b57cec5SDimitry Andric       Value *X;
3439349cc55cSDimitry Andric       if (*C0 == ~*C1) {
3440349cc55cSDimitry Andric         // ((X | B) & MaskC) | (B & ~MaskC) -> (X & MaskC) | B
34410b57cec5SDimitry Andric         if (match(A, m_c_Or(m_Value(X), m_Specific(B))))
3442349cc55cSDimitry Andric           return BinaryOperator::CreateOr(Builder.CreateAnd(X, *C0), B);
3443349cc55cSDimitry Andric         // (A & MaskC) | ((X | A) & ~MaskC) -> (X & ~MaskC) | A
34440b57cec5SDimitry Andric         if (match(B, m_c_Or(m_Specific(A), m_Value(X))))
3445349cc55cSDimitry Andric           return BinaryOperator::CreateOr(Builder.CreateAnd(X, *C1), A);
34460b57cec5SDimitry Andric 
3447349cc55cSDimitry Andric         // ((X ^ B) & MaskC) | (B & ~MaskC) -> (X & MaskC) ^ B
34480b57cec5SDimitry Andric         if (match(A, m_c_Xor(m_Value(X), m_Specific(B))))
3449349cc55cSDimitry Andric           return BinaryOperator::CreateXor(Builder.CreateAnd(X, *C0), B);
3450349cc55cSDimitry Andric         // (A & MaskC) | ((X ^ A) & ~MaskC) -> (X & ~MaskC) ^ A
34510b57cec5SDimitry Andric         if (match(B, m_c_Xor(m_Specific(A), m_Value(X))))
3452349cc55cSDimitry Andric           return BinaryOperator::CreateXor(Builder.CreateAnd(X, *C1), A);
3453349cc55cSDimitry Andric       }
3454349cc55cSDimitry Andric 
3455349cc55cSDimitry Andric       if ((*C0 & *C1).isZero()) {
3456349cc55cSDimitry Andric         // ((X | B) & C0) | (B & C1) --> (X | B) & (C0 | C1)
3457349cc55cSDimitry Andric         // iff (C0 & C1) == 0 and (X & ~C0) == 0
3458349cc55cSDimitry Andric         if (match(A, m_c_Or(m_Value(X), m_Specific(B))) &&
3459349cc55cSDimitry Andric             MaskedValueIsZero(X, ~*C0, 0, &I)) {
34604824e7fdSDimitry Andric           Constant *C01 = ConstantInt::get(Ty, *C0 | *C1);
3461349cc55cSDimitry Andric           return BinaryOperator::CreateAnd(A, C01);
3462349cc55cSDimitry Andric         }
3463349cc55cSDimitry Andric         // (A & C0) | ((X | A) & C1) --> (X | A) & (C0 | C1)
3464349cc55cSDimitry Andric         // iff (C0 & C1) == 0 and (X & ~C1) == 0
3465349cc55cSDimitry Andric         if (match(B, m_c_Or(m_Value(X), m_Specific(A))) &&
3466349cc55cSDimitry Andric             MaskedValueIsZero(X, ~*C1, 0, &I)) {
34674824e7fdSDimitry Andric           Constant *C01 = ConstantInt::get(Ty, *C0 | *C1);
3468349cc55cSDimitry Andric           return BinaryOperator::CreateAnd(B, C01);
3469349cc55cSDimitry Andric         }
3470349cc55cSDimitry Andric         // ((X | C2) & C0) | ((X | C3) & C1) --> (X | C2 | C3) & (C0 | C1)
3471349cc55cSDimitry Andric         // iff (C0 & C1) == 0 and (C2 & ~C0) == 0 and (C3 & ~C1) == 0.
3472349cc55cSDimitry Andric         const APInt *C2, *C3;
3473349cc55cSDimitry Andric         if (match(A, m_Or(m_Value(X), m_APInt(C2))) &&
3474349cc55cSDimitry Andric             match(B, m_Or(m_Specific(X), m_APInt(C3))) &&
3475349cc55cSDimitry Andric             (*C2 & ~*C0).isZero() && (*C3 & ~*C1).isZero()) {
3476349cc55cSDimitry Andric           Value *Or = Builder.CreateOr(X, *C2 | *C3, "bitfield");
34774824e7fdSDimitry Andric           Constant *C01 = ConstantInt::get(Ty, *C0 | *C1);
3478349cc55cSDimitry Andric           return BinaryOperator::CreateAnd(Or, C01);
3479349cc55cSDimitry Andric         }
34800b57cec5SDimitry Andric       }
34810b57cec5SDimitry Andric     }
34820b57cec5SDimitry Andric 
34830b57cec5SDimitry Andric     // Don't try to form a select if it's unlikely that we'll get rid of at
34840b57cec5SDimitry Andric     // least one of the operands. A select is generally more expensive than the
34850b57cec5SDimitry Andric     // 'or' that it is replacing.
34860b57cec5SDimitry Andric     if (Op0->hasOneUse() || Op1->hasOneUse()) {
34870b57cec5SDimitry Andric       // (Cond & C) | (~Cond & D) -> Cond ? C : D, and commuted variants.
34880b57cec5SDimitry Andric       if (Value *V = matchSelectFromAndOr(A, C, B, D))
34890b57cec5SDimitry Andric         return replaceInstUsesWith(I, V);
34900b57cec5SDimitry Andric       if (Value *V = matchSelectFromAndOr(A, C, D, B))
34910b57cec5SDimitry Andric         return replaceInstUsesWith(I, V);
34920b57cec5SDimitry Andric       if (Value *V = matchSelectFromAndOr(C, A, B, D))
34930b57cec5SDimitry Andric         return replaceInstUsesWith(I, V);
34940b57cec5SDimitry Andric       if (Value *V = matchSelectFromAndOr(C, A, D, B))
34950b57cec5SDimitry Andric         return replaceInstUsesWith(I, V);
34960b57cec5SDimitry Andric       if (Value *V = matchSelectFromAndOr(B, D, A, C))
34970b57cec5SDimitry Andric         return replaceInstUsesWith(I, V);
34980b57cec5SDimitry Andric       if (Value *V = matchSelectFromAndOr(B, D, C, A))
34990b57cec5SDimitry Andric         return replaceInstUsesWith(I, V);
35000b57cec5SDimitry Andric       if (Value *V = matchSelectFromAndOr(D, B, A, C))
35010b57cec5SDimitry Andric         return replaceInstUsesWith(I, V);
35020b57cec5SDimitry Andric       if (Value *V = matchSelectFromAndOr(D, B, C, A))
35030b57cec5SDimitry Andric         return replaceInstUsesWith(I, V);
35040b57cec5SDimitry Andric     }
35050b57cec5SDimitry Andric   }
35060b57cec5SDimitry Andric 
3507bdd1243dSDimitry Andric   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
3508bdd1243dSDimitry Andric       match(Op1, m_Not(m_Or(m_Value(B), m_Value(D)))) &&
3509bdd1243dSDimitry Andric       (Op0->hasOneUse() || Op1->hasOneUse())) {
3510bdd1243dSDimitry Andric     // (Cond & C) | ~(Cond | D) -> Cond ? C : ~D
3511bdd1243dSDimitry Andric     if (Value *V = matchSelectFromAndOr(A, C, B, D, true))
3512bdd1243dSDimitry Andric       return replaceInstUsesWith(I, V);
3513bdd1243dSDimitry Andric     if (Value *V = matchSelectFromAndOr(A, C, D, B, true))
3514bdd1243dSDimitry Andric       return replaceInstUsesWith(I, V);
3515bdd1243dSDimitry Andric     if (Value *V = matchSelectFromAndOr(C, A, B, D, true))
3516bdd1243dSDimitry Andric       return replaceInstUsesWith(I, V);
3517bdd1243dSDimitry Andric     if (Value *V = matchSelectFromAndOr(C, A, D, B, true))
3518bdd1243dSDimitry Andric       return replaceInstUsesWith(I, V);
3519bdd1243dSDimitry Andric   }
3520bdd1243dSDimitry Andric 
35210b57cec5SDimitry Andric   // (A ^ B) | ((B ^ C) ^ A) -> (A ^ B) | C
35220b57cec5SDimitry Andric   if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
35230b57cec5SDimitry Andric     if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
35240b57cec5SDimitry Andric       return BinaryOperator::CreateOr(Op0, C);
35250b57cec5SDimitry Andric 
35260b57cec5SDimitry Andric   // ((A ^ C) ^ B) | (B ^ A) -> (B ^ A) | C
35270b57cec5SDimitry Andric   if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
35280b57cec5SDimitry Andric     if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
35290b57cec5SDimitry Andric       return BinaryOperator::CreateOr(Op1, C);
35300b57cec5SDimitry Andric 
353181ad6265SDimitry Andric   // ((A & B) ^ C) | B -> C | B
353281ad6265SDimitry Andric   if (match(Op0, m_c_Xor(m_c_And(m_Value(A), m_Specific(Op1)), m_Value(C))))
353381ad6265SDimitry Andric     return BinaryOperator::CreateOr(C, Op1);
353481ad6265SDimitry Andric 
353581ad6265SDimitry Andric   // B | ((A & B) ^ C) -> B | C
353681ad6265SDimitry Andric   if (match(Op1, m_c_Xor(m_c_And(m_Value(A), m_Specific(Op0)), m_Value(C))))
353781ad6265SDimitry Andric     return BinaryOperator::CreateOr(Op0, C);
353881ad6265SDimitry Andric 
35390b57cec5SDimitry Andric   // ((B | C) & A) | B -> B | (A & C)
3540647cbc5dSDimitry Andric   if (match(Op0, m_c_And(m_c_Or(m_Specific(Op1), m_Value(C)), m_Value(A))))
35410b57cec5SDimitry Andric     return BinaryOperator::CreateOr(Op1, Builder.CreateAnd(A, C));
35420b57cec5SDimitry Andric 
3543647cbc5dSDimitry Andric   // B | ((B | C) & A) -> B | (A & C)
3544647cbc5dSDimitry Andric   if (match(Op1, m_c_And(m_c_Or(m_Specific(Op0), m_Value(C)), m_Value(A))))
3545647cbc5dSDimitry Andric     return BinaryOperator::CreateOr(Op0, Builder.CreateAnd(A, C));
3546647cbc5dSDimitry Andric 
35475f757f3fSDimitry Andric   if (Instruction *DeMorgan = matchDeMorgansLaws(I, *this))
35480b57cec5SDimitry Andric     return DeMorgan;
35490b57cec5SDimitry Andric 
35500b57cec5SDimitry Andric   // Canonicalize xor to the RHS.
35510b57cec5SDimitry Andric   bool SwappedForXor = false;
35520b57cec5SDimitry Andric   if (match(Op0, m_Xor(m_Value(), m_Value()))) {
35530b57cec5SDimitry Andric     std::swap(Op0, Op1);
35540b57cec5SDimitry Andric     SwappedForXor = true;
35550b57cec5SDimitry Andric   }
35560b57cec5SDimitry Andric 
35570b57cec5SDimitry Andric   if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3558bdd1243dSDimitry Andric     // (A | ?) | (A ^ B) --> (A | ?) | B
3559bdd1243dSDimitry Andric     // (B | ?) | (A ^ B) --> (B | ?) | A
3560bdd1243dSDimitry Andric     if (match(Op0, m_c_Or(m_Specific(A), m_Value())))
3561bdd1243dSDimitry Andric       return BinaryOperator::CreateOr(Op0, B);
3562bdd1243dSDimitry Andric     if (match(Op0, m_c_Or(m_Specific(B), m_Value())))
3563bdd1243dSDimitry Andric       return BinaryOperator::CreateOr(Op0, A);
35640b57cec5SDimitry Andric 
3565bdd1243dSDimitry Andric     // (A & B) | (A ^ B) --> A | B
3566bdd1243dSDimitry Andric     // (B & A) | (A ^ B) --> A | B
35670b57cec5SDimitry Andric     if (match(Op0, m_And(m_Specific(A), m_Specific(B))) ||
35680b57cec5SDimitry Andric         match(Op0, m_And(m_Specific(B), m_Specific(A))))
35690b57cec5SDimitry Andric       return BinaryOperator::CreateOr(A, B);
35700b57cec5SDimitry Andric 
3571bdd1243dSDimitry Andric     // ~A | (A ^ B) --> ~(A & B)
3572bdd1243dSDimitry Andric     // ~B | (A ^ B) --> ~(A & B)
3573bdd1243dSDimitry Andric     // The swap above should always make Op0 the 'not'.
3574349cc55cSDimitry Andric     if ((Op0->hasOneUse() || Op1->hasOneUse()) &&
3575349cc55cSDimitry Andric         (match(Op0, m_Not(m_Specific(A))) || match(Op0, m_Not(m_Specific(B)))))
3576349cc55cSDimitry Andric       return BinaryOperator::CreateNot(Builder.CreateAnd(A, B));
3577349cc55cSDimitry Andric 
3578bdd1243dSDimitry Andric     // Same as above, but peek through an 'and' to the common operand:
3579bdd1243dSDimitry Andric     // ~(A & ?) | (A ^ B) --> ~((A & ?) & B)
3580bdd1243dSDimitry Andric     // ~(B & ?) | (A ^ B) --> ~((B & ?) & A)
3581bdd1243dSDimitry Andric     Instruction *And;
3582bdd1243dSDimitry Andric     if ((Op0->hasOneUse() || Op1->hasOneUse()) &&
3583bdd1243dSDimitry Andric         match(Op0, m_Not(m_CombineAnd(m_Instruction(And),
3584bdd1243dSDimitry Andric                                       m_c_And(m_Specific(A), m_Value())))))
3585bdd1243dSDimitry Andric       return BinaryOperator::CreateNot(Builder.CreateAnd(And, B));
3586bdd1243dSDimitry Andric     if ((Op0->hasOneUse() || Op1->hasOneUse()) &&
3587bdd1243dSDimitry Andric         match(Op0, m_Not(m_CombineAnd(m_Instruction(And),
3588bdd1243dSDimitry Andric                                       m_c_And(m_Specific(B), m_Value())))))
3589bdd1243dSDimitry Andric       return BinaryOperator::CreateNot(Builder.CreateAnd(And, A));
3590bdd1243dSDimitry Andric 
3591bdd1243dSDimitry Andric     // (~A | C) | (A ^ B) --> ~(A & B) | C
3592bdd1243dSDimitry Andric     // (~B | C) | (A ^ B) --> ~(A & B) | C
3593bdd1243dSDimitry Andric     if (Op0->hasOneUse() && Op1->hasOneUse() &&
3594bdd1243dSDimitry Andric         (match(Op0, m_c_Or(m_Not(m_Specific(A)), m_Value(C))) ||
3595bdd1243dSDimitry Andric          match(Op0, m_c_Or(m_Not(m_Specific(B)), m_Value(C))))) {
3596bdd1243dSDimitry Andric       Value *Nand = Builder.CreateNot(Builder.CreateAnd(A, B), "nand");
3597bdd1243dSDimitry Andric       return BinaryOperator::CreateOr(Nand, C);
3598bdd1243dSDimitry Andric     }
3599bdd1243dSDimitry Andric 
3600bdd1243dSDimitry Andric     // A | (~A ^ B) --> ~B | A
3601bdd1243dSDimitry Andric     // B | (A ^ ~B) --> ~A | B
36020b57cec5SDimitry Andric     if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) {
3603bdd1243dSDimitry Andric       Value *NotB = Builder.CreateNot(B, B->getName() + ".not");
3604bdd1243dSDimitry Andric       return BinaryOperator::CreateOr(NotB, Op0);
36050b57cec5SDimitry Andric     }
36060b57cec5SDimitry Andric     if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) {
3607bdd1243dSDimitry Andric       Value *NotA = Builder.CreateNot(A, A->getName() + ".not");
3608bdd1243dSDimitry Andric       return BinaryOperator::CreateOr(NotA, Op0);
36090b57cec5SDimitry Andric     }
36100b57cec5SDimitry Andric   }
36110b57cec5SDimitry Andric 
36120b57cec5SDimitry Andric   // A | ~(A | B) -> A | ~B
36130b57cec5SDimitry Andric   // A | ~(A ^ B) -> A | ~B
36140b57cec5SDimitry Andric   if (match(Op1, m_Not(m_Value(A))))
36150b57cec5SDimitry Andric     if (BinaryOperator *B = dyn_cast<BinaryOperator>(A))
36160b57cec5SDimitry Andric       if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) &&
36170b57cec5SDimitry Andric           Op1->hasOneUse() && (B->getOpcode() == Instruction::Or ||
36180b57cec5SDimitry Andric                                B->getOpcode() == Instruction::Xor)) {
36190b57cec5SDimitry Andric         Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) :
36200b57cec5SDimitry Andric                                                  B->getOperand(0);
36210b57cec5SDimitry Andric         Value *Not = Builder.CreateNot(NotOp, NotOp->getName() + ".not");
36220b57cec5SDimitry Andric         return BinaryOperator::CreateOr(Not, Op0);
36230b57cec5SDimitry Andric       }
36240b57cec5SDimitry Andric 
36250b57cec5SDimitry Andric   if (SwappedForXor)
36260b57cec5SDimitry Andric     std::swap(Op0, Op1);
36270b57cec5SDimitry Andric 
36280b57cec5SDimitry Andric   {
36290b57cec5SDimitry Andric     ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
36300b57cec5SDimitry Andric     ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
36310b57cec5SDimitry Andric     if (LHS && RHS)
363281ad6265SDimitry Andric       if (Value *Res = foldAndOrOfICmps(LHS, RHS, I, /* IsAnd */ false))
36330b57cec5SDimitry Andric         return replaceInstUsesWith(I, Res);
36340b57cec5SDimitry Andric 
36350b57cec5SDimitry Andric     // TODO: Make this recursive; it's a little tricky because an arbitrary
36360b57cec5SDimitry Andric     // number of 'or' instructions might have to be created.
36370b57cec5SDimitry Andric     Value *X, *Y;
363881ad6265SDimitry Andric     if (LHS && match(Op1, m_OneUse(m_LogicalOr(m_Value(X), m_Value(Y))))) {
363981ad6265SDimitry Andric       bool IsLogical = isa<SelectInst>(Op1);
364081ad6265SDimitry Andric       // LHS | (X || Y) --> (LHS || X) || Y
36410b57cec5SDimitry Andric       if (auto *Cmp = dyn_cast<ICmpInst>(X))
364281ad6265SDimitry Andric         if (Value *Res =
364381ad6265SDimitry Andric                 foldAndOrOfICmps(LHS, Cmp, I, /* IsAnd */ false, IsLogical))
364481ad6265SDimitry Andric           return replaceInstUsesWith(I, IsLogical
364581ad6265SDimitry Andric                                             ? Builder.CreateLogicalOr(Res, Y)
364681ad6265SDimitry Andric                                             : Builder.CreateOr(Res, Y));
364781ad6265SDimitry Andric       // LHS | (X || Y) --> X || (LHS | Y)
36480b57cec5SDimitry Andric       if (auto *Cmp = dyn_cast<ICmpInst>(Y))
364981ad6265SDimitry Andric         if (Value *Res = foldAndOrOfICmps(LHS, Cmp, I, /* IsAnd */ false,
365081ad6265SDimitry Andric                                           /* IsLogical */ false))
365181ad6265SDimitry Andric           return replaceInstUsesWith(I, IsLogical
365281ad6265SDimitry Andric                                             ? Builder.CreateLogicalOr(X, Res)
365381ad6265SDimitry Andric                                             : Builder.CreateOr(X, Res));
36540b57cec5SDimitry Andric     }
365581ad6265SDimitry Andric     if (RHS && match(Op0, m_OneUse(m_LogicalOr(m_Value(X), m_Value(Y))))) {
365681ad6265SDimitry Andric       bool IsLogical = isa<SelectInst>(Op0);
365781ad6265SDimitry Andric       // (X || Y) | RHS --> (X || RHS) || Y
36580b57cec5SDimitry Andric       if (auto *Cmp = dyn_cast<ICmpInst>(X))
365981ad6265SDimitry Andric         if (Value *Res =
366081ad6265SDimitry Andric                 foldAndOrOfICmps(Cmp, RHS, I, /* IsAnd */ false, IsLogical))
366181ad6265SDimitry Andric           return replaceInstUsesWith(I, IsLogical
366281ad6265SDimitry Andric                                             ? Builder.CreateLogicalOr(Res, Y)
366381ad6265SDimitry Andric                                             : Builder.CreateOr(Res, Y));
366481ad6265SDimitry Andric       // (X || Y) | RHS --> X || (Y | RHS)
36650b57cec5SDimitry Andric       if (auto *Cmp = dyn_cast<ICmpInst>(Y))
366681ad6265SDimitry Andric         if (Value *Res = foldAndOrOfICmps(Cmp, RHS, I, /* IsAnd */ false,
366781ad6265SDimitry Andric                                           /* IsLogical */ false))
366881ad6265SDimitry Andric           return replaceInstUsesWith(I, IsLogical
366981ad6265SDimitry Andric                                             ? Builder.CreateLogicalOr(X, Res)
367081ad6265SDimitry Andric                                             : Builder.CreateOr(X, Res));
36710b57cec5SDimitry Andric     }
36720b57cec5SDimitry Andric   }
36730b57cec5SDimitry Andric 
36740b57cec5SDimitry Andric   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
36750b57cec5SDimitry Andric     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
367681ad6265SDimitry Andric       if (Value *Res = foldLogicOfFCmps(LHS, RHS, /*IsAnd*/ false))
36770b57cec5SDimitry Andric         return replaceInstUsesWith(I, Res);
36780b57cec5SDimitry Andric 
36790b57cec5SDimitry Andric   if (Instruction *FoldedFCmps = reassociateFCmps(I, Builder))
36800b57cec5SDimitry Andric     return FoldedFCmps;
36810b57cec5SDimitry Andric 
36820b57cec5SDimitry Andric   if (Instruction *CastedOr = foldCastedBitwiseLogic(I))
36830b57cec5SDimitry Andric     return CastedOr;
36840b57cec5SDimitry Andric 
36854824e7fdSDimitry Andric   if (Instruction *Sel = foldBinopOfSextBoolToSelect(I))
36864824e7fdSDimitry Andric     return Sel;
36874824e7fdSDimitry Andric 
36880b57cec5SDimitry Andric   // or(sext(A), B) / or(B, sext(A)) --> A ? -1 : B, where A is i1 or <N x i1>.
36894824e7fdSDimitry Andric   // TODO: Move this into foldBinopOfSextBoolToSelect as a more generalized fold
36904824e7fdSDimitry Andric   //       with binop identity constant. But creating a select with non-constant
36914824e7fdSDimitry Andric   //       arm may not be reversible due to poison semantics. Is that a good
36924824e7fdSDimitry Andric   //       canonicalization?
36935f757f3fSDimitry Andric   if (match(&I, m_c_Or(m_OneUse(m_SExt(m_Value(A))), m_Value(B))) &&
36940b57cec5SDimitry Andric       A->getType()->isIntOrIntVectorTy(1))
36955f757f3fSDimitry Andric     return SelectInst::Create(A, ConstantInt::getAllOnesValue(Ty), B);
36960b57cec5SDimitry Andric 
36970b57cec5SDimitry Andric   // Note: If we've gotten to the point of visiting the outer OR, then the
36980b57cec5SDimitry Andric   // inner one couldn't be simplified.  If it was a constant, then it won't
36990b57cec5SDimitry Andric   // be simplified by a later pass either, so we try swapping the inner/outer
37000b57cec5SDimitry Andric   // ORs in the hopes that we'll be able to simplify it this way.
37010b57cec5SDimitry Andric   // (X|C) | V --> (X|V) | C
37020b57cec5SDimitry Andric   ConstantInt *CI;
3703e8d8bef9SDimitry Andric   if (Op0->hasOneUse() && !match(Op1, m_ConstantInt()) &&
37040b57cec5SDimitry Andric       match(Op0, m_Or(m_Value(A), m_ConstantInt(CI)))) {
37050b57cec5SDimitry Andric     Value *Inner = Builder.CreateOr(A, Op1);
37060b57cec5SDimitry Andric     Inner->takeName(Op0);
37070b57cec5SDimitry Andric     return BinaryOperator::CreateOr(Inner, CI);
37080b57cec5SDimitry Andric   }
37090b57cec5SDimitry Andric 
37100b57cec5SDimitry Andric   // Change (or (bool?A:B),(bool?C:D)) --> (bool?(or A,C):(or B,D))
37110b57cec5SDimitry Andric   // Since this OR statement hasn't been optimized further yet, we hope
37120b57cec5SDimitry Andric   // that this transformation will allow the new ORs to be optimized.
37130b57cec5SDimitry Andric   {
37140b57cec5SDimitry Andric     Value *X = nullptr, *Y = nullptr;
37150b57cec5SDimitry Andric     if (Op0->hasOneUse() && Op1->hasOneUse() &&
37160b57cec5SDimitry Andric         match(Op0, m_Select(m_Value(X), m_Value(A), m_Value(B))) &&
37170b57cec5SDimitry Andric         match(Op1, m_Select(m_Value(Y), m_Value(C), m_Value(D))) && X == Y) {
37180b57cec5SDimitry Andric       Value *orTrue = Builder.CreateOr(A, C);
37190b57cec5SDimitry Andric       Value *orFalse = Builder.CreateOr(B, D);
37200b57cec5SDimitry Andric       return SelectInst::Create(X, orTrue, orFalse);
37210b57cec5SDimitry Andric     }
37220b57cec5SDimitry Andric   }
37230b57cec5SDimitry Andric 
37248bcb0991SDimitry Andric   // or(ashr(subNSW(Y, X), ScalarSizeInBits(Y) - 1), X)  --> X s> Y ? -1 : X.
37258bcb0991SDimitry Andric   {
37268bcb0991SDimitry Andric     Value *X, *Y;
3727e8d8bef9SDimitry Andric     if (match(&I, m_c_Or(m_OneUse(m_AShr(
3728e8d8bef9SDimitry Andric                              m_NSWSub(m_Value(Y), m_Value(X)),
3729e8d8bef9SDimitry Andric                              m_SpecificInt(Ty->getScalarSizeInBits() - 1))),
3730e8d8bef9SDimitry Andric                          m_Deferred(X)))) {
37318bcb0991SDimitry Andric       Value *NewICmpInst = Builder.CreateICmpSGT(X, Y);
3732e8d8bef9SDimitry Andric       Value *AllOnes = ConstantInt::getAllOnesValue(Ty);
3733e8d8bef9SDimitry Andric       return SelectInst::Create(NewICmpInst, AllOnes, X);
37348bcb0991SDimitry Andric     }
37358bcb0991SDimitry Andric   }
37368bcb0991SDimitry Andric 
37375f757f3fSDimitry Andric   {
37385f757f3fSDimitry Andric     // ((A & B) ^ A) | ((A & B) ^ B) -> A ^ B
37395f757f3fSDimitry Andric     // (A ^ (A & B)) | (B ^ (A & B)) -> A ^ B
37405f757f3fSDimitry Andric     // ((A & B) ^ B) | ((A & B) ^ A) -> A ^ B
37415f757f3fSDimitry Andric     // (B ^ (A & B)) | (A ^ (A & B)) -> A ^ B
37425f757f3fSDimitry Andric     const auto TryXorOpt = [&](Value *Lhs, Value *Rhs) -> Instruction * {
37435f757f3fSDimitry Andric       if (match(Lhs, m_c_Xor(m_And(m_Value(A), m_Value(B)), m_Deferred(A))) &&
37445f757f3fSDimitry Andric           match(Rhs,
37455f757f3fSDimitry Andric                 m_c_Xor(m_And(m_Specific(A), m_Specific(B)), m_Deferred(B)))) {
37465f757f3fSDimitry Andric         return BinaryOperator::CreateXor(A, B);
37475f757f3fSDimitry Andric       }
37485f757f3fSDimitry Andric       return nullptr;
37495f757f3fSDimitry Andric     };
37505f757f3fSDimitry Andric 
37515f757f3fSDimitry Andric     if (Instruction *Result = TryXorOpt(Op0, Op1))
37525f757f3fSDimitry Andric       return Result;
37535f757f3fSDimitry Andric     if (Instruction *Result = TryXorOpt(Op1, Op0))
37545f757f3fSDimitry Andric       return Result;
37555f757f3fSDimitry Andric   }
37565f757f3fSDimitry Andric 
37578bcb0991SDimitry Andric   if (Instruction *V =
37588bcb0991SDimitry Andric           canonicalizeCondSignextOfHighBitExtractToSignextHighBitExtract(I))
37598bcb0991SDimitry Andric     return V;
37608bcb0991SDimitry Andric 
37615ffd83dbSDimitry Andric   CmpInst::Predicate Pred;
37625ffd83dbSDimitry Andric   Value *Mul, *Ov, *MulIsNotZero, *UMulWithOv;
37635ffd83dbSDimitry Andric   // Check if the OR weakens the overflow condition for umul.with.overflow by
37645ffd83dbSDimitry Andric   // treating any non-zero result as overflow. In that case, we overflow if both
37655ffd83dbSDimitry Andric   // umul.with.overflow operands are != 0, as in that case the result can only
37665ffd83dbSDimitry Andric   // be 0, iff the multiplication overflows.
37675ffd83dbSDimitry Andric   if (match(&I,
37685ffd83dbSDimitry Andric             m_c_Or(m_CombineAnd(m_ExtractValue<1>(m_Value(UMulWithOv)),
37695ffd83dbSDimitry Andric                                 m_Value(Ov)),
37705ffd83dbSDimitry Andric                    m_CombineAnd(m_ICmp(Pred,
37715ffd83dbSDimitry Andric                                        m_CombineAnd(m_ExtractValue<0>(
37725ffd83dbSDimitry Andric                                                         m_Deferred(UMulWithOv)),
37735ffd83dbSDimitry Andric                                                     m_Value(Mul)),
37745ffd83dbSDimitry Andric                                        m_ZeroInt()),
37755ffd83dbSDimitry Andric                                 m_Value(MulIsNotZero)))) &&
37765ffd83dbSDimitry Andric       (Ov->hasOneUse() || (MulIsNotZero->hasOneUse() && Mul->hasOneUse())) &&
37775ffd83dbSDimitry Andric       Pred == CmpInst::ICMP_NE) {
37785ffd83dbSDimitry Andric     Value *A, *B;
37795ffd83dbSDimitry Andric     if (match(UMulWithOv, m_Intrinsic<Intrinsic::umul_with_overflow>(
37805ffd83dbSDimitry Andric                               m_Value(A), m_Value(B)))) {
37815ffd83dbSDimitry Andric       Value *NotNullA = Builder.CreateIsNotNull(A);
37825ffd83dbSDimitry Andric       Value *NotNullB = Builder.CreateIsNotNull(B);
37835ffd83dbSDimitry Andric       return BinaryOperator::CreateAnd(NotNullA, NotNullB);
37845ffd83dbSDimitry Andric     }
37855ffd83dbSDimitry Andric   }
37865ffd83dbSDimitry Andric 
37875f757f3fSDimitry Andric   /// Res, Overflow = xxx_with_overflow X, C1
37885f757f3fSDimitry Andric   /// Try to canonicalize the pattern "Overflow | icmp pred Res, C2" into
37895f757f3fSDimitry Andric   /// "Overflow | icmp pred X, C2 +/- C1".
37905f757f3fSDimitry Andric   const WithOverflowInst *WO;
37915f757f3fSDimitry Andric   const Value *WOV;
37925f757f3fSDimitry Andric   const APInt *C1, *C2;
37935f757f3fSDimitry Andric   if (match(&I, m_c_Or(m_CombineAnd(m_ExtractValue<1>(m_CombineAnd(
37945f757f3fSDimitry Andric                                         m_WithOverflowInst(WO), m_Value(WOV))),
37955f757f3fSDimitry Andric                                     m_Value(Ov)),
37965f757f3fSDimitry Andric                        m_OneUse(m_ICmp(Pred, m_ExtractValue<0>(m_Deferred(WOV)),
37975f757f3fSDimitry Andric                                        m_APInt(C2))))) &&
37985f757f3fSDimitry Andric       (WO->getBinaryOp() == Instruction::Add ||
37995f757f3fSDimitry Andric        WO->getBinaryOp() == Instruction::Sub) &&
38005f757f3fSDimitry Andric       (ICmpInst::isEquality(Pred) ||
38015f757f3fSDimitry Andric        WO->isSigned() == ICmpInst::isSigned(Pred)) &&
38025f757f3fSDimitry Andric       match(WO->getRHS(), m_APInt(C1))) {
38035f757f3fSDimitry Andric     bool Overflow;
38045f757f3fSDimitry Andric     APInt NewC = WO->getBinaryOp() == Instruction::Add
38055f757f3fSDimitry Andric                      ? (ICmpInst::isSigned(Pred) ? C2->ssub_ov(*C1, Overflow)
38065f757f3fSDimitry Andric                                                  : C2->usub_ov(*C1, Overflow))
38075f757f3fSDimitry Andric                      : (ICmpInst::isSigned(Pred) ? C2->sadd_ov(*C1, Overflow)
38085f757f3fSDimitry Andric                                                  : C2->uadd_ov(*C1, Overflow));
38095f757f3fSDimitry Andric     if (!Overflow || ICmpInst::isEquality(Pred)) {
38105f757f3fSDimitry Andric       Value *NewCmp = Builder.CreateICmp(
38115f757f3fSDimitry Andric           Pred, WO->getLHS(), ConstantInt::get(WO->getLHS()->getType(), NewC));
38125f757f3fSDimitry Andric       return BinaryOperator::CreateOr(Ov, NewCmp);
38135f757f3fSDimitry Andric     }
38145f757f3fSDimitry Andric   }
38155f757f3fSDimitry Andric 
3816e8d8bef9SDimitry Andric   // (~x) | y  -->  ~(x & (~y))  iff that gets rid of inversions
3817bdd1243dSDimitry Andric   if (sinkNotIntoOtherHandOfLogicalOp(I))
3818e8d8bef9SDimitry Andric     return &I;
3819e8d8bef9SDimitry Andric 
3820fe6060f1SDimitry Andric   // Improve "get low bit mask up to and including bit X" pattern:
3821fe6060f1SDimitry Andric   //   (1 << X) | ((1 << X) + -1)  -->  -1 l>> (bitwidth(x) - 1 - X)
3822fe6060f1SDimitry Andric   if (match(&I, m_c_Or(m_Add(m_Shl(m_One(), m_Value(X)), m_AllOnes()),
3823fe6060f1SDimitry Andric                        m_Shl(m_One(), m_Deferred(X)))) &&
3824fe6060f1SDimitry Andric       match(&I, m_c_Or(m_OneUse(m_Value()), m_Value()))) {
3825fe6060f1SDimitry Andric     Value *Sub = Builder.CreateSub(
3826fe6060f1SDimitry Andric         ConstantInt::get(Ty, Ty->getScalarSizeInBits() - 1), X);
3827fe6060f1SDimitry Andric     return BinaryOperator::CreateLShr(Constant::getAllOnesValue(Ty), Sub);
3828fe6060f1SDimitry Andric   }
3829fe6060f1SDimitry Andric 
3830fe6060f1SDimitry Andric   // An or recurrence w/loop invariant step is equivelent to (or start, step)
3831fe6060f1SDimitry Andric   PHINode *PN = nullptr;
3832fe6060f1SDimitry Andric   Value *Start = nullptr, *Step = nullptr;
3833fe6060f1SDimitry Andric   if (matchSimpleRecurrence(&I, PN, Start, Step) && DT.dominates(Step, PN))
3834fe6060f1SDimitry Andric     return replaceInstUsesWith(I, Builder.CreateOr(Start, Step));
3835fe6060f1SDimitry Andric 
383681ad6265SDimitry Andric   // (A & B) | (C | D) or (C | D) | (A & B)
383781ad6265SDimitry Andric   // Can be combined if C or D is of type (A/B & X)
383881ad6265SDimitry Andric   if (match(&I, m_c_Or(m_OneUse(m_And(m_Value(A), m_Value(B))),
383981ad6265SDimitry Andric                        m_OneUse(m_Or(m_Value(C), m_Value(D)))))) {
384081ad6265SDimitry Andric     // (A & B) | (C | ?) -> C | (? | (A & B))
384181ad6265SDimitry Andric     // (A & B) | (C | ?) -> C | (? | (A & B))
384281ad6265SDimitry Andric     // (A & B) | (C | ?) -> C | (? | (A & B))
384381ad6265SDimitry Andric     // (A & B) | (C | ?) -> C | (? | (A & B))
384481ad6265SDimitry Andric     // (C | ?) | (A & B) -> C | (? | (A & B))
384581ad6265SDimitry Andric     // (C | ?) | (A & B) -> C | (? | (A & B))
384681ad6265SDimitry Andric     // (C | ?) | (A & B) -> C | (? | (A & B))
384781ad6265SDimitry Andric     // (C | ?) | (A & B) -> C | (? | (A & B))
384881ad6265SDimitry Andric     if (match(D, m_OneUse(m_c_And(m_Specific(A), m_Value()))) ||
384981ad6265SDimitry Andric         match(D, m_OneUse(m_c_And(m_Specific(B), m_Value()))))
385081ad6265SDimitry Andric       return BinaryOperator::CreateOr(
385181ad6265SDimitry Andric           C, Builder.CreateOr(D, Builder.CreateAnd(A, B)));
385281ad6265SDimitry Andric     // (A & B) | (? | D) -> (? | (A & B)) | D
385381ad6265SDimitry Andric     // (A & B) | (? | D) -> (? | (A & B)) | D
385481ad6265SDimitry Andric     // (A & B) | (? | D) -> (? | (A & B)) | D
385581ad6265SDimitry Andric     // (A & B) | (? | D) -> (? | (A & B)) | D
385681ad6265SDimitry Andric     // (? | D) | (A & B) -> (? | (A & B)) | D
385781ad6265SDimitry Andric     // (? | D) | (A & B) -> (? | (A & B)) | D
385881ad6265SDimitry Andric     // (? | D) | (A & B) -> (? | (A & B)) | D
385981ad6265SDimitry Andric     // (? | D) | (A & B) -> (? | (A & B)) | D
386081ad6265SDimitry Andric     if (match(C, m_OneUse(m_c_And(m_Specific(A), m_Value()))) ||
386181ad6265SDimitry Andric         match(C, m_OneUse(m_c_And(m_Specific(B), m_Value()))))
386281ad6265SDimitry Andric       return BinaryOperator::CreateOr(
386381ad6265SDimitry Andric           Builder.CreateOr(C, Builder.CreateAnd(A, B)), D);
386481ad6265SDimitry Andric   }
386581ad6265SDimitry Andric 
3866bdd1243dSDimitry Andric   if (Instruction *R = reassociateForUses(I, Builder))
3867bdd1243dSDimitry Andric     return R;
3868bdd1243dSDimitry Andric 
3869bdd1243dSDimitry Andric   if (Instruction *Canonicalized = canonicalizeLogicFirst(I, Builder))
3870bdd1243dSDimitry Andric     return Canonicalized;
3871bdd1243dSDimitry Andric 
3872bdd1243dSDimitry Andric   if (Instruction *Folded = foldLogicOfIsFPClass(I, Op0, Op1))
3873bdd1243dSDimitry Andric     return Folded;
3874bdd1243dSDimitry Andric 
387506c3fb27SDimitry Andric   if (Instruction *Res = foldBinOpOfDisplacedShifts(I))
387606c3fb27SDimitry Andric     return Res;
387706c3fb27SDimitry Andric 
38785f757f3fSDimitry Andric   // If we are setting the sign bit of a floating-point value, convert
38795f757f3fSDimitry Andric   // this to fneg(fabs), then cast back to integer.
38805f757f3fSDimitry Andric   //
38815f757f3fSDimitry Andric   // If the result isn't immediately cast back to a float, this will increase
38825f757f3fSDimitry Andric   // the number of instructions. This is still probably a better canonical form
38835f757f3fSDimitry Andric   // as it enables FP value tracking.
38845f757f3fSDimitry Andric   //
38855f757f3fSDimitry Andric   // Assumes any IEEE-represented type has the sign bit in the high bit.
38865f757f3fSDimitry Andric   //
38875f757f3fSDimitry Andric   // This is generous interpretation of noimplicitfloat, this is not a true
38885f757f3fSDimitry Andric   // floating-point operation.
38895f757f3fSDimitry Andric   Value *CastOp;
38905f757f3fSDimitry Andric   if (match(Op0, m_BitCast(m_Value(CastOp))) && match(Op1, m_SignMask()) &&
38915f757f3fSDimitry Andric       !Builder.GetInsertBlock()->getParent()->hasFnAttribute(
38925f757f3fSDimitry Andric           Attribute::NoImplicitFloat)) {
38935f757f3fSDimitry Andric     Type *EltTy = CastOp->getType()->getScalarType();
38945f757f3fSDimitry Andric     if (EltTy->isFloatingPointTy() && EltTy->isIEEE() &&
38955f757f3fSDimitry Andric         EltTy->getPrimitiveSizeInBits() ==
38965f757f3fSDimitry Andric         I.getType()->getScalarType()->getPrimitiveSizeInBits()) {
38975f757f3fSDimitry Andric       Value *FAbs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, CastOp);
38985f757f3fSDimitry Andric       Value *FNegFAbs = Builder.CreateFNeg(FAbs);
38995f757f3fSDimitry Andric       return new BitCastInst(FNegFAbs, I.getType());
39005f757f3fSDimitry Andric     }
39015f757f3fSDimitry Andric   }
39025f757f3fSDimitry Andric 
3903647cbc5dSDimitry Andric   // (X & C1) | C2 -> X & (C1 | C2) iff (X & C2) == C2
3904647cbc5dSDimitry Andric   if (match(Op0, m_OneUse(m_And(m_Value(X), m_APInt(C1)))) &&
3905647cbc5dSDimitry Andric       match(Op1, m_APInt(C2))) {
3906647cbc5dSDimitry Andric     KnownBits KnownX = computeKnownBits(X, /*Depth*/ 0, &I);
3907647cbc5dSDimitry Andric     if ((KnownX.One & *C2) == *C2)
3908647cbc5dSDimitry Andric       return BinaryOperator::CreateAnd(X, ConstantInt::get(Ty, *C1 | *C2));
3909647cbc5dSDimitry Andric   }
3910647cbc5dSDimitry Andric 
3911297eecfbSDimitry Andric   if (Instruction *Res = foldBitwiseLogicWithIntrinsics(I, Builder))
3912297eecfbSDimitry Andric     return Res;
3913297eecfbSDimitry Andric 
39140b57cec5SDimitry Andric   return nullptr;
39150b57cec5SDimitry Andric }
39160b57cec5SDimitry Andric 
39170b57cec5SDimitry Andric /// A ^ B can be specified using other logic ops in a variety of patterns. We
39180b57cec5SDimitry Andric /// can fold these early and efficiently by morphing an existing instruction.
foldXorToXor(BinaryOperator & I,InstCombiner::BuilderTy & Builder)39190b57cec5SDimitry Andric static Instruction *foldXorToXor(BinaryOperator &I,
39200b57cec5SDimitry Andric                                  InstCombiner::BuilderTy &Builder) {
39210b57cec5SDimitry Andric   assert(I.getOpcode() == Instruction::Xor);
39220b57cec5SDimitry Andric   Value *Op0 = I.getOperand(0);
39230b57cec5SDimitry Andric   Value *Op1 = I.getOperand(1);
39240b57cec5SDimitry Andric   Value *A, *B;
39250b57cec5SDimitry Andric 
39260b57cec5SDimitry Andric   // There are 4 commuted variants for each of the basic patterns.
39270b57cec5SDimitry Andric 
39280b57cec5SDimitry Andric   // (A & B) ^ (A | B) -> A ^ B
39290b57cec5SDimitry Andric   // (A & B) ^ (B | A) -> A ^ B
39300b57cec5SDimitry Andric   // (A | B) ^ (A & B) -> A ^ B
39310b57cec5SDimitry Andric   // (A | B) ^ (B & A) -> A ^ B
39320b57cec5SDimitry Andric   if (match(&I, m_c_Xor(m_And(m_Value(A), m_Value(B)),
39335ffd83dbSDimitry Andric                         m_c_Or(m_Deferred(A), m_Deferred(B)))))
39345ffd83dbSDimitry Andric     return BinaryOperator::CreateXor(A, B);
39350b57cec5SDimitry Andric 
39360b57cec5SDimitry Andric   // (A | ~B) ^ (~A | B) -> A ^ B
39370b57cec5SDimitry Andric   // (~B | A) ^ (~A | B) -> A ^ B
39380b57cec5SDimitry Andric   // (~A | B) ^ (A | ~B) -> A ^ B
39390b57cec5SDimitry Andric   // (B | ~A) ^ (A | ~B) -> A ^ B
39400b57cec5SDimitry Andric   if (match(&I, m_Xor(m_c_Or(m_Value(A), m_Not(m_Value(B))),
39415ffd83dbSDimitry Andric                       m_c_Or(m_Not(m_Deferred(A)), m_Deferred(B)))))
39425ffd83dbSDimitry Andric     return BinaryOperator::CreateXor(A, B);
39430b57cec5SDimitry Andric 
39440b57cec5SDimitry Andric   // (A & ~B) ^ (~A & B) -> A ^ B
39450b57cec5SDimitry Andric   // (~B & A) ^ (~A & B) -> A ^ B
39460b57cec5SDimitry Andric   // (~A & B) ^ (A & ~B) -> A ^ B
39470b57cec5SDimitry Andric   // (B & ~A) ^ (A & ~B) -> A ^ B
39480b57cec5SDimitry Andric   if (match(&I, m_Xor(m_c_And(m_Value(A), m_Not(m_Value(B))),
39495ffd83dbSDimitry Andric                       m_c_And(m_Not(m_Deferred(A)), m_Deferred(B)))))
39505ffd83dbSDimitry Andric     return BinaryOperator::CreateXor(A, B);
39510b57cec5SDimitry Andric 
39520b57cec5SDimitry Andric   // For the remaining cases we need to get rid of one of the operands.
39530b57cec5SDimitry Andric   if (!Op0->hasOneUse() && !Op1->hasOneUse())
39540b57cec5SDimitry Andric     return nullptr;
39550b57cec5SDimitry Andric 
39560b57cec5SDimitry Andric   // (A | B) ^ ~(A & B) -> ~(A ^ B)
39570b57cec5SDimitry Andric   // (A | B) ^ ~(B & A) -> ~(A ^ B)
39580b57cec5SDimitry Andric   // (A & B) ^ ~(A | B) -> ~(A ^ B)
39590b57cec5SDimitry Andric   // (A & B) ^ ~(B | A) -> ~(A ^ B)
39600b57cec5SDimitry Andric   // Complexity sorting ensures the not will be on the right side.
39610b57cec5SDimitry Andric   if ((match(Op0, m_Or(m_Value(A), m_Value(B))) &&
39620b57cec5SDimitry Andric        match(Op1, m_Not(m_c_And(m_Specific(A), m_Specific(B))))) ||
39630b57cec5SDimitry Andric       (match(Op0, m_And(m_Value(A), m_Value(B))) &&
39640b57cec5SDimitry Andric        match(Op1, m_Not(m_c_Or(m_Specific(A), m_Specific(B))))))
39650b57cec5SDimitry Andric     return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
39660b57cec5SDimitry Andric 
39670b57cec5SDimitry Andric   return nullptr;
39680b57cec5SDimitry Andric }
39690b57cec5SDimitry Andric 
foldXorOfICmps(ICmpInst * LHS,ICmpInst * RHS,BinaryOperator & I)3970e8d8bef9SDimitry Andric Value *InstCombinerImpl::foldXorOfICmps(ICmpInst *LHS, ICmpInst *RHS,
39718bcb0991SDimitry Andric                                         BinaryOperator &I) {
39728bcb0991SDimitry Andric   assert(I.getOpcode() == Instruction::Xor && I.getOperand(0) == LHS &&
39738bcb0991SDimitry Andric          I.getOperand(1) == RHS && "Should be 'xor' with these operands");
39748bcb0991SDimitry Andric 
397581ad6265SDimitry Andric   ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
397681ad6265SDimitry Andric   Value *LHS0 = LHS->getOperand(0), *LHS1 = LHS->getOperand(1);
397781ad6265SDimitry Andric   Value *RHS0 = RHS->getOperand(0), *RHS1 = RHS->getOperand(1);
397881ad6265SDimitry Andric 
397981ad6265SDimitry Andric   if (predicatesFoldable(PredL, PredR)) {
398081ad6265SDimitry Andric     if (LHS0 == RHS1 && LHS1 == RHS0) {
398181ad6265SDimitry Andric       std::swap(LHS0, LHS1);
398281ad6265SDimitry Andric       PredL = ICmpInst::getSwappedPredicate(PredL);
398381ad6265SDimitry Andric     }
398481ad6265SDimitry Andric     if (LHS0 == RHS0 && LHS1 == RHS1) {
39850b57cec5SDimitry Andric       // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
398681ad6265SDimitry Andric       unsigned Code = getICmpCode(PredL) ^ getICmpCode(PredR);
39870b57cec5SDimitry Andric       bool IsSigned = LHS->isSigned() || RHS->isSigned();
398881ad6265SDimitry Andric       return getNewICmpValue(Code, IsSigned, LHS0, LHS1, Builder);
39890b57cec5SDimitry Andric     }
39900b57cec5SDimitry Andric   }
39910b57cec5SDimitry Andric 
39920b57cec5SDimitry Andric   // TODO: This can be generalized to compares of non-signbits using
39930b57cec5SDimitry Andric   // decomposeBitTestICmp(). It could be enhanced more by using (something like)
39940b57cec5SDimitry Andric   // foldLogOpOfMaskedICmps().
3995fcaf7f86SDimitry Andric   const APInt *LC, *RC;
3996fcaf7f86SDimitry Andric   if (match(LHS1, m_APInt(LC)) && match(RHS1, m_APInt(RC)) &&
39970b57cec5SDimitry Andric       LHS0->getType() == RHS0->getType() &&
3998cb14a3feSDimitry Andric       LHS0->getType()->isIntOrIntVectorTy()) {
3999fcaf7f86SDimitry Andric     // Convert xor of signbit tests to signbit test of xor'd values:
40000b57cec5SDimitry Andric     // (X > -1) ^ (Y > -1) --> (X ^ Y) < 0
40010b57cec5SDimitry Andric     // (X <  0) ^ (Y <  0) --> (X ^ Y) < 0
40020b57cec5SDimitry Andric     // (X > -1) ^ (Y <  0) --> (X ^ Y) > -1
40030b57cec5SDimitry Andric     // (X <  0) ^ (Y > -1) --> (X ^ Y) > -1
4004fcaf7f86SDimitry Andric     bool TrueIfSignedL, TrueIfSignedR;
4005cb14a3feSDimitry Andric     if ((LHS->hasOneUse() || RHS->hasOneUse()) &&
4006cb14a3feSDimitry Andric         isSignBitCheck(PredL, *LC, TrueIfSignedL) &&
4007fcaf7f86SDimitry Andric         isSignBitCheck(PredR, *RC, TrueIfSignedR)) {
4008fcaf7f86SDimitry Andric       Value *XorLR = Builder.CreateXor(LHS0, RHS0);
4009fcaf7f86SDimitry Andric       return TrueIfSignedL == TrueIfSignedR ? Builder.CreateIsNeg(XorLR) :
4010fcaf7f86SDimitry Andric                                               Builder.CreateIsNotNeg(XorLR);
4011fcaf7f86SDimitry Andric     }
401281ad6265SDimitry Andric 
4013cb14a3feSDimitry Andric     // Fold (icmp pred1 X, C1) ^ (icmp pred2 X, C2)
4014cb14a3feSDimitry Andric     // into a single comparison using range-based reasoning.
4015cb14a3feSDimitry Andric     if (LHS0 == RHS0) {
4016cb14a3feSDimitry Andric       ConstantRange CR1 = ConstantRange::makeExactICmpRegion(PredL, *LC);
4017cb14a3feSDimitry Andric       ConstantRange CR2 = ConstantRange::makeExactICmpRegion(PredR, *RC);
4018cb14a3feSDimitry Andric       auto CRUnion = CR1.exactUnionWith(CR2);
4019cb14a3feSDimitry Andric       auto CRIntersect = CR1.exactIntersectWith(CR2);
4020cb14a3feSDimitry Andric       if (CRUnion && CRIntersect)
4021cb14a3feSDimitry Andric         if (auto CR = CRUnion->exactIntersectWith(CRIntersect->inverse())) {
4022cb14a3feSDimitry Andric           if (CR->isFullSet())
4023cb14a3feSDimitry Andric             return ConstantInt::getTrue(I.getType());
4024cb14a3feSDimitry Andric           if (CR->isEmptySet())
4025cb14a3feSDimitry Andric             return ConstantInt::getFalse(I.getType());
4026cb14a3feSDimitry Andric 
4027cb14a3feSDimitry Andric           CmpInst::Predicate NewPred;
4028cb14a3feSDimitry Andric           APInt NewC, Offset;
4029cb14a3feSDimitry Andric           CR->getEquivalentICmp(NewPred, NewC, Offset);
4030cb14a3feSDimitry Andric 
4031cb14a3feSDimitry Andric           if ((Offset.isZero() && (LHS->hasOneUse() || RHS->hasOneUse())) ||
4032cb14a3feSDimitry Andric               (LHS->hasOneUse() && RHS->hasOneUse())) {
4033cb14a3feSDimitry Andric             Value *NewV = LHS0;
4034cb14a3feSDimitry Andric             Type *Ty = LHS0->getType();
4035cb14a3feSDimitry Andric             if (!Offset.isZero())
4036cb14a3feSDimitry Andric               NewV = Builder.CreateAdd(NewV, ConstantInt::get(Ty, Offset));
4037cb14a3feSDimitry Andric             return Builder.CreateICmp(NewPred, NewV,
4038cb14a3feSDimitry Andric                                       ConstantInt::get(Ty, NewC));
4039cb14a3feSDimitry Andric           }
4040cb14a3feSDimitry Andric         }
4041cb14a3feSDimitry Andric     }
40420b57cec5SDimitry Andric   }
40430b57cec5SDimitry Andric 
40440b57cec5SDimitry Andric   // Instead of trying to imitate the folds for and/or, decompose this 'xor'
40450b57cec5SDimitry Andric   // into those logic ops. That is, try to turn this into an and-of-icmps
40460b57cec5SDimitry Andric   // because we have many folds for that pattern.
40470b57cec5SDimitry Andric   //
40480b57cec5SDimitry Andric   // This is based on a truth table definition of xor:
40490b57cec5SDimitry Andric   // X ^ Y --> (X | Y) & !(X & Y)
405081ad6265SDimitry Andric   if (Value *OrICmp = simplifyBinOp(Instruction::Or, LHS, RHS, SQ)) {
40510b57cec5SDimitry Andric     // TODO: If OrICmp is true, then the definition of xor simplifies to !(X&Y).
40520b57cec5SDimitry Andric     // TODO: If OrICmp is false, the whole thing is false (InstSimplify?).
405381ad6265SDimitry Andric     if (Value *AndICmp = simplifyBinOp(Instruction::And, LHS, RHS, SQ)) {
40540b57cec5SDimitry Andric       // TODO: Independently handle cases where the 'and' side is a constant.
40558bcb0991SDimitry Andric       ICmpInst *X = nullptr, *Y = nullptr;
40568bcb0991SDimitry Andric       if (OrICmp == LHS && AndICmp == RHS) {
40578bcb0991SDimitry Andric         // (LHS | RHS) & !(LHS & RHS) --> LHS & !RHS  --> X & !Y
40588bcb0991SDimitry Andric         X = LHS;
40598bcb0991SDimitry Andric         Y = RHS;
40600b57cec5SDimitry Andric       }
40618bcb0991SDimitry Andric       if (OrICmp == RHS && AndICmp == LHS) {
40628bcb0991SDimitry Andric         // !(LHS & RHS) & (LHS | RHS) --> !LHS & RHS  --> !Y & X
40638bcb0991SDimitry Andric         X = RHS;
40648bcb0991SDimitry Andric         Y = LHS;
40658bcb0991SDimitry Andric       }
40668bcb0991SDimitry Andric       if (X && Y && (Y->hasOneUse() || canFreelyInvertAllUsersOf(Y, &I))) {
40678bcb0991SDimitry Andric         // Invert the predicate of 'Y', thus inverting its output.
40688bcb0991SDimitry Andric         Y->setPredicate(Y->getInversePredicate());
40698bcb0991SDimitry Andric         // So, are there other uses of Y?
40708bcb0991SDimitry Andric         if (!Y->hasOneUse()) {
40718bcb0991SDimitry Andric           // We need to adapt other uses of Y though. Get a value that matches
40728bcb0991SDimitry Andric           // the original value of Y before inversion. While this increases
40738bcb0991SDimitry Andric           // immediate instruction count, we have just ensured that all the
40748bcb0991SDimitry Andric           // users are freely-invertible, so that 'not' *will* get folded away.
40758bcb0991SDimitry Andric           BuilderTy::InsertPointGuard Guard(Builder);
40768bcb0991SDimitry Andric           // Set insertion point to right after the Y.
40778bcb0991SDimitry Andric           Builder.SetInsertPoint(Y->getParent(), ++(Y->getIterator()));
40788bcb0991SDimitry Andric           Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
40798bcb0991SDimitry Andric           // Replace all uses of Y (excluding the one in NotY!) with NotY.
40805ffd83dbSDimitry Andric           Worklist.pushUsersToWorkList(*Y);
40818bcb0991SDimitry Andric           Y->replaceUsesWithIf(NotY,
40828bcb0991SDimitry Andric                                [NotY](Use &U) { return U.getUser() != NotY; });
40838bcb0991SDimitry Andric         }
40848bcb0991SDimitry Andric         // All done.
40850b57cec5SDimitry Andric         return Builder.CreateAnd(LHS, RHS);
40860b57cec5SDimitry Andric       }
40870b57cec5SDimitry Andric     }
40880b57cec5SDimitry Andric   }
40890b57cec5SDimitry Andric 
40900b57cec5SDimitry Andric   return nullptr;
40910b57cec5SDimitry Andric }
40920b57cec5SDimitry Andric 
40930b57cec5SDimitry Andric /// If we have a masked merge, in the canonical form of:
40940b57cec5SDimitry Andric /// (assuming that A only has one use.)
40950b57cec5SDimitry Andric ///   |        A  |  |B|
40960b57cec5SDimitry Andric ///   ((x ^ y) & M) ^ y
40970b57cec5SDimitry Andric ///    |  D  |
40980b57cec5SDimitry Andric /// * If M is inverted:
40990b57cec5SDimitry Andric ///      |  D  |
41000b57cec5SDimitry Andric ///     ((x ^ y) & ~M) ^ y
41010b57cec5SDimitry Andric ///   We can canonicalize by swapping the final xor operand
41020b57cec5SDimitry Andric ///   to eliminate the 'not' of the mask.
41030b57cec5SDimitry Andric ///     ((x ^ y) & M) ^ x
41040b57cec5SDimitry Andric /// * If M is a constant, and D has one use, we transform to 'and' / 'or' ops
41050b57cec5SDimitry Andric ///   because that shortens the dependency chain and improves analysis:
41060b57cec5SDimitry Andric ///     (x & M) | (y & ~M)
visitMaskedMerge(BinaryOperator & I,InstCombiner::BuilderTy & Builder)41070b57cec5SDimitry Andric static Instruction *visitMaskedMerge(BinaryOperator &I,
41080b57cec5SDimitry Andric                                      InstCombiner::BuilderTy &Builder) {
41090b57cec5SDimitry Andric   Value *B, *X, *D;
41100b57cec5SDimitry Andric   Value *M;
41110b57cec5SDimitry Andric   if (!match(&I, m_c_Xor(m_Value(B),
41120b57cec5SDimitry Andric                          m_OneUse(m_c_And(
41130b57cec5SDimitry Andric                              m_CombineAnd(m_c_Xor(m_Deferred(B), m_Value(X)),
41140b57cec5SDimitry Andric                                           m_Value(D)),
41150b57cec5SDimitry Andric                              m_Value(M))))))
41160b57cec5SDimitry Andric     return nullptr;
41170b57cec5SDimitry Andric 
41180b57cec5SDimitry Andric   Value *NotM;
41190b57cec5SDimitry Andric   if (match(M, m_Not(m_Value(NotM)))) {
41200b57cec5SDimitry Andric     // De-invert the mask and swap the value in B part.
41210b57cec5SDimitry Andric     Value *NewA = Builder.CreateAnd(D, NotM);
41220b57cec5SDimitry Andric     return BinaryOperator::CreateXor(NewA, X);
41230b57cec5SDimitry Andric   }
41240b57cec5SDimitry Andric 
41250b57cec5SDimitry Andric   Constant *C;
41260b57cec5SDimitry Andric   if (D->hasOneUse() && match(M, m_Constant(C))) {
41275ffd83dbSDimitry Andric     // Propagating undef is unsafe. Clamp undef elements to -1.
41285ffd83dbSDimitry Andric     Type *EltTy = C->getType()->getScalarType();
41295ffd83dbSDimitry Andric     C = Constant::replaceUndefsWith(C, ConstantInt::getAllOnesValue(EltTy));
41300b57cec5SDimitry Andric     // Unfold.
41310b57cec5SDimitry Andric     Value *LHS = Builder.CreateAnd(X, C);
41320b57cec5SDimitry Andric     Value *NotC = Builder.CreateNot(C);
41330b57cec5SDimitry Andric     Value *RHS = Builder.CreateAnd(B, NotC);
41340b57cec5SDimitry Andric     return BinaryOperator::CreateOr(LHS, RHS);
41350b57cec5SDimitry Andric   }
41360b57cec5SDimitry Andric 
41370b57cec5SDimitry Andric   return nullptr;
41380b57cec5SDimitry Andric }
41390b57cec5SDimitry Andric 
foldNotXor(BinaryOperator & I,InstCombiner::BuilderTy & Builder)4140bdd1243dSDimitry Andric static Instruction *foldNotXor(BinaryOperator &I,
4141bdd1243dSDimitry Andric                                InstCombiner::BuilderTy &Builder) {
4142bdd1243dSDimitry Andric   Value *X, *Y;
4143bdd1243dSDimitry Andric   // FIXME: one-use check is not needed in general, but currently we are unable
4144bdd1243dSDimitry Andric   // to fold 'not' into 'icmp', if that 'icmp' has multiple uses. (D35182)
4145bdd1243dSDimitry Andric   if (!match(&I, m_Not(m_OneUse(m_Xor(m_Value(X), m_Value(Y))))))
4146bdd1243dSDimitry Andric     return nullptr;
4147bdd1243dSDimitry Andric 
4148bdd1243dSDimitry Andric   auto hasCommonOperand = [](Value *A, Value *B, Value *C, Value *D) {
4149bdd1243dSDimitry Andric     return A == C || A == D || B == C || B == D;
4150bdd1243dSDimitry Andric   };
4151bdd1243dSDimitry Andric 
4152bdd1243dSDimitry Andric   Value *A, *B, *C, *D;
4153bdd1243dSDimitry Andric   // Canonicalize ~((A & B) ^ (A | ?)) -> (A & B) | ~(A | ?)
4154bdd1243dSDimitry Andric   // 4 commuted variants
4155bdd1243dSDimitry Andric   if (match(X, m_And(m_Value(A), m_Value(B))) &&
4156bdd1243dSDimitry Andric       match(Y, m_Or(m_Value(C), m_Value(D))) && hasCommonOperand(A, B, C, D)) {
4157bdd1243dSDimitry Andric     Value *NotY = Builder.CreateNot(Y);
4158bdd1243dSDimitry Andric     return BinaryOperator::CreateOr(X, NotY);
4159bdd1243dSDimitry Andric   };
4160bdd1243dSDimitry Andric 
4161bdd1243dSDimitry Andric   // Canonicalize ~((A | ?) ^ (A & B)) -> (A & B) | ~(A | ?)
4162bdd1243dSDimitry Andric   // 4 commuted variants
4163bdd1243dSDimitry Andric   if (match(Y, m_And(m_Value(A), m_Value(B))) &&
4164bdd1243dSDimitry Andric       match(X, m_Or(m_Value(C), m_Value(D))) && hasCommonOperand(A, B, C, D)) {
4165bdd1243dSDimitry Andric     Value *NotX = Builder.CreateNot(X);
4166bdd1243dSDimitry Andric     return BinaryOperator::CreateOr(Y, NotX);
4167bdd1243dSDimitry Andric   };
4168bdd1243dSDimitry Andric 
4169bdd1243dSDimitry Andric   return nullptr;
4170bdd1243dSDimitry Andric }
4171bdd1243dSDimitry Andric 
4172fe6060f1SDimitry Andric /// Canonicalize a shifty way to code absolute value to the more common pattern
4173fe6060f1SDimitry Andric /// that uses negation and select.
canonicalizeAbs(BinaryOperator & Xor,InstCombiner::BuilderTy & Builder)4174fe6060f1SDimitry Andric static Instruction *canonicalizeAbs(BinaryOperator &Xor,
4175fe6060f1SDimitry Andric                                     InstCombiner::BuilderTy &Builder) {
4176fe6060f1SDimitry Andric   assert(Xor.getOpcode() == Instruction::Xor && "Expected an xor instruction.");
4177fe6060f1SDimitry Andric 
4178fe6060f1SDimitry Andric   // There are 4 potential commuted variants. Move the 'ashr' candidate to Op1.
4179fe6060f1SDimitry Andric   // We're relying on the fact that we only do this transform when the shift has
4180fe6060f1SDimitry Andric   // exactly 2 uses and the add has exactly 1 use (otherwise, we might increase
4181fe6060f1SDimitry Andric   // instructions).
4182fe6060f1SDimitry Andric   Value *Op0 = Xor.getOperand(0), *Op1 = Xor.getOperand(1);
4183fe6060f1SDimitry Andric   if (Op0->hasNUses(2))
4184fe6060f1SDimitry Andric     std::swap(Op0, Op1);
4185fe6060f1SDimitry Andric 
4186fe6060f1SDimitry Andric   Type *Ty = Xor.getType();
4187fe6060f1SDimitry Andric   Value *A;
4188fe6060f1SDimitry Andric   const APInt *ShAmt;
4189fe6060f1SDimitry Andric   if (match(Op1, m_AShr(m_Value(A), m_APInt(ShAmt))) &&
4190fe6060f1SDimitry Andric       Op1->hasNUses(2) && *ShAmt == Ty->getScalarSizeInBits() - 1 &&
4191fe6060f1SDimitry Andric       match(Op0, m_OneUse(m_c_Add(m_Specific(A), m_Specific(Op1))))) {
4192fe6060f1SDimitry Andric     // Op1 = ashr i32 A, 31   ; smear the sign bit
4193fe6060f1SDimitry Andric     // xor (add A, Op1), Op1  ; add -1 and flip bits if negative
4194fe6060f1SDimitry Andric     // --> (A < 0) ? -A : A
419581ad6265SDimitry Andric     Value *IsNeg = Builder.CreateIsNeg(A);
4196fe6060f1SDimitry Andric     // Copy the nuw/nsw flags from the add to the negate.
4197fe6060f1SDimitry Andric     auto *Add = cast<BinaryOperator>(Op0);
419881ad6265SDimitry Andric     Value *NegA = Builder.CreateNeg(A, "", Add->hasNoUnsignedWrap(),
4199fe6060f1SDimitry Andric                                    Add->hasNoSignedWrap());
420081ad6265SDimitry Andric     return SelectInst::Create(IsNeg, NegA, A);
4201fe6060f1SDimitry Andric   }
4202fe6060f1SDimitry Andric   return nullptr;
4203fe6060f1SDimitry Andric }
4204fe6060f1SDimitry Andric 
canFreelyInvert(InstCombiner & IC,Value * Op,Instruction * IgnoredUser)420506c3fb27SDimitry Andric static bool canFreelyInvert(InstCombiner &IC, Value *Op,
420606c3fb27SDimitry Andric                             Instruction *IgnoredUser) {
420706c3fb27SDimitry Andric   auto *I = dyn_cast<Instruction>(Op);
420806c3fb27SDimitry Andric   return I && IC.isFreeToInvert(I, /*WillInvertAllUses=*/true) &&
42095f757f3fSDimitry Andric          IC.canFreelyInvertAllUsersOf(I, IgnoredUser);
421006c3fb27SDimitry Andric }
421106c3fb27SDimitry Andric 
freelyInvert(InstCombinerImpl & IC,Value * Op,Instruction * IgnoredUser)421206c3fb27SDimitry Andric static Value *freelyInvert(InstCombinerImpl &IC, Value *Op,
421306c3fb27SDimitry Andric                            Instruction *IgnoredUser) {
421406c3fb27SDimitry Andric   auto *I = cast<Instruction>(Op);
42155f757f3fSDimitry Andric   IC.Builder.SetInsertPoint(*I->getInsertionPointAfterDef());
421606c3fb27SDimitry Andric   Value *NotOp = IC.Builder.CreateNot(Op, Op->getName() + ".not");
421706c3fb27SDimitry Andric   Op->replaceUsesWithIf(NotOp,
421806c3fb27SDimitry Andric                         [NotOp](Use &U) { return U.getUser() != NotOp; });
421906c3fb27SDimitry Andric   IC.freelyInvertAllUsersOf(NotOp, IgnoredUser);
422006c3fb27SDimitry Andric   return NotOp;
422106c3fb27SDimitry Andric }
422206c3fb27SDimitry Andric 
4223e8d8bef9SDimitry Andric // Transform
4224bdd1243dSDimitry Andric //   z = ~(x &/| y)
4225bdd1243dSDimitry Andric // into:
4226bdd1243dSDimitry Andric //   z = ((~x) |/& (~y))
4227bdd1243dSDimitry Andric // iff both x and y are free to invert and all uses of z can be freely updated.
sinkNotIntoLogicalOp(Instruction & I)4228bdd1243dSDimitry Andric bool InstCombinerImpl::sinkNotIntoLogicalOp(Instruction &I) {
4229bdd1243dSDimitry Andric   Value *Op0, *Op1;
4230bdd1243dSDimitry Andric   if (!match(&I, m_LogicalOp(m_Value(Op0), m_Value(Op1))))
4231bdd1243dSDimitry Andric     return false;
4232bdd1243dSDimitry Andric 
4233bdd1243dSDimitry Andric   // If this logic op has not been simplified yet, just bail out and let that
4234bdd1243dSDimitry Andric   // happen first. Otherwise, the code below may wrongly invert.
4235bdd1243dSDimitry Andric   if (Op0 == Op1)
4236bdd1243dSDimitry Andric     return false;
4237bdd1243dSDimitry Andric 
4238bdd1243dSDimitry Andric   Instruction::BinaryOps NewOpc =
4239bdd1243dSDimitry Andric       match(&I, m_LogicalAnd()) ? Instruction::Or : Instruction::And;
4240bdd1243dSDimitry Andric   bool IsBinaryOp = isa<BinaryOperator>(I);
4241bdd1243dSDimitry Andric 
4242bdd1243dSDimitry Andric   // Can our users be adapted?
4243bdd1243dSDimitry Andric   if (!InstCombiner::canFreelyInvertAllUsersOf(&I, /*IgnoredUser=*/nullptr))
4244bdd1243dSDimitry Andric     return false;
4245bdd1243dSDimitry Andric 
4246bdd1243dSDimitry Andric   // And can the operands be adapted?
424706c3fb27SDimitry Andric   if (!canFreelyInvert(*this, Op0, &I) || !canFreelyInvert(*this, Op1, &I))
4248bdd1243dSDimitry Andric     return false;
4249bdd1243dSDimitry Andric 
425006c3fb27SDimitry Andric   Op0 = freelyInvert(*this, Op0, &I);
425106c3fb27SDimitry Andric   Op1 = freelyInvert(*this, Op1, &I);
4252bdd1243dSDimitry Andric 
42535f757f3fSDimitry Andric   Builder.SetInsertPoint(*I.getInsertionPointAfterDef());
4254bdd1243dSDimitry Andric   Value *NewLogicOp;
4255bdd1243dSDimitry Andric   if (IsBinaryOp)
4256bdd1243dSDimitry Andric     NewLogicOp = Builder.CreateBinOp(NewOpc, Op0, Op1, I.getName() + ".not");
4257bdd1243dSDimitry Andric   else
4258bdd1243dSDimitry Andric     NewLogicOp =
4259bdd1243dSDimitry Andric         Builder.CreateLogicalOp(NewOpc, Op0, Op1, I.getName() + ".not");
4260bdd1243dSDimitry Andric 
4261bdd1243dSDimitry Andric   replaceInstUsesWith(I, NewLogicOp);
4262bdd1243dSDimitry Andric   // We can not just create an outer `not`, it will most likely be immediately
4263bdd1243dSDimitry Andric   // folded back, reconstructing our initial pattern, and causing an
4264bdd1243dSDimitry Andric   // infinite combine loop, so immediately manually fold it away.
4265bdd1243dSDimitry Andric   freelyInvertAllUsersOf(NewLogicOp);
4266bdd1243dSDimitry Andric   return true;
4267bdd1243dSDimitry Andric }
4268bdd1243dSDimitry Andric 
4269bdd1243dSDimitry Andric // Transform
4270e8d8bef9SDimitry Andric //   z = (~x) &/| y
4271e8d8bef9SDimitry Andric // into:
4272e8d8bef9SDimitry Andric //   z = ~(x |/& (~y))
4273e8d8bef9SDimitry Andric // iff y is free to invert and all uses of z can be freely updated.
sinkNotIntoOtherHandOfLogicalOp(Instruction & I)4274bdd1243dSDimitry Andric bool InstCombinerImpl::sinkNotIntoOtherHandOfLogicalOp(Instruction &I) {
4275bdd1243dSDimitry Andric   Value *Op0, *Op1;
4276bdd1243dSDimitry Andric   if (!match(&I, m_LogicalOp(m_Value(Op0), m_Value(Op1))))
4277e8d8bef9SDimitry Andric     return false;
4278bdd1243dSDimitry Andric   Instruction::BinaryOps NewOpc =
4279bdd1243dSDimitry Andric       match(&I, m_LogicalAnd()) ? Instruction::Or : Instruction::And;
4280bdd1243dSDimitry Andric   bool IsBinaryOp = isa<BinaryOperator>(I);
4281e8d8bef9SDimitry Andric 
4282bdd1243dSDimitry Andric   Value *NotOp0 = nullptr;
4283bdd1243dSDimitry Andric   Value *NotOp1 = nullptr;
4284bdd1243dSDimitry Andric   Value **OpToInvert = nullptr;
428506c3fb27SDimitry Andric   if (match(Op0, m_Not(m_Value(NotOp0))) && canFreelyInvert(*this, Op1, &I)) {
4286bdd1243dSDimitry Andric     Op0 = NotOp0;
4287bdd1243dSDimitry Andric     OpToInvert = &Op1;
4288bdd1243dSDimitry Andric   } else if (match(Op1, m_Not(m_Value(NotOp1))) &&
428906c3fb27SDimitry Andric              canFreelyInvert(*this, Op0, &I)) {
4290bdd1243dSDimitry Andric     Op1 = NotOp1;
4291bdd1243dSDimitry Andric     OpToInvert = &Op0;
4292bdd1243dSDimitry Andric   } else
4293e8d8bef9SDimitry Andric     return false;
4294e8d8bef9SDimitry Andric 
4295e8d8bef9SDimitry Andric   // And can our users be adapted?
4296e8d8bef9SDimitry Andric   if (!InstCombiner::canFreelyInvertAllUsersOf(&I, /*IgnoredUser=*/nullptr))
4297e8d8bef9SDimitry Andric     return false;
4298e8d8bef9SDimitry Andric 
429906c3fb27SDimitry Andric   *OpToInvert = freelyInvert(*this, *OpToInvert, &I);
4300bdd1243dSDimitry Andric 
43015f757f3fSDimitry Andric   Builder.SetInsertPoint(*I.getInsertionPointAfterDef());
4302bdd1243dSDimitry Andric   Value *NewBinOp;
4303bdd1243dSDimitry Andric   if (IsBinaryOp)
4304bdd1243dSDimitry Andric     NewBinOp = Builder.CreateBinOp(NewOpc, Op0, Op1, I.getName() + ".not");
4305bdd1243dSDimitry Andric   else
4306bdd1243dSDimitry Andric     NewBinOp = Builder.CreateLogicalOp(NewOpc, Op0, Op1, I.getName() + ".not");
4307e8d8bef9SDimitry Andric   replaceInstUsesWith(I, NewBinOp);
4308e8d8bef9SDimitry Andric   // We can not just create an outer `not`, it will most likely be immediately
4309e8d8bef9SDimitry Andric   // folded back, reconstructing our initial pattern, and causing an
4310e8d8bef9SDimitry Andric   // infinite combine loop, so immediately manually fold it away.
4311e8d8bef9SDimitry Andric   freelyInvertAllUsersOf(NewBinOp);
4312e8d8bef9SDimitry Andric   return true;
4313e8d8bef9SDimitry Andric }
4314e8d8bef9SDimitry Andric 
foldNot(BinaryOperator & I)4315349cc55cSDimitry Andric Instruction *InstCombinerImpl::foldNot(BinaryOperator &I) {
4316349cc55cSDimitry Andric   Value *NotOp;
4317349cc55cSDimitry Andric   if (!match(&I, m_Not(m_Value(NotOp))))
4318349cc55cSDimitry Andric     return nullptr;
43190b57cec5SDimitry Andric 
43200b57cec5SDimitry Andric   // Apply DeMorgan's Law for 'nand' / 'nor' logic with an inverted operand.
43210b57cec5SDimitry Andric   // We must eliminate the and/or (one-use) for these transforms to not increase
43220b57cec5SDimitry Andric   // the instruction count.
4323349cc55cSDimitry Andric   //
43240b57cec5SDimitry Andric   // ~(~X & Y) --> (X | ~Y)
43250b57cec5SDimitry Andric   // ~(Y & ~X) --> (X | ~Y)
4326349cc55cSDimitry Andric   //
4327349cc55cSDimitry Andric   // Note: The logical matches do not check for the commuted patterns because
4328349cc55cSDimitry Andric   //       those are handled via SimplifySelectsFeedingBinaryOp().
4329349cc55cSDimitry Andric   Type *Ty = I.getType();
4330349cc55cSDimitry Andric   Value *X, *Y;
4331349cc55cSDimitry Andric   if (match(NotOp, m_OneUse(m_c_And(m_Not(m_Value(X)), m_Value(Y))))) {
43320b57cec5SDimitry Andric     Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
43330b57cec5SDimitry Andric     return BinaryOperator::CreateOr(X, NotY);
43340b57cec5SDimitry Andric   }
4335349cc55cSDimitry Andric   if (match(NotOp, m_OneUse(m_LogicalAnd(m_Not(m_Value(X)), m_Value(Y))))) {
4336349cc55cSDimitry Andric     Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
4337349cc55cSDimitry Andric     return SelectInst::Create(X, ConstantInt::getTrue(Ty), NotY);
4338349cc55cSDimitry Andric   }
4339349cc55cSDimitry Andric 
43400b57cec5SDimitry Andric   // ~(~X | Y) --> (X & ~Y)
43410b57cec5SDimitry Andric   // ~(Y | ~X) --> (X & ~Y)
4342349cc55cSDimitry Andric   if (match(NotOp, m_OneUse(m_c_Or(m_Not(m_Value(X)), m_Value(Y))))) {
43430b57cec5SDimitry Andric     Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
43440b57cec5SDimitry Andric     return BinaryOperator::CreateAnd(X, NotY);
43450b57cec5SDimitry Andric   }
4346349cc55cSDimitry Andric   if (match(NotOp, m_OneUse(m_LogicalOr(m_Not(m_Value(X)), m_Value(Y))))) {
4347349cc55cSDimitry Andric     Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
4348349cc55cSDimitry Andric     return SelectInst::Create(X, NotY, ConstantInt::getFalse(Ty));
4349349cc55cSDimitry Andric   }
43500b57cec5SDimitry Andric 
43510b57cec5SDimitry Andric   // Is this a 'not' (~) fed by a binary operator?
43520b57cec5SDimitry Andric   BinaryOperator *NotVal;
4353349cc55cSDimitry Andric   if (match(NotOp, m_BinOp(NotVal))) {
4354fe6060f1SDimitry Andric     // ~((-X) | Y) --> (X - 1) & (~Y)
4355fe6060f1SDimitry Andric     if (match(NotVal,
4356fe6060f1SDimitry Andric               m_OneUse(m_c_Or(m_OneUse(m_Neg(m_Value(X))), m_Value(Y))))) {
4357fe6060f1SDimitry Andric       Value *DecX = Builder.CreateAdd(X, ConstantInt::getAllOnesValue(Ty));
4358fe6060f1SDimitry Andric       Value *NotY = Builder.CreateNot(Y);
4359fe6060f1SDimitry Andric       return BinaryOperator::CreateAnd(DecX, NotY);
4360fe6060f1SDimitry Andric     }
4361fe6060f1SDimitry Andric 
43620b57cec5SDimitry Andric     // ~(~X >>s Y) --> (X >>s Y)
43630b57cec5SDimitry Andric     if (match(NotVal, m_AShr(m_Not(m_Value(X)), m_Value(Y))))
43640b57cec5SDimitry Andric       return BinaryOperator::CreateAShr(X, Y);
43650b57cec5SDimitry Andric 
43665f757f3fSDimitry Andric     // Treat lshr with non-negative operand as ashr.
43675f757f3fSDimitry Andric     // ~(~X >>u Y) --> (X >>s Y) iff X is known negative
43685f757f3fSDimitry Andric     if (match(NotVal, m_LShr(m_Not(m_Value(X)), m_Value(Y))) &&
43695f757f3fSDimitry Andric         isKnownNegative(X, SQ.getWithInstruction(NotVal)))
43705f757f3fSDimitry Andric       return BinaryOperator::CreateAShr(X, Y);
43715f757f3fSDimitry Andric 
437206c3fb27SDimitry Andric     // Bit-hack form of a signbit test for iN type:
437306c3fb27SDimitry Andric     // ~(X >>s (N - 1)) --> sext i1 (X > -1) to iN
4374bdd1243dSDimitry Andric     unsigned FullShift = Ty->getScalarSizeInBits() - 1;
4375bdd1243dSDimitry Andric     if (match(NotVal, m_OneUse(m_AShr(m_Value(X), m_SpecificInt(FullShift))))) {
4376bdd1243dSDimitry Andric       Value *IsNotNeg = Builder.CreateIsNotNeg(X, "isnotneg");
4377bdd1243dSDimitry Andric       return new SExtInst(IsNotNeg, Ty);
4378bdd1243dSDimitry Andric     }
4379bdd1243dSDimitry Andric 
43800b57cec5SDimitry Andric     // If we are inverting a right-shifted constant, we may be able to eliminate
43810b57cec5SDimitry Andric     // the 'not' by inverting the constant and using the opposite shift type.
43820b57cec5SDimitry Andric     // Canonicalization rules ensure that only a negative constant uses 'ashr',
43830b57cec5SDimitry Andric     // but we must check that in case that transform has not fired yet.
43840b57cec5SDimitry Andric 
43850b57cec5SDimitry Andric     // ~(C >>s Y) --> ~C >>u Y (when inverting the replicated sign bits)
43860b57cec5SDimitry Andric     Constant *C;
43870b57cec5SDimitry Andric     if (match(NotVal, m_AShr(m_Constant(C), m_Value(Y))) &&
43885ffd83dbSDimitry Andric         match(C, m_Negative())) {
43895ffd83dbSDimitry Andric       // We matched a negative constant, so propagating undef is unsafe.
43905ffd83dbSDimitry Andric       // Clamp undef elements to -1.
4391e8d8bef9SDimitry Andric       Type *EltTy = Ty->getScalarType();
43925ffd83dbSDimitry Andric       C = Constant::replaceUndefsWith(C, ConstantInt::getAllOnesValue(EltTy));
43930b57cec5SDimitry Andric       return BinaryOperator::CreateLShr(ConstantExpr::getNot(C), Y);
43945ffd83dbSDimitry Andric     }
43950b57cec5SDimitry Andric 
43960b57cec5SDimitry Andric     // ~(C >>u Y) --> ~C >>s Y (when inverting the replicated sign bits)
43970b57cec5SDimitry Andric     if (match(NotVal, m_LShr(m_Constant(C), m_Value(Y))) &&
43985ffd83dbSDimitry Andric         match(C, m_NonNegative())) {
43995ffd83dbSDimitry Andric       // We matched a non-negative constant, so propagating undef is unsafe.
44005ffd83dbSDimitry Andric       // Clamp undef elements to 0.
4401e8d8bef9SDimitry Andric       Type *EltTy = Ty->getScalarType();
44025ffd83dbSDimitry Andric       C = Constant::replaceUndefsWith(C, ConstantInt::getNullValue(EltTy));
44030b57cec5SDimitry Andric       return BinaryOperator::CreateAShr(ConstantExpr::getNot(C), Y);
44045ffd83dbSDimitry Andric     }
44050b57cec5SDimitry Andric 
440623408297SDimitry Andric     // ~(X + C) --> ~C - X
440723408297SDimitry Andric     if (match(NotVal, m_c_Add(m_Value(X), m_ImmConstant(C))))
440823408297SDimitry Andric       return BinaryOperator::CreateSub(ConstantExpr::getNot(C), X);
440923408297SDimitry Andric 
441023408297SDimitry Andric     // ~(X - Y) --> ~X + Y
441123408297SDimitry Andric     // FIXME: is it really beneficial to sink the `not` here?
441223408297SDimitry Andric     if (match(NotVal, m_Sub(m_Value(X), m_Value(Y))))
441323408297SDimitry Andric       if (isa<Constant>(X) || NotVal->hasOneUse())
441423408297SDimitry Andric         return BinaryOperator::CreateAdd(Builder.CreateNot(X), Y);
4415e8d8bef9SDimitry Andric 
4416e8d8bef9SDimitry Andric     // ~(~X + Y) --> X - Y
4417e8d8bef9SDimitry Andric     if (match(NotVal, m_c_Add(m_Not(m_Value(X)), m_Value(Y))))
4418e8d8bef9SDimitry Andric       return BinaryOperator::CreateWithCopiedFlags(Instruction::Sub, X, Y,
4419e8d8bef9SDimitry Andric                                                    NotVal);
44200b57cec5SDimitry Andric   }
44210b57cec5SDimitry Andric 
4422349cc55cSDimitry Andric   // not (cmp A, B) = !cmp A, B
4423349cc55cSDimitry Andric   CmpInst::Predicate Pred;
4424bdd1243dSDimitry Andric   if (match(NotOp, m_Cmp(Pred, m_Value(), m_Value())) &&
4425bdd1243dSDimitry Andric       (NotOp->hasOneUse() ||
4426bdd1243dSDimitry Andric        InstCombiner::canFreelyInvertAllUsersOf(cast<Instruction>(NotOp),
4427bdd1243dSDimitry Andric                                                /*IgnoredUser=*/nullptr))) {
4428349cc55cSDimitry Andric     cast<CmpInst>(NotOp)->setPredicate(CmpInst::getInversePredicate(Pred));
4429bdd1243dSDimitry Andric     freelyInvertAllUsersOf(NotOp);
4430bdd1243dSDimitry Andric     return &I;
4431349cc55cSDimitry Andric   }
4432349cc55cSDimitry Andric 
4433bdd1243dSDimitry Andric   // Move a 'not' ahead of casts of a bool to enable logic reduction:
4434bdd1243dSDimitry Andric   // not (bitcast (sext i1 X)) --> bitcast (sext (not i1 X))
4435bdd1243dSDimitry Andric   if (match(NotOp, m_OneUse(m_BitCast(m_OneUse(m_SExt(m_Value(X)))))) && X->getType()->isIntOrIntVectorTy(1)) {
4436bdd1243dSDimitry Andric     Type *SextTy = cast<BitCastOperator>(NotOp)->getSrcTy();
4437bdd1243dSDimitry Andric     Value *NotX = Builder.CreateNot(X);
4438bdd1243dSDimitry Andric     Value *Sext = Builder.CreateSExt(NotX, SextTy);
4439bdd1243dSDimitry Andric     return CastInst::CreateBitOrPointerCast(Sext, Ty);
4440bdd1243dSDimitry Andric   }
4441bdd1243dSDimitry Andric 
4442bdd1243dSDimitry Andric   if (auto *NotOpI = dyn_cast<Instruction>(NotOp))
4443bdd1243dSDimitry Andric     if (sinkNotIntoLogicalOp(*NotOpI))
4444bdd1243dSDimitry Andric       return &I;
4445bdd1243dSDimitry Andric 
4446349cc55cSDimitry Andric   // Eliminate a bitwise 'not' op of 'not' min/max by inverting the min/max:
4447349cc55cSDimitry Andric   // ~min(~X, ~Y) --> max(X, Y)
4448349cc55cSDimitry Andric   // ~max(~X, Y) --> min(X, ~Y)
4449349cc55cSDimitry Andric   auto *II = dyn_cast<IntrinsicInst>(NotOp);
4450349cc55cSDimitry Andric   if (II && II->hasOneUse()) {
4451349cc55cSDimitry Andric     if (match(NotOp, m_c_MaxOrMin(m_Not(m_Value(X)), m_Value(Y)))) {
4452349cc55cSDimitry Andric       Intrinsic::ID InvID = getInverseMinMaxIntrinsic(II->getIntrinsicID());
4453349cc55cSDimitry Andric       Value *NotY = Builder.CreateNot(Y);
4454349cc55cSDimitry Andric       Value *InvMaxMin = Builder.CreateBinaryIntrinsic(InvID, X, NotY);
4455349cc55cSDimitry Andric       return replaceInstUsesWith(I, InvMaxMin);
4456349cc55cSDimitry Andric     }
4457bdd1243dSDimitry Andric 
4458bdd1243dSDimitry Andric     if (II->getIntrinsicID() == Intrinsic::is_fpclass) {
4459bdd1243dSDimitry Andric       ConstantInt *ClassMask = cast<ConstantInt>(II->getArgOperand(1));
4460bdd1243dSDimitry Andric       II->setArgOperand(
4461bdd1243dSDimitry Andric           1, ConstantInt::get(ClassMask->getType(),
4462bdd1243dSDimitry Andric                               ~ClassMask->getZExtValue() & fcAllFlags));
4463bdd1243dSDimitry Andric       return replaceInstUsesWith(I, II);
4464bdd1243dSDimitry Andric     }
4465349cc55cSDimitry Andric   }
4466349cc55cSDimitry Andric 
4467349cc55cSDimitry Andric   if (NotOp->hasOneUse()) {
4468349cc55cSDimitry Andric     // Pull 'not' into operands of select if both operands are one-use compares
4469349cc55cSDimitry Andric     // or one is one-use compare and the other one is a constant.
4470349cc55cSDimitry Andric     // Inverting the predicates eliminates the 'not' operation.
4471349cc55cSDimitry Andric     // Example:
4472349cc55cSDimitry Andric     //   not (select ?, (cmp TPred, ?, ?), (cmp FPred, ?, ?) -->
4473349cc55cSDimitry Andric     //     select ?, (cmp InvTPred, ?, ?), (cmp InvFPred, ?, ?)
4474349cc55cSDimitry Andric     //   not (select ?, (cmp TPred, ?, ?), true -->
4475349cc55cSDimitry Andric     //     select ?, (cmp InvTPred, ?, ?), false
4476349cc55cSDimitry Andric     if (auto *Sel = dyn_cast<SelectInst>(NotOp)) {
4477349cc55cSDimitry Andric       Value *TV = Sel->getTrueValue();
4478349cc55cSDimitry Andric       Value *FV = Sel->getFalseValue();
4479349cc55cSDimitry Andric       auto *CmpT = dyn_cast<CmpInst>(TV);
4480349cc55cSDimitry Andric       auto *CmpF = dyn_cast<CmpInst>(FV);
4481349cc55cSDimitry Andric       bool InvertibleT = (CmpT && CmpT->hasOneUse()) || isa<Constant>(TV);
4482349cc55cSDimitry Andric       bool InvertibleF = (CmpF && CmpF->hasOneUse()) || isa<Constant>(FV);
4483349cc55cSDimitry Andric       if (InvertibleT && InvertibleF) {
4484349cc55cSDimitry Andric         if (CmpT)
4485349cc55cSDimitry Andric           CmpT->setPredicate(CmpT->getInversePredicate());
4486349cc55cSDimitry Andric         else
4487349cc55cSDimitry Andric           Sel->setTrueValue(ConstantExpr::getNot(cast<Constant>(TV)));
4488349cc55cSDimitry Andric         if (CmpF)
4489349cc55cSDimitry Andric           CmpF->setPredicate(CmpF->getInversePredicate());
4490349cc55cSDimitry Andric         else
4491349cc55cSDimitry Andric           Sel->setFalseValue(ConstantExpr::getNot(cast<Constant>(FV)));
4492349cc55cSDimitry Andric         return replaceInstUsesWith(I, Sel);
4493349cc55cSDimitry Andric       }
4494349cc55cSDimitry Andric     }
4495349cc55cSDimitry Andric   }
4496349cc55cSDimitry Andric 
4497bdd1243dSDimitry Andric   if (Instruction *NewXor = foldNotXor(I, Builder))
4498349cc55cSDimitry Andric     return NewXor;
4499349cc55cSDimitry Andric 
45005f757f3fSDimitry Andric   // TODO: Could handle multi-use better by checking if all uses of NotOp (other
45015f757f3fSDimitry Andric   // than I) can be inverted.
45025f757f3fSDimitry Andric   if (Value *R = getFreelyInverted(NotOp, NotOp->hasOneUse(), &Builder))
45035f757f3fSDimitry Andric     return replaceInstUsesWith(I, R);
45045f757f3fSDimitry Andric 
4505349cc55cSDimitry Andric   return nullptr;
4506349cc55cSDimitry Andric }
4507349cc55cSDimitry Andric 
4508349cc55cSDimitry Andric // FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
4509349cc55cSDimitry Andric // here. We should standardize that construct where it is needed or choose some
4510349cc55cSDimitry Andric // other way to ensure that commutated variants of patterns are not missed.
visitXor(BinaryOperator & I)4511349cc55cSDimitry Andric Instruction *InstCombinerImpl::visitXor(BinaryOperator &I) {
451281ad6265SDimitry Andric   if (Value *V = simplifyXorInst(I.getOperand(0), I.getOperand(1),
4513349cc55cSDimitry Andric                                  SQ.getWithInstruction(&I)))
4514349cc55cSDimitry Andric     return replaceInstUsesWith(I, V);
4515349cc55cSDimitry Andric 
4516349cc55cSDimitry Andric   if (SimplifyAssociativeOrCommutative(I))
4517349cc55cSDimitry Andric     return &I;
4518349cc55cSDimitry Andric 
4519349cc55cSDimitry Andric   if (Instruction *X = foldVectorBinop(I))
4520349cc55cSDimitry Andric     return X;
4521349cc55cSDimitry Andric 
452204eeddc0SDimitry Andric   if (Instruction *Phi = foldBinopWithPhiOperands(I))
452304eeddc0SDimitry Andric     return Phi;
452404eeddc0SDimitry Andric 
4525349cc55cSDimitry Andric   if (Instruction *NewXor = foldXorToXor(I, Builder))
4526349cc55cSDimitry Andric     return NewXor;
4527349cc55cSDimitry Andric 
4528349cc55cSDimitry Andric   // (A&B)^(A&C) -> A&(B^C) etc
4529bdd1243dSDimitry Andric   if (Value *V = foldUsingDistributiveLaws(I))
4530349cc55cSDimitry Andric     return replaceInstUsesWith(I, V);
4531349cc55cSDimitry Andric 
4532349cc55cSDimitry Andric   // See if we can simplify any instructions used by the instruction whose sole
4533349cc55cSDimitry Andric   // purpose is to compute bits we don't care about.
4534349cc55cSDimitry Andric   if (SimplifyDemandedInstructionBits(I))
4535349cc55cSDimitry Andric     return &I;
4536349cc55cSDimitry Andric 
4537349cc55cSDimitry Andric   if (Instruction *R = foldNot(I))
4538349cc55cSDimitry Andric     return R;
4539349cc55cSDimitry Andric 
454006c3fb27SDimitry Andric   if (Instruction *R = foldBinOpShiftWithShift(I))
454106c3fb27SDimitry Andric     return R;
454206c3fb27SDimitry Andric 
4543349cc55cSDimitry Andric   // Fold (X & M) ^ (Y & ~M) -> (X & M) | (Y & ~M)
4544349cc55cSDimitry Andric   // This it a special case in haveNoCommonBitsSet, but the computeKnownBits
4545349cc55cSDimitry Andric   // calls in there are unnecessary as SimplifyDemandedInstructionBits should
4546349cc55cSDimitry Andric   // have already taken care of those cases.
4547349cc55cSDimitry Andric   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4548349cc55cSDimitry Andric   Value *M;
4549349cc55cSDimitry Andric   if (match(&I, m_c_Xor(m_c_And(m_Not(m_Value(M)), m_Value()),
4550349cc55cSDimitry Andric                         m_c_And(m_Deferred(M), m_Value()))))
45515f757f3fSDimitry Andric     return BinaryOperator::CreateDisjointOr(Op0, Op1);
4552349cc55cSDimitry Andric 
4553349cc55cSDimitry Andric   if (Instruction *Xor = visitMaskedMerge(I, Builder))
4554349cc55cSDimitry Andric     return Xor;
4555349cc55cSDimitry Andric 
4556349cc55cSDimitry Andric   Value *X, *Y;
45570b57cec5SDimitry Andric   Constant *C1;
45580b57cec5SDimitry Andric   if (match(Op1, m_Constant(C1))) {
45590b57cec5SDimitry Andric     Constant *C2;
456081ad6265SDimitry Andric 
456181ad6265SDimitry Andric     if (match(Op0, m_OneUse(m_Or(m_Value(X), m_ImmConstant(C2)))) &&
456281ad6265SDimitry Andric         match(C1, m_ImmConstant())) {
456381ad6265SDimitry Andric       // (X | C2) ^ C1 --> (X & ~C2) ^ (C1^C2)
456481ad6265SDimitry Andric       C2 = Constant::replaceUndefsWith(
456581ad6265SDimitry Andric           C2, Constant::getAllOnesValue(C2->getType()->getScalarType()));
456681ad6265SDimitry Andric       Value *And = Builder.CreateAnd(
456781ad6265SDimitry Andric           X, Constant::mergeUndefsWith(ConstantExpr::getNot(C2), C1));
456881ad6265SDimitry Andric       return BinaryOperator::CreateXor(
456981ad6265SDimitry Andric           And, Constant::mergeUndefsWith(ConstantExpr::getXor(C1, C2), C1));
457081ad6265SDimitry Andric     }
457181ad6265SDimitry Andric 
457281ad6265SDimitry Andric     // Use DeMorgan and reassociation to eliminate a 'not' op.
45730b57cec5SDimitry Andric     if (match(Op0, m_OneUse(m_Or(m_Not(m_Value(X)), m_Constant(C2))))) {
45740b57cec5SDimitry Andric       // (~X | C2) ^ C1 --> ((X & ~C2) ^ -1) ^ C1 --> (X & ~C2) ^ ~C1
45750b57cec5SDimitry Andric       Value *And = Builder.CreateAnd(X, ConstantExpr::getNot(C2));
45760b57cec5SDimitry Andric       return BinaryOperator::CreateXor(And, ConstantExpr::getNot(C1));
45770b57cec5SDimitry Andric     }
45780b57cec5SDimitry Andric     if (match(Op0, m_OneUse(m_And(m_Not(m_Value(X)), m_Constant(C2))))) {
45790b57cec5SDimitry Andric       // (~X & C2) ^ C1 --> ((X | ~C2) ^ -1) ^ C1 --> (X | ~C2) ^ ~C1
45800b57cec5SDimitry Andric       Value *Or = Builder.CreateOr(X, ConstantExpr::getNot(C2));
45810b57cec5SDimitry Andric       return BinaryOperator::CreateXor(Or, ConstantExpr::getNot(C1));
45820b57cec5SDimitry Andric     }
4583349cc55cSDimitry Andric 
4584349cc55cSDimitry Andric     // Convert xor ([trunc] (ashr X, BW-1)), C =>
4585349cc55cSDimitry Andric     //   select(X >s -1, C, ~C)
4586349cc55cSDimitry Andric     // The ashr creates "AllZeroOrAllOne's", which then optionally inverses the
4587349cc55cSDimitry Andric     // constant depending on whether this input is less than 0.
4588349cc55cSDimitry Andric     const APInt *CA;
4589349cc55cSDimitry Andric     if (match(Op0, m_OneUse(m_TruncOrSelf(
4590349cc55cSDimitry Andric                        m_AShr(m_Value(X), m_APIntAllowUndef(CA))))) &&
4591349cc55cSDimitry Andric         *CA == X->getType()->getScalarSizeInBits() - 1 &&
4592349cc55cSDimitry Andric         !match(C1, m_AllOnes())) {
4593349cc55cSDimitry Andric       assert(!C1->isZeroValue() && "Unexpected xor with 0");
459481ad6265SDimitry Andric       Value *IsNotNeg = Builder.CreateIsNotNeg(X);
459581ad6265SDimitry Andric       return SelectInst::Create(IsNotNeg, Op1, Builder.CreateNot(Op1));
4596349cc55cSDimitry Andric     }
45970b57cec5SDimitry Andric   }
45980b57cec5SDimitry Andric 
4599349cc55cSDimitry Andric   Type *Ty = I.getType();
46000b57cec5SDimitry Andric   {
46010b57cec5SDimitry Andric     const APInt *RHSC;
46020b57cec5SDimitry Andric     if (match(Op1, m_APInt(RHSC))) {
46030b57cec5SDimitry Andric       Value *X;
46040b57cec5SDimitry Andric       const APInt *C;
4605e8d8bef9SDimitry Andric       // (C - X) ^ signmaskC --> (C + signmaskC) - X
4606e8d8bef9SDimitry Andric       if (RHSC->isSignMask() && match(Op0, m_Sub(m_APInt(C), m_Value(X))))
4607e8d8bef9SDimitry Andric         return BinaryOperator::CreateSub(ConstantInt::get(Ty, *C + *RHSC), X);
46080b57cec5SDimitry Andric 
4609e8d8bef9SDimitry Andric       // (X + C) ^ signmaskC --> X + (C + signmaskC)
4610e8d8bef9SDimitry Andric       if (RHSC->isSignMask() && match(Op0, m_Add(m_Value(X), m_APInt(C))))
4611e8d8bef9SDimitry Andric         return BinaryOperator::CreateAdd(X, ConstantInt::get(Ty, *C + *RHSC));
4612e8d8bef9SDimitry Andric 
4613e8d8bef9SDimitry Andric       // (X | C) ^ RHSC --> X ^ (C ^ RHSC) iff X & C == 0
46140b57cec5SDimitry Andric       if (match(Op0, m_Or(m_Value(X), m_APInt(C))) &&
4615e8d8bef9SDimitry Andric           MaskedValueIsZero(X, *C, 0, &I))
4616e8d8bef9SDimitry Andric         return BinaryOperator::CreateXor(X, ConstantInt::get(Ty, *C ^ *RHSC));
4617e8d8bef9SDimitry Andric 
4618bdd1243dSDimitry Andric       // When X is a power-of-two or zero and zero input is poison:
4619bdd1243dSDimitry Andric       // ctlz(i32 X) ^ 31 --> cttz(X)
4620bdd1243dSDimitry Andric       // cttz(i32 X) ^ 31 --> ctlz(X)
4621bdd1243dSDimitry Andric       auto *II = dyn_cast<IntrinsicInst>(Op0);
4622bdd1243dSDimitry Andric       if (II && II->hasOneUse() && *RHSC == Ty->getScalarSizeInBits() - 1) {
4623bdd1243dSDimitry Andric         Intrinsic::ID IID = II->getIntrinsicID();
4624bdd1243dSDimitry Andric         if ((IID == Intrinsic::ctlz || IID == Intrinsic::cttz) &&
4625bdd1243dSDimitry Andric             match(II->getArgOperand(1), m_One()) &&
4626bdd1243dSDimitry Andric             isKnownToBeAPowerOfTwo(II->getArgOperand(0), /*OrZero */ true)) {
4627bdd1243dSDimitry Andric           IID = (IID == Intrinsic::ctlz) ? Intrinsic::cttz : Intrinsic::ctlz;
4628bdd1243dSDimitry Andric           Function *F = Intrinsic::getDeclaration(II->getModule(), IID, Ty);
4629bdd1243dSDimitry Andric           return CallInst::Create(F, {II->getArgOperand(0), Builder.getTrue()});
4630bdd1243dSDimitry Andric         }
4631bdd1243dSDimitry Andric       }
4632bdd1243dSDimitry Andric 
4633e8d8bef9SDimitry Andric       // If RHSC is inverting the remaining bits of shifted X,
4634e8d8bef9SDimitry Andric       // canonicalize to a 'not' before the shift to help SCEV and codegen:
4635e8d8bef9SDimitry Andric       // (X << C) ^ RHSC --> ~X << C
4636e8d8bef9SDimitry Andric       if (match(Op0, m_OneUse(m_Shl(m_Value(X), m_APInt(C)))) &&
4637349cc55cSDimitry Andric           *RHSC == APInt::getAllOnes(Ty->getScalarSizeInBits()).shl(*C)) {
4638e8d8bef9SDimitry Andric         Value *NotX = Builder.CreateNot(X);
4639e8d8bef9SDimitry Andric         return BinaryOperator::CreateShl(NotX, ConstantInt::get(Ty, *C));
46400b57cec5SDimitry Andric       }
4641e8d8bef9SDimitry Andric       // (X >>u C) ^ RHSC --> ~X >>u C
4642e8d8bef9SDimitry Andric       if (match(Op0, m_OneUse(m_LShr(m_Value(X), m_APInt(C)))) &&
4643349cc55cSDimitry Andric           *RHSC == APInt::getAllOnes(Ty->getScalarSizeInBits()).lshr(*C)) {
4644e8d8bef9SDimitry Andric         Value *NotX = Builder.CreateNot(X);
4645e8d8bef9SDimitry Andric         return BinaryOperator::CreateLShr(NotX, ConstantInt::get(Ty, *C));
4646e8d8bef9SDimitry Andric       }
4647e8d8bef9SDimitry Andric       // TODO: We could handle 'ashr' here as well. That would be matching
4648e8d8bef9SDimitry Andric       //       a 'not' op and moving it before the shift. Doing that requires
4649e8d8bef9SDimitry Andric       //       preventing the inverse fold in canShiftBinOpWithConstantRHS().
46500b57cec5SDimitry Andric     }
46515f757f3fSDimitry Andric 
46525f757f3fSDimitry Andric     // If we are XORing the sign bit of a floating-point value, convert
46535f757f3fSDimitry Andric     // this to fneg, then cast back to integer.
46545f757f3fSDimitry Andric     //
46555f757f3fSDimitry Andric     // This is generous interpretation of noimplicitfloat, this is not a true
46565f757f3fSDimitry Andric     // floating-point operation.
46575f757f3fSDimitry Andric     //
46585f757f3fSDimitry Andric     // Assumes any IEEE-represented type has the sign bit in the high bit.
46595f757f3fSDimitry Andric     // TODO: Unify with APInt matcher. This version allows undef unlike m_APInt
46605f757f3fSDimitry Andric     Value *CastOp;
46615f757f3fSDimitry Andric     if (match(Op0, m_BitCast(m_Value(CastOp))) && match(Op1, m_SignMask()) &&
46625f757f3fSDimitry Andric         !Builder.GetInsertBlock()->getParent()->hasFnAttribute(
46635f757f3fSDimitry Andric             Attribute::NoImplicitFloat)) {
46645f757f3fSDimitry Andric       Type *EltTy = CastOp->getType()->getScalarType();
46655f757f3fSDimitry Andric       if (EltTy->isFloatingPointTy() && EltTy->isIEEE() &&
46665f757f3fSDimitry Andric           EltTy->getPrimitiveSizeInBits() ==
46675f757f3fSDimitry Andric           I.getType()->getScalarType()->getPrimitiveSizeInBits()) {
46685f757f3fSDimitry Andric         Value *FNeg = Builder.CreateFNeg(CastOp);
46695f757f3fSDimitry Andric         return new BitCastInst(FNeg, I.getType());
46705f757f3fSDimitry Andric       }
46715f757f3fSDimitry Andric     }
46720b57cec5SDimitry Andric   }
46730b57cec5SDimitry Andric 
4674e8d8bef9SDimitry Andric   // FIXME: This should not be limited to scalar (pull into APInt match above).
4675e8d8bef9SDimitry Andric   {
4676e8d8bef9SDimitry Andric     Value *X;
4677e8d8bef9SDimitry Andric     ConstantInt *C1, *C2, *C3;
46780b57cec5SDimitry Andric     // ((X^C1) >> C2) ^ C3 -> (X>>C2) ^ ((C1>>C2)^C3)
4679e8d8bef9SDimitry Andric     if (match(Op1, m_ConstantInt(C3)) &&
4680e8d8bef9SDimitry Andric         match(Op0, m_LShr(m_Xor(m_Value(X), m_ConstantInt(C1)),
4681e8d8bef9SDimitry Andric                           m_ConstantInt(C2))) &&
4682e8d8bef9SDimitry Andric         Op0->hasOneUse()) {
46830b57cec5SDimitry Andric       // fold (C1 >> C2) ^ C3
46840b57cec5SDimitry Andric       APInt FoldConst = C1->getValue().lshr(C2->getValue());
46850b57cec5SDimitry Andric       FoldConst ^= C3->getValue();
46860b57cec5SDimitry Andric       // Prepare the two operands.
468781ad6265SDimitry Andric       auto *Opnd0 = Builder.CreateLShr(X, C2);
468881ad6265SDimitry Andric       Opnd0->takeName(Op0);
4689e8d8bef9SDimitry Andric       return BinaryOperator::CreateXor(Opnd0, ConstantInt::get(Ty, FoldConst));
46900b57cec5SDimitry Andric     }
46910b57cec5SDimitry Andric   }
46920b57cec5SDimitry Andric 
46930b57cec5SDimitry Andric   if (Instruction *FoldedLogic = foldBinOpIntoSelectOrPhi(I))
46940b57cec5SDimitry Andric     return FoldedLogic;
46950b57cec5SDimitry Andric 
46960b57cec5SDimitry Andric   // Y ^ (X | Y) --> X & ~Y
46970b57cec5SDimitry Andric   // Y ^ (Y | X) --> X & ~Y
46980b57cec5SDimitry Andric   if (match(Op1, m_OneUse(m_c_Or(m_Value(X), m_Specific(Op0)))))
46990b57cec5SDimitry Andric     return BinaryOperator::CreateAnd(X, Builder.CreateNot(Op0));
47000b57cec5SDimitry Andric   // (X | Y) ^ Y --> X & ~Y
47010b57cec5SDimitry Andric   // (Y | X) ^ Y --> X & ~Y
47020b57cec5SDimitry Andric   if (match(Op0, m_OneUse(m_c_Or(m_Value(X), m_Specific(Op1)))))
47030b57cec5SDimitry Andric     return BinaryOperator::CreateAnd(X, Builder.CreateNot(Op1));
47040b57cec5SDimitry Andric 
47050b57cec5SDimitry Andric   // Y ^ (X & Y) --> ~X & Y
47060b57cec5SDimitry Andric   // Y ^ (Y & X) --> ~X & Y
47070b57cec5SDimitry Andric   if (match(Op1, m_OneUse(m_c_And(m_Value(X), m_Specific(Op0)))))
47080b57cec5SDimitry Andric     return BinaryOperator::CreateAnd(Op0, Builder.CreateNot(X));
47090b57cec5SDimitry Andric   // (X & Y) ^ Y --> ~X & Y
47100b57cec5SDimitry Andric   // (Y & X) ^ Y --> ~X & Y
47110b57cec5SDimitry Andric   // Canonical form is (X & C) ^ C; don't touch that.
47120b57cec5SDimitry Andric   // TODO: A 'not' op is better for analysis and codegen, but demanded bits must
47130b57cec5SDimitry Andric   //       be fixed to prefer that (otherwise we get infinite looping).
47140b57cec5SDimitry Andric   if (!match(Op1, m_Constant()) &&
47150b57cec5SDimitry Andric       match(Op0, m_OneUse(m_c_And(m_Value(X), m_Specific(Op1)))))
47160b57cec5SDimitry Andric     return BinaryOperator::CreateAnd(Op1, Builder.CreateNot(X));
47170b57cec5SDimitry Andric 
47180b57cec5SDimitry Andric   Value *A, *B, *C;
47190b57cec5SDimitry Andric   // (A ^ B) ^ (A | C) --> (~A & C) ^ B -- There are 4 commuted variants.
47200b57cec5SDimitry Andric   if (match(&I, m_c_Xor(m_OneUse(m_Xor(m_Value(A), m_Value(B))),
47210b57cec5SDimitry Andric                         m_OneUse(m_c_Or(m_Deferred(A), m_Value(C))))))
47220b57cec5SDimitry Andric       return BinaryOperator::CreateXor(
47230b57cec5SDimitry Andric           Builder.CreateAnd(Builder.CreateNot(A), C), B);
47240b57cec5SDimitry Andric 
47250b57cec5SDimitry Andric   // (A ^ B) ^ (B | C) --> (~B & C) ^ A -- There are 4 commuted variants.
47260b57cec5SDimitry Andric   if (match(&I, m_c_Xor(m_OneUse(m_Xor(m_Value(A), m_Value(B))),
47270b57cec5SDimitry Andric                         m_OneUse(m_c_Or(m_Deferred(B), m_Value(C))))))
47280b57cec5SDimitry Andric       return BinaryOperator::CreateXor(
47290b57cec5SDimitry Andric           Builder.CreateAnd(Builder.CreateNot(B), C), A);
47300b57cec5SDimitry Andric 
47310b57cec5SDimitry Andric   // (A & B) ^ (A ^ B) -> (A | B)
47320b57cec5SDimitry Andric   if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
47330b57cec5SDimitry Andric       match(Op1, m_c_Xor(m_Specific(A), m_Specific(B))))
47340b57cec5SDimitry Andric     return BinaryOperator::CreateOr(A, B);
47350b57cec5SDimitry Andric   // (A ^ B) ^ (A & B) -> (A | B)
47360b57cec5SDimitry Andric   if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
47370b57cec5SDimitry Andric       match(Op1, m_c_And(m_Specific(A), m_Specific(B))))
47380b57cec5SDimitry Andric     return BinaryOperator::CreateOr(A, B);
47390b57cec5SDimitry Andric 
47400b57cec5SDimitry Andric   // (A & ~B) ^ ~A -> ~(A & B)
47410b57cec5SDimitry Andric   // (~B & A) ^ ~A -> ~(A & B)
47420b57cec5SDimitry Andric   if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
47430b57cec5SDimitry Andric       match(Op1, m_Not(m_Specific(A))))
47440b57cec5SDimitry Andric     return BinaryOperator::CreateNot(Builder.CreateAnd(A, B));
47450b57cec5SDimitry Andric 
4746e8d8bef9SDimitry Andric   // (~A & B) ^ A --> A | B -- There are 4 commuted variants.
4747e8d8bef9SDimitry Andric   if (match(&I, m_c_Xor(m_c_And(m_Not(m_Value(A)), m_Value(B)), m_Deferred(A))))
4748e8d8bef9SDimitry Andric     return BinaryOperator::CreateOr(A, B);
4749e8d8bef9SDimitry Andric 
47504824e7fdSDimitry Andric   // (~A | B) ^ A --> ~(A & B)
47514824e7fdSDimitry Andric   if (match(Op0, m_OneUse(m_c_Or(m_Not(m_Specific(Op1)), m_Value(B)))))
47524824e7fdSDimitry Andric     return BinaryOperator::CreateNot(Builder.CreateAnd(Op1, B));
47534824e7fdSDimitry Andric 
47544824e7fdSDimitry Andric   // A ^ (~A | B) --> ~(A & B)
47554824e7fdSDimitry Andric   if (match(Op1, m_OneUse(m_c_Or(m_Not(m_Specific(Op0)), m_Value(B)))))
47564824e7fdSDimitry Andric     return BinaryOperator::CreateNot(Builder.CreateAnd(Op0, B));
47574824e7fdSDimitry Andric 
4758e8d8bef9SDimitry Andric   // (A | B) ^ (A | C) --> (B ^ C) & ~A -- There are 4 commuted variants.
4759e8d8bef9SDimitry Andric   // TODO: Loosen one-use restriction if common operand is a constant.
4760e8d8bef9SDimitry Andric   Value *D;
4761e8d8bef9SDimitry Andric   if (match(Op0, m_OneUse(m_Or(m_Value(A), m_Value(B)))) &&
4762e8d8bef9SDimitry Andric       match(Op1, m_OneUse(m_Or(m_Value(C), m_Value(D))))) {
4763e8d8bef9SDimitry Andric     if (B == C || B == D)
4764e8d8bef9SDimitry Andric       std::swap(A, B);
4765e8d8bef9SDimitry Andric     if (A == C)
4766e8d8bef9SDimitry Andric       std::swap(C, D);
4767e8d8bef9SDimitry Andric     if (A == D) {
4768e8d8bef9SDimitry Andric       Value *NotA = Builder.CreateNot(A);
4769e8d8bef9SDimitry Andric       return BinaryOperator::CreateAnd(Builder.CreateXor(B, C), NotA);
4770e8d8bef9SDimitry Andric     }
4771e8d8bef9SDimitry Andric   }
4772e8d8bef9SDimitry Andric 
477306c3fb27SDimitry Andric   // (A & B) ^ (A | C) --> A ? ~B : C -- There are 4 commuted variants.
477406c3fb27SDimitry Andric   if (I.getType()->isIntOrIntVectorTy(1) &&
477506c3fb27SDimitry Andric       match(Op0, m_OneUse(m_LogicalAnd(m_Value(A), m_Value(B)))) &&
477606c3fb27SDimitry Andric       match(Op1, m_OneUse(m_LogicalOr(m_Value(C), m_Value(D))))) {
477706c3fb27SDimitry Andric     bool NeedFreeze = isa<SelectInst>(Op0) && isa<SelectInst>(Op1) && B == D;
477806c3fb27SDimitry Andric     if (B == C || B == D)
477906c3fb27SDimitry Andric       std::swap(A, B);
478006c3fb27SDimitry Andric     if (A == C)
478106c3fb27SDimitry Andric       std::swap(C, D);
478206c3fb27SDimitry Andric     if (A == D) {
478306c3fb27SDimitry Andric       if (NeedFreeze)
478406c3fb27SDimitry Andric         A = Builder.CreateFreeze(A);
478506c3fb27SDimitry Andric       Value *NotB = Builder.CreateNot(B);
478606c3fb27SDimitry Andric       return SelectInst::Create(A, NotB, C);
478706c3fb27SDimitry Andric     }
478806c3fb27SDimitry Andric   }
478906c3fb27SDimitry Andric 
47900b57cec5SDimitry Andric   if (auto *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
47910b57cec5SDimitry Andric     if (auto *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
47928bcb0991SDimitry Andric       if (Value *V = foldXorOfICmps(LHS, RHS, I))
47930b57cec5SDimitry Andric         return replaceInstUsesWith(I, V);
47940b57cec5SDimitry Andric 
47950b57cec5SDimitry Andric   if (Instruction *CastedXor = foldCastedBitwiseLogic(I))
47960b57cec5SDimitry Andric     return CastedXor;
47970b57cec5SDimitry Andric 
4798fe6060f1SDimitry Andric   if (Instruction *Abs = canonicalizeAbs(I, Builder))
4799fe6060f1SDimitry Andric     return Abs;
4800fe6060f1SDimitry Andric 
4801e8d8bef9SDimitry Andric   // Otherwise, if all else failed, try to hoist the xor-by-constant:
4802e8d8bef9SDimitry Andric   //   (X ^ C) ^ Y --> (X ^ Y) ^ C
4803e8d8bef9SDimitry Andric   // Just like we do in other places, we completely avoid the fold
4804e8d8bef9SDimitry Andric   // for constantexprs, at least to avoid endless combine loop.
4805e8d8bef9SDimitry Andric   if (match(&I, m_c_Xor(m_OneUse(m_Xor(m_CombineAnd(m_Value(X),
4806e8d8bef9SDimitry Andric                                                     m_Unless(m_ConstantExpr())),
4807e8d8bef9SDimitry Andric                                        m_ImmConstant(C1))),
4808e8d8bef9SDimitry Andric                         m_Value(Y))))
4809e8d8bef9SDimitry Andric     return BinaryOperator::CreateXor(Builder.CreateXor(X, Y), C1);
4810e8d8bef9SDimitry Andric 
4811bdd1243dSDimitry Andric   if (Instruction *R = reassociateForUses(I, Builder))
4812bdd1243dSDimitry Andric     return R;
4813bdd1243dSDimitry Andric 
4814bdd1243dSDimitry Andric   if (Instruction *Canonicalized = canonicalizeLogicFirst(I, Builder))
4815bdd1243dSDimitry Andric     return Canonicalized;
4816bdd1243dSDimitry Andric 
4817bdd1243dSDimitry Andric   if (Instruction *Folded = foldLogicOfIsFPClass(I, Op0, Op1))
4818bdd1243dSDimitry Andric     return Folded;
4819bdd1243dSDimitry Andric 
4820bdd1243dSDimitry Andric   if (Instruction *Folded = canonicalizeConditionalNegationViaMathToSelect(I))
4821bdd1243dSDimitry Andric     return Folded;
4822bdd1243dSDimitry Andric 
482306c3fb27SDimitry Andric   if (Instruction *Res = foldBinOpOfDisplacedShifts(I))
482406c3fb27SDimitry Andric     return Res;
482506c3fb27SDimitry Andric 
4826297eecfbSDimitry Andric   if (Instruction *Res = foldBitwiseLogicWithIntrinsics(I, Builder))
4827297eecfbSDimitry Andric     return Res;
4828297eecfbSDimitry Andric 
48290b57cec5SDimitry Andric   return nullptr;
48300b57cec5SDimitry Andric }
4831