xref: /freebsd/contrib/llvm-project/llvm/lib/Transforms/InstCombine/InstCombineAndOrXor.cpp (revision f126890ac5386406dadf7c4cfa9566cbb56537c5)
1 //===- InstCombineAndOrXor.cpp --------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the visitAnd, visitOr, and visitXor functions.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "InstCombineInternal.h"
14 #include "llvm/Analysis/CmpInstAnalysis.h"
15 #include "llvm/Analysis/InstructionSimplify.h"
16 #include "llvm/IR/ConstantRange.h"
17 #include "llvm/IR/Intrinsics.h"
18 #include "llvm/IR/PatternMatch.h"
19 #include "llvm/Transforms/InstCombine/InstCombiner.h"
20 #include "llvm/Transforms/Utils/Local.h"
21 
22 using namespace llvm;
23 using namespace PatternMatch;
24 
25 #define DEBUG_TYPE "instcombine"
26 
27 /// This is the complement of getICmpCode, which turns an opcode and two
28 /// operands into either a constant true or false, or a brand new ICmp
29 /// instruction. The sign is passed in to determine which kind of predicate to
30 /// use in the new icmp instruction.
31 static Value *getNewICmpValue(unsigned Code, bool Sign, Value *LHS, Value *RHS,
32                               InstCombiner::BuilderTy &Builder) {
33   ICmpInst::Predicate NewPred;
34   if (Constant *TorF = getPredForICmpCode(Code, Sign, LHS->getType(), NewPred))
35     return TorF;
36   return Builder.CreateICmp(NewPred, LHS, RHS);
37 }
38 
39 /// This is the complement of getFCmpCode, which turns an opcode and two
40 /// operands into either a FCmp instruction, or a true/false constant.
41 static Value *getFCmpValue(unsigned Code, Value *LHS, Value *RHS,
42                            InstCombiner::BuilderTy &Builder) {
43   FCmpInst::Predicate NewPred;
44   if (Constant *TorF = getPredForFCmpCode(Code, LHS->getType(), NewPred))
45     return TorF;
46   return Builder.CreateFCmp(NewPred, LHS, RHS);
47 }
48 
49 /// Transform BITWISE_OP(BSWAP(A),BSWAP(B)) or
50 /// BITWISE_OP(BSWAP(A), Constant) to BSWAP(BITWISE_OP(A, B))
51 /// \param I Binary operator to transform.
52 /// \return Pointer to node that must replace the original binary operator, or
53 ///         null pointer if no transformation was made.
54 static Value *SimplifyBSwap(BinaryOperator &I,
55                             InstCombiner::BuilderTy &Builder) {
56   assert(I.isBitwiseLogicOp() && "Unexpected opcode for bswap simplifying");
57 
58   Value *OldLHS = I.getOperand(0);
59   Value *OldRHS = I.getOperand(1);
60 
61   Value *NewLHS;
62   if (!match(OldLHS, m_BSwap(m_Value(NewLHS))))
63     return nullptr;
64 
65   Value *NewRHS;
66   const APInt *C;
67 
68   if (match(OldRHS, m_BSwap(m_Value(NewRHS)))) {
69     // OP( BSWAP(x), BSWAP(y) ) -> BSWAP( OP(x, y) )
70     if (!OldLHS->hasOneUse() && !OldRHS->hasOneUse())
71       return nullptr;
72     // NewRHS initialized by the matcher.
73   } else if (match(OldRHS, m_APInt(C))) {
74     // OP( BSWAP(x), CONSTANT ) -> BSWAP( OP(x, BSWAP(CONSTANT) ) )
75     if (!OldLHS->hasOneUse())
76       return nullptr;
77     NewRHS = ConstantInt::get(I.getType(), C->byteSwap());
78   } else
79     return nullptr;
80 
81   Value *BinOp = Builder.CreateBinOp(I.getOpcode(), NewLHS, NewRHS);
82   Function *F = Intrinsic::getDeclaration(I.getModule(), Intrinsic::bswap,
83                                           I.getType());
84   return Builder.CreateCall(F, BinOp);
85 }
86 
87 /// Emit a computation of: (V >= Lo && V < Hi) if Inside is true, otherwise
88 /// (V < Lo || V >= Hi). This method expects that Lo < Hi. IsSigned indicates
89 /// whether to treat V, Lo, and Hi as signed or not.
90 Value *InstCombinerImpl::insertRangeTest(Value *V, const APInt &Lo,
91                                          const APInt &Hi, bool isSigned,
92                                          bool Inside) {
93   assert((isSigned ? Lo.slt(Hi) : Lo.ult(Hi)) &&
94          "Lo is not < Hi in range emission code!");
95 
96   Type *Ty = V->getType();
97 
98   // V >= Min && V <  Hi --> V <  Hi
99   // V <  Min || V >= Hi --> V >= Hi
100   ICmpInst::Predicate Pred = Inside ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_UGE;
101   if (isSigned ? Lo.isMinSignedValue() : Lo.isMinValue()) {
102     Pred = isSigned ? ICmpInst::getSignedPredicate(Pred) : Pred;
103     return Builder.CreateICmp(Pred, V, ConstantInt::get(Ty, Hi));
104   }
105 
106   // V >= Lo && V <  Hi --> V - Lo u<  Hi - Lo
107   // V <  Lo || V >= Hi --> V - Lo u>= Hi - Lo
108   Value *VMinusLo =
109       Builder.CreateSub(V, ConstantInt::get(Ty, Lo), V->getName() + ".off");
110   Constant *HiMinusLo = ConstantInt::get(Ty, Hi - Lo);
111   return Builder.CreateICmp(Pred, VMinusLo, HiMinusLo);
112 }
113 
114 /// Classify (icmp eq (A & B), C) and (icmp ne (A & B), C) as matching patterns
115 /// that can be simplified.
116 /// One of A and B is considered the mask. The other is the value. This is
117 /// described as the "AMask" or "BMask" part of the enum. If the enum contains
118 /// only "Mask", then both A and B can be considered masks. If A is the mask,
119 /// then it was proven that (A & C) == C. This is trivial if C == A or C == 0.
120 /// If both A and C are constants, this proof is also easy.
121 /// For the following explanations, we assume that A is the mask.
122 ///
123 /// "AllOnes" declares that the comparison is true only if (A & B) == A or all
124 /// bits of A are set in B.
125 ///   Example: (icmp eq (A & 3), 3) -> AMask_AllOnes
126 ///
127 /// "AllZeros" declares that the comparison is true only if (A & B) == 0 or all
128 /// bits of A are cleared in B.
129 ///   Example: (icmp eq (A & 3), 0) -> Mask_AllZeroes
130 ///
131 /// "Mixed" declares that (A & B) == C and C might or might not contain any
132 /// number of one bits and zero bits.
133 ///   Example: (icmp eq (A & 3), 1) -> AMask_Mixed
134 ///
135 /// "Not" means that in above descriptions "==" should be replaced by "!=".
136 ///   Example: (icmp ne (A & 3), 3) -> AMask_NotAllOnes
137 ///
138 /// If the mask A contains a single bit, then the following is equivalent:
139 ///    (icmp eq (A & B), A) equals (icmp ne (A & B), 0)
140 ///    (icmp ne (A & B), A) equals (icmp eq (A & B), 0)
141 enum MaskedICmpType {
142   AMask_AllOnes           =     1,
143   AMask_NotAllOnes        =     2,
144   BMask_AllOnes           =     4,
145   BMask_NotAllOnes        =     8,
146   Mask_AllZeros           =    16,
147   Mask_NotAllZeros        =    32,
148   AMask_Mixed             =    64,
149   AMask_NotMixed          =   128,
150   BMask_Mixed             =   256,
151   BMask_NotMixed          =   512
152 };
153 
154 /// Return the set of patterns (from MaskedICmpType) that (icmp SCC (A & B), C)
155 /// satisfies.
156 static unsigned getMaskedICmpType(Value *A, Value *B, Value *C,
157                                   ICmpInst::Predicate Pred) {
158   const APInt *ConstA = nullptr, *ConstB = nullptr, *ConstC = nullptr;
159   match(A, m_APInt(ConstA));
160   match(B, m_APInt(ConstB));
161   match(C, m_APInt(ConstC));
162   bool IsEq = (Pred == ICmpInst::ICMP_EQ);
163   bool IsAPow2 = ConstA && ConstA->isPowerOf2();
164   bool IsBPow2 = ConstB && ConstB->isPowerOf2();
165   unsigned MaskVal = 0;
166   if (ConstC && ConstC->isZero()) {
167     // if C is zero, then both A and B qualify as mask
168     MaskVal |= (IsEq ? (Mask_AllZeros | AMask_Mixed | BMask_Mixed)
169                      : (Mask_NotAllZeros | AMask_NotMixed | BMask_NotMixed));
170     if (IsAPow2)
171       MaskVal |= (IsEq ? (AMask_NotAllOnes | AMask_NotMixed)
172                        : (AMask_AllOnes | AMask_Mixed));
173     if (IsBPow2)
174       MaskVal |= (IsEq ? (BMask_NotAllOnes | BMask_NotMixed)
175                        : (BMask_AllOnes | BMask_Mixed));
176     return MaskVal;
177   }
178 
179   if (A == C) {
180     MaskVal |= (IsEq ? (AMask_AllOnes | AMask_Mixed)
181                      : (AMask_NotAllOnes | AMask_NotMixed));
182     if (IsAPow2)
183       MaskVal |= (IsEq ? (Mask_NotAllZeros | AMask_NotMixed)
184                        : (Mask_AllZeros | AMask_Mixed));
185   } else if (ConstA && ConstC && ConstC->isSubsetOf(*ConstA)) {
186     MaskVal |= (IsEq ? AMask_Mixed : AMask_NotMixed);
187   }
188 
189   if (B == C) {
190     MaskVal |= (IsEq ? (BMask_AllOnes | BMask_Mixed)
191                      : (BMask_NotAllOnes | BMask_NotMixed));
192     if (IsBPow2)
193       MaskVal |= (IsEq ? (Mask_NotAllZeros | BMask_NotMixed)
194                        : (Mask_AllZeros | BMask_Mixed));
195   } else if (ConstB && ConstC && ConstC->isSubsetOf(*ConstB)) {
196     MaskVal |= (IsEq ? BMask_Mixed : BMask_NotMixed);
197   }
198 
199   return MaskVal;
200 }
201 
202 /// Convert an analysis of a masked ICmp into its equivalent if all boolean
203 /// operations had the opposite sense. Since each "NotXXX" flag (recording !=)
204 /// is adjacent to the corresponding normal flag (recording ==), this just
205 /// involves swapping those bits over.
206 static unsigned conjugateICmpMask(unsigned Mask) {
207   unsigned NewMask;
208   NewMask = (Mask & (AMask_AllOnes | BMask_AllOnes | Mask_AllZeros |
209                      AMask_Mixed | BMask_Mixed))
210             << 1;
211 
212   NewMask |= (Mask & (AMask_NotAllOnes | BMask_NotAllOnes | Mask_NotAllZeros |
213                       AMask_NotMixed | BMask_NotMixed))
214              >> 1;
215 
216   return NewMask;
217 }
218 
219 // Adapts the external decomposeBitTestICmp for local use.
220 static bool decomposeBitTestICmp(Value *LHS, Value *RHS, CmpInst::Predicate &Pred,
221                                  Value *&X, Value *&Y, Value *&Z) {
222   APInt Mask;
223   if (!llvm::decomposeBitTestICmp(LHS, RHS, Pred, X, Mask))
224     return false;
225 
226   Y = ConstantInt::get(X->getType(), Mask);
227   Z = ConstantInt::get(X->getType(), 0);
228   return true;
229 }
230 
231 /// Handle (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E).
232 /// Return the pattern classes (from MaskedICmpType) for the left hand side and
233 /// the right hand side as a pair.
234 /// LHS and RHS are the left hand side and the right hand side ICmps and PredL
235 /// and PredR are their predicates, respectively.
236 static std::optional<std::pair<unsigned, unsigned>> getMaskedTypeForICmpPair(
237     Value *&A, Value *&B, Value *&C, Value *&D, Value *&E, ICmpInst *LHS,
238     ICmpInst *RHS, ICmpInst::Predicate &PredL, ICmpInst::Predicate &PredR) {
239   // Don't allow pointers. Splat vectors are fine.
240   if (!LHS->getOperand(0)->getType()->isIntOrIntVectorTy() ||
241       !RHS->getOperand(0)->getType()->isIntOrIntVectorTy())
242     return std::nullopt;
243 
244   // Here comes the tricky part:
245   // LHS might be of the form L11 & L12 == X, X == L21 & L22,
246   // and L11 & L12 == L21 & L22. The same goes for RHS.
247   // Now we must find those components L** and R**, that are equal, so
248   // that we can extract the parameters A, B, C, D, and E for the canonical
249   // above.
250   Value *L1 = LHS->getOperand(0);
251   Value *L2 = LHS->getOperand(1);
252   Value *L11, *L12, *L21, *L22;
253   // Check whether the icmp can be decomposed into a bit test.
254   if (decomposeBitTestICmp(L1, L2, PredL, L11, L12, L2)) {
255     L21 = L22 = L1 = nullptr;
256   } else {
257     // Look for ANDs in the LHS icmp.
258     if (!match(L1, m_And(m_Value(L11), m_Value(L12)))) {
259       // Any icmp can be viewed as being trivially masked; if it allows us to
260       // remove one, it's worth it.
261       L11 = L1;
262       L12 = Constant::getAllOnesValue(L1->getType());
263     }
264 
265     if (!match(L2, m_And(m_Value(L21), m_Value(L22)))) {
266       L21 = L2;
267       L22 = Constant::getAllOnesValue(L2->getType());
268     }
269   }
270 
271   // Bail if LHS was a icmp that can't be decomposed into an equality.
272   if (!ICmpInst::isEquality(PredL))
273     return std::nullopt;
274 
275   Value *R1 = RHS->getOperand(0);
276   Value *R2 = RHS->getOperand(1);
277   Value *R11, *R12;
278   bool Ok = false;
279   if (decomposeBitTestICmp(R1, R2, PredR, R11, R12, R2)) {
280     if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
281       A = R11;
282       D = R12;
283     } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
284       A = R12;
285       D = R11;
286     } else {
287       return std::nullopt;
288     }
289     E = R2;
290     R1 = nullptr;
291     Ok = true;
292   } else {
293     if (!match(R1, m_And(m_Value(R11), m_Value(R12)))) {
294       // As before, model no mask as a trivial mask if it'll let us do an
295       // optimization.
296       R11 = R1;
297       R12 = Constant::getAllOnesValue(R1->getType());
298     }
299 
300     if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
301       A = R11;
302       D = R12;
303       E = R2;
304       Ok = true;
305     } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
306       A = R12;
307       D = R11;
308       E = R2;
309       Ok = true;
310     }
311   }
312 
313   // Bail if RHS was a icmp that can't be decomposed into an equality.
314   if (!ICmpInst::isEquality(PredR))
315     return std::nullopt;
316 
317   // Look for ANDs on the right side of the RHS icmp.
318   if (!Ok) {
319     if (!match(R2, m_And(m_Value(R11), m_Value(R12)))) {
320       R11 = R2;
321       R12 = Constant::getAllOnesValue(R2->getType());
322     }
323 
324     if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
325       A = R11;
326       D = R12;
327       E = R1;
328       Ok = true;
329     } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
330       A = R12;
331       D = R11;
332       E = R1;
333       Ok = true;
334     } else {
335       return std::nullopt;
336     }
337 
338     assert(Ok && "Failed to find AND on the right side of the RHS icmp.");
339   }
340 
341   if (L11 == A) {
342     B = L12;
343     C = L2;
344   } else if (L12 == A) {
345     B = L11;
346     C = L2;
347   } else if (L21 == A) {
348     B = L22;
349     C = L1;
350   } else if (L22 == A) {
351     B = L21;
352     C = L1;
353   }
354 
355   unsigned LeftType = getMaskedICmpType(A, B, C, PredL);
356   unsigned RightType = getMaskedICmpType(A, D, E, PredR);
357   return std::optional<std::pair<unsigned, unsigned>>(
358       std::make_pair(LeftType, RightType));
359 }
360 
361 /// Try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E) into a single
362 /// (icmp(A & X) ==/!= Y), where the left-hand side is of type Mask_NotAllZeros
363 /// and the right hand side is of type BMask_Mixed. For example,
364 /// (icmp (A & 12) != 0) & (icmp (A & 15) == 8) -> (icmp (A & 15) == 8).
365 /// Also used for logical and/or, must be poison safe.
366 static Value *foldLogOpOfMaskedICmps_NotAllZeros_BMask_Mixed(
367     ICmpInst *LHS, ICmpInst *RHS, bool IsAnd, Value *A, Value *B, Value *C,
368     Value *D, Value *E, ICmpInst::Predicate PredL, ICmpInst::Predicate PredR,
369     InstCombiner::BuilderTy &Builder) {
370   // We are given the canonical form:
371   //   (icmp ne (A & B), 0) & (icmp eq (A & D), E).
372   // where D & E == E.
373   //
374   // If IsAnd is false, we get it in negated form:
375   //   (icmp eq (A & B), 0) | (icmp ne (A & D), E) ->
376   //      !((icmp ne (A & B), 0) & (icmp eq (A & D), E)).
377   //
378   // We currently handle the case of B, C, D, E are constant.
379   //
380   const APInt *BCst, *CCst, *DCst, *OrigECst;
381   if (!match(B, m_APInt(BCst)) || !match(C, m_APInt(CCst)) ||
382       !match(D, m_APInt(DCst)) || !match(E, m_APInt(OrigECst)))
383     return nullptr;
384 
385   ICmpInst::Predicate NewCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
386 
387   // Update E to the canonical form when D is a power of two and RHS is
388   // canonicalized as,
389   // (icmp ne (A & D), 0) -> (icmp eq (A & D), D) or
390   // (icmp ne (A & D), D) -> (icmp eq (A & D), 0).
391   APInt ECst = *OrigECst;
392   if (PredR != NewCC)
393     ECst ^= *DCst;
394 
395   // If B or D is zero, skip because if LHS or RHS can be trivially folded by
396   // other folding rules and this pattern won't apply any more.
397   if (*BCst == 0 || *DCst == 0)
398     return nullptr;
399 
400   // If B and D don't intersect, ie. (B & D) == 0, no folding because we can't
401   // deduce anything from it.
402   // For example,
403   // (icmp ne (A & 12), 0) & (icmp eq (A & 3), 1) -> no folding.
404   if ((*BCst & *DCst) == 0)
405     return nullptr;
406 
407   // If the following two conditions are met:
408   //
409   // 1. mask B covers only a single bit that's not covered by mask D, that is,
410   // (B & (B ^ D)) is a power of 2 (in other words, B minus the intersection of
411   // B and D has only one bit set) and,
412   //
413   // 2. RHS (and E) indicates that the rest of B's bits are zero (in other
414   // words, the intersection of B and D is zero), that is, ((B & D) & E) == 0
415   //
416   // then that single bit in B must be one and thus the whole expression can be
417   // folded to
418   //   (A & (B | D)) == (B & (B ^ D)) | E.
419   //
420   // For example,
421   // (icmp ne (A & 12), 0) & (icmp eq (A & 7), 1) -> (icmp eq (A & 15), 9)
422   // (icmp ne (A & 15), 0) & (icmp eq (A & 7), 0) -> (icmp eq (A & 15), 8)
423   if ((((*BCst & *DCst) & ECst) == 0) &&
424       (*BCst & (*BCst ^ *DCst)).isPowerOf2()) {
425     APInt BorD = *BCst | *DCst;
426     APInt BandBxorDorE = (*BCst & (*BCst ^ *DCst)) | ECst;
427     Value *NewMask = ConstantInt::get(A->getType(), BorD);
428     Value *NewMaskedValue = ConstantInt::get(A->getType(), BandBxorDorE);
429     Value *NewAnd = Builder.CreateAnd(A, NewMask);
430     return Builder.CreateICmp(NewCC, NewAnd, NewMaskedValue);
431   }
432 
433   auto IsSubSetOrEqual = [](const APInt *C1, const APInt *C2) {
434     return (*C1 & *C2) == *C1;
435   };
436   auto IsSuperSetOrEqual = [](const APInt *C1, const APInt *C2) {
437     return (*C1 & *C2) == *C2;
438   };
439 
440   // In the following, we consider only the cases where B is a superset of D, B
441   // is a subset of D, or B == D because otherwise there's at least one bit
442   // covered by B but not D, in which case we can't deduce much from it, so
443   // no folding (aside from the single must-be-one bit case right above.)
444   // For example,
445   // (icmp ne (A & 14), 0) & (icmp eq (A & 3), 1) -> no folding.
446   if (!IsSubSetOrEqual(BCst, DCst) && !IsSuperSetOrEqual(BCst, DCst))
447     return nullptr;
448 
449   // At this point, either B is a superset of D, B is a subset of D or B == D.
450 
451   // If E is zero, if B is a subset of (or equal to) D, LHS and RHS contradict
452   // and the whole expression becomes false (or true if negated), otherwise, no
453   // folding.
454   // For example,
455   // (icmp ne (A & 3), 0) & (icmp eq (A & 7), 0) -> false.
456   // (icmp ne (A & 15), 0) & (icmp eq (A & 3), 0) -> no folding.
457   if (ECst.isZero()) {
458     if (IsSubSetOrEqual(BCst, DCst))
459       return ConstantInt::get(LHS->getType(), !IsAnd);
460     return nullptr;
461   }
462 
463   // At this point, B, D, E aren't zero and (B & D) == B, (B & D) == D or B ==
464   // D. If B is a superset of (or equal to) D, since E is not zero, LHS is
465   // subsumed by RHS (RHS implies LHS.) So the whole expression becomes
466   // RHS. For example,
467   // (icmp ne (A & 255), 0) & (icmp eq (A & 15), 8) -> (icmp eq (A & 15), 8).
468   // (icmp ne (A & 15), 0) & (icmp eq (A & 15), 8) -> (icmp eq (A & 15), 8).
469   if (IsSuperSetOrEqual(BCst, DCst))
470     return RHS;
471   // Otherwise, B is a subset of D. If B and E have a common bit set,
472   // ie. (B & E) != 0, then LHS is subsumed by RHS. For example.
473   // (icmp ne (A & 12), 0) & (icmp eq (A & 15), 8) -> (icmp eq (A & 15), 8).
474   assert(IsSubSetOrEqual(BCst, DCst) && "Precondition due to above code");
475   if ((*BCst & ECst) != 0)
476     return RHS;
477   // Otherwise, LHS and RHS contradict and the whole expression becomes false
478   // (or true if negated.) For example,
479   // (icmp ne (A & 7), 0) & (icmp eq (A & 15), 8) -> false.
480   // (icmp ne (A & 6), 0) & (icmp eq (A & 15), 8) -> false.
481   return ConstantInt::get(LHS->getType(), !IsAnd);
482 }
483 
484 /// Try to fold (icmp(A & B) ==/!= 0) &/| (icmp(A & D) ==/!= E) into a single
485 /// (icmp(A & X) ==/!= Y), where the left-hand side and the right hand side
486 /// aren't of the common mask pattern type.
487 /// Also used for logical and/or, must be poison safe.
488 static Value *foldLogOpOfMaskedICmpsAsymmetric(
489     ICmpInst *LHS, ICmpInst *RHS, bool IsAnd, Value *A, Value *B, Value *C,
490     Value *D, Value *E, ICmpInst::Predicate PredL, ICmpInst::Predicate PredR,
491     unsigned LHSMask, unsigned RHSMask, InstCombiner::BuilderTy &Builder) {
492   assert(ICmpInst::isEquality(PredL) && ICmpInst::isEquality(PredR) &&
493          "Expected equality predicates for masked type of icmps.");
494   // Handle Mask_NotAllZeros-BMask_Mixed cases.
495   // (icmp ne/eq (A & B), C) &/| (icmp eq/ne (A & D), E), or
496   // (icmp eq/ne (A & B), C) &/| (icmp ne/eq (A & D), E)
497   //    which gets swapped to
498   //    (icmp ne/eq (A & D), E) &/| (icmp eq/ne (A & B), C).
499   if (!IsAnd) {
500     LHSMask = conjugateICmpMask(LHSMask);
501     RHSMask = conjugateICmpMask(RHSMask);
502   }
503   if ((LHSMask & Mask_NotAllZeros) && (RHSMask & BMask_Mixed)) {
504     if (Value *V = foldLogOpOfMaskedICmps_NotAllZeros_BMask_Mixed(
505             LHS, RHS, IsAnd, A, B, C, D, E,
506             PredL, PredR, Builder)) {
507       return V;
508     }
509   } else if ((LHSMask & BMask_Mixed) && (RHSMask & Mask_NotAllZeros)) {
510     if (Value *V = foldLogOpOfMaskedICmps_NotAllZeros_BMask_Mixed(
511             RHS, LHS, IsAnd, A, D, E, B, C,
512             PredR, PredL, Builder)) {
513       return V;
514     }
515   }
516   return nullptr;
517 }
518 
519 /// Try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
520 /// into a single (icmp(A & X) ==/!= Y).
521 static Value *foldLogOpOfMaskedICmps(ICmpInst *LHS, ICmpInst *RHS, bool IsAnd,
522                                      bool IsLogical,
523                                      InstCombiner::BuilderTy &Builder) {
524   Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr, *E = nullptr;
525   ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
526   std::optional<std::pair<unsigned, unsigned>> MaskPair =
527       getMaskedTypeForICmpPair(A, B, C, D, E, LHS, RHS, PredL, PredR);
528   if (!MaskPair)
529     return nullptr;
530   assert(ICmpInst::isEquality(PredL) && ICmpInst::isEquality(PredR) &&
531          "Expected equality predicates for masked type of icmps.");
532   unsigned LHSMask = MaskPair->first;
533   unsigned RHSMask = MaskPair->second;
534   unsigned Mask = LHSMask & RHSMask;
535   if (Mask == 0) {
536     // Even if the two sides don't share a common pattern, check if folding can
537     // still happen.
538     if (Value *V = foldLogOpOfMaskedICmpsAsymmetric(
539             LHS, RHS, IsAnd, A, B, C, D, E, PredL, PredR, LHSMask, RHSMask,
540             Builder))
541       return V;
542     return nullptr;
543   }
544 
545   // In full generality:
546   //     (icmp (A & B) Op C) | (icmp (A & D) Op E)
547   // ==  ![ (icmp (A & B) !Op C) & (icmp (A & D) !Op E) ]
548   //
549   // If the latter can be converted into (icmp (A & X) Op Y) then the former is
550   // equivalent to (icmp (A & X) !Op Y).
551   //
552   // Therefore, we can pretend for the rest of this function that we're dealing
553   // with the conjunction, provided we flip the sense of any comparisons (both
554   // input and output).
555 
556   // In most cases we're going to produce an EQ for the "&&" case.
557   ICmpInst::Predicate NewCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
558   if (!IsAnd) {
559     // Convert the masking analysis into its equivalent with negated
560     // comparisons.
561     Mask = conjugateICmpMask(Mask);
562   }
563 
564   if (Mask & Mask_AllZeros) {
565     // (icmp eq (A & B), 0) & (icmp eq (A & D), 0)
566     // -> (icmp eq (A & (B|D)), 0)
567     if (IsLogical && !isGuaranteedNotToBeUndefOrPoison(D))
568       return nullptr; // TODO: Use freeze?
569     Value *NewOr = Builder.CreateOr(B, D);
570     Value *NewAnd = Builder.CreateAnd(A, NewOr);
571     // We can't use C as zero because we might actually handle
572     //   (icmp ne (A & B), B) & (icmp ne (A & D), D)
573     // with B and D, having a single bit set.
574     Value *Zero = Constant::getNullValue(A->getType());
575     return Builder.CreateICmp(NewCC, NewAnd, Zero);
576   }
577   if (Mask & BMask_AllOnes) {
578     // (icmp eq (A & B), B) & (icmp eq (A & D), D)
579     // -> (icmp eq (A & (B|D)), (B|D))
580     if (IsLogical && !isGuaranteedNotToBeUndefOrPoison(D))
581       return nullptr; // TODO: Use freeze?
582     Value *NewOr = Builder.CreateOr(B, D);
583     Value *NewAnd = Builder.CreateAnd(A, NewOr);
584     return Builder.CreateICmp(NewCC, NewAnd, NewOr);
585   }
586   if (Mask & AMask_AllOnes) {
587     // (icmp eq (A & B), A) & (icmp eq (A & D), A)
588     // -> (icmp eq (A & (B&D)), A)
589     if (IsLogical && !isGuaranteedNotToBeUndefOrPoison(D))
590       return nullptr; // TODO: Use freeze?
591     Value *NewAnd1 = Builder.CreateAnd(B, D);
592     Value *NewAnd2 = Builder.CreateAnd(A, NewAnd1);
593     return Builder.CreateICmp(NewCC, NewAnd2, A);
594   }
595 
596   // Remaining cases assume at least that B and D are constant, and depend on
597   // their actual values. This isn't strictly necessary, just a "handle the
598   // easy cases for now" decision.
599   const APInt *ConstB, *ConstD;
600   if (!match(B, m_APInt(ConstB)) || !match(D, m_APInt(ConstD)))
601     return nullptr;
602 
603   if (Mask & (Mask_NotAllZeros | BMask_NotAllOnes)) {
604     // (icmp ne (A & B), 0) & (icmp ne (A & D), 0) and
605     // (icmp ne (A & B), B) & (icmp ne (A & D), D)
606     //     -> (icmp ne (A & B), 0) or (icmp ne (A & D), 0)
607     // Only valid if one of the masks is a superset of the other (check "B&D" is
608     // the same as either B or D).
609     APInt NewMask = *ConstB & *ConstD;
610     if (NewMask == *ConstB)
611       return LHS;
612     else if (NewMask == *ConstD)
613       return RHS;
614   }
615 
616   if (Mask & AMask_NotAllOnes) {
617     // (icmp ne (A & B), B) & (icmp ne (A & D), D)
618     //     -> (icmp ne (A & B), A) or (icmp ne (A & D), A)
619     // Only valid if one of the masks is a superset of the other (check "B|D" is
620     // the same as either B or D).
621     APInt NewMask = *ConstB | *ConstD;
622     if (NewMask == *ConstB)
623       return LHS;
624     else if (NewMask == *ConstD)
625       return RHS;
626   }
627 
628   if (Mask & (BMask_Mixed | BMask_NotMixed)) {
629     // Mixed:
630     // (icmp eq (A & B), C) & (icmp eq (A & D), E)
631     // We already know that B & C == C && D & E == E.
632     // If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of
633     // C and E, which are shared by both the mask B and the mask D, don't
634     // contradict, then we can transform to
635     // -> (icmp eq (A & (B|D)), (C|E))
636     // Currently, we only handle the case of B, C, D, and E being constant.
637     // We can't simply use C and E because we might actually handle
638     //   (icmp ne (A & B), B) & (icmp eq (A & D), D)
639     // with B and D, having a single bit set.
640 
641     // NotMixed:
642     // (icmp ne (A & B), C) & (icmp ne (A & D), E)
643     // -> (icmp ne (A & (B & D)), (C & E))
644     // Check the intersection (B & D) for inequality.
645     // Assume that (B & D) == B || (B & D) == D, i.e B/D is a subset of D/B
646     // and (B & D) & (C ^ E) == 0, bits of C and E, which are shared by both the
647     // B and the D, don't contradict.
648     // Note that we can assume (~B & C) == 0 && (~D & E) == 0, previous
649     // operation should delete these icmps if it hadn't been met.
650 
651     const APInt *OldConstC, *OldConstE;
652     if (!match(C, m_APInt(OldConstC)) || !match(E, m_APInt(OldConstE)))
653       return nullptr;
654 
655     auto FoldBMixed = [&](ICmpInst::Predicate CC, bool IsNot) -> Value * {
656       CC = IsNot ? CmpInst::getInversePredicate(CC) : CC;
657       const APInt ConstC = PredL != CC ? *ConstB ^ *OldConstC : *OldConstC;
658       const APInt ConstE = PredR != CC ? *ConstD ^ *OldConstE : *OldConstE;
659 
660       if (((*ConstB & *ConstD) & (ConstC ^ ConstE)).getBoolValue())
661         return IsNot ? nullptr : ConstantInt::get(LHS->getType(), !IsAnd);
662 
663       if (IsNot && !ConstB->isSubsetOf(*ConstD) && !ConstD->isSubsetOf(*ConstB))
664         return nullptr;
665 
666       APInt BD, CE;
667       if (IsNot) {
668         BD = *ConstB & *ConstD;
669         CE = ConstC & ConstE;
670       } else {
671         BD = *ConstB | *ConstD;
672         CE = ConstC | ConstE;
673       }
674       Value *NewAnd = Builder.CreateAnd(A, BD);
675       Value *CEVal = ConstantInt::get(A->getType(), CE);
676       return Builder.CreateICmp(CC, CEVal, NewAnd);
677     };
678 
679     if (Mask & BMask_Mixed)
680       return FoldBMixed(NewCC, false);
681     if (Mask & BMask_NotMixed) // can be else also
682       return FoldBMixed(NewCC, true);
683   }
684   return nullptr;
685 }
686 
687 /// Try to fold a signed range checked with lower bound 0 to an unsigned icmp.
688 /// Example: (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
689 /// If \p Inverted is true then the check is for the inverted range, e.g.
690 /// (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
691 Value *InstCombinerImpl::simplifyRangeCheck(ICmpInst *Cmp0, ICmpInst *Cmp1,
692                                             bool Inverted) {
693   // Check the lower range comparison, e.g. x >= 0
694   // InstCombine already ensured that if there is a constant it's on the RHS.
695   ConstantInt *RangeStart = dyn_cast<ConstantInt>(Cmp0->getOperand(1));
696   if (!RangeStart)
697     return nullptr;
698 
699   ICmpInst::Predicate Pred0 = (Inverted ? Cmp0->getInversePredicate() :
700                                Cmp0->getPredicate());
701 
702   // Accept x > -1 or x >= 0 (after potentially inverting the predicate).
703   if (!((Pred0 == ICmpInst::ICMP_SGT && RangeStart->isMinusOne()) ||
704         (Pred0 == ICmpInst::ICMP_SGE && RangeStart->isZero())))
705     return nullptr;
706 
707   ICmpInst::Predicate Pred1 = (Inverted ? Cmp1->getInversePredicate() :
708                                Cmp1->getPredicate());
709 
710   Value *Input = Cmp0->getOperand(0);
711   Value *RangeEnd;
712   if (Cmp1->getOperand(0) == Input) {
713     // For the upper range compare we have: icmp x, n
714     RangeEnd = Cmp1->getOperand(1);
715   } else if (Cmp1->getOperand(1) == Input) {
716     // For the upper range compare we have: icmp n, x
717     RangeEnd = Cmp1->getOperand(0);
718     Pred1 = ICmpInst::getSwappedPredicate(Pred1);
719   } else {
720     return nullptr;
721   }
722 
723   // Check the upper range comparison, e.g. x < n
724   ICmpInst::Predicate NewPred;
725   switch (Pred1) {
726     case ICmpInst::ICMP_SLT: NewPred = ICmpInst::ICMP_ULT; break;
727     case ICmpInst::ICMP_SLE: NewPred = ICmpInst::ICMP_ULE; break;
728     default: return nullptr;
729   }
730 
731   // This simplification is only valid if the upper range is not negative.
732   KnownBits Known = computeKnownBits(RangeEnd, /*Depth=*/0, Cmp1);
733   if (!Known.isNonNegative())
734     return nullptr;
735 
736   if (Inverted)
737     NewPred = ICmpInst::getInversePredicate(NewPred);
738 
739   return Builder.CreateICmp(NewPred, Input, RangeEnd);
740 }
741 
742 // Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
743 // Fold (!iszero(A & K1) & !iszero(A & K2)) -> (A & (K1 | K2)) == (K1 | K2)
744 Value *InstCombinerImpl::foldAndOrOfICmpsOfAndWithPow2(ICmpInst *LHS,
745                                                        ICmpInst *RHS,
746                                                        Instruction *CxtI,
747                                                        bool IsAnd,
748                                                        bool IsLogical) {
749   CmpInst::Predicate Pred = IsAnd ? CmpInst::ICMP_NE : CmpInst::ICMP_EQ;
750   if (LHS->getPredicate() != Pred || RHS->getPredicate() != Pred)
751     return nullptr;
752 
753   if (!match(LHS->getOperand(1), m_Zero()) ||
754       !match(RHS->getOperand(1), m_Zero()))
755     return nullptr;
756 
757   Value *L1, *L2, *R1, *R2;
758   if (match(LHS->getOperand(0), m_And(m_Value(L1), m_Value(L2))) &&
759       match(RHS->getOperand(0), m_And(m_Value(R1), m_Value(R2)))) {
760     if (L1 == R2 || L2 == R2)
761       std::swap(R1, R2);
762     if (L2 == R1)
763       std::swap(L1, L2);
764 
765     if (L1 == R1 &&
766         isKnownToBeAPowerOfTwo(L2, false, 0, CxtI) &&
767         isKnownToBeAPowerOfTwo(R2, false, 0, CxtI)) {
768       // If this is a logical and/or, then we must prevent propagation of a
769       // poison value from the RHS by inserting freeze.
770       if (IsLogical)
771         R2 = Builder.CreateFreeze(R2);
772       Value *Mask = Builder.CreateOr(L2, R2);
773       Value *Masked = Builder.CreateAnd(L1, Mask);
774       auto NewPred = IsAnd ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;
775       return Builder.CreateICmp(NewPred, Masked, Mask);
776     }
777   }
778 
779   return nullptr;
780 }
781 
782 /// General pattern:
783 ///   X & Y
784 ///
785 /// Where Y is checking that all the high bits (covered by a mask 4294967168)
786 /// are uniform, i.e.  %arg & 4294967168  can be either  4294967168  or  0
787 /// Pattern can be one of:
788 ///   %t = add        i32 %arg,    128
789 ///   %r = icmp   ult i32 %t,      256
790 /// Or
791 ///   %t0 = shl       i32 %arg,    24
792 ///   %t1 = ashr      i32 %t0,     24
793 ///   %r  = icmp  eq  i32 %t1,     %arg
794 /// Or
795 ///   %t0 = trunc     i32 %arg  to i8
796 ///   %t1 = sext      i8  %t0   to i32
797 ///   %r  = icmp  eq  i32 %t1,     %arg
798 /// This pattern is a signed truncation check.
799 ///
800 /// And X is checking that some bit in that same mask is zero.
801 /// I.e. can be one of:
802 ///   %r = icmp sgt i32   %arg,    -1
803 /// Or
804 ///   %t = and      i32   %arg,    2147483648
805 ///   %r = icmp eq  i32   %t,      0
806 ///
807 /// Since we are checking that all the bits in that mask are the same,
808 /// and a particular bit is zero, what we are really checking is that all the
809 /// masked bits are zero.
810 /// So this should be transformed to:
811 ///   %r = icmp ult i32 %arg, 128
812 static Value *foldSignedTruncationCheck(ICmpInst *ICmp0, ICmpInst *ICmp1,
813                                         Instruction &CxtI,
814                                         InstCombiner::BuilderTy &Builder) {
815   assert(CxtI.getOpcode() == Instruction::And);
816 
817   // Match  icmp ult (add %arg, C01), C1   (C1 == C01 << 1; powers of two)
818   auto tryToMatchSignedTruncationCheck = [](ICmpInst *ICmp, Value *&X,
819                                             APInt &SignBitMask) -> bool {
820     CmpInst::Predicate Pred;
821     const APInt *I01, *I1; // powers of two; I1 == I01 << 1
822     if (!(match(ICmp,
823                 m_ICmp(Pred, m_Add(m_Value(X), m_Power2(I01)), m_Power2(I1))) &&
824           Pred == ICmpInst::ICMP_ULT && I1->ugt(*I01) && I01->shl(1) == *I1))
825       return false;
826     // Which bit is the new sign bit as per the 'signed truncation' pattern?
827     SignBitMask = *I01;
828     return true;
829   };
830 
831   // One icmp needs to be 'signed truncation check'.
832   // We need to match this first, else we will mismatch commutative cases.
833   Value *X1;
834   APInt HighestBit;
835   ICmpInst *OtherICmp;
836   if (tryToMatchSignedTruncationCheck(ICmp1, X1, HighestBit))
837     OtherICmp = ICmp0;
838   else if (tryToMatchSignedTruncationCheck(ICmp0, X1, HighestBit))
839     OtherICmp = ICmp1;
840   else
841     return nullptr;
842 
843   assert(HighestBit.isPowerOf2() && "expected to be power of two (non-zero)");
844 
845   // Try to match/decompose into:  icmp eq (X & Mask), 0
846   auto tryToDecompose = [](ICmpInst *ICmp, Value *&X,
847                            APInt &UnsetBitsMask) -> bool {
848     CmpInst::Predicate Pred = ICmp->getPredicate();
849     // Can it be decomposed into  icmp eq (X & Mask), 0  ?
850     if (llvm::decomposeBitTestICmp(ICmp->getOperand(0), ICmp->getOperand(1),
851                                    Pred, X, UnsetBitsMask,
852                                    /*LookThroughTrunc=*/false) &&
853         Pred == ICmpInst::ICMP_EQ)
854       return true;
855     // Is it  icmp eq (X & Mask), 0  already?
856     const APInt *Mask;
857     if (match(ICmp, m_ICmp(Pred, m_And(m_Value(X), m_APInt(Mask)), m_Zero())) &&
858         Pred == ICmpInst::ICMP_EQ) {
859       UnsetBitsMask = *Mask;
860       return true;
861     }
862     return false;
863   };
864 
865   // And the other icmp needs to be decomposable into a bit test.
866   Value *X0;
867   APInt UnsetBitsMask;
868   if (!tryToDecompose(OtherICmp, X0, UnsetBitsMask))
869     return nullptr;
870 
871   assert(!UnsetBitsMask.isZero() && "empty mask makes no sense.");
872 
873   // Are they working on the same value?
874   Value *X;
875   if (X1 == X0) {
876     // Ok as is.
877     X = X1;
878   } else if (match(X0, m_Trunc(m_Specific(X1)))) {
879     UnsetBitsMask = UnsetBitsMask.zext(X1->getType()->getScalarSizeInBits());
880     X = X1;
881   } else
882     return nullptr;
883 
884   // So which bits should be uniform as per the 'signed truncation check'?
885   // (all the bits starting with (i.e. including) HighestBit)
886   APInt SignBitsMask = ~(HighestBit - 1U);
887 
888   // UnsetBitsMask must have some common bits with SignBitsMask,
889   if (!UnsetBitsMask.intersects(SignBitsMask))
890     return nullptr;
891 
892   // Does UnsetBitsMask contain any bits outside of SignBitsMask?
893   if (!UnsetBitsMask.isSubsetOf(SignBitsMask)) {
894     APInt OtherHighestBit = (~UnsetBitsMask) + 1U;
895     if (!OtherHighestBit.isPowerOf2())
896       return nullptr;
897     HighestBit = APIntOps::umin(HighestBit, OtherHighestBit);
898   }
899   // Else, if it does not, then all is ok as-is.
900 
901   // %r = icmp ult %X, SignBit
902   return Builder.CreateICmpULT(X, ConstantInt::get(X->getType(), HighestBit),
903                                CxtI.getName() + ".simplified");
904 }
905 
906 /// Fold (icmp eq ctpop(X) 1) | (icmp eq X 0) into (icmp ult ctpop(X) 2) and
907 /// fold (icmp ne ctpop(X) 1) & (icmp ne X 0) into (icmp ugt ctpop(X) 1).
908 /// Also used for logical and/or, must be poison safe.
909 static Value *foldIsPowerOf2OrZero(ICmpInst *Cmp0, ICmpInst *Cmp1, bool IsAnd,
910                                    InstCombiner::BuilderTy &Builder) {
911   CmpInst::Predicate Pred0, Pred1;
912   Value *X;
913   if (!match(Cmp0, m_ICmp(Pred0, m_Intrinsic<Intrinsic::ctpop>(m_Value(X)),
914                           m_SpecificInt(1))) ||
915       !match(Cmp1, m_ICmp(Pred1, m_Specific(X), m_ZeroInt())))
916     return nullptr;
917 
918   Value *CtPop = Cmp0->getOperand(0);
919   if (IsAnd && Pred0 == ICmpInst::ICMP_NE && Pred1 == ICmpInst::ICMP_NE)
920     return Builder.CreateICmpUGT(CtPop, ConstantInt::get(CtPop->getType(), 1));
921   if (!IsAnd && Pred0 == ICmpInst::ICMP_EQ && Pred1 == ICmpInst::ICMP_EQ)
922     return Builder.CreateICmpULT(CtPop, ConstantInt::get(CtPop->getType(), 2));
923 
924   return nullptr;
925 }
926 
927 /// Reduce a pair of compares that check if a value has exactly 1 bit set.
928 /// Also used for logical and/or, must be poison safe.
929 static Value *foldIsPowerOf2(ICmpInst *Cmp0, ICmpInst *Cmp1, bool JoinedByAnd,
930                              InstCombiner::BuilderTy &Builder) {
931   // Handle 'and' / 'or' commutation: make the equality check the first operand.
932   if (JoinedByAnd && Cmp1->getPredicate() == ICmpInst::ICMP_NE)
933     std::swap(Cmp0, Cmp1);
934   else if (!JoinedByAnd && Cmp1->getPredicate() == ICmpInst::ICMP_EQ)
935     std::swap(Cmp0, Cmp1);
936 
937   // (X != 0) && (ctpop(X) u< 2) --> ctpop(X) == 1
938   CmpInst::Predicate Pred0, Pred1;
939   Value *X;
940   if (JoinedByAnd && match(Cmp0, m_ICmp(Pred0, m_Value(X), m_ZeroInt())) &&
941       match(Cmp1, m_ICmp(Pred1, m_Intrinsic<Intrinsic::ctpop>(m_Specific(X)),
942                          m_SpecificInt(2))) &&
943       Pred0 == ICmpInst::ICMP_NE && Pred1 == ICmpInst::ICMP_ULT) {
944     Value *CtPop = Cmp1->getOperand(0);
945     return Builder.CreateICmpEQ(CtPop, ConstantInt::get(CtPop->getType(), 1));
946   }
947   // (X == 0) || (ctpop(X) u> 1) --> ctpop(X) != 1
948   if (!JoinedByAnd && match(Cmp0, m_ICmp(Pred0, m_Value(X), m_ZeroInt())) &&
949       match(Cmp1, m_ICmp(Pred1, m_Intrinsic<Intrinsic::ctpop>(m_Specific(X)),
950                          m_SpecificInt(1))) &&
951       Pred0 == ICmpInst::ICMP_EQ && Pred1 == ICmpInst::ICMP_UGT) {
952     Value *CtPop = Cmp1->getOperand(0);
953     return Builder.CreateICmpNE(CtPop, ConstantInt::get(CtPop->getType(), 1));
954   }
955   return nullptr;
956 }
957 
958 /// Try to fold (icmp(A & B) == 0) & (icmp(A & D) != E) into (icmp A u< D) iff
959 /// B is a contiguous set of ones starting from the most significant bit
960 /// (negative power of 2), D and E are equal, and D is a contiguous set of ones
961 /// starting at the most significant zero bit in B. Parameter B supports masking
962 /// using undef/poison in either scalar or vector values.
963 static Value *foldNegativePower2AndShiftedMask(
964     Value *A, Value *B, Value *D, Value *E, ICmpInst::Predicate PredL,
965     ICmpInst::Predicate PredR, InstCombiner::BuilderTy &Builder) {
966   assert(ICmpInst::isEquality(PredL) && ICmpInst::isEquality(PredR) &&
967          "Expected equality predicates for masked type of icmps.");
968   if (PredL != ICmpInst::ICMP_EQ || PredR != ICmpInst::ICMP_NE)
969     return nullptr;
970 
971   if (!match(B, m_NegatedPower2()) || !match(D, m_ShiftedMask()) ||
972       !match(E, m_ShiftedMask()))
973     return nullptr;
974 
975   // Test scalar arguments for conversion. B has been validated earlier to be a
976   // negative power of two and thus is guaranteed to have one or more contiguous
977   // ones starting from the MSB followed by zero or more contiguous zeros. D has
978   // been validated earlier to be a shifted set of one or more contiguous ones.
979   // In order to match, B leading ones and D leading zeros should be equal. The
980   // predicate that B be a negative power of 2 prevents the condition of there
981   // ever being zero leading ones. Thus 0 == 0 cannot occur. The predicate that
982   // D always be a shifted mask prevents the condition of D equaling 0. This
983   // prevents matching the condition where B contains the maximum number of
984   // leading one bits (-1) and D contains the maximum number of leading zero
985   // bits (0).
986   auto isReducible = [](const Value *B, const Value *D, const Value *E) {
987     const APInt *BCst, *DCst, *ECst;
988     return match(B, m_APIntAllowUndef(BCst)) && match(D, m_APInt(DCst)) &&
989            match(E, m_APInt(ECst)) && *DCst == *ECst &&
990            (isa<UndefValue>(B) ||
991             (BCst->countLeadingOnes() == DCst->countLeadingZeros()));
992   };
993 
994   // Test vector type arguments for conversion.
995   if (const auto *BVTy = dyn_cast<VectorType>(B->getType())) {
996     const auto *BFVTy = dyn_cast<FixedVectorType>(BVTy);
997     const auto *BConst = dyn_cast<Constant>(B);
998     const auto *DConst = dyn_cast<Constant>(D);
999     const auto *EConst = dyn_cast<Constant>(E);
1000 
1001     if (!BFVTy || !BConst || !DConst || !EConst)
1002       return nullptr;
1003 
1004     for (unsigned I = 0; I != BFVTy->getNumElements(); ++I) {
1005       const auto *BElt = BConst->getAggregateElement(I);
1006       const auto *DElt = DConst->getAggregateElement(I);
1007       const auto *EElt = EConst->getAggregateElement(I);
1008 
1009       if (!BElt || !DElt || !EElt)
1010         return nullptr;
1011       if (!isReducible(BElt, DElt, EElt))
1012         return nullptr;
1013     }
1014   } else {
1015     // Test scalar type arguments for conversion.
1016     if (!isReducible(B, D, E))
1017       return nullptr;
1018   }
1019   return Builder.CreateICmp(ICmpInst::ICMP_ULT, A, D);
1020 }
1021 
1022 /// Try to fold ((icmp X u< P) & (icmp(X & M) != M)) or ((icmp X s> -1) &
1023 /// (icmp(X & M) != M)) into (icmp X u< M). Where P is a power of 2, M < P, and
1024 /// M is a contiguous shifted mask starting at the right most significant zero
1025 /// bit in P. SGT is supported as when P is the largest representable power of
1026 /// 2, an earlier optimization converts the expression into (icmp X s> -1).
1027 /// Parameter P supports masking using undef/poison in either scalar or vector
1028 /// values.
1029 static Value *foldPowerOf2AndShiftedMask(ICmpInst *Cmp0, ICmpInst *Cmp1,
1030                                          bool JoinedByAnd,
1031                                          InstCombiner::BuilderTy &Builder) {
1032   if (!JoinedByAnd)
1033     return nullptr;
1034   Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr, *E = nullptr;
1035   ICmpInst::Predicate CmpPred0 = Cmp0->getPredicate(),
1036                       CmpPred1 = Cmp1->getPredicate();
1037   // Assuming P is a 2^n, getMaskedTypeForICmpPair will normalize (icmp X u<
1038   // 2^n) into (icmp (X & ~(2^n-1)) == 0) and (icmp X s> -1) into (icmp (X &
1039   // SignMask) == 0).
1040   std::optional<std::pair<unsigned, unsigned>> MaskPair =
1041       getMaskedTypeForICmpPair(A, B, C, D, E, Cmp0, Cmp1, CmpPred0, CmpPred1);
1042   if (!MaskPair)
1043     return nullptr;
1044 
1045   const auto compareBMask = BMask_NotMixed | BMask_NotAllOnes;
1046   unsigned CmpMask0 = MaskPair->first;
1047   unsigned CmpMask1 = MaskPair->second;
1048   if ((CmpMask0 & Mask_AllZeros) && (CmpMask1 == compareBMask)) {
1049     if (Value *V = foldNegativePower2AndShiftedMask(A, B, D, E, CmpPred0,
1050                                                     CmpPred1, Builder))
1051       return V;
1052   } else if ((CmpMask0 == compareBMask) && (CmpMask1 & Mask_AllZeros)) {
1053     if (Value *V = foldNegativePower2AndShiftedMask(A, D, B, C, CmpPred1,
1054                                                     CmpPred0, Builder))
1055       return V;
1056   }
1057   return nullptr;
1058 }
1059 
1060 /// Commuted variants are assumed to be handled by calling this function again
1061 /// with the parameters swapped.
1062 static Value *foldUnsignedUnderflowCheck(ICmpInst *ZeroICmp,
1063                                          ICmpInst *UnsignedICmp, bool IsAnd,
1064                                          const SimplifyQuery &Q,
1065                                          InstCombiner::BuilderTy &Builder) {
1066   Value *ZeroCmpOp;
1067   ICmpInst::Predicate EqPred;
1068   if (!match(ZeroICmp, m_ICmp(EqPred, m_Value(ZeroCmpOp), m_Zero())) ||
1069       !ICmpInst::isEquality(EqPred))
1070     return nullptr;
1071 
1072   auto IsKnownNonZero = [&](Value *V) {
1073     return isKnownNonZero(V, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT);
1074   };
1075 
1076   ICmpInst::Predicate UnsignedPred;
1077 
1078   Value *A, *B;
1079   if (match(UnsignedICmp,
1080             m_c_ICmp(UnsignedPred, m_Specific(ZeroCmpOp), m_Value(A))) &&
1081       match(ZeroCmpOp, m_c_Add(m_Specific(A), m_Value(B))) &&
1082       (ZeroICmp->hasOneUse() || UnsignedICmp->hasOneUse())) {
1083     auto GetKnownNonZeroAndOther = [&](Value *&NonZero, Value *&Other) {
1084       if (!IsKnownNonZero(NonZero))
1085         std::swap(NonZero, Other);
1086       return IsKnownNonZero(NonZero);
1087     };
1088 
1089     // Given  ZeroCmpOp = (A + B)
1090     //   ZeroCmpOp <  A && ZeroCmpOp != 0  -->  (0-X) <  Y  iff
1091     //   ZeroCmpOp >= A || ZeroCmpOp == 0  -->  (0-X) >= Y  iff
1092     //     with X being the value (A/B) that is known to be non-zero,
1093     //     and Y being remaining value.
1094     if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_NE &&
1095         IsAnd && GetKnownNonZeroAndOther(B, A))
1096       return Builder.CreateICmpULT(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 struct IntPart {
1139   Value *From;
1140   unsigned StartBit;
1141   unsigned NumBits;
1142 };
1143 
1144 /// Match an extraction of bits from an integer.
1145 static std::optional<IntPart> matchIntPart(Value *V) {
1146   Value *X;
1147   if (!match(V, m_OneUse(m_Trunc(m_Value(X)))))
1148     return std::nullopt;
1149 
1150   unsigned NumOriginalBits = X->getType()->getScalarSizeInBits();
1151   unsigned NumExtractedBits = V->getType()->getScalarSizeInBits();
1152   Value *Y;
1153   const APInt *Shift;
1154   // For a trunc(lshr Y, Shift) pattern, make sure we're only extracting bits
1155   // from Y, not any shifted-in zeroes.
1156   if (match(X, m_OneUse(m_LShr(m_Value(Y), m_APInt(Shift)))) &&
1157       Shift->ule(NumOriginalBits - NumExtractedBits))
1158     return {{Y, (unsigned)Shift->getZExtValue(), NumExtractedBits}};
1159   return {{X, 0, NumExtractedBits}};
1160 }
1161 
1162 /// Materialize an extraction of bits from an integer in IR.
1163 static Value *extractIntPart(const IntPart &P, IRBuilderBase &Builder) {
1164   Value *V = P.From;
1165   if (P.StartBit)
1166     V = Builder.CreateLShr(V, P.StartBit);
1167   Type *TruncTy = V->getType()->getWithNewBitWidth(P.NumBits);
1168   if (TruncTy != V->getType())
1169     V = Builder.CreateTrunc(V, TruncTy);
1170   return V;
1171 }
1172 
1173 /// (icmp eq X0, Y0) & (icmp eq X1, Y1) -> icmp eq X01, Y01
1174 /// (icmp ne X0, Y0) | (icmp ne X1, Y1) -> icmp ne X01, Y01
1175 /// where X0, X1 and Y0, Y1 are adjacent parts extracted from an integer.
1176 Value *InstCombinerImpl::foldEqOfParts(ICmpInst *Cmp0, ICmpInst *Cmp1,
1177                                        bool IsAnd) {
1178   if (!Cmp0->hasOneUse() || !Cmp1->hasOneUse())
1179     return nullptr;
1180 
1181   CmpInst::Predicate Pred = IsAnd ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;
1182   if (Cmp0->getPredicate() != Pred || Cmp1->getPredicate() != Pred)
1183     return nullptr;
1184 
1185   std::optional<IntPart> L0 = matchIntPart(Cmp0->getOperand(0));
1186   std::optional<IntPart> R0 = matchIntPart(Cmp0->getOperand(1));
1187   std::optional<IntPart> L1 = matchIntPart(Cmp1->getOperand(0));
1188   std::optional<IntPart> R1 = matchIntPart(Cmp1->getOperand(1));
1189   if (!L0 || !R0 || !L1 || !R1)
1190     return nullptr;
1191 
1192   // Make sure the LHS/RHS compare a part of the same value, possibly after
1193   // an operand swap.
1194   if (L0->From != L1->From || R0->From != R1->From) {
1195     if (L0->From != R1->From || R0->From != L1->From)
1196       return nullptr;
1197     std::swap(L1, R1);
1198   }
1199 
1200   // Make sure the extracted parts are adjacent, canonicalizing to L0/R0 being
1201   // the low part and L1/R1 being the high part.
1202   if (L0->StartBit + L0->NumBits != L1->StartBit ||
1203       R0->StartBit + R0->NumBits != R1->StartBit) {
1204     if (L1->StartBit + L1->NumBits != L0->StartBit ||
1205         R1->StartBit + R1->NumBits != R0->StartBit)
1206       return nullptr;
1207     std::swap(L0, L1);
1208     std::swap(R0, R1);
1209   }
1210 
1211   // We can simplify to a comparison of these larger parts of the integers.
1212   IntPart L = {L0->From, L0->StartBit, L0->NumBits + L1->NumBits};
1213   IntPart R = {R0->From, R0->StartBit, R0->NumBits + R1->NumBits};
1214   Value *LValue = extractIntPart(L, Builder);
1215   Value *RValue = extractIntPart(R, Builder);
1216   return Builder.CreateICmp(Pred, LValue, RValue);
1217 }
1218 
1219 /// Reduce logic-of-compares with equality to a constant by substituting a
1220 /// common operand with the constant. Callers are expected to call this with
1221 /// Cmp0/Cmp1 switched to handle logic op commutativity.
1222 static Value *foldAndOrOfICmpsWithConstEq(ICmpInst *Cmp0, ICmpInst *Cmp1,
1223                                           bool IsAnd, bool IsLogical,
1224                                           InstCombiner::BuilderTy &Builder,
1225                                           const SimplifyQuery &Q) {
1226   // Match an equality compare with a non-poison constant as Cmp0.
1227   // Also, give up if the compare can be constant-folded to avoid looping.
1228   ICmpInst::Predicate Pred0;
1229   Value *X;
1230   Constant *C;
1231   if (!match(Cmp0, m_ICmp(Pred0, m_Value(X), m_Constant(C))) ||
1232       !isGuaranteedNotToBeUndefOrPoison(C) || isa<Constant>(X))
1233     return nullptr;
1234   if ((IsAnd && Pred0 != ICmpInst::ICMP_EQ) ||
1235       (!IsAnd && Pred0 != ICmpInst::ICMP_NE))
1236     return nullptr;
1237 
1238   // The other compare must include a common operand (X). Canonicalize the
1239   // common operand as operand 1 (Pred1 is swapped if the common operand was
1240   // operand 0).
1241   Value *Y;
1242   ICmpInst::Predicate Pred1;
1243   if (!match(Cmp1, m_c_ICmp(Pred1, m_Value(Y), m_Deferred(X))))
1244     return nullptr;
1245 
1246   // Replace variable with constant value equivalence to remove a variable use:
1247   // (X == C) && (Y Pred1 X) --> (X == C) && (Y Pred1 C)
1248   // (X != C) || (Y Pred1 X) --> (X != C) || (Y Pred1 C)
1249   // Can think of the 'or' substitution with the 'and' bool equivalent:
1250   // A || B --> A || (!A && B)
1251   Value *SubstituteCmp = simplifyICmpInst(Pred1, Y, C, Q);
1252   if (!SubstituteCmp) {
1253     // If we need to create a new instruction, require that the old compare can
1254     // be removed.
1255     if (!Cmp1->hasOneUse())
1256       return nullptr;
1257     SubstituteCmp = Builder.CreateICmp(Pred1, Y, C);
1258   }
1259   if (IsLogical)
1260     return IsAnd ? Builder.CreateLogicalAnd(Cmp0, SubstituteCmp)
1261                  : Builder.CreateLogicalOr(Cmp0, SubstituteCmp);
1262   return Builder.CreateBinOp(IsAnd ? Instruction::And : Instruction::Or, Cmp0,
1263                              SubstituteCmp);
1264 }
1265 
1266 /// Fold (icmp Pred1 V1, C1) & (icmp Pred2 V2, C2)
1267 /// or   (icmp Pred1 V1, C1) | (icmp Pred2 V2, C2)
1268 /// into a single comparison using range-based reasoning.
1269 /// NOTE: This is also used for logical and/or, must be poison-safe!
1270 Value *InstCombinerImpl::foldAndOrOfICmpsUsingRanges(ICmpInst *ICmp1,
1271                                                      ICmpInst *ICmp2,
1272                                                      bool IsAnd) {
1273   ICmpInst::Predicate Pred1, Pred2;
1274   Value *V1, *V2;
1275   const APInt *C1, *C2;
1276   if (!match(ICmp1, m_ICmp(Pred1, m_Value(V1), m_APInt(C1))) ||
1277       !match(ICmp2, m_ICmp(Pred2, m_Value(V2), m_APInt(C2))))
1278     return nullptr;
1279 
1280   // Look through add of a constant offset on V1, V2, or both operands. This
1281   // allows us to interpret the V + C' < C'' range idiom into a proper range.
1282   const APInt *Offset1 = nullptr, *Offset2 = nullptr;
1283   if (V1 != V2) {
1284     Value *X;
1285     if (match(V1, m_Add(m_Value(X), m_APInt(Offset1))))
1286       V1 = X;
1287     if (match(V2, m_Add(m_Value(X), m_APInt(Offset2))))
1288       V2 = X;
1289   }
1290 
1291   if (V1 != V2)
1292     return nullptr;
1293 
1294   ConstantRange CR1 = ConstantRange::makeExactICmpRegion(
1295       IsAnd ? ICmpInst::getInversePredicate(Pred1) : Pred1, *C1);
1296   if (Offset1)
1297     CR1 = CR1.subtract(*Offset1);
1298 
1299   ConstantRange CR2 = ConstantRange::makeExactICmpRegion(
1300       IsAnd ? ICmpInst::getInversePredicate(Pred2) : Pred2, *C2);
1301   if (Offset2)
1302     CR2 = CR2.subtract(*Offset2);
1303 
1304   Type *Ty = V1->getType();
1305   Value *NewV = V1;
1306   std::optional<ConstantRange> CR = CR1.exactUnionWith(CR2);
1307   if (!CR) {
1308     if (!(ICmp1->hasOneUse() && ICmp2->hasOneUse()) || CR1.isWrappedSet() ||
1309         CR2.isWrappedSet())
1310       return nullptr;
1311 
1312     // Check whether we have equal-size ranges that only differ by one bit.
1313     // In that case we can apply a mask to map one range onto the other.
1314     APInt LowerDiff = CR1.getLower() ^ CR2.getLower();
1315     APInt UpperDiff = (CR1.getUpper() - 1) ^ (CR2.getUpper() - 1);
1316     APInt CR1Size = CR1.getUpper() - CR1.getLower();
1317     if (!LowerDiff.isPowerOf2() || LowerDiff != UpperDiff ||
1318         CR1Size != CR2.getUpper() - CR2.getLower())
1319       return nullptr;
1320 
1321     CR = CR1.getLower().ult(CR2.getLower()) ? CR1 : CR2;
1322     NewV = Builder.CreateAnd(NewV, ConstantInt::get(Ty, ~LowerDiff));
1323   }
1324 
1325   if (IsAnd)
1326     CR = CR->inverse();
1327 
1328   CmpInst::Predicate NewPred;
1329   APInt NewC, Offset;
1330   CR->getEquivalentICmp(NewPred, NewC, Offset);
1331 
1332   if (Offset != 0)
1333     NewV = Builder.CreateAdd(NewV, ConstantInt::get(Ty, Offset));
1334   return Builder.CreateICmp(NewPred, NewV, ConstantInt::get(Ty, NewC));
1335 }
1336 
1337 /// Ignore all operations which only change the sign of a value, returning the
1338 /// underlying magnitude value.
1339 static Value *stripSignOnlyFPOps(Value *Val) {
1340   match(Val, m_FNeg(m_Value(Val)));
1341   match(Val, m_FAbs(m_Value(Val)));
1342   match(Val, m_CopySign(m_Value(Val), m_Value()));
1343   return Val;
1344 }
1345 
1346 /// Matches canonical form of isnan, fcmp ord x, 0
1347 static bool matchIsNotNaN(FCmpInst::Predicate P, Value *LHS, Value *RHS) {
1348   return P == FCmpInst::FCMP_ORD && match(RHS, m_AnyZeroFP());
1349 }
1350 
1351 /// Matches fcmp u__ x, +/-inf
1352 static bool matchUnorderedInfCompare(FCmpInst::Predicate P, Value *LHS,
1353                                      Value *RHS) {
1354   return FCmpInst::isUnordered(P) && match(RHS, m_Inf());
1355 }
1356 
1357 /// and (fcmp ord x, 0), (fcmp u* x, inf) -> fcmp o* x, inf
1358 ///
1359 /// Clang emits this pattern for doing an isfinite check in __builtin_isnormal.
1360 static Value *matchIsFiniteTest(InstCombiner::BuilderTy &Builder, FCmpInst *LHS,
1361                                 FCmpInst *RHS) {
1362   Value *LHS0 = LHS->getOperand(0), *LHS1 = LHS->getOperand(1);
1363   Value *RHS0 = RHS->getOperand(0), *RHS1 = RHS->getOperand(1);
1364   FCmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
1365 
1366   if (!matchIsNotNaN(PredL, LHS0, LHS1) ||
1367       !matchUnorderedInfCompare(PredR, RHS0, RHS1))
1368     return nullptr;
1369 
1370   IRBuilder<>::FastMathFlagGuard FMFG(Builder);
1371   FastMathFlags FMF = LHS->getFastMathFlags();
1372   FMF &= RHS->getFastMathFlags();
1373   Builder.setFastMathFlags(FMF);
1374 
1375   return Builder.CreateFCmp(FCmpInst::getOrderedPredicate(PredR), RHS0, RHS1);
1376 }
1377 
1378 Value *InstCombinerImpl::foldLogicOfFCmps(FCmpInst *LHS, FCmpInst *RHS,
1379                                           bool IsAnd, bool IsLogicalSelect) {
1380   Value *LHS0 = LHS->getOperand(0), *LHS1 = LHS->getOperand(1);
1381   Value *RHS0 = RHS->getOperand(0), *RHS1 = RHS->getOperand(1);
1382   FCmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
1383 
1384   if (LHS0 == RHS1 && RHS0 == LHS1) {
1385     // Swap RHS operands to match LHS.
1386     PredR = FCmpInst::getSwappedPredicate(PredR);
1387     std::swap(RHS0, RHS1);
1388   }
1389 
1390   // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
1391   // Suppose the relation between x and y is R, where R is one of
1392   // U(1000), L(0100), G(0010) or E(0001), and CC0 and CC1 are the bitmasks for
1393   // testing the desired relations.
1394   //
1395   // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
1396   //    bool(R & CC0) && bool(R & CC1)
1397   //  = bool((R & CC0) & (R & CC1))
1398   //  = bool(R & (CC0 & CC1)) <= by re-association, commutation, and idempotency
1399   //
1400   // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
1401   //    bool(R & CC0) || bool(R & CC1)
1402   //  = bool((R & CC0) | (R & CC1))
1403   //  = bool(R & (CC0 | CC1)) <= by reversed distribution (contribution? ;)
1404   if (LHS0 == RHS0 && LHS1 == RHS1) {
1405     unsigned FCmpCodeL = getFCmpCode(PredL);
1406     unsigned FCmpCodeR = getFCmpCode(PredR);
1407     unsigned NewPred = IsAnd ? FCmpCodeL & FCmpCodeR : FCmpCodeL | FCmpCodeR;
1408 
1409     // Intersect the fast math flags.
1410     // TODO: We can union the fast math flags unless this is a logical select.
1411     IRBuilder<>::FastMathFlagGuard FMFG(Builder);
1412     FastMathFlags FMF = LHS->getFastMathFlags();
1413     FMF &= RHS->getFastMathFlags();
1414     Builder.setFastMathFlags(FMF);
1415 
1416     return getFCmpValue(NewPred, LHS0, LHS1, Builder);
1417   }
1418 
1419   // This transform is not valid for a logical select.
1420   if (!IsLogicalSelect &&
1421       ((PredL == FCmpInst::FCMP_ORD && PredR == FCmpInst::FCMP_ORD && IsAnd) ||
1422        (PredL == FCmpInst::FCMP_UNO && PredR == FCmpInst::FCMP_UNO &&
1423         !IsAnd))) {
1424     if (LHS0->getType() != RHS0->getType())
1425       return nullptr;
1426 
1427     // FCmp canonicalization ensures that (fcmp ord/uno X, X) and
1428     // (fcmp ord/uno X, C) will be transformed to (fcmp X, +0.0).
1429     if (match(LHS1, m_PosZeroFP()) && match(RHS1, m_PosZeroFP()))
1430       // Ignore the constants because they are obviously not NANs:
1431       // (fcmp ord x, 0.0) & (fcmp ord y, 0.0)  -> (fcmp ord x, y)
1432       // (fcmp uno x, 0.0) | (fcmp uno y, 0.0)  -> (fcmp uno x, y)
1433       return Builder.CreateFCmp(PredL, LHS0, RHS0);
1434   }
1435 
1436   if (IsAnd && stripSignOnlyFPOps(LHS0) == stripSignOnlyFPOps(RHS0)) {
1437     // and (fcmp ord x, 0), (fcmp u* x, inf) -> fcmp o* x, inf
1438     // and (fcmp ord x, 0), (fcmp u* fabs(x), inf) -> fcmp o* x, inf
1439     if (Value *Left = matchIsFiniteTest(Builder, LHS, RHS))
1440       return Left;
1441     if (Value *Right = matchIsFiniteTest(Builder, RHS, LHS))
1442       return Right;
1443   }
1444 
1445   // Turn at least two fcmps with constants into llvm.is.fpclass.
1446   //
1447   // If we can represent a combined value test with one class call, we can
1448   // potentially eliminate 4-6 instructions. If we can represent a test with a
1449   // single fcmp with fneg and fabs, that's likely a better canonical form.
1450   if (LHS->hasOneUse() && RHS->hasOneUse()) {
1451     auto [ClassValRHS, ClassMaskRHS] =
1452         fcmpToClassTest(PredR, *RHS->getFunction(), RHS0, RHS1);
1453     if (ClassValRHS) {
1454       auto [ClassValLHS, ClassMaskLHS] =
1455           fcmpToClassTest(PredL, *LHS->getFunction(), LHS0, LHS1);
1456       if (ClassValLHS == ClassValRHS) {
1457         unsigned CombinedMask = IsAnd ? (ClassMaskLHS & ClassMaskRHS)
1458                                       : (ClassMaskLHS | ClassMaskRHS);
1459         return Builder.CreateIntrinsic(
1460             Intrinsic::is_fpclass, {ClassValLHS->getType()},
1461             {ClassValLHS, Builder.getInt32(CombinedMask)});
1462       }
1463     }
1464   }
1465 
1466   return nullptr;
1467 }
1468 
1469 /// Match an fcmp against a special value that performs a test possible by
1470 /// llvm.is.fpclass.
1471 static bool matchIsFPClassLikeFCmp(Value *Op, Value *&ClassVal,
1472                                    uint64_t &ClassMask) {
1473   auto *FCmp = dyn_cast<FCmpInst>(Op);
1474   if (!FCmp || !FCmp->hasOneUse())
1475     return false;
1476 
1477   std::tie(ClassVal, ClassMask) =
1478       fcmpToClassTest(FCmp->getPredicate(), *FCmp->getParent()->getParent(),
1479                       FCmp->getOperand(0), FCmp->getOperand(1));
1480   return ClassVal != nullptr;
1481 }
1482 
1483 /// or (is_fpclass x, mask0), (is_fpclass x, mask1)
1484 ///     -> is_fpclass x, (mask0 | mask1)
1485 /// and (is_fpclass x, mask0), (is_fpclass x, mask1)
1486 ///     -> is_fpclass x, (mask0 & mask1)
1487 /// xor (is_fpclass x, mask0), (is_fpclass x, mask1)
1488 ///     -> is_fpclass x, (mask0 ^ mask1)
1489 Instruction *InstCombinerImpl::foldLogicOfIsFPClass(BinaryOperator &BO,
1490                                                     Value *Op0, Value *Op1) {
1491   Value *ClassVal0 = nullptr;
1492   Value *ClassVal1 = nullptr;
1493   uint64_t ClassMask0, ClassMask1;
1494 
1495   // Restrict to folding one fcmp into one is.fpclass for now, don't introduce a
1496   // new class.
1497   //
1498   // TODO: Support forming is.fpclass out of 2 separate fcmps when codegen is
1499   // better.
1500 
1501   bool IsLHSClass =
1502       match(Op0, m_OneUse(m_Intrinsic<Intrinsic::is_fpclass>(
1503                      m_Value(ClassVal0), m_ConstantInt(ClassMask0))));
1504   bool IsRHSClass =
1505       match(Op1, m_OneUse(m_Intrinsic<Intrinsic::is_fpclass>(
1506                      m_Value(ClassVal1), m_ConstantInt(ClassMask1))));
1507   if ((((IsLHSClass || matchIsFPClassLikeFCmp(Op0, ClassVal0, ClassMask0)) &&
1508         (IsRHSClass || matchIsFPClassLikeFCmp(Op1, ClassVal1, ClassMask1)))) &&
1509       ClassVal0 == ClassVal1) {
1510     unsigned NewClassMask;
1511     switch (BO.getOpcode()) {
1512     case Instruction::And:
1513       NewClassMask = ClassMask0 & ClassMask1;
1514       break;
1515     case Instruction::Or:
1516       NewClassMask = ClassMask0 | ClassMask1;
1517       break;
1518     case Instruction::Xor:
1519       NewClassMask = ClassMask0 ^ ClassMask1;
1520       break;
1521     default:
1522       llvm_unreachable("not a binary logic operator");
1523     }
1524 
1525     if (IsLHSClass) {
1526       auto *II = cast<IntrinsicInst>(Op0);
1527       II->setArgOperand(
1528           1, ConstantInt::get(II->getArgOperand(1)->getType(), NewClassMask));
1529       return replaceInstUsesWith(BO, II);
1530     }
1531 
1532     if (IsRHSClass) {
1533       auto *II = cast<IntrinsicInst>(Op1);
1534       II->setArgOperand(
1535           1, ConstantInt::get(II->getArgOperand(1)->getType(), NewClassMask));
1536       return replaceInstUsesWith(BO, II);
1537     }
1538 
1539     CallInst *NewClass =
1540         Builder.CreateIntrinsic(Intrinsic::is_fpclass, {ClassVal0->getType()},
1541                                 {ClassVal0, Builder.getInt32(NewClassMask)});
1542     return replaceInstUsesWith(BO, NewClass);
1543   }
1544 
1545   return nullptr;
1546 }
1547 
1548 /// Look for the pattern that conditionally negates a value via math operations:
1549 ///   cond.splat = sext i1 cond
1550 ///   sub = add cond.splat, x
1551 ///   xor = xor sub, cond.splat
1552 /// and rewrite it to do the same, but via logical operations:
1553 ///   value.neg = sub 0, value
1554 ///   cond = select i1 neg, value.neg, value
1555 Instruction *InstCombinerImpl::canonicalizeConditionalNegationViaMathToSelect(
1556     BinaryOperator &I) {
1557   assert(I.getOpcode() == BinaryOperator::Xor && "Only for xor!");
1558   Value *Cond, *X;
1559   // As per complexity ordering, `xor` is not commutative here.
1560   if (!match(&I, m_c_BinOp(m_OneUse(m_Value()), m_Value())) ||
1561       !match(I.getOperand(1), m_SExt(m_Value(Cond))) ||
1562       !Cond->getType()->isIntOrIntVectorTy(1) ||
1563       !match(I.getOperand(0), m_c_Add(m_SExt(m_Deferred(Cond)), m_Value(X))))
1564     return nullptr;
1565   return SelectInst::Create(Cond, Builder.CreateNeg(X, X->getName() + ".neg"),
1566                             X);
1567 }
1568 
1569 /// This a limited reassociation for a special case (see above) where we are
1570 /// checking if two values are either both NAN (unordered) or not-NAN (ordered).
1571 /// This could be handled more generally in '-reassociation', but it seems like
1572 /// an unlikely pattern for a large number of logic ops and fcmps.
1573 static Instruction *reassociateFCmps(BinaryOperator &BO,
1574                                      InstCombiner::BuilderTy &Builder) {
1575   Instruction::BinaryOps Opcode = BO.getOpcode();
1576   assert((Opcode == Instruction::And || Opcode == Instruction::Or) &&
1577          "Expecting and/or op for fcmp transform");
1578 
1579   // There are 4 commuted variants of the pattern. Canonicalize operands of this
1580   // logic op so an fcmp is operand 0 and a matching logic op is operand 1.
1581   Value *Op0 = BO.getOperand(0), *Op1 = BO.getOperand(1), *X;
1582   FCmpInst::Predicate Pred;
1583   if (match(Op1, m_FCmp(Pred, m_Value(), m_AnyZeroFP())))
1584     std::swap(Op0, Op1);
1585 
1586   // Match inner binop and the predicate for combining 2 NAN checks into 1.
1587   Value *BO10, *BO11;
1588   FCmpInst::Predicate NanPred = Opcode == Instruction::And ? FCmpInst::FCMP_ORD
1589                                                            : FCmpInst::FCMP_UNO;
1590   if (!match(Op0, m_FCmp(Pred, m_Value(X), m_AnyZeroFP())) || Pred != NanPred ||
1591       !match(Op1, m_BinOp(Opcode, m_Value(BO10), m_Value(BO11))))
1592     return nullptr;
1593 
1594   // The inner logic op must have a matching fcmp operand.
1595   Value *Y;
1596   if (!match(BO10, m_FCmp(Pred, m_Value(Y), m_AnyZeroFP())) ||
1597       Pred != NanPred || X->getType() != Y->getType())
1598     std::swap(BO10, BO11);
1599 
1600   if (!match(BO10, m_FCmp(Pred, m_Value(Y), m_AnyZeroFP())) ||
1601       Pred != NanPred || X->getType() != Y->getType())
1602     return nullptr;
1603 
1604   // and (fcmp ord X, 0), (and (fcmp ord Y, 0), Z) --> and (fcmp ord X, Y), Z
1605   // or  (fcmp uno X, 0), (or  (fcmp uno Y, 0), Z) --> or  (fcmp uno X, Y), Z
1606   Value *NewFCmp = Builder.CreateFCmp(Pred, X, Y);
1607   if (auto *NewFCmpInst = dyn_cast<FCmpInst>(NewFCmp)) {
1608     // Intersect FMF from the 2 source fcmps.
1609     NewFCmpInst->copyIRFlags(Op0);
1610     NewFCmpInst->andIRFlags(BO10);
1611   }
1612   return BinaryOperator::Create(Opcode, NewFCmp, BO11);
1613 }
1614 
1615 /// Match variations of De Morgan's Laws:
1616 /// (~A & ~B) == (~(A | B))
1617 /// (~A | ~B) == (~(A & B))
1618 static Instruction *matchDeMorgansLaws(BinaryOperator &I,
1619                                        InstCombiner::BuilderTy &Builder) {
1620   const Instruction::BinaryOps Opcode = I.getOpcode();
1621   assert((Opcode == Instruction::And || Opcode == Instruction::Or) &&
1622          "Trying to match De Morgan's Laws with something other than and/or");
1623 
1624   // Flip the logic operation.
1625   const Instruction::BinaryOps FlippedOpcode =
1626       (Opcode == Instruction::And) ? Instruction::Or : Instruction::And;
1627 
1628   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1629   Value *A, *B;
1630   if (match(Op0, m_OneUse(m_Not(m_Value(A)))) &&
1631       match(Op1, m_OneUse(m_Not(m_Value(B)))) &&
1632       !InstCombiner::isFreeToInvert(A, A->hasOneUse()) &&
1633       !InstCombiner::isFreeToInvert(B, B->hasOneUse())) {
1634     Value *AndOr =
1635         Builder.CreateBinOp(FlippedOpcode, A, B, I.getName() + ".demorgan");
1636     return BinaryOperator::CreateNot(AndOr);
1637   }
1638 
1639   // The 'not' ops may require reassociation.
1640   // (A & ~B) & ~C --> A & ~(B | C)
1641   // (~B & A) & ~C --> A & ~(B | C)
1642   // (A | ~B) | ~C --> A | ~(B & C)
1643   // (~B | A) | ~C --> A | ~(B & C)
1644   Value *C;
1645   if (match(Op0, m_OneUse(m_c_BinOp(Opcode, m_Value(A), m_Not(m_Value(B))))) &&
1646       match(Op1, m_Not(m_Value(C)))) {
1647     Value *FlippedBO = Builder.CreateBinOp(FlippedOpcode, B, C);
1648     return BinaryOperator::Create(Opcode, A, Builder.CreateNot(FlippedBO));
1649   }
1650 
1651   return nullptr;
1652 }
1653 
1654 bool InstCombinerImpl::shouldOptimizeCast(CastInst *CI) {
1655   Value *CastSrc = CI->getOperand(0);
1656 
1657   // Noop casts and casts of constants should be eliminated trivially.
1658   if (CI->getSrcTy() == CI->getDestTy() || isa<Constant>(CastSrc))
1659     return false;
1660 
1661   // If this cast is paired with another cast that can be eliminated, we prefer
1662   // to have it eliminated.
1663   if (const auto *PrecedingCI = dyn_cast<CastInst>(CastSrc))
1664     if (isEliminableCastPair(PrecedingCI, CI))
1665       return false;
1666 
1667   return true;
1668 }
1669 
1670 /// Fold {and,or,xor} (cast X), C.
1671 static Instruction *foldLogicCastConstant(BinaryOperator &Logic, CastInst *Cast,
1672                                           InstCombiner::BuilderTy &Builder) {
1673   Constant *C = dyn_cast<Constant>(Logic.getOperand(1));
1674   if (!C)
1675     return nullptr;
1676 
1677   auto LogicOpc = Logic.getOpcode();
1678   Type *DestTy = Logic.getType();
1679   Type *SrcTy = Cast->getSrcTy();
1680 
1681   // Move the logic operation ahead of a zext or sext if the constant is
1682   // unchanged in the smaller source type. Performing the logic in a smaller
1683   // type may provide more information to later folds, and the smaller logic
1684   // instruction may be cheaper (particularly in the case of vectors).
1685   Value *X;
1686   if (match(Cast, m_OneUse(m_ZExt(m_Value(X))))) {
1687     Constant *TruncC = ConstantExpr::getTrunc(C, SrcTy);
1688     Constant *ZextTruncC = ConstantExpr::getZExt(TruncC, DestTy);
1689     if (ZextTruncC == C) {
1690       // LogicOpc (zext X), C --> zext (LogicOpc X, C)
1691       Value *NewOp = Builder.CreateBinOp(LogicOpc, X, TruncC);
1692       return new ZExtInst(NewOp, DestTy);
1693     }
1694   }
1695 
1696   if (match(Cast, m_OneUse(m_SExt(m_Value(X))))) {
1697     Constant *TruncC = ConstantExpr::getTrunc(C, SrcTy);
1698     Constant *SextTruncC = ConstantExpr::getSExt(TruncC, DestTy);
1699     if (SextTruncC == C) {
1700       // LogicOpc (sext X), C --> sext (LogicOpc X, C)
1701       Value *NewOp = Builder.CreateBinOp(LogicOpc, X, TruncC);
1702       return new SExtInst(NewOp, DestTy);
1703     }
1704   }
1705 
1706   return nullptr;
1707 }
1708 
1709 /// Fold {and,or,xor} (cast X), Y.
1710 Instruction *InstCombinerImpl::foldCastedBitwiseLogic(BinaryOperator &I) {
1711   auto LogicOpc = I.getOpcode();
1712   assert(I.isBitwiseLogicOp() && "Unexpected opcode for bitwise logic folding");
1713 
1714   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1715 
1716   // fold bitwise(A >> BW - 1, zext(icmp))     (BW is the scalar bits of the
1717   // type of A)
1718   //   -> bitwise(zext(A < 0), zext(icmp))
1719   //   -> zext(bitwise(A < 0, icmp))
1720   auto FoldBitwiseICmpZeroWithICmp = [&](Value *Op0,
1721                                          Value *Op1) -> Instruction * {
1722     ICmpInst::Predicate Pred;
1723     Value *A;
1724     bool IsMatched =
1725         match(Op0,
1726               m_OneUse(m_LShr(
1727                   m_Value(A),
1728                   m_SpecificInt(Op0->getType()->getScalarSizeInBits() - 1)))) &&
1729         match(Op1, m_OneUse(m_ZExt(m_ICmp(Pred, m_Value(), m_Value()))));
1730 
1731     if (!IsMatched)
1732       return nullptr;
1733 
1734     auto *ICmpL =
1735         Builder.CreateICmpSLT(A, Constant::getNullValue(A->getType()));
1736     auto *ICmpR = cast<ZExtInst>(Op1)->getOperand(0);
1737     auto *BitwiseOp = Builder.CreateBinOp(LogicOpc, ICmpL, ICmpR);
1738 
1739     return new ZExtInst(BitwiseOp, Op0->getType());
1740   };
1741 
1742   if (auto *Ret = FoldBitwiseICmpZeroWithICmp(Op0, Op1))
1743     return Ret;
1744 
1745   if (auto *Ret = FoldBitwiseICmpZeroWithICmp(Op1, Op0))
1746     return Ret;
1747 
1748   CastInst *Cast0 = dyn_cast<CastInst>(Op0);
1749   if (!Cast0)
1750     return nullptr;
1751 
1752   // This must be a cast from an integer or integer vector source type to allow
1753   // transformation of the logic operation to the source type.
1754   Type *DestTy = I.getType();
1755   Type *SrcTy = Cast0->getSrcTy();
1756   if (!SrcTy->isIntOrIntVectorTy())
1757     return nullptr;
1758 
1759   if (Instruction *Ret = foldLogicCastConstant(I, Cast0, Builder))
1760     return Ret;
1761 
1762   CastInst *Cast1 = dyn_cast<CastInst>(Op1);
1763   if (!Cast1)
1764     return nullptr;
1765 
1766   // Both operands of the logic operation are casts. The casts must be the
1767   // same kind for reduction.
1768   Instruction::CastOps CastOpcode = Cast0->getOpcode();
1769   if (CastOpcode != Cast1->getOpcode())
1770     return nullptr;
1771 
1772   // If the source types do not match, but the casts are matching extends, we
1773   // can still narrow the logic op.
1774   if (SrcTy != Cast1->getSrcTy()) {
1775     Value *X, *Y;
1776     if (match(Cast0, m_OneUse(m_ZExtOrSExt(m_Value(X)))) &&
1777         match(Cast1, m_OneUse(m_ZExtOrSExt(m_Value(Y))))) {
1778       // Cast the narrower source to the wider source type.
1779       unsigned XNumBits = X->getType()->getScalarSizeInBits();
1780       unsigned YNumBits = Y->getType()->getScalarSizeInBits();
1781       if (XNumBits < YNumBits)
1782         X = Builder.CreateCast(CastOpcode, X, Y->getType());
1783       else
1784         Y = Builder.CreateCast(CastOpcode, Y, X->getType());
1785       // Do the logic op in the intermediate width, then widen more.
1786       Value *NarrowLogic = Builder.CreateBinOp(LogicOpc, X, Y);
1787       return CastInst::Create(CastOpcode, NarrowLogic, DestTy);
1788     }
1789 
1790     // Give up for other cast opcodes.
1791     return nullptr;
1792   }
1793 
1794   Value *Cast0Src = Cast0->getOperand(0);
1795   Value *Cast1Src = Cast1->getOperand(0);
1796 
1797   // fold logic(cast(A), cast(B)) -> cast(logic(A, B))
1798   if ((Cast0->hasOneUse() || Cast1->hasOneUse()) &&
1799       shouldOptimizeCast(Cast0) && shouldOptimizeCast(Cast1)) {
1800     Value *NewOp = Builder.CreateBinOp(LogicOpc, Cast0Src, Cast1Src,
1801                                        I.getName());
1802     return CastInst::Create(CastOpcode, NewOp, DestTy);
1803   }
1804 
1805   // For now, only 'and'/'or' have optimizations after this.
1806   if (LogicOpc == Instruction::Xor)
1807     return nullptr;
1808 
1809   // If this is logic(cast(icmp), cast(icmp)), try to fold this even if the
1810   // cast is otherwise not optimizable.  This happens for vector sexts.
1811   ICmpInst *ICmp0 = dyn_cast<ICmpInst>(Cast0Src);
1812   ICmpInst *ICmp1 = dyn_cast<ICmpInst>(Cast1Src);
1813   if (ICmp0 && ICmp1) {
1814     if (Value *Res =
1815             foldAndOrOfICmps(ICmp0, ICmp1, I, LogicOpc == Instruction::And))
1816       return CastInst::Create(CastOpcode, Res, DestTy);
1817     return nullptr;
1818   }
1819 
1820   // If this is logic(cast(fcmp), cast(fcmp)), try to fold this even if the
1821   // cast is otherwise not optimizable.  This happens for vector sexts.
1822   FCmpInst *FCmp0 = dyn_cast<FCmpInst>(Cast0Src);
1823   FCmpInst *FCmp1 = dyn_cast<FCmpInst>(Cast1Src);
1824   if (FCmp0 && FCmp1)
1825     if (Value *R = foldLogicOfFCmps(FCmp0, FCmp1, LogicOpc == Instruction::And))
1826       return CastInst::Create(CastOpcode, R, DestTy);
1827 
1828   return nullptr;
1829 }
1830 
1831 static Instruction *foldAndToXor(BinaryOperator &I,
1832                                  InstCombiner::BuilderTy &Builder) {
1833   assert(I.getOpcode() == Instruction::And);
1834   Value *Op0 = I.getOperand(0);
1835   Value *Op1 = I.getOperand(1);
1836   Value *A, *B;
1837 
1838   // Operand complexity canonicalization guarantees that the 'or' is Op0.
1839   // (A | B) & ~(A & B) --> A ^ B
1840   // (A | B) & ~(B & A) --> A ^ B
1841   if (match(&I, m_BinOp(m_Or(m_Value(A), m_Value(B)),
1842                         m_Not(m_c_And(m_Deferred(A), m_Deferred(B))))))
1843     return BinaryOperator::CreateXor(A, B);
1844 
1845   // (A | ~B) & (~A | B) --> ~(A ^ B)
1846   // (A | ~B) & (B | ~A) --> ~(A ^ B)
1847   // (~B | A) & (~A | B) --> ~(A ^ B)
1848   // (~B | A) & (B | ~A) --> ~(A ^ B)
1849   if (Op0->hasOneUse() || Op1->hasOneUse())
1850     if (match(&I, m_BinOp(m_c_Or(m_Value(A), m_Not(m_Value(B))),
1851                           m_c_Or(m_Not(m_Deferred(A)), m_Deferred(B)))))
1852       return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
1853 
1854   return nullptr;
1855 }
1856 
1857 static Instruction *foldOrToXor(BinaryOperator &I,
1858                                 InstCombiner::BuilderTy &Builder) {
1859   assert(I.getOpcode() == Instruction::Or);
1860   Value *Op0 = I.getOperand(0);
1861   Value *Op1 = I.getOperand(1);
1862   Value *A, *B;
1863 
1864   // Operand complexity canonicalization guarantees that the 'and' is Op0.
1865   // (A & B) | ~(A | B) --> ~(A ^ B)
1866   // (A & B) | ~(B | A) --> ~(A ^ B)
1867   if (Op0->hasOneUse() || Op1->hasOneUse())
1868     if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
1869         match(Op1, m_Not(m_c_Or(m_Specific(A), m_Specific(B)))))
1870       return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
1871 
1872   // Operand complexity canonicalization guarantees that the 'xor' is Op0.
1873   // (A ^ B) | ~(A | B) --> ~(A & B)
1874   // (A ^ B) | ~(B | A) --> ~(A & B)
1875   if (Op0->hasOneUse() || Op1->hasOneUse())
1876     if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
1877         match(Op1, m_Not(m_c_Or(m_Specific(A), m_Specific(B)))))
1878       return BinaryOperator::CreateNot(Builder.CreateAnd(A, B));
1879 
1880   // (A & ~B) | (~A & B) --> A ^ B
1881   // (A & ~B) | (B & ~A) --> A ^ B
1882   // (~B & A) | (~A & B) --> A ^ B
1883   // (~B & A) | (B & ~A) --> A ^ B
1884   if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
1885       match(Op1, m_c_And(m_Not(m_Specific(A)), m_Specific(B))))
1886     return BinaryOperator::CreateXor(A, B);
1887 
1888   return nullptr;
1889 }
1890 
1891 /// Return true if a constant shift amount is always less than the specified
1892 /// bit-width. If not, the shift could create poison in the narrower type.
1893 static bool canNarrowShiftAmt(Constant *C, unsigned BitWidth) {
1894   APInt Threshold(C->getType()->getScalarSizeInBits(), BitWidth);
1895   return match(C, m_SpecificInt_ICMP(ICmpInst::ICMP_ULT, Threshold));
1896 }
1897 
1898 /// Try to use narrower ops (sink zext ops) for an 'and' with binop operand and
1899 /// a common zext operand: and (binop (zext X), C), (zext X).
1900 Instruction *InstCombinerImpl::narrowMaskedBinOp(BinaryOperator &And) {
1901   // This transform could also apply to {or, and, xor}, but there are better
1902   // folds for those cases, so we don't expect those patterns here. AShr is not
1903   // handled because it should always be transformed to LShr in this sequence.
1904   // The subtract transform is different because it has a constant on the left.
1905   // Add/mul commute the constant to RHS; sub with constant RHS becomes add.
1906   Value *Op0 = And.getOperand(0), *Op1 = And.getOperand(1);
1907   Constant *C;
1908   if (!match(Op0, m_OneUse(m_Add(m_Specific(Op1), m_Constant(C)))) &&
1909       !match(Op0, m_OneUse(m_Mul(m_Specific(Op1), m_Constant(C)))) &&
1910       !match(Op0, m_OneUse(m_LShr(m_Specific(Op1), m_Constant(C)))) &&
1911       !match(Op0, m_OneUse(m_Shl(m_Specific(Op1), m_Constant(C)))) &&
1912       !match(Op0, m_OneUse(m_Sub(m_Constant(C), m_Specific(Op1)))))
1913     return nullptr;
1914 
1915   Value *X;
1916   if (!match(Op1, m_ZExt(m_Value(X))) || Op1->hasNUsesOrMore(3))
1917     return nullptr;
1918 
1919   Type *Ty = And.getType();
1920   if (!isa<VectorType>(Ty) && !shouldChangeType(Ty, X->getType()))
1921     return nullptr;
1922 
1923   // If we're narrowing a shift, the shift amount must be safe (less than the
1924   // width) in the narrower type. If the shift amount is greater, instsimplify
1925   // usually handles that case, but we can't guarantee/assert it.
1926   Instruction::BinaryOps Opc = cast<BinaryOperator>(Op0)->getOpcode();
1927   if (Opc == Instruction::LShr || Opc == Instruction::Shl)
1928     if (!canNarrowShiftAmt(C, X->getType()->getScalarSizeInBits()))
1929       return nullptr;
1930 
1931   // and (sub C, (zext X)), (zext X) --> zext (and (sub C', X), X)
1932   // and (binop (zext X), C), (zext X) --> zext (and (binop X, C'), X)
1933   Value *NewC = ConstantExpr::getTrunc(C, X->getType());
1934   Value *NewBO = Opc == Instruction::Sub ? Builder.CreateBinOp(Opc, NewC, X)
1935                                          : Builder.CreateBinOp(Opc, X, NewC);
1936   return new ZExtInst(Builder.CreateAnd(NewBO, X), Ty);
1937 }
1938 
1939 /// Try folding relatively complex patterns for both And and Or operations
1940 /// with all And and Or swapped.
1941 static Instruction *foldComplexAndOrPatterns(BinaryOperator &I,
1942                                              InstCombiner::BuilderTy &Builder) {
1943   const Instruction::BinaryOps Opcode = I.getOpcode();
1944   assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1945 
1946   // Flip the logic operation.
1947   const Instruction::BinaryOps FlippedOpcode =
1948       (Opcode == Instruction::And) ? Instruction::Or : Instruction::And;
1949 
1950   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1951   Value *A, *B, *C, *X, *Y, *Dummy;
1952 
1953   // Match following expressions:
1954   // (~(A | B) & C)
1955   // (~(A & B) | C)
1956   // Captures X = ~(A | B) or ~(A & B)
1957   const auto matchNotOrAnd =
1958       [Opcode, FlippedOpcode](Value *Op, auto m_A, auto m_B, auto m_C,
1959                               Value *&X, bool CountUses = false) -> bool {
1960     if (CountUses && !Op->hasOneUse())
1961       return false;
1962 
1963     if (match(Op, m_c_BinOp(FlippedOpcode,
1964                             m_CombineAnd(m_Value(X),
1965                                          m_Not(m_c_BinOp(Opcode, m_A, m_B))),
1966                             m_C)))
1967       return !CountUses || X->hasOneUse();
1968 
1969     return false;
1970   };
1971 
1972   // (~(A | B) & C) | ... --> ...
1973   // (~(A & B) | C) & ... --> ...
1974   // TODO: One use checks are conservative. We just need to check that a total
1975   //       number of multiple used values does not exceed reduction
1976   //       in operations.
1977   if (matchNotOrAnd(Op0, m_Value(A), m_Value(B), m_Value(C), X)) {
1978     // (~(A | B) & C) | (~(A | C) & B) --> (B ^ C) & ~A
1979     // (~(A & B) | C) & (~(A & C) | B) --> ~((B ^ C) & A)
1980     if (matchNotOrAnd(Op1, m_Specific(A), m_Specific(C), m_Specific(B), Dummy,
1981                       true)) {
1982       Value *Xor = Builder.CreateXor(B, C);
1983       return (Opcode == Instruction::Or)
1984                  ? BinaryOperator::CreateAnd(Xor, Builder.CreateNot(A))
1985                  : BinaryOperator::CreateNot(Builder.CreateAnd(Xor, A));
1986     }
1987 
1988     // (~(A | B) & C) | (~(B | C) & A) --> (A ^ C) & ~B
1989     // (~(A & B) | C) & (~(B & C) | A) --> ~((A ^ C) & B)
1990     if (matchNotOrAnd(Op1, m_Specific(B), m_Specific(C), m_Specific(A), Dummy,
1991                       true)) {
1992       Value *Xor = Builder.CreateXor(A, C);
1993       return (Opcode == Instruction::Or)
1994                  ? BinaryOperator::CreateAnd(Xor, Builder.CreateNot(B))
1995                  : BinaryOperator::CreateNot(Builder.CreateAnd(Xor, B));
1996     }
1997 
1998     // (~(A | B) & C) | ~(A | C) --> ~((B & C) | A)
1999     // (~(A & B) | C) & ~(A & C) --> ~((B | C) & A)
2000     if (match(Op1, m_OneUse(m_Not(m_OneUse(
2001                        m_c_BinOp(Opcode, m_Specific(A), m_Specific(C)))))))
2002       return BinaryOperator::CreateNot(Builder.CreateBinOp(
2003           Opcode, Builder.CreateBinOp(FlippedOpcode, B, C), A));
2004 
2005     // (~(A | B) & C) | ~(B | C) --> ~((A & C) | B)
2006     // (~(A & B) | C) & ~(B & C) --> ~((A | C) & B)
2007     if (match(Op1, m_OneUse(m_Not(m_OneUse(
2008                        m_c_BinOp(Opcode, m_Specific(B), m_Specific(C)))))))
2009       return BinaryOperator::CreateNot(Builder.CreateBinOp(
2010           Opcode, Builder.CreateBinOp(FlippedOpcode, A, C), B));
2011 
2012     // (~(A | B) & C) | ~(C | (A ^ B)) --> ~((A | B) & (C | (A ^ B)))
2013     // Note, the pattern with swapped and/or is not handled because the
2014     // result is more undefined than a source:
2015     // (~(A & B) | C) & ~(C & (A ^ B)) --> (A ^ B ^ C) | ~(A | C) is invalid.
2016     if (Opcode == Instruction::Or && Op0->hasOneUse() &&
2017         match(Op1, m_OneUse(m_Not(m_CombineAnd(
2018                        m_Value(Y),
2019                        m_c_BinOp(Opcode, m_Specific(C),
2020                                  m_c_Xor(m_Specific(A), m_Specific(B)))))))) {
2021       // X = ~(A | B)
2022       // Y = (C | (A ^ B)
2023       Value *Or = cast<BinaryOperator>(X)->getOperand(0);
2024       return BinaryOperator::CreateNot(Builder.CreateAnd(Or, Y));
2025     }
2026   }
2027 
2028   // (~A & B & C) | ... --> ...
2029   // (~A | B | C) | ... --> ...
2030   // TODO: One use checks are conservative. We just need to check that a total
2031   //       number of multiple used values does not exceed reduction
2032   //       in operations.
2033   if (match(Op0,
2034             m_OneUse(m_c_BinOp(FlippedOpcode,
2035                                m_BinOp(FlippedOpcode, m_Value(B), m_Value(C)),
2036                                m_CombineAnd(m_Value(X), m_Not(m_Value(A)))))) ||
2037       match(Op0, m_OneUse(m_c_BinOp(
2038                      FlippedOpcode,
2039                      m_c_BinOp(FlippedOpcode, m_Value(C),
2040                                m_CombineAnd(m_Value(X), m_Not(m_Value(A)))),
2041                      m_Value(B))))) {
2042     // X = ~A
2043     // (~A & B & C) | ~(A | B | C) --> ~(A | (B ^ C))
2044     // (~A | B | C) & ~(A & B & C) --> (~A | (B ^ C))
2045     if (match(Op1, m_OneUse(m_Not(m_c_BinOp(
2046                        Opcode, m_c_BinOp(Opcode, m_Specific(A), m_Specific(B)),
2047                        m_Specific(C))))) ||
2048         match(Op1, m_OneUse(m_Not(m_c_BinOp(
2049                        Opcode, m_c_BinOp(Opcode, m_Specific(B), m_Specific(C)),
2050                        m_Specific(A))))) ||
2051         match(Op1, m_OneUse(m_Not(m_c_BinOp(
2052                        Opcode, m_c_BinOp(Opcode, m_Specific(A), m_Specific(C)),
2053                        m_Specific(B)))))) {
2054       Value *Xor = Builder.CreateXor(B, C);
2055       return (Opcode == Instruction::Or)
2056                  ? BinaryOperator::CreateNot(Builder.CreateOr(Xor, A))
2057                  : BinaryOperator::CreateOr(Xor, X);
2058     }
2059 
2060     // (~A & B & C) | ~(A | B) --> (C | ~B) & ~A
2061     // (~A | B | C) & ~(A & B) --> (C & ~B) | ~A
2062     if (match(Op1, m_OneUse(m_Not(m_OneUse(
2063                        m_c_BinOp(Opcode, m_Specific(A), m_Specific(B)))))))
2064       return BinaryOperator::Create(
2065           FlippedOpcode, Builder.CreateBinOp(Opcode, C, Builder.CreateNot(B)),
2066           X);
2067 
2068     // (~A & B & C) | ~(A | C) --> (B | ~C) & ~A
2069     // (~A | B | C) & ~(A & C) --> (B & ~C) | ~A
2070     if (match(Op1, m_OneUse(m_Not(m_OneUse(
2071                        m_c_BinOp(Opcode, m_Specific(A), m_Specific(C)))))))
2072       return BinaryOperator::Create(
2073           FlippedOpcode, Builder.CreateBinOp(Opcode, B, Builder.CreateNot(C)),
2074           X);
2075   }
2076 
2077   return nullptr;
2078 }
2079 
2080 /// Try to reassociate a pair of binops so that values with one use only are
2081 /// part of the same instruction. This may enable folds that are limited with
2082 /// multi-use restrictions and makes it more likely to match other patterns that
2083 /// are looking for a common operand.
2084 static Instruction *reassociateForUses(BinaryOperator &BO,
2085                                        InstCombinerImpl::BuilderTy &Builder) {
2086   Instruction::BinaryOps Opcode = BO.getOpcode();
2087   Value *X, *Y, *Z;
2088   if (match(&BO,
2089             m_c_BinOp(Opcode, m_OneUse(m_BinOp(Opcode, m_Value(X), m_Value(Y))),
2090                       m_OneUse(m_Value(Z))))) {
2091     if (!isa<Constant>(X) && !isa<Constant>(Y) && !isa<Constant>(Z)) {
2092       // (X op Y) op Z --> (Y op Z) op X
2093       if (!X->hasOneUse()) {
2094         Value *YZ = Builder.CreateBinOp(Opcode, Y, Z);
2095         return BinaryOperator::Create(Opcode, YZ, X);
2096       }
2097       // (X op Y) op Z --> (X op Z) op Y
2098       if (!Y->hasOneUse()) {
2099         Value *XZ = Builder.CreateBinOp(Opcode, X, Z);
2100         return BinaryOperator::Create(Opcode, XZ, Y);
2101       }
2102     }
2103   }
2104 
2105   return nullptr;
2106 }
2107 
2108 // Match
2109 // (X + C2) | C
2110 // (X + C2) ^ C
2111 // (X + C2) & C
2112 // and convert to do the bitwise logic first:
2113 // (X | C) + C2
2114 // (X ^ C) + C2
2115 // (X & C) + C2
2116 // iff bits affected by logic op are lower than last bit affected by math op
2117 static Instruction *canonicalizeLogicFirst(BinaryOperator &I,
2118                                            InstCombiner::BuilderTy &Builder) {
2119   Type *Ty = I.getType();
2120   Instruction::BinaryOps OpC = I.getOpcode();
2121   Value *Op0 = I.getOperand(0);
2122   Value *Op1 = I.getOperand(1);
2123   Value *X;
2124   const APInt *C, *C2;
2125 
2126   if (!(match(Op0, m_OneUse(m_Add(m_Value(X), m_APInt(C2)))) &&
2127         match(Op1, m_APInt(C))))
2128     return nullptr;
2129 
2130   unsigned Width = Ty->getScalarSizeInBits();
2131   unsigned LastOneMath = Width - C2->countr_zero();
2132 
2133   switch (OpC) {
2134   case Instruction::And:
2135     if (C->countl_one() < LastOneMath)
2136       return nullptr;
2137     break;
2138   case Instruction::Xor:
2139   case Instruction::Or:
2140     if (C->countl_zero() < LastOneMath)
2141       return nullptr;
2142     break;
2143   default:
2144     llvm_unreachable("Unexpected BinaryOp!");
2145   }
2146 
2147   Value *NewBinOp = Builder.CreateBinOp(OpC, X, ConstantInt::get(Ty, *C));
2148   return BinaryOperator::CreateWithCopiedFlags(Instruction::Add, NewBinOp,
2149                                                ConstantInt::get(Ty, *C2), Op0);
2150 }
2151 
2152 // binop(shift(ShiftedC1, ShAmt), shift(ShiftedC2, add(ShAmt, AddC))) ->
2153 // shift(binop(ShiftedC1, shift(ShiftedC2, AddC)), ShAmt)
2154 // where both shifts are the same and AddC is a valid shift amount.
2155 Instruction *InstCombinerImpl::foldBinOpOfDisplacedShifts(BinaryOperator &I) {
2156   assert((I.isBitwiseLogicOp() || I.getOpcode() == Instruction::Add) &&
2157          "Unexpected opcode");
2158 
2159   Value *ShAmt;
2160   Constant *ShiftedC1, *ShiftedC2, *AddC;
2161   Type *Ty = I.getType();
2162   unsigned BitWidth = Ty->getScalarSizeInBits();
2163   if (!match(&I,
2164              m_c_BinOp(m_Shift(m_ImmConstant(ShiftedC1), m_Value(ShAmt)),
2165                        m_Shift(m_ImmConstant(ShiftedC2),
2166                                m_Add(m_Deferred(ShAmt), m_ImmConstant(AddC))))))
2167     return nullptr;
2168 
2169   // Make sure the add constant is a valid shift amount.
2170   if (!match(AddC,
2171              m_SpecificInt_ICMP(ICmpInst::ICMP_ULT, APInt(BitWidth, BitWidth))))
2172     return nullptr;
2173 
2174   // Avoid constant expressions.
2175   auto *Op0Inst = dyn_cast<Instruction>(I.getOperand(0));
2176   auto *Op1Inst = dyn_cast<Instruction>(I.getOperand(1));
2177   if (!Op0Inst || !Op1Inst)
2178     return nullptr;
2179 
2180   // Both shifts must be the same.
2181   Instruction::BinaryOps ShiftOp =
2182       static_cast<Instruction::BinaryOps>(Op0Inst->getOpcode());
2183   if (ShiftOp != Op1Inst->getOpcode())
2184     return nullptr;
2185 
2186   // For adds, only left shifts are supported.
2187   if (I.getOpcode() == Instruction::Add && ShiftOp != Instruction::Shl)
2188     return nullptr;
2189 
2190   Value *NewC = Builder.CreateBinOp(
2191       I.getOpcode(), ShiftedC1, Builder.CreateBinOp(ShiftOp, ShiftedC2, AddC));
2192   return BinaryOperator::Create(ShiftOp, NewC, ShAmt);
2193 }
2194 
2195 // FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
2196 // here. We should standardize that construct where it is needed or choose some
2197 // other way to ensure that commutated variants of patterns are not missed.
2198 Instruction *InstCombinerImpl::visitAnd(BinaryOperator &I) {
2199   Type *Ty = I.getType();
2200 
2201   if (Value *V = simplifyAndInst(I.getOperand(0), I.getOperand(1),
2202                                  SQ.getWithInstruction(&I)))
2203     return replaceInstUsesWith(I, V);
2204 
2205   if (SimplifyAssociativeOrCommutative(I))
2206     return &I;
2207 
2208   if (Instruction *X = foldVectorBinop(I))
2209     return X;
2210 
2211   if (Instruction *Phi = foldBinopWithPhiOperands(I))
2212     return Phi;
2213 
2214   // See if we can simplify any instructions used by the instruction whose sole
2215   // purpose is to compute bits we don't care about.
2216   if (SimplifyDemandedInstructionBits(I))
2217     return &I;
2218 
2219   // Do this before using distributive laws to catch simple and/or/not patterns.
2220   if (Instruction *Xor = foldAndToXor(I, Builder))
2221     return Xor;
2222 
2223   if (Instruction *X = foldComplexAndOrPatterns(I, Builder))
2224     return X;
2225 
2226   // (A|B)&(A|C) -> A|(B&C) etc
2227   if (Value *V = foldUsingDistributiveLaws(I))
2228     return replaceInstUsesWith(I, V);
2229 
2230   if (Value *V = SimplifyBSwap(I, Builder))
2231     return replaceInstUsesWith(I, V);
2232 
2233   if (Instruction *R = foldBinOpShiftWithShift(I))
2234     return R;
2235 
2236   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2237 
2238   Value *X, *Y;
2239   if (match(Op0, m_OneUse(m_LogicalShift(m_One(), m_Value(X)))) &&
2240       match(Op1, m_One())) {
2241     // (1 << X) & 1 --> zext(X == 0)
2242     // (1 >> X) & 1 --> zext(X == 0)
2243     Value *IsZero = Builder.CreateICmpEQ(X, ConstantInt::get(Ty, 0));
2244     return new ZExtInst(IsZero, Ty);
2245   }
2246 
2247   // (-(X & 1)) & Y --> (X & 1) == 0 ? 0 : Y
2248   Value *Neg;
2249   if (match(&I,
2250             m_c_And(m_CombineAnd(m_Value(Neg),
2251                                  m_OneUse(m_Neg(m_And(m_Value(), m_One())))),
2252                     m_Value(Y)))) {
2253     Value *Cmp = Builder.CreateIsNull(Neg);
2254     return SelectInst::Create(Cmp, ConstantInt::getNullValue(Ty), Y);
2255   }
2256 
2257   const APInt *C;
2258   if (match(Op1, m_APInt(C))) {
2259     const APInt *XorC;
2260     if (match(Op0, m_OneUse(m_Xor(m_Value(X), m_APInt(XorC))))) {
2261       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2262       Constant *NewC = ConstantInt::get(Ty, *C & *XorC);
2263       Value *And = Builder.CreateAnd(X, Op1);
2264       And->takeName(Op0);
2265       return BinaryOperator::CreateXor(And, NewC);
2266     }
2267 
2268     const APInt *OrC;
2269     if (match(Op0, m_OneUse(m_Or(m_Value(X), m_APInt(OrC))))) {
2270       // (X | C1) & C2 --> (X & C2^(C1&C2)) | (C1&C2)
2271       // NOTE: This reduces the number of bits set in the & mask, which
2272       // can expose opportunities for store narrowing for scalars.
2273       // NOTE: SimplifyDemandedBits should have already removed bits from C1
2274       // that aren't set in C2. Meaning we can replace (C1&C2) with C1 in
2275       // above, but this feels safer.
2276       APInt Together = *C & *OrC;
2277       Value *And = Builder.CreateAnd(X, ConstantInt::get(Ty, Together ^ *C));
2278       And->takeName(Op0);
2279       return BinaryOperator::CreateOr(And, ConstantInt::get(Ty, Together));
2280     }
2281 
2282     unsigned Width = Ty->getScalarSizeInBits();
2283     const APInt *ShiftC;
2284     if (match(Op0, m_OneUse(m_SExt(m_AShr(m_Value(X), m_APInt(ShiftC))))) &&
2285         ShiftC->ult(Width)) {
2286       if (*C == APInt::getLowBitsSet(Width, Width - ShiftC->getZExtValue())) {
2287         // We are clearing high bits that were potentially set by sext+ashr:
2288         // and (sext (ashr X, ShiftC)), C --> lshr (sext X), ShiftC
2289         Value *Sext = Builder.CreateSExt(X, Ty);
2290         Constant *ShAmtC = ConstantInt::get(Ty, ShiftC->zext(Width));
2291         return BinaryOperator::CreateLShr(Sext, ShAmtC);
2292       }
2293     }
2294 
2295     // If this 'and' clears the sign-bits added by ashr, replace with lshr:
2296     // and (ashr X, ShiftC), C --> lshr X, ShiftC
2297     if (match(Op0, m_AShr(m_Value(X), m_APInt(ShiftC))) && ShiftC->ult(Width) &&
2298         C->isMask(Width - ShiftC->getZExtValue()))
2299       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, *ShiftC));
2300 
2301     const APInt *AddC;
2302     if (match(Op0, m_Add(m_Value(X), m_APInt(AddC)))) {
2303       // If we add zeros to every bit below a mask, the add has no effect:
2304       // (X + AddC) & LowMaskC --> X & LowMaskC
2305       unsigned Ctlz = C->countl_zero();
2306       APInt LowMask(APInt::getLowBitsSet(Width, Width - Ctlz));
2307       if ((*AddC & LowMask).isZero())
2308         return BinaryOperator::CreateAnd(X, Op1);
2309 
2310       // If we are masking the result of the add down to exactly one bit and
2311       // the constant we are adding has no bits set below that bit, then the
2312       // add is flipping a single bit. Example:
2313       // (X + 4) & 4 --> (X & 4) ^ 4
2314       if (Op0->hasOneUse() && C->isPowerOf2() && (*AddC & (*C - 1)) == 0) {
2315         assert((*C & *AddC) != 0 && "Expected common bit");
2316         Value *NewAnd = Builder.CreateAnd(X, Op1);
2317         return BinaryOperator::CreateXor(NewAnd, Op1);
2318       }
2319     }
2320 
2321     // ((C1 OP zext(X)) & C2) -> zext((C1 OP X) & C2) if C2 fits in the
2322     // bitwidth of X and OP behaves well when given trunc(C1) and X.
2323     auto isNarrowableBinOpcode = [](BinaryOperator *B) {
2324       switch (B->getOpcode()) {
2325       case Instruction::Xor:
2326       case Instruction::Or:
2327       case Instruction::Mul:
2328       case Instruction::Add:
2329       case Instruction::Sub:
2330         return true;
2331       default:
2332         return false;
2333       }
2334     };
2335     BinaryOperator *BO;
2336     if (match(Op0, m_OneUse(m_BinOp(BO))) && isNarrowableBinOpcode(BO)) {
2337       Instruction::BinaryOps BOpcode = BO->getOpcode();
2338       Value *X;
2339       const APInt *C1;
2340       // TODO: The one-use restrictions could be relaxed a little if the AND
2341       // is going to be removed.
2342       // Try to narrow the 'and' and a binop with constant operand:
2343       // and (bo (zext X), C1), C --> zext (and (bo X, TruncC1), TruncC)
2344       if (match(BO, m_c_BinOp(m_OneUse(m_ZExt(m_Value(X))), m_APInt(C1))) &&
2345           C->isIntN(X->getType()->getScalarSizeInBits())) {
2346         unsigned XWidth = X->getType()->getScalarSizeInBits();
2347         Constant *TruncC1 = ConstantInt::get(X->getType(), C1->trunc(XWidth));
2348         Value *BinOp = isa<ZExtInst>(BO->getOperand(0))
2349                            ? Builder.CreateBinOp(BOpcode, X, TruncC1)
2350                            : Builder.CreateBinOp(BOpcode, TruncC1, X);
2351         Constant *TruncC = ConstantInt::get(X->getType(), C->trunc(XWidth));
2352         Value *And = Builder.CreateAnd(BinOp, TruncC);
2353         return new ZExtInst(And, Ty);
2354       }
2355 
2356       // Similar to above: if the mask matches the zext input width, then the
2357       // 'and' can be eliminated, so we can truncate the other variable op:
2358       // and (bo (zext X), Y), C --> zext (bo X, (trunc Y))
2359       if (isa<Instruction>(BO->getOperand(0)) &&
2360           match(BO->getOperand(0), m_OneUse(m_ZExt(m_Value(X)))) &&
2361           C->isMask(X->getType()->getScalarSizeInBits())) {
2362         Y = BO->getOperand(1);
2363         Value *TrY = Builder.CreateTrunc(Y, X->getType(), Y->getName() + ".tr");
2364         Value *NewBO =
2365             Builder.CreateBinOp(BOpcode, X, TrY, BO->getName() + ".narrow");
2366         return new ZExtInst(NewBO, Ty);
2367       }
2368       // and (bo Y, (zext X)), C --> zext (bo (trunc Y), X)
2369       if (isa<Instruction>(BO->getOperand(1)) &&
2370           match(BO->getOperand(1), m_OneUse(m_ZExt(m_Value(X)))) &&
2371           C->isMask(X->getType()->getScalarSizeInBits())) {
2372         Y = BO->getOperand(0);
2373         Value *TrY = Builder.CreateTrunc(Y, X->getType(), Y->getName() + ".tr");
2374         Value *NewBO =
2375             Builder.CreateBinOp(BOpcode, TrY, X, BO->getName() + ".narrow");
2376         return new ZExtInst(NewBO, Ty);
2377       }
2378     }
2379 
2380     // This is intentionally placed after the narrowing transforms for
2381     // efficiency (transform directly to the narrow logic op if possible).
2382     // If the mask is only needed on one incoming arm, push the 'and' op up.
2383     if (match(Op0, m_OneUse(m_Xor(m_Value(X), m_Value(Y)))) ||
2384         match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2385       APInt NotAndMask(~(*C));
2386       BinaryOperator::BinaryOps BinOp = cast<BinaryOperator>(Op0)->getOpcode();
2387       if (MaskedValueIsZero(X, NotAndMask, 0, &I)) {
2388         // Not masking anything out for the LHS, move mask to RHS.
2389         // and ({x}or X, Y), C --> {x}or X, (and Y, C)
2390         Value *NewRHS = Builder.CreateAnd(Y, Op1, Y->getName() + ".masked");
2391         return BinaryOperator::Create(BinOp, X, NewRHS);
2392       }
2393       if (!isa<Constant>(Y) && MaskedValueIsZero(Y, NotAndMask, 0, &I)) {
2394         // Not masking anything out for the RHS, move mask to LHS.
2395         // and ({x}or X, Y), C --> {x}or (and X, C), Y
2396         Value *NewLHS = Builder.CreateAnd(X, Op1, X->getName() + ".masked");
2397         return BinaryOperator::Create(BinOp, NewLHS, Y);
2398       }
2399     }
2400 
2401     // When the mask is a power-of-2 constant and op0 is a shifted-power-of-2
2402     // constant, test if the shift amount equals the offset bit index:
2403     // (ShiftC << X) & C --> X == (log2(C) - log2(ShiftC)) ? C : 0
2404     // (ShiftC >> X) & C --> X == (log2(ShiftC) - log2(C)) ? C : 0
2405     if (C->isPowerOf2() &&
2406         match(Op0, m_OneUse(m_LogicalShift(m_Power2(ShiftC), m_Value(X))))) {
2407       int Log2ShiftC = ShiftC->exactLogBase2();
2408       int Log2C = C->exactLogBase2();
2409       bool IsShiftLeft =
2410          cast<BinaryOperator>(Op0)->getOpcode() == Instruction::Shl;
2411       int BitNum = IsShiftLeft ? Log2C - Log2ShiftC : Log2ShiftC - Log2C;
2412       assert(BitNum >= 0 && "Expected demanded bits to handle impossible mask");
2413       Value *Cmp = Builder.CreateICmpEQ(X, ConstantInt::get(Ty, BitNum));
2414       return SelectInst::Create(Cmp, ConstantInt::get(Ty, *C),
2415                                 ConstantInt::getNullValue(Ty));
2416     }
2417 
2418     Constant *C1, *C2;
2419     const APInt *C3 = C;
2420     Value *X;
2421     if (C3->isPowerOf2()) {
2422       Constant *Log2C3 = ConstantInt::get(Ty, C3->countr_zero());
2423       if (match(Op0, m_OneUse(m_LShr(m_Shl(m_ImmConstant(C1), m_Value(X)),
2424                                      m_ImmConstant(C2)))) &&
2425           match(C1, m_Power2())) {
2426         Constant *Log2C1 = ConstantExpr::getExactLogBase2(C1);
2427         Constant *LshrC = ConstantExpr::getAdd(C2, Log2C3);
2428         KnownBits KnownLShrc = computeKnownBits(LshrC, 0, nullptr);
2429         if (KnownLShrc.getMaxValue().ult(Width)) {
2430           // iff C1,C3 is pow2 and C2 + cttz(C3) < BitWidth:
2431           // ((C1 << X) >> C2) & C3 -> X == (cttz(C3)+C2-cttz(C1)) ? C3 : 0
2432           Constant *CmpC = ConstantExpr::getSub(LshrC, Log2C1);
2433           Value *Cmp = Builder.CreateICmpEQ(X, CmpC);
2434           return SelectInst::Create(Cmp, ConstantInt::get(Ty, *C3),
2435                                     ConstantInt::getNullValue(Ty));
2436         }
2437       }
2438 
2439       if (match(Op0, m_OneUse(m_Shl(m_LShr(m_ImmConstant(C1), m_Value(X)),
2440                                     m_ImmConstant(C2)))) &&
2441           match(C1, m_Power2())) {
2442         Constant *Log2C1 = ConstantExpr::getExactLogBase2(C1);
2443         Constant *Cmp =
2444             ConstantExpr::getCompare(ICmpInst::ICMP_ULT, Log2C3, C2);
2445         if (Cmp->isZeroValue()) {
2446           // iff C1,C3 is pow2 and Log2(C3) >= C2:
2447           // ((C1 >> X) << C2) & C3 -> X == (cttz(C1)+C2-cttz(C3)) ? C3 : 0
2448           Constant *ShlC = ConstantExpr::getAdd(C2, Log2C1);
2449           Constant *CmpC = ConstantExpr::getSub(ShlC, Log2C3);
2450           Value *Cmp = Builder.CreateICmpEQ(X, CmpC);
2451           return SelectInst::Create(Cmp, ConstantInt::get(Ty, *C3),
2452                                     ConstantInt::getNullValue(Ty));
2453         }
2454       }
2455     }
2456   }
2457 
2458   if (match(&I, m_And(m_OneUse(m_Shl(m_ZExt(m_Value(X)), m_Value(Y))),
2459                       m_SignMask())) &&
2460       match(Y, m_SpecificInt_ICMP(
2461                    ICmpInst::Predicate::ICMP_EQ,
2462                    APInt(Ty->getScalarSizeInBits(),
2463                          Ty->getScalarSizeInBits() -
2464                              X->getType()->getScalarSizeInBits())))) {
2465     auto *SExt = Builder.CreateSExt(X, Ty, X->getName() + ".signext");
2466     auto *SanitizedSignMask = cast<Constant>(Op1);
2467     // We must be careful with the undef elements of the sign bit mask, however:
2468     // the mask elt can be undef iff the shift amount for that lane was undef,
2469     // otherwise we need to sanitize undef masks to zero.
2470     SanitizedSignMask = Constant::replaceUndefsWith(
2471         SanitizedSignMask, ConstantInt::getNullValue(Ty->getScalarType()));
2472     SanitizedSignMask =
2473         Constant::mergeUndefsWith(SanitizedSignMask, cast<Constant>(Y));
2474     return BinaryOperator::CreateAnd(SExt, SanitizedSignMask);
2475   }
2476 
2477   if (Instruction *Z = narrowMaskedBinOp(I))
2478     return Z;
2479 
2480   if (I.getType()->isIntOrIntVectorTy(1)) {
2481     if (auto *SI0 = dyn_cast<SelectInst>(Op0)) {
2482       if (auto *I =
2483               foldAndOrOfSelectUsingImpliedCond(Op1, *SI0, /* IsAnd */ true))
2484         return I;
2485     }
2486     if (auto *SI1 = dyn_cast<SelectInst>(Op1)) {
2487       if (auto *I =
2488               foldAndOrOfSelectUsingImpliedCond(Op0, *SI1, /* IsAnd */ true))
2489         return I;
2490     }
2491   }
2492 
2493   if (Instruction *FoldedLogic = foldBinOpIntoSelectOrPhi(I))
2494     return FoldedLogic;
2495 
2496   if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder))
2497     return DeMorgan;
2498 
2499   {
2500     Value *A, *B, *C;
2501     // A & (A ^ B) --> A & ~B
2502     if (match(Op1, m_OneUse(m_c_Xor(m_Specific(Op0), m_Value(B)))))
2503       return BinaryOperator::CreateAnd(Op0, Builder.CreateNot(B));
2504     // (A ^ B) & A --> A & ~B
2505     if (match(Op0, m_OneUse(m_c_Xor(m_Specific(Op1), m_Value(B)))))
2506       return BinaryOperator::CreateAnd(Op1, Builder.CreateNot(B));
2507 
2508     // A & ~(A ^ B) --> A & B
2509     if (match(Op1, m_Not(m_c_Xor(m_Specific(Op0), m_Value(B)))))
2510       return BinaryOperator::CreateAnd(Op0, B);
2511     // ~(A ^ B) & A --> A & B
2512     if (match(Op0, m_Not(m_c_Xor(m_Specific(Op1), m_Value(B)))))
2513       return BinaryOperator::CreateAnd(Op1, B);
2514 
2515     // (A ^ B) & ((B ^ C) ^ A) -> (A ^ B) & ~C
2516     if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
2517       if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
2518         if (Op1->hasOneUse() || isFreeToInvert(C, C->hasOneUse()))
2519           return BinaryOperator::CreateAnd(Op0, Builder.CreateNot(C));
2520 
2521     // ((A ^ C) ^ B) & (B ^ A) -> (B ^ A) & ~C
2522     if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
2523       if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
2524         if (Op0->hasOneUse() || isFreeToInvert(C, C->hasOneUse()))
2525           return BinaryOperator::CreateAnd(Op1, Builder.CreateNot(C));
2526 
2527     // (A | B) & (~A ^ B) -> A & B
2528     // (A | B) & (B ^ ~A) -> A & B
2529     // (B | A) & (~A ^ B) -> A & B
2530     // (B | A) & (B ^ ~A) -> A & B
2531     if (match(Op1, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
2532         match(Op0, m_c_Or(m_Specific(A), m_Specific(B))))
2533       return BinaryOperator::CreateAnd(A, B);
2534 
2535     // (~A ^ B) & (A | B) -> A & B
2536     // (~A ^ B) & (B | A) -> A & B
2537     // (B ^ ~A) & (A | B) -> A & B
2538     // (B ^ ~A) & (B | A) -> A & B
2539     if (match(Op0, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
2540         match(Op1, m_c_Or(m_Specific(A), m_Specific(B))))
2541       return BinaryOperator::CreateAnd(A, B);
2542 
2543     // (~A | B) & (A ^ B) -> ~A & B
2544     // (~A | B) & (B ^ A) -> ~A & B
2545     // (B | ~A) & (A ^ B) -> ~A & B
2546     // (B | ~A) & (B ^ A) -> ~A & B
2547     if (match(Op0, m_c_Or(m_Not(m_Value(A)), m_Value(B))) &&
2548         match(Op1, m_c_Xor(m_Specific(A), m_Specific(B))))
2549       return BinaryOperator::CreateAnd(Builder.CreateNot(A), B);
2550 
2551     // (A ^ B) & (~A | B) -> ~A & B
2552     // (B ^ A) & (~A | B) -> ~A & B
2553     // (A ^ B) & (B | ~A) -> ~A & B
2554     // (B ^ A) & (B | ~A) -> ~A & B
2555     if (match(Op1, m_c_Or(m_Not(m_Value(A)), m_Value(B))) &&
2556         match(Op0, m_c_Xor(m_Specific(A), m_Specific(B))))
2557       return BinaryOperator::CreateAnd(Builder.CreateNot(A), B);
2558   }
2559 
2560   {
2561     ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
2562     ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
2563     if (LHS && RHS)
2564       if (Value *Res = foldAndOrOfICmps(LHS, RHS, I, /* IsAnd */ true))
2565         return replaceInstUsesWith(I, Res);
2566 
2567     // TODO: Make this recursive; it's a little tricky because an arbitrary
2568     // number of 'and' instructions might have to be created.
2569     if (LHS && match(Op1, m_OneUse(m_LogicalAnd(m_Value(X), m_Value(Y))))) {
2570       bool IsLogical = isa<SelectInst>(Op1);
2571       // LHS & (X && Y) --> (LHS && X) && Y
2572       if (auto *Cmp = dyn_cast<ICmpInst>(X))
2573         if (Value *Res =
2574                 foldAndOrOfICmps(LHS, Cmp, I, /* IsAnd */ true, IsLogical))
2575           return replaceInstUsesWith(I, IsLogical
2576                                             ? Builder.CreateLogicalAnd(Res, Y)
2577                                             : Builder.CreateAnd(Res, Y));
2578       // LHS & (X && Y) --> X && (LHS & Y)
2579       if (auto *Cmp = dyn_cast<ICmpInst>(Y))
2580         if (Value *Res = foldAndOrOfICmps(LHS, Cmp, I, /* IsAnd */ true,
2581                                           /* IsLogical */ false))
2582           return replaceInstUsesWith(I, IsLogical
2583                                             ? Builder.CreateLogicalAnd(X, Res)
2584                                             : Builder.CreateAnd(X, Res));
2585     }
2586     if (RHS && match(Op0, m_OneUse(m_LogicalAnd(m_Value(X), m_Value(Y))))) {
2587       bool IsLogical = isa<SelectInst>(Op0);
2588       // (X && Y) & RHS --> (X && RHS) && Y
2589       if (auto *Cmp = dyn_cast<ICmpInst>(X))
2590         if (Value *Res =
2591                 foldAndOrOfICmps(Cmp, RHS, I, /* IsAnd */ true, IsLogical))
2592           return replaceInstUsesWith(I, IsLogical
2593                                             ? Builder.CreateLogicalAnd(Res, Y)
2594                                             : Builder.CreateAnd(Res, Y));
2595       // (X && Y) & RHS --> X && (Y & RHS)
2596       if (auto *Cmp = dyn_cast<ICmpInst>(Y))
2597         if (Value *Res = foldAndOrOfICmps(Cmp, RHS, I, /* IsAnd */ true,
2598                                           /* IsLogical */ false))
2599           return replaceInstUsesWith(I, IsLogical
2600                                             ? Builder.CreateLogicalAnd(X, Res)
2601                                             : Builder.CreateAnd(X, Res));
2602     }
2603   }
2604 
2605   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
2606     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
2607       if (Value *Res = foldLogicOfFCmps(LHS, RHS, /*IsAnd*/ true))
2608         return replaceInstUsesWith(I, Res);
2609 
2610   if (Instruction *FoldedFCmps = reassociateFCmps(I, Builder))
2611     return FoldedFCmps;
2612 
2613   if (Instruction *CastedAnd = foldCastedBitwiseLogic(I))
2614     return CastedAnd;
2615 
2616   if (Instruction *Sel = foldBinopOfSextBoolToSelect(I))
2617     return Sel;
2618 
2619   // and(sext(A), B) / and(B, sext(A)) --> A ? B : 0, where A is i1 or <N x i1>.
2620   // TODO: Move this into foldBinopOfSextBoolToSelect as a more generalized fold
2621   //       with binop identity constant. But creating a select with non-constant
2622   //       arm may not be reversible due to poison semantics. Is that a good
2623   //       canonicalization?
2624   Value *A;
2625   if (match(Op0, m_OneUse(m_SExt(m_Value(A)))) &&
2626       A->getType()->isIntOrIntVectorTy(1))
2627     return SelectInst::Create(A, Op1, Constant::getNullValue(Ty));
2628   if (match(Op1, m_OneUse(m_SExt(m_Value(A)))) &&
2629       A->getType()->isIntOrIntVectorTy(1))
2630     return SelectInst::Create(A, Op0, Constant::getNullValue(Ty));
2631 
2632   // Similarly, a 'not' of the bool translates to a swap of the select arms:
2633   // ~sext(A) & Op1 --> A ? 0 : Op1
2634   // Op0 & ~sext(A) --> A ? 0 : Op0
2635   if (match(Op0, m_Not(m_SExt(m_Value(A)))) &&
2636       A->getType()->isIntOrIntVectorTy(1))
2637     return SelectInst::Create(A, Constant::getNullValue(Ty), Op1);
2638   if (match(Op1, m_Not(m_SExt(m_Value(A)))) &&
2639       A->getType()->isIntOrIntVectorTy(1))
2640     return SelectInst::Create(A, Constant::getNullValue(Ty), Op0);
2641 
2642   // (iN X s>> (N-1)) & Y --> (X s< 0) ? Y : 0 -- with optional sext
2643   if (match(&I, m_c_And(m_OneUse(m_SExtOrSelf(
2644                             m_AShr(m_Value(X), m_APIntAllowUndef(C)))),
2645                         m_Value(Y))) &&
2646       *C == X->getType()->getScalarSizeInBits() - 1) {
2647     Value *IsNeg = Builder.CreateIsNeg(X, "isneg");
2648     return SelectInst::Create(IsNeg, Y, ConstantInt::getNullValue(Ty));
2649   }
2650   // If there's a 'not' of the shifted value, swap the select operands:
2651   // ~(iN X s>> (N-1)) & Y --> (X s< 0) ? 0 : Y -- with optional sext
2652   if (match(&I, m_c_And(m_OneUse(m_SExtOrSelf(
2653                             m_Not(m_AShr(m_Value(X), m_APIntAllowUndef(C))))),
2654                         m_Value(Y))) &&
2655       *C == X->getType()->getScalarSizeInBits() - 1) {
2656     Value *IsNeg = Builder.CreateIsNeg(X, "isneg");
2657     return SelectInst::Create(IsNeg, ConstantInt::getNullValue(Ty), Y);
2658   }
2659 
2660   // (~x) & y  -->  ~(x | (~y))  iff that gets rid of inversions
2661   if (sinkNotIntoOtherHandOfLogicalOp(I))
2662     return &I;
2663 
2664   // An and recurrence w/loop invariant step is equivelent to (and start, step)
2665   PHINode *PN = nullptr;
2666   Value *Start = nullptr, *Step = nullptr;
2667   if (matchSimpleRecurrence(&I, PN, Start, Step) && DT.dominates(Step, PN))
2668     return replaceInstUsesWith(I, Builder.CreateAnd(Start, Step));
2669 
2670   if (Instruction *R = reassociateForUses(I, Builder))
2671     return R;
2672 
2673   if (Instruction *Canonicalized = canonicalizeLogicFirst(I, Builder))
2674     return Canonicalized;
2675 
2676   if (Instruction *Folded = foldLogicOfIsFPClass(I, Op0, Op1))
2677     return Folded;
2678 
2679   if (Instruction *Res = foldBinOpOfDisplacedShifts(I))
2680     return Res;
2681 
2682   return nullptr;
2683 }
2684 
2685 Instruction *InstCombinerImpl::matchBSwapOrBitReverse(Instruction &I,
2686                                                       bool MatchBSwaps,
2687                                                       bool MatchBitReversals) {
2688   SmallVector<Instruction *, 4> Insts;
2689   if (!recognizeBSwapOrBitReverseIdiom(&I, MatchBSwaps, MatchBitReversals,
2690                                        Insts))
2691     return nullptr;
2692   Instruction *LastInst = Insts.pop_back_val();
2693   LastInst->removeFromParent();
2694 
2695   for (auto *Inst : Insts)
2696     Worklist.push(Inst);
2697   return LastInst;
2698 }
2699 
2700 /// Match UB-safe variants of the funnel shift intrinsic.
2701 static Instruction *matchFunnelShift(Instruction &Or, InstCombinerImpl &IC) {
2702   // TODO: Can we reduce the code duplication between this and the related
2703   // rotate matching code under visitSelect and visitTrunc?
2704   unsigned Width = Or.getType()->getScalarSizeInBits();
2705 
2706   // First, find an or'd pair of opposite shifts:
2707   // or (lshr ShVal0, ShAmt0), (shl ShVal1, ShAmt1)
2708   BinaryOperator *Or0, *Or1;
2709   if (!match(Or.getOperand(0), m_BinOp(Or0)) ||
2710       !match(Or.getOperand(1), m_BinOp(Or1)))
2711     return nullptr;
2712 
2713   Value *ShVal0, *ShVal1, *ShAmt0, *ShAmt1;
2714   if (!match(Or0, m_OneUse(m_LogicalShift(m_Value(ShVal0), m_Value(ShAmt0)))) ||
2715       !match(Or1, m_OneUse(m_LogicalShift(m_Value(ShVal1), m_Value(ShAmt1)))) ||
2716       Or0->getOpcode() == Or1->getOpcode())
2717     return nullptr;
2718 
2719   // Canonicalize to or(shl(ShVal0, ShAmt0), lshr(ShVal1, ShAmt1)).
2720   if (Or0->getOpcode() == BinaryOperator::LShr) {
2721     std::swap(Or0, Or1);
2722     std::swap(ShVal0, ShVal1);
2723     std::swap(ShAmt0, ShAmt1);
2724   }
2725   assert(Or0->getOpcode() == BinaryOperator::Shl &&
2726          Or1->getOpcode() == BinaryOperator::LShr &&
2727          "Illegal or(shift,shift) pair");
2728 
2729   // Match the shift amount operands for a funnel shift pattern. This always
2730   // matches a subtraction on the R operand.
2731   auto matchShiftAmount = [&](Value *L, Value *R, unsigned Width) -> Value * {
2732     // Check for constant shift amounts that sum to the bitwidth.
2733     const APInt *LI, *RI;
2734     if (match(L, m_APIntAllowUndef(LI)) && match(R, m_APIntAllowUndef(RI)))
2735       if (LI->ult(Width) && RI->ult(Width) && (*LI + *RI) == Width)
2736         return ConstantInt::get(L->getType(), *LI);
2737 
2738     Constant *LC, *RC;
2739     if (match(L, m_Constant(LC)) && match(R, m_Constant(RC)) &&
2740         match(L, m_SpecificInt_ICMP(ICmpInst::ICMP_ULT, APInt(Width, Width))) &&
2741         match(R, m_SpecificInt_ICMP(ICmpInst::ICMP_ULT, APInt(Width, Width))) &&
2742         match(ConstantExpr::getAdd(LC, RC), m_SpecificIntAllowUndef(Width)))
2743       return ConstantExpr::mergeUndefsWith(LC, RC);
2744 
2745     // (shl ShVal, X) | (lshr ShVal, (Width - x)) iff X < Width.
2746     // We limit this to X < Width in case the backend re-expands the intrinsic,
2747     // and has to reintroduce a shift modulo operation (InstCombine might remove
2748     // it after this fold). This still doesn't guarantee that the final codegen
2749     // will match this original pattern.
2750     if (match(R, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(L))))) {
2751       KnownBits KnownL = IC.computeKnownBits(L, /*Depth*/ 0, &Or);
2752       return KnownL.getMaxValue().ult(Width) ? L : nullptr;
2753     }
2754 
2755     // For non-constant cases, the following patterns currently only work for
2756     // rotation patterns.
2757     // TODO: Add general funnel-shift compatible patterns.
2758     if (ShVal0 != ShVal1)
2759       return nullptr;
2760 
2761     // For non-constant cases we don't support non-pow2 shift masks.
2762     // TODO: Is it worth matching urem as well?
2763     if (!isPowerOf2_32(Width))
2764       return nullptr;
2765 
2766     // The shift amount may be masked with negation:
2767     // (shl ShVal, (X & (Width - 1))) | (lshr ShVal, ((-X) & (Width - 1)))
2768     Value *X;
2769     unsigned Mask = Width - 1;
2770     if (match(L, m_And(m_Value(X), m_SpecificInt(Mask))) &&
2771         match(R, m_And(m_Neg(m_Specific(X)), m_SpecificInt(Mask))))
2772       return X;
2773 
2774     // Similar to above, but the shift amount may be extended after masking,
2775     // so return the extended value as the parameter for the intrinsic.
2776     if (match(L, m_ZExt(m_And(m_Value(X), m_SpecificInt(Mask)))) &&
2777         match(R, m_And(m_Neg(m_ZExt(m_And(m_Specific(X), m_SpecificInt(Mask)))),
2778                        m_SpecificInt(Mask))))
2779       return L;
2780 
2781     if (match(L, m_ZExt(m_And(m_Value(X), m_SpecificInt(Mask)))) &&
2782         match(R, m_ZExt(m_And(m_Neg(m_Specific(X)), m_SpecificInt(Mask)))))
2783       return L;
2784 
2785     return nullptr;
2786   };
2787 
2788   Value *ShAmt = matchShiftAmount(ShAmt0, ShAmt1, Width);
2789   bool IsFshl = true; // Sub on LSHR.
2790   if (!ShAmt) {
2791     ShAmt = matchShiftAmount(ShAmt1, ShAmt0, Width);
2792     IsFshl = false; // Sub on SHL.
2793   }
2794   if (!ShAmt)
2795     return nullptr;
2796 
2797   Intrinsic::ID IID = IsFshl ? Intrinsic::fshl : Intrinsic::fshr;
2798   Function *F = Intrinsic::getDeclaration(Or.getModule(), IID, Or.getType());
2799   return CallInst::Create(F, {ShVal0, ShVal1, ShAmt});
2800 }
2801 
2802 /// Attempt to combine or(zext(x),shl(zext(y),bw/2) concat packing patterns.
2803 static Instruction *matchOrConcat(Instruction &Or,
2804                                   InstCombiner::BuilderTy &Builder) {
2805   assert(Or.getOpcode() == Instruction::Or && "bswap requires an 'or'");
2806   Value *Op0 = Or.getOperand(0), *Op1 = Or.getOperand(1);
2807   Type *Ty = Or.getType();
2808 
2809   unsigned Width = Ty->getScalarSizeInBits();
2810   if ((Width & 1) != 0)
2811     return nullptr;
2812   unsigned HalfWidth = Width / 2;
2813 
2814   // Canonicalize zext (lower half) to LHS.
2815   if (!isa<ZExtInst>(Op0))
2816     std::swap(Op0, Op1);
2817 
2818   // Find lower/upper half.
2819   Value *LowerSrc, *ShlVal, *UpperSrc;
2820   const APInt *C;
2821   if (!match(Op0, m_OneUse(m_ZExt(m_Value(LowerSrc)))) ||
2822       !match(Op1, m_OneUse(m_Shl(m_Value(ShlVal), m_APInt(C)))) ||
2823       !match(ShlVal, m_OneUse(m_ZExt(m_Value(UpperSrc)))))
2824     return nullptr;
2825   if (*C != HalfWidth || LowerSrc->getType() != UpperSrc->getType() ||
2826       LowerSrc->getType()->getScalarSizeInBits() != HalfWidth)
2827     return nullptr;
2828 
2829   auto ConcatIntrinsicCalls = [&](Intrinsic::ID id, Value *Lo, Value *Hi) {
2830     Value *NewLower = Builder.CreateZExt(Lo, Ty);
2831     Value *NewUpper = Builder.CreateZExt(Hi, Ty);
2832     NewUpper = Builder.CreateShl(NewUpper, HalfWidth);
2833     Value *BinOp = Builder.CreateOr(NewLower, NewUpper);
2834     Function *F = Intrinsic::getDeclaration(Or.getModule(), id, Ty);
2835     return Builder.CreateCall(F, BinOp);
2836   };
2837 
2838   // BSWAP: Push the concat down, swapping the lower/upper sources.
2839   // concat(bswap(x),bswap(y)) -> bswap(concat(x,y))
2840   Value *LowerBSwap, *UpperBSwap;
2841   if (match(LowerSrc, m_BSwap(m_Value(LowerBSwap))) &&
2842       match(UpperSrc, m_BSwap(m_Value(UpperBSwap))))
2843     return ConcatIntrinsicCalls(Intrinsic::bswap, UpperBSwap, LowerBSwap);
2844 
2845   // BITREVERSE: Push the concat down, swapping the lower/upper sources.
2846   // concat(bitreverse(x),bitreverse(y)) -> bitreverse(concat(x,y))
2847   Value *LowerBRev, *UpperBRev;
2848   if (match(LowerSrc, m_BitReverse(m_Value(LowerBRev))) &&
2849       match(UpperSrc, m_BitReverse(m_Value(UpperBRev))))
2850     return ConcatIntrinsicCalls(Intrinsic::bitreverse, UpperBRev, LowerBRev);
2851 
2852   return nullptr;
2853 }
2854 
2855 /// If all elements of two constant vectors are 0/-1 and inverses, return true.
2856 static bool areInverseVectorBitmasks(Constant *C1, Constant *C2) {
2857   unsigned NumElts = cast<FixedVectorType>(C1->getType())->getNumElements();
2858   for (unsigned i = 0; i != NumElts; ++i) {
2859     Constant *EltC1 = C1->getAggregateElement(i);
2860     Constant *EltC2 = C2->getAggregateElement(i);
2861     if (!EltC1 || !EltC2)
2862       return false;
2863 
2864     // One element must be all ones, and the other must be all zeros.
2865     if (!((match(EltC1, m_Zero()) && match(EltC2, m_AllOnes())) ||
2866           (match(EltC2, m_Zero()) && match(EltC1, m_AllOnes()))))
2867       return false;
2868   }
2869   return true;
2870 }
2871 
2872 /// We have an expression of the form (A & C) | (B & D). If A is a scalar or
2873 /// vector composed of all-zeros or all-ones values and is the bitwise 'not' of
2874 /// B, it can be used as the condition operand of a select instruction.
2875 /// We will detect (A & C) | ~(B | D) when the flag ABIsTheSame enabled.
2876 Value *InstCombinerImpl::getSelectCondition(Value *A, Value *B,
2877                                             bool ABIsTheSame) {
2878   // We may have peeked through bitcasts in the caller.
2879   // Exit immediately if we don't have (vector) integer types.
2880   Type *Ty = A->getType();
2881   if (!Ty->isIntOrIntVectorTy() || !B->getType()->isIntOrIntVectorTy())
2882     return nullptr;
2883 
2884   // If A is the 'not' operand of B and has enough signbits, we have our answer.
2885   if (ABIsTheSame ? (A == B) : match(B, m_Not(m_Specific(A)))) {
2886     // If these are scalars or vectors of i1, A can be used directly.
2887     if (Ty->isIntOrIntVectorTy(1))
2888       return A;
2889 
2890     // If we look through a vector bitcast, the caller will bitcast the operands
2891     // to match the condition's number of bits (N x i1).
2892     // To make this poison-safe, disallow bitcast from wide element to narrow
2893     // element. That could allow poison in lanes where it was not present in the
2894     // original code.
2895     A = peekThroughBitcast(A);
2896     if (A->getType()->isIntOrIntVectorTy()) {
2897       unsigned NumSignBits = ComputeNumSignBits(A);
2898       if (NumSignBits == A->getType()->getScalarSizeInBits() &&
2899           NumSignBits <= Ty->getScalarSizeInBits())
2900         return Builder.CreateTrunc(A, CmpInst::makeCmpResultType(A->getType()));
2901     }
2902     return nullptr;
2903   }
2904 
2905   // TODO: add support for sext and constant case
2906   if (ABIsTheSame)
2907     return nullptr;
2908 
2909   // If both operands are constants, see if the constants are inverse bitmasks.
2910   Constant *AConst, *BConst;
2911   if (match(A, m_Constant(AConst)) && match(B, m_Constant(BConst)))
2912     if (AConst == ConstantExpr::getNot(BConst) &&
2913         ComputeNumSignBits(A) == Ty->getScalarSizeInBits())
2914       return Builder.CreateZExtOrTrunc(A, CmpInst::makeCmpResultType(Ty));
2915 
2916   // Look for more complex patterns. The 'not' op may be hidden behind various
2917   // casts. Look through sexts and bitcasts to find the booleans.
2918   Value *Cond;
2919   Value *NotB;
2920   if (match(A, m_SExt(m_Value(Cond))) &&
2921       Cond->getType()->isIntOrIntVectorTy(1)) {
2922     // A = sext i1 Cond; B = sext (not (i1 Cond))
2923     if (match(B, m_SExt(m_Not(m_Specific(Cond)))))
2924       return Cond;
2925 
2926     // A = sext i1 Cond; B = not ({bitcast} (sext (i1 Cond)))
2927     // TODO: The one-use checks are unnecessary or misplaced. If the caller
2928     //       checked for uses on logic ops/casts, that should be enough to
2929     //       make this transform worthwhile.
2930     if (match(B, m_OneUse(m_Not(m_Value(NotB))))) {
2931       NotB = peekThroughBitcast(NotB, true);
2932       if (match(NotB, m_SExt(m_Specific(Cond))))
2933         return Cond;
2934     }
2935   }
2936 
2937   // All scalar (and most vector) possibilities should be handled now.
2938   // Try more matches that only apply to non-splat constant vectors.
2939   if (!Ty->isVectorTy())
2940     return nullptr;
2941 
2942   // If both operands are xor'd with constants using the same sexted boolean
2943   // operand, see if the constants are inverse bitmasks.
2944   // TODO: Use ConstantExpr::getNot()?
2945   if (match(A, (m_Xor(m_SExt(m_Value(Cond)), m_Constant(AConst)))) &&
2946       match(B, (m_Xor(m_SExt(m_Specific(Cond)), m_Constant(BConst)))) &&
2947       Cond->getType()->isIntOrIntVectorTy(1) &&
2948       areInverseVectorBitmasks(AConst, BConst)) {
2949     AConst = ConstantExpr::getTrunc(AConst, CmpInst::makeCmpResultType(Ty));
2950     return Builder.CreateXor(Cond, AConst);
2951   }
2952   return nullptr;
2953 }
2954 
2955 /// We have an expression of the form (A & C) | (B & D). Try to simplify this
2956 /// to "A' ? C : D", where A' is a boolean or vector of booleans.
2957 /// When InvertFalseVal is set to true, we try to match the pattern
2958 /// where we have peeked through a 'not' op and A and B are the same:
2959 /// (A & C) | ~(A | D) --> (A & C) | (~A & ~D) --> A' ? C : ~D
2960 Value *InstCombinerImpl::matchSelectFromAndOr(Value *A, Value *C, Value *B,
2961                                               Value *D, bool InvertFalseVal) {
2962   // The potential condition of the select may be bitcasted. In that case, look
2963   // through its bitcast and the corresponding bitcast of the 'not' condition.
2964   Type *OrigType = A->getType();
2965   A = peekThroughBitcast(A, true);
2966   B = peekThroughBitcast(B, true);
2967   if (Value *Cond = getSelectCondition(A, B, InvertFalseVal)) {
2968     // ((bc Cond) & C) | ((bc ~Cond) & D) --> bc (select Cond, (bc C), (bc D))
2969     // If this is a vector, we may need to cast to match the condition's length.
2970     // The bitcasts will either all exist or all not exist. The builder will
2971     // not create unnecessary casts if the types already match.
2972     Type *SelTy = A->getType();
2973     if (auto *VecTy = dyn_cast<VectorType>(Cond->getType())) {
2974       // For a fixed or scalable vector get N from <{vscale x} N x iM>
2975       unsigned Elts = VecTy->getElementCount().getKnownMinValue();
2976       // For a fixed or scalable vector, get the size in bits of N x iM; for a
2977       // scalar this is just M.
2978       unsigned SelEltSize = SelTy->getPrimitiveSizeInBits().getKnownMinValue();
2979       Type *EltTy = Builder.getIntNTy(SelEltSize / Elts);
2980       SelTy = VectorType::get(EltTy, VecTy->getElementCount());
2981     }
2982     Value *BitcastC = Builder.CreateBitCast(C, SelTy);
2983     if (InvertFalseVal)
2984       D = Builder.CreateNot(D);
2985     Value *BitcastD = Builder.CreateBitCast(D, SelTy);
2986     Value *Select = Builder.CreateSelect(Cond, BitcastC, BitcastD);
2987     return Builder.CreateBitCast(Select, OrigType);
2988   }
2989 
2990   return nullptr;
2991 }
2992 
2993 // (icmp eq X, C) | (icmp ult Other, (X - C)) -> (icmp ule Other, (X - (C + 1)))
2994 // (icmp ne X, C) & (icmp uge Other, (X - C)) -> (icmp ugt Other, (X - (C + 1)))
2995 static Value *foldAndOrOfICmpEqConstantAndICmp(ICmpInst *LHS, ICmpInst *RHS,
2996                                                bool IsAnd, bool IsLogical,
2997                                                IRBuilderBase &Builder) {
2998   Value *LHS0 = LHS->getOperand(0);
2999   Value *RHS0 = RHS->getOperand(0);
3000   Value *RHS1 = RHS->getOperand(1);
3001 
3002   ICmpInst::Predicate LPred =
3003       IsAnd ? LHS->getInversePredicate() : LHS->getPredicate();
3004   ICmpInst::Predicate RPred =
3005       IsAnd ? RHS->getInversePredicate() : RHS->getPredicate();
3006 
3007   const APInt *CInt;
3008   if (LPred != ICmpInst::ICMP_EQ ||
3009       !match(LHS->getOperand(1), m_APIntAllowUndef(CInt)) ||
3010       !LHS0->getType()->isIntOrIntVectorTy() ||
3011       !(LHS->hasOneUse() || RHS->hasOneUse()))
3012     return nullptr;
3013 
3014   auto MatchRHSOp = [LHS0, CInt](const Value *RHSOp) {
3015     return match(RHSOp,
3016                  m_Add(m_Specific(LHS0), m_SpecificIntAllowUndef(-*CInt))) ||
3017            (CInt->isZero() && RHSOp == LHS0);
3018   };
3019 
3020   Value *Other;
3021   if (RPred == ICmpInst::ICMP_ULT && MatchRHSOp(RHS1))
3022     Other = RHS0;
3023   else if (RPred == ICmpInst::ICMP_UGT && MatchRHSOp(RHS0))
3024     Other = RHS1;
3025   else
3026     return nullptr;
3027 
3028   if (IsLogical)
3029     Other = Builder.CreateFreeze(Other);
3030 
3031   return Builder.CreateICmp(
3032       IsAnd ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_UGE,
3033       Builder.CreateSub(LHS0, ConstantInt::get(LHS0->getType(), *CInt + 1)),
3034       Other);
3035 }
3036 
3037 /// Fold (icmp)&(icmp) or (icmp)|(icmp) if possible.
3038 /// If IsLogical is true, then the and/or is in select form and the transform
3039 /// must be poison-safe.
3040 Value *InstCombinerImpl::foldAndOrOfICmps(ICmpInst *LHS, ICmpInst *RHS,
3041                                           Instruction &I, bool IsAnd,
3042                                           bool IsLogical) {
3043   const SimplifyQuery Q = SQ.getWithInstruction(&I);
3044 
3045   // Fold (iszero(A & K1) | iszero(A & K2)) ->  (A & (K1 | K2)) != (K1 | K2)
3046   // Fold (!iszero(A & K1) & !iszero(A & K2)) ->  (A & (K1 | K2)) == (K1 | K2)
3047   // if K1 and K2 are a one-bit mask.
3048   if (Value *V = foldAndOrOfICmpsOfAndWithPow2(LHS, RHS, &I, IsAnd, IsLogical))
3049     return V;
3050 
3051   ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
3052   Value *LHS0 = LHS->getOperand(0), *RHS0 = RHS->getOperand(0);
3053   Value *LHS1 = LHS->getOperand(1), *RHS1 = RHS->getOperand(1);
3054   const APInt *LHSC = nullptr, *RHSC = nullptr;
3055   match(LHS1, m_APInt(LHSC));
3056   match(RHS1, m_APInt(RHSC));
3057 
3058   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3059   // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3060   if (predicatesFoldable(PredL, PredR)) {
3061     if (LHS0 == RHS1 && LHS1 == RHS0) {
3062       PredL = ICmpInst::getSwappedPredicate(PredL);
3063       std::swap(LHS0, LHS1);
3064     }
3065     if (LHS0 == RHS0 && LHS1 == RHS1) {
3066       unsigned Code = IsAnd ? getICmpCode(PredL) & getICmpCode(PredR)
3067                             : getICmpCode(PredL) | getICmpCode(PredR);
3068       bool IsSigned = LHS->isSigned() || RHS->isSigned();
3069       return getNewICmpValue(Code, IsSigned, LHS0, LHS1, Builder);
3070     }
3071   }
3072 
3073   // handle (roughly):
3074   // (icmp ne (A & B), C) | (icmp ne (A & D), E)
3075   // (icmp eq (A & B), C) & (icmp eq (A & D), E)
3076   if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, IsAnd, IsLogical, Builder))
3077     return V;
3078 
3079   if (Value *V =
3080           foldAndOrOfICmpEqConstantAndICmp(LHS, RHS, IsAnd, IsLogical, Builder))
3081     return V;
3082   // We can treat logical like bitwise here, because both operands are used on
3083   // the LHS, and as such poison from both will propagate.
3084   if (Value *V = foldAndOrOfICmpEqConstantAndICmp(RHS, LHS, IsAnd,
3085                                                   /*IsLogical*/ false, Builder))
3086     return V;
3087 
3088   if (Value *V =
3089           foldAndOrOfICmpsWithConstEq(LHS, RHS, IsAnd, IsLogical, Builder, Q))
3090     return V;
3091   // We can convert this case to bitwise and, because both operands are used
3092   // on the LHS, and as such poison from both will propagate.
3093   if (Value *V = foldAndOrOfICmpsWithConstEq(RHS, LHS, IsAnd,
3094                                              /*IsLogical*/ false, Builder, Q))
3095     return V;
3096 
3097   if (Value *V = foldIsPowerOf2OrZero(LHS, RHS, IsAnd, Builder))
3098     return V;
3099   if (Value *V = foldIsPowerOf2OrZero(RHS, LHS, IsAnd, Builder))
3100     return V;
3101 
3102   // TODO: One of these directions is fine with logical and/or, the other could
3103   // be supported by inserting freeze.
3104   if (!IsLogical) {
3105     // E.g. (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
3106     // E.g. (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
3107     if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/!IsAnd))
3108       return V;
3109 
3110     // E.g. (icmp sgt x, n) | (icmp slt x, 0) --> icmp ugt x, n
3111     // E.g. (icmp slt x, n) & (icmp sge x, 0) --> icmp ult x, n
3112     if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/!IsAnd))
3113       return V;
3114   }
3115 
3116   // TODO: Add conjugated or fold, check whether it is safe for logical and/or.
3117   if (IsAnd && !IsLogical)
3118     if (Value *V = foldSignedTruncationCheck(LHS, RHS, I, Builder))
3119       return V;
3120 
3121   if (Value *V = foldIsPowerOf2(LHS, RHS, IsAnd, Builder))
3122     return V;
3123 
3124   if (Value *V = foldPowerOf2AndShiftedMask(LHS, RHS, IsAnd, Builder))
3125     return V;
3126 
3127   // TODO: Verify whether this is safe for logical and/or.
3128   if (!IsLogical) {
3129     if (Value *X = foldUnsignedUnderflowCheck(LHS, RHS, IsAnd, Q, Builder))
3130       return X;
3131     if (Value *X = foldUnsignedUnderflowCheck(RHS, LHS, IsAnd, Q, Builder))
3132       return X;
3133   }
3134 
3135   if (Value *X = foldEqOfParts(LHS, RHS, IsAnd))
3136     return X;
3137 
3138   // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
3139   // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
3140   // TODO: Remove this and below when foldLogOpOfMaskedICmps can handle undefs.
3141   if (!IsLogical && PredL == (IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE) &&
3142       PredL == PredR && match(LHS1, m_ZeroInt()) && match(RHS1, m_ZeroInt()) &&
3143       LHS0->getType() == RHS0->getType()) {
3144     Value *NewOr = Builder.CreateOr(LHS0, RHS0);
3145     return Builder.CreateICmp(PredL, NewOr,
3146                               Constant::getNullValue(NewOr->getType()));
3147   }
3148 
3149   // (icmp ne A, -1) | (icmp ne B, -1) --> (icmp ne (A&B), -1)
3150   // (icmp eq A, -1) & (icmp eq B, -1) --> (icmp eq (A&B), -1)
3151   if (!IsLogical && PredL == (IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE) &&
3152       PredL == PredR && match(LHS1, m_AllOnes()) && match(RHS1, m_AllOnes()) &&
3153       LHS0->getType() == RHS0->getType()) {
3154     Value *NewAnd = Builder.CreateAnd(LHS0, RHS0);
3155     return Builder.CreateICmp(PredL, NewAnd,
3156                               Constant::getAllOnesValue(LHS0->getType()));
3157   }
3158 
3159   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
3160   if (!LHSC || !RHSC)
3161     return nullptr;
3162 
3163   // (trunc x) == C1 & (and x, CA) == C2 -> (and x, CA|CMAX) == C1|C2
3164   // (trunc x) != C1 | (and x, CA) != C2 -> (and x, CA|CMAX) != C1|C2
3165   // where CMAX is the all ones value for the truncated type,
3166   // iff the lower bits of C2 and CA are zero.
3167   if (PredL == (IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE) &&
3168       PredL == PredR && LHS->hasOneUse() && RHS->hasOneUse()) {
3169     Value *V;
3170     const APInt *AndC, *SmallC = nullptr, *BigC = nullptr;
3171 
3172     // (trunc x) == C1 & (and x, CA) == C2
3173     // (and x, CA) == C2 & (trunc x) == C1
3174     if (match(RHS0, m_Trunc(m_Value(V))) &&
3175         match(LHS0, m_And(m_Specific(V), m_APInt(AndC)))) {
3176       SmallC = RHSC;
3177       BigC = LHSC;
3178     } else if (match(LHS0, m_Trunc(m_Value(V))) &&
3179                match(RHS0, m_And(m_Specific(V), m_APInt(AndC)))) {
3180       SmallC = LHSC;
3181       BigC = RHSC;
3182     }
3183 
3184     if (SmallC && BigC) {
3185       unsigned BigBitSize = BigC->getBitWidth();
3186       unsigned SmallBitSize = SmallC->getBitWidth();
3187 
3188       // Check that the low bits are zero.
3189       APInt Low = APInt::getLowBitsSet(BigBitSize, SmallBitSize);
3190       if ((Low & *AndC).isZero() && (Low & *BigC).isZero()) {
3191         Value *NewAnd = Builder.CreateAnd(V, Low | *AndC);
3192         APInt N = SmallC->zext(BigBitSize) | *BigC;
3193         Value *NewVal = ConstantInt::get(NewAnd->getType(), N);
3194         return Builder.CreateICmp(PredL, NewAnd, NewVal);
3195       }
3196     }
3197   }
3198 
3199   // Match naive pattern (and its inverted form) for checking if two values
3200   // share same sign. An example of the pattern:
3201   // (icmp slt (X & Y), 0) | (icmp sgt (X | Y), -1) -> (icmp sgt (X ^ Y), -1)
3202   // Inverted form (example):
3203   // (icmp slt (X | Y), 0) & (icmp sgt (X & Y), -1) -> (icmp slt (X ^ Y), 0)
3204   bool TrueIfSignedL, TrueIfSignedR;
3205   if (isSignBitCheck(PredL, *LHSC, TrueIfSignedL) &&
3206       isSignBitCheck(PredR, *RHSC, TrueIfSignedR) &&
3207       (RHS->hasOneUse() || LHS->hasOneUse())) {
3208     Value *X, *Y;
3209     if (IsAnd) {
3210       if ((TrueIfSignedL && !TrueIfSignedR &&
3211            match(LHS0, m_Or(m_Value(X), m_Value(Y))) &&
3212            match(RHS0, m_c_And(m_Specific(X), m_Specific(Y)))) ||
3213           (!TrueIfSignedL && TrueIfSignedR &&
3214            match(LHS0, m_And(m_Value(X), m_Value(Y))) &&
3215            match(RHS0, m_c_Or(m_Specific(X), m_Specific(Y))))) {
3216         Value *NewXor = Builder.CreateXor(X, Y);
3217         return Builder.CreateIsNeg(NewXor);
3218       }
3219     } else {
3220       if ((TrueIfSignedL && !TrueIfSignedR &&
3221             match(LHS0, m_And(m_Value(X), m_Value(Y))) &&
3222             match(RHS0, m_c_Or(m_Specific(X), m_Specific(Y)))) ||
3223           (!TrueIfSignedL && TrueIfSignedR &&
3224            match(LHS0, m_Or(m_Value(X), m_Value(Y))) &&
3225            match(RHS0, m_c_And(m_Specific(X), m_Specific(Y))))) {
3226         Value *NewXor = Builder.CreateXor(X, Y);
3227         return Builder.CreateIsNotNeg(NewXor);
3228       }
3229     }
3230   }
3231 
3232   return foldAndOrOfICmpsUsingRanges(LHS, RHS, IsAnd);
3233 }
3234 
3235 // FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
3236 // here. We should standardize that construct where it is needed or choose some
3237 // other way to ensure that commutated variants of patterns are not missed.
3238 Instruction *InstCombinerImpl::visitOr(BinaryOperator &I) {
3239   if (Value *V = simplifyOrInst(I.getOperand(0), I.getOperand(1),
3240                                 SQ.getWithInstruction(&I)))
3241     return replaceInstUsesWith(I, V);
3242 
3243   if (SimplifyAssociativeOrCommutative(I))
3244     return &I;
3245 
3246   if (Instruction *X = foldVectorBinop(I))
3247     return X;
3248 
3249   if (Instruction *Phi = foldBinopWithPhiOperands(I))
3250     return Phi;
3251 
3252   // See if we can simplify any instructions used by the instruction whose sole
3253   // purpose is to compute bits we don't care about.
3254   if (SimplifyDemandedInstructionBits(I))
3255     return &I;
3256 
3257   // Do this before using distributive laws to catch simple and/or/not patterns.
3258   if (Instruction *Xor = foldOrToXor(I, Builder))
3259     return Xor;
3260 
3261   if (Instruction *X = foldComplexAndOrPatterns(I, Builder))
3262     return X;
3263 
3264   // (A&B)|(A&C) -> A&(B|C) etc
3265   if (Value *V = foldUsingDistributiveLaws(I))
3266     return replaceInstUsesWith(I, V);
3267 
3268   if (Value *V = SimplifyBSwap(I, Builder))
3269     return replaceInstUsesWith(I, V);
3270 
3271   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3272   Type *Ty = I.getType();
3273   if (Ty->isIntOrIntVectorTy(1)) {
3274     if (auto *SI0 = dyn_cast<SelectInst>(Op0)) {
3275       if (auto *I =
3276               foldAndOrOfSelectUsingImpliedCond(Op1, *SI0, /* IsAnd */ false))
3277         return I;
3278     }
3279     if (auto *SI1 = dyn_cast<SelectInst>(Op1)) {
3280       if (auto *I =
3281               foldAndOrOfSelectUsingImpliedCond(Op0, *SI1, /* IsAnd */ false))
3282         return I;
3283     }
3284   }
3285 
3286   if (Instruction *FoldedLogic = foldBinOpIntoSelectOrPhi(I))
3287     return FoldedLogic;
3288 
3289   if (Instruction *BitOp = matchBSwapOrBitReverse(I, /*MatchBSwaps*/ true,
3290                                                   /*MatchBitReversals*/ true))
3291     return BitOp;
3292 
3293   if (Instruction *Funnel = matchFunnelShift(I, *this))
3294     return Funnel;
3295 
3296   if (Instruction *Concat = matchOrConcat(I, Builder))
3297     return replaceInstUsesWith(I, Concat);
3298 
3299   if (Instruction *R = foldBinOpShiftWithShift(I))
3300     return R;
3301 
3302   Value *X, *Y;
3303   const APInt *CV;
3304   if (match(&I, m_c_Or(m_OneUse(m_Xor(m_Value(X), m_APInt(CV))), m_Value(Y))) &&
3305       !CV->isAllOnes() && MaskedValueIsZero(Y, *CV, 0, &I)) {
3306     // (X ^ C) | Y -> (X | Y) ^ C iff Y & C == 0
3307     // The check for a 'not' op is for efficiency (if Y is known zero --> ~X).
3308     Value *Or = Builder.CreateOr(X, Y);
3309     return BinaryOperator::CreateXor(Or, ConstantInt::get(Ty, *CV));
3310   }
3311 
3312   // If the operands have no common bits set:
3313   // or (mul X, Y), X --> add (mul X, Y), X --> mul X, (Y + 1)
3314   if (match(&I,
3315             m_c_Or(m_OneUse(m_Mul(m_Value(X), m_Value(Y))), m_Deferred(X))) &&
3316       haveNoCommonBitsSet(Op0, Op1, DL)) {
3317     Value *IncrementY = Builder.CreateAdd(Y, ConstantInt::get(Ty, 1));
3318     return BinaryOperator::CreateMul(X, IncrementY);
3319   }
3320 
3321   // X | (X ^ Y) --> X | Y (4 commuted patterns)
3322   if (match(&I, m_c_Or(m_Value(X), m_c_Xor(m_Deferred(X), m_Value(Y)))))
3323     return BinaryOperator::CreateOr(X, Y);
3324 
3325   // (A & C) | (B & D)
3326   Value *A, *B, *C, *D;
3327   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
3328       match(Op1, m_And(m_Value(B), m_Value(D)))) {
3329 
3330     // (A & C0) | (B & C1)
3331     const APInt *C0, *C1;
3332     if (match(C, m_APInt(C0)) && match(D, m_APInt(C1))) {
3333       Value *X;
3334       if (*C0 == ~*C1) {
3335         // ((X | B) & MaskC) | (B & ~MaskC) -> (X & MaskC) | B
3336         if (match(A, m_c_Or(m_Value(X), m_Specific(B))))
3337           return BinaryOperator::CreateOr(Builder.CreateAnd(X, *C0), B);
3338         // (A & MaskC) | ((X | A) & ~MaskC) -> (X & ~MaskC) | A
3339         if (match(B, m_c_Or(m_Specific(A), m_Value(X))))
3340           return BinaryOperator::CreateOr(Builder.CreateAnd(X, *C1), A);
3341 
3342         // ((X ^ B) & MaskC) | (B & ~MaskC) -> (X & MaskC) ^ B
3343         if (match(A, m_c_Xor(m_Value(X), m_Specific(B))))
3344           return BinaryOperator::CreateXor(Builder.CreateAnd(X, *C0), B);
3345         // (A & MaskC) | ((X ^ A) & ~MaskC) -> (X & ~MaskC) ^ A
3346         if (match(B, m_c_Xor(m_Specific(A), m_Value(X))))
3347           return BinaryOperator::CreateXor(Builder.CreateAnd(X, *C1), A);
3348       }
3349 
3350       if ((*C0 & *C1).isZero()) {
3351         // ((X | B) & C0) | (B & C1) --> (X | B) & (C0 | C1)
3352         // iff (C0 & C1) == 0 and (X & ~C0) == 0
3353         if (match(A, m_c_Or(m_Value(X), m_Specific(B))) &&
3354             MaskedValueIsZero(X, ~*C0, 0, &I)) {
3355           Constant *C01 = ConstantInt::get(Ty, *C0 | *C1);
3356           return BinaryOperator::CreateAnd(A, C01);
3357         }
3358         // (A & C0) | ((X | A) & C1) --> (X | A) & (C0 | C1)
3359         // iff (C0 & C1) == 0 and (X & ~C1) == 0
3360         if (match(B, m_c_Or(m_Value(X), m_Specific(A))) &&
3361             MaskedValueIsZero(X, ~*C1, 0, &I)) {
3362           Constant *C01 = ConstantInt::get(Ty, *C0 | *C1);
3363           return BinaryOperator::CreateAnd(B, C01);
3364         }
3365         // ((X | C2) & C0) | ((X | C3) & C1) --> (X | C2 | C3) & (C0 | C1)
3366         // iff (C0 & C1) == 0 and (C2 & ~C0) == 0 and (C3 & ~C1) == 0.
3367         const APInt *C2, *C3;
3368         if (match(A, m_Or(m_Value(X), m_APInt(C2))) &&
3369             match(B, m_Or(m_Specific(X), m_APInt(C3))) &&
3370             (*C2 & ~*C0).isZero() && (*C3 & ~*C1).isZero()) {
3371           Value *Or = Builder.CreateOr(X, *C2 | *C3, "bitfield");
3372           Constant *C01 = ConstantInt::get(Ty, *C0 | *C1);
3373           return BinaryOperator::CreateAnd(Or, C01);
3374         }
3375       }
3376     }
3377 
3378     // Don't try to form a select if it's unlikely that we'll get rid of at
3379     // least one of the operands. A select is generally more expensive than the
3380     // 'or' that it is replacing.
3381     if (Op0->hasOneUse() || Op1->hasOneUse()) {
3382       // (Cond & C) | (~Cond & D) -> Cond ? C : D, and commuted variants.
3383       if (Value *V = matchSelectFromAndOr(A, C, B, D))
3384         return replaceInstUsesWith(I, V);
3385       if (Value *V = matchSelectFromAndOr(A, C, D, B))
3386         return replaceInstUsesWith(I, V);
3387       if (Value *V = matchSelectFromAndOr(C, A, B, D))
3388         return replaceInstUsesWith(I, V);
3389       if (Value *V = matchSelectFromAndOr(C, A, D, B))
3390         return replaceInstUsesWith(I, V);
3391       if (Value *V = matchSelectFromAndOr(B, D, A, C))
3392         return replaceInstUsesWith(I, V);
3393       if (Value *V = matchSelectFromAndOr(B, D, C, A))
3394         return replaceInstUsesWith(I, V);
3395       if (Value *V = matchSelectFromAndOr(D, B, A, C))
3396         return replaceInstUsesWith(I, V);
3397       if (Value *V = matchSelectFromAndOr(D, B, C, A))
3398         return replaceInstUsesWith(I, V);
3399     }
3400   }
3401 
3402   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
3403       match(Op1, m_Not(m_Or(m_Value(B), m_Value(D)))) &&
3404       (Op0->hasOneUse() || Op1->hasOneUse())) {
3405     // (Cond & C) | ~(Cond | D) -> Cond ? C : ~D
3406     if (Value *V = matchSelectFromAndOr(A, C, B, D, true))
3407       return replaceInstUsesWith(I, V);
3408     if (Value *V = matchSelectFromAndOr(A, C, D, B, true))
3409       return replaceInstUsesWith(I, V);
3410     if (Value *V = matchSelectFromAndOr(C, A, B, D, true))
3411       return replaceInstUsesWith(I, V);
3412     if (Value *V = matchSelectFromAndOr(C, A, D, B, true))
3413       return replaceInstUsesWith(I, V);
3414   }
3415 
3416   // (A ^ B) | ((B ^ C) ^ A) -> (A ^ B) | C
3417   if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
3418     if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
3419       return BinaryOperator::CreateOr(Op0, C);
3420 
3421   // ((A ^ C) ^ B) | (B ^ A) -> (B ^ A) | C
3422   if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
3423     if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
3424       return BinaryOperator::CreateOr(Op1, C);
3425 
3426   // ((A & B) ^ C) | B -> C | B
3427   if (match(Op0, m_c_Xor(m_c_And(m_Value(A), m_Specific(Op1)), m_Value(C))))
3428     return BinaryOperator::CreateOr(C, Op1);
3429 
3430   // B | ((A & B) ^ C) -> B | C
3431   if (match(Op1, m_c_Xor(m_c_And(m_Value(A), m_Specific(Op0)), m_Value(C))))
3432     return BinaryOperator::CreateOr(Op0, C);
3433 
3434   // ((B | C) & A) | B -> B | (A & C)
3435   if (match(Op0, m_And(m_Or(m_Specific(Op1), m_Value(C)), m_Value(A))))
3436     return BinaryOperator::CreateOr(Op1, Builder.CreateAnd(A, C));
3437 
3438   if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder))
3439     return DeMorgan;
3440 
3441   // Canonicalize xor to the RHS.
3442   bool SwappedForXor = false;
3443   if (match(Op0, m_Xor(m_Value(), m_Value()))) {
3444     std::swap(Op0, Op1);
3445     SwappedForXor = true;
3446   }
3447 
3448   if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3449     // (A | ?) | (A ^ B) --> (A | ?) | B
3450     // (B | ?) | (A ^ B) --> (B | ?) | A
3451     if (match(Op0, m_c_Or(m_Specific(A), m_Value())))
3452       return BinaryOperator::CreateOr(Op0, B);
3453     if (match(Op0, m_c_Or(m_Specific(B), m_Value())))
3454       return BinaryOperator::CreateOr(Op0, A);
3455 
3456     // (A & B) | (A ^ B) --> A | B
3457     // (B & A) | (A ^ B) --> A | B
3458     if (match(Op0, m_And(m_Specific(A), m_Specific(B))) ||
3459         match(Op0, m_And(m_Specific(B), m_Specific(A))))
3460       return BinaryOperator::CreateOr(A, B);
3461 
3462     // ~A | (A ^ B) --> ~(A & B)
3463     // ~B | (A ^ B) --> ~(A & B)
3464     // The swap above should always make Op0 the 'not'.
3465     if ((Op0->hasOneUse() || Op1->hasOneUse()) &&
3466         (match(Op0, m_Not(m_Specific(A))) || match(Op0, m_Not(m_Specific(B)))))
3467       return BinaryOperator::CreateNot(Builder.CreateAnd(A, B));
3468 
3469     // Same as above, but peek through an 'and' to the common operand:
3470     // ~(A & ?) | (A ^ B) --> ~((A & ?) & B)
3471     // ~(B & ?) | (A ^ B) --> ~((B & ?) & A)
3472     Instruction *And;
3473     if ((Op0->hasOneUse() || Op1->hasOneUse()) &&
3474         match(Op0, m_Not(m_CombineAnd(m_Instruction(And),
3475                                       m_c_And(m_Specific(A), m_Value())))))
3476       return BinaryOperator::CreateNot(Builder.CreateAnd(And, B));
3477     if ((Op0->hasOneUse() || Op1->hasOneUse()) &&
3478         match(Op0, m_Not(m_CombineAnd(m_Instruction(And),
3479                                       m_c_And(m_Specific(B), m_Value())))))
3480       return BinaryOperator::CreateNot(Builder.CreateAnd(And, A));
3481 
3482     // (~A | C) | (A ^ B) --> ~(A & B) | C
3483     // (~B | C) | (A ^ B) --> ~(A & B) | C
3484     if (Op0->hasOneUse() && Op1->hasOneUse() &&
3485         (match(Op0, m_c_Or(m_Not(m_Specific(A)), m_Value(C))) ||
3486          match(Op0, m_c_Or(m_Not(m_Specific(B)), m_Value(C))))) {
3487       Value *Nand = Builder.CreateNot(Builder.CreateAnd(A, B), "nand");
3488       return BinaryOperator::CreateOr(Nand, C);
3489     }
3490 
3491     // A | (~A ^ B) --> ~B | A
3492     // B | (A ^ ~B) --> ~A | B
3493     if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) {
3494       Value *NotB = Builder.CreateNot(B, B->getName() + ".not");
3495       return BinaryOperator::CreateOr(NotB, Op0);
3496     }
3497     if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) {
3498       Value *NotA = Builder.CreateNot(A, A->getName() + ".not");
3499       return BinaryOperator::CreateOr(NotA, Op0);
3500     }
3501   }
3502 
3503   // A | ~(A | B) -> A | ~B
3504   // A | ~(A ^ B) -> A | ~B
3505   if (match(Op1, m_Not(m_Value(A))))
3506     if (BinaryOperator *B = dyn_cast<BinaryOperator>(A))
3507       if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) &&
3508           Op1->hasOneUse() && (B->getOpcode() == Instruction::Or ||
3509                                B->getOpcode() == Instruction::Xor)) {
3510         Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) :
3511                                                  B->getOperand(0);
3512         Value *Not = Builder.CreateNot(NotOp, NotOp->getName() + ".not");
3513         return BinaryOperator::CreateOr(Not, Op0);
3514       }
3515 
3516   if (SwappedForXor)
3517     std::swap(Op0, Op1);
3518 
3519   {
3520     ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
3521     ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
3522     if (LHS && RHS)
3523       if (Value *Res = foldAndOrOfICmps(LHS, RHS, I, /* IsAnd */ false))
3524         return replaceInstUsesWith(I, Res);
3525 
3526     // TODO: Make this recursive; it's a little tricky because an arbitrary
3527     // number of 'or' instructions might have to be created.
3528     Value *X, *Y;
3529     if (LHS && match(Op1, m_OneUse(m_LogicalOr(m_Value(X), m_Value(Y))))) {
3530       bool IsLogical = isa<SelectInst>(Op1);
3531       // LHS | (X || Y) --> (LHS || X) || Y
3532       if (auto *Cmp = dyn_cast<ICmpInst>(X))
3533         if (Value *Res =
3534                 foldAndOrOfICmps(LHS, Cmp, I, /* IsAnd */ false, IsLogical))
3535           return replaceInstUsesWith(I, IsLogical
3536                                             ? Builder.CreateLogicalOr(Res, Y)
3537                                             : Builder.CreateOr(Res, Y));
3538       // LHS | (X || Y) --> X || (LHS | Y)
3539       if (auto *Cmp = dyn_cast<ICmpInst>(Y))
3540         if (Value *Res = foldAndOrOfICmps(LHS, Cmp, I, /* IsAnd */ false,
3541                                           /* IsLogical */ false))
3542           return replaceInstUsesWith(I, IsLogical
3543                                             ? Builder.CreateLogicalOr(X, Res)
3544                                             : Builder.CreateOr(X, Res));
3545     }
3546     if (RHS && match(Op0, m_OneUse(m_LogicalOr(m_Value(X), m_Value(Y))))) {
3547       bool IsLogical = isa<SelectInst>(Op0);
3548       // (X || Y) | RHS --> (X || RHS) || Y
3549       if (auto *Cmp = dyn_cast<ICmpInst>(X))
3550         if (Value *Res =
3551                 foldAndOrOfICmps(Cmp, RHS, I, /* IsAnd */ false, IsLogical))
3552           return replaceInstUsesWith(I, IsLogical
3553                                             ? Builder.CreateLogicalOr(Res, Y)
3554                                             : Builder.CreateOr(Res, Y));
3555       // (X || Y) | RHS --> X || (Y | RHS)
3556       if (auto *Cmp = dyn_cast<ICmpInst>(Y))
3557         if (Value *Res = foldAndOrOfICmps(Cmp, RHS, I, /* IsAnd */ false,
3558                                           /* IsLogical */ false))
3559           return replaceInstUsesWith(I, IsLogical
3560                                             ? Builder.CreateLogicalOr(X, Res)
3561                                             : Builder.CreateOr(X, Res));
3562     }
3563   }
3564 
3565   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
3566     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
3567       if (Value *Res = foldLogicOfFCmps(LHS, RHS, /*IsAnd*/ false))
3568         return replaceInstUsesWith(I, Res);
3569 
3570   if (Instruction *FoldedFCmps = reassociateFCmps(I, Builder))
3571     return FoldedFCmps;
3572 
3573   if (Instruction *CastedOr = foldCastedBitwiseLogic(I))
3574     return CastedOr;
3575 
3576   if (Instruction *Sel = foldBinopOfSextBoolToSelect(I))
3577     return Sel;
3578 
3579   // or(sext(A), B) / or(B, sext(A)) --> A ? -1 : B, where A is i1 or <N x i1>.
3580   // TODO: Move this into foldBinopOfSextBoolToSelect as a more generalized fold
3581   //       with binop identity constant. But creating a select with non-constant
3582   //       arm may not be reversible due to poison semantics. Is that a good
3583   //       canonicalization?
3584   if (match(Op0, m_OneUse(m_SExt(m_Value(A)))) &&
3585       A->getType()->isIntOrIntVectorTy(1))
3586     return SelectInst::Create(A, ConstantInt::getAllOnesValue(Ty), Op1);
3587   if (match(Op1, m_OneUse(m_SExt(m_Value(A)))) &&
3588       A->getType()->isIntOrIntVectorTy(1))
3589     return SelectInst::Create(A, ConstantInt::getAllOnesValue(Ty), Op0);
3590 
3591   // Note: If we've gotten to the point of visiting the outer OR, then the
3592   // inner one couldn't be simplified.  If it was a constant, then it won't
3593   // be simplified by a later pass either, so we try swapping the inner/outer
3594   // ORs in the hopes that we'll be able to simplify it this way.
3595   // (X|C) | V --> (X|V) | C
3596   ConstantInt *CI;
3597   if (Op0->hasOneUse() && !match(Op1, m_ConstantInt()) &&
3598       match(Op0, m_Or(m_Value(A), m_ConstantInt(CI)))) {
3599     Value *Inner = Builder.CreateOr(A, Op1);
3600     Inner->takeName(Op0);
3601     return BinaryOperator::CreateOr(Inner, CI);
3602   }
3603 
3604   // Change (or (bool?A:B),(bool?C:D)) --> (bool?(or A,C):(or B,D))
3605   // Since this OR statement hasn't been optimized further yet, we hope
3606   // that this transformation will allow the new ORs to be optimized.
3607   {
3608     Value *X = nullptr, *Y = nullptr;
3609     if (Op0->hasOneUse() && Op1->hasOneUse() &&
3610         match(Op0, m_Select(m_Value(X), m_Value(A), m_Value(B))) &&
3611         match(Op1, m_Select(m_Value(Y), m_Value(C), m_Value(D))) && X == Y) {
3612       Value *orTrue = Builder.CreateOr(A, C);
3613       Value *orFalse = Builder.CreateOr(B, D);
3614       return SelectInst::Create(X, orTrue, orFalse);
3615     }
3616   }
3617 
3618   // or(ashr(subNSW(Y, X), ScalarSizeInBits(Y) - 1), X)  --> X s> Y ? -1 : X.
3619   {
3620     Value *X, *Y;
3621     if (match(&I, m_c_Or(m_OneUse(m_AShr(
3622                              m_NSWSub(m_Value(Y), m_Value(X)),
3623                              m_SpecificInt(Ty->getScalarSizeInBits() - 1))),
3624                          m_Deferred(X)))) {
3625       Value *NewICmpInst = Builder.CreateICmpSGT(X, Y);
3626       Value *AllOnes = ConstantInt::getAllOnesValue(Ty);
3627       return SelectInst::Create(NewICmpInst, AllOnes, X);
3628     }
3629   }
3630 
3631   if (Instruction *V =
3632           canonicalizeCondSignextOfHighBitExtractToSignextHighBitExtract(I))
3633     return V;
3634 
3635   CmpInst::Predicate Pred;
3636   Value *Mul, *Ov, *MulIsNotZero, *UMulWithOv;
3637   // Check if the OR weakens the overflow condition for umul.with.overflow by
3638   // treating any non-zero result as overflow. In that case, we overflow if both
3639   // umul.with.overflow operands are != 0, as in that case the result can only
3640   // be 0, iff the multiplication overflows.
3641   if (match(&I,
3642             m_c_Or(m_CombineAnd(m_ExtractValue<1>(m_Value(UMulWithOv)),
3643                                 m_Value(Ov)),
3644                    m_CombineAnd(m_ICmp(Pred,
3645                                        m_CombineAnd(m_ExtractValue<0>(
3646                                                         m_Deferred(UMulWithOv)),
3647                                                     m_Value(Mul)),
3648                                        m_ZeroInt()),
3649                                 m_Value(MulIsNotZero)))) &&
3650       (Ov->hasOneUse() || (MulIsNotZero->hasOneUse() && Mul->hasOneUse())) &&
3651       Pred == CmpInst::ICMP_NE) {
3652     Value *A, *B;
3653     if (match(UMulWithOv, m_Intrinsic<Intrinsic::umul_with_overflow>(
3654                               m_Value(A), m_Value(B)))) {
3655       Value *NotNullA = Builder.CreateIsNotNull(A);
3656       Value *NotNullB = Builder.CreateIsNotNull(B);
3657       return BinaryOperator::CreateAnd(NotNullA, NotNullB);
3658     }
3659   }
3660 
3661   // (~x) | y  -->  ~(x & (~y))  iff that gets rid of inversions
3662   if (sinkNotIntoOtherHandOfLogicalOp(I))
3663     return &I;
3664 
3665   // Improve "get low bit mask up to and including bit X" pattern:
3666   //   (1 << X) | ((1 << X) + -1)  -->  -1 l>> (bitwidth(x) - 1 - X)
3667   if (match(&I, m_c_Or(m_Add(m_Shl(m_One(), m_Value(X)), m_AllOnes()),
3668                        m_Shl(m_One(), m_Deferred(X)))) &&
3669       match(&I, m_c_Or(m_OneUse(m_Value()), m_Value()))) {
3670     Value *Sub = Builder.CreateSub(
3671         ConstantInt::get(Ty, Ty->getScalarSizeInBits() - 1), X);
3672     return BinaryOperator::CreateLShr(Constant::getAllOnesValue(Ty), Sub);
3673   }
3674 
3675   // An or recurrence w/loop invariant step is equivelent to (or start, step)
3676   PHINode *PN = nullptr;
3677   Value *Start = nullptr, *Step = nullptr;
3678   if (matchSimpleRecurrence(&I, PN, Start, Step) && DT.dominates(Step, PN))
3679     return replaceInstUsesWith(I, Builder.CreateOr(Start, Step));
3680 
3681   // (A & B) | (C | D) or (C | D) | (A & B)
3682   // Can be combined if C or D is of type (A/B & X)
3683   if (match(&I, m_c_Or(m_OneUse(m_And(m_Value(A), m_Value(B))),
3684                        m_OneUse(m_Or(m_Value(C), m_Value(D)))))) {
3685     // (A & B) | (C | ?) -> C | (? | (A & B))
3686     // (A & B) | (C | ?) -> C | (? | (A & B))
3687     // (A & B) | (C | ?) -> C | (? | (A & B))
3688     // (A & B) | (C | ?) -> C | (? | (A & B))
3689     // (C | ?) | (A & B) -> C | (? | (A & B))
3690     // (C | ?) | (A & B) -> C | (? | (A & B))
3691     // (C | ?) | (A & B) -> C | (? | (A & B))
3692     // (C | ?) | (A & B) -> C | (? | (A & B))
3693     if (match(D, m_OneUse(m_c_And(m_Specific(A), m_Value()))) ||
3694         match(D, m_OneUse(m_c_And(m_Specific(B), m_Value()))))
3695       return BinaryOperator::CreateOr(
3696           C, Builder.CreateOr(D, Builder.CreateAnd(A, B)));
3697     // (A & B) | (? | D) -> (? | (A & B)) | D
3698     // (A & B) | (? | D) -> (? | (A & B)) | D
3699     // (A & B) | (? | D) -> (? | (A & B)) | D
3700     // (A & B) | (? | D) -> (? | (A & B)) | D
3701     // (? | D) | (A & B) -> (? | (A & B)) | D
3702     // (? | D) | (A & B) -> (? | (A & B)) | D
3703     // (? | D) | (A & B) -> (? | (A & B)) | D
3704     // (? | D) | (A & B) -> (? | (A & B)) | D
3705     if (match(C, m_OneUse(m_c_And(m_Specific(A), m_Value()))) ||
3706         match(C, m_OneUse(m_c_And(m_Specific(B), m_Value()))))
3707       return BinaryOperator::CreateOr(
3708           Builder.CreateOr(C, Builder.CreateAnd(A, B)), D);
3709   }
3710 
3711   if (Instruction *R = reassociateForUses(I, Builder))
3712     return R;
3713 
3714   if (Instruction *Canonicalized = canonicalizeLogicFirst(I, Builder))
3715     return Canonicalized;
3716 
3717   if (Instruction *Folded = foldLogicOfIsFPClass(I, Op0, Op1))
3718     return Folded;
3719 
3720   if (Instruction *Res = foldBinOpOfDisplacedShifts(I))
3721     return Res;
3722 
3723   return nullptr;
3724 }
3725 
3726 /// A ^ B can be specified using other logic ops in a variety of patterns. We
3727 /// can fold these early and efficiently by morphing an existing instruction.
3728 static Instruction *foldXorToXor(BinaryOperator &I,
3729                                  InstCombiner::BuilderTy &Builder) {
3730   assert(I.getOpcode() == Instruction::Xor);
3731   Value *Op0 = I.getOperand(0);
3732   Value *Op1 = I.getOperand(1);
3733   Value *A, *B;
3734 
3735   // There are 4 commuted variants for each of the basic patterns.
3736 
3737   // (A & B) ^ (A | B) -> A ^ B
3738   // (A & B) ^ (B | A) -> A ^ B
3739   // (A | B) ^ (A & B) -> A ^ B
3740   // (A | B) ^ (B & A) -> A ^ B
3741   if (match(&I, m_c_Xor(m_And(m_Value(A), m_Value(B)),
3742                         m_c_Or(m_Deferred(A), m_Deferred(B)))))
3743     return BinaryOperator::CreateXor(A, B);
3744 
3745   // (A | ~B) ^ (~A | B) -> A ^ B
3746   // (~B | A) ^ (~A | B) -> A ^ B
3747   // (~A | B) ^ (A | ~B) -> A ^ B
3748   // (B | ~A) ^ (A | ~B) -> A ^ B
3749   if (match(&I, m_Xor(m_c_Or(m_Value(A), m_Not(m_Value(B))),
3750                       m_c_Or(m_Not(m_Deferred(A)), m_Deferred(B)))))
3751     return BinaryOperator::CreateXor(A, B);
3752 
3753   // (A & ~B) ^ (~A & B) -> A ^ B
3754   // (~B & A) ^ (~A & B) -> A ^ B
3755   // (~A & B) ^ (A & ~B) -> A ^ B
3756   // (B & ~A) ^ (A & ~B) -> A ^ B
3757   if (match(&I, m_Xor(m_c_And(m_Value(A), m_Not(m_Value(B))),
3758                       m_c_And(m_Not(m_Deferred(A)), m_Deferred(B)))))
3759     return BinaryOperator::CreateXor(A, B);
3760 
3761   // For the remaining cases we need to get rid of one of the operands.
3762   if (!Op0->hasOneUse() && !Op1->hasOneUse())
3763     return nullptr;
3764 
3765   // (A | B) ^ ~(A & B) -> ~(A ^ B)
3766   // (A | B) ^ ~(B & A) -> ~(A ^ B)
3767   // (A & B) ^ ~(A | B) -> ~(A ^ B)
3768   // (A & B) ^ ~(B | A) -> ~(A ^ B)
3769   // Complexity sorting ensures the not will be on the right side.
3770   if ((match(Op0, m_Or(m_Value(A), m_Value(B))) &&
3771        match(Op1, m_Not(m_c_And(m_Specific(A), m_Specific(B))))) ||
3772       (match(Op0, m_And(m_Value(A), m_Value(B))) &&
3773        match(Op1, m_Not(m_c_Or(m_Specific(A), m_Specific(B))))))
3774     return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
3775 
3776   return nullptr;
3777 }
3778 
3779 Value *InstCombinerImpl::foldXorOfICmps(ICmpInst *LHS, ICmpInst *RHS,
3780                                         BinaryOperator &I) {
3781   assert(I.getOpcode() == Instruction::Xor && I.getOperand(0) == LHS &&
3782          I.getOperand(1) == RHS && "Should be 'xor' with these operands");
3783 
3784   ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
3785   Value *LHS0 = LHS->getOperand(0), *LHS1 = LHS->getOperand(1);
3786   Value *RHS0 = RHS->getOperand(0), *RHS1 = RHS->getOperand(1);
3787 
3788   if (predicatesFoldable(PredL, PredR)) {
3789     if (LHS0 == RHS1 && LHS1 == RHS0) {
3790       std::swap(LHS0, LHS1);
3791       PredL = ICmpInst::getSwappedPredicate(PredL);
3792     }
3793     if (LHS0 == RHS0 && LHS1 == RHS1) {
3794       // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
3795       unsigned Code = getICmpCode(PredL) ^ getICmpCode(PredR);
3796       bool IsSigned = LHS->isSigned() || RHS->isSigned();
3797       return getNewICmpValue(Code, IsSigned, LHS0, LHS1, Builder);
3798     }
3799   }
3800 
3801   // TODO: This can be generalized to compares of non-signbits using
3802   // decomposeBitTestICmp(). It could be enhanced more by using (something like)
3803   // foldLogOpOfMaskedICmps().
3804   const APInt *LC, *RC;
3805   if (match(LHS1, m_APInt(LC)) && match(RHS1, m_APInt(RC)) &&
3806       LHS0->getType() == RHS0->getType() &&
3807       LHS0->getType()->isIntOrIntVectorTy() &&
3808       (LHS->hasOneUse() || RHS->hasOneUse())) {
3809     // Convert xor of signbit tests to signbit test of xor'd values:
3810     // (X > -1) ^ (Y > -1) --> (X ^ Y) < 0
3811     // (X <  0) ^ (Y <  0) --> (X ^ Y) < 0
3812     // (X > -1) ^ (Y <  0) --> (X ^ Y) > -1
3813     // (X <  0) ^ (Y > -1) --> (X ^ Y) > -1
3814     bool TrueIfSignedL, TrueIfSignedR;
3815     if (isSignBitCheck(PredL, *LC, TrueIfSignedL) &&
3816         isSignBitCheck(PredR, *RC, TrueIfSignedR)) {
3817       Value *XorLR = Builder.CreateXor(LHS0, RHS0);
3818       return TrueIfSignedL == TrueIfSignedR ? Builder.CreateIsNeg(XorLR) :
3819                                               Builder.CreateIsNotNeg(XorLR);
3820     }
3821 
3822     // (X > C) ^ (X < C + 2) --> X != C + 1
3823     // (X < C + 2) ^ (X > C) --> X != C + 1
3824     // Considering the correctness of this pattern, we should avoid that C is
3825     // non-negative and C + 2 is negative, although it will be matched by other
3826     // patterns.
3827     const APInt *C1, *C2;
3828     if ((PredL == CmpInst::ICMP_SGT && match(LHS1, m_APInt(C1)) &&
3829          PredR == CmpInst::ICMP_SLT && match(RHS1, m_APInt(C2))) ||
3830         (PredL == CmpInst::ICMP_SLT && match(LHS1, m_APInt(C2)) &&
3831          PredR == CmpInst::ICMP_SGT && match(RHS1, m_APInt(C1))))
3832       if (LHS0 == RHS0 && *C1 + 2 == *C2 &&
3833           (C1->isNegative() || C2->isNonNegative()))
3834         return Builder.CreateICmpNE(LHS0,
3835                                     ConstantInt::get(LHS0->getType(), *C1 + 1));
3836   }
3837 
3838   // Instead of trying to imitate the folds for and/or, decompose this 'xor'
3839   // into those logic ops. That is, try to turn this into an and-of-icmps
3840   // because we have many folds for that pattern.
3841   //
3842   // This is based on a truth table definition of xor:
3843   // X ^ Y --> (X | Y) & !(X & Y)
3844   if (Value *OrICmp = simplifyBinOp(Instruction::Or, LHS, RHS, SQ)) {
3845     // TODO: If OrICmp is true, then the definition of xor simplifies to !(X&Y).
3846     // TODO: If OrICmp is false, the whole thing is false (InstSimplify?).
3847     if (Value *AndICmp = simplifyBinOp(Instruction::And, LHS, RHS, SQ)) {
3848       // TODO: Independently handle cases where the 'and' side is a constant.
3849       ICmpInst *X = nullptr, *Y = nullptr;
3850       if (OrICmp == LHS && AndICmp == RHS) {
3851         // (LHS | RHS) & !(LHS & RHS) --> LHS & !RHS  --> X & !Y
3852         X = LHS;
3853         Y = RHS;
3854       }
3855       if (OrICmp == RHS && AndICmp == LHS) {
3856         // !(LHS & RHS) & (LHS | RHS) --> !LHS & RHS  --> !Y & X
3857         X = RHS;
3858         Y = LHS;
3859       }
3860       if (X && Y && (Y->hasOneUse() || canFreelyInvertAllUsersOf(Y, &I))) {
3861         // Invert the predicate of 'Y', thus inverting its output.
3862         Y->setPredicate(Y->getInversePredicate());
3863         // So, are there other uses of Y?
3864         if (!Y->hasOneUse()) {
3865           // We need to adapt other uses of Y though. Get a value that matches
3866           // the original value of Y before inversion. While this increases
3867           // immediate instruction count, we have just ensured that all the
3868           // users are freely-invertible, so that 'not' *will* get folded away.
3869           BuilderTy::InsertPointGuard Guard(Builder);
3870           // Set insertion point to right after the Y.
3871           Builder.SetInsertPoint(Y->getParent(), ++(Y->getIterator()));
3872           Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
3873           // Replace all uses of Y (excluding the one in NotY!) with NotY.
3874           Worklist.pushUsersToWorkList(*Y);
3875           Y->replaceUsesWithIf(NotY,
3876                                [NotY](Use &U) { return U.getUser() != NotY; });
3877         }
3878         // All done.
3879         return Builder.CreateAnd(LHS, RHS);
3880       }
3881     }
3882   }
3883 
3884   return nullptr;
3885 }
3886 
3887 /// If we have a masked merge, in the canonical form of:
3888 /// (assuming that A only has one use.)
3889 ///   |        A  |  |B|
3890 ///   ((x ^ y) & M) ^ y
3891 ///    |  D  |
3892 /// * If M is inverted:
3893 ///      |  D  |
3894 ///     ((x ^ y) & ~M) ^ y
3895 ///   We can canonicalize by swapping the final xor operand
3896 ///   to eliminate the 'not' of the mask.
3897 ///     ((x ^ y) & M) ^ x
3898 /// * If M is a constant, and D has one use, we transform to 'and' / 'or' ops
3899 ///   because that shortens the dependency chain and improves analysis:
3900 ///     (x & M) | (y & ~M)
3901 static Instruction *visitMaskedMerge(BinaryOperator &I,
3902                                      InstCombiner::BuilderTy &Builder) {
3903   Value *B, *X, *D;
3904   Value *M;
3905   if (!match(&I, m_c_Xor(m_Value(B),
3906                          m_OneUse(m_c_And(
3907                              m_CombineAnd(m_c_Xor(m_Deferred(B), m_Value(X)),
3908                                           m_Value(D)),
3909                              m_Value(M))))))
3910     return nullptr;
3911 
3912   Value *NotM;
3913   if (match(M, m_Not(m_Value(NotM)))) {
3914     // De-invert the mask and swap the value in B part.
3915     Value *NewA = Builder.CreateAnd(D, NotM);
3916     return BinaryOperator::CreateXor(NewA, X);
3917   }
3918 
3919   Constant *C;
3920   if (D->hasOneUse() && match(M, m_Constant(C))) {
3921     // Propagating undef is unsafe. Clamp undef elements to -1.
3922     Type *EltTy = C->getType()->getScalarType();
3923     C = Constant::replaceUndefsWith(C, ConstantInt::getAllOnesValue(EltTy));
3924     // Unfold.
3925     Value *LHS = Builder.CreateAnd(X, C);
3926     Value *NotC = Builder.CreateNot(C);
3927     Value *RHS = Builder.CreateAnd(B, NotC);
3928     return BinaryOperator::CreateOr(LHS, RHS);
3929   }
3930 
3931   return nullptr;
3932 }
3933 
3934 // Transform
3935 //   ~(x ^ y)
3936 // into:
3937 //   (~x) ^ y
3938 // or into
3939 //   x ^ (~y)
3940 static Instruction *sinkNotIntoXor(BinaryOperator &I, Value *X, Value *Y,
3941                                    InstCombiner::BuilderTy &Builder) {
3942   // We only want to do the transform if it is free to do.
3943   if (InstCombiner::isFreeToInvert(X, X->hasOneUse())) {
3944     // Ok, good.
3945   } else if (InstCombiner::isFreeToInvert(Y, Y->hasOneUse())) {
3946     std::swap(X, Y);
3947   } else
3948     return nullptr;
3949 
3950   Value *NotX = Builder.CreateNot(X, X->getName() + ".not");
3951   return BinaryOperator::CreateXor(NotX, Y, I.getName() + ".demorgan");
3952 }
3953 
3954 static Instruction *foldNotXor(BinaryOperator &I,
3955                                InstCombiner::BuilderTy &Builder) {
3956   Value *X, *Y;
3957   // FIXME: one-use check is not needed in general, but currently we are unable
3958   // to fold 'not' into 'icmp', if that 'icmp' has multiple uses. (D35182)
3959   if (!match(&I, m_Not(m_OneUse(m_Xor(m_Value(X), m_Value(Y))))))
3960     return nullptr;
3961 
3962   if (Instruction *NewXor = sinkNotIntoXor(I, X, Y, Builder))
3963     return NewXor;
3964 
3965   auto hasCommonOperand = [](Value *A, Value *B, Value *C, Value *D) {
3966     return A == C || A == D || B == C || B == D;
3967   };
3968 
3969   Value *A, *B, *C, *D;
3970   // Canonicalize ~((A & B) ^ (A | ?)) -> (A & B) | ~(A | ?)
3971   // 4 commuted variants
3972   if (match(X, m_And(m_Value(A), m_Value(B))) &&
3973       match(Y, m_Or(m_Value(C), m_Value(D))) && hasCommonOperand(A, B, C, D)) {
3974     Value *NotY = Builder.CreateNot(Y);
3975     return BinaryOperator::CreateOr(X, NotY);
3976   };
3977 
3978   // Canonicalize ~((A | ?) ^ (A & B)) -> (A & B) | ~(A | ?)
3979   // 4 commuted variants
3980   if (match(Y, m_And(m_Value(A), m_Value(B))) &&
3981       match(X, m_Or(m_Value(C), m_Value(D))) && hasCommonOperand(A, B, C, D)) {
3982     Value *NotX = Builder.CreateNot(X);
3983     return BinaryOperator::CreateOr(Y, NotX);
3984   };
3985 
3986   return nullptr;
3987 }
3988 
3989 /// Canonicalize a shifty way to code absolute value to the more common pattern
3990 /// that uses negation and select.
3991 static Instruction *canonicalizeAbs(BinaryOperator &Xor,
3992                                     InstCombiner::BuilderTy &Builder) {
3993   assert(Xor.getOpcode() == Instruction::Xor && "Expected an xor instruction.");
3994 
3995   // There are 4 potential commuted variants. Move the 'ashr' candidate to Op1.
3996   // We're relying on the fact that we only do this transform when the shift has
3997   // exactly 2 uses and the add has exactly 1 use (otherwise, we might increase
3998   // instructions).
3999   Value *Op0 = Xor.getOperand(0), *Op1 = Xor.getOperand(1);
4000   if (Op0->hasNUses(2))
4001     std::swap(Op0, Op1);
4002 
4003   Type *Ty = Xor.getType();
4004   Value *A;
4005   const APInt *ShAmt;
4006   if (match(Op1, m_AShr(m_Value(A), m_APInt(ShAmt))) &&
4007       Op1->hasNUses(2) && *ShAmt == Ty->getScalarSizeInBits() - 1 &&
4008       match(Op0, m_OneUse(m_c_Add(m_Specific(A), m_Specific(Op1))))) {
4009     // Op1 = ashr i32 A, 31   ; smear the sign bit
4010     // xor (add A, Op1), Op1  ; add -1 and flip bits if negative
4011     // --> (A < 0) ? -A : A
4012     Value *IsNeg = Builder.CreateIsNeg(A);
4013     // Copy the nuw/nsw flags from the add to the negate.
4014     auto *Add = cast<BinaryOperator>(Op0);
4015     Value *NegA = Builder.CreateNeg(A, "", Add->hasNoUnsignedWrap(),
4016                                    Add->hasNoSignedWrap());
4017     return SelectInst::Create(IsNeg, NegA, A);
4018   }
4019   return nullptr;
4020 }
4021 
4022 static bool canFreelyInvert(InstCombiner &IC, Value *Op,
4023                             Instruction *IgnoredUser) {
4024   auto *I = dyn_cast<Instruction>(Op);
4025   return I && IC.isFreeToInvert(I, /*WillInvertAllUses=*/true) &&
4026          InstCombiner::canFreelyInvertAllUsersOf(I, IgnoredUser);
4027 }
4028 
4029 static Value *freelyInvert(InstCombinerImpl &IC, Value *Op,
4030                            Instruction *IgnoredUser) {
4031   auto *I = cast<Instruction>(Op);
4032   IC.Builder.SetInsertPoint(&*I->getInsertionPointAfterDef());
4033   Value *NotOp = IC.Builder.CreateNot(Op, Op->getName() + ".not");
4034   Op->replaceUsesWithIf(NotOp,
4035                         [NotOp](Use &U) { return U.getUser() != NotOp; });
4036   IC.freelyInvertAllUsersOf(NotOp, IgnoredUser);
4037   return NotOp;
4038 }
4039 
4040 // Transform
4041 //   z = ~(x &/| y)
4042 // into:
4043 //   z = ((~x) |/& (~y))
4044 // iff both x and y are free to invert and all uses of z can be freely updated.
4045 bool InstCombinerImpl::sinkNotIntoLogicalOp(Instruction &I) {
4046   Value *Op0, *Op1;
4047   if (!match(&I, m_LogicalOp(m_Value(Op0), m_Value(Op1))))
4048     return false;
4049 
4050   // If this logic op has not been simplified yet, just bail out and let that
4051   // happen first. Otherwise, the code below may wrongly invert.
4052   if (Op0 == Op1)
4053     return false;
4054 
4055   Instruction::BinaryOps NewOpc =
4056       match(&I, m_LogicalAnd()) ? Instruction::Or : Instruction::And;
4057   bool IsBinaryOp = isa<BinaryOperator>(I);
4058 
4059   // Can our users be adapted?
4060   if (!InstCombiner::canFreelyInvertAllUsersOf(&I, /*IgnoredUser=*/nullptr))
4061     return false;
4062 
4063   // And can the operands be adapted?
4064   if (!canFreelyInvert(*this, Op0, &I) || !canFreelyInvert(*this, Op1, &I))
4065     return false;
4066 
4067   Op0 = freelyInvert(*this, Op0, &I);
4068   Op1 = freelyInvert(*this, Op1, &I);
4069 
4070   Builder.SetInsertPoint(I.getInsertionPointAfterDef());
4071   Value *NewLogicOp;
4072   if (IsBinaryOp)
4073     NewLogicOp = Builder.CreateBinOp(NewOpc, Op0, Op1, I.getName() + ".not");
4074   else
4075     NewLogicOp =
4076         Builder.CreateLogicalOp(NewOpc, Op0, Op1, I.getName() + ".not");
4077 
4078   replaceInstUsesWith(I, NewLogicOp);
4079   // We can not just create an outer `not`, it will most likely be immediately
4080   // folded back, reconstructing our initial pattern, and causing an
4081   // infinite combine loop, so immediately manually fold it away.
4082   freelyInvertAllUsersOf(NewLogicOp);
4083   return true;
4084 }
4085 
4086 // Transform
4087 //   z = (~x) &/| y
4088 // into:
4089 //   z = ~(x |/& (~y))
4090 // iff y is free to invert and all uses of z can be freely updated.
4091 bool InstCombinerImpl::sinkNotIntoOtherHandOfLogicalOp(Instruction &I) {
4092   Value *Op0, *Op1;
4093   if (!match(&I, m_LogicalOp(m_Value(Op0), m_Value(Op1))))
4094     return false;
4095   Instruction::BinaryOps NewOpc =
4096       match(&I, m_LogicalAnd()) ? Instruction::Or : Instruction::And;
4097   bool IsBinaryOp = isa<BinaryOperator>(I);
4098 
4099   Value *NotOp0 = nullptr;
4100   Value *NotOp1 = nullptr;
4101   Value **OpToInvert = nullptr;
4102   if (match(Op0, m_Not(m_Value(NotOp0))) && canFreelyInvert(*this, Op1, &I)) {
4103     Op0 = NotOp0;
4104     OpToInvert = &Op1;
4105   } else if (match(Op1, m_Not(m_Value(NotOp1))) &&
4106              canFreelyInvert(*this, Op0, &I)) {
4107     Op1 = NotOp1;
4108     OpToInvert = &Op0;
4109   } else
4110     return false;
4111 
4112   // And can our users be adapted?
4113   if (!InstCombiner::canFreelyInvertAllUsersOf(&I, /*IgnoredUser=*/nullptr))
4114     return false;
4115 
4116   *OpToInvert = freelyInvert(*this, *OpToInvert, &I);
4117 
4118   Builder.SetInsertPoint(&*I.getInsertionPointAfterDef());
4119   Value *NewBinOp;
4120   if (IsBinaryOp)
4121     NewBinOp = Builder.CreateBinOp(NewOpc, Op0, Op1, I.getName() + ".not");
4122   else
4123     NewBinOp = Builder.CreateLogicalOp(NewOpc, Op0, Op1, I.getName() + ".not");
4124   replaceInstUsesWith(I, NewBinOp);
4125   // We can not just create an outer `not`, it will most likely be immediately
4126   // folded back, reconstructing our initial pattern, and causing an
4127   // infinite combine loop, so immediately manually fold it away.
4128   freelyInvertAllUsersOf(NewBinOp);
4129   return true;
4130 }
4131 
4132 Instruction *InstCombinerImpl::foldNot(BinaryOperator &I) {
4133   Value *NotOp;
4134   if (!match(&I, m_Not(m_Value(NotOp))))
4135     return nullptr;
4136 
4137   // Apply DeMorgan's Law for 'nand' / 'nor' logic with an inverted operand.
4138   // We must eliminate the and/or (one-use) for these transforms to not increase
4139   // the instruction count.
4140   //
4141   // ~(~X & Y) --> (X | ~Y)
4142   // ~(Y & ~X) --> (X | ~Y)
4143   //
4144   // Note: The logical matches do not check for the commuted patterns because
4145   //       those are handled via SimplifySelectsFeedingBinaryOp().
4146   Type *Ty = I.getType();
4147   Value *X, *Y;
4148   if (match(NotOp, m_OneUse(m_c_And(m_Not(m_Value(X)), m_Value(Y))))) {
4149     Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
4150     return BinaryOperator::CreateOr(X, NotY);
4151   }
4152   if (match(NotOp, m_OneUse(m_LogicalAnd(m_Not(m_Value(X)), m_Value(Y))))) {
4153     Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
4154     return SelectInst::Create(X, ConstantInt::getTrue(Ty), NotY);
4155   }
4156 
4157   // ~(~X | Y) --> (X & ~Y)
4158   // ~(Y | ~X) --> (X & ~Y)
4159   if (match(NotOp, m_OneUse(m_c_Or(m_Not(m_Value(X)), m_Value(Y))))) {
4160     Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
4161     return BinaryOperator::CreateAnd(X, NotY);
4162   }
4163   if (match(NotOp, m_OneUse(m_LogicalOr(m_Not(m_Value(X)), m_Value(Y))))) {
4164     Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
4165     return SelectInst::Create(X, NotY, ConstantInt::getFalse(Ty));
4166   }
4167 
4168   // Is this a 'not' (~) fed by a binary operator?
4169   BinaryOperator *NotVal;
4170   if (match(NotOp, m_BinOp(NotVal))) {
4171     // ~((-X) | Y) --> (X - 1) & (~Y)
4172     if (match(NotVal,
4173               m_OneUse(m_c_Or(m_OneUse(m_Neg(m_Value(X))), m_Value(Y))))) {
4174       Value *DecX = Builder.CreateAdd(X, ConstantInt::getAllOnesValue(Ty));
4175       Value *NotY = Builder.CreateNot(Y);
4176       return BinaryOperator::CreateAnd(DecX, NotY);
4177     }
4178 
4179     // ~(~X >>s Y) --> (X >>s Y)
4180     if (match(NotVal, m_AShr(m_Not(m_Value(X)), m_Value(Y))))
4181       return BinaryOperator::CreateAShr(X, Y);
4182 
4183     // Bit-hack form of a signbit test for iN type:
4184     // ~(X >>s (N - 1)) --> sext i1 (X > -1) to iN
4185     unsigned FullShift = Ty->getScalarSizeInBits() - 1;
4186     if (match(NotVal, m_OneUse(m_AShr(m_Value(X), m_SpecificInt(FullShift))))) {
4187       Value *IsNotNeg = Builder.CreateIsNotNeg(X, "isnotneg");
4188       return new SExtInst(IsNotNeg, Ty);
4189     }
4190 
4191     // If we are inverting a right-shifted constant, we may be able to eliminate
4192     // the 'not' by inverting the constant and using the opposite shift type.
4193     // Canonicalization rules ensure that only a negative constant uses 'ashr',
4194     // but we must check that in case that transform has not fired yet.
4195 
4196     // ~(C >>s Y) --> ~C >>u Y (when inverting the replicated sign bits)
4197     Constant *C;
4198     if (match(NotVal, m_AShr(m_Constant(C), m_Value(Y))) &&
4199         match(C, m_Negative())) {
4200       // We matched a negative constant, so propagating undef is unsafe.
4201       // Clamp undef elements to -1.
4202       Type *EltTy = Ty->getScalarType();
4203       C = Constant::replaceUndefsWith(C, ConstantInt::getAllOnesValue(EltTy));
4204       return BinaryOperator::CreateLShr(ConstantExpr::getNot(C), Y);
4205     }
4206 
4207     // ~(C >>u Y) --> ~C >>s Y (when inverting the replicated sign bits)
4208     if (match(NotVal, m_LShr(m_Constant(C), m_Value(Y))) &&
4209         match(C, m_NonNegative())) {
4210       // We matched a non-negative constant, so propagating undef is unsafe.
4211       // Clamp undef elements to 0.
4212       Type *EltTy = Ty->getScalarType();
4213       C = Constant::replaceUndefsWith(C, ConstantInt::getNullValue(EltTy));
4214       return BinaryOperator::CreateAShr(ConstantExpr::getNot(C), Y);
4215     }
4216 
4217     // ~(X + C) --> ~C - X
4218     if (match(NotVal, m_c_Add(m_Value(X), m_ImmConstant(C))))
4219       return BinaryOperator::CreateSub(ConstantExpr::getNot(C), X);
4220 
4221     // ~(X - Y) --> ~X + Y
4222     // FIXME: is it really beneficial to sink the `not` here?
4223     if (match(NotVal, m_Sub(m_Value(X), m_Value(Y))))
4224       if (isa<Constant>(X) || NotVal->hasOneUse())
4225         return BinaryOperator::CreateAdd(Builder.CreateNot(X), Y);
4226 
4227     // ~(~X + Y) --> X - Y
4228     if (match(NotVal, m_c_Add(m_Not(m_Value(X)), m_Value(Y))))
4229       return BinaryOperator::CreateWithCopiedFlags(Instruction::Sub, X, Y,
4230                                                    NotVal);
4231   }
4232 
4233   // not (cmp A, B) = !cmp A, B
4234   CmpInst::Predicate Pred;
4235   if (match(NotOp, m_Cmp(Pred, m_Value(), m_Value())) &&
4236       (NotOp->hasOneUse() ||
4237        InstCombiner::canFreelyInvertAllUsersOf(cast<Instruction>(NotOp),
4238                                                /*IgnoredUser=*/nullptr))) {
4239     cast<CmpInst>(NotOp)->setPredicate(CmpInst::getInversePredicate(Pred));
4240     freelyInvertAllUsersOf(NotOp);
4241     return &I;
4242   }
4243 
4244   // Move a 'not' ahead of casts of a bool to enable logic reduction:
4245   // not (bitcast (sext i1 X)) --> bitcast (sext (not i1 X))
4246   if (match(NotOp, m_OneUse(m_BitCast(m_OneUse(m_SExt(m_Value(X)))))) && X->getType()->isIntOrIntVectorTy(1)) {
4247     Type *SextTy = cast<BitCastOperator>(NotOp)->getSrcTy();
4248     Value *NotX = Builder.CreateNot(X);
4249     Value *Sext = Builder.CreateSExt(NotX, SextTy);
4250     return CastInst::CreateBitOrPointerCast(Sext, Ty);
4251   }
4252 
4253   if (auto *NotOpI = dyn_cast<Instruction>(NotOp))
4254     if (sinkNotIntoLogicalOp(*NotOpI))
4255       return &I;
4256 
4257   // Eliminate a bitwise 'not' op of 'not' min/max by inverting the min/max:
4258   // ~min(~X, ~Y) --> max(X, Y)
4259   // ~max(~X, Y) --> min(X, ~Y)
4260   auto *II = dyn_cast<IntrinsicInst>(NotOp);
4261   if (II && II->hasOneUse()) {
4262     if (match(NotOp, m_MaxOrMin(m_Value(X), m_Value(Y))) &&
4263         isFreeToInvert(X, X->hasOneUse()) &&
4264         isFreeToInvert(Y, Y->hasOneUse())) {
4265       Intrinsic::ID InvID = getInverseMinMaxIntrinsic(II->getIntrinsicID());
4266       Value *NotX = Builder.CreateNot(X);
4267       Value *NotY = Builder.CreateNot(Y);
4268       Value *InvMaxMin = Builder.CreateBinaryIntrinsic(InvID, NotX, NotY);
4269       return replaceInstUsesWith(I, InvMaxMin);
4270     }
4271     if (match(NotOp, m_c_MaxOrMin(m_Not(m_Value(X)), m_Value(Y)))) {
4272       Intrinsic::ID InvID = getInverseMinMaxIntrinsic(II->getIntrinsicID());
4273       Value *NotY = Builder.CreateNot(Y);
4274       Value *InvMaxMin = Builder.CreateBinaryIntrinsic(InvID, X, NotY);
4275       return replaceInstUsesWith(I, InvMaxMin);
4276     }
4277 
4278     if (II->getIntrinsicID() == Intrinsic::is_fpclass) {
4279       ConstantInt *ClassMask = cast<ConstantInt>(II->getArgOperand(1));
4280       II->setArgOperand(
4281           1, ConstantInt::get(ClassMask->getType(),
4282                               ~ClassMask->getZExtValue() & fcAllFlags));
4283       return replaceInstUsesWith(I, II);
4284     }
4285   }
4286 
4287   if (NotOp->hasOneUse()) {
4288     // Pull 'not' into operands of select if both operands are one-use compares
4289     // or one is one-use compare and the other one is a constant.
4290     // Inverting the predicates eliminates the 'not' operation.
4291     // Example:
4292     //   not (select ?, (cmp TPred, ?, ?), (cmp FPred, ?, ?) -->
4293     //     select ?, (cmp InvTPred, ?, ?), (cmp InvFPred, ?, ?)
4294     //   not (select ?, (cmp TPred, ?, ?), true -->
4295     //     select ?, (cmp InvTPred, ?, ?), false
4296     if (auto *Sel = dyn_cast<SelectInst>(NotOp)) {
4297       Value *TV = Sel->getTrueValue();
4298       Value *FV = Sel->getFalseValue();
4299       auto *CmpT = dyn_cast<CmpInst>(TV);
4300       auto *CmpF = dyn_cast<CmpInst>(FV);
4301       bool InvertibleT = (CmpT && CmpT->hasOneUse()) || isa<Constant>(TV);
4302       bool InvertibleF = (CmpF && CmpF->hasOneUse()) || isa<Constant>(FV);
4303       if (InvertibleT && InvertibleF) {
4304         if (CmpT)
4305           CmpT->setPredicate(CmpT->getInversePredicate());
4306         else
4307           Sel->setTrueValue(ConstantExpr::getNot(cast<Constant>(TV)));
4308         if (CmpF)
4309           CmpF->setPredicate(CmpF->getInversePredicate());
4310         else
4311           Sel->setFalseValue(ConstantExpr::getNot(cast<Constant>(FV)));
4312         return replaceInstUsesWith(I, Sel);
4313       }
4314     }
4315   }
4316 
4317   if (Instruction *NewXor = foldNotXor(I, Builder))
4318     return NewXor;
4319 
4320   return nullptr;
4321 }
4322 
4323 // FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
4324 // here. We should standardize that construct where it is needed or choose some
4325 // other way to ensure that commutated variants of patterns are not missed.
4326 Instruction *InstCombinerImpl::visitXor(BinaryOperator &I) {
4327   if (Value *V = simplifyXorInst(I.getOperand(0), I.getOperand(1),
4328                                  SQ.getWithInstruction(&I)))
4329     return replaceInstUsesWith(I, V);
4330 
4331   if (SimplifyAssociativeOrCommutative(I))
4332     return &I;
4333 
4334   if (Instruction *X = foldVectorBinop(I))
4335     return X;
4336 
4337   if (Instruction *Phi = foldBinopWithPhiOperands(I))
4338     return Phi;
4339 
4340   if (Instruction *NewXor = foldXorToXor(I, Builder))
4341     return NewXor;
4342 
4343   // (A&B)^(A&C) -> A&(B^C) etc
4344   if (Value *V = foldUsingDistributiveLaws(I))
4345     return replaceInstUsesWith(I, V);
4346 
4347   // See if we can simplify any instructions used by the instruction whose sole
4348   // purpose is to compute bits we don't care about.
4349   if (SimplifyDemandedInstructionBits(I))
4350     return &I;
4351 
4352   if (Value *V = SimplifyBSwap(I, Builder))
4353     return replaceInstUsesWith(I, V);
4354 
4355   if (Instruction *R = foldNot(I))
4356     return R;
4357 
4358   if (Instruction *R = foldBinOpShiftWithShift(I))
4359     return R;
4360 
4361   // Fold (X & M) ^ (Y & ~M) -> (X & M) | (Y & ~M)
4362   // This it a special case in haveNoCommonBitsSet, but the computeKnownBits
4363   // calls in there are unnecessary as SimplifyDemandedInstructionBits should
4364   // have already taken care of those cases.
4365   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4366   Value *M;
4367   if (match(&I, m_c_Xor(m_c_And(m_Not(m_Value(M)), m_Value()),
4368                         m_c_And(m_Deferred(M), m_Value()))))
4369     return BinaryOperator::CreateOr(Op0, Op1);
4370 
4371   if (Instruction *Xor = visitMaskedMerge(I, Builder))
4372     return Xor;
4373 
4374   Value *X, *Y;
4375   Constant *C1;
4376   if (match(Op1, m_Constant(C1))) {
4377     Constant *C2;
4378 
4379     if (match(Op0, m_OneUse(m_Or(m_Value(X), m_ImmConstant(C2)))) &&
4380         match(C1, m_ImmConstant())) {
4381       // (X | C2) ^ C1 --> (X & ~C2) ^ (C1^C2)
4382       C2 = Constant::replaceUndefsWith(
4383           C2, Constant::getAllOnesValue(C2->getType()->getScalarType()));
4384       Value *And = Builder.CreateAnd(
4385           X, Constant::mergeUndefsWith(ConstantExpr::getNot(C2), C1));
4386       return BinaryOperator::CreateXor(
4387           And, Constant::mergeUndefsWith(ConstantExpr::getXor(C1, C2), C1));
4388     }
4389 
4390     // Use DeMorgan and reassociation to eliminate a 'not' op.
4391     if (match(Op0, m_OneUse(m_Or(m_Not(m_Value(X)), m_Constant(C2))))) {
4392       // (~X | C2) ^ C1 --> ((X & ~C2) ^ -1) ^ C1 --> (X & ~C2) ^ ~C1
4393       Value *And = Builder.CreateAnd(X, ConstantExpr::getNot(C2));
4394       return BinaryOperator::CreateXor(And, ConstantExpr::getNot(C1));
4395     }
4396     if (match(Op0, m_OneUse(m_And(m_Not(m_Value(X)), m_Constant(C2))))) {
4397       // (~X & C2) ^ C1 --> ((X | ~C2) ^ -1) ^ C1 --> (X | ~C2) ^ ~C1
4398       Value *Or = Builder.CreateOr(X, ConstantExpr::getNot(C2));
4399       return BinaryOperator::CreateXor(Or, ConstantExpr::getNot(C1));
4400     }
4401 
4402     // Convert xor ([trunc] (ashr X, BW-1)), C =>
4403     //   select(X >s -1, C, ~C)
4404     // The ashr creates "AllZeroOrAllOne's", which then optionally inverses the
4405     // constant depending on whether this input is less than 0.
4406     const APInt *CA;
4407     if (match(Op0, m_OneUse(m_TruncOrSelf(
4408                        m_AShr(m_Value(X), m_APIntAllowUndef(CA))))) &&
4409         *CA == X->getType()->getScalarSizeInBits() - 1 &&
4410         !match(C1, m_AllOnes())) {
4411       assert(!C1->isZeroValue() && "Unexpected xor with 0");
4412       Value *IsNotNeg = Builder.CreateIsNotNeg(X);
4413       return SelectInst::Create(IsNotNeg, Op1, Builder.CreateNot(Op1));
4414     }
4415   }
4416 
4417   Type *Ty = I.getType();
4418   {
4419     const APInt *RHSC;
4420     if (match(Op1, m_APInt(RHSC))) {
4421       Value *X;
4422       const APInt *C;
4423       // (C - X) ^ signmaskC --> (C + signmaskC) - X
4424       if (RHSC->isSignMask() && match(Op0, m_Sub(m_APInt(C), m_Value(X))))
4425         return BinaryOperator::CreateSub(ConstantInt::get(Ty, *C + *RHSC), X);
4426 
4427       // (X + C) ^ signmaskC --> X + (C + signmaskC)
4428       if (RHSC->isSignMask() && match(Op0, m_Add(m_Value(X), m_APInt(C))))
4429         return BinaryOperator::CreateAdd(X, ConstantInt::get(Ty, *C + *RHSC));
4430 
4431       // (X | C) ^ RHSC --> X ^ (C ^ RHSC) iff X & C == 0
4432       if (match(Op0, m_Or(m_Value(X), m_APInt(C))) &&
4433           MaskedValueIsZero(X, *C, 0, &I))
4434         return BinaryOperator::CreateXor(X, ConstantInt::get(Ty, *C ^ *RHSC));
4435 
4436       // When X is a power-of-two or zero and zero input is poison:
4437       // ctlz(i32 X) ^ 31 --> cttz(X)
4438       // cttz(i32 X) ^ 31 --> ctlz(X)
4439       auto *II = dyn_cast<IntrinsicInst>(Op0);
4440       if (II && II->hasOneUse() && *RHSC == Ty->getScalarSizeInBits() - 1) {
4441         Intrinsic::ID IID = II->getIntrinsicID();
4442         if ((IID == Intrinsic::ctlz || IID == Intrinsic::cttz) &&
4443             match(II->getArgOperand(1), m_One()) &&
4444             isKnownToBeAPowerOfTwo(II->getArgOperand(0), /*OrZero */ true)) {
4445           IID = (IID == Intrinsic::ctlz) ? Intrinsic::cttz : Intrinsic::ctlz;
4446           Function *F = Intrinsic::getDeclaration(II->getModule(), IID, Ty);
4447           return CallInst::Create(F, {II->getArgOperand(0), Builder.getTrue()});
4448         }
4449       }
4450 
4451       // If RHSC is inverting the remaining bits of shifted X,
4452       // canonicalize to a 'not' before the shift to help SCEV and codegen:
4453       // (X << C) ^ RHSC --> ~X << C
4454       if (match(Op0, m_OneUse(m_Shl(m_Value(X), m_APInt(C)))) &&
4455           *RHSC == APInt::getAllOnes(Ty->getScalarSizeInBits()).shl(*C)) {
4456         Value *NotX = Builder.CreateNot(X);
4457         return BinaryOperator::CreateShl(NotX, ConstantInt::get(Ty, *C));
4458       }
4459       // (X >>u C) ^ RHSC --> ~X >>u C
4460       if (match(Op0, m_OneUse(m_LShr(m_Value(X), m_APInt(C)))) &&
4461           *RHSC == APInt::getAllOnes(Ty->getScalarSizeInBits()).lshr(*C)) {
4462         Value *NotX = Builder.CreateNot(X);
4463         return BinaryOperator::CreateLShr(NotX, ConstantInt::get(Ty, *C));
4464       }
4465       // TODO: We could handle 'ashr' here as well. That would be matching
4466       //       a 'not' op and moving it before the shift. Doing that requires
4467       //       preventing the inverse fold in canShiftBinOpWithConstantRHS().
4468     }
4469   }
4470 
4471   // FIXME: This should not be limited to scalar (pull into APInt match above).
4472   {
4473     Value *X;
4474     ConstantInt *C1, *C2, *C3;
4475     // ((X^C1) >> C2) ^ C3 -> (X>>C2) ^ ((C1>>C2)^C3)
4476     if (match(Op1, m_ConstantInt(C3)) &&
4477         match(Op0, m_LShr(m_Xor(m_Value(X), m_ConstantInt(C1)),
4478                           m_ConstantInt(C2))) &&
4479         Op0->hasOneUse()) {
4480       // fold (C1 >> C2) ^ C3
4481       APInt FoldConst = C1->getValue().lshr(C2->getValue());
4482       FoldConst ^= C3->getValue();
4483       // Prepare the two operands.
4484       auto *Opnd0 = Builder.CreateLShr(X, C2);
4485       Opnd0->takeName(Op0);
4486       return BinaryOperator::CreateXor(Opnd0, ConstantInt::get(Ty, FoldConst));
4487     }
4488   }
4489 
4490   if (Instruction *FoldedLogic = foldBinOpIntoSelectOrPhi(I))
4491     return FoldedLogic;
4492 
4493   // Y ^ (X | Y) --> X & ~Y
4494   // Y ^ (Y | X) --> X & ~Y
4495   if (match(Op1, m_OneUse(m_c_Or(m_Value(X), m_Specific(Op0)))))
4496     return BinaryOperator::CreateAnd(X, Builder.CreateNot(Op0));
4497   // (X | Y) ^ Y --> X & ~Y
4498   // (Y | X) ^ Y --> X & ~Y
4499   if (match(Op0, m_OneUse(m_c_Or(m_Value(X), m_Specific(Op1)))))
4500     return BinaryOperator::CreateAnd(X, Builder.CreateNot(Op1));
4501 
4502   // Y ^ (X & Y) --> ~X & Y
4503   // Y ^ (Y & X) --> ~X & Y
4504   if (match(Op1, m_OneUse(m_c_And(m_Value(X), m_Specific(Op0)))))
4505     return BinaryOperator::CreateAnd(Op0, Builder.CreateNot(X));
4506   // (X & Y) ^ Y --> ~X & Y
4507   // (Y & X) ^ Y --> ~X & Y
4508   // Canonical form is (X & C) ^ C; don't touch that.
4509   // TODO: A 'not' op is better for analysis and codegen, but demanded bits must
4510   //       be fixed to prefer that (otherwise we get infinite looping).
4511   if (!match(Op1, m_Constant()) &&
4512       match(Op0, m_OneUse(m_c_And(m_Value(X), m_Specific(Op1)))))
4513     return BinaryOperator::CreateAnd(Op1, Builder.CreateNot(X));
4514 
4515   Value *A, *B, *C;
4516   // (A ^ B) ^ (A | C) --> (~A & C) ^ B -- There are 4 commuted variants.
4517   if (match(&I, m_c_Xor(m_OneUse(m_Xor(m_Value(A), m_Value(B))),
4518                         m_OneUse(m_c_Or(m_Deferred(A), m_Value(C))))))
4519       return BinaryOperator::CreateXor(
4520           Builder.CreateAnd(Builder.CreateNot(A), C), B);
4521 
4522   // (A ^ B) ^ (B | C) --> (~B & C) ^ A -- There are 4 commuted variants.
4523   if (match(&I, m_c_Xor(m_OneUse(m_Xor(m_Value(A), m_Value(B))),
4524                         m_OneUse(m_c_Or(m_Deferred(B), m_Value(C))))))
4525       return BinaryOperator::CreateXor(
4526           Builder.CreateAnd(Builder.CreateNot(B), C), A);
4527 
4528   // (A & B) ^ (A ^ B) -> (A | B)
4529   if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
4530       match(Op1, m_c_Xor(m_Specific(A), m_Specific(B))))
4531     return BinaryOperator::CreateOr(A, B);
4532   // (A ^ B) ^ (A & B) -> (A | B)
4533   if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
4534       match(Op1, m_c_And(m_Specific(A), m_Specific(B))))
4535     return BinaryOperator::CreateOr(A, B);
4536 
4537   // (A & ~B) ^ ~A -> ~(A & B)
4538   // (~B & A) ^ ~A -> ~(A & B)
4539   if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
4540       match(Op1, m_Not(m_Specific(A))))
4541     return BinaryOperator::CreateNot(Builder.CreateAnd(A, B));
4542 
4543   // (~A & B) ^ A --> A | B -- There are 4 commuted variants.
4544   if (match(&I, m_c_Xor(m_c_And(m_Not(m_Value(A)), m_Value(B)), m_Deferred(A))))
4545     return BinaryOperator::CreateOr(A, B);
4546 
4547   // (~A | B) ^ A --> ~(A & B)
4548   if (match(Op0, m_OneUse(m_c_Or(m_Not(m_Specific(Op1)), m_Value(B)))))
4549     return BinaryOperator::CreateNot(Builder.CreateAnd(Op1, B));
4550 
4551   // A ^ (~A | B) --> ~(A & B)
4552   if (match(Op1, m_OneUse(m_c_Or(m_Not(m_Specific(Op0)), m_Value(B)))))
4553     return BinaryOperator::CreateNot(Builder.CreateAnd(Op0, B));
4554 
4555   // (A | B) ^ (A | C) --> (B ^ C) & ~A -- There are 4 commuted variants.
4556   // TODO: Loosen one-use restriction if common operand is a constant.
4557   Value *D;
4558   if (match(Op0, m_OneUse(m_Or(m_Value(A), m_Value(B)))) &&
4559       match(Op1, m_OneUse(m_Or(m_Value(C), m_Value(D))))) {
4560     if (B == C || B == D)
4561       std::swap(A, B);
4562     if (A == C)
4563       std::swap(C, D);
4564     if (A == D) {
4565       Value *NotA = Builder.CreateNot(A);
4566       return BinaryOperator::CreateAnd(Builder.CreateXor(B, C), NotA);
4567     }
4568   }
4569 
4570   // (A & B) ^ (A | C) --> A ? ~B : C -- There are 4 commuted variants.
4571   if (I.getType()->isIntOrIntVectorTy(1) &&
4572       match(Op0, m_OneUse(m_LogicalAnd(m_Value(A), m_Value(B)))) &&
4573       match(Op1, m_OneUse(m_LogicalOr(m_Value(C), m_Value(D))))) {
4574     bool NeedFreeze = isa<SelectInst>(Op0) && isa<SelectInst>(Op1) && B == D;
4575     if (B == C || B == D)
4576       std::swap(A, B);
4577     if (A == C)
4578       std::swap(C, D);
4579     if (A == D) {
4580       if (NeedFreeze)
4581         A = Builder.CreateFreeze(A);
4582       Value *NotB = Builder.CreateNot(B);
4583       return SelectInst::Create(A, NotB, C);
4584     }
4585   }
4586 
4587   if (auto *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4588     if (auto *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4589       if (Value *V = foldXorOfICmps(LHS, RHS, I))
4590         return replaceInstUsesWith(I, V);
4591 
4592   if (Instruction *CastedXor = foldCastedBitwiseLogic(I))
4593     return CastedXor;
4594 
4595   if (Instruction *Abs = canonicalizeAbs(I, Builder))
4596     return Abs;
4597 
4598   // Otherwise, if all else failed, try to hoist the xor-by-constant:
4599   //   (X ^ C) ^ Y --> (X ^ Y) ^ C
4600   // Just like we do in other places, we completely avoid the fold
4601   // for constantexprs, at least to avoid endless combine loop.
4602   if (match(&I, m_c_Xor(m_OneUse(m_Xor(m_CombineAnd(m_Value(X),
4603                                                     m_Unless(m_ConstantExpr())),
4604                                        m_ImmConstant(C1))),
4605                         m_Value(Y))))
4606     return BinaryOperator::CreateXor(Builder.CreateXor(X, Y), C1);
4607 
4608   if (Instruction *R = reassociateForUses(I, Builder))
4609     return R;
4610 
4611   if (Instruction *Canonicalized = canonicalizeLogicFirst(I, Builder))
4612     return Canonicalized;
4613 
4614   if (Instruction *Folded = foldLogicOfIsFPClass(I, Op0, Op1))
4615     return Folded;
4616 
4617   if (Instruction *Folded = canonicalizeConditionalNegationViaMathToSelect(I))
4618     return Folded;
4619 
4620   if (Instruction *Res = foldBinOpOfDisplacedShifts(I))
4621     return Res;
4622 
4623   return nullptr;
4624 }
4625