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