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