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