1 //===- InstCombineAndOrXor.cpp --------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the visitAnd, visitOr, and visitXor functions.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "InstCombineInternal.h"
14 #include "llvm/Analysis/CmpInstAnalysis.h"
15 #include "llvm/Analysis/InstructionSimplify.h"
16 #include "llvm/IR/ConstantRange.h"
17 #include "llvm/IR/Intrinsics.h"
18 #include "llvm/IR/PatternMatch.h"
19 #include "llvm/Transforms/InstCombine/InstCombiner.h"
20 #include "llvm/Transforms/Utils/Local.h"
21 
22 using namespace llvm;
23 using namespace PatternMatch;
24 
25 #define DEBUG_TYPE "instcombine"
26 
27 /// Similar to getICmpCode but for FCmpInst. This encodes a fcmp predicate into
28 /// a four bit mask.
29 static unsigned getFCmpCode(FCmpInst::Predicate CC) {
30   assert(FCmpInst::FCMP_FALSE <= CC && CC <= FCmpInst::FCMP_TRUE &&
31          "Unexpected FCmp predicate!");
32   // Take advantage of the bit pattern of FCmpInst::Predicate here.
33   //                                                 U L G E
34   static_assert(FCmpInst::FCMP_FALSE ==  0, "");  // 0 0 0 0
35   static_assert(FCmpInst::FCMP_OEQ   ==  1, "");  // 0 0 0 1
36   static_assert(FCmpInst::FCMP_OGT   ==  2, "");  // 0 0 1 0
37   static_assert(FCmpInst::FCMP_OGE   ==  3, "");  // 0 0 1 1
38   static_assert(FCmpInst::FCMP_OLT   ==  4, "");  // 0 1 0 0
39   static_assert(FCmpInst::FCMP_OLE   ==  5, "");  // 0 1 0 1
40   static_assert(FCmpInst::FCMP_ONE   ==  6, "");  // 0 1 1 0
41   static_assert(FCmpInst::FCMP_ORD   ==  7, "");  // 0 1 1 1
42   static_assert(FCmpInst::FCMP_UNO   ==  8, "");  // 1 0 0 0
43   static_assert(FCmpInst::FCMP_UEQ   ==  9, "");  // 1 0 0 1
44   static_assert(FCmpInst::FCMP_UGT   == 10, "");  // 1 0 1 0
45   static_assert(FCmpInst::FCMP_UGE   == 11, "");  // 1 0 1 1
46   static_assert(FCmpInst::FCMP_ULT   == 12, "");  // 1 1 0 0
47   static_assert(FCmpInst::FCMP_ULE   == 13, "");  // 1 1 0 1
48   static_assert(FCmpInst::FCMP_UNE   == 14, "");  // 1 1 1 0
49   static_assert(FCmpInst::FCMP_TRUE  == 15, "");  // 1 1 1 1
50   return CC;
51 }
52 
53 /// This is the complement of getICmpCode, which turns an opcode and two
54 /// operands into either a constant true or false, or a brand new ICmp
55 /// instruction. The sign is passed in to determine which kind of predicate to
56 /// use in the new icmp instruction.
57 static Value *getNewICmpValue(unsigned Code, bool Sign, Value *LHS, Value *RHS,
58                               InstCombiner::BuilderTy &Builder) {
59   ICmpInst::Predicate NewPred;
60   if (Constant *TorF = getPredForICmpCode(Code, Sign, LHS->getType(), NewPred))
61     return TorF;
62   return Builder.CreateICmp(NewPred, LHS, RHS);
63 }
64 
65 /// This is the complement of getFCmpCode, which turns an opcode and two
66 /// operands into either a FCmp instruction, or a true/false constant.
67 static Value *getFCmpValue(unsigned Code, Value *LHS, Value *RHS,
68                            InstCombiner::BuilderTy &Builder) {
69   const auto Pred = static_cast<FCmpInst::Predicate>(Code);
70   assert(FCmpInst::FCMP_FALSE <= Pred && Pred <= FCmpInst::FCMP_TRUE &&
71          "Unexpected FCmp predicate!");
72   if (Pred == FCmpInst::FCMP_FALSE)
73     return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
74   if (Pred == FCmpInst::FCMP_TRUE)
75     return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
76   return Builder.CreateFCmp(Pred, LHS, RHS);
77 }
78 
79 /// Transform BITWISE_OP(BSWAP(A),BSWAP(B)) or
80 /// BITWISE_OP(BSWAP(A), Constant) to BSWAP(BITWISE_OP(A, B))
81 /// \param I Binary operator to transform.
82 /// \return Pointer to node that must replace the original binary operator, or
83 ///         null pointer if no transformation was made.
84 static Value *SimplifyBSwap(BinaryOperator &I,
85                             InstCombiner::BuilderTy &Builder) {
86   assert(I.isBitwiseLogicOp() && "Unexpected opcode for bswap simplifying");
87 
88   Value *OldLHS = I.getOperand(0);
89   Value *OldRHS = I.getOperand(1);
90 
91   Value *NewLHS;
92   if (!match(OldLHS, m_BSwap(m_Value(NewLHS))))
93     return nullptr;
94 
95   Value *NewRHS;
96   const APInt *C;
97 
98   if (match(OldRHS, m_BSwap(m_Value(NewRHS)))) {
99     // OP( BSWAP(x), BSWAP(y) ) -> BSWAP( OP(x, y) )
100     if (!OldLHS->hasOneUse() && !OldRHS->hasOneUse())
101       return nullptr;
102     // NewRHS initialized by the matcher.
103   } else if (match(OldRHS, m_APInt(C))) {
104     // OP( BSWAP(x), CONSTANT ) -> BSWAP( OP(x, BSWAP(CONSTANT) ) )
105     if (!OldLHS->hasOneUse())
106       return nullptr;
107     NewRHS = ConstantInt::get(I.getType(), C->byteSwap());
108   } else
109     return nullptr;
110 
111   Value *BinOp = Builder.CreateBinOp(I.getOpcode(), NewLHS, NewRHS);
112   Function *F = Intrinsic::getDeclaration(I.getModule(), Intrinsic::bswap,
113                                           I.getType());
114   return Builder.CreateCall(F, BinOp);
115 }
116 
117 /// This handles expressions of the form ((val OP C1) & C2).  Where
118 /// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.
119 Instruction *InstCombinerImpl::OptAndOp(BinaryOperator *Op, ConstantInt *OpRHS,
120                                         ConstantInt *AndRHS,
121                                         BinaryOperator &TheAnd) {
122   Value *X = Op->getOperand(0);
123 
124   switch (Op->getOpcode()) {
125   default: break;
126   case Instruction::Add:
127     if (Op->hasOneUse()) {
128       // Adding a one to a single bit bit-field should be turned into an XOR
129       // of the bit.  First thing to check is to see if this AND is with a
130       // single bit constant.
131       const APInt &AndRHSV = AndRHS->getValue();
132 
133       // If there is only one bit set.
134       if (AndRHSV.isPowerOf2()) {
135         // Ok, at this point, we know that we are masking the result of the
136         // ADD down to exactly one bit.  If the constant we are adding has
137         // no bits set below this bit, then we can eliminate the ADD.
138         const APInt& AddRHS = OpRHS->getValue();
139 
140         // Check to see if any bits below the one bit set in AndRHSV are set.
141         if ((AddRHS & (AndRHSV - 1)).isNullValue()) {
142           // If not, the only thing that can effect the output of the AND is
143           // the bit specified by AndRHSV.  If that bit is set, the effect of
144           // the XOR is to toggle the bit.  If it is clear, then the ADD has
145           // no effect.
146           if ((AddRHS & AndRHSV).isNullValue()) { // Bit is not set, noop
147             return replaceOperand(TheAnd, 0, X);
148           } else {
149             // Pull the XOR out of the AND.
150             Value *NewAnd = Builder.CreateAnd(X, AndRHS);
151             NewAnd->takeName(Op);
152             return BinaryOperator::CreateXor(NewAnd, AndRHS);
153           }
154         }
155       }
156     }
157     break;
158   }
159   return nullptr;
160 }
161 
162 /// Emit a computation of: (V >= Lo && V < Hi) if Inside is true, otherwise
163 /// (V < Lo || V >= Hi). This method expects that Lo < Hi. IsSigned indicates
164 /// whether to treat V, Lo, and Hi as signed or not.
165 Value *InstCombinerImpl::insertRangeTest(Value *V, const APInt &Lo,
166                                          const APInt &Hi, bool isSigned,
167                                          bool Inside) {
168   assert((isSigned ? Lo.slt(Hi) : Lo.ult(Hi)) &&
169          "Lo is not < Hi in range emission code!");
170 
171   Type *Ty = V->getType();
172 
173   // V >= Min && V <  Hi --> V <  Hi
174   // V <  Min || V >= Hi --> V >= Hi
175   ICmpInst::Predicate Pred = Inside ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_UGE;
176   if (isSigned ? Lo.isMinSignedValue() : Lo.isMinValue()) {
177     Pred = isSigned ? ICmpInst::getSignedPredicate(Pred) : Pred;
178     return Builder.CreateICmp(Pred, V, ConstantInt::get(Ty, Hi));
179   }
180 
181   // V >= Lo && V <  Hi --> V - Lo u<  Hi - Lo
182   // V <  Lo || V >= Hi --> V - Lo u>= Hi - Lo
183   Value *VMinusLo =
184       Builder.CreateSub(V, ConstantInt::get(Ty, Lo), V->getName() + ".off");
185   Constant *HiMinusLo = ConstantInt::get(Ty, Hi - Lo);
186   return Builder.CreateICmp(Pred, VMinusLo, HiMinusLo);
187 }
188 
189 /// Classify (icmp eq (A & B), C) and (icmp ne (A & B), C) as matching patterns
190 /// that can be simplified.
191 /// One of A and B is considered the mask. The other is the value. This is
192 /// described as the "AMask" or "BMask" part of the enum. If the enum contains
193 /// only "Mask", then both A and B can be considered masks. If A is the mask,
194 /// then it was proven that (A & C) == C. This is trivial if C == A or C == 0.
195 /// If both A and C are constants, this proof is also easy.
196 /// For the following explanations, we assume that A is the mask.
197 ///
198 /// "AllOnes" declares that the comparison is true only if (A & B) == A or all
199 /// bits of A are set in B.
200 ///   Example: (icmp eq (A & 3), 3) -> AMask_AllOnes
201 ///
202 /// "AllZeros" declares that the comparison is true only if (A & B) == 0 or all
203 /// bits of A are cleared in B.
204 ///   Example: (icmp eq (A & 3), 0) -> Mask_AllZeroes
205 ///
206 /// "Mixed" declares that (A & B) == C and C might or might not contain any
207 /// number of one bits and zero bits.
208 ///   Example: (icmp eq (A & 3), 1) -> AMask_Mixed
209 ///
210 /// "Not" means that in above descriptions "==" should be replaced by "!=".
211 ///   Example: (icmp ne (A & 3), 3) -> AMask_NotAllOnes
212 ///
213 /// If the mask A contains a single bit, then the following is equivalent:
214 ///    (icmp eq (A & B), A) equals (icmp ne (A & B), 0)
215 ///    (icmp ne (A & B), A) equals (icmp eq (A & B), 0)
216 enum MaskedICmpType {
217   AMask_AllOnes           =     1,
218   AMask_NotAllOnes        =     2,
219   BMask_AllOnes           =     4,
220   BMask_NotAllOnes        =     8,
221   Mask_AllZeros           =    16,
222   Mask_NotAllZeros        =    32,
223   AMask_Mixed             =    64,
224   AMask_NotMixed          =   128,
225   BMask_Mixed             =   256,
226   BMask_NotMixed          =   512
227 };
228 
229 /// Return the set of patterns (from MaskedICmpType) that (icmp SCC (A & B), C)
230 /// satisfies.
231 static unsigned getMaskedICmpType(Value *A, Value *B, Value *C,
232                                   ICmpInst::Predicate Pred) {
233   ConstantInt *ACst = dyn_cast<ConstantInt>(A);
234   ConstantInt *BCst = dyn_cast<ConstantInt>(B);
235   ConstantInt *CCst = dyn_cast<ConstantInt>(C);
236   bool IsEq = (Pred == ICmpInst::ICMP_EQ);
237   bool IsAPow2 = (ACst && !ACst->isZero() && ACst->getValue().isPowerOf2());
238   bool IsBPow2 = (BCst && !BCst->isZero() && BCst->getValue().isPowerOf2());
239   unsigned MaskVal = 0;
240   if (CCst && CCst->isZero()) {
241     // if C is zero, then both A and B qualify as mask
242     MaskVal |= (IsEq ? (Mask_AllZeros | AMask_Mixed | BMask_Mixed)
243                      : (Mask_NotAllZeros | AMask_NotMixed | BMask_NotMixed));
244     if (IsAPow2)
245       MaskVal |= (IsEq ? (AMask_NotAllOnes | AMask_NotMixed)
246                        : (AMask_AllOnes | AMask_Mixed));
247     if (IsBPow2)
248       MaskVal |= (IsEq ? (BMask_NotAllOnes | BMask_NotMixed)
249                        : (BMask_AllOnes | BMask_Mixed));
250     return MaskVal;
251   }
252 
253   if (A == C) {
254     MaskVal |= (IsEq ? (AMask_AllOnes | AMask_Mixed)
255                      : (AMask_NotAllOnes | AMask_NotMixed));
256     if (IsAPow2)
257       MaskVal |= (IsEq ? (Mask_NotAllZeros | AMask_NotMixed)
258                        : (Mask_AllZeros | AMask_Mixed));
259   } else if (ACst && CCst && ConstantExpr::getAnd(ACst, CCst) == CCst) {
260     MaskVal |= (IsEq ? AMask_Mixed : AMask_NotMixed);
261   }
262 
263   if (B == C) {
264     MaskVal |= (IsEq ? (BMask_AllOnes | BMask_Mixed)
265                      : (BMask_NotAllOnes | BMask_NotMixed));
266     if (IsBPow2)
267       MaskVal |= (IsEq ? (Mask_NotAllZeros | BMask_NotMixed)
268                        : (Mask_AllZeros | BMask_Mixed));
269   } else if (BCst && CCst && ConstantExpr::getAnd(BCst, CCst) == CCst) {
270     MaskVal |= (IsEq ? BMask_Mixed : BMask_NotMixed);
271   }
272 
273   return MaskVal;
274 }
275 
276 /// Convert an analysis of a masked ICmp into its equivalent if all boolean
277 /// operations had the opposite sense. Since each "NotXXX" flag (recording !=)
278 /// is adjacent to the corresponding normal flag (recording ==), this just
279 /// involves swapping those bits over.
280 static unsigned conjugateICmpMask(unsigned Mask) {
281   unsigned NewMask;
282   NewMask = (Mask & (AMask_AllOnes | BMask_AllOnes | Mask_AllZeros |
283                      AMask_Mixed | BMask_Mixed))
284             << 1;
285 
286   NewMask |= (Mask & (AMask_NotAllOnes | BMask_NotAllOnes | Mask_NotAllZeros |
287                       AMask_NotMixed | BMask_NotMixed))
288              >> 1;
289 
290   return NewMask;
291 }
292 
293 // Adapts the external decomposeBitTestICmp for local use.
294 static bool decomposeBitTestICmp(Value *LHS, Value *RHS, CmpInst::Predicate &Pred,
295                                  Value *&X, Value *&Y, Value *&Z) {
296   APInt Mask;
297   if (!llvm::decomposeBitTestICmp(LHS, RHS, Pred, X, Mask))
298     return false;
299 
300   Y = ConstantInt::get(X->getType(), Mask);
301   Z = ConstantInt::get(X->getType(), 0);
302   return true;
303 }
304 
305 /// Handle (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E).
306 /// Return the pattern classes (from MaskedICmpType) for the left hand side and
307 /// the right hand side as a pair.
308 /// LHS and RHS are the left hand side and the right hand side ICmps and PredL
309 /// and PredR are their predicates, respectively.
310 static
311 Optional<std::pair<unsigned, unsigned>>
312 getMaskedTypeForICmpPair(Value *&A, Value *&B, Value *&C,
313                          Value *&D, Value *&E, ICmpInst *LHS,
314                          ICmpInst *RHS,
315                          ICmpInst::Predicate &PredL,
316                          ICmpInst::Predicate &PredR) {
317   // vectors are not (yet?) supported. Don't support pointers either.
318   if (!LHS->getOperand(0)->getType()->isIntegerTy() ||
319       !RHS->getOperand(0)->getType()->isIntegerTy())
320     return None;
321 
322   // Here comes the tricky part:
323   // LHS might be of the form L11 & L12 == X, X == L21 & L22,
324   // and L11 & L12 == L21 & L22. The same goes for RHS.
325   // Now we must find those components L** and R**, that are equal, so
326   // that we can extract the parameters A, B, C, D, and E for the canonical
327   // above.
328   Value *L1 = LHS->getOperand(0);
329   Value *L2 = LHS->getOperand(1);
330   Value *L11, *L12, *L21, *L22;
331   // Check whether the icmp can be decomposed into a bit test.
332   if (decomposeBitTestICmp(L1, L2, PredL, L11, L12, L2)) {
333     L21 = L22 = L1 = nullptr;
334   } else {
335     // Look for ANDs in the LHS icmp.
336     if (!match(L1, m_And(m_Value(L11), m_Value(L12)))) {
337       // Any icmp can be viewed as being trivially masked; if it allows us to
338       // remove one, it's worth it.
339       L11 = L1;
340       L12 = Constant::getAllOnesValue(L1->getType());
341     }
342 
343     if (!match(L2, m_And(m_Value(L21), m_Value(L22)))) {
344       L21 = L2;
345       L22 = Constant::getAllOnesValue(L2->getType());
346     }
347   }
348 
349   // Bail if LHS was a icmp that can't be decomposed into an equality.
350   if (!ICmpInst::isEquality(PredL))
351     return None;
352 
353   Value *R1 = RHS->getOperand(0);
354   Value *R2 = RHS->getOperand(1);
355   Value *R11, *R12;
356   bool Ok = false;
357   if (decomposeBitTestICmp(R1, R2, PredR, R11, R12, R2)) {
358     if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
359       A = R11;
360       D = R12;
361     } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
362       A = R12;
363       D = R11;
364     } else {
365       return None;
366     }
367     E = R2;
368     R1 = nullptr;
369     Ok = true;
370   } else {
371     if (!match(R1, m_And(m_Value(R11), m_Value(R12)))) {
372       // As before, model no mask as a trivial mask if it'll let us do an
373       // optimization.
374       R11 = R1;
375       R12 = Constant::getAllOnesValue(R1->getType());
376     }
377 
378     if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
379       A = R11;
380       D = R12;
381       E = R2;
382       Ok = true;
383     } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
384       A = R12;
385       D = R11;
386       E = R2;
387       Ok = true;
388     }
389   }
390 
391   // Bail if RHS was a icmp that can't be decomposed into an equality.
392   if (!ICmpInst::isEquality(PredR))
393     return None;
394 
395   // Look for ANDs on the right side of the RHS icmp.
396   if (!Ok) {
397     if (!match(R2, m_And(m_Value(R11), m_Value(R12)))) {
398       R11 = R2;
399       R12 = Constant::getAllOnesValue(R2->getType());
400     }
401 
402     if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
403       A = R11;
404       D = R12;
405       E = R1;
406       Ok = true;
407     } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
408       A = R12;
409       D = R11;
410       E = R1;
411       Ok = true;
412     } else {
413       return None;
414     }
415   }
416   if (!Ok)
417     return None;
418 
419   if (L11 == A) {
420     B = L12;
421     C = L2;
422   } else if (L12 == A) {
423     B = L11;
424     C = L2;
425   } else if (L21 == A) {
426     B = L22;
427     C = L1;
428   } else if (L22 == A) {
429     B = L21;
430     C = L1;
431   }
432 
433   unsigned LeftType = getMaskedICmpType(A, B, C, PredL);
434   unsigned RightType = getMaskedICmpType(A, D, E, PredR);
435   return Optional<std::pair<unsigned, unsigned>>(std::make_pair(LeftType, RightType));
436 }
437 
438 /// Try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E) into a single
439 /// (icmp(A & X) ==/!= Y), where the left-hand side is of type Mask_NotAllZeros
440 /// and the right hand side is of type BMask_Mixed. For example,
441 /// (icmp (A & 12) != 0) & (icmp (A & 15) == 8) -> (icmp (A & 15) == 8).
442 static Value *foldLogOpOfMaskedICmps_NotAllZeros_BMask_Mixed(
443     ICmpInst *LHS, ICmpInst *RHS, bool IsAnd, Value *A, Value *B, Value *C,
444     Value *D, Value *E, ICmpInst::Predicate PredL, ICmpInst::Predicate PredR,
445     InstCombiner::BuilderTy &Builder) {
446   // We are given the canonical form:
447   //   (icmp ne (A & B), 0) & (icmp eq (A & D), E).
448   // where D & E == E.
449   //
450   // If IsAnd is false, we get it in negated form:
451   //   (icmp eq (A & B), 0) | (icmp ne (A & D), E) ->
452   //      !((icmp ne (A & B), 0) & (icmp eq (A & D), E)).
453   //
454   // We currently handle the case of B, C, D, E are constant.
455   //
456   ConstantInt *BCst, *CCst, *DCst, *ECst;
457   if (!match(B, m_ConstantInt(BCst)) || !match(C, m_ConstantInt(CCst)) ||
458       !match(D, m_ConstantInt(DCst)) || !match(E, m_ConstantInt(ECst)))
459     return nullptr;
460 
461   ICmpInst::Predicate NewCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
462 
463   // Update E to the canonical form when D is a power of two and RHS is
464   // canonicalized as,
465   // (icmp ne (A & D), 0) -> (icmp eq (A & D), D) or
466   // (icmp ne (A & D), D) -> (icmp eq (A & D), 0).
467   if (PredR != NewCC)
468     ECst = cast<ConstantInt>(ConstantExpr::getXor(DCst, ECst));
469 
470   // If B or D is zero, skip because if LHS or RHS can be trivially folded by
471   // other folding rules and this pattern won't apply any more.
472   if (BCst->getValue() == 0 || DCst->getValue() == 0)
473     return nullptr;
474 
475   // If B and D don't intersect, ie. (B & D) == 0, no folding because we can't
476   // deduce anything from it.
477   // For example,
478   // (icmp ne (A & 12), 0) & (icmp eq (A & 3), 1) -> no folding.
479   if ((BCst->getValue() & DCst->getValue()) == 0)
480     return nullptr;
481 
482   // If the following two conditions are met:
483   //
484   // 1. mask B covers only a single bit that's not covered by mask D, that is,
485   // (B & (B ^ D)) is a power of 2 (in other words, B minus the intersection of
486   // B and D has only one bit set) and,
487   //
488   // 2. RHS (and E) indicates that the rest of B's bits are zero (in other
489   // words, the intersection of B and D is zero), that is, ((B & D) & E) == 0
490   //
491   // then that single bit in B must be one and thus the whole expression can be
492   // folded to
493   //   (A & (B | D)) == (B & (B ^ D)) | E.
494   //
495   // For example,
496   // (icmp ne (A & 12), 0) & (icmp eq (A & 7), 1) -> (icmp eq (A & 15), 9)
497   // (icmp ne (A & 15), 0) & (icmp eq (A & 7), 0) -> (icmp eq (A & 15), 8)
498   if ((((BCst->getValue() & DCst->getValue()) & ECst->getValue()) == 0) &&
499       (BCst->getValue() & (BCst->getValue() ^ DCst->getValue())).isPowerOf2()) {
500     APInt BorD = BCst->getValue() | DCst->getValue();
501     APInt BandBxorDorE = (BCst->getValue() & (BCst->getValue() ^ DCst->getValue())) |
502         ECst->getValue();
503     Value *NewMask = ConstantInt::get(BCst->getType(), BorD);
504     Value *NewMaskedValue = ConstantInt::get(BCst->getType(), BandBxorDorE);
505     Value *NewAnd = Builder.CreateAnd(A, NewMask);
506     return Builder.CreateICmp(NewCC, NewAnd, NewMaskedValue);
507   }
508 
509   auto IsSubSetOrEqual = [](ConstantInt *C1, ConstantInt *C2) {
510     return (C1->getValue() & C2->getValue()) == C1->getValue();
511   };
512   auto IsSuperSetOrEqual = [](ConstantInt *C1, ConstantInt *C2) {
513     return (C1->getValue() & C2->getValue()) == C2->getValue();
514   };
515 
516   // In the following, we consider only the cases where B is a superset of D, B
517   // is a subset of D, or B == D because otherwise there's at least one bit
518   // covered by B but not D, in which case we can't deduce much from it, so
519   // no folding (aside from the single must-be-one bit case right above.)
520   // For example,
521   // (icmp ne (A & 14), 0) & (icmp eq (A & 3), 1) -> no folding.
522   if (!IsSubSetOrEqual(BCst, DCst) && !IsSuperSetOrEqual(BCst, DCst))
523     return nullptr;
524 
525   // At this point, either B is a superset of D, B is a subset of D or B == D.
526 
527   // If E is zero, if B is a subset of (or equal to) D, LHS and RHS contradict
528   // and the whole expression becomes false (or true if negated), otherwise, no
529   // folding.
530   // For example,
531   // (icmp ne (A & 3), 0) & (icmp eq (A & 7), 0) -> false.
532   // (icmp ne (A & 15), 0) & (icmp eq (A & 3), 0) -> no folding.
533   if (ECst->isZero()) {
534     if (IsSubSetOrEqual(BCst, DCst))
535       return ConstantInt::get(LHS->getType(), !IsAnd);
536     return nullptr;
537   }
538 
539   // At this point, B, D, E aren't zero and (B & D) == B, (B & D) == D or B ==
540   // D. If B is a superset of (or equal to) D, since E is not zero, LHS is
541   // subsumed by RHS (RHS implies LHS.) So the whole expression becomes
542   // RHS. For example,
543   // (icmp ne (A & 255), 0) & (icmp eq (A & 15), 8) -> (icmp eq (A & 15), 8).
544   // (icmp ne (A & 15), 0) & (icmp eq (A & 15), 8) -> (icmp eq (A & 15), 8).
545   if (IsSuperSetOrEqual(BCst, DCst))
546     return RHS;
547   // Otherwise, B is a subset of D. If B and E have a common bit set,
548   // ie. (B & E) != 0, then LHS is subsumed by RHS. For example.
549   // (icmp ne (A & 12), 0) & (icmp eq (A & 15), 8) -> (icmp eq (A & 15), 8).
550   assert(IsSubSetOrEqual(BCst, DCst) && "Precondition due to above code");
551   if ((BCst->getValue() & ECst->getValue()) != 0)
552     return RHS;
553   // Otherwise, LHS and RHS contradict and the whole expression becomes false
554   // (or true if negated.) For example,
555   // (icmp ne (A & 7), 0) & (icmp eq (A & 15), 8) -> false.
556   // (icmp ne (A & 6), 0) & (icmp eq (A & 15), 8) -> false.
557   return ConstantInt::get(LHS->getType(), !IsAnd);
558 }
559 
560 /// Try to fold (icmp(A & B) ==/!= 0) &/| (icmp(A & D) ==/!= E) into a single
561 /// (icmp(A & X) ==/!= Y), where the left-hand side and the right hand side
562 /// aren't of the common mask pattern type.
563 static Value *foldLogOpOfMaskedICmpsAsymmetric(
564     ICmpInst *LHS, ICmpInst *RHS, bool IsAnd, Value *A, Value *B, Value *C,
565     Value *D, Value *E, ICmpInst::Predicate PredL, ICmpInst::Predicate PredR,
566     unsigned LHSMask, unsigned RHSMask, InstCombiner::BuilderTy &Builder) {
567   assert(ICmpInst::isEquality(PredL) && ICmpInst::isEquality(PredR) &&
568          "Expected equality predicates for masked type of icmps.");
569   // Handle Mask_NotAllZeros-BMask_Mixed cases.
570   // (icmp ne/eq (A & B), C) &/| (icmp eq/ne (A & D), E), or
571   // (icmp eq/ne (A & B), C) &/| (icmp ne/eq (A & D), E)
572   //    which gets swapped to
573   //    (icmp ne/eq (A & D), E) &/| (icmp eq/ne (A & B), C).
574   if (!IsAnd) {
575     LHSMask = conjugateICmpMask(LHSMask);
576     RHSMask = conjugateICmpMask(RHSMask);
577   }
578   if ((LHSMask & Mask_NotAllZeros) && (RHSMask & BMask_Mixed)) {
579     if (Value *V = foldLogOpOfMaskedICmps_NotAllZeros_BMask_Mixed(
580             LHS, RHS, IsAnd, A, B, C, D, E,
581             PredL, PredR, Builder)) {
582       return V;
583     }
584   } else if ((LHSMask & BMask_Mixed) && (RHSMask & Mask_NotAllZeros)) {
585     if (Value *V = foldLogOpOfMaskedICmps_NotAllZeros_BMask_Mixed(
586             RHS, LHS, IsAnd, A, D, E, B, C,
587             PredR, PredL, Builder)) {
588       return V;
589     }
590   }
591   return nullptr;
592 }
593 
594 /// Try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
595 /// into a single (icmp(A & X) ==/!= Y).
596 static Value *foldLogOpOfMaskedICmps(ICmpInst *LHS, ICmpInst *RHS, bool IsAnd,
597                                      InstCombiner::BuilderTy &Builder) {
598   Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr, *E = nullptr;
599   ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
600   Optional<std::pair<unsigned, unsigned>> MaskPair =
601       getMaskedTypeForICmpPair(A, B, C, D, E, LHS, RHS, PredL, PredR);
602   if (!MaskPair)
603     return nullptr;
604   assert(ICmpInst::isEquality(PredL) && ICmpInst::isEquality(PredR) &&
605          "Expected equality predicates for masked type of icmps.");
606   unsigned LHSMask = MaskPair->first;
607   unsigned RHSMask = MaskPair->second;
608   unsigned Mask = LHSMask & RHSMask;
609   if (Mask == 0) {
610     // Even if the two sides don't share a common pattern, check if folding can
611     // still happen.
612     if (Value *V = foldLogOpOfMaskedICmpsAsymmetric(
613             LHS, RHS, IsAnd, A, B, C, D, E, PredL, PredR, LHSMask, RHSMask,
614             Builder))
615       return V;
616     return nullptr;
617   }
618 
619   // In full generality:
620   //     (icmp (A & B) Op C) | (icmp (A & D) Op E)
621   // ==  ![ (icmp (A & B) !Op C) & (icmp (A & D) !Op E) ]
622   //
623   // If the latter can be converted into (icmp (A & X) Op Y) then the former is
624   // equivalent to (icmp (A & X) !Op Y).
625   //
626   // Therefore, we can pretend for the rest of this function that we're dealing
627   // with the conjunction, provided we flip the sense of any comparisons (both
628   // input and output).
629 
630   // In most cases we're going to produce an EQ for the "&&" case.
631   ICmpInst::Predicate NewCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
632   if (!IsAnd) {
633     // Convert the masking analysis into its equivalent with negated
634     // comparisons.
635     Mask = conjugateICmpMask(Mask);
636   }
637 
638   if (Mask & Mask_AllZeros) {
639     // (icmp eq (A & B), 0) & (icmp eq (A & D), 0)
640     // -> (icmp eq (A & (B|D)), 0)
641     Value *NewOr = Builder.CreateOr(B, D);
642     Value *NewAnd = Builder.CreateAnd(A, NewOr);
643     // We can't use C as zero because we might actually handle
644     //   (icmp ne (A & B), B) & (icmp ne (A & D), D)
645     // with B and D, having a single bit set.
646     Value *Zero = Constant::getNullValue(A->getType());
647     return Builder.CreateICmp(NewCC, NewAnd, Zero);
648   }
649   if (Mask & BMask_AllOnes) {
650     // (icmp eq (A & B), B) & (icmp eq (A & D), D)
651     // -> (icmp eq (A & (B|D)), (B|D))
652     Value *NewOr = Builder.CreateOr(B, D);
653     Value *NewAnd = Builder.CreateAnd(A, NewOr);
654     return Builder.CreateICmp(NewCC, NewAnd, NewOr);
655   }
656   if (Mask & AMask_AllOnes) {
657     // (icmp eq (A & B), A) & (icmp eq (A & D), A)
658     // -> (icmp eq (A & (B&D)), A)
659     Value *NewAnd1 = Builder.CreateAnd(B, D);
660     Value *NewAnd2 = Builder.CreateAnd(A, NewAnd1);
661     return Builder.CreateICmp(NewCC, NewAnd2, A);
662   }
663 
664   // Remaining cases assume at least that B and D are constant, and depend on
665   // their actual values. This isn't strictly necessary, just a "handle the
666   // easy cases for now" decision.
667   ConstantInt *BCst, *DCst;
668   if (!match(B, m_ConstantInt(BCst)) || !match(D, m_ConstantInt(DCst)))
669     return nullptr;
670 
671   if (Mask & (Mask_NotAllZeros | BMask_NotAllOnes)) {
672     // (icmp ne (A & B), 0) & (icmp ne (A & D), 0) and
673     // (icmp ne (A & B), B) & (icmp ne (A & D), D)
674     //     -> (icmp ne (A & B), 0) or (icmp ne (A & D), 0)
675     // Only valid if one of the masks is a superset of the other (check "B&D" is
676     // the same as either B or D).
677     APInt NewMask = BCst->getValue() & DCst->getValue();
678 
679     if (NewMask == BCst->getValue())
680       return LHS;
681     else if (NewMask == DCst->getValue())
682       return RHS;
683   }
684 
685   if (Mask & AMask_NotAllOnes) {
686     // (icmp ne (A & B), B) & (icmp ne (A & D), D)
687     //     -> (icmp ne (A & B), A) or (icmp ne (A & D), A)
688     // Only valid if one of the masks is a superset of the other (check "B|D" is
689     // the same as either B or D).
690     APInt NewMask = BCst->getValue() | DCst->getValue();
691 
692     if (NewMask == BCst->getValue())
693       return LHS;
694     else if (NewMask == DCst->getValue())
695       return RHS;
696   }
697 
698   if (Mask & BMask_Mixed) {
699     // (icmp eq (A & B), C) & (icmp eq (A & D), E)
700     // We already know that B & C == C && D & E == E.
701     // If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of
702     // C and E, which are shared by both the mask B and the mask D, don't
703     // contradict, then we can transform to
704     // -> (icmp eq (A & (B|D)), (C|E))
705     // Currently, we only handle the case of B, C, D, and E being constant.
706     // We can't simply use C and E because we might actually handle
707     //   (icmp ne (A & B), B) & (icmp eq (A & D), D)
708     // with B and D, having a single bit set.
709     ConstantInt *CCst, *ECst;
710     if (!match(C, m_ConstantInt(CCst)) || !match(E, m_ConstantInt(ECst)))
711       return nullptr;
712     if (PredL != NewCC)
713       CCst = cast<ConstantInt>(ConstantExpr::getXor(BCst, CCst));
714     if (PredR != NewCC)
715       ECst = cast<ConstantInt>(ConstantExpr::getXor(DCst, ECst));
716 
717     // If there is a conflict, we should actually return a false for the
718     // whole construct.
719     if (((BCst->getValue() & DCst->getValue()) &
720          (CCst->getValue() ^ ECst->getValue())).getBoolValue())
721       return ConstantInt::get(LHS->getType(), !IsAnd);
722 
723     Value *NewOr1 = Builder.CreateOr(B, D);
724     Value *NewOr2 = ConstantExpr::getOr(CCst, ECst);
725     Value *NewAnd = Builder.CreateAnd(A, NewOr1);
726     return Builder.CreateICmp(NewCC, NewAnd, NewOr2);
727   }
728 
729   return nullptr;
730 }
731 
732 /// Try to fold a signed range checked with lower bound 0 to an unsigned icmp.
733 /// Example: (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
734 /// If \p Inverted is true then the check is for the inverted range, e.g.
735 /// (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
736 Value *InstCombinerImpl::simplifyRangeCheck(ICmpInst *Cmp0, ICmpInst *Cmp1,
737                                             bool Inverted) {
738   // Check the lower range comparison, e.g. x >= 0
739   // InstCombine already ensured that if there is a constant it's on the RHS.
740   ConstantInt *RangeStart = dyn_cast<ConstantInt>(Cmp0->getOperand(1));
741   if (!RangeStart)
742     return nullptr;
743 
744   ICmpInst::Predicate Pred0 = (Inverted ? Cmp0->getInversePredicate() :
745                                Cmp0->getPredicate());
746 
747   // Accept x > -1 or x >= 0 (after potentially inverting the predicate).
748   if (!((Pred0 == ICmpInst::ICMP_SGT && RangeStart->isMinusOne()) ||
749         (Pred0 == ICmpInst::ICMP_SGE && RangeStart->isZero())))
750     return nullptr;
751 
752   ICmpInst::Predicate Pred1 = (Inverted ? Cmp1->getInversePredicate() :
753                                Cmp1->getPredicate());
754 
755   Value *Input = Cmp0->getOperand(0);
756   Value *RangeEnd;
757   if (Cmp1->getOperand(0) == Input) {
758     // For the upper range compare we have: icmp x, n
759     RangeEnd = Cmp1->getOperand(1);
760   } else if (Cmp1->getOperand(1) == Input) {
761     // For the upper range compare we have: icmp n, x
762     RangeEnd = Cmp1->getOperand(0);
763     Pred1 = ICmpInst::getSwappedPredicate(Pred1);
764   } else {
765     return nullptr;
766   }
767 
768   // Check the upper range comparison, e.g. x < n
769   ICmpInst::Predicate NewPred;
770   switch (Pred1) {
771     case ICmpInst::ICMP_SLT: NewPred = ICmpInst::ICMP_ULT; break;
772     case ICmpInst::ICMP_SLE: NewPred = ICmpInst::ICMP_ULE; break;
773     default: return nullptr;
774   }
775 
776   // This simplification is only valid if the upper range is not negative.
777   KnownBits Known = computeKnownBits(RangeEnd, /*Depth=*/0, Cmp1);
778   if (!Known.isNonNegative())
779     return nullptr;
780 
781   if (Inverted)
782     NewPred = ICmpInst::getInversePredicate(NewPred);
783 
784   return Builder.CreateICmp(NewPred, Input, RangeEnd);
785 }
786 
787 static Value *
788 foldAndOrOfEqualityCmpsWithConstants(ICmpInst *LHS, ICmpInst *RHS,
789                                      bool JoinedByAnd,
790                                      InstCombiner::BuilderTy &Builder) {
791   Value *X = LHS->getOperand(0);
792   if (X != RHS->getOperand(0))
793     return nullptr;
794 
795   const APInt *C1, *C2;
796   if (!match(LHS->getOperand(1), m_APInt(C1)) ||
797       !match(RHS->getOperand(1), m_APInt(C2)))
798     return nullptr;
799 
800   // We only handle (X != C1 && X != C2) and (X == C1 || X == C2).
801   ICmpInst::Predicate Pred = LHS->getPredicate();
802   if (Pred !=  RHS->getPredicate())
803     return nullptr;
804   if (JoinedByAnd && Pred != ICmpInst::ICMP_NE)
805     return nullptr;
806   if (!JoinedByAnd && Pred != ICmpInst::ICMP_EQ)
807     return nullptr;
808 
809   // The larger unsigned constant goes on the right.
810   if (C1->ugt(*C2))
811     std::swap(C1, C2);
812 
813   APInt Xor = *C1 ^ *C2;
814   if (Xor.isPowerOf2()) {
815     // If LHSC and RHSC differ by only one bit, then set that bit in X and
816     // compare against the larger constant:
817     // (X == C1 || X == C2) --> (X | (C1 ^ C2)) == C2
818     // (X != C1 && X != C2) --> (X | (C1 ^ C2)) != C2
819     // We choose an 'or' with a Pow2 constant rather than the inverse mask with
820     // 'and' because that may lead to smaller codegen from a smaller constant.
821     Value *Or = Builder.CreateOr(X, ConstantInt::get(X->getType(), Xor));
822     return Builder.CreateICmp(Pred, Or, ConstantInt::get(X->getType(), *C2));
823   }
824 
825   // Special case: get the ordering right when the values wrap around zero.
826   // Ie, we assumed the constants were unsigned when swapping earlier.
827   if (C1->isNullValue() && C2->isAllOnesValue())
828     std::swap(C1, C2);
829 
830   if (*C1 == *C2 - 1) {
831     // (X == 13 || X == 14) --> X - 13 <=u 1
832     // (X != 13 && X != 14) --> X - 13  >u 1
833     // An 'add' is the canonical IR form, so favor that over a 'sub'.
834     Value *Add = Builder.CreateAdd(X, ConstantInt::get(X->getType(), -(*C1)));
835     auto NewPred = JoinedByAnd ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_ULE;
836     return Builder.CreateICmp(NewPred, Add, ConstantInt::get(X->getType(), 1));
837   }
838 
839   return nullptr;
840 }
841 
842 // Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
843 // Fold (!iszero(A & K1) & !iszero(A & K2)) -> (A & (K1 | K2)) == (K1 | K2)
844 Value *InstCombinerImpl::foldAndOrOfICmpsOfAndWithPow2(ICmpInst *LHS,
845                                                        ICmpInst *RHS,
846                                                        BinaryOperator &Logic) {
847   bool JoinedByAnd = Logic.getOpcode() == Instruction::And;
848   assert((JoinedByAnd || Logic.getOpcode() == Instruction::Or) &&
849          "Wrong opcode");
850   ICmpInst::Predicate Pred = LHS->getPredicate();
851   if (Pred != RHS->getPredicate())
852     return nullptr;
853   if (JoinedByAnd && Pred != ICmpInst::ICMP_NE)
854     return nullptr;
855   if (!JoinedByAnd && Pred != ICmpInst::ICMP_EQ)
856     return nullptr;
857 
858   if (!match(LHS->getOperand(1), m_Zero()) ||
859       !match(RHS->getOperand(1), m_Zero()))
860     return nullptr;
861 
862   Value *A, *B, *C, *D;
863   if (match(LHS->getOperand(0), m_And(m_Value(A), m_Value(B))) &&
864       match(RHS->getOperand(0), m_And(m_Value(C), m_Value(D)))) {
865     if (A == D || B == D)
866       std::swap(C, D);
867     if (B == C)
868       std::swap(A, B);
869 
870     if (A == C &&
871         isKnownToBeAPowerOfTwo(B, false, 0, &Logic) &&
872         isKnownToBeAPowerOfTwo(D, false, 0, &Logic)) {
873       Value *Mask = Builder.CreateOr(B, D);
874       Value *Masked = Builder.CreateAnd(A, Mask);
875       auto NewPred = JoinedByAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
876       return Builder.CreateICmp(NewPred, Masked, Mask);
877     }
878   }
879 
880   return nullptr;
881 }
882 
883 /// General pattern:
884 ///   X & Y
885 ///
886 /// Where Y is checking that all the high bits (covered by a mask 4294967168)
887 /// are uniform, i.e.  %arg & 4294967168  can be either  4294967168  or  0
888 /// Pattern can be one of:
889 ///   %t = add        i32 %arg,    128
890 ///   %r = icmp   ult i32 %t,      256
891 /// Or
892 ///   %t0 = shl       i32 %arg,    24
893 ///   %t1 = ashr      i32 %t0,     24
894 ///   %r  = icmp  eq  i32 %t1,     %arg
895 /// Or
896 ///   %t0 = trunc     i32 %arg  to i8
897 ///   %t1 = sext      i8  %t0   to i32
898 ///   %r  = icmp  eq  i32 %t1,     %arg
899 /// This pattern is a signed truncation check.
900 ///
901 /// And X is checking that some bit in that same mask is zero.
902 /// I.e. can be one of:
903 ///   %r = icmp sgt i32   %arg,    -1
904 /// Or
905 ///   %t = and      i32   %arg,    2147483648
906 ///   %r = icmp eq  i32   %t,      0
907 ///
908 /// Since we are checking that all the bits in that mask are the same,
909 /// and a particular bit is zero, what we are really checking is that all the
910 /// masked bits are zero.
911 /// So this should be transformed to:
912 ///   %r = icmp ult i32 %arg, 128
913 static Value *foldSignedTruncationCheck(ICmpInst *ICmp0, ICmpInst *ICmp1,
914                                         Instruction &CxtI,
915                                         InstCombiner::BuilderTy &Builder) {
916   assert(CxtI.getOpcode() == Instruction::And);
917 
918   // Match  icmp ult (add %arg, C01), C1   (C1 == C01 << 1; powers of two)
919   auto tryToMatchSignedTruncationCheck = [](ICmpInst *ICmp, Value *&X,
920                                             APInt &SignBitMask) -> bool {
921     CmpInst::Predicate Pred;
922     const APInt *I01, *I1; // powers of two; I1 == I01 << 1
923     if (!(match(ICmp,
924                 m_ICmp(Pred, m_Add(m_Value(X), m_Power2(I01)), m_Power2(I1))) &&
925           Pred == ICmpInst::ICMP_ULT && I1->ugt(*I01) && I01->shl(1) == *I1))
926       return false;
927     // Which bit is the new sign bit as per the 'signed truncation' pattern?
928     SignBitMask = *I01;
929     return true;
930   };
931 
932   // One icmp needs to be 'signed truncation check'.
933   // We need to match this first, else we will mismatch commutative cases.
934   Value *X1;
935   APInt HighestBit;
936   ICmpInst *OtherICmp;
937   if (tryToMatchSignedTruncationCheck(ICmp1, X1, HighestBit))
938     OtherICmp = ICmp0;
939   else if (tryToMatchSignedTruncationCheck(ICmp0, X1, HighestBit))
940     OtherICmp = ICmp1;
941   else
942     return nullptr;
943 
944   assert(HighestBit.isPowerOf2() && "expected to be power of two (non-zero)");
945 
946   // Try to match/decompose into:  icmp eq (X & Mask), 0
947   auto tryToDecompose = [](ICmpInst *ICmp, Value *&X,
948                            APInt &UnsetBitsMask) -> bool {
949     CmpInst::Predicate Pred = ICmp->getPredicate();
950     // Can it be decomposed into  icmp eq (X & Mask), 0  ?
951     if (llvm::decomposeBitTestICmp(ICmp->getOperand(0), ICmp->getOperand(1),
952                                    Pred, X, UnsetBitsMask,
953                                    /*LookThroughTrunc=*/false) &&
954         Pred == ICmpInst::ICMP_EQ)
955       return true;
956     // Is it  icmp eq (X & Mask), 0  already?
957     const APInt *Mask;
958     if (match(ICmp, m_ICmp(Pred, m_And(m_Value(X), m_APInt(Mask)), m_Zero())) &&
959         Pred == ICmpInst::ICMP_EQ) {
960       UnsetBitsMask = *Mask;
961       return true;
962     }
963     return false;
964   };
965 
966   // And the other icmp needs to be decomposable into a bit test.
967   Value *X0;
968   APInt UnsetBitsMask;
969   if (!tryToDecompose(OtherICmp, X0, UnsetBitsMask))
970     return nullptr;
971 
972   assert(!UnsetBitsMask.isNullValue() && "empty mask makes no sense.");
973 
974   // Are they working on the same value?
975   Value *X;
976   if (X1 == X0) {
977     // Ok as is.
978     X = X1;
979   } else if (match(X0, m_Trunc(m_Specific(X1)))) {
980     UnsetBitsMask = UnsetBitsMask.zext(X1->getType()->getScalarSizeInBits());
981     X = X1;
982   } else
983     return nullptr;
984 
985   // So which bits should be uniform as per the 'signed truncation check'?
986   // (all the bits starting with (i.e. including) HighestBit)
987   APInt SignBitsMask = ~(HighestBit - 1U);
988 
989   // UnsetBitsMask must have some common bits with SignBitsMask,
990   if (!UnsetBitsMask.intersects(SignBitsMask))
991     return nullptr;
992 
993   // Does UnsetBitsMask contain any bits outside of SignBitsMask?
994   if (!UnsetBitsMask.isSubsetOf(SignBitsMask)) {
995     APInt OtherHighestBit = (~UnsetBitsMask) + 1U;
996     if (!OtherHighestBit.isPowerOf2())
997       return nullptr;
998     HighestBit = APIntOps::umin(HighestBit, OtherHighestBit);
999   }
1000   // Else, if it does not, then all is ok as-is.
1001 
1002   // %r = icmp ult %X, SignBit
1003   return Builder.CreateICmpULT(X, ConstantInt::get(X->getType(), HighestBit),
1004                                CxtI.getName() + ".simplified");
1005 }
1006 
1007 /// Reduce a pair of compares that check if a value has exactly 1 bit set.
1008 static Value *foldIsPowerOf2(ICmpInst *Cmp0, ICmpInst *Cmp1, bool JoinedByAnd,
1009                              InstCombiner::BuilderTy &Builder) {
1010   // Handle 'and' / 'or' commutation: make the equality check the first operand.
1011   if (JoinedByAnd && Cmp1->getPredicate() == ICmpInst::ICMP_NE)
1012     std::swap(Cmp0, Cmp1);
1013   else if (!JoinedByAnd && Cmp1->getPredicate() == ICmpInst::ICMP_EQ)
1014     std::swap(Cmp0, Cmp1);
1015 
1016   // (X != 0) && (ctpop(X) u< 2) --> ctpop(X) == 1
1017   CmpInst::Predicate Pred0, Pred1;
1018   Value *X;
1019   if (JoinedByAnd && match(Cmp0, m_ICmp(Pred0, m_Value(X), m_ZeroInt())) &&
1020       match(Cmp1, m_ICmp(Pred1, m_Intrinsic<Intrinsic::ctpop>(m_Specific(X)),
1021                          m_SpecificInt(2))) &&
1022       Pred0 == ICmpInst::ICMP_NE && Pred1 == ICmpInst::ICMP_ULT) {
1023     Value *CtPop = Cmp1->getOperand(0);
1024     return Builder.CreateICmpEQ(CtPop, ConstantInt::get(CtPop->getType(), 1));
1025   }
1026   // (X == 0) || (ctpop(X) u> 1) --> ctpop(X) != 1
1027   if (!JoinedByAnd && match(Cmp0, m_ICmp(Pred0, m_Value(X), m_ZeroInt())) &&
1028       match(Cmp1, m_ICmp(Pred1, m_Intrinsic<Intrinsic::ctpop>(m_Specific(X)),
1029                          m_SpecificInt(1))) &&
1030       Pred0 == ICmpInst::ICMP_EQ && Pred1 == ICmpInst::ICMP_UGT) {
1031     Value *CtPop = Cmp1->getOperand(0);
1032     return Builder.CreateICmpNE(CtPop, ConstantInt::get(CtPop->getType(), 1));
1033   }
1034   return nullptr;
1035 }
1036 
1037 /// Commuted variants are assumed to be handled by calling this function again
1038 /// with the parameters swapped.
1039 static Value *foldUnsignedUnderflowCheck(ICmpInst *ZeroICmp,
1040                                          ICmpInst *UnsignedICmp, bool IsAnd,
1041                                          const SimplifyQuery &Q,
1042                                          InstCombiner::BuilderTy &Builder) {
1043   Value *ZeroCmpOp;
1044   ICmpInst::Predicate EqPred;
1045   if (!match(ZeroICmp, m_ICmp(EqPred, m_Value(ZeroCmpOp), m_Zero())) ||
1046       !ICmpInst::isEquality(EqPred))
1047     return nullptr;
1048 
1049   auto IsKnownNonZero = [&](Value *V) {
1050     return isKnownNonZero(V, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT);
1051   };
1052 
1053   ICmpInst::Predicate UnsignedPred;
1054 
1055   Value *A, *B;
1056   if (match(UnsignedICmp,
1057             m_c_ICmp(UnsignedPred, m_Specific(ZeroCmpOp), m_Value(A))) &&
1058       match(ZeroCmpOp, m_c_Add(m_Specific(A), m_Value(B))) &&
1059       (ZeroICmp->hasOneUse() || UnsignedICmp->hasOneUse())) {
1060     auto GetKnownNonZeroAndOther = [&](Value *&NonZero, Value *&Other) {
1061       if (!IsKnownNonZero(NonZero))
1062         std::swap(NonZero, Other);
1063       return IsKnownNonZero(NonZero);
1064     };
1065 
1066     // Given  ZeroCmpOp = (A + B)
1067     //   ZeroCmpOp <= A && ZeroCmpOp != 0  -->  (0-B) <  A
1068     //   ZeroCmpOp >  A || ZeroCmpOp == 0  -->  (0-B) >= A
1069     //
1070     //   ZeroCmpOp <  A && ZeroCmpOp != 0  -->  (0-X) <  Y  iff
1071     //   ZeroCmpOp >= A || ZeroCmpOp == 0  -->  (0-X) >= Y  iff
1072     //     with X being the value (A/B) that is known to be non-zero,
1073     //     and Y being remaining value.
1074     if (UnsignedPred == ICmpInst::ICMP_ULE && EqPred == ICmpInst::ICMP_NE &&
1075         IsAnd)
1076       return Builder.CreateICmpULT(Builder.CreateNeg(B), A);
1077     if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_NE &&
1078         IsAnd && GetKnownNonZeroAndOther(B, A))
1079       return Builder.CreateICmpULT(Builder.CreateNeg(B), A);
1080     if (UnsignedPred == ICmpInst::ICMP_UGT && EqPred == ICmpInst::ICMP_EQ &&
1081         !IsAnd)
1082       return Builder.CreateICmpUGE(Builder.CreateNeg(B), A);
1083     if (UnsignedPred == ICmpInst::ICMP_UGE && EqPred == ICmpInst::ICMP_EQ &&
1084         !IsAnd && GetKnownNonZeroAndOther(B, A))
1085       return Builder.CreateICmpUGE(Builder.CreateNeg(B), A);
1086   }
1087 
1088   Value *Base, *Offset;
1089   if (!match(ZeroCmpOp, m_Sub(m_Value(Base), m_Value(Offset))))
1090     return nullptr;
1091 
1092   if (!match(UnsignedICmp,
1093              m_c_ICmp(UnsignedPred, m_Specific(Base), m_Specific(Offset))) ||
1094       !ICmpInst::isUnsigned(UnsignedPred))
1095     return nullptr;
1096 
1097   // Base >=/> Offset && (Base - Offset) != 0  <-->  Base > Offset
1098   // (no overflow and not null)
1099   if ((UnsignedPred == ICmpInst::ICMP_UGE ||
1100        UnsignedPred == ICmpInst::ICMP_UGT) &&
1101       EqPred == ICmpInst::ICMP_NE && IsAnd)
1102     return Builder.CreateICmpUGT(Base, Offset);
1103 
1104   // Base <=/< Offset || (Base - Offset) == 0  <-->  Base <= Offset
1105   // (overflow or null)
1106   if ((UnsignedPred == ICmpInst::ICMP_ULE ||
1107        UnsignedPred == ICmpInst::ICMP_ULT) &&
1108       EqPred == ICmpInst::ICMP_EQ && !IsAnd)
1109     return Builder.CreateICmpULE(Base, Offset);
1110 
1111   // Base <= Offset && (Base - Offset) != 0  -->  Base < Offset
1112   if (UnsignedPred == ICmpInst::ICMP_ULE && EqPred == ICmpInst::ICMP_NE &&
1113       IsAnd)
1114     return Builder.CreateICmpULT(Base, Offset);
1115 
1116   // Base > Offset || (Base - Offset) == 0  -->  Base >= Offset
1117   if (UnsignedPred == ICmpInst::ICMP_UGT && EqPred == ICmpInst::ICMP_EQ &&
1118       !IsAnd)
1119     return Builder.CreateICmpUGE(Base, Offset);
1120 
1121   return nullptr;
1122 }
1123 
1124 /// Reduce logic-of-compares with equality to a constant by substituting a
1125 /// common operand with the constant. Callers are expected to call this with
1126 /// Cmp0/Cmp1 switched to handle logic op commutativity.
1127 static Value *foldAndOrOfICmpsWithConstEq(ICmpInst *Cmp0, ICmpInst *Cmp1,
1128                                           BinaryOperator &Logic,
1129                                           InstCombiner::BuilderTy &Builder,
1130                                           const SimplifyQuery &Q) {
1131   bool IsAnd = Logic.getOpcode() == Instruction::And;
1132   assert((IsAnd || Logic.getOpcode() == Instruction::Or) && "Wrong logic op");
1133 
1134   // Match an equality compare with a non-poison constant as Cmp0.
1135   // Also, give up if the compare can be constant-folded to avoid looping.
1136   ICmpInst::Predicate Pred0;
1137   Value *X;
1138   Constant *C;
1139   if (!match(Cmp0, m_ICmp(Pred0, m_Value(X), m_Constant(C))) ||
1140       !isGuaranteedNotToBeUndefOrPoison(C) || isa<Constant>(X))
1141     return nullptr;
1142   if ((IsAnd && Pred0 != ICmpInst::ICMP_EQ) ||
1143       (!IsAnd && Pred0 != ICmpInst::ICMP_NE))
1144     return nullptr;
1145 
1146   // The other compare must include a common operand (X). Canonicalize the
1147   // common operand as operand 1 (Pred1 is swapped if the common operand was
1148   // operand 0).
1149   Value *Y;
1150   ICmpInst::Predicate Pred1;
1151   if (!match(Cmp1, m_c_ICmp(Pred1, m_Value(Y), m_Deferred(X))))
1152     return nullptr;
1153 
1154   // Replace variable with constant value equivalence to remove a variable use:
1155   // (X == C) && (Y Pred1 X) --> (X == C) && (Y Pred1 C)
1156   // (X != C) || (Y Pred1 X) --> (X != C) || (Y Pred1 C)
1157   // Can think of the 'or' substitution with the 'and' bool equivalent:
1158   // A || B --> A || (!A && B)
1159   Value *SubstituteCmp = SimplifyICmpInst(Pred1, Y, C, Q);
1160   if (!SubstituteCmp) {
1161     // If we need to create a new instruction, require that the old compare can
1162     // be removed.
1163     if (!Cmp1->hasOneUse())
1164       return nullptr;
1165     SubstituteCmp = Builder.CreateICmp(Pred1, Y, C);
1166   }
1167   return Builder.CreateBinOp(Logic.getOpcode(), Cmp0, SubstituteCmp);
1168 }
1169 
1170 /// Fold (icmp)&(icmp) if possible.
1171 Value *InstCombinerImpl::foldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS,
1172                                         BinaryOperator &And) {
1173   const SimplifyQuery Q = SQ.getWithInstruction(&And);
1174 
1175   // Fold (!iszero(A & K1) & !iszero(A & K2)) ->  (A & (K1 | K2)) == (K1 | K2)
1176   // if K1 and K2 are a one-bit mask.
1177   if (Value *V = foldAndOrOfICmpsOfAndWithPow2(LHS, RHS, And))
1178     return V;
1179 
1180   ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
1181 
1182   // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
1183   if (predicatesFoldable(PredL, PredR)) {
1184     if (LHS->getOperand(0) == RHS->getOperand(1) &&
1185         LHS->getOperand(1) == RHS->getOperand(0))
1186       LHS->swapOperands();
1187     if (LHS->getOperand(0) == RHS->getOperand(0) &&
1188         LHS->getOperand(1) == RHS->getOperand(1)) {
1189       Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1190       unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
1191       bool IsSigned = LHS->isSigned() || RHS->isSigned();
1192       return getNewICmpValue(Code, IsSigned, Op0, Op1, Builder);
1193     }
1194   }
1195 
1196   // handle (roughly):  (icmp eq (A & B), C) & (icmp eq (A & D), E)
1197   if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, true, Builder))
1198     return V;
1199 
1200   if (Value *V = foldAndOrOfICmpsWithConstEq(LHS, RHS, And, Builder, Q))
1201     return V;
1202   if (Value *V = foldAndOrOfICmpsWithConstEq(RHS, LHS, And, Builder, Q))
1203     return V;
1204 
1205   // E.g. (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
1206   if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/false))
1207     return V;
1208 
1209   // E.g. (icmp slt x, n) & (icmp sge x, 0) --> icmp ult x, n
1210   if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/false))
1211     return V;
1212 
1213   if (Value *V = foldAndOrOfEqualityCmpsWithConstants(LHS, RHS, true, Builder))
1214     return V;
1215 
1216   if (Value *V = foldSignedTruncationCheck(LHS, RHS, And, Builder))
1217     return V;
1218 
1219   if (Value *V = foldIsPowerOf2(LHS, RHS, true /* JoinedByAnd */, Builder))
1220     return V;
1221 
1222   if (Value *X =
1223           foldUnsignedUnderflowCheck(LHS, RHS, /*IsAnd=*/true, Q, Builder))
1224     return X;
1225   if (Value *X =
1226           foldUnsignedUnderflowCheck(RHS, LHS, /*IsAnd=*/true, Q, Builder))
1227     return X;
1228 
1229   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
1230   Value *LHS0 = LHS->getOperand(0), *RHS0 = RHS->getOperand(0);
1231 
1232   ConstantInt *LHSC, *RHSC;
1233   if (!match(LHS->getOperand(1), m_ConstantInt(LHSC)) ||
1234       !match(RHS->getOperand(1), m_ConstantInt(RHSC)))
1235     return nullptr;
1236 
1237   if (LHSC == RHSC && PredL == PredR) {
1238     // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
1239     // where C is a power of 2 or
1240     // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
1241     if ((PredL == ICmpInst::ICMP_ULT && LHSC->getValue().isPowerOf2()) ||
1242         (PredL == ICmpInst::ICMP_EQ && LHSC->isZero())) {
1243       Value *NewOr = Builder.CreateOr(LHS0, RHS0);
1244       return Builder.CreateICmp(PredL, NewOr, LHSC);
1245     }
1246   }
1247 
1248   // (trunc x) == C1 & (and x, CA) == C2 -> (and x, CA|CMAX) == C1|C2
1249   // where CMAX is the all ones value for the truncated type,
1250   // iff the lower bits of C2 and CA are zero.
1251   if (PredL == ICmpInst::ICMP_EQ && PredL == PredR && LHS->hasOneUse() &&
1252       RHS->hasOneUse()) {
1253     Value *V;
1254     ConstantInt *AndC, *SmallC = nullptr, *BigC = nullptr;
1255 
1256     // (trunc x) == C1 & (and x, CA) == C2
1257     // (and x, CA) == C2 & (trunc x) == C1
1258     if (match(RHS0, m_Trunc(m_Value(V))) &&
1259         match(LHS0, m_And(m_Specific(V), m_ConstantInt(AndC)))) {
1260       SmallC = RHSC;
1261       BigC = LHSC;
1262     } else if (match(LHS0, m_Trunc(m_Value(V))) &&
1263                match(RHS0, m_And(m_Specific(V), m_ConstantInt(AndC)))) {
1264       SmallC = LHSC;
1265       BigC = RHSC;
1266     }
1267 
1268     if (SmallC && BigC) {
1269       unsigned BigBitSize = BigC->getType()->getBitWidth();
1270       unsigned SmallBitSize = SmallC->getType()->getBitWidth();
1271 
1272       // Check that the low bits are zero.
1273       APInt Low = APInt::getLowBitsSet(BigBitSize, SmallBitSize);
1274       if ((Low & AndC->getValue()).isNullValue() &&
1275           (Low & BigC->getValue()).isNullValue()) {
1276         Value *NewAnd = Builder.CreateAnd(V, Low | AndC->getValue());
1277         APInt N = SmallC->getValue().zext(BigBitSize) | BigC->getValue();
1278         Value *NewVal = ConstantInt::get(AndC->getType()->getContext(), N);
1279         return Builder.CreateICmp(PredL, NewAnd, NewVal);
1280       }
1281     }
1282   }
1283 
1284   // From here on, we only handle:
1285   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
1286   if (LHS0 != RHS0)
1287     return nullptr;
1288 
1289   // ICMP_[US][GL]E X, C is folded to ICMP_[US][GL]T elsewhere.
1290   if (PredL == ICmpInst::ICMP_UGE || PredL == ICmpInst::ICMP_ULE ||
1291       PredR == ICmpInst::ICMP_UGE || PredR == ICmpInst::ICMP_ULE ||
1292       PredL == ICmpInst::ICMP_SGE || PredL == ICmpInst::ICMP_SLE ||
1293       PredR == ICmpInst::ICMP_SGE || PredR == ICmpInst::ICMP_SLE)
1294     return nullptr;
1295 
1296   // We can't fold (ugt x, C) & (sgt x, C2).
1297   if (!predicatesFoldable(PredL, PredR))
1298     return nullptr;
1299 
1300   // Ensure that the larger constant is on the RHS.
1301   bool ShouldSwap;
1302   if (CmpInst::isSigned(PredL) ||
1303       (ICmpInst::isEquality(PredL) && CmpInst::isSigned(PredR)))
1304     ShouldSwap = LHSC->getValue().sgt(RHSC->getValue());
1305   else
1306     ShouldSwap = LHSC->getValue().ugt(RHSC->getValue());
1307 
1308   if (ShouldSwap) {
1309     std::swap(LHS, RHS);
1310     std::swap(LHSC, RHSC);
1311     std::swap(PredL, PredR);
1312   }
1313 
1314   // At this point, we know we have two icmp instructions
1315   // comparing a value against two constants and and'ing the result
1316   // together.  Because of the above check, we know that we only have
1317   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
1318   // (from the icmp folding check above), that the two constants
1319   // are not equal and that the larger constant is on the RHS
1320   assert(LHSC != RHSC && "Compares not folded above?");
1321 
1322   switch (PredL) {
1323   default:
1324     llvm_unreachable("Unknown integer condition code!");
1325   case ICmpInst::ICMP_NE:
1326     switch (PredR) {
1327     default:
1328       llvm_unreachable("Unknown integer condition code!");
1329     case ICmpInst::ICMP_ULT:
1330       // (X != 13 & X u< 14) -> X < 13
1331       if (LHSC->getValue() == (RHSC->getValue() - 1))
1332         return Builder.CreateICmpULT(LHS0, LHSC);
1333       if (LHSC->isZero()) // (X != 0 & X u< C) -> X-1 u< C-1
1334         return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(),
1335                                false, true);
1336       break; // (X != 13 & X u< 15) -> no change
1337     case ICmpInst::ICMP_SLT:
1338       // (X != 13 & X s< 14) -> X < 13
1339       if (LHSC->getValue() == (RHSC->getValue() - 1))
1340         return Builder.CreateICmpSLT(LHS0, LHSC);
1341       // (X != INT_MIN & X s< C) -> X-(INT_MIN+1) u< (C-(INT_MIN+1))
1342       if (LHSC->isMinValue(true))
1343         return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(),
1344                                true, true);
1345       break; // (X != 13 & X s< 15) -> no change
1346     case ICmpInst::ICMP_NE:
1347       // Potential folds for this case should already be handled.
1348       break;
1349     }
1350     break;
1351   case ICmpInst::ICMP_UGT:
1352     switch (PredR) {
1353     default:
1354       llvm_unreachable("Unknown integer condition code!");
1355     case ICmpInst::ICMP_NE:
1356       // (X u> 13 & X != 14) -> X u> 14
1357       if (RHSC->getValue() == (LHSC->getValue() + 1))
1358         return Builder.CreateICmp(PredL, LHS0, RHSC);
1359       // X u> C & X != UINT_MAX -> (X-(C+1)) u< UINT_MAX-(C+1)
1360       if (RHSC->isMaxValue(false))
1361         return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(),
1362                                false, true);
1363       break;                 // (X u> 13 & X != 15) -> no change
1364     case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) u< 1
1365       return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(),
1366                              false, true);
1367     }
1368     break;
1369   case ICmpInst::ICMP_SGT:
1370     switch (PredR) {
1371     default:
1372       llvm_unreachable("Unknown integer condition code!");
1373     case ICmpInst::ICMP_NE:
1374       // (X s> 13 & X != 14) -> X s> 14
1375       if (RHSC->getValue() == (LHSC->getValue() + 1))
1376         return Builder.CreateICmp(PredL, LHS0, RHSC);
1377       // X s> C & X != INT_MAX -> (X-(C+1)) u< INT_MAX-(C+1)
1378       if (RHSC->isMaxValue(true))
1379         return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(),
1380                                true, true);
1381       break;                 // (X s> 13 & X != 15) -> no change
1382     case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) u< 1
1383       return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(), true,
1384                              true);
1385     }
1386     break;
1387   }
1388 
1389   return nullptr;
1390 }
1391 
1392 Value *InstCombinerImpl::foldLogicOfFCmps(FCmpInst *LHS, FCmpInst *RHS,
1393                                           bool IsAnd) {
1394   Value *LHS0 = LHS->getOperand(0), *LHS1 = LHS->getOperand(1);
1395   Value *RHS0 = RHS->getOperand(0), *RHS1 = RHS->getOperand(1);
1396   FCmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
1397 
1398   if (LHS0 == RHS1 && RHS0 == LHS1) {
1399     // Swap RHS operands to match LHS.
1400     PredR = FCmpInst::getSwappedPredicate(PredR);
1401     std::swap(RHS0, RHS1);
1402   }
1403 
1404   // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
1405   // Suppose the relation between x and y is R, where R is one of
1406   // U(1000), L(0100), G(0010) or E(0001), and CC0 and CC1 are the bitmasks for
1407   // testing the desired relations.
1408   //
1409   // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
1410   //    bool(R & CC0) && bool(R & CC1)
1411   //  = bool((R & CC0) & (R & CC1))
1412   //  = bool(R & (CC0 & CC1)) <= by re-association, commutation, and idempotency
1413   //
1414   // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
1415   //    bool(R & CC0) || bool(R & CC1)
1416   //  = bool((R & CC0) | (R & CC1))
1417   //  = bool(R & (CC0 | CC1)) <= by reversed distribution (contribution? ;)
1418   if (LHS0 == RHS0 && LHS1 == RHS1) {
1419     unsigned FCmpCodeL = getFCmpCode(PredL);
1420     unsigned FCmpCodeR = getFCmpCode(PredR);
1421     unsigned NewPred = IsAnd ? FCmpCodeL & FCmpCodeR : FCmpCodeL | FCmpCodeR;
1422     return getFCmpValue(NewPred, LHS0, LHS1, Builder);
1423   }
1424 
1425   if ((PredL == FCmpInst::FCMP_ORD && PredR == FCmpInst::FCMP_ORD && IsAnd) ||
1426       (PredL == FCmpInst::FCMP_UNO && PredR == FCmpInst::FCMP_UNO && !IsAnd)) {
1427     if (LHS0->getType() != RHS0->getType())
1428       return nullptr;
1429 
1430     // FCmp canonicalization ensures that (fcmp ord/uno X, X) and
1431     // (fcmp ord/uno X, C) will be transformed to (fcmp X, +0.0).
1432     if (match(LHS1, m_PosZeroFP()) && match(RHS1, m_PosZeroFP()))
1433       // Ignore the constants because they are obviously not NANs:
1434       // (fcmp ord x, 0.0) & (fcmp ord y, 0.0)  -> (fcmp ord x, y)
1435       // (fcmp uno x, 0.0) | (fcmp uno y, 0.0)  -> (fcmp uno x, y)
1436       return Builder.CreateFCmp(PredL, LHS0, RHS0);
1437   }
1438 
1439   return nullptr;
1440 }
1441 
1442 /// This a limited reassociation for a special case (see above) where we are
1443 /// checking if two values are either both NAN (unordered) or not-NAN (ordered).
1444 /// This could be handled more generally in '-reassociation', but it seems like
1445 /// an unlikely pattern for a large number of logic ops and fcmps.
1446 static Instruction *reassociateFCmps(BinaryOperator &BO,
1447                                      InstCombiner::BuilderTy &Builder) {
1448   Instruction::BinaryOps Opcode = BO.getOpcode();
1449   assert((Opcode == Instruction::And || Opcode == Instruction::Or) &&
1450          "Expecting and/or op for fcmp transform");
1451 
1452   // There are 4 commuted variants of the pattern. Canonicalize operands of this
1453   // logic op so an fcmp is operand 0 and a matching logic op is operand 1.
1454   Value *Op0 = BO.getOperand(0), *Op1 = BO.getOperand(1), *X;
1455   FCmpInst::Predicate Pred;
1456   if (match(Op1, m_FCmp(Pred, m_Value(), m_AnyZeroFP())))
1457     std::swap(Op0, Op1);
1458 
1459   // Match inner binop and the predicate for combining 2 NAN checks into 1.
1460   BinaryOperator *BO1;
1461   FCmpInst::Predicate NanPred = Opcode == Instruction::And ? FCmpInst::FCMP_ORD
1462                                                            : FCmpInst::FCMP_UNO;
1463   if (!match(Op0, m_FCmp(Pred, m_Value(X), m_AnyZeroFP())) || Pred != NanPred ||
1464       !match(Op1, m_BinOp(BO1)) || BO1->getOpcode() != Opcode)
1465     return nullptr;
1466 
1467   // The inner logic op must have a matching fcmp operand.
1468   Value *BO10 = BO1->getOperand(0), *BO11 = BO1->getOperand(1), *Y;
1469   if (!match(BO10, m_FCmp(Pred, m_Value(Y), m_AnyZeroFP())) ||
1470       Pred != NanPred || X->getType() != Y->getType())
1471     std::swap(BO10, BO11);
1472 
1473   if (!match(BO10, m_FCmp(Pred, m_Value(Y), m_AnyZeroFP())) ||
1474       Pred != NanPred || X->getType() != Y->getType())
1475     return nullptr;
1476 
1477   // and (fcmp ord X, 0), (and (fcmp ord Y, 0), Z) --> and (fcmp ord X, Y), Z
1478   // or  (fcmp uno X, 0), (or  (fcmp uno Y, 0), Z) --> or  (fcmp uno X, Y), Z
1479   Value *NewFCmp = Builder.CreateFCmp(Pred, X, Y);
1480   if (auto *NewFCmpInst = dyn_cast<FCmpInst>(NewFCmp)) {
1481     // Intersect FMF from the 2 source fcmps.
1482     NewFCmpInst->copyIRFlags(Op0);
1483     NewFCmpInst->andIRFlags(BO10);
1484   }
1485   return BinaryOperator::Create(Opcode, NewFCmp, BO11);
1486 }
1487 
1488 /// Match De Morgan's Laws:
1489 /// (~A & ~B) == (~(A | B))
1490 /// (~A | ~B) == (~(A & B))
1491 static Instruction *matchDeMorgansLaws(BinaryOperator &I,
1492                                        InstCombiner::BuilderTy &Builder) {
1493   auto Opcode = I.getOpcode();
1494   assert((Opcode == Instruction::And || Opcode == Instruction::Or) &&
1495          "Trying to match De Morgan's Laws with something other than and/or");
1496 
1497   // Flip the logic operation.
1498   Opcode = (Opcode == Instruction::And) ? Instruction::Or : Instruction::And;
1499 
1500   Value *A, *B;
1501   if (match(I.getOperand(0), m_OneUse(m_Not(m_Value(A)))) &&
1502       match(I.getOperand(1), m_OneUse(m_Not(m_Value(B)))) &&
1503       !InstCombiner::isFreeToInvert(A, A->hasOneUse()) &&
1504       !InstCombiner::isFreeToInvert(B, B->hasOneUse())) {
1505     Value *AndOr = Builder.CreateBinOp(Opcode, A, B, I.getName() + ".demorgan");
1506     return BinaryOperator::CreateNot(AndOr);
1507   }
1508 
1509   return nullptr;
1510 }
1511 
1512 bool InstCombinerImpl::shouldOptimizeCast(CastInst *CI) {
1513   Value *CastSrc = CI->getOperand(0);
1514 
1515   // Noop casts and casts of constants should be eliminated trivially.
1516   if (CI->getSrcTy() == CI->getDestTy() || isa<Constant>(CastSrc))
1517     return false;
1518 
1519   // If this cast is paired with another cast that can be eliminated, we prefer
1520   // to have it eliminated.
1521   if (const auto *PrecedingCI = dyn_cast<CastInst>(CastSrc))
1522     if (isEliminableCastPair(PrecedingCI, CI))
1523       return false;
1524 
1525   return true;
1526 }
1527 
1528 /// Fold {and,or,xor} (cast X), C.
1529 static Instruction *foldLogicCastConstant(BinaryOperator &Logic, CastInst *Cast,
1530                                           InstCombiner::BuilderTy &Builder) {
1531   Constant *C = dyn_cast<Constant>(Logic.getOperand(1));
1532   if (!C)
1533     return nullptr;
1534 
1535   auto LogicOpc = Logic.getOpcode();
1536   Type *DestTy = Logic.getType();
1537   Type *SrcTy = Cast->getSrcTy();
1538 
1539   // Move the logic operation ahead of a zext or sext if the constant is
1540   // unchanged in the smaller source type. Performing the logic in a smaller
1541   // type may provide more information to later folds, and the smaller logic
1542   // instruction may be cheaper (particularly in the case of vectors).
1543   Value *X;
1544   if (match(Cast, m_OneUse(m_ZExt(m_Value(X))))) {
1545     Constant *TruncC = ConstantExpr::getTrunc(C, SrcTy);
1546     Constant *ZextTruncC = ConstantExpr::getZExt(TruncC, DestTy);
1547     if (ZextTruncC == C) {
1548       // LogicOpc (zext X), C --> zext (LogicOpc X, C)
1549       Value *NewOp = Builder.CreateBinOp(LogicOpc, X, TruncC);
1550       return new ZExtInst(NewOp, DestTy);
1551     }
1552   }
1553 
1554   if (match(Cast, m_OneUse(m_SExt(m_Value(X))))) {
1555     Constant *TruncC = ConstantExpr::getTrunc(C, SrcTy);
1556     Constant *SextTruncC = ConstantExpr::getSExt(TruncC, DestTy);
1557     if (SextTruncC == C) {
1558       // LogicOpc (sext X), C --> sext (LogicOpc X, C)
1559       Value *NewOp = Builder.CreateBinOp(LogicOpc, X, TruncC);
1560       return new SExtInst(NewOp, DestTy);
1561     }
1562   }
1563 
1564   return nullptr;
1565 }
1566 
1567 /// Fold {and,or,xor} (cast X), Y.
1568 Instruction *InstCombinerImpl::foldCastedBitwiseLogic(BinaryOperator &I) {
1569   auto LogicOpc = I.getOpcode();
1570   assert(I.isBitwiseLogicOp() && "Unexpected opcode for bitwise logic folding");
1571 
1572   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1573   CastInst *Cast0 = dyn_cast<CastInst>(Op0);
1574   if (!Cast0)
1575     return nullptr;
1576 
1577   // This must be a cast from an integer or integer vector source type to allow
1578   // transformation of the logic operation to the source type.
1579   Type *DestTy = I.getType();
1580   Type *SrcTy = Cast0->getSrcTy();
1581   if (!SrcTy->isIntOrIntVectorTy())
1582     return nullptr;
1583 
1584   if (Instruction *Ret = foldLogicCastConstant(I, Cast0, Builder))
1585     return Ret;
1586 
1587   CastInst *Cast1 = dyn_cast<CastInst>(Op1);
1588   if (!Cast1)
1589     return nullptr;
1590 
1591   // Both operands of the logic operation are casts. The casts must be of the
1592   // same type for reduction.
1593   auto CastOpcode = Cast0->getOpcode();
1594   if (CastOpcode != Cast1->getOpcode() || SrcTy != Cast1->getSrcTy())
1595     return nullptr;
1596 
1597   Value *Cast0Src = Cast0->getOperand(0);
1598   Value *Cast1Src = Cast1->getOperand(0);
1599 
1600   // fold logic(cast(A), cast(B)) -> cast(logic(A, B))
1601   if (shouldOptimizeCast(Cast0) && shouldOptimizeCast(Cast1)) {
1602     Value *NewOp = Builder.CreateBinOp(LogicOpc, Cast0Src, Cast1Src,
1603                                         I.getName());
1604     return CastInst::Create(CastOpcode, NewOp, DestTy);
1605   }
1606 
1607   // For now, only 'and'/'or' have optimizations after this.
1608   if (LogicOpc == Instruction::Xor)
1609     return nullptr;
1610 
1611   // If this is logic(cast(icmp), cast(icmp)), try to fold this even if the
1612   // cast is otherwise not optimizable.  This happens for vector sexts.
1613   ICmpInst *ICmp0 = dyn_cast<ICmpInst>(Cast0Src);
1614   ICmpInst *ICmp1 = dyn_cast<ICmpInst>(Cast1Src);
1615   if (ICmp0 && ICmp1) {
1616     Value *Res = LogicOpc == Instruction::And ? foldAndOfICmps(ICmp0, ICmp1, I)
1617                                               : foldOrOfICmps(ICmp0, ICmp1, I);
1618     if (Res)
1619       return CastInst::Create(CastOpcode, Res, DestTy);
1620     return nullptr;
1621   }
1622 
1623   // If this is logic(cast(fcmp), cast(fcmp)), try to fold this even if the
1624   // cast is otherwise not optimizable.  This happens for vector sexts.
1625   FCmpInst *FCmp0 = dyn_cast<FCmpInst>(Cast0Src);
1626   FCmpInst *FCmp1 = dyn_cast<FCmpInst>(Cast1Src);
1627   if (FCmp0 && FCmp1)
1628     if (Value *R = foldLogicOfFCmps(FCmp0, FCmp1, LogicOpc == Instruction::And))
1629       return CastInst::Create(CastOpcode, R, DestTy);
1630 
1631   return nullptr;
1632 }
1633 
1634 static Instruction *foldAndToXor(BinaryOperator &I,
1635                                  InstCombiner::BuilderTy &Builder) {
1636   assert(I.getOpcode() == Instruction::And);
1637   Value *Op0 = I.getOperand(0);
1638   Value *Op1 = I.getOperand(1);
1639   Value *A, *B;
1640 
1641   // Operand complexity canonicalization guarantees that the 'or' is Op0.
1642   // (A | B) & ~(A & B) --> A ^ B
1643   // (A | B) & ~(B & A) --> A ^ B
1644   if (match(&I, m_BinOp(m_Or(m_Value(A), m_Value(B)),
1645                         m_Not(m_c_And(m_Deferred(A), m_Deferred(B))))))
1646     return BinaryOperator::CreateXor(A, B);
1647 
1648   // (A | ~B) & (~A | B) --> ~(A ^ B)
1649   // (A | ~B) & (B | ~A) --> ~(A ^ B)
1650   // (~B | A) & (~A | B) --> ~(A ^ B)
1651   // (~B | A) & (B | ~A) --> ~(A ^ B)
1652   if (Op0->hasOneUse() || Op1->hasOneUse())
1653     if (match(&I, m_BinOp(m_c_Or(m_Value(A), m_Not(m_Value(B))),
1654                           m_c_Or(m_Not(m_Deferred(A)), m_Deferred(B)))))
1655       return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
1656 
1657   return nullptr;
1658 }
1659 
1660 static Instruction *foldOrToXor(BinaryOperator &I,
1661                                 InstCombiner::BuilderTy &Builder) {
1662   assert(I.getOpcode() == Instruction::Or);
1663   Value *Op0 = I.getOperand(0);
1664   Value *Op1 = I.getOperand(1);
1665   Value *A, *B;
1666 
1667   // Operand complexity canonicalization guarantees that the 'and' is Op0.
1668   // (A & B) | ~(A | B) --> ~(A ^ B)
1669   // (A & B) | ~(B | A) --> ~(A ^ B)
1670   if (Op0->hasOneUse() || Op1->hasOneUse())
1671     if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
1672         match(Op1, m_Not(m_c_Or(m_Specific(A), m_Specific(B)))))
1673       return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
1674 
1675   // (A & ~B) | (~A & B) --> A ^ B
1676   // (A & ~B) | (B & ~A) --> A ^ B
1677   // (~B & A) | (~A & B) --> A ^ B
1678   // (~B & A) | (B & ~A) --> A ^ B
1679   if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
1680       match(Op1, m_c_And(m_Not(m_Specific(A)), m_Specific(B))))
1681     return BinaryOperator::CreateXor(A, B);
1682 
1683   return nullptr;
1684 }
1685 
1686 /// Return true if a constant shift amount is always less than the specified
1687 /// bit-width. If not, the shift could create poison in the narrower type.
1688 static bool canNarrowShiftAmt(Constant *C, unsigned BitWidth) {
1689   APInt Threshold(C->getType()->getScalarSizeInBits(), BitWidth);
1690   return match(C, m_SpecificInt_ICMP(ICmpInst::ICMP_ULT, Threshold));
1691 }
1692 
1693 /// Try to use narrower ops (sink zext ops) for an 'and' with binop operand and
1694 /// a common zext operand: and (binop (zext X), C), (zext X).
1695 Instruction *InstCombinerImpl::narrowMaskedBinOp(BinaryOperator &And) {
1696   // This transform could also apply to {or, and, xor}, but there are better
1697   // folds for those cases, so we don't expect those patterns here. AShr is not
1698   // handled because it should always be transformed to LShr in this sequence.
1699   // The subtract transform is different because it has a constant on the left.
1700   // Add/mul commute the constant to RHS; sub with constant RHS becomes add.
1701   Value *Op0 = And.getOperand(0), *Op1 = And.getOperand(1);
1702   Constant *C;
1703   if (!match(Op0, m_OneUse(m_Add(m_Specific(Op1), m_Constant(C)))) &&
1704       !match(Op0, m_OneUse(m_Mul(m_Specific(Op1), m_Constant(C)))) &&
1705       !match(Op0, m_OneUse(m_LShr(m_Specific(Op1), m_Constant(C)))) &&
1706       !match(Op0, m_OneUse(m_Shl(m_Specific(Op1), m_Constant(C)))) &&
1707       !match(Op0, m_OneUse(m_Sub(m_Constant(C), m_Specific(Op1)))))
1708     return nullptr;
1709 
1710   Value *X;
1711   if (!match(Op1, m_ZExt(m_Value(X))) || Op1->hasNUsesOrMore(3))
1712     return nullptr;
1713 
1714   Type *Ty = And.getType();
1715   if (!isa<VectorType>(Ty) && !shouldChangeType(Ty, X->getType()))
1716     return nullptr;
1717 
1718   // If we're narrowing a shift, the shift amount must be safe (less than the
1719   // width) in the narrower type. If the shift amount is greater, instsimplify
1720   // usually handles that case, but we can't guarantee/assert it.
1721   Instruction::BinaryOps Opc = cast<BinaryOperator>(Op0)->getOpcode();
1722   if (Opc == Instruction::LShr || Opc == Instruction::Shl)
1723     if (!canNarrowShiftAmt(C, X->getType()->getScalarSizeInBits()))
1724       return nullptr;
1725 
1726   // and (sub C, (zext X)), (zext X) --> zext (and (sub C', X), X)
1727   // and (binop (zext X), C), (zext X) --> zext (and (binop X, C'), X)
1728   Value *NewC = ConstantExpr::getTrunc(C, X->getType());
1729   Value *NewBO = Opc == Instruction::Sub ? Builder.CreateBinOp(Opc, NewC, X)
1730                                          : Builder.CreateBinOp(Opc, X, NewC);
1731   return new ZExtInst(Builder.CreateAnd(NewBO, X), Ty);
1732 }
1733 
1734 // FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
1735 // here. We should standardize that construct where it is needed or choose some
1736 // other way to ensure that commutated variants of patterns are not missed.
1737 Instruction *InstCombinerImpl::visitAnd(BinaryOperator &I) {
1738   Type *Ty = I.getType();
1739 
1740   if (Value *V = SimplifyAndInst(I.getOperand(0), I.getOperand(1),
1741                                  SQ.getWithInstruction(&I)))
1742     return replaceInstUsesWith(I, V);
1743 
1744   if (SimplifyAssociativeOrCommutative(I))
1745     return &I;
1746 
1747   if (Instruction *X = foldVectorBinop(I))
1748     return X;
1749 
1750   // See if we can simplify any instructions used by the instruction whose sole
1751   // purpose is to compute bits we don't care about.
1752   if (SimplifyDemandedInstructionBits(I))
1753     return &I;
1754 
1755   // Do this before using distributive laws to catch simple and/or/not patterns.
1756   if (Instruction *Xor = foldAndToXor(I, Builder))
1757     return Xor;
1758 
1759   // (A|B)&(A|C) -> A|(B&C) etc
1760   if (Value *V = SimplifyUsingDistributiveLaws(I))
1761     return replaceInstUsesWith(I, V);
1762 
1763   if (Value *V = SimplifyBSwap(I, Builder))
1764     return replaceInstUsesWith(I, V);
1765 
1766   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1767 
1768   Value *X, *Y;
1769   if (match(Op0, m_OneUse(m_LogicalShift(m_One(), m_Value(X)))) &&
1770       match(Op1, m_One())) {
1771     // (1 << X) & 1 --> zext(X == 0)
1772     // (1 >> X) & 1 --> zext(X == 0)
1773     Value *IsZero = Builder.CreateICmpEQ(X, ConstantInt::get(Ty, 0));
1774     return new ZExtInst(IsZero, Ty);
1775   }
1776 
1777   const APInt *C;
1778   if (match(Op1, m_APInt(C))) {
1779     const APInt *XorC;
1780     if (match(Op0, m_OneUse(m_Xor(m_Value(X), m_APInt(XorC))))) {
1781       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1782       Constant *NewC = ConstantInt::get(Ty, *C & *XorC);
1783       Value *And = Builder.CreateAnd(X, Op1);
1784       And->takeName(Op0);
1785       return BinaryOperator::CreateXor(And, NewC);
1786     }
1787 
1788     const APInt *OrC;
1789     if (match(Op0, m_OneUse(m_Or(m_Value(X), m_APInt(OrC))))) {
1790       // (X | C1) & C2 --> (X & C2^(C1&C2)) | (C1&C2)
1791       // NOTE: This reduces the number of bits set in the & mask, which
1792       // can expose opportunities for store narrowing for scalars.
1793       // NOTE: SimplifyDemandedBits should have already removed bits from C1
1794       // that aren't set in C2. Meaning we can replace (C1&C2) with C1 in
1795       // above, but this feels safer.
1796       APInt Together = *C & *OrC;
1797       Value *And = Builder.CreateAnd(X, ConstantInt::get(Ty, Together ^ *C));
1798       And->takeName(Op0);
1799       return BinaryOperator::CreateOr(And, ConstantInt::get(Ty, Together));
1800     }
1801 
1802     // If the mask is only needed on one incoming arm, push the 'and' op up.
1803     if (match(Op0, m_OneUse(m_Xor(m_Value(X), m_Value(Y)))) ||
1804         match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
1805       APInt NotAndMask(~(*C));
1806       BinaryOperator::BinaryOps BinOp = cast<BinaryOperator>(Op0)->getOpcode();
1807       if (MaskedValueIsZero(X, NotAndMask, 0, &I)) {
1808         // Not masking anything out for the LHS, move mask to RHS.
1809         // and ({x}or X, Y), C --> {x}or X, (and Y, C)
1810         Value *NewRHS = Builder.CreateAnd(Y, Op1, Y->getName() + ".masked");
1811         return BinaryOperator::Create(BinOp, X, NewRHS);
1812       }
1813       if (!isa<Constant>(Y) && MaskedValueIsZero(Y, NotAndMask, 0, &I)) {
1814         // Not masking anything out for the RHS, move mask to LHS.
1815         // and ({x}or X, Y), C --> {x}or (and X, C), Y
1816         Value *NewLHS = Builder.CreateAnd(X, Op1, X->getName() + ".masked");
1817         return BinaryOperator::Create(BinOp, NewLHS, Y);
1818       }
1819     }
1820     const APInt *ShiftC;
1821     if (match(Op0, m_OneUse(m_SExt(m_AShr(m_Value(X), m_APInt(ShiftC)))))) {
1822       unsigned Width = Ty->getScalarSizeInBits();
1823       if (*C == APInt::getLowBitsSet(Width, Width - ShiftC->getZExtValue())) {
1824         // We are clearing high bits that were potentially set by sext+ashr:
1825         // and (sext (ashr X, ShiftC)), C --> lshr (sext X), ShiftC
1826         Value *Sext = Builder.CreateSExt(X, Ty);
1827         Constant *ShAmtC = ConstantInt::get(Ty, ShiftC->zext(Width));
1828         return BinaryOperator::CreateLShr(Sext, ShAmtC);
1829       }
1830     }
1831   }
1832 
1833   ConstantInt *AndRHS;
1834   if (match(Op1, m_ConstantInt(AndRHS))) {
1835     const APInt &AndRHSMask = AndRHS->getValue();
1836 
1837     // Optimize a variety of ((val OP C1) & C2) combinations...
1838     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1839       // ((C1 OP zext(X)) & C2) -> zext((C1-X) & C2) if C2 fits in the bitwidth
1840       // of X and OP behaves well when given trunc(C1) and X.
1841       // TODO: Do this for vectors by using m_APInt instead of m_ConstantInt.
1842       switch (Op0I->getOpcode()) {
1843       default:
1844         break;
1845       case Instruction::Xor:
1846       case Instruction::Or:
1847       case Instruction::Mul:
1848       case Instruction::Add:
1849       case Instruction::Sub:
1850         Value *X;
1851         ConstantInt *C1;
1852         // TODO: The one use restrictions could be relaxed a little if the AND
1853         // is going to be removed.
1854         if (match(Op0I, m_OneUse(m_c_BinOp(m_OneUse(m_ZExt(m_Value(X))),
1855                                            m_ConstantInt(C1))))) {
1856           if (AndRHSMask.isIntN(X->getType()->getScalarSizeInBits())) {
1857             auto *TruncC1 = ConstantExpr::getTrunc(C1, X->getType());
1858             Value *BinOp;
1859             Value *Op0LHS = Op0I->getOperand(0);
1860             if (isa<ZExtInst>(Op0LHS))
1861               BinOp = Builder.CreateBinOp(Op0I->getOpcode(), X, TruncC1);
1862             else
1863               BinOp = Builder.CreateBinOp(Op0I->getOpcode(), TruncC1, X);
1864             auto *TruncC2 = ConstantExpr::getTrunc(AndRHS, X->getType());
1865             auto *And = Builder.CreateAnd(BinOp, TruncC2);
1866             return new ZExtInst(And, Ty);
1867           }
1868         }
1869       }
1870 
1871       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1872         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
1873           return Res;
1874     }
1875   }
1876 
1877   if (Instruction *Z = narrowMaskedBinOp(I))
1878     return Z;
1879 
1880   if (Instruction *FoldedLogic = foldBinOpIntoSelectOrPhi(I))
1881     return FoldedLogic;
1882 
1883   if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder))
1884     return DeMorgan;
1885 
1886   {
1887     Value *A, *B, *C;
1888     // A & (A ^ B) --> A & ~B
1889     if (match(Op1, m_OneUse(m_c_Xor(m_Specific(Op0), m_Value(B)))))
1890       return BinaryOperator::CreateAnd(Op0, Builder.CreateNot(B));
1891     // (A ^ B) & A --> A & ~B
1892     if (match(Op0, m_OneUse(m_c_Xor(m_Specific(Op1), m_Value(B)))))
1893       return BinaryOperator::CreateAnd(Op1, Builder.CreateNot(B));
1894 
1895     // (A ^ B) & ((B ^ C) ^ A) -> (A ^ B) & ~C
1896     if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
1897       if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
1898         if (Op1->hasOneUse() || isFreeToInvert(C, C->hasOneUse()))
1899           return BinaryOperator::CreateAnd(Op0, Builder.CreateNot(C));
1900 
1901     // ((A ^ C) ^ B) & (B ^ A) -> (B ^ A) & ~C
1902     if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
1903       if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
1904         if (Op0->hasOneUse() || isFreeToInvert(C, C->hasOneUse()))
1905           return BinaryOperator::CreateAnd(Op1, Builder.CreateNot(C));
1906 
1907     // (A | B) & ((~A) ^ B) -> (A & B)
1908     // (A | B) & (B ^ (~A)) -> (A & B)
1909     // (B | A) & ((~A) ^ B) -> (A & B)
1910     // (B | A) & (B ^ (~A)) -> (A & B)
1911     if (match(Op1, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
1912         match(Op0, m_c_Or(m_Specific(A), m_Specific(B))))
1913       return BinaryOperator::CreateAnd(A, B);
1914 
1915     // ((~A) ^ B) & (A | B) -> (A & B)
1916     // ((~A) ^ B) & (B | A) -> (A & B)
1917     // (B ^ (~A)) & (A | B) -> (A & B)
1918     // (B ^ (~A)) & (B | A) -> (A & B)
1919     if (match(Op0, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
1920         match(Op1, m_c_Or(m_Specific(A), m_Specific(B))))
1921       return BinaryOperator::CreateAnd(A, B);
1922   }
1923 
1924   {
1925     ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
1926     ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
1927     if (LHS && RHS)
1928       if (Value *Res = foldAndOfICmps(LHS, RHS, I))
1929         return replaceInstUsesWith(I, Res);
1930 
1931     // TODO: Make this recursive; it's a little tricky because an arbitrary
1932     // number of 'and' instructions might have to be created.
1933     Value *X, *Y;
1934     if (LHS && match(Op1, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1935       if (auto *Cmp = dyn_cast<ICmpInst>(X))
1936         if (Value *Res = foldAndOfICmps(LHS, Cmp, I))
1937           return replaceInstUsesWith(I, Builder.CreateAnd(Res, Y));
1938       if (auto *Cmp = dyn_cast<ICmpInst>(Y))
1939         if (Value *Res = foldAndOfICmps(LHS, Cmp, I))
1940           return replaceInstUsesWith(I, Builder.CreateAnd(Res, X));
1941     }
1942     if (RHS && match(Op0, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1943       if (auto *Cmp = dyn_cast<ICmpInst>(X))
1944         if (Value *Res = foldAndOfICmps(Cmp, RHS, I))
1945           return replaceInstUsesWith(I, Builder.CreateAnd(Res, Y));
1946       if (auto *Cmp = dyn_cast<ICmpInst>(Y))
1947         if (Value *Res = foldAndOfICmps(Cmp, RHS, I))
1948           return replaceInstUsesWith(I, Builder.CreateAnd(Res, X));
1949     }
1950   }
1951 
1952   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1953     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
1954       if (Value *Res = foldLogicOfFCmps(LHS, RHS, true))
1955         return replaceInstUsesWith(I, Res);
1956 
1957   if (Instruction *FoldedFCmps = reassociateFCmps(I, Builder))
1958     return FoldedFCmps;
1959 
1960   if (Instruction *CastedAnd = foldCastedBitwiseLogic(I))
1961     return CastedAnd;
1962 
1963   // and(sext(A), B) / and(B, sext(A)) --> A ? B : 0, where A is i1 or <N x i1>.
1964   Value *A;
1965   if (match(Op0, m_OneUse(m_SExt(m_Value(A)))) &&
1966       A->getType()->isIntOrIntVectorTy(1))
1967     return SelectInst::Create(A, Op1, Constant::getNullValue(Ty));
1968   if (match(Op1, m_OneUse(m_SExt(m_Value(A)))) &&
1969       A->getType()->isIntOrIntVectorTy(1))
1970     return SelectInst::Create(A, Op0, Constant::getNullValue(Ty));
1971 
1972   // and(ashr(subNSW(Y, X), ScalarSizeInBits(Y)-1), X) --> X s> Y ? X : 0.
1973   {
1974     Value *X, *Y;
1975     const APInt *ShAmt;
1976     if (match(&I, m_c_And(m_OneUse(m_AShr(m_NSWSub(m_Value(Y), m_Value(X)),
1977                                           m_APInt(ShAmt))),
1978                           m_Deferred(X))) &&
1979         *ShAmt == Ty->getScalarSizeInBits() - 1) {
1980       Value *NewICmpInst = Builder.CreateICmpSGT(X, Y);
1981       return SelectInst::Create(NewICmpInst, X, ConstantInt::getNullValue(Ty));
1982     }
1983   }
1984 
1985   return nullptr;
1986 }
1987 
1988 Instruction *InstCombinerImpl::matchBSwap(BinaryOperator &Or) {
1989   assert(Or.getOpcode() == Instruction::Or && "bswap requires an 'or'");
1990   Value *Op0 = Or.getOperand(0), *Op1 = Or.getOperand(1);
1991 
1992   // Look through zero extends.
1993   if (Instruction *Ext = dyn_cast<ZExtInst>(Op0))
1994     Op0 = Ext->getOperand(0);
1995 
1996   if (Instruction *Ext = dyn_cast<ZExtInst>(Op1))
1997     Op1 = Ext->getOperand(0);
1998 
1999   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
2000   bool OrWithOrs = match(Op0, m_Or(m_Value(), m_Value())) ||
2001                    match(Op1, m_Or(m_Value(), m_Value()));
2002 
2003   // (A >> B) | C  and  (A << B) | C                -> bswap if possible.
2004   bool OrWithShifts = match(Op0, m_LogicalShift(m_Value(), m_Value())) ||
2005                       match(Op1, m_LogicalShift(m_Value(), m_Value()));
2006 
2007   // (A & B) | C  and  A | (B & C)                  -> bswap if possible.
2008   bool OrWithAnds = match(Op0, m_And(m_Value(), m_Value())) ||
2009                     match(Op1, m_And(m_Value(), m_Value()));
2010 
2011   if (!OrWithOrs && !OrWithShifts && !OrWithAnds)
2012     return nullptr;
2013 
2014   SmallVector<Instruction*, 4> Insts;
2015   if (!recognizeBSwapOrBitReverseIdiom(&Or, true, false, Insts))
2016     return nullptr;
2017   Instruction *LastInst = Insts.pop_back_val();
2018   LastInst->removeFromParent();
2019 
2020   for (auto *Inst : Insts)
2021     Worklist.push(Inst);
2022   return LastInst;
2023 }
2024 
2025 /// Match UB-safe variants of the funnel shift intrinsic.
2026 static Instruction *matchFunnelShift(Instruction &Or, InstCombinerImpl &IC) {
2027   // TODO: Can we reduce the code duplication between this and the related
2028   // rotate matching code under visitSelect and visitTrunc?
2029   unsigned Width = Or.getType()->getScalarSizeInBits();
2030 
2031   // First, find an or'd pair of opposite shifts:
2032   // or (lshr ShVal0, ShAmt0), (shl ShVal1, ShAmt1)
2033   BinaryOperator *Or0, *Or1;
2034   if (!match(Or.getOperand(0), m_BinOp(Or0)) ||
2035       !match(Or.getOperand(1), m_BinOp(Or1)))
2036     return nullptr;
2037 
2038   Value *ShVal0, *ShVal1, *ShAmt0, *ShAmt1;
2039   if (!match(Or0, m_OneUse(m_LogicalShift(m_Value(ShVal0), m_Value(ShAmt0)))) ||
2040       !match(Or1, m_OneUse(m_LogicalShift(m_Value(ShVal1), m_Value(ShAmt1)))) ||
2041       Or0->getOpcode() == Or1->getOpcode())
2042     return nullptr;
2043 
2044   // Canonicalize to or(shl(ShVal0, ShAmt0), lshr(ShVal1, ShAmt1)).
2045   if (Or0->getOpcode() == BinaryOperator::LShr) {
2046     std::swap(Or0, Or1);
2047     std::swap(ShVal0, ShVal1);
2048     std::swap(ShAmt0, ShAmt1);
2049   }
2050   assert(Or0->getOpcode() == BinaryOperator::Shl &&
2051          Or1->getOpcode() == BinaryOperator::LShr &&
2052          "Illegal or(shift,shift) pair");
2053 
2054   // Match the shift amount operands for a funnel shift pattern. This always
2055   // matches a subtraction on the R operand.
2056   auto matchShiftAmount = [&](Value *L, Value *R, unsigned Width) -> Value * {
2057     // Check for constant shift amounts that sum to the bitwidth.
2058     const APInt *LI, *RI;
2059     if (match(L, m_APIntAllowUndef(LI)) && match(R, m_APIntAllowUndef(RI)))
2060       if (LI->ult(Width) && RI->ult(Width) && (*LI + *RI) == Width)
2061         return ConstantInt::get(L->getType(), *LI);
2062 
2063     Constant *LC, *RC;
2064     if (match(L, m_Constant(LC)) && match(R, m_Constant(RC)) &&
2065         match(L, m_SpecificInt_ICMP(ICmpInst::ICMP_ULT, APInt(Width, Width))) &&
2066         match(R, m_SpecificInt_ICMP(ICmpInst::ICMP_ULT, APInt(Width, Width))) &&
2067         match(ConstantExpr::getAdd(LC, RC), m_SpecificIntAllowUndef(Width)))
2068       return ConstantExpr::mergeUndefsWith(LC, RC);
2069 
2070     // (shl ShVal, X) | (lshr ShVal, (Width - x)) iff X < Width.
2071     // We limit this to X < Width in case the backend re-expands the intrinsic,
2072     // and has to reintroduce a shift modulo operation (InstCombine might remove
2073     // it after this fold). This still doesn't guarantee that the final codegen
2074     // will match this original pattern.
2075     if (match(R, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(L))))) {
2076       KnownBits KnownL = IC.computeKnownBits(L, /*Depth*/ 0, &Or);
2077       return KnownL.getMaxValue().ult(Width) ? L : nullptr;
2078     }
2079 
2080     // For non-constant cases, the following patterns currently only work for
2081     // rotation patterns.
2082     // TODO: Add general funnel-shift compatible patterns.
2083     if (ShVal0 != ShVal1)
2084       return nullptr;
2085 
2086     // For non-constant cases we don't support non-pow2 shift masks.
2087     // TODO: Is it worth matching urem as well?
2088     if (!isPowerOf2_32(Width))
2089       return nullptr;
2090 
2091     // The shift amount may be masked with negation:
2092     // (shl ShVal, (X & (Width - 1))) | (lshr ShVal, ((-X) & (Width - 1)))
2093     Value *X;
2094     unsigned Mask = Width - 1;
2095     if (match(L, m_And(m_Value(X), m_SpecificInt(Mask))) &&
2096         match(R, m_And(m_Neg(m_Specific(X)), m_SpecificInt(Mask))))
2097       return X;
2098 
2099     // Similar to above, but the shift amount may be extended after masking,
2100     // so return the extended value as the parameter for the intrinsic.
2101     if (match(L, m_ZExt(m_And(m_Value(X), m_SpecificInt(Mask)))) &&
2102         match(R, m_And(m_Neg(m_ZExt(m_And(m_Specific(X), m_SpecificInt(Mask)))),
2103                        m_SpecificInt(Mask))))
2104       return L;
2105 
2106     return nullptr;
2107   };
2108 
2109   Value *ShAmt = matchShiftAmount(ShAmt0, ShAmt1, Width);
2110   bool IsFshl = true; // Sub on LSHR.
2111   if (!ShAmt) {
2112     ShAmt = matchShiftAmount(ShAmt1, ShAmt0, Width);
2113     IsFshl = false; // Sub on SHL.
2114   }
2115   if (!ShAmt)
2116     return nullptr;
2117 
2118   Intrinsic::ID IID = IsFshl ? Intrinsic::fshl : Intrinsic::fshr;
2119   Function *F = Intrinsic::getDeclaration(Or.getModule(), IID, Or.getType());
2120   return IntrinsicInst::Create(F, {ShVal0, ShVal1, ShAmt});
2121 }
2122 
2123 /// Attempt to combine or(zext(x),shl(zext(y),bw/2) concat packing patterns.
2124 static Instruction *matchOrConcat(Instruction &Or,
2125                                   InstCombiner::BuilderTy &Builder) {
2126   assert(Or.getOpcode() == Instruction::Or && "bswap requires an 'or'");
2127   Value *Op0 = Or.getOperand(0), *Op1 = Or.getOperand(1);
2128   Type *Ty = Or.getType();
2129 
2130   unsigned Width = Ty->getScalarSizeInBits();
2131   if ((Width & 1) != 0)
2132     return nullptr;
2133   unsigned HalfWidth = Width / 2;
2134 
2135   // Canonicalize zext (lower half) to LHS.
2136   if (!isa<ZExtInst>(Op0))
2137     std::swap(Op0, Op1);
2138 
2139   // Find lower/upper half.
2140   Value *LowerSrc, *ShlVal, *UpperSrc;
2141   const APInt *C;
2142   if (!match(Op0, m_OneUse(m_ZExt(m_Value(LowerSrc)))) ||
2143       !match(Op1, m_OneUse(m_Shl(m_Value(ShlVal), m_APInt(C)))) ||
2144       !match(ShlVal, m_OneUse(m_ZExt(m_Value(UpperSrc)))))
2145     return nullptr;
2146   if (*C != HalfWidth || LowerSrc->getType() != UpperSrc->getType() ||
2147       LowerSrc->getType()->getScalarSizeInBits() != HalfWidth)
2148     return nullptr;
2149 
2150   auto ConcatIntrinsicCalls = [&](Intrinsic::ID id, Value *Lo, Value *Hi) {
2151     Value *NewLower = Builder.CreateZExt(Lo, Ty);
2152     Value *NewUpper = Builder.CreateZExt(Hi, Ty);
2153     NewUpper = Builder.CreateShl(NewUpper, HalfWidth);
2154     Value *BinOp = Builder.CreateOr(NewLower, NewUpper);
2155     Function *F = Intrinsic::getDeclaration(Or.getModule(), id, Ty);
2156     return Builder.CreateCall(F, BinOp);
2157   };
2158 
2159   // BSWAP: Push the concat down, swapping the lower/upper sources.
2160   // concat(bswap(x),bswap(y)) -> bswap(concat(x,y))
2161   Value *LowerBSwap, *UpperBSwap;
2162   if (match(LowerSrc, m_BSwap(m_Value(LowerBSwap))) &&
2163       match(UpperSrc, m_BSwap(m_Value(UpperBSwap))))
2164     return ConcatIntrinsicCalls(Intrinsic::bswap, UpperBSwap, LowerBSwap);
2165 
2166   // BITREVERSE: Push the concat down, swapping the lower/upper sources.
2167   // concat(bitreverse(x),bitreverse(y)) -> bitreverse(concat(x,y))
2168   Value *LowerBRev, *UpperBRev;
2169   if (match(LowerSrc, m_BitReverse(m_Value(LowerBRev))) &&
2170       match(UpperSrc, m_BitReverse(m_Value(UpperBRev))))
2171     return ConcatIntrinsicCalls(Intrinsic::bitreverse, UpperBRev, LowerBRev);
2172 
2173   return nullptr;
2174 }
2175 
2176 /// If all elements of two constant vectors are 0/-1 and inverses, return true.
2177 static bool areInverseVectorBitmasks(Constant *C1, Constant *C2) {
2178   unsigned NumElts = cast<FixedVectorType>(C1->getType())->getNumElements();
2179   for (unsigned i = 0; i != NumElts; ++i) {
2180     Constant *EltC1 = C1->getAggregateElement(i);
2181     Constant *EltC2 = C2->getAggregateElement(i);
2182     if (!EltC1 || !EltC2)
2183       return false;
2184 
2185     // One element must be all ones, and the other must be all zeros.
2186     if (!((match(EltC1, m_Zero()) && match(EltC2, m_AllOnes())) ||
2187           (match(EltC2, m_Zero()) && match(EltC1, m_AllOnes()))))
2188       return false;
2189   }
2190   return true;
2191 }
2192 
2193 /// We have an expression of the form (A & C) | (B & D). If A is a scalar or
2194 /// vector composed of all-zeros or all-ones values and is the bitwise 'not' of
2195 /// B, it can be used as the condition operand of a select instruction.
2196 Value *InstCombinerImpl::getSelectCondition(Value *A, Value *B) {
2197   // Step 1: We may have peeked through bitcasts in the caller.
2198   // Exit immediately if we don't have (vector) integer types.
2199   Type *Ty = A->getType();
2200   if (!Ty->isIntOrIntVectorTy() || !B->getType()->isIntOrIntVectorTy())
2201     return nullptr;
2202 
2203   // Step 2: We need 0 or all-1's bitmasks.
2204   if (ComputeNumSignBits(A) != Ty->getScalarSizeInBits())
2205     return nullptr;
2206 
2207   // Step 3: If B is the 'not' value of A, we have our answer.
2208   if (match(A, m_Not(m_Specific(B)))) {
2209     // If these are scalars or vectors of i1, A can be used directly.
2210     if (Ty->isIntOrIntVectorTy(1))
2211       return A;
2212     return Builder.CreateTrunc(A, CmpInst::makeCmpResultType(Ty));
2213   }
2214 
2215   // If both operands are constants, see if the constants are inverse bitmasks.
2216   Constant *AConst, *BConst;
2217   if (match(A, m_Constant(AConst)) && match(B, m_Constant(BConst)))
2218     if (AConst == ConstantExpr::getNot(BConst))
2219       return Builder.CreateZExtOrTrunc(A, CmpInst::makeCmpResultType(Ty));
2220 
2221   // Look for more complex patterns. The 'not' op may be hidden behind various
2222   // casts. Look through sexts and bitcasts to find the booleans.
2223   Value *Cond;
2224   Value *NotB;
2225   if (match(A, m_SExt(m_Value(Cond))) &&
2226       Cond->getType()->isIntOrIntVectorTy(1) &&
2227       match(B, m_OneUse(m_Not(m_Value(NotB))))) {
2228     NotB = peekThroughBitcast(NotB, true);
2229     if (match(NotB, m_SExt(m_Specific(Cond))))
2230       return Cond;
2231   }
2232 
2233   // All scalar (and most vector) possibilities should be handled now.
2234   // Try more matches that only apply to non-splat constant vectors.
2235   if (!Ty->isVectorTy())
2236     return nullptr;
2237 
2238   // If both operands are xor'd with constants using the same sexted boolean
2239   // operand, see if the constants are inverse bitmasks.
2240   // TODO: Use ConstantExpr::getNot()?
2241   if (match(A, (m_Xor(m_SExt(m_Value(Cond)), m_Constant(AConst)))) &&
2242       match(B, (m_Xor(m_SExt(m_Specific(Cond)), m_Constant(BConst)))) &&
2243       Cond->getType()->isIntOrIntVectorTy(1) &&
2244       areInverseVectorBitmasks(AConst, BConst)) {
2245     AConst = ConstantExpr::getTrunc(AConst, CmpInst::makeCmpResultType(Ty));
2246     return Builder.CreateXor(Cond, AConst);
2247   }
2248   return nullptr;
2249 }
2250 
2251 /// We have an expression of the form (A & C) | (B & D). Try to simplify this
2252 /// to "A' ? C : D", where A' is a boolean or vector of booleans.
2253 Value *InstCombinerImpl::matchSelectFromAndOr(Value *A, Value *C, Value *B,
2254                                               Value *D) {
2255   // The potential condition of the select may be bitcasted. In that case, look
2256   // through its bitcast and the corresponding bitcast of the 'not' condition.
2257   Type *OrigType = A->getType();
2258   A = peekThroughBitcast(A, true);
2259   B = peekThroughBitcast(B, true);
2260   if (Value *Cond = getSelectCondition(A, B)) {
2261     // ((bc Cond) & C) | ((bc ~Cond) & D) --> bc (select Cond, (bc C), (bc D))
2262     // The bitcasts will either all exist or all not exist. The builder will
2263     // not create unnecessary casts if the types already match.
2264     Value *BitcastC = Builder.CreateBitCast(C, A->getType());
2265     Value *BitcastD = Builder.CreateBitCast(D, A->getType());
2266     Value *Select = Builder.CreateSelect(Cond, BitcastC, BitcastD);
2267     return Builder.CreateBitCast(Select, OrigType);
2268   }
2269 
2270   return nullptr;
2271 }
2272 
2273 /// Fold (icmp)|(icmp) if possible.
2274 Value *InstCombinerImpl::foldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS,
2275                                        BinaryOperator &Or) {
2276   const SimplifyQuery Q = SQ.getWithInstruction(&Or);
2277 
2278   // Fold (iszero(A & K1) | iszero(A & K2)) ->  (A & (K1 | K2)) != (K1 | K2)
2279   // if K1 and K2 are a one-bit mask.
2280   if (Value *V = foldAndOrOfICmpsOfAndWithPow2(LHS, RHS, Or))
2281     return V;
2282 
2283   ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
2284   Value *LHS0 = LHS->getOperand(0), *RHS0 = RHS->getOperand(0);
2285   Value *LHS1 = LHS->getOperand(1), *RHS1 = RHS->getOperand(1);
2286   auto *LHSC = dyn_cast<ConstantInt>(LHS1);
2287   auto *RHSC = dyn_cast<ConstantInt>(RHS1);
2288 
2289   // Fold (icmp ult/ule (A + C1), C3) | (icmp ult/ule (A + C2), C3)
2290   //                   -->  (icmp ult/ule ((A & ~(C1 ^ C2)) + max(C1, C2)), C3)
2291   // The original condition actually refers to the following two ranges:
2292   // [MAX_UINT-C1+1, MAX_UINT-C1+1+C3] and [MAX_UINT-C2+1, MAX_UINT-C2+1+C3]
2293   // We can fold these two ranges if:
2294   // 1) C1 and C2 is unsigned greater than C3.
2295   // 2) The two ranges are separated.
2296   // 3) C1 ^ C2 is one-bit mask.
2297   // 4) LowRange1 ^ LowRange2 and HighRange1 ^ HighRange2 are one-bit mask.
2298   // This implies all values in the two ranges differ by exactly one bit.
2299   if ((PredL == ICmpInst::ICMP_ULT || PredL == ICmpInst::ICMP_ULE) &&
2300       PredL == PredR && LHSC && RHSC && LHS->hasOneUse() && RHS->hasOneUse() &&
2301       LHSC->getType() == RHSC->getType() &&
2302       LHSC->getValue() == (RHSC->getValue())) {
2303 
2304     Value *LAddOpnd, *RAddOpnd;
2305     ConstantInt *LAddC, *RAddC;
2306     if (match(LHS0, m_Add(m_Value(LAddOpnd), m_ConstantInt(LAddC))) &&
2307         match(RHS0, m_Add(m_Value(RAddOpnd), m_ConstantInt(RAddC))) &&
2308         LAddC->getValue().ugt(LHSC->getValue()) &&
2309         RAddC->getValue().ugt(LHSC->getValue())) {
2310 
2311       APInt DiffC = LAddC->getValue() ^ RAddC->getValue();
2312       if (LAddOpnd == RAddOpnd && DiffC.isPowerOf2()) {
2313         ConstantInt *MaxAddC = nullptr;
2314         if (LAddC->getValue().ult(RAddC->getValue()))
2315           MaxAddC = RAddC;
2316         else
2317           MaxAddC = LAddC;
2318 
2319         APInt RRangeLow = -RAddC->getValue();
2320         APInt RRangeHigh = RRangeLow + LHSC->getValue();
2321         APInt LRangeLow = -LAddC->getValue();
2322         APInt LRangeHigh = LRangeLow + LHSC->getValue();
2323         APInt LowRangeDiff = RRangeLow ^ LRangeLow;
2324         APInt HighRangeDiff = RRangeHigh ^ LRangeHigh;
2325         APInt RangeDiff = LRangeLow.sgt(RRangeLow) ? LRangeLow - RRangeLow
2326                                                    : RRangeLow - LRangeLow;
2327 
2328         if (LowRangeDiff.isPowerOf2() && LowRangeDiff == HighRangeDiff &&
2329             RangeDiff.ugt(LHSC->getValue())) {
2330           Value *MaskC = ConstantInt::get(LAddC->getType(), ~DiffC);
2331 
2332           Value *NewAnd = Builder.CreateAnd(LAddOpnd, MaskC);
2333           Value *NewAdd = Builder.CreateAdd(NewAnd, MaxAddC);
2334           return Builder.CreateICmp(LHS->getPredicate(), NewAdd, LHSC);
2335         }
2336       }
2337     }
2338   }
2339 
2340   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
2341   if (predicatesFoldable(PredL, PredR)) {
2342     if (LHS0 == RHS1 && LHS1 == RHS0)
2343       LHS->swapOperands();
2344     if (LHS0 == RHS0 && LHS1 == RHS1) {
2345       unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
2346       bool IsSigned = LHS->isSigned() || RHS->isSigned();
2347       return getNewICmpValue(Code, IsSigned, LHS0, LHS1, Builder);
2348     }
2349   }
2350 
2351   // handle (roughly):
2352   // (icmp ne (A & B), C) | (icmp ne (A & D), E)
2353   if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, false, Builder))
2354     return V;
2355 
2356   if (LHS->hasOneUse() || RHS->hasOneUse()) {
2357     // (icmp eq B, 0) | (icmp ult A, B) -> (icmp ule A, B-1)
2358     // (icmp eq B, 0) | (icmp ugt B, A) -> (icmp ule A, B-1)
2359     Value *A = nullptr, *B = nullptr;
2360     if (PredL == ICmpInst::ICMP_EQ && match(LHS1, m_Zero())) {
2361       B = LHS0;
2362       if (PredR == ICmpInst::ICMP_ULT && LHS0 == RHS1)
2363         A = RHS0;
2364       else if (PredR == ICmpInst::ICMP_UGT && LHS0 == RHS0)
2365         A = RHS1;
2366     }
2367     // (icmp ult A, B) | (icmp eq B, 0) -> (icmp ule A, B-1)
2368     // (icmp ugt B, A) | (icmp eq B, 0) -> (icmp ule A, B-1)
2369     else if (PredR == ICmpInst::ICMP_EQ && match(RHS1, m_Zero())) {
2370       B = RHS0;
2371       if (PredL == ICmpInst::ICMP_ULT && RHS0 == LHS1)
2372         A = LHS0;
2373       else if (PredL == ICmpInst::ICMP_UGT && RHS0 == LHS0)
2374         A = LHS1;
2375     }
2376     if (A && B && B->getType()->isIntOrIntVectorTy())
2377       return Builder.CreateICmp(
2378           ICmpInst::ICMP_UGE,
2379           Builder.CreateAdd(B, Constant::getAllOnesValue(B->getType())), A);
2380   }
2381 
2382   if (Value *V = foldAndOrOfICmpsWithConstEq(LHS, RHS, Or, Builder, Q))
2383     return V;
2384   if (Value *V = foldAndOrOfICmpsWithConstEq(RHS, LHS, Or, Builder, Q))
2385     return V;
2386 
2387   // E.g. (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
2388   if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/true))
2389     return V;
2390 
2391   // E.g. (icmp sgt x, n) | (icmp slt x, 0) --> icmp ugt x, n
2392   if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/true))
2393     return V;
2394 
2395   if (Value *V = foldAndOrOfEqualityCmpsWithConstants(LHS, RHS, false, Builder))
2396     return V;
2397 
2398   if (Value *V = foldIsPowerOf2(LHS, RHS, false /* JoinedByAnd */, Builder))
2399     return V;
2400 
2401   if (Value *X =
2402           foldUnsignedUnderflowCheck(LHS, RHS, /*IsAnd=*/false, Q, Builder))
2403     return X;
2404   if (Value *X =
2405           foldUnsignedUnderflowCheck(RHS, LHS, /*IsAnd=*/false, Q, Builder))
2406     return X;
2407 
2408   // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
2409   // TODO: Remove this when foldLogOpOfMaskedICmps can handle vectors.
2410   if (PredL == ICmpInst::ICMP_NE && match(LHS1, m_Zero()) &&
2411       PredR == ICmpInst::ICMP_NE && match(RHS1, m_Zero()) &&
2412       LHS0->getType()->isIntOrIntVectorTy() &&
2413       LHS0->getType() == RHS0->getType()) {
2414     Value *NewOr = Builder.CreateOr(LHS0, RHS0);
2415     return Builder.CreateICmp(PredL, NewOr,
2416                               Constant::getNullValue(NewOr->getType()));
2417   }
2418 
2419   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
2420   if (!LHSC || !RHSC)
2421     return nullptr;
2422 
2423   // (icmp ult (X + CA), C1) | (icmp eq X, C2) -> (icmp ule (X + CA), C1)
2424   //   iff C2 + CA == C1.
2425   if (PredL == ICmpInst::ICMP_ULT && PredR == ICmpInst::ICMP_EQ) {
2426     ConstantInt *AddC;
2427     if (match(LHS0, m_Add(m_Specific(RHS0), m_ConstantInt(AddC))))
2428       if (RHSC->getValue() + AddC->getValue() == LHSC->getValue())
2429         return Builder.CreateICmpULE(LHS0, LHSC);
2430   }
2431 
2432   // From here on, we only handle:
2433   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
2434   if (LHS0 != RHS0)
2435     return nullptr;
2436 
2437   // ICMP_[US][GL]E X, C is folded to ICMP_[US][GL]T elsewhere.
2438   if (PredL == ICmpInst::ICMP_UGE || PredL == ICmpInst::ICMP_ULE ||
2439       PredR == ICmpInst::ICMP_UGE || PredR == ICmpInst::ICMP_ULE ||
2440       PredL == ICmpInst::ICMP_SGE || PredL == ICmpInst::ICMP_SLE ||
2441       PredR == ICmpInst::ICMP_SGE || PredR == ICmpInst::ICMP_SLE)
2442     return nullptr;
2443 
2444   // We can't fold (ugt x, C) | (sgt x, C2).
2445   if (!predicatesFoldable(PredL, PredR))
2446     return nullptr;
2447 
2448   // Ensure that the larger constant is on the RHS.
2449   bool ShouldSwap;
2450   if (CmpInst::isSigned(PredL) ||
2451       (ICmpInst::isEquality(PredL) && CmpInst::isSigned(PredR)))
2452     ShouldSwap = LHSC->getValue().sgt(RHSC->getValue());
2453   else
2454     ShouldSwap = LHSC->getValue().ugt(RHSC->getValue());
2455 
2456   if (ShouldSwap) {
2457     std::swap(LHS, RHS);
2458     std::swap(LHSC, RHSC);
2459     std::swap(PredL, PredR);
2460   }
2461 
2462   // At this point, we know we have two icmp instructions
2463   // comparing a value against two constants and or'ing the result
2464   // together.  Because of the above check, we know that we only have
2465   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
2466   // icmp folding check above), that the two constants are not
2467   // equal.
2468   assert(LHSC != RHSC && "Compares not folded above?");
2469 
2470   switch (PredL) {
2471   default:
2472     llvm_unreachable("Unknown integer condition code!");
2473   case ICmpInst::ICMP_EQ:
2474     switch (PredR) {
2475     default:
2476       llvm_unreachable("Unknown integer condition code!");
2477     case ICmpInst::ICMP_EQ:
2478       // Potential folds for this case should already be handled.
2479       break;
2480     case ICmpInst::ICMP_UGT:
2481       // (X == 0 || X u> C) -> (X-1) u>= C
2482       if (LHSC->isMinValue(false))
2483         return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue() + 1,
2484                                false, false);
2485       // (X == 13 | X u> 14) -> no change
2486       break;
2487     case ICmpInst::ICMP_SGT:
2488       // (X == INT_MIN || X s> C) -> (X-(INT_MIN+1)) u>= C-INT_MIN
2489       if (LHSC->isMinValue(true))
2490         return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue() + 1,
2491                                true, false);
2492       // (X == 13 | X s> 14) -> no change
2493       break;
2494     }
2495     break;
2496   case ICmpInst::ICMP_ULT:
2497     switch (PredR) {
2498     default:
2499       llvm_unreachable("Unknown integer condition code!");
2500     case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
2501       // (X u< C || X == UINT_MAX) => (X-C) u>= UINT_MAX-C
2502       if (RHSC->isMaxValue(false))
2503         return insertRangeTest(LHS0, LHSC->getValue(), RHSC->getValue(),
2504                                false, false);
2505       break;
2506     case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
2507       assert(!RHSC->isMaxValue(false) && "Missed icmp simplification");
2508       return insertRangeTest(LHS0, LHSC->getValue(), RHSC->getValue() + 1,
2509                              false, false);
2510     }
2511     break;
2512   case ICmpInst::ICMP_SLT:
2513     switch (PredR) {
2514     default:
2515       llvm_unreachable("Unknown integer condition code!");
2516     case ICmpInst::ICMP_EQ:
2517       // (X s< C || X == INT_MAX) => (X-C) u>= INT_MAX-C
2518       if (RHSC->isMaxValue(true))
2519         return insertRangeTest(LHS0, LHSC->getValue(), RHSC->getValue(),
2520                                true, false);
2521       // (X s< 13 | X == 14) -> no change
2522       break;
2523     case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) u> 2
2524       assert(!RHSC->isMaxValue(true) && "Missed icmp simplification");
2525       return insertRangeTest(LHS0, LHSC->getValue(), RHSC->getValue() + 1, true,
2526                              false);
2527     }
2528     break;
2529   }
2530   return nullptr;
2531 }
2532 
2533 // FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
2534 // here. We should standardize that construct where it is needed or choose some
2535 // other way to ensure that commutated variants of patterns are not missed.
2536 Instruction *InstCombinerImpl::visitOr(BinaryOperator &I) {
2537   if (Value *V = SimplifyOrInst(I.getOperand(0), I.getOperand(1),
2538                                 SQ.getWithInstruction(&I)))
2539     return replaceInstUsesWith(I, V);
2540 
2541   if (SimplifyAssociativeOrCommutative(I))
2542     return &I;
2543 
2544   if (Instruction *X = foldVectorBinop(I))
2545     return X;
2546 
2547   // See if we can simplify any instructions used by the instruction whose sole
2548   // purpose is to compute bits we don't care about.
2549   if (SimplifyDemandedInstructionBits(I))
2550     return &I;
2551 
2552   // Do this before using distributive laws to catch simple and/or/not patterns.
2553   if (Instruction *Xor = foldOrToXor(I, Builder))
2554     return Xor;
2555 
2556   // (A&B)|(A&C) -> A&(B|C) etc
2557   if (Value *V = SimplifyUsingDistributiveLaws(I))
2558     return replaceInstUsesWith(I, V);
2559 
2560   if (Value *V = SimplifyBSwap(I, Builder))
2561     return replaceInstUsesWith(I, V);
2562 
2563   if (Instruction *FoldedLogic = foldBinOpIntoSelectOrPhi(I))
2564     return FoldedLogic;
2565 
2566   if (Instruction *BSwap = matchBSwap(I))
2567     return BSwap;
2568 
2569   if (Instruction *Funnel = matchFunnelShift(I, *this))
2570     return Funnel;
2571 
2572   if (Instruction *Concat = matchOrConcat(I, Builder))
2573     return replaceInstUsesWith(I, Concat);
2574 
2575   Value *X, *Y;
2576   const APInt *CV;
2577   if (match(&I, m_c_Or(m_OneUse(m_Xor(m_Value(X), m_APInt(CV))), m_Value(Y))) &&
2578       !CV->isAllOnesValue() && MaskedValueIsZero(Y, *CV, 0, &I)) {
2579     // (X ^ C) | Y -> (X | Y) ^ C iff Y & C == 0
2580     // The check for a 'not' op is for efficiency (if Y is known zero --> ~X).
2581     Value *Or = Builder.CreateOr(X, Y);
2582     return BinaryOperator::CreateXor(Or, ConstantInt::get(I.getType(), *CV));
2583   }
2584 
2585   // (A & C)|(B & D)
2586   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2587   Value *A, *B, *C, *D;
2588   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
2589       match(Op1, m_And(m_Value(B), m_Value(D)))) {
2590     // (A & C1)|(B & C2)
2591     ConstantInt *C1, *C2;
2592     if (match(C, m_ConstantInt(C1)) && match(D, m_ConstantInt(C2))) {
2593       Value *V1 = nullptr, *V2 = nullptr;
2594       if ((C1->getValue() & C2->getValue()).isNullValue()) {
2595         // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
2596         // iff (C1&C2) == 0 and (N&~C1) == 0
2597         if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
2598             ((V1 == B &&
2599               MaskedValueIsZero(V2, ~C1->getValue(), 0, &I)) || // (V|N)
2600              (V2 == B &&
2601               MaskedValueIsZero(V1, ~C1->getValue(), 0, &I))))  // (N|V)
2602           return BinaryOperator::CreateAnd(A,
2603                                 Builder.getInt(C1->getValue()|C2->getValue()));
2604         // Or commutes, try both ways.
2605         if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
2606             ((V1 == A &&
2607               MaskedValueIsZero(V2, ~C2->getValue(), 0, &I)) || // (V|N)
2608              (V2 == A &&
2609               MaskedValueIsZero(V1, ~C2->getValue(), 0, &I))))  // (N|V)
2610           return BinaryOperator::CreateAnd(B,
2611                                  Builder.getInt(C1->getValue()|C2->getValue()));
2612 
2613         // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
2614         // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
2615         ConstantInt *C3 = nullptr, *C4 = nullptr;
2616         if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
2617             (C3->getValue() & ~C1->getValue()).isNullValue() &&
2618             match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
2619             (C4->getValue() & ~C2->getValue()).isNullValue()) {
2620           V2 = Builder.CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
2621           return BinaryOperator::CreateAnd(V2,
2622                                  Builder.getInt(C1->getValue()|C2->getValue()));
2623         }
2624       }
2625 
2626       if (C1->getValue() == ~C2->getValue()) {
2627         Value *X;
2628 
2629         // ((X|B)&C1)|(B&C2) -> (X&C1) | B iff C1 == ~C2
2630         if (match(A, m_c_Or(m_Value(X), m_Specific(B))))
2631           return BinaryOperator::CreateOr(Builder.CreateAnd(X, C1), B);
2632         // (A&C2)|((X|A)&C1) -> (X&C2) | A iff C1 == ~C2
2633         if (match(B, m_c_Or(m_Specific(A), m_Value(X))))
2634           return BinaryOperator::CreateOr(Builder.CreateAnd(X, C2), A);
2635 
2636         // ((X^B)&C1)|(B&C2) -> (X&C1) ^ B iff C1 == ~C2
2637         if (match(A, m_c_Xor(m_Value(X), m_Specific(B))))
2638           return BinaryOperator::CreateXor(Builder.CreateAnd(X, C1), B);
2639         // (A&C2)|((X^A)&C1) -> (X&C2) ^ A iff C1 == ~C2
2640         if (match(B, m_c_Xor(m_Specific(A), m_Value(X))))
2641           return BinaryOperator::CreateXor(Builder.CreateAnd(X, C2), A);
2642       }
2643     }
2644 
2645     // Don't try to form a select if it's unlikely that we'll get rid of at
2646     // least one of the operands. A select is generally more expensive than the
2647     // 'or' that it is replacing.
2648     if (Op0->hasOneUse() || Op1->hasOneUse()) {
2649       // (Cond & C) | (~Cond & D) -> Cond ? C : D, and commuted variants.
2650       if (Value *V = matchSelectFromAndOr(A, C, B, D))
2651         return replaceInstUsesWith(I, V);
2652       if (Value *V = matchSelectFromAndOr(A, C, D, B))
2653         return replaceInstUsesWith(I, V);
2654       if (Value *V = matchSelectFromAndOr(C, A, B, D))
2655         return replaceInstUsesWith(I, V);
2656       if (Value *V = matchSelectFromAndOr(C, A, D, B))
2657         return replaceInstUsesWith(I, V);
2658       if (Value *V = matchSelectFromAndOr(B, D, A, C))
2659         return replaceInstUsesWith(I, V);
2660       if (Value *V = matchSelectFromAndOr(B, D, C, A))
2661         return replaceInstUsesWith(I, V);
2662       if (Value *V = matchSelectFromAndOr(D, B, A, C))
2663         return replaceInstUsesWith(I, V);
2664       if (Value *V = matchSelectFromAndOr(D, B, C, A))
2665         return replaceInstUsesWith(I, V);
2666     }
2667   }
2668 
2669   // (A ^ B) | ((B ^ C) ^ A) -> (A ^ B) | C
2670   if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
2671     if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
2672       return BinaryOperator::CreateOr(Op0, C);
2673 
2674   // ((A ^ C) ^ B) | (B ^ A) -> (B ^ A) | C
2675   if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
2676     if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
2677       return BinaryOperator::CreateOr(Op1, C);
2678 
2679   // ((B | C) & A) | B -> B | (A & C)
2680   if (match(Op0, m_And(m_Or(m_Specific(Op1), m_Value(C)), m_Value(A))))
2681     return BinaryOperator::CreateOr(Op1, Builder.CreateAnd(A, C));
2682 
2683   if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder))
2684     return DeMorgan;
2685 
2686   // Canonicalize xor to the RHS.
2687   bool SwappedForXor = false;
2688   if (match(Op0, m_Xor(m_Value(), m_Value()))) {
2689     std::swap(Op0, Op1);
2690     SwappedForXor = true;
2691   }
2692 
2693   // A | ( A ^ B) -> A |  B
2694   // A | (~A ^ B) -> A | ~B
2695   // (A & B) | (A ^ B)
2696   if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2697     if (Op0 == A || Op0 == B)
2698       return BinaryOperator::CreateOr(A, B);
2699 
2700     if (match(Op0, m_And(m_Specific(A), m_Specific(B))) ||
2701         match(Op0, m_And(m_Specific(B), m_Specific(A))))
2702       return BinaryOperator::CreateOr(A, B);
2703 
2704     if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) {
2705       Value *Not = Builder.CreateNot(B, B->getName() + ".not");
2706       return BinaryOperator::CreateOr(Not, Op0);
2707     }
2708     if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) {
2709       Value *Not = Builder.CreateNot(A, A->getName() + ".not");
2710       return BinaryOperator::CreateOr(Not, Op0);
2711     }
2712   }
2713 
2714   // A | ~(A | B) -> A | ~B
2715   // A | ~(A ^ B) -> A | ~B
2716   if (match(Op1, m_Not(m_Value(A))))
2717     if (BinaryOperator *B = dyn_cast<BinaryOperator>(A))
2718       if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) &&
2719           Op1->hasOneUse() && (B->getOpcode() == Instruction::Or ||
2720                                B->getOpcode() == Instruction::Xor)) {
2721         Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) :
2722                                                  B->getOperand(0);
2723         Value *Not = Builder.CreateNot(NotOp, NotOp->getName() + ".not");
2724         return BinaryOperator::CreateOr(Not, Op0);
2725       }
2726 
2727   if (SwappedForXor)
2728     std::swap(Op0, Op1);
2729 
2730   {
2731     ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
2732     ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
2733     if (LHS && RHS)
2734       if (Value *Res = foldOrOfICmps(LHS, RHS, I))
2735         return replaceInstUsesWith(I, Res);
2736 
2737     // TODO: Make this recursive; it's a little tricky because an arbitrary
2738     // number of 'or' instructions might have to be created.
2739     Value *X, *Y;
2740     if (LHS && match(Op1, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2741       if (auto *Cmp = dyn_cast<ICmpInst>(X))
2742         if (Value *Res = foldOrOfICmps(LHS, Cmp, I))
2743           return replaceInstUsesWith(I, Builder.CreateOr(Res, Y));
2744       if (auto *Cmp = dyn_cast<ICmpInst>(Y))
2745         if (Value *Res = foldOrOfICmps(LHS, Cmp, I))
2746           return replaceInstUsesWith(I, Builder.CreateOr(Res, X));
2747     }
2748     if (RHS && match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2749       if (auto *Cmp = dyn_cast<ICmpInst>(X))
2750         if (Value *Res = foldOrOfICmps(Cmp, RHS, I))
2751           return replaceInstUsesWith(I, Builder.CreateOr(Res, Y));
2752       if (auto *Cmp = dyn_cast<ICmpInst>(Y))
2753         if (Value *Res = foldOrOfICmps(Cmp, RHS, I))
2754           return replaceInstUsesWith(I, Builder.CreateOr(Res, X));
2755     }
2756   }
2757 
2758   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
2759     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
2760       if (Value *Res = foldLogicOfFCmps(LHS, RHS, false))
2761         return replaceInstUsesWith(I, Res);
2762 
2763   if (Instruction *FoldedFCmps = reassociateFCmps(I, Builder))
2764     return FoldedFCmps;
2765 
2766   if (Instruction *CastedOr = foldCastedBitwiseLogic(I))
2767     return CastedOr;
2768 
2769   // or(sext(A), B) / or(B, sext(A)) --> A ? -1 : B, where A is i1 or <N x i1>.
2770   if (match(Op0, m_OneUse(m_SExt(m_Value(A)))) &&
2771       A->getType()->isIntOrIntVectorTy(1))
2772     return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op1);
2773   if (match(Op1, m_OneUse(m_SExt(m_Value(A)))) &&
2774       A->getType()->isIntOrIntVectorTy(1))
2775     return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op0);
2776 
2777   // Note: If we've gotten to the point of visiting the outer OR, then the
2778   // inner one couldn't be simplified.  If it was a constant, then it won't
2779   // be simplified by a later pass either, so we try swapping the inner/outer
2780   // ORs in the hopes that we'll be able to simplify it this way.
2781   // (X|C) | V --> (X|V) | C
2782   ConstantInt *CI;
2783   if (Op0->hasOneUse() && !match(Op1, m_ConstantInt()) &&
2784       match(Op0, m_Or(m_Value(A), m_ConstantInt(CI)))) {
2785     Value *Inner = Builder.CreateOr(A, Op1);
2786     Inner->takeName(Op0);
2787     return BinaryOperator::CreateOr(Inner, CI);
2788   }
2789 
2790   // Change (or (bool?A:B),(bool?C:D)) --> (bool?(or A,C):(or B,D))
2791   // Since this OR statement hasn't been optimized further yet, we hope
2792   // that this transformation will allow the new ORs to be optimized.
2793   {
2794     Value *X = nullptr, *Y = nullptr;
2795     if (Op0->hasOneUse() && Op1->hasOneUse() &&
2796         match(Op0, m_Select(m_Value(X), m_Value(A), m_Value(B))) &&
2797         match(Op1, m_Select(m_Value(Y), m_Value(C), m_Value(D))) && X == Y) {
2798       Value *orTrue = Builder.CreateOr(A, C);
2799       Value *orFalse = Builder.CreateOr(B, D);
2800       return SelectInst::Create(X, orTrue, orFalse);
2801     }
2802   }
2803 
2804   // or(ashr(subNSW(Y, X), ScalarSizeInBits(Y) - 1), X)  --> X s> Y ? -1 : X.
2805   {
2806     Value *X, *Y;
2807     Type *Ty = I.getType();
2808     if (match(&I, m_c_Or(m_OneUse(m_AShr(
2809                              m_NSWSub(m_Value(Y), m_Value(X)),
2810                              m_SpecificInt(Ty->getScalarSizeInBits() - 1))),
2811                          m_Deferred(X)))) {
2812       Value *NewICmpInst = Builder.CreateICmpSGT(X, Y);
2813       Value *AllOnes = ConstantInt::getAllOnesValue(Ty);
2814       return SelectInst::Create(NewICmpInst, AllOnes, X);
2815     }
2816   }
2817 
2818   if (Instruction *V =
2819           canonicalizeCondSignextOfHighBitExtractToSignextHighBitExtract(I))
2820     return V;
2821 
2822   CmpInst::Predicate Pred;
2823   Value *Mul, *Ov, *MulIsNotZero, *UMulWithOv;
2824   // Check if the OR weakens the overflow condition for umul.with.overflow by
2825   // treating any non-zero result as overflow. In that case, we overflow if both
2826   // umul.with.overflow operands are != 0, as in that case the result can only
2827   // be 0, iff the multiplication overflows.
2828   if (match(&I,
2829             m_c_Or(m_CombineAnd(m_ExtractValue<1>(m_Value(UMulWithOv)),
2830                                 m_Value(Ov)),
2831                    m_CombineAnd(m_ICmp(Pred,
2832                                        m_CombineAnd(m_ExtractValue<0>(
2833                                                         m_Deferred(UMulWithOv)),
2834                                                     m_Value(Mul)),
2835                                        m_ZeroInt()),
2836                                 m_Value(MulIsNotZero)))) &&
2837       (Ov->hasOneUse() || (MulIsNotZero->hasOneUse() && Mul->hasOneUse())) &&
2838       Pred == CmpInst::ICMP_NE) {
2839     Value *A, *B;
2840     if (match(UMulWithOv, m_Intrinsic<Intrinsic::umul_with_overflow>(
2841                               m_Value(A), m_Value(B)))) {
2842       Value *NotNullA = Builder.CreateIsNotNull(A);
2843       Value *NotNullB = Builder.CreateIsNotNull(B);
2844       return BinaryOperator::CreateAnd(NotNullA, NotNullB);
2845     }
2846   }
2847 
2848   return nullptr;
2849 }
2850 
2851 /// A ^ B can be specified using other logic ops in a variety of patterns. We
2852 /// can fold these early and efficiently by morphing an existing instruction.
2853 static Instruction *foldXorToXor(BinaryOperator &I,
2854                                  InstCombiner::BuilderTy &Builder) {
2855   assert(I.getOpcode() == Instruction::Xor);
2856   Value *Op0 = I.getOperand(0);
2857   Value *Op1 = I.getOperand(1);
2858   Value *A, *B;
2859 
2860   // There are 4 commuted variants for each of the basic patterns.
2861 
2862   // (A & B) ^ (A | B) -> A ^ B
2863   // (A & B) ^ (B | A) -> A ^ B
2864   // (A | B) ^ (A & B) -> A ^ B
2865   // (A | B) ^ (B & A) -> A ^ B
2866   if (match(&I, m_c_Xor(m_And(m_Value(A), m_Value(B)),
2867                         m_c_Or(m_Deferred(A), m_Deferred(B)))))
2868     return BinaryOperator::CreateXor(A, B);
2869 
2870   // (A | ~B) ^ (~A | B) -> A ^ B
2871   // (~B | A) ^ (~A | B) -> A ^ B
2872   // (~A | B) ^ (A | ~B) -> A ^ B
2873   // (B | ~A) ^ (A | ~B) -> A ^ B
2874   if (match(&I, m_Xor(m_c_Or(m_Value(A), m_Not(m_Value(B))),
2875                       m_c_Or(m_Not(m_Deferred(A)), m_Deferred(B)))))
2876     return BinaryOperator::CreateXor(A, B);
2877 
2878   // (A & ~B) ^ (~A & B) -> A ^ B
2879   // (~B & A) ^ (~A & B) -> A ^ B
2880   // (~A & B) ^ (A & ~B) -> A ^ B
2881   // (B & ~A) ^ (A & ~B) -> A ^ B
2882   if (match(&I, m_Xor(m_c_And(m_Value(A), m_Not(m_Value(B))),
2883                       m_c_And(m_Not(m_Deferred(A)), m_Deferred(B)))))
2884     return BinaryOperator::CreateXor(A, B);
2885 
2886   // For the remaining cases we need to get rid of one of the operands.
2887   if (!Op0->hasOneUse() && !Op1->hasOneUse())
2888     return nullptr;
2889 
2890   // (A | B) ^ ~(A & B) -> ~(A ^ B)
2891   // (A | B) ^ ~(B & A) -> ~(A ^ B)
2892   // (A & B) ^ ~(A | B) -> ~(A ^ B)
2893   // (A & B) ^ ~(B | A) -> ~(A ^ B)
2894   // Complexity sorting ensures the not will be on the right side.
2895   if ((match(Op0, m_Or(m_Value(A), m_Value(B))) &&
2896        match(Op1, m_Not(m_c_And(m_Specific(A), m_Specific(B))))) ||
2897       (match(Op0, m_And(m_Value(A), m_Value(B))) &&
2898        match(Op1, m_Not(m_c_Or(m_Specific(A), m_Specific(B))))))
2899     return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
2900 
2901   return nullptr;
2902 }
2903 
2904 Value *InstCombinerImpl::foldXorOfICmps(ICmpInst *LHS, ICmpInst *RHS,
2905                                         BinaryOperator &I) {
2906   assert(I.getOpcode() == Instruction::Xor && I.getOperand(0) == LHS &&
2907          I.getOperand(1) == RHS && "Should be 'xor' with these operands");
2908 
2909   if (predicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
2910     if (LHS->getOperand(0) == RHS->getOperand(1) &&
2911         LHS->getOperand(1) == RHS->getOperand(0))
2912       LHS->swapOperands();
2913     if (LHS->getOperand(0) == RHS->getOperand(0) &&
2914         LHS->getOperand(1) == RHS->getOperand(1)) {
2915       // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
2916       Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2917       unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
2918       bool IsSigned = LHS->isSigned() || RHS->isSigned();
2919       return getNewICmpValue(Code, IsSigned, Op0, Op1, Builder);
2920     }
2921   }
2922 
2923   // TODO: This can be generalized to compares of non-signbits using
2924   // decomposeBitTestICmp(). It could be enhanced more by using (something like)
2925   // foldLogOpOfMaskedICmps().
2926   ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
2927   Value *LHS0 = LHS->getOperand(0), *LHS1 = LHS->getOperand(1);
2928   Value *RHS0 = RHS->getOperand(0), *RHS1 = RHS->getOperand(1);
2929   if ((LHS->hasOneUse() || RHS->hasOneUse()) &&
2930       LHS0->getType() == RHS0->getType() &&
2931       LHS0->getType()->isIntOrIntVectorTy()) {
2932     // (X > -1) ^ (Y > -1) --> (X ^ Y) < 0
2933     // (X <  0) ^ (Y <  0) --> (X ^ Y) < 0
2934     if ((PredL == CmpInst::ICMP_SGT && match(LHS1, m_AllOnes()) &&
2935          PredR == CmpInst::ICMP_SGT && match(RHS1, m_AllOnes())) ||
2936         (PredL == CmpInst::ICMP_SLT && match(LHS1, m_Zero()) &&
2937          PredR == CmpInst::ICMP_SLT && match(RHS1, m_Zero()))) {
2938       Value *Zero = ConstantInt::getNullValue(LHS0->getType());
2939       return Builder.CreateICmpSLT(Builder.CreateXor(LHS0, RHS0), Zero);
2940     }
2941     // (X > -1) ^ (Y <  0) --> (X ^ Y) > -1
2942     // (X <  0) ^ (Y > -1) --> (X ^ Y) > -1
2943     if ((PredL == CmpInst::ICMP_SGT && match(LHS1, m_AllOnes()) &&
2944          PredR == CmpInst::ICMP_SLT && match(RHS1, m_Zero())) ||
2945         (PredL == CmpInst::ICMP_SLT && match(LHS1, m_Zero()) &&
2946          PredR == CmpInst::ICMP_SGT && match(RHS1, m_AllOnes()))) {
2947       Value *MinusOne = ConstantInt::getAllOnesValue(LHS0->getType());
2948       return Builder.CreateICmpSGT(Builder.CreateXor(LHS0, RHS0), MinusOne);
2949     }
2950   }
2951 
2952   // Instead of trying to imitate the folds for and/or, decompose this 'xor'
2953   // into those logic ops. That is, try to turn this into an and-of-icmps
2954   // because we have many folds for that pattern.
2955   //
2956   // This is based on a truth table definition of xor:
2957   // X ^ Y --> (X | Y) & !(X & Y)
2958   if (Value *OrICmp = SimplifyBinOp(Instruction::Or, LHS, RHS, SQ)) {
2959     // TODO: If OrICmp is true, then the definition of xor simplifies to !(X&Y).
2960     // TODO: If OrICmp is false, the whole thing is false (InstSimplify?).
2961     if (Value *AndICmp = SimplifyBinOp(Instruction::And, LHS, RHS, SQ)) {
2962       // TODO: Independently handle cases where the 'and' side is a constant.
2963       ICmpInst *X = nullptr, *Y = nullptr;
2964       if (OrICmp == LHS && AndICmp == RHS) {
2965         // (LHS | RHS) & !(LHS & RHS) --> LHS & !RHS  --> X & !Y
2966         X = LHS;
2967         Y = RHS;
2968       }
2969       if (OrICmp == RHS && AndICmp == LHS) {
2970         // !(LHS & RHS) & (LHS | RHS) --> !LHS & RHS  --> !Y & X
2971         X = RHS;
2972         Y = LHS;
2973       }
2974       if (X && Y && (Y->hasOneUse() || canFreelyInvertAllUsersOf(Y, &I))) {
2975         // Invert the predicate of 'Y', thus inverting its output.
2976         Y->setPredicate(Y->getInversePredicate());
2977         // So, are there other uses of Y?
2978         if (!Y->hasOneUse()) {
2979           // We need to adapt other uses of Y though. Get a value that matches
2980           // the original value of Y before inversion. While this increases
2981           // immediate instruction count, we have just ensured that all the
2982           // users are freely-invertible, so that 'not' *will* get folded away.
2983           BuilderTy::InsertPointGuard Guard(Builder);
2984           // Set insertion point to right after the Y.
2985           Builder.SetInsertPoint(Y->getParent(), ++(Y->getIterator()));
2986           Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
2987           // Replace all uses of Y (excluding the one in NotY!) with NotY.
2988           Worklist.pushUsersToWorkList(*Y);
2989           Y->replaceUsesWithIf(NotY,
2990                                [NotY](Use &U) { return U.getUser() != NotY; });
2991         }
2992         // All done.
2993         return Builder.CreateAnd(LHS, RHS);
2994       }
2995     }
2996   }
2997 
2998   return nullptr;
2999 }
3000 
3001 /// If we have a masked merge, in the canonical form of:
3002 /// (assuming that A only has one use.)
3003 ///   |        A  |  |B|
3004 ///   ((x ^ y) & M) ^ y
3005 ///    |  D  |
3006 /// * If M is inverted:
3007 ///      |  D  |
3008 ///     ((x ^ y) & ~M) ^ y
3009 ///   We can canonicalize by swapping the final xor operand
3010 ///   to eliminate the 'not' of the mask.
3011 ///     ((x ^ y) & M) ^ x
3012 /// * If M is a constant, and D has one use, we transform to 'and' / 'or' ops
3013 ///   because that shortens the dependency chain and improves analysis:
3014 ///     (x & M) | (y & ~M)
3015 static Instruction *visitMaskedMerge(BinaryOperator &I,
3016                                      InstCombiner::BuilderTy &Builder) {
3017   Value *B, *X, *D;
3018   Value *M;
3019   if (!match(&I, m_c_Xor(m_Value(B),
3020                          m_OneUse(m_c_And(
3021                              m_CombineAnd(m_c_Xor(m_Deferred(B), m_Value(X)),
3022                                           m_Value(D)),
3023                              m_Value(M))))))
3024     return nullptr;
3025 
3026   Value *NotM;
3027   if (match(M, m_Not(m_Value(NotM)))) {
3028     // De-invert the mask and swap the value in B part.
3029     Value *NewA = Builder.CreateAnd(D, NotM);
3030     return BinaryOperator::CreateXor(NewA, X);
3031   }
3032 
3033   Constant *C;
3034   if (D->hasOneUse() && match(M, m_Constant(C))) {
3035     // Propagating undef is unsafe. Clamp undef elements to -1.
3036     Type *EltTy = C->getType()->getScalarType();
3037     C = Constant::replaceUndefsWith(C, ConstantInt::getAllOnesValue(EltTy));
3038     // Unfold.
3039     Value *LHS = Builder.CreateAnd(X, C);
3040     Value *NotC = Builder.CreateNot(C);
3041     Value *RHS = Builder.CreateAnd(B, NotC);
3042     return BinaryOperator::CreateOr(LHS, RHS);
3043   }
3044 
3045   return nullptr;
3046 }
3047 
3048 // Transform
3049 //   ~(x ^ y)
3050 // into:
3051 //   (~x) ^ y
3052 // or into
3053 //   x ^ (~y)
3054 static Instruction *sinkNotIntoXor(BinaryOperator &I,
3055                                    InstCombiner::BuilderTy &Builder) {
3056   Value *X, *Y;
3057   // FIXME: one-use check is not needed in general, but currently we are unable
3058   // to fold 'not' into 'icmp', if that 'icmp' has multiple uses. (D35182)
3059   if (!match(&I, m_Not(m_OneUse(m_Xor(m_Value(X), m_Value(Y))))))
3060     return nullptr;
3061 
3062   // We only want to do the transform if it is free to do.
3063   if (InstCombiner::isFreeToInvert(X, X->hasOneUse())) {
3064     // Ok, good.
3065   } else if (InstCombiner::isFreeToInvert(Y, Y->hasOneUse())) {
3066     std::swap(X, Y);
3067   } else
3068     return nullptr;
3069 
3070   Value *NotX = Builder.CreateNot(X, X->getName() + ".not");
3071   return BinaryOperator::CreateXor(NotX, Y, I.getName() + ".demorgan");
3072 }
3073 
3074 // FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
3075 // here. We should standardize that construct where it is needed or choose some
3076 // other way to ensure that commutated variants of patterns are not missed.
3077 Instruction *InstCombinerImpl::visitXor(BinaryOperator &I) {
3078   if (Value *V = SimplifyXorInst(I.getOperand(0), I.getOperand(1),
3079                                  SQ.getWithInstruction(&I)))
3080     return replaceInstUsesWith(I, V);
3081 
3082   if (SimplifyAssociativeOrCommutative(I))
3083     return &I;
3084 
3085   if (Instruction *X = foldVectorBinop(I))
3086     return X;
3087 
3088   if (Instruction *NewXor = foldXorToXor(I, Builder))
3089     return NewXor;
3090 
3091   // (A&B)^(A&C) -> A&(B^C) etc
3092   if (Value *V = SimplifyUsingDistributiveLaws(I))
3093     return replaceInstUsesWith(I, V);
3094 
3095   // See if we can simplify any instructions used by the instruction whose sole
3096   // purpose is to compute bits we don't care about.
3097   if (SimplifyDemandedInstructionBits(I))
3098     return &I;
3099 
3100   if (Value *V = SimplifyBSwap(I, Builder))
3101     return replaceInstUsesWith(I, V);
3102 
3103   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3104   Type *Ty = I.getType();
3105 
3106   // Fold (X & M) ^ (Y & ~M) -> (X & M) | (Y & ~M)
3107   // This it a special case in haveNoCommonBitsSet, but the computeKnownBits
3108   // calls in there are unnecessary as SimplifyDemandedInstructionBits should
3109   // have already taken care of those cases.
3110   Value *M;
3111   if (match(&I, m_c_Xor(m_c_And(m_Not(m_Value(M)), m_Value()),
3112                         m_c_And(m_Deferred(M), m_Value()))))
3113     return BinaryOperator::CreateOr(Op0, Op1);
3114 
3115   // Apply DeMorgan's Law for 'nand' / 'nor' logic with an inverted operand.
3116   Value *X, *Y;
3117 
3118   // We must eliminate the and/or (one-use) for these transforms to not increase
3119   // the instruction count.
3120   // ~(~X & Y) --> (X | ~Y)
3121   // ~(Y & ~X) --> (X | ~Y)
3122   if (match(&I, m_Not(m_OneUse(m_c_And(m_Not(m_Value(X)), m_Value(Y)))))) {
3123     Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
3124     return BinaryOperator::CreateOr(X, NotY);
3125   }
3126   // ~(~X | Y) --> (X & ~Y)
3127   // ~(Y | ~X) --> (X & ~Y)
3128   if (match(&I, m_Not(m_OneUse(m_c_Or(m_Not(m_Value(X)), m_Value(Y)))))) {
3129     Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
3130     return BinaryOperator::CreateAnd(X, NotY);
3131   }
3132 
3133   if (Instruction *Xor = visitMaskedMerge(I, Builder))
3134     return Xor;
3135 
3136   // Is this a 'not' (~) fed by a binary operator?
3137   BinaryOperator *NotVal;
3138   if (match(&I, m_Not(m_BinOp(NotVal)))) {
3139     if (NotVal->getOpcode() == Instruction::And ||
3140         NotVal->getOpcode() == Instruction::Or) {
3141       // Apply DeMorgan's Law when inverts are free:
3142       // ~(X & Y) --> (~X | ~Y)
3143       // ~(X | Y) --> (~X & ~Y)
3144       if (isFreeToInvert(NotVal->getOperand(0),
3145                          NotVal->getOperand(0)->hasOneUse()) &&
3146           isFreeToInvert(NotVal->getOperand(1),
3147                          NotVal->getOperand(1)->hasOneUse())) {
3148         Value *NotX = Builder.CreateNot(NotVal->getOperand(0), "notlhs");
3149         Value *NotY = Builder.CreateNot(NotVal->getOperand(1), "notrhs");
3150         if (NotVal->getOpcode() == Instruction::And)
3151           return BinaryOperator::CreateOr(NotX, NotY);
3152         return BinaryOperator::CreateAnd(NotX, NotY);
3153       }
3154     }
3155 
3156     // ~(X - Y) --> ~X + Y
3157     if (match(NotVal, m_Sub(m_Value(X), m_Value(Y))))
3158       if (isa<Constant>(X) || NotVal->hasOneUse())
3159         return BinaryOperator::CreateAdd(Builder.CreateNot(X), Y);
3160 
3161     // ~(~X >>s Y) --> (X >>s Y)
3162     if (match(NotVal, m_AShr(m_Not(m_Value(X)), m_Value(Y))))
3163       return BinaryOperator::CreateAShr(X, Y);
3164 
3165     // If we are inverting a right-shifted constant, we may be able to eliminate
3166     // the 'not' by inverting the constant and using the opposite shift type.
3167     // Canonicalization rules ensure that only a negative constant uses 'ashr',
3168     // but we must check that in case that transform has not fired yet.
3169 
3170     // ~(C >>s Y) --> ~C >>u Y (when inverting the replicated sign bits)
3171     Constant *C;
3172     if (match(NotVal, m_AShr(m_Constant(C), m_Value(Y))) &&
3173         match(C, m_Negative())) {
3174       // We matched a negative constant, so propagating undef is unsafe.
3175       // Clamp undef elements to -1.
3176       Type *EltTy = Ty->getScalarType();
3177       C = Constant::replaceUndefsWith(C, ConstantInt::getAllOnesValue(EltTy));
3178       return BinaryOperator::CreateLShr(ConstantExpr::getNot(C), Y);
3179     }
3180 
3181     // ~(C >>u Y) --> ~C >>s Y (when inverting the replicated sign bits)
3182     if (match(NotVal, m_LShr(m_Constant(C), m_Value(Y))) &&
3183         match(C, m_NonNegative())) {
3184       // We matched a non-negative constant, so propagating undef is unsafe.
3185       // Clamp undef elements to 0.
3186       Type *EltTy = Ty->getScalarType();
3187       C = Constant::replaceUndefsWith(C, ConstantInt::getNullValue(EltTy));
3188       return BinaryOperator::CreateAShr(ConstantExpr::getNot(C), Y);
3189     }
3190 
3191     // ~(X + C) --> -(C + 1) - X
3192     if (match(Op0, m_Add(m_Value(X), m_Constant(C))))
3193       return BinaryOperator::CreateSub(ConstantExpr::getNeg(AddOne(C)), X);
3194 
3195     // ~(~X + Y) --> X - Y
3196     if (match(NotVal, m_c_Add(m_Not(m_Value(X)), m_Value(Y))))
3197       return BinaryOperator::CreateWithCopiedFlags(Instruction::Sub, X, Y,
3198                                                    NotVal);
3199   }
3200 
3201   // Use DeMorgan and reassociation to eliminate a 'not' op.
3202   Constant *C1;
3203   if (match(Op1, m_Constant(C1))) {
3204     Constant *C2;
3205     if (match(Op0, m_OneUse(m_Or(m_Not(m_Value(X)), m_Constant(C2))))) {
3206       // (~X | C2) ^ C1 --> ((X & ~C2) ^ -1) ^ C1 --> (X & ~C2) ^ ~C1
3207       Value *And = Builder.CreateAnd(X, ConstantExpr::getNot(C2));
3208       return BinaryOperator::CreateXor(And, ConstantExpr::getNot(C1));
3209     }
3210     if (match(Op0, m_OneUse(m_And(m_Not(m_Value(X)), m_Constant(C2))))) {
3211       // (~X & C2) ^ C1 --> ((X | ~C2) ^ -1) ^ C1 --> (X | ~C2) ^ ~C1
3212       Value *Or = Builder.CreateOr(X, ConstantExpr::getNot(C2));
3213       return BinaryOperator::CreateXor(Or, ConstantExpr::getNot(C1));
3214     }
3215   }
3216 
3217   // not (cmp A, B) = !cmp A, B
3218   CmpInst::Predicate Pred;
3219   if (match(&I, m_Not(m_OneUse(m_Cmp(Pred, m_Value(), m_Value()))))) {
3220     cast<CmpInst>(Op0)->setPredicate(CmpInst::getInversePredicate(Pred));
3221     return replaceInstUsesWith(I, Op0);
3222   }
3223 
3224   {
3225     const APInt *RHSC;
3226     if (match(Op1, m_APInt(RHSC))) {
3227       Value *X;
3228       const APInt *C;
3229       // (C - X) ^ signmaskC --> (C + signmaskC) - X
3230       if (RHSC->isSignMask() && match(Op0, m_Sub(m_APInt(C), m_Value(X))))
3231         return BinaryOperator::CreateSub(ConstantInt::get(Ty, *C + *RHSC), X);
3232 
3233       // (X + C) ^ signmaskC --> X + (C + signmaskC)
3234       if (RHSC->isSignMask() && match(Op0, m_Add(m_Value(X), m_APInt(C))))
3235         return BinaryOperator::CreateAdd(X, ConstantInt::get(Ty, *C + *RHSC));
3236 
3237       // (X | C) ^ RHSC --> X ^ (C ^ RHSC) iff X & C == 0
3238       if (match(Op0, m_Or(m_Value(X), m_APInt(C))) &&
3239           MaskedValueIsZero(X, *C, 0, &I))
3240         return BinaryOperator::CreateXor(X, ConstantInt::get(Ty, *C ^ *RHSC));
3241 
3242       // If RHSC is inverting the remaining bits of shifted X,
3243       // canonicalize to a 'not' before the shift to help SCEV and codegen:
3244       // (X << C) ^ RHSC --> ~X << C
3245       if (match(Op0, m_OneUse(m_Shl(m_Value(X), m_APInt(C)))) &&
3246           *RHSC == APInt::getAllOnesValue(Ty->getScalarSizeInBits()).shl(*C)) {
3247         Value *NotX = Builder.CreateNot(X);
3248         return BinaryOperator::CreateShl(NotX, ConstantInt::get(Ty, *C));
3249       }
3250       // (X >>u C) ^ RHSC --> ~X >>u C
3251       if (match(Op0, m_OneUse(m_LShr(m_Value(X), m_APInt(C)))) &&
3252           *RHSC == APInt::getAllOnesValue(Ty->getScalarSizeInBits()).lshr(*C)) {
3253         Value *NotX = Builder.CreateNot(X);
3254         return BinaryOperator::CreateLShr(NotX, ConstantInt::get(Ty, *C));
3255       }
3256       // TODO: We could handle 'ashr' here as well. That would be matching
3257       //       a 'not' op and moving it before the shift. Doing that requires
3258       //       preventing the inverse fold in canShiftBinOpWithConstantRHS().
3259     }
3260   }
3261 
3262   // FIXME: This should not be limited to scalar (pull into APInt match above).
3263   {
3264     Value *X;
3265     ConstantInt *C1, *C2, *C3;
3266     // ((X^C1) >> C2) ^ C3 -> (X>>C2) ^ ((C1>>C2)^C3)
3267     if (match(Op1, m_ConstantInt(C3)) &&
3268         match(Op0, m_LShr(m_Xor(m_Value(X), m_ConstantInt(C1)),
3269                           m_ConstantInt(C2))) &&
3270         Op0->hasOneUse()) {
3271       // fold (C1 >> C2) ^ C3
3272       APInt FoldConst = C1->getValue().lshr(C2->getValue());
3273       FoldConst ^= C3->getValue();
3274       // Prepare the two operands.
3275       auto *Opnd0 = cast<Instruction>(Builder.CreateLShr(X, C2));
3276       Opnd0->takeName(cast<Instruction>(Op0));
3277       Opnd0->setDebugLoc(I.getDebugLoc());
3278       return BinaryOperator::CreateXor(Opnd0, ConstantInt::get(Ty, FoldConst));
3279     }
3280   }
3281 
3282   if (Instruction *FoldedLogic = foldBinOpIntoSelectOrPhi(I))
3283     return FoldedLogic;
3284 
3285   // Y ^ (X | Y) --> X & ~Y
3286   // Y ^ (Y | X) --> X & ~Y
3287   if (match(Op1, m_OneUse(m_c_Or(m_Value(X), m_Specific(Op0)))))
3288     return BinaryOperator::CreateAnd(X, Builder.CreateNot(Op0));
3289   // (X | Y) ^ Y --> X & ~Y
3290   // (Y | X) ^ Y --> X & ~Y
3291   if (match(Op0, m_OneUse(m_c_Or(m_Value(X), m_Specific(Op1)))))
3292     return BinaryOperator::CreateAnd(X, Builder.CreateNot(Op1));
3293 
3294   // Y ^ (X & Y) --> ~X & Y
3295   // Y ^ (Y & X) --> ~X & Y
3296   if (match(Op1, m_OneUse(m_c_And(m_Value(X), m_Specific(Op0)))))
3297     return BinaryOperator::CreateAnd(Op0, Builder.CreateNot(X));
3298   // (X & Y) ^ Y --> ~X & Y
3299   // (Y & X) ^ Y --> ~X & Y
3300   // Canonical form is (X & C) ^ C; don't touch that.
3301   // TODO: A 'not' op is better for analysis and codegen, but demanded bits must
3302   //       be fixed to prefer that (otherwise we get infinite looping).
3303   if (!match(Op1, m_Constant()) &&
3304       match(Op0, m_OneUse(m_c_And(m_Value(X), m_Specific(Op1)))))
3305     return BinaryOperator::CreateAnd(Op1, Builder.CreateNot(X));
3306 
3307   Value *A, *B, *C;
3308   // (A ^ B) ^ (A | C) --> (~A & C) ^ B -- There are 4 commuted variants.
3309   if (match(&I, m_c_Xor(m_OneUse(m_Xor(m_Value(A), m_Value(B))),
3310                         m_OneUse(m_c_Or(m_Deferred(A), m_Value(C))))))
3311       return BinaryOperator::CreateXor(
3312           Builder.CreateAnd(Builder.CreateNot(A), C), B);
3313 
3314   // (A ^ B) ^ (B | C) --> (~B & C) ^ A -- There are 4 commuted variants.
3315   if (match(&I, m_c_Xor(m_OneUse(m_Xor(m_Value(A), m_Value(B))),
3316                         m_OneUse(m_c_Or(m_Deferred(B), m_Value(C))))))
3317       return BinaryOperator::CreateXor(
3318           Builder.CreateAnd(Builder.CreateNot(B), C), A);
3319 
3320   // (A & B) ^ (A ^ B) -> (A | B)
3321   if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
3322       match(Op1, m_c_Xor(m_Specific(A), m_Specific(B))))
3323     return BinaryOperator::CreateOr(A, B);
3324   // (A ^ B) ^ (A & B) -> (A | B)
3325   if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
3326       match(Op1, m_c_And(m_Specific(A), m_Specific(B))))
3327     return BinaryOperator::CreateOr(A, B);
3328 
3329   // (A & ~B) ^ ~A -> ~(A & B)
3330   // (~B & A) ^ ~A -> ~(A & B)
3331   if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
3332       match(Op1, m_Not(m_Specific(A))))
3333     return BinaryOperator::CreateNot(Builder.CreateAnd(A, B));
3334 
3335   // (~A & B) ^ A --> A | B -- There are 4 commuted variants.
3336   if (match(&I, m_c_Xor(m_c_And(m_Not(m_Value(A)), m_Value(B)), m_Deferred(A))))
3337     return BinaryOperator::CreateOr(A, B);
3338 
3339   // (A | B) ^ (A | C) --> (B ^ C) & ~A -- There are 4 commuted variants.
3340   // TODO: Loosen one-use restriction if common operand is a constant.
3341   Value *D;
3342   if (match(Op0, m_OneUse(m_Or(m_Value(A), m_Value(B)))) &&
3343       match(Op1, m_OneUse(m_Or(m_Value(C), m_Value(D))))) {
3344     if (B == C || B == D)
3345       std::swap(A, B);
3346     if (A == C)
3347       std::swap(C, D);
3348     if (A == D) {
3349       Value *NotA = Builder.CreateNot(A);
3350       return BinaryOperator::CreateAnd(Builder.CreateXor(B, C), NotA);
3351     }
3352   }
3353 
3354   if (auto *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
3355     if (auto *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
3356       if (Value *V = foldXorOfICmps(LHS, RHS, I))
3357         return replaceInstUsesWith(I, V);
3358 
3359   if (Instruction *CastedXor = foldCastedBitwiseLogic(I))
3360     return CastedXor;
3361 
3362   // Canonicalize a shifty way to code absolute value to the common pattern.
3363   // There are 4 potential commuted variants. Move the 'ashr' candidate to Op1.
3364   // We're relying on the fact that we only do this transform when the shift has
3365   // exactly 2 uses and the add has exactly 1 use (otherwise, we might increase
3366   // instructions).
3367   if (Op0->hasNUses(2))
3368     std::swap(Op0, Op1);
3369 
3370   const APInt *ShAmt;
3371   if (match(Op1, m_AShr(m_Value(A), m_APInt(ShAmt))) &&
3372       Op1->hasNUses(2) && *ShAmt == Ty->getScalarSizeInBits() - 1 &&
3373       match(Op0, m_OneUse(m_c_Add(m_Specific(A), m_Specific(Op1))))) {
3374     // B = ashr i32 A, 31 ; smear the sign bit
3375     // xor (add A, B), B  ; add -1 and flip bits if negative
3376     // --> (A < 0) ? -A : A
3377     Value *Cmp = Builder.CreateICmpSLT(A, ConstantInt::getNullValue(Ty));
3378     // Copy the nuw/nsw flags from the add to the negate.
3379     auto *Add = cast<BinaryOperator>(Op0);
3380     Value *Neg = Builder.CreateNeg(A, "", Add->hasNoUnsignedWrap(),
3381                                    Add->hasNoSignedWrap());
3382     return SelectInst::Create(Cmp, Neg, A);
3383   }
3384 
3385   // Eliminate a bitwise 'not' op of 'not' min/max by inverting the min/max:
3386   //
3387   //   %notx = xor i32 %x, -1
3388   //   %cmp1 = icmp sgt i32 %notx, %y
3389   //   %smax = select i1 %cmp1, i32 %notx, i32 %y
3390   //   %res = xor i32 %smax, -1
3391   // =>
3392   //   %noty = xor i32 %y, -1
3393   //   %cmp2 = icmp slt %x, %noty
3394   //   %res = select i1 %cmp2, i32 %x, i32 %noty
3395   //
3396   // Same is applicable for smin/umax/umin.
3397   if (match(Op1, m_AllOnes()) && Op0->hasOneUse()) {
3398     Value *LHS, *RHS;
3399     SelectPatternFlavor SPF = matchSelectPattern(Op0, LHS, RHS).Flavor;
3400     if (SelectPatternResult::isMinOrMax(SPF)) {
3401       // It's possible we get here before the not has been simplified, so make
3402       // sure the input to the not isn't freely invertible.
3403       if (match(LHS, m_Not(m_Value(X))) && !isFreeToInvert(X, X->hasOneUse())) {
3404         Value *NotY = Builder.CreateNot(RHS);
3405         return SelectInst::Create(
3406             Builder.CreateICmp(getInverseMinMaxPred(SPF), X, NotY), X, NotY);
3407       }
3408 
3409       // It's possible we get here before the not has been simplified, so make
3410       // sure the input to the not isn't freely invertible.
3411       if (match(RHS, m_Not(m_Value(Y))) && !isFreeToInvert(Y, Y->hasOneUse())) {
3412         Value *NotX = Builder.CreateNot(LHS);
3413         return SelectInst::Create(
3414             Builder.CreateICmp(getInverseMinMaxPred(SPF), NotX, Y), NotX, Y);
3415       }
3416 
3417       // If both sides are freely invertible, then we can get rid of the xor
3418       // completely.
3419       if (isFreeToInvert(LHS, !LHS->hasNUsesOrMore(3)) &&
3420           isFreeToInvert(RHS, !RHS->hasNUsesOrMore(3))) {
3421         Value *NotLHS = Builder.CreateNot(LHS);
3422         Value *NotRHS = Builder.CreateNot(RHS);
3423         return SelectInst::Create(
3424             Builder.CreateICmp(getInverseMinMaxPred(SPF), NotLHS, NotRHS),
3425             NotLHS, NotRHS);
3426       }
3427     }
3428 
3429     // Pull 'not' into operands of select if both operands are one-use compares.
3430     // Inverting the predicates eliminates the 'not' operation.
3431     // Example:
3432     //     not (select ?, (cmp TPred, ?, ?), (cmp FPred, ?, ?) -->
3433     //     select ?, (cmp InvTPred, ?, ?), (cmp InvFPred, ?, ?)
3434     // TODO: Canonicalize by hoisting 'not' into an arm of the select if only
3435     //       1 select operand is a cmp?
3436     if (auto *Sel = dyn_cast<SelectInst>(Op0)) {
3437       auto *CmpT = dyn_cast<CmpInst>(Sel->getTrueValue());
3438       auto *CmpF = dyn_cast<CmpInst>(Sel->getFalseValue());
3439       if (CmpT && CmpF && CmpT->hasOneUse() && CmpF->hasOneUse()) {
3440         CmpT->setPredicate(CmpT->getInversePredicate());
3441         CmpF->setPredicate(CmpF->getInversePredicate());
3442         return replaceInstUsesWith(I, Sel);
3443       }
3444     }
3445   }
3446 
3447   if (Instruction *NewXor = sinkNotIntoXor(I, Builder))
3448     return NewXor;
3449 
3450   return nullptr;
3451 }
3452