Coverage Report

Created: 2019-07-24 05:18

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