LLVM 20.0.0git
InstCombineAndOrXor.cpp
Go to the documentation of this file.
1//===- InstCombineAndOrXor.cpp --------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the visitAnd, visitOr, and visitXor functions.
10//
11//===----------------------------------------------------------------------===//
12
13#include "InstCombineInternal.h"
17#include "llvm/IR/Intrinsics.h"
21
22using namespace llvm;
23using namespace PatternMatch;
24
25#define DEBUG_TYPE "instcombine"
26
27/// This is the complement of getICmpCode, which turns an opcode and two
28/// operands into either a constant true or false, or a brand new ICmp
29/// instruction. The sign is passed in to determine which kind of predicate to
30/// use in the new icmp instruction.
31static Value *getNewICmpValue(unsigned Code, bool Sign, Value *LHS, Value *RHS,
32 InstCombiner::BuilderTy &Builder) {
33 ICmpInst::Predicate NewPred;
34 if (Constant *TorF = getPredForICmpCode(Code, Sign, LHS->getType(), NewPred))
35 return TorF;
36 return Builder.CreateICmp(NewPred, LHS, RHS);
37}
38
39/// This is the complement of getFCmpCode, which turns an opcode and two
40/// operands into either a FCmp instruction, or a true/false constant.
41static Value *getFCmpValue(unsigned Code, Value *LHS, Value *RHS,
42 InstCombiner::BuilderTy &Builder) {
43 FCmpInst::Predicate NewPred;
44 if (Constant *TorF = getPredForFCmpCode(Code, LHS->getType(), NewPred))
45 return TorF;
46 return Builder.CreateFCmp(NewPred, LHS, RHS);
47}
48
49/// Emit a computation of: (V >= Lo && V < Hi) if Inside is true, otherwise
50/// (V < Lo || V >= Hi). This method expects that Lo < Hi. IsSigned indicates
51/// whether to treat V, Lo, and Hi as signed or not.
53 const APInt &Hi, bool isSigned,
54 bool Inside) {
55 assert((isSigned ? Lo.slt(Hi) : Lo.ult(Hi)) &&
56 "Lo is not < Hi in range emission code!");
57
58 Type *Ty = V->getType();
59
60 // V >= Min && V < Hi --> V < Hi
61 // V < Min || V >= Hi --> V >= Hi
63 if (isSigned ? Lo.isMinSignedValue() : Lo.isMinValue()) {
64 Pred = isSigned ? ICmpInst::getSignedPredicate(Pred) : Pred;
65 return Builder.CreateICmp(Pred, V, ConstantInt::get(Ty, Hi));
66 }
67
68 // V >= Lo && V < Hi --> V - Lo u< Hi - Lo
69 // V < Lo || V >= Hi --> V - Lo u>= Hi - Lo
70 Value *VMinusLo =
71 Builder.CreateSub(V, ConstantInt::get(Ty, Lo), V->getName() + ".off");
72 Constant *HiMinusLo = ConstantInt::get(Ty, Hi - Lo);
73 return Builder.CreateICmp(Pred, VMinusLo, HiMinusLo);
74}
75
76/// Classify (icmp eq (A & B), C) and (icmp ne (A & B), C) as matching patterns
77/// that can be simplified.
78/// One of A and B is considered the mask. The other is the value. This is
79/// described as the "AMask" or "BMask" part of the enum. If the enum contains
80/// only "Mask", then both A and B can be considered masks. If A is the mask,
81/// then it was proven that (A & C) == C. This is trivial if C == A or C == 0.
82/// If both A and C are constants, this proof is also easy.
83/// For the following explanations, we assume that A is the mask.
84///
85/// "AllOnes" declares that the comparison is true only if (A & B) == A or all
86/// bits of A are set in B.
87/// Example: (icmp eq (A & 3), 3) -> AMask_AllOnes
88///
89/// "AllZeros" declares that the comparison is true only if (A & B) == 0 or all
90/// bits of A are cleared in B.
91/// Example: (icmp eq (A & 3), 0) -> Mask_AllZeroes
92///
93/// "Mixed" declares that (A & B) == C and C might or might not contain any
94/// number of one bits and zero bits.
95/// Example: (icmp eq (A & 3), 1) -> AMask_Mixed
96///
97/// "Not" means that in above descriptions "==" should be replaced by "!=".
98/// Example: (icmp ne (A & 3), 3) -> AMask_NotAllOnes
99///
100/// If the mask A contains a single bit, then the following is equivalent:
101/// (icmp eq (A & B), A) equals (icmp ne (A & B), 0)
102/// (icmp ne (A & B), A) equals (icmp eq (A & B), 0)
113 BMask_NotMixed = 512
115
116/// Return the set of patterns (from MaskedICmpType) that (icmp SCC (A & B), C)
117/// satisfies.
118static unsigned getMaskedICmpType(Value *A, Value *B, Value *C,
119 ICmpInst::Predicate Pred) {
120 const APInt *ConstA = nullptr, *ConstB = nullptr, *ConstC = nullptr;
121 match(A, m_APInt(ConstA));
122 match(B, m_APInt(ConstB));
123 match(C, m_APInt(ConstC));
124 bool IsEq = (Pred == ICmpInst::ICMP_EQ);
125 bool IsAPow2 = ConstA && ConstA->isPowerOf2();
126 bool IsBPow2 = ConstB && ConstB->isPowerOf2();
127 unsigned MaskVal = 0;
128 if (ConstC && ConstC->isZero()) {
129 // if C is zero, then both A and B qualify as mask
130 MaskVal |= (IsEq ? (Mask_AllZeros | AMask_Mixed | BMask_Mixed)
132 if (IsAPow2)
133 MaskVal |= (IsEq ? (AMask_NotAllOnes | AMask_NotMixed)
135 if (IsBPow2)
136 MaskVal |= (IsEq ? (BMask_NotAllOnes | BMask_NotMixed)
138 return MaskVal;
139 }
140
141 if (A == C) {
142 MaskVal |= (IsEq ? (AMask_AllOnes | AMask_Mixed)
144 if (IsAPow2)
145 MaskVal |= (IsEq ? (Mask_NotAllZeros | AMask_NotMixed)
147 } else if (ConstA && ConstC && ConstC->isSubsetOf(*ConstA)) {
148 MaskVal |= (IsEq ? AMask_Mixed : AMask_NotMixed);
149 }
150
151 if (B == C) {
152 MaskVal |= (IsEq ? (BMask_AllOnes | BMask_Mixed)
154 if (IsBPow2)
155 MaskVal |= (IsEq ? (Mask_NotAllZeros | BMask_NotMixed)
157 } else if (ConstB && ConstC && ConstC->isSubsetOf(*ConstB)) {
158 MaskVal |= (IsEq ? BMask_Mixed : BMask_NotMixed);
159 }
160
161 return MaskVal;
162}
163
164/// Convert an analysis of a masked ICmp into its equivalent if all boolean
165/// operations had the opposite sense. Since each "NotXXX" flag (recording !=)
166/// is adjacent to the corresponding normal flag (recording ==), this just
167/// involves swapping those bits over.
168static unsigned conjugateICmpMask(unsigned Mask) {
169 unsigned NewMask;
170 NewMask = (Mask & (AMask_AllOnes | BMask_AllOnes | Mask_AllZeros |
172 << 1;
173
174 NewMask |= (Mask & (AMask_NotAllOnes | BMask_NotAllOnes | Mask_NotAllZeros |
176 >> 1;
177
178 return NewMask;
179}
180
181// Adapts the external decomposeBitTestICmp for local use.
183 Value *&X, Value *&Y, Value *&Z) {
184 APInt Mask;
185 if (!llvm::decomposeBitTestICmp(LHS, RHS, Pred, X, Mask))
186 return false;
187
188 Y = ConstantInt::get(X->getType(), Mask);
189 Z = ConstantInt::get(X->getType(), 0);
190 return true;
191}
192
193/// Handle (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E).
194/// Return the pattern classes (from MaskedICmpType) for the left hand side and
195/// the right hand side as a pair.
196/// LHS and RHS are the left hand side and the right hand side ICmps and PredL
197/// and PredR are their predicates, respectively.
198static std::optional<std::pair<unsigned, unsigned>> getMaskedTypeForICmpPair(
199 Value *&A, Value *&B, Value *&C, Value *&D, Value *&E, ICmpInst *LHS,
200 ICmpInst *RHS, ICmpInst::Predicate &PredL, ICmpInst::Predicate &PredR) {
201 // Don't allow pointers. Splat vectors are fine.
202 if (!LHS->getOperand(0)->getType()->isIntOrIntVectorTy() ||
203 !RHS->getOperand(0)->getType()->isIntOrIntVectorTy())
204 return std::nullopt;
205
206 // Here comes the tricky part:
207 // LHS might be of the form L11 & L12 == X, X == L21 & L22,
208 // and L11 & L12 == L21 & L22. The same goes for RHS.
209 // Now we must find those components L** and R**, that are equal, so
210 // that we can extract the parameters A, B, C, D, and E for the canonical
211 // above.
212 Value *L1 = LHS->getOperand(0);
213 Value *L2 = LHS->getOperand(1);
214 Value *L11, *L12, *L21, *L22;
215 // Check whether the icmp can be decomposed into a bit test.
216 if (decomposeBitTestICmp(L1, L2, PredL, L11, L12, L2)) {
217 L21 = L22 = L1 = nullptr;
218 } else {
219 // Look for ANDs in the LHS icmp.
220 if (!match(L1, m_And(m_Value(L11), m_Value(L12)))) {
221 // Any icmp can be viewed as being trivially masked; if it allows us to
222 // remove one, it's worth it.
223 L11 = L1;
225 }
226
227 if (!match(L2, m_And(m_Value(L21), m_Value(L22)))) {
228 L21 = L2;
230 }
231 }
232
233 // Bail if LHS was a icmp that can't be decomposed into an equality.
234 if (!ICmpInst::isEquality(PredL))
235 return std::nullopt;
236
237 Value *R1 = RHS->getOperand(0);
238 Value *R2 = RHS->getOperand(1);
239 Value *R11, *R12;
240 bool Ok = false;
241 if (decomposeBitTestICmp(R1, R2, PredR, R11, R12, R2)) {
242 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
243 A = R11;
244 D = R12;
245 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
246 A = R12;
247 D = R11;
248 } else {
249 return std::nullopt;
250 }
251 E = R2;
252 R1 = nullptr;
253 Ok = true;
254 } else {
255 if (!match(R1, m_And(m_Value(R11), m_Value(R12)))) {
256 // As before, model no mask as a trivial mask if it'll let us do an
257 // optimization.
258 R11 = R1;
260 }
261
262 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
263 A = R11;
264 D = R12;
265 E = R2;
266 Ok = true;
267 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
268 A = R12;
269 D = R11;
270 E = R2;
271 Ok = true;
272 }
273 }
274
275 // Bail if RHS was a icmp that can't be decomposed into an equality.
276 if (!ICmpInst::isEquality(PredR))
277 return std::nullopt;
278
279 // Look for ANDs on the right side of the RHS icmp.
280 if (!Ok) {
281 if (!match(R2, m_And(m_Value(R11), m_Value(R12)))) {
282 R11 = R2;
283 R12 = Constant::getAllOnesValue(R2->getType());
284 }
285
286 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
287 A = R11;
288 D = R12;
289 E = R1;
290 Ok = true;
291 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
292 A = R12;
293 D = R11;
294 E = R1;
295 Ok = true;
296 } else {
297 return std::nullopt;
298 }
299
300 assert(Ok && "Failed to find AND on the right side of the RHS icmp.");
301 }
302
303 if (L11 == A) {
304 B = L12;
305 C = L2;
306 } else if (L12 == A) {
307 B = L11;
308 C = L2;
309 } else if (L21 == A) {
310 B = L22;
311 C = L1;
312 } else if (L22 == A) {
313 B = L21;
314 C = L1;
315 }
316
317 unsigned LeftType = getMaskedICmpType(A, B, C, PredL);
318 unsigned RightType = getMaskedICmpType(A, D, E, PredR);
319 return std::optional<std::pair<unsigned, unsigned>>(
320 std::make_pair(LeftType, RightType));
321}
322
323/// Try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E) into a single
324/// (icmp(A & X) ==/!= Y), where the left-hand side is of type Mask_NotAllZeros
325/// and the right hand side is of type BMask_Mixed. For example,
326/// (icmp (A & 12) != 0) & (icmp (A & 15) == 8) -> (icmp (A & 15) == 8).
327/// Also used for logical and/or, must be poison safe.
329 ICmpInst *LHS, ICmpInst *RHS, bool IsAnd, Value *A, Value *B, Value *D,
331 InstCombiner::BuilderTy &Builder) {
332 // We are given the canonical form:
333 // (icmp ne (A & B), 0) & (icmp eq (A & D), E).
334 // where D & E == E.
335 //
336 // If IsAnd is false, we get it in negated form:
337 // (icmp eq (A & B), 0) | (icmp ne (A & D), E) ->
338 // !((icmp ne (A & B), 0) & (icmp eq (A & D), E)).
339 //
340 // We currently handle the case of B, C, D, E are constant.
341 //
342 const APInt *BCst, *DCst, *OrigECst;
343 if (!match(B, m_APInt(BCst)) || !match(D, m_APInt(DCst)) ||
344 !match(E, m_APInt(OrigECst)))
345 return nullptr;
346
348
349 // Update E to the canonical form when D is a power of two and RHS is
350 // canonicalized as,
351 // (icmp ne (A & D), 0) -> (icmp eq (A & D), D) or
352 // (icmp ne (A & D), D) -> (icmp eq (A & D), 0).
353 APInt ECst = *OrigECst;
354 if (PredR != NewCC)
355 ECst ^= *DCst;
356
357 // If B or D is zero, skip because if LHS or RHS can be trivially folded by
358 // other folding rules and this pattern won't apply any more.
359 if (*BCst == 0 || *DCst == 0)
360 return nullptr;
361
362 // If B and D don't intersect, ie. (B & D) == 0, try to fold isNaN idiom:
363 // (icmp ne (A & FractionBits), 0) & (icmp eq (A & ExpBits), ExpBits)
364 // -> isNaN(A)
365 // Otherwise, we cannot deduce anything from it.
366 if (!BCst->intersects(*DCst)) {
367 Value *Src;
368 if (*DCst == ECst && match(A, m_ElementWiseBitCast(m_Value(Src))) &&
370 Attribute::StrictFP)) {
371 Type *Ty = Src->getType()->getScalarType();
372 if (!Ty->isIEEELikeFPTy())
373 return nullptr;
374
376 if (ECst != ExpBits)
377 return nullptr;
378 APInt FractionBits = ~ExpBits;
379 FractionBits.clearSignBit();
380 if (*BCst != FractionBits)
381 return nullptr;
382
383 return Builder.CreateFCmp(IsAnd ? FCmpInst::FCMP_UNO : FCmpInst::FCMP_ORD,
384 Src, ConstantFP::getZero(Src->getType()));
385 }
386 return nullptr;
387 }
388
389 // If the following two conditions are met:
390 //
391 // 1. mask B covers only a single bit that's not covered by mask D, that is,
392 // (B & (B ^ D)) is a power of 2 (in other words, B minus the intersection of
393 // B and D has only one bit set) and,
394 //
395 // 2. RHS (and E) indicates that the rest of B's bits are zero (in other
396 // words, the intersection of B and D is zero), that is, ((B & D) & E) == 0
397 //
398 // then that single bit in B must be one and thus the whole expression can be
399 // folded to
400 // (A & (B | D)) == (B & (B ^ D)) | E.
401 //
402 // For example,
403 // (icmp ne (A & 12), 0) & (icmp eq (A & 7), 1) -> (icmp eq (A & 15), 9)
404 // (icmp ne (A & 15), 0) & (icmp eq (A & 7), 0) -> (icmp eq (A & 15), 8)
405 if ((((*BCst & *DCst) & ECst) == 0) &&
406 (*BCst & (*BCst ^ *DCst)).isPowerOf2()) {
407 APInt BorD = *BCst | *DCst;
408 APInt BandBxorDorE = (*BCst & (*BCst ^ *DCst)) | ECst;
409 Value *NewMask = ConstantInt::get(A->getType(), BorD);
410 Value *NewMaskedValue = ConstantInt::get(A->getType(), BandBxorDorE);
411 Value *NewAnd = Builder.CreateAnd(A, NewMask);
412 return Builder.CreateICmp(NewCC, NewAnd, NewMaskedValue);
413 }
414
415 auto IsSubSetOrEqual = [](const APInt *C1, const APInt *C2) {
416 return (*C1 & *C2) == *C1;
417 };
418 auto IsSuperSetOrEqual = [](const APInt *C1, const APInt *C2) {
419 return (*C1 & *C2) == *C2;
420 };
421
422 // In the following, we consider only the cases where B is a superset of D, B
423 // is a subset of D, or B == D because otherwise there's at least one bit
424 // covered by B but not D, in which case we can't deduce much from it, so
425 // no folding (aside from the single must-be-one bit case right above.)
426 // For example,
427 // (icmp ne (A & 14), 0) & (icmp eq (A & 3), 1) -> no folding.
428 if (!IsSubSetOrEqual(BCst, DCst) && !IsSuperSetOrEqual(BCst, DCst))
429 return nullptr;
430
431 // At this point, either B is a superset of D, B is a subset of D or B == D.
432
433 // If E is zero, if B is a subset of (or equal to) D, LHS and RHS contradict
434 // and the whole expression becomes false (or true if negated), otherwise, no
435 // folding.
436 // For example,
437 // (icmp ne (A & 3), 0) & (icmp eq (A & 7), 0) -> false.
438 // (icmp ne (A & 15), 0) & (icmp eq (A & 3), 0) -> no folding.
439 if (ECst.isZero()) {
440 if (IsSubSetOrEqual(BCst, DCst))
441 return ConstantInt::get(LHS->getType(), !IsAnd);
442 return nullptr;
443 }
444
445 // At this point, B, D, E aren't zero and (B & D) == B, (B & D) == D or B ==
446 // D. If B is a superset of (or equal to) D, since E is not zero, LHS is
447 // subsumed by RHS (RHS implies LHS.) So the whole expression becomes
448 // RHS. For example,
449 // (icmp ne (A & 255), 0) & (icmp eq (A & 15), 8) -> (icmp eq (A & 15), 8).
450 // (icmp ne (A & 15), 0) & (icmp eq (A & 15), 8) -> (icmp eq (A & 15), 8).
451 if (IsSuperSetOrEqual(BCst, DCst))
452 return RHS;
453 // Otherwise, B is a subset of D. If B and E have a common bit set,
454 // ie. (B & E) != 0, then LHS is subsumed by RHS. For example.
455 // (icmp ne (A & 12), 0) & (icmp eq (A & 15), 8) -> (icmp eq (A & 15), 8).
456 assert(IsSubSetOrEqual(BCst, DCst) && "Precondition due to above code");
457 if ((*BCst & ECst) != 0)
458 return RHS;
459 // Otherwise, LHS and RHS contradict and the whole expression becomes false
460 // (or true if negated.) For example,
461 // (icmp ne (A & 7), 0) & (icmp eq (A & 15), 8) -> false.
462 // (icmp ne (A & 6), 0) & (icmp eq (A & 15), 8) -> false.
463 return ConstantInt::get(LHS->getType(), !IsAnd);
464}
465
466/// Try to fold (icmp(A & B) ==/!= 0) &/| (icmp(A & D) ==/!= E) into a single
467/// (icmp(A & X) ==/!= Y), where the left-hand side and the right hand side
468/// aren't of the common mask pattern type.
469/// Also used for logical and/or, must be poison safe.
471 ICmpInst *LHS, ICmpInst *RHS, bool IsAnd, Value *A, Value *B, Value *C,
473 unsigned LHSMask, unsigned RHSMask, InstCombiner::BuilderTy &Builder) {
475 "Expected equality predicates for masked type of icmps.");
476 // Handle Mask_NotAllZeros-BMask_Mixed cases.
477 // (icmp ne/eq (A & B), C) &/| (icmp eq/ne (A & D), E), or
478 // (icmp eq/ne (A & B), C) &/| (icmp ne/eq (A & D), E)
479 // which gets swapped to
480 // (icmp ne/eq (A & D), E) &/| (icmp eq/ne (A & B), C).
481 if (!IsAnd) {
482 LHSMask = conjugateICmpMask(LHSMask);
483 RHSMask = conjugateICmpMask(RHSMask);
484 }
485 if ((LHSMask & Mask_NotAllZeros) && (RHSMask & BMask_Mixed)) {
487 LHS, RHS, IsAnd, A, B, D, E, PredL, PredR, Builder)) {
488 return V;
489 }
490 } else if ((LHSMask & BMask_Mixed) && (RHSMask & Mask_NotAllZeros)) {
492 RHS, LHS, IsAnd, A, D, B, C, PredR, PredL, Builder)) {
493 return V;
494 }
495 }
496 return nullptr;
497}
498
499/// Try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
500/// into a single (icmp(A & X) ==/!= Y).
501static Value *foldLogOpOfMaskedICmps(ICmpInst *LHS, ICmpInst *RHS, bool IsAnd,
502 bool IsLogical,
503 InstCombiner::BuilderTy &Builder) {
504 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr, *E = nullptr;
505 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
506 std::optional<std::pair<unsigned, unsigned>> MaskPair =
507 getMaskedTypeForICmpPair(A, B, C, D, E, LHS, RHS, PredL, PredR);
508 if (!MaskPair)
509 return nullptr;
511 "Expected equality predicates for masked type of icmps.");
512 unsigned LHSMask = MaskPair->first;
513 unsigned RHSMask = MaskPair->second;
514 unsigned Mask = LHSMask & RHSMask;
515 if (Mask == 0) {
516 // Even if the two sides don't share a common pattern, check if folding can
517 // still happen.
519 LHS, RHS, IsAnd, A, B, C, D, E, PredL, PredR, LHSMask, RHSMask,
520 Builder))
521 return V;
522 return nullptr;
523 }
524
525 // In full generality:
526 // (icmp (A & B) Op C) | (icmp (A & D) Op E)
527 // == ![ (icmp (A & B) !Op C) & (icmp (A & D) !Op E) ]
528 //
529 // If the latter can be converted into (icmp (A & X) Op Y) then the former is
530 // equivalent to (icmp (A & X) !Op Y).
531 //
532 // Therefore, we can pretend for the rest of this function that we're dealing
533 // with the conjunction, provided we flip the sense of any comparisons (both
534 // input and output).
535
536 // In most cases we're going to produce an EQ for the "&&" case.
538 if (!IsAnd) {
539 // Convert the masking analysis into its equivalent with negated
540 // comparisons.
541 Mask = conjugateICmpMask(Mask);
542 }
543
544 if (Mask & Mask_AllZeros) {
545 // (icmp eq (A & B), 0) & (icmp eq (A & D), 0)
546 // -> (icmp eq (A & (B|D)), 0)
547 if (IsLogical && !isGuaranteedNotToBeUndefOrPoison(D))
548 return nullptr; // TODO: Use freeze?
549 Value *NewOr = Builder.CreateOr(B, D);
550 Value *NewAnd = Builder.CreateAnd(A, NewOr);
551 // We can't use C as zero because we might actually handle
552 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
553 // with B and D, having a single bit set.
554 Value *Zero = Constant::getNullValue(A->getType());
555 return Builder.CreateICmp(NewCC, NewAnd, Zero);
556 }
557 if (Mask & BMask_AllOnes) {
558 // (icmp eq (A & B), B) & (icmp eq (A & D), D)
559 // -> (icmp eq (A & (B|D)), (B|D))
560 if (IsLogical && !isGuaranteedNotToBeUndefOrPoison(D))
561 return nullptr; // TODO: Use freeze?
562 Value *NewOr = Builder.CreateOr(B, D);
563 Value *NewAnd = Builder.CreateAnd(A, NewOr);
564 return Builder.CreateICmp(NewCC, NewAnd, NewOr);
565 }
566 if (Mask & AMask_AllOnes) {
567 // (icmp eq (A & B), A) & (icmp eq (A & D), A)
568 // -> (icmp eq (A & (B&D)), A)
569 if (IsLogical && !isGuaranteedNotToBeUndefOrPoison(D))
570 return nullptr; // TODO: Use freeze?
571 Value *NewAnd1 = Builder.CreateAnd(B, D);
572 Value *NewAnd2 = Builder.CreateAnd(A, NewAnd1);
573 return Builder.CreateICmp(NewCC, NewAnd2, A);
574 }
575
576 // Remaining cases assume at least that B and D are constant, and depend on
577 // their actual values. This isn't strictly necessary, just a "handle the
578 // easy cases for now" decision.
579 const APInt *ConstB, *ConstD;
580 if (!match(B, m_APInt(ConstB)) || !match(D, m_APInt(ConstD)))
581 return nullptr;
582
583 if (Mask & (Mask_NotAllZeros | BMask_NotAllOnes)) {
584 // (icmp ne (A & B), 0) & (icmp ne (A & D), 0) and
585 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
586 // -> (icmp ne (A & B), 0) or (icmp ne (A & D), 0)
587 // Only valid if one of the masks is a superset of the other (check "B&D" is
588 // the same as either B or D).
589 APInt NewMask = *ConstB & *ConstD;
590 if (NewMask == *ConstB)
591 return LHS;
592 else if (NewMask == *ConstD)
593 return RHS;
594 }
595
596 if (Mask & AMask_NotAllOnes) {
597 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
598 // -> (icmp ne (A & B), A) or (icmp ne (A & D), A)
599 // Only valid if one of the masks is a superset of the other (check "B|D" is
600 // the same as either B or D).
601 APInt NewMask = *ConstB | *ConstD;
602 if (NewMask == *ConstB)
603 return LHS;
604 else if (NewMask == *ConstD)
605 return RHS;
606 }
607
608 if (Mask & (BMask_Mixed | BMask_NotMixed)) {
609 // Mixed:
610 // (icmp eq (A & B), C) & (icmp eq (A & D), E)
611 // We already know that B & C == C && D & E == E.
612 // If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of
613 // C and E, which are shared by both the mask B and the mask D, don't
614 // contradict, then we can transform to
615 // -> (icmp eq (A & (B|D)), (C|E))
616 // Currently, we only handle the case of B, C, D, and E being constant.
617 // We can't simply use C and E because we might actually handle
618 // (icmp ne (A & B), B) & (icmp eq (A & D), D)
619 // with B and D, having a single bit set.
620
621 // NotMixed:
622 // (icmp ne (A & B), C) & (icmp ne (A & D), E)
623 // -> (icmp ne (A & (B & D)), (C & E))
624 // Check the intersection (B & D) for inequality.
625 // Assume that (B & D) == B || (B & D) == D, i.e B/D is a subset of D/B
626 // and (B & D) & (C ^ E) == 0, bits of C and E, which are shared by both the
627 // B and the D, don't contradict.
628 // Note that we can assume (~B & C) == 0 && (~D & E) == 0, previous
629 // operation should delete these icmps if it hadn't been met.
630
631 const APInt *OldConstC, *OldConstE;
632 if (!match(C, m_APInt(OldConstC)) || !match(E, m_APInt(OldConstE)))
633 return nullptr;
634
635 auto FoldBMixed = [&](ICmpInst::Predicate CC, bool IsNot) -> Value * {
637 const APInt ConstC = PredL != CC ? *ConstB ^ *OldConstC : *OldConstC;
638 const APInt ConstE = PredR != CC ? *ConstD ^ *OldConstE : *OldConstE;
639
640 if (((*ConstB & *ConstD) & (ConstC ^ ConstE)).getBoolValue())
641 return IsNot ? nullptr : ConstantInt::get(LHS->getType(), !IsAnd);
642
643 if (IsNot && !ConstB->isSubsetOf(*ConstD) && !ConstD->isSubsetOf(*ConstB))
644 return nullptr;
645
646 APInt BD, CE;
647 if (IsNot) {
648 BD = *ConstB & *ConstD;
649 CE = ConstC & ConstE;
650 } else {
651 BD = *ConstB | *ConstD;
652 CE = ConstC | ConstE;
653 }
654 Value *NewAnd = Builder.CreateAnd(A, BD);
655 Value *CEVal = ConstantInt::get(A->getType(), CE);
656 return Builder.CreateICmp(CC, CEVal, NewAnd);
657 };
658
659 if (Mask & BMask_Mixed)
660 return FoldBMixed(NewCC, false);
661 if (Mask & BMask_NotMixed) // can be else also
662 return FoldBMixed(NewCC, true);
663 }
664 return nullptr;
665}
666
667/// Try to fold a signed range checked with lower bound 0 to an unsigned icmp.
668/// Example: (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
669/// If \p Inverted is true then the check is for the inverted range, e.g.
670/// (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
672 bool Inverted) {
673 // Check the lower range comparison, e.g. x >= 0
674 // InstCombine already ensured that if there is a constant it's on the RHS.
675 ConstantInt *RangeStart = dyn_cast<ConstantInt>(Cmp0->getOperand(1));
676 if (!RangeStart)
677 return nullptr;
678
679 ICmpInst::Predicate Pred0 = (Inverted ? Cmp0->getInversePredicate() :
680 Cmp0->getPredicate());
681
682 // Accept x > -1 or x >= 0 (after potentially inverting the predicate).
683 if (!((Pred0 == ICmpInst::ICMP_SGT && RangeStart->isMinusOne()) ||
684 (Pred0 == ICmpInst::ICMP_SGE && RangeStart->isZero())))
685 return nullptr;
686
687 ICmpInst::Predicate Pred1 = (Inverted ? Cmp1->getInversePredicate() :
688 Cmp1->getPredicate());
689
690 Value *Input = Cmp0->getOperand(0);
691 Value *RangeEnd;
692 if (Cmp1->getOperand(0) == Input) {
693 // For the upper range compare we have: icmp x, n
694 RangeEnd = Cmp1->getOperand(1);
695 } else if (Cmp1->getOperand(1) == Input) {
696 // For the upper range compare we have: icmp n, x
697 RangeEnd = Cmp1->getOperand(0);
698 Pred1 = ICmpInst::getSwappedPredicate(Pred1);
699 } else {
700 return nullptr;
701 }
702
703 // Check the upper range comparison, e.g. x < n
704 ICmpInst::Predicate NewPred;
705 switch (Pred1) {
706 case ICmpInst::ICMP_SLT: NewPred = ICmpInst::ICMP_ULT; break;
707 case ICmpInst::ICMP_SLE: NewPred = ICmpInst::ICMP_ULE; break;
708 default: return nullptr;
709 }
710
711 // This simplification is only valid if the upper range is not negative.
712 KnownBits Known = computeKnownBits(RangeEnd, /*Depth=*/0, Cmp1);
713 if (!Known.isNonNegative())
714 return nullptr;
715
716 if (Inverted)
717 NewPred = ICmpInst::getInversePredicate(NewPred);
718
719 return Builder.CreateICmp(NewPred, Input, RangeEnd);
720}
721
722// (or (icmp eq X, 0), (icmp eq X, Pow2OrZero))
723// -> (icmp eq (and X, Pow2OrZero), X)
724// (and (icmp ne X, 0), (icmp ne X, Pow2OrZero))
725// -> (icmp ne (and X, Pow2OrZero), X)
726static Value *
728 ICmpInst *LHS, ICmpInst *RHS, bool IsAnd,
729 const SimplifyQuery &Q) {
731 // Make sure we have right compares for our op.
732 if (LHS->getPredicate() != Pred || RHS->getPredicate() != Pred)
733 return nullptr;
734
735 // Make it so we can match LHS against the (icmp eq/ne X, 0) just for
736 // simplicity.
737 if (match(RHS->getOperand(1), m_Zero()))
738 std::swap(LHS, RHS);
739
740 Value *Pow2, *Op;
741 // Match the desired pattern:
742 // LHS: (icmp eq/ne X, 0)
743 // RHS: (icmp eq/ne X, Pow2OrZero)
744 // Skip if Pow2OrZero is 1. Either way it gets folded to (icmp ugt X, 1) but
745 // this form ends up slightly less canonical.
746 // We could potentially be more sophisticated than requiring LHS/RHS
747 // be one-use. We don't create additional instructions if only one
748 // of them is one-use. So cases where one is one-use and the other
749 // is two-use might be profitable.
750 if (!match(LHS, m_OneUse(m_ICmp(Pred, m_Value(Op), m_Zero()))) ||
751 !match(RHS, m_OneUse(m_c_ICmp(Pred, m_Specific(Op), m_Value(Pow2)))) ||
752 match(Pow2, m_One()) ||
753 !isKnownToBeAPowerOfTwo(Pow2, Q.DL, /*OrZero=*/true, /*Depth=*/0, Q.AC,
754 Q.CxtI, Q.DT))
755 return nullptr;
756
757 Value *And = Builder.CreateAnd(Op, Pow2);
758 return Builder.CreateICmp(Pred, And, Op);
759}
760
761// Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
762// Fold (!iszero(A & K1) & !iszero(A & K2)) -> (A & (K1 | K2)) == (K1 | K2)
763Value *InstCombinerImpl::foldAndOrOfICmpsOfAndWithPow2(ICmpInst *LHS,
764 ICmpInst *RHS,
765 Instruction *CxtI,
766 bool IsAnd,
767 bool IsLogical) {
769 if (LHS->getPredicate() != Pred || RHS->getPredicate() != Pred)
770 return nullptr;
771
772 if (!match(LHS->getOperand(1), m_Zero()) ||
773 !match(RHS->getOperand(1), m_Zero()))
774 return nullptr;
775
776 Value *L1, *L2, *R1, *R2;
777 if (match(LHS->getOperand(0), m_And(m_Value(L1), m_Value(L2))) &&
778 match(RHS->getOperand(0), m_And(m_Value(R1), m_Value(R2)))) {
779 if (L1 == R2 || L2 == R2)
780 std::swap(R1, R2);
781 if (L2 == R1)
782 std::swap(L1, L2);
783
784 if (L1 == R1 &&
785 isKnownToBeAPowerOfTwo(L2, false, 0, CxtI) &&
786 isKnownToBeAPowerOfTwo(R2, false, 0, CxtI)) {
787 // If this is a logical and/or, then we must prevent propagation of a
788 // poison value from the RHS by inserting freeze.
789 if (IsLogical)
791 Value *Mask = Builder.CreateOr(L2, R2);
792 Value *Masked = Builder.CreateAnd(L1, Mask);
793 auto NewPred = IsAnd ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;
794 return Builder.CreateICmp(NewPred, Masked, Mask);
795 }
796 }
797
798 return nullptr;
799}
800
801/// General pattern:
802/// X & Y
803///
804/// Where Y is checking that all the high bits (covered by a mask 4294967168)
805/// are uniform, i.e. %arg & 4294967168 can be either 4294967168 or 0
806/// Pattern can be one of:
807/// %t = add i32 %arg, 128
808/// %r = icmp ult i32 %t, 256
809/// Or
810/// %t0 = shl i32 %arg, 24
811/// %t1 = ashr i32 %t0, 24
812/// %r = icmp eq i32 %t1, %arg
813/// Or
814/// %t0 = trunc i32 %arg to i8
815/// %t1 = sext i8 %t0 to i32
816/// %r = icmp eq i32 %t1, %arg
817/// This pattern is a signed truncation check.
818///
819/// And X is checking that some bit in that same mask is zero.
820/// I.e. can be one of:
821/// %r = icmp sgt i32 %arg, -1
822/// Or
823/// %t = and i32 %arg, 2147483648
824/// %r = icmp eq i32 %t, 0
825///
826/// Since we are checking that all the bits in that mask are the same,
827/// and a particular bit is zero, what we are really checking is that all the
828/// masked bits are zero.
829/// So this should be transformed to:
830/// %r = icmp ult i32 %arg, 128
832 Instruction &CxtI,
833 InstCombiner::BuilderTy &Builder) {
834 assert(CxtI.getOpcode() == Instruction::And);
835
836 // Match icmp ult (add %arg, C01), C1 (C1 == C01 << 1; powers of two)
837 auto tryToMatchSignedTruncationCheck = [](ICmpInst *ICmp, Value *&X,
838 APInt &SignBitMask) -> bool {
839 const APInt *I01, *I1; // powers of two; I1 == I01 << 1
841 m_Add(m_Value(X), m_Power2(I01)),
842 m_Power2(I1))) &&
843 I1->ugt(*I01) && I01->shl(1) == *I1))
844 return false;
845 // Which bit is the new sign bit as per the 'signed truncation' pattern?
846 SignBitMask = *I01;
847 return true;
848 };
849
850 // One icmp needs to be 'signed truncation check'.
851 // We need to match this first, else we will mismatch commutative cases.
852 Value *X1;
853 APInt HighestBit;
854 ICmpInst *OtherICmp;
855 if (tryToMatchSignedTruncationCheck(ICmp1, X1, HighestBit))
856 OtherICmp = ICmp0;
857 else if (tryToMatchSignedTruncationCheck(ICmp0, X1, HighestBit))
858 OtherICmp = ICmp1;
859 else
860 return nullptr;
861
862 assert(HighestBit.isPowerOf2() && "expected to be power of two (non-zero)");
863
864 // Try to match/decompose into: icmp eq (X & Mask), 0
865 auto tryToDecompose = [](ICmpInst *ICmp, Value *&X,
866 APInt &UnsetBitsMask) -> bool {
867 CmpInst::Predicate Pred = ICmp->getPredicate();
868 // Can it be decomposed into icmp eq (X & Mask), 0 ?
869 if (llvm::decomposeBitTestICmp(ICmp->getOperand(0), ICmp->getOperand(1),
870 Pred, X, UnsetBitsMask,
871 /*LookThroughTrunc=*/false) &&
872 Pred == ICmpInst::ICMP_EQ)
873 return true;
874 // Is it icmp eq (X & Mask), 0 already?
875 const APInt *Mask;
876 if (match(ICmp, m_ICmp(Pred, m_And(m_Value(X), m_APInt(Mask)), m_Zero())) &&
877 Pred == ICmpInst::ICMP_EQ) {
878 UnsetBitsMask = *Mask;
879 return true;
880 }
881 return false;
882 };
883
884 // And the other icmp needs to be decomposable into a bit test.
885 Value *X0;
886 APInt UnsetBitsMask;
887 if (!tryToDecompose(OtherICmp, X0, UnsetBitsMask))
888 return nullptr;
889
890 assert(!UnsetBitsMask.isZero() && "empty mask makes no sense.");
891
892 // Are they working on the same value?
893 Value *X;
894 if (X1 == X0) {
895 // Ok as is.
896 X = X1;
897 } else if (match(X0, m_Trunc(m_Specific(X1)))) {
898 UnsetBitsMask = UnsetBitsMask.zext(X1->getType()->getScalarSizeInBits());
899 X = X1;
900 } else
901 return nullptr;
902
903 // So which bits should be uniform as per the 'signed truncation check'?
904 // (all the bits starting with (i.e. including) HighestBit)
905 APInt SignBitsMask = ~(HighestBit - 1U);
906
907 // UnsetBitsMask must have some common bits with SignBitsMask,
908 if (!UnsetBitsMask.intersects(SignBitsMask))
909 return nullptr;
910
911 // Does UnsetBitsMask contain any bits outside of SignBitsMask?
912 if (!UnsetBitsMask.isSubsetOf(SignBitsMask)) {
913 APInt OtherHighestBit = (~UnsetBitsMask) + 1U;
914 if (!OtherHighestBit.isPowerOf2())
915 return nullptr;
916 HighestBit = APIntOps::umin(HighestBit, OtherHighestBit);
917 }
918 // Else, if it does not, then all is ok as-is.
919
920 // %r = icmp ult %X, SignBit
921 return Builder.CreateICmpULT(X, ConstantInt::get(X->getType(), HighestBit),
922 CxtI.getName() + ".simplified");
923}
924
925/// Fold (icmp eq ctpop(X) 1) | (icmp eq X 0) into (icmp ult ctpop(X) 2) and
926/// fold (icmp ne ctpop(X) 1) & (icmp ne X 0) into (icmp ugt ctpop(X) 1).
927/// Also used for logical and/or, must be poison safe.
928static Value *foldIsPowerOf2OrZero(ICmpInst *Cmp0, ICmpInst *Cmp1, bool IsAnd,
929 InstCombiner::BuilderTy &Builder) {
930 CmpInst::Predicate Pred0, Pred1;
931 Value *X;
932 if (!match(Cmp0, m_ICmp(Pred0, m_Intrinsic<Intrinsic::ctpop>(m_Value(X)),
933 m_SpecificInt(1))) ||
934 !match(Cmp1, m_ICmp(Pred1, m_Specific(X), m_ZeroInt())))
935 return nullptr;
936
937 Value *CtPop = Cmp0->getOperand(0);
938 if (IsAnd && Pred0 == ICmpInst::ICMP_NE && Pred1 == ICmpInst::ICMP_NE)
939 return Builder.CreateICmpUGT(CtPop, ConstantInt::get(CtPop->getType(), 1));
940 if (!IsAnd && Pred0 == ICmpInst::ICMP_EQ && Pred1 == ICmpInst::ICMP_EQ)
941 return Builder.CreateICmpULT(CtPop, ConstantInt::get(CtPop->getType(), 2));
942
943 return nullptr;
944}
945
946/// Reduce a pair of compares that check if a value has exactly 1 bit set.
947/// Also used for logical and/or, must be poison safe.
948static Value *foldIsPowerOf2(ICmpInst *Cmp0, ICmpInst *Cmp1, bool JoinedByAnd,
949 InstCombiner::BuilderTy &Builder) {
950 // Handle 'and' / 'or' commutation: make the equality check the first operand.
951 if (JoinedByAnd && Cmp1->getPredicate() == ICmpInst::ICMP_NE)
952 std::swap(Cmp0, Cmp1);
953 else if (!JoinedByAnd && Cmp1->getPredicate() == ICmpInst::ICMP_EQ)
954 std::swap(Cmp0, Cmp1);
955
956 // (X != 0) && (ctpop(X) u< 2) --> ctpop(X) == 1
957 Value *X;
958 if (JoinedByAnd &&
961 m_Intrinsic<Intrinsic::ctpop>(m_Specific(X)),
962 m_SpecificInt(2)))) {
963 Value *CtPop = Cmp1->getOperand(0);
964 return Builder.CreateICmpEQ(CtPop, ConstantInt::get(CtPop->getType(), 1));
965 }
966 // (X == 0) || (ctpop(X) u> 1) --> ctpop(X) != 1
967 if (!JoinedByAnd &&
970 m_Intrinsic<Intrinsic::ctpop>(m_Specific(X)),
971 m_SpecificInt(1)))) {
972 Value *CtPop = Cmp1->getOperand(0);
973 return Builder.CreateICmpNE(CtPop, ConstantInt::get(CtPop->getType(), 1));
974 }
975 return nullptr;
976}
977
978/// Try to fold (icmp(A & B) == 0) & (icmp(A & D) != E) into (icmp A u< D) iff
979/// B is a contiguous set of ones starting from the most significant bit
980/// (negative power of 2), D and E are equal, and D is a contiguous set of ones
981/// starting at the most significant zero bit in B. Parameter B supports masking
982/// using undef/poison in either scalar or vector values.
984 Value *A, Value *B, Value *D, Value *E, ICmpInst::Predicate PredL,
987 "Expected equality predicates for masked type of icmps.");
988 if (PredL != ICmpInst::ICMP_EQ || PredR != ICmpInst::ICMP_NE)
989 return nullptr;
990
991 if (!match(B, m_NegatedPower2()) || !match(D, m_ShiftedMask()) ||
992 !match(E, m_ShiftedMask()))
993 return nullptr;
994
995 // Test scalar arguments for conversion. B has been validated earlier to be a
996 // negative power of two and thus is guaranteed to have one or more contiguous
997 // ones starting from the MSB followed by zero or more contiguous zeros. D has
998 // been validated earlier to be a shifted set of one or more contiguous ones.
999 // In order to match, B leading ones and D leading zeros should be equal. The
1000 // predicate that B be a negative power of 2 prevents the condition of there
1001 // ever being zero leading ones. Thus 0 == 0 cannot occur. The predicate that
1002 // D always be a shifted mask prevents the condition of D equaling 0. This
1003 // prevents matching the condition where B contains the maximum number of
1004 // leading one bits (-1) and D contains the maximum number of leading zero
1005 // bits (0).
1006 auto isReducible = [](const Value *B, const Value *D, const Value *E) {
1007 const APInt *BCst, *DCst, *ECst;
1008 return match(B, m_APIntAllowPoison(BCst)) && match(D, m_APInt(DCst)) &&
1009 match(E, m_APInt(ECst)) && *DCst == *ECst &&
1010 (isa<PoisonValue>(B) ||
1011 (BCst->countLeadingOnes() == DCst->countLeadingZeros()));
1012 };
1013
1014 // Test vector type arguments for conversion.
1015 if (const auto *BVTy = dyn_cast<VectorType>(B->getType())) {
1016 const auto *BFVTy = dyn_cast<FixedVectorType>(BVTy);
1017 const auto *BConst = dyn_cast<Constant>(B);
1018 const auto *DConst = dyn_cast<Constant>(D);
1019 const auto *EConst = dyn_cast<Constant>(E);
1020
1021 if (!BFVTy || !BConst || !DConst || !EConst)
1022 return nullptr;
1023
1024 for (unsigned I = 0; I != BFVTy->getNumElements(); ++I) {
1025 const auto *BElt = BConst->getAggregateElement(I);
1026 const auto *DElt = DConst->getAggregateElement(I);
1027 const auto *EElt = EConst->getAggregateElement(I);
1028
1029 if (!BElt || !DElt || !EElt)
1030 return nullptr;
1031 if (!isReducible(BElt, DElt, EElt))
1032 return nullptr;
1033 }
1034 } else {
1035 // Test scalar type arguments for conversion.
1036 if (!isReducible(B, D, E))
1037 return nullptr;
1038 }
1039 return Builder.CreateICmp(ICmpInst::ICMP_ULT, A, D);
1040}
1041
1042/// Try to fold ((icmp X u< P) & (icmp(X & M) != M)) or ((icmp X s> -1) &
1043/// (icmp(X & M) != M)) into (icmp X u< M). Where P is a power of 2, M < P, and
1044/// M is a contiguous shifted mask starting at the right most significant zero
1045/// bit in P. SGT is supported as when P is the largest representable power of
1046/// 2, an earlier optimization converts the expression into (icmp X s> -1).
1047/// Parameter P supports masking using undef/poison in either scalar or vector
1048/// values.
1050 bool JoinedByAnd,
1051 InstCombiner::BuilderTy &Builder) {
1052 if (!JoinedByAnd)
1053 return nullptr;
1054 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr, *E = nullptr;
1055 ICmpInst::Predicate CmpPred0 = Cmp0->getPredicate(),
1056 CmpPred1 = Cmp1->getPredicate();
1057 // Assuming P is a 2^n, getMaskedTypeForICmpPair will normalize (icmp X u<
1058 // 2^n) into (icmp (X & ~(2^n-1)) == 0) and (icmp X s> -1) into (icmp (X &
1059 // SignMask) == 0).
1060 std::optional<std::pair<unsigned, unsigned>> MaskPair =
1061 getMaskedTypeForICmpPair(A, B, C, D, E, Cmp0, Cmp1, CmpPred0, CmpPred1);
1062 if (!MaskPair)
1063 return nullptr;
1064
1065 const auto compareBMask = BMask_NotMixed | BMask_NotAllOnes;
1066 unsigned CmpMask0 = MaskPair->first;
1067 unsigned CmpMask1 = MaskPair->second;
1068 if ((CmpMask0 & Mask_AllZeros) && (CmpMask1 == compareBMask)) {
1069 if (Value *V = foldNegativePower2AndShiftedMask(A, B, D, E, CmpPred0,
1070 CmpPred1, Builder))
1071 return V;
1072 } else if ((CmpMask0 == compareBMask) && (CmpMask1 & Mask_AllZeros)) {
1073 if (Value *V = foldNegativePower2AndShiftedMask(A, D, B, C, CmpPred1,
1074 CmpPred0, Builder))
1075 return V;
1076 }
1077 return nullptr;
1078}
1079
1080/// Commuted variants are assumed to be handled by calling this function again
1081/// with the parameters swapped.
1083 ICmpInst *UnsignedICmp, bool IsAnd,
1084 const SimplifyQuery &Q,
1085 InstCombiner::BuilderTy &Builder) {
1086 Value *ZeroCmpOp;
1087 ICmpInst::Predicate EqPred;
1088 if (!match(ZeroICmp, m_ICmp(EqPred, m_Value(ZeroCmpOp), m_Zero())) ||
1089 !ICmpInst::isEquality(EqPred))
1090 return nullptr;
1091
1092 ICmpInst::Predicate UnsignedPred;
1093
1094 Value *A, *B;
1095 if (match(UnsignedICmp,
1096 m_c_ICmp(UnsignedPred, m_Specific(ZeroCmpOp), m_Value(A))) &&
1097 match(ZeroCmpOp, m_c_Add(m_Specific(A), m_Value(B))) &&
1098 (ZeroICmp->hasOneUse() || UnsignedICmp->hasOneUse())) {
1099 auto GetKnownNonZeroAndOther = [&](Value *&NonZero, Value *&Other) {
1100 if (!isKnownNonZero(NonZero, Q))
1101 std::swap(NonZero, Other);
1102 return isKnownNonZero(NonZero, Q);
1103 };
1104
1105 // Given ZeroCmpOp = (A + B)
1106 // ZeroCmpOp < A && ZeroCmpOp != 0 --> (0-X) < Y iff
1107 // ZeroCmpOp >= A || ZeroCmpOp == 0 --> (0-X) >= Y iff
1108 // with X being the value (A/B) that is known to be non-zero,
1109 // and Y being remaining value.
1110 if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_NE &&
1111 IsAnd && GetKnownNonZeroAndOther(B, A))
1112 return Builder.CreateICmpULT(Builder.CreateNeg(B), A);
1113 if (UnsignedPred == ICmpInst::ICMP_UGE && EqPred == ICmpInst::ICMP_EQ &&
1114 !IsAnd && GetKnownNonZeroAndOther(B, A))
1115 return Builder.CreateICmpUGE(Builder.CreateNeg(B), A);
1116 }
1117
1118 return nullptr;
1119}
1120
1121struct IntPart {
1123 unsigned StartBit;
1124 unsigned NumBits;
1125};
1126
1127/// Match an extraction of bits from an integer.
1128static std::optional<IntPart> matchIntPart(Value *V) {
1129 Value *X;
1130 if (!match(V, m_OneUse(m_Trunc(m_Value(X)))))
1131 return std::nullopt;
1132
1133 unsigned NumOriginalBits = X->getType()->getScalarSizeInBits();
1134 unsigned NumExtractedBits = V->getType()->getScalarSizeInBits();
1135 Value *Y;
1136 const APInt *Shift;
1137 // For a trunc(lshr Y, Shift) pattern, make sure we're only extracting bits
1138 // from Y, not any shifted-in zeroes.
1139 if (match(X, m_OneUse(m_LShr(m_Value(Y), m_APInt(Shift)))) &&
1140 Shift->ule(NumOriginalBits - NumExtractedBits))
1141 return {{Y, (unsigned)Shift->getZExtValue(), NumExtractedBits}};
1142 return {{X, 0, NumExtractedBits}};
1143}
1144
1145/// Materialize an extraction of bits from an integer in IR.
1146static Value *extractIntPart(const IntPart &P, IRBuilderBase &Builder) {
1147 Value *V = P.From;
1148 if (P.StartBit)
1149 V = Builder.CreateLShr(V, P.StartBit);
1150 Type *TruncTy = V->getType()->getWithNewBitWidth(P.NumBits);
1151 if (TruncTy != V->getType())
1152 V = Builder.CreateTrunc(V, TruncTy);
1153 return V;
1154}
1155
1156/// (icmp eq X0, Y0) & (icmp eq X1, Y1) -> icmp eq X01, Y01
1157/// (icmp ne X0, Y0) | (icmp ne X1, Y1) -> icmp ne X01, Y01
1158/// where X0, X1 and Y0, Y1 are adjacent parts extracted from an integer.
1159Value *InstCombinerImpl::foldEqOfParts(ICmpInst *Cmp0, ICmpInst *Cmp1,
1160 bool IsAnd) {
1161 if (!Cmp0->hasOneUse() || !Cmp1->hasOneUse())
1162 return nullptr;
1163
1165 auto GetMatchPart = [&](ICmpInst *Cmp,
1166 unsigned OpNo) -> std::optional<IntPart> {
1167 if (Pred == Cmp->getPredicate())
1168 return matchIntPart(Cmp->getOperand(OpNo));
1169
1170 const APInt *C;
1171 // (icmp eq (lshr x, C), (lshr y, C)) gets optimized to:
1172 // (icmp ult (xor x, y), 1 << C) so also look for that.
1173 if (Pred == CmpInst::ICMP_EQ && Cmp->getPredicate() == CmpInst::ICMP_ULT) {
1174 if (!match(Cmp->getOperand(1), m_Power2(C)) ||
1175 !match(Cmp->getOperand(0), m_Xor(m_Value(), m_Value())))
1176 return std::nullopt;
1177 }
1178
1179 // (icmp ne (lshr x, C), (lshr y, C)) gets optimized to:
1180 // (icmp ugt (xor x, y), (1 << C) - 1) so also look for that.
1181 else if (Pred == CmpInst::ICMP_NE &&
1182 Cmp->getPredicate() == CmpInst::ICMP_UGT) {
1183 if (!match(Cmp->getOperand(1), m_LowBitMask(C)) ||
1184 !match(Cmp->getOperand(0), m_Xor(m_Value(), m_Value())))
1185 return std::nullopt;
1186 } else {
1187 return std::nullopt;
1188 }
1189
1190 unsigned From = Pred == CmpInst::ICMP_NE ? C->popcount() : C->countr_zero();
1191 Instruction *I = cast<Instruction>(Cmp->getOperand(0));
1192 return {{I->getOperand(OpNo), From, C->getBitWidth() - From}};
1193 };
1194
1195 std::optional<IntPart> L0 = GetMatchPart(Cmp0, 0);
1196 std::optional<IntPart> R0 = GetMatchPart(Cmp0, 1);
1197 std::optional<IntPart> L1 = GetMatchPart(Cmp1, 0);
1198 std::optional<IntPart> R1 = GetMatchPart(Cmp1, 1);
1199 if (!L0 || !R0 || !L1 || !R1)
1200 return nullptr;
1201
1202 // Make sure the LHS/RHS compare a part of the same value, possibly after
1203 // an operand swap.
1204 if (L0->From != L1->From || R0->From != R1->From) {
1205 if (L0->From != R1->From || R0->From != L1->From)
1206 return nullptr;
1207 std::swap(L1, R1);
1208 }
1209
1210 // Make sure the extracted parts are adjacent, canonicalizing to L0/R0 being
1211 // the low part and L1/R1 being the high part.
1212 if (L0->StartBit + L0->NumBits != L1->StartBit ||
1213 R0->StartBit + R0->NumBits != R1->StartBit) {
1214 if (L1->StartBit + L1->NumBits != L0->StartBit ||
1215 R1->StartBit + R1->NumBits != R0->StartBit)
1216 return nullptr;
1217 std::swap(L0, L1);
1218 std::swap(R0, R1);
1219 }
1220
1221 // We can simplify to a comparison of these larger parts of the integers.
1222 IntPart L = {L0->From, L0->StartBit, L0->NumBits + L1->NumBits};
1223 IntPart R = {R0->From, R0->StartBit, R0->NumBits + R1->NumBits};
1226 return Builder.CreateICmp(Pred, LValue, RValue);
1227}
1228
1229/// Reduce logic-of-compares with equality to a constant by substituting a
1230/// common operand with the constant. Callers are expected to call this with
1231/// Cmp0/Cmp1 switched to handle logic op commutativity.
1233 bool IsAnd, bool IsLogical,
1234 InstCombiner::BuilderTy &Builder,
1235 const SimplifyQuery &Q) {
1236 // Match an equality compare with a non-poison constant as Cmp0.
1237 // Also, give up if the compare can be constant-folded to avoid looping.
1238 ICmpInst::Predicate Pred0;
1239 Value *X;
1240 Constant *C;
1241 if (!match(Cmp0, m_ICmp(Pred0, m_Value(X), m_Constant(C))) ||
1242 !isGuaranteedNotToBeUndefOrPoison(C) || isa<Constant>(X))
1243 return nullptr;
1244 if ((IsAnd && Pred0 != ICmpInst::ICMP_EQ) ||
1245 (!IsAnd && Pred0 != ICmpInst::ICMP_NE))
1246 return nullptr;
1247
1248 // The other compare must include a common operand (X). Canonicalize the
1249 // common operand as operand 1 (Pred1 is swapped if the common operand was
1250 // operand 0).
1251 Value *Y;
1252 ICmpInst::Predicate Pred1;
1253 if (!match(Cmp1, m_c_ICmp(Pred1, m_Value(Y), m_Specific(X))))
1254 return nullptr;
1255
1256 // Replace variable with constant value equivalence to remove a variable use:
1257 // (X == C) && (Y Pred1 X) --> (X == C) && (Y Pred1 C)
1258 // (X != C) || (Y Pred1 X) --> (X != C) || (Y Pred1 C)
1259 // Can think of the 'or' substitution with the 'and' bool equivalent:
1260 // A || B --> A || (!A && B)
1261 Value *SubstituteCmp = simplifyICmpInst(Pred1, Y, C, Q);
1262 if (!SubstituteCmp) {
1263 // If we need to create a new instruction, require that the old compare can
1264 // be removed.
1265 if (!Cmp1->hasOneUse())
1266 return nullptr;
1267 SubstituteCmp = Builder.CreateICmp(Pred1, Y, C);
1268 }
1269 if (IsLogical)
1270 return IsAnd ? Builder.CreateLogicalAnd(Cmp0, SubstituteCmp)
1271 : Builder.CreateLogicalOr(Cmp0, SubstituteCmp);
1272 return Builder.CreateBinOp(IsAnd ? Instruction::And : Instruction::Or, Cmp0,
1273 SubstituteCmp);
1274}
1275
1276/// Fold (icmp Pred1 V1, C1) & (icmp Pred2 V2, C2)
1277/// or (icmp Pred1 V1, C1) | (icmp Pred2 V2, C2)
1278/// into a single comparison using range-based reasoning.
1279/// NOTE: This is also used for logical and/or, must be poison-safe!
1280Value *InstCombinerImpl::foldAndOrOfICmpsUsingRanges(ICmpInst *ICmp1,
1281 ICmpInst *ICmp2,
1282 bool IsAnd) {
1283 ICmpInst::Predicate Pred1, Pred2;
1284 Value *V1, *V2;
1285 const APInt *C1, *C2;
1286 if (!match(ICmp1, m_ICmp(Pred1, m_Value(V1), m_APInt(C1))) ||
1287 !match(ICmp2, m_ICmp(Pred2, m_Value(V2), m_APInt(C2))))
1288 return nullptr;
1289
1290 // Look through add of a constant offset on V1, V2, or both operands. This
1291 // allows us to interpret the V + C' < C'' range idiom into a proper range.
1292 const APInt *Offset1 = nullptr, *Offset2 = nullptr;
1293 if (V1 != V2) {
1294 Value *X;
1295 if (match(V1, m_Add(m_Value(X), m_APInt(Offset1))))
1296 V1 = X;
1297 if (match(V2, m_Add(m_Value(X), m_APInt(Offset2))))
1298 V2 = X;
1299 }
1300
1301 if (V1 != V2)
1302 return nullptr;
1303
1305 IsAnd ? ICmpInst::getInversePredicate(Pred1) : Pred1, *C1);
1306 if (Offset1)
1307 CR1 = CR1.subtract(*Offset1);
1308
1310 IsAnd ? ICmpInst::getInversePredicate(Pred2) : Pred2, *C2);
1311 if (Offset2)
1312 CR2 = CR2.subtract(*Offset2);
1313
1314 Type *Ty = V1->getType();
1315 Value *NewV = V1;
1316 std::optional<ConstantRange> CR = CR1.exactUnionWith(CR2);
1317 if (!CR) {
1318 if (!(ICmp1->hasOneUse() && ICmp2->hasOneUse()) || CR1.isWrappedSet() ||
1319 CR2.isWrappedSet())
1320 return nullptr;
1321
1322 // Check whether we have equal-size ranges that only differ by one bit.
1323 // In that case we can apply a mask to map one range onto the other.
1324 APInt LowerDiff = CR1.getLower() ^ CR2.getLower();
1325 APInt UpperDiff = (CR1.getUpper() - 1) ^ (CR2.getUpper() - 1);
1326 APInt CR1Size = CR1.getUpper() - CR1.getLower();
1327 if (!LowerDiff.isPowerOf2() || LowerDiff != UpperDiff ||
1328 CR1Size != CR2.getUpper() - CR2.getLower())
1329 return nullptr;
1330
1331 CR = CR1.getLower().ult(CR2.getLower()) ? CR1 : CR2;
1332 NewV = Builder.CreateAnd(NewV, ConstantInt::get(Ty, ~LowerDiff));
1333 }
1334
1335 if (IsAnd)
1336 CR = CR->inverse();
1337
1338 CmpInst::Predicate NewPred;
1339 APInt NewC, Offset;
1340 CR->getEquivalentICmp(NewPred, NewC, Offset);
1341
1342 if (Offset != 0)
1343 NewV = Builder.CreateAdd(NewV, ConstantInt::get(Ty, Offset));
1344 return Builder.CreateICmp(NewPred, NewV, ConstantInt::get(Ty, NewC));
1345}
1346
1347/// Ignore all operations which only change the sign of a value, returning the
1348/// underlying magnitude value.
1350 match(Val, m_FNeg(m_Value(Val)));
1351 match(Val, m_FAbs(m_Value(Val)));
1352 match(Val, m_CopySign(m_Value(Val), m_Value()));
1353 return Val;
1354}
1355
1356/// Matches canonical form of isnan, fcmp ord x, 0
1358 return P == FCmpInst::FCMP_ORD && match(RHS, m_AnyZeroFP());
1359}
1360
1361/// Matches fcmp u__ x, +/-inf
1363 Value *RHS) {
1364 return FCmpInst::isUnordered(P) && match(RHS, m_Inf());
1365}
1366
1367/// and (fcmp ord x, 0), (fcmp u* x, inf) -> fcmp o* x, inf
1368///
1369/// Clang emits this pattern for doing an isfinite check in __builtin_isnormal.
1371 FCmpInst *RHS) {
1372 Value *LHS0 = LHS->getOperand(0), *LHS1 = LHS->getOperand(1);
1373 Value *RHS0 = RHS->getOperand(0), *RHS1 = RHS->getOperand(1);
1374 FCmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
1375
1376 if (!matchIsNotNaN(PredL, LHS0, LHS1) ||
1377 !matchUnorderedInfCompare(PredR, RHS0, RHS1))
1378 return nullptr;
1379
1380 IRBuilder<>::FastMathFlagGuard FMFG(Builder);
1381 FastMathFlags FMF = LHS->getFastMathFlags();
1382 FMF &= RHS->getFastMathFlags();
1383 Builder.setFastMathFlags(FMF);
1384
1385 return Builder.CreateFCmp(FCmpInst::getOrderedPredicate(PredR), RHS0, RHS1);
1386}
1387
1388Value *InstCombinerImpl::foldLogicOfFCmps(FCmpInst *LHS, FCmpInst *RHS,
1389 bool IsAnd, bool IsLogicalSelect) {
1390 Value *LHS0 = LHS->getOperand(0), *LHS1 = LHS->getOperand(1);
1391 Value *RHS0 = RHS->getOperand(0), *RHS1 = RHS->getOperand(1);
1392 FCmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
1393
1394 if (LHS0 == RHS1 && RHS0 == LHS1) {
1395 // Swap RHS operands to match LHS.
1396 PredR = FCmpInst::getSwappedPredicate(PredR);
1397 std::swap(RHS0, RHS1);
1398 }
1399
1400 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
1401 // Suppose the relation between x and y is R, where R is one of
1402 // U(1000), L(0100), G(0010) or E(0001), and CC0 and CC1 are the bitmasks for
1403 // testing the desired relations.
1404 //
1405 // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
1406 // bool(R & CC0) && bool(R & CC1)
1407 // = bool((R & CC0) & (R & CC1))
1408 // = bool(R & (CC0 & CC1)) <= by re-association, commutation, and idempotency
1409 //
1410 // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
1411 // bool(R & CC0) || bool(R & CC1)
1412 // = bool((R & CC0) | (R & CC1))
1413 // = bool(R & (CC0 | CC1)) <= by reversed distribution (contribution? ;)
1414 if (LHS0 == RHS0 && LHS1 == RHS1) {
1415 unsigned FCmpCodeL = getFCmpCode(PredL);
1416 unsigned FCmpCodeR = getFCmpCode(PredR);
1417 unsigned NewPred = IsAnd ? FCmpCodeL & FCmpCodeR : FCmpCodeL | FCmpCodeR;
1418
1419 // Intersect the fast math flags.
1420 // TODO: We can union the fast math flags unless this is a logical select.
1422 FastMathFlags FMF = LHS->getFastMathFlags();
1423 FMF &= RHS->getFastMathFlags();
1425
1426 return getFCmpValue(NewPred, LHS0, LHS1, Builder);
1427 }
1428
1429 // This transform is not valid for a logical select.
1430 if (!IsLogicalSelect &&
1431 ((PredL == FCmpInst::FCMP_ORD && PredR == FCmpInst::FCMP_ORD && IsAnd) ||
1432 (PredL == FCmpInst::FCMP_UNO && PredR == FCmpInst::FCMP_UNO &&
1433 !IsAnd))) {
1434 if (LHS0->getType() != RHS0->getType())
1435 return nullptr;
1436
1437 // FCmp canonicalization ensures that (fcmp ord/uno X, X) and
1438 // (fcmp ord/uno X, C) will be transformed to (fcmp X, +0.0).
1439 if (match(LHS1, m_PosZeroFP()) && match(RHS1, m_PosZeroFP()))
1440 // Ignore the constants because they are obviously not NANs:
1441 // (fcmp ord x, 0.0) & (fcmp ord y, 0.0) -> (fcmp ord x, y)
1442 // (fcmp uno x, 0.0) | (fcmp uno y, 0.0) -> (fcmp uno x, y)
1443 return Builder.CreateFCmp(PredL, LHS0, RHS0);
1444 }
1445
1446 if (IsAnd && stripSignOnlyFPOps(LHS0) == stripSignOnlyFPOps(RHS0)) {
1447 // and (fcmp ord x, 0), (fcmp u* x, inf) -> fcmp o* x, inf
1448 // and (fcmp ord x, 0), (fcmp u* fabs(x), inf) -> fcmp o* x, inf
1449 if (Value *Left = matchIsFiniteTest(Builder, LHS, RHS))
1450 return Left;
1451 if (Value *Right = matchIsFiniteTest(Builder, RHS, LHS))
1452 return Right;
1453 }
1454
1455 // Turn at least two fcmps with constants into llvm.is.fpclass.
1456 //
1457 // If we can represent a combined value test with one class call, we can
1458 // potentially eliminate 4-6 instructions. If we can represent a test with a
1459 // single fcmp with fneg and fabs, that's likely a better canonical form.
1460 if (LHS->hasOneUse() && RHS->hasOneUse()) {
1461 auto [ClassValRHS, ClassMaskRHS] =
1462 fcmpToClassTest(PredR, *RHS->getFunction(), RHS0, RHS1);
1463 if (ClassValRHS) {
1464 auto [ClassValLHS, ClassMaskLHS] =
1465 fcmpToClassTest(PredL, *LHS->getFunction(), LHS0, LHS1);
1466 if (ClassValLHS == ClassValRHS) {
1467 unsigned CombinedMask = IsAnd ? (ClassMaskLHS & ClassMaskRHS)
1468 : (ClassMaskLHS | ClassMaskRHS);
1469 return Builder.CreateIntrinsic(
1470 Intrinsic::is_fpclass, {ClassValLHS->getType()},
1471 {ClassValLHS, Builder.getInt32(CombinedMask)});
1472 }
1473 }
1474 }
1475
1476 // Canonicalize the range check idiom:
1477 // and (fcmp olt/ole/ult/ule x, C), (fcmp ogt/oge/ugt/uge x, -C)
1478 // --> fabs(x) olt/ole/ult/ule C
1479 // or (fcmp ogt/oge/ugt/uge x, C), (fcmp olt/ole/ult/ule x, -C)
1480 // --> fabs(x) ogt/oge/ugt/uge C
1481 // TODO: Generalize to handle a negated variable operand?
1482 const APFloat *LHSC, *RHSC;
1483 if (LHS0 == RHS0 && LHS->hasOneUse() && RHS->hasOneUse() &&
1484 FCmpInst::getSwappedPredicate(PredL) == PredR &&
1485 match(LHS1, m_APFloatAllowPoison(LHSC)) &&
1486 match(RHS1, m_APFloatAllowPoison(RHSC)) &&
1487 LHSC->bitwiseIsEqual(neg(*RHSC))) {
1488 auto IsLessThanOrLessEqual = [](FCmpInst::Predicate Pred) {
1489 switch (Pred) {
1490 case FCmpInst::FCMP_OLT:
1491 case FCmpInst::FCMP_OLE:
1492 case FCmpInst::FCMP_ULT:
1493 case FCmpInst::FCMP_ULE:
1494 return true;
1495 default:
1496 return false;
1497 }
1498 };
1499 if (IsLessThanOrLessEqual(IsAnd ? PredR : PredL)) {
1500 std::swap(LHSC, RHSC);
1501 std::swap(PredL, PredR);
1502 }
1503 if (IsLessThanOrLessEqual(IsAnd ? PredL : PredR)) {
1505 Builder.setFastMathFlags(LHS->getFastMathFlags() |
1506 RHS->getFastMathFlags());
1507
1508 Value *FAbs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, LHS0);
1509 return Builder.CreateFCmp(PredL, FAbs,
1510 ConstantFP::get(LHS0->getType(), *LHSC));
1511 }
1512 }
1513
1514 return nullptr;
1515}
1516
1517/// Match an fcmp against a special value that performs a test possible by
1518/// llvm.is.fpclass.
1519static bool matchIsFPClassLikeFCmp(Value *Op, Value *&ClassVal,
1520 uint64_t &ClassMask) {
1521 auto *FCmp = dyn_cast<FCmpInst>(Op);
1522 if (!FCmp || !FCmp->hasOneUse())
1523 return false;
1524
1525 std::tie(ClassVal, ClassMask) =
1526 fcmpToClassTest(FCmp->getPredicate(), *FCmp->getParent()->getParent(),
1527 FCmp->getOperand(0), FCmp->getOperand(1));
1528 return ClassVal != nullptr;
1529}
1530
1531/// or (is_fpclass x, mask0), (is_fpclass x, mask1)
1532/// -> is_fpclass x, (mask0 | mask1)
1533/// and (is_fpclass x, mask0), (is_fpclass x, mask1)
1534/// -> is_fpclass x, (mask0 & mask1)
1535/// xor (is_fpclass x, mask0), (is_fpclass x, mask1)
1536/// -> is_fpclass x, (mask0 ^ mask1)
1537Instruction *InstCombinerImpl::foldLogicOfIsFPClass(BinaryOperator &BO,
1538 Value *Op0, Value *Op1) {
1539 Value *ClassVal0 = nullptr;
1540 Value *ClassVal1 = nullptr;
1541 uint64_t ClassMask0, ClassMask1;
1542
1543 // Restrict to folding one fcmp into one is.fpclass for now, don't introduce a
1544 // new class.
1545 //
1546 // TODO: Support forming is.fpclass out of 2 separate fcmps when codegen is
1547 // better.
1548
1549 bool IsLHSClass =
1550 match(Op0, m_OneUse(m_Intrinsic<Intrinsic::is_fpclass>(
1551 m_Value(ClassVal0), m_ConstantInt(ClassMask0))));
1552 bool IsRHSClass =
1553 match(Op1, m_OneUse(m_Intrinsic<Intrinsic::is_fpclass>(
1554 m_Value(ClassVal1), m_ConstantInt(ClassMask1))));
1555 if ((((IsLHSClass || matchIsFPClassLikeFCmp(Op0, ClassVal0, ClassMask0)) &&
1556 (IsRHSClass || matchIsFPClassLikeFCmp(Op1, ClassVal1, ClassMask1)))) &&
1557 ClassVal0 == ClassVal1) {
1558 unsigned NewClassMask;
1559 switch (BO.getOpcode()) {
1560 case Instruction::And:
1561 NewClassMask = ClassMask0 & ClassMask1;
1562 break;
1563 case Instruction::Or:
1564 NewClassMask = ClassMask0 | ClassMask1;
1565 break;
1566 case Instruction::Xor:
1567 NewClassMask = ClassMask0 ^ ClassMask1;
1568 break;
1569 default:
1570 llvm_unreachable("not a binary logic operator");
1571 }
1572
1573 if (IsLHSClass) {
1574 auto *II = cast<IntrinsicInst>(Op0);
1575 II->setArgOperand(
1576 1, ConstantInt::get(II->getArgOperand(1)->getType(), NewClassMask));
1577 return replaceInstUsesWith(BO, II);
1578 }
1579
1580 if (IsRHSClass) {
1581 auto *II = cast<IntrinsicInst>(Op1);
1582 II->setArgOperand(
1583 1, ConstantInt::get(II->getArgOperand(1)->getType(), NewClassMask));
1584 return replaceInstUsesWith(BO, II);
1585 }
1586
1587 CallInst *NewClass =
1588 Builder.CreateIntrinsic(Intrinsic::is_fpclass, {ClassVal0->getType()},
1589 {ClassVal0, Builder.getInt32(NewClassMask)});
1590 return replaceInstUsesWith(BO, NewClass);
1591 }
1592
1593 return nullptr;
1594}
1595
1596/// Look for the pattern that conditionally negates a value via math operations:
1597/// cond.splat = sext i1 cond
1598/// sub = add cond.splat, x
1599/// xor = xor sub, cond.splat
1600/// and rewrite it to do the same, but via logical operations:
1601/// value.neg = sub 0, value
1602/// cond = select i1 neg, value.neg, value
1603Instruction *InstCombinerImpl::canonicalizeConditionalNegationViaMathToSelect(
1604 BinaryOperator &I) {
1605 assert(I.getOpcode() == BinaryOperator::Xor && "Only for xor!");
1606 Value *Cond, *X;
1607 // As per complexity ordering, `xor` is not commutative here.
1608 if (!match(&I, m_c_BinOp(m_OneUse(m_Value()), m_Value())) ||
1609 !match(I.getOperand(1), m_SExt(m_Value(Cond))) ||
1610 !Cond->getType()->isIntOrIntVectorTy(1) ||
1611 !match(I.getOperand(0), m_c_Add(m_SExt(m_Specific(Cond)), m_Value(X))))
1612 return nullptr;
1613 return SelectInst::Create(Cond, Builder.CreateNeg(X, X->getName() + ".neg"),
1614 X);
1615}
1616
1617/// This a limited reassociation for a special case (see above) where we are
1618/// checking if two values are either both NAN (unordered) or not-NAN (ordered).
1619/// This could be handled more generally in '-reassociation', but it seems like
1620/// an unlikely pattern for a large number of logic ops and fcmps.
1622 InstCombiner::BuilderTy &Builder) {
1623 Instruction::BinaryOps Opcode = BO.getOpcode();
1624 assert((Opcode == Instruction::And || Opcode == Instruction::Or) &&
1625 "Expecting and/or op for fcmp transform");
1626
1627 // There are 4 commuted variants of the pattern. Canonicalize operands of this
1628 // logic op so an fcmp is operand 0 and a matching logic op is operand 1.
1629 Value *Op0 = BO.getOperand(0), *Op1 = BO.getOperand(1), *X;
1630 if (match(Op1, m_FCmp(m_Value(), m_AnyZeroFP())))
1631 std::swap(Op0, Op1);
1632
1633 // Match inner binop and the predicate for combining 2 NAN checks into 1.
1634 Value *BO10, *BO11;
1635 FCmpInst::Predicate NanPred = Opcode == Instruction::And ? FCmpInst::FCMP_ORD
1637 if (!match(Op0, m_SpecificFCmp(NanPred, m_Value(X), m_AnyZeroFP())) ||
1638 !match(Op1, m_BinOp(Opcode, m_Value(BO10), m_Value(BO11))))
1639 return nullptr;
1640
1641 // The inner logic op must have a matching fcmp operand.
1642 Value *Y;
1643 if (!match(BO10, m_SpecificFCmp(NanPred, m_Value(Y), m_AnyZeroFP())) ||
1644 X->getType() != Y->getType())
1645 std::swap(BO10, BO11);
1646
1647 if (!match(BO10, m_SpecificFCmp(NanPred, m_Value(Y), m_AnyZeroFP())) ||
1648 X->getType() != Y->getType())
1649 return nullptr;
1650
1651 // and (fcmp ord X, 0), (and (fcmp ord Y, 0), Z) --> and (fcmp ord X, Y), Z
1652 // or (fcmp uno X, 0), (or (fcmp uno Y, 0), Z) --> or (fcmp uno X, Y), Z
1653 Value *NewFCmp = Builder.CreateFCmp(NanPred, X, Y);
1654 if (auto *NewFCmpInst = dyn_cast<FCmpInst>(NewFCmp)) {
1655 // Intersect FMF from the 2 source fcmps.
1656 NewFCmpInst->copyIRFlags(Op0);
1657 NewFCmpInst->andIRFlags(BO10);
1658 }
1659 return BinaryOperator::Create(Opcode, NewFCmp, BO11);
1660}
1661
1662/// Match variations of De Morgan's Laws:
1663/// (~A & ~B) == (~(A | B))
1664/// (~A | ~B) == (~(A & B))
1666 InstCombiner &IC) {
1667 const Instruction::BinaryOps Opcode = I.getOpcode();
1668 assert((Opcode == Instruction::And || Opcode == Instruction::Or) &&
1669 "Trying to match De Morgan's Laws with something other than and/or");
1670
1671 // Flip the logic operation.
1672 const Instruction::BinaryOps FlippedOpcode =
1673 (Opcode == Instruction::And) ? Instruction::Or : Instruction::And;
1674
1675 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1676 Value *A, *B;
1677 if (match(Op0, m_OneUse(m_Not(m_Value(A)))) &&
1678 match(Op1, m_OneUse(m_Not(m_Value(B)))) &&
1679 !IC.isFreeToInvert(A, A->hasOneUse()) &&
1680 !IC.isFreeToInvert(B, B->hasOneUse())) {
1681 Value *AndOr =
1682 IC.Builder.CreateBinOp(FlippedOpcode, A, B, I.getName() + ".demorgan");
1683 return BinaryOperator::CreateNot(AndOr);
1684 }
1685
1686 // The 'not' ops may require reassociation.
1687 // (A & ~B) & ~C --> A & ~(B | C)
1688 // (~B & A) & ~C --> A & ~(B | C)
1689 // (A | ~B) | ~C --> A | ~(B & C)
1690 // (~B | A) | ~C --> A | ~(B & C)
1691 Value *C;
1692 if (match(Op0, m_OneUse(m_c_BinOp(Opcode, m_Value(A), m_Not(m_Value(B))))) &&
1693 match(Op1, m_Not(m_Value(C)))) {
1694 Value *FlippedBO = IC.Builder.CreateBinOp(FlippedOpcode, B, C);
1695 return BinaryOperator::Create(Opcode, A, IC.Builder.CreateNot(FlippedBO));
1696 }
1697
1698 return nullptr;
1699}
1700
1701bool InstCombinerImpl::shouldOptimizeCast(CastInst *CI) {
1702 Value *CastSrc = CI->getOperand(0);
1703
1704 // Noop casts and casts of constants should be eliminated trivially.
1705 if (CI->getSrcTy() == CI->getDestTy() || isa<Constant>(CastSrc))
1706 return false;
1707
1708 // If this cast is paired with another cast that can be eliminated, we prefer
1709 // to have it eliminated.
1710 if (const auto *PrecedingCI = dyn_cast<CastInst>(CastSrc))
1711 if (isEliminableCastPair(PrecedingCI, CI))
1712 return false;
1713
1714 return true;
1715}
1716
1717/// Fold {and,or,xor} (cast X), C.
1719 InstCombinerImpl &IC) {
1720 Constant *C = dyn_cast<Constant>(Logic.getOperand(1));
1721 if (!C)
1722 return nullptr;
1723
1724 auto LogicOpc = Logic.getOpcode();
1725 Type *DestTy = Logic.getType();
1726 Type *SrcTy = Cast->getSrcTy();
1727
1728 // Move the logic operation ahead of a zext or sext if the constant is
1729 // unchanged in the smaller source type. Performing the logic in a smaller
1730 // type may provide more information to later folds, and the smaller logic
1731 // instruction may be cheaper (particularly in the case of vectors).
1732 Value *X;
1733 if (match(Cast, m_OneUse(m_ZExt(m_Value(X))))) {
1734 if (Constant *TruncC = IC.getLosslessUnsignedTrunc(C, SrcTy)) {
1735 // LogicOpc (zext X), C --> zext (LogicOpc X, C)
1736 Value *NewOp = IC.Builder.CreateBinOp(LogicOpc, X, TruncC);
1737 return new ZExtInst(NewOp, DestTy);
1738 }
1739 }
1740
1741 if (match(Cast, m_OneUse(m_SExtLike(m_Value(X))))) {
1742 if (Constant *TruncC = IC.getLosslessSignedTrunc(C, SrcTy)) {
1743 // LogicOpc (sext X), C --> sext (LogicOpc X, C)
1744 Value *NewOp = IC.Builder.CreateBinOp(LogicOpc, X, TruncC);
1745 return new SExtInst(NewOp, DestTy);
1746 }
1747 }
1748
1749 return nullptr;
1750}
1751
1752/// Fold {and,or,xor} (cast X), Y.
1753Instruction *InstCombinerImpl::foldCastedBitwiseLogic(BinaryOperator &I) {
1754 auto LogicOpc = I.getOpcode();
1755 assert(I.isBitwiseLogicOp() && "Unexpected opcode for bitwise logic folding");
1756
1757 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1758
1759 // fold bitwise(A >> BW - 1, zext(icmp)) (BW is the scalar bits of the
1760 // type of A)
1761 // -> bitwise(zext(A < 0), zext(icmp))
1762 // -> zext(bitwise(A < 0, icmp))
1763 auto FoldBitwiseICmpZeroWithICmp = [&](Value *Op0,
1764 Value *Op1) -> Instruction * {
1765 Value *A;
1766 bool IsMatched =
1767 match(Op0,
1769 m_Value(A),
1770 m_SpecificInt(Op0->getType()->getScalarSizeInBits() - 1)))) &&
1771 match(Op1, m_OneUse(m_ZExt(m_ICmp(m_Value(), m_Value()))));
1772
1773 if (!IsMatched)
1774 return nullptr;
1775
1776 auto *ICmpL =
1778 auto *ICmpR = cast<ZExtInst>(Op1)->getOperand(0);
1779 auto *BitwiseOp = Builder.CreateBinOp(LogicOpc, ICmpL, ICmpR);
1780
1781 return new ZExtInst(BitwiseOp, Op0->getType());
1782 };
1783
1784 if (auto *Ret = FoldBitwiseICmpZeroWithICmp(Op0, Op1))
1785 return Ret;
1786
1787 if (auto *Ret = FoldBitwiseICmpZeroWithICmp(Op1, Op0))
1788 return Ret;
1789
1790 CastInst *Cast0 = dyn_cast<CastInst>(Op0);
1791 if (!Cast0)
1792 return nullptr;
1793
1794 // This must be a cast from an integer or integer vector source type to allow
1795 // transformation of the logic operation to the source type.
1796 Type *DestTy = I.getType();
1797 Type *SrcTy = Cast0->getSrcTy();
1798 if (!SrcTy->isIntOrIntVectorTy())
1799 return nullptr;
1800
1801 if (Instruction *Ret = foldLogicCastConstant(I, Cast0, *this))
1802 return Ret;
1803
1804 CastInst *Cast1 = dyn_cast<CastInst>(Op1);
1805 if (!Cast1)
1806 return nullptr;
1807
1808 // Both operands of the logic operation are casts. The casts must be the
1809 // same kind for reduction.
1810 Instruction::CastOps CastOpcode = Cast0->getOpcode();
1811 if (CastOpcode != Cast1->getOpcode())
1812 return nullptr;
1813
1814 // If the source types do not match, but the casts are matching extends, we
1815 // can still narrow the logic op.
1816 if (SrcTy != Cast1->getSrcTy()) {
1817 Value *X, *Y;
1818 if (match(Cast0, m_OneUse(m_ZExtOrSExt(m_Value(X)))) &&
1819 match(Cast1, m_OneUse(m_ZExtOrSExt(m_Value(Y))))) {
1820 // Cast the narrower source to the wider source type.
1821 unsigned XNumBits = X->getType()->getScalarSizeInBits();
1822 unsigned YNumBits = Y->getType()->getScalarSizeInBits();
1823 if (XNumBits < YNumBits)
1824 X = Builder.CreateCast(CastOpcode, X, Y->getType());
1825 else
1826 Y = Builder.CreateCast(CastOpcode, Y, X->getType());
1827 // Do the logic op in the intermediate width, then widen more.
1828 Value *NarrowLogic = Builder.CreateBinOp(LogicOpc, X, Y);
1829 return CastInst::Create(CastOpcode, NarrowLogic, DestTy);
1830 }
1831
1832 // Give up for other cast opcodes.
1833 return nullptr;
1834 }
1835
1836 Value *Cast0Src = Cast0->getOperand(0);
1837 Value *Cast1Src = Cast1->getOperand(0);
1838
1839 // fold logic(cast(A), cast(B)) -> cast(logic(A, B))
1840 if ((Cast0->hasOneUse() || Cast1->hasOneUse()) &&
1841 shouldOptimizeCast(Cast0) && shouldOptimizeCast(Cast1)) {
1842 Value *NewOp = Builder.CreateBinOp(LogicOpc, Cast0Src, Cast1Src,
1843 I.getName());
1844 return CastInst::Create(CastOpcode, NewOp, DestTy);
1845 }
1846
1847 return nullptr;
1848}
1849
1851 InstCombiner::BuilderTy &Builder) {
1852 assert(I.getOpcode() == Instruction::And);
1853 Value *Op0 = I.getOperand(0);
1854 Value *Op1 = I.getOperand(1);
1855 Value *A, *B;
1856
1857 // Operand complexity canonicalization guarantees that the 'or' is Op0.
1858 // (A | B) & ~(A & B) --> A ^ B
1859 // (A | B) & ~(B & A) --> A ^ B
1860 if (match(&I, m_BinOp(m_Or(m_Value(A), m_Value(B)),
1862 return BinaryOperator::CreateXor(A, B);
1863
1864 // (A | ~B) & (~A | B) --> ~(A ^ B)
1865 // (A | ~B) & (B | ~A) --> ~(A ^ B)
1866 // (~B | A) & (~A | B) --> ~(A ^ B)
1867 // (~B | A) & (B | ~A) --> ~(A ^ B)
1868 if (Op0->hasOneUse() || Op1->hasOneUse())
1871 return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
1872
1873 return nullptr;
1874}
1875
1877 InstCombiner::BuilderTy &Builder) {
1878 assert(I.getOpcode() == Instruction::Or);
1879 Value *Op0 = I.getOperand(0);
1880 Value *Op1 = I.getOperand(1);
1881 Value *A, *B;
1882
1883 // Operand complexity canonicalization guarantees that the 'and' is Op0.
1884 // (A & B) | ~(A | B) --> ~(A ^ B)
1885 // (A & B) | ~(B | A) --> ~(A ^ B)
1886 if (Op0->hasOneUse() || Op1->hasOneUse())
1887 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
1889 return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
1890
1891 // Operand complexity canonicalization guarantees that the 'xor' is Op0.
1892 // (A ^ B) | ~(A | B) --> ~(A & B)
1893 // (A ^ B) | ~(B | A) --> ~(A & B)
1894 if (Op0->hasOneUse() || Op1->hasOneUse())
1895 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
1897 return BinaryOperator::CreateNot(Builder.CreateAnd(A, B));
1898
1899 // (A & ~B) | (~A & B) --> A ^ B
1900 // (A & ~B) | (B & ~A) --> A ^ B
1901 // (~B & A) | (~A & B) --> A ^ B
1902 // (~B & A) | (B & ~A) --> A ^ B
1903 if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
1905 return BinaryOperator::CreateXor(A, B);
1906
1907 return nullptr;
1908}
1909
1910/// Return true if a constant shift amount is always less than the specified
1911/// bit-width. If not, the shift could create poison in the narrower type.
1912static bool canNarrowShiftAmt(Constant *C, unsigned BitWidth) {
1913 APInt Threshold(C->getType()->getScalarSizeInBits(), BitWidth);
1914 return match(C, m_SpecificInt_ICMP(ICmpInst::ICMP_ULT, Threshold));
1915}
1916
1917/// Try to use narrower ops (sink zext ops) for an 'and' with binop operand and
1918/// a common zext operand: and (binop (zext X), C), (zext X).
1919Instruction *InstCombinerImpl::narrowMaskedBinOp(BinaryOperator &And) {
1920 // This transform could also apply to {or, and, xor}, but there are better
1921 // folds for those cases, so we don't expect those patterns here. AShr is not
1922 // handled because it should always be transformed to LShr in this sequence.
1923 // The subtract transform is different because it has a constant on the left.
1924 // Add/mul commute the constant to RHS; sub with constant RHS becomes add.
1925 Value *Op0 = And.getOperand(0), *Op1 = And.getOperand(1);
1926 Constant *C;
1927 if (!match(Op0, m_OneUse(m_Add(m_Specific(Op1), m_Constant(C)))) &&
1928 !match(Op0, m_OneUse(m_Mul(m_Specific(Op1), m_Constant(C)))) &&
1929 !match(Op0, m_OneUse(m_LShr(m_Specific(Op1), m_Constant(C)))) &&
1930 !match(Op0, m_OneUse(m_Shl(m_Specific(Op1), m_Constant(C)))) &&
1931 !match(Op0, m_OneUse(m_Sub(m_Constant(C), m_Specific(Op1)))))
1932 return nullptr;
1933
1934 Value *X;
1935 if (!match(Op1, m_ZExt(m_Value(X))) || Op1->hasNUsesOrMore(3))
1936 return nullptr;
1937
1938 Type *Ty = And.getType();
1939 if (!isa<VectorType>(Ty) && !shouldChangeType(Ty, X->getType()))
1940 return nullptr;
1941
1942 // If we're narrowing a shift, the shift amount must be safe (less than the
1943 // width) in the narrower type. If the shift amount is greater, instsimplify
1944 // usually handles that case, but we can't guarantee/assert it.
1945 Instruction::BinaryOps Opc = cast<BinaryOperator>(Op0)->getOpcode();
1946 if (Opc == Instruction::LShr || Opc == Instruction::Shl)
1947 if (!canNarrowShiftAmt(C, X->getType()->getScalarSizeInBits()))
1948 return nullptr;
1949
1950 // and (sub C, (zext X)), (zext X) --> zext (and (sub C', X), X)
1951 // and (binop (zext X), C), (zext X) --> zext (and (binop X, C'), X)
1952 Value *NewC = ConstantExpr::getTrunc(C, X->getType());
1953 Value *NewBO = Opc == Instruction::Sub ? Builder.CreateBinOp(Opc, NewC, X)
1954 : Builder.CreateBinOp(Opc, X, NewC);
1955 return new ZExtInst(Builder.CreateAnd(NewBO, X), Ty);
1956}
1957
1958/// Try folding relatively complex patterns for both And and Or operations
1959/// with all And and Or swapped.
1961 InstCombiner::BuilderTy &Builder) {
1962 const Instruction::BinaryOps Opcode = I.getOpcode();
1963 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1964
1965 // Flip the logic operation.
1966 const Instruction::BinaryOps FlippedOpcode =
1967 (Opcode == Instruction::And) ? Instruction::Or : Instruction::And;
1968
1969 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1970 Value *A, *B, *C, *X, *Y, *Dummy;
1971
1972 // Match following expressions:
1973 // (~(A | B) & C)
1974 // (~(A & B) | C)
1975 // Captures X = ~(A | B) or ~(A & B)
1976 const auto matchNotOrAnd =
1977 [Opcode, FlippedOpcode](Value *Op, auto m_A, auto m_B, auto m_C,
1978 Value *&X, bool CountUses = false) -> bool {
1979 if (CountUses && !Op->hasOneUse())
1980 return false;
1981
1982 if (match(Op, m_c_BinOp(FlippedOpcode,
1984 m_Not(m_c_BinOp(Opcode, m_A, m_B))),
1985 m_C)))
1986 return !CountUses || X->hasOneUse();
1987
1988 return false;
1989 };
1990
1991 // (~(A | B) & C) | ... --> ...
1992 // (~(A & B) | C) & ... --> ...
1993 // TODO: One use checks are conservative. We just need to check that a total
1994 // number of multiple used values does not exceed reduction
1995 // in operations.
1996 if (matchNotOrAnd(Op0, m_Value(A), m_Value(B), m_Value(C), X)) {
1997 // (~(A | B) & C) | (~(A | C) & B) --> (B ^ C) & ~A
1998 // (~(A & B) | C) & (~(A & C) | B) --> ~((B ^ C) & A)
1999 if (matchNotOrAnd(Op1, m_Specific(A), m_Specific(C), m_Specific(B), Dummy,
2000 true)) {
2001 Value *Xor = Builder.CreateXor(B, C);
2002 return (Opcode == Instruction::Or)
2003 ? BinaryOperator::CreateAnd(Xor, Builder.CreateNot(A))
2005 }
2006
2007 // (~(A | B) & C) | (~(B | C) & A) --> (A ^ C) & ~B
2008 // (~(A & B) | C) & (~(B & C) | A) --> ~((A ^ C) & B)
2009 if (matchNotOrAnd(Op1, m_Specific(B), m_Specific(C), m_Specific(A), Dummy,
2010 true)) {
2011 Value *Xor = Builder.CreateXor(A, C);
2012 return (Opcode == Instruction::Or)
2013 ? BinaryOperator::CreateAnd(Xor, Builder.CreateNot(B))
2015 }
2016
2017 // (~(A | B) & C) | ~(A | C) --> ~((B & C) | A)
2018 // (~(A & B) | C) & ~(A & C) --> ~((B | C) & A)
2019 if (match(Op1, m_OneUse(m_Not(m_OneUse(
2020 m_c_BinOp(Opcode, m_Specific(A), m_Specific(C)))))))
2022 Opcode, Builder.CreateBinOp(FlippedOpcode, B, C), A));
2023
2024 // (~(A | B) & C) | ~(B | C) --> ~((A & C) | B)
2025 // (~(A & B) | C) & ~(B & C) --> ~((A | C) & B)
2026 if (match(Op1, m_OneUse(m_Not(m_OneUse(
2027 m_c_BinOp(Opcode, m_Specific(B), m_Specific(C)))))))
2029 Opcode, Builder.CreateBinOp(FlippedOpcode, A, C), B));
2030
2031 // (~(A | B) & C) | ~(C | (A ^ B)) --> ~((A | B) & (C | (A ^ B)))
2032 // Note, the pattern with swapped and/or is not handled because the
2033 // result is more undefined than a source:
2034 // (~(A & B) | C) & ~(C & (A ^ B)) --> (A ^ B ^ C) | ~(A | C) is invalid.
2035 if (Opcode == Instruction::Or && Op0->hasOneUse() &&
2037 m_Value(Y),
2038 m_c_BinOp(Opcode, m_Specific(C),
2039 m_c_Xor(m_Specific(A), m_Specific(B)))))))) {
2040 // X = ~(A | B)
2041 // Y = (C | (A ^ B)
2042 Value *Or = cast<BinaryOperator>(X)->getOperand(0);
2043 return BinaryOperator::CreateNot(Builder.CreateAnd(Or, Y));
2044 }
2045 }
2046
2047 // (~A & B & C) | ... --> ...
2048 // (~A | B | C) | ... --> ...
2049 // TODO: One use checks are conservative. We just need to check that a total
2050 // number of multiple used values does not exceed reduction
2051 // in operations.
2052 if (match(Op0,
2053 m_OneUse(m_c_BinOp(FlippedOpcode,
2054 m_BinOp(FlippedOpcode, m_Value(B), m_Value(C)),
2055 m_CombineAnd(m_Value(X), m_Not(m_Value(A)))))) ||
2057 FlippedOpcode,
2058 m_c_BinOp(FlippedOpcode, m_Value(C),
2060 m_Value(B))))) {
2061 // X = ~A
2062 // (~A & B & C) | ~(A | B | C) --> ~(A | (B ^ C))
2063 // (~A | B | C) & ~(A & B & C) --> (~A | (B ^ C))
2064 if (match(Op1, m_OneUse(m_Not(m_c_BinOp(
2065 Opcode, m_c_BinOp(Opcode, m_Specific(A), m_Specific(B)),
2066 m_Specific(C))))) ||
2068 Opcode, m_c_BinOp(Opcode, m_Specific(B), m_Specific(C)),
2069 m_Specific(A))))) ||
2071 Opcode, m_c_BinOp(Opcode, m_Specific(A), m_Specific(C)),
2072 m_Specific(B)))))) {
2073 Value *Xor = Builder.CreateXor(B, C);
2074 return (Opcode == Instruction::Or)
2076 : BinaryOperator::CreateOr(Xor, X);
2077 }
2078
2079 // (~A & B & C) | ~(A | B) --> (C | ~B) & ~A
2080 // (~A | B | C) & ~(A & B) --> (C & ~B) | ~A
2081 if (match(Op1, m_OneUse(m_Not(m_OneUse(
2082 m_c_BinOp(Opcode, m_Specific(A), m_Specific(B)))))))
2084 FlippedOpcode, Builder.CreateBinOp(Opcode, C, Builder.CreateNot(B)),
2085 X);
2086
2087 // (~A & B & C) | ~(A | C) --> (B | ~C) & ~A
2088 // (~A | B | C) & ~(A & C) --> (B & ~C) | ~A
2089 if (match(Op1, m_OneUse(m_Not(m_OneUse(
2090 m_c_BinOp(Opcode, m_Specific(A), m_Specific(C)))))))
2092 FlippedOpcode, Builder.CreateBinOp(Opcode, B, Builder.CreateNot(C)),
2093 X);
2094 }
2095
2096 return nullptr;
2097}
2098
2099/// Try to reassociate a pair of binops so that values with one use only are
2100/// part of the same instruction. This may enable folds that are limited with
2101/// multi-use restrictions and makes it more likely to match other patterns that
2102/// are looking for a common operand.
2104 InstCombinerImpl::BuilderTy &Builder) {
2105 Instruction::BinaryOps Opcode = BO.getOpcode();
2106 Value *X, *Y, *Z;
2107 if (match(&BO,
2108 m_c_BinOp(Opcode, m_OneUse(m_BinOp(Opcode, m_Value(X), m_Value(Y))),
2109 m_OneUse(m_Value(Z))))) {
2110 if (!isa<Constant>(X) && !isa<Constant>(Y) && !isa<Constant>(Z)) {
2111 // (X op Y) op Z --> (Y op Z) op X
2112 if (!X->hasOneUse()) {
2113 Value *YZ = Builder.CreateBinOp(Opcode, Y, Z);
2114 return BinaryOperator::Create(Opcode, YZ, X);
2115 }
2116 // (X op Y) op Z --> (X op Z) op Y
2117 if (!Y->hasOneUse()) {
2118 Value *XZ = Builder.CreateBinOp(Opcode, X, Z);
2119 return BinaryOperator::Create(Opcode, XZ, Y);
2120 }
2121 }
2122 }
2123
2124 return nullptr;
2125}
2126
2127// Match
2128// (X + C2) | C
2129// (X + C2) ^ C
2130// (X + C2) & C
2131// and convert to do the bitwise logic first:
2132// (X | C) + C2
2133// (X ^ C) + C2
2134// (X & C) + C2
2135// iff bits affected by logic op are lower than last bit affected by math op
2137 InstCombiner::BuilderTy &Builder) {
2138 Type *Ty = I.getType();
2139 Instruction::BinaryOps OpC = I.getOpcode();
2140 Value *Op0 = I.getOperand(0);
2141 Value *Op1 = I.getOperand(1);
2142 Value *X;
2143 const APInt *C, *C2;
2144
2145 if (!(match(Op0, m_OneUse(m_Add(m_Value(X), m_APInt(C2)))) &&
2146 match(Op1, m_APInt(C))))
2147 return nullptr;
2148
2149 unsigned Width = Ty->getScalarSizeInBits();
2150 unsigned LastOneMath = Width - C2->countr_zero();
2151
2152 switch (OpC) {
2153 case Instruction::And:
2154 if (C->countl_one() < LastOneMath)
2155 return nullptr;
2156 break;
2157 case Instruction::Xor:
2158 case Instruction::Or:
2159 if (C->countl_zero() < LastOneMath)
2160 return nullptr;
2161 break;
2162 default:
2163 llvm_unreachable("Unexpected BinaryOp!");
2164 }
2165
2166 Value *NewBinOp = Builder.CreateBinOp(OpC, X, ConstantInt::get(Ty, *C));
2167 return BinaryOperator::CreateWithCopiedFlags(Instruction::Add, NewBinOp,
2168 ConstantInt::get(Ty, *C2), Op0);
2169}
2170
2171// binop(shift(ShiftedC1, ShAmt), shift(ShiftedC2, add(ShAmt, AddC))) ->
2172// shift(binop(ShiftedC1, shift(ShiftedC2, AddC)), ShAmt)
2173// where both shifts are the same and AddC is a valid shift amount.
2174Instruction *InstCombinerImpl::foldBinOpOfDisplacedShifts(BinaryOperator &I) {
2175 assert((I.isBitwiseLogicOp() || I.getOpcode() == Instruction::Add) &&
2176 "Unexpected opcode");
2177
2178 Value *ShAmt;
2179 Constant *ShiftedC1, *ShiftedC2, *AddC;
2180 Type *Ty = I.getType();
2181 unsigned BitWidth = Ty->getScalarSizeInBits();
2182 if (!match(&I, m_c_BinOp(m_Shift(m_ImmConstant(ShiftedC1), m_Value(ShAmt)),
2183 m_Shift(m_ImmConstant(ShiftedC2),
2184 m_AddLike(m_Deferred(ShAmt),
2185 m_ImmConstant(AddC))))))
2186 return nullptr;
2187
2188 // Make sure the add constant is a valid shift amount.
2189 if (!match(AddC,
2191 return nullptr;
2192
2193 // Avoid constant expressions.
2194 auto *Op0Inst = dyn_cast<Instruction>(I.getOperand(0));
2195 auto *Op1Inst = dyn_cast<Instruction>(I.getOperand(1));
2196 if (!Op0Inst || !Op1Inst)
2197 return nullptr;
2198
2199 // Both shifts must be the same.
2200 Instruction::BinaryOps ShiftOp =
2201 static_cast<Instruction::BinaryOps>(Op0Inst->getOpcode());
2202 if (ShiftOp != Op1Inst->getOpcode())
2203 return nullptr;
2204
2205 // For adds, only left shifts are supported.
2206 if (I.getOpcode() == Instruction::Add && ShiftOp != Instruction::Shl)
2207 return nullptr;
2208
2209 Value *NewC = Builder.CreateBinOp(
2210 I.getOpcode(), ShiftedC1, Builder.CreateBinOp(ShiftOp, ShiftedC2, AddC));
2211 return BinaryOperator::Create(ShiftOp, NewC, ShAmt);
2212}
2213
2214// Fold and/or/xor with two equal intrinsic IDs:
2215// bitwise(fshl (A, B, ShAmt), fshl(C, D, ShAmt))
2216// -> fshl(bitwise(A, C), bitwise(B, D), ShAmt)
2217// bitwise(fshr (A, B, ShAmt), fshr(C, D, ShAmt))
2218// -> fshr(bitwise(A, C), bitwise(B, D), ShAmt)
2219// bitwise(bswap(A), bswap(B)) -> bswap(bitwise(A, B))
2220// bitwise(bswap(A), C) -> bswap(bitwise(A, bswap(C)))
2221// bitwise(bitreverse(A), bitreverse(B)) -> bitreverse(bitwise(A, B))
2222// bitwise(bitreverse(A), C) -> bitreverse(bitwise(A, bitreverse(C)))
2223static Instruction *
2225 InstCombiner::BuilderTy &Builder) {
2226 assert(I.isBitwiseLogicOp() && "Should and/or/xor");
2227 if (!I.getOperand(0)->hasOneUse())
2228 return nullptr;
2229 IntrinsicInst *X = dyn_cast<IntrinsicInst>(I.getOperand(0));
2230 if (!X)
2231 return nullptr;
2232
2233 IntrinsicInst *Y = dyn_cast<IntrinsicInst>(I.getOperand(1));
2234 if (Y && (!Y->hasOneUse() || X->getIntrinsicID() != Y->getIntrinsicID()))
2235 return nullptr;
2236
2237 Intrinsic::ID IID = X->getIntrinsicID();
2238 const APInt *RHSC;
2239 // Try to match constant RHS.
2240 if (!Y && (!(IID == Intrinsic::bswap || IID == Intrinsic::bitreverse) ||
2241 !match(I.getOperand(1), m_APInt(RHSC))))
2242 return nullptr;
2243
2244 switch (IID) {
2245 case Intrinsic::fshl:
2246 case Intrinsic::fshr: {
2247 if (X->getOperand(2) != Y->getOperand(2))
2248 return nullptr;
2249 Value *NewOp0 =
2250 Builder.CreateBinOp(I.getOpcode(), X->getOperand(0), Y->getOperand(0));
2251 Value *NewOp1 =
2252 Builder.CreateBinOp(I.getOpcode(), X->getOperand(1), Y->getOperand(1));
2253 Function *F = Intrinsic::getDeclaration(I.getModule(), IID, I.getType());
2254 return CallInst::Create(F, {NewOp0, NewOp1, X->getOperand(2)});
2255 }
2256 case Intrinsic::bswap:
2257 case Intrinsic::bitreverse: {
2258 Value *NewOp0 = Builder.CreateBinOp(
2259 I.getOpcode(), X->getOperand(0),
2260 Y ? Y->getOperand(0)
2261 : ConstantInt::get(I.getType(), IID == Intrinsic::bswap
2262 ? RHSC->byteSwap()
2263 : RHSC->reverseBits()));
2264 Function *F = Intrinsic::getDeclaration(I.getModule(), IID, I.getType());
2265 return CallInst::Create(F, {NewOp0});
2266 }
2267 default:
2268 return nullptr;
2269 }
2270}
2271
2272// Try to simplify V by replacing occurrences of Op with RepOp, but only look
2273// through bitwise operations. In particular, for X | Y we try to replace Y with
2274// 0 inside X and for X & Y we try to replace Y with -1 inside X.
2275// Return the simplified result of X if successful, and nullptr otherwise.
2276// If SimplifyOnly is true, no new instructions will be created.
2278 bool SimplifyOnly,
2279 InstCombinerImpl &IC,
2280 unsigned Depth = 0) {
2281 if (Op == RepOp)
2282 return nullptr;
2283
2284 if (V == Op)
2285 return RepOp;
2286
2287 auto *I = dyn_cast<BinaryOperator>(V);
2288 if (!I || !I->isBitwiseLogicOp() || Depth >= 3)
2289 return nullptr;
2290
2291 if (!I->hasOneUse())
2292 SimplifyOnly = true;
2293
2294 Value *NewOp0 = simplifyAndOrWithOpReplaced(I->getOperand(0), Op, RepOp,
2295 SimplifyOnly, IC, Depth + 1);
2296 Value *NewOp1 = simplifyAndOrWithOpReplaced(I->getOperand(1), Op, RepOp,
2297 SimplifyOnly, IC, Depth + 1);
2298 if (!NewOp0 && !NewOp1)
2299 return nullptr;
2300
2301 if (!NewOp0)
2302 NewOp0 = I->getOperand(0);
2303 if (!NewOp1)
2304 NewOp1 = I->getOperand(1);
2305
2306 if (Value *Res = simplifyBinOp(I->getOpcode(), NewOp0, NewOp1,
2308 return Res;
2309
2310 if (SimplifyOnly)
2311 return nullptr;
2312 return IC.Builder.CreateBinOp(I->getOpcode(), NewOp0, NewOp1);
2313}
2314
2315// FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
2316// here. We should standardize that construct where it is needed or choose some
2317// other way to ensure that commutated variants of patterns are not missed.
2319 Type *Ty = I.getType();
2320
2321 if (Value *V = simplifyAndInst(I.getOperand(0), I.getOperand(1),
2323 return replaceInstUsesWith(I, V);
2324
2326 return &I;
2327
2329 return X;
2330
2332 return Phi;
2333
2334 // See if we can simplify any instructions used by the instruction whose sole
2335 // purpose is to compute bits we don't care about.
2337 return &I;
2338
2339 // Do this before using distributive laws to catch simple and/or/not patterns.
2341 return Xor;
2342
2344 return X;
2345
2346 // (A|B)&(A|C) -> A|(B&C) etc
2348 return replaceInstUsesWith(I, V);
2349
2351 return R;
2352
2353 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2354
2355 Value *X, *Y;
2356 const APInt *C;
2357 if ((match(Op0, m_OneUse(m_LogicalShift(m_One(), m_Value(X)))) ||
2358 (match(Op0, m_OneUse(m_Shl(m_APInt(C), m_Value(X)))) && (*C)[0])) &&
2359 match(Op1, m_One())) {
2360 // (1 >> X) & 1 --> zext(X == 0)
2361 // (C << X) & 1 --> zext(X == 0), when C is odd
2362 Value *IsZero = Builder.CreateICmpEQ(X, ConstantInt::get(Ty, 0));
2363 return new ZExtInst(IsZero, Ty);
2364 }
2365
2366 // (-(X & 1)) & Y --> (X & 1) == 0 ? 0 : Y
2367 Value *Neg;
2368 if (match(&I,
2370 m_OneUse(m_Neg(m_And(m_Value(), m_One())))),
2371 m_Value(Y)))) {
2372 Value *Cmp = Builder.CreateIsNull(Neg);
2374 }
2375
2376 // Canonicalize:
2377 // (X +/- Y) & Y --> ~X & Y when Y is a power of 2.
2380 m_Sub(m_Value(X), m_Deferred(Y)))))) &&
2381 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, /*Depth*/ 0, &I))
2382 return BinaryOperator::CreateAnd(Builder.CreateNot(X), Y);
2383
2384 if (match(Op1, m_APInt(C))) {
2385 const APInt *XorC;
2386 if (match(Op0, m_OneUse(m_Xor(m_Value(X), m_APInt(XorC))))) {
2387 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2388 Constant *NewC = ConstantInt::get(Ty, *C & *XorC);
2389 Value *And = Builder.CreateAnd(X, Op1);
2390 And->takeName(Op0);
2391 return BinaryOperator::CreateXor(And, NewC);
2392 }
2393
2394 const APInt *OrC;
2395 if (match(Op0, m_OneUse(m_Or(m_Value(X), m_APInt(OrC))))) {
2396 // (X | C1) & C2 --> (X & C2^(C1&C2)) | (C1&C2)
2397 // NOTE: This reduces the number of bits set in the & mask, which
2398 // can expose opportunities for store narrowing for scalars.
2399 // NOTE: SimplifyDemandedBits should have already removed bits from C1
2400 // that aren't set in C2. Meaning we can replace (C1&C2) with C1 in
2401 // above, but this feels safer.
2402 APInt Together = *C & *OrC;
2403 Value *And = Builder.CreateAnd(X, ConstantInt::get(Ty, Together ^ *C));
2404 And->takeName(Op0);
2405 return BinaryOperator::CreateOr(And, ConstantInt::get(Ty, Together));
2406 }
2407
2408 unsigned Width = Ty->getScalarSizeInBits();
2409 const APInt *ShiftC;
2410 if (match(Op0, m_OneUse(m_SExt(m_AShr(m_Value(X), m_APInt(ShiftC))))) &&
2411 ShiftC->ult(Width)) {
2412 if (*C == APInt::getLowBitsSet(Width, Width - ShiftC->getZExtValue())) {
2413 // We are clearing high bits that were potentially set by sext+ashr:
2414 // and (sext (ashr X, ShiftC)), C --> lshr (sext X), ShiftC
2415 Value *Sext = Builder.CreateSExt(X, Ty);
2416 Constant *ShAmtC = ConstantInt::get(Ty, ShiftC->zext(Width));
2417 return BinaryOperator::CreateLShr(Sext, ShAmtC);
2418 }
2419 }
2420
2421 // If this 'and' clears the sign-bits added by ashr, replace with lshr:
2422 // and (ashr X, ShiftC), C --> lshr X, ShiftC
2423 if (match(Op0, m_AShr(m_Value(X), m_APInt(ShiftC))) && ShiftC->ult(Width) &&
2424 C->isMask(Width - ShiftC->getZExtValue()))
2425 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, *ShiftC));
2426
2427 const APInt *AddC;
2428 if (match(Op0, m_Add(m_Value(X), m_APInt(AddC)))) {
2429 // If we are masking the result of the add down to exactly one bit and
2430 // the constant we are adding has no bits set below that bit, then the
2431 // add is flipping a single bit. Example:
2432 // (X + 4) & 4 --> (X & 4) ^ 4
2433 if (Op0->hasOneUse() && C->isPowerOf2() && (*AddC & (*C - 1)) == 0) {
2434 assert((*C & *AddC) != 0 && "Expected common bit");
2435 Value *NewAnd = Builder.CreateAnd(X, Op1);
2436 return BinaryOperator::CreateXor(NewAnd, Op1);
2437 }
2438 }
2439
2440 // ((C1 OP zext(X)) & C2) -> zext((C1 OP X) & C2) if C2 fits in the
2441 // bitwidth of X and OP behaves well when given trunc(C1) and X.
2442 auto isNarrowableBinOpcode = [](BinaryOperator *B) {
2443 switch (B->getOpcode()) {
2444 case Instruction::Xor:
2445 case Instruction::Or:
2446 case Instruction::Mul:
2447 case Instruction::Add:
2448 case Instruction::Sub:
2449 return true;
2450 default:
2451 return false;
2452 }
2453 };
2454 BinaryOperator *BO;
2455 if (match(Op0, m_OneUse(m_BinOp(BO))) && isNarrowableBinOpcode(BO)) {
2456 Instruction::BinaryOps BOpcode = BO->getOpcode();
2457 Value *X;
2458 const APInt *C1;
2459 // TODO: The one-use restrictions could be relaxed a little if the AND
2460 // is going to be removed.
2461 // Try to narrow the 'and' and a binop with constant operand:
2462 // and (bo (zext X), C1), C --> zext (and (bo X, TruncC1), TruncC)
2463 if (match(BO, m_c_BinOp(m_OneUse(m_ZExt(m_Value(X))), m_APInt(C1))) &&
2464 C->isIntN(X->getType()->getScalarSizeInBits())) {
2465 unsigned XWidth = X->getType()->getScalarSizeInBits();
2466 Constant *TruncC1 = ConstantInt::get(X->getType(), C1->trunc(XWidth));
2467 Value *BinOp = isa<ZExtInst>(BO->getOperand(0))
2468 ? Builder.CreateBinOp(BOpcode, X, TruncC1)
2469 : Builder.CreateBinOp(BOpcode, TruncC1, X);
2470 Constant *TruncC = ConstantInt::get(X->getType(), C->trunc(XWidth));
2471 Value *And = Builder.CreateAnd(BinOp, TruncC);
2472 return new ZExtInst(And, Ty);
2473 }
2474
2475 // Similar to above: if the mask matches the zext input width, then the
2476 // 'and' can be eliminated, so we can truncate the other variable op:
2477 // and (bo (zext X), Y), C --> zext (bo X, (trunc Y))
2478 if (isa<Instruction>(BO->getOperand(0)) &&
2479 match(BO->getOperand(0), m_OneUse(m_ZExt(m_Value(X)))) &&
2480 C->isMask(X->getType()->getScalarSizeInBits())) {
2481 Y = BO->getOperand(1);
2482 Value *TrY = Builder.CreateTrunc(Y, X->getType(), Y->getName() + ".tr");
2483 Value *NewBO =
2484 Builder.CreateBinOp(BOpcode, X, TrY, BO->getName() + ".narrow");
2485 return new ZExtInst(NewBO, Ty);
2486 }
2487 // and (bo Y, (zext X)), C --> zext (bo (trunc Y), X)
2488 if (isa<Instruction>(BO->getOperand(1)) &&
2489 match(BO->getOperand(1), m_OneUse(m_ZExt(m_Value(X)))) &&
2490 C->isMask(X->getType()->getScalarSizeInBits())) {
2491 Y = BO->getOperand(0);
2492 Value *TrY = Builder.CreateTrunc(Y, X->getType(), Y->getName() + ".tr");
2493 Value *NewBO =
2494 Builder.CreateBinOp(BOpcode, TrY, X, BO->getName() + ".narrow");
2495 return new ZExtInst(NewBO, Ty);
2496 }
2497 }
2498
2499 // This is intentionally placed after the narrowing transforms for
2500 // efficiency (transform directly to the narrow logic op if possible).
2501 // If the mask is only needed on one incoming arm, push the 'and' op up.
2502 if (match(Op0, m_OneUse(m_Xor(m_Value(X), m_Value(Y)))) ||
2503 match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2504 APInt NotAndMask(~(*C));
2505 BinaryOperator::BinaryOps BinOp = cast<BinaryOperator>(Op0)->getOpcode();
2506 if (MaskedValueIsZero(X, NotAndMask, 0, &I)) {
2507 // Not masking anything out for the LHS, move mask to RHS.
2508 // and ({x}or X, Y), C --> {x}or X, (and Y, C)
2509 Value *NewRHS = Builder.CreateAnd(Y, Op1, Y->getName() + ".masked");
2510 return BinaryOperator::Create(BinOp, X, NewRHS);
2511 }
2512 if (!isa<Constant>(Y) && MaskedValueIsZero(Y, NotAndMask, 0, &I)) {
2513 // Not masking anything out for the RHS, move mask to LHS.
2514 // and ({x}or X, Y), C --> {x}or (and X, C), Y
2515 Value *NewLHS = Builder.CreateAnd(X, Op1, X->getName() + ".masked");
2516 return BinaryOperator::Create(BinOp, NewLHS, Y);
2517 }
2518 }
2519
2520 // When the mask is a power-of-2 constant and op0 is a shifted-power-of-2
2521 // constant, test if the shift amount equals the offset bit index:
2522 // (ShiftC << X) & C --> X == (log2(C) - log2(ShiftC)) ? C : 0
2523 // (ShiftC >> X) & C --> X == (log2(ShiftC) - log2(C)) ? C : 0
2524 if (C->isPowerOf2() &&
2525 match(Op0, m_OneUse(m_LogicalShift(m_Power2(ShiftC), m_Value(X))))) {
2526 int Log2ShiftC = ShiftC->exactLogBase2();
2527 int Log2C = C->exactLogBase2();
2528 bool IsShiftLeft =
2529 cast<BinaryOperator>(Op0)->getOpcode() == Instruction::Shl;
2530 int BitNum = IsShiftLeft ? Log2C - Log2ShiftC : Log2ShiftC - Log2C;
2531 assert(BitNum >= 0 && "Expected demanded bits to handle impossible mask");
2532 Value *Cmp = Builder.CreateICmpEQ(X, ConstantInt::get(Ty, BitNum));
2533 return SelectInst::Create(Cmp, ConstantInt::get(Ty, *C),
2535 }
2536
2537 Constant *C1, *C2;
2538 const APInt *C3 = C;
2539 Value *X;
2540 if (C3->isPowerOf2()) {
2541 Constant *Log2C3 = ConstantInt::get(Ty, C3->countr_zero());
2543 m_ImmConstant(C2)))) &&
2544 match(C1, m_Power2())) {
2546 Constant *LshrC = ConstantExpr::getAdd(C2, Log2C3);
2547 KnownBits KnownLShrc = computeKnownBits(LshrC, 0, nullptr);
2548 if (KnownLShrc.getMaxValue().ult(Width)) {
2549 // iff C1,C3 is pow2 and C2 + cttz(C3) < BitWidth:
2550 // ((C1 << X) >> C2) & C3 -> X == (cttz(C3)+C2-cttz(C1)) ? C3 : 0
2551 Constant *CmpC = ConstantExpr::getSub(LshrC, Log2C1);
2552 Value *Cmp = Builder.CreateICmpEQ(X, CmpC);
2553 return SelectInst::Create(Cmp, ConstantInt::get(Ty, *C3),
2555 }
2556 }
2557
2559 m_ImmConstant(C2)))) &&
2560 match(C1, m_Power2())) {
2562 Constant *Cmp =
2564 if (Cmp && Cmp->isZeroValue()) {
2565 // iff C1,C3 is pow2 and Log2(C3) >= C2:
2566 // ((C1 >> X) << C2) & C3 -> X == (cttz(C1)+C2-cttz(C3)) ? C3 : 0
2567 Constant *ShlC = ConstantExpr::getAdd(C2, Log2C1);
2568 Constant *CmpC = ConstantExpr::getSub(ShlC, Log2C3);
2569 Value *Cmp = Builder.CreateICmpEQ(X, CmpC);
2570 return SelectInst::Create(Cmp, ConstantInt::get(Ty, *C3),
2572 }
2573 }
2574 }
2575 }
2576
2577 // If we are clearing the sign bit of a floating-point value, convert this to
2578 // fabs, then cast back to integer.
2579 //
2580 // This is a generous interpretation for noimplicitfloat, this is not a true
2581 // floating-point operation.
2582 //
2583 // Assumes any IEEE-represented type has the sign bit in the high bit.
2584 // TODO: Unify with APInt matcher. This version allows undef unlike m_APInt
2585 Value *CastOp;
2586 if (match(Op0, m_ElementWiseBitCast(m_Value(CastOp))) &&
2587 match(Op1, m_MaxSignedValue()) &&
2589 Attribute::NoImplicitFloat)) {
2590 Type *EltTy = CastOp->getType()->getScalarType();
2591 if (EltTy->isFloatingPointTy() && EltTy->isIEEE()) {
2592 Value *FAbs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, CastOp);
2593 return new BitCastInst(FAbs, I.getType());
2594 }
2595 }
2596
2597 // and(shl(zext(X), Y), SignMask) -> and(sext(X), SignMask)
2598 // where Y is a valid shift amount.
2600 m_SignMask())) &&
2604 Ty->getScalarSizeInBits() -
2605 X->getType()->getScalarSizeInBits())))) {
2606 auto *SExt = Builder.CreateSExt(X, Ty, X->getName() + ".signext");
2607 return BinaryOperator::CreateAnd(SExt, Op1);
2608 }
2609
2610 if (Instruction *Z = narrowMaskedBinOp(I))
2611 return Z;
2612
2613 if (I.getType()->isIntOrIntVectorTy(1)) {
2614 if (auto *SI0 = dyn_cast<SelectInst>(Op0)) {
2615 if (auto *R =
2616 foldAndOrOfSelectUsingImpliedCond(Op1, *SI0, /* IsAnd */ true))
2617 return R;
2618 }
2619 if (auto *SI1 = dyn_cast<SelectInst>(Op1)) {
2620 if (auto *R =
2621 foldAndOrOfSelectUsingImpliedCond(Op0, *SI1, /* IsAnd */ true))
2622 return R;
2623 }
2624 }
2625
2626 if (Instruction *FoldedLogic = foldBinOpIntoSelectOrPhi(I))
2627 return FoldedLogic;
2628
2629 if (Instruction *DeMorgan = matchDeMorgansLaws(I, *this))
2630 return DeMorgan;
2631
2632 {
2633 Value *A, *B, *C;
2634 // A & ~(A ^ B) --> A & B
2635 if (match(Op1, m_Not(m_c_Xor(m_Specific(Op0), m_Value(B)))))
2636 return BinaryOperator::CreateAnd(Op0, B);
2637 // ~(A ^ B) & A --> A & B
2638 if (match(Op0, m_Not(m_c_Xor(m_Specific(Op1), m_Value(B)))))
2639 return BinaryOperator::CreateAnd(Op1, B);
2640
2641 // (A ^ B) & ((B ^ C) ^ A) -> (A ^ B) & ~C
2642 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
2643 match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A)))) {
2644 Value *NotC = Op1->hasOneUse()
2646 : getFreelyInverted(C, C->hasOneUse(), &Builder);
2647 if (NotC != nullptr)
2648 return BinaryOperator::CreateAnd(Op0, NotC);
2649 }
2650
2651 // ((A ^ C) ^ B) & (B ^ A) -> (B ^ A) & ~C
2652 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))) &&
2653 match(Op1, m_Xor(m_Specific(B), m_Specific(A)))) {
2654 Value *NotC = Op0->hasOneUse()
2656 : getFreelyInverted(C, C->hasOneUse(), &Builder);
2657 if (NotC != nullptr)
2658 return BinaryOperator::CreateAnd(Op1, Builder.CreateNot(C));
2659 }
2660
2661 // (A | B) & (~A ^ B) -> A & B
2662 // (A | B) & (B ^ ~A) -> A & B
2663 // (B | A) & (~A ^ B) -> A & B
2664 // (B | A) & (B ^ ~A) -> A & B
2665 if (match(Op1, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
2666 match(Op0, m_c_Or(m_Specific(A), m_Specific(B))))
2667 return BinaryOperator::CreateAnd(A, B);
2668
2669 // (~A ^ B) & (A | B) -> A & B
2670 // (~A ^ B) & (B | A) -> A & B
2671 // (B ^ ~A) & (A | B) -> A & B
2672 // (B ^ ~A) & (B | A) -> A & B
2673 if (match(Op0, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
2674 match(Op1, m_c_Or(m_Specific(A), m_Specific(B))))
2675 return BinaryOperator::CreateAnd(A, B);
2676
2677 // (~A | B) & (A ^ B) -> ~A & B
2678 // (~A | B) & (B ^ A) -> ~A & B
2679 // (B | ~A) & (A ^ B) -> ~A & B
2680 // (B | ~A) & (B ^ A) -> ~A & B
2681 if (match(Op0, m_c_Or(m_Not(m_Value(A)), m_Value(B))) &&
2683 return BinaryOperator::CreateAnd(Builder.CreateNot(A), B);
2684
2685 // (A ^ B) & (~A | B) -> ~A & B
2686 // (B ^ A) & (~A | B) -> ~A & B
2687 // (A ^ B) & (B | ~A) -> ~A & B
2688 // (B ^ A) & (B | ~A) -> ~A & B
2689 if (match(Op1, m_c_Or(m_Not(m_Value(A)), m_Value(B))) &&
2691 return BinaryOperator::CreateAnd(Builder.CreateNot(A), B);
2692 }
2693
2694 {
2695 ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
2696 ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
2697 if (LHS && RHS)
2698 if (Value *Res = foldAndOrOfICmps(LHS, RHS, I, /* IsAnd */ true))
2699 return replaceInstUsesWith(I, Res);
2700
2701 // TODO: Make this recursive; it's a little tricky because an arbitrary
2702 // number of 'and' instructions might have to be created.
2703 if (LHS && match(Op1, m_OneUse(m_LogicalAnd(m_Value(X), m_Value(Y))))) {
2704 bool IsLogical = isa<SelectInst>(Op1);
2705 // LHS & (X && Y) --> (LHS && X) && Y
2706 if (auto *Cmp = dyn_cast<ICmpInst>(X))
2707 if (Value *Res =
2708 foldAndOrOfICmps(LHS, Cmp, I, /* IsAnd */ true, IsLogical))
2709 return replaceInstUsesWith(I, IsLogical
2710 ? Builder.CreateLogicalAnd(Res, Y)
2711 : Builder.CreateAnd(Res, Y));
2712 // LHS & (X && Y) --> X && (LHS & Y)
2713 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
2714 if (Value *Res = foldAndOrOfICmps(LHS, Cmp, I, /* IsAnd */ true,
2715 /* IsLogical */ false))
2716 return replaceInstUsesWith(I, IsLogical
2717 ? Builder.CreateLogicalAnd(X, Res)
2718 : Builder.CreateAnd(X, Res));
2719 }
2720 if (RHS && match(Op0, m_OneUse(m_LogicalAnd(m_Value(X), m_Value(Y))))) {
2721 bool IsLogical = isa<SelectInst>(Op0);
2722 // (X && Y) & RHS --> (X && RHS) && Y
2723 if (auto *Cmp = dyn_cast<ICmpInst>(X))
2724 if (Value *Res =
2725 foldAndOrOfICmps(Cmp, RHS, I, /* IsAnd */ true, IsLogical))
2726 return replaceInstUsesWith(I, IsLogical
2727 ? Builder.CreateLogicalAnd(Res, Y)
2728 : Builder.CreateAnd(Res, Y));
2729 // (X && Y) & RHS --> X && (Y & RHS)
2730 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
2731 if (Value *Res = foldAndOrOfICmps(Cmp, RHS, I, /* IsAnd */ true,
2732 /* IsLogical */ false))
2733 return replaceInstUsesWith(I, IsLogical
2734 ? Builder.CreateLogicalAnd(X, Res)
2735 : Builder.CreateAnd(X, Res));
2736 }
2737 }
2738
2739 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
2740 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
2741 if (Value *Res = foldLogicOfFCmps(LHS, RHS, /*IsAnd*/ true))
2742 return replaceInstUsesWith(I, Res);
2743
2744 if (Instruction *FoldedFCmps = reassociateFCmps(I, Builder))
2745 return FoldedFCmps;
2746
2747 if (Instruction *CastedAnd = foldCastedBitwiseLogic(I))
2748 return CastedAnd;
2749
2750 if (Instruction *Sel = foldBinopOfSextBoolToSelect(I))
2751 return Sel;
2752
2753 // and(sext(A), B) / and(B, sext(A)) --> A ? B : 0, where A is i1 or <N x i1>.
2754 // TODO: Move this into foldBinopOfSextBoolToSelect as a more generalized fold
2755 // with binop identity constant. But creating a select with non-constant
2756 // arm may not be reversible due to poison semantics. Is that a good
2757 // canonicalization?
2758 Value *A, *B;
2759 if (match(&I, m_c_And(m_SExt(m_Value(A)), m_Value(B))) &&
2760 A->getType()->isIntOrIntVectorTy(1))
2762
2763 // Similarly, a 'not' of the bool translates to a swap of the select arms:
2764 // ~sext(A) & B / B & ~sext(A) --> A ? 0 : B
2765 if (match(&I, m_c_And(m_Not(m_SExt(m_Value(A))), m_Value(B))) &&
2766 A->getType()->isIntOrIntVectorTy(1))
2768
2769 // and(zext(A), B) -> A ? (B & 1) : 0
2770 if (match(&I, m_c_And(m_OneUse(m_ZExt(m_Value(A))), m_Value(B))) &&
2771 A->getType()->isIntOrIntVectorTy(1))
2772 return SelectInst::Create(A, Builder.CreateAnd(B, ConstantInt::get(Ty, 1)),
2774
2775 // (-1 + A) & B --> A ? 0 : B where A is 0/1.
2777 m_Value(B)))) {
2778 if (A->getType()->isIntOrIntVectorTy(1))
2780 if (computeKnownBits(A, /* Depth */ 0, &I).countMaxActiveBits() <= 1) {
2781 return SelectInst::Create(
2784 }
2785 }
2786
2787 // (iN X s>> (N-1)) & Y --> (X s< 0) ? Y : 0 -- with optional sext
2790 m_Value(Y))) &&
2791 *C == X->getType()->getScalarSizeInBits() - 1) {
2792 Value *IsNeg = Builder.CreateIsNeg(X, "isneg");
2794 }
2795 // If there's a 'not' of the shifted value, swap the select operands:
2796 // ~(iN X s>> (N-1)) & Y --> (X s< 0) ? 0 : Y -- with optional sext
2799 m_Value(Y))) &&
2800 *C == X->getType()->getScalarSizeInBits() - 1) {
2801 Value *IsNeg = Builder.CreateIsNeg(X, "isneg");
2803 }
2804
2805 // (~x) & y --> ~(x | (~y)) iff that gets rid of inversions
2807 return &I;
2808
2809 // An and recurrence w/loop invariant step is equivelent to (and start, step)
2810 PHINode *PN = nullptr;
2811 Value *Start = nullptr, *Step = nullptr;
2812 if (matchSimpleRecurrence(&I, PN, Start, Step) && DT.dominates(Step, PN))
2813 return replaceInstUsesWith(I, Builder.CreateAnd(Start, Step));
2814
2816 return R;
2817
2818 if (Instruction *Canonicalized = canonicalizeLogicFirst(I, Builder))
2819 return Canonicalized;
2820
2821 if (Instruction *Folded = foldLogicOfIsFPClass(I, Op0, Op1))
2822 return Folded;
2823
2824 if (Instruction *Res = foldBinOpOfDisplacedShifts(I))
2825 return Res;
2826
2828 return Res;
2829
2830 if (Value *V =
2832 /*SimplifyOnly*/ false, *this))
2833 return BinaryOperator::CreateAnd(V, Op1);
2834 if (Value *V =
2836 /*SimplifyOnly*/ false, *this))
2837 return BinaryOperator::CreateAnd(Op0, V);
2838
2839 return nullptr;
2840}
2841
2843 bool MatchBSwaps,
2844 bool MatchBitReversals) {
2846 if (!recognizeBSwapOrBitReverseIdiom(&I, MatchBSwaps, MatchBitReversals,
2847 Insts))
2848 return nullptr;
2849 Instruction *LastInst = Insts.pop_back_val();
2850 LastInst->removeFromParent();
2851
2852 for (auto *Inst : Insts)
2853 Worklist.push(Inst);
2854 return LastInst;
2855}
2856
2857std::optional<std::pair<Intrinsic::ID, SmallVector<Value *, 3>>>
2859 // TODO: Can we reduce the code duplication between this and the related
2860 // rotate matching code under visitSelect and visitTrunc?
2861 assert(Or.getOpcode() == BinaryOperator::Or && "Expecting or instruction");
2862
2863 unsigned Width = Or.getType()->getScalarSizeInBits();
2864
2865 Instruction *Or0, *Or1;
2866 if (!match(Or.getOperand(0), m_Instruction(Or0)) ||
2867 !match(Or.getOperand(1), m_Instruction(Or1)))
2868 return std::nullopt;
2869
2870 bool IsFshl = true; // Sub on LSHR.
2871 SmallVector<Value *, 3> FShiftArgs;
2872
2873 // First, find an or'd pair of opposite shifts:
2874 // or (lshr ShVal0, ShAmt0), (shl ShVal1, ShAmt1)
2875 if (isa<BinaryOperator>(Or0) && isa<BinaryOperator>(Or1)) {
2876 Value *ShVal0, *ShVal1, *ShAmt0, *ShAmt1;
2877 if (!match(Or0,
2878 m_OneUse(m_LogicalShift(m_Value(ShVal0), m_Value(ShAmt0)))) ||
2879 !match(Or1,
2880 m_OneUse(m_LogicalShift(m_Value(ShVal1), m_Value(ShAmt1)))) ||
2881 Or0->getOpcode() == Or1->getOpcode())
2882 return std::nullopt;
2883
2884 // Canonicalize to or(shl(ShVal0, ShAmt0), lshr(ShVal1, ShAmt1)).
2885 if (Or0->getOpcode() == BinaryOperator::LShr) {
2886 std::swap(Or0, Or1);
2887 std::swap(ShVal0, ShVal1);
2888 std::swap(ShAmt0, ShAmt1);
2889 }
2890 assert(Or0->getOpcode() == BinaryOperator::Shl &&
2891 Or1->getOpcode() == BinaryOperator::LShr &&
2892 "Illegal or(shift,shift) pair");
2893
2894 // Match the shift amount operands for a funnel shift pattern. This always
2895 // matches a subtraction on the R operand.
2896 auto matchShiftAmount = [&](Value *L, Value *R, unsigned Width) -> Value * {
2897 // Check for constant shift amounts that sum to the bitwidth.
2898 const APInt *LI, *RI;
2900 if (LI->ult(Width) && RI->ult(Width) && (*LI + *RI) == Width)
2901 return ConstantInt::get(L->getType(), *LI);
2902
2903 Constant *LC, *RC;
2904 if (match(L, m_Constant(LC)) && match(R, m_Constant(RC)) &&
2905 match(L,
2906 m_SpecificInt_ICMP(ICmpInst::ICMP_ULT, APInt(Width, Width))) &&
2907 match(R,
2908 m_SpecificInt_ICMP(ICmpInst::ICMP_ULT, APInt(Width, Width))) &&
2910 return ConstantExpr::mergeUndefsWith(LC, RC);
2911
2912 // (shl ShVal, X) | (lshr ShVal, (Width - x)) iff X < Width.
2913 // We limit this to X < Width in case the backend re-expands the
2914 // intrinsic, and has to reintroduce a shift modulo operation (InstCombine
2915 // might remove it after this fold). This still doesn't guarantee that the
2916 // final codegen will match this original pattern.
2917 if (match(R, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(L))))) {
2918 KnownBits KnownL = computeKnownBits(L, /*Depth*/ 0, &Or);
2919 return KnownL.getMaxValue().ult(Width) ? L : nullptr;
2920 }
2921
2922 // For non-constant cases, the following patterns currently only work for
2923 // rotation patterns.
2924 // TODO: Add general funnel-shift compatible patterns.
2925 if (ShVal0 != ShVal1)
2926 return nullptr;
2927
2928 // For non-constant cases we don't support non-pow2 shift masks.
2929 // TODO: Is it worth matching urem as well?
2930 if (!isPowerOf2_32(Width))
2931 return nullptr;
2932
2933 // The shift amount may be masked with negation:
2934 // (shl ShVal, (X & (Width - 1))) | (lshr ShVal, ((-X) & (Width - 1)))
2935 Value *X;
2936 unsigned Mask = Width - 1;
2937 if (match(L, m_And(m_Value(X), m_SpecificInt(Mask))) &&
2938 match(R, m_And(m_Neg(m_Specific(X)), m_SpecificInt(Mask))))
2939 return X;
2940
2941 // (shl ShVal, X) | (lshr ShVal, ((-X) & (Width - 1)))
2942 if (match(R, m_And(m_Neg(m_Specific(L)), m_SpecificInt(Mask))))
2943 return L;
2944
2945 // Similar to above, but the shift amount may be extended after masking,
2946 // so return the extended value as the parameter for the intrinsic.
2947 if (match(L, m_ZExt(m_And(m_Value(X), m_SpecificInt(Mask)))) &&
2948 match(R,
2950 m_SpecificInt(Mask))))
2951 return L;
2952
2953 if (match(L, m_ZExt(m_And(m_Value(X), m_SpecificInt(Mask)))) &&
2955 return L;
2956
2957 return nullptr;
2958 };
2959
2960 Value *ShAmt = matchShiftAmount(ShAmt0, ShAmt1, Width);
2961 if (!ShAmt) {
2962 ShAmt = matchShiftAmount(ShAmt1, ShAmt0, Width);
2963 IsFshl = false; // Sub on SHL.
2964 }
2965 if (!ShAmt)
2966 return std::nullopt;
2967
2968 FShiftArgs = {ShVal0, ShVal1, ShAmt};
2969 } else if (isa<ZExtInst>(Or0) || isa<ZExtInst>(Or1)) {
2970 // If there are two 'or' instructions concat variables in opposite order:
2971 //
2972 // Slot1 and Slot2 are all zero bits.
2973 // | Slot1 | Low | Slot2 | High |
2974 // LowHigh = or (shl (zext Low), ZextLowShlAmt), (zext High)
2975 // | Slot2 | High | Slot1 | Low |
2976 // HighLow = or (shl (zext High), ZextHighShlAmt), (zext Low)
2977 //
2978 // the latter 'or' can be safely convert to
2979 // -> HighLow = fshl LowHigh, LowHigh, ZextHighShlAmt
2980 // if ZextLowShlAmt + ZextHighShlAmt == Width.
2981 if (!isa<ZExtInst>(Or1))
2982 std::swap(Or0, Or1);
2983
2984 Value *High, *ZextHigh, *Low;
2985 const APInt *ZextHighShlAmt;
2986 if (!match(Or0,
2987 m_OneUse(m_Shl(m_Value(ZextHigh), m_APInt(ZextHighShlAmt)))))
2988 return std::nullopt;
2989
2990 if (!match(Or1, m_ZExt(m_Value(Low))) ||
2991 !match(ZextHigh, m_ZExt(m_Value(High))))
2992 return std::nullopt;
2993
2994 unsigned HighSize = High->getType()->getScalarSizeInBits();
2995 unsigned LowSize = Low->getType()->getScalarSizeInBits();
2996 // Make sure High does not overlap with Low and most significant bits of
2997 // High aren't shifted out.
2998 if (ZextHighShlAmt->ult(LowSize) || ZextHighShlAmt->ugt(Width - HighSize))
2999 return std::nullopt;
3000
3001 for (User *U : ZextHigh->users()) {
3002 Value *X, *Y;
3003 if (!match(U, m_Or(m_Value(X), m_Value(Y))))
3004 continue;
3005
3006 if (!isa<ZExtInst>(Y))
3007 std::swap(X, Y);
3008
3009 const APInt *ZextLowShlAmt;
3010 if (!match(X, m_Shl(m_Specific(Or1), m_APInt(ZextLowShlAmt))) ||
3011 !match(Y, m_Specific(ZextHigh)) || !DT.dominates(U, &Or))
3012 continue;
3013
3014 // HighLow is good concat. If sum of two shifts amount equals to Width,
3015 // LowHigh must also be a good concat.
3016 if (*ZextLowShlAmt + *ZextHighShlAmt != Width)
3017 continue;
3018
3019 // Low must not overlap with High and most significant bits of Low must
3020 // not be shifted out.
3021 assert(ZextLowShlAmt->uge(HighSize) &&
3022 ZextLowShlAmt->ule(Width - LowSize) && "Invalid concat");
3023
3024 FShiftArgs = {U, U, ConstantInt::get(Or0->getType(), *ZextHighShlAmt)};
3025 break;
3026 }
3027 }
3028
3029 if (FShiftArgs.empty())
3030 return std::nullopt;
3031
3032 Intrinsic::ID IID = IsFshl ? Intrinsic::fshl : Intrinsic::fshr;
3033 return std::make_pair(IID, FShiftArgs);
3034}
3035
3036/// Match UB-safe variants of the funnel shift intrinsic.
3038 if (auto Opt = IC.convertOrOfShiftsToFunnelShift(Or)) {
3039 auto [IID, FShiftArgs] = *Opt;
3040 Function *F = Intrinsic::getDeclaration(Or.getModule(), IID, Or.getType());
3041 return CallInst::Create(F, FShiftArgs);
3042 }
3043
3044 return nullptr;
3045}
3046
3047/// Attempt to combine or(zext(x),shl(zext(y),bw/2) concat packing patterns.
3049 InstCombiner::BuilderTy &Builder) {
3050 assert(Or.getOpcode() == Instruction::Or && "bswap requires an 'or'");
3051 Value *Op0 = Or.getOperand(0), *Op1 = Or.getOperand(1);
3052 Type *Ty = Or.getType();
3053
3054 unsigned Width = Ty->getScalarSizeInBits();
3055 if ((Width & 1) != 0)
3056 return nullptr;
3057 unsigned HalfWidth = Width / 2;
3058
3059 // Canonicalize zext (lower half) to LHS.
3060 if (!isa<ZExtInst>(Op0))
3061 std::swap(Op0, Op1);
3062
3063 // Find lower/upper half.
3064 Value *LowerSrc, *ShlVal, *UpperSrc;
3065 const APInt *C;
3066 if (!match(Op0, m_OneUse(m_ZExt(m_Value(LowerSrc)))) ||
3067 !match(Op1, m_OneUse(m_Shl(m_Value(ShlVal), m_APInt(C)))) ||
3068 !match(ShlVal, m_OneUse(m_ZExt(m_Value(UpperSrc)))))
3069 return nullptr;
3070 if (*C != HalfWidth || LowerSrc->getType() != UpperSrc->getType() ||
3071 LowerSrc->getType()->getScalarSizeInBits() != HalfWidth)
3072 return nullptr;
3073
3074 auto ConcatIntrinsicCalls = [&](Intrinsic::ID id, Value *Lo, Value *Hi) {
3075 Value *NewLower = Builder.CreateZExt(Lo, Ty);
3076 Value *NewUpper = Builder.CreateZExt(Hi, Ty);
3077 NewUpper = Builder.CreateShl(NewUpper, HalfWidth);
3078 Value *BinOp = Builder.CreateOr(NewLower, NewUpper);
3079 Function *F = Intrinsic::getDeclaration(Or.getModule(), id, Ty);
3080 return Builder.CreateCall(F, BinOp);
3081 };
3082
3083 // BSWAP: Push the concat down, swapping the lower/upper sources.
3084 // concat(bswap(x),bswap(y)) -> bswap(concat(x,y))
3085 Value *LowerBSwap, *UpperBSwap;
3086 if (match(LowerSrc, m_BSwap(m_Value(LowerBSwap))) &&
3087 match(UpperSrc, m_BSwap(m_Value(UpperBSwap))))
3088 return ConcatIntrinsicCalls(Intrinsic::bswap, UpperBSwap, LowerBSwap);
3089
3090 // BITREVERSE: Push the concat down, swapping the lower/upper sources.
3091 // concat(bitreverse(x),bitreverse(y)) -> bitreverse(concat(x,y))
3092 Value *LowerBRev, *UpperBRev;
3093 if (match(LowerSrc, m_BitReverse(m_Value(LowerBRev))) &&
3094 match(UpperSrc, m_BitReverse(m_Value(UpperBRev))))
3095 return ConcatIntrinsicCalls(Intrinsic::bitreverse, UpperBRev, LowerBRev);
3096
3097 return nullptr;
3098}
3099
3100/// If all elements of two constant vectors are 0/-1 and inverses, return true.
3102 unsigned NumElts = cast<FixedVectorType>(C1->getType())->getNumElements();
3103 for (unsigned i = 0; i != NumElts; ++i) {
3104 Constant *EltC1 = C1->getAggregateElement(i);
3105 Constant *EltC2 = C2->getAggregateElement(i);
3106 if (!EltC1 || !EltC2)
3107 return false;
3108
3109 // One element must be all ones, and the other must be all zeros.
3110 if (!((match(EltC1, m_Zero()) && match(EltC2, m_AllOnes())) ||
3111 (match(EltC2, m_Zero()) && match(EltC1, m_AllOnes()))))
3112 return false;
3113 }
3114 return true;
3115}
3116
3117/// We have an expression of the form (A & C) | (B & D). If A is a scalar or
3118/// vector composed of all-zeros or all-ones values and is the bitwise 'not' of
3119/// B, it can be used as the condition operand of a select instruction.
3120/// We will detect (A & C) | ~(B | D) when the flag ABIsTheSame enabled.
3121Value *InstCombinerImpl::getSelectCondition(Value *A, Value *B,
3122 bool ABIsTheSame) {
3123 // We may have peeked through bitcasts in the caller.
3124 // Exit immediately if we don't have (vector) integer types.
3125 Type *Ty = A->getType();
3126 if (!Ty->isIntOrIntVectorTy() || !B->getType()->isIntOrIntVectorTy())
3127 return nullptr;
3128
3129 // If A is the 'not' operand of B and has enough signbits, we have our answer.
3130 if (ABIsTheSame ? (A == B) : match(B, m_Not(m_Specific(A)))) {
3131 // If these are scalars or vectors of i1, A can be used directly.
3132 if (Ty->isIntOrIntVectorTy(1))
3133 return A;
3134
3135 // If we look through a vector bitcast, the caller will bitcast the operands
3136 // to match the condition's number of bits (N x i1).
3137 // To make this poison-safe, disallow bitcast from wide element to narrow
3138 // element. That could allow poison in lanes where it was not present in the
3139 // original code.
3141 if (A->getType()->isIntOrIntVectorTy()) {
3142 unsigned NumSignBits = ComputeNumSignBits(A);
3143 if (NumSignBits == A->getType()->getScalarSizeInBits() &&
3144 NumSignBits <= Ty->getScalarSizeInBits())
3145 return Builder.CreateTrunc(A, CmpInst::makeCmpResultType(A->getType()));
3146 }
3147 return nullptr;
3148 }
3149
3150 // TODO: add support for sext and constant case
3151 if (ABIsTheSame)
3152 return nullptr;
3153
3154 // If both operands are constants, see if the constants are inverse bitmasks.
3155 Constant *AConst, *BConst;
3156 if (match(A, m_Constant(AConst)) && match(B, m_Constant(BConst)))
3157 if (AConst == ConstantExpr::getNot(BConst) &&
3160
3161 // Look for more complex patterns. The 'not' op may be hidden behind various
3162 // casts. Look through sexts and bitcasts to find the booleans.
3163 Value *Cond;
3164 Value *NotB;
3165 if (match(A, m_SExt(m_Value(Cond))) &&
3166 Cond->getType()->isIntOrIntVectorTy(1)) {
3167 // A = sext i1 Cond; B = sext (not (i1 Cond))
3168 if (match(B, m_SExt(m_Not(m_Specific(Cond)))))
3169 return Cond;
3170
3171 // A = sext i1 Cond; B = not ({bitcast} (sext (i1 Cond)))
3172 // TODO: The one-use checks are unnecessary or misplaced. If the caller
3173 // checked for uses on logic ops/casts, that should be enough to
3174 // make this transform worthwhile.
3175 if (match(B, m_OneUse(m_Not(m_Value(NotB))))) {
3176 NotB = peekThroughBitcast(NotB, true);
3177 if (match(NotB, m_SExt(m_Specific(Cond))))
3178 return Cond;
3179 }
3180 }
3181
3182 // All scalar (and most vector) possibilities should be handled now.
3183 // Try more matches that only apply to non-splat constant vectors.
3184 if (!Ty->isVectorTy())
3185 return nullptr;
3186
3187 // If both operands are xor'd with constants using the same sexted boolean
3188 // operand, see if the constants are inverse bitmasks.
3189 // TODO: Use ConstantExpr::getNot()?
3190 if (match(A, (m_Xor(m_SExt(m_Value(Cond)), m_Constant(AConst)))) &&
3191 match(B, (m_Xor(m_SExt(m_Specific(Cond)), m_Constant(BConst)))) &&
3192 Cond->getType()->isIntOrIntVectorTy(1) &&
3193 areInverseVectorBitmasks(AConst, BConst)) {
3195 return Builder.CreateXor(Cond, AConst);
3196 }
3197 return nullptr;
3198}
3199
3200/// We have an expression of the form (A & B) | (C & D). Try to simplify this
3201/// to "A' ? B : D", where A' is a boolean or vector of booleans.
3202/// When InvertFalseVal is set to true, we try to match the pattern
3203/// where we have peeked through a 'not' op and A and C are the same:
3204/// (A & B) | ~(A | D) --> (A & B) | (~A & ~D) --> A' ? B : ~D
3205Value *InstCombinerImpl::matchSelectFromAndOr(Value *A, Value *B, Value *C,
3206 Value *D, bool InvertFalseVal) {
3207 // The potential condition of the select may be bitcasted. In that case, look
3208 // through its bitcast and the corresponding bitcast of the 'not' condition.
3209 Type *OrigType = A->getType();
3210 A = peekThroughBitcast(A, true);
3211 C = peekThroughBitcast(C, true);
3212 if (Value *Cond = getSelectCondition(A, C, InvertFalseVal)) {
3213 // ((bc Cond) & B) | ((bc ~Cond) & D) --> bc (select Cond, (bc B), (bc D))
3214 // If this is a vector, we may need to cast to match the condition's length.
3215 // The bitcasts will either all exist or all not exist. The builder will
3216 // not create unnecessary casts if the types already match.
3217 Type *SelTy = A->getType();
3218 if (auto *VecTy = dyn_cast<VectorType>(Cond->getType())) {
3219 // For a fixed or scalable vector get N from <{vscale x} N x iM>
3220 unsigned Elts = VecTy->getElementCount().getKnownMinValue();
3221 // For a fixed or scalable vector, get the size in bits of N x iM; for a
3222 // scalar this is just M.
3223 unsigned SelEltSize = SelTy->getPrimitiveSizeInBits().getKnownMinValue();
3224 Type *EltTy = Builder.getIntNTy(SelEltSize / Elts);
3225 SelTy = VectorType::get(EltTy, VecTy->getElementCount());
3226 }
3227 Value *BitcastB = Builder.CreateBitCast(B, SelTy);
3228 if (InvertFalseVal)
3229 D = Builder.CreateNot(D);
3230 Value *BitcastD = Builder.CreateBitCast(D, SelTy);
3231 Value *Select = Builder.CreateSelect(Cond, BitcastB, BitcastD);
3232 return Builder.CreateBitCast(Select, OrigType);
3233 }
3234
3235 return nullptr;
3236}
3237
3238// (icmp eq X, C) | (icmp ult Other, (X - C)) -> (icmp ule Other, (X - (C + 1)))
3239// (icmp ne X, C) & (icmp uge Other, (X - C)) -> (icmp ugt Other, (X - (C + 1)))
3241 bool IsAnd, bool IsLogical,
3242 IRBuilderBase &Builder) {
3243 Value *LHS0 = LHS->getOperand(0);
3244 Value *RHS0 = RHS->getOperand(0);
3245 Value *RHS1 = RHS->getOperand(1);
3246
3247 ICmpInst::Predicate LPred =
3248 IsAnd ? LHS->getInversePredicate() : LHS->getPredicate();
3249 ICmpInst::Predicate RPred =
3250 IsAnd ? RHS->getInversePredicate() : RHS->getPredicate();
3251
3252 const APInt *CInt;
3253 if (LPred != ICmpInst::ICMP_EQ ||
3254 !match(LHS->getOperand(1), m_APIntAllowPoison(CInt)) ||
3255 !LHS0->getType()->isIntOrIntVectorTy() ||
3256 !(LHS->hasOneUse() || RHS->hasOneUse()))
3257 return nullptr;
3258
3259 auto MatchRHSOp = [LHS0, CInt](const Value *RHSOp) {
3260 return match(RHSOp,
3261 m_Add(m_Specific(LHS0), m_SpecificIntAllowPoison(-*CInt))) ||
3262 (CInt->isZero() && RHSOp == LHS0);
3263 };
3264
3265 Value *Other;
3266 if (RPred == ICmpInst::ICMP_ULT && MatchRHSOp(RHS1))
3267 Other = RHS0;
3268 else if (RPred == ICmpInst::ICMP_UGT && MatchRHSOp(RHS0))
3269 Other = RHS1;
3270 else
3271 return nullptr;
3272
3273 if (IsLogical)
3274 Other = Builder.CreateFreeze(Other);
3275
3276 return Builder.CreateICmp(
3278 Builder.CreateSub(LHS0, ConstantInt::get(LHS0->getType(), *CInt + 1)),
3279 Other);
3280}
3281
3282/// Fold (icmp)&(icmp) or (icmp)|(icmp) if possible.
3283/// If IsLogical is true, then the and/or is in select form and the transform
3284/// must be poison-safe.
3285Value *InstCombinerImpl::foldAndOrOfICmps(ICmpInst *LHS, ICmpInst *RHS,
3286 Instruction &I, bool IsAnd,
3287 bool IsLogical) {
3289
3290 // Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
3291 // Fold (!iszero(A & K1) & !iszero(A & K2)) -> (A & (K1 | K2)) == (K1 | K2)
3292 // if K1 and K2 are a one-bit mask.
3293 if (Value *V = foldAndOrOfICmpsOfAndWithPow2(LHS, RHS, &I, IsAnd, IsLogical))
3294 return V;
3295
3296 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
3297 Value *LHS0 = LHS->getOperand(0), *RHS0 = RHS->getOperand(0);
3298 Value *LHS1 = LHS->getOperand(1), *RHS1 = RHS->getOperand(1);
3299
3300 const APInt *LHSC = nullptr, *RHSC = nullptr;
3301 match(LHS1, m_APInt(LHSC));
3302 match(RHS1, m_APInt(RHSC));
3303
3304 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3305 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3306 if (predicatesFoldable(PredL, PredR)) {
3307 if (LHS0 == RHS1 && LHS1 == RHS0) {
3308 PredL = ICmpInst::getSwappedPredicate(PredL);
3309 std::swap(LHS0, LHS1);
3310 }
3311 if (LHS0 == RHS0 && LHS1 == RHS1) {
3312 unsigned Code = IsAnd ? getICmpCode(PredL) & getICmpCode(PredR)
3313 : getICmpCode(PredL) | getICmpCode(PredR);
3314 bool IsSigned = LHS->isSigned() || RHS->isSigned();
3315 return getNewICmpValue(Code, IsSigned, LHS0, LHS1, Builder);
3316 }
3317 }
3318
3319 // handle (roughly):
3320 // (icmp ne (A & B), C) | (icmp ne (A & D), E)
3321 // (icmp eq (A & B), C) & (icmp eq (A & D), E)
3322 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, IsAnd, IsLogical, Builder))
3323 return V;
3324
3325 if (Value *V =
3326 foldAndOrOfICmpEqConstantAndICmp(LHS, RHS, IsAnd, IsLogical, Builder))
3327 return V;
3328 // We can treat logical like bitwise here, because both operands are used on
3329 // the LHS, and as such poison from both will propagate.
3330 if (Value *V = foldAndOrOfICmpEqConstantAndICmp(RHS, LHS, IsAnd,
3331 /*IsLogical*/ false, Builder))
3332 return V;
3333
3334 if (Value *V =
3335 foldAndOrOfICmpsWithConstEq(LHS, RHS, IsAnd, IsLogical, Builder, Q))
3336 return V;
3337 // We can convert this case to bitwise and, because both operands are used
3338 // on the LHS, and as such poison from both will propagate.
3339 if (Value *V = foldAndOrOfICmpsWithConstEq(RHS, LHS, IsAnd,
3340 /*IsLogical*/ false, Builder, Q))
3341 return V;
3342
3343 if (Value *V = foldIsPowerOf2OrZero(LHS, RHS, IsAnd, Builder))
3344 return V;
3345 if (Value *V = foldIsPowerOf2OrZero(RHS, LHS, IsAnd, Builder))
3346 return V;
3347
3348 // TODO: One of these directions is fine with logical and/or, the other could
3349 // be supported by inserting freeze.
3350 if (!IsLogical) {
3351 // E.g. (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
3352 // E.g. (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
3353 if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/!IsAnd))
3354 return V;
3355
3356 // E.g. (icmp sgt x, n) | (icmp slt x, 0) --> icmp ugt x, n
3357 // E.g. (icmp slt x, n) & (icmp sge x, 0) --> icmp ult x, n
3358 if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/!IsAnd))
3359 return V;
3360 }
3361
3362 // TODO: Add conjugated or fold, check whether it is safe for logical and/or.
3363 if (IsAnd && !IsLogical)
3364 if (Value *V = foldSignedTruncationCheck(LHS, RHS, I, Builder))
3365 return V;
3366
3367 if (Value *V = foldIsPowerOf2(LHS, RHS, IsAnd, Builder))
3368 return V;
3369
3370 if (Value *V = foldPowerOf2AndShiftedMask(LHS, RHS, IsAnd, Builder))
3371 return V;
3372
3373 // TODO: Verify whether this is safe for logical and/or.
3374 if (!IsLogical) {
3375 if (Value *X = foldUnsignedUnderflowCheck(LHS, RHS, IsAnd, Q, Builder))
3376 return X;
3377 if (Value *X = foldUnsignedUnderflowCheck(RHS, LHS, IsAnd, Q, Builder))
3378 return X;
3379 }
3380
3381 if (Value *X = foldEqOfParts(LHS, RHS, IsAnd))
3382 return X;
3383
3384 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
3385 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
3386 // TODO: Remove this and below when foldLogOpOfMaskedICmps can handle undefs.
3387 if (!IsLogical && PredL == (IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE) &&
3388 PredL == PredR && match(LHS1, m_ZeroInt()) && match(RHS1, m_ZeroInt()) &&
3389 LHS0->getType() == RHS0->getType()) {
3390 Value *NewOr = Builder.CreateOr(LHS0, RHS0);
3391 return Builder.CreateICmp(PredL, NewOr,
3393 }
3394
3395 // (icmp ne A, -1) | (icmp ne B, -1) --> (icmp ne (A&B), -1)
3396 // (icmp eq A, -1) & (icmp eq B, -1) --> (icmp eq (A&B), -1)
3397 if (!IsLogical && PredL == (IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE) &&
3398 PredL == PredR && match(LHS1, m_AllOnes()) && match(RHS1, m_AllOnes()) &&
3399 LHS0->getType() == RHS0->getType()) {
3400 Value *NewAnd = Builder.CreateAnd(LHS0, RHS0);
3401 return Builder.CreateICmp(PredL, NewAnd,
3403 }
3404
3405 if (!IsLogical)
3406 if (Value *V =
3407 foldAndOrOfICmpsWithPow2AndWithZero(Builder, LHS, RHS, IsAnd, Q))
3408 return V;
3409
3410 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
3411 if (!LHSC || !RHSC)
3412 return nullptr;
3413
3414 // (trunc x) == C1 & (and x, CA) == C2 -> (and x, CA|CMAX) == C1|C2
3415 // (trunc x) != C1 | (and x, CA) != C2 -> (and x, CA|CMAX) != C1|C2
3416 // where CMAX is the all ones value for the truncated type,
3417 // iff the lower bits of C2 and CA are zero.
3418 if (PredL == (IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE) &&
3419 PredL == PredR && LHS->hasOneUse() && RHS->hasOneUse()) {
3420 Value *V;
3421 const APInt *AndC, *SmallC = nullptr, *BigC = nullptr;
3422
3423 // (trunc x) == C1 & (and x, CA) == C2
3424 // (and x, CA) == C2 & (trunc x) == C1
3425 if (match(RHS0, m_Trunc(m_Value(V))) &&
3426 match(LHS0, m_And(m_Specific(V), m_APInt(AndC)))) {
3427 SmallC = RHSC;
3428 BigC = LHSC;
3429 } else if (match(LHS0, m_Trunc(m_Value(V))) &&
3430 match(RHS0, m_And(m_Specific(V), m_APInt(AndC)))) {
3431 SmallC = LHSC;
3432 BigC = RHSC;
3433 }
3434
3435 if (SmallC && BigC) {
3436 unsigned BigBitSize = BigC->getBitWidth();
3437 unsigned SmallBitSize = SmallC->getBitWidth();
3438
3439 // Check that the low bits are zero.
3440 APInt Low = APInt::getLowBitsSet(BigBitSize, SmallBitSize);
3441 if ((Low & *AndC).isZero() && (Low & *BigC).isZero()) {
3442 Value *NewAnd = Builder.CreateAnd(V, Low | *AndC);
3443 APInt N = SmallC->zext(BigBitSize) | *BigC;
3444 Value *NewVal = ConstantInt::get(NewAnd->getType(), N);
3445 return Builder.CreateICmp(PredL, NewAnd, NewVal);
3446 }
3447 }
3448 }
3449
3450 // Match naive pattern (and its inverted form) for checking if two values
3451 // share same sign. An example of the pattern:
3452 // (icmp slt (X & Y), 0) | (icmp sgt (X | Y), -1) -> (icmp sgt (X ^ Y), -1)
3453 // Inverted form (example):
3454 // (icmp slt (X | Y), 0) & (icmp sgt (X & Y), -1) -> (icmp slt (X ^ Y), 0)
3455 bool TrueIfSignedL, TrueIfSignedR;
3456 if (isSignBitCheck(PredL, *LHSC, TrueIfSignedL) &&
3457 isSignBitCheck(PredR, *RHSC, TrueIfSignedR) &&
3458 (RHS->hasOneUse() || LHS->hasOneUse())) {
3459 Value *X, *Y;
3460 if (IsAnd) {
3461 if ((TrueIfSignedL && !TrueIfSignedR &&
3462 match(LHS0, m_Or(m_Value(X), m_Value(Y))) &&
3463 match(RHS0, m_c_And(m_Specific(X), m_Specific(Y)))) ||
3464 (!TrueIfSignedL && TrueIfSignedR &&
3465 match(LHS0, m_And(m_Value(X), m_Value(Y))) &&
3466 match(RHS0, m_c_Or(m_Specific(X), m_Specific(Y))))) {
3467 Value *NewXor = Builder.CreateXor(X, Y);
3468 return Builder.CreateIsNeg(NewXor);
3469 }
3470 } else {
3471 if ((TrueIfSignedL && !TrueIfSignedR &&
3472 match(LHS0, m_And(m_Value(X), m_Value(Y))) &&
3473 match(RHS0, m_c_Or(m_Specific(X), m_Specific(Y)))) ||
3474 (!TrueIfSignedL && TrueIfSignedR &&
3475 match(LHS0, m_Or(m_Value(X), m_Value(Y))) &&
3476 match(RHS0, m_c_And(m_Specific(X), m_Specific(Y))))) {
3477 Value *NewXor = Builder.CreateXor(X, Y);
3478 return Builder.CreateIsNotNeg(NewXor);
3479 }
3480 }
3481 }
3482
3483 return foldAndOrOfICmpsUsingRanges(LHS, RHS, IsAnd);
3484}
3485
3487 InstCombiner::BuilderTy &Builder) {
3488 assert(I.getOpcode() == Instruction::Or &&
3489 "Simplification only supports or at the moment.");
3490
3491 Value *Cmp1, *Cmp2, *Cmp3, *Cmp4;
3492 if (!match(I.getOperand(0), m_And(m_Value(Cmp1), m_Value(Cmp2))) ||
3493 !match(I.getOperand(1), m_And(m_Value(Cmp3), m_Value(Cmp4))))
3494 return nullptr;
3495
3496 // Check if any two pairs of the and operations are inversions of each other.
3497 if (isKnownInversion(Cmp1, Cmp3) && isKnownInversion(Cmp2, Cmp4))
3498 return Builder.CreateXor(Cmp1, Cmp4);
3499 if (isKnownInversion(Cmp1, Cmp4) && isKnownInversion(Cmp2, Cmp3))
3500 return Builder.CreateXor(Cmp1, Cmp3);
3501
3502 return nullptr;
3503}
3504
3505// FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
3506// here. We should standardize that construct where it is needed or choose some
3507// other way to ensure that commutated variants of patterns are not missed.
3509 if (Value *V = simplifyOrInst(I.getOperand(0), I.getOperand(1),
3511 return replaceInstUsesWith(I, V);
3512
3514 return &I;
3515
3517 return X;
3518
3520 return Phi;
3521
3522 // See if we can simplify any instructions used by the instruction whose sole
3523 // purpose is to compute bits we don't care about.
3525 return &I;
3526
3527 // Do this before using distributive laws to catch simple and/or/not patterns.
3529 return Xor;
3530
3532 return X;
3533
3534 // (A & B) | (C & D) -> A ^ D where A == ~C && B == ~D
3535 // (A & B) | (C & D) -> A ^ C where A == ~D && B == ~C
3536 if (Value *V = foldOrOfInversions(I, Builder))
3537 return replaceInstUsesWith(I, V);
3538
3539 // (A&B)|(A&C) -> A&(B|C) etc
3541 return replaceInstUsesWith(I, V);
3542
3543 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3544 Type *Ty = I.getType();
3545 if (Ty->isIntOrIntVectorTy(1)) {
3546 if (auto *SI0 = dyn_cast<SelectInst>(Op0)) {
3547 if (auto *R =
3548 foldAndOrOfSelectUsingImpliedCond(Op1, *SI0, /* IsAnd */ false))
3549 return R;
3550 }
3551 if (auto *SI1 = dyn_cast<SelectInst>(Op1)) {
3552 if (auto *R =
3553 foldAndOrOfSelectUsingImpliedCond(Op0, *SI1, /* IsAnd */ false))
3554 return R;
3555 }
3556 }
3557
3558 if (Instruction *FoldedLogic = foldBinOpIntoSelectOrPhi(I))
3559 return FoldedLogic;
3560
3561 if (Instruction *BitOp = matchBSwapOrBitReverse(I, /*MatchBSwaps*/ true,
3562 /*MatchBitReversals*/ true))
3563 return BitOp;
3564
3565 if (Instruction *Funnel = matchFunnelShift(I, *this))
3566 return Funnel;
3567
3569 return replaceInstUsesWith(I, Concat);
3570
3572 return R;
3573
3575 return R;
3576
3577 Value *X, *Y;
3578 const APInt *CV;
3579 if (match(&I, m_c_Or(m_OneUse(m_Xor(m_Value(X), m_APInt(CV))), m_Value(Y))) &&
3580 !CV->isAllOnes() && MaskedValueIsZero(Y, *CV, 0, &I)) {
3581 // (X ^ C) | Y -> (X | Y) ^ C iff Y & C == 0
3582 // The check for a 'not' op is for efficiency (if Y is known zero --> ~X).
3583 Value *Or = Builder.CreateOr(X, Y);
3584 return BinaryOperator::CreateXor(Or, ConstantInt::get(Ty, *CV));
3585 }
3586
3587 // If the operands have no common bits set:
3588 // or (mul X, Y), X --> add (mul X, Y), X --> mul X, (Y + 1)
3590 m_Deferred(X)))) {
3591 Value *IncrementY = Builder.CreateAdd(Y, ConstantInt::get(Ty, 1));
3592 return BinaryOperator::CreateMul(X, IncrementY);
3593 }
3594
3595 // (A & C) | (B & D)
3596 Value *A, *B, *C, *D;
3597 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
3598 match(Op1, m_And(m_Value(B), m_Value(D)))) {
3599
3600 // (A & C0) | (B & C1)
3601 const APInt *C0, *C1;
3602 if (match(C, m_APInt(C0)) && match(D, m_APInt(C1))) {
3603 Value *X;
3604 if (*C0 == ~*C1) {
3605 // ((X | B) & MaskC) | (B & ~MaskC) -> (X & MaskC) | B
3606 if (match(A, m_c_Or(m_Value(X), m_Specific(B))))
3607 return BinaryOperator::CreateOr(Builder.CreateAnd(X, *C0), B);
3608 // (A & MaskC) | ((X | A) & ~MaskC) -> (X & ~MaskC) | A
3609 if (match(B, m_c_Or(m_Specific(A), m_Value(X))))
3610 return BinaryOperator::CreateOr(Builder.CreateAnd(X, *C1), A);
3611
3612 // ((X ^ B) & MaskC) | (B & ~MaskC) -> (X & MaskC) ^ B
3613 if (match(A, m_c_Xor(m_Value(X), m_Specific(B))))
3614 return BinaryOperator::CreateXor(Builder.CreateAnd(X, *C0), B);
3615 // (A & MaskC) | ((X ^ A) & ~MaskC) -> (X & ~MaskC) ^ A
3616 if (match(B, m_c_Xor(m_Specific(A), m_Value(X))))
3617 return BinaryOperator::CreateXor(Builder.CreateAnd(X, *C1), A);
3618 }
3619
3620 if ((*C0 & *C1).isZero()) {
3621 // ((X | B) & C0) | (B & C1) --> (X | B) & (C0 | C1)
3622 // iff (C0 & C1) == 0 and (X & ~C0) == 0
3623 if (match(A, m_c_Or(m_Value(X), m_Specific(B))) &&
3624 MaskedValueIsZero(X, ~*C0, 0, &I)) {
3625 Constant *C01 = ConstantInt::get(Ty, *C0 | *C1);
3626 return BinaryOperator::CreateAnd(A, C01);
3627 }
3628 // (A & C0) | ((X | A) & C1) --> (X | A) & (C0 | C1)
3629 // iff (C0 & C1) == 0 and (X & ~C1) == 0
3630 if (match(B, m_c_Or(m_Value(X), m_Specific(A))) &&
3631 MaskedValueIsZero(X, ~*C1, 0, &I)) {
3632 Constant *C01 = ConstantInt::get(Ty, *C0 | *C1);
3633 return BinaryOperator::CreateAnd(B, C01);
3634 }
3635 // ((X | C2) & C0) | ((X | C3) & C1) --> (X | C2 | C3) & (C0 | C1)
3636 // iff (C0 & C1) == 0 and (C2 & ~C0) == 0 and (C3 & ~C1) == 0.
3637 const APInt *C2, *C3;
3638 if (match(A, m_Or(m_Value(X), m_APInt(C2))) &&
3639 match(B, m_Or(m_Specific(X), m_APInt(C3))) &&
3640 (*C2 & ~*C0).isZero() && (*C3 & ~*C1).isZero()) {
3641 Value *Or = Builder.CreateOr(X, *C2 | *C3, "bitfield");
3642 Constant *C01 = ConstantInt::get(Ty, *C0 | *C1);
3643 return BinaryOperator::CreateAnd(Or, C01);
3644 }
3645 }
3646 }
3647
3648 // Don't try to form a select if it's unlikely that we'll get rid of at
3649 // least one of the operands. A select is generally more expensive than the
3650 // 'or' that it is replacing.
3651 if (Op0->hasOneUse() || Op1->hasOneUse()) {
3652 // (Cond & C) | (~Cond & D) -> Cond ? C : D, and commuted variants.
3653 if (Value *V = matchSelectFromAndOr(A, C, B, D))
3654 return replaceInstUsesWith(I, V);
3655 if (Value *V = matchSelectFromAndOr(A, C, D, B))
3656 return replaceInstUsesWith(I, V);
3657 if (Value *V = matchSelectFromAndOr(C, A, B, D))
3658 return replaceInstUsesWith(I, V);
3659 if (Value *V = matchSelectFromAndOr(C, A, D, B))
3660 return replaceInstUsesWith(I, V);
3661 if (Value *V = matchSelectFromAndOr(B, D, A, C))
3662 return replaceInstUsesWith(I, V);
3663 if (Value *V = matchSelectFromAndOr(B, D, C, A))
3664 return replaceInstUsesWith(I, V);
3665 if (Value *V = matchSelectFromAndOr(D, B, A, C))
3666 return replaceInstUsesWith(I, V);
3667 if (Value *V = matchSelectFromAndOr(D, B, C, A))
3668 return replaceInstUsesWith(I, V);
3669 }
3670 }
3671
3672 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
3673 match(Op1, m_Not(m_Or(m_Value(B), m_Value(D)))) &&
3674 (Op0->hasOneUse() || Op1->hasOneUse())) {
3675 // (Cond & C) | ~(Cond | D) -> Cond ? C : ~D
3676 if (Value *V = matchSelectFromAndOr(A, C, B, D, true))
3677 return replaceInstUsesWith(I, V);
3678 if (Value *V = matchSelectFromAndOr(A, C, D, B, true))
3679 return replaceInstUsesWith(I, V);
3680 if (Value *V = matchSelectFromAndOr(C, A, B, D, true))
3681 return replaceInstUsesWith(I, V);
3682 if (Value *V = matchSelectFromAndOr(C, A, D, B, true))
3683 return replaceInstUsesWith(I, V);
3684 }
3685
3686 // (A ^ B) | ((B ^ C) ^ A) -> (A ^ B) | C
3687 if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
3688 if (match(Op1,
3691 return BinaryOperator::CreateOr(Op0, C);
3692
3693 // ((B ^ C) ^ A) | (A ^ B) -> (A ^ B) | C
3694 if (match(Op1, m_Xor(m_Value(A), m_Value(B))))
3695 if (match(Op0,
3698 return BinaryOperator::CreateOr(Op1, C);
3699
3700 if (Instruction *DeMorgan = matchDeMorgansLaws(I, *this))
3701 return DeMorgan;
3702
3703 // Canonicalize xor to the RHS.
3704 bool SwappedForXor = false;
3705 if (match(Op0, m_Xor(m_Value(), m_Value()))) {
3706 std::swap(Op0, Op1);
3707 SwappedForXor = true;
3708 }
3709
3710 if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3711 // (A | ?) | (A ^ B) --> (A | ?) | B
3712 // (B | ?) | (A ^ B) --> (B | ?) | A
3713 if (match(Op0, m_c_Or(m_Specific(A), m_Value())))
3714 return BinaryOperator::CreateOr(Op0, B);
3715 if (match(Op0, m_c_Or(m_Specific(B), m_Value())))
3716 return BinaryOperator::CreateOr(Op0, A);
3717
3718 // (A & B) | (A ^ B) --> A | B
3719 // (B & A) | (A ^ B) --> A | B
3720 if (match(Op0, m_c_And(m_Specific(A), m_Specific(B))))
3721 return BinaryOperator::CreateOr(A, B);
3722
3723 // ~A | (A ^ B) --> ~(A & B)
3724 // ~B | (A ^ B) --> ~(A & B)
3725 // The swap above should always make Op0 the 'not'.
3726 if ((Op0->hasOneUse() || Op1->hasOneUse()) &&
3727 (match(Op0, m_Not(m_Specific(A))) || match(Op0, m_Not(m_Specific(B)))))
3729
3730 // Same as above, but peek through an 'and' to the common operand:
3731 // ~(A & ?) | (A ^ B) --> ~((A & ?) & B)
3732 // ~(B & ?) | (A ^ B) --> ~((B & ?) & A)
3734 if ((Op0->hasOneUse() || Op1->hasOneUse()) &&
3736 m_c_And(m_Specific(A), m_Value())))))
3738 if ((Op0->hasOneUse() || Op1->hasOneUse()) &&
3740 m_c_And(m_Specific(B), m_Value())))))
3742
3743 // (~A | C) | (A ^ B) --> ~(A & B) | C
3744 // (~B | C) | (A ^ B) --> ~(A & B) | C
3745 if (Op0->hasOneUse() && Op1->hasOneUse() &&
3746 (match(Op0, m_c_Or(m_Not(m_Specific(A)), m_Value(C))) ||
3747 match(Op0, m_c_Or(m_Not(m_Specific(B)), m_Value(C))))) {
3748 Value *Nand = Builder.CreateNot(Builder.CreateAnd(A, B), "nand");
3749 return BinaryOperator::CreateOr(Nand, C);
3750 }
3751 }
3752
3753 if (SwappedForXor)
3754 std::swap(Op0, Op1);
3755
3756 {
3757 ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
3758 ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
3759 if (LHS && RHS)
3760 if (Value *Res = foldAndOrOfICmps(LHS, RHS, I, /* IsAnd */ false))
3761 return replaceInstUsesWith(I, Res);
3762
3763 // TODO: Make this recursive; it's a little tricky because an arbitrary
3764 // number of 'or' instructions might have to be created.
3765 Value *X, *Y;
3766 if (LHS && match(Op1, m_OneUse(m_LogicalOr(m_Value(X), m_Value(Y))))) {
3767 bool IsLogical = isa<SelectInst>(Op1);
3768 // LHS | (X || Y) --> (LHS || X) || Y
3769 if (auto *Cmp = dyn_cast<ICmpInst>(X))
3770 if (Value *Res =
3771 foldAndOrOfICmps(LHS, Cmp, I, /* IsAnd */ false, IsLogical))
3772 return replaceInstUsesWith(I, IsLogical
3773 ? Builder.CreateLogicalOr(Res, Y)
3774 : Builder.CreateOr(Res, Y));
3775 // LHS | (X || Y) --> X || (LHS | Y)
3776 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
3777 if (Value *Res = foldAndOrOfICmps(LHS, Cmp, I, /* IsAnd */ false,
3778 /* IsLogical */ false))
3779 return replaceInstUsesWith(I, IsLogical
3780 ? Builder.CreateLogicalOr(X, Res)
3781 : Builder.CreateOr(X, Res));
3782 }
3783 if (RHS && match(Op0, m_OneUse(m_LogicalOr(m_Value(X), m_Value(Y))))) {
3784 bool IsLogical = isa<SelectInst>(Op0);
3785 // (X || Y) | RHS --> (X || RHS) || Y
3786 if (auto *Cmp = dyn_cast<ICmpInst>(X))
3787 if (Value *Res =
3788 foldAndOrOfICmps(Cmp, RHS, I, /* IsAnd */ false, IsLogical))
3789 return replaceInstUsesWith(I, IsLogical
3790 ? Builder.CreateLogicalOr(Res, Y)
3791 : Builder.CreateOr(Res, Y));
3792 // (X || Y) | RHS --> X || (Y | RHS)
3793 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
3794 if (Value *Res = foldAndOrOfICmps(Cmp, RHS, I, /* IsAnd */ false,
3795 /* IsLogical */ false))
3796 return replaceInstUsesWith(I, IsLogical
3797 ? Builder.CreateLogicalOr(X, Res)
3798 : Builder.CreateOr(X, Res));
3799 }
3800 }
3801
3802 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
3803 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
3804 if (Value *Res = foldLogicOfFCmps(LHS, RHS, /*IsAnd*/ false))
3805 return replaceInstUsesWith(I, Res);
3806
3807 if (Instruction *FoldedFCmps = reassociateFCmps(I, Builder))
3808 return FoldedFCmps;
3809
3810 if (Instruction *CastedOr = foldCastedBitwiseLogic(I))
3811 return CastedOr;
3812
3813 if (Instruction *Sel = foldBinopOfSextBoolToSelect(I))
3814 return Sel;
3815
3816 // or(sext(A), B) / or(B, sext(A)) --> A ? -1 : B, where A is i1 or <N x i1>.
3817 // TODO: Move this into foldBinopOfSextBoolToSelect as a more generalized fold
3818 // with binop identity constant. But creating a select with non-constant
3819 // arm may not be reversible due to poison semantics. Is that a good
3820 // canonicalization?
3821 if (match(&I, m_c_Or(m_OneUse(m_SExt(m_Value(A))), m_Value(B))) &&
3822 A->getType()->isIntOrIntVectorTy(1))
3824
3825 // Note: If we've gotten to the point of visiting the outer OR, then the
3826 // inner one couldn't be simplified. If it was a constant, then it won't
3827 // be simplified by a later pass either, so we try swapping the inner/outer
3828 // ORs in the hopes that we'll be able to simplify it this way.
3829 // (X|C) | V --> (X|V) | C
3830 ConstantInt *CI;
3831 if (Op0->hasOneUse() && !match(Op1, m_ConstantInt()) &&
3832 match(Op0, m_Or(m_Value(A), m_ConstantInt(CI)))) {
3833 Value *Inner = Builder.CreateOr(A, Op1);
3834 Inner->takeName(Op0);
3835 return BinaryOperator::CreateOr(Inner, CI);
3836 }
3837
3838 // Change (or (bool?A:B),(bool?C:D)) --> (bool?(or A,C):(or B,D))
3839 // Since this OR statement hasn't been optimized further yet, we hope
3840 // that this transformation will allow the new ORs to be optimized.
3841 {
3842 Value *X = nullptr, *Y = nullptr;
3843 if (Op0->hasOneUse() && Op1->hasOneUse() &&
3844 match(Op0, m_Select(m_Value(X), m_Value(A), m_Value(B))) &&
3845 match(Op1, m_Select(m_Value(Y), m_Value(C), m_Value(D))) && X == Y) {
3846 Value *orTrue = Builder.CreateOr(A, C);
3847 Value *orFalse = Builder.CreateOr(B, D);
3848 return SelectInst::Create(X, orTrue, orFalse);
3849 }
3850 }
3851
3852 // or(ashr(subNSW(Y, X), ScalarSizeInBits(Y) - 1), X) --> X s> Y ? -1 : X.
3853 {
3854 Value *X, *Y;