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  // TODO: Do this for vectors by using m_APInt isntead of m_ConstantInt.
1668  switch (Op0I->getOpcode()) {
1669  default:
1670  break;
1671  case Instruction::Xor:
1672  case Instruction::Or:
1673  case Instruction::Mul:
1674  case Instruction::Add:
1675  case Instruction::Sub:
1676  Value *X;
1677  ConstantInt *C1;
1678  // TODO: The one use restrictions could be relaxed a little if the AND
1679  // is going to be removed.
1680  if (match(Op0I, m_OneUse(m_c_BinOp(m_OneUse(m_ZExt(m_Value(X))),
1681  m_ConstantInt(C1))))) {
1682  if (AndRHSMask.isIntN(X->getType()->getScalarSizeInBits())) {
1683  auto *TruncC1 = ConstantExpr::getTrunc(C1, X->getType());
1684  Value *BinOp;
1685  Value *Op0LHS = Op0I->getOperand(0);
1686  if (isa<ZExtInst>(Op0LHS))
1687  BinOp = Builder.CreateBinOp(Op0I->getOpcode(), X, TruncC1);
1688  else
1689  BinOp = Builder.CreateBinOp(Op0I->getOpcode(), TruncC1, X);
1690  auto *TruncC2 = ConstantExpr::getTrunc(AndRHS, X->getType());
1691  auto *And = Builder.CreateAnd(BinOp, TruncC2);
1692  return new ZExtInst(And, I.getType());
1693  }
1694  }
1695  }
1696 
1697  if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1698  if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
1699  return Res;
1700  }
1701 
1702  // If this is an integer truncation, and if the source is an 'and' with
1703  // immediate, transform it. This frequently occurs for bitfield accesses.
1704  {
1705  Value *X = nullptr; ConstantInt *YC = nullptr;
1706  if (match(Op0, m_Trunc(m_And(m_Value(X), m_ConstantInt(YC))))) {
1707  // Change: and (trunc (and X, YC) to T), C2
1708  // into : and (trunc X to T), trunc(YC) & C2
1709  // This will fold the two constants together, which may allow
1710  // other simplifications.
1711  Value *NewCast = Builder.CreateTrunc(X, I.getType(), "and.shrunk");
1712  Constant *C3 = ConstantExpr::getTrunc(YC, I.getType());
1713  C3 = ConstantExpr::getAnd(C3, AndRHS);
1714  return BinaryOperator::CreateAnd(NewCast, C3);
1715  }
1716  }
1717  }
1718 
1719  if (Instruction *Z = narrowMaskedBinOp(I))
1720  return Z;
1721 
1722  if (Instruction *FoldedLogic = foldBinOpIntoSelectOrPhi(I))
1723  return FoldedLogic;
1724 
1725  if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder))
1726  return DeMorgan;
1727 
1728  {
1729  Value *A, *B, *C;
1730  // A & (A ^ B) --> A & ~B
1731  if (match(Op1, m_OneUse(m_c_Xor(m_Specific(Op0), m_Value(B)))))
1732  return BinaryOperator::CreateAnd(Op0, Builder.CreateNot(B));
1733  // (A ^ B) & A --> A & ~B
1734  if (match(Op0, m_OneUse(m_c_Xor(m_Specific(Op1), m_Value(B)))))
1735  return BinaryOperator::CreateAnd(Op1, Builder.CreateNot(B));
1736 
1737  // (A ^ B) & ((B ^ C) ^ A) -> (A ^ B) & ~C
1738  if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
1739  if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
1740  if (Op1->hasOneUse() || IsFreeToInvert(C, C->hasOneUse()))
1741  return BinaryOperator::CreateAnd(Op0, Builder.CreateNot(C));
1742 
1743  // ((A ^ C) ^ B) & (B ^ A) -> (B ^ A) & ~C
1744  if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
1745  if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
1746  if (Op0->hasOneUse() || IsFreeToInvert(C, C->hasOneUse()))
1747  return BinaryOperator::CreateAnd(Op1, Builder.CreateNot(C));
1748 
1749  // (A | B) & ((~A) ^ B) -> (A & B)
1750  // (A | B) & (B ^ (~A)) -> (A & B)
1751  // (B | A) & ((~A) ^ B) -> (A & B)
1752  // (B | A) & (B ^ (~A)) -> (A & B)
1753  if (match(Op1, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
1754  match(Op0, m_c_Or(m_Specific(A), m_Specific(B))))
1755  return BinaryOperator::CreateAnd(A, B);
1756 
1757  // ((~A) ^ B) & (A | B) -> (A & B)
1758  // ((~A) ^ B) & (B | A) -> (A & B)
1759  // (B ^ (~A)) & (A | B) -> (A & B)
1760  // (B ^ (~A)) & (B | A) -> (A & B)
1761  if (match(Op0, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
1762  match(Op1, m_c_Or(m_Specific(A), m_Specific(B))))
1763  return BinaryOperator::CreateAnd(A, B);
1764  }
1765 
1766  {
1767  ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
1768  ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
1769  if (LHS && RHS)
1770  if (Value *Res = foldAndOfICmps(LHS, RHS, I))
1771  return replaceInstUsesWith(I, Res);
1772 
1773  // TODO: Make this recursive; it's a little tricky because an arbitrary
1774  // number of 'and' instructions might have to be created.
1775  Value *X, *Y;
1776  if (LHS && match(Op1, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1777  if (auto *Cmp = dyn_cast<ICmpInst>(X))
1778  if (Value *Res = foldAndOfICmps(LHS, Cmp, I))
1779  return replaceInstUsesWith(I, Builder.CreateAnd(Res, Y));
1780  if (auto *Cmp = dyn_cast<ICmpInst>(Y))
1781  if (Value *Res = foldAndOfICmps(LHS, Cmp, I))
1782  return replaceInstUsesWith(I, Builder.CreateAnd(Res, X));
1783  }
1784  if (RHS && match(Op0, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1785  if (auto *Cmp = dyn_cast<ICmpInst>(X))
1786  if (Value *Res = foldAndOfICmps(Cmp, RHS, I))
1787  return replaceInstUsesWith(I, Builder.CreateAnd(Res, Y));
1788  if (auto *Cmp = dyn_cast<ICmpInst>(Y))
1789  if (Value *Res = foldAndOfICmps(Cmp, RHS, I))
1790  return replaceInstUsesWith(I, Builder.CreateAnd(Res, X));
1791  }
1792  }
1793 
1794  if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1795  if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
1796  if (Value *Res = foldLogicOfFCmps(LHS, RHS, true))
1797  return replaceInstUsesWith(I, Res);
1798 
1799  if (Instruction *FoldedFCmps = reassociateFCmps(I, Builder))
1800  return FoldedFCmps;
1801 
1802  if (Instruction *CastedAnd = foldCastedBitwiseLogic(I))
1803  return CastedAnd;
1804 
1805  // and(sext(A), B) / and(B, sext(A)) --> A ? B : 0, where A is i1 or <N x i1>.
1806  Value *A;
1807  if (match(Op0, m_OneUse(m_SExt(m_Value(A)))) &&
1808  A->getType()->isIntOrIntVectorTy(1))
1809  return SelectInst::Create(A, Op1, Constant::getNullValue(I.getType()));
1810  if (match(Op1, m_OneUse(m_SExt(m_Value(A)))) &&
1811  A->getType()->isIntOrIntVectorTy(1))
1812  return SelectInst::Create(A, Op0, Constant::getNullValue(I.getType()));
1813 
1814  return nullptr;
1815 }
1816 
1817 Instruction *InstCombiner::matchBSwap(BinaryOperator &Or) {
1818  assert(Or.getOpcode() == Instruction::Or && "bswap requires an 'or'");
1819  Value *Op0 = Or.getOperand(0), *Op1 = Or.getOperand(1);
1820 
1821  // Look through zero extends.
1822  if (Instruction *Ext = dyn_cast<ZExtInst>(Op0))
1823  Op0 = Ext->getOperand(0);
1824 
1825  if (Instruction *Ext = dyn_cast<ZExtInst>(Op1))
1826  Op1 = Ext->getOperand(0);
1827 
1828  // (A | B) | C and A | (B | C) -> bswap if possible.
1829  bool OrOfOrs = match(Op0, m_Or(m_Value(), m_Value())) ||
1830  match(Op1, m_Or(m_Value(), m_Value()));
1831 
1832  // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
1833  bool OrOfShifts = match(Op0, m_LogicalShift(m_Value(), m_Value())) &&
1834  match(Op1, m_LogicalShift(m_Value(), m_Value()));
1835 
1836  // (A & B) | (C & D) -> bswap if possible.
1837  bool OrOfAnds = match(Op0, m_And(m_Value(), m_Value())) &&
1838  match(Op1, m_And(m_Value(), m_Value()));
1839 
1840  // (A << B) | (C & D) -> bswap if possible.
1841  // The bigger pattern here is ((A & C1) << C2) | ((B >> C2) & C1), which is a
1842  // part of the bswap idiom for specific values of C1, C2 (e.g. C1 = 16711935,
1843  // C2 = 8 for i32).
1844  // This pattern can occur when the operands of the 'or' are not canonicalized
1845  // for some reason (not having only one use, for example).
1846  bool OrOfAndAndSh = (match(Op0, m_LogicalShift(m_Value(), m_Value())) &&
1847  match(Op1, m_And(m_Value(), m_Value()))) ||
1848  (match(Op0, m_And(m_Value(), m_Value())) &&
1849  match(Op1, m_LogicalShift(m_Value(), m_Value())));
1850 
1851  if (!OrOfOrs && !OrOfShifts && !OrOfAnds && !OrOfAndAndSh)
1852  return nullptr;
1853 
1855  if (!recognizeBSwapOrBitReverseIdiom(&Or, true, false, Insts))
1856  return nullptr;
1857  Instruction *LastInst = Insts.pop_back_val();
1858  LastInst->removeFromParent();
1859 
1860  for (auto *Inst : Insts)
1861  Worklist.Add(Inst);
1862  return LastInst;
1863 }
1864 
1865 /// Transform UB-safe variants of bitwise rotate to the funnel shift intrinsic.
1867  // TODO: Can we reduce the code duplication between this and the related
1868  // rotate matching code under visitSelect and visitTrunc?
1869  unsigned Width = Or.getType()->getScalarSizeInBits();
1870  if (!isPowerOf2_32(Width))
1871  return nullptr;
1872 
1873  // First, find an or'd pair of opposite shifts with the same shifted operand:
1874  // or (lshr ShVal, ShAmt0), (shl ShVal, ShAmt1)
1875  BinaryOperator *Or0, *Or1;
1876  if (!match(Or.getOperand(0), m_BinOp(Or0)) ||
1877  !match(Or.getOperand(1), m_BinOp(Or1)))
1878  return nullptr;
1879 
1880  Value *ShVal, *ShAmt0, *ShAmt1;
1881  if (!match(Or0, m_OneUse(m_LogicalShift(m_Value(ShVal), m_Value(ShAmt0)))) ||
1882  !match(Or1, m_OneUse(m_LogicalShift(m_Specific(ShVal), m_Value(ShAmt1)))))
1883  return nullptr;
1884 
1885  BinaryOperator::BinaryOps ShiftOpcode0 = Or0->getOpcode();
1886  BinaryOperator::BinaryOps ShiftOpcode1 = Or1->getOpcode();
1887  if (ShiftOpcode0 == ShiftOpcode1)
1888  return nullptr;
1889 
1890  // Match the shift amount operands for a rotate pattern. This always matches
1891  // a subtraction on the R operand.
1892  auto matchShiftAmount = [](Value *L, Value *R, unsigned Width) -> Value * {
1893  // The shift amount may be masked with negation:
1894  // (shl ShVal, (X & (Width - 1))) | (lshr ShVal, ((-X) & (Width - 1)))
1895  Value *X;
1896  unsigned Mask = Width - 1;
1897  if (match(L, m_And(m_Value(X), m_SpecificInt(Mask))) &&
1898  match(R, m_And(m_Neg(m_Specific(X)), m_SpecificInt(Mask))))
1899  return X;
1900 
1901  // Similar to above, but the shift amount may be extended after masking,
1902  // so return the extended value as the parameter for the intrinsic.
1903  if (match(L, m_ZExt(m_And(m_Value(X), m_SpecificInt(Mask)))) &&
1905  m_SpecificInt(Mask))))
1906  return L;
1907 
1908  return nullptr;
1909  };
1910 
1911  Value *ShAmt = matchShiftAmount(ShAmt0, ShAmt1, Width);
1912  bool SubIsOnLHS = false;
1913  if (!ShAmt) {
1914  ShAmt = matchShiftAmount(ShAmt1, ShAmt0, Width);
1915  SubIsOnLHS = true;
1916  }
1917  if (!ShAmt)
1918  return nullptr;
1919 
1920  bool IsFshl = (!SubIsOnLHS && ShiftOpcode0 == BinaryOperator::Shl) ||
1921  (SubIsOnLHS && ShiftOpcode1 == BinaryOperator::Shl);
1922  Intrinsic::ID IID = IsFshl ? Intrinsic::fshl : Intrinsic::fshr;
1924  return IntrinsicInst::Create(F, { ShVal, ShVal, ShAmt });
1925 }
1926 
1927 /// If all elements of two constant vectors are 0/-1 and inverses, return true.
1929  unsigned NumElts = C1->getType()->getVectorNumElements();
1930  for (unsigned i = 0; i != NumElts; ++i) {
1931  Constant *EltC1 = C1->getAggregateElement(i);
1932  Constant *EltC2 = C2->getAggregateElement(i);
1933  if (!EltC1 || !EltC2)
1934  return false;
1935 
1936  // One element must be all ones, and the other must be all zeros.
1937  if (!((match(EltC1, m_Zero()) && match(EltC2, m_AllOnes())) ||
1938  (match(EltC2, m_Zero()) && match(EltC1, m_AllOnes()))))
1939  return false;
1940  }
1941  return true;
1942 }
1943 
1944 /// We have an expression of the form (A & C) | (B & D). If A is a scalar or
1945 /// vector composed of all-zeros or all-ones values and is the bitwise 'not' of
1946 /// B, it can be used as the condition operand of a select instruction.
1947 Value *InstCombiner::getSelectCondition(Value *A, Value *B) {
1948  // Step 1: We may have peeked through bitcasts in the caller.
1949  // Exit immediately if we don't have (vector) integer types.
1950  Type *Ty = A->getType();
1951  if (!Ty->isIntOrIntVectorTy() || !B->getType()->isIntOrIntVectorTy())
1952  return nullptr;
1953 
1954  // Step 2: We need 0 or all-1's bitmasks.
1955  if (ComputeNumSignBits(A) != Ty->getScalarSizeInBits())
1956  return nullptr;
1957 
1958  // Step 3: If B is the 'not' value of A, we have our answer.
1959  if (match(A, m_Not(m_Specific(B)))) {
1960  // If these are scalars or vectors of i1, A can be used directly.
1961  if (Ty->isIntOrIntVectorTy(1))
1962  return A;
1963  return Builder.CreateTrunc(A, CmpInst::makeCmpResultType(Ty));
1964  }
1965 
1966  // If both operands are constants, see if the constants are inverse bitmasks.
1967  Constant *AConst, *BConst;
1968  if (match(A, m_Constant(AConst)) && match(B, m_Constant(BConst)))
1969  if (AConst == ConstantExpr::getNot(BConst))
1970  return Builder.CreateZExtOrTrunc(A, CmpInst::makeCmpResultType(Ty));
1971 
1972  // Look for more complex patterns. The 'not' op may be hidden behind various
1973  // casts. Look through sexts and bitcasts to find the booleans.
1974  Value *Cond;
1975  Value *NotB;
1976  if (match(A, m_SExt(m_Value(Cond))) &&
1977  Cond->getType()->isIntOrIntVectorTy(1) &&
1978  match(B, m_OneUse(m_Not(m_Value(NotB))))) {
1979  NotB = peekThroughBitcast(NotB, true);
1980  if (match(NotB, m_SExt(m_Specific(Cond))))
1981  return Cond;
1982  }
1983 
1984  // All scalar (and most vector) possibilities should be handled now.
1985  // Try more matches that only apply to non-splat constant vectors.
1986  if (!Ty->isVectorTy())
1987  return nullptr;
1988 
1989  // If both operands are xor'd with constants using the same sexted boolean
1990  // operand, see if the constants are inverse bitmasks.
1991  // TODO: Use ConstantExpr::getNot()?
1992  if (match(A, (m_Xor(m_SExt(m_Value(Cond)), m_Constant(AConst)))) &&
1993  match(B, (m_Xor(m_SExt(m_Specific(Cond)), m_Constant(BConst)))) &&
1994  Cond->getType()->isIntOrIntVectorTy(1) &&
1995  areInverseVectorBitmasks(AConst, BConst)) {
1996  AConst = ConstantExpr::getTrunc(AConst, CmpInst::makeCmpResultType(Ty));
1997  return Builder.CreateXor(Cond, AConst);
1998  }
1999  return nullptr;
2000 }
2001 
2002 /// We have an expression of the form (A & C) | (B & D). Try to simplify this
2003 /// to "A' ? C : D", where A' is a boolean or vector of booleans.
2004 Value *InstCombiner::matchSelectFromAndOr(Value *A, Value *C, Value *B,
2005  Value *D) {
2006  // The potential condition of the select may be bitcasted. In that case, look
2007  // through its bitcast and the corresponding bitcast of the 'not' condition.
2008  Type *OrigType = A->getType();
2009  A = peekThroughBitcast(A, true);
2010  B = peekThroughBitcast(B, true);
2011  if (Value *Cond = getSelectCondition(A, B)) {
2012  // ((bc Cond) & C) | ((bc ~Cond) & D) --> bc (select Cond, (bc C), (bc D))
2013  // The bitcasts will either all exist or all not exist. The builder will
2014  // not create unnecessary casts if the types already match.
2015  Value *BitcastC = Builder.CreateBitCast(C, A->getType());
2016  Value *BitcastD = Builder.CreateBitCast(D, A->getType());
2017  Value *Select = Builder.CreateSelect(Cond, BitcastC, BitcastD);
2018  return Builder.CreateBitCast(Select, OrigType);
2019  }
2020 
2021  return nullptr;
2022 }
2023 
2024 /// Fold (icmp)|(icmp) if possible.
2025 Value *InstCombiner::foldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS,
2026  Instruction &CxtI) {
2027  // Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
2028  // if K1 and K2 are a one-bit mask.
2029  if (Value *V = foldAndOrOfICmpsOfAndWithPow2(LHS, RHS, false, CxtI))
2030  return V;
2031 
2032  ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
2033 
2034  ConstantInt *LHSC = dyn_cast<ConstantInt>(LHS->getOperand(1));
2035  ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS->getOperand(1));
2036 
2037  // Fold (icmp ult/ule (A + C1), C3) | (icmp ult/ule (A + C2), C3)
2038  // --> (icmp ult/ule ((A & ~(C1 ^ C2)) + max(C1, C2)), C3)
2039  // The original condition actually refers to the following two ranges:
2040  // [MAX_UINT-C1+1, MAX_UINT-C1+1+C3] and [MAX_UINT-C2+1, MAX_UINT-C2+1+C3]
2041  // We can fold these two ranges if:
2042  // 1) C1 and C2 is unsigned greater than C3.
2043  // 2) The two ranges are separated.
2044  // 3) C1 ^ C2 is one-bit mask.
2045  // 4) LowRange1 ^ LowRange2 and HighRange1 ^ HighRange2 are one-bit mask.
2046  // This implies all values in the two ranges differ by exactly one bit.
2047 
2048  if ((PredL == ICmpInst::ICMP_ULT || PredL == ICmpInst::ICMP_ULE) &&
2049  PredL == PredR && LHSC && RHSC && LHS->hasOneUse() && RHS->hasOneUse() &&
2050  LHSC->getType() == RHSC->getType() &&
2051  LHSC->getValue() == (RHSC->getValue())) {
2052 
2053  Value *LAdd = LHS->getOperand(0);
2054  Value *RAdd = RHS->getOperand(0);
2055 
2056  Value *LAddOpnd, *RAddOpnd;
2057  ConstantInt *LAddC, *RAddC;
2058  if (match(LAdd, m_Add(m_Value(LAddOpnd), m_ConstantInt(LAddC))) &&
2059  match(RAdd, m_Add(m_Value(RAddOpnd), m_ConstantInt(RAddC))) &&
2060  LAddC->getValue().ugt(LHSC->getValue()) &&
2061  RAddC->getValue().ugt(LHSC->getValue())) {
2062 
2063  APInt DiffC = LAddC->getValue() ^ RAddC->getValue();
2064  if (LAddOpnd == RAddOpnd && DiffC.isPowerOf2()) {
2065  ConstantInt *MaxAddC = nullptr;
2066  if (LAddC->getValue().ult(RAddC->getValue()))
2067  MaxAddC = RAddC;
2068  else
2069  MaxAddC = LAddC;
2070 
2071  APInt RRangeLow = -RAddC->getValue();
2072  APInt RRangeHigh = RRangeLow + LHSC->getValue();
2073  APInt LRangeLow = -LAddC->getValue();
2074  APInt LRangeHigh = LRangeLow + LHSC->getValue();
2075  APInt LowRangeDiff = RRangeLow ^ LRangeLow;
2076  APInt HighRangeDiff = RRangeHigh ^ LRangeHigh;
2077  APInt RangeDiff = LRangeLow.sgt(RRangeLow) ? LRangeLow - RRangeLow
2078  : RRangeLow - LRangeLow;
2079 
2080  if (LowRangeDiff.isPowerOf2() && LowRangeDiff == HighRangeDiff &&
2081  RangeDiff.ugt(LHSC->getValue())) {
2082  Value *MaskC = ConstantInt::get(LAddC->getType(), ~DiffC);
2083 
2084  Value *NewAnd = Builder.CreateAnd(LAddOpnd, MaskC);
2085  Value *NewAdd = Builder.CreateAdd(NewAnd, MaxAddC);
2086  return Builder.CreateICmp(LHS->getPredicate(), NewAdd, LHSC);
2087  }
2088  }
2089  }
2090  }
2091 
2092  // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
2093  if (predicatesFoldable(PredL, PredR)) {
2094  if (LHS->getOperand(0) == RHS->getOperand(1) &&
2095  LHS->getOperand(1) == RHS->getOperand(0))
2096  LHS->swapOperands();
2097  if (LHS->getOperand(0) == RHS->getOperand(0) &&
2098  LHS->getOperand(1) == RHS->getOperand(1)) {
2099  Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2100  unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
2101  bool IsSigned = LHS->isSigned() || RHS->isSigned();
2102  return getNewICmpValue(Code, IsSigned, Op0, Op1, Builder);
2103  }
2104  }
2105 
2106  // handle (roughly):
2107  // (icmp ne (A & B), C) | (icmp ne (A & D), E)
2108  if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, false, Builder))
2109  return V;
2110 
2111  Value *LHS0 = LHS->getOperand(0), *RHS0 = RHS->getOperand(0);
2112  if (LHS->hasOneUse() || RHS->hasOneUse()) {
2113  // (icmp eq B, 0) | (icmp ult A, B) -> (icmp ule A, B-1)
2114  // (icmp eq B, 0) | (icmp ugt B, A) -> (icmp ule A, B-1)
2115  Value *A = nullptr, *B = nullptr;
2116  if (PredL == ICmpInst::ICMP_EQ && LHSC && LHSC->isZero()) {
2117  B = LHS0;
2118  if (PredR == ICmpInst::ICMP_ULT && LHS0 == RHS->getOperand(1))
2119  A = RHS0;
2120  else if (PredR == ICmpInst::ICMP_UGT && LHS0 == RHS0)
2121  A = RHS->getOperand(1);
2122  }
2123  // (icmp ult A, B) | (icmp eq B, 0) -> (icmp ule A, B-1)
2124  // (icmp ugt B, A) | (icmp eq B, 0) -> (icmp ule A, B-1)
2125  else if (PredR == ICmpInst::ICMP_EQ && RHSC && RHSC->isZero()) {
2126  B = RHS0;
2127  if (PredL == ICmpInst::ICMP_ULT && RHS0 == LHS->getOperand(1))
2128  A = LHS0;
2129  else if (PredL == ICmpInst::ICMP_UGT && LHS0 == RHS0)
2130  A = LHS->getOperand(1);
2131  }
2132  if (A && B)
2133  return Builder.CreateICmp(
2135  Builder.CreateAdd(B, ConstantInt::getSigned(B->getType(), -1)), A);
2136  }
2137 
2138  // E.g. (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
2139  if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/true))
2140  return V;
2141 
2142  // E.g. (icmp sgt x, n) | (icmp slt x, 0) --> icmp ugt x, n
2143  if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/true))
2144  return V;
2145 
2146  if (Value *V = foldAndOrOfEqualityCmpsWithConstants(LHS, RHS, false, Builder))
2147  return V;
2148 
2149  // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
2150  if (!LHSC || !RHSC)
2151  return nullptr;
2152 
2153  if (LHSC == RHSC && PredL == PredR) {
2154  // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
2155  if (PredL == ICmpInst::ICMP_NE && LHSC->isZero()) {
2156  Value *NewOr = Builder.CreateOr(LHS0, RHS0);
2157  return Builder.CreateICmp(PredL, NewOr, LHSC);
2158  }
2159  }
2160 
2161  // (icmp ult (X + CA), C1) | (icmp eq X, C2) -> (icmp ule (X + CA), C1)
2162  // iff C2 + CA == C1.
2163  if (PredL == ICmpInst::ICMP_ULT && PredR == ICmpInst::ICMP_EQ) {
2164  ConstantInt *AddC;
2165  if (match(LHS0, m_Add(m_Specific(RHS0), m_ConstantInt(AddC))))
2166  if (RHSC->getValue() + AddC->getValue() == LHSC->getValue())
2167  return Builder.CreateICmpULE(LHS0, LHSC);
2168  }
2169 
2170  // From here on, we only handle:
2171  // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
2172  if (LHS0 != RHS0)
2173  return nullptr;
2174 
2175  // ICMP_[US][GL]E X, C is folded to ICMP_[US][GL]T elsewhere.
2176  if (PredL == ICmpInst::ICMP_UGE || PredL == ICmpInst::ICMP_ULE ||
2177  PredR == ICmpInst::ICMP_UGE || PredR == ICmpInst::ICMP_ULE ||
2178  PredL == ICmpInst::ICMP_SGE || PredL == ICmpInst::ICMP_SLE ||
2179  PredR == ICmpInst::ICMP_SGE || PredR == ICmpInst::ICMP_SLE)
2180  return nullptr;
2181 
2182  // We can't fold (ugt x, C) | (sgt x, C2).
2183  if (!predicatesFoldable(PredL, PredR))
2184  return nullptr;
2185 
2186  // Ensure that the larger constant is on the RHS.
2187  bool ShouldSwap;
2188  if (CmpInst::isSigned(PredL) ||
2189  (ICmpInst::isEquality(PredL) && CmpInst::isSigned(PredR)))
2190  ShouldSwap = LHSC->getValue().sgt(RHSC->getValue());
2191  else
2192  ShouldSwap = LHSC->getValue().ugt(RHSC->getValue());
2193 
2194  if (ShouldSwap) {
2195  std::swap(LHS, RHS);
2196  std::swap(LHSC, RHSC);
2197  std::swap(PredL, PredR);
2198  }
2199 
2200  // At this point, we know we have two icmp instructions
2201  // comparing a value against two constants and or'ing the result
2202  // together. Because of the above check, we know that we only have
2203  // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
2204  // icmp folding check above), that the two constants are not
2205  // equal.
2206  assert(LHSC != RHSC && "Compares not folded above?");
2207 
2208  switch (PredL) {
2209  default:
2210  llvm_unreachable("Unknown integer condition code!");
2211  case ICmpInst::ICMP_EQ:
2212  switch (PredR) {
2213  default:
2214  llvm_unreachable("Unknown integer condition code!");
2215  case ICmpInst::ICMP_EQ:
2216  // Potential folds for this case should already be handled.
2217  break;
2218  case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
2219  case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
2220  break;
2221  }
2222  break;
2223  case ICmpInst::ICMP_ULT:
2224  switch (PredR) {
2225  default:
2226  llvm_unreachable("Unknown integer condition code!");
2227  case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
2228  break;
2229  case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
2230  assert(!RHSC->isMaxValue(false) && "Missed icmp simplification");
2231  return insertRangeTest(LHS0, LHSC->getValue(), RHSC->getValue() + 1,
2232  false, false);
2233  }
2234  break;
2235  case ICmpInst::ICMP_SLT:
2236  switch (PredR) {
2237  default:
2238  llvm_unreachable("Unknown integer condition code!");
2239  case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
2240  break;
2241  case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
2242  assert(!RHSC->isMaxValue(true) && "Missed icmp simplification");
2243  return insertRangeTest(LHS0, LHSC->getValue(), RHSC->getValue() + 1, true,
2244  false);
2245  }
2246  break;
2247  }
2248  return nullptr;
2249 }
2250 
2251 // FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
2252 // here. We should standardize that construct where it is needed or choose some
2253 // other way to ensure that commutated variants of patterns are not missed.
2255  if (Value *V = SimplifyOrInst(I.getOperand(0), I.getOperand(1),
2256  SQ.getWithInstruction(&I)))
2257  return replaceInstUsesWith(I, V);
2258 
2259  if (SimplifyAssociativeOrCommutative(I))
2260  return &I;
2261 
2262  if (Instruction *X = foldVectorBinop(I))
2263  return X;
2264 
2265  // See if we can simplify any instructions used by the instruction whose sole
2266  // purpose is to compute bits we don't care about.
2267  if (SimplifyDemandedInstructionBits(I))
2268  return &I;
2269 
2270  // Do this before using distributive laws to catch simple and/or/not patterns.
2271  if (Instruction *Xor = foldOrToXor(I, Builder))
2272  return Xor;
2273 
2274  // (A&B)|(A&C) -> A&(B|C) etc
2275  if (Value *V = SimplifyUsingDistributiveLaws(I))
2276  return replaceInstUsesWith(I, V);
2277 
2278  if (Value *V = SimplifyBSwap(I, Builder))
2279  return replaceInstUsesWith(I, V);
2280 
2281  if (Instruction *FoldedLogic = foldBinOpIntoSelectOrPhi(I))
2282  return FoldedLogic;
2283 
2284  if (Instruction *BSwap = matchBSwap(I))
2285  return BSwap;
2286 
2287  if (Instruction *Rotate = matchRotate(I))
2288  return Rotate;
2289 
2290  Value *X, *Y;
2291  const APInt *CV;
2292  if (match(&I, m_c_Or(m_OneUse(m_Xor(m_Value(X), m_APInt(CV))), m_Value(Y))) &&
2293  !CV->isAllOnesValue() && MaskedValueIsZero(Y, *CV, 0, &I)) {
2294  // (X ^ C) | Y -> (X | Y) ^ C iff Y & C == 0
2295  // The check for a 'not' op is for efficiency (if Y is known zero --> ~X).
2296  Value *Or = Builder.CreateOr(X, Y);
2297  return BinaryOperator::CreateXor(Or, ConstantInt::get(I.getType(), *CV));
2298  }
2299 
2300  // (A & C)|(B & D)
2301  Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2302  Value *A, *B, *C, *D;
2303  if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
2304  match(Op1, m_And(m_Value(B), m_Value(D)))) {
2307  if (C1 && C2) { // (A & C1)|(B & C2)
2308  Value *V1 = nullptr, *V2 = nullptr;
2309  if ((C1->getValue() & C2->getValue()).isNullValue()) {
2310  // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
2311  // iff (C1&C2) == 0 and (N&~C1) == 0
2312  if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
2313  ((V1 == B &&
2314  MaskedValueIsZero(V2, ~C1->getValue(), 0, &I)) || // (V|N)
2315  (V2 == B &&
2316  MaskedValueIsZero(V1, ~C1->getValue(), 0, &I)))) // (N|V)
2317  return BinaryOperator::CreateAnd(A,
2318  Builder.getInt(C1->getValue()|C2->getValue()));
2319  // Or commutes, try both ways.
2320  if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
2321  ((V1 == A &&
2322  MaskedValueIsZero(V2, ~C2->getValue(), 0, &I)) || // (V|N)
2323  (V2 == A &&
2324  MaskedValueIsZero(V1, ~C2->getValue(), 0, &I)))) // (N|V)
2325  return BinaryOperator::CreateAnd(B,
2326  Builder.getInt(C1->getValue()|C2->getValue()));
2327 
2328  // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
2329  // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
2330  ConstantInt *C3 = nullptr, *C4 = nullptr;
2331  if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
2332  (C3->getValue() & ~C1->getValue()).isNullValue() &&
2333  match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
2334  (C4->getValue() & ~C2->getValue()).isNullValue()) {
2335  V2 = Builder.CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
2336  return BinaryOperator::CreateAnd(V2,
2337  Builder.getInt(C1->getValue()|C2->getValue()));
2338  }
2339  }
2340 
2341  if (C1->getValue() == ~C2->getValue()) {
2342  Value *X;
2343 
2344  // ((X|B)&C1)|(B&C2) -> (X&C1) | B iff C1 == ~C2
2345  if (match(A, m_c_Or(m_Value(X), m_Specific(B))))
2346  return BinaryOperator::CreateOr(Builder.CreateAnd(X, C1), B);
2347  // (A&C2)|((X|A)&C1) -> (X&C2) | A iff C1 == ~C2
2348  if (match(B, m_c_Or(m_Specific(A), m_Value(X))))
2349  return BinaryOperator::CreateOr(Builder.CreateAnd(X, C2), A);
2350 
2351  // ((X^B)&C1)|(B&C2) -> (X&C1) ^ B iff C1 == ~C2
2352  if (match(A, m_c_Xor(m_Value(X), m_Specific(B))))
2353  return BinaryOperator::CreateXor(Builder.CreateAnd(X, C1), B);
2354  // (A&C2)|((X^A)&C1) -> (X&C2) ^ A iff C1 == ~C2
2355  if (match(B, m_c_Xor(m_Specific(A), m_Value(X))))
2356  return BinaryOperator::CreateXor(Builder.CreateAnd(X, C2), A);
2357  }
2358  }
2359 
2360  // Don't try to form a select if it's unlikely that we'll get rid of at
2361  // least one of the operands. A select is generally more expensive than the
2362  // 'or' that it is replacing.
2363  if (Op0->hasOneUse() || Op1->hasOneUse()) {
2364  // (Cond & C) | (~Cond & D) -> Cond ? C : D, and commuted variants.
2365  if (Value *V = matchSelectFromAndOr(A, C, B, D))
2366  return replaceInstUsesWith(I, V);
2367  if (Value *V = matchSelectFromAndOr(A, C, D, B))
2368  return replaceInstUsesWith(I, V);
2369  if (Value *V = matchSelectFromAndOr(C, A, B, D))
2370  return replaceInstUsesWith(I, V);
2371  if (Value *V = matchSelectFromAndOr(C, A, D, B))
2372  return replaceInstUsesWith(I, V);
2373  if (Value *V = matchSelectFromAndOr(B, D, A, C))
2374  return replaceInstUsesWith(I, V);
2375  if (Value *V = matchSelectFromAndOr(B, D, C, A))
2376  return replaceInstUsesWith(I, V);
2377  if (Value *V = matchSelectFromAndOr(D, B, A, C))
2378  return replaceInstUsesWith(I, V);
2379  if (Value *V = matchSelectFromAndOr(D, B, C, A))
2380  return replaceInstUsesWith(I, V);
2381  }
2382  }
2383 
2384  // (A ^ B) | ((B ^ C) ^ A) -> (A ^ B) | C
2385  if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
2386  if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
2387  return BinaryOperator::CreateOr(Op0, C);
2388 
2389  // ((A ^ C) ^ B) | (B ^ A) -> (B ^ A) | C
2390  if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
2391  if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
2392  return BinaryOperator::CreateOr(Op1, C);
2393 
2394  // ((B | C) & A) | B -> B | (A & C)
2395  if (match(Op0, m_And(m_Or(m_Specific(Op1), m_Value(C)), m_Value(A))))
2396  return BinaryOperator::CreateOr(Op1, Builder.CreateAnd(A, C));
2397 
2398  if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder))
2399  return DeMorgan;
2400 
2401  // Canonicalize xor to the RHS.
2402  bool SwappedForXor = false;
2403  if (match(Op0, m_Xor(m_Value(), m_Value()))) {
2404  std::swap(Op0, Op1);
2405  SwappedForXor = true;
2406  }
2407 
2408  // A | ( A ^ B) -> A | B
2409  // A | (~A ^ B) -> A | ~B
2410  // (A & B) | (A ^ B)
2411  if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2412  if (Op0 == A || Op0 == B)
2413  return BinaryOperator::CreateOr(A, B);
2414 
2415  if (match(Op0, m_And(m_Specific(A), m_Specific(B))) ||
2416  match(Op0, m_And(m_Specific(B), m_Specific(A))))
2417  return BinaryOperator::CreateOr(A, B);
2418 
2419  if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) {
2420  Value *Not = Builder.CreateNot(B, B->getName() + ".not");
2421  return BinaryOperator::CreateOr(Not, Op0);
2422  }
2423  if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) {
2424  Value *Not = Builder.CreateNot(A, A->getName() + ".not");
2425  return BinaryOperator::CreateOr(Not, Op0);
2426  }
2427  }
2428 
2429  // A | ~(A | B) -> A | ~B
2430  // A | ~(A ^ B) -> A | ~B
2431  if (match(Op1, m_Not(m_Value(A))))
2432  if (BinaryOperator *B = dyn_cast<BinaryOperator>(A))
2433  if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) &&
2434  Op1->hasOneUse() && (B->getOpcode() == Instruction::Or ||
2435  B->getOpcode() == Instruction::Xor)) {
2436  Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) :
2437  B->getOperand(0);
2438  Value *Not = Builder.CreateNot(NotOp, NotOp->getName() + ".not");
2439  return BinaryOperator::CreateOr(Not, Op0);
2440  }
2441 
2442  if (SwappedForXor)
2443  std::swap(Op0, Op1);
2444 
2445  {
2446  ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
2447  ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
2448  if (LHS && RHS)
2449  if (Value *Res = foldOrOfICmps(LHS, RHS, I))
2450  return replaceInstUsesWith(I, Res);
2451 
2452  // TODO: Make this recursive; it's a little tricky because an arbitrary
2453  // number of 'or' instructions might have to be created.
2454  Value *X, *Y;
2455  if (LHS && match(Op1, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2456  if (auto *Cmp = dyn_cast<ICmpInst>(X))
2457  if (Value *Res = foldOrOfICmps(LHS, Cmp, I))
2458  return replaceInstUsesWith(I, Builder.CreateOr(Res, Y));
2459  if (auto *Cmp = dyn_cast<ICmpInst>(Y))
2460  if (Value *Res = foldOrOfICmps(LHS, Cmp, I))
2461  return replaceInstUsesWith(I, Builder.CreateOr(Res, X));
2462  }
2463  if (RHS && match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2464  if (auto *Cmp = dyn_cast<ICmpInst>(X))
2465  if (Value *Res = foldOrOfICmps(Cmp, RHS, I))
2466  return replaceInstUsesWith(I, Builder.CreateOr(Res, Y));
2467  if (auto *Cmp = dyn_cast<ICmpInst>(Y))
2468  if (Value *Res = foldOrOfICmps(Cmp, RHS, I))
2469  return replaceInstUsesWith(I, Builder.CreateOr(Res, X));
2470  }
2471  }
2472 
2473  if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
2474  if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
2475  if (Value *Res = foldLogicOfFCmps(LHS, RHS, false))
2476  return replaceInstUsesWith(I, Res);
2477 
2478  if (Instruction *FoldedFCmps = reassociateFCmps(I, Builder))
2479  return FoldedFCmps;
2480 
2481  if (Instruction *CastedOr = foldCastedBitwiseLogic(I))
2482  return CastedOr;
2483 
2484  // or(sext(A), B) / or(B, sext(A)) --> A ? -1 : B, where A is i1 or <N x i1>.
2485  if (match(Op0, m_OneUse(m_SExt(m_Value(A)))) &&
2486  A->getType()->isIntOrIntVectorTy(1))
2487  return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op1);
2488  if (match(Op1, m_OneUse(m_SExt(m_Value(A)))) &&
2489  A->getType()->isIntOrIntVectorTy(1))
2490  return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op0);
2491 
2492  // Note: If we've gotten to the point of visiting the outer OR, then the
2493  // inner one couldn't be simplified. If it was a constant, then it won't
2494  // be simplified by a later pass either, so we try swapping the inner/outer
2495  // ORs in the hopes that we'll be able to simplify it this way.
2496  // (X|C) | V --> (X|V) | C
2497  ConstantInt *CI;
2498  if (Op0->hasOneUse() && !isa<ConstantInt>(Op1) &&
2499  match(Op0, m_Or(m_Value(A), m_ConstantInt(CI)))) {
2500  Value *Inner = Builder.CreateOr(A, Op1);
2501  Inner->takeName(Op0);
2502  return BinaryOperator::CreateOr(Inner, CI);
2503  }
2504 
2505  // Change (or (bool?A:B),(bool?C:D)) --> (bool?(or A,C):(or B,D))
2506  // Since this OR statement hasn't been optimized further yet, we hope
2507  // that this transformation will allow the new ORs to be optimized.
2508  {
2509  Value *X = nullptr, *Y = nullptr;
2510  if (Op0->hasOneUse() && Op1->hasOneUse() &&
2511  match(Op0, m_Select(m_Value(X), m_Value(A), m_Value(B))) &&
2512  match(Op1, m_Select(m_Value(Y), m_Value(C), m_Value(D))) && X == Y) {
2513  Value *orTrue = Builder.CreateOr(A, C);
2514  Value *orFalse = Builder.CreateOr(B, D);
2515  return SelectInst::Create(X, orTrue, orFalse);
2516  }
2517  }
2518 
2519  return nullptr;
2520 }
2521 
2522 /// A ^ B can be specified using other logic ops in a variety of patterns. We
2523 /// can fold these early and efficiently by morphing an existing instruction.
2525  InstCombiner::BuilderTy &Builder) {
2526  assert(I.getOpcode() == Instruction::Xor);
2527  Value *Op0 = I.getOperand(0);
2528  Value *Op1 = I.getOperand(1);
2529  Value *A, *B;
2530 
2531  // There are 4 commuted variants for each of the basic patterns.
2532 
2533  // (A & B) ^ (A | B) -> A ^ B
2534  // (A & B) ^ (B | A) -> A ^ B
2535  // (A | B) ^ (A & B) -> A ^ B
2536  // (A | B) ^ (B & A) -> A ^ B
2537  if (match(&I, m_c_Xor(m_And(m_Value(A), m_Value(B)),
2538  m_c_Or(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_Or(m_Value(A), m_Not(m_Value(B))),
2549  m_c_Or(m_Not(m_Deferred(A)), m_Deferred(B))))) {
2550  I.setOperand(0, A);
2551  I.setOperand(1, B);
2552  return &I;
2553  }
2554 
2555  // (A & ~B) ^ (~A & B) -> A ^ B
2556  // (~B & A) ^ (~A & B) -> A ^ B
2557  // (~A & B) ^ (A & ~B) -> A ^ B
2558  // (B & ~A) ^ (A & ~B) -> A ^ B
2559  if (match(&I, m_Xor(m_c_And(m_Value(A), m_Not(m_Value(B))),
2560  m_c_And(m_Not(m_Deferred(A)), m_Deferred(B))))) {
2561  I.setOperand(0, A);
2562  I.setOperand(1, B);
2563  return &I;
2564  }
2565 
2566  // For the remaining cases we need to get rid of one of the operands.
2567  if (!Op0->hasOneUse() && !Op1->hasOneUse())
2568  return nullptr;
2569 
2570  // (A | B) ^ ~(A & B) -> ~(A ^ B)
2571  // (A | B) ^ ~(B & A) -> ~(A ^ B)
2572  // (A & B) ^ ~(A | B) -> ~(A ^ B)
2573  // (A & B) ^ ~(B | A) -> ~(A ^ B)
2574  // Complexity sorting ensures the not will be on the right side.
2575  if ((match(Op0, m_Or(m_Value(A), m_Value(B))) &&
2576  match(Op1, m_Not(m_c_And(m_Specific(A), m_Specific(B))))) ||
2577  (match(Op0, m_And(m_Value(A), m_Value(B))) &&
2578  match(Op1, m_Not(m_c_Or(m_Specific(A), m_Specific(B))))))
2579  return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
2580 
2581  return nullptr;
2582 }
2583 
2584 Value *InstCombiner::foldXorOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
2585  if (predicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
2586  if (LHS->getOperand(0) == RHS->getOperand(1) &&
2587  LHS->getOperand(1) == RHS->getOperand(0))
2588  LHS->swapOperands();
2589  if (LHS->getOperand(0) == RHS->getOperand(0) &&
2590  LHS->getOperand(1) == RHS->getOperand(1)) {
2591  // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
2592  Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2593  unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
2594  bool IsSigned = LHS->isSigned() || RHS->isSigned();
2595  return getNewICmpValue(Code, IsSigned, Op0, Op1, Builder);
2596  }
2597  }
2598 
2599  // TODO: This can be generalized to compares of non-signbits using
2600  // decomposeBitTestICmp(). It could be enhanced more by using (something like)
2601  // foldLogOpOfMaskedICmps().
2602  ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
2603  Value *LHS0 = LHS->getOperand(0), *LHS1 = LHS->getOperand(1);
2604  Value *RHS0 = RHS->getOperand(0), *RHS1 = RHS->getOperand(1);
2605  if ((LHS->hasOneUse() || RHS->hasOneUse()) &&
2606  LHS0->getType() == RHS0->getType() &&
2607  LHS0->getType()->isIntOrIntVectorTy()) {
2608  // (X > -1) ^ (Y > -1) --> (X ^ Y) < 0
2609  // (X < 0) ^ (Y < 0) --> (X ^ Y) < 0
2610  if ((PredL == CmpInst::ICMP_SGT && match(LHS1, m_AllOnes()) &&
2611  PredR == CmpInst::ICMP_SGT && match(RHS1, m_AllOnes())) ||
2612  (PredL == CmpInst::ICMP_SLT && match(LHS1, m_Zero()) &&
2613  PredR == CmpInst::ICMP_SLT && match(RHS1, m_Zero()))) {
2614  Value *Zero = ConstantInt::getNullValue(LHS0->getType());
2615  return Builder.CreateICmpSLT(Builder.CreateXor(LHS0, RHS0), Zero);
2616  }
2617  // (X > -1) ^ (Y < 0) --> (X ^ Y) > -1
2618  // (X < 0) ^ (Y > -1) --> (X ^ Y) > -1
2619  if ((PredL == CmpInst::ICMP_SGT && match(LHS1, m_AllOnes()) &&
2620  PredR == CmpInst::ICMP_SLT && match(RHS1, m_Zero())) ||
2621  (PredL == CmpInst::ICMP_SLT && match(LHS1, m_Zero()) &&
2622  PredR == CmpInst::ICMP_SGT && match(RHS1, m_AllOnes()))) {
2623  Value *MinusOne = ConstantInt::getAllOnesValue(LHS0->getType());
2624  return Builder.CreateICmpSGT(Builder.CreateXor(LHS0, RHS0), MinusOne);
2625  }
2626  }
2627 
2628  // Instead of trying to imitate the folds for and/or, decompose this 'xor'
2629  // into those logic ops. That is, try to turn this into an and-of-icmps
2630  // because we have many folds for that pattern.
2631  //
2632  // This is based on a truth table definition of xor:
2633  // X ^ Y --> (X | Y) & !(X & Y)
2634  if (Value *OrICmp = SimplifyBinOp(Instruction::Or, LHS, RHS, SQ)) {
2635  // TODO: If OrICmp is true, then the definition of xor simplifies to !(X&Y).
2636  // TODO: If OrICmp is false, the whole thing is false (InstSimplify?).
2637  if (Value *AndICmp = SimplifyBinOp(Instruction::And, LHS, RHS, SQ)) {
2638  // TODO: Independently handle cases where the 'and' side is a constant.
2639  if (OrICmp == LHS && AndICmp == RHS && RHS->hasOneUse()) {
2640  // (LHS | RHS) & !(LHS & RHS) --> LHS & !RHS
2641  RHS->setPredicate(RHS->getInversePredicate());
2642  return Builder.CreateAnd(LHS, RHS);
2643  }
2644  if (OrICmp == RHS && AndICmp == LHS && LHS->hasOneUse()) {
2645  // !(LHS & RHS) & (LHS | RHS) --> !LHS & RHS
2646  LHS->setPredicate(LHS->getInversePredicate());
2647  return Builder.CreateAnd(LHS, RHS);
2648  }
2649  }
2650  }
2651 
2652  return nullptr;
2653 }
2654 
2655 /// If we have a masked merge, in the canonical form of:
2656 /// (assuming that A only has one use.)
2657 /// | A | |B|
2658 /// ((x ^ y) & M) ^ y
2659 /// | D |
2660 /// * If M is inverted:
2661 /// | D |
2662 /// ((x ^ y) & ~M) ^ y
2663 /// We can canonicalize by swapping the final xor operand
2664 /// to eliminate the 'not' of the mask.
2665 /// ((x ^ y) & M) ^ x
2666 /// * If M is a constant, and D has one use, we transform to 'and' / 'or' ops
2667 /// because that shortens the dependency chain and improves analysis:
2668 /// (x & M) | (y & ~M)
2670  InstCombiner::BuilderTy &Builder) {
2671  Value *B, *X, *D;
2672  Value *M;
2673  if (!match(&I, m_c_Xor(m_Value(B),
2674  m_OneUse(m_c_And(
2676  m_Value(D)),
2677  m_Value(M))))))
2678  return nullptr;
2679 
2680  Value *NotM;
2681  if (match(M, m_Not(m_Value(NotM)))) {
2682  // De-invert the mask and swap the value in B part.
2683  Value *NewA = Builder.CreateAnd(D, NotM);
2684  return BinaryOperator::CreateXor(NewA, X);
2685  }
2686 
2687  Constant *C;
2688  if (D->hasOneUse() && match(M, m_Constant(C))) {
2689  // Unfold.
2690  Value *LHS = Builder.CreateAnd(X, C);
2691  Value *NotC = Builder.CreateNot(C);
2692  Value *RHS = Builder.CreateAnd(B, NotC);
2693  return BinaryOperator::CreateOr(LHS, RHS);
2694  }
2695 
2696  return nullptr;
2697 }
2698 
2699 // Transform
2700 // ~(x ^ y)
2701 // into:
2702 // (~x) ^ y
2703 // or into
2704 // x ^ (~y)
2706  InstCombiner::BuilderTy &Builder) {
2707  Value *X, *Y;
2708  // FIXME: one-use check is not needed in general, but currently we are unable
2709  // to fold 'not' into 'icmp', if that 'icmp' has multiple uses. (D35182)
2710  if (!match(&I, m_Not(m_OneUse(m_Xor(m_Value(X), m_Value(Y))))))
2711  return nullptr;
2712 
2713  // We only want to do the transform if it is free to do.
2714  if (IsFreeToInvert(X, X->hasOneUse())) {
2715  // Ok, good.
2716  } else if (IsFreeToInvert(Y, Y->hasOneUse())) {
2717  std::swap(X, Y);
2718  } else
2719  return nullptr;
2720 
2721  Value *NotX = Builder.CreateNot(X, X->getName() + ".not");
2722  return BinaryOperator::CreateXor(NotX, Y, I.getName() + ".demorgan");
2723 }
2724 
2725 // FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
2726 // here. We should standardize that construct where it is needed or choose some
2727 // other way to ensure that commutated variants of patterns are not missed.
2729  if (Value *V = SimplifyXorInst(I.getOperand(0), I.getOperand(1),
2730  SQ.getWithInstruction(&I)))
2731  return replaceInstUsesWith(I, V);
2732 
2733  if (SimplifyAssociativeOrCommutative(I))
2734  return &I;
2735 
2736  if (Instruction *X = foldVectorBinop(I))
2737  return X;
2738 
2739  if (Instruction *NewXor = foldXorToXor(I, Builder))
2740  return NewXor;
2741 
2742  // (A&B)^(A&C) -> A&(B^C) etc
2743  if (Value *V = SimplifyUsingDistributiveLaws(I))
2744  return replaceInstUsesWith(I, V);
2745 
2746  // See if we can simplify any instructions used by the instruction whose sole
2747  // purpose is to compute bits we don't care about.
2748  if (SimplifyDemandedInstructionBits(I))
2749  return &I;
2750 
2751  if (Value *V = SimplifyBSwap(I, Builder))
2752  return replaceInstUsesWith(I, V);
2753 
2754  Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2755 
2756  // Fold (X & M) ^ (Y & ~M) -> (X & M) | (Y & ~M)
2757  // This it a special case in haveNoCommonBitsSet, but the computeKnownBits
2758  // calls in there are unnecessary as SimplifyDemandedInstructionBits should
2759  // have already taken care of those cases.
2760  Value *M;
2761  if (match(&I, m_c_Xor(m_c_And(m_Not(m_Value(M)), m_Value()),
2762  m_c_And(m_Deferred(M), m_Value()))))
2763  return BinaryOperator::CreateOr(Op0, Op1);
2764 
2765  // Apply DeMorgan's Law for 'nand' / 'nor' logic with an inverted operand.
2766  Value *X, *Y;
2767 
2768  // We must eliminate the and/or (one-use) for these transforms to not increase
2769  // the instruction count.
2770  // ~(~X & Y) --> (X | ~Y)
2771  // ~(Y & ~X) --> (X | ~Y)
2772  if (match(&I, m_Not(m_OneUse(m_c_And(m_Not(m_Value(X)), m_Value(Y)))))) {
2773  Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
2774  return BinaryOperator::CreateOr(X, NotY);
2775  }
2776  // ~(~X | Y) --> (X & ~Y)
2777  // ~(Y | ~X) --> (X & ~Y)
2778  if (match(&I, m_Not(m_OneUse(m_c_Or(m_Not(m_Value(X)), m_Value(Y)))))) {
2779  Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
2780  return BinaryOperator::CreateAnd(X, NotY);
2781  }
2782 
2783  if (Instruction *Xor = visitMaskedMerge(I, Builder))
2784  return Xor;
2785 
2786  // Is this a 'not' (~) fed by a binary operator?
2787  BinaryOperator *NotVal;
2788  if (match(&I, m_Not(m_BinOp(NotVal)))) {
2789  if (NotVal->getOpcode() == Instruction::And ||
2790  NotVal->getOpcode() == Instruction::Or) {
2791  // Apply DeMorgan's Law when inverts are free:
2792  // ~(X & Y) --> (~X | ~Y)
2793  // ~(X | Y) --> (~X & ~Y)
2794  if (IsFreeToInvert(NotVal->getOperand(0),
2795  NotVal->getOperand(0)->hasOneUse()) &&
2796  IsFreeToInvert(NotVal->getOperand(1),
2797  NotVal->getOperand(1)->hasOneUse())) {
2798  Value *NotX = Builder.CreateNot(NotVal->getOperand(0), "notlhs");
2799  Value *NotY = Builder.CreateNot(NotVal->getOperand(1), "notrhs");
2800  if (NotVal->getOpcode() == Instruction::And)
2801  return BinaryOperator::CreateOr(NotX, NotY);
2802  return BinaryOperator::CreateAnd(NotX, NotY);
2803  }
2804  }
2805 
2806  // ~(X - Y) --> ~X + Y
2807  if (match(NotVal, m_Sub(m_Value(X), m_Value(Y))))
2808  if (isa<Constant>(X) || NotVal->hasOneUse())
2809  return BinaryOperator::CreateAdd(Builder.CreateNot(X), Y);
2810 
2811  // ~(~X >>s Y) --> (X >>s Y)
2812  if (match(NotVal, m_AShr(m_Not(m_Value(X)), m_Value(Y))))
2813  return BinaryOperator::CreateAShr(X, Y);
2814 
2815  // If we are inverting a right-shifted constant, we may be able to eliminate
2816  // the 'not' by inverting the constant and using the opposite shift type.
2817  // Canonicalization rules ensure that only a negative constant uses 'ashr',
2818  // but we must check that in case that transform has not fired yet.
2819 
2820  // ~(C >>s Y) --> ~C >>u Y (when inverting the replicated sign bits)
2821  Constant *C;
2822  if (match(NotVal, m_AShr(m_Constant(C), m_Value(Y))) &&
2823  match(C, m_Negative()))
2824  return BinaryOperator::CreateLShr(ConstantExpr::getNot(C), Y);
2825 
2826  // ~(C >>u Y) --> ~C >>s Y (when inverting the replicated sign bits)
2827  if (match(NotVal, m_LShr(m_Constant(C), m_Value(Y))) &&
2828  match(C, m_NonNegative()))
2829  return BinaryOperator::CreateAShr(ConstantExpr::getNot(C), Y);
2830 
2831  // ~(X + C) --> -(C + 1) - X
2832  if (match(Op0, m_Add(m_Value(X), m_Constant(C))))
2833  return BinaryOperator::CreateSub(ConstantExpr::getNeg(AddOne(C)), X);
2834  }
2835 
2836  // Use DeMorgan and reassociation to eliminate a 'not' op.
2837  Constant *C1;
2838  if (match(Op1, m_Constant(C1))) {
2839  Constant *C2;
2840  if (match(Op0, m_OneUse(m_Or(m_Not(m_Value(X)), m_Constant(C2))))) {
2841  // (~X | C2) ^ C1 --> ((X & ~C2) ^ -1) ^ C1 --> (X & ~C2) ^ ~C1
2842  Value *And = Builder.CreateAnd(X, ConstantExpr::getNot(C2));
2843  return BinaryOperator::CreateXor(And, ConstantExpr::getNot(C1));
2844  }
2845  if (match(Op0, m_OneUse(m_And(m_Not(m_Value(X)), m_Constant(C2))))) {
2846  // (~X & C2) ^ C1 --> ((X | ~C2) ^ -1) ^ C1 --> (X | ~C2) ^ ~C1
2847  Value *Or = Builder.CreateOr(X, ConstantExpr::getNot(C2));
2848  return BinaryOperator::CreateXor(Or, ConstantExpr::getNot(C1));
2849  }
2850  }
2851 
2852  // not (cmp A, B) = !cmp A, B
2853  CmpInst::Predicate Pred;
2854  if (match(&I, m_Not(m_OneUse(m_Cmp(Pred, m_Value(), m_Value()))))) {
2855  cast<CmpInst>(Op0)->setPredicate(CmpInst::getInversePredicate(Pred));
2856  return replaceInstUsesWith(I, Op0);
2857  }
2858 
2859  {
2860  const APInt *RHSC;
2861  if (match(Op1, m_APInt(RHSC))) {
2862  Value *X;
2863  const APInt *C;
2864  if (RHSC->isSignMask() && match(Op0, m_Sub(m_APInt(C), m_Value(X)))) {
2865  // (C - X) ^ signmask -> (C + signmask - X)
2866  Constant *NewC = ConstantInt::get(I.getType(), *C + *RHSC);
2867  return BinaryOperator::CreateSub(NewC, X);
2868  }
2869  if (RHSC->isSignMask() && match(Op0, m_Add(m_Value(X), m_APInt(C)))) {
2870  // (X + C) ^ signmask -> (X + C + signmask)
2871  Constant *NewC = ConstantInt::get(I.getType(), *C + *RHSC);
2872  return BinaryOperator::CreateAdd(X, NewC);
2873  }
2874 
2875  // (X|C1)^C2 -> X^(C1^C2) iff X&~C1 == 0
2876  if (match(Op0, m_Or(m_Value(X), m_APInt(C))) &&
2877  MaskedValueIsZero(X, *C, 0, &I)) {
2878  Constant *NewC = ConstantInt::get(I.getType(), *C ^ *RHSC);
2879  Worklist.Add(cast<Instruction>(Op0));
2880  I.setOperand(0, X);
2881  I.setOperand(1, NewC);
2882  return &I;
2883  }
2884  }
2885  }
2886 
2887  if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1)) {
2888  if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2889  if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
2890  if (Op0I->getOpcode() == Instruction::LShr) {
2891  // ((X^C1) >> C2) ^ C3 -> (X>>C2) ^ ((C1>>C2)^C3)
2892  // E1 = "X ^ C1"
2893  BinaryOperator *E1;
2894  ConstantInt *C1;
2895  if (Op0I->hasOneUse() &&
2896  (E1 = dyn_cast<BinaryOperator>(Op0I->getOperand(0))) &&
2897  E1->getOpcode() == Instruction::Xor &&
2898  (C1 = dyn_cast<ConstantInt>(E1->getOperand(1)))) {
2899  // fold (C1 >> C2) ^ C3
2900  ConstantInt *C2 = Op0CI, *C3 = RHSC;
2901  APInt FoldConst = C1->getValue().lshr(C2->getValue());
2902  FoldConst ^= C3->getValue();
2903  // Prepare the two operands.
2904  Value *Opnd0 = Builder.CreateLShr(E1->getOperand(0), C2);
2905  Opnd0->takeName(Op0I);
2906  cast<Instruction>(Opnd0)->setDebugLoc(I.getDebugLoc());
2907  Value *FoldVal = ConstantInt::get(Opnd0->getType(), FoldConst);
2908 
2909  return BinaryOperator::CreateXor(Opnd0, FoldVal);
2910  }
2911  }
2912  }
2913  }
2914  }
2915 
2916  if (Instruction *FoldedLogic = foldBinOpIntoSelectOrPhi(I))
2917  return FoldedLogic;
2918 
2919  // Y ^ (X | Y) --> X & ~Y
2920  // Y ^ (Y | X) --> X & ~Y
2921  if (match(Op1, m_OneUse(m_c_Or(m_Value(X), m_Specific(Op0)))))
2922  return BinaryOperator::CreateAnd(X, Builder.CreateNot(Op0));
2923  // (X | Y) ^ Y --> X & ~Y
2924  // (Y | X) ^ Y --> X & ~Y
2925  if (match(Op0, m_OneUse(m_c_Or(m_Value(X), m_Specific(Op1)))))
2926  return BinaryOperator::CreateAnd(X, Builder.CreateNot(Op1));
2927 
2928  // Y ^ (X & Y) --> ~X & Y
2929  // Y ^ (Y & X) --> ~X & Y
2930  if (match(Op1, m_OneUse(m_c_And(m_Value(X), m_Specific(Op0)))))
2931  return BinaryOperator::CreateAnd(Op0, Builder.CreateNot(X));
2932  // (X & Y) ^ Y --> ~X & Y
2933  // (Y & X) ^ Y --> ~X & Y
2934  // Canonical form is (X & C) ^ C; don't touch that.
2935  // TODO: A 'not' op is better for analysis and codegen, but demanded bits must
2936  // be fixed to prefer that (otherwise we get infinite looping).
2937  if (!match(Op1, m_Constant()) &&
2938  match(Op0, m_OneUse(m_c_And(m_Value(X), m_Specific(Op1)))))
2939  return BinaryOperator::CreateAnd(Op1, Builder.CreateNot(X));
2940 
2941  Value *A, *B, *C;
2942  // (A ^ B) ^ (A | C) --> (~A & C) ^ B -- There are 4 commuted variants.
2943  if (match(&I, m_c_Xor(m_OneUse(m_Xor(m_Value(A), m_Value(B))),
2944  m_OneUse(m_c_Or(m_Deferred(A), m_Value(C))))))
2945  return BinaryOperator::CreateXor(
2946  Builder.CreateAnd(Builder.CreateNot(A), C), B);
2947 
2948  // (A ^ B) ^ (B | C) --> (~B & C) ^ A -- There are 4 commuted variants.
2949  if (match(&I, m_c_Xor(m_OneUse(m_Xor(m_Value(A), m_Value(B))),
2950  m_OneUse(m_c_Or(m_Deferred(B), m_Value(C))))))
2951  return BinaryOperator::CreateXor(
2952  Builder.CreateAnd(Builder.CreateNot(B), C), A);
2953 
2954  // (A & B) ^ (A ^ B) -> (A | B)
2955  if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
2956  match(Op1, m_c_Xor(m_Specific(A), m_Specific(B))))
2957  return BinaryOperator::CreateOr(A, B);
2958  // (A ^ B) ^ (A & B) -> (A | B)
2959  if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
2960  match(Op1, m_c_And(m_Specific(A), m_Specific(B))))
2961  return BinaryOperator::CreateOr(A, B);
2962 
2963  // (A & ~B) ^ ~A -> ~(A & B)
2964  // (~B & A) ^ ~A -> ~(A & B)
2965  if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
2966  match(Op1, m_Not(m_Specific(A))))
2967  return BinaryOperator::CreateNot(Builder.CreateAnd(A, B));
2968 
2969  if (auto *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2970  if (auto *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
2971  if (Value *V = foldXorOfICmps(LHS, RHS))
2972  return replaceInstUsesWith(I, V);
2973 
2974  if (Instruction *CastedXor = foldCastedBitwiseLogic(I))
2975  return CastedXor;
2976 
2977  // Canonicalize a shifty way to code absolute value to the common pattern.
2978  // There are 4 potential commuted variants. Move the 'ashr' candidate to Op1.
2979  // We're relying on the fact that we only do this transform when the shift has
2980  // exactly 2 uses and the add has exactly 1 use (otherwise, we might increase
2981  // instructions).
2982  if (Op0->hasNUses(2))
2983  std::swap(Op0, Op1);
2984 
2985  const APInt *ShAmt;
2986  Type *Ty = I.getType();
2987  if (match(Op1, m_AShr(m_Value(A), m_APInt(ShAmt))) &&
2988  Op1->hasNUses(2) && *ShAmt == Ty->getScalarSizeInBits() - 1 &&
2989  match(Op0, m_OneUse(m_c_Add(m_Specific(A), m_Specific(Op1))))) {
2990  // B = ashr i32 A, 31 ; smear the sign bit
2991  // xor (add A, B), B ; add -1 and flip bits if negative
2992  // --> (A < 0) ? -A : A
2993  Value *Cmp = Builder.CreateICmpSLT(A, ConstantInt::getNullValue(Ty));
2994  // Copy the nuw/nsw flags from the add to the negate.
2995  auto *Add = cast<BinaryOperator>(Op0);
2996  Value *Neg = Builder.CreateNeg(A, "", Add->hasNoUnsignedWrap(),
2997  Add->hasNoSignedWrap());
2998  return SelectInst::Create(Cmp, Neg, A);
2999  }
3000 
3001  // Eliminate a bitwise 'not' op of 'not' min/max by inverting the min/max:
3002  //
3003  // %notx = xor i32 %x, -1
3004  // %cmp1 = icmp sgt i32 %notx, %y
3005  // %smax = select i1 %cmp1, i32 %notx, i32 %y
3006  // %res = xor i32 %smax, -1
3007  // =>
3008  // %noty = xor i32 %y, -1
3009  // %cmp2 = icmp slt %x, %noty
3010  // %res = select i1 %cmp2, i32 %x, i32 %noty
3011  //
3012  // Same is applicable for smin/umax/umin.
3013  if (match(Op1, m_AllOnes()) && Op0->hasOneUse()) {
3014  Value *LHS, *RHS;
3015  SelectPatternFlavor SPF = matchSelectPattern(Op0, LHS, RHS).Flavor;
3017  // It's possible we get here before the not has been simplified, so make
3018  // sure the input to the not isn't freely invertible.
3019  if (match(LHS, m_Not(m_Value(X))) && !IsFreeToInvert(X, X->hasOneUse())) {
3020  Value *NotY = Builder.CreateNot(RHS);
3021  return SelectInst::Create(
3022  Builder.CreateICmp(getInverseMinMaxPred(SPF), X, NotY), X, NotY);
3023  }
3024 
3025  // It's possible we get here before the not has been simplified, so make
3026  // sure the input to the not isn't freely invertible.
3027  if (match(RHS, m_Not(m_Value(Y))) && !IsFreeToInvert(Y, Y->hasOneUse())) {
3028  Value *NotX = Builder.CreateNot(LHS);
3029  return SelectInst::Create(
3030  Builder.CreateICmp(getInverseMinMaxPred(SPF), NotX, Y), NotX, Y);
3031  }
3032 
3033  // If both sides are freely invertible, then we can get rid of the xor
3034  // completely.
3035  if (IsFreeToInvert(LHS, !LHS->hasNUsesOrMore(3)) &&
3036  IsFreeToInvert(RHS, !RHS->hasNUsesOrMore(3))) {
3037  Value *NotLHS = Builder.CreateNot(LHS);
3038  Value *NotRHS = Builder.CreateNot(RHS);
3039  return SelectInst::Create(
3040  Builder.CreateICmp(getInverseMinMaxPred(SPF), NotLHS, NotRHS),
3041  NotLHS, NotRHS);
3042  }
3043  }
3044  }
3045 
3046  if (Instruction *NewXor = sinkNotIntoXor(I, Builder))
3047  return NewXor;
3048 
3049  return nullptr;
3050 }
const NoneType None
Definition: None.h:23
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
Definition: PatternMatch.h:756
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:674
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:952
This class represents lattice values for constants.
Definition: AllocatorList.h:23
BinaryOps getOpcode() const
Definition: InstrTypes.h:379
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:708
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:735
unsigned less than
Definition: InstrTypes.h:734
BinaryOp_match< LHS, RHS, Instruction::AShr > m_AShr(const LHS &L, const RHS &R)
Definition: PatternMatch.h:786
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:715
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:725
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:948
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:720
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:719
CmpClass_match< LHS, RHS, FCmpInst, FCmpInst::Predicate > m_FCmp(FCmpInst::Predicate &Pred, const LHS &L, const RHS &R)
bool isSigned() const
Definition: InstrTypes.h:879
BinaryOp_match< LHS, RHS, Instruction::Xor > m_Xor(const LHS &L, const RHS &R)
Definition: PatternMatch.h:768
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:808
This is the base class for all instructions that perform data casts.
Definition: InstrTypes.h:416
static Value * getNewICmpValue(unsigned Code, bool Sign, Value *LHS, Value *RHS, InstCombiner::BuilderTy &Builder)
This is the complement of getICmpCode, which turns an opcode and two operands into either a constant ...
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition: APInt.h:992
static Optional< unsigned > getOpcode(ArrayRef< VPValue *> Values)
Returns the opcode of Values or ~0 if they do not all agree.
Definition: VPlanSLP.cpp:196
CastClass_match< OpTy, Instruction::Trunc > m_Trunc(const OpTy &Op)
Matches Trunc.
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:196
static Constant * AddOne(Constant *C)
Add one to a Constant.
0 1 0 1 True if ordered and less than or equal
Definition: InstrTypes.h:716
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:669
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:1022
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:780
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:762
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:2287
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:774
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:709
0 1 1 1 True if ordered (no nans)
Definition: InstrTypes.h:718
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:2222
static Constant * getAllOnesValue(Type *Ty)
Definition: Constants.cpp:328
1 1 1 1 Always true (always folded)
Definition: InstrTypes.h:726
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:724
#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:736
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:713
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:723
SelectPatternFlavor
Specific patterns of select instructions we can match.
signed less than
Definition: InstrTypes.h:738
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:676
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:789
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:739
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:2209
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:784
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Definition: Instruction.h:321
bool intersects(const APInt &RHS) const
This operation tests if there are any pairs of corresponding bits between this APInt and RHS that are...
Definition: APInt.h:1320
static bool isMinOrMax(SelectPatternFlavor SPF)
When implementing this min/max pattern as fcmp; select, does the fcmp have to be ordered?
unsigned greater or equal
Definition: InstrTypes.h:733
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:2291
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:717
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:332
Value * SimplifyXorInst(Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for an Xor, fold the result or return null.
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value *> Args=None, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:2009
1 0 1 0 True if unordered or greater than
Definition: InstrTypes.h:721
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:712
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:722
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:732
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition: InstrTypes.h:824
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:2801
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:714
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:711
signed greater or equal
Definition: InstrTypes.h:737
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:2295