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